<?xml version="1.0" encoding="UTF-8"?><rss 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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexandre Souza on Medium]]></title>
        <description><![CDATA[Stories by Alexandre Souza on Medium]]></description>
        <link>https://medium.com/@alexandre.highrollers?source=rss-72e65b227730------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jT2H4FW2663wGwHFeCSDlg.jpeg</url>
            <title>Stories by Alexandre Souza on Medium</title>
            <link>https://medium.com/@alexandre.highrollers?source=rss-72e65b227730------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:28:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexandre.highrollers/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The challenges of configuring Kubernetes resources’ Requests & Limits in combination with HPA at…]]></title>
            <link>https://medium.com/@alexandre.highrollers/the-challenges-of-configuring-kubernetes-resources-requests-limits-in-combination-with-hpa-at-92177cb5a378?source=rss-72e65b227730------2</link>
            <guid isPermaLink="false">https://medium.com/p/92177cb5a378</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubecost]]></category>
            <dc:creator><![CDATA[Alexandre Souza]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 16:53:32 GMT</pubDate>
            <atom:updated>2024-05-06T09:14:23.679Z</atom:updated>
            <content:encoded><![CDATA[<h3>The challenges of configuring Kubernetes resources’ requests/limits and HPAs at Scale</h3><p>Have you ever faced the challenges of configuring Kubernetes resources’ utilization at Scale? In this article, I highlight the issue and explain how I can help you save thousands of dollars in cloud bills when managing GPU, CPU, and Memory utilization!</p><p>When dealing with medium to large Kubernetes clusters, resource utilization such as Memory (RAM) and CPU becomes one of the many priorities for Platform teams or anyone responsible for managing and paying for it.</p><p>I’m a Platform Engineer at <a href="http://getir.com/"><strong><em>Getir</em></strong></a>, a leading player in the speedy grocery market and, as <a href="https://sifted.eu/articles/getir-leadership-team-turkey-us">Sifted.eu</a> once said, the “grandfather of the speedy grocery world”. Because of its success and drive, Getir’s technical needs are challenging. Thankfully, it makes the job very exciting.</p><p>One of our challenges is managing Kubernetes clusters throughout our Dev, Stage, and Prod environments.</p><p>To paint the picture with some analytics, our Development cluster alone has <strong><em>146 namespaces</em></strong> with about <strong><em>2213 workloads</em></strong><em> </em>spanning <em>Deployments</em>,<em> StatefulSets</em>, and <em>Daemonsets</em>. Of course, most of the Development workloads will miss Production as they might be under development, research, or trial.</p><p>Our Staging follows, and our Production environment has <strong><em>46 namespaces</em></strong> with <strong><em>797 workloads</em></strong><em> </em>spanning <em>Deployments</em>, <em>StatefulSets</em>, and <em>Daemonsets</em>. If we count the other workloads, the number increases. However, we’re looking for resource utilization here, and no other workload than Pods can give us the real numbers.</p><p>We work with replication in Production, so our deployments will carry Pods with multiple replicas. We currently have <strong><em>780</em></strong><em> Deployments</em> with <strong><em>8816</em></strong><em> replicated Pods</em> running.</p><p>And because of the scale of our operations, more often than not, we end up having over-provisioned resources. The majority of the time, it’s Memory (RAM).</p><p><strong>Those are not ordinary numbers, nor are they easy to maintain.</strong></p><p>Now that you have learned our reality, let’s dive deep into how we can save costs with some scenarios. <em>Before continuing, please check the “Resource Management for Pods and Containers” banner at the end if you know little about it.</em></p><h4>Scenario 1: Single Replica Pods</h4><p>Managing resources for single replica Pods is the least difficult. As a good rule of thumb, <em>always request lower resources</em> such as Memory (RAM) and CPU. In most cases, if no <em>limits </em>are set, it will work just fine! <em>Beware, it depends on the size of your clusters and how many Pods you’re orchestrating.</em></p><blockquote>If the node where a Pod is running has enough of a resource available, it’s possible (and allowed) for a container to use more resource than its requests for that resource specifies. However, a container is not allowed to use more than its resource limits.</blockquote><p>In the code below, we set the spec.containers[].resources.requests but left the <em>limits</em> out on purpose.</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: backend<br>spec:<br>  containers:<br>  - name: app<br>    image: images.my-company.example/backend-app:v2<br>    resources:<br>      requests:<br>        memory: 35Mi</pre><p>This setup has some wanted behaviors:</p><ul><li>We won’t over-provision by requesting more cloud resources, such as Memory (RAM), CPU, GPU, etc., than we initially need.</li><li>We didn’t configure any <em>limits</em> so that <em>kubelet</em> won’t enforce them. Again, don’t worry; your application will get more resources as it goes if required. Of course, only as long as you have resources to provide 🙂</li><li>We’re saving costs by not over-provisioning cloud resources.</li></ul><p>Let&#39;s take a hypothetical example with a simple <em>.NET 8 Hosted App</em> to understand how we save costs. This app implements IHostedService with a lightweight algorithm to process some data. Because of the simplicity of this application, it would require about <em>35 Mebibytes (≈36 Megabytes)</em>. However, instead of requesting a lower value for our memory resource <em>requests</em>, we unknowingly requested our Pod’s container to start with <em>300Mi (≈314 Megabytes)</em>.</p><blockquote>The challenge in large-scale K8s clusters is how to right-size our workload while minimizing Node-pressure Eviction!</blockquote><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: backend<br>spec:<br>  containers:<br>  - name: app<br>    image: images.my-company.example/backend-app:v2<br>    resources:<br>      requests:<br>        memory: 300Mi</pre><p>If you have a small cluster with a few Pods on it, that wouldn’t be a problem, nor too expensive. But once you go to scales as we have at <em>Getir</em>, that results in hundreds of thousands of dollars in bills 😭💸💸</p><p>One challenge when dealing with workloads at scale is that <em>kube-schedule</em> uses resource <em>requests</em> to decide where to place a <em>Pod</em>. If it places a <em>Pod</em> in a <em>Node</em> with enough resources to accept scheduling at the time but eventually doesn’t have enough resources to allow that workload to scale vertically (if no limits are set), our Pod will be a candidate for <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/">Node-pressure Eviction</a> as we get closer to the Node’s limit<em>. </em>To minimize <em>Node-pressure Eviction</em>, we can replicate your workloads and use a <em>Cluster Autoscaler</em> solution. Many cloud providers have Kubernetes Cluster Autoscaler as a service, but if it’s not your case, there are also open-source solutions, such as <a href="https://karpenter.sh/">Karpenter</a>.</p><p>Back to the happy, but not too happy-case scenario, to demonstrate what I mean by having set a high resource request, the below chart shows that our <em>Pod‘s container</em> started with a memory request of <em>300Mi</em>, but the running application on the container only needs <em>35Mi</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSwRq8jDXCtp-lgKaBfeLA.png" /><figcaption>Sample of single Pod with over-provisioned resource</figcaption></figure><p>In this case, we have requested an extra <em>≈265Mi</em> from the cloud provider, which is not being utilized, <strong>but we’re paying for it!</strong></p><blockquote>To avoid over-provisioning, we must ensure we economically set our “resource requests” and consistently provision with lower requests!</blockquote><p>One easy way to bring cost awareness to your teams is by enabling Kubernetes cost monitoring with <a href="https://www.kubecost.com/"><em>Kubecost</em></a>. It provides real-time cost visibility and insights so your teams can tackle the problem at the core.</p><p><em>Kubecost</em> will show you under- or over-provisioned resources so you can adjust accordingly. Keep reading; you’ll find more tips as you go 😜</p><h4>Scenario 2: Multiple Replicas Pods</h4><p>Again, managing resources for replicated Pods is still simple on a small scale, but the challenges arise when going beyond. The biggest problem is ensuring teams think sustainably when requesting resources for their Pods and consistently don’t over-provision them.</p><p>Still, following the same principle of lower resource allocation, we can easily solve the problem of over-provisioning our Pods.</p><p>With another hypothetical situation, let’s think of a ReplicaSet with three Pods, exposing a Node.js RESTful API. And to make it more exciting, let’s expect those endpoints will get tons of concurrent requests.</p><pre>apiVersion: apps/v1<br>kind: ReplicaSet<br>metadata:<br>  name: orders-api<br>  labels:<br>    api: orders<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      api: orders<br>  template:<br>    metadata:<br>      labels:<br>        api: orders<br>    spec:<br>      containers:<br>      - name: orders-api<br>        image: images.my-company.example/orders-api:latest<br>        resources:<br>          requests:<br>            memory: 300Mi</pre><p>Because of the nature of our RESTful API, we expect it to receive tons of requests, so we provisioned it with <em>300Mi </em>(<em>≈314 Megabytes</em>). But in reality, it only requires about <em>60Mi (≈62 Megabytes), </em>perhaps even less, to function outside peak-hours situations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-sTJMKGRoEpGx3RGA2Ing.png" /><figcaption>Sample of replicated Pods with over-provisioned resources</figcaption></figure><p>Once more, we over-provisioned it because of our upfront expectations, and by doing so, we’ll have the same problems as before, but this time on a larger scale. The issue is that we’ll be paying for unused cloud resources as long as the memory utilization generated by the HTTP requests load doesn’t surpass the initial memory request.</p><p>If, as in this hypothetical case, the values stay around <em>60Mi</em> for each of the three replicas, we would be paying for an extra <em>720Mi</em> of unused resources. <em>And there are many other resource utilization variations that would cause us to overpay!</em> However, if we set a low memory request, say <em>60Mi,</em> our application will still function as well as if we had set <em>300Mi</em>. But this time, we’re NOT overpaying.</p><p>As you can see in the previous example, we didn’t configure any resource <em>limits,</em> so we can get more if required and available. Yet, if you want full control over the maximum resource utilization and be more strict about their usage, you can set <em>limits:</em> spec.containers[].resources.limits.</p><blockquote>Again: To avoid over-provisioning, we must ensure we economically set our “resource requests” and consistently provision with lower requests!</blockquote><p>Suppose you work in an organization that manages hundreds if not thousands of Dev teams and their K8s workloads. In that case, keeping cost awareness and resource requests to a minimum becomes cumbersome and challenging. Some would say it even becomes toil work!</p><p>Nevertheless, ensure teams always take the “lower resource request” approach whenever possible. Also, try applying operators to your Kubernetes cluster that will do the hard work for you. One such tool is <a href="https://www.stormforge.io/">stormforge.io</a>. It’s not free, but it will autonomously and continuously auto-right-size your workloads. But it comes with some gotchas! The quick tip is to adjust your resource <em>requests’</em> values in your IaC consistently and let the tool work only with edge cases!</p><p>Another more economical option is to use <a href="https://docs.kubecost.com/using-kubecost/navigating-the-kubecost-ui/alerts"><em>Kubecost Alerts</em></a><em> </em>and let your teams have real-time insights into your resource utilization and respective costs — You can also set Kubernetes <a href="https://kubernetes.io/docs/concepts/policy/resource-quotas/">Resource Quotas</a> or <a href="https://kubernetes.io/docs/concepts/policy/limit-range/">Limit Ranges</a> for your namespaces to ensure teams (split by namespace) will consume resources until a pre-defined ceiling.</p><h4>Scenario 3: Multiple Replicas Pods with HPAs</h4><p>Finally, we decided to use Horizontal Pod Autoscaling, a.k.a. HPA, in our workloads! <em>Go to the “Horizontal Pod Autoscaling” banner at the end if you know little about it.</em></p><blockquote>The challenge here is to ensure we use our resources smartly and don’t over-provision them on the way!</blockquote><p>There are so many configuration sets we can do with HPAs that it makes writing them very exciting. However, let’s stick to the core configuration, which is to enable workloads such as Deployment or StatefulSet to scale out automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*CiQqIqUw_TROzUHypexNbw.png" /><figcaption>Source: kubernetes.io — HorizontalPodAutoscaler controls the scale of a Deployment and its ReplicaSet.</figcaption></figure><p>For the sake of simplicity, let’s take our previous example from “Scenario 2: Multiple Replicas Pods” and use it with our HPA. <em>Remember, we have over-provisioned a ReplicaSet with 3 Pods, requesting an initial 300Mi of memory for each.</em></p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: orders-api<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: ReplicaSet<br>    name: orders-api<br>  minReplicas: 3<br>  maxReplicas: 10<br>  metrics:<br>  - type: Resource<br>    resource:<br>      name: memory<br>      target:<br>        type: Utilization<br>        averageUtilization: 70</pre><p>In the code above, we’re setting our HPA to scale if we reach a target <strong><em>average utilization</em></strong> of 70. The unit of <strong><em>averageUtilization</em></strong> is % (percentage), and it is “represented as a percentage of the requested value”. Here, we configured our HPA to scale when the actual App/Runtime allocated memory utilization reaches 70% of its requested value. I will explain it with some pictures soon!</p><p>To recap, Kubernetes HPA supports 3 types of target values (<strong><em>averageUtilization</em></strong>, <strong><em>averageValue</em></strong>, and <strong><em>value</em></strong><em>):</em></p><blockquote><strong>metrics.containerResource.target.averageUtilization</strong> (int32)<br>averageUtilization is the target value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. Currently only valid for Resource metric source type</blockquote><blockquote><strong>metrics.containerResource.target.averageValue</strong> (<a href="https://kubernetes.io/docs/reference/kubernetes-api/common-definitions/quantity/#Quantity">Quantity</a>)<br>averageValue is the target value of the average of the metric across all relevant pods (as a quantity)</blockquote><blockquote><strong>metrics.containerResource.target.value</strong> (<a href="https://kubernetes.io/docs/reference/kubernetes-api/common-definitions/quantity/#Quantity">Quantity</a>)<br>value is the target value of the metric (as a quantity).</blockquote><p>Remember that by setting resource <em>requests</em>, we’re issuing Kubernetes to make an initial reservation of that resource, if available in the Node. That consequentially translates to our Cloud Provider reserving and charging those resources in a PAYG (pay-as-you-go) pricing model.</p><p>Continuing with our example, the picture below represents a single replica over time resource utilization, which eventually will trigger HPAs’ Pod replication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaKG-HxDlsmVDDxRZ0nuXg.png" /><figcaption>Sample of replicated Pods with HPA</figcaption></figure><p>As we set our HPA with an <strong><em>averageUtilization of 70%</em></strong>, the HPA controller will only spin another <em>Pod</em> once we reach <em>210Mi (300 x 0.7 = 210).</em> And as long as we don’t surpass the ceiling of <em>300Mi</em> resource <em>requests, </em>we’ll have over-provisioned and overpaid resources.</p><p><em>Remember, we didn’t configure resource limits here, so if our Node has more resources to give, we’ll get it!</em></p><p>This waste of resources and money will continue until our HPA provisions the 10th Pod replica and all 10 Pods consume <em>300Mi</em> or more of our resources. Until then, we have lots of unutilized resources.</p><p><em>As a side note, with such attempts to reduce over-provisioning resources, we need to make some trade-offs. One is how Kubernetes would schedule our Pods and how we can be more prone to experience Node-pressure Eviction in some cases. My advice is to constantly monitor your workloads to identify the Failure Rate related to Node-pressure Eviction so you can better decide what’s best for your organization, teams, or set of workloads.</em></p><p>Continuing with the hypothetical problem… <strong>How can we avoid over-provisioning replicated workloads?</strong> One simple solution, again, is to set a lower resource request. Let’s say <em>60Mi,</em> for example. But by doing that, we’re not solving the core problem; we’re just wasting a bit less resources as the same consumption pattern happens — Having <em>60Mi</em> of memory brings us to a scaling target of 60 x 0.7 = <strong><em>42Mi</em></strong>. It’s clearly better than before. We now have an average of <em>18Mi</em> of unused resources per Pod (in the worst-case scenario, if truly using up to the target) compared to <em>90Mi</em> per Pod from the <em>300Mi</em> at a scaling target of 70%.</p><p>A better solution would comprise two main decisions, The first one being what I’ve been repeating over and over 😁</p><ol><li>Set lower resource requests</li><li>Set <strong><em>averageUtilization</em></strong> at <strong><em>100%</em></strong>. Yes, you can do it!</li></ol><p>Another option is to use target <strong><em>averageValue</em></strong>, or target <strong><em>value,</em></strong><em> instead of </em><strong><em>averageUtilization</em></strong>!</p><blockquote>Again, those are still “happy case scenarios” and are somehow easy to solve. The challenge now is working with HPA in combination with resource <em>requests</em> and <em>limits</em>.</blockquote><p>Once we put resource <em>limits</em> in the picture, things get a bit more complicated. An easy solution when using limits is to set your HPA’s target ceiling using the target <strong><em>averageValue</em></strong>, or target <strong><em>value,</em></strong> as you could set a value above the request and below the limit.</p><pre>apiVersion: apps/v1<br>kind: ReplicaSet<br>metadata:<br>  name: orders-api<br>  labels:<br>    api: orders<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      api: orders<br>  template:<br>    metadata:<br>      labels:<br>        api: orders<br>    spec:<br>      containers:<br>      - name: orders-api<br>        image: images.my-company.example/orders-api:latest<br>        resources:<br>          requests:<br>            memory: 60Mi<br>          limits:<br>            memory: 450Mi<br>------<br>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: orders-api<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: ReplicaSet<br>    name: orders-api<br>  minReplicas: 3<br>  maxReplicas: 10<br>  metrics:<br>  - type: Resource<br>    resource:<br>      name: memory<br>      target:<br>        type: Value<br>        value: 420</pre><p>In the example above, I corrected the initial resource <em>requests</em> to <em>60Mi</em>, added resource <em>limits </em>at <em>450Mi</em>, and set my HPA to use the target <strong><em>value</em></strong> instead of <strong><em>averageUtilization</em></strong>. This means we didn’t over-provision any resources, and if we did, it is very minimal; we’ll get more resources as long as the Node can provide, and our HPAs will only trigger at <em>420Mi (at a ratio of 7 — 420Mi:60Mi)</em>. Again, we don’t have any remainder as we did in the previous example. That’s because we only requested <em>60Mi</em> of memory initially, and it grew as the application load increased.</p><p><strong>Yey, we have no idle resources waiting to be used, and we’re being sustainable!</strong></p><p>And to finish with another possibility, the <strong><em>averageUtilization</em></strong> accepts values higher than 100%. So, if you want to stick the the percentage notation for your HPAs, you only need to calculate its <em>limits</em> equivalent.</p><p>This simple linear equation shows how to calculate the request <strong><em>averageUtilization</em></strong> equivalent in % for the <em>limits</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*a3IzUS6nUQyxrI0emEoWRA.png" /><figcaption>A simple linear equation to calculate a desired <strong><em>averageUtilization</em></strong><em> based on a limit</em></figcaption></figure><p>Taking our latest HPA manifest, we only need three values to discover the <strong><em>averageUtilization</em></strong> percentage we must set on our HPA. They are:</p><ul><li><strong>tP = target percentage </strong>(this is the 0–100 <em>requests</em> % we want to convert to the equivalent in <em>limits</em>),</li><li><strong>r = request (in this case, Mebibytes)</strong>, and</li><li><strong>l = limits (in this case, Mebibytes).</strong></li></ul><p>Previously, we had our target <strong><em>averageUtilization</em></strong> at 70% for our <em>requests</em>, so for that <strong>tP=70</strong>, the rest stays the same. We have memory requests of <em>60Mi,</em> so <strong>r=60</strong>, and memory <em>limits</em> of <em>450Mi</em>, so <strong>l=450</strong>.</p><p>Summarising, we have: tP=70, r=60, and l=450; And the linear equation translates to:</p><p>tU = tP * (l * tP / 100) / (r * tP / 100)<br>tU = 70 * (450 * 70 / 100) / (60 * 70 / 100)<br>tU = 70 * (450 * 0.7) / (60 * 0.7)<br>tU = 70 * 315 / 42<br>tU = 22050 / 42<br>tU = 525% (It’s a ratio of 7.5 over the 70%)</p><p>Reviewing it again, <strong>525%</strong> is the <em>requests’</em> average utilization, equivalent to <strong>70%</strong> of our <em>limits</em>. And you ask: H<strong>ow’s that?</strong> And I say: Apologies if I failed to make the math simple enough😅</p><blockquote>r=60 * 5.25 (525%) equals to <em>315Mi;</em> this same value, <em>315Mi,</em> is 70% of <em>450Mi (450 * 0.7 = 315)</em>.</blockquote><p>Of course, a mathematician would probably come up with a simpler formula. Please, feel free to give suggestions in the comments!👍</p><p>Remember, it’s all about trade-offs, and in the end, you must decide what’s best for your organization!</p><ul><li><a href="https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/">Resource Management for Pods and Containers</a></li><li><a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">Horizontal Pod Autoscaling</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92177cb5a378" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code inspection with SonarQube and Docker]]></title>
            <link>https://medium.com/@alexandre.highrollers/code-inspection-with-sonarqube-and-docker-4359c37fab12?source=rss-72e65b227730------2</link>
            <guid isPermaLink="false">https://medium.com/p/4359c37fab12</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Alexandre Souza]]></dc:creator>
            <pubDate>Tue, 19 May 2020 13:10:21 GMT</pubDate>
            <atom:updated>2023-05-15T10:03:10.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Code inspection with SonarQube</h3><p>Nowadays, delivering quality code at a fast pace is essential to have a great TTM (Time to Market), also keeping the product&#39;s maintainability attributes after release. Having too many bugs in the code because of poor design affects the success rate of your product.</p><p><a href="https://www.sonarqube.org/">SonarQube</a> is an open-source platform developed by <a href="https://www.sonarsource.com/">SonarSource</a> for continuous inspection of code quality to perform automatic reviews with static code analysis to detect bugs, code smells, and security vulnerabilities in many popular programming languages.</p><figure><img alt="SonarQube dashboard" src="https://cdn-images-1.medium.com/max/1024/1*1-KZ112UugrZ30KVdoL_Qg.png" /><figcaption>Sample project with several technical debits and 0% code coverage.</figcaption></figure><p>In the long term, SonarQube helps you improve your code, reducing or eliminating bugs and security threats. Also, check my article about reducing bugs with higher <a href="https://medium.com/@alexandre.higtrollers/code-coverage-with-coverlet-for-net-f69bba50d37c">code coverage</a>.</p><p>I am showing how to have SonarQube running in a Docker instance and how to push your code to it so that you can benefit from its analytics. Also, you get some advice on the best approach in a production environment.</p><p>An alternative is using <a href="https://sonarcloud.io/">SonarCloud</a>. They offer <a href="https://sonarcloud.io/pricing">free and paid plans</a>, though the free version exposes your code and analysis, being more suitable for OSS (open-source software) projects.</p><p>You might have to spend some time working on the metrics results produced to get your code neat, as your project might have bugs, code smells, low code coverage, and some vulnerabilities.</p><p>Another excellent feature is creating custom Quality Profiles, allowing you to be restrictive with your code.</p><p>Let us get started!</p><h3>Running on Docker</h3><p>First, you must have Docker running. You can get it from the <a href="https://www.docker.com/products/docker-desktop">Docker download page</a>.</p><p><em>We will use Docker for Linux and bitnami image as it comes with pre-installed plugins for the most common languages, including code rules for analyzing your code. They also have the latest features and bug fixes available soon.</em></p><p>Creates a volume and runs PostgreSQL:</p><pre># Creates a volume for PostgreSQL<br>docker volume create --name postgresql_data<br><br># Runs PostgreSQL image<br>docker run -d --name postgresql \<br>  -e ALLOW_EMPTY_PASSWORD=yes \<br>  -e POSTGRESQL_USERNAME=bn_sonarqube \<br>  -e POSTGRESQL_DATABASE=bitnami_sonarqube \<br>  -e POSTGRESQL_PASSWORD=bitnami1234 <br>  --net sonarqube-tier \<br>  --volume postgresql_data:/bitnami/postgresql \<br>  bitnami/postgresql:latest</pre><p>Creates a volume and runs SonarQube:</p><pre># Creates a volume for SonarQube<br>docker volume create --name sonarqube_data<br><br># Runs SonarQube<br>docker run -d --name sonarqube \<br>  -p 9000:9000 \<br>  -e ALLOW_EMPTY_PASSWORD=yes \<br>  -e SONARQUBE_DATABASE_USER=bn_sonarqube \<br>  -e SONARQUBE_DATABASE_NAME=bitnami_sonarqube \<br>  -e SONARQUBE_DATABASE_PASSWORD=bitnami1234 \<br>  --net sonarqube-tier \<br>  --volume sonarqube_data:/bitnami \<br>  bitnami/sonarqube:latest</pre><p>Once you run the Docker commands above, you&#39;ll have SonarQube running on port 9000, access it through <a href="http://localhost:9000/">http://localhost:9000</a> and credentials <strong>admin:bitnami</strong>. Check <a href="https://hub.docker.com/r/bitnami/sonarqube/">SonarQube bitnami</a> to learn more.</p><p>Make sure NOT to use the credentials above in production environments. Also, if deploying to K8s, use the <a href="https://github.com/helm/charts/tree/master/stable/sonarqube">bitnami Helm charts</a>.</p><h3>Installing SonarQube plugins</h3><p>If you can&#39;t find your language&#39;s quality gates and code rules, you can install them through <a href="https://docs.sonarqube.org/display/PLUG">SonarQube plugins</a>. <a href="https://binaries.sonarsource.com/">Here is the list</a> of available plugins.</p><p>Go to the &quot;<em>Analyzing your Code&quot;</em><strong> </strong>section if you don&#39;t need to install any plugins.</p><p>I am using a sample plugin (<em>sonar-tsql-plugin-1.4.0.3334.jar)</em> to demonstrate adding plugins to SonarQube. However, you might need some other plugin instead.</p><pre># Sample plugin download, latest version of the plugin JAR<br>sudo wget https://binaries.sonarsource.com/CommercialDistribution/sonar-tsql-plugin/sonar-tsql-plugin-1.4.0.3334.jar<br><br># Copy TSQL plugin to sonarqube running container<br>docker cp sonar-tsql-plugin-1.4.0.3334.jar &lt;container-id&gt;:/bitnami/sonarqube/extensions/plugins<br><br># Change the ownership of the sample plugin to sonarqube:sonarqube<br>docker exec -it &lt;container-id&gt; chown -R sonarqube:sonarqube /bitnami/sonarqube/extensions/plugins/sonar-tsql-plugin-1.4.0.3334.jar</pre><h3><strong>Analyzing your Code</strong></h3><p>First of all, you need to download <a href="https://docs.sonarqube.org/latest/analysis/overview/">SonarScanner</a>. It&#39;s a tool to push analyses and code coverage to SonarQube. I am using the <a href="https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/">SonarQube CLI</a>.</p><p><em>For simplicity, use an Access Token for the Admin account to publish code analysis. However, I suggest you organize your projects by groups and users for production cases, having each of your teams or projects a user token for publishing code analysis to SonarQube.</em></p><p>Once you&#39;ve configured the CLI tool, access the dashboard using the previously-mentioned credentials, go to <strong><em>My Account</em>, </strong>and then to the <strong><em>Security </em></strong>tab. Generate a Token for further use when publishing your code.</p><pre>sonar-scanner \<br>  -D sonar.host.url=http://localhost:9000 \<br>  -D sonar.projectKey=&lt;Your-Project-Key&gt; \<br>  -D sonar.projectName=&quot;Your Project Name&quot; \<br>  -D sonar.projectVersion=&lt;SemVer&gt; \<br>  -D sonar.login=&lt;Your-Token-Here&gt; \<br>  -D sonar.test.exclusions=tests/**/*.cs</pre><p>You don&#39;t have to create the <em>Project-Key</em> and <em>Project-Name</em> upfront; SonarQube does it for you! Organizing your projects and permissions before pushing code analysis is a good practice.</p><h3><strong>Working on the Analysis</strong></h3><p>In the screenshot below, you should see warnings regarding your code analysis as the second project. If you see all green, congrats, your code looks healthy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*wTaJ93mtMuG3_IVnmOlSFw.jpeg" /></figure><p>Keep working iteratively on the suggestions SonarQube gives you to improve your code with time.</p><h3>Next Steps</h3><p>It was just a tiny taste of configuring SonarQube locally. I suggest running it on a Kubernetes cluster, most likely deployed to two or more environments.</p><ul><li>The first is the Development or such environment, where developers can use it as a safe playground, pushing features or hotfix branches code to it,</li><li>And the second is the Production environment for final and approved code releases.</li></ul><p><em>The Development environment is optional, as developers can use </em><a href="https://www.sonarlint.org/"><em>SonarLint</em></a><em> to find issues in their code.</em></p><p>Also, when working with multiple projects and teams, structure and manage permission properly for pushing code analysis, otherwise, teams could override each other reports.</p><p>Consider <a href="https://sonarcloud.io/">SonarCloud</a> if you need a fast setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4359c37fab12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RESTful API for Distributed Hypermedia System]]></title>
            <link>https://medium.com/@alexandre.highrollers/restful-api-for-distributed-hypermedia-system-78dbfb8a58b9?source=rss-72e65b227730------2</link>
            <guid isPermaLink="false">https://medium.com/p/78dbfb8a58b9</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[restful-api]]></category>
            <dc:creator><![CDATA[Alexandre Souza]]></dc:creator>
            <pubDate>Fri, 15 May 2020 07:08:27 GMT</pubDate>
            <atom:updated>2023-05-15T09:41:51.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDGDQrD_k4MfK9ibtq7FHg.jpeg" /><figcaption>Sciensoft.Hateoas sample links.</figcaption></figure><h3>HATEOAS and the REST architecture style.</h3><p>HATEOAS stands for Hypermedia As The Engine Of Application State, and it&#39;s an element of the REST architectural style for distributed hypermedia systems.</p><p>The benefits of REST include loosely coupled clients and servers, improved portability, reliability, scalability, and network efficiency, plus independent evolvability for internet-scale applications.</p><p>Roy Fielding first presented REST in his <a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">doctoral dissertation</a>, comprising several constraints and sub-constraints for designing loosely coupled applications over HTTP. It is often used when developing web services.</p><p><em>Even 20+ years later, some developers and architects still not getting it right. By the way, an easy way to design a distributed RESTful API in ASP.NET is using </em><a href="https://github.com/higtrollers/Sciensoft.Hateoas"><em>Sciensoft.Hateoas</em></a><em>.</em></p><p>Continuing, the primary REST constraints are:</p><ul><li>Client-Server,</li><li>Stateless,</li><li>Cacheable,</li><li>Uniform Interface,</li><li>Layered System,</li><li>Code On-Demand (optional).</li></ul><p>We will be concentrating on the <em>Uniform Interface</em> constraint, which is one of the principal features of the REST architectural style. However, I will quickly walk you through all of them.</p><p><strong>Client-Server </strong>is related to the principle of separation of concerns by having the UI isolated entirely from data persistence, allowing them to evolve and scale independently.</p><p><strong>Stateless </strong>tackles the application architecture&#39;s requirement of improving visibility, reliability, and scalability. A server-side application that does not hold any server state or context allows it to better recover from failures and improves its observability and independent scaling.</p><p><strong>Cacheable</strong> is related to improving network efficiency and reducing latency across the network, and it requires that the data requested be implicitly or explicitly marked as cacheable.</p><p><strong>Uniform Interface</strong> applies the <a href="https://www.d.umn.edu/~tcolburn/cs4531/slides/software_engineering/principles/principles.xhtml">software engineering principle of generality</a> to improve interface visibility and simplify the architecture. The uniform interface has four sub-constraints:</p><ul><li>Identification of resources;</li><li>Manipulation of resources through representations;</li><li>Self-descriptive messages; and,</li><li>HATEOAS (hypermedia as the engine of application state).</li></ul><p><em>In this article, we will focus on HATEOAS, but for more information about the other sub-constraints, check </em><a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_2"><em>Fielding&#39;s dissertation</em></a><em>.</em></p><p><strong>Layered System</strong> allows the architecture to be composed hierarchically, and each layer is constrained to the layer it&#39;s communicating with and no further. It&#39;s a web API communicating with the following layered API, and this one to the next, and so on.</p><p><strong>Code On-Demand</strong> is an optional constraint in REST. However, it enables the client to be extended through existing scripts provided by the server, reducing the pre-implemented feature requirements.</p><h3>What is HATEOAS, and why is it essential?</h3><p>HATEOAS is a sub-constraint allowing clients to traverse resources using hypermedia links dynamically. The term &quot;<strong><em>hypermedia</em></strong>&quot; refers to any resource that links to other media forms, such as images, movies, and text.</p><p>A resource that implements HATEOAS will have a collection of links to other operations that might manipulate its representation state. In doing so, the client-side is loosely coupled with the server-side resources endpoints.</p><p>As per the code below, a JSON (the read-model) might have encapsulated links allowing UI developers to provide features such as Listing, Deleting, Updating, and others in a resource.</p><pre>{<br>    &quot;Id&quot;: &quot;8f46d29e-6c0d-4511-85e7-b1d7ae42934a&quot;,<br>    &quot;Title&quot;: &quot;The Girl Who Lived: A Thrilling Suspense Novel&quot;,<br>    &quot;Author&quot;: &quot;Christopher Greyson&quot;,<br>    &quot;Tags&quot;: [<br>        &quot;Fiction&quot;,<br>        &quot;Crime&quot;,<br>        &quot;Murder&quot;,<br>        &quot;Thriller&quot;<br>    ],<br>    &quot;links&quot;: [<br>        {<br>            &quot;method&quot;: &quot;GET&quot;,<br>            &quot;uri&quot;: &quot;http://localhost:6080/api/books/83389205-b1c9-4523-a3bb-85d7255546f9&quot;,<br>            &quot;relation&quot;: &quot;Self&quot;,<br>            &quot;message&quot;: &quot;This is a GET self link.&quot;<br>        },<br>        {<br>            &quot;method&quot;: &quot;PUT&quot;,<br>            &quot;uri&quot;: &quot;http://localhost:6080/api/books/83389205-b1c9-4523-a3bb-85d7255546f9&quot;,<br>            &quot;relation&quot;: &quot;UpdateBookById&quot;<br>        },<br>        {<br>            &quot;method&quot;: &quot;DELETE&quot;,<br>            &quot;uri&quot;: &quot;http://localhost:6080/api/books/83389205-b1c9-4523-a3bb-85d7255546f9&quot;,<br>            &quot;relation&quot;: &quot;DeleteBookById&quot;<br>        },<br>        {<br>            &quot;method&quot;: &quot;POST&quot;,<br>            &quot;uri&quot;: &quot;http://localhost:6080/api/books/83389205-b1c9-4523-a3bb-85d7255546f9&quot;,<br>            &quot;relation&quot;: &quot;Edit&quot;,<br>            &quot;message&quot;: &quot;Edits resource&quot;<br>        }<br>    ]<br>}</pre><h3>What are the benefits of HATEOAS?</h3><p>The main benefits would be improved visibility of interactions and loosely coupled client-side. Although the benefits below also apply:</p><ul><li>Client-side navigation through links,</li><li>Change of state made easy by links metadata,</li><li>Easy to identify and traverse resources representations,</li><li>Everything the UI needs is in one place,</li><li>Standardized information,</li><li>Cacheable.</li></ul><blockquote>The <strong>trade-off</strong>, though, is that a uniform interface degrades efficiency since information is transferred in a standardized form rather than one which is specific to an application’s needs. The REST interface is designed to be efficient for large-grain hypermedia data transfer, optimizing for the common case of the Web, but resulting in an interface that is not optimal for other forms of architectural interaction. (<a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5">Fielding, 2000, c. 5 s. 5.1.5</a>)</blockquote><p>An example of having a more specific form would be using technologies such as GraphQL, allowing you to request the &quot;resource representation&quot; you need and avoiding under or over-fetching data. Though GraphQL is a beautiful piece of technology, it has its downsides, and it&#39;s not HTTP caching specification compliant. Though, choose it wisely!</p><h3>When to use HATEOAS?</h3><p>Useful when designing distributed RESTful services, supplying links to the client-side for representation state transfer operations such as fetching or updating a resource.</p><p>Any Client-Server service or any RESTful API, Web API, or API Gateway can benefit from HATEOAS.</p><p>The client-side is loosely coupled to the RESTful API and can use the links provided for navigation across resources.</p><h3>Why use Sciensoft.Hateoas?</h3><p><a href="https://github.com/higtrollers/Sciensoft.Hateoas">Sciensoft.Hateoas</a> is my open-source project in .NET Core for achieving HATEOAS in RESTful and Web APIs.</p><p>It allows you to benefit from the link generation out of the box through a fluent API configuration.</p><p>The library currently supports the following:</p><ul><li>Attribute and Conventional routing configuration.</li><li>Collection results with links,</li><li><em>Json.NET</em> and <em>System.Text.Json </em>settings,</li><li>Self-link generation,</li><li>Named route link generation,</li><li>Custom link generation with support for path override,</li><li>External links configuration and,</li><li>Configuration with Lambda Expression.</li></ul><p>And features such as link configuration per endpoint, link generation based on user context authorization, and content negotiation in link metadata are under development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78dbfb8a58b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code coverage with Coverlet for .NET]]></title>
            <link>https://medium.com/@alexandre.highrollers/code-coverage-with-coverlet-for-net-f69bba50d37c?source=rss-72e65b227730------2</link>
            <guid isPermaLink="false">https://medium.com/p/f69bba50d37c</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[coverlet]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[code-coverage]]></category>
            <dc:creator><![CDATA[Alexandre Souza]]></dc:creator>
            <pubDate>Fri, 15 May 2020 07:01:04 GMT</pubDate>
            <atom:updated>2023-06-14T10:13:46.495Z</atom:updated>
            <content:encoded><![CDATA[<h3>Code coverage with Coverlet for .NET</h3><p>Code coverage measures how much of your source code is executed while tests are running, the measurement result is represented in percentage, and one or more coverage criteria are used as rules which tests must satisfy.</p><p><strong>Why measure code coverage?</strong> Doing that assures you that the program with a higher code coverage percentage will have a lower chance of undetected bugs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65vlUR49fezAhwW1zJ02kA.jpeg" /><figcaption>Sciensoft.Hateoas Sonarcloud code coverage report.</figcaption></figure><h3>About Coverlet</h3><p><a href="https://github.com/tonerdo/coverlet">Coverlet</a> is a cross-platform code coverage framework for .NET, supporting code lines, branch, and method coverage. It works with .NET Framework on Windows and .NET Core on all supported platforms.</p><p>Coverlet supports coverage results in several formats. The output format can be configured by CoverletOutputFormat property with values: json (default), lcov, opencover, cobertura, and teamcity.</p><p>It also supports <strong>VSTest</strong> and <strong>MSBuild</strong> type of integration, plus its own coverlet dotnet tool.</p><p>I prefer to have Coverlet integration with MSBuild as it writes to console output, it looks fantastic, and you have a simplified table with the results. The only downside is that it has some <a href="https://github.com/tonerdo/coverlet/blob/master/Documentation/KnownIssues.md#1-vstest-stops-process-execution-earlydotnet-test">known issues</a>. However, you can also pick the VSTest or Coverlet dotnet tool, and the results will be the same.</p><h3>Configuring Coverlet with MSBuild</h3><p>To get the advantage of Coverlet with MSBuild, you have only to add coverlet.msbuild to your test projects.</p><pre>dotnet add &lt;./MyProject.Tdd.csproj&gt; package coverlet.msbuild</pre><p><strong>IMPORTANT:</strong> Only add the package reference to the test projects.</p><p>You will find the packages below in your project file.</p><pre>&lt;PackageReference Include=&quot;coverlet.msbuild&quot; Version=&quot;2.8.1&quot;&gt;<br>    &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;<br>    &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>&lt;/PackageReference&gt;</pre><p>Once added, you have to run your tests, passing some parameters to the test tool.</p><pre>dotnet test ./MyProject.Tdd.csproj /p:CollectCoverage=true /p:CoverletOutputFormat=json</pre><p>It will produce the typical test output plus the coverage results, as shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*DFQqezS00Qv0c2NY.jpg" /><figcaption>Coverlet coverage results.</figcaption></figure><p>That’s all, and happy testing!</p><p>If you also want to push your code coverage to SonarQube, check this other article out:</p><p><a href="https://medium.com/@alexandre.highrollers/code-inspection-with-sonarqube-and-docker-4359c37fab12">Code inspection with SonarQube and Docker</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f69bba50d37c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Application Security]]></title>
            <link>https://medium.com/@alexandre.highrollers/basic-application-security-17f9f7f6cea3?source=rss-72e65b227730------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f9f7f6cea3</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Alexandre Souza]]></dc:creator>
            <pubDate>Fri, 15 May 2020 06:52:41 GMT</pubDate>
            <atom:updated>2023-12-04T14:22:46.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Basics of Application Security</h3><p>Ensuring robust security is paramount to the success of any product, yet it is a factor that is frequently overlooked. Recognizing this challenge, modern DevOps teams prioritize “shift-left” security practices, emphasizing the early integration of security measures and testing in the application development process.</p><p>In this post, I aim to shed light on common web application attacks and provide insights into effective protective measures. Additionally, I will underscore the essential security implementations that application developers should rigorously enforce.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ZD3qoeQo7Qddqc750zzzg.jpeg" /></figure><h3>Enforcing TLS/SSL</h3><p>Sites that process sensitive data should always use SSL. Most of the “secure” websites redirect their HTTP request to HTTPS. Below is the pseudocode explaining how to achieve it.</p><pre>// Request Pipeline Middleware Algorithm<br>start<br>    define function to verify request =&gt; f(x), x = HttpContext<br>  if x.Request url scheme is not HTTPS<br>    attribute and change the request url scheme to HTTPS to var newUrl<br>    redirect x.Response to newUrl<br>  end<br>finish</pre><p>The very first HTTP request, even when using SSL, is not encrypted. A man-in-the-middle attack could forgery this first request to his application version and gather users’ sensitive data. Some procedures must be applied to secure communication between the client and your application.</p><h3>Common Attacks and Solutions</h3><h3>HTTP Strict Transport Security — HSTS</h3><p>To avoid a man-in-the-middle attack by providing “his own version” of your application, add the <em>Strict-Transport-Security</em> (STS) HTTP header to your responses.</p><p>The <em>STS</em> header will add your web application to an internal list in the browser accessing it, and the browser will not allow future access to your Web App insecurely.</p><pre>Strict-Transport-Security: max-age=31536000; includeSubDomains; preload</pre><p>Adding the header above will restrict insecure access to your Web App for 31536000 seconds (1 year).</p><p><strong><em>Note:</em></strong><em> Once you’ve done it, there is no way back, and your web application will only be accessible through HTTPS.</em></p><p>To disable it, you’ll have to set the header as Strict-Transport-Security: max-age=0.</p><p>Another essential technique for avoiding that first insecure request is adding your domain to an HSTS preload list, which most modern web browsers support.</p><p>Once you’ve added your application domain to the <a href="https://hstspreload.org/">HSTS preload list</a>, any future release of those supported browsers will contain your domain in their internal list of secure domains. Any communication to that domain will only go through HTTPS.</p><h4>Browser Support</h4><ul><li>Edge &amp; Internet Explorer 11 on Windows 8.1 and Windows 7[2]</li><li>Firefox 4 +</li><li>Opera 12 +</li><li>Safari Mavericks (Mac OS X 10.9) +</li><li>Chrome 4.0.211.0 +</li></ul><h4>Frameworks</h4><ul><li>NWebsec.Mvc (ASP.NET)</li><li>helmetjs (NodeJs)</li><li>pyramid_hsts (Python)</li></ul><p><strong>References:</strong></p><ul><li><a href="https://hstspreload.org/">https://hstspreload.org/</a></li><li><a href="https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet">HTTP Strict Transport Security Cheat Sheet</a></li></ul><h3>Cross-Site Scripting (XSS)</h3><p>XSS is when attackers place JavaScript code into your application.</p><blockquote><em>It usually happens when applications provide data input forms with no input validation, and those inputs will be shown somewhere else in the app.</em></blockquote><p>A countermeasure is to encode any input provided. Depending on your application&#39;s framework, it will supply helpers to encode inputs or outputs.</p><p><strong>JavaScript:</strong></p><pre>var data = &quot;&lt;script&gt;alert(&#39;Hello World!&#39;);&lt;\/script&gt;&quot;;<br>var newData = escape(data); // encodeURI(data);<br><br>document.write(newData); // =&gt; %3Cscript%3Ealert(&#39;Hello%20World!&#39;);%3C/script%3E</pre><p><strong>C# &amp; .NET Core — ASP.NET MVC:</strong></p><pre>private readonly IHtmlGenerator _htmlGenerator;<br><br>public HomeController(IHtmlGenerator htmlGenerator)<br>  =&gt; _htmlGenerator = htmlGenerator ?? throw new ArgumentNullException(nameof(htmlGenerator));<br><br>public IActionResult Index()<br>{<br>  ViewBag.Data = @&quot;&lt;script&gt;alert(&#39;Hello World!&#39;);&lt;/script&gt;&quot;;<br>  ViewBag.Encoded = _htmlGenerator.Encode(ViewBag.Data);<br>  ViewBag.HtmlData = new HtmlString(ViewBag.Data);<br><br>  return View();<br>}</pre><pre>// View Index.cshtml <br>@ViewBag.HtmlData <br><br>// =&gt; executes the script <br>@Html.Raw(@ViewBag.Data) <br>// =&gt; executes the script <br>@ViewBag.Encoded <br>// show text =&gt; &amp;lt;script&amp;gt;alert(&amp;#x27;Hello World!&amp;#x27;);&amp;lt;/script&amp;gt; <br>@Html.Raw(@ViewBag.Encoded) <br>// show text =&gt; &lt;script&gt;alert(&#39;Hello World!&#39;);&lt;/script&gt;</pre><p>See also the <a href="https://github.com/higtrollers/Documentation/blob/master/brown.bags/web-application-security/quickstarts/XSS-and-CSP/XSS.html">XSS.html</a> sample.</p><h3>Content Security Policy (CSP)</h3><p>CSP allows you to restrict which resource type (such as JavaScript, CSS, Images, etc.) and the URLs from which they can be loaded. Simply by adding an HTTP header Content-Security-Policy: script-src &#39;self&#39; will disable the loading and execution of external or inline JavaScript. It cannot be used only for loading JavaScript but many other content types as per below:</p><ul><li>script-src</li><li>style-src</li><li>img-src</li><li>connect-src</li><li>media-src</li><li>frame-src</li><li>font-src</li><li>default-src (general configuration for all above)</li></ul><p><strong>Sample:</strong></p><pre>Content-Security-Policy: default-src &#39;self&#39;; script-src &#39;self&#39; *.googletagmanager.com techmeout.io cdnjs.cloudflare.com; connect-src &#39;self&#39; blob: *.google-analytics.com; style-src &#39;self&#39; &#39;unsafe-inline&#39;; img-src &#39;self&#39; data: logo.clearbit.com; font-src &#39;self&#39; fonts.gstatic.com; frame-src &#39;none&#39;;</pre><p>See also the <a href="https://github.com/higtrollers/Documentation/blob/master/brown.bags/web-application-security/quickstarts/XSS-and-CSP/CSP.html">CSP.html</a> sample or visit <a href="https://content-security-policy.com/">content-security-policy.com</a> for more comprehensive examples.</p><p><strong>References:</strong></p><ul><li><a href="https://content-security-policy.com/">https://content-security-policy.com/</a></li><li><a href="https://www.owasp.org/index.php/Content_Security_Policy_Cheat_Sheet">https://www.owasp.org/index.php/Content_Security_Policy_Cheat_Sheet</a></li><li><a href="https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html">https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html</a></li></ul><h3>Unvalidated Redirects &amp; Forwards / Open Redirect Attacks</h3><p>Unvalidated Redirects and Forwards exploits happen when attackers discover redirect mechanisms in your web application that transfer requests based on a query-string value provided.</p><p><strong>Sample:</strong></p><pre>https://somebank.ie/?returnUrl=http://somebank.net/login</pre><p>To secure your application against such a threat, configure the redirect mechanism to validate the URL “query-string” using a domain-allowed list. Some frameworks have helpers to validate local URLs.</p><h3>Cross-Site Request Forgery</h3><p>CSRF attackers create fake forms of, for example, a marketing campaign&#39;s page with inviting messages such as “You have won $1000!”. However, these forms contain hidden fields and action posts to the victim bank. Then, the victim subscribes to that fake campaign, and the form operation will, in reality, perform some other operation in the victim’s bank account. It’s a simple example, but it can happen with any further action. Typically, the attackers know the victim has access to specific apps and areas in those apps, and they use the victim’s app access to do operations on behalf of that user.</p><pre>&lt;!-- Fake form --&gt;<br>&lt;h1&gt;You have won $1000!&lt;/h1&gt;<br>&lt;form action=&quot;https://somebank.ie/api/transfer&quot; method=&quot;post&quot;&gt;<br>    &lt;input type=&quot;hidden&quot; name=&quot;Amount&quot; value=&quot;100000&quot; /&gt;<br>    &lt;input type=&quot;hidden&quot; name=&quot;AccountNumber&quot; value=&quot;ATK3R489456646465465&quot; /&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Click here to redeem!&quot; /&gt;<br>&lt;/form&gt;</pre><h4>Clickjacking</h4><p>Clicking-jacking threats are related to CSRF vulnerability, as attackers send users to their fake pages with buttons like “You have won $100” or some “call to action” type of message. When users click these links, they trigger a post through a hidden button/form into an iframe hosted on the attacker’s website.</p><p><em>This post could be to their bank money transfer form, which will transfer their money (as the victim may still be logged on) to someone else.</em></p><p>Adding the HTTP header Content-Security-Policy: frame-ancestors ‘none’; as shown below, lets you instantly control how and who will load your page into &lt;frame&gt;, &lt;iframe&gt;, &lt;embed&gt; or &lt;object&gt;.</p><pre>Content-Security-Policy: frame-ancestors &#39;none&#39;;<br><br>// Or <br><br>Content-Security-Policy: frame-ancestors &#39;self&#39; *.yourdomain.com;</pre><blockquote>Historically the X-Frame-Options header has been used for this, but it has been obsoleted by the frame-ancestors CSP directive in supporting browsers.</blockquote><p>The image below could be on a webpage, and once clicked, it would trigger a script execution without the end-user consent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*XnYY2LnpD4eGxpul.jpg" /><figcaption>clicking-jacking campaign sample</figcaption></figure><h3>SQL Injection</h3><p>SQL Injection is when attackers can execute malicious SQL statements in your database.</p><p>See also <a href="https://github.com/higtrollers/Documentation/tree/master/brown.bags/web-application-security/quickstarts/SQLInjection">SQL Injection Quickstart</a>, C# sample.</p><pre>public IActionResult Product(string value)<br>{<br>    var query = $&quot;select * from [DataEntry] where [Name] = &#39;{value}&#39;&quot;;<br>    // executes command with above query without validate the input<br>    // . . . code ommited for simplicity<br>}</pre><p>Some examples of SQL Injection statements are:</p><pre># Expose all entries on the table<br>&#39; OR 1=1 --<br><br># Executes destructive operation<br>gone&#39;; DROP TABLE [DataEntry]<br><br># Executes ultimate destructive operation<br>&#39;; BEGIN TRY DROP TABLE #TempEvil; END TRY BEGIN CATCH END CATCH; SELECT [name] INTO #TempEvil FROM [sys].[databases] WHERE [name] = &#39;SqlInjection&#39;; DECLARE @counter INT; DECLARE @au_id CHAR(55); SET @counter = 1; SELECT @au_id = min([name]) FROM #TempEvil; WHILE @counter &lt;= 1 BEGIN EXEC(&#39;ALTER DATABASE &#39; + @au_id + &#39; SET OFFLINE WITH ROLLBACK IMMEDIATE; DROP DATABASE &#39; + @au_id + &#39;;&#39;); SET @counter = 2; END; --<br><br># Beautify<br>BEGIN TRY DROP TABLE #TempEvil; END TRY BEGIN CATCH END CATCH;<br>SELECT<br>  [name]<br>INTO #TempEvil<br>FROM sys.[databases]<br>WHERE [name] = &#39;SqlInjection&#39;<br><br>DECLARE @counter INT;<br>DECLARE @au_id CHAR(55);<br><br>SET @counter = 1;<br><br>SELECT @au_id = min([name]) FROM #TempEvil;<br><br>WHILE @counter &lt;= 1--@au_id IS NOT NULL<br>BEGIN<br>  EXEC(&#39;ALTER DATABASE &#39; + @au_id + &#39; SET OFFLINE WITH ROLLBACK IMMEDIATE; DROP DATABASE &#39; + @au_id + &#39;;&#39;);<br>  SET @counter = 2;<br>  --ALTER DATABASE [SqlInjection];<br>  --SET OFFLINE WITH ROLLBACK IMMEDIATE;<br>  --DROP DATABASE [SqlInjection];<br>  --SELECT * FROM #TempEvil WHERE [name] = @au_id<br>  --SELECT @au_id = min([name]) FROM #TempEvil WHERE [name] &amp;gt; @au_id<br>END;</pre><p><strong>How to secure your app against SQL Injection?</strong></p><ul><li>Validate Inputs</li><li>Last privilege account (specific grant access)</li><li>ORM (Object Relational Mapper) — Entity Framework, NHibernate, Django ORM</li></ul><p><strong>WARN:</strong> ORMs can be vulnerable when working with Store-Procedures.</p><p><strong>References:</strong></p><ul><li><a href="https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/">SQL Injection Cheat Sheet</a></li><li><a href="https://security.stackexchange.com/questions/128412/sql-injection-is-17-years-old-why-is-it-still-around">Why is SQL Injection…</a></li></ul><h3>Cross-Origin Resource Sharing — CORS</h3><p>It is a browser mechanism that restricts (cross-domain) resource requests.</p><p><strong>HTTP Request Headers:</strong></p><pre>Access-Control-Request-Method: POST<br>Access-Control-Request-Headers: X-PINGOTHER, Content-Type</pre><p><strong>HTTP Response Headers:</strong></p><pre>Access-Control-Allow-Origin: *.techmeout.io<br>Access-Control-Allow-Methods: POST, GET, OPTIONS<br>Access-Control-Allow-Headers: X-PINGOTHER, Content-Type</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/0*qFzQnMaWRjUZWWGq.jpg" /><figcaption>UML Sequence Diagram of an HTTP request.</figcaption></figure><p><strong>References:</strong></p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">Access control CORS</a></li><li><a href="https://app.pluralsight.com/player?course=asp-dot-net-core-security-understanding&amp;author=roland-guijt&amp;name=c34a5efc-a275-4675-bc0d-495aefb5ed1a&amp;clip=0&amp;mode=live">ASP.NET — Common Attacks</a></li><li><a href="https://app.pluralsight.com/library/courses/https-every-developer-must-know/table-of-contents">What Every Developer Must Know About HTTPS</a></li><li><a href="https://www.owasp.org/index.php">OWASP</a></li><li><a href="https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project#OWASP_Top_10_for_2013">OWASP List</a></li><li><a href="https://www.owasp.org/index.php/Category:Attack">OWASP Attacks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f9f7f6cea3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>