// verifyMemberRoleInTeam checks if role give in MemberInfo matches
// what team chain says. Nothing is checked when MemberInfo's role is
// NONE, in this context it means that user has implied membership in
// the team and no role given in sigchain.
511177
func verifyMemberRoleInTeam(ctx context.Context, userID keybase1.UID, expectedRole keybase1.TeamRole,
	team *Team) (res keybase1.UserVersion, err error) {
	if expectedRole == keybase1.TeamRole_NONE {
		return res, nil
	}

	memberUV, err := team.chain().GetLatestUVWithUID(userID)
	if err != nil {
		return res, err
	}
	role, err := team.chain().GetUserRole(memberUV)
	if err != nil {
		return res, err
	}
	if role != expectedRole {
		return res, fmt.Errorf("unexpected member role: expected %v but actual role is %v", expectedRole, role)
	}
	return memberUV, nil
}
62175
func GetAndVerifyPerTeamKey(mctx libkb.MetaContext, teamData *keybase1.TeamData,
	gen keybase1.PerTeamKeyGeneration) (ret keybase1.PerTeamKeySeedItem, err error) {

	ret, ok := teamData.PerTeamKeySeedsUnverified[gen]
	if !ok {
		return ret, libkb.NotFoundError{
			Msg: fmt.Sprintf("no team secret found at generation %v", gen)}
	}

	km, err := NewTeamKeyManagerWithSecret(ret.Seed, gen)
	if err != nil {
		return ret, err
	}

	chainKey, err := TeamSigChainState{inner: teamData.Chain}.GetPerTeamKeyAtGeneration(gen)
	if err != nil {
		return ret, err
	}

	// Takes roughly 280us on android (Honor 6X)
	localSigKey, err := km.SigningKey()
	if err != nil {
		return ret, err
	}

	// Takes roughly 900us on android (Honor 6X)
	localEncKey, err := km.EncryptionKey()
	if err != nil {
		return ret, err
	}

	if !chainKey.SigKID.SecureEqual(localSigKey.GetKID()) {
		mctx.Debug("sig KID gen:%v (local) %v != %v (chain)", gen, localSigKey.GetKID(), chainKey.SigKID)
		return ret, fmt.Errorf("wrong team key found at generation %v", gen)
	}

	if !chainKey.EncKID.SecureEqual(localEncKey.GetKID()) {
		mctx.Debug("enc KID gen:%v (local) %v != %v (chain)", gen, localEncKey.GetKID(), chainKey.EncKID)
		return ret, fmt.Errorf("wrong team key (enc) found at generation %v", gen)
	}

	return ret, nil
}
1156934
func (a *AuthWithRoles) hasRemoteBuiltinRole(name string) bool {
	if _, ok := a.checker.(RemoteBuiltinRoleSet); !ok {
		return false
	}
	if !a.checker.HasRole(name) {
		return false
	}

	return true
}
626778
func selectTeam(ctx context.Context, api *api.Client, orgID *identity.ID, name string) (*envelope.Team, bool, error) {
	teams, err := api.Teams.List(ctx, orgID, "", primitive.MachineTeamName)
	if err != nil {
		return nil, false, err
	}

	for _, t := range teams {
		if t.Body.Name == name {
			return &t, false, nil
		}
	}

	return nil, true, nil
}
137106
func (l *TeamLoader) checkParentChildOperations(ctx context.Context,
	me keybase1.UserVersion, loadingTeamID keybase1.TeamID, parentID *keybase1.TeamID, readSubteamID keybase1.TeamID,
	parentChildOperations []*parentChildOperation, proofSet *proofSetT) error {

	if len(parentChildOperations) == 0 {
		return nil
	}
	if parentID == nil {
		return fmt.Errorf("cannot check parent-child operations with no parent")
	}

	var needParentSeqnos []keybase1.Seqno
	for _, pco := range parentChildOperations {
		needParentSeqnos = append(needParentSeqnos, pco.parentSeqno)
	}

	parent, err := l.load2(ctx, load2ArgT{
		teamID: *parentID,

		reason: "checkParentChildOperations-parent",

		needAdmin:                             false,
		needKeyGeneration:                     0,
		needApplicationsAtGenerations:         nil,
		needApplicationsAtGenerationsWithKBFS: nil,
		wantMembers:                           nil,
		wantMembersRole:                       keybase1.TeamRole_NONE,
		forceFullReload:                       false,
		forceRepoll:                           false,
		staleOK:                               true, // stale is fine, as long as get those seqnos.

		needSeqnos:    needParentSeqnos,
		readSubteamID: &readSubteamID,

		me: me,
	})
	if err != nil {
		return fmt.Errorf("error loading parent: %v", err)
	}

	parentChain := TeamSigChainState{inner: parent.team.Chain}

	for _, pco := range parentChildOperations {
		err = l.checkOneParentChildOperation(ctx, pco, loadingTeamID, &parentChain)
		if err != nil {
			return err
		}
	}

	// Give a more up-to-date linkmap to the ordering checker for the parent.
	// Without this it could fail if the parent is new.
	// Because the team linkmap in the proof objects is stale.
	proofSet.SetTeamLinkMap(ctx, parentChain.inner.Id, parentChain.inner.LinkIDs)

	return nil
}
1143431
func GetTeamsByUser(query *m.GetTeamsByUserQuery) error {
	query.Result = make([]*m.TeamDTO, 0)

	var sql bytes.Buffer

	sql.WriteString(getTeamSelectSqlBase())
	sql.WriteString(` INNER JOIN team_member on team.id = team_member.team_id`)
	sql.WriteString(` WHERE team.org_id = ? and team_member.user_id = ?`)

	err := x.SQL(sql.String(), query.OrgId, query.UserId).Find(&query.Result)
	return err
}
328272
func (db ErroringDB) CheckMembership(c context.Context, id identity.Identity, groups []string) ([]string, error) {
	logging.Errorf(c, "%s", db.Error)
	return nil, db.Error
}
653627
func (f *FastTeamChainLoader) verifyTeamNameViaParentLoad(m libkb.MetaContext, id keybase1.TeamID, isPublic bool, unverifiedName keybase1.TeamName, parent *keybase1.UpPointer, bottomSubteam keybase1.TeamID, forceRefresh bool) (res keybase1.TeamName, err error) {

	defer m.Trace(fmt.Sprintf("FastTeamChainLoader#verifyTeamNameViaParentLoad(%s,%s)", id, unverifiedName), func() error { return err })()

	if parent == nil {
		if !unverifiedName.IsRootTeam() {
			return res, NewBadNameError("expected a root team")
		}
		if !unverifiedName.ToTeamID(isPublic).Eq(id) {
			return res, NewBadNameError("root team v. team ID mismatch")
		}
		return unverifiedName, nil
	}

	if parent.ParentID.IsPublic() != isPublic {
		return res, NewBadPublicError(parent.ParentID, isPublic)
	}

	parentRes, err := f.load(m, fastLoadArg{
		FastTeamLoadArg: keybase1.FastTeamLoadArg{
			ID:           parent.ParentID,
			Public:       isPublic,
			ForceRefresh: forceRefresh,
		},
		downPointersNeeded: []keybase1.Seqno{parent.ParentSeqno},
		needLatestName:     true,
		readSubteamID:      bottomSubteam,
	})
	if err != nil {
		return res, err
	}
	downPointer, ok := parentRes.downPointers[parent.ParentSeqno]
	if !ok {
		return res, NewBadNameError("down pointer not found in parent")
	}
	suffix := downPointer.NameComponent

	parentName, err := f.verifyTeamNameViaParentLoad(m, parent.ParentID, isPublic, parentRes.unverifiedName, parentRes.upPointer, bottomSubteam, forceRefresh)
	if err != nil {
		return res, err
	}

	return parentName.Append(suffix)
}
693050
func (ref *Ref) Verify(serializedID []byte, msg []byte, sig []byte) error {
	membership, err := ref.get()
	if err != nil {
		return err
	}
	return membership.Verify(serializedID, msg, sig)
}
712410
func (r Account_ProofOfConcept) GetTotalRequestsPendingIntegratedOfferingTeamReview(accessToken *string) (resp int, err error) {
	params := []interface{}{
		accessToken,
	}
	err = r.Session.DoRequest("SoftLayer_Account_ProofOfConcept", "getTotalRequestsPendingIntegratedOfferingTeamReview", params, &r.Options, &resp)
	return
}
935921
func RemoveTeamMember(orgID, teamID, uid int64) error {
	sess := x.NewSession()
	defer sess.Close()
	if err := sess.Begin(); err != nil {
		return err
	}
	if err := removeTeamMember(sess, orgID, teamID, uid); err != nil {
		return err
	}
	return sess.Commit()
}
1224386
func (hs *HTTPServer) GetTeamPreferences(c *m.ReqContext) Response {
	teamId := c.ParamsInt64(":teamId")
	orgId := c.OrgId

	if err := teamguardian.CanAdmin(hs.Bus, orgId, teamId, c.SignedInUser); err != nil {
		return Error(403, "Not allowed to view team preferences.", err)
	}

	return getPreferencesFor(orgId, 0, teamId)
}
1144820
func (rm *roleManager) removeMember(ctx context.Context, member *membership.Member) {
	// Quorum safeguard - quorum should have been checked before a node was allowed to be demoted, but if in the
	// intervening time some other node disconnected, removing this node would result in a loss of cluster quorum.
	// We leave it
	if !rm.raft.CanRemoveMember(member.RaftID) {
		// TODO(aaronl): Retry later
		log.G(ctx).Debugf("can't demote node %s at this time: removing member from raft would result in a loss of quorum", member.NodeID)
		return
	}

	rmCtx, rmCancel := context.WithTimeout(rm.ctx, removalTimeout)
	defer rmCancel()

	if member.RaftID == rm.raft.Config.ID {
		// Don't use rmCtx, because we expect to lose
		// leadership, which will cancel this context.
		log.G(ctx).Info("demoted; transferring leadership")
		err := rm.raft.TransferLeadership(context.Background())
		if err == nil {
			return
		}
		log.G(ctx).WithError(err).Info("failed to transfer leadership")
	}
	if err := rm.raft.RemoveMember(rmCtx, member.RaftID); err != nil {
		// TODO(aaronl): Retry later
		log.G(ctx).WithError(err).Debugf("can't demote node %s at this time", member.NodeID)
	}
}
361008
func (c *Client) GetTeamRoster(teamKey string, week int) ([]Player, error) {
	content, err := c.GetFantasyContent(
		fmt.Sprintf("%s/team/%s/roster;week=%d",
			YahooBaseURL,
			teamKey,
			week))
	if err != nil {
		return nil, err
	}

	return content.Team.Roster.Players, nil
}
293026
func (t TeamID) IsSubTeam() bool {
	suffix := t[len(t)-2:]
	switch suffix {
	case SUB_TEAMID_PRIVATE_SUFFIX_HEX, SUB_TEAMID_PUBLIC_SUFFIX_HEX:
		return true
	}
	return false
}
1195830
func (api *Client) GetTeamInfoContext(ctx context.Context) (*TeamInfo, error) {
	values := url.Values{
		"token": {api.token},
	}

	response, err := api.teamRequest(ctx, "team.info", values)
	if err != nil {
		return nil, err
	}
	return &response.Team, nil
}
594650
func verifyRoleTagValue(rTag *roleTag, roleEntry *awsRoleEntry) (bool, error) {
	if rTag == nil {
		return false, fmt.Errorf("nil role tag")
	}

	if roleEntry == nil {
		return false, fmt.Errorf("nil role entry")
	}

	// Fetch the plaintext part of role tag
	rTagPlaintext, err := prepareRoleTagPlaintextValue(rTag)
	if err != nil {
		return false, err
	}

	// Compute the HMAC of the plaintext
	hmacB64, err := createRoleTagHMACBase64(roleEntry.HMACKey, rTagPlaintext)
	if err != nil {
		return false, err
	}

	return subtle.ConstantTimeCompare([]byte(rTag.HMAC), []byte(hmacB64)) == 1, nil
}