<?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 Sebastian Curland on Medium]]></title>
        <description><![CDATA[Stories by Sebastian Curland on Medium]]></description>
        <link>https://medium.com/@sebcurland?source=rss-b2ac41d816df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZCeZX7AhRdHkZEQQBaTD8w.jpeg</url>
            <title>Stories by Sebastian Curland on Medium</title>
            <link>https://medium.com/@sebcurland?source=rss-b2ac41d816df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:39:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sebcurland/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[New JS features in Node.js v14.0]]></title>
            <link>https://medium.com/@sebcurland/new-js-features-in-node-js-v14-0-6d833c7665b6?source=rss-b2ac41d816df------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d833c7665b6</guid>
            <category><![CDATA[nullish-coalescing]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[optional-chaining]]></category>
            <dc:creator><![CDATA[Sebastian Curland]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 12:29:16 GMT</pubDate>
            <atom:updated>2020-04-24T12:31:41.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*b544jCqMC3sLwlVNxBtO_Q.jpeg" /><figcaption>source: <a href="http://www.pikrepo.com/">www.pikrepo.com</a></figcaption></figure><p>Node.js v14.0 was released this week, becoming the <em>Current</em> release. That means that in six months, by the end of October 2020, it will be moved to <em>Active LTS</em> (long-term-support) status and will be ready for general use.</p><p>Node.js v14.0.0 was updated to use <strong>V8 8.1</strong>, which brings support for the latest JS features. In this article, I would like to do a recap of those exciting features.</p><h4>Optional Chaining</h4><p>If you are a JS developer you probably ran into code where you need to check if an object property is <em>null</em> or <em>undefined</em> before accessing it, like in the following code:</p><pre>if(user &amp;&amp; user.details) {<br>  const name = user.details.name<br>}</pre><p>This type of code is not declarative, and it is very error-prone — I’m pretty sure you are already familiar with the error <strong><em>Cannot read property ‘xxx’ of undefined.</em></strong><br>This also has the (unwanted) consequence of checking for all <em>truthy</em> values instead of checking only <em>non-nullish</em> values.</p><p>V8 version 8.0 introduced <strong>Optional Chaining</strong> and its operator ?. , so the above code can be rewritten to:</p><p>const name = user?.details?.name</p><p>What happens if <em>user</em> or <em>details</em> are undefined? JavaScript initializes <em>name</em> to undefined instead of throwing an error.</p><p>Other use-cases where Optional Chaining operator come in handy:</p><pre>// user.details is deleted only if user is defined<br>delete user?.details</pre><pre>// Use operator <strong>?.()</strong> to call optional methods<br>const adminOption = user?.prefs?.getPrefs?.().option</pre><pre>// Use operator <strong>?.[]</strong> to access dynamic properties<br>const rolesCount = user?.preferences?.[&#39;roles&#39;].length</pre><pre>// If usersArray is null or undefined then name will be undefined<br>const userIndex = 5<br>const name = usersArray?.[userIndex].name</pre><h4>Nullish Coalescing</h4><p>A common pattern in Javascript is to use the || operator to set default values, like in the below example:</p><pre>function convertUser(user) {<br>  const isActive = user.active || true<br>}</pre><p>But what would happen if user.active is false? Then the variable <em>isActive</em> will still be <em>true, </em>probably causing an unexpected behavior in our code.</p><p>V8 version 8.0 gives us the <strong>Nullish Coalescing</strong> operator ?? that can be used instead of || to fix the above bug:</p><pre>const isActive = user.active ?? true</pre><p><em>isActive</em> will be true if <em>user.active</em> is <em>null</em> or <em>undefined</em> but will be false if <em>user.active</em> is falsy.</p><h4>Optional Chaining + Nullish Coalescing</h4><p>Nullish Coalescing can be used to set a default value when using optional chaining. In the below example <em>name</em> will be <em>unknown</em> if the user object does not have a <em>name</em> property inside <em>details</em>.</p><p>const name = user?.details?.name ?? &#39;unknown&#39;</p><p>The last two features are related to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"><em>Intl</em> module</a>.</p><blockquote>The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.</blockquote><h4>Intl.DisplayNames</h4><p>The new Intl.DisplayNames API allows us to get translations of language, currency, and region names in different languages. For example, let’s say we want region names in Spanish, we can use the following code:</p><pre>const regionNames = new Intl.DisplayNames([&#39;es&#39;], {type: &#39;region&#39;})</pre><pre>regionNames.of(&#39;FR&#39;) // &#39;Francia&#39;<br>regionNames.of(&#39;US&#39;) // &#39;Estados Unidos&#39;</pre><p>Or if we want to get language names in French:</p><pre>const langNames = new Intl.DisplayNames([&#39;fr&#39;], {type: &#39;language&#39;})</pre><pre>langNames.of(&#39;ES&#39;) // &#39;espagnol&#39;<br>langNames.of(&#39;EN&#39;) // &#39;anglais&#39;</pre><p>And lastly, let’s see an example of getting currency names in Simplified Chinese:</p><pre>const currencyNames = new Intl.DisplayNames([&#39;zh-Hans&#39;], {type: &#39;currency&#39;});</pre><pre>currencyNames.of(&#39;USD&#39;) // &#39;美元&#39;<br>currencyNames.of(&#39;EUR&#39;) // &#39;欧元&#39;</pre><h4>Intl.DateTimeFormat options</h4><p>The Intl.DateTimeFormat API is used to work with language-specific date and time formatting. For example:</p><pre>const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0))</pre><pre>// British English uses day-month-year order<br>console.log(new Intl.DateTimeFormat(&#39;en-GB&#39;).format(date))<br>// &quot;19/12/2012&quot;</pre><p>The date and time formats can be customized using the options argument in the DateTimeFormat constructor.</p><p>This API is not new and was added to V8 in the past, but now it supports <em>calendar</em> and <em>numberingSystem</em> options:</p><pre>const options = {calendar: &#39;chinese&#39;, numberingSystem: &#39;arab&#39;}<br>const dateFormat = new Intl.DateTimeFormat(&#39;default&#39;, options)</pre><p>All the above features come with Node.js v14.0 by default. Also, the version includes other non-V8-related features that you can read about in the <a href="https://nodejs.org/en/blog/release/v14.0.0/">release notes</a>. I would probably write more about them in the coming months.</p><p>Thanks for reading! I hope you enjoyed this article. Let me know if you have any comments or feedback.</p><p>Stay tuned for more Node.js articles and follow me on Twitter <a href="https://twitter.com/sebcurland">https://twitter.com/sebcurland</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d833c7665b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The power of Async Hooks in Node.js]]></title>
            <link>https://medium.com/@sebcurland/the-power-of-async-hooks-in-node-js-8a2a84238acb?source=rss-b2ac41d816df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a2a84238acb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[asynchooks]]></category>
            <category><![CDATA[node-js-development]]></category>
            <dc:creator><![CDATA[Sebastian Curland]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 20:52:06 GMT</pubDate>
            <atom:updated>2020-03-30T10:24:35.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*zSzjvD556Oty00T-dP9f9A.png" /></figure><p>Theasync_hooks module provides an API to track asynchronous resources in Node.js. An async resource is an object with a callback function associated with it. Because of Node’s nature, almost all things happening under the hood in Node.js are asynchronous calls, and a lot of these async resources are created.</p><p>Examples of async resources are <strong>Promises</strong>, <strong>Timeouts</strong>, <strong>Immediates</strong> (when calling <em>setImmediate</em>), <strong>TickObject</strong> (when calling <em>process.nextTick</em>), <strong>TCPWRAP</strong> (when creating a server). <br>You can find the full list of async resources in the <a href="https://nodejs.org/dist/latest-v13.x/docs/api/async_hooks.html">Async Hooks docs</a>.</p><p>Before deep-diving into useful examples, let’s do a quick overview of the Async Hooks API.</p><h3>API basics</h3><p>The API provides the following events to track the life-cycle of async resources:</p><ul><li><strong>init</strong> — called when an async resource is initialized.</li><li><strong>before/after</strong> — called just before/after the callback associated with the async resource is executed.</li><li><strong>destroy</strong> — called after the resource is destroyed.</li><li><strong>promiseResolve</strong> — called when the resolve function of the Promise constructor is invoked.</li></ul><p>When creating an <em>AsyncHooks</em> instance, you need to specify which of the above events you want to be triggered, and for each of those events, a callback function should be provided.</p><pre>// Only <em>init</em> and <em>destroy</em> are used in this example</pre><pre>const async_hooks = require(&#39;async_hooks&#39;)<br>const asyncHook = async_hooks.createHook({ init, destroy })<br>asyncHook.enable()</pre><pre>function init(asyncId, type, triggerAsyncId, resource) { // code }<br>function destroy(asyncId) { // code }</pre><p>The <strong>init</strong> callback gets these parameters:</p><ul><li><strong>asyncId</strong> — unique ID of the async resource.</li><li><strong>type</strong> — a string representing the type of the async resource (e.g., <em>Promise</em>, <em>Timeout</em>, <em>Immediate, TCPWRAP, etc.</em>).</li><li><strong>triggerAsyncId</strong> — the unique ID of the async resource in whose execution context this async resource was created.</li><li><strong>resource</strong> — an object that represents the actual async resource and contains information about it.</li></ul><p>The <strong>before</strong>, <strong>after</strong>,<strong> destroy,</strong> and <strong>PromiseResolve </strong>callbacks only get the asyncId of the resource.</p><h3>Using console.log() in AsyncHooks callbacks</h3><p>Hopefully, this module caught your attention by now, and all you want is to print to the console all the async resources in your application. You’ll probably end up writing something like this:</p><pre>const async_hooks = require(&#39;async_hooks&#39;)<br>const asyncHook = async_hooks.createHook({ init })<br>asyncHook.enable()</pre><pre>function init(asyncId, type, triggerAsyncId, resource) {<br>  console.log(asyncId, type)<br>}</pre><p>Running the above code will output:</p><blockquote><strong>RangeError: Maximum call stack size exceeded</strong></blockquote><p>The reason is that <em>console.log()</em> is an asynchronous operation in Node.js. That means that when the <em>init</em> callback runs, <em>console.log()</em> will trigger a new <em>init</em> event, producing an endless recursion, and in the end, reaching the maximum call stack size.</p><p>To work around this problem, you can use a synchronous print function instead of <em>console.log().</em> For example fs.writeFileSync will print to the console and will not invoke AsyncHooks recursively because it is synchronous.</p><pre>function debug(...args) {<br>  fs.writeFileSync(1, `${util.format(...args)}\n`, { flag: &#39;a&#39; });<br>}</pre><pre>function init(asyncId, type, triggerAsyncId, resource) {<br>  debug(asyncId, type)<br>}</pre><p>Ok, this should cover the basics of the API. If you want to get more details on Async Hooks API, just check <a href="https://nodejs.org/dist/latest-v13.x/docs/api/async_hooks.html#async_hooks_async_hooks">Node’s docs</a>. <br>Let’s see now some examples and use-cases on how and when to use async hooks.</p><h3>Async / await</h3><p>It is a common misbelief that async/await is just syntactic sugar on top of Promises. While it is true that async/await is implemented with Promises under the hood, there are some differences to using explicit promises in your code. With async hooks, we can check the <em>Promise</em> resources being created when using async/await:</p><pre>// init async hook<br>function init(asyncId, type, triggerAsyncId, resource) {<br>  debug(asyncId)<br>}</pre><pre>// two functions with async/await<br>const computeAnswer = async () =&gt; { 123 }</pre><pre>(async () =&gt; {<br>  await computeAnswer()<br>})()</pre><pre>// Output:<br>// when running on Node &lt; v12.0.0<br>5 &#39;PROMISE&#39;<br>6 &#39;PROMISE&#39;<br>7 &#39;PROMISE&#39;<br>8 &#39;PROMISE&#39;<br>9 &#39;PROMISE&#39;</pre><pre>// when running on Node &gt;= v12.0.0<br>2 PROMISE 1<br>3 PROMISE 1<br>4 PROMISE 3</pre><p>The <em>computeAnswer</em> and the <em>immediately-invoked</em> functions return a Promise, so two <em>Promise</em> resources are created for them. If the above program is executed in a Node version smaller than v12.0.0, then the await creates three additional Promises.<br>When running the code in Node 12, we can see that only three <em>Promise</em> resources are created in total, and this is because of the <a href="https://v8.dev/blog/fast-async">Async performance improvements</a> in V8 that were included in Node 12.</p><h3>Profiling — Measuring the duration of async operations</h3><p>When we combine the Async Hooks module with the <a href="https://nodejs.org/dist/latest-v12.x/docs/api/perf_hooks.html">Performance API</a> — another core module in Node, we can do more exciting things like measuring the duration of asynchronous operations.</p><p>Let’s explore a simple example that illustrates this — the below example measures the real-time that takes to execute a <em>timeout</em> operation, including the time that takes to execute its callback function.</p><pre>const async_hooks = require(&#39;async_hooks&#39;)<br>const {performance, PerformanceObserver} = require(&#39;perf_hooks&#39;)</pre><pre>const set = new Set()<br>const hook = async_hooks.createHook({<br>  init(id, type) {<br>    if (type === &#39;Timeout&#39;) {<br>      performance.mark(`Timeout-${id}-Init`)<br>      set.add(id)<br>    }<br>  },<br>  destroy(id) {<br>    if (set.has(id)) {<br>      set.delete(id);<br>      performance.mark(`Timeout-${id}-Destroy`)<br>      performance.measure(`Timeout-${id}`,<br>                          `Timeout-${id}-Init`,<br>                          `Timeout-${id}-Destroy`)<br>    }<br>  }<br>})<br>hook.enable()</pre><pre>const obs = new PerformanceObserver((list, observer) =&gt; {<br>  console.log(list.getEntries()[0])<br>  performance.clearMarks()<br>  observer.disconnect()<br>})<br>obs.observe({ entryTypes: [&#39;measure&#39;], buffered: true })</pre><pre>setTimeout(() =&gt; {}, 1000)</pre><p>And the output is:</p><pre>PerformanceEntry {<br>  name: &#39;Timeout-3&#39;,<br>  entryType: &#39;measure&#39;,<br>  startTime: 40.573846,<br>  duration: 1004.292745<br>}</pre><p>In the init hook, a <em>PerformanceMark</em> is created if the type of the async resource created is <em>Timeout, </em>and the id of that timeout resource is stored in a Set.<br>When the timeout resource is destroyed (meaning that its callback is completed), we add another <em>PerformanceMark</em> for the destroy event. We measure, using the Performance module, the time of the two marks — when the timeout resource was created (startTime) and when it was destroyed (duration).</p><p>In the profiling-land, <a href="https://clinicjs.org/">clinic.js</a> has a tool called <em>Bubbleprof</em> that helps users to determine where asynchronous time is spent in their application. <em>Bubbleprof</em> tries to collect and aggregate <em>all</em> async operations — using Async Hooks, and then group them into visual bubbles based on this analysis.</p><h3>Execution Context</h3><p>Another popular use-case for Async Hooks is storing context data like it’s done with <em>thread-local</em> <em>storage</em> in other programming languages. Suppose you have a web application, and you want to access data that is included in an HTTP request, like a user id in some header. You want to get this id in the different layers of your application, like in the business logic layer and the data-access layer. A straightforward solution would be to pass the request object to every function on every layer so you will be able to get the user id. But this solution is against Clean Code principles — why your business logic or the data-access code should “know” about HTTP request objects?</p><p>The solution would be to store the request data (the context) and provide a getter to get the context at any time, everywhere in the code. Also, it would be nice to remove the request context data once the request is fulfilled. This can be achieved easily with Async Hooks:</p><pre>asyncHooks.createHook({ init, destroy }).enable()<br>const reqContextMap = new Map()</pre><pre>function createRequestContext (data) {<br>  reqContextMap.set(asyncHooks.executionAsyncId(), data)<br>}</pre><pre>function getRequestContext () {<br>  return reqContextMap.get(asyncHooks.executionAsyncId())<br>}</pre><pre>function init (asyncId, type, triggerAsyncId, resource) {<br>  // Store same context data for child async resources<br>  if (reqContextMap.has(triggerAsyncId)) {<br>    reqContextMap.set(asyncId, reqContextMap.get(triggerAsyncId))<br>  }<br>}</pre><pre>function destroy (asyncId) {<br>  if (reqContextMap.has(asyncId)) {<br>    reqContextMap.delete(asyncId)<br>  }<br>}</pre><p>The way this work is when the server gets a new request the createRequestContext function is called with the data we want to store for the request. The data is stored in a Map with the <em>executionAsyncId</em> as the key. Every async operation, like Promises, that are created as part of the current request, will be added to the Map with the same context data that was saved initially for the request (this is what the init hook does).<br>The destroy hook will do the cleanup, making sure the Map size does not endlessly grow.<br>Finally, everywhere in the code, you can call getRequestContext to get the data of the current execution context, without knowing nothing about HTTP requests.</p><p>Luckily for us, Node has this functionality built-in in the Async Hooks module, with the <a href="https://nodejs.org/dist/latest-v13.x/docs/api/async_hooks.html#async_hooks_class_asynclocalstorage">AsyncLocalStorage</a> class that was added in Node v13.10.0.<br>This class provides a high-level API on top of async hooks. Since it’s part of Node core, it’s supposed to be more stable and to have better performance than other custom solutions like the code example above or other popular packages like <a href="https://www.npmjs.com/package/node-cls">CLS — Continuation Local Storage</a> (of course, once the async hooks API becomes officially stable and not experimental like it is today, as of April 2020).</p><h3>Enhanced Stack Traces</h3><p>Back in 2011, Ryan Dahl — the man behind Node.Js, gave an <a href="https://www.youtube.com/watch?feature=youtu.be&amp;v=jo_B4LTHi3I&amp;app=desktop">introductory talk about Node.JS</a>, and when talking about debuggability problems he said:</p><blockquote>there’s this problem with event loops which is that you’re always killing your stack, your stacks are very short</blockquote><p>What Ryan Dahl is pointing out is the fact that, in Javascript, when executing the callbacks of asynchronous operations, the call stack is empty.</p><p>With Async Hooks we have a way to capture the stack traces of async operations and, similar to what we did with execution context, we can save the stack traces and get them whenever there is an error:</p><pre>const asyncHooks = require(&#39;async_hooks&#39;)<br>const stackMap = new Map()</pre><pre>asyncHooks.createHook({ init }).enable()</pre><pre>function init(asyncId, type, triggerAsyncId) {<br> const parentStack = stackMap.get(triggerAsyncId) || &#39;&#39;<br> let currentStack = {}<br> Error.captureStackTrace(currentStack)<br> stackMap.set(asyncId, currentStack.stack + parentStack)<br>}</pre><pre>const getError = function (...args) {<br> const err = new Error(...args)<br> err.stack += stackMap.get(asyncHooks.executionAsyncId())<br> return err<br>}</pre><p>Eight years after Ryan Dahl’s talk, V8 added <a href="https://docs.google.com/document/d/13Sy_kBIJGP0XT34V1CV3nkWya4TwYx9L3Yv45LdGB6Q/edit">Async Stack Traces</a> to the engine (release v7.3) which was included in Node v12.<br>V8’s Async stack traces provide similar functionality to the above code (and probably works much faster), with the only drawback that they don’t work with Promise.then() and Promise.catch() .</p><h3>Worker Threads</h3><p>If you are already using or planning to use Node’s worker threads and combine them with Async Hooks API, you need to keep in mind that each thread will have an independent async_hooks interface, and each thread will use a new set of async IDs.</p><p>In this case, what will come in handy is the AsyncResource class from Async Hooks module that allows us to create custom async resources that will benefit from the Async Hooks API.</p><p>There is an excellent <a href="https://nodejs.org/dist/latest-v13.x/docs/api/async_hooks.html#async_hooks_using_asyncresource_for_a_worker_thread_pool">example</a> in Async Hooks documentation that demonstrates how to use the AsyncResource class to provide async tracking for a Worker pool.</p><p>Thanks for reading! I hope you enjoyed this article. Let me know if you have any comments or feedback.</p><p>Stay tuned for more Node.js articles and follow me on Twitter <a href="https://twitter.com/sebcurland">https://twitter.com/sebcurland</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a2a84238acb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When DevOps met Security — DevSecOps in a nutshell]]></title>
            <link>https://medium.com/@sebcurland/when-devops-met-security-devsecops-in-a-nutshell-b228386c30f6?source=rss-b2ac41d816df------2</link>
            <guid isPermaLink="false">https://medium.com/p/b228386c30f6</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[shiftleft]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sebastian Curland]]></dc:creator>
            <pubDate>Mon, 12 Mar 2018 09:52:21 GMT</pubDate>
            <atom:updated>2018-03-12T09:52:21.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*a--ng-FOc65yYNikMgOkQA.jpeg" /></figure><h3>The Creation of Security 😆</h3><p>In the beginning there was only Waterfall and chaos. But then Agile was created and with it new processes and tools rose from the ashes. DevOps, Continuous Integration, Continuous Delivery, Continuous Deployment, Automation, Alice and Bob. Everything was beauty and perfection. Almost.</p><p>One day, Alice and Bob were in the Garden of the Web. There were many trees in the garden but one was special. It was the Tree of Code. It had good O(1) code and malicious code. Alice and Bob executed the malicious code. Suddenly, the perfect web was not so perfect, it was full of vulnerabilities. From that moment Alice and Bob were not the same. No one recognized them. They were… Anonymous. And the web? The web was not secure anymore.</p><h3>The DevOps Era</h3><p>With the move from Waterfall to Agile development methodology, the development teams moved from long development cycles to short sprints that helped to reduce the time to market. But that was not possible without DevOps.</p><p>DevOps brought us new processes and tools that focused on testing and automation. And speed. Developers are now able to release new features and hotfixes to Production in a matter of minutes, and that, of course, after unit tests and the whole <a href="https://martinfowler.com/bliki/TestPyramid.html">testing pyramid</a> ran on the code, several times and in different environments before Production. With DevOps, developers can deliver continuously high quality applications that can be easily monitored and maintained.</p><h3>Security — the missing link</h3><p>Ok, high quality applications delivered fast, but no one said secure applications.</p><p>Traditionally, security was involved only at the end of the development cycle. That is during the testing phase, the deployment phase or even after the application was already deployed. Either way finding a security vulnerability in those phases meant a delay in the release and a lot of pressure to patch the vulnerability if the code was already in Production.</p><blockquote>The way we’ve traditionally approached security doesn’t scale in a DevOps world.</blockquote><p>I found somewhere that the cost for fixing vulnerabilities is <strong>30x higher</strong> after the application has been deployed. In reality that number can be even higher, like in the <em>Equifax</em> case where their shares went down ~14% in one day after they publicly announced a security breach.</p><h4>Shift Security Left</h4><p>Shift Left model means to put efforts in finding security vulnerabilities during the first phases of the development cycle, during planning, design and coding. It also means educating and guiding developers on security coding practices and help them to test for security during the coding phase.</p><h4><strong>Continuous Security</strong></h4><p>The shift left model together with DevOps creates a new world of possibilities where security is integrated in all parts of the DevOps cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*EJ1bsViwpLdIwqVI." /></figure><p>So, <strong>DevOps</strong> + <strong>Continuous Security</strong> = <strong>DevSecOps</strong>. <br>And <strong>with DevSecOps we can deliver secure software at DevOps speed</strong>.</p><h3>DevSecOps in practice</h3><p>The following is a list of real things that you can do in order to secure the DevOps pipeline.</p><h4>Risk analysis and threat modeling during planning</h4><p>Risk analysis and threat modeling can help develop applications that are secure from the very beginning. The first step in the threat modeling process is to understand the application or the features that will be developed. You need to understand how the application will be used, what are the entry points that can be used by potential attackers, which data will be exposed and what are the permissions required for the new code.</p><p>Once you identify the potential threats, the second step in the threat modeling is to categorize the threats (models like <a href="https://en.wikipedia.org/wiki/STRIDE_(security)">STRIDE</a> or <a href="https://msdn.microsoft.com/en-us/library/ff649461.aspx">Application Security Frame</a> will help you in the categorization process) and give them a “security risk” value or rank (check the <a href="https://en.wikipedia.org/wiki/DREAD_(risk_assessment_model)">DREAD</a> model for that).</p><p>The third step would be to define a mitigation plan for the threats found. In most cases the threats with the higher security risk will be mitigated first, although sometimes threats that have a lower risk but a high business impact will be handled first.</p><h4>Security code reviews</h4><p>I’m almost certain that every developer heard about code reviews and hopefully many of them are doing it. But how many heard about security code reviews?</p><p>Security code reviews are a powerful tool to find vulnerabilities early in the software development life cycle and they are a complement for the risk analysis and threat modeling. Static code analysis tools does not understand the context in the code and sometimes an additional pair of eyes on the code are the only way to have a security flawless application.</p><p>For the code reviewer is important to understand the business purpose of the application and the critical business impacts. As in the threat modeling phase, the reviewer should be familiar with the entry points of the application and think how the application can be potentially attacked. In order to do a productive code review, the reviewer should be also familiar with the (sensitive) data that is being exposed and with the user roles and access rights of the application.</p><p>A security code review should be focused on the following areas:</p><ul><li>Data Validation</li><li>Authentication</li><li>Session Management</li><li>Authorization</li><li>Cryptography</li><li>Error Handling</li><li>Logging</li><li>Configurations</li><li>Network Architecture</li></ul><h4>Static code analysis</h4><p>The purpose of static code analysis tools is to find vulnerabilities by scanning the source code (‘static’ code) of your application during the development phase. This kind of tools are good in finding vulnerabilities that have a certain pattern, like SQL Injections, malicious regular expressions, buffer overflow, etc. In the other hand, static code analysis tools will often produce false positives — vulnerabilities that in fact are not.</p><p>Some tools can be integrated into the IDE so the developer will get live alerts while writing the code. Other tools can be integrated in CI build systems like Jenkins, so the code will be analyzed during the build phase.</p><p>Some examples of Open Source static code analysis tools are <a href="https://www.sonarqube.org/">SonarQube</a> and the <a href="https://github.com/nodesecurity/eslint-plugin-security">security plugin</a> of <a href="https://eslint.org/">ESLint</a> (for Javascript).</p><h4>Dependencies analysis</h4><blockquote>The security of your application is only as strong as the weakest link in your dependencies</blockquote><p>Most of the the code that you’ll have in your application will come from third-party dependencies. When we find a dependency that does what we need we feel excited that we saved time writing that code and we blindly trust that piece of code as if it were ours. But unfortunately if that dependency has vulnerabilities our application will be exposed and vulnerable as well.</p><p>Tools like <a href="https://www.owasp.org/index.php/OWASP_Dependency_Check">OWASP Dependency Check</a> and <a href="https://snyk.io/">Snyk</a> can help you find vulnerabilities in your dependencies and you should integrate them during a pre-commit stage, before your code is merged into the “master” branch.</p><p>In my next blog posts I’ll deep dive into DevSecOps practices and how to implement them. Stay tuned!</p><p>Follow me on twitter <a href="https://twitter.com/sebcurland">@sebcurland</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b228386c30f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveling Security Up With Snyk]]></title>
            <link>https://medium.com/@sebcurland/leveling-security-up-with-snyk-40e25737b303?source=rss-b2ac41d816df------2</link>
            <guid isPermaLink="false">https://medium.com/p/40e25737b303</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sebastian Curland]]></dc:creator>
            <pubDate>Sat, 19 Aug 2017 12:30:24 GMT</pubDate>
            <atom:updated>2017-10-01T11:12:06.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*hAiwCQVI3bHWz4Viqm3sRw.jpeg" /></figure><p>The number nine in OWASP Top 10 Application Security Risks for 2017 is <a href="https://www.owasp.org/index.php/Top_10_2017-Top_10">“Using Components with Known Vulnerabilities”.</a></p><h3>Intro to snyk</h3><p>In my team, we take security very seriously so we started to use snyk. <a href="https://snyk.io/">Snyk</a> is a tool that helps you find, fix and prevent vulnerabilities in the dependencies that you use in your project.</p><p>In a nutshell, <a href="https://snyk.io/docs/using-snyk">snyk CLI</a> has these useful commands:<br><strong><em>snyk test</em></strong> — to scan your dependencies for known vulnerabilities.</p><p><strong><em>snyk wizard</em></strong> — goes through each vulnerability found and asks you how to address it (upgrade dependency, patch it or ignore the vulnerability)</p><p><strong><em>snyk protect</em> </strong>— will apply the patches and policies that you choose when running snyk wizard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjFs9Fw3gGtb0y09kCZZRQ.png" /><figcaption>A vulnerability was found with snyk test</figcaption></figure><p><strong>Integrating snyk into your CI system</strong></p><p>If you want to proactively keep your dependencies free from vulnerabilities then you should integrate snyk into your CI system.<br>The best way to tackle this is to run snyk every time new code is added to your project.</p><p>We use Jenkins and GIT.<br>Every time a developer creates a Pull Request, a Jenkins job that run tests on the PR code is automatically triggered.</p><p>So we added a new step to that job to run <strong><em>snyk test</em></strong>.</p><p>Before scanning the dependencies you should apply the patches and policies that you put in place when running <strong><em>snyk wizard</em></strong>, otherwise <strong><em>snyk test</em></strong> will fail even if you decided to ignore some vulnerability. <br><strong><em>snyk protect</em></strong> will do that for you.</p><p>The job fails if vulnerabilities are found in the new code, the same way that it fails if there are failing tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpTKiWiKo0dGd-knvaDvXA.png" /><figcaption>Run snyk protect and then snyk test when a PR is created</figcaption></figure><p><strong>Note</strong>: In Node.js projects we have snyk installed as part of the projects and snyk commands are executed with <em>yarn</em>. In Java projects you can install snyk globally in the Jenkins server and run the commands directly with snyk cli.</p><p>It would be also a good idea to run <strong><em>snyk monitor</em></strong> to keep your dependency list updated in your snyk account. We do that as part of another Jenkins job that is triggered when new code is merged into the master branch.</p><h3><strong>Node.js VS Java</strong></h3><p><strong><em>snyk wizard</em></strong> is only available for Node.js projects so in Java projects you will need to upgrade your dependencies manually.</p><p>Moreover, snyk does not provide patches for Java vulnerabilities as opposed to Node.js.</p><p>But, if you want to ignore vulnerabilities in your Java project then you can use <strong><em>snyk ignore</em></strong> command for that.</p><p><strong>Things to consider when using snyk on existing projects</strong></p><p>If you integrate snyk on existing projects, specially on large monolithic projects, you’ll probably find a bunch of vulnerabilities when you run <strong><em>snyk test</em></strong> for the first time.</p><p>For Java projects, as I mentioned before, there is no magic wizard that can upgrade your dependencies so you will need to manually check for each vulnerable dependency whether there is a newer version with a fix and then update the pom.xml to use that new version.</p><p>But that’s not all. Once you upgrade the dependencies, even if you use Node.JS and you upgraded them with <em>snyk wizard</em>, you will want to do a <strong>sanity check on your application</strong>. Upgrading dependencies, specially when upgrading to major versions, can be risky and might break your application functionality.</p><p>This can be a very challenging and time consuming task that might involve many developers from different teams. But, as <em>Buddha</em> said:</p><blockquote>There are <strong>only</strong> two mistakes one can make along the road to “<strong>secured applications”</strong>; not going all the way, and not <strong>starting</strong>.</blockquote><p>Now it’s your turn. Install snyk and let’s make the world a bit more secure.</p><p>Stay tuned for my upcoming articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40e25737b303" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>