// parseToken is used to parse the ?token query param or the X-Consul-Token header or
// Authorization Bearer token header (RFC6750) and resolve proxy tokens to real ACL tokens
972391
func (s *HTTPServer) parseToken(req *http.Request, token *string) {
	s.parseTokenInternal(req, token, true)
}
45651
func (s *HTTPServer) parseTokenWithoutResolvingProxyToken(req *http.Request, token *string) {
	s.parseTokenInternal(req, token, false)
}
1350317
func NewToken(rawToken string) (*Token, error) {
	parts := strings.Split(rawToken, TokenSeparator)
	if len(parts) != 3 {
		return nil, ErrMalformedToken
	}

	var (
		rawHeader, rawClaims   = parts[0], parts[1]
		headerJSON, claimsJSON []byte
		err                    error
	)

	defer func() {
		if err != nil {
			log.Infof("error while unmarshalling raw token: %s", err)
		}
	}()

	if headerJSON, err = joseBase64UrlDecode(rawHeader); err != nil {
		err = fmt.Errorf("unable to decode header: %s", err)
		return nil, ErrMalformedToken
	}

	if claimsJSON, err = joseBase64UrlDecode(rawClaims); err != nil {
		err = fmt.Errorf("unable to decode claims: %s", err)
		return nil, ErrMalformedToken
	}

	token := new(Token)
	token.Header = new(Header)
	token.Claims = new(ClaimSet)

	token.Raw = strings.Join(parts[:2], TokenSeparator)
	if token.Signature, err = joseBase64UrlDecode(parts[2]); err != nil {
		err = fmt.Errorf("unable to decode signature: %s", err)
		return nil, ErrMalformedToken
	}

	if err = json.Unmarshal(headerJSON, token.Header); err != nil {
		return nil, ErrMalformedToken
	}

	if err = json.Unmarshal(claimsJSON, token.Claims); err != nil {
		return nil, ErrMalformedToken
	}

	return token, 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
}
983908
func (s *Restore) ACLToken(token *structs.ACLToken) error {
	if err := s.tx.Insert("acl-tokens", token); err != nil {
		return fmt.Errorf("failed restoring acl token: %s", err)
	}

	if err := indexUpdateMaxTxn(s.tx, token.ModifyIndex, "acl-tokens"); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}
	return nil
}
1299993
func (c *UserConfig) parseAccessToken(response *http.Response) error {
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	params, err := url.ParseQuery(string(body))
	tokenKey := params.Get("oauth_token")
	tokenSecret := params.Get("oauth_token_secret")
	if tokenKey == "" || tokenSecret == "" {
		return fmt.Errorf("No token or secret found")
	}
	c.AccessTokenKey = tokenKey
	c.AccessTokenSecret = tokenSecret
	c.AccessValues = params
	return nil
}
1302248
func NewToken(tokenType TokenType, token, expiry string) *Token {
	return &Token{
		TokenType: tokenType,
		Token:     token,
		Expiry:    expiry,
	}
}
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
}
29436
func (t *tokenAccessor) ParseAckToken(auth *connection.AuthInfo, data []byte) (*tokens.ConnectionClaims, error) {

	gt := t.getToken()
	if gt == nil {
		return nil, errors.New("token is nil")
	}
	if auth == nil {
		return nil, errors.New("auth is nil")
	}
	// Validate the certificate and parse the token
	claims, _, _, err := t.getToken().Decode(true, data, auth.RemotePublicKey)
	if err != nil {
		return nil, err
	}

	// Compare the incoming random context with the stored context
	matchLocal := bytes.Compare(claims.RMT, auth.LocalContext)
	matchRemote := bytes.Compare(claims.LCL, auth.RemoteContext)
	if matchLocal != 0 || matchRemote != 0 {
		return nil, errors.New("failed to match context in ack packet")
	}

	return claims, nil
}
294419
func ParseRequestToken(response string) (*RequestToken, error) {
	val, err := url.ParseQuery(strings.TrimSpace(response))
	if err != nil {
		return nil, err
	}

	ret := &RequestToken{}

	oauth_problem := val.Get("oauth_problem")
	if oauth_problem != "" {
		ret.OAuthProblem = oauth_problem
		return ret, flickErr.NewError(flickErr.RequestTokenError, oauth_problem)
	}

	confirmed, _ := strconv.ParseBool(val.Get("oauth_callback_confirmed"))
	ret.OauthCallbackConfirmed = confirmed
	ret.OauthToken = val.Get("oauth_token")
	ret.OauthTokenSecret = val.Get("oauth_token_secret")

	return ret, nil
}
1140784
func (s *TestInvokeAuthorizerInput) SetToken(v string) *TestInvokeAuthorizerInput {
	s.Token = &v
	return s
}
150427
func parseTokens(dirs []string) []token {
	if len(dirs) == 0 {
		return make([]token, 0)
	}

	switch dirs[0] {
	case "":
		if len(dirs) == 1 {
			return []token{&component{fns: []componentFn{substring("")}}}
		}
		return parseTokens(dirs[1:])
	case "**":

		rest := parseTokens(dirs[1:])
		if len(rest) == 0 {
			// If there are no remaining tokens, return a lone
			// doubleStar token.
			return []token{&doubleStar{
				Until: nil,
			}}
		}

		// Otherwise, return a doubleStar token that will match greedily
		// until the first component in the remainder of the pattern,
		// and then the remainder of the pattern.
		return append([]token{&doubleStar{
			Until: rest[0],
		}}, rest[1:]...)
	default:
		// Ordinarily, simply return the appropriate component, and
		// continue on.
		return append([]token{&component{
			fns: parseComponent(dirs[0]),
		}}, parseTokens(dirs[1:])...)
	}
}
531436
func (ts *tokenServer) postToken(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	grantType := r.PostFormValue("grant_type")
	if grantType == "" {
		handleError(ctx, ErrorMissingRequiredField.WithDetail("missing grant_type value"), w)
		return
	}

	service := r.PostFormValue("service")
	if service == "" {
		handleError(ctx, ErrorMissingRequiredField.WithDetail("missing service value"), w)
		return
	}

	clientID := r.PostFormValue("client_id")
	if clientID == "" {
		handleError(ctx, ErrorMissingRequiredField.WithDetail("missing client_id value"), w)
		return
	}

	var offline bool
	switch r.PostFormValue("access_type") {
	case "", "online":
	case "offline":
		offline = true
	default:
		handleError(ctx, ErrorUnsupportedValue.WithDetail("unknown access_type value"), w)
		return
	}

	requestedAccessList := ResolveScopeList(ctx, r.PostFormValue("scope"))

	var subject string
	var rToken string
	switch grantType {
	case "refresh_token":
		rToken = r.PostFormValue("refresh_token")
		if rToken == "" {
			handleError(ctx, ErrorUnsupportedValue.WithDetail("missing refresh_token value"), w)
			return
		}
		rt, ok := ts.refreshCache[rToken]
		if !ok || rt.service != service {
			handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail("invalid refresh token"), w)
			return
		}
		subject = rt.subject
	case "password":
		ca, ok := ts.accessController.(auth.CredentialAuthenticator)
		if !ok {
			handleError(ctx, ErrorUnsupportedValue.WithDetail("password grant type not supported"), w)
			return
		}
		subject = r.PostFormValue("username")
		if subject == "" {
			handleError(ctx, ErrorUnsupportedValue.WithDetail("missing username value"), w)
			return
		}
		password := r.PostFormValue("password")
		if password == "" {
			handleError(ctx, ErrorUnsupportedValue.WithDetail("missing password value"), w)
			return
		}
		if err := ca.AuthenticateUser(subject, password); err != nil {
			handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail("invalid credentials"), w)
			return
		}
	default:
		handleError(ctx, ErrorUnsupportedValue.WithDetail("unknown grant_type value"), w)
		return
	}

	ctx = context.WithValue(ctx, acctSubject{}, subject)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, acctSubject{}))

	dcontext.GetLogger(ctx).Info("authenticated client")

	ctx = context.WithValue(ctx, requestedAccess{}, requestedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, requestedAccess{}))

	grantedAccessList := filterAccessList(ctx, subject, requestedAccessList)
	ctx = context.WithValue(ctx, grantedAccess{}, grantedAccessList)
	ctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, grantedAccess{}))

	token, err := ts.issuer.CreateJWT(subject, service, grantedAccessList)
	if err != nil {
		handleError(ctx, err, w)
		return
	}

	dcontext.GetLogger(ctx).Info("authorized client")

	response := postTokenResponse{
		Token:     token,
		ExpiresIn: int(ts.issuer.Expiration.Seconds()),
		IssuedAt:  time.Now().UTC().Format(time.RFC3339),
		Scope:     ToScopeList(grantedAccessList),
	}

	if offline {
		rToken = newRefreshToken()
		ts.refreshCache[rToken] = refreshToken{
			subject: subject,
			service: service,
		}
	}

	if rToken != "" {
		response.RefreshToken = rToken
	}

	ctx, w = dcontext.WithResponseWriter(ctx, w)

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)

	dcontext.GetResponseLogger(ctx).Info("post token complete")
}
986999
func (o *Config) ExchangeGatewayKeyForToken(gatewayID, gatewayKey string) (*oauth2.Token, error) {
	strategy := auth.AccessKey(gatewayKey)
	token := &tok{}
	err := util.GET(log.Get(), o.Server, strategy, fmt.Sprintf("/api/v2/gateways/%s/token", gatewayID), o.Client.ExtraHeaders, token)
	return token.Token(), err
}
1087796
func ParseTokenParam(paramString string, info SearchParamInfo) *TokenParam {
	t := &TokenParam{SearchParamInfo: info}
	splitCode := escapeFriendlySplit(paramString, '|')
	if len(splitCode) > 1 {
		t.System = unescape(splitCode[0])
		t.Code = unescape(splitCode[1])
	} else {
		t.AnySystem = true
		t.Code = unescape(splitCode[0])
	}
	return t
}
1342369
func (req *MCRequest) ParseTapCommands() (TapConnect, error) {
	rv := TapConnect{
		Flags: map[TapConnectFlag]interface{}{},
		Name:  string(req.Key),
	}

	if len(req.Extras) < 4 {
		return rv, fmt.Errorf("not enough extra bytes: %x", req.Extras)
	}

	flags := TapConnectFlag(binary.BigEndian.Uint32(req.Extras))

	r := bytes.NewReader(req.Body)

	for _, f := range flags.SplitFlags() {
		fun := TapFlagParsers[f]
		if fun == nil {
			fun = TapParseBool
		}

		val, err := fun(r)
		if err != nil {
			return rv, err
		}

		rv.Flags[f] = val
	}

	var err error
	rv.RemainingBody, err = ioutil.ReadAll(r)

	return rv, err
}
1177999
func NewToken(token string) *Token {
	tok := Token{
		Tok:        token,
		reEllipsis: reEllipsis,
		reNumeric:  reNumeric,
		reInitial:  reInitial,
		reAlpha:    reAlpha,
	}

	return &tok
}