// handleTokenSecretUpdate checks if the service account token secret is populated with
// token data and triggers re-sync of service account when the data are observed.
423200
func (e *DockercfgController) handleTokenSecretUpdate(oldObj, newObj interface{}) {
	secret := newObj.(*v1.Secret)
	if secret.Annotations[DeprecatedKubeCreatedByAnnotation] != CreateDockercfgSecretsController {
		return
	}
	isPopulated := len(secret.Data[v1.ServiceAccountTokenKey]) > 0

	wasPopulated := false
	if oldObj != nil {
		oldSecret := oldObj.(*v1.Secret)
		wasPopulated = len(oldSecret.Data[v1.ServiceAccountTokenKey]) > 0
		klog.V(5).Infof("Updating token secret %s/%s", secret.Namespace, secret.Name)
	} else {
		klog.V(5).Infof("Adding token secret %s/%s", secret.Namespace, secret.Name)
	}

	if !wasPopulated && isPopulated {
		e.enqueueServiceAccountForToken(secret)
	}
}
1299957
func (ts *TokenStore) handleCreateCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, orphan bool, role *tsRoleEntry) (*logical.Response, error) {
	// Read the parent policy
	parent, err := ts.Lookup(ctx, req.ClientToken)
	if err != nil {
		return nil, errwrap.Wrapf("parent token lookup failed: {{err}}", err)
	}
	if parent == nil {
		return logical.ErrorResponse("parent token lookup failed: no parent found"), logical.ErrInvalidRequest
	}
	if parent.Type == logical.TokenTypeBatch {
		return logical.ErrorResponse("batch tokens cannot create more tokens"), nil
	}

	// A token with a restricted number of uses cannot create a new token
	// otherwise it could escape the restriction count.
	if parent.NumUses > 0 {
		return logical.ErrorResponse("restricted use token cannot generate child tokens"),
			logical.ErrInvalidRequest
	}

	// Check if the client token has sudo/root privileges for the requested path
	isSudo := ts.System().SudoPrivilege(ctx, req.MountPoint+req.Path, req.ClientToken)

	// Read and parse the fields
	var data struct {
		ID              string
		Policies        []string
		Metadata        map[string]string `mapstructure:"meta"`
		NoParent        bool              `mapstructure:"no_parent"`
		NoDefaultPolicy bool              `mapstructure:"no_default_policy"`
		Lease           string
		TTL             string
		Renewable       *bool
		ExplicitMaxTTL  string `mapstructure:"explicit_max_ttl"`
		DisplayName     string `mapstructure:"display_name"`
		NumUses         int    `mapstructure:"num_uses"`
		Period          string
		Type            string `mapstructure:"type"`
	}
	if err := mapstructure.WeakDecode(req.Data, &data); err != nil {
		return logical.ErrorResponse(fmt.Sprintf(
			"Error decoding request: %s", err)), logical.ErrInvalidRequest
	}

	// If the context's namespace is different from the parent and this is an
	// orphan token creation request, then this is an admin token generation for
	// the namespace
	ns, err := namespace.FromContext(ctx)
	if err != nil {
		return nil, err
	}
	if ns.ID != parent.NamespaceID {
		parentNS, err := NamespaceByID(ctx, parent.NamespaceID, ts.core)
		if err != nil {
			ts.logger.Error("error looking up parent namespace", "error", err, "parent_namespace", parent.NamespaceID)
			return nil, ErrInternalError
		}
		if parentNS == nil {
			ts.logger.Error("could not find information for parent namespace", "parent_namespace", parent.NamespaceID)
			return nil, ErrInternalError
		}

		if !isSudo {
			return logical.ErrorResponse("root or sudo privileges required to directly generate a token in a child namespace"), logical.ErrInvalidRequest
		}

		if strutil.StrListContains(data.Policies, "root") {
			return logical.ErrorResponse("root tokens may not be created from a parent namespace"), logical.ErrInvalidRequest
		}
	}

	renewable := true
	if data.Renewable != nil {
		renewable = *data.Renewable
	}

	tokenType := logical.TokenTypeService
	tokenTypeStr := data.Type
	if role != nil {
		switch role.TokenType {
		case logical.TokenTypeDefault, logical.TokenTypeDefaultService:
			// Use the user-given value, but fall back to service
		case logical.TokenTypeDefaultBatch:
			// Use the user-given value, but fall back to batch
			if tokenTypeStr == "" {
				tokenTypeStr = logical.TokenTypeBatch.String()
			}
		case logical.TokenTypeService:
			tokenTypeStr = logical.TokenTypeService.String()
		case logical.TokenTypeBatch:
			tokenTypeStr = logical.TokenTypeBatch.String()
		default:
			return logical.ErrorResponse(fmt.Sprintf("role being used for token creation contains invalid token type %q", role.TokenType.String())), nil
		}
	}
	switch tokenTypeStr {
	case "", "service":
	case "batch":
		var badReason string
		switch {
		case data.ExplicitMaxTTL != "":
			dur, err := parseutil.ParseDurationSecond(data.ExplicitMaxTTL)
			if err != nil {
				return logical.ErrorResponse(`"explicit_max_ttl" value could not be parsed`), nil
			}
			if dur != 0 {
				badReason = "explicit_max_ttl"
			}
		case data.NumUses != 0:
			badReason = "num_uses"
		case data.Period != "":
			dur, err := parseutil.ParseDurationSecond(data.Period)
			if err != nil {
				return logical.ErrorResponse(`"period" value could not be parsed`), nil
			}
			if dur != 0 {
				badReason = "period"
			}
		}
		if badReason != "" {
			return logical.ErrorResponse(fmt.Sprintf("batch tokens cannot have %q set", badReason)), nil
		}
		tokenType = logical.TokenTypeBatch
		renewable = false
	default:
		return logical.ErrorResponse("invalid 'token_type' value"), logical.ErrInvalidRequest
	}

	// Verify the number of uses is positive
	if data.NumUses < 0 {
		return logical.ErrorResponse("number of uses cannot be negative"),
			logical.ErrInvalidRequest
	}

	// Setup the token entry
	te := logical.TokenEntry{
		Parent: req.ClientToken,

		// The mount point is always the same since we have only one token
		// store; using req.MountPoint causes trouble in tests since they don't
		// have an official mount
		Path: fmt.Sprintf("auth/token/%s", req.Path),

		Meta:         data.Metadata,
		DisplayName:  "token",
		NumUses:      data.NumUses,
		CreationTime: time.Now().Unix(),
		NamespaceID:  ns.ID,
		Type:         tokenType,
	}

	// If the role is not nil, we add the role name as part of the token's
	// path. This makes it much easier to later revoke tokens that were issued
	// by a role (using revoke-prefix). Users can further specify a PathSuffix
	// in the role; that way they can use something like "v1", "v2" to indicate
	// role revisions, and revoke only tokens issued with a previous revision.
	if role != nil {
		te.Role = role.Name

		// If renewable hasn't been disabled in the call and the role has
		// renewability disabled, set renewable false
		if renewable && !role.Renewable {
			renewable = false
		}

		if role.PathSuffix != "" {
			te.Path = fmt.Sprintf("%s/%s", te.Path, role.PathSuffix)
		}
	}

	// Attach the given display name if any
	if data.DisplayName != "" {
		full := "token-" + data.DisplayName
		full = displayNameSanitize.ReplaceAllString(full, "-")
		full = strings.TrimSuffix(full, "-")
		te.DisplayName = full
	}

	// Allow specifying the ID of the token if the client has root or sudo privileges
	if data.ID != "" {
		if !isSudo {
			return logical.ErrorResponse("root or sudo privileges required to specify token id"),
				logical.ErrInvalidRequest
		}
		if ns.ID != namespace.RootNamespaceID {
			return logical.ErrorResponse("token IDs can only be manually specified in the root namespace"),
				logical.ErrInvalidRequest
		}
		te.ID = data.ID
	}

	resp := &logical.Response{}

	var addDefault bool

	// N.B.: The logic here uses various calculations as to whether default
	// should be added. In the end we decided that if NoDefaultPolicy is set it
	// should be stripped out regardless, *but*, the logic of when it should
	// and shouldn't be added is kept because we want to do subset comparisons
	// based on adding default when it's correct to do so.
	switch {
	case role != nil && (len(role.AllowedPolicies) > 0 || len(role.DisallowedPolicies) > 0):
		// Holds the final set of policies as they get munged
		var finalPolicies []string

		// We don't make use of the global one because roles with allowed or
		// disallowed set do their own policy rules
		var localAddDefault bool

		// If the request doesn't say not to add "default" and if "default"
		// isn't in the disallowed list, add it. This is in line with the idea
		// that roles, when allowed/disallowed ar set, allow a subset of
		// policies to be set disjoint from the parent token's policies.
		if !data.NoDefaultPolicy && !strutil.StrListContains(role.DisallowedPolicies, "default") {
			localAddDefault = true
		}

		// Start with passed-in policies as a baseline, if they exist
		if len(data.Policies) > 0 {
			finalPolicies = policyutil.SanitizePolicies(data.Policies, localAddDefault)
		}

		var sanitizedRolePolicies []string

		// First check allowed policies; if policies are specified they will be
		// checked, otherwise if an allowed set exists that will be the set
		// that is used
		if len(role.AllowedPolicies) > 0 {
			// Note that if "default" is already in allowed, and also in
			// disallowed, this will still result in an error later since this
			// doesn't strip out default
			sanitizedRolePolicies = policyutil.SanitizePolicies(role.AllowedPolicies, localAddDefault)

			if len(finalPolicies) == 0 {
				finalPolicies = sanitizedRolePolicies
			} else {
				if !strutil.StrListSubset(sanitizedRolePolicies, finalPolicies) {
					return logical.ErrorResponse(fmt.Sprintf("token policies (%q) must be subset of the role's allowed policies (%q)", finalPolicies, sanitizedRolePolicies)), logical.ErrInvalidRequest
				}
			}
		} else {
			// Assign parent policies if none have been requested. As this is a
			// role, add default unless explicitly disabled.
			if len(finalPolicies) == 0 {
				finalPolicies = policyutil.SanitizePolicies(parent.Policies, localAddDefault)
			}
		}

		if len(role.DisallowedPolicies) > 0 {
			// We don't add the default here because we only want to disallow it if it's explicitly set
			sanitizedRolePolicies = strutil.RemoveDuplicates(role.DisallowedPolicies, true)

			for _, finalPolicy := range finalPolicies {
				if strutil.StrListContains(sanitizedRolePolicies, finalPolicy) {
					return logical.ErrorResponse(fmt.Sprintf("token policy %q is disallowed by this role", finalPolicy)), logical.ErrInvalidRequest
				}
			}
		}

		data.Policies = finalPolicies

	// We are creating a token from a parent namespace. We should only use the input
	// policies.
	case ns.ID != parent.NamespaceID:
		addDefault = !data.NoDefaultPolicy

	// No policies specified, inherit parent
	case len(data.Policies) == 0:
		// Only inherit "default" if the parent already has it, so don't touch addDefault here
		data.Policies = policyutil.SanitizePolicies(parent.Policies, policyutil.DoNotAddDefaultPolicy)

	// When a role is not in use or does not specify allowed/disallowed, only
	// permit policies to be a subset unless the client has root or sudo
	// privileges. Default is added in this case if the parent has it, unless
	// the client specified for it not to be added.
	case !isSudo:
		// Sanitize passed-in and parent policies before comparison
		sanitizedInputPolicies := policyutil.SanitizePolicies(data.Policies, policyutil.DoNotAddDefaultPolicy)
		sanitizedParentPolicies := policyutil.SanitizePolicies(parent.Policies, policyutil.DoNotAddDefaultPolicy)

		if !strutil.StrListSubset(sanitizedParentPolicies, sanitizedInputPolicies) {
			return logical.ErrorResponse("child policies must be subset of parent"), logical.ErrInvalidRequest
		}

		// If the parent has default, and they haven't requested not to get it,
		// add it. Note that if they have explicitly put "default" in
		// data.Policies it will still be added because NoDefaultPolicy
		// controls *automatic* adding.
		if !data.NoDefaultPolicy && strutil.StrListContains(parent.Policies, "default") {
			addDefault = true
		}

	// Add default by default in this case unless requested not to
	case isSudo:
		addDefault = !data.NoDefaultPolicy
	}

	te.Policies = policyutil.SanitizePolicies(data.Policies, addDefault)

	// Yes, this is a little inefficient to do it like this, but meh
	if data.NoDefaultPolicy {
		te.Policies = strutil.StrListDelete(te.Policies, "default")
	}

	// Prevent internal policies from being assigned to tokens
	for _, policy := range te.Policies {
		if strutil.StrListContains(nonAssignablePolicies, policy) {
			return logical.ErrorResponse(fmt.Sprintf("cannot assign policy %q", policy)), nil
		}
	}

	if strutil.StrListContains(te.Policies, "root") {
		// Prevent attempts to create a root token without an actual root token as parent.
		// This is to thwart privilege escalation by tokens having 'sudo' privileges.
		if !strutil.StrListContains(parent.Policies, "root") {
			return logical.ErrorResponse("root tokens may not be created without parent token being root"), logical.ErrInvalidRequest
		}

		if te.Type == logical.TokenTypeBatch {
			// Batch tokens cannot be revoked so we should never have root batch tokens
			return logical.ErrorResponse("batch tokens cannot be root tokens"), nil
		}
	}

	//
	// NOTE: Do not modify policies below this line. We need the checks above
	// to be the last checks as they must look at the final policy set.
	//

	switch {
	case role != nil:
		if role.Orphan {
			te.Parent = ""
		}

		if len(role.BoundCIDRs) > 0 {
			te.BoundCIDRs = role.BoundCIDRs
		}

	case data.NoParent:
		// Only allow an orphan token if the client has sudo policy
		if !isSudo {
			return logical.ErrorResponse("root or sudo privileges required to create orphan token"),
				logical.ErrInvalidRequest
		}

		te.Parent = ""

	default:
		// This comes from create-orphan, which can be properly ACLd
		if orphan {
			te.Parent = ""
		}
	}

	// At this point, it is clear whether the token is going to be an orphan or
	// not. If the token is not going to be an orphan, inherit the parent's
	// entity identifier into the child token.
	if te.Parent != "" {
		te.EntityID = parent.EntityID

		// If the parent has bound CIDRs, copy those into the child. We don't
		// do this if role is not nil because then we always use the role's
		// bound CIDRs; roles allow escalation of privilege in proper
		// circumstances.
		if role == nil {
			te.BoundCIDRs = parent.BoundCIDRs
		}
	}

	var explicitMaxTTLToUse time.Duration
	if data.ExplicitMaxTTL != "" {
		dur, err := parseutil.ParseDurationSecond(data.ExplicitMaxTTL)
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}
		if dur < 0 {
			return logical.ErrorResponse("explicit_max_ttl must be positive"), logical.ErrInvalidRequest
		}
		te.ExplicitMaxTTL = dur
		explicitMaxTTLToUse = dur
	}

	var periodToUse time.Duration
	if data.Period != "" {
		dur, err := parseutil.ParseDurationSecond(data.Period)
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}

		switch {
		case dur < 0:
			return logical.ErrorResponse("period must be positive"), logical.ErrInvalidRequest
		case dur == 0:
		default:
			if !isSudo {
				return logical.ErrorResponse("root or sudo privileges required to create periodic token"),
					logical.ErrInvalidRequest
			}
			te.Period = dur
			periodToUse = dur
		}
	}

	// Parse the TTL/lease if any
	if data.TTL != "" {
		dur, err := parseutil.ParseDurationSecond(data.TTL)
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}
		if dur < 0 {
			return logical.ErrorResponse("ttl must be positive"), logical.ErrInvalidRequest
		}
		te.TTL = dur
	} else if data.Lease != "" {
		// This block is compatibility
		dur, err := time.ParseDuration(data.Lease)
		if err != nil {
			return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
		}
		if dur < 0 {
			return logical.ErrorResponse("lease must be positive"), logical.ErrInvalidRequest
		}
		te.TTL = dur
	}

	// Set the lesser period/explicit max TTL if defined both in arguments and
	// in role. Batch tokens will error out if not set via role, but here we
	// need to explicitly check
	if role != nil && te.Type != logical.TokenTypeBatch {
		if role.ExplicitMaxTTL != 0 {
			switch {
			case explicitMaxTTLToUse == 0:
				explicitMaxTTLToUse = role.ExplicitMaxTTL
			default:
				if role.ExplicitMaxTTL < explicitMaxTTLToUse {
					explicitMaxTTLToUse = role.ExplicitMaxTTL
				}
				resp.AddWarning(fmt.Sprintf("Explicit max TTL specified both during creation call and in role; using the lesser value of %d seconds", int64(explicitMaxTTLToUse.Seconds())))
			}
		}
		if role.Period != 0 {
			switch {
			case periodToUse == 0:
				periodToUse = role.Period
			default:
				if role.Period < periodToUse {
					periodToUse = role.Period
				}
				resp.AddWarning(fmt.Sprintf("Period specified both during creation call and in role; using the lesser value of %d seconds", int64(periodToUse.Seconds())))
			}
		}
	}

	sysView := ts.System()

	// Only calculate a TTL if you are A) periodic, B) have a TTL, C) do not have a TTL and are not a root token
	if periodToUse > 0 || te.TTL > 0 || (te.TTL == 0 && !strutil.StrListContains(te.Policies, "root")) {
		ttl, warnings, err := framework.CalculateTTL(sysView, 0, te.TTL, periodToUse, 0, explicitMaxTTLToUse, time.Unix(te.CreationTime, 0))
		if err != nil {
			return nil, err
		}
		for _, warning := range warnings {
			resp.AddWarning(warning)
		}
		te.TTL = ttl
	}

	// Root tokens are still bound by explicit max TTL
	if te.TTL == 0 && explicitMaxTTLToUse > 0 {
		te.TTL = explicitMaxTTLToUse
	}

	// Don't advertise non-expiring root tokens as renewable, as attempts to
	// renew them are denied. Don't CIDR-restrict these either.
	if te.TTL == 0 {
		if parent.TTL != 0 {
			return logical.ErrorResponse("expiring root tokens cannot create non-expiring root tokens"), logical.ErrInvalidRequest
		}
		renewable = false
		te.BoundCIDRs = nil
	}

	if te.ID != "" {
		resp.AddWarning("Supplying a custom ID for the token uses the weaker SHA1 hashing instead of the more secure SHA2-256 HMAC for token obfuscation. SHA1 hashed tokens on the wire leads to less secure lookups.")
	}

	// Create the token
	if err := ts.create(ctx, &te); err != nil {
		return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
	}

	// Generate the response
	resp.Auth = &logical.Auth{
		NumUses:     te.NumUses,
		DisplayName: te.DisplayName,
		Policies:    te.Policies,
		Metadata:    te.Meta,
		LeaseOptions: logical.LeaseOptions{
			TTL:       te.TTL,
			Renewable: renewable,
		},
		ClientToken:    te.ID,
		Accessor:       te.Accessor,
		EntityID:       te.EntityID,
		Period:         periodToUse,
		ExplicitMaxTTL: explicitMaxTTLToUse,
		CreationPath:   te.Path,
		TokenType:      te.Type,
		Orphan:         te.Parent == "",
	}

	for _, p := range te.Policies {
		policy, err := ts.core.policyStore.GetPolicy(ctx, p, PolicyTypeToken)
		if err != nil {
			return logical.ErrorResponse(fmt.Sprintf("could not look up policy %s", p)), nil
		}
		if policy == nil {
			resp.AddWarning(fmt.Sprintf("Policy %q does not exist", p))
		}
	}

	return resp, nil
}
592898
func (m *Manager) DeleteServiceAccountToken(podUID types.UID) {
	m.cacheMutex.Lock()
	defer m.cacheMutex.Unlock()
	for k, tr := range m.cache {
		if tr.Spec.BoundObjectRef.UID == podUID {
			delete(m.cache, k)
		}
	}
}
1362059
func (idr *InitDryRunGetter) handleGetBootstrapToken(action core.GetAction) (bool, runtime.Object, error) {
	if !strings.HasPrefix(action.GetName(), "bootstrap-token-") || action.GetNamespace() != metav1.NamespaceSystem || action.GetResource().Resource != "secrets" {
		// We can't handle this event
		return false, nil, nil
	}
	// We can safely return a NotFound error here as the code will just proceed normally and create the Bootstrap Token
	return true, nil, apierrors.NewNotFound(action.GetResource().GroupResource(), "secret not found")
}
1124402
func (r *MintOAuthTokenGrantRPC) MintOAuthTokenGrant(c context.Context, req *minter.MintOAuthTokenGrantRequest) (*minter.MintOAuthTokenGrantResponse, error) {
	state := auth.GetState(c)

	// Don't allow delegation tokens here to reduce total number of possible
	// scenarios. Proxies aren't expected to use delegation for these tokens.
	callerID := state.User().Identity
	if callerID != state.PeerIdentity() {
		logging.Errorf(c, "Trying to use delegation, it's forbidden")
		return nil, status.Errorf(codes.PermissionDenied, "delegation is forbidden for this API call")
	}

	// Check that the request is allowed by the rules, fill in defaults.
	rule, err := r.validateRequest(c, req, callerID)
	if err != nil {
		return nil, err // the error is already logged
	}
	if req.ValidityDuration == 0 {
		if rule.Rule.MaxGrantValidityDuration > 3600 {
			req.ValidityDuration = 3600
		} else {
			req.ValidityDuration = rule.Rule.MaxGrantValidityDuration
		}
	}

	// Grab a string that identifies token server version. This almost always
	// just hits local memory cache.
	serviceVer, err := utils.ServiceVersion(c, r.Signer)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "can't grab service version - %s", err)
	}

	// Generate and sign the token.
	var resp *minter.MintOAuthTokenGrantResponse
	var body *tokenserver.OAuthTokenGrantBody
	p := mintParams{
		serviceAccount:   req.ServiceAccount,
		proxyID:          callerID,
		endUserID:        identity.Identity(req.EndUser), // already validated
		validityDuration: req.ValidityDuration,
		serviceVer:       serviceVer,
	}
	if r.mintMock != nil {
		resp, body, err = r.mintMock(c, &p)
	} else {
		resp, body, err = r.mint(c, &p)
	}
	if err != nil {
		return nil, err
	}

	// Log it to BigQuery.
	if r.LogGrant != nil {
		// Errors during logging are considered not fatal. bqlog library has
		// a monitoring counter that tracks number of errors, so they are not
		// totally invisible.
		info := MintedGrantInfo{
			Request:   req,
			Response:  resp,
			GrantBody: body,
			ConfigRev: rule.Revision,
			Rule:      rule.Rule,
			PeerIP:    state.PeerIP(),
			RequestID: info.RequestID(c),
			AuthDBRev: authdb.Revision(state.DB()),
		}
		if logErr := r.LogGrant(c, &info); logErr != nil {
			logging.WithError(logErr).Errorf(c, "Failed to insert the grant token into the BigQuery log")
		}
	}

	return resp, nil
}
448563
func (s *serviceAccount) getReferencedServiceAccountToken(serviceAccount *corev1.ServiceAccount) (string, error) {
	if len(serviceAccount.Secrets) == 0 {
		return "", nil
	}

	tokens, err := s.getServiceAccountTokens(serviceAccount)
	if err != nil {
		return "", err
	}

	accountTokens := sets.NewString()
	for _, token := range tokens {
		accountTokens.Insert(token.Name)
	}
	// Prefer secrets in the order they're referenced.
	for _, secret := range serviceAccount.Secrets {
		if accountTokens.Has(secret.Name) {
			return secret.Name, nil
		}
	}

	return "", nil
}
778497
func (settings FileSettings) ServicePrincipalTokenFromClientCertificate(baseURI string) (*adal.ServicePrincipalToken, error) {
	resource, err := settings.getResourceForToken(baseURI)
	if err != nil {
		return nil, err
	}
	return settings.ServicePrincipalTokenFromClientCertificateWithResource(resource)
}
449037
func (b *buildPaymentData) CheckReadyToSend(arg stellar1.SendPaymentLocalArg) error {
	if !b.ReadyToSend {
		if !b.ReadyToReview {
			// Payment is not even ready for review.
			return fmt.Errorf("this payment is not ready to send")
		}
		// Payment is ready to review but has not been reviewed.
		return fmt.Errorf("this payment has not been reviewed")
	}
	if b.Frozen == nil {
		return fmt.Errorf("payment is ready to send but missing frozen values")
	}
	if !arg.From.Eq(b.Frozen.From) {
		return fmt.Errorf("mismatched from account: %v != %v", arg.From, b.Frozen.From)
	}
	if arg.To != b.Frozen.To {
		return fmt.Errorf("mismatched recipient: %v != %v", arg.To, b.Frozen.To)
	}
	if arg.ToIsAccountID != b.Frozen.ToIsAccountID {
		return fmt.Errorf("mismatches account ID type (expected %v)", b.Frozen.ToIsAccountID)
	}
	// Check the true amount and asset that will be sent.
	// Don't bother checking the display worth. It's finicky and the server does a coarse check.
	if arg.Amount != b.Frozen.Amount {
		return fmt.Errorf("mismatched amount: %v != %v", arg.Amount, b.Frozen.Amount)
	}
	if !arg.Asset.SameAsset(b.Frozen.Asset) {
		return fmt.Errorf("mismatched asset: %v != %v", arg.Asset, b.Frozen.Asset)
	}
	return nil
}
308961
func (e *DockercfgController) handleTokenSecretDelete(obj interface{}) {
	secret, isSecret := obj.(*v1.Secret)
	if !isSecret {
		tombstone, objIsTombstone := obj.(cache.DeletedFinalStateUnknown)
		if !objIsTombstone {
			klog.V(2).Infof("Expected tombstone object when deleting token, got %v", obj)
			return
		}
		secret, isSecret = tombstone.Obj.(*v1.Secret)
		if !isSecret {
			klog.V(2).Infof("Expected tombstone object to contain secret, got: %v", obj)
			return
		}
	}
	if secret.Annotations[DeprecatedKubeCreatedByAnnotation] != CreateDockercfgSecretsController {
		return
	}
	if len(secret.Data[v1.ServiceAccountTokenKey]) > 0 {
		// Let deleted_token_secrets handle deletion of populated tokens
		return
	}
	e.enqueueServiceAccountForToken(secret)
}
1270096
func (c *Ctx) SignEncryptUpdate(sh SessionHandle, part []byte) ([]byte, error) {
	var (
		enc    C.CK_BYTE_PTR
		enclen C.CK_ULONG
	)
	e := C.SignEncryptUpdate(c.ctx, C.CK_SESSION_HANDLE(sh), cMessage(part), C.CK_ULONG(len(part)), &enc, &enclen)
	if toError(e) != nil {
		return nil, toError(e)
	}
	h := C.GoBytes(unsafe.Pointer(enc), C.int(enclen))
	C.free(unsafe.Pointer(enc))
	return h, nil
}
42973
func handleUnauthorized(w http.ResponseWriter, r *http.Request, rule Rule, realm string) int {
	if rule.Redirect != "" {
		replacer := httpserver.NewReplacer(r, nil, "")
		http.Redirect(w, r, replacer.Replace(rule.Redirect), http.StatusSeeOther)
		return http.StatusSeeOther
	}

	w.Header().Add("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"%s\",error=\"invalid_token\"", realm))
	return http.StatusUnauthorized
}
251103
func (s *ServiceController) processServiceUpdate(cachedService *cachedService, service *v1.Service, key string) error {
	if cachedService.state != nil {
		if cachedService.state.UID != service.UID {
			err := s.processLoadBalancerDelete(cachedService, key)
			if err != nil {
				return err
			}
		}
	}
	// cache the service, we need the info for service deletion
	cachedService.state = service
	err := s.syncLoadBalancerIfNeeded(key, service)
	if err != nil {
		eventType := "CreatingLoadBalancerFailed"
		message := "Error creating load balancer (will retry): "
		if !wantsLoadBalancer(service) {
			eventType = "CleanupLoadBalancerFailed"
			message = "Error cleaning up load balancer (will retry): "
		}
		message += err.Error()
		s.eventRecorder.Event(service, v1.EventTypeWarning, eventType, message)
		return err
	}
	// Always update the cache upon success.
	// NOTE: Since we update the cached service if and only if we successfully
	// processed it, a cached service being nil implies that it hasn't yet
	// been successfully processed.
	s.cache.set(key, cachedService)

	return nil
}
1361428
func (s *APIServer) getSignupTokenData(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) {
	token := p.ByName("token")

	user, otpQRCode, err := auth.GetSignupTokenData(token)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return &getSignupTokenDataResponse{
		User:  user,
		QRImg: otpQRCode,
	}, nil
}
499145
func (s *AccessTokenSession) TokenFunc(retried bool) (string, error) {
	if !s.token.IsValid() || retried {
		refreshToken, refreshable := s.token.(RefreshableAccessToken)
		if !refreshable {
			return "", errors.New("not a refresh token")
		}

		tokenResp, err := s.uaa.RefreshTokenGrant(refreshToken.RefreshValue())
		if err != nil {
			return "", bosherr.WrapError(err, "refreshing token")
		}

		s.token = tokenResp
		if err = s.saveTokenCreds(); err != nil {
			return "", err
		}
	}

	return s.token.Type() + " " + s.token.Value(), nil
}
843162
func (u *Client) RefreshTokenGrant(clientId, clientSecret, refreshToken string) (string, string, error) {
	values := url.Values{
		"grant_type":    {"refresh_token"},
		"response_type": {"token"},
		"client_id":     {clientId},
		"client_secret": {clientSecret},
		"refresh_token": {refreshToken},
	}

	token, err := u.tokenGrantRequest(values)

	return token.AccessToken, token.RefreshToken, err
}
1077545
func (m *MockTokenEndpointHandler) HandleTokenEndpointRequest(arg0 context.Context, arg1 fosite.AccessRequester) error {
	ret := m.ctrl.Call(m, "HandleTokenEndpointRequest", arg0, arg1)
	ret0, _ := ret[0].(error)
	return ret0
}
717239
func (a *Authenticator) refreshCredsLocked(r *clientauthentication.Response) error {
	cred := &clientauthentication.ExecCredential{
		Spec: clientauthentication.ExecCredentialSpec{
			Response:    r,
			Interactive: a.interactive,
		},
	}

	env := append(a.environ(), a.env...)
	if a.group == v1alpha1.SchemeGroupVersion {
		// Input spec disabled for beta due to lack of use. Possibly re-enable this later if
		// someone wants it back.
		//
		// See: https://github.com/kubernetes/kubernetes/issues/61796
		data, err := runtime.Encode(codecs.LegacyCodec(a.group), cred)
		if err != nil {
			return fmt.Errorf("encode ExecCredentials: %v", err)
		}
		env = append(env, fmt.Sprintf("%s=%s", execInfoEnv, data))
	}

	stdout := &bytes.Buffer{}
	cmd := exec.Command(a.cmd, a.args...)
	cmd.Env = env
	cmd.Stderr = a.stderr
	cmd.Stdout = stdout
	if a.interactive {
		cmd.Stdin = a.stdin
	}

	if err := cmd.Run(); err != nil {
		return fmt.Errorf("exec: %v", err)
	}

	_, gvk, err := codecs.UniversalDecoder(a.group).Decode(stdout.Bytes(), nil, cred)
	if err != nil {
		return fmt.Errorf("decoding stdout: %v", err)
	}
	if gvk.Group != a.group.Group || gvk.Version != a.group.Version {
		return fmt.Errorf("exec plugin is configured to use API version %s, plugin returned version %s",
			a.group, schema.GroupVersion{Group: gvk.Group, Version: gvk.Version})
	}

	if cred.Status == nil {
		return fmt.Errorf("exec plugin didn't return a status field")
	}
	if cred.Status.Token == "" && cred.Status.ClientCertificateData == "" && cred.Status.ClientKeyData == "" {
		return fmt.Errorf("exec plugin didn't return a token or cert/key pair")
	}
	if (cred.Status.ClientCertificateData == "") != (cred.Status.ClientKeyData == "") {
		return fmt.Errorf("exec plugin returned only certificate or key, not both")
	}

	if cred.Status.ExpirationTimestamp != nil {
		a.exp = cred.Status.ExpirationTimestamp.Time
	} else {
		a.exp = time.Time{}
	}

	newCreds := &credentials{
		token: cred.Status.Token,
	}
	if cred.Status.ClientKeyData != "" && cred.Status.ClientCertificateData != "" {
		cert, err := tls.X509KeyPair([]byte(cred.Status.ClientCertificateData), []byte(cred.Status.ClientKeyData))
		if err != nil {
			return fmt.Errorf("failed parsing client key/certificate: %v", err)
		}
		newCreds.cert = &cert
	}

	oldCreds := a.cachedCreds
	a.cachedCreds = newCreds
	// Only close all connections when TLS cert rotates. Token rotation doesn't
	// need the extra noise.
	if a.onRotate != nil && oldCreds != nil && !reflect.DeepEqual(oldCreds.cert, a.cachedCreds.cert) {
		a.onRotate()
	}
	return nil
}