code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def limited? @query_op.limit > 0 end
Class
2
it "updates all records matching selector with change" do query.should_receive(:update).with(change, [:multi]) query.update_all change end
Class
2
def team_organize Log.add_info(request, params.inspect) team_id = params[:team_id] unless team_id.blank? begin @team = Team.find(team_id) rescue @team = nil ensure if @team.nil? flash[:notice] = t('msg.already_deleted', :name => Team.model_name.human) return end end users = @team.get_users_a end team_members = params[:team_members] created = false modified = false if team_members.nil? or team_members.empty? unless team_id.blank? # @team must not be nil. @team.save if modified = @team.clear_users end else if team_members != users if team_id.blank? item = Item.find(params[:id]) created = true @team = Team.new @team.name = item.title @team.item_id = params[:id] @team.status = Team::STATUS_STANDBY else @team.clear_users end @team.add_users team_members @team.save @team.remove_application team_members modified = true end end if created @team.create_team_folder end @item = @team.item if modified flash[:notice] = t('msg.register_success') end render(:partial => 'ajax_team_info', :layout => false) rescue => evar Log.add_error(request, evar) render(:partial => 'ajax_team_info', :layout => false) end
Base
1
def authenticate(*credentials, &block) raise ArgumentError, 'at least 2 arguments required' if credentials.size < 2 if credentials[0].blank? return authentication_response(return_value: false, failure: :invalid_login, &block) end if @sorcery_config.downcase_username_before_authenticating credentials[0].downcase! end user = sorcery_adapter.find_by_credentials(credentials) unless user return authentication_response(failure: :invalid_login, &block) end set_encryption_attributes unless user.valid_password?(credentials[1]) return authentication_response(user: user, failure: :invalid_password, &block) end if user.respond_to?(:active_for_authentication?) && !user.active_for_authentication? return authentication_response(user: user, failure: :inactive, &block) end @sorcery_config.before_authenticate.each do |callback| success, reason = user.send(callback) unless success return authentication_response(user: user, failure: reason, &block) end end authentication_response(user: user, return_value: user, &block) end
Base
1
def drop command dropDatabase: 1 end
Class
2
def test_parse_memory_nil assert_raises(ArgumentError) do @parser.parse_memory(nil) end end
Base
1
def update_images_order Log.add_info(request, params.inspect) order_ary = params[:images_order] item = Item.find(params[:id]) item.images_without_content.each do |img| class << img def record_timestamps; false; end end img.update_attribute(:xorder, order_ary.index(img.id.to_s) + 1) class << img remove_method :record_timestamps end end render(:text => '') rescue => evar Log.add_error(request, evar) render(:text => evar.to_s) end
Base
1
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
Class
2
it "stores the collection" do query.collection.should eq collection end
Class
2
def add_order_set_constraint( session, resource_set_list, force=false, autocorrect=true ) command = [PCS, "constraint", "order"] resource_set_list.each { |resource_set| command << "set" command.concat(resource_set) } command << '--force' if force command << '--autocorrect' if autocorrect stdout, stderr, retval = run_cmd(session, *command) return retval, stderr.join(' ') end
Compound
4
def week Log.add_info(request, params.inspect) date_s = params[:date] if date_s.nil? or date_s.empty? @date = Date.today else @date = Date.parse(date_s) end params[:display] = 'week' end
Base
1
it "with params as nil" do cl = subject.build_command_line("true", nil) expect(cl).to eq "true" end
Base
1
def setup FactoryGirl.create(:host) end
Class
2
it "merges the old and new session's options" do session.with(new_options) do |new_session| new_session.options.should eq options.merge(new_options) end end
Class
2
def self.from(stream) header = stream.read 512 empty = (header == "\0" * 512) fields = header.unpack UNPACK_FORMAT new :name => fields.shift, :mode => fields.shift.oct, :uid => fields.shift.oct, :gid => fields.shift.oct, :size => fields.shift.oct, :mtime => fields.shift.oct, :checksum => fields.shift.oct, :typeflag => fields.shift, :linkname => fields.shift, :magic => fields.shift, :version => fields.shift.oct, :uname => fields.shift, :gname => fields.shift, :devmajor => fields.shift.oct, :devminor => fields.shift.oct, :prefix => fields.shift, :empty => empty end
Base
1
def team_organize Log.add_info(request, params.inspect) team_id = params[:team_id] unless team_id.blank? begin @team = Team.find(team_id) rescue @team = nil ensure if @team.nil? flash[:notice] = t('msg.already_deleted', :name => Team.model_name.human) return end end users = @team.get_users_a end team_members = params[:team_members] SqlHelper.validate_token([team_members]) created = false modified = false if team_members.nil? or team_members.empty? unless team_id.blank? # @team must not be nil. @team.save if modified = @team.clear_users end else if team_members != users if team_id.blank? item = Item.find(params[:id]) created = true @team = Team.new @team.name = item.title @team.item_id = params[:id] @team.status = Team::STATUS_STANDBY else @team.clear_users end @team.add_users(team_members) @team.save @team.remove_application(team_members) modified = true end end if created @team.create_team_folder end @item = @team.item if modified flash[:notice] = t('msg.register_success') end render(:partial => 'ajax_team_info', :layout => false) rescue => evar Log.add_error(request, evar) render(:partial => 'ajax_team_info', :layout => false) end
Base
1
def build_actions(actions, guardian, args) return unless pending? if guardian.can_approve?(target) || args[:approved_by_invite] actions.add(:approve_user) do |a| a.icon = 'user-plus' a.label = "reviewables.actions.approve_user.title" end end delete_user_actions(actions, require_reject_reason: !is_a_suspect_user?) end
Class
2
def test_edit get :edit, {:id => Hostgroup.first}, set_session_user assert_template 'edit' end
Class
2
def dup session = super session.instance_variable_set :@options, options.dup if defined? @current_database session.send(:remove_instance_variable, :@current_database) end session end
Class
2
def set_certs(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end ssl_cert = (params['ssl_cert'] || '').strip ssl_key = (params['ssl_key'] || '').strip if ssl_cert.empty? and !ssl_key.empty? return [400, 'cannot save ssl certificate without ssl key'] end if !ssl_cert.empty? and ssl_key.empty? return [400, 'cannot save ssl key without ssl certificate'] end if !ssl_cert.empty? and !ssl_key.empty? ssl_errors = verify_cert_key_pair(ssl_cert, ssl_key) if ssl_errors and !ssl_errors.empty? return [400, ssl_errors.join] end begin write_file_lock(CRT_FILE, 0700, ssl_cert) write_file_lock(KEY_FILE, 0700, ssl_key) rescue => e # clean the files if we ended in the middle # the files will be regenerated on next pcsd start FileUtils.rm(CRT_FILE, {:force => true}) FileUtils.rm(KEY_FILE, {:force => true}) return [400, "cannot save ssl files: #{e}"] end end if params['cookie_secret'] cookie_secret = params['cookie_secret'].strip if !cookie_secret.empty? begin write_file_lock(COOKIE_FILE, 0700, cookie_secret) rescue => e return [400, "cannot save cookie secret: #{e}"] end end end return [200, 'success'] end
Compound
4
it "returns the living socket" do cluster.socket_for(:write).should eq socket end
Class
2
it "adds the credentials to the auth cache" do cluster.login("admin", "username", "password") cluster.auth.should eq("admin" => ["username", "password"]) end
Class
2
it "adds the node to the master set" do cluster.sync_server server cluster.primaries.should include server end
Class
2
it "executes a count command" do database.should_receive(:command).with( count: collection.name, query: selector ).and_return("n" => 4) query.count end
Class
2
def secondaries servers.select(&:secondary?) end
Class
2
it "should should include the IndirectionHooks module in its indirection" do Puppet::FileServing::Metadata.indirection.singleton_class.included_modules.should include(Puppet::FileServing::IndirectionHooks) end
Class
2
def update(change, flags = nil) update = Protocol::Update.new( operation.database, operation.collection, operation.selector, change, flags: flags ) session.with(consistency: :strong) do |session| session.execute update end end
Class
2
def kill session.execute kill_cursor_op end
Class
2
def self.up add_column :items, :source_id, :integer add_column :addresses, :groups, :text add_column :addresses, :teams, :text add_column :workflows, :groups, :text add_column :users, :figure, :string add_column :groups, :xtype, :string add_column :teams, :req_to_del_at, :datetime change_table :teams do |t| t.timestamps end teams = Team.all unless teams.nil? teams.each do |team| begin item = Item.find(team.item_id) rescue end next if item.nil? attrs = ActionController::Parameters.new({created_at: item.created_at, updated_at: item.updated_at}) attrs.permit! team.update_attributes(attrs) end end end
Base
1
it "removes the socket" do cluster.should_receive(:remove).with(dead_server) cluster.socket_for :write end
Class
2
def self.password_reset_via_token(token, password) # check token user = by_reset_token(token) return if !user # reset password user.update!(password: password) # delete token Token.find_by(action: 'PasswordReset', name: token).destroy user end
Class
2
def remove(server) servers.delete(server) end
Class
2
def self.update_xorder(title, order) if title.nil? con = nil else con = ['title=?', title] end SqlHelper.validate_token([order]) User.update_all("xorder=#{order}", con) end
Base
1
def _call(env) unless ALLOWED_VERBS.include? env["REQUEST_METHOD"] return fail(405, "Method Not Allowed") end path_info = Utils.unescape(env["PATH_INFO"]) parts = path_info.split SEPS parts.inject(0) do |depth, part| case part when '', '.' depth when '..' return fail(404, "Not Found") if depth - 1 < 0 depth - 1 else depth + 1 end end
Base
1
it 'does not include user or group archived messages' do UserArchivedMessage.archive!(user.id, group_message) UserArchivedMessage.archive!(user.id, private_message) topics = TopicQuery.new(nil).list_private_messages_all(user).topics expect(topics).to eq([]) GroupArchivedMessage.archive!(user_2.id, group_message) topics = TopicQuery.new(nil).list_private_messages_all(user_2).topics expect(topics).to contain_exactly(private_message) end
Class
2
def instantiate variant, mac=nil # Filenames must end in a hex representation of a mac address but only if mac is not empty log_halt 403, "Invalid MAC address: #{mac}" unless valid_mac?(mac) || mac.nil? log_halt 403, "Unrecognized pxeboot config type: #{variant}" unless defined? variant.capitalize eval "Proxy::TFTP::#{variant.capitalize}.new" end
Pillar
3
it 'fails when local logins is disabled' do SiteSetting.enable_local_logins = false get "/session/email-login/#{email_token.token}" expect(response.status).to eq(500) end
Class
2
it "executes a distinct command" do database.should_receive(:command).with( distinct: collection.name, key: "name", query: selector ).and_return("values" => [ "durran", "bernerd" ]) query.distinct(:name) end
Class
2
func getGateway(ctx *statsContext) error { gatewayID := helpers.GetGatewayID(&ctx.gatewayStats) gw, err := storage.GetAndCacheGateway(ctx.ctx, storage.DB(), gatewayID) if err != nil { return errors.Wrap(err, "get gateway error") } ctx.gateway = gw return nil }
Class
2
func (x *UpdateGroupRequest) Reset() { *x = UpdateGroupRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
Base
1
func newSignV4ChunkedReader(req *http.Request) (io.ReadCloser, APIErrorCode) { cred, seedSignature, region, seedDate, errCode := calculateSeedSignature(req) if errCode != ErrNone { return nil, errCode } return &s3ChunkedReader{ reader: bufio.NewReader(req.Body), cred: cred, seedSignature: seedSignature, seedDate: seedDate, region: region, chunkSHA256Writer: sha256.New(), state: readChunkHeader, }, ErrNone }
Base
1
func (p *HTTPClient) closeResponse() error { var err error if p.response != nil && p.response.Body != nil { // The docs specify that if keepalive is enabled and the response body is not // read to completion the connection will never be returned to the pool and // reused. Errors are being ignored here because if the connection is invalid // and this fails for some reason, the Close() method will do any remaining // cleanup. io.Copy(ioutil.Discard, p.response.Body) err = p.response.Body.Close() } p.response = nil return err }
Base
1
func (m *Sub) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowUnmarshalmerge } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Sub: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Sub: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field SubNumber", wireType) } var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowUnmarshalmerge } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= int64(b&0x7F) << shift if b < 0x80 { break } } m.SubNumber = &v default: iNdEx = preIndex skippy, err := skipUnmarshalmerge(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthUnmarshalmerge } if (iNdEx + skippy) < 0 { return ErrInvalidLengthUnmarshalmerge } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func doesPolicySignatureMatch(formValues http.Header) APIErrorCode { // For SignV2 - Signature field will be valid if _, ok := formValues["Signature"]; ok { return doesPolicySignatureV2Match(formValues) } return doesPolicySignatureV4Match(formValues) }
Class
2
func sendCode(id string) (err error) { a, err := account.SelectAccount(id, 0) if err != nil { logger.Error("发送验证码失败", zap.Error(err)) return } if len(a) == 0 { return errors.New("账号不存在") } rand.Seed(time.Now().UnixNano()) c := strconv.FormatFloat(rand.Float64(), 'f', -1, 64)[2:6] client.GetClient().SendMessage( message.NewTextMessage("您的验证码是:" + c + ",请勿泄露给他人。有效期5分钟"). SetTarget(&message.Target{ID: a[0].QQ}), ) account.WriteCode(id, c) go func() { timer := time.NewTimer(5 * time.Minute) defer timer.Stop() <-timer.C account.DeleteCode(id) }() return }
Base
1
func (svc Service) CountSoftware(ctx context.Context, opt fleet.SoftwareListOptions) (int, error) { if err := svc.authz.Authorize(ctx, &fleet.Software{}, fleet.ActionRead); err != nil { return 0, err } return svc.ds.CountSoftware(ctx, opt) }
Class
2
func (EmptyEvidencePool) Update(State, types.EvidenceList) {}
Class
2
func LoadDir(dirname string) (*Plugin, error) { data, err := ioutil.ReadFile(filepath.Join(dirname, PluginFileName)) if err != nil { return nil, err } plug := &Plugin{Dir: dirname} if err := yaml.Unmarshal(data, &plug.Metadata); err != nil { return nil, err } return plug, nil }
Class
2
func doTmpfsCopyUp(m *configs.Mount, rootfs, mountLabel string) (Err error) { // Set up a scratch dir for the tmpfs on the host. tmpdir, err := prepareTmp("/tmp") if err != nil { return fmt.Errorf("tmpcopyup: failed to setup tmpdir: %w", err) } defer cleanupTmp(tmpdir) tmpDir, err := ioutil.TempDir(tmpdir, "runctmpdir") if err != nil { return fmt.Errorf("tmpcopyup: failed to create tmpdir: %w", err) } defer os.RemoveAll(tmpDir) // Configure the *host* tmpdir as if it's the container mount. We change // m.Destination since we are going to mount *on the host*. oldDest := m.Destination m.Destination = tmpDir err = mountPropagate(m, "/", mountLabel) m.Destination = oldDest if err != nil { return err } defer func() { if Err != nil { if err := unmount(tmpDir, unix.MNT_DETACH); err != nil { logrus.Warnf("tmpcopyup: %v", err) } } }() return utils.WithProcfd(rootfs, m.Destination, func(procfd string) (Err error) { // Copy the container data to the host tmpdir. We append "/" to force // CopyDirectory to resolve the symlink rather than trying to copy the // symlink itself. if err := fileutils.CopyDirectory(procfd+"/", tmpDir); err != nil { return fmt.Errorf("tmpcopyup: failed to copy %s to %s (%s): %w", m.Destination, procfd, tmpDir, err) } // Now move the mount into the container. if err := mount(tmpDir, m.Destination, procfd, "", unix.MS_MOVE, ""); err != nil { return fmt.Errorf("tmpcopyup: failed to move mount: %w", err) } return nil }) }
Base
1
func ZeroTierLeaveNetwork(c *gin.Context) { networkId := c.Param("id") service.MyService.ZeroTier().ZeroTierLeaveNetwork(networkId) if len(networkId) == 0 { c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)}) return } c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)}) }
Base
1
func (m *M) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowAsym } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: M: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: M: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Arr", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowAsym } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthAsym } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthAsym } if postIndex > l { return io.ErrUnexpectedEOF } var v MyType m.Arr = append(m.Arr, v) if err := m.Arr[len(m.Arr)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipAsym(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthAsym } if (iNdEx + skippy) < 0 { return ErrInvalidLengthAsym } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func (*ListAccountsRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{26} }
Base
1
func (*DeleteGroupRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{17} }
Base
1
func resize(in []byte, n int) (head, tail []byte) { if cap(in) >= n { head = in[:n] } else { head = make([]byte, n) copy(head, in) } tail = head[len(in):] return }
Base
1
func (m *SourceContext) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowSourceContext } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: SourceContext: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: SourceContext: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field FileName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowSourceContext } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthSourceContext } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthSourceContext } if postIndex > l { return io.ErrUnexpectedEOF } m.FileName = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipSourceContext(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthSourceContext } if (iNdEx + skippy) < 0 { return ErrInvalidLengthSourceContext } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func (p *Profile) write() (pth string, err error) { rootDir, err := utils.GetTempDir() if err != nil { return } pth = filepath.Join(rootDir, p.Id) _ = os.Remove(pth) err = ioutil.WriteFile(pth, []byte(p.Data), os.FileMode(0600)) if err != nil { err = &WriteError{ errors.Wrap(err, "profile: Failed to write profile"), } return } return }
Class
2
func (p *Profile) writeConfWgQuick(data *WgConf) (pth string, err error) { allowedIps := []string{} if data.Routes != nil { for _, route := range data.Routes { allowedIps = append(allowedIps, route.Network) } } if data.Routes6 != nil { for _, route := range data.Routes6 { allowedIps = append(allowedIps, route.Network) } } addr := data.Address if data.Address6 != "" { addr += "," + data.Address6 } templData := WgConfData{ Address: addr, PrivateKey: p.PrivateKeyWg, PublicKey: data.PublicKey, AllowedIps: strings.Join(allowedIps, ","), Endpoint: fmt.Sprintf("%s:%d", data.Hostname, data.Port), } if data.DnsServers != nil && len(data.DnsServers) > 0 { templData.HasDns = true templData.DnsServers = strings.Join(data.DnsServers, ",") } output := &bytes.Buffer{} err = WgConfTempl.Execute(output, templData) if err != nil { err = &errortypes.ParseError{ errors.Wrap(err, "profile: Failed to exec wg template"), } return } rootDir := "" switch runtime.GOOS { case "linux": rootDir = WgLinuxConfPath err = os.MkdirAll(WgLinuxConfPath, 0700) if err != nil { err = &errortypes.WriteError{ errors.Wrap( err, "profile: Failed to create wg conf directory"), } return } case "darwin": rootDir = WgMacConfPath err = os.MkdirAll(WgMacConfPath, 0700) if err != nil { err = &errortypes.WriteError{ errors.Wrap( err, "profile: Failed to create wg conf directory"), } return } default: rootDir, err = utils.GetTempDir() if err != nil { return } } pth = filepath.Join(rootDir, p.Iface+".conf") os.Remove(pth) err = ioutil.WriteFile( pth, []byte(output.String()), os.FileMode(0600), ) if err != nil { err = &WriteError{ errors.Wrap(err, "profile: Failed to write wg conf"), } return } return }
Base
1
func (*DeleteStorageObjectRequest) Descriptor() ([]byte, []int) { return file_console_proto_rawDescGZIP(), []int{21} }
Base
1
func TestMaxDepthValidation(t *testing.T) { s, err := schema.ParseSchema(interfaceSimple, false) if err != nil { t.Fatal(err) } for _, tc := range []struct { name string query string maxDepth int expected bool }{ { name: "off", query: `query Fine { # depth 0 characters { # depth 1 id # depth 2 name # depth 2 friends { # depth 2 id # depth 3 name # depth 3 } } }`, maxDepth: 0, }, { name: "fields", query: `query Fine { # depth 0 characters { # depth 1 id # depth 2 name # depth 2 friends { # depth 2 id # depth 3 name # depth 3 } } }`, maxDepth: 2, expected: true, }, { name: "fragment", query: `fragment friend on Character { id # depth 6 name friends { name # depth 7 } } query { # depth 0 characters { # depth 1 id # depth 2 name # depth 2 friends { # depth 2 friends { # depth 3 friends { # depth 4 friends { # depth 5 ...friend # depth 6 } } } } } }`, maxDepth: 5, expected: true, }, { name: "inlinefragment", query: `query { # depth 0 characters { # depth 1 ... on Droid { # depth 2 primaryFunction # depth 2 } } }`, maxDepth: 1, expected: true, }, } { t.Run(tc.name, func(t *testing.T) { doc, err := query.Parse(tc.query) if err != nil { t.Fatal(err) } context := newContext(s, doc, tc.maxDepth) op := doc.Operations[0] opc := &opContext{context: context, ops: doc.Operations} actual := validateMaxDepth(opc, op.Selections, 1) if actual != tc.expected { t.Errorf("expected %t, actual %t", tc.expected, actual) } }) } }
Class
2
func isLoopbackURI(requested *url.URL, registeredURI string) bool { registered, err := url.Parse(registeredURI) if err != nil { return false } if registered.Scheme != "http" || !isLoopbackAddress(registered.Host) { return false } if requested.Scheme == "http" && isLoopbackAddress(requested.Host) && registered.Path == requested.Path { return true } return false }
Base
1
func (x *LeaderboardList) Reset() { *x = LeaderboardList{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
Base
1
func (evpool *Pool) flushConsensusBuffer() { for _, ev := range evpool.consensusBuffer { if err := evpool.addPendingEvidence(ev); err != nil { evpool.logger.Error("failed to flush evidence from consensus buffer to pending list: %w", err) continue } evpool.evidenceList.PushBack(ev) } // reset consensus buffer evpool.consensusBuffer = make([]types.Evidence, 0) }
Class
2
func (b *Builder) buildControlPlanePrefixRoute(prefix string, protected bool) (*envoy_config_route_v3.Route, error) { r := &envoy_config_route_v3.Route{ Name: "pomerium-prefix-" + prefix, Match: &envoy_config_route_v3.RouteMatch{ PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: prefix}, }, Action: &envoy_config_route_v3.Route_Route{ Route: &envoy_config_route_v3.RouteAction{ ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{ Cluster: httpCluster, }, }, }, } if !protected { r.TypedPerFilterConfig = map[string]*any.Any{ "envoy.filters.http.ext_authz": disableExtAuthz, } } return r, nil }
Class
2
func Render(tmpl string, s *types.Step) (types.StepSlice, error) { buffer := new(bytes.Buffer) config := new(types.Build) velaFuncs := funcHandler{envs: convertPlatformVars(s.Environment)} templateFuncMap := map[string]interface{}{ "vela": velaFuncs.returnPlatformVar, } // parse the template with Masterminds/sprig functions // // https://pkg.go.dev/github.com/Masterminds/sprig?tab=doc#TxtFuncMap t, err := template.New(s.Name).Funcs(sprig.TxtFuncMap()).Funcs(templateFuncMap).Parse(tmpl) if err != nil { return types.StepSlice{}, fmt.Errorf("unable to parse template %s: %v", s.Template.Name, err) } // apply the variables to the parsed template err = t.Execute(buffer, s.Template.Variables) if err != nil { return types.StepSlice{}, fmt.Errorf("unable to execute template %s: %v", s.Template.Name, err) } // unmarshal the template to the pipeline err = yaml.Unmarshal(buffer.Bytes(), config) if err != nil { return types.StepSlice{}, fmt.Errorf("unable to unmarshal yaml: %v", err) } // ensure all templated steps have template prefix for index, newStep := range config.Steps { config.Steps[index].Name = fmt.Sprintf("%s_%s", s.Name, newStep.Name) } return config.Steps, nil }
Base
1
func (s *Server) CheckDeletionToken(deletionToken, token, filename string) error { s.Lock(token, filename) defer s.Unlock(token, filename) var metadata Metadata r, _, err := s.storage.Get(token, fmt.Sprintf("%s.metadata", filename)) if s.storage.IsNotExist(err) { return nil } else if err != nil { return err } defer r.Close() if err := json.NewDecoder(r).Decode(&metadata); err != nil { return err } else if metadata.DeletionToken != deletionToken { return errors.New("Deletion token doesn't match.") } return nil }
Base
1
func (v *validator) ValidateSignature(auth kolide.Auth) (kolide.Auth, error) { info := auth.(*resp) status, err := info.status() if err != nil { return nil, errors.New("missing or malformed response") } if status != Success { return nil, errors.Errorf("response status %s", info.statusDescription()) } decoded, err := base64.StdEncoding.DecodeString(info.rawResponse()) if err != nil { return nil, errors.Wrap(err, "based64 decoding response") } doc := etree.NewDocument() err = doc.ReadFromBytes(decoded) if err != nil || doc.Root() == nil { return nil, errors.Wrap(err, "parsing xml response") } elt := doc.Root() signed, err := v.validateSignature(elt) if err != nil { return nil, errors.Wrap(err, "signing verification failed") } // We've verified that the response hasn't been tampered with at this point signedDoc := etree.NewDocument() signedDoc.SetRoot(signed) buffer, err := signedDoc.WriteToBytes() if err != nil { return nil, errors.Wrap(err, "creating signed doc buffer") } var response Response err = xml.Unmarshal(buffer, &response) if err != nil { return nil, errors.Wrap(err, "unmarshalling signed doc") } info.setResponse(&response) return info, nil }
Base
1
func (m *Wilson) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCasttype } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Wilson: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Wilson: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Int64", wireType) } var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCasttype } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= int64(b&0x7F) << shift if b < 0x80 { break } } m.Int64 = &v default: iNdEx = preIndex skippy, err := skipCasttype(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthCasttype } if (iNdEx + skippy) < 0 { return ErrInvalidLengthCasttype } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func compileRegexps(regexpStrings []string) ([]*regexp.Regexp, error) { regexps := []*regexp.Regexp{} for _, regexpStr := range regexpStrings { r, err := regexp.Compile(regexpStr) if err != nil { return regexps, err } regexps = append(regexps, r) } return regexps, nil }
Base
1
func (x *UserList_User) Reset() { *x = UserList_User{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[48] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
Base
1
func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error { var ( dest = m.Destination data = label.FormatMountLabel(m.Data, mountLabel) flags = m.Flags ) if libcontainerUtils.CleanPath(dest) == "/dev" { flags &= ^unix.MS_RDONLY } // Mount it rw to allow chmod operation. A remount will be performed // later to make it ro if set. if m.Device == "tmpfs" { flags &= ^unix.MS_RDONLY } copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP if !(copyUp || strings.HasPrefix(dest, rootfs)) { dest = filepath.Join(rootfs, dest) } if err := unix.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil { return err } for _, pflag := range m.PropagationFlags { if err := unix.Mount("", dest, "", uintptr(pflag), ""); err != nil { return err } } return nil }
Class
2
func main() { if len(os.Args) < 3 { fatal(usage) } cmd, filename := os.Args[1], os.Args[2] ff := archiver.MatchingFormat(filename) if ff == nil { fatalf("%s: Unsupported file extension", filename) } var err error switch cmd { case "make": if len(os.Args) < 4 { fatal(usage) } err = ff.Make(filename, os.Args[3:]) case "open": dest := "" if len(os.Args) == 4 { dest = os.Args[3] } else if len(os.Args) > 4 { fatal(usage) } err = ff.Open(filename, dest) default: fatal(usage) } if err != nil { fatal(err) } }
Base
1
s := strings.Map(func(c rune) rune { switch c { case ' ', '\t', '\n', '\f', '\r': return c } return -1 }, p.tok.Data) if s != "" { p.addText(s) } case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Frameset: p.addElement() case a.Frame: p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() case a.Noframes: return inHeadIM(p) case a.Template: // TODO: remove this divergence from the HTML5 spec. // // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 return inTemplateIM(p) } case EndTagToken: switch p.tok.DataAtom { case a.Frameset: if p.oe.top().DataAtom != a.Html { p.oe.pop() if p.oe.top().DataAtom != a.Frameset { p.im = afterFramesetIM return true } } } default: // Ignore the token. }
Base
1
func SetJWTSecret() { currentSecret, jwtErr := FetchJWTSecret() if jwtErr != nil { jwtSecretKey = []byte(RandomString(64)) // 512 bit random password if err := StoreJWTSecret(string(jwtSecretKey)); err != nil { logger.FatalLog("something went wrong when configuring JWT authentication") } } else { jwtSecretKey = []byte(currentSecret) } }
Variant
0
func (m *Bar4) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowIssue530 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Bar4: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Bar4: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Str", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowIssue530 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthIssue530 } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthIssue530 } if postIndex > l { return io.ErrUnexpectedEOF } m.Str = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipIssue530(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthIssue530 } if (iNdEx + skippy) < 0 { return ErrInvalidLengthIssue530 } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func (m *Nil) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Nil: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Nil: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { default: iNdEx = preIndex skippy, err := skipThetest(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func (err ErrInvalidCloneAddr) Error() string { return fmt.Sprintf("invalid clone address [is_url_error: %v, is_invalid_path: %v, is_permission_denied: %v]", err.IsURLError, err.IsInvalidPath, err.IsPermissionDenied) }
Base
1
func testExternalNameServiceInsecure(namespace string) { Specify("external name services work over http", func() { t := f.T() f.Fixtures.Echo.Deploy(namespace, "ingress-conformance-echo") externalNameService := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: "external-name-service", }, Spec: corev1.ServiceSpec{ Type: corev1.ServiceTypeExternalName, ExternalName: "ingress-conformance-echo." + namespace, Ports: []corev1.ServicePort{ { Name: "http", Port: 80, }, }, }, } require.NoError(t, f.Client.Create(context.TODO(), externalNameService)) p := &contourv1.HTTPProxy{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: "external-name-proxy", }, Spec: contourv1.HTTPProxySpec{ VirtualHost: &contourv1.VirtualHost{ Fqdn: "externalnameservice.projectcontour.io", }, Routes: []contourv1.Route{ { Services: []contourv1.Service{ { Name: externalNameService.Name, Port: 80, }, }, RequestHeadersPolicy: &contourv1.HeadersPolicy{ Set: []contourv1.HeaderValue{ { Name: "Host", Value: externalNameService.Spec.ExternalName, }, }, }, }, }, }, } f.CreateHTTPProxyAndWaitFor(p, httpProxyValid) res, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{ Host: p.Spec.VirtualHost.Fqdn, Condition: e2e.HasStatusCode(200), }) require.Truef(t, ok, "expected 200 response code, got %d", res.StatusCode) }) }
Class
2
func (x *RuntimeInfo_ModuleInfo) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[50] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) }
Base
1
func TestBuilder_BuildBootstrapAdmin(t *testing.T) { b := New("local-grpc", "local-http", filemgr.NewManager(), nil) t.Run("valid", func(t *testing.T) { adminCfg, err := b.BuildBootstrapAdmin(&config.Config{ Options: &config.Options{ EnvoyAdminAddress: "localhost:9901", }, }) assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "address": { "socketAddress": { "address": "127.0.0.1", "portValue": 9901 } } } `, adminCfg) }) t.Run("bad address", func(t *testing.T) { _, err := b.BuildBootstrapAdmin(&config.Config{ Options: &config.Options{ EnvoyAdminAddress: "xyz1234:zyx4321", }, }) assert.Error(t, err) }) }
Class
2
func (p *OAuthProxy) IsValidRedirect(redirect string) bool { switch { case redirect == "": // The user didn't specify a redirect, should fallback to `/` return false case strings.HasPrefix(redirect, "/") && !strings.HasPrefix(redirect, "//") && !invalidRedirectRegex.MatchString(redirect): return true case strings.HasPrefix(redirect, "http://") || strings.HasPrefix(redirect, "https://"): redirectURL, err := url.Parse(redirect) if err != nil { logger.Printf("Rejecting invalid redirect %q: scheme unsupported or missing", redirect) return false } redirectHostname := redirectURL.Hostname() for _, domain := range p.whitelistDomains { domainHostname, domainPort := splitHostPort(strings.TrimLeft(domain, ".")) if domainHostname == "" { continue } if (redirectHostname == domainHostname) || (strings.HasPrefix(domain, ".") && strings.HasSuffix(redirectHostname, domainHostname)) { // the domain names match, now validate the ports // if the whitelisted domain's port is '*', allow all ports // if the whitelisted domain contains a specific port, only allow that port // if the whitelisted domain doesn't contain a port at all, only allow empty redirect ports ie http and https redirectPort := redirectURL.Port() if (domainPort == "*") || (domainPort == redirectPort) || (domainPort == "" && redirectPort == "") { return true } } } logger.Printf("Rejecting invalid redirect %q: domain / port not in whitelist", redirect) return false default: logger.Printf("Rejecting invalid redirect %q: not an absolute or relative URL", redirect) return false } }
Base
1
func (x *UpdateGroupRequest) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[37] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) }
Base
1
func (x *ListSubscriptionsRequest) Reset() { *x = ListSubscriptionsRequest{} if protoimpl.UnsafeEnabled { mi := &file_console_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } }
Base
1
func (m *FieldMask) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowFieldMask } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: FieldMask: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: FieldMask: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Paths", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowFieldMask } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthFieldMask } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthFieldMask } if postIndex > l { return io.ErrUnexpectedEOF } m.Paths = append(m.Paths, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipFieldMask(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthFieldMask } if (iNdEx + skippy) < 0 { return ErrInvalidLengthFieldMask } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func setCapabilities(spec *specs.Spec, keepCaps ...string) error { currentCaps, err := capability.NewPid2(0) if err != nil { return errors.Wrapf(err, "error reading capabilities of current process") } if err := currentCaps.Load(); err != nil { return errors.Wrapf(err, "error loading capabilities") } caps, err := capability.NewPid2(0) if err != nil { return errors.Wrapf(err, "error reading capabilities of current process") } capMap := map[capability.CapType][]string{ capability.BOUNDING: spec.Process.Capabilities.Bounding, capability.EFFECTIVE: spec.Process.Capabilities.Effective, capability.INHERITABLE: spec.Process.Capabilities.Inheritable, capability.PERMITTED: spec.Process.Capabilities.Permitted, capability.AMBIENT: spec.Process.Capabilities.Ambient, } knownCaps := capability.List() noCap := capability.Cap(-1) for capType, capList := range capMap { for _, capToSet := range capList { cap := noCap for _, c := range knownCaps { if strings.EqualFold("CAP_"+c.String(), capToSet) { cap = c break } } if cap == noCap { return errors.Errorf("error mapping capability %q to a number", capToSet) } caps.Set(capType, cap) } for _, capToSet := range keepCaps { cap := noCap for _, c := range knownCaps { if strings.EqualFold("CAP_"+c.String(), capToSet) { cap = c break } } if cap == noCap { return errors.Errorf("error mapping capability %q to a number", capToSet) } if currentCaps.Get(capType, cap) { caps.Set(capType, cap) } } } if err = caps.Apply(capability.CAPS | capability.BOUNDS | capability.AMBS); err != nil { return errors.Wrapf(err, "error setting capabilities") } return nil }
Base
1
func (m *CustomDash) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: CustomDash: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: CustomDash: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthThetest } postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthThetest } if postIndex > l { return io.ErrUnexpectedEOF } var v github_com_gogo_protobuf_test_custom_dash_type.Bytes m.Value = &v if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipThetest(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func (m *UInt64Value) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowWrappers } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: UInt64Value: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: UInt64Value: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) } m.Value = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowWrappers } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Value |= uint64(b&0x7F) << shift if b < 0x80 { break } } default: iNdEx = preIndex skippy, err := skipWrappers(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthWrappers } if (iNdEx + skippy) < 0 { return ErrInvalidLengthWrappers } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func (x *UserList) ProtoReflect() protoreflect.Message { mi := &file_console_proto_msgTypes[39] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) }
Base
1
func (m *CustomContainer) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: CustomContainer: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: CustomContainer: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field CustomStruct", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowThetest } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthThetest } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthThetest } if postIndex > l { return io.ErrUnexpectedEOF } if err := m.CustomStruct.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipThetest(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) < 0 { return ErrInvalidLengthThetest } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
func (m *FloatingPoint) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowMapsproto2 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: FloatingPoint: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: FloatingPoint: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field F", wireType) } var v uint64 if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) iNdEx += 8 v2 := float64(math.Float64frombits(v)) m.F = &v2 default: iNdEx = preIndex skippy, err := skipMapsproto2(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthMapsproto2 } if (iNdEx + skippy) < 0 { return ErrInvalidLengthMapsproto2 } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
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() } }
Class
2
func TestResourceServer_ValidateAccessToken(t *testing.T) { r := newMockResourceServer(t) _, err := r.ValidateAccessToken(context.Background(), "myserver", sampleIDToken) assert.Error(t, err) }
Base
1
func (g DashboardHandler) Append(router *mux.Router) { if g.Assets == nil { log.WithoutContext().Error("No assets for dashboard") return } // Expose dashboard router.Methods(http.MethodGet). Path("/"). HandlerFunc(func(response http.ResponseWriter, request *http.Request) { http.Redirect(response, request, request.Header.Get("X-Forwarded-Prefix")+"/dashboard/", http.StatusFound) }) router.Methods(http.MethodGet). PathPrefix("/dashboard/"). Handler(http.StripPrefix("/dashboard/", http.FileServer(g.Assets))) }
Base
1
func TestBuilder_BuildBootstrapStaticResources(t *testing.T) { t.Run("valid", func(t *testing.T) { b := New("localhost:1111", "localhost:2222", filemgr.NewManager(), nil) staticCfg, err := b.BuildBootstrapStaticResources() assert.NoError(t, err) testutil.AssertProtoJSONEqual(t, ` { "clusters": [ { "name": "pomerium-control-plane-grpc", "type": "STATIC", "connectTimeout": "5s", "http2ProtocolOptions": {}, "loadAssignment": { "clusterName": "pomerium-control-plane-grpc", "endpoints": [{ "lbEndpoints": [{ "endpoint": { "address": { "socketAddress":{ "address": "127.0.0.1", "portValue": 1111 } } } }] }] } } ] } `, staticCfg) }) t.Run("bad gRPC address", func(t *testing.T) { b := New("xyz:zyx", "localhost:2222", filemgr.NewManager(), nil) _, err := b.BuildBootstrapStaticResources() assert.Error(t, err) }) }
Class
2
func (m *Bar8) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowIssue530 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Bar8: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Bar8: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Bars1", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowIssue530 } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= int(b&0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthIssue530 } postIndex := iNdEx + msglen if postIndex < 0 { return ErrInvalidLengthIssue530 } if postIndex > l { return io.ErrUnexpectedEOF } m.Bars1 = append(m.Bars1, Bar9{}) if err := m.Bars1[len(m.Bars1)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipIssue530(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthIssue530 } if (iNdEx + skippy) < 0 { return ErrInvalidLengthIssue530 } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil }
Variant
0
ctx := log.WithContext(context.TODO(), func(c zerolog.Context) zerolog.Context { return c.Str("config_file_source", configFile) }) options, err := newOptionsFromConfig(configFile) if err != nil { return nil, err } ports, err := netutil.AllocatePorts(3) if err != nil { return nil, err } grpcPort := ports[0] httpPort := ports[1] outboundPort := ports[2] cfg := &Config{ Options: options, EnvoyVersion: envoyVersion, GRPCPort: grpcPort, HTTPPort: httpPort, OutboundPort: outboundPort, } metrics.SetConfigInfo(ctx, cfg.Options.Services, "local", cfg.Checksum(), true) src := &FileOrEnvironmentSource{ configFile: configFile, config: cfg, } options.viper.OnConfigChange(src.onConfigChange(ctx)) go options.viper.WatchConfig() return src, nil }
Class
2
func handleConnect(config *Config, pctx *goproxy.ProxyCtx) error { sctx := pctx.UserData.(*smokescreenContext) // Check if requesting role is allowed to talk to remote sctx.decision, sctx.lookupTime, pctx.Error = checkIfRequestShouldBeProxied(config, pctx.Req, pctx.Req.Host) if pctx.Error != nil { return pctx.Error } if !sctx.decision.allow { return denyError{errors.New(sctx.decision.reason)} } return nil }
Base
1
func newContainerInit(t initType, pipe *os.File, consoleSocket *os.File, fifoFd, logFd int) (initer, error) { var config *initConfig if err := json.NewDecoder(pipe).Decode(&config); err != nil { return nil, err } if err := populateProcessEnvironment(config.Env); err != nil { return nil, err } switch t { case initSetns: return &linuxSetnsInit{ pipe: pipe, consoleSocket: consoleSocket, config: config, logFd: logFd, }, nil case initStandard: return &linuxStandardInit{ pipe: pipe, consoleSocket: consoleSocket, parentPid: unix.Getppid(), config: config, fifoFd: fifoFd, logFd: logFd, }, nil } return nil, fmt.Errorf("unknown init type %q", t) }
Base
1
func (svc *Service) GetGlobalScheduledQueries(ctx context.Context, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) { if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionRead); err != nil { return nil, err } gp, err := svc.ds.EnsureGlobalPack(ctx) if err != nil { return nil, err } return svc.ds.ListScheduledQueriesInPackWithStats(ctx, gp.ID, opts) }
Class
2
func isLoopbackURI(requested *url.URL, registeredURI string) bool { registered, err := url.Parse(registeredURI) if err != nil { return false } if registered.Scheme != "http" || !isLoopbackAddress(registered.Host) { return false } if requested.Scheme == "http" && isLoopbackAddress(requested.Host) && registered.Path == requested.Path { return true } return false }
Base
1
func NewConcatKDF(hash crypto.Hash, z, algID, ptyUInfo, ptyVInfo, supPubInfo, supPrivInfo []byte) io.Reader { buffer := make([]byte, len(algID)+len(ptyUInfo)+len(ptyVInfo)+len(supPubInfo)+len(supPrivInfo)) n := 0 n += copy(buffer, algID) n += copy(buffer[n:], ptyUInfo) n += copy(buffer[n:], ptyVInfo) n += copy(buffer[n:], supPubInfo) copy(buffer[n:], supPrivInfo) hasher := hash.New() return &concatKDF{ z: z, info: buffer, hasher: hasher, cache: []byte{}, i: 1, } }
Base
1