<?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 Fabio Gollinucci on Medium]]></title>
        <description><![CDATA[Stories by Fabio Gollinucci on Medium]]></description>
        <link>https://medium.com/@daaru?source=rss-7cb6ae2574e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_klxdjiGDb57WI6O9oMbtQ.png</url>
            <title>Stories by Fabio Gollinucci on Medium</title>
            <link>https://medium.com/@daaru?source=rss-7cb6ae2574e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:47:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daaru/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[Serverless AI Search]]></title>
            <link>https://daaru.medium.com/serverless-ai-search-e32b576c0abf?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e32b576c0abf</guid>
            <category><![CDATA[amazon-s3-vectors]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 12:59:32 GMT</pubDate>
            <atom:updated>2026-01-18T12:59:32.922Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most interesting AWS announcements this year was the introduction of S3 Vectors, a completely serverless vector database. Until now, if you needed a vector database, you had to create large &quot;serverless&quot; OpenSearch clusters, paying several dollars for just a few hours of use, making it impractical for testing.</p><h3>What is a vector database?</h3><p>With the advent of LLMs, there has been a lot of talk about RAG and vector databases. These are a particular type of database where data, instead of being expressed in tables (SQL) or JSON objects (NoSQL), is expressed as vectors. This data represents the memory accessible by LLMs, where they can insert data and search for it using special queries based on the similarity of the data’s context.</p><p>For example, if I want to save a simple piece of text information like:</p><pre>black leather bag</pre><p>I first need to use a special LLM model called &quot;embedding&quot; to transform this text into a vector representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*m30viIUViozIkWdWdinK5Q.png" /><figcaption>Vectors bag-black-leather</figcaption></figure><p>The embedding model will transform the text into a series of vectors, arrows on a graph, that express a starting point, orientation, and length of the arrow. Each word and concept expressed in the text will become a vector:</p><pre>bag -&gt; [0.7, 0.4, ...]<br>black -&gt; [0.3, 0.5, ...]<br>leather -&gt; [0.8, 0.2, ...]</pre><p>thus transforming the entire text into a matrix of vectors:</p><pre>[<br>  [0.7, 0.4, ...],<br>  [0.3, 0.5, ...],<br>  [0.8, 0.2, ...]<br>]</pre><p>this representation will then be saved inside the vector database, referencing this data with an identifier (key), for example, in this case, it could be &quot;black-leather-bag&quot;.</p><p>When you later want to access this information, you will use a text query, for example:</p><pre>what material is the black bag made of?</pre><p>you will again use an embedding LLM model to transform this query into a series of vectors, simplifying:</p><pre>material -&gt; [0.9, 0.1, ...]<br>bag -&gt; [0.7, 0.4, ...]<br>black -&gt; [0.3, 0.5, ...]</pre><p>Inside the vector database, &quot;black bag&quot; will be expressed with the same vectors, while &quot;material&quot; will be a different vector from &quot;leather&quot; but not so distant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*pK4JdhVLg77veP48372FEQ.png" /><figcaption>Vectors search black-bag-material</figcaption></figure><p>The search will be performed by looking for nearby vectors within a certain radius (called topK), responding with the identifiers of the found data, in this case, &quot;black-leather-bag&quot;, as the vectors of the query are very close to those of the saved information.</p><h3>S3 Vectors setup</h3><p>This service operates as a database for these vectors and allows you to save and search for information, not only through a simple text query but also by adding metadata filters saved with the information. This type of filter is useful for segregating information, for example, by the user interacting with the LLM, by product category, by year of production, and much more.</p><p>The data is organized into indexes, the grouping of data we want to save. For example, in the same Vector Bucket, you can save user preferences, product catalog, and company data by describing three separate indexes, and when the query is performed, you will specify which of these data to search.</p><p>Support for CloudFormation has recently been added for creating the vector bucket and indexes, so we can describe:</p><pre>VectorBucket:<br>  Type: AWS::S3Vectors::VectorBucket<br>  Properties:<br>    VectorBucketName: &quot;my-vector-bucket&quot;<br>VectorIndexCatalog:<br>  Type: AWS::S3Vectors::Index<br>  DependsOn: VectorBucket<br>  Properties:<br>    VectorBucketName: &quot;my-vector-bucket&quot;<br>    IndexName: &quot;catalog&quot;<br>    Dimension: 256<br>    DistanceMetric: &quot;cosine&quot;<br>    DataType: &quot;float32&quot;</pre><p>The creation of the index requires some special properties, including:</p><ul><li><strong>Dimension</strong>: the number of values in a vector. The larger this number, the more specifically the vector will be expressed, but the data will have a greater weight.</li><li><strong>DistanceMetric</strong>: the type of measurement to describe the vectors, &quot;cosine&quot; to use the length (in simple contexts) or &quot;euclidean&quot; for a larger context (in more elaborate contexts such as image recognition).</li></ul><h3>Data ingestion</h3><p>Once the vector bucket is created, we can proceed to interact with it. To insert data inside, you will need to use an embedding model, via Bedrock, to transform the input data into numerical vectors (embeddings).</p><pre>import { BedrockRuntimeClient, InvokeModelCommand } from &#39;@aws-sdk/client-bedrock-runtime&#39;<br><br>const bedrock = new BedrockRuntimeClient()<br>const bedrockResponse = await bedrock.send(new InvokeModelCommand({<br>  modelId: &#39;amazon.titan-embed-text-v2:0&#39;,<br>  body: JSON.stringify({<br>    inputText: `black leather bag`, // the data to store<br>    dimensions: 256,<br>    normalize: true<br>  }),<br>}))<br>const decodedResponseBody = new TextDecoder().decode(bedrockResponse.body)<br>const { embedding } = JSON.parse(decodedResponseBody)</pre><p>We will now find in &quot;embedding&quot; the values of the vectors transformed by the embedding model. I recommend using the Amazon Titan Text Embeddings model, as it is simple to interact with and quite fast in processing.</p><p>The dimension of the vectors depends on the model used. For “amazon.titan-embed-text-v2:0”, you can choose a dimension of 256, 512, or 1024. It is crucial that the dimensions value you choose here (in this case, 256) exactly matches the “Dimension” property you set in your CloudFormation template for the index.</p><p>Now let&#39;s insert the values into the vector bucket:</p><pre>import { S3VectorsClient, PutVectorsCommand } from &#39;@aws-sdk/client-s3vectors&#39;<br><br>const s3vectors = new S3VectorsClient()<br>await s3vectors.send(new PutVectorsCommand({<br>  vectorBucketName: &#39;my-vector-bucket&#39;,<br>  indexName: &#39;catalog&#39;,<br>  vectors: [{<br>    key: &#39;black-leather-bag&#39;, // the data identifier<br>    data: {<br>      float32: embedding<br>    },<br>    metadata: {<br>      product_type: &#39;bag&#39; // additional metadata<br>    }<br>  }, {<br>    // other vectors<br>  }]<br>}))</pre><p>In addition to the embedding data, you need to add a data identifier, for example, the product handle or SKU, in order to relate it in the search results. You can also add metadata to filter the results.</p><h3>Query data</h3><p>To be able to perform a data search, starting from a query, you first need to transform it into an embedding, exactly as was done before for data insertion.</p><pre>import { BedrockRuntimeClient, InvokeModelCommand } from &#39;@aws-sdk/client-bedrock-runtime&#39;<br><br>const bedrock = new BedrockRuntimeClient()<br>const bedrockResponse = await bedrock.send(new InvokeModelCommand({<br>  modelId: &#39;amazon.titan-embed-text-v2:0&#39;,<br>  body: JSON.stringify({<br>    inputText: `material of the black bag`, // the query<br>    dimensions: 256,<br>    normalize: true<br>  }),<br>}))<br>const decodedResponseBody = new TextDecoder().decode(bedrockResponse.body)<br>const { embedding } = JSON.parse(decodedResponseBody)</pre><p>Now let&#39;s execute the query in the vector bucket:</p><pre>import { S3VectorsClient, QueryVectorsCommand } from &#39;@aws-sdk/client-s3vectors&#39;<br><br>const s3vectors = new S3VectorsClient()<br>let { vectors } = await s3vectors.send(new QueryVectorsCommand({<br>  vectorBucketName: &#39;my-vector-bucket&#39;,<br>  indexName: &#39;catalog&#39;,<br>  queryVector: {<br>    float32: embedding<br>  },<br>  topK: 10, // the results limit<br>  returnDistance: true,<br>  returnMetadata: true,<br>}))</pre><p>The result in &quot;vectors&quot; will contain the data identifiers and, if specified in the query, also the distance and metadata:</p><pre>[<br>  {<br>    &quot;distance&quot;: 0.8545453691482544,<br>    &quot;key&quot;: &quot;black-leather-bag&quot;,<br>    &quot;metadata&quot;: {<br>      &quot;product_type&quot;: &quot;bag&quot;<br>    }<br>  }<br>]</pre><p>We can add filters to the search to narrow down the data to search in:</p><pre>let { vectors } = await s3vectors.send(new QueryVectorsCommand({<br>  vectorBucketName: &#39;my-vector-bucket&#39;,<br>  indexName: &#39;catalog&#39;,<br>  queryVector: {<br>    float32: embedding<br>  },<br>  filter: {<br>    product_type: {<br>      &#39;$eq&#39;: &#39;bag&#39;<br>    }<br>  },<br>  topK: 10, // the results limit<br>  returnDistance: true,<br>  returnMetadata: true,<br>}))</pre><p>You can use equality, exclusion, and numerical (greater/less than) filters, concatenate filters with “and” and “or” logical operators, and much more.</p><pre>{&quot;genre&quot;: {&quot;$eq&quot;: &quot;documentary&quot;}}<br>{&quot;genre&quot;: {&quot;$ne&quot;: &quot;drama&quot;}}<br><br>{&quot;year&quot;: {&quot;$gt&quot;: 2019}}<br>{&quot;year&quot;: {&quot;$lte&quot;: 2020}}<br><br>{&quot;genre&quot;: {&quot;$in&quot;: [&quot;comedy&quot;, &quot;documentary&quot;]}}<br>{&quot;genre&quot;: {&quot;$nin&quot;: [&quot;comedy&quot;, &quot;documentary&quot;]}}<br><br>{&quot;genre&quot;: {&quot;$exists&quot;: true}}<br><br>{&quot;$and&quot;: [{&quot;genre&quot;: {&quot;$eq&quot;: &quot;drama&quot;}}, {&quot;year&quot;: {&quot;$gte&quot;: 2020}}]}<br>{&quot;$or&quot;: [{&quot;genre&quot;: {&quot;$eq&quot;: &quot;drama&quot;}}, {&quot;year&quot;: {&quot;$gte&quot;: 2020}}]}<br><br>{&quot;price&quot;: {&quot;$gte&quot;: 10, &quot;$lte&quot;: 50}}</pre><p>Be careful that to combine filters, you cannot use the syntax:</p><pre>{ &quot;genre&quot;: {&quot;$eq&quot;: &quot;drama&quot;}, &quot;year&quot;: {&quot;$gte&quot;: 2020} }</pre><p>but it will always be necessary to use a single property in the main object and use logical operators to concatenate the filters</p><pre>{&quot;$and&quot;: [{&quot;genre&quot;: {&quot;$eq&quot;: &quot;drama&quot;}}, {&quot;year&quot;: {&quot;$gte&quot;: 2020}}]}</pre><p>The format of the filters is a bit particular, more information is available in the relative documentation.</p><h3>Build a search API</h3><p>Putting together what we have gathered, we can therefore implement a simple search API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbtEX_CAn9bsiW1EKuIMNA.png" /><figcaption>Infrastructure schema</figcaption></figure><p>To do this, I created two API Gateways, one to manage the content and one to expose the search.</p><p>As for the content APIs, it is not possible to retrieve data from the vector database explicitly via its identifier or to list it. To simplify this access, I created a simple S3 support bucket where to save the data. In this way, I can perform get, put, delete operations on the objects of a standard bucket and synchronize this data in the vector bucket by listening to the creation, modification, and deletion events of the objects through the integration with EventBridge. This approach can be improved by putting an SQS queue (possibly FIFO) in the middle to have greater control over the resources used in synchronization, retries, and the sequence of changes.</p><p>The search endpoint, on the other hand, uses the approach described before to convert the text query into an embedding and then query the vector bucket.</p><h3>Limitations</h3><p>This is a rather simple and very powerful system, but there are some limitations:</p><ul><li>Response times with such a system are around 800ms; a good part of the time spent is due to the embedding model’s processing, which is unfortunately fundamental. However, it’s not bad considering the minimal resource consumption and the total serverless approach.</li><li>The search query must necessarily have text (queryVector); only filters can be used.</li><li>The possible filters and values to apply (facets) are not returned in the response, which is common for search engines like OpenSearch.</li></ul><h3>Knowledge base integration</h3><p>This vector database can be used as a knowledge base for an LLM model. <a href="https://aws.amazon.com/bedrock/knowledge-bases/">Amazon Bedrock Knowledge Bases</a> helps with this, as configuring it with S3 Vectors makes saving and retrieving data simpler for this use case.</p><p>To ingest data, its specific API is used:</p><pre>import { BedrockAgentClient, IngestKnowledgeBaseDocumentsCommand } from &#39;@aws-sdk/client-bedrock-agent&#39;<br><br>const bedrock = new BedrockAgentClient()<br>await bedrock.send(new IngestKnowledgeBaseDocumentsCommand({<br>  knowledgeBaseId: KNOWLEDGE_BASE_ID,<br>  dataSourceId: DATA_SOURCE_ID,<br>  documents: [{<br>    metadata: metadata ? {<br>      type: &#39;IN_LINE_ATTRIBUTE&#39;,<br>      inlineAttributes: metadata<br>    } : undefined,<br>    content: {<br>      dataSourceType: &#39;CUSTOM&#39;,<br>      custom: {<br>        sourceType: &#39;IN_LINE&#39;,<br>        customDocumentIdentifier: {<br>          id: &#39;preference-1&#39; // the data identifier<br>        },<br>        inlineContent: {<br>          type: &#39;TEXT&#39;,<br>          textContent: {<br>            data: &#39;the user prefer bag over backpack&#39;, // the text to ingest<br>          }<br>        }<br>      }<br>    }<br>  }]<br>}))</pre><p>To then search and retrieve data, two approaches can be used. One is the simple retrieval of the saved text:</p><pre>import { BedrockAgentRuntimeClient, RetrieveCommand } from &#39;@aws-sdk/client-bedrock-agent-runtime&#39;<br><br>const bedrockRuntime = new BedrockAgentRuntimeClient()<br>const response = await bedrockRuntime.send(new RetrieveCommand({<br>  knowledgeBaseId: KNOWLEDGE_BASE_ID,<br>  retrievalQuery: {<br>    text: query, // the plain query text<br>  },<br>  retrievalConfiguration: {<br>    vectorSearchConfiguration: {<br>      filter // filter to apply<br>    }<br>  }<br>}))<br>const results = response.retrievalResults.map(result =&gt; result.content.text) // will contain the ingested text &#39;the user prefer bag over backpack&#39;</pre><p>Alternatively, another LLM model can be used to re-elaborate the search result:</p><pre>import { BedrockAgentRuntimeClient, RetrieveAndGenerateCommand } from &#39;@aws-sdk/client-bedrock-agent-runtime&#39;<br><br>const bedrockRuntime = new BedrockAgentRuntimeClient()<br>const response = await bedrockRuntime.send(new RetrieveAndGenerateCommand({<br>  retrieveAndGenerateConfiguration: {<br>    type: &#39;KNOWLEDGE_BASE&#39;,<br>    knowledgeBaseConfiguration: {<br>      knowledgeBaseId: KNOWLEDGE_BASE_ID,<br>      modelArn: KNOWLEDGE_BASE_MODEL_ARN, // the ARN of the model to use to elaborate response<br>      generationConfiguration: {<br>        inferenceConfig: {<br>          textInferenceConfig: {<br>            maxTokens: 1000,<br>            temperature: 0.1,<br>            topP: 0.9<br>          }<br>        }<br>      },<br>      orchestrationConfiguration: {<br>        inferenceConfig: {<br>          textInferenceConfig: {<br>            maxTokens: 1000,<br>            temperature: 0.1,<br>            topP: 0.9<br>          }<br>        }<br>      },<br>      retrievalConfiguration: {<br>        vectorSearchConfiguration: {<br>          filter // filter to apply<br>        }<br>      }<br>    }<br>  },<br>  input: {<br>    text: query, // the plain query text<br>  }<br>}))<br>// if no results will be find the model will return a fixed response<br>if (!response.output || !response.output.text || response.output.text.includes(&#39;I am unable to assist you with this request&#39;)) {<br>  return null<br>}<br>return response.output.text // the results summary</pre><p>in this case, if the search query is “what does the user prefer most?”, the answer will simply be “bag”.</p><p>This type of approach is more focused on usage by an LLM model; there is less control over the data (put and delete). In return, you get the retrieval of the text saved in the vector database or even a summary of it centered on the request made by the textual query.</p><p><em>Credits: </em><a href="https://www.cloudcraft.co/"><em>Cloudcraft</em></a><em>.</em></p><p><em>Repository: </em><a href="https://github.com/daaru00/aws-serverless-ai-search"><em>daaru00/aws-serverless-ai-search</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e32b576c0abf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Websocket Chat]]></title>
            <link>https://daaru.medium.com/serverless-websocket-chat-4cde5cea26ef?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cde5cea26ef</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-appsync]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 22:07:21 GMT</pubDate>
            <atom:updated>2025-11-30T22:07:21.230Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently implemented a real-time chat solution. I had worked with API Gateway and its <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api.html">Websocket support</a> in the past and found it quite difficult. I started again by looking for a managed Websocket service and came across <a href="https://docs.aws.amazon.com/appsync/latest/eventapi/event-api-welcome.html">AppSync Events</a>.</p><h3>AppSync Events</h3><p>This serverless service allows you to expose both GraphQL and Websocket endpoints and use numerous integrations with other services. This service is the backbone of <a href="https://aws.amazon.com/amplify/">Amplify’s</a> backend integration.</p><p>The event endpoint, in particular, is a system specifically designed for implementing chats, sending and receiving events (pub/sub), receiving updates, and everything related to real-time activities, exactly what I was looking for.</p><p>The client will connect to the endpoint, subscribe to a channel (a path /&lt;namespace&gt;/&lt;channel&gt;), and will be able to listen and publish events, if allowed. The backend implementation can send events by publishing to a specific channel, and the clients that have subscribed will receive the event.</p><h3>Event endpoint</h3><p>Following the first tutorials, I started to describe the endpoint:</p><pre>EventAPI:<br>  Type: AWS::AppSync::Api<br>  Properties:<br>    Name: !Ref AWS::StackName<br>    EventConfig:<br>      AuthProviders:<br>        - AuthType: API_KEY<br>      ConnectionAuthModes:<br>        - AuthType: API_KEY<br>      DefaultPublishAuthModes:<br>        - AuthType: API_KEY<br>      DefaultSubscribeAuthModes:<br>        - AuthType: API_KEY<br><br>EventAPIKey:<br>  Type: AWS::AppSync::ApiKey<br>  Properties:<br>    ApiId: !GetAtt EventAPI.ApiId<br>    Description: API Key for Events API</pre><p>Connected to the endpoint, it is necessary to describe the DataSource, which is what will handle receiving the messages, in my case a Lambda function:</p><pre>DataSourceRole:<br>  Type: AWS::IAM::Role<br>  Properties:<br>    AssumeRolePolicyDocument:<br>      Version: &quot;2012-10-17&quot;<br>      Statement:<br>        - Effect: &quot;Allow&quot;<br>          Principal:<br>            Service:<br>              - &quot;appsync.amazonaws.com&quot;<br>          Action:<br>            - &quot;sts:AssumeRole&quot;<br>    Policies:<br>      - PolicyName: &quot;invoke&quot;<br>        PolicyDocument:<br>          Version: &quot;2012-10-17&quot;<br>          Statement:<br>            - Effect: &quot;Allow&quot;<br>              Action:<br>                - &quot;lambda:InvokeFunction&quot; # permit the DataSource to call the Lambda function<br>              Resource:<br>                - !GetAtt SubscriberFunction.Arn<br><br>DataSource:<br>  Type: AWS::AppSync::DataSource<br>  Properties:<br>    ApiId: !GetAtt EventAPI.ApiId<br>    Name: &quot;LambdaDataSource&quot;<br>    Type: &quot;AWS_LAMBDA&quot;<br>    ServiceRoleArn: !GetAtt DataSourceRole.Arn<br>    LambdaConfig:<br>      LambdaFunctionArn: !GetAtt SubscriberFunction.Arn # the Lambda function to call when an event is published<br><br>EventApiNameSpace:<br>  Type: AWS::AppSync::ChannelNamespace<br>  Properties:<br>    ApiId: !GetAtt EventAPI.ApiId<br>    Name: &#39;sessions&#39; # this is the connection path &quot;/session/&lt;something else&gt;&quot;<br>    HandlerConfigs:<br>      OnPublish:<br>        Behavior: &#39;DIRECT&#39;<br>        Integration:<br>          DataSourceName: !GetAtt DataSource.Name<br>          LambdaConfig:<br>            InvokeType: &#39;EVENT&#39;</pre><p>This way, the endpoint is ready to receive connections. The connection will be made to the exported endpoint:</p><pre>Outputs:<br>  EventApiEndpoint:<br>    Description: &quot;Event API Endpoint&quot;<br>    Value: !Sub &quot;https://${EventAPI.Dns.Http}/event&quot;</pre><p>The authentication in this case is very simple and will use an API key, also declared in the template (EventAPIKey), which allows all operations of connection, subscription to an endpoint, and publication of events.</p><h3>Lambda subscriber and publisher</h3><p>The Lambda function that will listen for events is quite simple:</p><pre>SubscriberFunction:<br>  Type: AWS::Serverless::Function<br>  Properties:<br>    FunctionName: !Sub &quot;${AWS::StackName}-subscriber&quot;<br>    Handler: events/subscriber.handler</pre><p>When one or more events are published to a channel in the declared namespace (EventApiNameSpace), the Lambda function will receive:</p><pre>export async function handler({ info, events }) {<br>  const sessionId = info.channel.segments[1] // the channel name, for exemple /session/&lt;session id&gt;<br>  for (const event of events) {<br>    console.log(event.payload) // the event payload<br>  }<br>}</pre><p>To send an event to a channel, we use another Lambda function, passing the endpoint and the API key in the environment variables:</p><pre>PublisherFunction:<br>  Type: AWS::Serverless::Function<br>  Properties:<br>    FunctionName: !Sub &quot;${AWS::StackName}-publisher&quot;<br>    Handler: events/publisher.handler<br>    Environment:<br>      Variables:<br>        PUBLISH_ENDPOINT: !Sub &quot;https://${EventAPI.Dns.Http}/event&quot;<br>        PUBLISH_API_KEY: !GetAtt EventAPIKey.ApiKey</pre><p>The sending is done by executing a simple HTTP request to the event endpoint:</p><pre>const PUBLISH_ENDPOINT = process.env.PUBLISH_ENDPOINT<br>const PUBLISH_API_KEY = process.env.PUBLISH_API_KEY<br><br>export async function handler(event) {<br> const response = await fetch(PUBLISH_ENDPOINT, {<br>  method: &#39;POST&#39;,<br>  headers: {<br>   &#39;Content-Type&#39;: &#39;application/json&#39;,<br>   &#39;x-api-key&#39;: PUBLISH_API_KEY<br>  },<br>  body: JSON.stringify({<br>   channel: `sessions/${event.detail.session}`, // the channel<br>   events: [<br>    JSON.stringify(event.detail.message) // list of message as JSON strings<br>   ]<br>  })<br> })<br><br> if (!response.ok) {<br>  const { errors } = await response.json()<br>  console.error(&#39;Failed to publish event&#39;, errors)<br>  throw new Error(&#39;Failed to publish event&#39;)<br> }<br><br> const { failed, successful } = await response.json()<br> if (failed.length &gt; 0) {<br>  console.error(failed)<br>  throw new Error(&#39;Failed to publish event&#39;)<br> }<br><br> return successful<br>}</pre><p>The request must be authenticated, in this case via an API key specified in the x-api-key header, passing the channel to send the events to and the list of event payloads in JSON string format.</p><h3>Authentication</h3><p>Using this simplistic way of authentication via API key might have been fine for sending events server-side while keeping the API key secret, but it’s not enough to protect the connection from clients, where the API key would be in plain text.</p><p>Another fundamental problem with the API key, which I discovered at my own expense after a few weeks of use… <strong>the API key has an expiration date!</strong> The setting is mandatory and therefore requires a rotation of the key upon its expiration or a change of the expiration date.</p><p>AppSync Events allows for numerous authentication methods, including Cognito, IAM, OpenID Connect, Lambda, or, indeed, API key. If we are already using Cognito or another OpenID authentication system in our system, it is easy to use these two types of authentication. If you want to use a more customized method, you can use a Lambda function that acts as a request authenticator.</p><h3>Lambda authentication</h3><p>To use a Lambda function, you first need to declare its use in the endpoint configuration, in my case protecting the client’s operations (connect, publish, and subscribe):</p><pre>EventAPI:<br>  Type: AWS::AppSync::Api<br>  Properties:<br>    Name: !Ref AWS::StackName<br>    EventConfig:<br>      AuthProviders:<br>        - AuthType: API_KEY<br>        - AuthType: AWS_LAMBDA<br>          LambdaAuthorizerConfig:<br>            AuthorizerUri: !GetAtt AuthorizerFunction.Arn<br>            IdentityValidationExpression: &#39;.*&#39;<br>            AuthorizerResultTtlInSeconds: 300<br>      ConnectionAuthModes:<br>        - AuthType: AWS_LAMBDA<br>      DefaultPublishAuthModes:<br>        - AuthType: AWS_LAMBDA<br>        - AuthType: API_KEY<br>      DefaultSubscribeAuthModes:<br>        - AuthType: AWS_LAMBDA</pre><p>We then declare the Lambda function and the relative permissions for it to be called by AppSync:</p><pre>AuthorizerFunction:<br>  Type: AWS::Serverless::Function<br>  Properties:<br>    FunctionName: !Sub &quot;${AWS::StackName}-authorizer&quot;<br>    Handler: events/authorizer.handler<br>    <br>AuthorizerPermission:<br>  Type: AWS::Lambda::Permission<br>  Properties:<br>    FunctionName: !Ref AuthorizerFunction<br>    Action: lambda:InvokeFunction<br>    Principal: appsync.amazonaws.com<br>    SourceArn: !GetAtt EventAPI.ApiArn</pre><p>The implementation is quite simple, the Lambda function will be called indicating the event (EVENT_CONNECT, EVENT_SUBSCRIBE, EVENT_PUBLISH) and the token used:</p><pre>export async function handler(event) {<br>  // extract the provided token<br>  const token = event.authorizationToken<br><br>  // check the channel subscription<br>  if (event.requestContext.operation === &#39;EVENT_SUBSCRIBE&#39; &amp;&amp; event.requestContext.channel !== `/sessions/&lt;session id&gt;`) {<br>    console.error(&#39;Unauthorized subscription attempt to channel:&#39;, event.requestContext.channel)<br>    return {<br>      isAuthorized: false<br>    }<br>  }<br><br>  return {<br>   isAuthorized: true<br>  }<br>}</pre><h3>IAM authentication</h3><p>To protect the publication of the event on the client side, I used IAM authentication, which is very simple to manage with a Lambda function:</p><pre>EventAPI:<br>  Type: AWS::AppSync::Api<br>  Properties:<br>    Name: !Ref AWS::StackName<br>    EventConfig:<br>      AuthProviders:<br>        - AuthType: AWS_IAM<br>        - AuthType: AWS_LAMBDA<br>          LambdaAuthorizerConfig:<br>            AuthorizerUri: !GetAtt AuthorizerFunction.Arn<br>            IdentityValidationExpression: &#39;.*&#39;<br>            AuthorizerResultTtlInSeconds: 300<br>      ConnectionAuthModes:<br>        - AuthType: AWS_LAMBDA<br>      DefaultPublishAuthModes:<br>        - AuthType: AWS_LAMBDA<br>        - AuthType: AWS_IAM<br>      DefaultSubscribeAuthModes:<br>        - AuthType: AWS_LAMBDA</pre><p>The Lambda function will then need the permissions to publish the events in the channels:</p><pre>PublisherFunction:<br>  Type: AWS::Serverless::Function<br>  Properties:<br>    FunctionName: !Sub &quot;${AWS::StackName}-publisher&quot;<br>    Handler: events/publisher.handler<br>    Environment:<br>      Variables:<br>        PUBLISH_ENDPOINT: !Sub &quot;https://${EventAPI.Dns.Http}/event&quot;<br>    Policies:<br>      - Statement:<br>          Effect: &quot;Allow&quot;<br>          Action:<br>            - &quot;appsync:EventPublish&quot;<br>          Resource:<br>            - !Sub &quot;arn:aws:appsync:${AWS::Region}:${AWS::AccountId}:apis/${EventAPI.ApiId}/*&quot;</pre><p>To authenticate the HTTP call, you will need to use the same method used by the AWS SDK to contact the actual services, which is <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html">AWS Signature Version 4</a>.</p><p>To do this, I found a very simple node library that wraps around fetch: <a href="https://www.npmjs.com/package/aws-sigv4-fetch">aws-sigv4-fetch</a></p><pre>import { createSignedFetcher } from &#39;aws-sigv4-fetch&#39;<br><br>const PUBLISH_ENDPOINT = process.env.PUBLISH_ENDPOINT<br><br>export async function handler(event) {<br> const signedFetch = createSignedFetcher({<br>  service: &#39;appsync&#39;,<br>  region: process.env.AWS_REGION,<br>  credentials: { // passing credentials from Lambda to the HTP request<br>   accessKeyId: process.env.AWS_ACCESS_KEY_ID,<br>   secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,<br>   sessionToken: process.env.AWS_SESSION_TOKEN,<br>  }<br> });<br><br> const response = await signedFetch(PUBLISH_ENDPOINT, {<br>  method: &#39;POST&#39;,<br>  headers: {<br>   &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  },<br>  body: JSON.stringify({<br>   channel: `sessions/${event.detail.session}`,<br>   events: [<br>    JSON.stringify(event.detail.message)<br>   ]<br>  })<br> })<br><br> // same response check as above<br>}</pre><p>After these changes, everything remains more controllable and secure without exposing fixed API keys.</p><h3>Origin verification</h3><p>After the first tests, you may notice that the events received also include those sent server-side. This could therefore open up the possibility of event injection from the frontend or simply create confusion as to which ones were sent by the client and which by the server.</p><p>With a small modification, I noticed that you can add headers in the event publication call:</p><pre>const SOURCE_VERIFICATION_TOKEN = process.env.SOURCE_VERIFICATION_TOKEN<br><br>export async function handler(event) {<br>  // ...<br><br>  const response = await signedFetch(PUBLISH_ENDPOINT, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      &#39;x-source-token&#39;: SOURCE_VERIFICATION_TOKEN // static generated key<br>    },<br>    body: JSON.stringify({<br>      channel: `sessions/${event.detail.session}`,<br>      events: [<br>        JSON.stringify(event.detail.message)<br>      ]<br>    })<br>  })<br><br>  // ...<br>}</pre><p>We will find these additional headers in the event of the function that listens for incoming events:</p><pre>const SOURCE_VERIFICATION_TOKEN = process.env.SOURCE_VERIFICATION_TOKEN<br><br>export async function handler({ info, events, request }) {<br>  let source<br>  if (request.headers[&#39;x-source-token&#39;] === SOURCE_VERIFICATION_TOKEN) {<br>    source = &#39;server&#39;<br>  } else {<br>    source = &#39;user&#39;<br>  }<br> <br>  // ...<br>}</pre><p>This approach provides a further level of control by marking the source of the events in a controlled manner.</p><h3>Infrastructure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGnnATNP3psAeY4FmYfRzw.png" /><figcaption>Infrastructure schema</figcaption></figure><p>The complete solution is built around an EventBridge event bus, which serves as the central component for decoupling the application. This architectural choice enhances scalability, resilience, and maintainability. When a client sends a message via the AppSync Websocket channel, the SubscriberFunction receives it and forwards the event to the EventBridge bus. The bus can then route the event to multiple downstream consumers, without the subscriber function having any knowledge of them.</p><p>When the backend needs to send a message to a client, another service publishes an event to the bus, and the PublisherFunction listens for it to publish it to the correct AppSync channel. This decoupling ensures the real-time communication core is not tied to business logic, allowing for easier extensions and greater resilience.</p><p>For Lambda authentication, a simple REST endpoint using API Gateway is implemented. It exposes an API for the client to create a session and obtain an authentication token. This mechanism provides a straightforward way to manage authentication and allows for custom logic to save information about the user, the chat, or its history, for example, by leveraging a DynamoDB table. This approach makes it possible to lock down the client to connect only to its own channel, ensuring precise access control.</p><h3>Frontend usage</h3><p>Let’s now see how to connect a client, in this case a web client, to the event endpoint. It is not easy to manually manage the connection to a Websocket and also manage the Lambda authentication, which requires a series of initial events to send the token.</p><p>AWS provides the primaries for connecting to an AppSync event endpoint in the <a href="https://www.npmjs.com/package/aws-amplify">aws-amplify</a> library:</p><pre>npm install aws-amplify</pre><p>First, you need to initialize the library by passing the event endpoint configuration:</p><pre>import { Amplify } from &#39;aws-amplify&#39;<br><br>Amplify.configure({<br>  &quot;API&quot;: {<br>    &quot;Events&quot;: {<br>      &quot;endpoint&quot;: &#39;https://xxxxxxxxxxxxxx.appsync-api.us-east-1.amazonaws.com/event&#39;,<br>      &quot;region&quot;: &#39;us-east-1&#39;,<br>      &quot;defaultAuthMode&quot;: &#39;lambda&#39;<br>    }<br>  }<br>})</pre><p>Now, after retrieving a session ID and its token from the endpoint exposed with API Gateway, you can connect and subscribe to the channel to receive events:</p><pre>import { events } from &#39;aws-amplify/data&#39;<br><br>const channel = await events.connect(`/sessions/${sessionId}`, {<br>  authToken: sessionToken<br>})<br>channel.subscribe({<br>  next: (data) =&gt; {<br>    console.log(&#39;Event received&#39;, data.event) // the vent payload recevied<br>  },<br>  error: ({ errors }) =&gt; {<br>    console.error(&#39;Event channel error&#39;, errors)<br>    channel.close()<br>  },<br>}, {<br>  authToken: sessionToken<br>})</pre><p>Once connected to the channel, you can send events to the server:</p><pre>channel.publish({ /** the event payload */ }, {<br>  authToken: sessionToken<br>})</pre><p><em>Credits: </em><a href="https://www.cloudcraft.co/"><em>Cloudcraft</em></a><em>.</em></p><p><em>Repository: </em><a href="https://github.com/daaru00/aws-serverless-chat"><em>daaru00/aws-serverless-chat</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cde5cea26ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orchestrate ECS Tasks with StepFunction]]></title>
            <link>https://daaru.medium.com/orchestrate-ecs-tasks-with-stepfunction-c59b0f81f541?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c59b0f81f541</guid>
            <category><![CDATA[ecs-fargate]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 15:52:55 GMT</pubDate>
            <atom:updated>2025-07-10T15:52:55.253Z</atom:updated>
            <content:encoded><![CDATA[<p>In some cases it is not possible to perform some work operations within a Lambda function, this is due to timeouts or system dependencies that are difficult to install and manage.</p><p>In some cases running a bash script in a given Docker image does the job more than well. This especially applies to DevOps tasks, such as dumping a database or converting a series of JPEG/PNG images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTw7qct9Jvzm9Yhd670ZLQ.png" /><figcaption>Infrastructure schema</figcaption></figure><p>Let’s start first with the infrastructure configurations, some resources are needed to run a Docker container in the AWS world.</p><h3>Docker repository</h3><p>You can use a public repository like <a href="https://hub.docker.com/">Docker Hub</a> or public ECR repository.</p><pre>ECRRepository:<br>  Type: AWS::ECR::PublicRepository<br>  Properties:<br>    RepositoryName: !Sub &quot;${ProjectName}/${ImageName}&quot; # example/my-image<br>    ImageScanningConfiguration:<br>      ScanOnPush: &#39;true&#39;</pre><p>For private repositories you will need to add the necessary permissions to repository to be able to pull and run Docker images from your account:</p><pre>  ECRRepository:<br>    Type: AWS::ECR::Repository<br>    Properties:<br>      RepositoryName: !Sub &quot;${ProjectName}/${ImageName}&quot;<br>      ImageScanningConfiguration:<br>        ScanOnPush: &#39;true&#39;<br>      RepositoryPolicyText: <br>        Version: &quot;2012-10-17&quot;<br>        Statement:<br>          Effect: &quot;Allow&quot;<br>          Principal:<br>            AWS: !Sub &quot;arn:aws:iam::${AWS::AccountId}:root&quot;<br>          Action:<br>            - &quot;ecr:BatchCheckLayerAvailability&quot;<br>            - &quot;ecr:BatchGetImage&quot;<br>            - &quot;ecr:DescribeImages&quot;<br>            - &quot;ecr:DescribeRepositories&quot;<br>            - &quot;ecr:GetDownloadUrlForLayer&quot;</pre><h3>ECS Cluster</h3><p>The simplest way to run an ECS task is to use <a href="https://aws.amazon.com/fargate/">Fargate</a>, without having to do EC2 instance configurations and worry about the underlying infrastructure.</p><pre>EcsCluster:<br>  Type: &#39;AWS::ECS::Cluster&#39;<br>  Properties:<br>    ClusterName: !Ref AWS::StackName<br>    CapacityProviders:<br>      - FARGATE_SPOT<br>    DefaultCapacityProviderStrategy:<br>      - CapacityProvider: FARGATE_SPOT<br>        Weight: 1</pre><p>Using SPOT mode also reduces the price of execution by using <a href="https://aws.amazon.com/blogs/aws/aws-fargate-spot-now-generally-available/">Spot instances</a>.</p><p>A fundamental part in the execution of the docker container is the definition of the task, this describes how it will be executed: with which permissions, which environment variables, where to log the output and how many resources in terms of CPU and memory to allocate to the execution.</p><h4>Log</h4><p>To save the output of the docker container you will need to declare a CloudWatch Log group:</p><pre>EcsTaskLogGroup: <br>  Type: AWS::Logs::LogGroup<br>  Properties: <br>    LogGroupName: !Sub &quot;/aws/ecs/${AWS::StackName}/my-task&quot;<br>    RetentionInDays: 30</pre><p>Remember to import a retention to avoid accumulating logs forever, increasing CloudWatch costs.</p><h4>Permissions</h4><p>The permits that we will declare will be two:</p><ul><li>Task execution role: ECS container and Fargate agents permission to make AWS API calls on your behalf, for example to log output to CloudWatch or retrieving SSM secrets to put into environment variables</li><li>Task role: Role assumed by the containers running in the task, the permissions required depend on which AWS APIs will be used within the container execution.</li></ul><pre>TaskExecutionRole:<br>  Type: AWS::IAM::Role<br>  Properties:<br>    RoleName: !Sub &quot;${AWS::StackName}-task-execution-role&quot;<br>    AssumeRolePolicyDocument:<br>      Version: 2012-10-17<br>      Statement:<br>        - Effect: Allow<br>          Principal:<br>            Service:<br>            - ecs-tasks.amazonaws.com<br>          Action:<br>            - &#39;sts:AssumeRole&#39;<br>    Policies:<br>      - PolicyName: logging<br>        PolicyDocument:<br>          Version: &quot;2012-10-17&quot;<br>          Statement:<br>            - Effect: &quot;Allow&quot;<br>              Action: <br>                - logs:CreateLogStream<br>                - logs:PutLogEvents<br>              Resource: !GetAtt EcsTaskLogGroup.Arn<br>      - PolicyName: secrets<br>        PolicyDocument:<br>          Version: &quot;2012-10-17&quot;<br>          Statement:<br>            - Effect: &quot;Allow&quot;<br>              Action: <br>                - &quot;ssm:GetParameters&quot;<br>              Resource: <br>                - !Sub &quot;arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${AWS::StackName}/*&quot;<br><br>TaskRole:<br>  Type: AWS::IAM::Role<br>  Properties:<br>    RoleName: !Sub &quot;${AWS::StackName}-task-role&quot;<br>    AssumeRolePolicyDocument:<br>      Version: 2012-10-17<br>      Statement:<br>        - Effect: Allow<br>          Principal:<br>            Service:<br>            - ecs-tasks.amazonaws.com<br>          Action:<br>            - &#39;sts:AssumeRole&#39;<br>    Policies:<br>      - PolicyName: !Ref AWS::StackName<br>        PolicyDocument:<br>          Version: &quot;2012-10-17&quot;<br>          Statement:<br>            - Effect: &quot;Allow&quot;<br>              Action:<br>                - states:SendTaskSuccess<br>                - states:SendTaskFailure<br>              Resource:<br>                # this avoid circular dependency between step function and task definition<br>                - !Sub &quot;arn:aws:states:${AWS::Region}:${AWS::AccountId}:stateMachine:${AWS::StackName}-*&quot;</pre><p>In our case the Docker container will have to communicate back to StepFunction using the SendTaskSuccess API (in case of successful execution) or SendTaskFailure API (in case of errors).</p><h4>Task definition</h4><p>Let’s create the task definition now, we will specify the execution through Fargate, configure its resources and environment variables</p><pre>EcsTaskDefinition: <br>  Type: AWS::ECS::TaskDefinition<br>  Properties:<br>    Family: !Ref AWS::StackName<br>    Cpu: 256 # The number of cpu units used by the task, 256 = 0.25 vCPU <br>    Memory: 512 # The amount (in MiB) of memory used by the task<br>    NetworkMode: awsvpc<br>    ContainerDefinitions: <br>      - Name: &quot;my-container&quot;<br>        Image: !Ref DockerImage<br>        Essential: true<br>        Secrets:<br>          - Name: DB_USER<br>            ValueFrom: !Sub &quot;arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter${DbUsernameParameter}&quot;<br>          - Name: DB_PASS<br>            ValueFrom: !Sub &quot;arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter${DbPasswordParameter}&quot;<br>        LogConfiguration:<br>          LogDriver: &quot;awslogs&quot;<br>          Options:<br>            awslogs-group: !Ref EcsTaskLogGroup<br>            awslogs-region: !Ref AWS::Region<br>            awslogs-stream-prefix: &quot;ecs&quot;<br>    ExecutionRoleArn: !GetAtt TaskExecutionRole.Arn<br>    TaskRoleArn: !GetAtt TaskRole.Arn<br>    RequiresCompatibilities: <br>      - FARGATE</pre><p>Pay attention to the CPU definition, this is a bit of a complicated step, you need to check the <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html">documentation carefully</a>.</p><p>A very convenient and interesting feature is secrets, you can load values ​​from SSM automatically without specifying them inside the template definition.</p><h3>StepFunction task</h3><p>The StateMachine resource is defined in the “template.yaml” referring to its own declaration file with the “DefinitionUri” property. The content of the definition file will be parsed and all “DefinitionSubstitutions” keys will be replaced with the corresponding value.</p><p>The StateMachine needs policy to access other AWS services, like a Lambda function. For ECS the RunTask action policy is required and also passing the Task’s roles needs to be allowed via “iam:PassRole”.</p><pre>Resources:  <br>  StateMachine:<br>    Type: AWS::Serverless::StateMachine<br>    Properties:<br>      Name: !Ref AWS::StackName<br>      DefinitionUri: execute.asl.yaml<br>      DefinitionSubstitutions:<br>        ClusterArn: !GetAtt EcsCluster.Arn<br>        TaskDefinitionArn: !Ref EcsTaskDefinition<br>        VpcSubnet1: !Select [ 0, !Ref VpcSubnets ]<br>        VpcSubnet2: !Select [ 1, !Ref VpcSubnets ]<br>        VpcSubnet3: !Select [ 2, !Ref VpcSubnets ]<br>      Policies:<br>        - Statement:<br>          - Effect: &quot;Allow&quot;<br>            Action:<br>              - ecs:RunTask<br>            Resource: <br>              - !Ref EcsTaskDefinition<br>          - Effect: Allow<br>            Action:<br>              - iam:PassRole<br>            Resource:<br>             - !GetAtt TaskRole.Arn<br>             - !GetAtt TaskExecutionRole.Arn</pre><p>StepFunction has a direct integration with ECS, for executing a new task some network configurations are required like the ECS cluster ARN, the Task Definition ARN and at least one VPC subnet ID.</p><p>The StepFunction and ECS integration also supports the async mode using TaskToken. Accessing the token from “$$.Task.Token” the StateMachine’s step will pass it through the environment variable TASK_TOKEN to the task’s execution.</p><pre>StartAt: ExecuteTask<br>States:<br>  ExecuteTask:<br>    Type: Task<br>    Resource: &#39;arn:aws:states:::ecs:runTask.waitForTaskToken&#39;<br>    TimeoutSeconds: 300<br>    Parameters:<br>      Cluster: &#39;${ClusterArn}&#39;<br>      TaskDefinition: &#39;${TaskDefinitionArn}&#39;<br>      NetworkConfiguration:<br>        AwsvpcConfiguration:<br>          Subnets:<br>            - &#39;${VpcSubnet1}&#39;<br>            - &#39;${VpcSubnet2}&#39;<br>            - &#39;${VpcSubnet3}&#39;<br>          AssignPublicIp: ENABLED<br>      Overrides:<br>        ContainerOverrides:<br>          - Name: container<br>            Command: &quot;example&quot;<br>            Environment:<br>              - Name: TASK_TOKEN<br>                Value.$: $$.Task.Token<br>    Catch:<br>      - ErrorEquals:<br>          - ScriptFailed<br>        Next: Fail<br>    ResultPath: $.Output<br>    Next: Success</pre><pre>  Fail:<br>    Type: Fail<br>    Cause: An error occured during script execution.<br>    Error: ScriptError</pre><pre>  Success:<br>    Type: Succeed<br>    InputPath: $.Output</pre><p>Specific errors (like “ScriptFailed”) can be triggered from script execution and handled on the StepFunction flow.</p><h3>Entrypoint and task execution</h3><p>The entrypoint script should exit for every error, this simplifies the StepFunction task execution.</p><pre>#!/bin/bash<br>set -e</pre><p>Using a “trap” it’s possible to catch every script’s exit and execute a specific bash function that checks the exit code. If the script exits with a code different than 0 the StateMachine’s task will fail:</p><pre>trap &#39;catch $? $2&#39; EXIT<br>catch() {<br>  if [ &quot;$1&quot; != &quot;0&quot; ]; then<br>    aws stepfunctions send-task-failure --error &quot;ScriptFailed&quot; --cause &quot;$1&quot; --task-token &quot;$TASK_TOKEN&quot;<br>  fi<br>}</pre><p>If the script reaches the end of the file without error the StateMachine’s task will continue execution:</p><pre>OUTPUT=&quot;{ \&quot;Example\&quot;: \&quot;Test\&quot; }&quot;<br>aws stepfunctions send-task-success --task-output &quot;$OUTPUT&quot; --task-token &quot;$TASK_TOKEN&quot;</pre><p>A JSON payload can be passed as a task execution result.</p><h3>Docker image build and deploy</h3><p>As a base image you can use for example the AWS CLI one so as to already have a large set of features available for communicating with the AWS APIs.</p><p>Let’s define a very simple Dockerfile that takes our script and add it as an entrypoint of the image:</p><pre>FROM public.ecr.aws/aws-cli/aws-cli<br><br>USER root<br><br>RUN yum install -y bash jq curl<br><br>RUN rm -rf /var/cache/apk/*<br><br>COPY entrypoint.sh /entrypoint.sh<br>RUN chmod +x /entrypoint.sh<br><br>ENTRYPOINT [ &quot;/entrypoint.sh&quot; ]<br><br>WORKDIR /tmp</pre><p>If we are using a Docker repository we will first have to log in to ECR:</p><pre>aws --profile &lt;your aws profile&gt; ecr get-login-password | docker login --username AWS --password-stdin &quot;&lt;account id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com&quot;</pre><p>Now build and deploy the Docker image:</p><pre>docker build -t &lt;account id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/my-repository:tag .<br>docker push &lt;account id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/my-repository:tag</pre><p>Now everything is ready to execute the stepfunction and check its execution.</p><p>For a concrete example I leave at the bottom of the article a repository with the execution of MySQL dump.</p><p><em>Credits: </em><a href="https://www.cloudcraft.co/"><em>Cloudcraft</em></a><em>.</em></p><p><em>Repository: </em><a href="https://github.com/bitbull-serverless/rds-mysql-dump/"><em>bitbull-serverless/rds-mysql-dump</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c59b0f81f541" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cognito password-less login]]></title>
            <link>https://daaru.medium.com/cognito-password-less-login-0fd33709308e?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fd33709308e</guid>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[passwordless]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 15:52:23 GMT</pubDate>
            <atom:updated>2025-06-06T15:52:23.657Z</atom:updated>
            <content:encoded><![CDATA[<p>To implement a password-less solution with Cognito until recently it was necessary to take care of sending the code and verifying it via Cognito triggers and using custom authentication.</p><p>Recently and I would say finally, Cognito <a href="https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-cognito-passwordless-authentication-low-friction-secure-logins/?nc1=h_ls">has added support natively</a> via some simple User Pool configuration.</p><h3>UserPool</h3><p>The default user pool configuration is “AllowedFirstAuthFactors”, this allows you to specify a new EMAIL_OTP value (or SMS_OTP) to activate the password-less flow via OTP.</p><pre>UserPool:<br>  Type: AWS::Cognito::UserPool<br>  Properties:<br>    UserPoolName: !Sub &quot;${Project}-${Environment}&quot;<br>    UserPoolTier: ESSENTIALS<br>    DeletionProtection: ACTIVE<br>    AutoVerifiedAttributes:<br>      - &quot;email&quot;<br>    UsernameAttributes:<br>      - &quot;email&quot;<br>    Schema:<br>      - Name: email<br>        AttributeDataType: String<br>        Mutable: true<br>        Required: true<br>    MfaConfiguration: &quot;OFF&quot;<br>    Policies:<br>      SignInPolicy:<br>        AllowedFirstAuthFactors:<br>          - PASSWORD<br>          - EMAIL_OTP<br>    AccountRecoverySetting:<br>      RecoveryMechanisms:<br>        - Name: &quot;verified_email&quot;<br>          Priority: 1<br>    EmailAuthenticationMessage: &quot;Your code is {####}&quot;<br>    EmailAuthenticationSubject: &quot;My Auth Server&quot;<br>    VerificationMessageTemplate:<br>      EmailMessage: &quot;Your verification code is {####}&quot;<br>      EmailSubject: &quot;Your verification code&quot;<br>      DefaultEmailOption: &quot;CONFIRM_WITH_CODE&quot;</pre><h3>Frontend implementation</h3><p>Install Amplify auth module, you don’t need the entire library</p><pre>npm install @aws-amplify/auth</pre><p>Import the auth module and configure it</p><pre>import { Auth } from &#39;@aws-amplify/auth&#39;<br><br>Auth.configure({<br>  region: &quot;eu-south-1&quot;,<br>  userPoolId: &quot;eu-south-1_xxxxxxxxxxx&quot;,<br>  userPoolWebClientId: &quot;xxxxxxxxxxxxxxxxxxxxxxxxx&quot;,<br>})</pre><p>Send the login request requesting an OTP:</p><pre>import { signIn} from &#39;aws-amplify/auth&#39;<br><br>await signIn({<br>  username: email.value,<br>  options: {<br>    authFlowType: &#39;USER_AUTH&#39;,<br>    preferredChallenge: &#39;EMAIL_OTP&#39;<br>  }<br>})</pre><p>Sending back to Cognito the OTP to finalize the login:</p><pre>import { confirmSignIn } from &#39;aws-amplify/auth&#39;<br><br>await confirmSignIn({<br>  challengeResponse: code.value<br>})</pre><p>And it’s done! The user is now logged in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fd33709308e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless MCP framework]]></title>
            <link>https://daaru.medium.com/serverless-mcp-framework-9705225ec4fa?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9705225ec4fa</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Sun, 04 May 2025 14:52:21 GMT</pubDate>
            <atom:updated>2025-05-04T21:58:20.345Z</atom:updated>
            <content:encoded><![CDATA[<p>A specific protocol for standardizing the way to serve context and functionality to LLMs has recently been published: the <a href="https://modelcontextprotocol.io/introduction">MCP</a> protocol. This protocol describes how to serve and implement resources, pre-configured prompts, and tools.</p><p>Convenient SDKs has then been published to implement servers and clients for many programming languages: Python, Java, C#, Kotlin and finally also Typescript (or used as pure Javascript in NodeJS). This piqued my curiosity and I started trying to implement it with AWS services, Serverless of course!</p><h3>SSE and the stream pain</h3><p>The MCP protocol is based on receiving and sending messages in JSON-RPC format via stream on the format, this is to transmit the response in real time and maintain a connection for new messages.</p><p>Unfortunately this is very complicated to implement with serverless services, API Gateway does not support the stream response but rather Lambda buffers the response before delivering it to the client. You can instead implement the <strong>stream response using Function URL</strong>, but you need to use some wrapper libraries for that like <a href="https://www.npmjs.com/package/aws-lambda-stream">aws-lambda-stream</a> in combination with another wrapper for Express.JS, which is what the SDK is based on.</p><pre>Resources:<br>  McpFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      FunctionName: !Sub &quot;${Environment}-${AppName}-mcp&quot;<br>      MemorySize: 512<br>      Timeout: 900            <br>      FunctionUrlConfig:<br>        InvokeMode: RESPONSE_STREAM<br>        AuthType: NONE<br>        Cors:<br>          AllowOrigins:<br>            - &quot;*&quot;<br>          AllowMethods:<br>            - GET<br>            - POST<br>          AllowHeaders:<br>            - Content-Type</pre><p>As if this were not enough, when a client opens such a connection it completely occupies the execution of the Lambda function, creating a disproportionate number of concurrent executions.</p><p>The peculiarity of this stream is also that it is initialized as a request on a path /sse then wait for server-to-client messages and another request on /messages to send messages client-to-server. This becomes even more complicated with different executions of functions not being able to share memory it is necessary to use an external system to store the sessions (a DynamoDB table for example).</p><h3>The HTTP Streamable</h3><p>The MCP protocol has recently (<a href="https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http">2025-03-26</a>) been updated with HTTP Streamable support, even on a single path /mcp. This certainly simplifies the previous implementation, even if the stream is still very complicated to implement.</p><p>However, there is a very nice setting in the transport initialization, the <strong>enableJsonResponse</strong>:</p><pre>const transport = new StreamableHTTPServerTransport({<br>  sessionIdGenerator: undefined,<br>  enableJsonResponse: true<br>})</pre><p>This setting allows you to set the immediate response to the client without using a response stream!</p><h3>Serverless implementations</h3><p>We can now simply use API Gateway to serve the MCP server:</p><pre>Resources:<br>  RestApi:<br>    Type: AWS::Serverless::Api<br>    Properties:<br>      Name: !Sub &quot;${Project}-${Environment}-mcp&quot;<br>      StageName: !Ref Environment<br>  <br>  McpFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      FunctionName: !Sub &quot;${Project}-${Environment}-mcp&quot;<br>      Handler: index.handler<br>      MemorySize: 512<br>      Timeout: 90<br>      Events:<br>        ApiEvent:<br>          Type: Api<br>          Properties:<br>            Path: /mcp<br>            Method: ANY<br>            RestApiId: !Ref RestApi</pre><p>Just a small wrapper is needed to allow using Espress.JS inside a Lambda function, this can be done with <a href="https://www.npmjs.com/package/@codegenie/serverless-express">@codegenie/serverless-express</a> module</p><pre>import app from &#39;./app.mjs&#39;<br>import serverlessExpress from &#39;@codegenie/serverless-express&#39;<br>export const handler = serverlessExpress({ app })</pre><p>You can now complete the configuration and initialization of the MCP server as per the SDK documentation.</p><h3>Deploy and test</h3><p>As with other solutions, once the code has been put together and the two resources of API Gateway and Lambda have been described, the deployment is ready.</p><p>In order to test the MCP server we need some tools, both of these mentioned have been updated recently to support HTTP Streamable transport, when doing these tests it is good to verify this support otherwise most clients will attempt a GET request trying to use the SSE transport.</p><h4>MCP Inspector</h4><p>The <a href="https://modelcontextprotocol.io/docs/tools/inspector">MCP Inspector</a> is a graphical tool that allows you to test MCP server response and trigger tools executions</p><pre>npx @modelcontextprotocol/inspector</pre><p>Configure the inspector with:</p><ul><li>Transport Type: Streamable HTTP</li><li>URL: http://localhost:3000/mcp</li></ul><p>Connect to the MCP server with the &quot;Connect&quot; button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j46qAZfRO8P5frRYzxtMKQ.png" /><figcaption>MCP Inspector</figcaption></figure><h4>Claude Desktop</h4><p>The Claude Desktop can be configured to use MCP server using <a href="https://www.npmjs.com/package/mcp-remote">mcp-remote</a> to proxy HTTP to STDIO:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;example&quot;: {<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [<br>        &quot;-y&quot;,<br>        &quot;mcp-remote&quot;,<br>        &quot;https://xxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/dev/mcp&quot;,<br>        &quot;--transport&quot;,<br>        &quot;http-only&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>Once restarted you will be able to see the tools appear in the configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*bQy-7ZM8ulX8FHzJ_VdwEw.png" /><figcaption>Claude Desktop</figcaption></figure><h3>Make solution reusable</h3><p>I have already experimented in <a href="https://medium.com/@daaru/telegram-bot-powered-by-amazon-bedrock-5301ce537210">another solution</a> the connection of Lambda functions via SSM parameters to implement the tools of a solution with LLM, I’d like to reuse it to decouple the server instance and tools implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYJ0UFxmu9GGfFQ19Dp8qA.png" /><figcaption>Infrastructure schema</figcaption></figure><p>In order to declare resources, prompts and tools. I create SSM parameters and Lambda functions in a different template, every SSM parameters begin with a prefix /&lt;project name&gt;/&lt;environment name&gt;/, for example /mcp/dev/tools/echo, the MCP server load all parameters when a request is made and declare them using the MCP SDK.</p><pre>const parameters = await listParameters()<br><br>const resources = await listResources(parameters)<br>for (const resource of resources) {<br> server.resource(<br>  resource.name,<br>  resource.uri,<br>  async (uri) =&gt; ({<br>   contents: [{<br>    uri: uri.href,<br>    text: resource.content<br>   }]<br>  })<br> )<br>}<br><br>const prompts = await listPrompts(parameters)<br>for (const prompt of prompts) {<br> server.prompt(<br>  prompt.name,<br>  prompt.description,<br>  prompt.inputSchema ? jsonSchemaObjectToZodRawShape(prompt.inputSchema) : {},<br>  async (input) =&gt; ({<br>   messages: [{<br>    role: &#39;user&#39;,<br>    content: {<br>     type: &#39;text&#39;,<br>     text: buildPrompt(prompt.content, input)<br>    }<br>   }]<br>  })<br> )<br>}<br><br>const tools = await listTools(parameters)<br>for (const tool of tools) {<br> server.tool(<br>  tool.name,<br>  tool.description,<br>  tool.inputSchema ? jsonSchemaObjectToZodRawShape(tool.inputSchema) : {},<br>  async (input) =&gt; await invokeTool(tool.name, input, context)<br> )<br>}</pre><p>The MCP SDK uses <a href="https://www.npmjs.com/package/zod">zod</a> for input schema declaration, instead wanting to use the declaration in JSON schema I used the module <a href="https://www.npmjs.com/package/zod-from-json-schema">zod-from-json-schema</a>:</p><pre>import { jsonSchemaObjectToZodRawShape } from &#39;zod-from-json-schema&#39;<br><br>server.tool(<br>  tool.inputSchema ? jsonSchemaObjectToZodRawShape(tool.inputSchema) : {}<br>)</pre><h4>Resources</h4><p>Being a simple GET of information I’ve just declared them as follows:</p><pre>ExampleResourceParameter:<br>  Type: AWS::SSM::Parameter<br>  Properties:<br>    Name: !Sub &quot;/${Project}/${Environment}/resources/example&quot;<br>    Type: String<br>    Value: |<br>      {<br>        &quot;name&quot;: &quot;example&quot;,<br>        &quot;uri&quot;: &quot;config://example&quot;,<br>        &quot;content&quot;: &quot;Just an example resource&quot;<br>      }</pre><p>Simple as that, the content is returned as the resource’s text.</p><pre>server.resource(<br> resource.name,<br> resource.uri,<br> async (uri) =&gt; ({<br>  contents: [{<br>   uri: uri.href,<br>   text: resource.content<br>  }]<br> })<br>)</pre><p>Testing with MCP Inspector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-ue7lhfesYSydeE4sZfuw.png" /><figcaption>MCP Inspector test resource</figcaption></figure><h4>Prompts</h4><p>A slightly more dynamic approach for the prompts instead, wanting to interpolate the inputs within the response to the client I first tried to use <a href="https://handlebarsjs.com/">handlebars</a>, however I encountered a limitation of SSM on the content of the value: <a href="https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_PutParameter.html#API_PutParameter_RequestSyntax">you cannot use double curly brackets</a>.</p><p>I then used <a href="https://ejs.co/">ejs</a> since it has a different (and configurable) syntax:</p><pre>EchoPromptParameter:<br>  Type: AWS::SSM::Parameter<br>  Properties:<br>    Name: !Sub &quot;/${Project}/${Environment}/prompts/echo&quot;<br>    Type: String<br>    Value: |<br>      {<br>        &quot;name&quot;: &quot;echo&quot;,<br>        &quot;description&quot;: &quot;Execute the example tool&quot;,<br>        &quot;inputSchema&quot;: {<br>          &quot;json&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>              &quot;message&quot;: {<br>                &quot;type&quot;: &quot;string&quot;<br>              }<br>            },<br>            &quot;required&quot;: [&quot;message&quot;]<br>          }<br>        },<br>        &quot;content&quot;: &quot;Execute the tool &#39;echo&#39; with the message &#39;&lt;%= message %&gt;&#39;&quot;<br>      }</pre><p>This way the input parameters are interpolated creating a dynamic prompt</p><pre>import ejs from &#39;ejs&#39;<br><br>server.prompt(<br> prompt.name,<br> prompt.description,<br> prompt.inputSchema ? jsonSchemaObjectToZodRawShape(prompt.inputSchema) : {},<br> async (input) =&gt; ({<br>  messages: [{<br>   role: &#39;user&#39;,<br>   content: {<br>    type: &#39;text&#39;,<br>    text: ejs.render(prompt.content, input)<br>   }<br>  }]<br> })<br>)</pre><p>Testing with MCP Inspector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-ue7lhfesYSydeE4sZfuw.png" /><figcaption>MCP Inspector test prompt</figcaption></figure><h4>Tools</h4><p>Since the tools are more complex, they require greater flexibility in processing the response, perhaps by contacting external APIs, databases, files and other resources.</p><pre>EchoToolFunction:<br>  Type: AWS::Serverless::Function<br>  Properties:<br>    FunctionName: !Sub &quot;${Project}-${Environment}-tools-echo&quot;<br>    Handler: index.handler<br>    InlineCode: |<br>      exports.handler = async ({ toolUseId, name, input }, context) =&gt; {<br>        console.log(JSON.stringify({ input, context }, null, 2))<br>        return {<br>          name,<br>          toolUseId,<br>          status: &#39;success&#39;,<br>          content: [{<br>            text: input.message<br>          }]<br>        }<br>      }<br><br>EchoToolParameter:<br>  Type: AWS::SSM::Parameter<br>  Properties:<br>    Name: !Sub &quot;/${Project}/${Environment}/tools/echo&quot;<br>    Type: String<br>    Value: |<br>      {<br>        &quot;name&quot;: &quot;echo&quot;,<br>        &quot;description&quot;: &quot;Print the message provided in input&quot;,<br>        &quot;inputSchema&quot;: {<br>          &quot;json&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>              &quot;message&quot;: {<br>                &quot;type&quot;: &quot;string&quot;<br>              }<br>            },<br>            &quot;required&quot;: [&quot;message&quot;]<br>          }<br>        }<br>      }</pre><p>The name of the functions must respect a certain nomenclature in order to connect them to the tool, in my case I use as a prefix &lt;project name&gt;-&lt;environment name&gt;-tools-&lt;tool name&gt;.</p><p>Additionally to the input to the Lambda function, the ClientContext is also passed with endpoint query parameters (for example using <a href="http://localhost:3000/mcp?param=value">http://localhost:3000/mcp?param=value</a>), client headers or the token can be sent to the execution of the Lambda function if authentication is enabled:</p><pre>{<br>  &quot;input&quot;: {<br>    &quot;message&quot;: &quot;test&quot;<br>  },<br>  &quot;context&quot;: {<br>    &quot;clientContext&quot;: {<br>      &quot;query&quot;: {<br>        &quot;param&quot;: &quot;value&quot;<br>      },<br>      &quot;userAgent&quot;: &quot;node&quot;,<br>      &quot;token&quot;: &quot;xxxxxxxxxxxxxxxx&quot;<br>    }<br>  }<br>}</pre><p>Testing with MCP Inspector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ES1rSOW4RmRDfqgECLowWA.png" /><figcaption>MCP Inspector test tool</figcaption></figure><p><em>Credits: </em><a href="https://www.cloudcraft.co/"><em>Cloudcraft</em></a><em>.</em></p><p><em>Repository: </em><a href="https://github.com/daaru00/aws-serverless-mcp"><em>daaru00/aws-serverless-mcp</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9705225ec4fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue3 composable poller]]></title>
            <link>https://daaru.medium.com/vue3-composable-poller-3e2007e25a4b?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e2007e25a4b</guid>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 16:21:02 GMT</pubDate>
            <atom:updated>2024-04-26T16:21:02.458Z</atom:updated>
            <content:encoded><![CDATA[<p>I found myself in the situation of having to refresh frontend data every few seconds to make people wait for the end of an asynchronous remote procedure. The optimal solution for this type of problem is certainly a WebSocket, this with API Gateway is done by configuring its specific functionality, it would not be possible to forcibly manage it from within a Lambda function, it could not remain active for more than 15 minutes (and it would unnecessarily expensive).</p><p>Wanting to use a simple polling solution, an HTTP request sent every few seconds, I created a composable function to be able to reuse this functionality in the application:</p><pre>export default function (fn: Function, seconds: number = 5) {<br>  let timer: NodeJS.Timeout|undefined<br>  let counter = 0<br>  const config = useAppConfig()<br><br>  async function tick() {<br>    counter++<br>    await Promise.resolve(fn(counter))<br>  }<br><br>  async function start() {<br>    if (timer) {<br>      stop()<br>    }<br>    if (!config.polling) {<br>      return<br>    }<br>    counter = 0<br>    await tick()<br>    timer = setInterval(() =&gt; tick(), seconds * 1000)<br>  }<br><br>  function stop() {<br>    if (!timer) {<br>      return<br>    }<br>    clearInterval(timer)<br>    timer = undefined<br>  }<br><br>  return {<br>    start,<br>    tick,<br>    stop,<br>  }<br>}</pre><p>I didn’t just need to start the polling and that’s it, I also needed to control when it was started or stopped depending of the situation, for example to mount and unmount the component:</p><pre>&lt;script setup&gt;<br>const api = useApi()<br>const processes = ref([])<br><br>const poller = usePoller(async () =&gt; {<br>  processes.value = await api.listProcesses()<br>}, 15)<br><br>onMounted(() =&gt; poller.start())<br>onUnmounted(() =&gt; poller.stop())<br>&lt;/script&gt;</pre><p>In some cases it was not necessary to start the polling when the component was mounted, but at least an initial data recovery was necessary. To do this I used a “tick” function that forces the poller to run one round, whether it is running or not:</p><pre>&lt;script setup&gt;<br>const api = useApi()<br>const processes = ref([])<br><br>const poller = usePoller(async () =&gt; {<br>  processes.value = await api.listProcesses()<br>}, 15)<br><br>onMounted(() =&gt; poller.tick()) // &lt;---- <br>onUnmounted(() =&gt; poller.stop())<br><br>const startPoller = async () =&gt; {<br>  await poller.start()<br>}<br>const stopPoller = async () =&gt; {<br>  await poller.stop()<br>}<br>&lt;/script&gt;</pre><p>If the poller is already running and the data changes due to a modification of the frontend itself, it would be a good idea to immediately refresh the data instead of waiting for the next poller execution.</p><p>To do this I linked some application events to the execution of the “tick” function:</p><pre>&lt;process-list :processes=&quot;processes&quot; @stopped=&quot;poller.tick()&quot; @started=&quot;poller.tick()&quot; /&gt;</pre><p>This solution can have many approaches, not to be abused so as not to waste HTTP request executions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e2007e25a4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CloudFront invalidation queue]]></title>
            <link>https://daaru.medium.com/cloudfront-invalidation-queue-91dbc14c7234?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/91dbc14c7234</guid>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 19:32:01 GMT</pubDate>
            <atom:updated>2024-04-10T19:32:01.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9BuuUpZdL8-yWb9IkNuUg.png" /><figcaption>Infrastructure schema</figcaption></figure><p>When a CloudFront distribution handles a lot of cached content invalidating paths can cost computation.</p><p>When content changes, its exposed path needs to be invalidated. CloudFormation invalidations are billed for requested path, so lot of path invalidations cost lot of money.</p><p>A more elegant solution could be required instead of just invalidating /* at every content change.</p><h3>SQS queue</h3><p>Being an operations queue the first service that comes to mind is SQS.</p><p>Using an SQS queue the message can hidden for a certain amount of time, sadly, only for standard, can be only up to 15 minutes. This might even be enough, the problem arises when you try to limit the number of parallel executions of the Lambda function.</p><p>using standard queues it is possible to limit the scaling of the lambda function, as described in the <a href="https://aws.amazon.com/it/blogs/compute/introducing-maximum-concurrency-of-aws-lambda-functions-when-using-amazon-sqs-as-an-event-source/">AWS blog article</a> the minimum value that can be set is 2. By executing two lambda functions at the same time the invalidation queue is divided in half and two invalidations will always be created with possible duplication, not being able to clean the complete list but only having a view of half at a time.</p><p>For content that changes very often with possible applications it is not the right solution, otherwise it may already be a good solution</p><h3>Scheduled Lambda</h3><p>Another solution could be to create a custom queue implementation, with a DynamoDB table to store the queue and a scheduled Lambda function that executes queued invalidations.</p><p>For content that doesn’t change that often it could result in wasted executions, otherwise it is a very simple solution that already solves some problems.</p><h3>StepFunction wait step</h3><p>When an invalidation is requested it will be related to the current “time batch”. This is calculated by dividing the unix timestamp by the requested batch time, each time the code is executed the same “sequence token” will be returned for the entire batch period:</p><pre>const sequence = Math.floor(currentTimestamp / BATCH_WINDOW_SECONDS)</pre><p>Invalidation request will be store into a DynamoDB table using sequence and invalidation path and item key. This will prevent duplicated path inside the same batch:</p><pre>await dynamo.transactWrite({<br>  TransactItems: paths.map(path =&gt; ({<br>   Put: {<br>    TableName: TABLE_QUEUE_NAME,<br>    Item: {<br>     &#39;sequence&#39;: sequence,<br>     &#39;path&#39;: path,<br>     &#39;ttl&#39;: currentTimestamp + BATCH_TTL_SECONDS<br>    }<br>   }<br>  }))<br> }).promise()</pre><p>Also adding a TTL specification to keep the table clean without too old invalidation history. The expiration time must be longer than the retry time so that the batch can be retrieved to retry the invalidation without the records disappearing</p><p>A StepFunction will be executed using the time sequence token as execution name, this in order to prevents a temporal batch from being executed twice.</p><pre>Comment: Invalidate CloudFront distribution<br>StartAt: Wait<br>States:<br>  Wait:<br>    Type: Wait<br>    SecondsPath: $.wait<br>    Next: Execute Consumer<br>  <br>  Execute Consumer:<br>    Type: Task<br>    Resource: &quot;arn:aws:states:::lambda:invoke&quot;<br>    Parameters:<br>      FunctionName: &quot;${ConsumerFunctionName}&quot;<br>      Payload:<br>        sequence.$: $.sequence<br>    OutputPath: $.Payload<br>    Retry:<br>      - ErrorEquals:<br>          - States.TaskFailed<br>        IntervalSeconds: 60<br>        MaxAttempts: 3<br>        BackoffRate: 2.0<br>    End: true</pre><p>The StepFunction use a Wait step to pause execution until the temporal batch end; during this period the requested invalidations are collected in the DynamoDB table.</p><p>At the end of the temporal batch, a Lambda function is executed which creates an invalidation on CloudFront using the paths collected in the Dynamodb table up to this moment.</p><p>I find this solution is much better suited to content that I change often or almost never and it is possible to manage the entire invalidation list by filtering out any duplications.</p><p><em>Repository: </em><a href="https://github.com/bitbull-serverless/cloudfront-invalidation-queue"><em>bitbull-serverless/cloudfront-invalidation-queue</em></a></p><p><em>Credits: </em><a href="https://www.cloudcraft.co/"><em>Cloudcraft</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91dbc14c7234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocked API with API Gateway]]></title>
            <link>https://daaru.medium.com/mocked-api-with-api-gateway-8aa470ab7ff6?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aa470ab7ff6</guid>
            <category><![CDATA[http-api]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 21:27:09 GMT</pubDate>
            <atom:updated>2024-03-20T21:27:09.447Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently had to test a serverless solution whose main job is to contact an HTTP API of a service exposed by the client. The main problem was the absence of a test environment with resources and data separate from the production one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHKgV8xoITN9E_1n7sYhZw.png" /><figcaption>Infrastructure schema</figcaption></figure><h4>Application level mocking</h4><p>In order to perform a test, you can act at the application level by not making outgoing calls, but pretending that the API was called and that a certain fixed data item responded. Essentially this can be <a href="https://medium.com/@daaru/testing-lambda-functions-with-vitest-fc713caa975d">implemented with a test suite</a> mocking the client that makes the HTTP calls to the API.</p><p>With this approach I can test the application layer, but I’m not really using the HTTP client, this means that the reliability of the test is limited on the type of data sent, not on timing or infrastructure setup.</p><h4>Mocked API</h4><p>Another useful approach to testing was to create a clone API endpoint that fixedly responds to requests. There are some online services that allow you to record incoming calls and describe the responses, but I wanted to replicate this kind of service with AWS.</p><p>The simplest thing that comes to mind is a Lambda function, called from API Gateway, with a fixed response in the code:</p><pre>Resources:  <br>  MockedApi:<br>    Type: AWS::Serverless::Api<br>    Properties:<br>      Name: !Ref AWS::StackName<br>      StageName: api<br><br>  MockedResponseFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      FunctionName: !Sub &quot;${AWS::StackName}-response&quot;<br>      Runtime: nodejs16.x<br>      Handler: index.handler<br>      InlineCode: !Sub |<br>        exports.handler = async (event) =&gt; ({<br>          statusCode: 200,<br>          body: JSON.stringify({<br>            &quot;id&quot;: &quot;example&quot;,<br>            &quot;sku&quot;: &quot;example&quot;,<br>            &quot;name&quot;: &quot;Example&quot;,<br>            &quot;description&quot;: &quot;This is an example&quot;,<br>            &quot;price&quot;: 15.49<br>          })<br>        })<br>      Events:<br>        HttpRequest:<br>          Type: Api<br>          Properties:<br>            RestApiId:<br>              Ref: MockedApi<br>            Method: GET<br>            Path: /</pre><p>I didn’t want to add running code so as not to have to mess with the cost of Lambda and any limitations in the stress tests.</p><p>API Gateway integrations with AWS services, including Lambda but also DynamoDB and EventBridge, are described through the &quot;API Gateway Integration Response&quot;; one of these possible integrations is called “mock”. This type of configuration can be described by declaring API methods and resources, very verbose in my opinion, or via the DefinitionBody passing a Swagger definition:</p><pre>Resources:<br>  MockedApi:<br>    Type: AWS::Serverless::Api<br>    Properties:<br>      Name: !Ref AWS::StackName<br>      StageName: api<br>      DefinitionBody:<br>        swagger: 2.0<br>        info:<br>          title: &quot;Mocked API&quot;<br>        schemes:<br>          - &quot;https&quot;<br>        paths:<br>          /:<br>            get:<br>              produces:<br>                - &quot;application/json&quot;<br>              responses:<br>                &quot;200&quot;:<br>                  description: &quot;OK&quot;<br>              x-amazon-apigateway-integration:<br>                type: &quot;mock&quot;<br>                requestTemplates:<br>                  application/json: |<br>                    {<br>                      &quot;statusCode&quot;: 200<br>                    }<br>                responses:<br>                  default:<br>                    statusCode: &quot;200&quot;<br>                    responseTemplates:<br>                      application/json: |<br>                        {<br>                          &quot;id&quot;: &quot;example&quot;,<br>                          &quot;sku&quot;: &quot;example&quot;,<br>                          &quot;name&quot;: &quot;Example&quot;,<br>                          &quot;description&quot;: &quot;This is an example&quot;,<br>                          &quot;price&quot;: 15.49<br>                        }</pre><p>Obliviously also POST, PUT and DELETE requests can be used!</p><p>By creating a stack from this template an endpoint will be created which, if contacted on the declared method, will respond with a simple 200:</p><pre>curl -X GET https://xxxxxxxx.execute-api.eu-west-1.amazonaws.com/api/<br>{<br>  &quot;id&quot;: &quot;example&quot;,<br>  &quot;sku&quot;: &quot;example&quot;,<br>  &quot;name&quot;: &quot;Example&quot;,<br>  &quot;description&quot;: &quot;This is an example&quot;,<br>  &quot;price&quot;: 15.49<br>}</pre><p>This allows you to test with the overhead of an HTTP call with associated network consumption, memory and response times.</p><h3>Conditional responses</h3><p>API gateway integration <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-mock-integration.html">template</a> is not so flexible, allow you to create custom responses based on request parameters:</p><pre>paths:<br>  /:<br>    get:<br>      produces:<br>        - &quot;application/json&quot;<br>        - &quot;text/plain&quot;<br>      responses:<br>        &quot;200&quot;:<br>          description: &quot;OK&quot;<br>        &quot;404&quot;:<br>          description: &quot;Not Found&quot;<br>      x-amazon-apigateway-integration:<br>        type: &quot;mock&quot;<br>        requestTemplates:<br>          application/json: |<br>            {<br>              #if( $input.params(&#39;error&#39;) == &quot;yes&quot; )<br>                &quot;statusCode&quot;: 404              <br>              #else<br>                &quot;statusCode&quot;: 200<br>              #end<br>            }<br>        responses:<br>          &quot;404&quot;:<br>            statusCode: &quot;404&quot;<br>            responseTemplates:<br>              text/plain: |<br>                &#39;Not Found&#39;<br>          default:<br>            statusCode: &quot;200&quot;<br>            responseTemplates:<br>              application/json: |<br>                {<br>                  &quot;id&quot;: &quot;example&quot;,<br>                  &quot;sku&quot;: &quot;example&quot;,<br>                  &quot;name&quot;: &quot;Example&quot;,<br>                  &quot;description&quot;: &quot;This is an example&quot;,<br>                  &quot;price&quot;: 15.49<br>                }</pre><p>In this example adding a query parameter will cause the request to fail:</p><pre>curl -i -X GET https://xxxxxxxxx.execute-api.eu-west-1.amazonaws.com/api/?error=yes<br>HTTP/2 404 <br>content-type: application/json<br>content-length: 12<br>...<br><br>&#39;Not Found&#39;</pre><p>If you need greater flexibility in describing the response you can always fall back to the solution of a Lambda function.</p><h3>Method Throttling</h3><p>However, these solutions do not allow you to test behaviors such as call throttling. This limitation in the HTTP API is more or less declared, if the service is enterprise grade there will probably be a limitation of calls per second per user (API key), if it is a more “domestic” service the limitation could be due to the hardware limit. Even simply an AWS service can have limits, imposed by the platform, some of which are modifiable and others not. More simply, the limitation may be due to the project budget, an API with no limitations would imply having infinite resources and money.</p><p>API gateway has a very useful throttling configuration that can be set by a couple of simple API endpoint resource parameters:</p><pre>Resources:  <br>  MockedApi:<br>    Type: AWS::Serverless::Api<br>    Properties:<br>      Name: !Ref AWS::StackName<br>      StageName: api<br>      MethodSettings:<br>        - ResourcePath: &quot;/*&quot;<br>          HttpMethod: &quot;*&quot;<br>          ThrottlingRateLimit: 10<br>          ThrottlingBurstLimit: 1<br>      DefinitionBody:<br>        # ...</pre><p>These two configurations regulate the limit for the overall number of requests in one second (ThrottlingRateLimit) and the maximum number of “concurrent” requests, within 100ms (ThrottlingBurstLimit). So giving a ThrottlingRateLimit of 10 and ThrottlingBurstLimit mean that API Gateway will handle 10 requests per seconds but just one at time.</p><p>As a benchmark tool I used <a href="https://github.com/mcollina/autocannon">autocannon</a>, very simple and immediate to use. I used some of its parameters to control the number of parallel connections (-c) and the number of requests per connection (-r) to describe some cases. For example setting the throttling configuration to RateLimit 1 and BurstLimit 1, I can stay under the limit with:</p><pre>autocannon -c 1 -r 1 -d 5 https://xxxxxxxx.execute-api.eu-west-1.amazonaws.com/api/<br>...<br>6 requests in 5.03s, 2.7 kB read</pre><p>doubling the number of requests per connection causes requests to begin to fail:</p><pre>autocannon -c 1 -r 2 -d 5 https://xxxxxxxx.execute-api.eu-west-1.amazonaws.com/api/<br>...<br>5 2xx responses, 5 non 2xx responses<br>12 requests in 5.04s, 5.07 kB read</pre><p>However too high! It should only be 5 of those in 200 and all the others in 429, there is something wrong. This happens because API Gateway use an algorithm called <a href="https://it.wikipedia.org/wiki/Token_bucket">“token bucket”</a> to evaluate whether a request should be blocked or not.</p><p>In short, the token bucket algorithm works like this:</p><ul><li>Every seconds the system (virtually) adds tokens to the bucket in the amount indicated by the <strong>RateLimit</strong> value.</li><li>Every request made to the endpoint method remove a token from that bucket, when the bucket empties the requests are throttled.</li><li>The bucket can only contain a certain number of tokens, indicated by the value of <strong>BurstLimit</strong>, if the bucket is full no more tokens are added.</li></ul><h3>API Usage Plan</h3><p>The same throttling configuration can be applied using an API Usage Plan with a related API key, with the same results as above.</p><pre>Resources:  <br>  MockedApi:<br>    Type: AWS::Serverless::Api<br>    Properties:<br>      Name: !Ref AWS::StackName<br>      StageName: api<br>      Auth:<br>        ApiKeyRequired: true<br>        UsagePlan:<br>          CreateUsagePlan: SHARED<br>          Description: Throttled API key<br>          Throttle:<br>            BurstLimit: 10<br>            RateLimit: 1</pre><p>In conclusion, however, by remaining below the limit no requests are blocked, rising above the limit the number of blocked requests is not reliable.</p><h3>Metrics and alarms</h3><p>An interesting addition is the monitoring of any errors due to excessive competition via API Gateway metrics. If the mocked API solution wants to be used as a target during end to end tests, it may be useful to add alarms, perhaps with notifications to alert the development team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQ8E106VCW6VWAVvLbX5ZQ.png" /><figcaption>CloudWatch metrics for ApiGateway</figcaption></figure><p>The metrics to keep an eye on is have namespace as “AWS/ApiGateway”, as ApiName your stack name.</p><p><em>Gist: </em><a href="https://gist.github.com/daaru00/423725d838acdc117413df95497543e7"><em>daaru00/423725d838acdc117413df95497543e7</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aa470ab7ff6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encrypted server-side session cookie with AWS Lambda]]></title>
            <link>https://daaru.medium.com/encrypted-server-side-session-cookie-with-aws-lambda-2be227fd3cff?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2be227fd3cff</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[cookies]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 16:47:34 GMT</pubDate>
            <atom:updated>2024-02-26T16:47:34.137Z</atom:updated>
            <content:encoded><![CDATA[<p>I ran into a problem while managing the <a href="https://oauth.net/2/">OAuth2 flow</a>, at one point I needed to save some information to persist between one redirect and another. This is commonly implemented with a session: the client receives a session identifier (generated by the server) and reuses it during all calls (using a cookie), the server uses the identifier to retrieve session data persisted in a database.</p><p>Wanting to keep the solution as streamlined as possible, I opted for a solution without a database: directly saving the serialized and encrypted session information in a cookie accessible only by the server. In this way the client does not just communicate an identifier, but rather all the data is already within the request (serialized in the cookie) and there is no need to retrieve it elsewhere. The client will not be able to manipulate the cookie as it is encrypted.</p><h3>Request and response headers</h3><h4>Send cookie to client</h4><p>To be able to send a cookie to the client it is necessary to specify the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie">Set-Cookie</a> header in the response to the client:</p><pre>Set-Cookie: &lt;cookie-name&gt;=&lt;cookie-value&gt;</pre><p>The first part of the value indicates the name and value that the cookie must take on.</p><p>Some parameters are added to the bottom of the string, separated by semicolons, to manage their behavior. For example, to make the cookie readable only by the server server, add “HttpOnly”, to send it only in HTTPS we add “Secure” and so on.</p><pre>Set-Cookie: session=&lt;cookie-value&gt;; HttpOnly; Secure</pre><p>Since the value is a string it is possible to serialize a value inside it:</p><pre>Set-Cookie: session={&quot;test&quot;: &quot;abc&quot;}; HttpOnly; Secure</pre><p>Obviously we cannot insert sensitive data in this way, they would be readable in plain text from the response header and modifiable at will when sending a subsequent request. We must therefore encrypt the string so that only the server can read or write it:</p><pre>Set-Cookie: session=f4b860ed2e5d0cd80f9ce97; HttpOnly; Secure</pre><p>In this way the client cannot do anything other than resend the string as it received it, without knowing its de-serialized content.</p><h4>Read sent cookie from client</h4><p>Once the client receives this header in response, it will save the cookie in the browser and resend it in future calls within the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie">Cookie</a> header:</p><pre>Cookie: &lt;cookie-name&gt;=&lt;cookie-value&gt;</pre><p>Multiple cookies can be sent by the client by separating the values with semicolons:</p><pre>Cookie: name=value; session=f4b860ed2e5d0cd80f9ce97; name3=value3</pre><p>It is therefore necessary to process the header in order to extract the value corresponding to the desired cookie.</p><h4>Remove cookie</h4><p>There are no directives via response headers that can ask the customer to delete a specific cookie. It is possible instead to use the Max-Age parameter to set an expiration of 1 second, as soon as the response is received:</p><pre>Cookie: session=none; Max-Age=1</pre><p>The client browser deletes it as quickly as possible and does not resend it in the next requests.</p><h3>AWS Lambda code</h3><h4>Create and send session to client</h4><p>A Lambda function invoked by API Gateway to evaluate the response headers must return an object with the “headers” property:</p><pre>/**<br> * Lambda handler<br> * @param {object} event<br> */<br>export async function handler(event) {<br>  const setCookieHeader = &#39;&#39;<br><br>  return {<br>    statusCode: 200,<br>    headers: {<br>       &#39;Set-Cookie&#39;: setCookieHeader<br>    }<br>  }<br>}</pre><p>To save session information securely we will therefore serialize and then encrypt the session object:</p><pre>/**<br> * Lambda handler<br> * @param {object} event<br> */<br>export async function handler(event) {<br>  const session = {<br>    test: &#39;abc&#39;<br>  }<br><br>  const encrypted = encrypt(JSON.stringify(session))<br>  const setCookieHeader = `session=${encrypted}; HttpOnly; Secure`<br><br>  return {<br>    statusCode: 200,<br>    headers: {<br>       &#39;Set-Cookie&#39;: setCookieHeader<br>    }<br>  }<br>}</pre><h4>Read session from request cookies</h4><p>A Lambda function invoked by API Gateway will contain the request headers within the event object. Since the value is a series of cookies separated by semicolons, they must be processed before being correctly read:</p><pre>/**<br> * Lambda handler<br> * @param {object} event<br> */<br>export async function handler(event) {<br>  const cookieHeader = event.headers[&#39;Cookie&#39;] || &#39;&#39;<br>  <br>  const cookies = cookieHeader.split(&#39;;&#39;).map(v =&gt; v.trim()).reduce((acc, cookie) =&gt; {<br>    const [key, value] = cookie.split(&#39;=&#39;)<br>    acc[key] = value<br>    return acc<br>   }, {})<br><br>  console.log(cookies)<br><br>  return {<br>    statusCode: 200<br>  }<br>}</pre><p>In this way we can control and access the value of the individual cookie:</p><pre>{<br>  &quot;name&quot;: &quot;value&quot;,<br>  &quot;session&quot;: &quot;f4b860ed2e5d0cd80f9ce97&quot;,<br>  &quot;name3&quot;: &quot;value3&quot;<br>}</pre><p>If the session cookie is present, once decrypted, it will be possible to de-serialize it and access it:</p><pre>/**<br> * Lambda handler<br> * @param {object} event<br> */<br>export async function handler(event) {<br>  const cookieHeader = event.headers[&#39;Cookie&#39;] || &#39;&#39;<br>  <br>  const cookies = cookieHeader.split(&#39;;&#39;).map(v =&gt; v.trim()).reduce((acc, cookie) =&gt; {<br>    const [key, value] = cookie.split(&#39;=&#39;)<br>    acc[key] = value<br>    return acc<br>   }, {})<br><br>  let session = null<br>  if (cookies[&#39;session&#39;]) {<br>    const decrypted = decrypt(cookies[&#39;session&#39;], &#39;secret&#39;)<br>    session = JSON.parse(decrypted)<br>  }<br><br>  console.log(session)<br><br>  return {<br>    statusCode: 200<br>  }<br>}</pre><h4>Delete session</h4><p>To delete the session we simply send an empty value with an expiration of one second:</p><pre>/**<br> * Lambda handler<br> * @param {object} event<br> */<br>export async function handler(event) {<br>  return {<br>    statusCode: 200,<br>    headers: {<br>       &#39;Set-Cookie&#39;: &#39;session=none; Max-Age=1&#39;<br>    }<br>  }<br>}</pre><h3>Security consideration</h3><p>To make this system as secure as possible it is necessary to use a suitable encryption algorithm (AES 256 for example). However, it is not advisable to enter sensitive information such as API keys or passwords.</p><p>Deleting the session is just an indication to the browser to delete the cookie, it does not guarantee that it will not be reused. This problem is similar to a JWT token, once generated and sent to the client it is only possible to check its expiration but not withdraw it.</p><p>I recommend inserting an expiration date into the serialized session data and checking it accordingly before considering the session valid:</p><pre>const session = {<br>  test: &#39;abc&#39;,<br>  expires: new Date(Date.now() + (1000 * 60 * 60 * 24)) // 1 day from now<br>}</pre><p><em>Gist: </em><a href="https://gist.github.com/daaru00/faef5b3b243a470c2eab15a4e3deff9d"><em>daaru00/faef5b3b243a470c2eab15a4e3deff9d</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2be227fd3cff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cognito Hosted UI with CloudFormation]]></title>
            <link>https://daaru.medium.com/cognito-hosted-ui-with-cloudformation-8993fc878a4f?source=rss-7cb6ae2574e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8993fc878a4f</guid>
            <category><![CDATA[aws-cognito]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Fabio Gollinucci]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 20:46:52 GMT</pubDate>
            <atom:updated>2024-03-18T08:57:24.948Z</atom:updated>
            <content:encoded><![CDATA[<p>Almost every project needs authentication at some point. This is how to describe configuring <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html">Cognito</a> via CloudFormation to speed up the user integration part of your application.</p><h4>UserPool</h4><p>The <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html">user pool</a> is the main resource that store users registered or signed in using social providers.</p><pre>UserPool:<br>  Type: AWS::Cognito::UserPool<br>  Properties:<br>    UserPoolName: !Sub &quot;${Project}-${Environment}&quot;<br>    DeletionProtection: ACTIVE<br>    AutoVerifiedAttributes:<br>      - &quot;email&quot;<br>    UsernameAttributes:<br>      - &quot;email&quot;<br>    Schema:<br>      - Name: email<br>        AttributeDataType: String<br>        Mutable: false<br>        Required: true<br>    MfaConfiguration: &quot;OFF&quot;<br>    Policies:<br>      PasswordPolicy:<br>        RequireLowercase: true<br>        RequireSymbols: false<br>        RequireNumbers: true<br>        MinimumLength: &quot;8&quot;<br>        RequireUppercase: true<br>    AccountRecoverySetting:<br>      RecoveryMechanisms:<br>        - Name: &quot;verified_email&quot;<br>          Priority: 1</pre><p>This configurations use the “email” field as main user identifier (UsernameAttributes), tell Cognito to verify it sending a verification code (AutoVerifiedAttributes). The email, once verified, is also used to recover password (AccountRecoverySetting).</p><p>The attributes schema just contains the email attributes, other <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#cognito-user-pools-standard-attributes">standard attributes</a> like family_name, gender, given_name, locale, middle_name, name and so on can be directly used without configurations. Custom attributes ca be declare as used with “custom:” prefix like custom:my_custom_attribute.</p><p>Remember to activate the DeletionProtection in order to prevent accidentally replacement and consequentially lost of all users.</p><h4>User Pool Client</h4><p>The <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html">user pool client</a> describe a client application that will connect to Cognito to perform login, registration and any other user-related actions.</p><pre>UserPoolClient:<br>  Type: AWS::Cognito::UserPoolClient<br>  DependsOn: [GoogleIdentityProvider, FacebookIdentityProvider, AmazonIdentityProvider]<br>  Properties:<br>    ClientName: !Sub &quot;${Project}-${Environment}&quot;<br>    UserPoolId: !Ref UserPool<br>    SupportedIdentityProviders:<br>      - COGNITO<br>      - Facebook<br>      - Google<br>      - SignInWithApple<br>    GenerateSecret: false # enabling this will break the frontend login<br>    AllowedOAuthFlowsUserPoolClient: true<br>    CallbackURLs: !Ref CallbackURLs<br>    LogoutURLs: !Ref CallbackURLs<br>    AllowedOAuthFlows:<br>      - code<br>    AllowedOAuthScopes:<br>      - email<br>      - openid<br>      - profile<br>      - aws.cognito.signin.user.admin<br>    TokenValidityUnits:<br>      IdToken: days<br>      AccessToken: days<br>      RefreshToken: days<br>    IdTokenValidity: 1 # from five minutes to one day<br>    AccessTokenValidity: 1 # from five minutes to one day<br>    RefreshTokenValidity: 30 # from 60 minutes to 10 years.</pre><p>There are different type of login and registration experiences that can be handled with Cognito:</p><ul><li>AWS managed hosted UI for login, registration and handle OAuth2 from your application</li><li>Self hosted frontend for login, registration and directly connect your application to Cognito</li></ul><p>This configuration is handled by AllowedOAuthFlowsUserPoolClient properties.</p><p>If is is set to true you will also need to configure:</p><ul><li>CallBackURLs: Your frontend login landing page URL.</li><li>LogoutURLs: Your frontend logout landing page URL.</li><li>AllowedOAuthScopes: The OAuth 2.0 scopes that ca be used.</li><li>AllowedOAuthFlows: Add support for authorization code, implicit, and client credentials OAuth 2.0 grants.</li></ul><p>This will enable the AWS Hosted UI and allow user to login and register from it.</p><p>If is is set to false you will need to handle login, registration, confirmation and password reset using the <a href="https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html">Cognito APIs</a>.</p><h4>The identity pool</h4><p>The identity pool handle user’s access to AWS resources like DynamoDB or S3 directly using AWS API with its own authentication system (IAM).</p><pre>IdentityPool:<br>  Type: AWS::Cognito::IdentityPool<br>  Properties:<br>    IdentityPoolName: !Sub &quot;${Project}${Environment}Identity&quot;<br>    AllowUnauthenticatedIdentities: false<br>    CognitoIdentityProviders:<br>      - ClientId: !Ref UserPoolClient<br>        ProviderName: !GetAtt UserPool.ProviderName</pre><p>Describe the role that authenticated users can assume in order to call AWS APIs and access protected resources.</p><pre>CognitoAuthorizedRole:<br>  Type: AWS::IAM::Role<br>  Properties:<br>    RoleName: !Sub &quot;${Project}-${Environment}-cognito-authorized&quot;<br>    AssumeRolePolicyDocument:<br>      Version: &quot;2012-10-17&quot;<br>      Statement:<br>        - Effect: &quot;Allow&quot;<br>          Principal:<br>            Federated: &quot;cognito-identity.amazonaws.com&quot;<br>          Action:<br>            - &quot;sts:AssumeRoleWithWebIdentity&quot;<br>          Condition:<br>            &quot;StringEquals&quot;:<br>              &quot;cognito-identity.amazonaws.com:aud&quot;: !Ref IdentityPool<br>            &quot;ForAnyValue:StringLike&quot;:<br>              &quot;cognito-identity.amazonaws.com:amr&quot;: authenticated<br>    Policies:<br>      - PolicyName: &quot;CognitoAuthorizedPolicy&quot;<br>        PolicyDocument:<br>          Version: &quot;2012-10-17&quot;<br>          Statement:<br>            - Effect: &quot;Allow&quot;<br>              Action:<br>                - &quot;cognito-sync:*&quot;<br>                - &quot;cognito-identity:*&quot;<br>              Resource: &quot;*&quot;</pre><p>Attach the role to the identity pool.</p><pre>IdentityPoolRoleMapping:<br>  Type: AWS::Cognito::IdentityPoolRoleAttachment<br>  Properties:<br>    IdentityPoolId: !Ref IdentityPool<br>    Roles:<br>      authenticated: !GetAtt CognitoAuthorizedRole.Arn</pre><p>Cognito can be used to allow unauthenticated user to also assume a role, this is used for example for tracking with <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-RUM.html">ClooudWatch RUM</a>, do not made public an access to S3 bucket or a DynamoDB table.</p><h4>Social Identity providers</h4><p>A classic authentication use case includes access via social media, this can be managed by configuring the providers made available by AWS.</p><pre>AmazonIdentityProvider:<br>  Type: AWS::Cognito::UserPoolIdentityProvider<br>  Properties:<br>    UserPoolId: !Ref UserPool<br>    ProviderName: &quot;LoginWithAmazon&quot;<br>    ProviderDetails:<br>      client_id: &quot;xxxxxxxxxxxxxxxxxxxx&quot;<br>      client_secret: &quot;xxxxxxxxxxxxxxxxxxxx&quot;<br>      authorize_scopes: &quot;profile postal_code&quot;<br>    ProviderType: &quot;LoginWithAmazon&quot;<br>    AttributeMapping:<br>      email: &quot;email&quot;<br><br>GoogleIdentityProvider:<br>  Type: AWS::Cognito::UserPoolIdentityProvider<br>  Properties:<br>    UserPoolId: !Ref UserPool<br>    ProviderName: &quot;Google&quot;<br>    ProviderDetails:<br>      client_id: &quot;xxxxxxxxxxxxxxxxxxxx&quot;<br>      client_secret: &quot;xxxxxxxxxxxxxxxxxxxx&quot;<br>      authorize_scopes: &quot;profile email openid&quot;<br>    ProviderType: &quot;Google&quot;<br>    AttributeMapping:<br>      email: &quot;email&quot;<br><br>FacebookIdentityProvider:<br>  Type: AWS::Cognito::UserPoolIdentityProvider<br>  Properties:<br>    UserPoolId: !Ref UserPool<br>    ProviderName: &quot;Facebook&quot;<br>    ProviderDetails:<br>      client_id: &quot;xxxxxxxxxxxxxxxxxxxx&quot;<br>      client_secret: &quot;xxxxxxxxxxxxxxxxxxxx&quot;<br>      authorize_scopes: &quot;public_profile,email&quot;<br>    ProviderType: &quot;Facebook&quot;<br>    AttributeMapping:<br>      email: &quot;email&quot;<br><br>AppleIdentityProvider:<br>  Type: AWS::Cognito::UserPoolIdentityProvider<br>  Properties:<br>    UserPoolId: !Ref UserPool<br>    ProviderName: &quot;SignInWithApple&quot;<br>    ProviderDetails:<br>      client_id: &quot;xx.xxxxx.xx&quot; # the service bundle id<br>      team_id: &quot;xxxxxxxxx&quot;<br>      key_id: &quot;xxxxxxxxxx&quot;<br>      private_key: &quot;--- xxxxxxxxxxxxxxxxxxxx ---&quot; # require a valid private key<br>      authorize_scopes: &quot;public_profile,email&quot;<br>    ProviderType: &quot;SignInWithApple&quot;<br>    AttributeMapping:<br>      email: &quot;email&quot;</pre><p>In your are using a custom frontend instead of the hosted UI, iIn order to use the “Login with” button you will need to interact with social’s tokens, federated access, attributes mapping and <a href="https://docs.amplify.aws/lib/auth/advanced/q/platform/js/#identity-pool-federation">lot of other stuff</a>, not just a redirect.</p><p>The advice is to still activate the hosted UI even if you use a custom frontend and use that panel to manage authentication via social media in order to let Cognito do the dirty work, you just need to <a href="https://docs.amplify.aws/lib/auth/social/q/platform/js/">add the social’s related buttons</a>.</p><h4>Hosted UI</h4><p>The AWS managed hosted UI implements all user access features, it is very useful in the testing phase to quickly add authentication to an existing application. Unfortunately, the lack of some imported features such as label translation, privacy policy management, custom field validation <strong>is not something that can be used in a production environment</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*VwYO1CoquprwK-DrNcyLSQ.png" /></figure><p>You can use your own domain to serve Hosted UI endpoints, not just the login/registration UI but also the exposed OAuth2 endpoints.</p><pre>UserPoolDomain: <br>  Type: AWS::Cognito::UserPoolDomain <br>  Properties:<br>    UserPoolId: !Ref UserPool <br>    Domain: !Sub &quot;${Project}-${Environment}&quot;</pre><p>Customize Hosted UI</p><pre>UserPoolUICustomization: <br>  Type: AWS::Cognito::UserPoolUICustomizationAttachment<br>  DependsOn: UserPoolDomain<br>  Properties: <br>    UserPoolId: !Ref UserPool<br>    ClientId: &#39;ALL&#39;<br>    CSS: |<br>      .banner-customizable { <br>        background-color: #6E6F6E;<br>        padding: 2em 0;<br>      }<br>      .background-customizable {<br>        background-color: #FAFAFA;<br>      }<br>      .submitButton-customizable {<br>        background-color: #6E6F6E;<br>      }<br>      .submitButton-customizable:hover {<br>        background-color: #6E6F6E;<br>      }<br>      .inputField-customizable {<br>        border-color: #FAFAFA;<br>      }<br>      .inputField-customizable:focus {<br>        border-color: #6E6F6E;<br>      }</pre><p>You cannot use it on all elements and you can only use some properties for some specific elements, see the <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-ui-customization.html">AWS documentation</a> for more details.</p><h4>Frontend implementation</h4><p>Install Amplify auth module, you don’t need the entire library</p><pre>npm install @aws-amplify/auth</pre><p>Import the auth module and configure it</p><pre>import { Auth } from &#39;@aws-amplify/auth&#39;<br><br>Auth.configure({<br>  region: &quot;eu-south-1&quot;,<br>  userPoolId: &quot;eu-south-1_xxxxxxxxxxx&quot;,<br>  userPoolWebClientId: &quot;xxxxxxxxxxxxxxxxxxxxxxxxx&quot;,<br>})</pre><p>Use the Hosted UI login/registration form to handle users authentication</p><pre><br>import { CognitoHostedUIIdentityProvider, Auth } from &#39;@aws-amplify/auth&#39;<br><br>await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Cognito })</pre><p>Implements self-hosted login form using <a href="https://docs.amplify.aws/lib/auth/emailpassword/q/platform/js/">auth module APIs</a> and integrate the authentication functionalities with your own custom UI</p><pre>import { Auth } from &#39;@aws-amplify/auth&#39;<br><br>await Auth.signUp({<br>  username,<br>  password,<br>  attributes: {<br>    email<br>  }<br>})<br><br>await Auth.confirmSignUp(username, code)<br><br>await Auth.signIn(username, password)<br></pre><p>Login with configured social provider using the hosted UI to manage the various redirects.</p><pre>import { CognitoHostedUIIdentityProvider, Auth } from &#39;@aws-amplify/auth&#39;<br><br>await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google })<br>await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Facebook })<br>await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Apple })<br>await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Amazon })</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8993fc878a4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>