Commit 77b36bd1 authored by Maksim Moskvitin's avatar Maksim Moskvitin Committed by Commit Bot

[TrustedVault] Implement VaultServiceApiCallFlow

New class wraps network logic and allows sending GET and POST requests,
indicating that both request and response content types should be
serialized protobufs.

Bug: 1113598
Change-Id: Iccb65cd734025bde6df7bf927698d90d19b5b0a8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2404796Reviewed-by: default avatarMatt Menke <mmenke@chromium.org>
Reviewed-by: default avatarMikel Astiz <mastiz@chromium.org>
Commit-Queue: Maksim Moskvitin <mmoskvitin@google.com>
Cr-Commit-Position: refs/heads/master@{#815158}
parent 711fd958
......@@ -507,6 +507,7 @@ source_set("unit_tests") {
"trusted_vault/securebox_unittest.cc",
"trusted_vault/standalone_trusted_vault_backend_unittest.cc",
"trusted_vault/trusted_vault_access_token_fetcher_frontend_unittest.cc",
"trusted_vault/vault_service_api_call_flow_unittest.cc",
]
configs += [ "//build/config:precompiled_headers" ]
......
......@@ -18,6 +18,8 @@ static_library("trusted_vault") {
"trusted_vault_connection.h",
"trusted_vault_connection_impl.cc",
"trusted_vault_connection_impl.h",
"vault_service_api_call_flow.cc",
"vault_service_api_call_flow.h",
]
public_deps = [
"//base",
......@@ -29,6 +31,7 @@ static_library("trusted_vault") {
"//components/sync/base",
"//components/sync/protocol",
"//crypto",
"//net",
"//services/network/public/cpp:cpp",
"//third_party/boringssl",
]
......
......@@ -6,6 +6,8 @@ include_rules = [
"+components/sync/engine",
"+components/sync/protocol",
"+crypto",
"+net",
"+services/network/public",
"+services/network/test",
"+third_party/boringssl",
]
\ No newline at end of file
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/trusted_vault/vault_service_api_call_flow.h"
#include <utility>
#include "components/signin/public/identity_manager/access_token_info.h"
#include "components/sync/trusted_vault/trusted_vault_access_token_fetcher.h"
#include "net/base/url_util.h"
#include "net/http/http_request_headers.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace syncer {
namespace {
const char kProtobufContentType[] = "application/x-protobuf";
const char kQueryParameterAlternateOutputKey[] = "alt";
const char kQueryParameterAlternateOutputProto[] = "proto";
} // namespace
VaultServiceApiCallFlow::VaultServiceApiCallFlow(
HttpMethod http_method,
const GURL& request_url,
const net::PartialNetworkTrafficAnnotationTag partial_annotation_tag,
const base::Optional<std::string>& serialized_request_proto)
: http_method_(http_method),
request_url_(request_url),
serialized_request_proto_(serialized_request_proto),
partial_annotation_tag_(partial_annotation_tag) {
DCHECK(http_method == HttpMethod::kPost ||
!serialized_request_proto.has_value());
}
VaultServiceApiCallFlow::~VaultServiceApiCallFlow() = default;
void VaultServiceApiCallFlow::FetchAccessTokenAndStartFlow(
const CoreAccountId& account_id,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
TrustedVaultAccessTokenFetcher* access_token_fetcher,
CompletionCallback callback) {
DCHECK(url_loader_factory);
DCHECK(access_token_fetcher);
completion_callback_ = std::move(callback);
access_token_fetcher->FetchAccessToken(
account_id,
base::BindOnce(&VaultServiceApiCallFlow::OnAccessTokenFetched,
weak_ptr_factory_.GetWeakPtr(), url_loader_factory));
}
void VaultServiceApiCallFlow::Start(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const std::string& access_token) {
OAuth2ApiCallFlow::Start(url_loader_factory, access_token);
}
GURL VaultServiceApiCallFlow::CreateApiCallUrl() {
// Specify that the server's response body should be formatted as a
// serialized proto.
return net::AppendQueryParameter(request_url_,
kQueryParameterAlternateOutputKey,
kQueryParameterAlternateOutputProto);
}
std::string VaultServiceApiCallFlow::CreateApiCallBody() {
return serialized_request_proto_.value_or(std::string());
}
std::string VaultServiceApiCallFlow::CreateApiCallBodyContentType() {
return serialized_request_proto_.has_value() ? kProtobufContentType
: std::string();
}
std::string VaultServiceApiCallFlow::GetRequestTypeForBody(
const std::string& body) {
switch (http_method_) {
case HttpMethod::kGet:
return "GET";
case HttpMethod::kPost:
return "POST";
}
NOTREACHED();
return std::string();
}
void VaultServiceApiCallFlow::ProcessApiCallSuccess(
const network::mojom::URLResponseHead* head,
std::unique_ptr<std::string> body) {
// Response proto can be filled with default values and be not presented as
// |body|.
RunCompletionCallbackAndMaybeDestroySelf(/*success=*/true,
body ? *body : std::string());
}
void VaultServiceApiCallFlow::ProcessApiCallFailure(
int net_error,
const network::mojom::URLResponseHead* head,
std::unique_ptr<std::string> body) {
RunCompletionCallbackAndMaybeDestroySelf(/*success=*/false,
/*response_body=*/std::string());
}
net::PartialNetworkTrafficAnnotationTag
VaultServiceApiCallFlow::GetNetworkTrafficAnnotationTag() {
return partial_annotation_tag_;
}
void VaultServiceApiCallFlow::OnAccessTokenFetched(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
base::Optional<signin::AccessTokenInfo> access_token_info) {
if (access_token_info.has_value()) {
Start(url_loader_factory, access_token_info->token);
return;
}
RunCompletionCallbackAndMaybeDestroySelf(/*success=*/false,
/*response_body=*/std::string());
}
void VaultServiceApiCallFlow::RunCompletionCallbackAndMaybeDestroySelf(
bool success,
const std::string& response_body) {
std::move(completion_callback_).Run(success, response_body);
}
} // namespace syncer
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_TRUSTED_VAULT_VAULT_SERVICE_API_CALL_FLOW_H_
#define COMPONENTS_SYNC_TRUSTED_VAULT_VAULT_SERVICE_API_CALL_FLOW_H_
#include <memory>
#include <string>
#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
#include "google_apis/gaia/oauth2_api_call_flow.h"
#include "url/gurl.h"
struct CoreAccountId;
namespace signin {
struct AccessTokenInfo;
} // namespace signin
namespace syncer {
class TrustedVaultAccessTokenFetcher;
// Allows calling VaultService API using proto-over-http.
class VaultServiceApiCallFlow : public OAuth2ApiCallFlow {
public:
using CompletionCallback =
base::OnceCallback<void(bool success, const std::string& response_body)>;
enum class HttpMethod { kGet, kPost };
// |callback| will be run upon completion and it's allowed to delete this
// object upon |callback| call. For GET requests, |serialized_request_proto|
// must be null. For |POST| requests, it can be either way (optional payload).
VaultServiceApiCallFlow(
HttpMethod http_method,
const GURL& request_url,
const net::PartialNetworkTrafficAnnotationTag partial_annotation_tag,
const base::Optional<std::string>& serialized_request_proto);
VaultServiceApiCallFlow(const VaultServiceApiCallFlow& other) = delete;
VaultServiceApiCallFlow& operator=(const VaultServiceApiCallFlow& other) =
delete;
~VaultServiceApiCallFlow() override;
// Attempts to fetch access token, Start() the flow if fetch is successful
// and populate error into ResultCallback otherwise. Should be called at most
// once.
void FetchAccessTokenAndStartFlow(
const CoreAccountId& account_id,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
TrustedVaultAccessTokenFetcher* access_token_fetcher,
CompletionCallback callback);
// Starts the flow by forwarding call to OAuth2ApiCallFlow::Start().
// Overridden to make public class API explicit.
// WARNING: don't call this directly and use FetchAccessTokenAndStartFlow().
void Start(scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const std::string& access_token) override;
protected:
// OAuth2ApiCallFlow implementation.
GURL CreateApiCallUrl() override;
std::string CreateApiCallBody() override;
std::string CreateApiCallBodyContentType() override;
std::string GetRequestTypeForBody(const std::string& body) override;
void ProcessApiCallSuccess(const network::mojom::URLResponseHead* head,
std::unique_ptr<std::string> body) override;
void ProcessApiCallFailure(int net_error,
const network::mojom::URLResponseHead* head,
std::unique_ptr<std::string> body) override;
net::PartialNetworkTrafficAnnotationTag GetNetworkTrafficAnnotationTag()
override;
private:
void OnAccessTokenFetched(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
base::Optional<signin::AccessTokenInfo> access_token_info);
// Running |completion_callback_| may cause destroying of this object, so all
// callers of this method must not run any code afterwards.
void RunCompletionCallbackAndMaybeDestroySelf(
bool success,
const std::string& response_body);
const HttpMethod http_method_;
const GURL request_url_;
const base::Optional<std::string> serialized_request_proto_;
const net::PartialNetworkTrafficAnnotationTag partial_annotation_tag_;
CompletionCallback completion_callback_;
base::WeakPtrFactory<VaultServiceApiCallFlow> weak_ptr_factory_{this};
};
} // namespace syncer
#endif // COMPONENTS_SYNC_TRUSTED_VAULT_VAULT_SERVICE_API_CALL_FLOW_H_
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/trusted_vault/vault_service_api_call_flow.h"
#include <memory>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "components/signin/public/identity_manager/access_token_info.h"
#include "components/sync/trusted_vault/trusted_vault_access_token_fetcher.h"
#include "google_apis/gaia/core_account_id.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/network/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace syncer {
namespace {
using testing::_;
using testing::Eq;
using testing::Invoke;
using testing::IsEmpty;
using testing::Ne;
using testing::Pointee;
const char kAccessToken[] = "access_token";
const char kRequestUrl[] = "https://test.com/test";
const char kRequestUrlWithAlternateOutputProto[] =
"https://test.com/test?alt=proto";
const char kResponseBody[] = "response_body";
MATCHER(HasValidAccessToken, "") {
const network::TestURLLoaderFactory::PendingRequest& pending_request = arg;
std::string access_token_header;
pending_request.request.headers.GetHeader("Authorization",
&access_token_header);
return access_token_header == base::StringPrintf("Bearer %s", kAccessToken);
}
class FakeTrustedVaultAccessTokenFetcher
: public TrustedVaultAccessTokenFetcher {
public:
explicit FakeTrustedVaultAccessTokenFetcher(
const base::Optional<std::string>& access_token)
: access_token_(access_token) {}
~FakeTrustedVaultAccessTokenFetcher() override = default;
void FetchAccessToken(const CoreAccountId& account_id,
TokenCallback callback) override {
base::Optional<signin::AccessTokenInfo> access_token_info;
if (access_token_) {
access_token_info = signin::AccessTokenInfo(
*access_token_, base::Time::Now() + base::TimeDelta::FromHours(1),
/*id_token=*/std::string());
}
std::move(callback).Run(access_token_info);
}
private:
const base::Optional<std::string> access_token_;
};
class VaultServiceApiCallFlowTest : public testing::Test {
public:
VaultServiceApiCallFlowTest()
: shared_url_loader_factory_(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory_)) {}
std::unique_ptr<VaultServiceApiCallFlow> StartNewFlowWithAccessToken(
const base::Optional<std::string>& access_token,
VaultServiceApiCallFlow::HttpMethod http_method,
const base::Optional<std::string>& request_body,
VaultServiceApiCallFlow::CompletionCallback completion_callback) {
const CoreAccountId account_id = CoreAccountId::FromEmail("user@gmail.com");
FakeTrustedVaultAccessTokenFetcher access_token_fetcher(access_token);
auto flow = std::make_unique<VaultServiceApiCallFlow>(
http_method, GURL(kRequestUrl), PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS,
request_body);
flow->FetchAccessTokenAndStartFlow(account_id, shared_url_loader_factory_,
&access_token_fetcher,
std::move(completion_callback));
return flow;
}
bool RespondToHttpRequest(
net::Error error,
base::Optional<net::HttpStatusCode> response_http_code,
const std::string& response_body) {
network::mojom::URLResponseHeadPtr response_head;
if (response_http_code.has_value()) {
response_head = network::CreateURLResponseHead(*response_http_code);
} else {
response_head = network::mojom::URLResponseHead::New();
}
return test_url_loader_factory_.SimulateResponseForPendingRequest(
GURL(kRequestUrlWithAlternateOutputProto),
network::URLLoaderCompletionStatus(error), std::move(response_head),
response_body);
}
network::TestURLLoaderFactory::PendingRequest* GetPendingRequest() {
return test_url_loader_factory_.GetPendingRequest(/*index=*/0);
}
private:
base::test::TaskEnvironment task_environment_;
network::TestURLLoaderFactory test_url_loader_factory_;
scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_;
};
} // namespace
TEST_F(VaultServiceApiCallFlowTest, ShouldSendGetRequestAndHandleSuccess) {
base::MockCallback<VaultServiceApiCallFlow::CompletionCallback>
completion_callback;
std::unique_ptr<VaultServiceApiCallFlow> flow = StartNewFlowWithAccessToken(
kAccessToken, VaultServiceApiCallFlow::HttpMethod::kGet,
/*request_body=*/base::nullopt, completion_callback.Get());
network::TestURLLoaderFactory::PendingRequest* pending_request =
GetPendingRequest();
EXPECT_THAT(pending_request, Pointee(HasValidAccessToken()));
const network::ResourceRequest& resource_request = pending_request->request;
EXPECT_THAT(resource_request.method, Eq("GET"));
EXPECT_THAT(resource_request.url,
Eq(GURL(kRequestUrlWithAlternateOutputProto)));
EXPECT_THAT(network::GetUploadData(resource_request), IsEmpty());
// |completion_callback| should be called after receiving response.
EXPECT_CALL(completion_callback, Run(/*success=*/true, Eq(kResponseBody)));
EXPECT_TRUE(RespondToHttpRequest(net::OK, net::HTTP_OK, kResponseBody));
}
TEST_F(VaultServiceApiCallFlowTest,
ShouldSendPostRequestWithoutPayloadAndHandleSuccess) {
base::MockCallback<VaultServiceApiCallFlow::CompletionCallback>
completion_callback;
std::unique_ptr<VaultServiceApiCallFlow> flow = StartNewFlowWithAccessToken(
kAccessToken, VaultServiceApiCallFlow::HttpMethod::kPost,
/*request_body=*/base::nullopt, completion_callback.Get());
network::TestURLLoaderFactory::PendingRequest* pending_request =
GetPendingRequest();
EXPECT_THAT(pending_request, Pointee(HasValidAccessToken()));
const network::ResourceRequest& resource_request = pending_request->request;
EXPECT_THAT(resource_request.method, Eq("POST"));
EXPECT_THAT(resource_request.url,
Eq(GURL(kRequestUrlWithAlternateOutputProto)));
EXPECT_THAT(network::GetUploadData(resource_request), IsEmpty());
// |completion_callback| should be called after receiving response.
EXPECT_CALL(completion_callback, Run(/*success=*/true, Eq(kResponseBody)));
EXPECT_TRUE(RespondToHttpRequest(net::OK, net::HTTP_OK, kResponseBody));
}
TEST_F(VaultServiceApiCallFlowTest,
ShouldSendPostRequestWithPayloadAndHandleSuccess) {
base::MockCallback<VaultServiceApiCallFlow::CompletionCallback>
completion_callback;
const std::string kRequestBody = "Request body";
std::unique_ptr<VaultServiceApiCallFlow> flow = StartNewFlowWithAccessToken(
kAccessToken, VaultServiceApiCallFlow::HttpMethod::kPost, kRequestBody,
completion_callback.Get());
network::TestURLLoaderFactory::PendingRequest* pending_request =
GetPendingRequest();
EXPECT_THAT(pending_request, Pointee(HasValidAccessToken()));
const network::ResourceRequest& resource_request = pending_request->request;
EXPECT_THAT(resource_request.method, Eq("POST"));
EXPECT_THAT(resource_request.url,
Eq(GURL(kRequestUrlWithAlternateOutputProto)));
EXPECT_THAT(network::GetUploadData(resource_request), Eq(kRequestBody));
// |completion_callback| should be called after receiving response.
EXPECT_CALL(completion_callback, Run(/*success=*/true, Eq(kResponseBody)));
EXPECT_TRUE(RespondToHttpRequest(net::OK, net::HTTP_OK, kResponseBody));
}
TEST_F(VaultServiceApiCallFlowTest, ShouldHandleNetworkFailures) {
base::MockCallback<VaultServiceApiCallFlow::CompletionCallback>
completion_callback;
std::unique_ptr<VaultServiceApiCallFlow> flow = StartNewFlowWithAccessToken(
kAccessToken, VaultServiceApiCallFlow::HttpMethod::kGet,
/*request_body=*/base::nullopt, completion_callback.Get());
// |completion_callback| should be called after receiving response.
EXPECT_CALL(completion_callback, Run(/*success=*/false, _));
EXPECT_TRUE(RespondToHttpRequest(net::ERR_FAILED, base::nullopt,
/*response_body=*/std::string()));
}
TEST_F(VaultServiceApiCallFlowTest, ShouldHandleHttpErrors) {
base::MockCallback<VaultServiceApiCallFlow::CompletionCallback>
completion_callback;
std::unique_ptr<VaultServiceApiCallFlow> flow = StartNewFlowWithAccessToken(
kAccessToken, VaultServiceApiCallFlow::HttpMethod::kGet,
/*request_body=*/base::nullopt, completion_callback.Get());
// |completion_callback| should be called after receiving response.
EXPECT_CALL(completion_callback, Run(/*success=*/false, _));
EXPECT_TRUE(RespondToHttpRequest(net::OK, net::HTTP_INTERNAL_SERVER_ERROR,
/*response_body=*/""));
}
TEST_F(VaultServiceApiCallFlowTest, ShouldHandleAccessTokenFetchingFailures) {
base::MockCallback<VaultServiceApiCallFlow::CompletionCallback>
completion_callback;
// Access token fetching failure propagated immediately in this test, so
// |completion_callback| should be called immediately as well.
EXPECT_CALL(completion_callback, Run(/*success=*/false, _));
std::unique_ptr<VaultServiceApiCallFlow> flow = StartNewFlowWithAccessToken(
/*access_token=*/base::nullopt, VaultServiceApiCallFlow::HttpMethod::kGet,
/*request_body=*/base::nullopt, completion_callback.Get());
}
} // namespace syncer
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment