// ExchangeAppKeyForToken enables authentication with the App Access Key
188668
func (c *Component) ExchangeAppKeyForToken(appID, key string) (string, error) {
	issuerID := keys.KeyIssuer(key)
	if issuerID == "" {
		// Take the first configured auth server
		for k := range c.Config.AuthServers {
			issuerID = k
			break
		}
		key = fmt.Sprintf("%s.%s", issuerID, key)
	}
	issuer, ok := c.Config.AuthServers[issuerID]
	if !ok {
		return "", fmt.Errorf("Auth server \"%s\" not registered", issuerID)
	}

	token, err := getTokenFromCache(oauthCache, appID, key)
	if err != nil {
		return "", err
	}

	if token != nil {
		return token.AccessToken, nil
	}

	srv, _ := parseAuthServer(issuer)
	acc := account.New(srv.url)

	if srv.username != "" {
		acc = acc.WithAuth(auth.BasicAuth(srv.username, srv.password))
	} else {
		acc = acc.WithAuth(auth.AccessToken(c.AccessToken))
	}

	token, err = acc.ExchangeAppKeyForToken(appID, key)
	if err != nil {
		return "", err
	}

	saveTokenToCache(oauthCache, appID, key, token)

	return token.AccessToken, nil
}
813018
func (e *TokensController) ensureReferencedToken(serviceAccount *v1.ServiceAccount) ( /* retry */ bool, error) {
	if hasToken, err := e.hasReferencedToken(serviceAccount); err != nil {
		// Don't retry cache lookup errors
		return false, err
	} else if hasToken {
		// A service account token already exists, and is referenced, short-circuit
		return false, nil
	}

	// We don't want to update the cache's copy of the service account
	// so add the secret to a freshly retrieved copy of the service account
	serviceAccounts := e.client.CoreV1().ServiceAccounts(serviceAccount.Namespace)
	liveServiceAccount, err := serviceAccounts.Get(serviceAccount.Name, metav1.GetOptions{})
	if err != nil {
		// Retry if we cannot fetch the live service account (for a NotFound error, either the live lookup or our cache are stale)
		return true, err
	}
	if liveServiceAccount.ResourceVersion != serviceAccount.ResourceVersion {
		// Retry if our liveServiceAccount doesn't match our cache's resourceVersion (either the live lookup or our cache are stale)
		klog.V(4).Infof("liveServiceAccount.ResourceVersion (%s) does not match cache (%s), retrying", liveServiceAccount.ResourceVersion, serviceAccount.ResourceVersion)
		return true, nil
	}

	// Build the secret
	secret := &v1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Name:      secret.Strategy.GenerateName(fmt.Sprintf("%s-token-", serviceAccount.Name)),
			Namespace: serviceAccount.Namespace,
			Annotations: map[string]string{
				v1.ServiceAccountNameKey: serviceAccount.Name,
				v1.ServiceAccountUIDKey:  string(serviceAccount.UID),
			},
		},
		Type: v1.SecretTypeServiceAccountToken,
		Data: map[string][]byte{},
	}

	// Generate the token
	token, err := e.token.GenerateToken(serviceaccount.LegacyClaims(*serviceAccount, *secret))
	if err != nil {
		// retriable error
		return true, err
	}
	secret.Data[v1.ServiceAccountTokenKey] = []byte(token)
	secret.Data[v1.ServiceAccountNamespaceKey] = []byte(serviceAccount.Namespace)
	if e.rootCA != nil && len(e.rootCA) > 0 {
		secret.Data[v1.ServiceAccountRootCAKey] = e.rootCA
	}

	// Save the secret
	createdToken, err := e.client.CoreV1().Secrets(serviceAccount.Namespace).Create(secret)
	if err != nil {
		// retriable error
		return true, err
	}
	// Manually add the new token to the cache store.
	// This prevents the service account update (below) triggering another token creation, if the referenced token couldn't be found in the store
	e.updatedSecrets.Mutation(createdToken)

	// Try to add a reference to the newly created token to the service account
	addedReference := false
	err = clientretry.RetryOnConflict(clientretry.DefaultRetry, func() error {
		// refresh liveServiceAccount on every retry
		defer func() { liveServiceAccount = nil }()

		// fetch the live service account if needed, and verify the UID matches and that we still need a token
		if liveServiceAccount == nil {
			liveServiceAccount, err = serviceAccounts.Get(serviceAccount.Name, metav1.GetOptions{})
			if err != nil {
				return err
			}

			if liveServiceAccount.UID != serviceAccount.UID {
				// If we don't have the same service account, stop trying to add a reference to the token made for the old service account.
				return nil
			}

			if hasToken, err := e.hasReferencedToken(liveServiceAccount); err != nil {
				// Don't retry cache lookup errors
				return nil
			} else if hasToken {
				// A service account token already exists, and is referenced, short-circuit
				return nil
			}
		}

		// Try to add a reference to the token
		liveServiceAccount.Secrets = append(liveServiceAccount.Secrets, v1.ObjectReference{Name: secret.Name})
		if _, err := serviceAccounts.Update(liveServiceAccount); err != nil {
			return err
		}

		addedReference = true
		return nil
	})

	if !addedReference {
		// we weren't able to use the token, try to clean it up.
		klog.V(2).Infof("deleting secret %s/%s because reference couldn't be added (%v)", secret.Namespace, secret.Name, err)
		deleteOpts := &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &createdToken.UID}}
		if deleteErr := e.client.CoreV1().Secrets(createdToken.Namespace).Delete(createdToken.Name, deleteOpts); deleteErr != nil {
			klog.Error(deleteErr) // if we fail, just log it
		}
	}

	if err != nil {
		if apierrors.IsConflict(err) || apierrors.IsNotFound(err) {
			// if we got a Conflict error, the service account was updated by someone else, and we'll get an update notification later
			// if we got a NotFound error, the service account no longer exists, and we don't need to create a token for it
			return false, nil
		}
		// retry in all other cases
		return true, err
	}

	// success!
	return false, nil
}
561991
func UserFromKey(c *deis.Client, fingerprint string) (api.UserApps, error) {
	res, reqErr := c.Request("GET", fmt.Sprintf("/v2/hooks/key/%s", fingerprint), nil)
	if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) {
		return api.UserApps{}, reqErr
	}

	defer res.Body.Close()

	resUser := api.UserApps{}
	if err := json.NewDecoder(res.Body).Decode(&resUser); err != nil {
		return api.UserApps{}, err
	}

	return resUser, reqErr
}
1224069
func (c *Client) ExchangePublicToken(publicToken string) (resp ExchangePublicTokenResponse, err error) {
	if publicToken == "" {
		return resp, errors.New("/item/public_token/exchange - public token must be specified")
	}

	jsonBody, err := json.Marshal(exchangePublicTokenRequest{
		ClientID:    c.clientID,
		Secret:      c.secret,
		PublicToken: publicToken,
	})

	if err != nil {
		return resp, err
	}

	err = c.Call("/item/public_token/exchange", jsonBody, &resp)
	return resp, err
}
1211002
func IsKeyEExistsError(err error) bool {

	res, ok := err.(*gomemcached.MCResponse)
	if ok && res.Status == gomemcached.KEY_EEXISTS {
		return true
	}

	return false
}
1100584
func (s *AuthServer) rotateAndFetchSignupToken(token string) (*services.SignupToken, error) {
	var err error

	// Fetch original signup token.
	st, err := s.GetSignupToken(token)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// Generate and set new OTP code for user in *services.SignupToken.
	accountName := st.User.V2().GetName() + "@" + s.AuthServiceName
	st.OTPKey, st.OTPQRCode, err = s.initializeTOTP(accountName)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// Upsert token into backend.
	err = s.UpsertSignupToken(token, *st, st.Expires.Sub(s.clock.Now()))
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return st, nil
}
210692
func (s *authenticationProviderServiceImpl) ExchangeCodeWithProvider(ctx context.Context, code string, redirectURL string) (*oauth2.Token, error) {

	// Exchange the code for an access token
	provider := s.Factories().IdentityProviderFactory().NewIdentityProvider(ctx, s.config)
	provider.SetRedirectURL(redirectURL)
	token, err := provider.Exchange(ctx, code)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"code":         code,
			"err":          err,
			"redirect_url": redirectURL,
		}, "oauth exchange operation failed")
		return nil, autherrors.NewUnauthorizedError(err.Error())
	}

	log.Debug(ctx, map[string]interface{}{
		"code": code,
	}, "exchanged code to access token")

	return token, nil
}
423909
func KeyExchange(pub *rsa.PublicKey) []byte {
	asn1, err := x509.MarshalPKIXPublicKey(pub)
	if err != nil {
		return nil
	}
	return asn1
}
16731
func handleAppVariantType(service *push.Service, appName string, appVariant string) string {
	// custom apps have separate certificate
	base := getKey("SNS_BASE", true) // 'arn:aws:sns:eu-west-1:123454678:app'
	env := getKey("ENVIRONMENT", true)
	specialType := "ios_" + appVariant
	if _, ok := service.Platforms[specialType]; !ok {
		service.Platforms[specialType] = fmt.Sprintf("%v/%v/%v_%v_%v", base, "APNS", env, appName, appVariant)
	}
	return specialType
}
173545
func (s *tokenServiceImpl) ExchangeRefreshToken(ctx context.Context, refreshToken string, rptToken string) (*manager.TokenSet, error) {

	tkn, err := s.tokenManager.Parse(ctx, refreshToken)
	if err != nil {
		return nil, errors.NewUnauthorizedError(err.Error())
	}

	err = s.ValidateToken(ctx, tkn)
	if err != nil {
		return nil, errors.NewUnauthorizedError(err.Error())
	}

	claims := tkn.Claims.(jwt.MapClaims)
	sub := claims["sub"]
	if sub == nil {
		return nil, errors.NewUnauthorizedError("missing 'sub' claim in the refresh token")
	}
	identityID, err := uuid.FromString(fmt.Sprintf("%s", sub))
	if err != nil {
		return nil, errors.NewUnauthorizedError(err.Error())
	}

	identity, err := s.Repositories().Identities().LoadWithUser(ctx, identityID)

	if err != nil {
		if unauth, _ := errors.IsUnauthorizedError(err); unauth {
			return nil, err
		}
		// It's OK if we didn't find the identity, if the token was issued for an API client
		// Just log it and proceed.
		log.Warn(ctx, map[string]interface{}{
			"err": err,
		}, "failed to load identity when refreshing token; it's OK if the token was issued for an API client")
	}

	if identity != nil && identity.User.Banned {
		log.Warn(ctx, map[string]interface{}{
			"identity_id": identity.ID,
			"user_name":   identity.Username,
		}, "banned user tried to refresh token")
		return nil, errors.NewUnauthorizedError("unauthorized access")
	}

	// Initialize an array of permission objects that *may* be included in the token
	permissions := []manager.Permissions{}

	// Initialize an array of TokenPrivilege objects so that we can persist a record of the token's privileges to the database
	tokenPrivs := []tokenrepo.TokenPrivilege{}

	var generatedToken *oauth2.Token

	err = s.ExecuteInTransaction(func() error {

		// if an RPT token is provided, then use it to generate a permissions claim for the refreshed token
		if identity != nil && rptToken != "" {

			// Parse the claims from the provided token string
			tokenClaims, err := s.tokenManager.ParseToken(ctx, rptToken)
			if err != nil {
				log.Error(ctx, map[string]interface{}{"error": err, "rptToken": rptToken}, "invalid RPT token could not be parsed")
				return errors.NewUnauthorizedError("invalid RPT token could not be parsed")
			}

			// Extract the id from the refresh token
			tokenID, err := uuid.FromString(tokenClaims.Id)
			if err != nil {
				log.Error(ctx, map[string]interface{}{"error": err, "rptToken": rptToken}, "could not extract token ID from RPT token")
				return errors.NewUnauthorizedError("could not extract token ID from RPT token")
			}

			loadedToken, err := s.Repositories().TokenRepository().Load(ctx, tokenID)
			if err != nil {
				// This is not an error per se, so we'll just log an informational message
				log.Info(ctx, map[string]interface{}{
					"token_id": tokenID,
				}, "token with specified id not found")
			}

			// check if the token is still valid
			if loadedToken != nil {
				// Confirm that the token belongs to the current identity
				if loadedToken.IdentityID != identity.ID {
					return errors.NewUnauthorizedError("invalid token for identity")
				}
				// We now process the various token status codes in order of priority, starting with DEPROVISIONED
				if loadedToken.HasStatus(authtoken.TOKEN_STATUS_DEPROVISIONED) {
					return errors.NewUnauthorizedErrorWithCode("token banned", errors.UNAUTHORIZED_CODE_TOKEN_DEPROVISIONED)
				}
				// If the token has been revoked or the user is logged out, we respond in the same way
				if loadedToken.HasStatus(authtoken.TOKEN_STATUS_REVOKED) || loadedToken.HasStatus(authtoken.TOKEN_STATUS_LOGGED_OUT) {
					return errors.NewUnauthorizedErrorWithCode("token revoked or logged out", errors.UNAUTHORIZED_CODE_TOKEN_REVOKED)
				}
			}

			// If we've gotten this far, it means that either no existing token was found, or the token that was found
			// has been marked with status STALE and its privileges have changed, in either case we must generate a new token

			// If an existing RPT token is being replaced with a new token, then populate it with the privileges from the
			// existing token.  HOWEVER, don't exceed the maximum configured permissions for the token
			if loadedToken != nil {
				oldTokenPrivs, err := s.Repositories().TokenRepository().ListPrivileges(ctx, loadedToken.TokenID)
				if err != nil {
					return errors.NewInternalError(ctx, err)
				}
				// Sort the old token privileges by expiry time, from latest to earliest
				sort.Slice(oldTokenPrivs, func(i, j int) bool {
					return oldTokenPrivs[i].ExpiryTime.After(oldTokenPrivs[j].ExpiryTime)
				})
				// Loop through the privileges stored in the previous token, and add them to the permissions of the
				// new token, breaking once the maximum permission limit has been hit
				for _, oldPriv := range oldTokenPrivs {
					// If we have hit the maximum permissions limit then break
					if len(permissions) >= s.config.GetRPTTokenMaxPermissions() {
						break
					}
					oldPrivResourceID := oldPriv.ResourceID
					if loadedToken.HasStatus(authtoken.TOKEN_STATUS_STALE) || oldPriv.Stale {
						privilegeCache, err := s.Services().PrivilegeCacheService().CachedPrivileges(ctx, identity.ID, oldPrivResourceID)
						if err != nil {
							return errors.NewInternalError(ctx, err)
						}

						log.Debug(ctx, map[string]interface{}{"resource_id": oldPrivResourceID,
							"new_scopes": privilegeCache.ScopesAsArray(), "old_scopes": oldPriv.ScopesAsArray()},
							"old privileges are stale")

						perm := &manager.Permissions{
							ResourceSetID: &oldPrivResourceID,
							Scopes:        privilegeCache.ScopesAsArray(),
							Expiry:        privilegeCache.ExpiryTime.Unix(),
						}
						permissions = append(permissions, *perm)
					} else {
						// Create a new permissions object for the RPT token and store it in the array
						perm := &manager.Permissions{
							ResourceSetID: &oldPrivResourceID,
							Scopes:        oldPriv.ScopesAsArray(),
							Expiry:        oldPriv.ExpiryTime.Unix(),
						}
						permissions = append(permissions, *perm)
					}
					// Create a token privilege object to store in the database
					tokenPriv := &tokenrepo.TokenPrivilege{
						PrivilegeCacheID: oldPriv.PrivilegeCacheID,
					}
					tokenPrivs = append(tokenPrivs, *tokenPriv)
				}
			}
		}

		// Generate the new user token
		generatedToken, err = s.tokenManager.GenerateUserTokenUsingRefreshToken(ctx, refreshToken, identity, permissions)
		if err != nil {
			return err
		}

		// Register the new token - if it has permission it's an RPT token, otherwise it's a standard access token
		if len(permissions) > 0 {
			_, err = s.RegisterToken(ctx, identity.ID, generatedToken.AccessToken, authtoken.TOKEN_TYPE_RPT, tokenPrivs)
		} else {
			_, err = s.RegisterToken(ctx, identity.ID, generatedToken.AccessToken, authtoken.TOKEN_TYPE_ACCESS, nil)
		}

		if err != nil {
			log.Error(ctx, map[string]interface{}{"error": err}, "could not register token")
			return errors.NewInternalError(ctx, err)
		}

		// Register the refresh token
		_, err = s.RegisterToken(ctx, identity.ID, generatedToken.RefreshToken, authtoken.TOKEN_TYPE_REFRESH, nil)
		if err != nil {
			log.Error(ctx, map[string]interface{}{"error": err}, "could not register token")
			return errors.NewInternalError(ctx, err)
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return s.tokenManager.ConvertToken(*generatedToken)
}
1095213
func AuthToken(ctx context.Context) (*types.AuthToken, bool) {
	if v, ok := ctx.Value(AuthTokenKey).(*types.AuthToken); ok {
		return v, ok
	}
	return nil, false
}
1211924
func (c Client) Exchange(code string) (*oauth2.Token, error) {
	jwt := NewClientJWT(c.ISS, c.AUD)
	clientAssertion, err := SignJWT(jwt, c.PrivateKey)
	if err != nil {
		return nil, err
	}
	values := url.Values{"client_assertion": {clientAssertion},
		"client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},
		"client_id":             {c.ISS}, "grant_type": {"authorization_code"},
		"code": {code}}
	resp, err := http.PostForm(c.Endpoint.TokenURL, values)
	if err != nil {
		return nil, errors.Annotate(err, "Couldn't connect to the token endpoint")
	}
	defer resp.Body.Close()
	decoder := json.NewDecoder(resp.Body)
	token := &oauth2.Token{}
	err = decoder.Decode(token)
	if err != nil {
		return nil, errors.Annotate(err, "Couldn't decode the token")
	}
	return token, nil
}
1236989
func (idp *IDP) getChallengeToken(challengeString string) (*jwt.Token, error) {
	token, err := jwt.Parse(challengeString, func(token *jwt.Token) (interface{}, error) {
		_, ok := token.Method.(*jwt.SigningMethodRSA)
		if !ok {
			return nil, ErrorBadSigningMethod
		}

		return idp.getVerificationKey()
	})

	if err != nil {
		return nil, err
	}

	if !token.Valid {
		return nil, ErrorInvalidToken
	}

	return token, nil
}
1263913
func (c *Client) FetchAppToken() (err error) {
	var (
		req  *http.Request
		resp *http.Response
		rb   []byte
		rj   = map[string]interface{}{}
		url  = fmt.Sprintf("https://%v/oauth2/token", c.Host)
		ct   = "application/x-www-form-urlencoded;charset=UTF-8"
		body = "grant_type=client_credentials"
		ek   = oauth1a.Rfc3986Escape(c.OAuth.ClientConfig.ConsumerKey)
		es   = oauth1a.Rfc3986Escape(c.OAuth.ClientConfig.ConsumerSecret)
		cred = fmt.Sprintf("%v:%v", ek, es)
		ec   = base64.StdEncoding.EncodeToString([]byte(cred))
		h    = fmt.Sprintf("Basic %v", ec)
	)
	req, err = http.NewRequest("POST", url, bytes.NewBufferString(body))
	if err != nil {
		return
	}
	req.Header.Set("Authorization", h)
	req.Header.Set("Content-Type", ct)
	if resp, err = c.HttpClient.Do(req); err != nil {
		return
	}
	if resp.StatusCode != 200 {
		err = fmt.Errorf("Got HTTP %v instead of 200", resp.StatusCode)
		return
	}
	if rb, err = ioutil.ReadAll(resp.Body); err != nil {
		return
	}
	if err = json.Unmarshal(rb, &rj); err != nil {
		return
	}
	var (
		token_type   = rj["token_type"].(string)
		access_token = rj["access_token"].(string)
	)
	if token_type != "bearer" {
		err = fmt.Errorf("Got invalid token type: %v", token_type)
	}
	c.SetAppToken(access_token)
	return nil
}
762149
func (k *SimpleFS) SimpleFSGetHTTPAddressAndToken(ctx context.Context) (
	resp keybase1.SimpleFSGetHTTPAddressAndTokenResponse, err error) {
	if k.localHTTPServer == nil {
		return resp, errors.New("HTTP server is disabled")
	}
	if resp.Token, err = k.localHTTPServer.NewToken(); err != nil {
		return keybase1.SimpleFSGetHTTPAddressAndTokenResponse{}, err
	}
	if resp.Address, err = k.localHTTPServer.Address(); err != nil {
		return keybase1.SimpleFSGetHTTPAddressAndTokenResponse{}, err
	}

	return resp, nil
}
244987
func (c *ConfigurationData) GetDeprecatedServiceAccountPrivateKey() ([]byte, string) {
	return []byte(c.v.GetString(varServiceAccountPrivateKeyDeprecated)), c.v.GetString(varServiceAccountPrivateKeyIDDeprecated)
}
54519
func (a *Account) AddAccessKey(appID string, name string, rights []types.Right) (key types.AccessKey, err error) {
	body := addAccessKeyReq{
		Name:   name,
		Rights: rights,
	}
	err = a.post(a.auth.WithScope(scope.App(appID)), fmt.Sprintf("/api/v2/applications/%s/access-keys", appID), body, &key)
	return key, err
}