File: request_matcher.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (294 lines) | stat: -rw-r--r-- 10,776 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/updater/test/request_matcher.h"

#include <array>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/containers/contains.h"
#include "base/containers/flat_map.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/updater/branded_constants.h"
#include "chrome/updater/test/http_request.h"
#include "chrome/updater/update_service.h"
#include "chrome/updater/updater_scope.h"
#include "chrome/updater/util/util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/re2/src/re2/re2.h"
#include "url/gurl.h"

namespace updater::test::request {

FormExpectations::FormExpectations(const std::string& name,
                                   std::vector<std::string> regexes)
    : name(name), regex_sequence(std::move(regexes)) {}

FormExpectations::FormExpectations(const FormExpectations&) = default;
FormExpectations& FormExpectations::operator=(const FormExpectations& other) =
    default;
FormExpectations::~FormExpectations() = default;

Matcher GetPathMatcher(const std::string& expected_path_regex) {
  return base::BindLambdaForTesting(
      [expected_path_regex](const HttpRequest& request) {
        if (!re2::RE2::FullMatch(request.relative_url, expected_path_regex)) {
          ADD_FAILURE() << "Request path [" << request.relative_url
                        << "], did not match expected path regex ["
                        << expected_path_regex << "].";
          return false;
        }
        return true;
      });
}

Matcher GetHeaderMatcher(
    const base::flat_map<std::string, std::string> expected_headers) {
  return base::BindLambdaForTesting([expected_headers](
                                        const HttpRequest& request) {
    for (const auto& [header_name, expected_header_regex] : expected_headers) {
      re2::RE2::Options opt;
      opt.set_case_sensitive(false);
      HttpRequest::HeaderMap::const_iterator it =
          request.headers.find(header_name);
      if (it == request.headers.end()) {
        ADD_FAILURE() << "Request header '" << header_name
                      << "' not found, expected regex "
                      << expected_header_regex;
        return false;
      } else if (!re2::RE2::FullMatch(it->second,
                                      re2::RE2(expected_header_regex, opt))) {
        ADD_FAILURE() << "Request header [" << it->first << " = '" << it->second
                      << "], did not match expected regex ["
                      << expected_header_regex << "]";
        return false;
      }
    }
    return true;
  });
}

Matcher GetUpdaterUserAgentMatcher(const base::Version& updater_version) {
  return GetHeaderMatcher(
      {{"User-Agent", GetUpdaterUserAgent(updater_version)}});
}

Matcher GetTargetURLMatcher(GURL target_url) {
  return base::BindLambdaForTesting([target_url](const HttpRequest& request) {
    const std::string post_target = base::StrCat({"POST ", target_url.spec()});
    if (!base::StartsWith(request.all_headers, post_target,
                          base::CompareCase::INSENSITIVE_ASCII)) {
      ADD_FAILURE() << "Request all_headers [" << request.all_headers
                    << "] does not starts with the expected [" << post_target
                    << "]";
      return false;
    }
    return GetHeaderMatcher({{"Host", target_url.host()}}).Run(request);
  });
}

Matcher GetContentMatcher(
    const std::vector<std::string>& expected_content_regex_sequence) {
  return base::BindLambdaForTesting(
      [expected_content_regex_sequence](const HttpRequest& request) {
        std::string_view input(request.decoded_content);
        for (const std::string& regex : expected_content_regex_sequence) {
          re2::RE2::Options opt;
          opt.set_case_sensitive(false);
          if (re2::RE2::FindAndConsume(&input, re2::RE2(regex, opt))) {
            VLOG(3) << "Found regex: [" << regex << "]";
          } else {
            ADD_FAILURE() << "Request content match failed. Expected regex: ["
                          << regex << "] not found in content: ["
                          << GetPrintableContent(request) << "]";
            return false;
          }
        }
        return true;
      });
}

Matcher GetScopeMatcher(UpdaterScope scope) {
  return base::BindLambdaForTesting([scope](const HttpRequest& request) {
    const bool is_match = [&scope, &request] {
      const std::optional<base::Value::Dict> doc =
          base::JSONReader::ReadDict(request.decoded_content);
      if (!doc) {
        return false;
      }
      const base::Value::Dict* object_request = doc->FindDict("request");
      if (!object_request) {
        return false;
      }
      std::optional<bool> ismachine = object_request->FindBool("ismachine");
      if (!ismachine.has_value()) {
        return false;
      }
      switch (scope) {
        case UpdaterScope::kSystem:
          return *ismachine;
        case UpdaterScope::kUser:
          return !*ismachine;
      }
    }();
    if (!is_match) {
      ADD_FAILURE() << R"(Request does not match "ismachine": )"
                    << GetPrintableContent(request);
    }
    return is_match;
  });
}

Matcher GetAppPriorityMatcher(const std::string& app_id,
                              UpdateService::Priority priority) {
  return base::BindLambdaForTesting([app_id,
                                     priority](const HttpRequest& request) {
    const bool is_match = [&app_id, priority, &request] {
      const std::optional<base::Value::Dict> doc =
          base::JSONReader::ReadDict(request.decoded_content);
      if (!doc) {
        return false;
      }
      const base::Value::List* app_list =
          doc->FindListByDottedPath("request.apps");
      if (!app_list) {
        app_list = doc->FindListByDottedPath("request.app");  // V3 fallback.
        if (!app_list) {
          return false;
        }
      }
      for (const base::Value& app : *app_list) {
        if (const auto* dict = app.GetIfDict()) {
          if (const auto* appid = dict->FindString("appid"); *appid == app_id) {
            if (const auto* install_source =
                    dict->FindString("installsource")) {
              static constexpr auto kInstallSources =
                  std::array{"ondemand", "taggedmi", "policy"};
              return base::Contains(kInstallSources, *install_source) ==
                     (priority == UpdateService::Priority::kForeground);
            }
          }
        }
      }
      return priority != UpdateService::Priority::kForeground;
    }();
    if (!is_match) {
      ADD_FAILURE() << R"(Request does not match "appid", "priority: )"
                    << GetPrintableContent(request);
    }
    return is_match;
  });
}

