// processTokenLookupResponse checks if the request was one of token
// lookup-self. If the auto-auth token was used to perform lookup-self, the
// identifier of the token and its accessor same will be stripped off of the
// response.
510187
func processTokenLookupResponse(ctx context.Context, logger hclog.Logger, inmemSink sink.Sink, req *SendRequest, resp *SendResponse) error {
	// If auto-auth token is not being used, there is nothing to do.
	if inmemSink == nil {
		return nil
	}
	autoAuthToken := inmemSink.(sink.SinkReader).Token()

	// If lookup responded with non 200 status, there is nothing to do.
	if resp.Response.StatusCode != http.StatusOK {
		return nil
	}

	_, path := deriveNamespaceAndRevocationPath(req)
	switch path {
	case vaultPathTokenLookupSelf:
		if req.Token != autoAuthToken {
			return nil
		}
	case vaultPathTokenLookup:
		jsonBody := map[string]interface{}{}
		if err := json.Unmarshal(req.RequestBody, &jsonBody); err != nil {
			return err
		}
		tokenRaw, ok := jsonBody["token"]
		if !ok {
			// Input error will be caught by the API
			return nil
		}
		token, ok := tokenRaw.(string)
		if !ok {
			// Input error will be caught by the API
			return nil
		}
		if token != "" && token != autoAuthToken {
			// Lookup is performed on the non-auto-auth token
			return nil
		}
	default:
		return nil
	}

	logger.Info("stripping auto-auth token from the response", "path", req.Request.URL.Path, "method", req.Request.Method)
	secret, err := api.ParseSecret(bytes.NewReader(resp.ResponseBody))
	if err != nil {
		return fmt.Errorf("failed to parse token lookup response: %v", err)
	}
	if secret == nil || secret.Data == nil {
		return nil
	}
	if secret.Data["id"] == nil && secret.Data["accessor"] == nil {
		return nil
	}

	delete(secret.Data, "id")
	delete(secret.Data, "accessor")

	bodyBytes, err := json.Marshal(secret)
	if err != nil {
		return err
	}
	if resp.Response.Body != nil {
		resp.Response.Body.Close()
	}
	resp.Response.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))
	resp.Response.ContentLength = int64(len(bodyBytes))

	// Serialize and re-read the reponse
	var respBytes bytes.Buffer
	err = resp.Response.Write(&respBytes)
	if err != nil {
		return fmt.Errorf("failed to serialize the updated response: %v", err)
	}

	updatedResponse, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(respBytes.Bytes())), nil)
	if err != nil {
		return fmt.Errorf("failed to deserialize the updated response: %v", err)
	}

	resp.Response = &api.Response{
		Response: updatedResponse,
	}
	resp.ResponseBody = bodyBytes

	return nil
}
1302183
func ParseOAuthToken(response string) (*OAuthToken, error) {
	val, err := url.ParseQuery(strings.TrimSpace(response))
	if err != nil {
		return nil, err
	}

	ret := &OAuthToken{}

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

	ret.OAuthToken = val.Get("oauth_token")
	ret.OAuthTokenSecret = val.Get("oauth_token_secret")
	ret.Fullname = val.Get("fullname")
	ret.UserNsid = val.Get("user_nsid")
	ret.Username = val.Get("username")

	return ret, nil
}
542067
func (a *HistoricalApi) processMetricRequest(key core.HistoricalKey, request *restful.Request, response *restful.Response) {
	start, end, err := getStartEndTimeHistorical(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}
	labels, err := getLabels(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}
	metricName := request.PathParameter("metric-name")
	convertedMetricName := convertMetricName(metricName)

	var metrics map[core.HistoricalKey][]core.TimestampedMetricValue
	if labels != nil {
		metrics, err = a.historicalSource.GetLabeledMetric(convertedMetricName, labels, []core.HistoricalKey{key}, start, end)
	} else {
		metrics, err = a.historicalSource.GetMetric(convertedMetricName, []core.HistoricalKey{key}, start, end)
	}
	if err != nil {
		response.WriteError(http.StatusInternalServerError, err)
		return
	}

	converted := exportTimestampedMetricValue(metrics[key])
	response.WriteEntity(converted)
}
1208727
func (r *InspectOAuthTokenGrantRPC) InspectOAuthTokenGrant(c context.Context, req *admin.InspectOAuthTokenGrantRequest) (*admin.InspectOAuthTokenGrantResponse, error) {
	inspection, err := InspectGrant(c, r.Signer, req.Token)
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}

	resp := &admin.InspectOAuthTokenGrantResponse{
		Valid:            inspection.Signed && inspection.NonExpired,
		Signed:           inspection.Signed,
		NonExpired:       inspection.NonExpired,
		InvalidityReason: inspection.InvalidityReason,
	}

	addInvalidityReason := func(msg string, args ...interface{}) {
		reason := fmt.Sprintf(msg, args...)
		resp.Valid = false
		if resp.InvalidityReason == "" {
			resp.InvalidityReason = reason
		} else {
			resp.InvalidityReason += "; " + reason
		}
	}

	if env, _ := inspection.Envelope.(*tokenserver.OAuthTokenGrantEnvelope); env != nil {
		resp.SigningKeyId = env.KeyId
	}

	// Examine the body, even if the token is expired or unsigned. This helps to
	// debug expired or unsigned tokens...
	resp.TokenBody, _ = inspection.Body.(*tokenserver.OAuthTokenGrantBody)
	if resp.TokenBody != nil {
		rules, err := r.Rules(c)
		if err != nil {
			return nil, status.Errorf(codes.Internal, "failed to load service accounts rules")
		}

		// Always return the rule that matches the service account, even if the
		// token itself is not allowed by it (we check it separately below).
		rule, err := rules.Rule(c, resp.TokenBody.ServiceAccount, "")
		switch {
		case status.Code(err) == codes.PermissionDenied:
			s, _ := status.FromError(err)
			addInvalidityReason("%s", s.Message())
			return resp, nil
		case err != nil: // usually codes.Internal
			return nil, err
		default:
			resp.MatchingRule = rule.Rule
		}

		q := &RulesQuery{
			ServiceAccount: resp.TokenBody.ServiceAccount,
			Rule:           rule,
			Proxy:          identity.Identity(resp.TokenBody.Proxy),
			EndUser:        identity.Identity(resp.TokenBody.EndUser),
		}
		switch _, err = rules.Check(c, q); {
		case err == nil:
			resp.AllowedByRules = true
		case status.Code(err) == codes.Internal:
			return nil, err // a transient error when checking rules
		default: // fatal gRPC error => the rules forbid the token
			addInvalidityReason("not allowed by the rules (rev %s)", rules.ConfigRevision())
		}
	}

	return resp, nil
}
799654
func (m *Middleware) VerifyToken(token string, v VerifyClaimsFunc, r *http.Request) (int, string, error) {
	tokenParts := strings.Split(token, ".")
	if len(tokenParts) != 3 {
		return http.StatusUnauthorized, "", ErrMalformedToken
	}

	// First, verify JOSE header
	header, err := decode(tokenParts[0])
	if err != nil {
		return http.StatusInternalServerError, fmt.Sprintf("decoding header (%v)", tokenParts[0]), err
	}
	var t struct {
		Typ string
		Alg string
	}
	err = json.Unmarshal(header, &t)
	if err != nil {
		return http.StatusInternalServerError, fmt.Sprintf("unmarshalling header (%s)", header), ErrMalformedToken
	}

	// Then, verify signature
	mac := hmac.New(sha256.New, []byte(m.secret))
	message := []byte(strings.Join([]string{tokenParts[0], tokenParts[1]}, "."))
	mac.Write(message)
	expectedMac, err := encode(mac.Sum(nil))
	if err != nil {
		return http.StatusInternalServerError, "", err
	}
	if !hmac.Equal([]byte(tokenParts[2]), []byte(expectedMac)) {
		return http.StatusUnauthorized, fmt.Sprintf("checking signature (%v)", tokenParts[2]), ErrInvalidSignature
	}

	// Finally, check claims
	claimSet, err := decode(tokenParts[1])
	if err != nil {
		return http.StatusInternalServerError, "decoding claims", ErrDecoding
	}
	err = v(claimSet, r)
	if err != nil {
		return http.StatusUnauthorized, "handling claims callback", err
	}

	return 200, "", nil
}
624440
func (l *channelLink) processExitHop(pd *lnwallet.PaymentDescriptor,
	obfuscator ErrorEncrypter, fwdInfo ForwardingInfo, heightNow uint32) (
	bool, error) {

	// If hodl.ExitSettle is requested, we will not validate the final hop's
	// ADD, nor will we settle the corresponding invoice or respond with the
	// preimage.
	if l.cfg.DebugHTLC && l.cfg.HodlMask.Active(hodl.ExitSettle) {
		l.warnf(hodl.ExitSettle.Warning())

		return false, nil
	}

	// First, we'll check the expiry of the HTLC itself against, the current
	// block height. If the timeout is too soon, then we'll reject the HTLC.
	if pd.Timeout <= heightNow+l.cfg.FinalCltvRejectDelta {
		log.Errorf("htlc(%x) has an expiry that's too soon: expiry=%v"+
			", best_height=%v", pd.RHash[:], pd.Timeout, heightNow)

		failure := lnwire.NewFinalExpiryTooSoon()
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// We're the designated payment destination.  Therefore we attempt to
	// see if we have an invoice locally which'll allow us to settle this
	// htlc.
	//
	// Only the immutable data from LookupInvoice is used, because otherwise
	// a race condition may be created with concurrent writes to the invoice
	// registry. For example: cancelation of an invoice.
	invoiceHash := lntypes.Hash(pd.RHash)
	invoice, minCltvDelta, err := l.cfg.Registry.LookupInvoice(invoiceHash)
	if err != nil {
		log.Errorf("unable to query invoice registry: %v", err)
		failure := lnwire.NewFailUnknownPaymentHash(pd.Amount)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// If the invoice is already settled, we choose to accept the payment to
	// simplify failure recovery.
	//
	// NOTE: Though our recovery and forwarding logic is predominately
	// batched, settling invoices happens iteratively. We may reject one of
	// two payments for the same rhash at first, but then restart and reject
	// both after seeing that the invoice has been settled. Without any
	// record of which one settles first, it is ambiguous as to which one
	// actually settled the invoice. Thus, by accepting all payments, we
	// eliminate the race condition that can lead to this inconsistency.
	//
	// TODO(conner): track ownership of settlements to properly recover from
	// failures? or add batch invoice settlement
	//
	// TODO(joostjager): The log statement below is not always accurate, as
	// the invoice may have been canceled after the LookupInvoice call.
	// Leaving it as is for now, because fixing this would involve changing
	// the signature of InvoiceRegistry.SettleInvoice just because of this
	// log statement.
	if invoice.Terms.State == channeldb.ContractSettled {
		log.Warnf("Accepting duplicate payment for hash=%x",
			pd.RHash[:])
	}

	// If we're not currently in debug mode, and the extended htlc doesn't
	// meet the value requested, then we'll fail the htlc.  Otherwise, we
	// settle this htlc within our local state update log, then send the
	// update entry to the remote party.
	//
	// NOTE: We make an exception when the value requested by the invoice is
	// zero. This means the invoice allows the payee to specify the amount
	// of satoshis they wish to send.  So since we expect the htlc to have a
	// different amount, we should not fail.
	if !l.cfg.DebugHTLC && invoice.Terms.Value > 0 &&
		pd.Amount < invoice.Terms.Value {

		log.Errorf("rejecting htlc due to incorrect amount: expected "+
			"%v, received %v", invoice.Terms.Value, pd.Amount)

		failure := lnwire.NewFailUnknownPaymentHash(pd.Amount)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// As we're the exit hop, we'll double check the hop-payload included in
	// the HTLC to ensure that it was crafted correctly by the sender and
	// matches the HTLC we were extended.
	//
	// NOTE: We make an exception when the value requested by the invoice is
	// zero. This means the invoice allows the payee to specify the amount
	// of satoshis they wish to send.  So since we expect the htlc to have a
	// different amount, we should not fail.
	if !l.cfg.DebugHTLC && invoice.Terms.Value > 0 &&
		fwdInfo.AmountToForward < invoice.Terms.Value {

		log.Errorf("Onion payload of incoming htlc(%x) has incorrect "+
			"value: expected %v, got %v", pd.RHash,
			invoice.Terms.Value, fwdInfo.AmountToForward)

		failure := lnwire.NewFailUnknownPaymentHash(pd.Amount)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// We'll also ensure that our time-lock value has been computed
	// correctly. Only check the final cltv expiry for invoices when the
	// invoice has not yet moved to the accepted state. Otherwise hodl htlcs
	// would be canceled after a restart.
	expectedHeight := heightNow + minCltvDelta
	switch {
	case !l.cfg.DebugHTLC &&
		invoice.Terms.State == channeldb.ContractOpen &&
		pd.Timeout < expectedHeight:

		log.Errorf("Incoming htlc(%x) has an expiration that is too "+
			"soon: expected at least %v, got %v",
			pd.RHash[:], expectedHeight, pd.Timeout)

		failure := lnwire.FailFinalExpiryTooSoon{}
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil

	case !l.cfg.DebugHTLC && pd.Timeout != fwdInfo.OutgoingCTLV:
		log.Errorf("HTLC(%x) has incorrect time-lock: expected %v, "+
			"got %v", pd.RHash[:], pd.Timeout, fwdInfo.OutgoingCTLV)

		failure := lnwire.NewFinalIncorrectCltvExpiry(
			fwdInfo.OutgoingCTLV,
		)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// Notify the invoiceRegistry of the exit hop htlc. If we crash right
	// after this, this code will be re-executed after restart. We will
	// receive back a resolution event.
	event, err := l.cfg.Registry.NotifyExitHopHtlc(
		invoiceHash, pd.Amount, l.hodlQueue.ChanIn(),
	)
	if err != nil {
		return false, err
	}

	// Create a hodlHtlc struct and decide either resolved now or later.
	htlc := hodlHtlc{
		pd:         pd,
		obfuscator: obfuscator,
	}

	if event == nil {
		// Save payment descriptor for future reference.
		hodlHtlcs := l.hodlMap[invoiceHash]
		l.hodlMap[invoiceHash] = append(hodlHtlcs, htlc)

		return false, nil
	}

	// Process the received resolution.
	err = l.processHodlEvent(*event, htlc)
	if err != nil {
		return false, err
	}
	return true, nil
}
791479
func (f TokenFunc) AuthenticateToken(ctx context.Context, token string) (*Response, bool, error) {
	return f(ctx, token)
}
1186911
func Lookup(ident []byte) Token {
	// TODO Maps with []byte key are illegal because []byte does not
	//      support == . Should find a more efficient solution eventually.
	if tok, is_keyword := keywords[string(ident)]; is_keyword {
		return tok
	}
	return IDENT
}
943497
func (f *FilterChain) ProcessFilter(request *Request, response *Response) {
	if f.Index < len(f.Filters) {
		f.Index++
		f.Filters[f.Index-1](request, response, f)
	} else {
		f.Target(request, response)
	}
}
35724
func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams) (err error) {
	uri := EndpointWebhookToken(webhookID, token)

	if wait {
		uri += "?wait=true"
	}

	_, err = s.RequestWithBucketID("POST", uri, data, EndpointWebhookToken("", ""))

	return
}
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
}
491225
func (hcc *healthCheckConn) processResponse(hc *HealthCheckImpl, shr *querypb.StreamHealthResponse) error {
	select {
	case <-hcc.ctx.Done():
		return hcc.ctx.Err()
	default:
	}

	// Check for invalid data, better than panicking.
	if shr.Target == nil || shr.RealtimeStats == nil {
		return fmt.Errorf("health stats is not valid: %v", shr)
	}

	// an app-level error from tablet, force serving state.
	var healthErr error
	serving := shr.Serving
	if shr.RealtimeStats.HealthError != "" {
		healthErr = fmt.Errorf("vttablet error: %v", shr.RealtimeStats.HealthError)
		serving = false
	}

	// hcc.TabletStats.Tablet.Alias.Uid may be 0 because the youtube internal mechanism uses a different
	// code path to initialize this value. If so, we should skip this check.
	if shr.TabletAlias != nil && hcc.tabletStats.Tablet.Alias.Uid != 0 && !proto.Equal(shr.TabletAlias, hcc.tabletStats.Tablet.Alias) {
		return fmt.Errorf("health stats mismatch, tablet %+v alias does not match response alias %v", hcc.tabletStats.Tablet, shr.TabletAlias)
	}

	// In this case where a new tablet is initialized or a tablet type changes, we want to
	// initialize the counter so the rate can be calculated correctly.
	if hcc.tabletStats.Target.TabletType != shr.Target.TabletType {
		hcErrorCounters.Add([]string{shr.Target.Keyspace, shr.Target.Shard, topoproto.TabletTypeLString(shr.Target.TabletType)}, 0)
	}

	// Update our record, and notify downstream for tabletType and
	// realtimeStats change.
	hcc.lastResponseTimestamp = time.Now()
	hcc.tabletStats.Target = shr.Target
	hcc.tabletStats.TabletExternallyReparentedTimestamp = shr.TabletExternallyReparentedTimestamp
	hcc.tabletStats.Stats = shr.RealtimeStats
	hcc.tabletStats.LastError = healthErr
	reason := "healthCheck update"
	if healthErr != nil {
		reason = "healthCheck update error: " + healthErr.Error()
	}
	hcc.setServingState(serving, reason)
	hc.updateHealth(hcc.tabletStats.Copy(), hcc.conn)
	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
}
263593
func doesSignatureMatch(hashedPayload string, r *http.Request, region string, stype serviceType) APIErrorCode {
	// Copy request.
	req := *r

	// Save authorization header.
	v4Auth := req.Header.Get("Authorization")

	// Parse signature version '4' header.
	signV4Values, err := parseSignV4(v4Auth, region, stype)
	if err != ErrNone {
		return err
	}

	// Extract all the signed headers along with its values.
	extractedSignedHeaders, errCode := extractSignedHeaders(signV4Values.SignedHeaders, r)
	if errCode != ErrNone {
		return errCode
	}

	cred, _, s3Err := checkKeyValid(signV4Values.Credential.accessKey)
	if s3Err != ErrNone {
		return s3Err
	}

	// Extract date, if not present throw error.
	var date string
	if date = req.Header.Get(http.CanonicalHeaderKey("x-amz-date")); date == "" {
		if date = r.Header.Get("Date"); date == "" {
			return ErrMissingDateHeader
		}
	}

	// Parse date header.
	t, e := time.Parse(iso8601Format, date)
	if e != nil {
		return ErrMalformedDate
	}

	// Query string.
	queryStr := req.URL.Query().Encode()

	// Get canonical request.
	canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, queryStr, req.URL.Path, req.Method)

	// Get string to sign from canonical request.
	stringToSign := getStringToSign(canonicalRequest, t, signV4Values.Credential.getScope())

	// Get hmac signing key.
	signingKey := getSigningKey(cred.SecretKey, signV4Values.Credential.scope.date,
		signV4Values.Credential.scope.region, stype)

	// Calculate signature.
	newSignature := getSignature(signingKey, stringToSign)

	// Verify if signature match.
	if !compareSignatureV4(newSignature, signV4Values.Signature) {
		return ErrSignatureDoesNotMatch
	}

	// Return error none.
	return ErrNone
}
1359441
func (nc *Conn) processAuthorizationViolation(err string) {
	nc.mu.Lock()
	nc.err = ErrAuthorization
	if nc.Opts.AsyncErrorCB != nil {
		nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, ErrAuthorization) })
	}
	nc.mu.Unlock()
}
744472
func Lookup(identity *identityPkg.Identity) SelectorPolicy {
	cip, _ := globalPolicyCache.lookupOrCreate(identity, false)
	return cip
}
579552
func (ts *TokenStore) handleUpdateLookupAccessor(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	accessor := data.Get("accessor").(string)
	if accessor == "" {
		return nil, &logical.StatusBadRequest{Err: "missing accessor"}
	}

	aEntry, err := ts.lookupByAccessor(ctx, accessor, false, false)
	if err != nil {
		return nil, err
	}

	// Prepare the field data required for a lookup call
	d := &framework.FieldData{
		Raw: map[string]interface{}{
			"token": aEntry.TokenID,
		},
		Schema: map[string]*framework.FieldSchema{
			"token": &framework.FieldSchema{
				Type:        framework.TypeString,
				Description: "Token to lookup",
			},
		},
	}
	resp, err := ts.handleLookup(ctx, req, d)
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, fmt.Errorf("failed to lookup the token")
	}
	if resp.IsError() {
		return resp, nil

	}

	// Remove the token ID from the response
	if resp.Data != nil {
		resp.Data["id"] = ""
	}

	return resp, nil
}