// FetchLeaseTimesByToken is a helper function to use token values to compute
// the leaseID, rather than pushing that logic back into the token store.
// As a special case, for a batch token it simply returns the information
// encoded on it.
777406
func (m *ExpirationManager) FetchLeaseTimesByToken(ctx context.Context, te *logical.TokenEntry) (*leaseEntry, error) {
	defer metrics.MeasureSince([]string{"expire", "fetch-lease-times-by-token"}, time.Now())

	if te == nil {
		return nil, errors.New("cannot fetch lease times for nil token")
	}

	if te.Type == logical.TokenTypeBatch {
		issueTime := time.Unix(te.CreationTime, 0)
		return &leaseEntry{
			IssueTime:       issueTime,
			ExpireTime:      issueTime.Add(te.TTL),
			ClientTokenType: logical.TokenTypeBatch,
		}, nil
	}

	tokenNS, err := NamespaceByID(ctx, te.NamespaceID, m.core)
	if err != nil {
		return nil, err
	}
	if tokenNS == nil {
		return nil, namespace.ErrNoNamespace
	}

	saltCtx := namespace.ContextWithNamespace(ctx, tokenNS)
	saltedID, err := m.tokenStore.SaltID(saltCtx, te.ID)
	if err != nil {
		return nil, err
	}

	leaseID := path.Join(te.Path, saltedID)

	if tokenNS.ID != namespace.RootNamespaceID {
		leaseID = fmt.Sprintf("%s.%s", leaseID, tokenNS.ID)
	}

	return m.FetchLeaseTimes(ctx, leaseID)
}
1072840
func (r *Lexer) FetchToken() {
	r.token.kind = tokenUndef
	r.start = r.pos

	// Check if r.Data has r.pos element
	// If it doesn't, it mean corrupted input data
	if len(r.Data) < r.pos {
		r.errParse("Unexpected end of data")
		return
	}
	// Determine the type of a token by skipping whitespace and reading the
	// first character.
	for _, c := range r.Data[r.pos:] {
		switch c {
		case ':', ',':
			if r.wantSep == c {
				r.pos++
				r.start++
				r.wantSep = 0
			} else {
				r.errSyntax()
			}

		case ' ', '\t', '\r', '\n':
			r.pos++
			r.start++

		case '"':
			if r.wantSep != 0 {
				r.errSyntax()
			}

			r.token.kind = tokenString
			r.fetchString()
			return

		case '{', '[':
			if r.wantSep != 0 {
				r.errSyntax()
			}
			r.firstElement = true
			r.token.kind = tokenDelim
			r.token.delimValue = r.Data[r.pos]
			r.pos++
			return

		case '}', ']':
			if !r.firstElement && (r.wantSep != ',') {
				r.errSyntax()
			}
			r.wantSep = 0
			r.token.kind = tokenDelim
			r.token.delimValue = r.Data[r.pos]
			r.pos++
			return

		case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-':
			if r.wantSep != 0 {
				r.errSyntax()
			}
			r.token.kind = tokenNumber
			r.fetchNumber()
			return

		case 'n':
			if r.wantSep != 0 {
				r.errSyntax()
			}

			r.token.kind = tokenNull
			r.fetchNull()
			return

		case 't':
			if r.wantSep != 0 {
				r.errSyntax()
			}

			r.token.kind = tokenBool
			r.token.boolValue = true
			r.fetchTrue()
			return

		case 'f':
			if r.wantSep != 0 {
				r.errSyntax()
			}

			r.token.kind = tokenBool
			r.token.boolValue = false
			r.fetchFalse()
			return

		default:
			r.errSyntax()
			return
		}
	}
	r.fatalError = io.EOF
	return
}
121357
func (i *InternalTokenHelper) Get() (string, error) {
	i.populateTokenPath()
	f, err := os.Open(i.tokenPath)
	if os.IsNotExist(err) {
		return "", nil
	}
	if err != nil {
		return "", err
	}
	defer f.Close()

	buf := bytes.NewBuffer(nil)
	if _, err := io.Copy(buf, f); err != nil {
		return "", err
	}

	return strings.TrimSpace(buf.String()), nil
}
1105193
func (m *tokenManager) ParseToken(ctx context.Context, tokenString string) (*TokenClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &TokenClaims{}, m.KeyFunction(ctx))
	if err != nil {
		return nil, err
	}
	claims := token.Claims.(*TokenClaims)
	if token.Valid {
		return claims, nil
	}
	return nil, errors.WithStack(errors.New("token is not valid"))
}
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
}
362319
func (v *Oneway_Echo_Args) GetToken() (o string) {
	if v != nil && v.Token != nil {
		return *v.Token
	}

	return
}
537871
func TokenFromSecret(secret string) *Token {
	return &Token{
		Provider: provider,
		User:     "",
		Secret:   secret,
	}
}
374229
func (m *tokenManager) GenerateUnsignedUserAccessTokenFromRefreshToken(ctx context.Context, refreshTokenString string, identity *repository.Identity) (*jwt.Token, error) {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Header["kid"] = m.userAccountPrivateKey.KeyID

	req := goa.ContextRequest(ctx)
	if req == nil {
		return nil, errors.New("missing request in context")
	}

	authOpenshiftIO := rest.AbsoluteURL(req, "", m.config)
	openshiftIO, err := rest.ReplaceDomainPrefixInAbsoluteURL(req, "", "", m.config)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	refreshTokenClaims, err := m.ParseToken(ctx, refreshTokenString)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	claims := token.Claims.(jwt.MapClaims)
	claims["jti"] = uuid.NewV4().String()
	iat := time.Now().Unix()
	claims["exp"] = iat + m.config.GetAccessTokenExpiresIn()
	claims["nbf"] = 0
	claims["iat"] = iat
	claims["iss"] = authOpenshiftIO
	claims["aud"] = openshiftIO
	claims["typ"] = "Bearer"
	claims["auth_time"] = iat // TODO should use the time when user actually logged-in the last time. Will need to get this time from the RHD token
	claims["allowed-origins"] = []string{
		authOpenshiftIO,
		openshiftIO,
	}
	claims["approved"] = identity != nil && !identity.User.Banned
	if identity != nil {
		claims["sub"] = identity.ID.String()
		claims["email_verified"] = identity.User.EmailVerified
		claims["name"] = identity.User.FullName
		claims["preferred_username"] = identity.Username
		firstName, lastName := account.SplitFullName(identity.User.FullName)
		claims["given_name"] = firstName
		claims["family_name"] = lastName
		claims["email"] = identity.User.Email
		claims["company"] = identity.User.Company
	} else {
		claims["sub"] = refreshTokenClaims.Subject

		// refresh token should have all following claims included only for api_client(e.g. vscode analytics) who don't have identity in auth db
		claims["email_verified"] = refreshTokenClaims.EmailVerified
		claims["name"] = refreshTokenClaims.Name
		claims["preferred_username"] = refreshTokenClaims.Username
		claims["given_name"] = refreshTokenClaims.GivenName
		claims["family_name"] = refreshTokenClaims.FamilyName
		claims["email"] = refreshTokenClaims.Email
		claims["company"] = refreshTokenClaims.Company
	}

	claims["azp"] = refreshTokenClaims.Audience
	claims["session_state"] = refreshTokenClaims.SessionState
	claims["acr"] = "0"

	realmAccess := make(map[string]interface{})
	realmAccess["roles"] = []string{"uma_authorization"}
	claims["realm_access"] = realmAccess

	resourceAccess := make(map[string]interface{})
	broker := make(map[string]interface{})
	broker["roles"] = []string{"read-token"}
	resourceAccess["broker"] = broker

	account := make(map[string]interface{})
	account["roles"] = []string{"manage-account", "manage-account-links", "view-profile"}
	resourceAccess["account"] = account

	claims["resource_access"] = resourceAccess

	return token, nil
}
221355
func (a *Authorization) GetToken() string {
	if a == nil || a.Token == nil {
		return ""
	}
	return *a.Token
}
416671
func (i *InstallationToken) GetExpiresAt() time.Time {
	if i == nil || i.ExpiresAt == nil {
		return time.Time{}
	}
	return *i.ExpiresAt
}
71592
func (c *LeaseCache) RegisterAutoAuthToken(token string) error {
	// Get the token from the cache
	oldIndex, err := c.db.Get(cachememdb.IndexNameToken, token)
	if err != nil {
		return err
	}

	// If the index is found, defer its cancelFunc
	if oldIndex != nil {
		defer oldIndex.RenewCtxInfo.CancelFunc()
	}

	// The following randomly generated values are required for index stored by
	// the cache, but are not actually used. We use random values to prevent
	// accidental access.
	id, err := base62.Random(5)
	if err != nil {
		return err
	}
	namespace, err := base62.Random(5)
	if err != nil {
		return err
	}
	requestPath, err := base62.Random(5)
	if err != nil {
		return err
	}

	index := &cachememdb.Index{
		ID:          id,
		Token:       token,
		Namespace:   namespace,
		RequestPath: requestPath,
	}

	// Derive a context off of the lease cache's base context
	ctxInfo := c.createCtxInfo(nil)

	index.RenewCtxInfo = &cachememdb.ContextInfo{
		Ctx:        ctxInfo.Ctx,
		CancelFunc: ctxInfo.CancelFunc,
		DoneCh:     ctxInfo.DoneCh,
	}

	// Store the index in the cache
	c.logger.Debug("storing auto-auth token into the cache")
	err = c.db.Set(index)
	if err != nil {
		c.logger.Error("failed to cache the auto-auth token", "error", err)
		return err
	}

	return nil
}
157954
func (c *Client) GetToken(token string) (services.ProvisionToken, error) {
	out, err := c.Get(c.Endpoint("tokens", token), url.Values{})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return services.UnmarshalProvisionToken(out.Bytes(), services.SkipValidation())
}
446530
func (k *Kontrol) generateToken(tok *token) (string, error) {
	uniqKey := tok.String()

	k.tokenCacheMu.Lock()
	defer k.tokenCacheMu.Unlock()

	if !tok.force {
		if ct, ok := k.tokenCache[uniqKey]; ok {
			return ct.signed, nil
		}
	}

	rsaPrivate, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(tok.keyPair.Private))
	if err != nil {
		return "", err
	}

	id, err := uuid.NewV4()
	if err != nil {
		return "", err
	}

	now := time.Now().UTC()

	claims := &kitekey.KiteClaims{
		StandardClaims: jwt.StandardClaims{
			Issuer:    tok.issuer,
			Subject:   tok.username,
			Audience:  tok.audience,
			ExpiresAt: now.Add(k.tokenTTL()).Add(k.tokenLeeway()).UTC().Unix(),
			IssuedAt:  now.Add(-k.tokenLeeway()).UTC().Unix(),
			Id:        id.String(),
		},
	}

	if !k.TokenNoNBF {
		claims.NotBefore = now.Add(-k.tokenLeeway()).Unix()
	}

	signed, err := jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims).SignedString(rsaPrivate)
	if err != nil {
		return "", errors.New("Server error: Cannot generate a token")
	}

	k.cacheToken(uniqKey, signed)

	return signed, nil
}
912498
func (client *MyInventoryClient) GetLease(leaseID string) (lease InventoryLease, err error) {
  if !client.Enabled {
    return
  }
  effectiveURL := fmt.Sprint(client.ServiceBaseURL, "/leases/", leaseID)
  log.Printf("Fetching lease at %s", effectiveURL)
  response, err := getRawResponseFromURL(effectiveURL)

  if err != nil {
    log.Println(err)
    return
  }

  var remoteLease inventoryLease
  err = json.Unmarshal(response.Data, &remoteLease)
  lease = InventoryLease{Username: remoteLease.User, DaysUntilExpires: getDaysRemainingFromEndDate(remoteLease.EndDate)}

  return
}
144209
func (tf *defaultTokenFetcher) Fetch() (string, error) {
	tf.logger.Printf("[INFO] Getting auth token of %q from UAA (%s)", tf.username, tf.uaaAddr)
	client, err := uaago.NewClient(tf.uaaAddr)
	if err != nil {
		return "", err
	}

	resCh, errCh := make(chan string), make(chan error)
	go func() {
		token, err := client.GetAuthToken(tf.username, tf.password, tf.insecure)
		if err != nil {
			errCh <- err
		}
		resCh <- token
	}()

	timeout := defaultUAATimeout
	if tf.timeout != 0 {
		timeout = tf.timeout
	}

	select {
	case err := <-errCh:
		return "", err
	case <-time.After(timeout):
		return "", fmt.Errorf("request timeout: %s", timeout)
	case token := <-resCh:
		return token, nil
	}
}
246975
func (m *tokenManager) GenerateUnsignedServiceAccountToken(saID string, saName string) *jwt.Token {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Header["kid"] = m.serviceAccountPrivateKey.KeyID
	claims := token.Claims.(jwt.MapClaims)
	claims["service_accountname"] = saName
	claims["sub"] = saID
	claims["jti"] = uuid.NewV4().String()
	claims["iat"] = time.Now().Unix()
	claims["iss"] = m.config.GetAuthServiceURL()
	claims["scopes"] = []string{"uma_protection"}
	return token
}
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
}