void TokenSubscriber::processResponse()

in src/envoy/token/token_subscriber.cc [146:209]


void TokenSubscriber::processResponse(
    Envoy::Http::ResponseMessagePtr&& response) {
  auto status =
      Envoy::Http::Utility::getResponseStatusOrNullopt(response->headers());
  if (!status.has_value()) {
    // This occurs if the status header is missing.
    // Catch the exception to prevent unwinding and skipping cleanup.
    ENVOY_LOG(error, "{}: failed: No status in headers", debug_name_);
    handleFailResponse();
    return;
  }

  const uint64_t status_code = status.value();
  if (status_code != Envoy::enumToInt(Envoy::Http::Code::OK)) {
    ENVOY_LOG(error, "{}: failed: {}", debug_name_, status_code);
    handleFailResponse();
    return;
  }

  // Delegate parsing the HTTP response.
  TokenResult result{};
  bool success;
  switch (token_type_) {
    case IdentityToken:
      success =
          token_info_->parseIdentityToken(response->bodyAsString(), &result);
      break;
    case AccessToken:
      success =
          token_info_->parseAccessToken(response->bodyAsString(), &result);
      break;
    default:
      PANIC(absl::StrCat("invalid token type: ", token_type_));
  }

  // Determine status.
  if (!success) {
    handleFailResponse();
    return;
  }

  // Token will be used as a HTTP_HEADER_VALUE in the future. Ensure it is
  // sanitized. Otherwise, special characters will cause a runtime failure
  // in other components.
  if (!Envoy::Http::validHeaderString(result.token)) {
    ENVOY_LOG(error,
              "{}: failed because invalid characters were detected in token {}",
              debug_name_, result.token);
    handleFailResponse();
    return;
  }

  // Tokens that have already expired are treated as failures.
  if (result.expiry_duration.count() <= 0) {
    ENVOY_LOG(error,
              "{}: failed because token has already expired, it expired {} "
              "seconds ago",
              debug_name_, result.expiry_duration.count());
    handleFailResponse();
    return;
  }

  handleSuccessResponse(result.token, result.expiry_duration);
}