
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
    <channel>
        <title><![CDATA[ The Cloudflare Blog ]]></title>
        <description><![CDATA[ Get the latest news on how products at Cloudflare are built, technologies used, and join the teams helping to build a better Internet. ]]></description>
        <link>https://blog.cloudflare.com</link>
        <atom:link href="https://blog.cloudflare.com/" rel="self" type="application/rss+xml"/>
        <language>en-us</language>
        <image>
            <url>https://blog.cloudflare.com/favicon.png</url>
            <title>The Cloudflare Blog</title>
            <link>https://blog.cloudflare.com</link>
        </image>
        <lastBuildDate>Fri, 03 Apr 2026 13:33:02 GMT</lastBuildDate>
        <item>
            <title><![CDATA[Protecting APIs from abuse using sequence learning and variable order Markov chains]]></title>
            <link>https://blog.cloudflare.com/protecting-apis-from-abuse-using-sequence-learning-and-variable-order-markov/</link>
            <pubDate>Thu, 12 Sep 2024 14:15:00 GMT</pubDate>
            <description><![CDATA[ At Cloudflare, we protect customer APIs from abuse. This is no easy task, as abusive traffic can take different forms, from giant DDoS attacks to low-and-slow credential stuffing campaigns. We now address this challenge in a new way: by looking outside typical volumetric measures and using statistical machine learning to find important API client request sequences. ]]></description>
            <content:encoded><![CDATA[ <p>Consider the case of a malicious actor attempting to inject, <a href="https://www.cloudflare.com/learning/ai/how-to-prevent-web-scraping/">scrape</a>, harvest, or <a href="https://www.cloudflare.com/learning/security/what-is-data-exfiltration/">exfiltrate</a> data via an API. Such malicious activities are often characterized by the particular order in which the actor initiates requests to API endpoints. Moreover, the malicious activity is often not readily detectable using volumetric techniques alone, because the actor may intentionally execute API requests slowly, in an attempt to thwart volumetric abuse protection. To reliably prevent such malicious activity, we therefore need to consider the sequential order of API requests. We use the term <b>sequential abuse</b> to refer to malicious API request behavior. Our fundamental goal thus involves distinguishing malicious from benign API request sequences.</p><p>In this blog post, you’ll learn about how we address the challenge of helping customers protect their APIs against sequential abuse. To this end, we’ll unmask the statistical machine learning (ML) techniques currently underpinning our <a href="https://developers.cloudflare.com/api-shield/security/sequence-analytics/"><u>Sequence Analytics</u></a> product. We’ll build on the high-level introduction to Sequence Analytics provided in a <a href="https://blog.cloudflare.com/api-sequence-analytics"><u>previous blog post</u></a>.</p>
    <div>
      <h3>API sessions</h3>
      <a href="#api-sessions">
        
      </a>
    </div>
    <p>Introduced in the previous blog post, let’s consider the idea of a time-ordered series of HTTP API requests initiated by a specific user. These occur as the user interacts with a service, such as while browsing a website or using a mobile app. We refer to the user’s time-ordered series of API requests as a <b>session</b>. Choosing a familiar example, the session for a customer interacting with a banking service might look like:</p><table><thead>
  <tr>
    <th>Time Order</th>
    <th>Method</th>
    <th>Path</th>
    <th>Description</th>
  </tr></thead>
<tbody>
  <tr>
    <td>1</td>
    <td>POST</td>
    <td>/api/v1/auth</td>
    <td>Authenticates a user</td>
  </tr>
  <tr>
    <td>2</td>
    <td>GET</td>
    <td>/api/v1/accounts/{account_id}</td>
    <td>Displays account balance, where account_id is an account belonging to the user</td>
  </tr>
  <tr>
    <td>3</td>
    <td>POST</td>
    <td>/api/v1/transferFunds</td>
    <td>Containing a request body detailing an account to transfer funds from, an account to transfer funds to, and an amount of money to transfer</td>
  </tr>
</tbody>
</table>
<br /><p>One of our aims is to enable our customers to <a href="https://www.cloudflare.com/learning/security/api/what-is-api-security/"><u>secure their APIs</u></a> by automatically suggesting rules applicable to our <a href="https://developers.cloudflare.com/api-shield/security/sequence-mitigation/"><u>Sequence Mitigation</u></a> product for enforcing desired sequential behavior. If we enforce the expected behavior, we can prevent unwanted sequential behavior. In our example, desired sequential behavior might entail that /api/v1/auth must always precede /api/v1/accounts/{account_id}.</p><p>One important challenge we had to address is that the <a href="https://blog.cloudflare.com/api-sequence-analytics"><u>number of possible sessions grows rapidly as the session length increases</u></a>. To see why, we can consider the alternative ways in which a user might interact with the example banking service: The user may, for example, execute multiple transfers, and/or check the balance of multiple accounts, in any order. Assuming that there are 3 possible <b>endpoints</b>, the following graph illustrates possible sessions when the user interacts with the banking service:</p>
          <figure>
          <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/5YqgBdzxmu1z2Rm5xiSR6h/ca920cfb0496e476c7af24b066581d2d/image2.png" />
          </figure><p>Because of this large number of possible sessions, suggesting mitigation rules requires that we address the challenge of summarizing sequential behavior from past session data as an intermediate step. We’ll refer to a series of consecutive endpoints in a session (for example /api/v1/accounts/{account_id} → /api/v1/transferFunds) in our example as a <b>sequence</b>. Specifically, a challenge we needed to address is that the sequential behavior relevant for creating rules isn’t necessarily apparent from volume alone: Consider for example that /api/transferFunds might nearly always be preceded by /api/v1/accounts/{account_id}, but also that the sequence /api/v1/accounts/{account_id} → /api/v1/transferFunds might occur relatively rarely, compared to the sequence /api/v1/auth → /api/v1/accounts/{account_id}. It is therefore conceivable that if we were to summarize based on volume alone, we might potentially deem the sequence /api/v1/accounts/{account_id} → /api/v1/transferFunds as unimportant, when in fact we ought to surface it as a potential rule. </p>
    <div>
      <h3>Learning important sequences from API sessions</h3>
      <a href="#learning-important-sequences-from-api-sessions">
        
      </a>
    </div>
    <p>A widely-applied modeling approach applicable to sequential data is the <a href="https://en.wikipedia.org/wiki/Markov_chain"><b><u>Markov chain</u></b></a>, in which the probability of each endpoint in our session data depends only on a fixed number of preceding endpoints. First, we’ll show how standard Markov chains can be applied to our session data, while pointing out some of their limitations. Second, we’ll show how we use a less well-known, but powerful, type of Markov chain to determine important sequences.</p><p>For illustrative purposes, let’s assume that there are 3 possible endpoints in our session data. We’ll represent these endpoints using the letters <i>a</i>, <i>b</i> and <i>c</i>:</p><ul><li><p><i>a</i>: /api/v1/auth</p></li><li><p><i>b</i>: /api/v1/accounts/{account_id}</p></li><li><p><i>c</i>: /api/v1/transferFunds</p></li></ul><p>In its simplest form, a Markov chain is nothing more than a table which tells us the probability of the next letter, given knowledge of the immediately preceding letter. If we were to model past session data using the simplest kind of Markov chain, we might end up with a table like this one:</p><table>
  <tr>
    <td>Known preceding endpoint in the session</td>
    <td>Estimated probability of next endpoint in the session</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
<tbody>
  <tr>
    <td>a</td>
    <td>0.10 (1555)</td>
    <td>0.89 (13718)</td>
    <td>0.01 (169)</td>
  </tr>
  <tr>
    <td>b</td>
    <td>0.03 (9618)</td>
    <td>0.63 (205084)</td>
    <td>0.35 (113382)</td>
  </tr>
  <tr>
    <td>c</td>
    <td>0.02 (3340)</td>
    <td>0.67 (109896)</td>
    <td>0.31 (51553)</td>
  </tr>
</tbody>
</table>
<small>Table 1</small>
<br /><p>Table 1 lists the parameters of the Markov chain, namely the estimated probabilities of observing <i>a</i>, <i>b</i> or <i>c</i> as the next endpoint in a session, given knowledge of the immediately preceding endpoint in the session. For example, the 3rd row cell with value 0.67 means that given knowledge of immediately preceding endpoint <i>c</i>, the estimated probability of observing <i>b</i> as the next endpoint in a session is 67%, regardless of whether <i>c </i>was preceded by any endpoints. Thus, each entry in the table corresponds to a sequence of two endpoints. The values in brackets are the number of times we saw each two-endpoint sequence in past session data and are used to compute the probabilities in the table. For example, the value 0.01 is the result of evaluating the fraction 169 / (1555+13718+169). This method of estimating probabilities is known as <a href="https://en.wikipedia.org/wiki/Maximum_likelihood_estimation"><u>maximum likelihood estimation</u></a>.</p><p>To determine important sequences, we rely on <a href="https://en.wikipedia.org/wiki/Credible_interval"><b><u>credible intervals</u></b></a> for estimating probabilities instead of maximum likelihood estimation. Instead of producing a single point estimate (as described above), credible intervals represent a plausible range of probabilities. This range reflects the amount of data available, i.e. the total number of sequence occurrences in each row. More data produces narrower credible intervals (reflecting a greater degree of certainty) and conversely less data produces wider credible intervals (reflecting a lesser degree of certainty). Based on the values in brackets in the table above, we thus might obtain the following credible intervals (entries in boldface will be explained further on):</p><table><thead>
  <tr>
    <td>Known preceding endpoint in the session</td>
    <td>Estimated probability of next endpoint in the session</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr></thead>
<tbody>
  <tr>
    <td>a</td>
    <td><b>0.09-0.11 (1555)</b></td>
    <td><b>0.88-0.89 (13718)</b></td>
    <td><b>0.01-0.01 (169)</b></td>
  </tr>
  <tr>
    <td>b</td>
    <td>0.03-0.03 (9618)</td>
    <td>0.62-0.63 (205084)</td>
    <td>0.34-0.35 (113382)</td>
  </tr>
  <tr>
    <td>c</td>
    <td>0.02-0.02 (3340)</td>
    <td>0.66-0.67 (109896)</td>
    <td>0.31-0.32 (51553)</td>
  </tr>
</tbody>
</table>
<small>Table 2</small>
<br /><p>For brevity, we won’t demonstrate here how to work out the credible intervals by hand (they involve evaluating the <a href="https://en.wikipedia.org/wiki/Quantile_function"><u>quantile function</u></a> of a <a href="https://en.wikipedia.org/wiki/Beta_distribution"><u>beta distribution</u></a>). Notwithstanding, the revised table indicates how more data causes credible intervals to shrink: note the first row with a total of 15442 occurrences in comparison to the second row with a total of 328084 occurrences.</p><p>To determine important sequences, we use slightly more complex Markov chains than those described above. As an intermediate step, let’s first consider the case where each table entry corresponds to a sequence of 3 endpoints (instead of 2 as above), exemplified by the following table:</p><table><thead>
  <tr>
    <td>Known preceding endpoints in the session</td>
    <td>Estimated probability of next endpoint in the session</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr></thead>
<tbody>
  <tr>
    <td>aa</td>
    <td><b>0.09-0.13 (173)</b></td>
    <td><b>0.86-0.90 (1367)</b></td>
    <td><b>0.00-0.02 (13)</b></td>
  </tr>
  <tr>
    <td>ba</td>
    <td><b>0.09-0.11 (940)</b></td>
    <td><b>0.88-0.90 (8552)</b></td>
    <td><b>0.01-0.01 (109)</b></td>
  </tr>
  <tr>
    <td>ca</td>
    <td><b>0.09-0.12 (357)</b></td>
    <td><b>0.87-0.90 (2945)</b></td>
    <td><b>0.01-0.02 (35)</b></td>
  </tr>
  <tr>
    <td>ab</td>
    <td>0.02-0.02 (272)</td>
    <td>0.56-0.58 (7823)</td>
    <td>0.40-0.42 (5604)</td>
  </tr>
  <tr>
    <td>bb</td>
    <td>0.03-0.03 (6067)</td>
    <td>0.60-0.60 (122796)</td>
    <td>0.37-0.37 (75801)</td>
  </tr>
  <tr>
    <td>cb</td>
    <td>0.03-0.03 (3279)</td>
    <td>0.68-0.68 (74449)</td>
    <td>0.29-0.29 (31960)</td>
  </tr>
  <tr>
    <td>ac</td>
    <td>0.01-0.09 (6)</td>
    <td>0.77-0.91 (144)</td>
    <td>0.06-0.19 (19)</td>
  </tr>
  <tr>
    <td>bc</td>
    <td>0.02-0.02 (2326)</td>
    <td>0.77-0.77 (87215)</td>
    <td>0.21-0.21 (23612)</td>
  </tr>
  <tr>
    <td>cc</td>
    <td>0.02-0.02 (1008)</td>
    <td>0.43-0.44 (22527)</td>
    <td>0.54-0.55 (27919)</td>
  </tr>
</tbody></table>
<small>Table 3</small>
<br /><p>Table 3 again lists the estimated probabilities of observing <i>a</i>, <i>b</i> or <i>c</i> as the next endpoint in a session, but given knowledge of 2 immediately preceding endpoints in the session (instead of 1 immediately preceding endpoint as before). That is, the 3rd row cell with interval 0.09-0.13 means that given knowledge of immediately preceding endpoints <i>ca</i>, the probability of observing <i>a</i> as the next endpoint has a credible interval spanning 9% and 13%, regardless of whether <i>ca </i>was preceded by any endpoints. In parlance, we say that the above table represents a Markov chain of <b>order</b> 2. This is because the entries in the table represent probabilities of observing the next endpoint, given knowledge of 2 immediately preceding endpoints as <b>context</b>.</p><p>As a special case, the Markov chain of order 0 simply represents the distribution over endpoints in a session. We can tabulate the probabilities as follows, in relation to a single row corresponding to an ‘empty context’:</p><table><thead>
  <tr>
    <td>Known preceding endpoints in the session</td>
    <td>Estimated probability of next endpoint in the session</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr></thead>
<tbody>
  <tr>
    <td></td>
    <td>0.03-0.03 (15466)</td>
    <td>0.64-0.65 (328732)</td>
    <td>0.32-0.33 (165117)</td>
  </tr>
</tbody>
</table>
<small>Table 4</small>
<br /><p>Note that the probabilities in Table 4 do not solely represent the case where there were no preceding endpoints in the session. Rather, the probabilities are for the occurrence of endpoints in the session, for the general case where we have no knowledge of the preceding endpoints and regardless of how many endpoints previously occurred.    </p><p>Returning to our task of identifying important sequences, one possible approach might be to simply use a Markov chain of some fixed order <i>N</i>. For example, if we were to apply a threshold of 0.85 to the lower bounds of credible intervals in Table 3, we’d retain 3 sequences in total. On the other hand, this approach comes with two noteworthy limitations:</p><ol><li><p>We need a way to select a suitable value for the model order <i>N</i>. </p></li><li><p>Since the model order remains fixed, identified sequences all have the same length <i>N</i>+1.</p></li></ol>
    <div>
      <h3>Variable order Markov chains</h3>
      <a href="#variable-order-markov-chains">
        
      </a>
    </div>
    <p><b>Variable order Markov chains</b> (VOMCs) are a more powerful extension of the described fixed-order Markov chains which address the preceding limitations. VOMCs make use of the fact that for some chosen value of the Markov chain of fixed order <i>N</i>, the probability table might include statistically redundant information: Let’s compare Tables 3 and 2 above and consider in Table 3 the rows in boldface corresponding to contexts <i>aa</i>, <i>ba</i>, <i>ca</i> (these 3 contexts all share <code><i>a</i></code> as their suffix). </p><p>For all the 3 possible next endpoints <i>a, b, c</i>, these rows specify credible intervals which overlap with their respective estimates in Table 2 corresponding to context <i>a</i> (also indicated in boldface). We can interpret these overlapping intervals as representing no discernible difference between probability estimates, given knowledge of <i>a</i> as the preceding endpoint. With no discernible effect of what preceded <i>a </i>on the probability of the next endpoint, we can consider these 3 rows in Table 3 redundant: We may ‘collapse’ them by replacing them with the row in Table 2 corresponding to context <i>a</i>. </p><p>The result of revising Table 3 as described looks as follows (with the new row indicated in boldface):</p><table><thead>
  <tr>
    <td>Known preceding endpoints in the session</td>
    <td>Estimated probability of next endpoint in the session</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr></thead>
<tbody>
  <tr>
    <td> a</td>
    <td><b>0.09-0.11 (1555)</b></td>
    <td><b>0.88-0.89 (13718)</b></td>
    <td><b>0.01-0.01 (169)</b></td>
  </tr>
  <tr>
    <td>ab</td>
    <td>0.02-0.02 (272)</td>
    <td>0.56-0.58 (7823)</td>
    <td>0.40-0.42 (5604)</td>
  </tr>
  <tr>
    <td>ac</td>
    <td>0.03-0.03 (6067)</td>
    <td>0.60-0.60 (122796)</td>
    <td>0.37-0.37 (75801)</td>
  </tr>
  <tr>
    <td>bb</td>
    <td>0.03-0.03 (3279)</td>
    <td>0.68-0.68 (74449)</td>
    <td>0.29-0.29 (31960)</td>
  </tr>
  <tr>
    <td>bc</td>
    <td>0.01-0.09 (6)</td>
    <td>0.77-0.91 (144)</td>
    <td>0.06-0.19 (19)</td>
  </tr>
  <tr>
    <td>cb</td>
    <td>0.02-0.02 (2326)</td>
    <td>0.77-0.77 (87215)</td>
    <td>0.21-0.21 (23612)</td>
  </tr>
  <tr>
    <td>cc</td>
    <td>0.02-0.02 (1008)</td>
    <td>0.43-0.44 (22527)</td>
    <td>0.54-0.55 (27919)</td>
  </tr>
</tbody></table>
<small>Table 5</small>
<br /><p>Table 5 represents a VOMC, because the context length varies: In the example, we have context lengths 1 and 2. It follows that entries in the table represent sequences of length varying between 2 and 3 endpoints, depending on context length. Generalizing the described approach of collapsing contexts leads to the following algorithm sketch for learning a VOMC in an offline setting:</p><p><code>(1) Define the table </code><code><i>T</i></code><code> containing the estimated probability of the next endpoint in a session, given alternatively </code><code><i>0, 1, 2, …, N_max</i></code><code> preceding endpoints in the session. That is, form a single table by concatenating the rows corresponding to Markov chains of fixed orders </code><code><i>0, 1, 2, …, N_max</i></code><code>.</code></p><p><code>(2) is_modified := true </code></p><p><code>(3) DO WHILE is_modified</code></p><p><code>   (4) </code><code><i>D</i></code><code> := all contexts in </code><code><i>T </i></code><code>which are not suffixes of at least 1 other      context in </code><code><i>T</i></code></p><p><code>   (5) is_modified = false</code></p><p><code>   (6) FOR </code><code><i>ctx</i></code><code> IN </code><code><i>C</i></code></p><p><code>        (7) IF length(</code><code><i>ctx</i></code><code>) &gt; 0</code></p><p><code>           (8) </code><code><i>parent_ctx</i></code><code> := the context obtained by deleting the leftmost endpoint in </code><code><i>ctx</i></code></p><p><code>           (9) IF is_collapsible(</code><code><i>ctx</i></code><code>, </code><code><i>parent_ctx</i></code><code>)</code></p><p><code>              (10) Modify </code><code><i>T</i></code><code> by discarding </code><code><i>ctx</i></code></p><p><code>              (11) is_modified = true</code></p><p>In the pseudo-code, length(<i>ctx</i>) is the length of context <i>ctx</i>. On line 9, is_collapsible() involves comparing credible intervals for the contexts <i>ctx</i> and <i>parent_ctx</i> in the manner described for generating Table 5: is_collapsible() evaluates to true, if and only if we observe that all credible intervals overlap, when comparing contexts <i>ctx</i> and <i>parent_ctx</i> separately for each of the possible next endpoints. The maximum sequence length is <i>N_max</i>+1<i>, </i>where <i>N_max </i>is some constant. On line 4, we say that context <i>q </i>is a <b>suffix</b> of another context <i>p</i> if we can form <i>p</i> by prepending zero or more endpoints to <i>q</i>. (According to this definition, the ‘empty context’ mentioned above for the order 0 model is a suffix of all contexts in <i>T</i>.) The above algorithm sketch is a variant of the ideas first introduced by Rissanen [<a href="https://ieeexplore.ieee.org/abstract/document/1056741/"><u>1</u></a>], Ron et al. [<a href="https://link.springer.com/article/10.1023/A:1026490906255"><u>2</u></a>].</p><p>Finally, we take the entries in the resulting table <i>T</i> as our important sequences. Thus, the result of applying VOMCs is a set of sequences that we deem important. For Sequence Analytics however, we believe that it is additionally useful to rank sequences. We do this by computing a ‘precedence score’ between 0.0 and 1.0, which is the number of occurrences of the sequence divided by the number of occurrences of the last endpoint in the sequence. Thus, precedence scores close to 1.0 indicate that a given endpoint is nearly always preceded by the remaining endpoints in the sequence. In this way, manual inspection of the highest-scoring sequences is a semi-automated heuristic for creating precedence rules in our Sequence Mitigation product.</p>
    <div>
      <h3>Learning sequences at scale</h3>
      <a href="#learning-sequences-at-scale">
        
      </a>
    </div>
    <p>The preceding represents a very high-level overview of the statistical ML techniques that we use in Sequence Analytics. In practice, we have devised an efficient algorithm which does not require an upfront training step, but rather updates the model continuously as the data arrive and generates a frequently-updating summary of important sequences. This approach allows us to overcome additional challenges around memory cost not touched on in this blog post. Most significantly, a straightforward implementation of the algorithm sketch above would still result in the number of table rows (contexts) exploding with increasing maximum sequence length. A further challenge we had to address is how to ensure that our system is able to deal with high-volume APIs, without adversely impacting CPU load. We use a horizontally scalable adaptive sampling strategy upfront, such that more aggressive sampling is applied to high-volume APIs. Our algorithm then consumes the sampled streams of API requests. After a customer onboards, sequences are assembled and learned over time, so that the current summary of important sequences represents a sliding window with a look-back interval of approximately 24 hours. Sequence Analytics further stores sequences in <a href="https://blog.cloudflare.com/tag/clickhouse/"><u>Clickhouse</u></a> and exposes them via a <a href="https://developers.cloudflare.com/analytics/graphql-api/"><u>GraphQL API</u></a> and via the <a href="https://dash.cloudflare.com/"><u>Cloudflare dashboard</u></a>. Customers who would like to enforce sequence rules can do so using <a href="https://developers.cloudflare.com/api-shield/security/sequence-mitigation/"><u>Sequence Mitigation</u></a>. Sequence Mitigation is what is responsible for ensuring that rules are shared and matched in distributed fashion on Cloudflare’s global network — another exciting topic for a future blog post!</p>
    <div>
      <h3>What’s next</h3>
      <a href="#whats-next">
        
      </a>
    </div>
    <p>Now that you have a better understanding of how we surface important API request sequences, stay tuned for a future blog post in this series, where we’ll describe how we find the anomalous API request sequences that customers may want to stop. For now, API Gateway customers can get started in two ways: with <a href="https://developers.cloudflare.com/api-shield/security/sequence-analytics/"><u>Sequence Analytics</u></a> to explore important API request sequences and with <a href="https://developers.cloudflare.com/api-shield/security/sequence-mitigation/"><u>Sequence Mitigation</u></a> to enforce sequences of API requests. Enterprise customers that haven’t purchased API Gateway can get started by <a href="https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield"><u>enabling the API Gateway trial</u></a> inside the Cloudflare Dashboard or contacting their account manager.</p> ]]></content:encoded>
            <category><![CDATA[AI]]></category>
            <category><![CDATA[API Shield]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[API Security]]></category>
            <guid isPermaLink="false">27ZTkLyAI8VPmwUK2U3jU7</guid>
            <dc:creator>Peter Foster</dc:creator>
        </item>
        <item>
            <title><![CDATA[Securing Cloudflare with Cloudflare: a Zero Trust journey]]></title>
            <link>https://blog.cloudflare.com/securing-cloudflare-with-cloudflare-zero-trust/</link>
            <pubDate>Tue, 05 Mar 2024 14:00:51 GMT</pubDate>
            <description><![CDATA[ A deep dive into how we have deployed Zero Trust at Cloudflare while maintaining user privacy ]]></description>
            <content:encoded><![CDATA[ <p></p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/4r1CIssX038rlnrx4n00m8/5893d5cb949bc417ad6eb899c88ebb75/image1-8.png" />
            
            </figure><p>Cloudflare is committed to providing our customers with industry-leading <a href="https://www.cloudflare.com/network-security/">network security solutions</a>. At the same time, we recognize that establishing robust security measures involves identifying potential threats by using processes that may involve scrutinizing sensitive or personal data, which in turn can pose a risk to privacy. As a result, we work hard to balance privacy and security by building privacy-first security solutions that we offer to our customers and use for our own network.</p><p>In this post, we'll walk through how we deployed Cloudflare products like Access and our Zero Trust Agent in a privacy-focused way for employees who use the Cloudflare network. Even though global legal regimes generally afford employees a lower level of privacy protection on corporate networks, we work hard to make sure our employees understand their privacy choices because Cloudflare has a strong culture and history of respecting and furthering user privacy on the Internet. We’ve found that many of our customers feel similarly about ensuring that they are protecting privacy while also securing their networks.</p><p>So how do we balance our commitment to privacy with ensuring the security of our internal corporate environment using Cloudflare products and services? We start with the basics: We only retain the minimum amount of data needed, we de-identify personal data where we can, we communicate transparently with employees about the security measures we have in place on corporate systems and their privacy choices, and we retain necessary information for the shortest time period needed.</p>
    <div>
      <h2>How we secure Cloudflare using Cloudflare</h2>
      <a href="#how-we-secure-cloudflare-using-cloudflare">
        
      </a>
    </div>
    <p>We take a comprehensive approach to securing our globally distributed hybrid workforce with both organizational controls and technological solutions. Our organizational approach includes a number of measures, such as a company-wide Acceptable Use Policy, employee privacy notices tailored by jurisdiction, required annual and new-hire privacy and security trainings, role-based access controls (<a href="https://www.cloudflare.com/learning/access-management/role-based-access-control-rbac/">RBAC</a>), and least privilege principles. These organizational controls allow us to communicate expectations for both the company and the employees that we can implement with technological controls and that we enforce through logging and other mechanisms.</p><p>Our technological controls are rooted in <a href="https://www.cloudflare.com/learning/security/glossary/what-is-zero-trust/">Zero Trust best practices</a> and start with a focus on our Cloudflare One services to secure our workforce as described below.</p>
    <div>
      <h3>Securing access to applications</h3>
      <a href="#securing-access-to-applications">
        
      </a>
    </div>
    <p>Cloudflare <a href="https://www.cloudflare.com/application-services/solutions/">secures access to self-hosted and SaaS applications</a> for our workforce, whether remote or in-office, using our own <a href="https://www.cloudflare.com/learning/access-management/what-is-ztna/">Zero Trust Network Access</a> (ZTNA) service, Cloudflare Access, to verify identity, <a href="/how-cloudflare-implemented-fido2-and-zero-trust/">enforce multi-factor authentication with security keys</a>, and evaluate device posture using the Zero Trust client for every request. This approach evolved over several years and has enabled Cloudflare to more effectively protect our growing workforce.</p>
    <div>
      <h3>Defending against cyber threats</h3>
      <a href="#defending-against-cyber-threats">
        
      </a>
    </div>
    <p>Cloudflare leverages <a href="https://www.cloudflare.com/network-services/products/magic-wan/">Cloudflare Magic WAN</a> to secure our office networks and <a href="https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/warp/">the Cloudflare Zero Trust agent</a> to secure our workforce. We use both of these technologies as an onramp to our own <a href="https://www.cloudflare.com/zero-trust/products/gateway/">Secure Web Gateway (also known as Gateway)</a> to secure our workforce from a rise in online threats.</p><p>As we have evolved our hybrid work and office configurations, our security teams have benefited from additional controls and visibility for forward-proxied Internet traffic, including:</p><ul><li><p><b>Granular HTTP controls</b>: Our security teams <a href="https://www.cloudflare.com/learning/security/what-is-https-inspection/">inspect HTTPS traffic</a> to block access to specific websites identified as malicious by our security team, conduct <a href="https://developers.cloudflare.com/cloudflare-one/policies/gateway/http-policies/antivirus-scanning/">antivirus scanning</a>, and apply identity-aware browsing policies.</p></li><li><p><b>Selectively isolating Internet browsing</b>: With <a href="https://www.cloudflare.com/learning/access-management/what-is-browser-isolation/">remote browser isolated (RBI)</a> sessions, all web code is run on Cloudflare’s network far from local devices, insulating users from any untrusted and malicious content. Today, Cloudflare isolates social media, news outlets, personal email, and other potentially risky Internet categories, and we have set up feedback loops for our employees to help us fine-tune these categories.</p></li><li><p><b>Geography-based logging</b>: Seeing where outbound requests originate helps our security teams understand the geographic distribution of our workforce, including our presence in high-risk areas.</p></li><li><p><b>Data Loss Prevention:</b> To keep sensitive data inside our corporate network, this tool allows us to identify data we’ve flagged as sensitive in outbound HTTP/S traffic and prevent it from leaving the network.</p></li><li><p><b>Cloud Access Security Broker:</b> This tool allows us to monitor our SaaS apps for misconfigurations and sensitive data that is potentially exposed or shared too broadly.</p></li></ul>
    <div>
      <h3>Protecting inboxes with cloud email security</h3>
      <a href="#protecting-inboxes-with-cloud-email-security">
        
      </a>
    </div>
    <p>Additionally, we have deployed our <a href="https://www.cloudflare.com/zero-trust/products/email-security/">Cloud Email Security</a> solution to protect our workforce from increased phishing and <a href="https://www.cloudflare.com/learning/email-security/business-email-compromise-bec/">business email compromise</a> attacks that we have not only seen directed against our employees, but that are <a href="/2023-phishing-report">plaguing organizations globally</a>. One key feature we use is <a href="/safe-email-links/">email link isolation</a>, which uses RBI and email security functionality to open potentially suspicious links in an isolated browser. This allows us to be slightly more relaxed with blocking suspicious links without compromising security. This is a big win for productivity for our employees and the security team, as both sets of employees aren’t having to deal with large volumes of false positives.</p><p>More details on our implementation can be found in our <a href="https://www.cloudflare.com/case-studies/cloudflare-one/">Securing Cloudflare with Cloudflare One</a> case study.</p>
    <div>
      <h2>How we respect privacy</h2>
      <a href="#how-we-respect-privacy">
        
      </a>
    </div>
    <p>The very nature of these powerful security technologies Cloudflare has created and deployed underscores the responsibility we have to use privacy-first principles in handling this data, and to recognize that the data should be respected and protected at all times.</p><p>The journey to respecting privacy starts with the products themselves. We develop products that have privacy controls built in at their foundation. To achieve this, our product teams work closely with Cloudflare’s product and privacy counsels to practice privacy by design. A great example of this collaboration is the ability to manage personally identifiable information (PII) in the Secure Web Gateway logs. You can choose to <a href="https://developers.cloudflare.com/cloudflare-one/insights/logs/gateway-logs/manage-pii/#exclude-pii">exclude PII from Gateway logs</a> entirely or <a href="https://developers.cloudflare.com/cloudflare-one/insights/logs/gateway-logs/manage-pii/#redact-pii">redact PII from the logs</a> and gain granular control over access to PII with the <a href="https://developers.cloudflare.com/cloudflare-one/roles-permissions/#cloudflare-zero-trust-pii">Zero Trust PII Role</a>.</p><p>In addition to building privacy-first security products, we are also committed to communicating transparently with Cloudflare employees about how these security products work and what they can – and can’t – see about traffic on our internal systems. This empowers employees to see themselves as part of the security solution, rather than set up an “us vs. them” mentality around employee use of company systems.</p><p>For example, while our employee privacy policies and our Acceptable Use Policy provide broad notice to our employees about what happens to data when they use the company’s systems, we thought it was important to provide even more detail. As a result, our security team collaborated with our privacy team to create an internal wiki page that plainly explains the data our security tools collect and why. We also describe the privacy choices available to our employees. This is particularly important for the “bring your own device” (BYOD) employees who have opted for the convenience of using their personal mobile device for work. BYOD employees must install endpoint management (provided by a third party) and Cloudflare’s Zero trust client on their devices if they want to access Cloudflare systems. We described clearly to our employees what this means about what traffic on their devices can be seen by Cloudflare teams, and we explained how they can take steps to protect their privacy when they are using their devices for purely personal purposes.</p><p>For the teams that develop for and support our <a href="https://www.cloudflare.com/zero-trust/solutions/">Zero Trust services</a>, we ensure that data is available only on a strict, need-to-know basis and is restricted to Cloudflare team members that require access as an essential part of their job. The set of people with access are required to take training that reminds them of their responsibility to respect this data and provides them with best practices for handling sensitive data. Additionally, to ensure we have full auditability, we log all the queries run against this database and by whom they are run.</p><p>Cloudflare has also made it easy for our employees to express any concerns they may have about how their data is handled or what it is used for. We have mechanisms in place that allow employees to ask questions or express concerns about the use of Zero Trust Security on Cloudflare’s network.</p><p>In addition, we make it easy for employees to reach out directly to the leaders responsible for these tools. All of these efforts have helped our employees better understand what information we collect and why. This has helped to expand our strong foundation for security and privacy at Cloudflare.</p>
    <div>
      <h2>Encouraging privacy-first security for all</h2>
      <a href="#encouraging-privacy-first-security-for-all">
        
      </a>
    </div>
    <p>We believe firmly that great security is critical for ensuring data privacy, and that privacy and security can co-exist harmoniously. We also know that it is possible to secure a corporate network in a way that respects the employees using those systems.</p><p>For anyone looking to secure a corporate network, we encourage focusing on network security products and solutions that build in personal data protections, like our Zero Trust suite of products. If you are curious to explore <a href="https://www.cloudflare.com/learning/access-management/how-to-implement-zero-trust/">how to implement</a> these Cloudflare services in your own organizations, <a href="https://www.cloudflare.com/products/zero-trust/plans/enterprise/">request a consultation on Zero Trust here</a>.</p><p>We also urge organizations to make sure they communicate clearly with their users. In addition to making sure company policies are transparent and accessible, it is important to help employees understand their privacy choices. Under the laws of almost every jurisdiction globally, individuals have a lower level of privacy on a company device or a company’s systems than they do on their own personal accounts or devices, so it’s important to communicate clearly to help employees understand the difference. If an organization has privacy champions, works councils, or other employee representation groups, it is critical to communicate early and often with these groups to help employees understand what controls they can exercise over their data.</p> ]]></content:encoded>
            <category><![CDATA[Security Week]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[Zero Trust]]></category>
            <category><![CDATA[Privacy]]></category>
            <guid isPermaLink="false">6l7ydA66mxLvZMpnAgzEhD</guid>
            <dc:creator>Derek Pitts</dc:creator>
            <dc:creator>Ankur Aggarwal</dc:creator>
            <dc:creator>Emily Hancock</dc:creator>
        </item>
        <item>
            <title><![CDATA[Protecting APIs with JWT Validation]]></title>
            <link>https://blog.cloudflare.com/protecting-apis-with-jwt-validation/</link>
            <pubDate>Tue, 05 Mar 2024 14:00:34 GMT</pubDate>
            <description><![CDATA[ Cloudflare customers can now protect their APIs from broken authentication attacks by validating incoming JSON Web Tokens (JWTs) with API Gateway ]]></description>
            <content:encoded><![CDATA[ <p></p><p>Today, we are happy to announce that Cloudflare customers can protect their APIs from broken authentication attacks by validating incoming JSON Web Tokens (JWTs) with <a href="https://www.cloudflare.com/application-services/products/api-gateway/">API Gateway</a>. Developers and their security teams need to control who can communicate with their APIs. Using API Gateway’s JWT Validation, Cloudflare customers can ensure that their Identity Provider previously validated the user sending the request, and that the user’s authentication tokens have not expired or been tampered with.</p>
    <div>
      <h3>What’s new in this release?</h3>
      <a href="#whats-new-in-this-release">
        
      </a>
    </div>
    <p>After our beta release in early 2023, we continued to gather feedback from customers on what they needed from JWT validation in API Gateway. We uncovered four main feature requests and shipped updates in this GA release to address them all:</p>
<table>
<thead>
  <tr>
    <th><span>Old, Beta limitation</span></th>
    <th><span>New, GA release capability</span></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><span>Only supported validating the raw JWT</span></td>
    <td><span>Support for the Bearer token format</span></td>
  </tr>
  <tr>
    <td><span>Only supported one JWKS configuration</span></td>
    <td><span>Create up to four different JWKS configs to support different environments per zone</span></td>
  </tr>
  <tr>
    <td><span>Only supported validating JWTs sent in HTTP headers</span></td>
    <td><span>Validate JWTs if they are sent in a cookie, not just an HTTP header</span></td>
  </tr>
  <tr>
    <td><span>JWT validation ran on all requests to the entire zone</span></td>
    <td><span>Exclude any number of managed endpoints in a JWT validation rule</span></td>
  </tr>
</tbody>
</table>
    <div>
      <h3>What is the threat?</h3>
      <a href="#what-is-the-threat">
        
      </a>
    </div>
    <p>Broken authentication is the <a href="https://owasp.org/Top10/A01_2021-Broken_Access_Control/">#1 threat</a> on the OWASP Top 10 and the <a href="https://owasp.org/API-Security/editions/2023/en/0xa2-broken-authentication/">#2 threat</a> on the OWASP API Top 10. We’ve <a href="/2024-api-security-report/">written before</a> about how flaws in API authentication and authorization at Optus led to a <a href="https://www.bleepingcomputer.com/news/security/optus-hacker-apologizes-and-allegedly-deletes-all-stolen-data/">threat actor offering</a> 10 million user records for sale, and government agencies have <a href="https://www.cisa.gov/news-events/cybersecurity-advisories/aa23-208a">warned about</a> these exact API attacks.</p><p>According to Gartner®<sup>1</sup>, “attacks and data breaches involving poorly secured application programming interfaces (APIs) are occurring frequently.” Getting authentication correct for your API users can be challenging, but there are best practices you can employ to cover your bases. JSON Web Token Validation in API Gateway fulfills one of these best practices by enforcing a positive security model for your authenticated API users.</p>
    <div>
      <h3>A primer on authentication and authorization</h3>
      <a href="#a-primer-on-authentication-and-authorization">
        
      </a>
    </div>
    <p><a href="https://www.cloudflare.com/learning/access-management/authn-vs-authz/#:~:text=What%20is%20authentication%20(authn)%3F">Authentication</a> establishes identity. Imagine you’re collaborating with multiple colleagues and writing a document in Google Docs. When you’re all authors of the document, you have the same privileges, and you can overwrite each other’s text. You can all see each other’s name next to your respective cursor while you’re typing. You’re all authenticated to Google Docs, so Docs can show all the users on a document who everyone is.</p><p><a href="https://www.cloudflare.com/learning/access-management/authn-vs-authz/#:~:text=What%20is%20authorization%20(authz)%3F">Authorization</a> establishes ownership or permissions to objects. Imagine you’re collaborating with your colleague in Docs again, but this time they’ve written a document ahead of time and simply wish for you to review it and add comments without changing the document. As the owner of the document, your colleague sets an authorization policy to only allow you ‘comment’ access. As such, you cannot change their writing at all, but you can still view the document and leave comments.</p><p>While the words themselves might sound similar, the differences between them are hugely important for security. It’s not enough to simply check that a user logging in has the correct login credentials (authentication). If you never check their permissions (authorization), they would be free to overwrite, add, or delete other users’ content. When this happens for APIs, <a href="https://owasp.org/">OWASP</a> calls it a <a href="https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/">Broken Object Level Authorization</a> attack.</p>
    <div>
      <h3>A primer on API access tokens</h3>
      <a href="#a-primer-on-api-access-tokens">
        
      </a>
    </div>
    <p>Users authenticate to services in many different ways on the web today. Let’s take a look at the history of authentication with username and password authentication, API key authentication, and JWT authentication before we mention how JWTs can help <a href="https://www.cloudflare.com/the-net/api-security/">stop API attacks</a>.</p><p>In the early days, the web used <a href="https://datatracker.ietf.org/doc/html/rfc7617">HTTP Basic Authentication</a>, where browsers transmitted username and password pairs as an HTTP header, posing significant security risks and making credentials visible to any observer when the application failed to adopt <a href="https://www.cloudflare.com/application-services/products/ssl/">SSL/TLS certificates</a>. Basic authentication also complicated API access, requiring hard-coded credentials and potentially giving broad authorization policies to a single user.</p><p>The introduction of API access keys improved security by detaching authentication from user credentials and instead sending secret text strings along with requests. This approach allowed for more nuanced access control by key instead of by user ID, though API keys still faced risks from man-in-the-middle attacks and problematic storage of secrets in source code.</p><p><a href="https://datatracker.ietf.org/doc/html/rfc7519">JSON Web Tokens (JWTs)</a> address these issues by removing the need to send long-lived secrets on every request, introducing cryptographically verifiable, auto-expiring, short-lived sessions. Think of a JWT like a tamper-evident seal on a bottle of medication. Along with the seal, medication also has an expiration date printed on it. Users notice when the seal is tampered with or missing altogether, and when the medication expires.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/771ZNa71vA96wLeQdZ1Oz2/8ae10ada5cd6bc77b3d31f3f6ad9500f/image2-5.png" />
            
            </figure><p>These attributes enhance security any time a JWT is used instead of a long-lived shared secret. JWTs are not an end-all-be-all solution, but they do represent an evolution in authentication technology and are widely used for authentication and authorization on the Internet today.</p>
    <div>
      <h3>What’s the structure of a JWT?</h3>
      <a href="#whats-the-structure-of-a-jwt">
        
      </a>
    </div>
    <p>JWTs are composed of three fields separated by periods. The first field is a header, the second a payload, and the third a signature:</p>
            <pre><code>eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJNeURlbW9JRFAiLCJzdWIiOiJqb2huZG9lIiwiYXVkIjoiTXlBcHAiLCJpYXQiOjE3MDg5ODU2MDEsImV4cCI6MTcwODk4NjIwMSwiY2xhc3MiOiJhZG1pbiJ9.v0nywcQemlEU4A18QD9UTgJLyH4ZPXppuW-n0iOmtj4x-hWJuExlMKeNS-vMZt4K6n0pDCFIAKo7_VZqACx4gILXObXMU4MEleFoKKd0f58KscNrC3BQqs3Gnq-vb5Ut9CmcvevQ5h9cBCI4XhpP2_LkYcZiuoSd3zAm2W_0LNZuFXp1wo8swDoKETYmtrdTjuF-IlVjLDAxNsWm2e7T5A8HmCnAWRItEPedm_8XVJAOemx_KqIH5w6zHY1U-M6PJkHK6D2gDU5eiN35A4FCrC5bQ1-0HSTtJkLIed2-1mRO1oANWHpscvpNLQBWQLLiIZ_evbcq_tnwh1X1sA3uxQ</code></pre>
            <p>If we base64 decode the first two sections, we arrive at the following structure (comments added for clarity):</p>
            <pre><code>{
  "alg": "RS256",     // JWT signature algorithm
  "typ": "JWT"        // JWT type
}

{
  "iss": "MyDemoIDP", // Which identity provider issued this JWT
  "sub": "johndoe",   // Which user this JWT identifies
  "aud": "MyApp",     // Which app this JWT is destined for
  "iat": 1708985601,  // When this JWT was issued
  "exp": 1709986201,  // When this JWT expires
  "class": "admin"    // Extra, customer-defined metadata
}</code></pre>
            <p>We can then use the algorithm mentioned in the header (RS256) as well as the Identity Provider’s public key (example below) to check the last segment in the JWT, the signature (code not shown).</p>
            <pre><code>-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3exXmNOELAnrtejo3jb2
S6p+GFR5FFlO0AqC4lA4HjNX9stgxX8tcbzv1yl5CT6VWl4kpnBweJzdBsNOauPz
uiCFQ0PtTfS0wDZm3inRPR1bTvJEuqsRTbsCxw/nRLU2+Dvu0zF41Wo4OkAbuKGS
3FwfdKOY/rX5tzjhnTe7uhWTarJG3nVnwmuD03INeNI+fbTgbUrOaVFT06Ussb9L
NNe6BHGQjs6NfG037Jk36dGY1Yiy/rutj6nJ7WkEK5ktQgWrvMMoXW9TfpYHi6sC
mnSEdaxNS8jtFodqpURUaLDIdTOGGgpUZsvzv3jDMYo5IxQK+6y+HUV8eRyDYd/o
rQIDAQAB
-----END PUBLIC KEY-----</code></pre>
            <p>The signature is what makes a JWT special. The token issuer, taking into account the claims, generates a signature based on a private secret or a public/private key pair. The public key can be published online, allowing anyone to check if a JWT was legitimately issued by an organization.</p>
    <div>
      <h3>Proper authentication and authorization stop API attacks</h3>
      <a href="#proper-authentication-and-authorization-stop-api-attacks">
        
      </a>
    </div>
    <p>No developer wants to release an insecure application, and no security team wants their developers to skip secure coding practices, but we know both happen. In the Enterprise Strategy Group report “Securing the API Attack Surface”<sup>2</sup>, a survey found that 39% of developers skip security processes due to the faster development cycles of <a href="https://www.cloudflare.com/learning/serverless/glossary/what-is-ci-cd/">continuous integration and continuous delivery (CI/CD)</a>. The same survey found more than half (57%) of responding organizations faced multiple security incidents related to insecure APIs in the last 12 months, and 35% of responding organizations faced at least one incident within the last year.</p><p>Along with its accompanying database, permissions, and user roles, your origin application is the ultimate security backstop of your API. However, Cloudflare can assist in keeping attacks away from your origin when you configure API Gateway with the correct context. Let’s examine three different API attacks and how to protect against them.</p>
    <div>
      <h3>Missing or broken authentication</h3>
      <a href="#missing-or-broken-authentication">
        
      </a>
    </div>
    <p>The ability for a user to send or receive data to an API and entirely bypass authentication falls into ‘<a href="https://owasp.org/API-Security/editions/2023/en/0xa2-broken-authentication/">broken authentication</a>’. It’s easy to think of the expected use cases your users will take with your application. You may assume that just because a user logs in and your application is written so that users can only access their own data in their dashboard, that all users are logged in and would only access their own data. This assumption fails to account for a user making an HTTP request outside your application requesting or modifying another user’s data and there being nothing in the way to stop your API from replying. In the worst case, a lack of authorization policy checks can enable an API client to change data without an authentication token at all!</p><p>Ensuring that incoming requests have an authentication token attached to them and dropping the requests that don’t is a great way to stop the simplest API attacks.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/42Mpb21IPLfulvcmZ6FPlV/f6a4139960a60f3d6940ade90809a42f/image1-6.png" />
            
            </figure>
    <div>
      <h3>Expired token reuse</h3>
      <a href="#expired-token-reuse">
        
      </a>
    </div>
    <p>Maybe your application already uses JWTs for user authentication. Your application decodes the JWT and looks for user claims for group membership, and you validate the claims before allowing customers access to your API. But are you checking the JWT expiration time?</p><p>Imagine a user pays for your service, but they secretly know they will soon downgrade to a free account. If the user’s tier is stored within the JWT and the application or gateway doesn’t validate the expiration time of the JWT, the user could save an old JWT and replay it to continue their access to their paid benefits. Validating JWT expiration time can prevent this type of replay attack.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/3SYRZ4vdgAps8zy5oaRzew/79f8c731747f0e90c75e614c84765220/image5-1.png" />
            
            </figure>
    <div>
      <h3><a href="https://owasp.org/API-Security/editions/2023/en/0xa5-broken-function-level-authorization/">Broken Function Level Authorization</a> attacks: Tampering with claims</h3>
      <a href="#attacks-tampering-with-claims">
        
      </a>
    </div>
    <p>Let’s say you’re using JWTs for authentication, validating the claims inside them, and also validating expiration time. But do you verify the JWT signature? Practically every JWT is signed by its issuer such that API admins and security teams that know the issuer’s signing key can verify that the JWT hasn’t been tampered with. Without the API Gateway or application checking the JWT signature, a malicious user could change their JWT claims, elevating their privileges to assume an administrator role in an application by starting with a normal, non-privileged user account.</p><p>JWT Validation from API Gateway <a href="https://www.cloudflare.com/application-services/solutions/api-security/">safeguards your API</a> from broken authentication and authorization attacks by checking that JWT signatures are intact, expiry times haven’t yet passed, and that authentication tokens are present to begin with.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/7J6x1nH7rK3Ox7jQmQDOuI/57af3725eb76213308498228e9b55996/image4-7.png" />
            
            </figure>
    <div>
      <h3>Don’t other Cloudflare products do this?</h3>
      <a href="#dont-other-cloudflare-products-do-this">
        
      </a>
    </div>
    <p>Other Cloudflare products also use JWTs. Cloudflare Access is part of our suite of Zero Trust products, and is meant to tie into your Identity Provider. As a best practice, customers should <a href="https://developers.cloudflare.com/cloudflare-one/identity/authorization-cookie/validating-json/">validate</a> the JWT that Access creates and sends to the origin.</p><p>Conversely, JWT Validation for API Gateway is a security layer compatible with any API without changing the setup, management, or expectation of the existing user flow. API Gateway’s JWT Validation is meant to validate pre-existing JWTs that may be used by any number of services at your API origin. You really need both: Access for your internal users or employees and API Gateway for your external users.</p><p>In addition, some customers use a custom Cloudflare Worker to validate JWTs, which is a great use case for the Workers platform. However, for straightforward use cases customers may find the JWT Validation experience of API Gateway easier to interact with and manage over the lifecycle of their application. If you are validating JWTs with a Worker and today’s release of JWT Validation isn’t yet at feature parity for your custom Worker, let your account representative know. We’re interested in expanding our capabilities to meet your requirements.</p>
    <div>
      <h3>What’s next?</h3>
      <a href="#whats-next">
        
      </a>
    </div>
    <p>In a future release, we will go beyond checking pre-existing JWTs, and customers will be able to generate and enforce authorization policies entirely within API Gateway. We’ll also upgrade our <a href="https://developers.cloudflare.com/api-shield/management-and-monitoring/developer-portal/">on-demand developer portal creation</a> with the ability to issue keys and authentication tokens to your development team directly, streamlining API management with Cloudflare.</p><p>In addition, stay tuned for future API Gateway feature launches where we’ll use our knowledge of API traffic norms to automatically suggest security policies that highlight and stop Broken Object/Function Level Authorization attacks outside the JWT Validation use case.</p><p>Existing API Gateway customers can <a href="https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield/api-rules">try the new feature now</a>. Enterprise customers without API Gateway should <a href="https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield">sign up</a> for the trial to try the latest from API Gateway.</p><p>--</p><p><sup>1</sup>Gartner, “API Security: What You Need to Do to Protect Your APIs”, Analyst(s) Mark O'Neill, Dionisio Zumerle, Jeremy D'Hoinne, January 13, 2023</p><p><sup>2</sup>Enterprise Strategy Group, “Securing the API Attack Surface”, Analyst, Melinda Marks, May 2023</p> ]]></content:encoded>
            <category><![CDATA[Security Week]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[API Shield]]></category>
            <category><![CDATA[API Security]]></category>
            <category><![CDATA[Security]]></category>
            <guid isPermaLink="false">6N1T1V4DK6CoLMLGwuxKvk</guid>
            <dc:creator>John Cosgrove</dc:creator>
        </item>
        <item>
            <title><![CDATA[Introducing Cloudflare’s 2024 API security and management report]]></title>
            <link>https://blog.cloudflare.com/2024-api-security-report/</link>
            <pubDate>Tue, 09 Jan 2024 14:00:03 GMT</pubDate>
            <description><![CDATA[ Today, we’re releasing our 2024 API Security and Management Report. This blog introduces and is a supplement to the API Security and Management Report for 2024 where we detail exactly how we’re protecting our customers, and what it means for the future of API security ]]></description>
            <content:encoded><![CDATA[ <p></p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/2wnkskFDuLFCKg3bJKxdEA/dde70afb5d2340f7a3939f79686cc670/Artboard-1-1.png" />
            
            </figure><p>You may know Cloudflare as the company powering nearly 20% of the web. But powering and protecting websites and static content is only a fraction of what we do. In fact, well over half of the dynamic traffic on our network consists not of web pages, but of Application Programming Interface (API) traffic — the plumbing that makes technology work. This blog introduces and is a supplement to the <a href="https://www.cloudflare.com/lp/api-security-report/">API Security Report for 2024</a> where we detail exactly how we’re protecting our customers, and what it means for the future of API security. Unlike other industry API reports, our report isn’t based on user surveys — but instead, based on real traffic data.</p><p>If there’s only one thing you take away from our report this year, it’s this: many organizations lack accurate API inventories, <i>even when they believe they can correctly identify API traffic</i>. Cloudflare helps organizations discover all of their public-facing APIs using <a href="/ml-api-discovery-and-schema-learning/">two approaches</a>. First, customers configure our API discovery tool to monitor for identifying tokens present in their known API traffic. We then use a machine learning model that scans not just these known API calls, but <i>all</i> HTTP requests, identifying API traffic that may be going unaccounted for. The difference between these approaches is striking: <b>we found 30.7% more API endpoints through machine learning-based discovery</b> than the self-reported approach, suggesting that nearly a third of APIs are “<a href="https://www.cloudflare.com/learning/security/api/what-is-shadow-api/">Shadow APIs</a>” — and may not be properly inventoried and secured.</p><p>Read on for extras and highlights from our inaugural API security report. In the <a href="https://www.cloudflare.com/2024-api-security-management-report/">full report</a>, you’ll find updated statistics about the threats we see and prevent, along with our predictions for 2024. We predict that a lack of API security focus at organizations will lead to increased complexity and loss of control, and increased access to generative AI will lead to more API risk. We also anticipate an increase in API business logic attacks in 2024. Lastly, all of the above risks will necessitate growing governance around API security.</p>
    <div>
      <h3>Hidden attack surfaces</h3>
      <a href="#hidden-attack-surfaces">
        
      </a>
    </div>
    <p>How are web pages and APIs different? APIs are a quick and easy way for applications to retrieve data in the background, or ask that work be done from other applications. For example, anyone can write a weather app without being a meteorologist: a developer can write the structure of the page or mobile application and ask a weather API for the forecast using the user’s location. Critically, most end users don’t know that the data was provided by the weather API and not the app’s owner.</p><p>While APIs are the critical plumbing of the Internet, they're also ripe for abuse. For example, flaws in API authentication and authorization at Optus <a href="https://www.bleepingcomputer.com/news/security/optus-hacker-apologizes-and-allegedly-deletes-all-stolen-data/">led to a threat actor offering</a> 10 million user records for sale, and government agencies have <a href="https://www.cisa.gov/news-events/cybersecurity-advisories/aa23-208a">warned about</a> these exact API attacks. Developers in an organization will often create Internet-facing APIs, used by their own applications to function more efficiently, but it's on the security team to protect these new public interfaces. If the process of documenting APIs and bringing them to the attention of the security team isn't clear, they become Shadow APIs — operating in production but without the organization's knowledge. This is where the <a href="https://www.cloudflare.com/learning/security/what-is-an-attack-surface/">security challenge</a> begins to emerge.</p><p>To help customers solve this problem, we shipped <a href="https://developers.cloudflare.com/api-shield/security/api-discovery/">API Discovery</a>. When we <a href="/ml-api-discovery-and-schema-learning/">introduced</a> our latest release, we mentioned how few organizations have accurate API inventories. Security teams sometimes are forced to adopt an “email and ask” approach to build an inventory, and in doing so responses are immediately stale upon the next application release when APIs change. Better is to track API changes by code base changes, keeping up with new releases. However, this still has a drawback of only inventorying actively maintained code. Legacy applications may not see new releases, despite receiving production traffic.</p><p>Cloudflare's approach to API management involves creating a comprehensive, accurate API inventory using a blend of machine learning-based API discovery and network traffic inspection. This is integral to our <a href="https://www.cloudflare.com/application-services/products/api-gateway/">API Gateway</a> product, where customers can manage their Internet-facing endpoints and monitor API health. The API Gateway also allows customers to identify their API traffic using session identifiers (typically a header or cookie), which aids in specifically identifying API traffic for the discovery process.</p><p>As noted earlier, our analysis reveals that even knowledgeable customers often overlook significant portions of their API traffic. By comparing session-based API discovery (using API sessions to pinpoint traffic) with our machine learning-based API discovery (analyzing <i>all</i> incoming traffic), we found that the latter uncovers on average 30.7% more endpoints! Without broad traffic analysis, you may be missing almost a third of your API inventory.</p><p>If you aren’t a Cloudflare customer, you can still get started building an API inventory. APIs are typically cataloged in a standardized format called <a href="https://spec.openapis.org/oas/latest.html">OpenAPI</a>, and many development tools can build OpenAPI formatted schema files. If you have a file with that format, you can start to build an API inventory yourself by collecting these schemas. Here is an example of how you can pull the endpoints out of a schema file, assuming your have an OpenAPI v3 formatted file named <code>my_schema.json</code>:</p>
            <pre><code>import json
import csv
from io import StringIO

# Load the OpenAPI schema from a file
with open("my_schema.json", "r") as file:
    schema = json.load(file)

# Prepare CSV output
output = StringIO()
writer = csv.writer(output)

# Write CSV header
writer.writerow(["Server", "Path", "Method"])

# Extract and write data to CSV
servers = schema.get("servers", [])
for server in servers:
    url = server['url']
    for path, methods in schema['paths'].items():
        for method in methods.keys():
            writer.writerow([url, path, method])

# Get and print CSV string
csv_output = output.getvalue().strip()
print(csv_output)</code></pre>
            <p>Unless you have been generating OpenAPI schemas and tracking API inventory from the beginning of your application’s development process, you’re probably missing some endpoints across your production application API inventory.</p>
    <div>
      <h3>Precise rate limits minimize attack potential</h3>
      <a href="#precise-rate-limits-minimize-attack-potential">
        
      </a>
    </div>
    <p>When it comes to stopping abuse, most practitioners’ thoughts first come to <a href="https://www.cloudflare.com/learning/bots/what-is-rate-limiting/">rate limiting</a>. <b>Implementing limits on your API is a valuable tool to keep abuse in check and prevent accidental overload of the origin.</b> But how do you know if you’ve chosen the correct rate limiting approach? Approaches can vary, but they generally come down to the error code chosen, and the basis for the limit value itself.</p><p>For some APIs, practitioners configure rate limiting errors to respond with an HTTP 403 (forbidden), while others will respond with HTTP 429 (too many requests). Using HTTP 403 sounds innocent enough until you realize that other security tools are also responding with 403 codes. When you’re under attack, it can be hard to decipher which tools are responsible for which errors / blocking.</p><p>Alternatively, if you utilize HTTP 429 for your rate limits, attackers will instantly know that they’ve been rate limited and can “surf” right under the limit without being detected. This can be OK if you’re only limiting requests to ensure your back-end stays alive, but it can tip your cards to attackers. In addition, attackers can “scale out” to more API clients to effectively request above the rate limit.</p><p>There are pros and cons to both approaches, but we find that by far most APIs respond with HTTP 429 out of all the 4xx and 5xx error messages (almost 52%).</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/6cJjGIFScYgWUrc7KizhvE/8cc248c65dde6736cd9f634e988ff73e/Untitled.png" />
            
            </figure><p>What about the logic of the rate limit rule itself, not just the response code? Implementing request limits on IP addresses can be tempting, but <b>we recommend you base the limit on a session ID as a best practice and only fall back to IP address (or IP + JA3 fingerprint) when session IDs aren’t available</b>. Setting rate limits on user sessions instead of IPs will reliably identify your real users and minimize false positives due to shared IP space. Cloudflare’s <a href="https://www.cloudflare.com/application-services/products/rate-limiting/">Advanced Rate Limiting</a> and API Gateway’s <a href="https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/">volumetric abuse protection</a> make it easy to enforce these limits by profiling session traffic on each API endpoint and giving one-click solutions to set up the per-endpoint rate limits.</p><p>To find values for your rate limits, Cloudflare API Gateway computes session request statistics for you. We suggest a limit by looking at the distribution of requests per session across <i>all</i> sessions to your API as identified by the customer-configured API session identifier. We then <a href="https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/#observe-rate-limits">compute statistical p-levels</a> — which describe the request rates for different cohorts of traffic — for p50, p90, and p99 on this distribution and use the variance of the distribution to come up with a recommended threshold for every single endpoint in your API inventory. The recommendation might not match the p-levels, which is an important distinction and a reason not to use p-levels alone. Along with the recommendation, API Gateway informs users of our confidence in the recommendation. Generally, the more API sessions we’re able to collect, the more confident we’ll be in the recommendation.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/5b6UZSSACJxBUGIBkD7lBL/d9bdf32f1648685ec291f5c172e86d5a/Screenshot-2024-01-04-at-12.50.45-1.png" />
            
            </figure><p>Activating a rate limit is as easy as clicking the ‘create rule’ link, and API Gateway will automatically bring your session identifier over to the advanced rate limit rule creation page, ensuring your rules have pinpoint accuracy to defend against attacks and minimize false positives compared to traditional, overly broad limits.</p>
    <div>
      <h3>APIs are also victim to web application attacks</h3>
      <a href="#apis-are-also-victim-to-web-application-attacks">
        
      </a>
    </div>
    <p>APIs aren’t immune from normal OWASP Top 10 style attacks like <a href="https://www.cloudflare.com/learning/security/threats/sql-injection/">SQL injection</a>. The body of API requests can also find its way as a database input just like a web page form input or URL argument. It’s important to ensure that you have a <a href="https://www.cloudflare.com/learning/ddos/glossary/web-application-firewall-waf/">web application firewall (WAF)</a> also protecting your API traffic to defend against these styles of attacks.</p><p>In fact, when we looked at Cloudflare’s WAF managed rules, injection attacks were the second most common threat vector Cloudflare saw carried out on APIs. The most common threat was HTTP Anomaly. Examples of HTTP anomalies include malformed method names, null byte characters in headers, non-standard ports or content length of zero with a POST request. Here are the stats on the other top threats we saw against APIs:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/4RAYOdH61ox07Ps1INKxO2/35e3eeed0b2981d15ac65b22e27ce692/Untitled--1---1-.png" />
            
            </figure><p>Absent from the chart is broken authentication and authorization. Broken authentication and authorization occur when an API fails to check whether the entity sending requests for information to an API actually has the permission to request that data or not. It can also happen when attacks try to forge credentials and insert less restricted permissions into their existing (valid) credentials that have more restricted permissions. OWASP categorizes these attacks in a few different ways, but the main categories are Broken Object Level Authorization (BOLA) and Broken Function Level Authorization (BFLA) attacks.</p><p>The root cause of a successful BOLA / BFLA attack lies in an origin API not checking proper ownership of database records against the identity requesting those records. Tracking these specific attacks can be difficult, as the permission structure may be simply absent, inadequate, or improperly implemented. Can you see the chicken-and-egg problem here? It would be easy to stop these attacks if we knew the proper permission structure, but if we or our customers knew the proper permission structure or could guarantee its enforcement, the attacks would be unsuccessful to begin with. Stay tuned for future API Gateway feature launches where we’ll use our knowledge of API traffic norms to automatically suggest security policies that highlight and stop BOLA / BFLA attacks.</p><p>Here are four ways to plug authentication loopholes that may exist for your APIs, even if you don’t have a fine-grained authorization policy available:</p><ol><li><p>First, enforce authentication on each publicly accessible API unless there's a business approved exception. Look to technologies like mTLS and JSON Web Tokens.</p></li><li><p>Limit the speed of API requests to your servers to slow down potential attackers.</p></li><li><p>Block abnormal volumes of sensitive data outflow.</p></li><li><p>Block attackers from skipping legitimate sequences of API requests.</p></li></ol>
    <div>
      <h3>APIs are surprisingly human driven, not machine driven anymore</h3>
      <a href="#apis-are-surprisingly-human-driven-not-machine-driven-anymore">
        
      </a>
    </div>
    <p>If you’ve been around technology since the pre-smartphone days when fewer people were habitually online, it can be tempting to think of APIs as only used for machine-to-machine communication in something like an overnight batch job process. However, the truth couldn’t be more different. As we’ve discussed, many web and mobile applications are powered by APIs, which facilitate everything from authentication to transactions to serving media files. As people use these applications, there is a corresponding increase in API traffic volume.</p><p>We can illustrate this by looking at the API traffic patterns observed during holidays, when people gather around friends and family and spend more time socializing in person and less time online. We’ve annotated the following Worldwide API traffic graph with common holidays and promotions. Notice how traffic peaks around Black Friday and Cyber Monday around the +10% level when people shop online, but then traffic drops off for the festivities of Christmas and New Years days.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/7aETzYYdiYbkQws35HSDlK/e6212b57845bb2e2813d513e4de8c5a0/Untitled--2-.png" />
            
            </figure><p>This pattern <a href="/cyber-week-analyzing-internet-traffic-and-e-commerce-trends">closely resembles</a> what we observe in regular HTTP traffic. It’s clear that APIs are no longer just the realm of automated processes but are intricately linked with human behaviors and social trends.</p>
    <div>
      <h3>Recommendations</h3>
      <a href="#recommendations">
        
      </a>
    </div>
    <p>There is no silver bullet for holistic API security. For the best effect, Cloudflare recommends four strategies for increasing API security posture:</p><ol><li><p>Combine API application development, visibility, performance, and security with a unified control plane that can keep an up-to-date API inventory.</p></li><li><p>Use security tools that utilize machine learning technologies to free up human resources and reduce costs.</p></li><li><p>Adopt a positive security model for your APIs (see below for an explanation on positive and negative security models).</p></li><li><p>Measure and improve your organization’s API maturity level over time (also see below for an explanation of an API maturity level).</p></li></ol><p>What do we mean by a ‘positive’ or ‘negative’ security model? In a negative model, security tools look for known signs of attack and take action to stop those attacks. In a positive model, security tools look for known good requests and only let those through, blocking all else. APIs are often so structured that positive security models make sense for the highest levels of security. You can also combine security models, such as using a WAF in a negative model sense, and using API Schema Validation in a positive model sense.</p><p>Here’s a quick way to gauge your organization’s API security maturity level over time: Novice organizations will get started by assembling their first API inventory, no matter how incomplete. More mature organizations will strive for API inventory accuracy and automatic updates. The most mature organizations will actively enforce security checks in a positive security model on their APIs, enforcing API schema, valid authentication, and checking behavior for signs of abuse.</p>
    <div>
      <h3>Predictions</h3>
      <a href="#predictions">
        
      </a>
    </div>
    <p>In closing, our top four predictions for 2024 and beyond:</p><p><b>Increased loss of control and complexity:</b> we surveyed practitioners in the API Security and Management field and 73% responded that security requirements interfere with their productivity and innovation. Coupled with increasingly sprawling applications and inaccurate inventories, API risks and complexity will rise.</p><p><b>Easier access to AI leading to more API risks:</b> the rise in generative AI brings <a href="https://www.cloudflare.com/learning/ai/what-is-ai-security/">potential risks</a>, including AI models’ APIs being vulnerable to attack, but also developers shipping buggy, AI-written code. Forrester predicts that, in 2024, without <a href="https://www.cloudflare.com/ai-security/">proper guardrails</a>, “at least three data breaches will be publicly blamed on insecure AI-generated code – either due to security flaws in the generated code itself or vulnerabilities in AI-suggested dependencies.”</p><p><b>Increase in business logic-based fraud attacks:</b> professional fraudsters run their operations just like a business, and they have costs like any other. We anticipate attackers will run fraud bots efficiently against APIs even more than in previous years.</p><p><b>Growing governance:</b> The first version of <a href="https://www.cloudflare.com/learning/privacy/what-is-pci-dss-compliance/">PCI DSS</a> that directly addresses API security will go into effect in March 2024. Check your industry’s specific requirements with your audit department to be ready for requirements as they come into effect.</p><p>If you’re interested in the full report, you can download the 2024 API Security Report <a href="https://www.cloudflare.com/2024-api-security-management-report/">here</a>, which includes full detail on our recommendations.</p><p><i>Cloudflare API Gateway is our </i><a href="https://www.cloudflare.com/application-services/solutions/api-security/"><i>API security solution</i></a><i>, and it is available for all Enterprise customers. If you aren’t subscribed to API Gateway,</i> <a href="http://dash.cloudflare.com/?to=/:account/:zone/security/api-shield"><i>click here</i></a> <i>to view your initial API Discovery results and start a trial in the Cloudflare dashboard. To learn how to use API Gateway to secure your traffic,</i> <a href="https://developers.cloudflare.com/api-shield/"><i>click here</i></a> <i>to view our development docs and</i> <a href="https://developers.cloudflare.com/api-shield/get-started/"><i>here</i></a> <i>for our getting started guide.</i></p> ]]></content:encoded>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[API Security]]></category>
            <category><![CDATA[API Shield]]></category>
            <category><![CDATA[Security]]></category>
            <guid isPermaLink="false">7dEgZBP69KIcuJAqhX5Ety</guid>
            <dc:creator>John Cosgrove</dc:creator>
            <dc:creator>Sabina Zejnilovic</dc:creator>
        </item>
        <item>
            <title><![CDATA[Protecting GraphQL APIs from malicious queries]]></title>
            <link>https://blog.cloudflare.com/protecting-graphql-apis-from-malicious-queries/</link>
            <pubDate>Mon, 12 Jun 2023 13:00:08 GMT</pubDate>
            <description><![CDATA[ Starting today, Cloudflare’s API Gateway can protect GraphQL APIs against malicious requests that may cause a denial of service to the origin ]]></description>
            <content:encoded><![CDATA[ <p></p><p>Starting today, Cloudflare’s API Gateway can protect GraphQL APIs against malicious requests that may cause a denial of service to the origin. In particular, <a href="https://www.cloudflare.com/application-services/products/api-gateway/">API Gateway</a> will now protect against two of the most common GraphQL abuse vectors: <b>deeply nested queries</b> and <b>queries that request more information</b> than they should.</p><p>Typical RESTful HTTP APIs contain tens or hundreds of endpoints. GraphQL APIs differ by typically only providing a single endpoint for clients to communicate with and offering highly flexible queries that can return variable amounts of data. While GraphQL’s power and usefulness rests on the flexibility to query an API about only the specific data you need, that same flexibility adds an increased risk of abuse. Abusive requests to a single GraphQL API can place disproportional load on the origin, abuse <a href="https://hygraph.com/blog/graphql-n-1-problem">the N+1 problem</a>, or exploit a recursive relationship between data dimensions. In order to add GraphQL security features to API Gateway, we needed to obtain visibility <i>inside</i> the requests so that we could apply different security settings based on request parameters. To achieve that visibility, we built our own GraphQL query parser. Read on to learn about how we built the parser and the security features it enabled.</p>
    <div>
      <h3>The power of GraphQL</h3>
      <a href="#the-power-of-graphql">
        
      </a>
    </div>
    <p>Unlike a REST API, where the API’s users are limited to what data they can query and change on a per-endpoint basis, a GraphQL API offers users the ability to query and change any data they wish with an open-ended, yet structured request to a single endpoint. This open-endedness makes GraphQL APIs very <a href="https://graphql.org/learn/">powerful</a>. Each user can query for a completely custom set of data and receive their custom response in a single HTTP request. Here are two example queries and their responses. These requests are typically sent via HTTP POST methods to an endpoint at /graphql.</p>
            <pre><code># A query asking for multiple nested subfields of the "hero" object. This query has a depth level of 2.
{
  hero {
    name
    friends {
      name
    }
  }
}

# The corresponding response.
{
  "data": {
    "hero": {
      "name": "R2-D2",
      "friends": [
        {
          "name": "Luke Skywalker"
        },
        {
          "name": "Han Solo"
        },
        {
          "name": "Leia Organa"
        }
      ]
    }
  }
}</code></pre>
            
            <pre><code># A query asking for just one subfield on the same "hero" object. This query has a depth level of 1.
{
  hero {
    name
  }
}

# The corresponding response.
{
  "data": {
    "hero": {
      "name": "R2-D2"
    }
  }
}</code></pre>
            <p>These custom queries give GraphQL endpoints <i>more flexibility than conventional REST endpoints</i>. But this flexibility also means GraphQL APIs can be subject to very different load or security risks based on the requests that they are receiving. For example, an attacker can request the exact same, valid data as a benevolent user would, but exploit the data’s self-referencing structure and ask that an origin return hundreds of thousands of rows replicated over and over again. Let’s consider an example, in which we operate a petitioning platform where our data model contains petitions and signers objects. With GraphQL, an attacker can, in a single request, query for a single petition, then for all people who signed that petition, then for all petitions each of those people have signed, then for all people that signed any of those petitions, then for all petitions that… you see where this is going!</p>
            <pre><code>query {
 petition(ID: 123) {
   signers {
     nodes {
       petitions {
         nodes {
           signers {
             nodes {
               petitions {
                 nodes {
                    ...
                 }
               }
             }
           }
         }
       }
     }
   }
 }
}</code></pre>
            <p>A rate limit won’t protect against such an attack because the entire query fits into a single request.</p><p>So how can we secure GraphQL APIs? There is little agreement in the industry around what makes a GraphQL endpoint secure. For some, this means rejecting invalid queries. Normally, an invalid query refers to a query that would fail to compile by a GraphQL server and not cause any substantial load on the origin, but would still add noise and error logs and reduce operational visibility. For others, this means creating complexity-based rate limits or perhaps flagging <a href="https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/">broken object-level authorization</a>. Still others want deeper visibility into query behavior and an ability to validate queries against a predefined schema.</p><p>When creating new features in API Gateway, we often start by providing deeper visibility for customers into their traffic behavior related to the feature in question. This way we create value from the large amount of data we see in the Cloudflare network, and can have conversations with customers where we ask: <i>“Now that you have these data insights, what actions would you like to take with them?”</i>. This process puts us in a good position to build a second, more actionable iteration of the feature.</p><p>We decided to follow the same process with GraphQL protection, with parsing GraphQL requests and gathering data as our first goal.</p>
    <div>
      <h3>Parsing GraphQL quickly</h3>
      <a href="#parsing-graphql-quickly">
        
      </a>
    </div>
    <p>As a starting point, we wanted to collect request query size and depth attributes. These attributes offer a surprising amount of insight into the query – if the query is requesting a single field at depth level 15, is it really innocuous or is it exploiting some recursive data relationship? if the query is asking for hundreds of fields at depth level 3, why wouldn’t it just ask for the entire object at level 2 instead?</p><p>To do this, we needed to parse queries without adding latency to incoming requests. We evaluated multiple open source GraphQL parsers and quickly realized that their performance would put us at the risk of adding hundreds of microseconds of latency to the request duration. Our goal was to have a p95 parsing time of under 50 microseconds. Additionally, the infrastructure we were planning to use to ship this functionality has a strict no-heap-allocation policy – this means that any memory allocated by a parser to process a request has to be amortized by being reused when parsing any subsequent requests. Parsing GraphQL in a no-allocation manner is not a fundamental technical requirement for us over the long-term, but it was a necessity if we wanted to build something quickly with confidence that the proof of concept will meet our performance expectations.</p><p>Meeting the latency and memory allocation constraints meant that we had to write a parser of our own. Building an entire abstract syntax tree of unpredictable structure requires allocating memory on the heap, and that’s what made conventional parsers unfit for our requirements. What if instead of building a tree, we processed the query in a streaming fashion, token by token? We realized that if we were to write our own GraphQL lexer that produces a list of GraphQL tokens (“comment”, “string”, “variable name”, “opening parenthesis”, etc.), we could use a number of heuristics to infer the query depth and size without actually building a tree or fully validating the query. Using this approach meant that we could deliver the new feature fast, both in engineering time and wall clock time – and, most importantly, visualize data insights for our customers.</p><p>To start, we needed to prepare GraphQL queries for parsing. <a href="https://graphql.org/learn/serving-over-http/">Most of the time</a>, GraphQL queries are delivered as <code>HTTP POST</code> requests with <code>application/json</code> or <code>application/graphql Content-Type</code>. Requests with <code>application/graphql</code> content type are easy to work with – they contain the raw query you can just parse. However, JSON-encoded queries present a challenge since JSON objects contain escaped characters – normally, any deserialization library will allocate new memory into which the raw string is copied with escape sequences removed, but we committed to allocating no memory, remember? So to parse GraphQL queries encoded in JSON fields, we used <a href="https://docs.rs/serde_json/latest/serde_json/value/struct.RawValue.html">serde RawValue</a> to locate the JSON field in which the escaped query was placed and then iterated over the constituent bytes one-by-one, feeding them into our tokenizer and removing escape sequences on the fly.</p><p>Once we had our query input ready, we built a simple Rust program that converts raw GraphQL input into a list of <a href="https://spec.graphql.org/October2021/#sec-Appendix-Grammar-Summary.Lexical-Tokens">lexical tokens according to the GraphQL grammar</a>. Tokenization is the first step in any parser – our insight was that this step was all we needed for what we wanted to achieve in the MVP.</p>
            <pre><code>mutation CreateMessage($input: MessageInput) {
    createMessage(input: $input) {
        id
    }
}</code></pre>
            <p>For example, the mutation operation above gets converted into the following list of tokens:</p>
            <pre><code>name
name
punctuator (
punctuator $
name
punctuator :
name
punctuator )
punctuator {
name
punctuator (
name
punctuator :
punctuator $
name
punctuator )
punctuator {
name
punctuator }
punctuator }</code></pre>
            <p>With this list of tokens available to us, we built our validation engine and added the ability to calculate query depth and size. Again, everything is done one-the-fly in a single pass. A limitation of this approach is that we can’t parse 100% of the requests – there are some syntactic features of GraphQL that we have to fail open on; however, a major advantage of this approach is its performance – in our initial trial run against a stream of 10s of thousands of requests per second, we achieved a p95 parsing time of 25 microseconds. This is a good starting point to collect some data and to prototype our first GraphQL security features.</p>
    <div>
      <h3>Getting started</h3>
      <a href="#getting-started">
        
      </a>
    </div>
    <p>Today, any API Gateway customer can use the Cloudflare GraphQL API to retrieve information about depth and size of GraphQL queries we see for them on the edge.</p><p>As an example, we’ve run the analysis below visualizing over 400,000 data points for query sizes and depths for a production domain utilizing API Gateway.</p><p>First let’s look at query sizes in our sample:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/5eeTSSluDMta6Plvi8qHZQ/568e15f9b4f325795f9d2511038a1707/image3-1.png" />
            
            </figure><p>It looks like queries almost never request more than 60 fields. Let’s also look at query depths:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/1kLstN02f8pItr1RHNyyiO/16acff492c433861d1bba2365ec6633e/image2-1.png" />
            
            </figure><p>It looks like queries are never more than seven levels deep.</p><p>These two insights can be converted into security rules: we added three new Wirefilter fields that API Gateway customers can use to protect their GraphQL endpoints:</p>
            <pre><code>1. cf.api_gateway.graphql.query_size
2. cf.api_gateway.graphql.query_depth
3. cf.api_gateway.graphql.parsed_successfully</code></pre>
            <p>For now, we recommend the use of <code>cf.api_gateway.graphql.parsed_successfully</code> in all rules. Rules created with the use of this field will be backwards compatible with future GraphQL protection releases.</p><p>If a customer feels that there is nothing out of the ordinary with the traffic sample and that it represents a meaningful amount of normal usage, they can manually create and deploy the following custom rule to log all queries that were parsed by Cloudflare and that look like outliers:</p>
            <pre><code>cf.api_gateway.graphql.parsed_successfully and
(cf.api_gateway.graphql.query_depth &gt; 7 or 
cf.api_gateway.graphql.query_size &gt; 60)</code></pre>
            <p>Learn more and run your own analysis with our <a href="https://developers.cloudflare.com/api-shield/security/graphql-protection/configure/">documentation</a>.</p>
    <div>
      <h3>What’s next?</h3>
      <a href="#whats-next">
        
      </a>
    </div>
    <p>We are already receiving feedback from our first customers and are planning out the next iteration of this feature. These are the features we will build next:</p><ul><li><p>Integrating GraphQL security with <a href="https://developers.cloudflare.com/waf/rate-limiting-rules/request-rate#complexity-based-rate-limiting">complexity-based rate limiting</a> such that we automatically calculate query <i>cost</i> and let customers rate limit eyeballs based on the total query execution cost the eyeballs use during their entire session.</p></li><li><p>Allowing customers to configure specifically which endpoints GraphQL security features run on.</p></li><li><p>Creating data insights on the relationship between query complexity and the time it takes the customer origin to respond to the query.</p></li><li><p>Creating automatic GraphQL threshold recommendations based on historical trends.</p></li></ul><p>If you’re an Enterprise customer that hasn't purchased API Gateway and you’re interested in protecting your GraphQL APIs today, you can get started by <a href="https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield">enabling the API Gateway trial</a> inside the Cloudflare Dashboard or by contacting your account manager. Check out our <a href="https://developers.cloudflare.com/api-shield/security/graphql-protection/">documentation</a> on the feature to get started once you have access.</p> ]]></content:encoded>
            <category><![CDATA[API Shield]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[API Security]]></category>
            <guid isPermaLink="false">3jtCfJe8BOPYKyIvFdXqhj</guid>
            <dc:creator>John Cosgrove</dc:creator>
            <dc:creator>Ilya Andreev</dc:creator>
        </item>
        <item>
            <title><![CDATA[Everything you might have missed during Security Week 2023]]></title>
            <link>https://blog.cloudflare.com/security-week-2023-wrap-up/</link>
            <pubDate>Mon, 20 Mar 2023 13:00:00 GMT</pubDate>
            <description><![CDATA[ Learn how Cloudflare made it easier to shift from protecting applications, to protecting employees, and making sure they are protected everywhere during Security Week 2023 ]]></description>
            <content:encoded><![CDATA[ <p></p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/60Kso4XsCtJn6Ye4Ukzr4T/d4344147b06e9c920babd4e0fa5f1968/Security-Week-2023-Hero-Dark-1.png" />
            
            </figure><p>Security Week 2023 is officially in the books. In our <a href="/welcome-to-security-week-2023/">welcome post last Saturday</a>, I talked about Cloudflare’s years-long evolution from protecting websites, to protecting applications, to protecting people. Our goal this week was to help our customers solve a broader range of problems, reduce external points of vulnerability, and make their jobs easier.</p><p>We announced 34 new tools and integrations that will do just that. Combined, these announcement will help you do five key things faster and easier:</p><ol><li><p>Making it easier to deploy and manage <a href="https://www.cloudflare.com/learning/security/glossary/what-is-zero-trust/">Zero Trust</a> everywhere</p></li><li><p>Reducing the number of third parties customers must use</p></li><li><p>Leverage machine learning to let humans focus on critical thinking</p></li><li><p>Opening up more proprietary Cloudflare threat intelligence to our customers</p></li><li><p>Making it harder for humans to make mistakes</p></li></ol><p>And to help you respond to the most current attacks in real time, we reported on how we’re seeing <a href="/how-sophisticated-scammers-and-phishers-are-preying-on-customers-of-silicon-valley-bank/">scammers use the Silicon Valley Bank news</a> to phish new victims, and what you can do to protect yourself.</p><p>In case you missed any of the announcements, take a look at the summary and navigation guide below.</p>
    <div>
      <h3>Monday</h3>
      <a href="#monday">
        
      </a>
    </div>
    
<table>
<thead>
  <tr>
    <th><span>Blog</span></th>
    <th><span>Summary</span></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/50-most-impersonated-brands-protect-phishing/"><span>Top phished brands and new phishing and brand protections</span></a><br /></td>
    <td><span>Today we have released insights from our global network on the top 50 brands used in phishing attacks coupled with the tools customers need to stay safer. Our new phishing and brand protection capabilities, part of Security Center, let customers better preserve brand trust by detecting and even blocking “confusable” and lookalike domains involved in phishing campaigns.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/stay-safe-phishing-attacks/"><span>How to stay safe from phishing</span></a></td>
    <td><span>Phishing attacks come in all sorts of ways to fool people. Email is definitely the most common, but there are others. Following up on our Top 50 brands in phishing attacks post, here are some tips to help you catch these scams before you fall for them.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/page-shield-positive-blocking-policies/"><span>Locking down your JavaScript: positive blocking with Page Shield policies</span></a></td>
    <td><span>Page Shield now ensures only vetted and secure JavaScript is being executed by browsers to stop unwanted or malicious JavaScript from loading to keep end user data safer. </span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/cloudflare-aegis/"><span>Cloudflare Aegis: dedicated IPs for Zero Trust migration</span></a><br /></td>
    <td><span>With Aegis, customers can now get dedicated IPs from Cloudflare we use to send them traffic. This allows customers to lock down services and applications at an IP level and build a protected environment that is application, protocol, and even IP-aware.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/mtls-workers/"><span>Mutual TLS now available for Workers</span></a></td>
    <td><span>mTLS support for Workers allows for communication with resources that enforce an mTLS connection. mTLS provides greater security for those building on Workers so they can identify and authenticate both the client and the server helps protect sensitive data.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/access-aegis-cni/"><span>Using Cloudflare Access with CNI</span></a></td>
    <td><span>We have introduced an innovative new approach to secure hosted applications via Cloudflare Access without the need for any installed software or custom code on application servers.</span></td>
  </tr>
</tbody>
</table>
    <div>
      <h3>Tuesday</h3>
      <a href="#tuesday">
        
      </a>
    </div>
    
<table>
<thead>
  <tr>
    <th><span>Blog </span></th>
    <th><span>Summary</span></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/descaler-program/"><span>No hassle migration from Zscaler to Cloudflare One with The Descaler Program</span></a></td>
    <td><span>Cloudflare is excited to launch the Descaler Program, a frictionless path to migrate existing Zscaler customers to Cloudflare One. With this announcement, Cloudflare is making it even easier for enterprise customers to make the switch to a </span><a href="http://staging.blog.mrk.cfdata.org/network-performance-update-cio-edition/"><span>faster</span></a><span>, simpler, and more agile foundation for security and network transformation.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/application-security-2023/"><span>The state of application security in 2023</span></a></td>
    <td><span>For Security Week 2023, we are providing updated insights and trends related to mitigated traffic, bot and API traffic, and <a href="https://www.cloudflare.com/zero-trust/solutions/account-takeover-prevention/">account takeover attacks</a>.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/zero-trust-signals-to-sumo-logic/"><span>Adding Zero Trust signals to Sumo Logic for better security insights</span></a></td>
    <td><span>Today we’re excited to announce the expansion of support for automated normalization and correlation of Zero Trust logs for </span><a href="https://developers.cloudflare.com/logs/about/"><span>Logpush</span></a><span> in Sumo Logic’s </span><a href="https://www.sumologic.com/solutions/cloud-siem-enterprise/"><span>Cloud SIEM</span></a><span>. Joint customers will reduce alert fatigue and accelerate the triage process by converging security and network data into high-fidelity insights.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/cloudflare-dlp-mip/"><span>Cloudflare One DLP integrates with Microsoft Information Protection labels</span></a></td>
    <td><a href="https://www.cloudflare.com/cloudflare-one/"><span>Cloudflare One</span></a><span> now offers Data Loss Prevention (DLP) detections for Microsoft Purview Information Protection labels. This extends the power of Microsoft’s labels to any of your corporate traffic in just a few clicks.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/scan-atlassian-casb/"><span>Scan and secure Atlassian with Cloudflare CASB</span></a></td>
    <td><span>We are unveiling two new integrations for Cloudflare CASB: one for Atlassian Confluence and the other for Atlassian Jira. Security teams can begin scanning for Atlassian- and Confluence-specific security issues that may be leaving sensitive corporate data at risk.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/cloudflare-ping/"><span>Zero Trust security with Ping Identity and Cloudflare Access</span></a></td>
    <td><span>Cloudflare Access and Ping Identity offer a powerful solution for organizations looking to implement Zero Trust security controls to protect their applications and data. Cloudflare is now offering </span><a href="https://developers.cloudflare.com/cloudflare-one/identity/idp-integration/pingone-oidc/"><span>full integration support</span></a><span>, so Ping Identity customers can easily integrate their identity management solutions with Cloudflare Access to provide a comprehensive security solution for their applications</span></td>
  </tr>
</tbody>
</table>
    <div>
      <h3>Wednesday</h3>
      <a href="#wednesday">
        
      </a>
    </div>
    
<table>
<thead>
  <tr>
    <th><span>Blog</span></th>
    <th><span>Summary</span></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/cloudflare-fraud-detection/"><span>Announcing Cloudflare Fraud Detection</span></a></td>
    <td><span>We are excited to announce Cloudflare Fraud Detection that will provide precise, easy to use tools that can be deployed in seconds to detect and categorize fraud such as fake account creation or card testing and fraudulent transactions. Fraud Detection will be in early access later this year, those interested </span><a href="https://www.cloudflare.com/lp/fraud-detection/"><span>can sign up here</span></a><span>. </span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/ml-api-discovery-and-schema-learning/"><span>Automatically discovering API endpoints and generating schemas using machine learning</span></a></td>
    <td><span>Customers can use these new features to enforce a positive security model on their API endpoints even if they have little-to-no information about their existing APIs today.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/api-sequence-analytics/"><span>Detecting API abuse automatically using sequence analysis</span></a><br /></td>
    <td><span>With our new Cloudflare Sequence Analytics for APIs, organizations can view the most important sequences of API requests to their endpoints to better understand potential abuse and where to apply protections first. </span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/threat-detection-machine-learning-models/"><span>Using the power of Cloudflare’s global network to detect malicious domains using machine learning</span></a></td>
    <td><span>Read our post on how we keep users and organizations safer with machine learning models that detect attackers attempting to evade detection with DNS tunneling and domain generation algorithms.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/waf-attack-score-for-business-plan/"><span>Announcing WAF Attack Score Lite and Security Analytics for business customers</span></a></td>
    <td><span>We are making the machine learning empowered WAF and Security analytics view available to our Business plan customers, to help detect and stop attacks before they are known.</span><br /></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/radar-url-scanner-early-access/"><span>Analyze any URL safely using the Cloudflare Radar URL Scanner</span></a></td>
    <td><span>We have made Cloudflare Radar’s newest free tool available, </span><a href="https://radar.cloudflare.com/scan"><span>URL Scanner</span></a><span>, providing an under-the-hood look at any webpage to make the Internet more transparent and secure for all.</span></td>
  </tr>
</tbody>
</table>
    <div>
      <h3>Thursday</h3>
      <a href="#thursday">
        
      </a>
    </div>
    
<table>
<thead>
  <tr>
    <th><span>Blog</span></th>
    <th><span>Summary</span></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/post-quantum-crypto-should-be-free/"><span>Post-quantum crypto should be free, so we’re including it for free, forever</span></a></td>
    <td><span>One of our core beliefs is that privacy is a human right. To achieve that right, we are announcing that our implementations of post-quantum cryptography will be available to everyone, free of charge, forever.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/kyber-isnt-broken/"><span>No, AI did not break post-quantum cryptography</span></a></td>
    <td><span>The recent news reports of AI cracking post-quantum cryptography are greatly exaggerated. In this blog, we take a deep dive into the world of side-channel attacks and how AI has been used for more than a decade already to aid it</span><span>.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/configurable-super-bot-fight-mode/"><span>Super Bot Fight Mode is now configurable</span></a><br /></td>
    <td><span>We are making Super Bot Fight Mode even more configurable with new flexibility to allow legitimate, automated traffic to access their site.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/ibm-keyless-bots/"><span>How Cloudflare and IBM partner to help build a better Internet</span></a></td>
    <td><span>IBM and Cloudflare continue to partner together to help customers meet the unique security, performance, resiliency and compliance needs of their customers through the addition of exciting new product and service offerings.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/protect-your-key-server-with-keyless-ssl-and-cloudflare-tunnel-integration/"><span>Protect your key server with Keyless SSL and Cloudflare</span></a><a href="http://staging.blog.mrk.cfdata.org/protect-your-key-server-with-keyless-ssl-and-cloudflare-tunnel-integration/"><span> </span></a><a href="http://staging.blog.mrk.cfdata.org/protect-your-key-server-with-keyless-ssl-and-cloudflare-tunnel-integration/"><span>Tunnel integration</span></a></td>
    <td><span>Customers will now be able to use our Cloudflare Tunnels product to send traffic to the key server through a secure channel, without publicly exposing it to the rest of the Internet.</span></td>
  </tr>
</tbody>
</table>
    <div>
      <h3>Friday</h3>
      <a href="#friday">
        
      </a>
    </div>
    
<table>
<thead>
  <tr>
    <th><span>Blog</span></th>
    <th><span>Summary</span></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/DMARC-Management"><span>Stop Brand Impersonation with Cloudflare DMARC Management</span></a><span> </span></td>
    <td><span>Brand impersonation continues to be a big problem globally. Setting SPF, DKIM and DMARC policies is a great way to reduce that risk, and protect your domains from being used in spoofing emails. But maintaining a correct SPF configuration can be very costly and time consuming, and that’s why we’re launching Cloudflare DMARC Management.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/how-we-built-dmarc-management"><span>How we built DMARC Management using Cloudflare Workers</span></a></td>
    <td><span>At Cloudflare, we use the Workers platform and our product stack to build new services. Read how we made the new DMARC Management solution entirely on top of our APIs.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/Knowbe4-emailsecurity-integration"><span>Cloudflare partners with KnowBe4 to equip organizations with real-time security coaching to avoid phishing attacks</span></a></td>
    <td><span>Cloudflare’s cloud email security solution now integrates with KnowBe4, allowing mutual customers to offer real-time coaching to employees when a phishing campaign is detected by Cloudflare.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/access-custom-pages"><span>Introducing custom pages for Cloudflare Access</span></a></td>
    <td><span>We are excited to announce new options to customize user experience in Access, including customizable pages including login, blocks and the application launcher.</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/network-performance-update-security-week-2023/"><span>Cloudflare Access is the fastest Zero Trust proxy</span></a></td>
    <td><span>Cloudflare Access is 75% faster than Netskope and 50% faster than Zscaler, and our network is faster than other providers in 48% of last mile networks.</span></td>
  </tr>
</tbody>
</table>
    <div>
      <h3>Saturday</h3>
      <a href="#saturday">
        
      </a>
    </div>
    
<table>
<thead>
  <tr>
    <th><span>Blog</span></th>
    <th><span>Summary</span></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/one-click-iso-27001-deployment"><span>One-click ISO 27001 certified deployment of Regional Services in the EU</span></a></td>
    <td><span>Cloudflare announces one-click ISO certified region, a super easy way for customers to limit where traffic is serviced to ISO 27001 certified data centers inside the European Union.</span><br /></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/account-security-analytics-and-events"><span>Account level Security Analytics and Security Events: better visibility and control over all account zones at once</span></a></td>
    <td><span>All WAF customers will benefit fromAccount Security Analytics and Events. This allows organizations to new eyes on your account in Cloudflare dashboard to give holistic visibility. No matter how many zones you manage, they are all there!</span></td>
  </tr>
  <tr>
    <td><a href="http://staging.blog.mrk.cfdata.org/access-wildcard-and-multi-hostname/"><span>Wildcard and multi-hostname support in Cloudflare Access</span></a><br /></td>
    <td><span>We are thrilled to announce the full support of wildcard and multi-hostname application definitions in Cloudflare Access. Until now, Access had limitations that restricted it to a single hostname or a limited set of wildcards</span></td>
  </tr>
</tbody>
</table>
    <div>
      <h3>Watch our Security Week sessions on Cloudflare TV</h3>
      <a href="#watch-our-security-week-sessions-on-cloudflare-tv">
        
      </a>
    </div>
    <div></div><p><a href="https://cloudflare.tv/shows/security-week">Watch all of the Cloudflare TV segments here</a>.</p>
    <div>
      <h3>What’s next?</h3>
      <a href="#whats-next">
        
      </a>
    </div>
    <p>While that’s it for Security Week 2023, you all know by now that Innovation weeks never end for Cloudflare. Stay tuned for a week full of new developer tools coming soon, and a week dedicated to making the Internet faster later in the year.</p> ]]></content:encoded>
            <category><![CDATA[Security Week]]></category>
            <category><![CDATA[Product News]]></category>
            <category><![CDATA[Security]]></category>
            <category><![CDATA[Zero Trust]]></category>
            <category><![CDATA[API Shield]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[API Security]]></category>
            <category><![CDATA[AI]]></category>
            <guid isPermaLink="false">7e7mRjiKo0kNNOmI4oz4YH</guid>
            <dc:creator>Reid Tatoris</dc:creator>
        </item>
        <item>
            <title><![CDATA[Detecting API abuse automatically using sequence analysis]]></title>
            <link>https://blog.cloudflare.com/api-sequence-analytics/</link>
            <pubDate>Wed, 15 Mar 2023 13:00:00 GMT</pubDate>
            <description><![CDATA[ Today, we're announcing Cloudflare Sequence Analytics for APIs. Using Sequence Analytics, Customers subscribed to API Gateway can view the most important sequences of API requests to their endpoints ]]></description>
            <content:encoded><![CDATA[ <p></p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/4ZIGEKXxAHQjkdhTmJIlI7/88561d87ef5b611280c21d6ca2cf3c5a/image1-26.png" />
            
            </figure><p>Today, we're announcing Cloudflare Sequence Analytics for APIs. Using Sequence Analytics, Customers subscribed to <a href="https://developers.cloudflare.com/api-shield/">API Gateway</a> can view the most important sequences of API requests to their endpoints. This new feature helps customers to <a href="https://www.cloudflare.com/learning/security/api/what-is-an-api-gateway/">apply protection</a> to the most important endpoints first.</p><p>What is a sequence? It is simply a time-ordered list of HTTP API requests made by a specific visitor as they browse a website, use a mobile app, or interact with a B2B partner via API. For example, a portion of a sequence made during a bank funds transfer could look like:</p>
<table>
<thead>
  <tr>
    <th><span>Order</span></th>
    <th><span>Method</span></th>
    <th><span>Path</span></th>
    <th><span>Description</span></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><span>1</span></td>
    <td><span>GET</span></td>
    <td><span>/api/v1/users/{user_id}/accounts</span></td>
    <td><span>user_id is the active user</span></td>
  </tr>
  <tr>
    <td><span>2</span></td>
    <td><span>GET</span></td>
    <td><span>/api/v1/accounts/{account_id}/balance</span></td>
    <td><span>account_id is one of the user’s accounts</span></td>
  </tr>
  <tr>
    <td><span>3</span></td>
    <td><span>GET</span></td>
    <td><span>/api/v1/accounts/{account_id}/balance</span></td>
    <td><span>account_id is a different account belonging to the user</span></td>
  </tr>
  <tr>
    <td><span>4</span></td>
    <td><span>POST</span></td>
    <td><span>/api/v1/transferFunds</span></td>
    <td><span>Containing a request body detailing an account to transfer funds from, an account to transfer funds to, and an amount of money to transfer</span></td>
  </tr>
</tbody>
</table><p>Why is it important to pay attention to sequences for API security? If the above API received requests for POST /api/v1/transferFunds without any of the prior requests, it would seem suspicious. Think about it: how would the API client know what the relevant account IDs are without listing them for the user? How would the API client know how much money is available to transfer? While this example may be obvious, the sheer number of API requests to any given production API can make it hard for human analysts to spot suspicious usage.</p><p>In security, one approach to defending against an untold number of threats that are impossible to screen by a team of humans is to create a <i>positive security model</i>. Instead of trying to block everything that could potentially be a threat, you allow all known good or benign traffic and block everything else by default.</p><p>Customers could already create positive security models with <a href="https://www.cloudflare.com/application-services/products/api-gateway/">API Gateway</a> in two main areas: <a href="https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/">volumetric abuse protection</a> and <a href="https://developers.cloudflare.com/api-shield/security/schema-validation/">schema validation</a>. Sequences will form the third pillar of a positive security model for API traffic. API Gateway will be able to enforce the precedence of endpoints in any given API sequence. By establishing precedence within an API sequence, API Gateway will log or block any traffic that doesn’t match expectations, reducing abusive traffic.</p>
    <div>
      <h3>Detecting abuse by sequence</h3>
      <a href="#detecting-abuse-by-sequence">
        
      </a>
    </div>
    <p>When attackers attempt to exfiltrate data in an abusive way, they rarely follow the patterns of expected API traffic. Attacks often use special software to <a href="https://owasp.org/www-community/Fuzzing">‘fuzz’</a> the API, sending several requests with different request parameters hoping to find unexpected responses from the API indicating opportunities to exfiltrate data. Attackers can also manually send requests to APIs that attempt to trick the API in performing unauthorized actions, like granting an attacker elevated privileges or access to data through a <a href="https://github.com/OWASP/API-Security/blob/master/2019/en/src/0xa1-broken-object-level-authorization.md">Broken Object Level Authentication attack</a>. Protecting APIs with rate limits is a common best practice; however, in both of the above examples attackers may deliberately execute request sequences slowly, in an attempt to thwart volumetric abuse detection.</p><p>Think of the sequence of requests above again, but this time imagine an attacker copying the legitimate funds transfer request and modifying the request payload in an attempt to trick the system:</p>
<table>
<thead>
  <tr>
    <th><span>Order</span></th>
    <th><span>Method</span></th>
    <th><span>Path</span></th>
    <th><span>Description</span></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><span>1</span></td>
    <td><span>GET</span></td>
    <td><span>/api/v1/users/{user_id}/accounts</span></td>
    <td><span>user_id is the active user</span></td>
  </tr>
  <tr>
    <td><span>2</span></td>
    <td><span>GET</span></td>
    <td><span>/api/v1/accounts/{account_id}/balance</span></td>
    <td><span>account_id is one of the user’s accounts</span></td>
  </tr>
  <tr>
    <td><span>3</span></td>
    <td><span>GET</span></td>
    <td><span>/api/v1/accounts/{account_id}/balance</span></td>
    <td><span>account_id is a different account belonging to the user</span></td>
  </tr>
  <tr>
    <td><span>4</span></td>
    <td><span>POST</span></td>
    <td><span>/api/v1/transferFunds</span></td>
    <td><span>Containing a request body detailing an account to transfer funds from, an account to transfer funds to, and an amount of money to transfer</span></td>
  </tr>
  <tr>
    <td><span>… attacker copies the request to a debugging tool like Postman …</span></td>
  </tr>
  <tr>
    <td><span>5</span></td>
    <td><span>POST</span></td>
    <td><span>/api/v1/transferFunds</span></td>
    <td><span>Attacker has modified the POST body to try and trick the API</span></td>
  </tr>
  <tr>
    <td><span>6</span></td>
    <td><span>POST</span></td>
    <td><span>/api/v1/transferFunds</span></td>
    <td><span>A further modified POST body to try and trick the API</span></td>
  </tr>
  <tr>
    <td><span>7</span></td>
    <td><span>POST</span></td>
    <td><span>/api/v1/transferFunds</span></td>
    <td><span>Another</span><span>, further modified POST body to try and trick the API</span></td>
  </tr>
</tbody>
</table><p>If the customer knew beforehand that the funds transfer endpoint was critical to protect and only occurred once during a sequence, they could write a rule to ensure that it was never called twice in a row and a GET /balance always preceded a POST /transferFunds. But without prior knowledge of which endpoint sequences are critical to protect, how would the customer know which rules to define? A low rate limit is too risky, since an API user might legitimately have a few funds transfer requests to perform in a short amount of time. In the present reality there are few tools to prevent this type of abuse, and most customers are left with reactive efforts to clean up abuse with their application teams and fraud departments after it’s happened.</p><p>Ultimately, we believe that providing our customers with the ability to define positive security models on API request sequences requires a three-pronged approach:</p><ol><li><p><b>Sequence Analytics</b>: Determining which sequences of API requests occurred and when, as well as summarizing the data into readily understandable form.</p></li><li><p><b>Sequence Abuse Detection</b>: Identifying which sequences of API requests are likely of benign or malicious origin.</p></li><li><p><b>Sequence Mitigation:</b> Identifying relevant rules on sequences of API requests for deciding which traffic to allow or block.</p></li></ol>
    <div>
      <h3>Challenges of sequence creation</h3>
      <a href="#challenges-of-sequence-creation">
        
      </a>
    </div>
    <p>Sequence Analytics presents some difficult technical challenges, because sessions may be long-lived and may consist of many requests. As a result, it is not sufficient to define sequences by session identifier alone. Instead, it was necessary for us to develop a solution capable of automatically identifying multiple sequences which occur within a given session. Additionally, since important sequences are not necessarily characterized by volume alone and the set of possible sequences is large, it was necessary to develop a solution capable of identifying <i>important</i> sequences, as opposed to simply surfacing <i>frequent</i> sequences.</p><p>To help illustrate these challenges for the example of api.cloudflare.com, we can group API requests by session and plot the number of distinct sequences versus sequence length:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/3AJLBVYJl3ApceVT8ubl7v/995a6548852547fb31e6e9d6a5c4b917/unnamed-1.png" />
            
            </figure><p>The plot is based on a one hour snapshot comprising approximately 88,000 sessions and 260 million API requests, with 301 distinct API endpoints. We process the data by applying a fixed-length sliding window to each session, then we count the total number of different fixed-length sequences (‘n-grams’) that we observe as a result of applying the sliding window. The plot displays results for a window size (‘n-gram length’) varying between 1 and 10 requests. The number of distinct sequences ranges from 301 (for a window size of 1 request) to approximately 780,000 (for a window size of 10 requests). Based on the plot, we observe a large number of possible sequences which grows with sequence length: As we increase the sliding window size, we see an increasingly large amount of different sequences in the sample. The smooth trend can be explained by the fact that we apply a sliding window (sessions may themselves contain many sequences) in combination with many long sessions relative to the sequence length.</p><p>Given the large number of possible sequences, trying to find abusive sequences is a ‘needles in a haystack’ situation.</p>
    <div>
      <h3>Introducing Sequence Analytics</h3>
      <a href="#introducing-sequence-analytics">
        
      </a>
    </div>
    <p>Here is a screenshot from the API Gateway dashboard highlighting Sequence Analytics:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/XNYHZ4fxireN81jqHtCs5/401355249971c341845feed2f68445a0/image2-14.png" />
            
            </figure><p>Let’s break down the new functionality seen in the screenshot.</p><p>API Gateway intelligently determines sequences of requests made by your API consumers using the methods described earlier in this article. API Gateway scores sequences by a metric we call Correlation Score. Sequence Analytics displays the top 20 sequences by highest correlation score, and we refer to these as your most important sequences. High-importance sequences contain API requests which are likely to occur together in order.</p><p>You should inspect each of your sequences to understand their correlation scores. High correlation score sequences may consist of rarely used endpoints (potentially anomalous user behavior) as well as commonly used endpoints (likely benign user behavior). Since the endpoints found in these sequences commonly occur together, they represent true usage patterns of your API. You should apply all possible API Gateway protections to these endpoints (<a href="https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/">rate limiting suggestions</a>, <a href="https://developers.cloudflare.com/api-shield/security/schema-validation/">Schema Validation</a>, <a href="https://developers.cloudflare.com/api-shield/security/jwt-validation/">JWT Validation</a>, and <a href="https://developers.cloudflare.com/api-shield/security/mtls/">mTLS</a>) and check their specific endpoint order with your development team.</p><p>We know customers want to explicitly set allowable behavior on their APIs beyond the active protections offered by API Gateway today. Coming soon, we’re releasing sequence precedence rules and enabling the ability to block requests based on those rules. The new sequence precedence rules will allow customers to specify the exact order of allowable API requests, bringing yet another way of establishing a positive security model to <a href="https://www.cloudflare.com/application-services/solutions/api-security/">protect your API against unknown threats</a>.</p>
    <div>
      <h3>How to get started</h3>
      <a href="#how-to-get-started">
        
      </a>
    </div>
    <p>All API Gateway customers now have access to Sequence Analytics. Navigate to a zone in the Cloudflare dashboard, then click the Security tab &gt; API Gateway tab &gt; Sequences tab. You’ll see the most important sequences that your API consumers request.</p><p>Enterprise customers that haven’t purchased API Gateway can get started by <a href="https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield">enabling the API Gateway trial</a> inside the Cloudflare Dashboard or contacting their account manager.</p>
    <div>
      <h3>What’s next</h3>
      <a href="#whats-next">
        
      </a>
    </div>
    <p>Sequence-based detection is a powerful and unique capability that unlocks many new opportunities to identify and stop attacks. As we fine-tune the methods of identifying these sequences and shipping them to our global network, we will release custom sequence matching and real-time mitigation features at a future date. We will also ensure you have the actionable intelligence to take back to your team on who the API users were that attempted to request sequences that don’t match your policy.</p> ]]></content:encoded>
            <category><![CDATA[Security Week]]></category>
            <category><![CDATA[API Shield]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[API Security]]></category>
            <category><![CDATA[AI]]></category>
            <guid isPermaLink="false">1BliBrtxZ4mEP2GAGJ02Qn</guid>
            <dc:creator>John Cosgrove</dc:creator>
            <dc:creator>Peter Foster</dc:creator>
        </item>
        <item>
            <title><![CDATA[Automatically discovering API endpoints and generating schemas using machine learning]]></title>
            <link>https://blog.cloudflare.com/ml-api-discovery-and-schema-learning/</link>
            <pubDate>Wed, 15 Mar 2023 13:00:00 GMT</pubDate>
            <description><![CDATA[ Today we’re announcing that Cloudflare can now automatically discover all API endpoints and learn API schemas for all of our API Gateway customers ]]></description>
            <content:encoded><![CDATA[ <p></p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/O4mCKw9fBP5rNhxrGj3NP/e4439b1f3cfd0f4b0674c8be82e494e3/image6-6.png" />
            
            </figure><p>Cloudflare now automatically discovers all API endpoints and learns API schemas for all of our <a href="https://www.cloudflare.com/application-services/products/api-gateway/">API Gateway</a> customers. Customers can use these new features to enforce a positive security model on their API endpoints even if they have little-to-no information about their existing APIs today.</p><p>The first step in <a href="https://www.cloudflare.com/application-services/solutions/api-security/">securing your APIs</a> is knowing your API hostnames and endpoints. We often hear that customers are forced to start their API cataloging and management efforts with something along the lines of “<i>we email around a spreadsheet and ask developers to list all their endpoints</i>”.</p><p>Can you imagine the problems with this approach? Maybe you have seen them first hand. The “email and ask” approach creates a point-in-time inventory that is likely to change with the next code release. It relies on tribal knowledge that may disappear with people leaving the organization. Last but not least, it is susceptible to human error.</p><p>Even if you had an accurate API inventory collected by group effort, validating that API was being used as intended by enforcing an API schema would require even more collective knowledge to build that schema. Now, API Gateway’s new API Discovery and Schema Learning features combine to <a href="https://www.cloudflare.com/learning/security/api/what-is-an-api-gateway/">automatically protect APIs</a> across the Cloudflare global network and remove the need for manual <a href="https://www.cloudflare.com/learning/learning/security/api/what-is-api-discovery/">API discovery</a> and schema building.</p>
    <div>
      <h2>API Gateway discovers and protects APIs</h2>
      <a href="#api-gateway-discovers-and-protects-apis">
        
      </a>
    </div>
    <p>API Gateway discovers <a href="https://www.cloudflare.com/learning/security/api/what-is-an-api/">APIs</a> through a feature called API Discovery. Previously, API Discovery used customer-specific session identifiers (HTTP headers or cookies) to identify API endpoints and display their analytics to our customers.</p><p>Doing discovery in this way worked, but it presented three drawbacks:</p><ol><li><p>Customers had to know which header or cookie they used in order to delineate sessions. While session identifiers are common, finding the proper token to use can take time.</p></li><li><p>Needing a session identifier for API Discovery precluded us from monitoring and reporting on completely unauthenticated APIs. Customers today still want visibility into session-less traffic to ensure all API endpoints are documented and that abuse is at a minimum.</p></li><li><p>Once the session identifier was input into the dashboard, customers had to wait up to 24 hours for the Discovery process to complete. Nobody likes to wait.</p></li></ol><p>While this approach had drawbacks, we knew we could quickly deliver value to customers by starting with a session-based product. As we gained customers and passed more traffic through the system, we knew our new labeled data would be extremely useful to further build out our product. If we could train a <a href="https://www.cloudflare.com/learning/ai/what-is-machine-learning/">machine learning model</a> with our existing API metadata and the new labeled data, we would no longer need a session identifier to pinpoint which endpoints were for APIs. So we decided to build this new approach.</p><p>We took what we learned from the session identifier-based data and built a machine learning model to uncover all API traffic to a domain, regardless of session identifier. With our new Machine Learning-based API Discovery, Cloudflare continually discovers all API traffic routed through our network without any prerequisite customer input. With this release, API Gateway customers will be able to get started with API Discovery faster than ever, and they’ll uncover unauthenticated APIs that they could not discover before.</p><p>Session identifiers are still important to API Gateway, as they form the basis of our volumetric abuse prevention <a href="https://developers.cloudflare.com/api-shield/security/volumetric-abuse-detection/">rate limits</a> as well as our <a href="/api-sequence-analytics/">Sequence Analytics</a>. See more about how the new approach performs in the “How it works” section below.</p>
    <div>
      <h3>API Protection starting from nothing</h3>
      <a href="#api-protection-starting-from-nothing">
        
      </a>
    </div>
    <p>Now that you’ve found new APIs using API Discovery, how do you protect them? To defend against attacks, API developers must know exactly how they expect their APIs to be used. Luckily, developers can programmatically generate an API schema file which codifies acceptable input to an API and upload that into API Gateway’s <a href="https://developers.cloudflare.com/api-shield/security/schema-validation/">Schema Validation</a>.</p><p>However, we already talked about how many customers can't find their APIs as fast as their developers build them. When they do find APIs, it’s very difficult to accurately build a unique OpenAPI schema for each of potentially hundreds of API endpoints, given that security teams seldom see more than the HTTP request method and path in their logs.</p><p>When we looked at API Gateway’s usage patterns, we saw that customers would discover APIs but almost never enforce a schema. When we ask them ‘why not?’ the answer was simple: “<i>Even when I know an API exists, it takes so much time to track down who owns each API so that they can provide a schema. I have trouble prioritizing those tasks higher than other must-do security items.</i>” The lack of time and expertise was the biggest gap in our customers enabling protections.</p><p>So we decided to close that gap. We found that the same learning process we used to discover API endpoints could then be applied to endpoints once they were discovered in order to automatically learn a schema. Using this method <b><i>we can now generate an OpenAPI formatted schema for every single endpoint we discover, in real time</i></b>. We call this new feature Schema Learning. Customers can then upload that Cloudflare-generated schema into Schema Validation to enforce a positive security model.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/6VpHCVozyIsmpo7qSr6mTq/6193978955979c057b25a8f42b9d67d6/Schema-Learning-Flow.png" />
            
            </figure>
    <div>
      <h2>How it works</h2>
      <a href="#how-it-works">
        
      </a>
    </div>
    
    <div>
      <h3>Machine learning-based API discovery</h3>
      <a href="#machine-learning-based-api-discovery">
        
      </a>
    </div>
    <p>With RESTful APIs, requests are made up of different HTTP methods and paths. Take for example the <a href="https://developers.cloudflare.com/api/">Cloudflare API</a>. You’ll notice a common trend with the paths that might make requests to this API stand out amongst requests to this blog: API requests all start with /client/v4 and continue with the service name, a unique identifier, and sometimes service feature names and further identifiers.</p><p>How could we easily identify API requests? At first glance, these requests seem easy to programmatically discover with a heuristic like “path starts with /client”, but the core of our new Discovery contains a machine-learned model that powers a classifier that scores HTTP transactions. If API paths are so structured, why does one need machine-learning for this and can’t one just use some simple heuristic?</p><p>The answer boils down to the question: what actually constitutes an API request and how does it differ from a non-API request? Let’s look at two examples.</p><p>Like the Cloudflare API, many of our customers’ APIs follow patterns such as prefixing the path of their API request with an “api” identifier and a version, for example:  <i>/api/v2/user/7f577081-7003-451e-9abe-eb2e8a0f103d.</i></p><p>So just looking for “api” or a version in the path is already a pretty good heuristic that tells us this is very likely part of an API, but it is unfortunately not always as easy.</p><p>Let’s consider two further examples, /<i>users/7f577081-7003-451e-9abe-eb2e8a0f103d.jpg</i> and /<i>users/7f577081-7003-451e-9abe-eb2e8a0f103d,</i> both just differ in a .jpg extension. The first path could just be a static resource like the thumbnail of a user. The second path does not give us a lot of clues just from the path alone.</p><p>Manually crafting such heuristics quickly becomes difficult. While humans are great at finding patterns, building heuristics is challenging considering the scale of the data that Cloudflare sees each day. As such, we use machine learning to automatically derive these heuristics such that we know that they are reproducible and adhere to a certain accuracy.</p><p>Input to the training are features of HTTP request/response samples such as the content-type or file extension that we collected through the session identifiers-based Discovery mentioned earlier. Unfortunately, not everything that we have in this data is clearly an API. Additionally, we also need samples that represent non-API traffic. As such, we started out with the session-identifier Discovery data, manually cleaned it up and derived further samples of non-API traffic. We took great care in trying to not overfit the model to the data. That is, we want that the model generalizes beyond the training data.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/360Ff2sU2vH0xHRTwQ1a1i/9acd901bac12dd2e228f123904e1322d/ML-Discovery-Flow.png" />
            
            </figure><p>To train the model, we’ve used the <a href="/cloudflare-bot-management-machine-learning-and-more/">CatBoost library</a> for which we already have a good chunk of expertise as it also powers our <a href="/machine-learning-mobile-traffic-bots/">Bot Management ML-models</a>. In a simplification, one can regard the resulting model as a flow chart that tells us which conditions we should check after another, for example: if the path contains “api” then also check if there is no file extension and so forth. At the end of this flowchart is a score that tells us the likelihood that a HTTP transaction belongs to an API.</p><p>Given the trained model, we can thus input features of HTTP request/responses that run through the Cloudflare network and calculate the likelihood that this HTTP transaction belongs to an API or not. Feature extraction and model scoring is done in Rust and takes only a couple of microseconds on our global network. Since Discovery sources data from our powerful <a href="/http-analytics-for-6m-requests-per-second-using-clickhouse/">data pipeline</a>, it is not actually necessary to score <i>each</i> transaction. We can reduce the load on our servers by only scoring those transactions that we know will end up in our data pipeline to begin with thus saving CPU time and allowing the feature to be cost effective.</p><p>With the classification results in our data pipeline, we can use the same <a href="/api-abuse-detection/">API Discovery mechanism</a> that we’ve been using for the session identifier-based discovery. This existing system works great and allows us to reuse code efficiently. It also aided us when comparing our results with the session identifier-based Discovery, as the systems are directly comparable.</p><p>For API Discovery results to be useful, Discovery’s first task is to simplify the unique paths we see into variables. We’ve <a href="/api-abuse-detection/">talked about</a> this before. It is not trivial to deduce the various different identifier schemes that we see across the global network, especially when sites use custom identifiers beyond a straightforward GUID or integer format. API Discovery aptly normalizes paths containing variables with the help of a few different variable classifiers and supervised learning.</p><p>Only after normalizing paths are the Discovery results ready for our users to use in a straightforward fashion.</p>
    <div>
      <h3>The results: hundreds of found endpoints per customer</h3>
      <a href="#the-results-hundreds-of-found-endpoints-per-customer">
        
      </a>
    </div>
    <p>So, how does ML Discovery compare to the session identifier-based Discovery which relies on headers or cookies to tag API traffic?</p><p>Our expectation is that it detects a very similar set of endpoints. However, in our data we knew there would be two gaps. First, we sometimes see that customers are not able to cleanly dissect only API traffic using session identifiers. When this happens, Discovery surfaces non-API traffic. Second, since we required session identifiers in the first version of API Discovery, endpoints that are not part of a session (e.g. login endpoints or unauthenticated endpoints) were conceptually not discoverable.</p><p>The following graph shows a histogram of the number of endpoints detected on customer domains for both discovery variants.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/2B3SRaTlzY9IeP14TiJmJt/ec42e3ecc5072fc6bd6f839ea6414a18/imageLikeEmbed.png" />
            
            </figure><p>From a bird's eye perspective, the results look very similar, which is a good indicator that ML Discovery performs as it is supposed to. There are some differences already visible in this plot, which is also expected since we’ll also discover endpoints that are conceptually not discoverable with just a session identifier. In fact, if we take a closer look at a domain-by-domain comparison we see that there is no change for roughly ~46% of the domains. The next graph compares the difference (by percent of endpoints) between session-based and ML-based discovery:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/5xgilUYXsRSsK0szWTUE4Y/663978d4aa8a919010c024b5d2bea3bb/imageLikeEmbed--1-.png" />
            
            </figure><p>For ~15% of the domains, we see an increase in endpoints between 1 and 50, and for ~9%, we see a similar reduction. For ~28% of the domains, we find more than 50 additional endpoints.</p><p>These results highlight that ML Discovery is able to surface additional endpoints that have previously been flying under the radar, and thus expands the set tools API Gateway offers to help bring order to your API landscape.</p>
    <div>
      <h3>On-the-fly API protection through API schema learning</h3>
      <a href="#on-the-fly-api-protection-through-api-schema-learning">
        
      </a>
    </div>
    <p>With API Discovery taken care of, how can a practitioner protect the newly discovered endpoints? We already looked at the API request metadata, so now let’s look at the API request body. The compilation of all expected formats for all API endpoints of an API is known as an API schema. API Gateway’s Schema Validation is a great way to protect against <a href="https://github.com/OWASP/API-Security">OWASP Top 10 API attacks</a>, ensuring the body, path, and query string of a request contains the expected information for that API endpoint in an expected format. But what if you don’t know the expected format?</p><p>Even if the schema of a specific API is not known to a customer, the clients using this API will have been programmed to mostly send requests that conform to this unknown schema (or they would not be able to successfully query the endpoint). Schema Learning makes use of this fact and will look at successful requests to this API to reconstruct the input schema automatically for the customer. As an example, an API might expect the user-ID parameter in a request to have the form <i>id12345-a</i>. Even if this expectation is not explicitly stated, clients that want to have a successful interaction with the API will send user-IDs in this format.</p><p>Schema Learning first identifies all recent successful requests to an API-endpoint, and then parses the different input parameters for each request according to their position and type. After parsing all requests, Schema Learning looks at the different input values for each position and identifies which characteristics they have in common. After verifying that all observed requests share these commonalities, Schema Learning creates an input schema that restricts input to comply with these commonalities and that can directly be used for Schema Validation.</p><p>To allow for more accurate input schemas, Schema Learning identifies when a parameter can receive different types of input. Let's say you wanted to write an OpenAPIv3 schema file and manually observe in a small sample of requests that a query parameter is a unix timestamp. You write an API schema that forces that query parameter to be an integer greater than the start of last year's unix epoch. If your API also allowed that parameter in ISO 8601 format, your new rule would create false positives when the differently formatted (yet valid) parameter hit the API. Schema Learning automatically does all this heavy lifting for you and catches what manual inspection can't.</p><p>To prevent false positives, Schema Learning performs a statistical test on the distribution of these values and only writes the schema when the distribution is bounded with high confidence.</p><p>So how well does it work? Below are some statistics about the parameter types and values we see:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/76Sum5LAwABwVzNQqAjyIZ/8dfa9adfce34f3d7bdb871d4e17b9fc8/imageLikeEmbed--2-.png" />
            
            </figure><p>Parameter learning classifies slightly more than half of all parameters as strings, followed by integers which make up almost a third. The remaining 17% are made up of arrays, booleans, and number (float) parameters, while object parameters are seen more rarely in the path and query.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/4F7YFE3mJGLcJnFo2crtSU/6fba9b4f4cdf54bc17f659e3f2978aa7/imageLikeEmbed--3-.png" />
            
            </figure><p>The number of parameters in the path is usually very low, with 94% of all endpoints seeing at most one parameter in their path.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/4z6BUn5ZAabsQqscDeHaUx/d2a883f1eb8255deee3c459d7a5c3891/imageLikeEmbed--4-.png" />
            
            </figure><p>For the query, we do see a lot more parameters, sometimes reaching 50 different parameters for one endpoint!</p><p>Parameter learning is able to estimate numeric constraints with 99.9% confidence for the majority of parameters observed. These constraints can either be a maximum/minimum on the value, length, or size of the parameter, or a limited set of unique values that a parameter has to take.</p>
    <div>
      <h2>Protect your APIs in minutes</h2>
      <a href="#protect-your-apis-in-minutes">
        
      </a>
    </div>
    <p>Starting today, all API Gateway customers can now discover and protect APIs in just a few clicks, even if you're starting with no previous information. In the <a href="https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield">Cloudflare dash</a>, click into API Gateway and on to the <a href="https://developers.cloudflare.com/api-shield/security/api-discovery/">Discovery</a> tab to observe your discovered endpoints. These endpoints will be immediately available with no action required from you. Then, add relevant endpoints from Discovery into <a href="https://developers.cloudflare.com/api-shield/management-and-monitoring/">Endpoint Management</a>. Schema Learning runs automatically for all endpoints added to Endpoint Management. After 24 hours, export your learned schema and upload it into <a href="https://developers.cloudflare.com/api-shield/security/schema-validation/">Schema Validation</a>.</p><p>Enterprise customers that haven’t purchased API Gateway can get started by <a href="https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield">enabling the API Gateway trial</a> inside the Cloudflare Dashboard or contacting their account manager.</p>
    <div>
      <h2>What’s next</h2>
      <a href="#whats-next">
        
      </a>
    </div>
    <p>We plan to enhance Schema Learning by supporting more learned parameters in more formats, like POST body parameters with both JSON and URL-encoded formats as well as header and cookie schemas. In the future, Schema Learning will also notify customers when it detects changes in the identified API schema and present a refreshed schema.</p><p>We’d like to hear your feedback on these new features. Please direct your feedback to your account team so that we can prioritize the right areas of improvement. We look forward to hearing from you!</p> ]]></content:encoded>
            <category><![CDATA[Security Week]]></category>
            <category><![CDATA[API Shield]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[API Security]]></category>
            <category><![CDATA[AI]]></category>
            <guid isPermaLink="false">32vTIN2aiM5jMf0B8KBeqW</guid>
            <dc:creator>John Cosgrove</dc:creator>
            <dc:creator>Jan Rüth</dc:creator>
            <dc:creator>Henry Clausen</dc:creator>
        </item>
        <item>
            <title><![CDATA[Welcome to Security Week 2023]]></title>
            <link>https://blog.cloudflare.com/welcome-to-security-week-2023/</link>
            <pubDate>Sun, 12 Mar 2023 17:00:00 GMT</pubDate>
            <description><![CDATA[ Welcome to Security Week 2023. This week we’ll demonstrate how Cloudflare is making it as easy as possible to shift from protecting applications, to protecting employees, and making sure they are protected everywhere. ]]></description>
            <content:encoded><![CDATA[ <p></p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/1lPfiLSeLNNWZDu6MCdBQH/b96f6caacaa853ff16fe6eed1dfc5a43/image1-8.png" />
            
            </figure><p>Last month I had the chance to attend a dinner with 56 <a href="https://www.cloudflare.com/ciso/">CISOs</a> and CSOs across a range of banking, gaming, <a href="https://www.cloudflare.com/ecommerce/">ecommerce</a>, and retail companies. We rotated between tables of eight people and talked about the biggest challenges those in the group were facing, and what they were most worried about around the corner. We talk to customers every day at Cloudflare, but this was a unique opportunity to listen to customers (and non-customers) <i>talk to each other</i>. It was a fascinating evening and a few things stood out.</p><p>The common thread that dominated the discussions was “how do I convince my business and product teams to do the things I want them to”. Surprisingly little time was spent on specific technical challenges. No one brought up a concern about recent <a href="https://www.malwarebytes.com/blog/threat-intelligence/2023/02/multilingual-skimmer-fingerprints-users-via-cloudflare-endpoint-api">advanced mage cart skimmers</a>, or about protecting their new GraphQL APIs, or how to secure two different cloud vendors at once, or about the <a href="/ddos-threat-report-2022-q4/">size of DDoS attacks</a> consistently getting larger. Over and over again the conversation came back to struggles with getting humans to do the secure thing, or to not do the insecure thing.</p><p>This instantly brought to mind a major <a href="/2022-07-sms-phishing-attacks/">phishing attack that Cloudflare was able to thwart</a> last August. The attack was extremely sophisticated, using targeted text messages and an extremely professional impersonation of our Okta login page. Cloudflare did have individual employees fall for the phishing messages, because we are made up of a team of humans who are human. But we were able to thwart the attack through our own use of Cloudflare One products, and physical security keys issued to every employee that are required to access all our applications. The attacker was able to obtain compromised username and password credentials, but they could not get past the hard key requirement to log in. In 2023 phishing attacks are only getting <a href="https://www.cpomagazine.com/cyber-security/reddit-confirmed-a-security-breach-after-a-sophisticated-phishing-attack/">more frequent</a>.</p><p>Today's security challenges are often a case of having the right tools deployed to <i>prevent people from making mistakes</i>. Last year when we kicked off Security Week, we talked about making a <a href="/welcome-security-week-2022/">shift from protecting websites, to protecting applications</a>. Today, the shift is from protecting applications, to protecting employees, and making sure they are protected everywhere. Just a few weeks ago, the White House released a new national cybersecurity strategy directing all agencies to “<i>implement multi-factor authentication,</i> <a href="https://www.whitehouse.gov/briefing-room/statements-releases/2023/03/02/fact-sheet-biden-harris-administration-announces-national-cybersecurity-strategy/"><i>gain visibility into their entire attack surface</i></a><i>, manage authorization and access, and adopt cloud security tools</i>”. Over the next six days you’ll read more than 30 announcements that will make it as easy as possible to do just that.</p><p>Welcome to Security Week 2023.</p>
    <div>
      <h3>“The more tools you use the less secure you are”</h3>
      <a href="#the-more-tools-you-use-the-less-secure-you-are">
        
      </a>
    </div>
    <p>This was a direct quote from the CISO of a large online gaming platform. Adding more vendors might seem like you are adding layers of security, but you do also open up avenues for risk. First, every third party you add by definition adds another potential vulnerability. The <a href="https://blog.lastpass.com/2022/12/notice-of-recent-security-incident/">recent LastPass breach</a> is a perfect example. Attackers gained access to a cloud storage service, which gave them information they used in a secondary attack to phish an employee. Second, more tools means more complexity. More systems to log into, more dashboards to check. If information is spread across multiple systems you are more likely to miss important changes. Third, the more tools you use, the less likely it is that anyone is able to master them all. If you need the person who knows the application security tool, and the person who knows the <a href="https://www.cloudflare.com/learning/security/what-is-siem/">SIEM</a>, and the person who knows the access tool to coordinate on every potential vulnerability, things will get lost in translation. Complexity is the enemy of security. Fourth, adding more tools can add a false sense of security. Simply adding a new tool can give the impression you’ve added defense in depth. But that tool only adds protection if it works, if it's configured properly, and if people actually use it.</p><p>This week, you will hear about all of the initiatives we’ve been working on to help you solve this problem. We will announce multiple integrations that make it easier for you to <b><i>deploy and manage Zero Trust anywhere</i></b>, across multiple platforms, but all within the Cloudflare dashboard. We’re also extending our proven detection capabilities into new areas that will help you solve problems you couldn’t solve before, and thus allow you to get rid of additional vendors. And we’ll announce a brand new migration tool that makes it dead simple to move from those other vendors to Cloudflare.</p>
    <div>
      <h3>Leverage machine learning to let humans focus on critical thinking</h3>
      <a href="#leverage-machine-learning-to-let-humans-focus-on-critical-thinking">
        
      </a>
    </div>
    <p>We all hear machine learning thrown around as a buzzword too often, but it boils down to this: computers are really good at finding patterns. When we train them on what a good pattern looks like, they can spot them really well, and spot the outliers. Humans are great at finding patterns too. But it takes us a long time, and any time we spend finding patterns distracts us from the thing that even the best AI or ML model still can’t do: critical thinking. By using machine learning to find these good and bad patterns, you can optimize the time of your most valuable people. Rather than searching for exceptions, they can focus on only those exceptions, and use their wisdom to make the hard decisions about what to do next.</p><p>Cloudflare has used machine learning to catch DDoS attacks, malicious bots, and malicious web traffic. We were able to do this differently from others because we built a unique network where we run all of our code at every single data center, on every single machine. Since we have a massive global network that is close to end users, we can run machine learning close to those users, unlike competitors who have to use centralized data centers. The result is a machine learning pipeline that runs inference in a few microseconds. That unique speed is an advantage for our customers, one we now use to run inference more than 40 million times every second.</p><p>This week, we have an entire day focused on how we are using that machine learning pipeline to build new models that will allow you to find new patterns, like fraud and API endpoints.</p>
    <div>
      <h3>Our intelligence is your intelligence</h3>
      <a href="#our-intelligence-is-your-intelligence">
        
      </a>
    </div>
    <p>In June <a href="/introducing-cloudforce-one-threat-operations-and-threat-research/">we announced Cloudforce One</a>, the first step in our threat operations team dedicated to turning the intelligence we gather from handling nearly <a href="https://w3techs.com/technologies/overview/proxy">20%</a> of Internet traffic into actionable insights. Since that launch, we’ve heard customers ask us to do more with those insights and give them easy buttons and products to take the appropriate action on their behalf. This week you’ll read multiple announcements on new ways that you can view and take action on unique Cloudflare threat intelligence. We’ll also be announcing multiple new reporting views, like being able to view more data at an account level so you can have one single lens into security trends across your entire organization.</p>
    <div>
      <h3>Make it harder for humans to make mistakes</h3>
      <a href="#make-it-harder-for-humans-to-make-mistakes">
        
      </a>
    </div>
    <p>Each product, development, or business team wants to use their own tools, and wants to move as quickly as possible. For good reason! Any security that comes after the fact, and creates additional work for those teams, will be difficult to get internal buy on for. Which can lead to situations like the recent T-mobile hack where an API that was not intended to be public was exposed, <a href="https://www.bleepingcomputer.com/news/security/t-mobile-hacked-to-steal-data-of-37-million-accounts-in-api-data-breach/">discovered, and exploited</a>. You need to meet teams where they are by making the tools they already use more secure, and preventing them from making mistakes, rather than giving them additional tasks.</p><p>In addition to making it easier to deploy our Application Security and Zero Trust products to a wider scope, you’ll also read about how we are adding new features that prevent humans from making the mistakes they always do. You’ll hear about how you can make it impossible to <a href="https://www.cpomagazine.com/cyber-security/reddit-confirmed-a-security-breach-after-a-sophisticated-phishing-attack/">click on a phishing link</a> by automatically blocking the domains that host them, prevent data from leaving regions it should never leave, give your users security alerts directly in the tools they already use, and automatically detect shadow APIs without making your developers change their development process. All of this without having to convince internal teams to make any changes to their behavior.</p><p>If you’re reading this and any part of your job involves securing an organization, I think that by the end of the week we’ll have made your job easier. With the new tools and integrations we release, you’ll be able to <a href="https://www.cloudflare.com/products/zero-trust/threat-defense/">protect more of your infrastructure from a wider range of threats</a>, but reduce the number of third parties you rely on. More importantly, you’ll be able to reduce the number of mistakes that the incredible humans you work with can make. I hope that helps you rest a bit easier!</p> ]]></content:encoded>
            <category><![CDATA[Security Week]]></category>
            <category><![CDATA[API Shield]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[API Security]]></category>
            <category><![CDATA[AI]]></category>
            <guid isPermaLink="false">GLXK7nYI3sCicjMs7A1WR</guid>
            <dc:creator>Reid Tatoris</dc:creator>
        </item>
        <item>
            <title><![CDATA[API Endpoint Management and Metrics are now GA]]></title>
            <link>https://blog.cloudflare.com/api-management-metrics/</link>
            <pubDate>Thu, 22 Sep 2022 13:00:00 GMT</pubDate>
            <description><![CDATA[ API Shield customers can save, update, and monitor the performance of API endpoints ]]></description>
            <content:encoded><![CDATA[ <p></p><p>The Internet is an endless flow of conversations between computers. These conversations, the  constant exchange of information from one computer to another, are what allow us to interact with the Internet as we know it. <a href="https://www.cloudflare.com/learning/security/api/what-is-an-api/">Application Programming Interfaces (APIs)</a> are the vital channels that carry these conversations, and their usage is quickly growing: in fact, <a href="/landscape-of-api-traffic/">more than half of the traffic</a> handled by Cloudflare is for APIs, and this is increasing twice as fast as traditional web traffic.</p><p>In March, we announced that we’re expanding our API Shield into a full <a href="/api-gateway/">API Gateway</a> to make it easy for our customers to protect and manage those conversations. We already offer several features that allow you to secure your endpoints, but there’s more to endpoints than their security. It can be difficult to keep track of many endpoints over time and understand how they’re performing. Customers deserve to see what’s going on with their API-driven domains and have the ability to <i>manage</i> their endpoints.</p><p>Today, we’re excited to announce that the ability to save, update, and <a href="https://www.cloudflare.com/application-services/solutions/app-performance-monitoring/">monitor</a> the performance of all your API endpoints is now generally available to API Shield customers. This includes key performance metrics like latency, error rate, and response size that give you insights into the overall health of your API endpoints.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/2l4QNVWkbubZU8K4rh35T0/d7d325b5626506b6de3871795aeb4945/image3-19.png" />
            
            </figure>
    <div>
      <h3>A Refresher on APIs</h3>
      <a href="#a-refresher-on-apis">
        
      </a>
    </div>
    <p>The bar for what we expect an application to do for us has risen tremendously over the past few years. When we open a browser, app, or IoT device, we expect to be able to connect to data instantly, compare dozens of flights within seconds, choose a menu item from a food delivery app, or see the weather for ten locations at once.</p><p>How are applications able to provide this kind of dynamic engagement for their users? They rely on APIs, which provide access to data and services—either from the application developer or from another company. APIs are fundamental in how computers (or services) talk to each other and exchange information.</p><p>You can think of an API as a waiter: say a customer orders a delicious bowl of Mac n Cheese. The waiter accepts this order from the customer, communicates the request to the chef in a format the chef can understand, and then delivers the Mac n Cheese back to the customer (assuming the chef has the ingredients in stock). The waiter is the crucial <i>channel of communication</i>, which is exactly what the API does.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/4Tz8vFVlVKHWMjdXpCymyb/861e8f50df61cf032e2bf8b50012f069/image7-2.png" />
            
            </figure>
    <div>
      <h3>Managing API Endpoints</h3>
      <a href="#managing-api-endpoints">
        
      </a>
    </div>
    <p>The first step in managing APIs is to get a complete list of all the <a href="https://www.cloudflare.com/learning/learning/security/api/what-is-api-discovery/">endpoints exposed to the internet</a>. <a href="https://developers.cloudflare.com/api-shield/security/api-discovery/"><i>API Discovery</i></a> automatically does this for any traffic flowing through Cloudflare. Undiscovered APIs can’t be monitored by security teams (since they don't know about them) and they're thus less likely to have proper security policies and best practices applied. However, customers have told us they also want the ability to manually add and manage APIs that are not yet deployed, or they want to ignore certain endpoints (for example those in the process of deprecation). Now, API Shield customers can choose to save endpoints found by Discovery or manually add endpoints to API Shield.</p><p>But security vulnerabilities aren’t the only risk or area of concern with APIs – they can be painfully slow or connections can be unsuccessful. We heard questions from our customers such as: what are my most popular endpoints? Is this endpoint significantly slower than it was yesterday? Are any endpoints returning errors that may indicate a problem with the application?</p><p>That’s why we built Performance Metrics into API Shield, which allows our customers to quickly answer these questions themselves with real-time data.</p>
    <div>
      <h3>Prioritizing Performance</h3>
      <a href="#prioritizing-performance">
        
      </a>
    </div>
    
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/gOOOfuquNBYu7jErTcASu/68d914e2fae4dc560d002944a21a54d2/image2-28.png" />
            
            </figure><p>Once you’ve discovered, saved, or removed endpoints, you want to know what’s going well and what’s not. To end-users, a huge part of what defines the experience as “going well” is good performance. Poor performance can lead to a frustrating experience: when you’re shopping online and press a button to check out, you don’t want to wait around for minutes for the page to load. And you certainly never want to see a dreaded error symbol telling you that you can’t get what you came for.</p><p>Exposing performance metrics of API endpoints puts concrete numerical data into your developers’ hands to tell you how things are going. When things are going poorly, these dashboard metrics will point out exactly which aspect of performance is causing concern: maybe you expected to see a spike in requests, but find out that request count is normal and latency is just higher than usual.</p><p>Empowering our customers to make data-driven decisions to better manage their APIs ends up being a win for our customers <i>and</i> our customers’ customers, who expect to seamlessly engage with the domain’s APIs and get exactly what they came for.</p>
    <div>
      <h3>Management and Performance Metrics in the Dashboard</h3>
      <a href="#management-and-performance-metrics-in-the-dashboard">
        
      </a>
    </div>
    <p>So, what’s available today? Log onto your Cloudflare dashboard, go to the domain-level Security tab, and open up the API Shield page. Here, you’ll see the Endpoint Management tab, which shows you all the API endpoints that you’ve saved, alongside placeholders for metrics that will soon be gathered.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/11jqaqDrMTvF4L7rgtydlY/2e403ac4c5ba5d1f028cb390621f81a3/image10-1.png" />
            
            </figure><p>Here you can easily delete endpoints you no longer want to track, or click manually add additional endpoints. You can also export schemas for each host to share internally or externally.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/6Ka18IINPtkTxeQjGIvoN6/062065fe986c6be91ce5f082b1393932/image9-3.png" />
            
            </figure><p>Once you’ve saved the endpoints that you want to keep tabs on, Cloudflare will start collecting data on its performance and make it available to you as soon as possible.</p><p>In Endpoint Management, you can see a few summary metrics in the collapsed view of each endpoint, including recommended rate limits, average latency, and error rate. It can be difficult to tell whether things are going well or not just from seeing a value alone, so we added sparklines that show <i>relative</i> performance, comparing an endpoint’s current metrics with its usual or previous data.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/3DIMD3RnXplhBT7ghBPbbk/7db67978569894327e29dadd883e475d/image5-10.png" />
            
            </figure><p>If you want to view further details about a given endpoint, you can expand it for additional metrics such as response size and errors separated by 4xx and 5xx. The expanded view also allows you to view all metrics at a single timestamp by hovering over the charts.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/5dyhRVO579d42OVBOlptj5/cd53f412261a43704ca07fb8fdf799ea/unnamed-1.png" />
            
            </figure><p>For each saved endpoint, customers can see the following metrics:</p><ul><li><p><b>Request count</b>: total number of requests to the endpoint over time.</p></li><li><p><b>Rate limiting recommendation</b> per 10 minutes, which is guided by the request count.</p></li><li><p><b>Latency</b>: average origin response time, in milliseconds (ms). How long does it take from the moment a visitor makes a request to the moment the visitor gets a response back from the origin?</p></li><li><p><b>Error rate</b> vs. overall traffic: grouped by 4xx, 5xx, and their sum.</p></li><li><p><b>Response size</b>: average size of the response (in bytes) returned to the request.</p></li></ul><p>You can toggle between viewing these metrics on a 24-hour period or a 7-day period, depending on the scale on which you’d like to view your data. And in the expanded view, we provide a percentage difference between the averages of the current vs. the previous period. For example, say I’m viewing my metrics on a 24-hour timeline. My average latency yesterday was 10 ms, and my average latency today is 30 ms, so the dashboard shows a 200% increase. We also use anomaly detection to bring attention to endpoints that have concerning performance changes.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/7sptSfdramyWzuaOyJqaD1/f3c7f8811c0cf43bd4bf17fbbdeba45a/image6-5.png" />
            
            </figure>
    <div>
      <h3>Additional improvements to Discovery and Schema Validation</h3>
      <a href="#additional-improvements-to-discovery-and-schema-validation">
        
      </a>
    </div>
    <p>As part of making endpoint management GA, we’re also adding two additional enhancements to API Shield.</p><p>First, <b><i>API Discovery now accepts cookies</i></b> — in addition to authorization headers — to discover endpoints and suggest rate limiting thresholds. Previously, you could only identify an API session with HTTP headers, which didn’t allow customers to protect endpoints that use cookies as session identifiers. Now these endpoints can be protected as well. Simply go to the API Shield tab in the dashboard, choose edit session identifiers, and either change the type, or click <code>Add additional identifier</code>.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/1n4RtAi8Z5BPmkZDCZAqt3/6e33650b226257918ee927b30b1ee371/image1-34.png" />
            
            </figure><p>Second, we added the ability to <b><i>validate the body of requests via Schema Validation</i></b> for all customers. Schema Validation allows you to provide an OpenAPI schema (a template for your API traffic) and have Cloudflare block non-conformant requests as they arrive at our edge. Previously, you provided specific headers, cookies, and other features to validate. Now that we can validate the body of requests, you can use Schema Validation to confirm every element of a request matches what is expected. If a request contains strange information in the payload, we’ll notice. Note: <i>customers who have already uploaded schemas will need to re-upload to take advantage of body validation.</i></p><p>Take a look at our <a href="https://developers.cloudflare.com/api-shield/">developer documentation</a> for more details on both of these features.</p>
    <div>
      <h3>Get started</h3>
      <a href="#get-started">
        
      </a>
    </div>
    <p>Endpoint Management, performance metrics, schema exporting, discovery via cookies, and schema body validation are all available now for all API Shield customers. To use them, log into the Cloudflare dashboard, click on <code>Security</code> in the navigation bar, and choose API Shield. Once API Shield is enabled, you’ll be able to start discovering endpoints immediately. You can also use all features <a href="https://api.cloudflare.com/#api-shield-settings-properties">through our API</a>.</p><p>If you aren’t yet protecting a website with Cloudflare, it only takes a few minutes to <a href="https://dash.cloudflare.com/sign-up">sign up</a>.</p> ]]></content:encoded>
            <category><![CDATA[GA Week]]></category>
            <category><![CDATA[General Availability]]></category>
            <category><![CDATA[API]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[API Security]]></category>
            <category><![CDATA[Security]]></category>
            <category><![CDATA[API Shield]]></category>
            <guid isPermaLink="false">7Cxx3FtFMuLgbsPe1lYNge</guid>
            <dc:creator>Jin-Hee Lee</dc:creator>
        </item>
        <item>
            <title><![CDATA[Announcing the Cloudflare API Gateway]]></title>
            <link>https://blog.cloudflare.com/api-gateway/</link>
            <pubDate>Wed, 16 Mar 2022 12:59:25 GMT</pubDate>
            <description><![CDATA[ Today we’re announcing the Cloudflare API Gateway. We’re going to completely replace your existing gateway at a fraction of the cost ]]></description>
            <content:encoded><![CDATA[ <p></p><p>Over the past decade, the Internet has experienced a tectonic shift. It used to be composed of static websites: with text, images, and the occasional embedded movie. But the Internet has grown enormously. We now rely on API-driven applications to help with almost every aspect of life. Rather than just download files, we are able to <i>engage</i> with apps by exchanging rich data. We track workouts and send the results to the cloud. We use smart locks and all kinds of IoT devices. And we interact with our friends online.</p><p>This is all wonderful, but it comes with an explosion of complexity on the back end. Why? Developers need to manage <a href="https://www.cloudflare.com/learning/security/api/what-is-an-api/">APIs</a> in order to support this functionality. They need to monitor and authenticate every single request. And because these tasks are so difficult, they’re usually outsourced to an <a href="https://www.cloudflare.com/learning/security/api/what-is-an-api-gateway/">API gateway</a> provider.</p><p>Unfortunately, today’s gateways leave a lot to be desired. First: they’re not cheap. Then there’s the performance impact. And finally, there’s a data and privacy risk, since <a href="/landscape-of-api-traffic/">more than 50% of traffic</a> reaches APIs (and is presumably sent through a third party gateway). What a mess.</p><p>Today we’re announcing the Cloudflare API Gateway. <b>We’re going to completely replace your existing gateway at a fraction of the cost.</b> And our solution uses the technology behind <a href="https://workers.cloudflare.com/">Workers</a>, <a href="https://www.cloudflare.com/products/bot-management/">Bot Management</a>, <a href="https://www.cloudflare.com/products/zero-trust/access/">Access</a>, and <a href="https://developers.cloudflare.com/rules/transform/">Transform Rules</a> to provide the most advanced API toolset on the market.</p>
    <div>
      <h2>What is API Gateway?</h2>
      <a href="#what-is-api-gateway">
        
      </a>
    </div>
    <p>In short, it’s a package of features that will do everything for your APIs. We break it down into three categories:</p><p><b>Security</b>These are the products we have already blogged about. Tools like <a href="https://developers.cloudflare.com/api-shield/products/api-discovery/">Discovery</a>, <a href="https://developers.cloudflare.com/api-shield/products/schema-validation/">Schema Validation</a>, <a href="https://developers.cloudflare.com/api-shield/products/volumetric-abuse-detection/">Abuse Detection</a>, and more. We’ve spent a lot of time applying our security expertise to the world of APIs.</p><p><b>Management &amp; Monitoring</b>These are the foundational tools that keep your APIs in order. Some examples: analytics, routing, and authentication. We are already able to do these things with existing products like <a href="https://www.cloudflare.com/products/zero-trust/access/">Cloudflare Access</a>, and more features are on the way.</p><p><b>Everything Else</b>These are the small (but crucial) items that keep everything running. Cloudflare already offers SSL/TLS termination, load balancing, and proxy services that can run by default.</p><p>Today’s blog post describes each feature in detail. We’re excited to announce that <i>all</i> the security features are now generally available, so let’s start by discussing those.</p>
    <div>
      <h2>Discovery</h2>
      <a href="#discovery">
        
      </a>
    </div>
    <p>Our customers are eager to protect their APIs. Unfortunately, they don’t always have these endpoints documented—or worse, they <i>think</i> everything is documented, but have unknowingly lost or modified endpoints. These hidden endpoints are sometimes called <a href="https://www.bearer.com/resources/shadow-apis-detect-business-risk">shadow APIs</a>. We need to begin our journey with an exhaustive (and accurate) picture of API surface area.</p><p>That’s where Discovery comes in. Head to the <a href="https://dash.cloudflare.com/?to=/:account/:zone/security/api-shield">Cloudflare dashboard</a>, select the <b>Security</b> tab, then choose “API Shield.” Activate the feature and tell us how you want to identify your API traffic. Most users provide a header (available today), but we can also use the request body or cookie (available soon).</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/5cYcAk2aZnbvboWf4w7nH5/268c82e1fbdc7457aa5532bf17f72a07/image7.jpg" />
            
            </figure><p>We provide an exhaustive list of your API endpoints. Cloudflare lists each method, path, and additional metadata to help you understand your surface area. We even <i>collapse</i> endpoints that include variables (e.g., <i>/account/</i><b><i>217</i></b>) to become generally applicable (e.g., <i>/account/</i><b><i>{var1}</i></b>).</p><p>Discovery is a powerful countermeasure to entropy. Our customers often expect to find 30 endpoints, but are surprised to learn they have over <i>100</i> active endpoints.</p>
    <div>
      <h2>Schema Validation</h2>
      <a href="#schema-validation">
        
      </a>
    </div>
    <p>Perhaps you already have a schema for your API endpoints. A schema is like a template: it provides the paths, methods, and additional data you expect API requests to include. Many developers follow the <a href="https://swagger.io/specification/">OpenAPI standard</a> to generate (and maintain) a schema.</p><p>To harden your security, we can <i>validate</i> incoming traffic against this schema. This is a great way to stop basic attacks. Cloudflare will turn away nonconforming requests, discarding nonsense traffic that ignored the dress code. Simply upload your schema to the dashboard, select the actions you want to take, and deploy:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/5nWP8L7vs3ayf5fEA2OU5s/5650d04a6f8cbd0a13a7c95d696798ef/image9.jpg" />
            
            </figure><p>Schema Validation has already vetted traffic for some of the world’s largest crypto sites, delivery services, and payment platforms. It’s available now, and we’ll add body validation soon.</p>
    <div>
      <h2>Abuse Detection</h2>
      <a href="#abuse-detection">
        
      </a>
    </div>
    <p>A robust security approach will use Schema Validation <i>and</i> Discovery in tandem, ensuring traffic matches the expected format. But what about abusive traffic that makes it through?</p><p>As Cloudflare discovers new API endpoints, we actually <i>suggest rate limits</i> for each one. That’s the role of Abuse Detection, and it opens the door to a more sophisticated kind of security.</p><p>Consider an API endpoint that returns weather updates. Specifically, the endpoint will return “yes” if it is likely to snow in the next hour, and “no” otherwise. Our algorithm might detect that the average user requests this data once every 10 minutes. A small group of scrapers, however, makes 37 requests per 10 minutes. Cloudflare automatically recommends a threshold in between, weighted to provide normal users with some breathing room. This would <a href="https://www.cloudflare.com/learning/ai/how-to-prevent-web-scraping/">prevent abusive scraping services</a> from fetching the weather too often.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/7AmCy8IlDu6F2xQMz6Y9Bh/5a38cabf4a3694188bf6b4c8f0b97047/image3-18.png" />
            
            </figure><p>We provide the option to create a rule using our new <a href="/advanced-rate-limiting/">Advanced Rate Limiting</a> engine. You can use cookies, headers, and more to tune thresholds. We’ve been using Abuse Detection to protect <a href="https://api.cloudflare.com/">api.cloudflare.com</a> for months now.</p><p>Our favorite part of this feature: it relies on the <a href="https://www.cloudflare.com/learning/ai/what-is-machine-learning/">machine learning approach</a> we use for <a href="https://www.cloudflare.com/products/bot-management/">Bot Management</a>. Just another way our products can feed into (and benefit from) each other.</p><p>Abuse Detection is available now. If you’re interested in <a href="/api-abuse-detection/"><i>Sequential</i> Abuse Detection</a>, which we use to flag anomalous request flows, check out our previous blog post. The sequential piece is in early access, and we’re continuing to tune it before an official launch.</p>
    <div>
      <h2>mTLS</h2>
      <a href="#mtls">
        
      </a>
    </div>
    <p>Mutual TLS takes security to a new level. You can use certificates to validate incoming traffic as it reaches your APIs—which is especially useful for mobile and IoT devices. Moreover, this is an excellent positive security model that can (and should) be adopted for most device ecosystems.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/BoGPOVpajEoOtHvYpdzvX/c84536ef94f14bf09725e088c29d5154/image1-48.png" />
            
            </figure><p>As an example, let’s return to our weather API. Perhaps this service includes a second endpoint that <i>receives</i> the current temperature from a thermometer. But there’s a problem: anyone can make fake requests, providing inaccurate readings to the endpoint. To prevent this, use mTLS to install a client certificate on the <i>legitimate</i> thermometer, then let Cloudflare validate that certificate. Any other requests will be turned away. Problem solved!</p><p>We already offer a set of free certificates to every Cloudflare customer. That will continue. But starting today, API Gateway customers get <i>unlimited</i> certificates by default.</p>
    <div>
      <h2>Authentication</h2>
      <a href="#authentication">
        
      </a>
    </div>
    <p>Many modern APIs require authentication. In fact, authentication unlocks all sorts of capabilities—it allows sessions (with login), personal data exchange, and infrastructure efficiency. And of course, Cloudflare protects authenticated traffic as it passes through our network.</p><p>But with API Gateway, Cloudflare plays a more active role in authenticating traffic, helping to <b>issue</b> and <b>validate</b> the following:</p><ul><li><p>API keys</p></li><li><p>JSON web tokens (JWT)</p></li><li><p>OAuth 2.0 tokens</p></li></ul><p>Using access control lists, we help you manage different user groups with varying permissions. And this matters—because your current provider is introducing tons of latency and unnecessary data exchange. If a request has to go somewhere <i>outside</i> the Cloudflare ecosystem, it’s traveling farther than it needs to:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/53rdn4o2AexuxH6ebDhEV4/803f9fd2c8a7fa96570b84eb4fdb8515/image2-39.png" />
            
            </figure><p>Cloudflare can authenticate on our global network and handle requests in a fraction of the time. This kind of technology is difficult to implement, but we felt it was too important to ignore. How did we build it so quickly? <a href="https://www.cloudflare.com/products/zero-trust/access/">Cloudflare Access</a>. We took our experience working with identity providers and, once again, ported it over to the world of APIs. Our gateway includes unlimited authentication and token exchange. These features will be available soon.</p>
    <div>
      <h2>Routing &amp; Management</h2>
      <a href="#routing-management">
        
      </a>
    </div>
    <p>Let’s talk briefly about <a href="https://www.cloudflare.com/learning/serverless/glossary/serverless-microservice/">microservices</a>. Modern applications are behemoths, so developers break them up into smaller chunks called “microservices.”</p><p>Consider an application that helps you book a hotel room. It might use a microservice to fetch available dates, another to fetch prices, and still another to fetch room types. Perhaps a different team manages each microservice, but they all need to be available from a single public entry point:</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/2vE5CLMCH7SBOvyjUEdz1a/860064c062cab01677ce237ac35ab950/image8.png" />
            
            </figure><p>That single entry point—traditionally managed by an API gateway—is responsible for <i>routing</i> each request to the right microservice. Many of our customers have been paying standalone services to do this for years. That’s no longer necessary. We’ve built on our <a href="/introducing-transform-rules-with-url-rewriting-at-the-edge/">Transform Rules</a> product to dynamically re-write and re-route at our edge. It’s easy to configure, fast to deploy, and natively built into API Gateway. Cloudflare can now be your API’s single point of entry.</p><p>That’s just the tip of the iceberg. API Gateway can actually <i>replace</i> your microservices through an integration with our <a href="https://workers.cloudflare.com/">Workers</a> product. How? Consider writing a Worker that performs some action; perhaps return hotel prices, which are stored with <a href="/durable-objects-ga/">Durable Objects</a> on our network. With API Gateway, requests arrive at our network, are routed to the correct microservice with Transform Rules, and then are fully served with Workers (still on our network!). These Workers may contact your origin for additional information, where necessary.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/5Xlw0UyeftYsiiFsGbrHbE/7b9772d9a46cd8dc1ddef13d98285951/image4-3.png" />
            
            </figure><p>Workers are faster, cheaper, and simpler than microservice alternatives. This integration will be available soon.</p>
    <div>
      <h2>API Analytics</h2>
      <a href="#api-analytics">
        
      </a>
    </div>
    <p>Customers tell us that <i>seeing</i> API traffic is sometimes more important than even acting on it. In fact, this trend isn’t specific to APIs. We published <a href="/envoy-media-machine-learning-bot-management/">another blog</a> today that explores how one customer uses our bot intelligence to passively log information about threats.</p>
            <figure>
            
            <img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/Lod4XcchPemDNuK209PAg/24ef6bf697b80ddbc052e4cdb88701ad/image6.png" />
            
            </figure><p>With API Analytics, we’ve drawn on our other products to show useful data in real time. You can view popular endpoints, filter by ML-driven insights, see histograms of abuse thresholds, and capture trends.</p><p>API Analytics will be available soon. When this happens, you’ll also be able to export custom reports and share insights within your organization.</p>
    <div>
      <h2>Logging, Quota Management, and More</h2>
      <a href="#logging-quota-management-and-more">
        
      </a>
    </div>
    <p><i>All</i> of our established features, like caching, load balancing, and log integrations work natively with API Gateway. These shouldn’t be overlooked as primitive gateway features; they’re essential. And because Cloudflare performs all of these functions in the same place, you get the latency benefits without having to do a thing.</p><p>We are also expanding our Enterprise Logs functionality to perform real-time logging. If you choose to authenticate on Cloudflare’s network, you can view detailed logs of each user who has accessed an API. Similarly, we keep track of each request’s lifespan as it is received, validated, routed, and responded to. Everything is logged.</p><p>Finally, we are building Quota Management, a feature that counts API requests over a longer period of time (like a month) and allows you to manage thresholds for your users. We’ve also launched <a href="/advanced-rate-limiting/">Advanced Rate Limiting</a> to help with more sophisticated cases (including body inspection for GraphQL).</p>
    <div>
      <h2>Conclusion</h2>
      <a href="#conclusion">
        
      </a>
    </div>
    <p>Our <a href="https://www.cloudflare.com/application-services/solutions/api-security/">API security features</a>—Discovery, Schema Validation, Abuse Detection, and mTLS—are available now! We call these features <a href="https://developers.cloudflare.com/api-shield/">API Shield</a> because they form the shield that protects the remaining gateway functions. Enterprise customers can ask their account teams for access today.</p><p>Many of the other portions of API Gateway are now in early access. According to Gartner®, “by 2025, less than 50% of enterprise APIs will be managed, as explosive growth in APIs surpasses the capabilities of <a href="https://www.cloudflare.com/application-services/products/api-gateway/">API management tools</a>.” Our goal is to offer an affordable gateway that will fight this trend. If you have a specific feature you want to test, let your account team know, so we can onboard you as soon as possible.</p><p>Source: Gartner, “Predicts 2022: APIs Demand Improved Security and Management”, Shameen Pillai, Jeremy D'Hoinne, John Santoro, Mark O'Neill, Sham Gill, 6 December 2021. GARTNER is a registered trademark and service mark of Gartner, Inc. and/or its affiliates in the U.S. and internationally and is used herein with permission. All rights reserved.</p> ]]></content:encoded>
            <category><![CDATA[Security Week]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[Product News]]></category>
            <category><![CDATA[API]]></category>
            <category><![CDATA[Security]]></category>
            <guid isPermaLink="false">7vy7PiYRJxbMbGfxdIqhWu</guid>
            <dc:creator>Ben Solomon</dc:creator>
        </item>
        <item>
            <title><![CDATA[Cryptocurrency API Gateway using Typescript+Workers]]></title>
            <link>https://blog.cloudflare.com/cryptocurrency-api-gateway-typescript-workers/</link>
            <pubDate>Fri, 29 Jun 2018 13:00:00 GMT</pubDate>
            <description><![CDATA[ If you followed part one, I’ve set up an environment to write TypeScript with tests and deploy to the Cloudflare Edge using npm run upload. In this post, I’ll expand on one Worker Recipe even further. ]]></description>
            <content:encoded><![CDATA[ <p>If you followed <a href="/p/607ad519-5652-4688-9fff-33fbb1fc9d3f/">part one</a>, I have an environment setup where I can write Typescript with tests and deploy to the Cloudflare Edge with <code>npm run upload</code>. For this post, I want to take one of the <a href="https://developers.cloudflare.com/workers/recipes/aggregating-multiple-requests/">Worker Recipes</a> further.</p><p>I'm going to build a mini HTTP request routing and handling framework, then use it to build a <a href="https://www.cloudflare.com/learning/security/api/what-is-an-api-gateway/">gateway</a> to multiple cryptocurrency API providers. My point here is that in a single file, with no dependencies, you can quickly build pretty sophisticated logic and deploy fast and easily to the Edge. Furthermore, using modern Typescript with async/await and the rich type structure, you also write clean, async code.</p><p>OK, here we go...</p><p>My API will look like this:</p><table><tr><td><p>Verb</p></td><td><p>Path</p></td><td><p>Description</p></td></tr><tr><td><p>GET</p></td><td><p><code>/api/ping</code></p></td><td><p>Check the Worker is up</p></td></tr><tr><td><p>GET</p></td><td><p><code>/api/all/spot/:symbol</code></p></td><td><p>Aggregate the responses from all our configured gateways</p></td></tr><tr><td><p>GET</p></td><td><p><code>/api/race/spot/:symbol</code></p></td><td><p>Return the response of the provider who responds fastest</p></td></tr><tr><td><p>GET</p></td><td><p><code>/api/direct/:exchange/spot/:symbol</code></p></td><td><p>Pass through the request to the gateway. E.g. gdax or bitfinex</p></td></tr></table>
    <div>
      <h3>The Framework</h3>
      <a href="#the-framework">
        
      </a>
    </div>
    <p>OK, this is Typescript, I get interfaces and I'm going to use them. Here's my ultra-mini-http-routing framework definition:</p>
            <pre><code>export interface IRouter {
  route(req: RequestContextBase): IRouteHandler;
}

/**
 * A route
 */
export interface IRoute {
  match(req: RequestContextBase): IRouteHandler | null;
}

/**
 * Handles a request.
 */
export interface IRouteHandler {
  handle(req: RequestContextBase): Promise&lt;Response&gt;;
}

/**
 * Request with additional convenience properties
 */
export class RequestContextBase {
  public static fromString(str: string) {
    return new RequestContextBase(new Request(str));
  }

  public url: URL;
  constructor(public request: Request) {
    this.url = new URL(request.url);
  }
}</code></pre>
            <p>So basically all requests will go to <code>IRouter</code>. If it finds an <code>IRoute</code> that returns an <code>IRouterHandler</code>, then it will call that and pass in <code>RequestContextBase</code>, which is just the request with a parsed URL for convenience.</p><p>I stopped short of dependency injection, so here's the router implementation with 4 routes we've implemented (Ping, Race, All and Direct). Each route corresponds to one of the four operations I defined in the API above and returns the corresponding <code>IRouteHandler</code>.</p>
            <pre><code>export class Router implements IRouter {
  public routes: IRoute[];

  constructor() {
    this.routes = [
      new PingRoute(),
      new RaceRoute(),
      new AllRoute(),
      new DirectRoute(),
    ];
  }

  public async handle(request: Request): Promise&lt;Response&gt; {
    try {
      const req = new RequestContextBase(request);
      const handler = this.route(req);
      return handler.handle(req);
    } catch (e) {
      return new Response(undefined, {
        status: 500,
        statusText: `Error. ${e.message}`,
      });
    }
  }

  public route(req: RequestContextBase): IRouteHandler {
    const handler: IRouteHandler | null = this.match(req);
    if (handler) {
      logger.debug(`Found handler for ${req.url.pathname}`);
      return handler;
    }
    return new NotFoundHandler();
  }

  public match(req: RequestContextBase): IRouteHandler | null {
    for (const route of this.routes) {
      const handler = route.match(req);
      if (handler != null) {
        return handler;
      }
    }
    return null;
  }
}</code></pre>
            <p>You can see above I return a NotFoundHandler if we can't find a matching route. Its implementation is below. It's easy to see how 401, 405, 500 and all the common handlers could be implemented.</p>
            <pre><code>/**
 * 404 Not Found
 */
export class NotFoundHandler implements IRouteHandler {
  public async handle(req: RequestContextBase): Promise&lt;Response&gt; {
    return new Response(undefined, {
      status: 404,
      statusText: 'Unknown route',
    });
  }
}</code></pre>
            <p>Now let's start with Ping. The framework separates matching a route and handling the request. Firstly the route:</p>
            <pre><code>export class PingRoute implements IRoute {
  public match(req: RequestContextBase): IRouteHandler | null {
    if (req.request.method !== 'GET') {
      return new MethodNotAllowedHandler();
    }
    if (req.url.pathname.startsWith('/api/ping')) {
      return new PingRouteHandler();
    }
    return null;
  }
}</code></pre>
            <p>Simple enough, if the URL starts with <code>/api/ping</code>, handle the request with a <code>PingRouteHandler</code></p>
            <pre><code>export class PingRouteHandler implements IRouteHandler {
  public async handle(req: RequestContextBase): Promise&lt;Response&gt; {
    const pong = 'pong;';
    const res = new Response(pong);
    logger.info(`Responding with ${pong} and ${res.status}`);
    return new Response(pong);
  }
}</code></pre>
            <p>So at this point, if you followed along with Part 1, you can do:</p>
            <pre><code>$ npm run upload
$ curl https://cryptoserviceworker.com/api/ping
pong</code></pre>
            <p>OK, next the <code>AllHandler</code>, this aggregates the responses. Firstly the route matcher:</p>
            <pre><code>export class AllRoute implements IRoute {
  public match(req: RequestContextBase): IRouteHandler | null {
    if (req.url.pathname.startsWith('/api/all/')) {
      return new AllHandler();
    }
    return null;
  }
}</code></pre>
            <p>And if the route matches, we'll handle it by farming off the requests to our downstream handlers:</p>
            <pre><code>export class AllHandler implements IRouteHandler {
  constructor(private readonly handlers: IRouteHandler[] = []) {
    if (handlers.length === 0) {
      const factory = new HandlerFactory();
      logger.debug('No handlers, getting from factory');
      this.handlers = factory.getProviderHandlers();
    }
  }

  public async handle(req: RequestContextBase): Promise&lt;Response&gt; {
    const responses = await Promise.all(
      this.handlers.map(async h =&gt; h.handle(req))
    );
    const jsonArr = await Promise.all(responses.map(async r =&gt; r.json()));
    return new Response(JSON.stringify(jsonArr));
  }
}</code></pre>
            <p>I'm cheating a bit here because I haven't shown you the code for <code>HandlerFactory</code> or the implementation of <code>handle</code> for each one. You can look up the full source <a href="https://github.com/stevenpack/cryptoserviceworker/blob/master/src/service-worker.ts">here</a>.</p><p>Take a moment here to appreciate just what's happening. You're writing very expressive async code that in a few lines, is able to multiplex a request to multiple endpoints and aggregate the results. Furthermore, it's running in a sandboxed environment in a data center very close to your end user. <b>Edge-side code is a game changer.</b></p><p>Let's see it in action.</p>
            <pre><code>$ curl https://cryptoserviceworker.com/api/all/spot/btc-usd
[  
   {  
      "symbol":"btc-usd",
      "price":"6609.06000000",
      "utcTime":"2018-06-20T05:26:19.512000Z",
      "provider":"gdax"
   },
   {  
      "symbol":"btc-usd",
      "price":"6600.7",
      "utcTime":"2018-06-20T05:26:22.284Z",
      "provider":"bitfinex"
   }
]</code></pre>
            <p>Cool, OK, who's fastest? First, the route handler:</p>
            <pre><code>export class RaceRoute implements IRoute {
  public match(req: RequestContextBase): IRouteHandler | null {
    if (req.url.pathname.startsWith('/api/race/')) {
      return new RaceHandler();
    }
    return null;
  }
}</code></pre>
            <p>And the handler. Basically just using <code>Promise.race</code> to pick the winner</p>
            <pre><code>export class RaceHandler implements IRouteHandler {
  constructor(private readonly handlers: IRouteHandler[] = []) {
    const factory = new HandlerFactory();
    this.handlers = factory.getProviderHandlers();
  }

  public handle(req: RequestContextBase): Promise&lt;Response&gt; {
    return this.race(req, this.handlers);
  }

  public async race(
    req: RequestContextBase,
    responders: IRouteHandler[]
  ): Promise&lt;Response&gt; {
    const arr = responders.map(r =&gt; r.handle(req));
    return Promise.race(arr);
  }
}</code></pre>
            <p>So who's fastest? Tonight it's gdax.</p>
            <pre><code>curl https://cryptoserviceworker.com/api/race/spot/btc-usd
{  
   "symbol":"btc-usd",
   "price":"6607.15000000",
   "utcTime":"2018-06-20T05:33:16.074000Z",
   "provider":"gdax"
}</code></pre>
            
    <div>
      <h3>Summary</h3>
      <a href="#summary">
        
      </a>
    </div>
    <p>Using Typescript+Workers, in &lt; 500 lines of code, we were able to</p><ul><li><p>Define an interface for a mini HTTP routing and handling framework</p></li><li><p>Implement a basic implementation of that framework</p></li><li><p>Build Routes and Handlers to provide Ping, All, Race and Direct handlers</p></li><li><p>Deploy it to 160+ data centers with <code>npm run upload</code></p></li></ul><p>Stay tuned for more, and PRs welcome, particularly for more providers.</p><p><i>If you have a worker you'd like to share, or want to check out workers from other Cloudflare users, visit the </i><a href="https://community.cloudflare.com/tags/recipe-exchange"><i>“Recipe Exchange”</i></a><i> in the Workers section of the </i><a href="https://community.cloudflare.com/c/developers/workers"><i>Cloudflare Community Forum</i></a><i>.</i></p> ]]></content:encoded>
            <category><![CDATA[JavaScript]]></category>
            <category><![CDATA[Serverless]]></category>
            <category><![CDATA[Cloudflare Workers]]></category>
            <category><![CDATA[Programming]]></category>
            <category><![CDATA[Cryptography]]></category>
            <category><![CDATA[API Gateway]]></category>
            <category><![CDATA[Developers]]></category>
            <category><![CDATA[Developer Platform]]></category>
            <guid isPermaLink="false">6vJMJrpNtXwRzr8sYBkXpj</guid>
            <dc:creator>Steven Pack</dc:creator>
        </item>
    </channel>
</rss>