// FindForDecryption ignores tlfName or teamID based on membersType.
553363
func (k *KeyFinderImpl) FindForDecryption(ctx context.Context,
	tlfName string, tlfID chat1.TLFID,
	membersType chat1.ConversationMembersType, public bool,
	keyGeneration int, kbfsEncrypted bool) (res types.CryptKey, err error) {
	ckey := k.decCacheKey(tlfName, tlfID, membersType, keyGeneration, public, kbfsEncrypted)
	existing, ok := k.lookupDecKey(ckey)
	if ok {
		return existing, nil
	}
	defer func() {
		if err == nil {
			k.writeDecKey(ckey, res)
		}
	}()
	return k.createNameInfoSource(ctx, membersType).DecryptionKey(ctx, tlfName, tlfID,
		membersType, public, keyGeneration, kbfsEncrypted)
}
584837
func (km *KeyManagerStandard) GetTLFCryptKeyForBlockDecryption(
	ctx context.Context, kmd libkey.KeyMetadata, blockPtr data.BlockPointer) (
	tlfCryptKey kbfscrypto.TLFCryptKey, err error) {
	return km.getTLFCryptKeyUsingCurrentDevice(ctx, kmd, blockPtr.KeyGen, true)
}
745105
func (s *diskStorageGeneric) get(mctx libkb.MetaContext, teamID keybase1.TeamID, public bool) (teamDataGeneric, bool, error) {
	s.Lock()
	defer s.Unlock()

	key := s.dbKey(mctx, teamID, public)
	item := s.getEmptyDiskItem()
	found, err := s.encryptedDB.Get(mctx.Ctx(), key, item)
	if (err != nil) || !found {
		return nil, found, err
	}

	if item.version() != s.version {
		// Pretend it wasn't found.
		return nil, false, nil
	}

	ret := item.value()

	// Sanity check
	if len(ret.ID()) == 0 {
		return nil, false, fmt.Errorf("decode from disk had empty team id")
	}
	if !ret.ID().Eq(teamID) {
		return nil, false, fmt.Errorf("decode from disk had wrong team id %v != %v", ret.ID(), teamID)
	}
	if ret.IsPublic() != public {
		return nil, false, fmt.Errorf("decode from disk had wrong publicness %v != %v (%v)", ret.IsPublic(), public, teamID)
	}

	return item.value(), true, nil
}
645446
func (p *SeriesPartition) FindIDTypedBySeriesKey(key []byte) SeriesIDTyped {
	p.mu.RLock()
	if p.closed {
		p.mu.RUnlock()
		return SeriesIDTyped{}
	}
	id := p.index.FindIDBySeriesKey(p.segments, key)
	p.mu.RUnlock()
	return id
}
726506
func (d *DNSProvider) findTxtRecord(fqdn string, zoneID int) (*Record, error) {
	result, err := d.makeRequest(http.MethodGet, fmt.Sprintf("/domains/%d/records?type=TXT&name=%s", zoneID, dns01.UnFqdn(fqdn)), nil)
	if err != nil {
		return nil, err
	}

	var records Records
	err = json.Unmarshal(result, &records)
	if err != nil {
		return nil, err
	}

	switch len(records.Record) {
	case 1:
	case 0:
		return nil, fmt.Errorf("no TXT record found for %s", fqdn)
	default:
		return nil, fmt.Errorf("more than 1 TXT record found for %s", fqdn)
	}

	return &records.Record[0], nil
}
98944
func ExtractExactOnSingleWordQuery(opts ...interface{}) *opt.ExactOnSingleWordQueryOption {
	for _, o := range opts {
		if v, ok := o.(*opt.ExactOnSingleWordQueryOption); ok {
			return v
		}
	}
	return nil
}
523692
func (r Security_Certificate) FindByCommonName(commonName *string) (resp []datatypes.Security_Certificate, err error) {
	params := []interface{}{
		commonName,
	}
	err = r.Session.DoRequest("SoftLayer_Security_Certificate", "findByCommonName", params, &r.Options, &resp)
	return
}
763309
func (km *KeyManagerStandard) GetTLFCryptKeyOfAllGenerations(
	ctx context.Context, kmd libkey.KeyMetadata) (
	keys []kbfscrypto.TLFCryptKey, err error) {
	for g := kbfsmd.FirstValidKeyGen; g <= kmd.LatestKeyGeneration(); g++ {
		var key kbfscrypto.TLFCryptKey
		key, err = km.getTLFCryptKeyUsingCurrentDevice(ctx, kmd, g, true)
		if err != nil {
			return keys, err
		}
		keys = append(keys, key)
	}
	return keys, nil
}
1084494
func TLFReaderKeyBundleIDFromString(id string) (TLFReaderKeyBundleID, error) {
	if len(id) == 0 {
		return TLFReaderKeyBundleID{}, nil
	}
	h, err := kbfshash.HashFromString(id)
	if err != nil {
		return TLFReaderKeyBundleID{}, err
	}
	return TLFReaderKeyBundleID{h}, nil
}
370414
func (k *KeybaseServiceBase) GetTLFCryptKeys(ctx context.Context,
	query keybase1.TLFQuery) (res keybase1.GetTLFCryptKeysRes, err error) {
	if ctx, err = tlfhandle.MakeExtendedIdentify(
		CtxWithRandomIDReplayable(ctx,
			CtxKeybaseServiceIDKey, CtxKeybaseServiceOpID, k.log),
		query.IdentifyBehavior,
	); err != nil {
		return keybase1.GetTLFCryptKeysRes{}, err
	}

	tlfHandle, err := getHandleFromFolderName(
		ctx, k.config.KBPKI(), k.config.MDOps(), k.config, query.TlfName, false)
	if err != nil {
		return res, err
	}

	res.NameIDBreaks.CanonicalName = keybase1.CanonicalTlfName(
		tlfHandle.GetCanonicalName())

	keys, id, err := k.config.KBFSOps().GetTLFCryptKeys(ctx, tlfHandle)
	if err != nil {
		return res, err
	}
	res.NameIDBreaks.TlfID = keybase1.TLFID(id.String())

	for i, key := range keys {
		res.CryptKeys = append(res.CryptKeys, keybase1.CryptKey{
			KeyGeneration: int(kbfsmd.FirstValidKeyGen) + i,
			Key:           keybase1.Bytes32(key.Data()),
		})
	}

	if query.IdentifyBehavior.WarningInsteadOfErrorOnBrokenTracks() {
		res.NameIDBreaks.Breaks = tlfhandle.GetExtendedIdentify(ctx).
			GetTlfBreakAndClose()
	}

	return res, nil
}
370278
func FindSecrets(tx ReadTx, by By) ([]*api.Secret, error) {
	checkType := func(by By) error {
		switch by.(type) {
		case byName, byNamePrefix, byIDPrefix, byCustom, byCustomPrefix:
			return nil
		default:
			return ErrInvalidFindBy
		}
	}

	secretList := []*api.Secret{}
	appendResult := func(o api.StoreObject) {
		secretList = append(secretList, o.(*api.Secret))
	}

	err := tx.find(tableSecret, by, checkType, appendResult)
	return secretList, err
}
153002
func (m *GormResourceRepository) FindWithRoleByResourceTypeAndIdentity(ctx context.Context, resourceType string, identityID uuid.UUID) ([]string, error) {
	defer goa.MeasureSince([]string{"goa", "db", "resource", "FindWithRoleByResourceTypeAndIdentity"}, time.Now())
	var result []string
	db := m.db.Raw(`
		/* list all resources with their type and their ancestor (whatever level) */
		WITH RECURSIVE all_resources AS ( 
			SELECT r.resource_id, r.resource_type_id, r.parent_resource_id as ancestor_resource_id 
			FROM resource r INNER JOIN resource_type rt on r.resource_type_id = rt.resource_type_id 
			WHERE rt.name = $2 /* limit to resources of the given type */
			UNION SELECT r.resource_id, r.resource_type_id, a.ancestor_resource_id  
			FROM resource r INNER JOIN all_resources a ON r.parent_resource_id = a.resource_id
			WHERE a.ancestor_resource_id IS NOT NULL
			  AND r.deleted_at IS NULL
		),
		/* list the identities of the teams to which the current user belongs, plus herself's identity */
		teams AS ( 
			SELECT member_of as "id"
			FROM membership
			WHERE member_id = $1 /* user's identity */
			UNION SELECT m.member_of
			FROM membership m INNER JOIN teams ON teams.id = m.member_id
		)

		/* list the roles on resources of the given type when the user has a direct role */
		SELECT res.resource_id
		FROM identity_role ir
			INNER JOIN role ON role.role_id = ir.role_id
			INNER JOIN resource res ON res.resource_id = ir.resource_id
			INNER JOIN resource_type rt ON rt.resource_type_id = res.resource_type_id
		WHERE rt.name = $2 /* filter on given resource type */
			AND ir.identity_id IN ( /* look-up users alone or as a member of a team */
				SELECT $1
				UNION SELECT teams.id from teams
			)
			AND res.deleted_at IS NULL
			AND role.deleted_at IS NULL
			AND ir.deleted_at IS NULL
		/* list the roles on resources of the given type when the user has a role inherited from an ancestor resource via default role mapping */
		UNION
		SELECT inherited_res.resource_id
		FROM identity_role ir
			INNER JOIN role via_role ON via_role.role_id = ir.role_id
			INNER JOIN all_resources ar ON ir.resource_id = ar.ancestor_resource_id
			INNER JOIN resource inherited_res ON inherited_res.resource_id = ar.resource_id
			INNER JOIN resource_type inherited_rt ON inherited_rt.resource_type_id = inherited_res.resource_type_id
			INNER JOIN default_role_mapping drm on (ir.role_id = drm.from_role_id AND drm.resource_type_id = inherited_res.resource_type_id)
			INNER JOIN role inherited_role on drm.to_role_id = inherited_role.role_id
		WHERE inherited_rt.name = $2 /* filter on given resource type */
			AND ir.identity_id IN ( /* look-up users alone or as a member of a team */
				SELECT $1
				UNION SELECT teams.id from teams
			)
        	AND ir.deleted_at IS NULL
			AND via_role.deleted_at IS NULL
			AND inherited_res.deleted_at IS NULL
			AND drm.deleted_at IS NULL
			AND inherited_role.deleted_at IS NULL`,
		identityID, resourceType)

	rows, err := db.Rows()
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resourceType": resourceType,
			"err":          err,
		}, "error running custom sql to get available roles")
		return result, err
	}
	defer rows.Close()

	columns, err := rows.Columns()
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": resourceType,
			"err":           err,
		}, "error getting columns")
		return result, errors.NewInternalError(ctx, err)
	}
	columnValues := make([]interface{}, len(columns))

	var ignore interface{}
	for index := range columnValues {
		columnValues[index] = &ignore
	}

	for rows.Next() {
		var resourceID string
		if err = rows.Scan(&resourceID); err != nil {
			return result, errs.Wrapf(err, "failed to read database record")
		}
		result = append(result, resourceID)
	}
	return result, err
}
132934
func (d *Decoder) findHeader() (int, error) {
	header := uint32(0)
	consumed := 0

retry:
	for header&0xfff00000 != 0xfff00000 {
		b, err := d.stream.readByte()
		if err != nil {
			if err == io.EOF {
				if header&0xfff000 == 0xfff000 || header&0xfff0 == 0xfff0 {
					err = io.ErrUnexpectedEOF
				}
			}
			return 0, err
		}

		consumed++
		header = header<<8 | uint32(b)
	}

	// Free format headers have a high false positive rate, so we only accept
	// them under some fairly restricted circumstances.
	ffAllowed := consumed == 4 || d.layer != 0 && d.bitrateIndex == 0

	if !d.trueHeader(header, ffAllowed) {
		header &^= 0xff << 24
		goto retry
	}

	return int(header), nil
}
1125773
func (s *resourceServiceImpl) FindWithRoleByResourceTypeAndIdentity(ctx context.Context, resourceType string, identityID uuid.UUID) ([]string, error) {
	return s.Repositories().ResourceRepository().FindWithRoleByResourceTypeAndIdentity(ctx, resourceType, identityID)
}
289975
func FindEnumForFile(f *pb.FileDescriptorProto, name string) int {
	for i, x := range f.GetEnumType() {
		if x.GetName() == name {
			return i
		}
	}
	return -1
}
717735
func (md *MDOpsStandard) GetForTLF(
	ctx context.Context, id tlf.ID, lockBeforeGet *keybase1.LockID) (
	ImmutableRootMetadata, error) {
	return md.getForTLF(ctx, id, kbfsmd.NullBranchID, kbfsmd.Merged, lockBeforeGet)
}
794130
func (md *RootMetadataV2) GetTLFCryptKeyParams(
	keyGen KeyGen, user keybase1.UID, key kbfscrypto.CryptPublicKey,
	_ ExtraMetadata) (
	kbfscrypto.TLFEphemeralPublicKey, kbfscrypto.EncryptedTLFCryptKeyClientHalf,
	kbfscrypto.TLFCryptKeyServerHalfID, bool, error) {
	wkb, rkb, err := md.getTLFKeyBundles(keyGen)
	if err != nil {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false, err
	}

	dkim := wkb.WKeys[user]
	if dkim == nil {
		dkim = rkb.RKeys[user]
		if dkim == nil {
			return kbfscrypto.TLFEphemeralPublicKey{},
				kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
				kbfscrypto.TLFCryptKeyServerHalfID{}, false, nil
		}
	}
	info, ok := dkim[key.KID()]
	if !ok {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false, nil
	}

	_, _, ePubKey, err := GetEphemeralPublicKeyInfoV2(info, *wkb, *rkb)
	if err != nil {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false, err
	}

	return ePubKey, info.ClientHalf, info.ServerHalfID, true, nil
}