Matcher GetUpdaterEnableUpdatesMatcher() {
  return base::BindLambdaForTesting([](const HttpRequest& request) {
    const bool update_disabled = [&request] {
      const std::optional<base::Value::Dict> doc =
          base::JSONReader::ReadDict(request.decoded_content);
      if (!doc) {
        return false;
      }
      const base::Value::List* app_list =
          doc->FindListByDottedPath("request.apps");
      if (!app_list) {
        return false;
      }
      for (const base::Value& app : *app_list) {
        if (const auto* dict = app.GetIfDict()) {
          if (const auto* appid = dict->FindString("appid");
              *appid == kUpdaterAppId) {
            if (const auto* update_check = dict->FindDict("updatecheck")) {
              return update_check->FindBool("updatedisabled").value_or(false);
            }
          }
        }
      }
      return false;
    }();
    if (update_disabled) {
      ADD_FAILURE() << R"(Update is wrongfully disabled for updater itself: )"
                    << GetPrintableContent(request);
    }
    return !update_disabled;
  });
}

Matcher GetMultipartContentMatcher(
    const std::vector<FormExpectations>& form_expections) {
  return base::BindLambdaForTesting([form_expections](
                                        const HttpRequest& request) {
    static constexpr char kMultifpartBoundaryPrefix[] =
        "multipart/form-data; boundary=";
    if (!request.headers.contains("Content-Type")) {
      ADD_FAILURE() << "Content-Type header not found, which is expected "
                    << "for multipart content.";
      return false;
    }

    const std::string content_type = request.headers.at("Content-Type");
    if (!base::StartsWith(content_type, kMultifpartBoundaryPrefix)) {
      ADD_FAILURE() << "Content-Type value is not the expected "
                    << "[multipart/form-data].";
      return false;
    }

    const std::string form_data_boundary = content_type.substr(
        std::string_view(kMultifpartBoundaryPrefix).length());

    re2::RE2::Options opt;
    opt.set_case_sensitive(false);
    std::string_view input(request.decoded_content);

    for (const FormExpectations& form_expectation : form_expections) {
      if (re2::RE2::FindAndConsume(&input, form_data_boundary)) {
        VLOG(3) << "Advancing to next form in the multipart content.";
      } else {
        ADD_FAILURE() << "No boundary separator found between multipart forms.";
        return false;
      }

      const std::string& form_name = form_expectation.name;
      if (re2::RE2::FindAndConsume(
              &input,
              base::StringPrintf(R"(Content-Disposition: form-data; name="%s")",
                                 form_name.c_str()))) {
        VLOG(3) << "Found form with name [" << form_name << "]";
      } else {
        ADD_FAILURE() << "Form [" << form_name << "] not found.";
        return false;
      }

      for (const std::string& regex : form_expectation.regex_sequence) {
        if (re2::RE2::FindAndConsume(&input, re2::RE2(regex, opt))) {
          VLOG(3) << "Found regex: [" << regex << "]";
        } else {
          ADD_FAILURE() << "Form [" << form_name << "] match failed. "
                        << "Expected regex: [" << regex << "] not found in "
                        << "content: [" << GetPrintableContent(request) << "]";
          return false;
        }
      }
    }

    if (!re2::RE2::FindAndConsume(&input, form_data_boundary)) {
      ADD_FAILURE() << "Multipart data should end with boundary separator.";
      return false;
    }

    return true;
  });
}

}  // namespace updater::test::request