Envoy::Http::RequestMessagePtr IamTokenInfo::prepareRequest()

in src/envoy/token/iam_token_info.cc [59:107]


Envoy::Http::RequestMessagePtr IamTokenInfo::prepareRequest(
    absl::string_view token_url) const {
  const std::string access_token = access_token_fn_();
  // Wait for the access token to be set.
  if (access_token.empty()) {
    // This codes depends on access_token. This periodical pulling is not ideal.
    // But when both imds_token_subscriber and iam_token_subscriber register to
    // init_manager,  it will trigger both at the same time. For
    // easy implementation,  just using periodical pulling for now
    return nullptr;
  }

  absl::string_view host, path;
  Envoy::Http::Utility::extractHostPathFromUri(token_url, host, path);
  auto headers =
      Envoy::Http::createHeaderMap<Envoy::Http::RequestHeaderMapImpl>(
          {{Envoy::Http::Headers::get().Method, "POST"},
           {Envoy::Http::Headers::get().Host, std::string(host)},
           {Envoy::Http::Headers::get().Path, std::string(path)},
           {kAuthorizationKey, "Bearer " + access_token}});

  Envoy::Http::RequestMessagePtr message(
      new Envoy::Http::RequestMessageImpl(std::move(headers)));

  Envoy::ProtobufWkt::Value body;
  if (!delegates_.empty()) {
    insertStrListToProto(body, kDelegatesField, delegates_, kDelegatePrefix);
  }

  if (!scopes_.empty()) {
    insertStrListToProto(body, kScopesField, scopes_, Envoy::EMPTY_STRING);
  }

  if (include_email_) {
    Envoy::ProtobufWkt::Value val;
    val.set_bool_value(true);
    (*body.mutable_struct_value()->mutable_fields())[kIncludeEmail].Swap(&val);
  }

  if (!delegates_.empty() || !scopes_.empty() || include_email_) {
    auto json_or_error =
        Envoy::MessageUtil::getJsonStringFromMessage(body, false, false);
    if (json_or_error.ok()) {
      message->body().add(json_or_error.value().data(),
                          json_or_error.value().size());
    }
  }
  return message;
}