<?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 Anjan Biswas on Medium]]></title>
        <description><![CDATA[Stories by Anjan Biswas on Medium]]></description>
        <link>https://medium.com/@anjanava.biswas?source=rss-dbbc0b48552b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EW7RgbF4Ev2llySwlrEl3g.jpeg</url>
            <title>Stories by Anjan Biswas on Medium</title>
            <link>https://medium.com/@anjanava.biswas?source=rss-dbbc0b48552b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:42:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anjanava.biswas/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[Balancing Innovation With Safety & Privacy in the Era of Large Language Models (LLM)]]></title>
            <link>https://medium.com/data-science/balancing-innovation-with-safety-privacy-in-the-era-of-large-language-models-llm-a63570e4a24a?source=rss-dbbc0b48552b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a63570e4a24a</guid>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[trust-and-safety]]></category>
            <category><![CDATA[responsible-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Anjan Biswas]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 14:48:03 GMT</pubDate>
            <atom:updated>2023-09-20T14:48:03.925Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Guide to Implement Safety, and Privacy Mechanisms for your Generative AI applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EFgJ2IaxCk8HPxMG" /><figcaption>Photo by <a href="https://unsplash.com/@jdent?utm_source=medium&amp;utm_medium=referral">Jason Dent</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The AI era has ushered in Large Language Models (aka LLMs) to the technological forefront, which has been much of the talk in 2023, and is likely to remain as such for many years to come. LLMs are the AI models that are the power house behind things like <a href="https://chat.openai.com/">ChatGPT</a>. These AI models, fueled by vast amounts of data and computational prowess, have unlocked remarkable capabilities, from human-like text generating to assisting with natural language understanding (NLU) tasks. They have quickly become the foundation upon which countless applications and software services are being built, or at least being augmented with.</p><p>However, as with any groundbreaking innovations, the rise of LLMs brings forth a critical question — <em>“How do we balance this pursuit of technological advancement with the imperative of safety and privacy?”. </em>This is not a mere philosophical question, but a challenge that requires proactive and thoughtful action.</p><h3>Safety and privacy</h3><p>To prioritize safety and privacy in our LLM powered applications, we’ll be honing in on key areas, including controlling the spread of personal data (<a href="https://www.dol.gov/general/ppii">personally identifiable information</a>, a.k.a. PII) and harmful or toxic content. This is essential whether you’re fine-tuning an LLM with your own dataset or simply using an LLM for text generation tasks. <em>Why does this matter?</em> There are a few reasons as to why it could be important.</p><ul><li>Compliance with government regulations that mandates protection of user personal information (such as <a href="https://gdpr-info.eu/">GDPR</a>, <a href="https://oag.ca.gov/privacy/ccpa">CCPA</a>, <a href="https://www.hhs.gov/hipaa/for-professionals/privacy/special-topics/de-identification/index.html">HIPAA Privacy Rule</a> etc.)</li><li>Compliance with LLM provider End-User License Agreement (EULA) or Acceptable Use Policy (AUP)</li><li>Comply with InfoSec policies set within organizations</li><li>Mitigate possibility of bias and skew in your model; post fine tuning</li><li>Ensure the ethical use of LLMs and preserve brand reputation</li><li>Be prepared for any <a href="https://www.barrons.com/articles/washington-ai-regulation-meetings-senate-33e8c1a5">AI regulation</a> that may be in the horizon</li></ul><h4>Considerations for fine tuning</h4><p>When preparing for fine-tuning an LLM, the first step is data preparation. Outside of research, education, or personal projects, it is likely that you will run into situations where your training data may contain PII information. The first step here is to identify the existence of these PII entities in the data, and the second step is to scrub the data to ensure that these PII entities are anonymized properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5X7H7VceVM8s15fcOJuxA.png" /><figcaption>LLM fine tuning</figcaption></figure><h4>Considerations for text generation</h4><p>For text generation using LLMs, there are a couple if things to keep in mind. First, we ensure that any prompt containing toxic content are restricted from propagating to the LLM, and second we ensure that our prompt is free of any PII entities. Consecutively, in some cases, it may be appropriate to run these validations <strong>on the text generated by the LLM</strong>, or on the “<em>machine generated text”.</em> This gives a dual layer of protection in ensuring our ethos of safety and privacy. A third aspect is of determining the <em>intent </em>of the prompt itself which may, to some extent, curtail things like <a href="https://arxiv.org/pdf/2306.05499.pdf"><em>prompt injection</em></a><em> </em>attacks<em>. </em>However, I will primarily focus on PII and toxicity in this article and discuss <em>intent </em>classification and it’s effect on LLMs in a separate discussion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ndvaNM36Jlw4b5Cfhcrolw.png" /><figcaption>Text generation with LLM</figcaption></figure><h3>Implementation</h3><p>We will take a two step approach in order to implement a solution for this. First, we make use of a <strong>name entity recognition (NER)</strong> model that can identify PII entities in the text and allows us to anonymize the entities. PII entities usually includes things like person name, location or address, phone number, credit card number, SSN and so on. Second, we use a <strong>text classification</strong> model to classify if a text is toxic or neutral. Examples of toxic text typically are text that contain abuse, obscenities, harassment, bullying and so forth.</p><p>For the PII NER model, a most common choice would be a <a href="https://huggingface.co/bert-base-uncased">BERT Base model</a> that can be fine tuned to detect specific PII entities. You can also fine tune pre-trained <a href="https://huggingface.co/docs/transformers/index">transformer</a> models such as the <a href="https://huggingface.co/obi/deid_roberta_i2b2">Robust DeID</a> (de-identification) pre-trained model which is a <a href="https://arxiv.org/pdf/1907.11692.pdf">RoBERTa</a> model fine-tuned for de-identification of medical notes and mostly focuses on personal health information (a.k.a PHI). A much simpler option to begin experimenting would be using <a href="https://spacy.io/api/entityrecognizer">spaCy ER (EntityRecognizer)</a>.</p><pre>import spacy<br><br>nlp = spacy.load(&quot;en_core_web_lg&quot;)<br>text = &quot;Applicant&#39;s name is John Doe and he lives in Silver St. \<br>        and his phone number is 555-123-1290&quot;<br>doc = nlp(text)<br><br>displacy.render(doc, style=&quot;ent&quot;, jupyter=True)</pre><p>which gives us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNCekpCa6H5p2ye8h2_dfQ.png" /><figcaption>Annotation of PII entities detected by spaCy</figcaption></figure><p>spaCy EntityRecognizer was able to identify three entities — PERSON (People, including fictional characters), FAC (Location or address), and CARDINAL (Numerals that do not fall under another type). spaCy also gives us the start and end offset (character position in the text) of the detected entity which we can use to perform anonymization.</p><pre>ent_positions = [(ent.start_char, ent.end_char) for ent in doc.ents]<br><br>for start, end in reversed(ent_positions):<br>    text = text[:start] + &#39;#&#39; * (end - start) + text[end:]<br><br>print(text)</pre><p>which gives us</p><pre>Applicant&#39;s name is ######## and his he lives in ###################and his phone number is ###-123-1290</pre><p>But there are a few obvious issues here. spaCy ER’s default entity list is not exhaustive to cover for all types of PII entities. For example, in our case we would like to detect 555-123-1290 as a PHONE_NUMBER as opposed to just part of the text as CARDINAL leading to incomplete entity detection. Of-course, just like the transformer based NER models, spaCy can also be trained with your own dataset of custom name entities in order to make it more robust. However, we will use <strong>open-source </strong><a href="https://microsoft.github.io/presidio/"><strong>Presidio</strong></a><strong> SDK</strong> which is a more purpose-built toolkit for <em>data protection</em> and <em>de-identification</em>.</p><h4>PII detection and anonymization with Presidio</h4><p>The Presidio SDK provides a full set of PII detection capabilities, with a long list of <a href="https://microsoft.github.io/presidio/supported_entities/">supported PII entities</a>. Presidio primarily uses pattern matching, along with ML capabilities of spaCy and <a href="https://stanfordnlp.github.io/stanza/">Stanza</a>. However, Presidio is customizable and can be plugged-in to use your transformer based PII entity recognition model, or with even cloud based PII capabilities such as <a href="https://learn.microsoft.com/en-us/azure/ai-services/language-service/personally-identifiable-information/how-to-call">Azure Text Analytics PII detection</a>, or <a href="https://docs.aws.amazon.com/comprehend/latest/dg/how-pii.html">Amazon Comprehend PII detection</a>. It also comes with a built-in customizable anonymizer that can help scrub and redact PII entities from text.</p><pre>from presidio_analyzer import AnalyzerEngine<br><br>text=&quot;&quot;&quot;<br>Applicant&#39;s name is John Doe and his he lives in Silver St.<br>and his phone number is 555-123-1290.<br>&quot;&quot;&quot;<br><br>analyzer = AnalyzerEngine()<br>results = analyzer.analyze(text=text,<br>                           language=&#39;en&#39;)<br>for result in results:<br>  print(f&quot;PII Type={result.entity_type},&quot;,<br>        f&quot;Start offset={result.start},&quot;,<br>        f&quot;End offset={result.end},&quot;,<br>        f&quot;Score={result.score}&quot;)</pre><p>which gives us</p><pre>PII Type=PERSON, Start=21, End=29, Score=0.85<br>PII Type=LOCATION, Start=50, End=60, Score=0.85<br>PII Type=PHONE_NUMBER, Start=85, End=97, Score=0.75</pre><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bX-uXqil40srEYWJavCgrw.png" /><figcaption>Annotation of PII entities detected by Presidio</figcaption></figure><p>As we’ve seen before, it’s a rather trivial task to anonymize the text since we have the beginning and end offsets of each of the entities within the text. However, we are going to make use of Presidio’s built-in AnonymizerEngine to help us with this.</p><pre>from presidio_anonymizer import AnonymizerEngine<br><br>anonymizer = AnonymizerEngine()<br>anonymized_text = anonymizer.anonymize(text=text,analyzer_results=results)<br>print(anonymized_text.text)</pre><p>which gives us</p><pre>Applicant&#39;s name is &lt;PERSON&gt; and his he lives in &lt;LOCATION&gt;<br>and his phone number is &lt;PHONE_NUMBER&gt;.</pre><p>This so far is great, but what if we want the anonymization to be just plain masking. In that case we can pass in custom configuration to the AnonymizerEngine which can perform simple masking of the PII entities. For example, we mask the entities with the asterisk (*) characters only.</p><pre>from presidio_anonymizer import AnonymizerEngine<br>from presidio_anonymizer.entities import OperatorConfig<br><br>operators = dict()<br><br># assuming `results` is the output of PII entity detection by `AnalyzerEngine`<br>for result in results:<br>  operators[result.entity_type] = OperatorConfig(&quot;mask&quot;, <br>                                 {&quot;chars_to_mask&quot;: result.end - result.start, <br>                                  &quot;masking_char&quot;: &quot;*&quot;, <br>                                  &quot;from_end&quot;: False})<br><br>anonymizer = AnonymizerEngine()<br>anonymized_results = anonymizer.anonymize(<br>    text=text, analyzer_results=results, operators=operators<br>)<br><br>print(anonymized_results.text)</pre><p>gives us</p><pre>Applicant&#39;s name is ******** and he lives in ********** and his phone number is ************.</pre><h4>Considerations for anonymization</h4><p>There are a few things to keep in mind when you decide to anonymize PII entities in the text.</p><ul><li>Presidio’s default AnonymizerEngine uses a pattern &lt;ENTITY_LABEL&gt; to mask the PII entities (like &lt;PHONE_NUMBER&gt; ). This can potentially cause issues especially with LLM fine-tuning. Replacing PII with entity type labels can introduce words that carry semantic meaning, potentially affecting the behavior of language models.</li><li><a href="https://en.wikipedia.org/wiki/Pseudonymization"><strong><em>Pseudonymization</em></strong></a><em> </em>is a useful tool for data protection, however you should exercise caution performing pseudonymization on your training data. For example, replacing all NAME entities with the pseudonym John Doe , or replacing all DATE entities with 01-JAN-2000 in your fine-tuning data may lead to extreme bias in your fine-tuned model.</li><li>Be aware of how your LLM reacts to certain characters or patterns in your prompt. Some LLMs may need a very specific way of templating prompts to get the most out of the model, for example Anthropic recommends using <a href="https://docs.anthropic.com/claude/docs/constructing-a-prompt#mark-different-parts-of-the-prompt"><em>prompt tags</em></a><em>.</em> Being aware of this will help decide how you may want to perform anonymization.</li></ul><p>There could be other general side effects of anonymized data on model fine-tuning such as <em>loss of context</em>, <em>semantic drift</em>, <em>model</em> <em>hallucinations</em> and so on. It is important to iterate and experiment to see what level of anonymization is appropriate for your needs, while minimizing it’s negative effects on the model’s performance.</p><h4>Toxicity detection with text classification</h4><p>In order to identify whether a text contains toxic content or not, we will use a binary classification approach — 0 if the text is neutral, 1 if the text is toxic. I decided to train a <a href="https://arxiv.org/abs/1910.01108">DistilBERT base model (uncased)</a> which is a distilled version of a <a href="https://arxiv.org/abs/1810.04805">BERT base model</a>. For training data, I used the <a href="https://www.kaggle.com/c/jigsaw-multilingual-toxic-comment-classification">Jigsaw dataset</a>.</p><p>I won’t go into the details of how the model was trained and model metrics etc. however you can refer to this article on <a href="https://medium.com/geekculture/hugging-face-distilbert-tensorflow-for-custom-text-classification-1ad4a49e26a7">training a DistilBERT base model</a> for text-classification tasks. You can see the model training script I wrote <a href="https://github.com/annjawn/llm-safety-privacy/blob/main/toxicity.ipynb">here</a>. The model is available in HuggingFace Hub as <a href="https://huggingface.co/tensor-trek/distilbert-toxicity-classifier">tensor-trek/distilbert-toxicity-classifier</a>. Let’s run a few sample pieces of text through inference to check what the model tells us.</p><pre>from transformers import pipeline<br><br>text = [&quot;This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three.&quot;, <br>        &quot;I wish i could kill that bird, I hate it.&quot;]<br><br>classifier = pipeline(&quot;text-classification&quot;, model=&quot;tensor-trek/distilbert-toxicity-classifier&quot;)<br>classifier(text)</pre><p>which gives us —</p><pre>[<br>  {&#39;label&#39;: &#39;NEUTRAL&#39;, &#39;score&#39;: 0.9995143413543701},<br>  {&#39;label&#39;: &#39;TOXIC&#39;, &#39;score&#39;: 0.9622979164123535}<br>]</pre><p>The model is correctly classifying the text as NEUTRAL or TOXIC with pretty high confidence. This text classification model, in conjunction to our previously discussed PII entity classification can now be used to create a mechanism that can enforce privacy and safety within our LLM powered applications or services.</p><h3>Putting things together</h3><p>We’ve tackled <em>privacy</em> through a PII entity recognition mechanism, and we tackled the <em>safety</em> part with a text toxicity classifier. You can think of other mechanisms that may be relevant to your organization’s definition of safety &amp; privacy. For example, healthcare organizations may be more concerned about PHI instead of PII and so forth. Ultimately, the overall implementation approach for this remains the same no matter what controls you want to introduce.</p><p>With that in mind, it is now time to put everything together into action. We want to be able use both the privacy and safety mechanisms in conjunction with an LLM for an application where we want to introduce generative AI capabilities. I am going to use the popular <a href="https://www.langchain.com/">LangChain</a> framework’s <a href="https://python.langchain.com/docs/get_started/introduction">Python flavor</a> (also available in <a href="https://js.langchain.com/docs/get_started/introduction/">JavaScript/TS</a>) to build a generative AI application which will include the two mechanisms. Here’s how our overall architecture looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOwszLVIEPWYVgGV_T87vg.png" /><figcaption>Privacy and safety flow with LangChain</figcaption></figure><p>In the above architecture, the first thing I check is if the text contains toxic content with at least more than 80% of model accuracy. If so, the execution of the whole LangChain application stops at that point, and the user is shown an appropriate message. If the text is classified largely as <em>neutral, </em>then I pass it onto the next step of identifying PII entities. I then perform anonymization on those entities in the text if the confidence score of each of these entity detection is more than 50%. Once the text is fully anonymized, it is passed as a prompt to the LLM for further text generation by the model. Note that the accuracy thresholds (80% and 50%) are arbitrary, you would want to test the accuracy of both the detectors (PII &amp; toxicity) on your data and decide on a threshold that works best for your use-case. <em>The lower the threshold, the stricter the system becomes, the higher the threshold the weaker the enforcement of these checks</em>.</p><p>Another more conservative approach would be to stop the execution if any PII entities are detected. This could be useful for applications that are not certified to handle PII data at all and you want to ensure, no matter how, text containing PII doesn’t end up being fed into the application as an input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtxXR6v4VOp0Vx_8s2hYdA.png" /><figcaption>Privacy and safety flow with LangChain — <strong><em>alternate flow</em></strong></figcaption></figure><h4>LangChain implementation</h4><p>In order to make it work with LangChain, I created a <a href="https://python.langchain.com/docs/modules/chains/how_to/custom_chain">custom <em>chain</em></a><em> </em>called PrivacyAndSafetyChain . This can be chained with any <a href="https://python.langchain.com/docs/modules/model_io/models/llms/">LangChain supported LLMs</a> to implement a privacy and safety mechanism. This is how it looks like —</p><pre>from langchain import HuggingFaceHub<br>from langchain import PromptTemplate, LLMChain<br>from PrivacyAndSafety import PrivacyAndSafetyChain<br><br>safety_privacy = PrivacyAndSafetyChain(verbose=True,<br>                                       pii_labels = [&quot;PHONE_NUMBER&quot;, &quot;US_SSN&quot;])<br><br>template = &quot;&quot;&quot;{question}&quot;&quot;&quot;<br><br>prompt = PromptTemplate(template=template, input_variables=[&quot;question&quot;])<br>llm = HuggingFaceHub(<br>    repo_id=repo_id, model_kwargs={&quot;temperature&quot;: 0.5, &quot;max_length&quot;: 256}<br>)<br><br>chain = (<br>    prompt <br>    | safety_privacy <br>    | {&quot;input&quot;: (lambda x: x[&#39;output&#39;] ) | llm}<br>    | safety_privacy <br>)<br><br>try:<br>    response = chain.invoke({&quot;question&quot;: &quot;&quot;&quot;What is John Doe&#39;s address, phone number and SSN from the following text?<br><br>John Doe, a resident of 1234 Elm Street in Springfield, recently celebrated his birthday on January 1st. Turning 43 this year, John reflected on the years gone by. He often shares memories of his younger days with his close friends through calls on his phone, (555) 123-4567. Meanwhile, during a casual evening, he received an email at johndoe@example.com reminding him of an old acquaintance&#39;s reunion. As he navigated through some old documents, he stumbled upon a paper that listed his SSN as 338-12-6789, reminding him to store it in a safer place.<br>&quot;&quot;&quot;})<br>except Exception as e:<br>    print(str(e))<br>else:<br>    print(response[&#39;output&#39;])</pre><p>By default, PrivacyAndSafetyChain performs toxicity detection first. If it detects any toxic content then it will error out essentially stopping the chain as we discussed earlier. If not, then it passess the entered text to the PII entity recognizer and based on what masking character to use, the chain will perform anonymization of the text with the detected PII entities. The output of the preceding code is as shown below. Since there is no toxic content the chain didn’t stop, and it detected PHONE_NUMBER and SSN and correctly anonymized it.</p><pre>&gt; Entering new PrivacyAndSafetyChain chain...<br>Running PrivacyAndSafetyChain...<br>Checking for Toxic content...<br>Checking for PII...<br><br>&gt; Finished chain.<br><br><br>&gt; Entering new PrivacyAndSafetyChain chain...<br>Running PrivacyAndSafetyChain...<br>Checking for Toxic content...<br>Checking for PII...<br><br>&gt; Finished chain.<br>1234 Elm Street, **************, ***********</pre><h3>Conclusion</h3><p>The biggest takeaway in this post is that as we continue to innovate with Large Language Models, it becomes imperative to balance the scales of innovation with safety and privacy. The enthusiasm surrounding LLMs, and our ever-growing desire to integrate them with a whole world of possible use-cases is un-deniable. However, the potential pitfalls — like data privacy breaches, unintended biases, or misuse — are equally real and warrant our immediate attention. I covered how you can establish a mechanism of detecting PII and toxic content going into your LLMs and discussed an implementation with LangChain.</p><p>There’s still much research and development that remains to be done— perhaps a better architecture, more reliable and seamless way to ensure data privacy and safety. The code in this post is trimmed down for brevity, but I encourage you to checkout my <a href="https://github.com/annjawn/llm-safety-privacy/tree/main">GitHub repository</a> where I have collated detailed Notebooks on each step along with full source code of the custom LangChain that we discussed. Use it, fork it, improve it, go forth and innovate!</p><h4>References</h4><p>[1] Jacob Devlin, Ming-Wei Chang et. al. <a href="https://arxiv.org/abs/1810.04805">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a></p><p>[2] Victor Sanh, Lysandre Debut et. al <a href="https://arxiv.org/abs/1910.01108">DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter</a></p><p>[3] Dataset — <a href="https://www.kaggle.com/c/jigsaw-multilingual-toxic-comment-classification">Jigsaw Multilingual Toxic Comment Classification 2020</a></p><p><em>Unless otherwise noted, all images are by the author</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a63570e4a24a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/balancing-innovation-with-safety-privacy-in-the-era-of-large-language-models-llm-a63570e4a24a">Balancing Innovation With Safety &amp; Privacy in the Era of Large Language Models (LLM)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Cognito User Pool Federation With Onelogin IdP]]></title>
            <link>https://medium.com/@anjanava.biswas/aws-cognito-user-pool-federation-with-onelogin-idp-4b1962127b0b?source=rss-dbbc0b48552b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b1962127b0b</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[aws-cognito]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[onelogin]]></category>
            <category><![CDATA[aml]]></category>
            <dc:creator><![CDATA[Anjan Biswas]]></dc:creator>
            <pubDate>Thu, 28 Nov 2019 07:16:24 GMT</pubDate>
            <atom:updated>2019-11-28T07:19:17.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnRmbH63gjtaYOK36sVI5g.png" /></figure><p>In this article we’re going to look at how to use AWS Cognito User Pools with SAML Identity Federation. Cognito lets you add user sign-up, sign-in, and access control to your web and mobile apps quickly and easily. But more importantly Cognito lets you manage user’s access to the AWS Services (like S3) with fine grain permissions through temporary credential tokens from underlying STS (Security Token Service).</p><h3>Let’s Clear Things Up A Bit</h3><p>Before we proceed let’s discuss why we need Cognito and what is the purpose of Onelogin.</p><blockquote><strong><em>TLDR;</em></strong></blockquote><blockquote>Amazon Cognito user pools allow sign-in through a third party (federation), including through a SAML IdP such as OneLogin. To set up OneLogin as SAML IdP, you need an Amazon Cognito user pool and a OneLogin account with an application on it. We will use Cognito and Onelogin SAML IdP to setup authentication for our application’s users.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxa7axfI0YVVspgPZsi7zw.png" /><figcaption><strong>Single Sign On (SSO) with AWS Cognito <br>&amp; IdP (OneLogin / Auth0)</strong></figcaption></figure><p>As I mentioned earlier, if you are using AWS Public Cloud and it’s whole host of services to build an app, then chances are that you want to be able to manage how your users are going to access these services in a secure and controlled way. Cognito is a service that lets you do just that. With Cognito you can have your user authenticated as well as authorized to use specific services in your AWS infrastructure through temporary credential tokens. Cognito generates these tokens internally using STS (Security Token Service), once your user is successfully authenticated with the User Pool, and sends it over to your application. Your application can then use the token to access other services (such as an S3 bucket for example). The STS tokens generated by Cognito are typically tied to an IAM Role that you can create and assign to the Cognito Identity Pool (which works along side of your Cognito User Pool). These STS tokens lets the user user “assume” that particular IAM Role (temporarily) which has permissions to access, let’s say, S3 buckets and so on.</p><p>But where does Onelogin come into the picture here? Well, although Cognito can act as a user directory and to some extent as an IdP (Identity Provider) itself you may want to implement Single Sign On through other third party Identity Providers like Social Login Providers or SAML Providers without the need of managing users separately in your Cognito user pool, aka <a href="https://en.wikipedia.org/wiki/Federated_identity">Identity Federation</a>. Onelogin in this case is a cloud based SAML Identity Provider (other popular examples are <a href="https://auth0.com/">Auth0</a>, and <a href="https://www.shibboleth.net/products/identity-provider/">Shibboleth</a>) which not only can act like an identity provider but can integrate with <a href="https://searchwindowsserver.techtarget.com/definition/Active-Directory">Active Directory</a>. An organization may already be using an IdP to federate its own internal or external applications through SSO, it would only make sense for your app to support identity federation as well.</p><p>However, there’s good news and there’s bad news here. The bad news is with Cognito there’s <a href="https://grammarist.com/phrase/more-than-one-way-to-skin-a-cat/">more one than way to <em>skin the cat</em></a><em>. </em>Cognito supports identity federation with Identity Pools as well as User Pools and the distinction between the two may be somewhat confusing given the lack of proper documentation. Setting up SAML identity federation with Identity Pools are a bit more involved than setting it up with User Pools. But the good news is that we are going to talk about the simpler solution — Identity Federation with Cognito User Pools.</p><h3>Getting Started</h3><h4>Pre-requisites:</h4><p>A Onelogin developer account and an AWS Account.</p><p>The first step in the process is going to be setting up a Cognito User Pool. For the sake of this article we won’t indulge ourselves in setting up a User Pool from scratch but I recommend following this <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html">tutorial</a>. Once we have a Cognito User Pool created, we are going to use the User Pool’s “<strong>App Integration</strong>” and “<strong>Federation</strong>” sections to wire up the SAML IdP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3fvjY_zMijdl871gQzAhQ.png" /><figcaption>AWS Cognito User Pool</figcaption></figure><p>But before we can do that we need to setup a SAML Connector App using the Onelogin IdP administrator console.</p><h3>Onelogin Setup</h3><p>Logon to your Onelogin developer account and navigate over to the Administration page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsjJ4D1dS5R4kkAOieu6pA.png" /><figcaption>Onelogin Developer Account</figcaption></figure><p>We are going to add a SAML App in the administration page using the <strong>APPS</strong> menu and then “<strong>Add App</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecXbvi6wuJeMwlVxeohvaw.png" /><figcaption>Onelogin Administration Console</figcaption></figure><p>In the <em>Add Apps </em>screen, search for “<em>SAML Test Connector</em>” app and then select the “<strong>SAML Test Connector (IdP)</strong>” app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWNnJDgSb9y59Cz2ImUAZg.png" /><figcaption>Adding a SAML App in Onelogin</figcaption></figure><p>We will now need to configure the “SAML Test Connector (IdP)” app in the subsequent screens. The next screen is pretty self explanatory. Enter a display name, description (optional) and a logo (optional) for your SAML App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJstPuN-oS9iHQBBUWaDrQ.png" /></figure><p>The next tab in the Onelogin SAML App configuration screen is “Configuration” and this is where all the good stuff happens. However, we will need a few things to do on the Cognito side before we can setup the configurations of the SAML App correctly. Before we head on to Cognito, navigate to the SSO tab in the Onelogin SAML App and copy the “<strong>Issuer URL</strong>”. We are going to need that for Cognito next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nubsE3tHiGcfW_MFvpZPw.png" /></figure><h3>Cognito User Pool SAML Provider Setup</h3><p>Heading back to the Cognito user pool, navigate over to the <strong><em>Federation</em></strong>&gt; <strong><em>Identity Providers</em></strong> from the menu on the left of the Cognito User Pool console. This is where we will need to setup the SAML Federation for the user pool. Click on the SAML box to add a SAML identity provider. There are few things we need to discuss here-</p><ol><li>Use the “<strong><em>Issuer URL</em></strong>” that you copied from the step above to enter into the “<strong><em>Metadata document</em></strong>” URL field.</li><li>Enter a provider name in the “<strong><em>Provider Name</em></strong>” field. No hard and fast rules here but enter something that is identifiable.</li><li>Check the “<strong><em>Enable IdP Sign out flow</em>”</strong> checkbox. Enable IdP sign out flow allows Cognito to propagate the sign out action to the SAML provider. When the user logs on to your App via Cognito all the way through a SAML IdP they are logged into both Cognito and the IdP systems. Consecutively, you would want the user to sign out of the IdP when they sign out of Cognito through your app. This option enables just that. If you keep this option disabled (unchecked), the user signing out of Cognito will remain logged into the IdP, for an SSO to work you do not want that to happen.</li></ol><p>Once done, click “<strong><em>Create Provider</em></strong>” to create the SAML provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxU3qEsOQFK1UkfK4-Jv_Q.png" /></figure><h3>User attributes in Cognito User Pool and Onelogin IdP</h3><p>The next step is to map user attributes. Navigate over to the “<strong><em>Attribute Mapping</em></strong>” section using the menu on the left. In the following screen select the SAML tab. This is where you would map user attributes. User attributes can be anything like first name, last name, phone number, address, country etc. but it depends on what attributes you defined for users in Onelogin. We will take a look at how to configure custom attributes in Onelogin later, but for now let’s complete the setup. Assuming you want to have your users login using their email address, this is a mandatory step.</p><p>In the attributes mapping screen, make sure that your SAML Provider is selected in the dropdown, the same one that we created above. Then click on “<strong>Add SAML attribute</strong>” to add a new attribute and enter <a href="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier">http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier</a> in the “<strong><em>SAML Attribute” </em></strong>field and then select “<em>Email</em>” from the “<strong><em>User pool attribute</em></strong>” dropdown. Hit “<strong><em>Save changes</em></strong>” to save the mapping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCgNjGd0VE2xyCJQ1b_JPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-0kj6NW1aO-sovAryOUfA.png" /></figure><p>The step above is crucial, especially if your User Pool’s attributes settings uses “<strong><em>Allow email addresses</em></strong>” and has <em>email</em> marked as one of the mandatory attributes. You can mark other attributes as mandatory too, but you will need to make sure that each mandatory attribute is mapped correctly in the “<strong><em>Attribute mapping</em></strong>” screen and most importantly your SAML IdP has all those required attributes for the user. You can also, add “Custom Attributes” for a user in the user pool, for example, I have user <em>first_name</em> and <em>last_name</em> defined as custom attributes in the User Pool as shown below. So, in the next step we are going to map these custom attributes to the SAML attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWhsjNyDNpkMPzEEyIAGyg.png" /></figure><blockquote><strong>Note: </strong>Once you add custom attributes and create a user pool, you won’t be able to delete them, however, you can add new ones and the same rule applies to new custom attributes as well. If you want to remove a specific custom attribute(s) you will have delete and re-create the entire user pool again. So be careful in deciding what custom attributes you want to use prior to setting up the Cognito User Pool. Also note, while adding a custom attribute you only need to enter the attribute name in the “<strong>Name</strong>” field. Once you save it, Cognito will automatically prefix the attribute names with “<strong>custom:</strong>”, this continues to confuse most developers using custom attributes in their user pool. A <strong>mutable</strong> (the checkbox) custom attribute can is updatable whereas if the checkbox is left unchecked Cognito will not allow updating the attribute once its set.</blockquote><p>Now that we have all the user attributes we want in the Cognito User Pool, we need to configure the corresponding ones in Onelogin as well and then map them back to the User Pool attributes using Cognito console.</p><p>Heading back to the Onelogin Administration page. We will navigate back to the SAML IdP Connector App that we set up previously and then navigate to the “<strong><em>Parameters</em></strong>” tab. This is where we will define the equivalent attributes as our Cognito User Pool. You will notice an existing attribute already present with the name “<strong><em>NameID (fka Email)</em></strong>”, we are going to leave that as-is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mj2cLnuYkN9bdmfk7cmYwg.png" /></figure><p>Click on the “<strong><em>Add parameter</em></strong>” link to add a new attribute. Enter the same attribute name as the custom attributes created in Cognito, make sure that the “<strong><em>Include in SAML assertion</em></strong>” is checked. Including in SAML assertion will ensure that the attribute and the corresponding values are sent to Cognito from the Onelogin IdP in the SAML assertion. Once done click “<strong><em>Save</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-NGBcBzQNLwy61m4B-v7w.png" /></figure><p>In the next screen you can map an existing native Onelogin attribute to your newly created custom attribute. In our case we will map that to the “<strong><em>First Name</em></strong>” native attribute that already exists in our IdP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqS4MpU6zr9ApC3GmwwZOQ.png" /></figure><p>Repeat the same steps for <em>last_name </em>custom attribute and finally you should have something like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPXrTS5eMRROAt0hgNTDmg.png" /></figure><blockquote><strong>Note</strong>:</blockquote><blockquote>In the case above the “First Name” and “Last Name” are Onelogin attributes. You can also define custom attributes in Onelogin too. To do that, in the Onelogin Admin page, use the menu option <strong>USERS &gt; Custom User Fields </strong>and then create<strong> “New User Fields”. </strong>You can then use those Onelogin Custom User Fields to create attributes in the SAML Test Connector (IdP) App as shown above. Ultimately, it all depends on what attributes you require as user attributes, create them in Onelogin and Cognito individually and then map them.</blockquote><p>Now that we have defined the custom attributes in both Cognito and Onelogin, lets map them to each other in the Cognito Console. To do that, we will go back to the “<strong><em>Attribute mapping</em></strong>” screen and map them accordingly. Make sure that the “<strong><em>SAML attribute</em></strong>” field value matches the attribute name as defined in the Onelogin SAML Connector App. Once done click “<strong><em>Save changes</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2F1Yrf1CZ207Z-IPn4ioA.png" /></figure><p>Whew!! That was quite a bit. But we are close to being done, to be precise, we have three more steps to go in order to complete the setup. So let’s keep going.</p><h3>Cognito App Integration &amp; Onelogin Connector Configuration</h3><p>We have done quite a bit of work setting up the User Pool and Onelogin SAML Connector. In this section we will be setting up the Cognito User Pool’s “<strong>App Integration</strong>”. Before we get going with setting things up here, we need to understand what this setup is for.</p><p>Cognito allows you to add applications to it, these applications are nothing but clients that wishes to use authentication/authorization through your User Pool. You can add multiple Apps to your user pool to serve two different apps to your users, for example, a website and a mobile app. You will define each of them as an app in Cognito and Cognito in turn generates a unique “<strong><em>App Client id</em></strong>” for your app which can be used with Amplify SDK in your client (like Amplify Javascript SDK for Web or Swift SDK for iOS App). the App id allows Cognito to distinguish between your apps and apply app specific settings if any. In our case though, we are only going to create a single App as seen below.</p><p>Use the left menu to access the “<strong><em>App clients</em></strong>” screen and then add a new client. Make sure that “<strong><em>Generate Client Secret</em></strong>” is unchecked. Click “<strong><em>Create app client</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*01deJCjJvwq57tsOp5zhWw.png" /><figcaption>Add an App Client to User Pool</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yoj4qlV-FKn2swOzf7QnNw.png" /><figcaption>App Client id</figcaption></figure><p>We will now turn to hooking up this newly created App client with the SAML federation using “<strong><em>App integration</em></strong>”. Navigate to “<strong>App client settings</strong>” using the left menu where you will now notice your App client that we created above. There’s a lot goin on in here, so let’s break it down-</p><ol><li>Enabled Identity Providers — Since we only want to use OneLogin as our IdP we will select the “Identity Provider” that we created in Cognito in one the previous steps. This essentially enables SAML Authentication.</li><li>The <strong><em>Sign in</em></strong> URL is for the page where your user should be redirected to upon successful login and the <strong><em>Sign out</em></strong> URL is for the page is where the user should be redirected to upon successful sign out. <strong>Note</strong>: <em>you should only use </em><em>localhost while development and testing. For production, Cognito will only accept </em><em>https URLs.</em></li><li>Under OAuth 2.0 section you have two options to go for. “<strong>Authorization Code Grant</strong>” and “<strong>Implicit grant</strong>”. We will select “Authorization code grant” and we will discuss about it more down below.</li><li>For “<strong><em>Allowed OAuth Scopes</em></strong>” we will check email, openid, aws.cognito.signin.user.admin and profile.</li></ol><p>These are the settings that you would use to setup Amplify SDK to use Cognito Authentication in your client application. Essentially, your app is going to interact with the Onelogin SAML IdP through Cognito.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28_qiRRAjcDHArCJaKx80Q.png" /></figure><p>This step essentially enables Cognito’s “Hosted Web UI” (<a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-configuring-app-integration.html">documentation</a>) which is where your users should/will be redirected to in order to complete authentication. However, there’s a bit of a catch here since we are using SAML Federation through Onelogin, we’ll discuss about this a little later but let’s set it up for now. Use the left menu again to navigate to the “Domain name” page. In this screen, you basically have two options</p><ol><li>Use Cognito’s default domain</li><li>Use your own domain.</li></ol><p>In production, you would ideally chose option 2, but in our case we are going to go with Cognito’s default domain as shown below. You will be needed to enter a “<strong><em>Domain prefix</em></strong>” appropriate for your app and check if that name is available for use. In our case it’s “<em>testv</em>”, so our Cognito <strong>endpoint</strong> now is <a href="https://testv.auth.us-east-1.amazoncognito.com./">https://testv.auth.us-east-1.amazoncognito.com.</a> Keep a note of this endpoint since we need to do one last setup in Oneloging SAML Connector App’s configuration.</p><blockquote>Note: Cognito only allows http://localhost:&lt;port&gt; URLS in Callback URL and Sign out URL field in development mode. However, for a hosted or production environment the URLs must be <strong>https, </strong>so your hosting must have an SSL certificate linked in order to serve traffic over <strong>https. </strong>This can be done either using Route 53 hosted zone and domain purchased from Route 53 and a it’s provided SSL certificate or using CloudFront + either a Cloudfront provided certificate or a custom SSL certificate added via ACM.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72chKlw9pcQ87RJlsLdp0w.png" /></figure><p>Now back to Onelogin SAML Connector App navigate to the “<strong>Configuration</strong>” tab. There’s a few fields here and here’s what the values should be</p><ol><li>“<strong><em>Relay State</em></strong>”<strong><em>: </em></strong>This is the page where your user should be directed to upon successful log in. This is the same as the “Sign in” URL from Cognito’s App client settings.</li><li>“<strong>Audience</strong>”: The audience value looks like this <strong>urn:amazon:cognito:sp: &lt;cognito_user_pool_id&gt;.</strong> You can grab the Cognito User Pool ID from the Cognito console.</li><li>“<strong><em>ACS (Consumer) URL Validator*</em></strong>” and “<strong><em>ACS (Consumer) URL*</em></strong>”: This two fields should contain the same URL which looks like the domain you setup in Cognito in the previous step —<strong> </strong><a href="https://testvpcc.auth.us-east-1.amazoncognito.com/saml2/idpresponse"><strong>https://testv.auth.us-east-1.amazoncognito.com/saml2/idpresponse</strong></a></li><li>“<strong><em>Single Logout URL”</em></strong>: This is the Sign out URL where your users should be redirected to upon successful signout. Again, this should match with what you have set up in Cognito’s “<strong>Sign out</strong>” URL.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yTHC0Xyyd__qn_aT0qEZg.png" /></figure><p>This essentially completes our Cognito+Onelogin setup. We will now have a Cognito Sign-in hosted UI URL available for use with your client. This URL will direct the user to Cognito’s hosted web UI for the user to login which will then redirect your users to authenticate with Onelogin. The url is of the format —</p><pre>https://<strong>your_domain</strong>/login?<strong>response_type</strong>=code&amp;<strong>client_id</strong>=your_app_client_id&amp;<strong>redirect_uri</strong>=your_callback_url</pre><ol><li>In our case the <strong>your_domain</strong> is the default Cognito domain that we set up earlier which is “<strong> https://testv.auth.us-east-1.amazoncognito.com”</strong>.</li><li>Our <strong>response_type </strong>is going to be “<strong>code</strong>” since we used “<strong>Authorization code grant</strong>” in the “<em>Allowed OAuth Flows</em>” in the App settings in Cognito (note: in case you use “Implicit grant” you would use <strong>token_type=code</strong>).</li><li>The <strong>client_id </strong>is the App client id from Cognito.</li><li>The <strong>redirect_uri </strong>is basically the “Sign in” URL as specified int he Cognito App setting, i.e. the page where your users should redirected to upon successful authentication. <strong><em>Note</em></strong><em>: this URL should match exactly as the Sign in URL in Cognito App settings.</em></li></ol><p>We would have our Sign-In page URL something like this —</p><pre>https://<strong>testv.auth.us-east-1.amazoncognito.com</strong>/login?response_type=<strong>code</strong>&amp;client_id=<strong>13u7u9mmp8ucvb49ju1j2ol8j</strong>&amp;redirect_uri=<strong>https://www.myapp.com</strong></pre><p>This Cognito Sign-In page URL can then be used by your web-app or mobile app to perform authentication via Cognito and Onelogin. Of course, based on the type of application you intend to use it for, your redirect_uri will need to be set accordingly. Using <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-integrate-apps.html">AWS Amplify SDK’s Auth helper</a> with Cognito greatly improves the UI development experience, but Cognito SDK APIs can also be used by your back-end Lambda functions to authenticate against Onelogin to acquire auth token from Cognito. There are a few other configuration options available, such as enabling Multi-Factor Authentication, passwordless authentication et. al. but this should give you a beginners idea on how to federate an IdP with Cognito User Pool.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b1962127b0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading Files To AWS S3 From React App —Using  AWS Amplify]]></title>
            <link>https://medium.com/@anjanava.biswas/uploading-files-to-aws-s3-from-react-app-using-aws-amplify-b286dbad2dd7?source=rss-dbbc0b48552b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b286dbad2dd7</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[awsserverless]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Anjan Biswas]]></dc:creator>
            <pubDate>Sat, 08 Dec 2018 05:17:54 GMT</pubDate>
            <atom:updated>2018-12-08T05:20:28.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Upload Files To AWS S3 From React App —Using AWS Amplify</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoaRBM6nKfEzQS31OppxhA.png" /></figure><p>Amazon has made significant progress in creating tools, frameworks and libraries that finally give developers the true sense of focusing on the code and make them more resilient rather than being bogged down with infrastructure concerns. Once notable library which has made great progress is <a href="https://aws-amplify.github.io/">AWS Amplify</a>.</p><p>What existed as one-off solutions for developers to integrate their mobile and web apps with AWS services (via MobileHub) is now a more cohesive solution in the form of AWS Amplify, and with AWS re:Invent 2018 the introduction of Amplify Console is just icing on the cake.</p><p>In this post though, we are going to look at how to use AWS Amplify to let users upload files to S3 buckets from a React app. The use case is simple — authenticate users of your React app from the browser through Cognito and allow them to upload files to an S3 bucket. I’ll be honest, there’s quite a bit of configuration that is involved, but nothing that can’t be done, so let’s get to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*kRWmwk_JilR2B16UMXAPgw.png" /><figcaption>User authentication &amp; S3 operations</figcaption></figure><h3>Authentication Using Cognito (a pre-requisite)</h3><blockquote>You can skip this section if you already have a Cognito User Pool and Identity Pool set-up.</blockquote><p>Before we get into the details of implementing Amplify with React, it’s important to understand what role Cognito plays in this entire process. If you didn’t already know, <a href="https://aws.amazon.com/cognito/">Cognito</a> makes it easy for you to let your users sign up/sign in to your app and enables you to manage their access control to your AWS services (such as in this case, S3). For the sake of this article it’s important to understand the two functions of Cognito-</p><ol><li><strong>Cognito User Pool</strong>: User pools allow you to setup how your users are going to sign-up and sign-in to your app (i.e. using email, or username, or phone number or all of them), it let’s you define password policy (eg. minimum 8 characters), define custom user attributes, enable MFA (multi factor authentication), and so on. You can check out this <a href="https://www.youtube.com/watch?v=vr1njQyqlbk">webinar</a> on how to create a user pool (or there are plethora of articles online that will help you get started). Once, a user pool is created, it should provide you a “Cognito User Pool ID” (eg. us-east-1_18spw01t) and an “App client ID” (eg: 3v6a23ov3g1rhj23e27nm4v59si). We will need both of these later.</li><li><strong>Cognito Identity Pool: </strong>Technically, a User Pool alone is enough to setup a basic authentication service with Cognito for your app. However, if you want your users to have fine grain access to other AWS Services, or perhaps integrate 3rd party Authentication providers such as Google, Facebook, Twitter, SAML etc. you will need to setup a “Federated Identity” using Cognito Identity Pool (CIP). CIP lets you assign IAM roles at authenticated and unauthenticated levels which basically dictates what services (or parts of services) can a user access if they are authenticated vs. unauthenticated. Just like a user pool a CIP will have its own ID (eg: us-east-1:16e03s22-ce44–4cf5-jhg8-f11245xfcB15). We will keep a note of this as we will need it later.</li></ol><p>Once we have Cognito ready to go we can move on to the next section.</p><h3>Configure S3 permissions in Cognito</h3><p>Once we have our User Pool and Identity Pool ready, we need a way to add permissions to the Identity Pool which will give our users the ability to perform S3 operations (like PUT, GET, LIST etc.). When a user authenticates using the Cognito Identity Pool, their identity would “assume” the IAM role that we assigned to the identity pool and they can then perform the allowed operations on S3.</p><p>Identity Pool allows you to add two types of roles (IAM Roles).</p><ol><li><strong>Authenticated Role</strong> : For when the user is in authenticated state.</li><li><strong>Unauthenticated Role</strong>: For when the user is in unauthenticated state.</li></ol><p>We will need to assign individual IAM Roles to both even though we are only going to use the Authenticated Role since we want our users to only be able to upload files if they are authenticated.</p><p>Head over to Cognito console and click on the “<strong>Manage Identity Pool</strong>” from the homepage. This should take you to the identity pool manager. On the next page select your identity pool and then “<strong>Edit identity pool</strong>” link on the top right hand corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YW_A15MeXEwVuxtPRPmgJw.png" /><figcaption>Cognito Identity Pool</figcaption></figure><p>When you create an Identity Pool, two roles will be created for you by Cognito. One for “Unauthenticated Role” and another for “Authenticated Role” as shown in the image above. We will need to modify these roles using IAM console to add S3 permissions. Head over to IAM to edit the roles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9shSY6OiEFTiRnEHP6xkQ.png" /></figure><p>We will edit the roles using the policy editor and use the policy json below. We will assume our S3 bucket name is “<strong>my-test-bucket-amplify”.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9113cc4cd5deae6561dfaf91002bed46/href">https://medium.com/media/9113cc4cd5deae6561dfaf91002bed46/href</a></iframe><p>We will repeat this step for the unauth role, however for unauth role make sure you remove the DeleteObject and PutObject permissions. Everything else remains the same as the policy json above. We will discuss about public/, protected/, and private/ prefixes , as seen in the json above, a little bit further down.</p><p>We will also need to make sure that the “Trust Relationships” for both the roles are set correctly. Click on the “<strong>Trust Relationship</strong>” tab and then “<strong>Edit trust relationship</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHXNgrvPoyjFYUgv85LX4A.png" /><figcaption>Ensure Trust Relationship is set correctly</figcaption></figure><p><strong>IMPORTANT</strong>: Make sure that the cognito-identity.amazonaws.com:aud <strong>is your Cognito identity pool id</strong> and cognito-identity.amazonaws.com:amr is authenticated for the authenticated role and unauthenticated for the unauthenticated role.</p><p>Once both the IAM roles are edited as shown above, they will enable authenticated users to perform S3 operations.</p><h3>Setting Up Amplify</h3><p>We will install AWS Amplify’s Javascript SDK (amplify-js). Here’s the <a href="https://github.com/aws-amplify/amplify-js">Github</a> repo for the SDK and <a href="https://aws-amplify.github.io/docs/js/react">here’s the documentation</a>.</p><blockquote>NOTE: Amplify provides some boilerplate React components (HOCs) which can be created using the Amplify CLI. We will <strong>not</strong> be using Aplify CLI, but instead do our own implementation using the modules within amplify-js.</blockquote><p>We will use a create-react-app boilerplate to get started. Let’s create a CRA project and name it amplify-s3. We will also install amplify-js into our project.</p><pre>$ create-react-app amplify-s3<br>$ cd amplify-s3<br>$ npm install aws-amplify --save</pre><p>Now that we have amplify-js installed, we need to make use of the Storage sub-module for S3 related operations (and Auth sub-module for Cognito authentication related operations).</p><p>Let’s configure Amplify with the Cognito user pool, identity pool information, and the S3 bucket information. In order to do so, we will create a services.js in the root of the project and put all the Amplify Auth/S3 related operations there so that we can re-use it throughout our app. In services.js the first thing to do is to initialize and configure Amplify —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeb4fddfc3718bc9fb671893607c7efe/href">https://medium.com/media/aeb4fddfc3718bc9fb671893607c7efe/href</a></iframe><p>All the pieces of the configuration information above is mandatory in order to use Storage sub-module for S3 and authentication (Auth) operations<strong><em>. Note</em></strong> the process.env.REACT_APP_* variables. These are environment variables that are declared inside of a .env file in the root of your project. CRA has inbuilt implementation of <a href="https://github.com/motdotla/dotenv">DotEnv</a> so we can take advantage of that without having to type in the values again and again. The .env file’s content will look like this and we covered each of these values in the Cognito section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Qaftv8qNFr5ckGjw-wF2A.png" /><figcaption>.env file in React project</figcaption></figure><p>We need to perform Amplify.configure when your app is initialized, so we will need to import the configureAmplify() function in the index.js file of your project using named import so it would look like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nb6VjH_e7YlDW4J_E3RSZw.png" /></figure><p>It is important to call the configureAmplify() function before your App mounts. At this point we are good to start using Storage and Auth.</p><blockquote>For the sake of this article, we will assume you already have code in place to sign-in your users into your app using Auth sub-module and signIn() method that is built-in i.e. Auth.signIn() and so on. Take a look at the <a href="https://aws-amplify.github.io/docs/js/authentication">documentation</a> which explains Auth sub-module usage.</blockquote><h3>Using the Storage sub-module</h3><p>We can now use the <a href="https://aws-amplify.github.io/docs/js/storage">Storag</a>e submodule in Amplify and start performing S3 operations. But before we can do that, there is one important shortcoming that we need to discuss. As of this writing Amplify.configure() <strong><em>supports initializing only a single S3 bucket</em></strong>. This may not be ideal use case for everyone, for example; you may want user images to go to one bucket and videos to another and so on. This could become particularly challenging scenario with the way we configured Amplify above, and unfortunately this is the<a href="https://github.com/aws-amplify/amplify-js/issues/329#issuecomment-443480000"> only way to configure Amplify right now</a>. But, not all is lost. Let’s take a look at how we can use multiple S3 buckets in your app.</p><p>In order to be able to use different buckets, we need to perform some Storage specific configurations, specifically set the bucket name, level, region and Identity Pool ID every time you perform an S3 operation. Although this may not be an ideal way to do it, it is the only way to do it. We will add a new function in our services.js file to configure Storage with all these parameters for this purpose. We will first use modular import to import Storage from Amplify and then performconfigure()—</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb4f221600b9331b04b905617162be47/href">https://medium.com/media/fb4f221600b9331b04b905617162be47/href</a></iframe><p>Let’s discuss what we did here, and what level means. We simply passed an object to the built in configure() method for Storage. Most of the values are familiar, like bucket — bucket’s name, region — AWS region, and identityPoolId — the CIP ID. But what does level mean?</p><p>The Storage module can manage files with three different access levels; public, protected and private.</p><ol><li>public : Files with public access level can be accessed by all users who are using your app. In S3, they are stored under the public/ path in your S3 bucket. Amplify will automatically prepend the public/ prefix to the S3 object key (file name) when the level is set to public.</li><li>protected : Files with protected access level are readable by all users but writable only by the creating user. In S3, they are stored under protected/{user_identity_id}/ where the <strong>user_identity_id</strong> corresponds to a unique Amazon Cognito Identity ID for that user. <strong>IMPORTANT</strong>: Cognito user pool will automatically assign your users a “User ID” (which looks like: 09be2c02–8a21–4f51-g778–05448a6afbb5) and the Identity Pool assigns users an “Identity ID” (which looks like: us-east-1:09be2c02–3d0a-400d-a718–4e284dca6de4) and they are different. The user_identity_id signifies the “Identity ID”. Amplify will automatically prepend the protected/ prefix to the S3 object key (file name) when the level is set to protected and use the user_identity_id for the user that is logged into your app and has a valid session. So, give a file name of my_profile_pic.jpg, a bucket name of my_profile_pics_bucket, and authenticated user Identity ID of us-east-1:09be2c02–3d0a-400d-a718–4e284dca6de4 the S3 path will look like s3://my_profile_pics_bucket/protected/us-east-1:09be2c02–3d0a-400d-a718–4e284dca6de4/my_profile_pic.jpg</li><li>private: Files with private access level are only accessible for specific authenticated users only. In S3, they are stored under private/{user_identity_id}/ where the <strong>user_identity_id</strong> corresponds to a unique Amazon Cognito Identity ID for that user.</li></ol><p>In our case we want user’s to be able to store their files under the private file access level in the S3 bucket. This means that Amplify will always perform the operations under s://your_buck_name/private/{user_identity_id}/.</p><p>We can now use our reusable function in services.js file to configure the S3 Storage submodule by simply passing the bucket name and the file access level like so —</p><pre>SetS3Config(&quot;my_other_bucket&quot;,&quot;private&quot;);</pre><h3>Setting up the S3 bucket</h3><p>We will now setup our S3 bucket so that it works with Amplify’s Storage sub-module. The Storage sub-module is a convenient wrapper around S3’s API endpoints (which is also used by the AWS CLI internally) and abstracts away much of the implementation details from you. This means that you would actually be making API calls to the S3 endpoints from your React/Javascript code. With that in mind let us quickly create an S3 bucket.</p><p>Head over to AWS S3 console and click “<strong>Create Bucket</strong>”. We will name our bucket “<strong>my-test-bucket-amplify</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OAm6MRto0S-UWgLp-LXqw.png" /><figcaption>New my-test-bucket-amplify S3 bucket</figcaption></figure><p>We now have to enable <a href="https://www.codecademy.com/articles/what-is-cors">CORS</a> (Cross Origin Resource Sharing) for this bucket. We need to perform this step since Amplify will interact with this bucket through the S3 Rest API endpoints. In order to do that, click on the bucket name and then go to the “<strong>Permissions</strong>” tab, and then click the “<strong>CORS Configuration</strong>” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiXmd8QrnqsQerfbiu0ZwA.png" /><figcaption>S3 bucket CORS Configuration</figcaption></figure><p>In the CORS configuration editor enter the XML below-</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;CORSConfiguration xmlns=&quot;<a href="http://s3.amazonaws.com/doc/2006-03-01/">http://s3.amazonaws.com/doc/2006-03-01/</a>&quot;&gt;<br>&lt;CORSRule&gt;<br>    &lt;AllowedOrigin&gt;*&lt;/AllowedOrigin&gt;<br>    &lt;AllowedMethod&gt;HEAD&lt;/AllowedMethod&gt;<br>    &lt;AllowedMethod&gt;GET&lt;/AllowedMethod&gt;<br>    &lt;AllowedMethod&gt;PUT&lt;/AllowedMethod&gt;<br>    &lt;AllowedMethod&gt;POST&lt;/AllowedMethod&gt;<br>    &lt;AllowedMethod&gt;DELETE&lt;/AllowedMethod&gt;<br>    &lt;MaxAgeSeconds&gt;3000&lt;/MaxAgeSeconds&gt;<br>    &lt;ExposeHeader&gt;x-amz-server-side-encryption&lt;/ExposeHeader&gt;<br>    &lt;ExposeHeader&gt;x-amz-request-id&lt;/ExposeHeader&gt;<br>    &lt;ExposeHeader&gt;x-amz-id-2&lt;/ExposeHeader&gt;<br>    &lt;AllowedHeader&gt;*&lt;/AllowedHeader&gt;<br>&lt;/CORSRule&gt;<br>&lt;/CORSConfiguration&gt;</pre><p>This XML configures CORS for the S3 bucket API endpoint. You can allow all * domains in the AllowedOrigin or you can list specific domain for example &lt;AllowedOrigin&gt;yourdomain.com&lt;/AllowedOrigin&gt; to restrict calls from only your domain. You can also select which Rest methods to allow by listing them (or not listing them) with &lt;AllowedMethod&gt;. Learn more about S3 CORS configuration <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html">here</a>. Thats about it for S3, note that the bucket remains private by default and we have not added any Bucket policy explicitly since we do not need any for this example. Now it’s time to write some React code to see our upload operation in action.</p><h3>Uploading from React App</h3><p>We’ve come a long way, so now it’s time to put some code into our CRA Project’s index.js file and build a component that can actually perform an upload. Here’s how the code would look like —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2c84eb48ada20bf32f5d358714dd47/href">https://medium.com/media/cd2c84eb48ada20bf32f5d358714dd47/href</a></iframe><p>Pretty straight forward. Let’s take a look at what we did there.</p><ol><li>We imported configureAmplify() and SetS3Config() from our services.js file. These two functions will configure Amplify to initialize the services and help us set the bucket configurations respectively.</li><li>We then wrote a component with basic jsx with an upload field with &lt;input type=&quot;file&quot;&gt; and a couple of buttons — one to select files from our computer and another to upload the selected file. <strong>NOTE</strong>: the code restricts the file types to png and jpeg using accept=”image/png, image/jpeg” but that’s optional.</li><li>We save the image file and the image file name from HTML5’s <a href="https://w3c.github.io/FileAPI/">FileAPI</a> files[] array (array because you may select multiple files but in our case one one file is allowed), in the state using setState on onChange event of the input element. <strong>NOTE</strong>: The actual upload element (file selector i.e the regular button) is hidden and we have a regular field there just for styling purposes).</li><li>Once we have the file and file name in the state we invoke the uploadImage function from the button’s onClick event.</li><li>The uploadImage function initializes the S3 bucket configuration using SetS3Config function by setting the bucket name (“my-test-bucket-amplify”) and the file access level (“protected”).</li><li>Finally, we call the Storage.put() function which takes in the object key (i.e. the file name) with an S3 object prefix (i.e. in this case userimages/), the file and a file metadata object where we passed an object with contentType. Checkout Storage.put() example’s and documentation <a href="https://aws-amplify.github.io/docs/js/storage#put">here</a>.</li></ol><p>Here’s what it looks like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TwaIZJcxw7wXE-LyKjZVw.gif" /><figcaption>Upload from React App to S3 Bucket</figcaption></figure><h3>Conclusion</h3><p>It’s a rather simple implementation of a file uploader, considering you are using Cognito and Amplify, from your app but it also leaves quite a bit to be desired, for example multipart uploads are non-existent out of the box, and neither is file upload progress subscriber which indicates how much of the file has been uploaded (in order to show some sort of progress bar to the user while the file uploads), and so on. However, this is a step in the right direction with Amplify and simplifying a lot along the way of providing simple upload functionality in your web (or mobile apps) for your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b286dbad2dd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS Runtime Environment with AWS Lambda Layers]]></title>
            <link>https://medium.com/@anjanava.biswas/nodejs-runtime-environment-with-aws-lambda-layers-f3914613e20e?source=rss-dbbc0b48552b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3914613e20e</guid>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[lambda-architecture]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Anjan Biswas]]></dc:creator>
            <pubDate>Fri, 30 Nov 2018 05:22:51 GMT</pubDate>
            <atom:updated>2020-02-25T02:34:39.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzWUZ05IBI5eEWF3uBAoUA.jpeg" /></figure><p>With AWS re:Invent 2018 underway, AWS has been releasing pretty neat little (and big) features, updates to existing services, and brand new services. Today was serverless day, and of-course with serverless there was a huge focus on Lambda.</p><h3>What’s New with AWS Lambda?</h3><p>There’s quite a bit new in the latest updates to Lambda, but here are the major ones-</p><ol><li><strong><em>Lambda Layers</em></strong></li><li><strong><em>Lambda Runtime API</em></strong></li><li><strong><em>C++ and </em></strong><a href="https://aws.amazon.com/fr/blogs/compute/announcing-ruby-support-for-aws-lambda/"><strong><em>Ruby</em></strong></a><strong><em> native support</em></strong></li><li><strong><em>AWS Toolkits for PyCharm, IntelliJ, and VSCode IDEs (preview)</em></strong></li><li><strong><em>Improved Lambda container startups on a VPC (coming 2019)</em></strong></li></ol><h3>Amazon Web Services on Twitter</h3><p>Introducing the AWS Toolkits for PyCharm (GA), IntelliJ (Developer Preview) &amp;amp; Visual Studio Code (Developer Preview)! The open source toolkits make it easier to develop serverless applications on AWS. #reInvent https://t.co/zZ7GY98ce9</p><h3>Jeff Barr ☁️ on Twitter</h3><p>New for AWS Lambda - Use Any Programming Language and Share Common Components - https://t.co/EAqCd5l86W #AWS #reinvent</p><h3>Jeremy Daly @ re:Invent on Twitter</h3><p>Looks like @awscloud has some ideas to fix #Lambda cold starts in a #VPC. 🙌 Coming in 2019! #serverless #reInvent</p><p>You can read more about these features <a href="https://aws.amazon.com/blogs/aws/new-for-aws-lambda-use-any-programming-language-and-share-common-components/">here</a>, <a href="https://aws.amazon.com/blogs/compute/introducing-the-c-lambda-runtime/">here</a> and <a href="https://aws.amazon.com/blogs/opensource/rust-runtime-for-aws-lambda/">here</a>. We are going to focus more on the first two and see how to setup Runtime Environment with shared dependencies with NodeJS.</p><h3>Runtime Environment? What gives…?</h3><p>So I am going to leave the C++ and Ruby features to the C++ and Ruby experts. But let’s talk about the meat of the matter here — Layers and Runtime API.</p><p>Until now, language support in Lambda have been pretty slim with native support for Python, Java, NodeJS, Go, and C# only. With the two top most new features in Lambda a.k.a. <em>Lambda</em> <em>Layers</em> and <em>Lambda Runtime API, </em>Lambda can now virtually support a large variety of programming languages.</p><p>Lambda’s containerization may not be new to folks familiar with Lambda functions, but the very stateless nature of every function made data or even code sharing between independent Lambda function elaborate or in some cases impossible. Well, not anymore! With Layers you can now manage and share dependencies, configurations, or even data between multiple Lambda functions. So we are going to look at a typical use case of Lambda functions written in NodeJS with multiple node dependencies.</p><h3>Use Case</h3><p>A typical Lambda function with NodeJS and dependent module would look something like this in the Lambda inline code editor-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*e-dXHJOHjv8Uawj-_vLjRw.png" /><figcaption>Lambda inline code editor</figcaption></figure><p>As you can see, a single Lambda function that may have a few node dependencies will need to have the modules installed locally. You typically do that by -</p><p>npm install --save node_module</p><p>This would locally install a node_module inside of your Lambda function project directory. You would then need to zip the entire project directory’s content, and upload it to Lambda either via console or using AWS CLI. However, this can quickly get tiresome with growing number of Lambda functions. Repetitive installations of the same node modules for every single Lambda function not only result in redundant work but also hassle upgrading the node modules for every single Lambda function. It is also a huge challenge to maintain a “mono repo” git repository with all your Lambda code, since individual functions would have individual dependencies. In short, until now there wasn’t an elegant way to manage dependencies for ALL your lambda functions. The code size of your Lambda function may also be impacted due to larger dependencies, forcing you to break down a function into multiple functions (although the higher limit of a Lambda function code size is about <strong>50 MB</strong>, but it’s nonetheless a limit). Layer intends to solve these issues, and much more.</p><h3>Managing Dependencies Using Lambda Layers</h3><p>AWS has made it dead simple (atleast for NodeJS) to create a centralized, dependency manager for your entire Lambda Runtime using Layers. Layers allows you to create a dependency bundle with all the libraries that you may want to be used by all (or most) of your Lambda functions. You can maintain multiple versions of Layers and use different Layer versions for different Lambda functions. You can also manage different permissions for different Layers. But won’t delve much into versioning or permissions in this article. That’s a topic for a different article. A simple use case for a Lambda Layer for dependency management purposes could look something like this-</p><pre>Lambda-Layer-1 (Version 1)<br>├── nodejs<br>      └── package.json<br>      └── node_modules<br>              └── axios<em>(version x.x.x)</em><br>              └── lodash<em>(version y.y.y)</em></pre><p><em>And</em></p><pre>Lambda-Layer-2 (Version 2)<br>├── nodejs<br>      └── package.json<br>      └── node_modules<br>              └── axios<em>(version x.x.y)</em><br>              └── lodash<em>(version y.y.y)</em><br>              └── mysql<em>(version z.z.z)</em></pre><p>As you can see, the two layers Lambda-Layer-1 and Lambda-Layer-2 contains different node modules and different module versions or new modules. This makes Layers more appealing especially if you are managing Production and Non-Production stages in Lambda. You can now have Layers specific to a particular Stage/Team/Group of Functions and so on. That is <em>HUGE!</em></p><p>Let’s take a look at how to get started.</p><h3>How to create a Lambda Layer?</h3><p>Creating a Lambda Layer for NodeJS dependencies is pretty simple.</p><p>Create a directory for your Layer (name it whatever you want) —</p><pre>$ mkdir lambda-layer-test</pre><p>Create another directory inside it and name it nodejs. <strong>Note</strong>: the nodejs directory name is not random and must be nodejs. More on environment path’s <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">here</a>.</p><pre>$ cd lambda-layer-test<br>$ mkdir nodejs</pre><p>Once you have the nodejs directory created, initialize npm —</p><pre>$ cd nodejs<br>$ npm init</pre><p>At this point you should have a directory structure like this</p><pre>lambda-layer-test<br>├── nodejs</pre><p>Now it’s time to install all your favorite node modules. So go ahead and install the modules locally.</p><pre>$ npm install --save node_module1 node_module2 ...</pre><p>Once the installation is complete you should have something like this.</p><pre>lambda-layer-test<br>├── nodejs<br>      └── package.json<br>      └── node_modules<br>              └── node_module1<br>              └── node_module2</pre><p>Pretty standard stuff right? and that’s pretty much how to create a dependency bundle really. Now you need to zip up the nodejs directory-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*bALbsm-uwXY1HMl87PThrg.png" /><figcaption>Creating Zip Archive with Node dependencies</figcaption></figure><p>Now we are ready to create a Lambda Layer. Log on to your AWS Console, and navigate over to Lambda Console. Click on Layers on the left panel, and then “Create Layer”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmhrW6DSfhhmZh95o07G_Q.png" /></figure><p>The next section is pretty self explanatory. Give your Layer a name, description and upload your nodejs zip archive file. Make sure you select the appropriate runtime, in our case we selected Node.js 8.10. Runtime is important, since the runtime will dictate the environment path that your Lambda functions will refer to in order to import the dependencies. Once done, click “Create”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK6y6Q3tfQkThcFpgA4gfg.png" /><figcaption>Creating a Lambda Layer</figcaption></figure><p>Your Lambda Layer should now be ready to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOuxzt5QxB9w4O2QxwmQCw.png" /><figcaption>A Lambda Layer</figcaption></figure><p>Now it’s time to use your newly created Lambda Layer for NodeJS in a Lambda function. Head back to Lambda Console and click on “Functions” on the left panel and start creating a function from scratch.</p><p>You should now see a “new” option below the Lambda function name as “Layers”. Clicking on it reveals a section which lets you add your new Layer. We will do just that —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGCMq3UkjO7F2lzwhgMR4A.png" /><figcaption>Add Layer to a Lambda Function step 1</figcaption></figure><p>Click on “Add Layer”. On the next screen, select “Select from list of runtime compatible layers”. <strong><em>NOTE: Your Lambda Node version must match with the Lambda Layer Node Version</em></strong>. Chose your Lambda Layer from the drop down and then chose the “Version”. Click “Add”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lw61CCFMk8sbpx_Rll5XfA.png" /><figcaption>Add Layer to Lambda Function step 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w50oklt-EAug_XrZOejo3g.png" /><figcaption>Layer added to Lambda Function.</figcaption></figure><p>Don’t forget to save your function. That’s all as far as Layer configuration goes, now it’s time to write your Lambda code. There is nothing special about writing NodeJS Lambda function with this setup, with the exception that you can now simply open up the inline editor and start coding and importing the node modules that is included in the Lambda Layer.</p><p>Here’s a simple Lambda Function that makes call to an API using <a href="https://github.com/axios/axios">axios</a> module that is added in the Lambda Layer.</p><pre>const axios = require(&#39;axios&#39;);</pre><pre>exports.handler = async (event, context) =&gt; {<br>    const instance = axios.create({baseURL:&#39;<a href="http://api.yourdomain.com&/#39;">http://api.yourdomain.com&#39;</a>});<br>    try{<br>        const response = await instance.get(`/get/bookImages`);        <br>        const images = response.data.images;<br>        return {code: &quot;200&quot;, message: &quot;Success&quot;, images};<br>    }catch(error){<br>        console.log(`Error obtaining book images - ${error}`);<br>        return {<br>            code: &quot;400&quot;,<br>            message: `Error obtaining book images - ${error}`<br>        };<br>    }<br>};</pre><p>As you can see from the image below, there are no local node modules in the lambda function and I imported the axios module in the Lambda function just the regular way using require(&#39;axios&#39;).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZqeATusqroS8iDAzfMwsA.png" /></figure><p>That’s about it. You can now test your function. This is not just limited to node modules, you can add any piece of NodeJS custom code in the Layer and refer/import it in any Lambda function (speaking of efficient code re-use). Of course, everything you saw above can be done using AWS CLI as well, however certain IAC tools such as <a href="https://www.terraform.io/">Hashicorp’s Terraform</a> or <a href="https://serverless.com/">ServerLess Framework</a> are yet to support Lambda Layers, but the speed at which things are going, I won’t be surprised if they already start support for Lambda Layers by the time you stumble upon this article.</p><blockquote><strong>Update</strong>: IAC tools such as Terraform, Cloudformation, Serverless Framework, and SAM (Serverless Application Model) all support Lambda Layers now. I have personally used Terraform, Cloudformation and SAM in multiple production apps with Lambda Layers and haven’t faced any issues so far. I have <strong>not</strong> used Serverless Framework personally although their documentation suggests that it also supports Lambda Layers.</blockquote><h3>Custom re-usable code/data using Layers</h3><p>So far, we have seen how to use node_modules with Lambda Layers, but what about shared code or data? Maybe you have a common piece of utility function such as utlity.js or maybe you have a JSON file like options.json and you want to be able to include these into the Lambda Layer and be able to use them in all Lambda functions.</p><p>In order to do that simply, add your files under the nodejs directory as can be seen in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*zzsRJk07SQAz2G8e7LIwCg.png" /><figcaption>Custom files in Lambda Layer bundle</figcaption></figure><p>Once you have your desired files inside the nodejs directory, zip/archive the directory as explained previously and upload it into a Lambda Layer. Once we have the Lambda Layer assigned to our Lambda function, this is how we would import and use them-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qagn1xKCU3f1ciaHIqFPWg.png" /><figcaption>Importing and using the custom (shared) files</figcaption></figure><p>According to documentation -</p><blockquote>Your function can access the content of the layer during execution in the /opt directory. Layers are applied in the order that&#39;s specified, merging any folders with the same name. If the same file appears in multiple layers, the version in the last applied layer is used.</blockquote><p>This means the contents of the Layer are accessible using the /opt directory at runtime of the Lambda function, which gives us easy access to any shared piece of code or data that exists in the Lambda Layer. This not only applies to NodeJS, but is also applicable to any other language that is supported by Lambda and it’s corresponding Layer.</p><h3>What’s Next?</h3><p>This is barely scratching the surface with Lambda Layers and I am just starting to get my hands dirty with it. There’s quite a bit of documentation available now, and if you are interested checkout this amazing <a href="https://github.com/mthenw/awesome-layers">list of Lambda Runtimes</a> by the open source community on Github D̶o̶c̶u̶m̶e̶n̶t̶a̶t̶i̶o̶n̶ ̶i̶s̶ ̶l̶i̶t̶t̶l̶e̶ ̶s̶p̶a̶r̶s̶e̶,̶ ̶b̶u̶t̶ ̶t̶h̶a̶t̶’̶s̶ ̶j̶u̶s̶t̶ ̶a̶s̶ ̶a̶l̶m̶o̶s̶t̶ ̶a̶n̶y̶ ̶o̶t̶h̶e̶r̶ ̶A̶W̶S̶ ̶S̶e̶r̶v̶i̶c̶e̶. I highly recommend playing around with Layers, and as for me I̶ ̶m̶i̶g̶r̶a̶t̶e̶d̶ ̶2̶0̶ ̶s̶o̶m̶e̶t̶h̶i̶n̶g̶ ̶L̶a̶m̶b̶d̶a̶ ̶F̶u̶n̶c̶t̶i̶o̶n̶s̶ ̶o̶n̶ ̶o̶u̶r̶ ̶D̶e̶v̶ ̶e̶n̶v̶i̶r̶o̶n̶m̶e̶n̶t̶ ̶t̶o̶ ̶u̶s̶e̶ ̶L̶a̶y̶e̶r̶s̶ ̶a̶n̶d̶ ̶h̶a̶v̶e̶n̶’̶t̶ ̶f̶a̶c̶e̶d̶ ̶a̶n̶y̶ ̶i̶s̶s̶u̶e̶s̶ ̶s̶o̶ ̶f̶a̶r̶. As of 2020, all of our production as well as non-production Lambda workloads now extensively use Lambda Layers and we have adopted Continuous Deployment with <a href="https://github.com/awslabs/serverless-application-model">Serverless Application Model</a> (SAM) in developing and deploying Lambda functions at scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3914613e20e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>