// ExchangeAppKeyForToken exchanges an app ID and app Key for an app token
969644
func (a *Account) ExchangeAppKeyForToken(appID, accessKey string) (*oauth2.Token, error) {
	req := exchangeReq{
		Username: appID,
		Password: accessKey,
	}

	var res tokenRes

	err := a.post(a.auth, "/api/v2/applications/token", &req, &res)
	if err != nil {
		return nil, err
	}

	return res.Token(), nil
}
746020
func keyFunc(name, namespace string, tr *authenticationv1.TokenRequest) string {
	var exp int64
	if tr.Spec.ExpirationSeconds != nil {
		exp = *tr.Spec.ExpirationSeconds
	}

	var ref authenticationv1.BoundObjectReference
	if tr.Spec.BoundObjectRef != nil {
		ref = *tr.Spec.BoundObjectRef
	}

	return fmt.Sprintf("%q/%q/%#v/%#v/%#v", name, namespace, tr.Spec.Audiences, exp, ref)
}
571214
func (t *Template) GetAllAWSAppSyncApiKeyResources() map[string]*resources.AWSAppSyncApiKey {
	results := map[string]*resources.AWSAppSyncApiKey{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSAppSyncApiKey:
			results[name] = resource
		}
	}
	return results
}
94245
func (ch Challenge) ExpectedKeyAuthorization(key *jose.JSONWebKey) (string, error) {
	if key == nil {
		return "", fmt.Errorf("Cannot authorize a nil key")
	}

	thumbprint, err := key.Thumbprint(crypto.SHA256)
	if err != nil {
		return "", err
	}

	return ch.Token + "." + base64.RawURLEncoding.EncodeToString(thumbprint), nil
}
1302248
func NewToken(tokenType TokenType, token, expiry string) *Token {
	return &Token{
		TokenType: tokenType,
		Token:     token,
		Expiry:    expiry,
	}
}
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)
}
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
}
855196
func NewToken() (*Token, error) {
	id, err := utils.RandomBytes(tokenIDBytes)
	if err != nil {
		return nil, err
	}

	secret, err := utils.RandomBytes(tokenSecretBytes)
	if err != nil {
		return nil, err
	}

	return &Token{ID: id, Secret: secret}, nil
}
388133
func (i *InitToken) InitToken() (string, error) {
	if i.token != nil {
		return *i.token, nil
	}

	// get init token from the secrets backend
	token, err := i.secretsBackend().InitToken(i.Name(), i.Role, []string{fmt.Sprintf("%s-creator", i.namePath())}, i.ExpectedToken)
	if err != nil {
		return "", err
	}

	i.token = &token
	return token, nil
}
423909
func KeyExchange(pub *rsa.PublicKey) []byte {
	asn1, err := x509.MarshalPKIXPublicKey(pub)
	if err != nil {
		return nil
	}
	return asn1
}
787197
func (s *Service) OrganizationAppTransferToAccount(ctx context.Context, organizationAppIdentity string, o OrganizationAppTransferToAccountOpts) (*OrganizationApp, error) {
	var organizationApp OrganizationApp
	return &organizationApp, s.Patch(ctx, &organizationApp, fmt.Sprintf("/organizations/apps/%v", organizationAppIdentity), o)
}
579004
func (s *authenticationProviderServiceImpl) ExchangeAuthorizationCodeForUserToken(ctx context.Context, code string, clientID string, redirectURL *url.URL) (*string, *app.OauthToken, error) {
	// Default value of this public client id is set to "740650a2-9c44-4db5-b067-a3d1b2cd2d01"
	if clientID != s.config.GetPublicOAuthClientID() {
		log.Error(ctx, map[string]interface{}{
			"client_id": clientID,
		}, "unknown oauth client id")
		return nil, nil, autherrors.NewUnauthorizedError("invalid oauth client id")
	}

	// Exchange the authorization code for an access token with the identity provider
	providerToken, err := s.ExchangeCodeWithProvider(ctx, code, redirectURL.String())
	if err != nil {
		return nil, nil, err
	}

	notApprovedRedirectURL, userToken, err := s.CreateOrUpdateIdentityAndUser(ctx, redirectURL, providerToken)
	if err != nil {
		return nil, nil, err
	}

	var token *app.OauthToken

	if userToken != nil {
		// Convert expiry to expire_in
		expiry := userToken.Expiry
		var expireIn *string
		if expiry != *new(time.Time) {
			exp := expiry.Sub(time.Now())
			if exp > 0 {
				seconds := strconv.FormatInt(int64(exp/time.Second), 10)
				expireIn = &seconds
			}
		}

		token = &app.OauthToken{
			AccessToken:  &userToken.AccessToken,
			ExpiresIn:    expireIn,
			RefreshToken: &userToken.RefreshToken,
			TokenType:    &userToken.TokenType,
		}
	}

	return notApprovedRedirectURL, token, nil
}
257051
func (ctx *Context) GetAuthrAccessToken(appid string) (string, error) {
	authrTokenKey := "authorizer_access_token_" + appid
	val := ctx.Cache.Get(authrTokenKey)
	if val == nil {
		return "", fmt.Errorf("cannot get authorizer %s access token", appid)
	}
	return val.(string), nil
}
1181140
func NewToken(iss, scope string, key []byte) *Token {
	c := &ClaimSet{
		Iss:   iss,
		Scope: scope,
		Aud:   stdAud,
	}
	h := &Header{
		Algorithm: stdAlgorithm,
		Type:      stdType,
	}
	t := &Token{
		ClaimSet: c,
		Header:   h,
		Key:      key,
	}
	return t
}
416245
func (t *Transport) Exchange(code string) (*Token, error) {
	if t.Config == nil {
		return nil, OAuthError{"Exchange", "no Config supplied"}
	}

	// If the transport or the cache already has a token, it is
	// passed to `updateToken` to preserve existing refresh token.
	tok := t.Token
	if tok == nil && t.TokenCache != nil {
		tok, _ = t.TokenCache.Token()
	}
	if tok == nil {
		tok = new(Token)
	}
	err := t.updateToken(tok, url.Values{
		"grant_type":   {"authorization_code"},
		"redirect_uri": {t.RedirectURL},
		"scope":        {t.Scope},
		"code":         {code},
	})
	if err != nil {
		return nil, err
	}
	t.Token = tok
	if t.TokenCache != nil {
		return tok, t.TokenCache.PutToken(tok)
	}
	return tok, nil
}
1359566
func (f *FastTeamChainLoader) deriveKeyForApplicationAtGeneration(m libkb.MetaContext, app keybase1.TeamApplication, gen keybase1.PerTeamKeyGeneration, state *keybase1.FastTeamData) (key keybase1.TeamApplicationKey, err error) {

	seed, err := f.deriveSeedAtGeneration(m, gen, state)
	if err != nil {
		return key, err
	}

	var mask *keybase1.MaskB64
	if m := state.ReaderKeyMasks[app]; m != nil {
		tmp, ok := m[gen]
		if ok {
			mask = &tmp
		}
	}
	if mask == nil {
		m.Debug("Could not get reader key mask for <%s,%d>", app, gen)
		if state.ID().IsSubTeam() {
			m.Debug("guessing lack of RKM is due to not being an explicit member of the subteam")
			return key, NewNotExplicitMemberOfSubteamError()
		}
		return key, NewFastLoadError("Could not load application keys")
	}

	rkm := keybase1.ReaderKeyMask{
		Application: app,
		Generation:  gen,
		Mask:        *mask,
	}
	return applicationKeyForMask(rkm, seed)
}
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
}