xref: /aosp_15_r20/external/cronet/net/reporting/reporting_cache.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef NET_REPORTING_REPORTING_CACHE_H_
6 #define NET_REPORTING_REPORTING_CACHE_H_
7 
8 #include <memory>
9 #include <optional>
10 #include <set>
11 #include <string>
12 #include <vector>
13 
14 #include "base/containers/flat_map.h"
15 #include "base/containers/flat_set.h"
16 #include "base/functional/callback.h"
17 #include "base/memory/raw_ptr.h"
18 #include "base/time/time.h"
19 #include "base/unguessable_token.h"
20 #include "base/values.h"
21 #include "net/base/net_export.h"
22 #include "net/reporting/reporting_endpoint.h"
23 #include "net/reporting/reporting_header_parser.h"
24 #include "net/reporting/reporting_report.h"
25 #include "url/gurl.h"
26 #include "url/origin.h"
27 
28 namespace net {
29 
30 class ReportingContext;
31 class IsolationInfo;
32 class NetworkAnonymizationKey;
33 
34 // The cache holds undelivered reports and clients (per-origin endpoint
35 // configurations) in memory. (It is not responsible for persisting them.)
36 //
37 // Each Reporting "endpoint" represents a report collector at some specified
38 // URL. Endpoints are organized into named "endpoint groups", each of which
39 // additionally specifies some properties such as expiration time.
40 // A "client" represents the entire endpoint configuration set by an origin via
41 // a Report-To header, which consists of multiple endpoint groups, each of which
42 // consists of multiple endpoints. An endpoint group is keyed by its name.  An
43 // endpoint is unkeyed except by the client and group structure tree above it.
44 //
45 // The cache implementation corresponds roughly to the "Reporting cache"
46 // described in the spec, except that endpoints and clients are stored in a more
47 // structurally-convenient way, and endpoint failures/retry-after are tracked in
48 // ReportingEndpointManager.
49 //
50 // The cache implementation has the notion of "pending" reports. These are
51 // reports that are part of an active delivery attempt, so they won't be
52 // actually deallocated. Any attempt to remove a pending report will mark it
53 // "doomed", which will cause it to be deallocated once it is no longer pending.
54 class NET_EXPORT ReportingCache {
55  public:
56   class PersistentReportingStore;
57 
58   static std::unique_ptr<ReportingCache> Create(ReportingContext* context);
59 
60   virtual ~ReportingCache();
61 
62   // Adds a report to the cache.
63   //
64   // |reporting_source| and |network_anonymization_key| will be used when the
65   // report is delivered, to determine which endpoints are eligible to receive
66   // this report, and which other reports this report can be batched with.
67   //
68   // All other parameters correspond to the desired values for the relevant
69   // fields in ReportingReport.
70   virtual void AddReport(
71       const std::optional<base::UnguessableToken>& reporting_source,
72       const NetworkAnonymizationKey& network_anonymization_key,
73       const GURL& url,
74       const std::string& user_agent,
75       const std::string& group_name,
76       const std::string& type,
77       base::Value::Dict body,
78       int depth,
79       base::TimeTicks queued,
80       int attempts) = 0;
81 
82   // Gets all reports in the cache. The returned pointers are valid as long as
83   // either no calls to |RemoveReports| have happened or the reports' |pending|
84   // flag has been set to true using |SetReportsPending|. Does not return
85   // doomed reports (pending reports for which removal has been requested).
86   //
87   // (Clears any existing data in |*reports_out|.)
88   virtual void GetReports(
89       std::vector<raw_ptr<const ReportingReport, VectorExperimental>>*
90           reports_out) const = 0;
91 
92   // Gets all reports in the cache, including pending and doomed reports, as a
93   // base::Value.
94   virtual base::Value GetReportsAsValue() const = 0;
95 
96   // Gets all reports in the cache that aren't pending or doomed (i.e. that are
97   // eligible for delivery), and marks returned reports as pending in
98   // preparation for a delivery attempt. The returned pointers are valid as long
99   // as the reports are still pending.
100   virtual std::vector<raw_ptr<const ReportingReport, VectorExperimental>>
101   GetReportsToDeliver() = 0;
102 
103   // Gets all reports in the cache which are eligible for delivery, which were
104   // queued for a single `reporting_source`, and marks returned reports as
105   // pending in preparation for a delivery attempt. The returned pointers are
106   // valid as long as the reports are still pending. This method is used when a
107   // reporting source is being destroyed, to trigger delivery of any remaining
108   // outstanding reports.
109   virtual std::vector<raw_ptr<const ReportingReport, VectorExperimental>>
110   GetReportsToDeliverForSource(
111       const base::UnguessableToken& reporting_source) = 0;
112 
113   // Unmarks a set of reports as pending. |reports| must be previously marked as
114   // pending.
115   virtual void ClearReportsPending(
116       const std::vector<raw_ptr<const ReportingReport, VectorExperimental>>&
117           reports) = 0;
118 
119   // Increments |attempts| on a set of reports.
120   virtual void IncrementReportsAttempts(
121       const std::vector<raw_ptr<const ReportingReport, VectorExperimental>>&
122           reports) = 0;
123 
124   // Records that we attempted (and possibly succeeded at) delivering
125   // |reports_delivered| reports to the specified endpoint.
126   virtual void IncrementEndpointDeliveries(
127       const ReportingEndpointGroupKey& group_key,
128       const GURL& url,
129       int reports_delivered,
130       bool successful) = 0;
131 
132   // Marks a `reporting_source` as expired, when the source (document or
133   // worker) has beed destroyed. The endpoint configuration for the source will
134   // be removed by the garbage collector once all outstanding reports have been
135   // delivered or expired.
136   virtual void SetExpiredSource(
137       const base::UnguessableToken& reporting_source) = 0;
138 
139   // Gets the current set of expired reporting sources.
140   virtual const base::flat_set<base::UnguessableToken>& GetExpiredSources()
141       const = 0;
142 
143   // Removes a set of reports. Any reports that are pending will not be removed
144   // immediately, but rather marked doomed and removed once they are no longer
145   // pending.
146   virtual void RemoveReports(
147       const std::vector<raw_ptr<const ReportingReport, VectorExperimental>>&
148           reports) = 0;
149   virtual void RemoveReports(
150       const std::vector<raw_ptr<const ReportingReport, VectorExperimental>>&
151           reports,
152       bool delivery_success) = 0;
153 
154   // Removes all reports. Like |RemoveReports()|, pending reports are doomed
155   // until no longer pending.
156   virtual void RemoveAllReports() = 0;
157 
158   // Gets the count of reports in the cache, *including* doomed reports.
159   //
160   // Needed to ensure that doomed reports are eventually deleted, since no
161   // method provides a view of *every* report in the cache, just non-doomed
162   // ones.
163   virtual size_t GetFullReportCountForTesting() const = 0;
164 
165   // Gets the count of reports in the cache with a specific `status`.
166   virtual size_t GetReportCountWithStatusForTesting(
167       ReportingReport::Status status) const = 0;
168 
169   virtual bool IsReportPendingForTesting(
170       const ReportingReport* report) const = 0;
171 
172   virtual bool IsReportDoomedForTesting(
173       const ReportingReport* report) const = 0;
174 
175   // Adds a new client to the cache for |origin|, or updates the existing one
176   // to match the new header. All values are assumed to be valid as they have
177   // passed through the ReportingHeaderParser.
178   virtual void OnParsedHeader(
179       const NetworkAnonymizationKey& network_anonymization_key,
180       const url::Origin& origin,
181       std::vector<ReportingEndpointGroup> parsed_header) = 0;
182 
183   // Adds named endpoints for |reporting_source| to the cache, based on the
184   // received Reporting-Endpoints header.
185   // |reporting_source| is the token identifying the document or worker with
186   // which this header was received, and may not be empty.
187   // |isolation_info| is the appropriate network isolation info struct for that
188   // source, and is used for determining credentials to send with reports.
189   virtual void OnParsedReportingEndpointsHeader(
190       const base::UnguessableToken& reporting_source,
191       const IsolationInfo& isolation_info,
192       std::vector<ReportingEndpoint> parsed_header) = 0;
193 
194   // Gets all the origins of clients in the cache.
195   virtual std::set<url::Origin> GetAllOrigins() const = 0;
196 
197   // Remove client for the given (NAK, origin) pair, if it exists in the cache.
198   // All endpoint groups and endpoints for that client are also removed.
199   virtual void RemoveClient(
200       const NetworkAnonymizationKey& network_anonymization_key,
201       const url::Origin& origin) = 0;
202 
203   // Remove all clients for the given |origin|, if any exists in the cache.
204   // All endpoint groups and endpoints for |origin| are also removed.
205   virtual void RemoveClientsForOrigin(const url::Origin& origin) = 0;
206 
207   // Remove all clients, groups, and endpoints from the cache.
208   virtual void RemoveAllClients() = 0;
209 
210   // Remove the endpoint group matching |group_key|, and remove
211   // all endpoints for that group. May cause the client it was associated with
212   // to be deleted if it becomes empty.
213   virtual void RemoveEndpointGroup(
214       const ReportingEndpointGroupKey& group_key) = 0;
215 
216   // Remove all endpoints for with |url|, regardless of origin or group. Used
217   // when a delivery returns 410 Gone. May cause deletion of groups/clients if
218   // they become empty.
219   virtual void RemoveEndpointsForUrl(const GURL& url) = 0;
220 
221   // Remove `reporting_source` from the cache, including any configured
222   // endpoints. There should be no non-doomed reports in the cache for
223   // `reporting_source` when this is called.
224   virtual void RemoveSourceAndEndpoints(
225       const base::UnguessableToken& reporting_source) = 0;
226 
227   // Insert endpoints and endpoint groups that have been loaded from the store.
228   //
229   // You must only call this method if context.store() was non-null when you
230   // constructed the cache and persist_clients_across_restarts in your
231   // ReportingPolicy is true.
232   virtual void AddClientsLoadedFromStore(
233       std::vector<ReportingEndpoint> loaded_endpoints,
234       std::vector<CachedReportingEndpointGroup> loaded_endpoint_groups) = 0;
235 
236   // Gets endpoints that apply to a delivery for |origin| and |group|.
237   //
238   // First checks for |group| in a client exactly matching |origin|.
239   // If none exists, then checks for |group| in clients for superdomains
240   // of |origin| which have include_subdomains enabled, returning only the
241   // endpoints for the most specific applicable parent origin of |origin|. If
242   // there are multiple origins with that group within the most specific
243   // applicable superdomain, gets endpoints for that group from only one of
244   // them. The group must not be expired.
245   //
246   // For example, given the origin https://foo.bar.baz.com/, the cache
247   // would prioritize returning each potential match below over the ones below
248   // it, for groups with name |group| with include_subdomains enabled:
249   // 1. https://foo.bar.baz.com/ (exact origin match)
250   // 2. https://foo.bar.baz.com:444/ (technically, a superdomain)
251   // 3. https://bar.baz.com/, https://bar.baz.com:444/, etc. (superdomain)
252   // 4. https://baz.com/, https://baz.com:444/, etc. (superdomain)
253   // If both https://bar.baz.com/ and https://bar.baz.com:444/ had a group with
254   // name |group| with include_subdomains enabled, this method would return
255   // endpoints from that group from the earliest-inserted origin.
256   virtual std::vector<ReportingEndpoint> GetCandidateEndpointsForDelivery(
257       const ReportingEndpointGroupKey& group_key) = 0;
258 
259   // Gets the status of all clients in the cache, including expired ones, as a
260   // base::Value.
261   virtual base::Value GetClientsAsValue() const = 0;
262 
263   // Gets the total number of endpoints in the cache across all origins.
264   virtual size_t GetEndpointCount() const = 0;
265 
266   // Flush the contents of the cache to disk, if applicable.
267   virtual void Flush() = 0;
268 
269   // Returns all V1 endpoints keyed by origin.
270   virtual base::flat_map<url::Origin, std::vector<ReportingEndpoint>>
271   GetV1ReportingEndpointsByOrigin() const = 0;
272 
273   // Returns the endpoint named |endpoint_name| for the reporting source, if it
274   // was configured with the Reporting-Endpoints header, otherwise returns an
275   // invalid ReportingEndpoint.
276   // |reporting_source| must not be empty.
277   virtual ReportingEndpoint GetV1EndpointForTesting(
278       const base::UnguessableToken& reporting_source,
279       const std::string& endpoint_name) const = 0;
280 
281   // Finds an endpoint for the given |group_key| and |url|, otherwise returns an
282   // invalid ReportingEndpoint.
283   virtual ReportingEndpoint GetEndpointForTesting(
284       const ReportingEndpointGroupKey& group_key,
285       const GURL& url) const = 0;
286 
287   // Returns whether an endpoint group with exactly the given properties exists
288   // in the cache. If |expires| is base::Time(), it will not be checked.
289   virtual bool EndpointGroupExistsForTesting(
290       const ReportingEndpointGroupKey& group_key,
291       OriginSubdomains include_subdomains,
292       base::Time expires) const = 0;
293 
294   // Returns whether a client for the given (NAK, Origin) exists.
295   virtual bool ClientExistsForTesting(
296       const NetworkAnonymizationKey& network_anonymization_key,
297       const url::Origin& origin) const = 0;
298 
299   // Returns number of endpoint groups.
300   virtual size_t GetEndpointGroupCountForTesting() const = 0;
301 
302   // Returns number of endpoint groups.
303   virtual size_t GetClientCountForTesting() const = 0;
304 
305   // Returns number of reporting source tokens associated with endpoints.
306   virtual size_t GetReportingSourceCountForTesting() const = 0;
307 
308   // Sets an endpoint with the given properties in a group with the given
309   // properties, bypassing header parsing. Note that the endpoint is not
310   // guaranteed to exist in the cache after calling this function, if endpoint
311   // eviction is triggered. Unlike the AddOrUpdate*() methods used in header
312   // parsing, this method inserts or updates a single endpoint while leaving the
313   // existing configuration for that origin intact.
314   virtual void SetEndpointForTesting(const ReportingEndpointGroupKey& group_key,
315                                      const GURL& url,
316                                      OriginSubdomains include_subdomains,
317                                      base::Time expires,
318                                      int priority,
319                                      int weight) = 0;
320 
321   // Sets a V1 named endpoint with the given key for `reporting_source`,
322   // bypassing header parsing. This method inserts a single endpoint while
323   // leaving the existing configuration for that source intact. If any
324   // endpoints already exist for this source, then `isolation_info` must
325   // match the value that was previously associated with it.
326   virtual void SetV1EndpointForTesting(
327       const ReportingEndpointGroupKey& group_key,
328       const base::UnguessableToken& reporting_source,
329       const IsolationInfo& isolation_info,
330       const GURL& url) = 0;
331 
332   // Gets the isolation info associated with `reporting_source`, used when
333   // determining which credentials to send for a given report. If
334   // `reporting_source` is nullopt, as when a report is being delivered to a V0
335   // reporting endpoint group, this always will return an empty site.
336   virtual IsolationInfo GetIsolationInfoForEndpoint(
337       const ReportingEndpoint& endpoint) const = 0;
338 };
339 
340 // Persistent storage for Reporting reports and clients.
341 class NET_EXPORT ReportingCache::PersistentReportingStore {
342  public:
343   using ReportingClientsLoadedCallback =
344       base::OnceCallback<void(std::vector<ReportingEndpoint>,
345                               std::vector<CachedReportingEndpointGroup>)>;
346 
347   PersistentReportingStore() = default;
348 
349   PersistentReportingStore(const PersistentReportingStore&) = delete;
350   PersistentReportingStore& operator=(const PersistentReportingStore&) = delete;
351 
352   virtual ~PersistentReportingStore() = default;
353 
354   // Initializes the store and retrieves stored endpoints and endpoint groups.
355   // Called only once at startup.
356   virtual void LoadReportingClients(
357       ReportingClientsLoadedCallback loaded_callback) = 0;
358 
359   // Adds an endpoint to the store.
360   virtual void AddReportingEndpoint(const ReportingEndpoint& endpoint) = 0;
361   // Adds an endpoint group to the store.
362   virtual void AddReportingEndpointGroup(
363       const CachedReportingEndpointGroup& group) = 0;
364 
365   // Updates the access time of an endpoint group in the store.
366   virtual void UpdateReportingEndpointGroupAccessTime(
367       const CachedReportingEndpointGroup& group) = 0;
368 
369   // Updates the details of an endpoint in the store.
370   virtual void UpdateReportingEndpointDetails(
371       const ReportingEndpoint& endpoint) = 0;
372   // Updates the details of an endpoint group in the store.
373   virtual void UpdateReportingEndpointGroupDetails(
374       const CachedReportingEndpointGroup& group) = 0;
375 
376   // Deletes an endpoint from the store.
377   virtual void DeleteReportingEndpoint(const ReportingEndpoint& endpoint) = 0;
378   // Deletes an endpoint group from the store.
379   virtual void DeleteReportingEndpointGroup(
380       const CachedReportingEndpointGroup& group) = 0;
381 
382   // TODO(chlily): methods to load, add, and delete reports will be added.
383 
384   // Flushes the store.
385   virtual void Flush() = 0;
386 };
387 
388 }  // namespace net
389 
390 #endif  // NET_REPORTING_REPORTING_CACHE_H_
391