<?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 PeterToulouras on Medium]]></title>
        <description><![CDATA[Stories by PeterToulouras on Medium]]></description>
        <link>https://medium.com/@petertou12?source=rss-8a1f8ae6e1a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r1bQpT5Bhs0xg9whJoVlHA.png</url>
            <title>Stories by PeterToulouras on Medium</title>
            <link>https://medium.com/@petertou12?source=rss-8a1f8ae6e1a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:00:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@petertou12/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[Byte-sized Tech: Automated Reasoning and Generative AI]]></title>
            <link>https://medium.com/@petertou12/bite-sized-tech-automated-reasoning-and-generative-ai-04f6c0878c41?source=rss-8a1f8ae6e1a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/04f6c0878c41</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[automated-reasoning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[formal-verification]]></category>
            <dc:creator><![CDATA[PeterToulouras]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 03:32:38 GMT</pubDate>
            <atom:updated>2024-11-26T01:17:51.894Z</atom:updated>
            <content:encoded><![CDATA[<p>In the rapidly evolving landscape of artificial intelligence (AI), two fields are gaining significant attention namely; automated reasoning and generative AI (GenAI). While they may seem distinct at first glance, their intersection is paving the way for smarter, more reliable systems that can reason, learn, and adapt. This article delves into both concepts, their individual strengths, and how their integration can revolutionize various domains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIG6BKWmvnEXNDiDosZK0A.jpeg" /></figure><h3>What is Automated Reasoning?</h3><p>Automated reasoning is a discipline within AI that applies formal logic to derive conclusions from given premises. It enables systems to make logical inferences automatically, ensuring that outputs adhere to specified rules and conditions. The major key aspects include:</p><p><strong>Logical Deduction:</strong> Automated reasoning systems can prove that a system design or implementation meets its specifications<br><strong>Formal Verification</strong>: These systems produce proofs in formal logic, supporting mathematical theorems or known truths</p><p><strong>Use Cases:</strong> Applications range from verifying software correctness to ensuring security compliance in complex systems</p><h4>Example of Automated Reasoning</h4><p>Consider a practical example in software verification:</p><p><strong>Problem Statement:</strong> Verify that a banking system properly handles fund transfers.</p><p><strong>Assertions</strong>:<br>1. Account balances cannot be negative<br>2. The sum of all accounts must remain constant during transfers<br>3. A transfer can only occur if the sender has sufficient funds</p><p>Using these rules, an automated reasoning system could verify a transfer operation:</p><pre>Initial State:<br>Account A balance: $100<br>Account B balance: $50<br>Proposed Transfer:<br>From Account A to Account B: $75<br><br>Automated Reasoning Process:<br>1. Check if A has sufficient funds: $100 ≥ $75 (True)<br>2. Check if transfer maintains non-negative balance: $100 - $75 ≥ 0 (True)<br>3. Check if sum remains constant: ($100 - $75) + ($50 + $75) = $150 (True)<br>Conclusion: Transfer is valid</pre><p>This trivial example demonstrates how automated reasoning can validate operations against formal constraints.</p><h3>Generative AI and Its Challenges</h3><h4>What is Generative AI?</h4><p>Generative AI refers to models capable of producing new content based on learned patterns from existing data. This includes generating text (like chatbots), images (like DALL-E), music, and even complex solutions to problems. Key aspects include:</p><p><strong>Creative Output:</strong> Generative models can create unique content that mimics human creativity<br><strong>Adaptability:</strong> These models learn from vast datasets and adapt to new information quickly</p><h4>Limitations of Generative AI</h4><p>Despite its immense potential, generative AI faces challenges:</p><p><strong>Surface-Level Understanding:</strong> Generative models often produce text without genuinely understanding the underlying concepts<br><strong>Inconsistency: </strong>These models may generate contradictory statements when asked similar questions<br><strong>Lack of Proof Generation:</strong> Unlike automated reasoning systems, generative AI does not provide formal proofs for its outputs</p><h3>Integrating Automated Reasoning with Generative AI</h3><p>To enhance the reliability of generative AI responses, we can employ automated reasoning techniques. Here’s a practical example:</p><h4>Step 1: Generate a Response</h4><pre>Prompt: &quot;Generate SQL code to transfer funds between bank accounts&quot;<br>==================================================================<br>Generated Response:<br>UPDATE accounts <br>SET balance = balance - 75 <br>WHERE account_id = &#39;A&#39;;<br>UPDATE accounts <br>SET balance = balance + 75 <br>WHERE account_id = &#39;B&#39;;</pre><h4>Step 2: Define Logical Assertions</h4><pre>ASSERTIONS:<br>1. ∀ account ∈ accounts: account.balance ≥ 0<br>2. SUM(accounts.balance) = CONSTANT<br>3. ∀ transfer(amount, from, to):<br> from.balance - amount ≥ 0</pre><h4>Step 3: Apply Automated Reasoning</h4><pre>def validate_transfer(sql_code, initial_state, assertions):<br> # Parse SQL operations<br> operations = parse_sql(sql_code)<br> <br> # Simulate execution<br> final_state = simulate_execution(operations, initial_state)<br> <br> # Verify assertions<br> for account in final_state.accounts:<br> if account.balance &lt; 0:<br> return &quot;Invalid: Negative balance detected&quot;<br> <br> if sum(initial_state.balances) != sum(final_state.balances):<br> return &quot;Invalid: Total funds not conserved&quot;<br> <br> return &quot;Valid: All assertions passed&quot;</pre><p>This integration ensures that the generated SQL code maintains the system’s invariants and business rules.</p><h3>Conclusion</h3><p>The integration of automated reasoning with generative AI represents a potential autonomous way of ensuring the reliability of AI-generated content and avoiding hallucinations. By applying logical validation techniques to evaluate responses, we can enhance their accuracy and consistency. This approach:</p><p>1. Ensures generated content adheres to formal proof specifications<br>2. Reduces the risk of inconsistent or invalid outputs<br>3. Provides verifiable and repeatable guarantees about system behavior</p><p>As we continue to explore these technologies’ capabilities and limitations, combining their strengths can potentially lead to more intelligent and reliable systems in artificial intelligence.</p><p>What are your thoughts on integrating automated reasoning with generative AI? How do you see this approach shaping the future of AI-generated content?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04f6c0878c41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI Security: Emerging Attack Vectors and Mitigation Strategies]]></title>
            <link>https://medium.com/@petertou12/generative-ai-security-emerging-attack-vectors-and-mitigation-strategies-c0de90edb446?source=rss-8a1f8ae6e1a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0de90edb446</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[gen-ai-tools]]></category>
            <category><![CDATA[cyberattack]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[gen-ai-revolution]]></category>
            <dc:creator><![CDATA[PeterToulouras]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 08:09:35 GMT</pubDate>
            <atom:updated>2024-09-24T08:09:35.039Z</atom:updated>
            <content:encoded><![CDATA[<p>In the rapidly evolving landscape of artificial intelligence, Generative AI (GenAI) has emerged as a game-changer, revolutionizing industries with its ability to create relatively high-quality content quickly. In addition to the benefits, the rise of Generative AI (GenAI) technology has also introduced new attack vectors that need to be addressed. A recent paper by researchers from the University of California, Berkeley, sheds light on these challenges and proposes potential countermeasures.</p><h3>The Unique Security Landscape of GenAI</h3><p>GenAI systems, particularly Large Language Models (LLMs) like GPT-4 and Claude, have capabilities that surpass traditional machine learning systems. They can generate text and code, interact with humans and internet services, and even understand visual scenes. While this opens up exciting possibilities, it also introduces new security risks.</p><p>There are three main roles that GenAI can play in the security landscape:</p><ol><li><strong>Target</strong>: GenAI models can be susceptible to attacks.</li><li><strong>Goon</strong>: Misplaced reliance on GenAI might lead to vulnerabilities.</li><li><strong>Tool</strong>: GenAI models could be used by threat actors for malicious purposes.</li></ol><h3>GenAI as a Target</h3><p>As generative AI models become more prevalent in our digital landscape, they’re increasingly becoming targets for malicious actors. Two prominent threats that have emerged are jailbreaking and prompt injection, both of which pose significant risks to the integrity and security of AI systems.</p><p><strong>Jailbreaking</strong> is a technique where attackers craft specially designed prompts to manipulate AI models, coercing them into generating harmful or misleading outputs. This method often aims to circumvent the AI’s built-in safeguards and ethical constraints, potentially leading to the production of content that violates the AI’s intended use and ethical guidelines.</p><p><strong>Prompt injection</strong>, a more specific form of attack, involves inserting malicious data or instructions into the AI model’s input stream. This clever manipulation tricks the AI into following the attacker’s instructions rather than its intended programming. Prompt injections can be categorized into two main types: direct and indirect.</p><ul><li><strong>Direct prompt injections</strong> occur when users attempt to directly access or manipulate the AI’s system instructions. For instance, an attacker might try to reveal hidden system prompts or alter the AI’s behavior significantly by issuing commands that override its original programming.</li><li><strong>Indirect prompt injections</strong>, also known as second-order injections, are more subtle. In these scenarios, attackers poison data that an AI will later consume. Imagine an AI bot that analyzes websites or user comments. An adversary could craft a hidden message within this content, invisible to human users but detectable by the AI, instructing it to behave in unintended ways.</li></ul><p>A particularly concerning variant is the <strong>cross-context AI injection</strong>. This occurs when AI systems fail to maintain proper boundaries between different operational contexts. An attack initiated in one context, such as a specific website or document, might unexpectedly affect or extract data from another context within the same AI session, blurring the lines of data separation and privacy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y50PO6-HNDNYijyV.png" /></figure><p><a href="https://arxiv.org/pdf/2402.12617">source</a>: An example of a prompt injection attack involves embedding a hidden prompt within website content, causing the chat model to exhibit unintended behavior.</p><p>These attacks can lead to brand damage, security breaches, and even physical harm when integrated with real-world systems. The researchers suggest continuous monitoring and limiting high-sensitivity actions as temporary measures until more effective defenses are developed.</p><h3>GenAI as a Goon</h3><p>Even without deliberate attacks, GenAI systems can inadvertently introduce vulnerabilities. Two main concerns are data leakage and the generation of insecure code.</p><p>GenAI models trained on sensitive data might accidentally reveal this information in their outputs. Avoid training or fine-tuning models on sensitive data and implement monitoring systems to detect any unintentional data exposures.</p><p>While AI-assisted coding tools like GitHub Copilot have gained popularity, studies show that they can introduce security vulnerabilities in the generated code. Further research is needed to ensure the security of AI-generated code. Keep in mind these models have been trained on millions — billions of lines of code, with a vary high variance in code quality. A significant portion of the easily accessible and readily available code used to train these models is certainly not of ‘bar-raising’ quality.</p><h3>GenAI as a Tool for Threat Actors</h3><p>Bad actors could potentially use GenAI to enhance or automate cyber-attacks. This includes crafting sophisticated phishing emails, generating fake media for misinformation campaigns, producing malicious code, and even creating prompts to exploit other GenAI systems. GenAI systems can be leveraged along with traditional social engineering strategies as well.</p><h4>Automated Parts of Social Engineering</h4><p><strong>Phishing Emails:</strong></p><ul><li><strong>Manual Task</strong>: Crafting convincing phishing emails requires time and effort to ensure they appear legitimate and bypass spam filters.</li><li><a href="https://blog.knowbe4.com/generative-ai-automation-social-engineering"><strong>Automation</strong>: Generative AI can quickly generate highly convincing phishing emails with proper grammar and context-specific content, making them harder to detect</a>.</li></ul><p><strong>Voice Phishing (Vishing):</strong></p><ul><li><strong>Manual Task</strong>: Creating realistic voice messages or making phone calls to deceive targets.</li><li><strong>Automation</strong>: AI tools can generate lifelike voice messages that mimic specific individuals, adding credibility to the attack. <a href="https://blog.knowbe4.com/generative-ai-automation-social-engineering">This can be used for pre-recorded messages or even real-time voice synthesis during calls</a>.</li></ul><p><strong>Social Media Interaction:</strong></p><ul><li><strong>Manual Task</strong>: Engaging with targets on social media to build trust and gather information.</li><li><a href="https://www.thinkmind.org/articles/iccgi_2024_1_10_10002.pdf"><strong>Automation</strong>: AI can automate interactions on social media, sending friend requests, liking posts, and even engaging in conversations to build rapport with the target</a>.</li></ul><p><strong>Data Collection:</strong></p><ul><li><strong>Manual Task</strong>: Gathering information about targets from various sources to personalize attacks.</li><li><a href="https://www.thinkmind.org/articles/iccgi_2024_1_10_10002.pdf"><strong>Automation</strong>: AI can scrape data from social media profiles, public records, and other online sources to compile detailed profiles of potential targets</a>.</li></ul><h4>Examples</h4><ul><li><strong>Phishing Campaigns</strong>: Using AI to generate personalized phishing emails that address the recipient by name and reference specific details about their job or interests, making the email appear more legitimate.</li><li><strong>Voice Phishing</strong>: An attacker could use AI-generated voice messages to impersonate a company executive, instructing an employee to transfer funds or disclose sensitive information.</li><li><strong>Social Media Scams</strong>: AI bots can interact with users on platforms like LinkedIn, gradually building trust before sending a malicious link or request.</li></ul><p>Automation of these techniques allows malicious actors to expand their operations and boost their chances of breaching defenses. Organizations must stay vigilant about such strategies and deploy strong protective measures to thwart these attempts.</p><h3>The Need for New Approaches in Generative AI Security</h3><p>As we delve deeper into the world of Generative AI (GenAI), it’s becoming increasingly clear that our existing security approaches are falling short. The methods that have served us well for conventional software and earlier AI systems are often inadequate or ineffective when it comes to these new, highly capable systems. Let’s explore why we need to rethink our approach to AI security:</p><h4>Complexity of GenAI Systems</h4><p>GenAI models, particularly large language models (LLMs), possess broad, general capabilities across numerous domains. They can handle tasks ranging from casual conversation and creative writing to complex coding and technical analysis. This versatility makes it challenging to apply conventional security measures that are typically designed for more specific, constrained systems.</p><h4>Emergent Capabilities</h4><p>One of the most fascinating — and concerning — aspects of GenAI systems is their tendency to develop unexpected abilities during training, without intentional human design. These emergent capabilities can create unforeseen threat vectors that traditional security measures are not equipped to handle. For instance, the ability of LLMs to learn new tasks “in-context” or perform complex reasoning was only discovered after training at scale.</p><h4>Expanded Attack Surface</h4><p>GenAI systems rely on massive amounts of user-generated content for training and often incorporate external data sources during inference. This greatly expands the attack surface, making traditional methods like input sanitization or blacklisting impractical or ineffective. Adversaries have many more opportunities to introduce malicious content or manipulate the system’s behavior.</p><h4>Deep Integrations</h4><p>Many GenAI applications are being deeply integrated with other software systems, APIs, and even robotic systems. This level of integration and the ability to take real-world actions based on natural language input create new security challenges that go beyond what traditional measures can address.</p><h4>Economic Value and Attractiveness to Attackers</h4><p>The high economic value of GenAI applications in areas like healthcare, customer service, and software engineering makes them attractive targets for attackers. This increased motivation for malicious actors requires more robust and adaptable security measures.</p><h4>Limitations of Traditional Approaches</h4><p>Several traditional security approaches fall short when applied.n While it can be used to limit data access, the open-ended nature of user requests makes it difficult to predetermine all necessary permissions.<br><strong>1. Rule-based Blocking:</strong> Simple rule-based filters are easily bypassed due to the complexity of GenAI prompts and the many ways to obfuscate malicious intent.<br><strong>2. Sandboxing: </strong>The deep integrations of many GenAI systems make effective sandboxing challenging without severely limiting functionality.<br><strong>3. Antivirus and Blacklisting:</strong> The vast number of ways to phrase attacks or obfuscate them makes traditional signature-based detection ineffective.<br><strong>4. Parameterized Queries:</strong> The flexibility required for GenAI applications makes it impractical to use pre-defined query templates.<br><strong>5. Software Patching:</strong> The monolithic nature of LLMs makes it difficult to develop localized fixes for specific vulnerabilities without affecting other behaviors.</p><h3>The Way Forward</h3><p>To effectively secure GenAI systems, we need to leverage machine learning as a core tool in our security arsenal. This includes developing intelligent monitoring systems that can detect subtle patterns of malicious behavior and adapt to new threats.</p><p>Moreover, the rapidly evolving nature of GenAI technology means that our security measures must be dynamic and adaptable. Unlike traditional software vulnerabilities, GenAI threats are likely to evolve quickly, requiring constant vigilance and updating of security strategies.</p><p>The unique characteristics of GenAI systems — their complexity, emergent capabilities, expanded attack surfaces, and deep integrations — necessitate new, more sophisticated approaches to security. These new approaches will likely need to be as intelligent and adaptable as the GenAI systems they aim to protect, marking a significant shift in how we think about and implement AI security.</p><h3>Potential Research Directions</h3><p>Researchers propose several promising research directions to address these challenges:</p><h4>AI Firewall:</h4><p>An AI Firewall is a protective system designed to safeguard a black-box Generative AI (GenAI) model by monitoring and potentially transforming its inputs and outputs. The primary goals of an AI Firewall include:</p><ol><li><strong>Input Monitoring and Transformation:</strong></li></ol><ul><li><strong>Jailbreak Detection:</strong> The AI Firewall can monitor inputs to detect jailbreak attacks, which are attempts to bypass the model’s restrictions. Continuous learning techniques could be employed to identify new jailbreak prompts.</li><li><strong>Stateful Analysis:</strong> The system could analyze a sequence of inputs from a particular user to detect patterns that might indicate malicious intent.</li></ul><p>2. <strong>Output Monitoring and Transformation:</strong></p><ul><li><strong>Content Moderation:</strong> The AI Firewall can check outputs to ensure they do not violate security policies, such as containing toxic, offensive, or inappropriate content. This might involve using a content moderation model.</li><li><strong>Sophistication Matching:</strong> It is crucial that the detection and moderation model matches the sophistication of the GenAI model it protects. Less capable models might be vulnerable to obfuscation techniques, especially if they rely on simple blacklist policies.</li></ul><p>3. <strong>Moderation Model Capabilities:</strong></p><ul><li><strong>Smaller Models for Moderation:</strong> There is ongoing research into whether smaller models can effectively and safely perform moderation tasks. This is related to the concept of superalignment, where a less capable model is used to align a more intelligent one.</li></ul><p>4. <strong>Practical Examples:</strong></p><ul><li><strong>DALL-E 3 and ChatGPT:</strong> In this setup, ChatGPT acts as an AI Firewall by crafting prompts for DALL-E 3 and enforcing policies on the types of images generated. ChatGPT’s superior language understanding helps prevent attacks that could exploit DALL-E 3’s vulnerabilities.</li><li><strong>Cloud AI Services:</strong> Content filtering and input filtering mechanisms in services like Bing Chat demonstrate how AI systems are equipped to monitor and control generated content, ensuring adherence to guidelines and preventing misuse.</li></ul><p>5. <strong>Access Control:</strong></p><ul><li><strong>Limits and Permissions:</strong> An AI Firewall might impose limits or access controls on the model’s ability to invoke tools or take actions. Designing a suitable access control system is an open problem, potentially involving a secondary model to analyze queries and determine appropriate limits, obtaining user consent when necessary.</li></ul><h4>Integrated Firewall:</h4><p>An Integrated Firewall leverages access to a Generative AI (GenAI) model’s internal weights to enhance security by detecting and mitigating attacks more effectively. This approach includes two main research directions:</p><ol><li><strong>Internal State Monitoring:</strong></li></ol><ul><li><strong>Neuron Surveillance:</strong> By monitoring specific neurons or neuron clusters within the language model, researchers can identify correlations with the generation of hallucinatory or unethical outputs. This early detection can help mitigate undesirable behaviors during the response generation process.</li></ul><p>2. <strong>Safety Fine-Tuning:</strong></p><ul><li><strong>Supervised Fine-Tuning (SFT) and Reinforcement Learning from Human Feedback (RLHF):</strong> Open-source GenAI models can be fine-tuned against known malicious prompts and behaviors. This process is similar to equipping a person with self-defense skills, enhancing the model’s ability to recognize and counteract harmful inputs. Training on a dataset of known threats enables the model to learn and adapt its responses to minimize risks.</li></ul><p>3. <strong>Combining AI Firewall and Integrated Firewall:</strong></p><ul><li><strong>Enhanced Defense:</strong> Combining an AI Firewall with an Integrated Firewall can provide stronger protection than either approach alone. Direct integration with the AI model’s internal states promises superior efficiency and efficacy in countering threats, aligning with the safety-capability criterion.</li></ul><h4>Guardrails:</h4><p>Guardrails refer to application-specific restrictions or policies enforced on the output of a Large Language Model (LLM). The primary challenge is to ensure that the LLM’s outputs adhere to these guardrails, even when only black-box access to the model is available. Key points include:</p><ol><li><strong>Scenario and Challenge:</strong></li></ol><ul><li><strong>Application-Specific Guardrails:</strong> For example, a guardrail might restrict the LLM to only discuss a company’s products and avoid topics like other companies’ products, religion, or politics.</li><li><strong>Steering Outputs:</strong> The challenge is to guide the LLM’s outputs to comply with these guardrails during test time.</li></ul><p>2. <strong>Rejection Sampling:</strong></p><ul><li><strong>Method:</strong> This involves running the LLM multiple times (e.g., 10 times) on the same prompt to generate multiple outputs. A second model then scores each output based on how well it follows the guardrail, and the highest-scoring output is selected.</li><li><strong>Effectiveness and Cost:</strong> While rejection sampling is effective, it is computationally expensive, increasing test-time costs significantly.</li></ul><p>3. <strong>Alternative Methods:</strong></p><ul><li><strong>Controlled Decoding:</strong> This approach introduces bias in the logits of the LLM during the decoding process to steer the outputs towards complying with the guardrails. This method aims to achieve similar effectiveness at a lower computational cost.</li></ul><h4>Watermarking and Content Detection:</h4><p>Differentiating between human-generated and machine-generated content is crucial for addressing issues like plagiarism, data contamination, and misinformation. The primary approaches include:</p><ol><li><strong>Classification vs. Watermarking:</strong></li></ol><ul><li><strong>Classification-Based Methods:</strong> These involve training a classifier to distinguish between human-generated and machine-generated content. However, this approach may not be effective in the future due to the increasing sophistication of GenAI models, sensitivity to output distribution, and potential biases for non-English content or rarely-seen samples.</li><li><strong>Watermarking:</strong> Embedding hidden signals in LLMs (Large Language Models) to identify machine-generated content. This approach is seen as more promising than classification-based methods.</li></ul><p>2. <strong>Future Research Directions:</strong></p><ul><li><strong>Watermarking Open Source Models:</strong> A significant challenge is watermarking open-source models, as attackers can easily remove watermark-specific code or modify the model’s weights and decoding methods. Without a practical solution, open-source models can be used to rephrase watermarked content from closed-source models.</li><li><strong>Watermarking Human-Generated Content:</strong> Inspired by image authentication methods, this approach involves developing special watermarks for human-authored content. This could complement existing methods and enhance the robustness of content verification systems by distinguishing between human and machine-generated content.</li><li><strong>Cross-Model Coordination:</strong> Ensuring that watermarking mechanisms are effective across different models and generations of AI technologies requires a unified watermarking method acceptable to all model providers.</li></ul><h4>Regulations Enforcement:</h4><p>Policies and regulations can help mitigate the risks associated with the misuse of Generative AI (GenAI). Researchers can influence this by making realistic predictions about GenAI’s development and effects, and proposing policy options for policymakers. Key considerations include:</p><ol><li><strong>Regulation of Proprietary and Open Source Models:</strong></li></ol><ul><li><strong>Insights from the “Crypto Wars”:</strong> Overly stringent national regulations can be counterproductive, potentially stifling innovation and slowing the adoption of beneficial technology. This is particularly relevant for both proprietary and open-source GenAI models.</li><li><strong>Proprietary Models:</strong> Easier to regulate due to the limited number of companies involved, but regulation depends on the responsible and ethical practices of these companies.</li><li><strong>Open Source Models:</strong> Allow for unregulated use and modifications, fostering rapid innovation and supporting research on AI safety. Policies should balance fostering innovation with ensuring security.</li></ul><p>2. <strong>Government Licensing of LLM Companies:</strong></p><ul><li><strong>Structured Framework:</strong> Licensing companies that develop large language models (LLMs) could create a framework for accountability, oversight, and ethical compliance, enhancing the trustworthiness of GenAI systems.</li></ul><p>3. <strong>Dynamic Policy Evolution:</strong></p><ul><li><strong>Regular Updates:</strong> Given the rapid advancement of GenAI technology, policies and regulations need regular updates to adapt to new technological realities and challenges.</li></ul><h4>Evolving Threat Management:</h4><p>GenAI threats are dynamic, requiring security systems to continuously adapt. Key points include:</p><ol><li><strong>Continuous Evolution:</strong></li></ol><ul><li><strong>Cat and Mouse Game:</strong> For every defensive move, attackers develop counter-moves. Security systems must evolve by learning from past breaches and anticipating future strategies.</li></ul><p>2. <strong>No Universal Protection:</strong></p><ul><li><strong>Adversarial Examples:</strong> Similar to adversarial examples in computer vision, there is no universal protection against prompt injection, jailbreaks, or other attacks. Monitoring and detecting threats is a pragmatic defense for now.</li></ul><p>3. <strong>Tools and Strategies:</strong></p><ul><li><strong>Monitoring and Detection:</strong> Developers need tools to monitor, detect, and respond to attacks on GenAI. A threat intelligence strategy is essential to track emerging threats.</li></ul><p>4. <strong>Historical Context:</strong></p><ul><li><strong>Long-Term Defense Development:</strong> Society has had thousands of years to develop defenses against scammers, but GenAIs have only been around for a few years. Defending them is still a work in progress.</li></ul><p>5. <strong>Future Flexibility:</strong></p><ul><li><strong>Design for Adaptability:</strong> Predicting future AI threats is challenging. Researchers are investigating new countermeasures, so systems should be designed to remain flexible, allowing new defenses to be integrated as they are discovered.</li></ul><h3>Conclusion</h3><p>As we continue to unlock the potential of Generative AI, it’s crucial that we simultaneously work on strengthening its defenses. The challenges are complex, but with continued research and collaboration, we can create a safer ecosystem for this transformative technology.</p><p>While the road ahead may seem daunting, it’s important to remember that we’re still in the early stages of GenAI development. Just as we’ve developed robust security measures for traditional computing systems over time, we will undoubtedly rise to meet the security challenges posed by GenAI.</p><p>Moreover, the complex, opaque nature of many state-of-the-art LLMs used in GenAI poses its own set of challenges. These models can be somewhat of a “black box”, making it difficult to fully understand their inner workings and potential vulnerabilities. This opacity creates an environment where determined adversaries may be incentivized to invest significant time and effort into uncovering the deep, intricate details of these models, seeking to uncover weaknesses that can be exploited for malicious purposes. Addressing the transparency and interpretability of GenAI systems will be a crucial step in bolstering their security and resilience against such attacks.</p><p>By staying vigilant, fostering innovation in AI security, and maintaining a balance between regulation and technological progress, we can harness the power of Generative AI while mitigating its risks.</p><p><em>This article is based on the research paper “Generative AI Security: Challenges and Countermeasures” by Banghua Zhu, Norman Mu, Jiantao Jiao, and David Wagner from the University of California, Berkeley. For more detailed information, please refer to the original paper.</em></p><p><a href="https://arxiv.org/abs/2402.12617">Generative AI Security: Challenges and Countermeasures</a></p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//arxiv.org/pdf/2402.12617&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4161443a203f1f5e2a8484c1a67b21c/href">https://medium.com/media/b4161443a203f1f5e2a8484c1a67b21c/href</a></iframe><p><a href="https://blog.knowbe4.com/generative-ai-automation-social-engineering">Generative AI and the Automation of Social Engineering Increasingly Used By Threat Actors</a></p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//www.thinkmind.org/articles/iccgi_2024_1_10_10002.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0798e988fbb4208fd2d7d584b083f18/href">https://medium.com/media/a0798e988fbb4208fd2d7d584b083f18/href</a></iframe><p><a href="https://embracethered.com/blog/posts/2023/ai-injections-direct-and-indirect-prompt-injection-basics/">AI Injections: Direct and Indirect Prompt Injections and Their Implications · Embrace The Red</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0de90edb446" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust on AWS Lambda: Building a CV-to-Job Recommender via API Gateway and S3]]></title>
            <link>https://medium.com/@petertou12/rust-on-aws-lambda-building-a-cv-to-job-recommender-via-api-gateway-and-s3-3db7a7b4c651?source=rss-8a1f8ae6e1a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3db7a7b4c651</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[PeterToulouras]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 17:17:33 GMT</pubDate>
            <atom:updated>2024-08-08T18:08:20.571Z</atom:updated>
            <content:encoded><![CDATA[<p>Rust has become a popular programming language in recent years, offering a unique blend of performance, safety, and concurrency. Its rise to prominence has evolved from a niche interest among developers, to now being a tool used in industry for leveraging a competitive advantages.</p><p>In a notable endorsement, Dr. Werner Vogels, CTO of Amazon.com, highlighted Rust’s potential during his <a href="https://community.aws/content/2ZPEXFlhe2kIW855VnaW3aViRfC/recap-of-werner-vogels-keynote-at-re-invent-2023?lang=en">re:Invent 2023 keynote</a>. He emphasized Rust’s ability to deliver “performance, reliability, and productivity” all at once, marking it as a language of choice for building cloud infrastructure and beyond.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMdh_2PXe9i8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMdh_2PXe9i8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMdh_2PXe9i8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ed4b3f797c0857b0b0b30c6a2864a2d/href">https://medium.com/media/4ed4b3f797c0857b0b0b30c6a2864a2d/href</a></iframe><p>Rust’s appeal lies in its memory safety without sacrificing speed, making it an suitable choice for performance-critical applications. It achieves this through its innovative ownership model, which prevents common pitfalls like null or dangling pointer references at compile-time. Albeit, a bit of a pain to learn and grasp initially.</p><p>For serverless environments like AWS Lambda, Rust’s efficiency translates to faster cold starts and lower execution costs. Its robust type system and expressive syntax also contribute to more maintainable codebases, a crucial factor in the fast-paced world of cloud computing.</p><p>As we explore building a CV-to-Job recommender using Rust on AWS Lambda, we’ll see firsthand why this language is gaining traction in cloud-native development. Rust’s combination of safety, speed, and developer productivity makes it a compelling choice for modern serverless architectures.</p><p>The serverless service we will be leveraging is Lambda. Lambda has a simple <a href="https://docs.aws.amazon.com/lambda/latest/operatorguide/computing-power.html">costing model</a>, reducing either the memory allocation or execution time , or both, will bring down the cost, especially when dealing with high throughput:</p><blockquote><strong><em>“Cost = Allocated Memory X Execution Time”</em></strong></blockquote><p>In this tutorial involves the following:</p><ol><li>Comparison between Rust and Python Lambdas</li><li>Setup Lambda function</li><li>Deploying to AWS</li><li>Setup API Gateway</li><li>Deploy simple frontend hosted on S3</li></ol><h3>Comparison between Rust and Python Lambdas</h3><p>Before diving into the setup and implementation details of the tool, let’s start with a performance comparison between Rust and Python Lambdas. This analysis provides valuable insights into how these languages perform in a serverless environment, setting the stage for our exploration and providing valid reasoning for consideration of Rust in AWS Lambda.</p><p>For this comparison, we implemented identical CV-to-job matching functions in both Rust and Python. These Lambda functions take a CV as input, extract relevant skills, and match them against a predefined set of required skills for given Job postings. Both implementations use AWS Lambda, integrated with API Gateway for HTTP access and S3 for storing and retrieving CV documents.</p><p>We conducted a straightforward benchmark test, sending 1,000 requests to both Rust and Python Lambda functions using BurpSuite’s Intruder functionality. The test utilized a default resource pool with 10 concurrent requests to simulate a realistic load scenario.</p><p>Key metrics such as execution time, memory usage, CPU utilization, cold start frequency, and network I/O have been captured and analyzed. Here are the results:</p><h4>Execution Time</h4><p>The analysis reveals that Rust Lambdas significantly outperform Python Lambdas in terms of execution time. The average duration for Rust functions was 99.19 ms, compared to 1725.38 ms for Python functions. This represents an impressive 94.3% improvement in execution speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UcoKVRzMrZWT_AzT2wfBKg.png" /></figure><p>As seen in the box plot above, Rust functions not only have a much lower median execution time but also demonstrate less variability in performance. This consistency is crucial for applications with strict latency requirements.</p><h4>Cold Start Performance</h4><p>Cold starts are a common concern in serverless architectures. As mentioned earlier, this analysis is relatively simple and small and hence we have a small percentage of cold start data. Cold start frequency: Rust (1.08%), Python (0.90%). The duration of cold starts for each respective Lambda can be seen below</p><ul><li>Average cold start duration: Rust (852.09 ms), Python (2139.33 ms)</li></ul><p>Specifically, Rust cold starts are 60.17% faster than Python cold starts. This substantial difference can lead to significant performance improvements in real-world scenarios, especially for applications that experience frequent cold starts or have strict latency requirements. The faster recovery time of Rust Lambdas can greatly enhance user experience and overall system responsiveness, particularly during traffic spikes or after periods of inactivity.</p><h4>Memory Usage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zdFp0xh3AhEvXu940f_Gig.png" /></figure><p>Our analysis shows that Rust Lambdas use less memory on average:</p><ul><li>Average memory usage: Rust (29.34%), Python (84.56%)</li></ul><p>This represents a 65.3% reduction in memory usage, which can lead to cost savings and improved performance, especially for memory-intensive applications.</p><h4>CPU Usage Time</h4><p>Rust Lambdas demonstrate significantly more efficient CPU utilization:</p><ul><li>Average CPU usage time: Rust (8.57 ms), Python (118.18 ms)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*HGFg7TrM1Sghwl-JBBOUrw.png" /></figure><p>The bar graph plot above shows a clear difference in CPU usage between the two languages. Rust functions consistently use less CPU time, as displayed above, indicating lower CPU usage and faster execution times.</p><ol><li>Billing Efficiency</li></ol><p>In terms of billing efficiency (actual duration vs. billed duration), both languages perform similarly, with Python having a slight edge:</p><ul><li>Average billing efficiency: Rust (98.73%), Python (99.94%)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eRPg2mwtBNkBgwo9oPfbMg.png" /></figure><p>The difference is minimal, suggesting that both languages are equally cost-effective in terms of billed vs. actual execution time. It does appear as though the cold starts in Rust have a lower billing efficiency.</p><p>2. Network I/O</p><p>The analysis of network I/O reveals interesting patterns in how Rust and Python Lambdas handle data transfer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NKTDQsojrgm6YHf-Id5_BA.png" /></figure><ol><li>Throughput: Rust Lambdas demonstrate significantly higher network throughput. Rust consistently achieves high NetworkIOBytes values (up to 70,000 bytes) with very low execution times (mostly under 500ms). This suggests that Rust is more efficient in handling network operations, possibly due to its low-level control and efficient memory management.</li><li>Consistency: Rust shows a more consistent performance pattern. The vertical clustering of Rust data points indicates that it can handle varying amounts of network I/O without substantially impacting execution time. This consistency could be valuable for applications with unpredictable network loads.</li><li>Scalability: Python Lambdas, while capable of handling similar NetworkIOBytes values, do so at much longer execution times (1500ms and above). This indicates that Python’s network I/O performance may not scale as well as Rust’s under higher loads.</li><li>Efficiency at lower I/O: For lower NetworkIOBytes values (below 40,000), both languages show similar patterns, but Rust consistently executes faster.</li><li>Variability: Python shows more scattered data points, suggesting that its execution time is more sensitive to changes in network I/O volume. This could lead to less predictable performance in network-intensive applications.</li></ol><p>While the average Network I/O values are similar (Rust: 27,401.042 bytes, Python: 28,570.721 bytes), the way each language handles this I/O differs significantly. Rust’s ability to maintain low execution times even with high network I/O suggests it could be particularly well-suited for applications requiring high-throughput, low-latency network operations.</p><p>The difference in network I/O is relatively small (about 4.7% less for Rust), suggesting that both languages handle network operations similarly in this context.</p><h3>Setup Lambda function</h3><p>We will use the <a href="https://github.com/awslabs/aws-lambda-rust-runtime">Rust runtime client</a> to build our project locally, then deploy it to AWS Lambda using either the provided.al2023 or provided.al2 runtime. This approach leverages Rust&#39;s ability to compile to native code, eliminating the need for a dedicated runtime on Lambda. By choosing provided.al2023 or provided.al2, we ensure that Lambda automatically maintains the operating system with the latest security patches.</p><p>The easiest way to start writing Lambda functions with Rust is by using <a href="https://www.cargo-lambda.info/">Cargo Lambda</a>, a related project. Cargo Lambda is a Cargo plugin, or subcommand, that provides several commands to help you in your journey with Rust on AWS Lambda.</p><h4><strong>Installing Cargo Lambda</strong></h4><p>The preferred way to install Cargo Lambda is by using a package manager.</p><p><strong>1- Use Homebrew on </strong><a href="https://brew.sh/"><strong>MacOS</strong></a><strong>:</strong></p><pre>brew tap cargo-lambda/cargo-lambda<br>brew install cargo-lambda</pre><p><strong>2- Use </strong><a href="https://scoop.sh/"><strong>Scoop</strong></a><strong> on Windows:</strong></p><pre>scoop bucket add cargo-lambda https://github.com/cargo-lambda/scoop-cargo-lambda<br>scoop install cargo-lambda/cargo-lambda</pre><p><strong>3- Or PiP on any system with Python 3 installed:</strong></p><pre>pip3 install cargo-lambda</pre><h4><strong>Creating our Function</strong></h4><p>To create our function, run Cargo Lambda with the <a href="https://www.cargo-lambda.info/commands/new.html">subcommand </a><a href="https://www.cargo-lambda.info/commands/new.html">new</a>. This command will generate a Rust package with the initial source code for the respective function:</p><pre>cargo lambda new suitable_jobs</pre><p>After creating our function with cargo lambda new suitable_jobs, we need to set up the necessary Rust files within this function. Let&#39;s break down the structure and content of these files:</p><p><strong>“Database” Schema</strong></p><p>We are going to upload a CSV file with the following format to S3 and then pull this data during execution</p><p>The provided data is in a CSV format, with the following schema</p><pre>+---------------+---------------+------------------+---------------+-----------------+-------------+---------------+<br>| id            | title         | description      |required_skills| preferred_skills| location    | pay           |<br>+---------------+---------------+------------------+---------------+-----------------+-------------+---------------+</pre><p>Each of the entries in the schema above is of type String.</p><h4>Uploading the Data to Amazon S3</h4><p>To upload the data to an Amazon S3 bucket, follow these steps:</p><ol><li>Create an S3 bucket using the AWS CLI or the AWS Management Console.</li></ol><pre>aws s3 mb s3://my-job-postings-unique-bucket-name</pre><p>2. Upload the *.csv file to the S3 bucket using the AWS CLI.</p><pre>aws s3 cp *.csv s3://my-job-postings-unique-bucket-name/</pre><p>Alternatively, you can use the AWS Management Console to upload the file by navigating to your S3 bucket and clicking “Upload”.</p><p>3. Verify that the file has been uploaded successfully by checking the contents of the S3 bucket.</p><pre>aws s3 ls s3://my-job-postings-unique-bucket-name</pre><p>Take not of the name of this bucket as well as the name of the csv file as we will be using it later</p><ol><li><strong>main.rs</strong></li></ol><pre>use driver::execute;<br>use lambda_http::{run, service_fn, tracing, Body, Error, Request, Response};<br>use serde_json::Value;<br>use tracing::{info, instrument};<br>mod driver;<br>mod job_finder;<br>mod jobs;<br><br>#[instrument(skip(event), fields(req_id))]<br>async fn function_handler(event: Request) -&gt; Result&lt;Response&lt;Body&gt;, Error&gt; {<br>    println!(&quot;Incoming request&quot;);<br>    let body = match event.body() {<br>        lambda_http::Body::Text(s) =&gt; s,<br>        _ =&gt; return Err(&quot;Invalid body format&quot;.into()),<br>    };<br><br>    let json_body: Value = serde_json::from_str(body)?;<br><br>    // Extract the base64EncodedString<br>    let base64_encoded_string = match json_body.get(&quot;base64EncodedString&quot;) {<br>        Some(Value::String(s)) =&gt; s,<br>        _ =&gt; return Err(&quot;Missing base64EncodedString field&quot;.into()),<br>    };<br><br>    // Decode the base64 string<br>    let decoded_bytes = base64::decode(base64_encoded_string)?;<br>    let decoded_input = String::from_utf8(decoded_bytes)?;<br><br>    info!(&quot;{:?}&quot;, &amp;body);<br><br>    let input_words: Vec&lt;String&gt; = decoded_input<br>        .split_whitespace()<br>        .map(|word| word.chars().filter(|ch| ch.is_alphabetic()).collect())<br>        .collect();<br><br>    let matched_jobs = execute(input_words).await.unwrap();<br>    let results = serde_json::to_string(&amp;matched_jobs).expect(&quot;Failed to serialize to JSON&quot;);<br><br>    println!(&quot;Output should be {:?}&quot;, &amp;results);<br><br>    let resp = Response::builder()<br>        .status(200)<br>        .header(&quot;content-type&quot;, &quot;application/json&quot;)<br>        .header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)<br>        .header(&quot;Access-Control-Allow-Headers&quot;, &quot;Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token&quot;)<br>        .header(&quot;Access-Control-Allow-Methods&quot;, &quot;OPTIONS,POST,GET&quot;)<br>        .body(results.into())<br>        .map_err(Box::new)?;<br>    Ok(resp)<br>}<br><br>#[tokio::main]<br>async fn main() -&gt; Result&lt;(), Error&gt; {<br>    tracing::init_default_subscriber();<br><br>    run(service_fn(function_handler)).await<br>}</pre><p>This is the entry point of our Lambda function. It contains the function_handler which processes incoming HTTP requests and returns responses. Here&#39;s what&#39;s happening in this file:</p><ul><li>We import necessary modules and set up async function handling.</li><li>The function_handler decodes a base64-encoded string from the request body, which contains the parsed CV text.</li><li>It processes the input, calls the execute function from the driver module, and returns the matched jobs as a JSON response.</li><li>CORS headers are added to the response to allow cross-origin requests.</li><li>The main function also sets up tracing and runs the Lambda service.</li></ul><p><strong>2. jobs.rs</strong></p><pre>use serde::{Deserialize, Serialize};<br><br>#[derive(Clone, Debug, Deserialize, Serialize)]<br>pub struct Job {<br>    pub id: String,<br>    pub title: String,<br>    pub description: String,<br>    pub required_skills: String,<br>    pub preferred_skills: String,<br>    pub location: String,<br>    pub pay: String,<br>}</pre><p>This file defines the Job struct, which represents the structure of a job listing. It includes fields like id, title, description, required skills, preferred skills, location, and pay. The struct derives Serialize and Deserialize traits, allowing for easy JSON conversion.</p><p><strong>3. job_finder.rs</strong></p><p>This module contains the core logic for finding matching jobs based on skills. It uses a graph-based approach:</p><ul><li>The find_jobs function takes a graph representation of jobs and skills, and a list of candidate skills.</li><li>It finds jobs that match each skill and ranks them based on the number of matching skills.</li><li>The function returns a sorted list of job nodes, with the best matches first.</li></ul><pre>use itertools::Itertools;<br>use petgraph::graph::NodeIndex;<br>use petgraph::visit::EdgeRef;<br>use petgraph::Direction::Incoming;<br>use petgraph::{Directed, Graph};<br>use std::collections::HashMap;<br><br>pub(crate) fn find_jobs(<br>    graph: Graph&lt;String, &amp;str, Directed&gt;,<br>    skills: Vec&lt;String&gt;,<br>) -&gt; Vec&lt;NodeIndex&gt; {<br>    fn find_jobs_with_skill(graph: &amp;Graph&lt;String, &amp;str, Directed&gt;, skill: &amp;str) -&gt; Vec&lt;NodeIndex&gt; {<br>        let mut jobs_idxs = Vec::new();<br>        for node in graph.node_indices() {<br>            if graph[node].trim() == skill {<br>                for edge in graph.edges_directed(node, Incoming) {<br>                    jobs_idxs.push(edge.source());<br>                }<br>            }<br>        }<br>        jobs_idxs<br>    }<br><br>    // For each skill in the candidate&#39;s skill set, call the function and store the jobs<br>    let mut job_matches: HashMap&lt;NodeIndex, usize&gt; = HashMap::new();<br>    for skill in skills {<br>        let jobs_idxs = find_jobs_with_skill(&amp;graph, &amp;skill);<br>        for node_idx in jobs_idxs {<br>            *job_matches.entry(node_idx).or_insert(0) += 1;<br>        }<br>    }<br><br>    let mut job_matches: Vec&lt;(NodeIndex, usize)&gt; = job_matches.into_iter().collect();<br>    job_matches.sort_by(|a, b| b.1.cmp(&amp;a.1));<br><br>    let matched_job_nodes: Vec&lt;NodeIndex&gt; = job_matches<br>        .into_iter()<br>        .sorted_by(|a, b| b.1.cmp(&amp;a.1))<br>        .map(|(node, _)| node)<br>        .collect();<br><br>    matched_job_nodes<br>}</pre><p><strong>4. driver.rs</strong></p><p>This method demonstrates a simple blueprint for creating and searching a graph based on job data. The graph construction and skill searching are kept straightforward for illustration purposes. In a real-world scenario, you might need to handle more complex relationships and data structures.</p><pre>use aws_config;<br>use aws_sdk_s3 as s3;<br>use csv::Reader;<br>use futures::TryStreamExt;<br>use petgraph::graph::NodeIndex;<br>use petgraph::{Directed, Graph};<br>use std::collections::HashMap;<br>use std::io::Cursor;<br>use std::sync::Arc;<br>use tokio::sync::OnceCell;<br><br>use crate::job_finder::find_jobs;<br>use crate::jobs::Job;<br><br>// Initialize the S3 client once (outside the function)<br>static S3_CLIENT: OnceCell&lt;Arc&lt;s3::Client&gt;&gt; = OnceCell::const_new();<br><br>async fn initialize_s3_client() -&gt; Arc&lt;s3::Client&gt; {<br>    let shared_config = aws_config::load_from_env().await;<br>    let client = s3::Client::new(&amp;shared_config);<br>    Arc::new(client)<br>}<br><br>async fn get_s3_client() -&gt; Arc&lt;s3::Client&gt; {<br>    S3_CLIENT.get_or_init(initialize_s3_client).await.clone()<br>}<br><br>pub(crate) async fn execute(input_words: Vec&lt;String&gt;) -&gt; Result&lt;Vec&lt;Job&gt;, Box&lt;dyn std::error::Error&gt;&gt; {<br>    let mut data = get_data_from_s3().await?;<br>    let mut graph = Graph::&lt;String, &amp;str, Directed&gt;::new();<br>    let mut nodes: HashMap&lt;String, NodeIndex&gt; = HashMap::new();<br>    let mut job_mappings: HashMap&lt;String, Job&gt; = HashMap::new();<br><br>    for result in data.deserialize() {<br>        let job: Job = result?;<br>        job_mappings.insert(job.id.clone(), job.clone());<br>        let job_node = *nodes<br>            .entry(job.id.clone())<br>            .or_insert_with(|| graph.add_node(job.id.clone()));<br><br>        let job_location = job.location.clone();<br>        let location_node = *nodes<br>            .entry(job_location.clone())<br>            .or_insert_with(|| graph.add_node(job_location));<br>        graph.add_edge(job_node, location_node, &quot;preferred&quot;);<br><br>        for skill in job.required_skills.split(&quot;,&quot;) {<br>            let trimmed_skill = skill.trim().to_string();<br>            let skill_node = *nodes<br>                .entry(trimmed_skill.clone())<br>                .or_insert_with(|| graph.add_node(trimmed_skill.clone()));<br>            graph.add_edge(job_node, skill_node, &quot;required&quot;);<br>            graph.add_edge(job_node, skill_node, &quot;preferred&quot;);<br>        }<br><br>        for skill in job.preferred_skills.split(&quot;,&quot;) {<br>            let trimmed_skill = skill.trim().to_string();<br>            let skill_node = *nodes<br>                .entry(trimmed_skill.clone())<br>                .or_insert_with(|| graph.add_node(trimmed_skill.clone()));<br>            graph.add_edge(job_node, skill_node, &quot;preferred&quot;);<br>        }<br>    }<br><br>    let matched_node_idxs = find_jobs(graph.clone(), input_words);<br><br>    let matched_jobs: Vec&lt;Job&gt; = matched_node_idxs<br>        .into_iter()<br>        .filter_map(|node_idx| {<br>            let job_id = &amp;graph[node_idx];<br>            job_mappings.get(job_id)<br>        })<br>        .cloned()<br>        .collect();<br><br>    return Ok(matched_jobs);<br>}<br><br>pub async fn get_data_from_s3() -&gt; Result&lt;Reader&lt;Cursor&lt;Vec&lt;u8&gt;&gt;&gt;, Box&lt;dyn std::error::Error&gt;&gt; {<br>    // Create an S3 client<br>    let client = get_s3_client().await;<br><br>    let bucket = &quot;my-job-postings-unique-bucket-name&quot;;<br>    let key = &quot;*.csv&quot;;<br><br>    let resp = client.get_object().bucket(bucket).key(key).send().await?;<br><br>    let stream = resp.body;<br>    let buffer = stream.map_ok(|b| b.to_vec()).try_concat().await?;<br><br>    // Create a Cursor from the buffer and then a csv::Reader from the Cursor<br>    let cursor = Cursor::new(buffer);<br>    let reader = Reader::from_reader(cursor);<br><br>    Ok(reader)<br>}</pre><p>For the the following variables from the code extract above</p><pre>let bucket = &quot;my-job-postings-unique-bucket-name&quot;;<br>let key = &quot;*.csv&quot;;</pre><p>Provide the names of the S3 bucket and CSV file that you uploaded previously.</p><p>This module orchestrates the job-matching process and demonstrates interaction with AWS services:</p><ul><li>It initializes an S3 client to fetch job data from an S3 bucket, showcasing how to interact with a core AWS service in Rust.</li><li>The execute function builds a graph representation of jobs and skills from CSV data stored in S3.</li><li>It then calls the find_jobs function from job_finder.rs to match the input skills against the job graph.</li><li>Finally, it returns a list of matched Job structs.</li></ul><p><strong>Important Notes on Architecture and Software Implementations:</strong> While this example uses S3 to store and retrieve job data, it’s crucial to understand that this approach has limitations in a serverless context:</p><ol><li><strong>Cold Start Impact:</strong> Initializing the S3 client for every cold start can introduce latency and increase execution time, potentially affecting both performance and costs.</li><li><strong>Scalability Concerns:</strong> As the job dataset grows, fetching and processing all data for each request may become inefficient.</li><li><strong>Demonstration Purpose:</strong> The S3 integration here primarily serves to illustrate how to statically and lazily initialize an AWS SDK client (in this case, S3) using Rust. This pattern is valuable when working with various AWS services in Rust applications.</li><li><strong>Hard-Coding: </strong>Hard-coding the name of the object key is also not the best strategy from an implementation perspective. Keep in mind this is a demo</li><li><strong>Error Handling: </strong>Throughout the code examples, you may notice the use of unwrap(). It&#39;s important to emphasize that this approach to error handling is not recommended for production code. The unwrap() method is used here for simplicity and brevity, but it can lead to panics if an error occurs, potentially crashing your Lambda function. In a production environment, proper error handling is crucial. Please review the <a href="https://doc.rust-lang.org/book/ch09-00-error-handling.html">Rust documentation for appropriate error handling</a>. These practices ensure that your code gracefully handles unexpected situations, provides meaningful error messages, and maintains stability in a production setting. The use of unwrap() in this demo serves to keep the code concise and focused on the main concepts being illustrated. When adapting this code for real-world use, replacing these unwrap() calls with proper error handling should be a priority.</li><li><strong>Clone Optimization:</strong> The use of clone() in the demo code can also be optimized. While cloning is a convenient way to create copies of data, it can lead to unnecessary memory usage and performance degradation, especially for larger data structures. In a production environment, it&#39;s important to carefully consider when to use clone() and explore alternative approaches, such as borrowing or using reference-counted types like Rc or Arc, to minimize unnecessary copying and improve the overall efficiency of the application.</li></ol><p><strong>Real-World Scalable Solution:</strong> For a production-grade, scalable job recommendation system, consider these alternatives:</p><ol><li><strong>Amazon Neptune:</strong> A fully managed graph database service that would be ideal for storing and querying the job-skill relationships efficiently.</li><li><strong>DynamoDB:</strong> For faster data retrieval and better scalability in a serverless environment.</li><li><strong>ElastiCache:</strong> To cache frequently accessed data and reduce database load.</li><li><strong>API Gateway with VPC Link:</strong> To securely connect your Lambda function to resources in a VPC, such as a database, without exposing them to the public internet.</li></ol><p>By showcasing the S3 integration, this example provides a starting point for understanding AWS service interactions in Rust. However, in a real-world scenario, the architecture would need to be adapted based on specific performance, scalability, and cost requirements.</p><h3>Deploying to AWS</h3><h3>Building and deploying your Lambda functions</h3><p>If you already have Cargo Lambda installed in your machine, run the next command to build your function and to zip it up:</p><p>Don’t forget ( — — release)</p><pre>cargo lambda build --release --x86-64 --output-format zip</pre><p>The Zip binary will be stored in fileb://target/lambda/suitable_jobs/bootstrap.zip</p><p>There are other ways of building your function: manually with the AWS CLI, with <a href="https://github.com/aws/aws-sam-cli">AWS SAM</a>, and with the <a href="https://serverless.com/framework/">Serverless framework</a>.</p><p>Before deploying to our AWS accounts, we need to ensure we have a suitable role to execute the deployment. Below is a sample role with few permissive permissions to get the ball rolling:</p><p><strong>Attached Policies: </strong>AWS managed policies are predefined permissions created and maintained by AWS, while customer managed policies are custom policies that you create and manage within your AWS account to tailor permissions based on your specific needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-P9u-nrWEDDMknoINVb0Lw.png" /></figure><p>AmazonS3ReadOnlyAccess role is an AWS managed role and can be selected from the console or attached via the CLI.</p><p>The <strong>AWSLambdaBasicExecutionRole</strong> from above has the following template:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;logs:CreateLogGroup&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:logs:us-east-1:&lt;aws_account_id&gt;:*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;logs:CreateLogStream&quot;,<br>                &quot;logs:PutLogEvents&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:logs:us-east-1:&lt;aws_account_id&gt;:log-group:/aws/lambda/suitable_jobs:*&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p><strong>Trust Policy: </strong><a href="https://aws.amazon.com/blogs/security/how-to-use-trust-policies-with-iam-roles/">An AWS trust policy defines which principals (such as users, services, or accounts) can assume an IAM role, and under what conditions</a>. Essentially, it specifies who is allowed to take on the permissions associated with a particular role.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;Service&quot;: &quot;lambda.amazonaws.com&quot;<br>            },<br>            &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>        }<br>    ]<br>}</pre><p>Once the above has been created we can go ahead and run the following command from the CLI (<a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">Assuming you have already installed and configured the AWS CLI</a>):</p><pre>aws lambda create-function --function-name suitable-jobs \<br>  --handler bootstrap \<br>  --zip-file fileb://target/lambda/suitable_jobs/bootstrap.zip \<br>  --runtime provided.al2023 \<br>  --role &lt;role arn created above&gt;\<br>  --environment Variables={RUST_BACKTRACE=1} \<br>  --tracing-config Mode=Active</pre><h3>Setup API Gateway</h3><p><strong>Note: </strong>This setup configures API Gateway without authentication for simplicity. In a production environment,<strong> you should implement proper authentication and authorization mechanisms to secure your API</strong> and protect sensitive data. Options include API keys, AWS Cognito, IAM roles, OAuth 2.0, or custom Lambda authorizers, depending on your security requirements.</p><h4>1. Create the REST API</h4><pre>aws apigateway create-rest-api --name &quot;SuitableJobsAPI&quot; --description &quot;API for Suitable Jobs Lambda Function&quot;</pre><p>Note the API ID from the output.</p><h4>2. Get the root resource ID</h4><pre>aws apigateway get-resources --rest-api-id &lt;your-api-id&gt;</pre><p>Note the root resource ID.</p><h4>3. Create a resource</h4><pre>aws apigateway create-resource --rest-api-id &lt;your-api-id&gt; --parent-id &lt;root-resource-id&gt; --path-part &quot;suitable-jobs&quot;</pre><p>Note the resource ID from the output.</p><h4>4. Create a POST method</h4><pre>aws apigateway put-method --rest-api-id &lt;your-api-id&gt; --resource-id &lt;resource-id&gt; --http-method POST --authorization-type NONE</pre><p>We’re using POST here because:</p><ul><li>The API receives parsed CV data from the client, which is best sent in the request body.</li><li>POST is suitable for operations that create or generate new data (in this case, job suggestions).</li><li>It allows for sending larger amounts of data compared to GET, which is important for detailed CV information.</li><li>The operation isn’t idempotent</li></ul><h4>5. Set up Lambda integration</h4><pre>aws apigateway put-integration --rest-api-id &lt;your-api-id&gt; --resource-id &lt;resource-id&gt; --http-method POST --type AWS_PROXY --integration-http-method POST --uri arn:aws:apigateway:&lt;region&gt;:lambda:path/2015-03-31/functions/arn:aws:lambda:&lt;region&gt;:&lt;account-id&gt;:function:suitable-jobs/invocations</pre><h4>6. Grant API Gateway permission to invoke your Lambda function</h4><pre>aws lambda add-permission --function-name suitable-jobs --statement-id apigateway-test --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn &quot;arn:aws:execute-api:&lt;region&gt;:&lt;account-id&gt;:&lt;your-api-id&gt;/*/POST/suitable-jobs&quot;</pre><h4><strong>7. CORS Configuration</strong></h4><p>CORS (Cross-Origin Resource Sharing) headers are required when integrating an API Gateway with a Lambda function because of the same-origin policy enforced by web browsers. The same-origin policy is a security mechanism that prevents a web page or application from making requests to a different domain than the one it was loaded from.</p><p>When a client (such as a web browser) makes a request to an API hosted on a different domain, the browser will first send an HTTP OPTIONS request to the API to check if the request is allowed. This is known as a “preflight” request. The API must respond to the OPTIONS request with the appropriate CORS headers, such as “Access-Control-Allow-Origin” and “Access-Control-Allow-Methods”, to indicate which origins and HTTP methods are allowed. This allows the browser to determine if the cross-origin request is permitted before sending the actual request. Implementing the correct CORS headers in the API Gateway and Lambda integration is essential to ensure that the cross-origin requests are properly handled and the API is accessible from the intended client applications.</p><p>7.1 Create the OPTIONS Method</p><pre>aws apigateway put-method \<br>    --rest-api-id &lt;your-api-id&gt; \<br>    --resource-id &lt;resource-id&gt; \<br>    --http-method OPTIONS \<br>    --authorization-type NONE</pre><p>7.1.2 Set Up a Mock Integration for the OPTIONS Method</p><pre>aws apigateway put-integration \<br>    --rest-api-id &lt;your-api-id&gt; \<br>    --resource-id &lt;resource-id&gt; \<br>    --http-method OPTIONS \<br>    --type MOCK \<br>    --request-templates &#39;{&quot;application/json&quot;:&quot;{\&quot;statusCode\&quot;: 200}&quot;}&#39;</pre><p>7.1.3 Add Response Headers to the OPTIONS Method</p><pre>aws apigateway put-method-response \<br>    --rest-api-id &lt;your-api-id&gt; \<br>    --resource-id &lt;resource-id&gt; \<br>    --http-method OPTIONS \<br>    --status-code 200 \<br>    --response-models &#39;{&quot;application/json&quot;: &quot;Empty&quot;}&#39; \<br>    --response-parameters &#39;{&quot;method.response.header.Access-Control-Allow-Headers&quot;: true, &quot;method.response.header.Access-Control-Allow-Methods&quot;: true, &quot;method.response.header.Access-Control-Allow-Origin&quot;: true}&#39;</pre><p>7.1.4 Add Integration Response Headers</p><pre>aws apigateway put-integration-response \<br>--rest-api-id &lt;your-api-id&gt; \<br>--resource-id &lt;resource-id&gt; \<br>--http-method OPTIONS \<br>--status-code 200 \<br>--response-templates &#39;{&quot;application/json&quot;: &quot;&quot;}&#39; \<br>--response-parameters &quot;{\&quot;method.response.header.Access-Control-Allow-Headers\&quot;:\&quot;&#39;Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token&#39;\&quot;,\&quot;method.response.header.Access-Control-Allow-Methods\&quot;:\&quot;&#39;OPTIONS,POST,GET&#39;\&quot;,\&quot;method.response.header.Access-Control-Allow-Origin\&quot;:\&quot;&#39;*&#39;\&quot;}&quot;</pre><p>7.2 Configure CORS Headers for POST</p><p>7.2.1 Add Response Headers to the POST Method</p><pre>aws apigateway put-method-response \<br>    --rest-api-id &lt;your-api-id&gt; \<br>    --resource-id &lt;resource-id&gt; \<br>    --http-method POST \<br>    --status-code 200 \<br>    --response-parameters &#39;{&quot;method.response.header.Access-Control-Allow-Headers&quot;: true, &quot;method.response.header.Access-Control-Allow-Methods&quot;: true, &quot;method.response.header.Access-Control-Allow-Origin&quot;: true}&#39;</pre><p>7.2.2 Add Integration Response Headers</p><pre>aws apigateway put-integration-response \<br>    --rest-api-id &lt;your-api-id&gt; \<br>    --resource-id &lt;resource-id&gt; \<br>    --http-method POST \<br>    --status-code 200 \<br>    --response-templates &#39;{&quot;application/json&quot;: &quot;&quot;}&#39; \<br>    --response-parameters &quot;{\&quot;method.response.header.Access-Control-Allow-Headers\&quot;:\&quot;&#39;Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token&#39;\&quot;,\&quot;method.response.header.Access-Control-Allow-Methods\&quot;:\&quot;&#39;OPTIONS,POST,GET&#39;\&quot;,\&quot;method.response.header.Access-Control-Allow-Origin\&quot;:\&quot;&#39;*&#39;\&quot;}&quot;</pre><h4>8. Create a deployment</h4><pre>aws apigateway create-deployment --rest-api-id &lt;your-api-id&gt; --stage-name alpha</pre><h4>8. Test the API</h4><p>You can now test the API using the following URL:</p><pre>https://&lt;api-id&gt;.execute-api.&lt;region&gt;.amazonaws.com/alpha/suitable-jobs</pre><p>Your API is now set up and linked to your Lambda function. You can send POST requests with parsed CV data to the URL from step 8 followed by “/suitable-jobs”. The Lambda function will process this data and return suggested jobs based on the CV information. In the next steps we will set up a basic frontend to simplify invocations.</p><h3>Deploy simple frontend hosted on S3</h3><p>Amazon S3 (Simple Storage Service) is a highly scalable and cost-effective object storage service provided by AWS. It can be used to host static websites, making it an excellent choice for deploying lightweight frontend applications.</p><p>In this section, we’ll guide you through the process of deploying a simple frontend application on Amazon S3. By the end of this walkthrough, you’ll have your application hosted on a secure, highly available, and globally accessible S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYGOncTZnt8ku9wskHWVFw.png" /></figure><h3>File Structure</h3><p>The file structure for our simple frontend application will look like this:</p><pre>&lt;unique bucket name&gt;/<br>├── index.html<br>├── css/<br>│   └── style.css<br>└── js/<br>    └── script.js</pre><p>The index.html file is the entry point of the application.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Resume Upload&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>    &lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-bs4.min.css&quot; rel=&quot;stylesheet&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;css/styles.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container mt-5&quot;&gt;<br>        &lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-12&quot;&gt;<br>                &lt;ul class=&quot;step d-flex justify-content-between&quot;&gt;<br>                    &lt;li class=&quot;step-item active&quot;&gt;<br>                        &lt;a href=&quot;#&quot;&gt;1&lt;/a&gt;<br>                        &lt;p&gt;Upload Resume&lt;/p&gt;<br>                    &lt;/li&gt;<br>                    &lt;li class=&quot;step-item&quot;&gt;<br>                        &lt;a href=&quot;#&quot;&gt;2&lt;/a&gt;<br>                        &lt;p&gt;View Matched Jobs&lt;/p&gt;<br>                    &lt;/li&gt;<br>                    &lt;li class=&quot;step-item&quot;&gt;<br>                        &lt;a href=&quot;#&quot;&gt;3&lt;/a&gt;<br>                        &lt;p&gt;View Results&lt;/p&gt;<br>                    &lt;/li&gt;<br>                &lt;/ul&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-12&quot;&gt;<br>                &lt;div class=&quot;upload-section p-5 border rounded&quot;&gt;<br>                    &lt;h2 class=&quot;mb-4&quot;&gt;Upload Your Resume&lt;/h2&gt;<br>                    &lt;p&gt;Upload your resume to get started&lt;/p&gt;<br>                    &lt;input type=&quot;file&quot; id=&quot;resumeUpload&quot; class=&quot;form-control mb-3&quot; accept=&quot;.pdf,.doc,.docx&quot;&gt;<br>                    &lt;div id=&quot;uploadedFileName&quot;&gt;&lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;row mt-5&quot;&gt;<br>            &lt;div class=&quot;col-12&quot;&gt;<br>                &lt;div id=&quot;parsedSkillsSection&quot;&gt;<br>                    &lt;h2&gt;Parsed Skills&lt;/h2&gt;<br>                    &lt;form&gt;<br>                        &lt;div class=&quot;form-group&quot;&gt;<br>                            &lt;textarea id=&quot;summernote&quot; name=&quot;editordata&quot;&gt;&lt;/textarea&gt;<br>                        &lt;/div&gt;<br>                        &lt;button type=&quot;button&quot; class=&quot;btn btn-primary&quot; id=&quot;sendButton&quot;&gt;Send Content&lt;/button&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;div id=&quot;apiResponse&quot; class=&quot;mt-3 p-3 border rounded&quot;&gt;<br>        &lt;!-- Your API response content goes here --&gt;<br>    &lt;/div&gt;<br><br>    &lt;script src=&quot;https://code.jquery.com/jquery-3.5.1.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-bs4.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/@aws-sdk/signature-v4@latest/dist/aws-sdk-signature-v4.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/@aws-crypto/sha256-browser@latest/dist/aws-crypto-sha256-browser.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;js/scripts.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/pako/2.0.3/pako.min.js&quot;&gt;&lt;/script&gt;<br><br>    &lt;script&gt;<br>    $(document).ready(function() {<br>        $(&#39;#summernote&#39;).summernote({<br>            placeholder: &#39;Edit your resume here...&#39;,<br>            tabsize: 2,<br>            height: 300,<br>            toolbar: [<br>                [&#39;style&#39;, [&#39;style&#39;]],<br>                [&#39;font&#39;, [&#39;bold&#39;, &#39;underline&#39;, &#39;clear&#39;]],<br>                [&#39;fontname&#39;, [&#39;fontname&#39;]],<br>                [&#39;color&#39;, [&#39;color&#39;]],<br>                [&#39;para&#39;, [&#39;ul&#39;, &#39;ol&#39;, &#39;paragraph&#39;]],<br>                [&#39;table&#39;, [&#39;table&#39;]],<br>                [&#39;insert&#39;, [&#39;link&#39;, &#39;picture&#39;, &#39;video&#39;]],<br>                [&#39;view&#39;, [&#39;fullscreen&#39;, &#39;codeview&#39;, &#39;help&#39;]]<br>            ]<br>        });<br><br>        // Handle send button click<br>        $(&#39;#sendButton&#39;).on(&#39;click&#39;, function() {<br>            var summernoteContent = $(&#39;#summernote&#39;).summernote(&#39;code&#39;);<br>            processResumeUpload(summernoteContent);<br>        });<br>    });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The css folder contains the main CSS file, style.css</p><pre>/* Existing CSS */<br>body {<br>    font-family: Arial, sans-serif;<br>}<br><br>.container {<br>    max-width: 1200px;<br>    margin: 0 auto;<br>}<br><br>.step {<br>    list-style: none;<br>    padding: 0;<br>    margin: 0;<br>}<br><br>.step-item {<br>    text-align: center;<br>    flex: 1;<br>}<br><br>.step-item.active-blue a {<br>    color: blue;<br>}<br><br>.step-item a {<br>    display: inline-block;<br>    width: 30px;<br>    height: 30px;<br>    line-height: 30px;<br>    border-radius: 50%;<br>    background: #ccc;<br>    color: #fff;<br>    text-decoration: none;<br>}<br><br>.step-item.active a {<br>    background: #0d6efd;<br>}<br><br>.step-item p {<br>    margin: 10px 0 0;<br>}<br><br>.upload-section {<br>    border: 2px dashed #0d6efd;<br>    text-align: center;<br>    padding: 30px;<br>    background-color: #f9f9f9;<br>    max-width: 800px;<br>    margin: 0 auto;<br>}<br><br>#uploadedFileName {<br>    margin-top: 10px;<br>}<br><br>#parsedSkillsSection, #apiResponse {<br>    max-width: 800px;<br>    margin: 0 auto;<br>}<br><br>.job-list {<br>    list-style: none;<br>    padding: 0;<br>    margin: 0;<br>}<br><br>.job-list-item {<br>    padding: 10px;<br>    border-bottom: 1px solid #ccc;<br>    background-color: #f9f9f9;<br>    margin-bottom: 10px;<br>    border-radius: 5px;<br>    list-style: none;<br>}<br><br>.job-list-item-title {<br>    font-weight: bold;<br>    color: #0d6efd;<br>    font-size: 1.2em;<br>}<br><br>.job-list-item-details {<br>    margin-left: 20px;<br>    list-style: none;<br>    padding: 0;<br>    color: #333;<br>    font-size: 0.9em;<br>}<br><br>.job-list-item-details li {<br>    margin-bottom: 5px;<br>    list-style: none;<br>}<br><br>.card-container {<br>    display: flex;<br>    flex-direction: column;<br>    gap: 20px;<br>    margin-top: 20px;<br>}<br><br>.job-card {<br>    background-color: #fff;<br>    border: 1px solid #ccc;<br>    border-radius: 5px;<br>    padding: 15px;<br>    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);<br>    width: 100%;<br>    max-height: 300px;<br>    overflow: hidden;<br>    display: flex;<br>    flex-direction: column;<br>    justify-content: space-between;<br>}<br><br>.job-card-title {<br>    font-size: 1.2em;<br>    color: #0056b3;<br>    margin-bottom: 10px;<br>    font-family: &#39;Arial&#39;, sans-serif;<br>}<br><br>.job-card-detail {<br>    margin-bottom: 5px;<br>    color: #333;<br>    font-family: &#39;Arial&#39;, sans-serif;<br>}<br><br>.job-card-detail strong {<br>    color: #0056b3;<br>}<br><br>.job-card-footer {<br>    margin-top: auto;<br>    text-align: right;<br>    font-size: 0.9em;<br>    color: #666;<br>}</pre><p>The js folder contains the main JavaScript file, script.js</p><pre><br>function handleFile(event) {<br>    const file = event.target.files[0];<br>    if (!file) {<br>        console.error(&#39;No file selected.&#39;);<br>        return;<br>    }<br><br>    // Read the file as ArrayBuffer<br>    const reader = new FileReader();<br>    reader.onload = function (event) {<br>        const arrayBuffer = event.target.result;<br><br>        // Load the PDF using PDF.js<br>        window.pdfjsLib.getDocument(arrayBuffer).promise.then(function (pdf) {<br>            // Fetch all pages<br>            let allPages = [];<br>            for(let i = 1; i &lt;= pdf.numPages; i++) {<br>                allPages.push(pdf.getPage(i));<br>            }<br>            return Promise.all(allPages).then(function(pages) {<br>                // Render each page as text content<br>                let allTextContent = pages.map(function(page) {<br>                    return page.getTextContent();<br>                });<br>                return Promise.all(allTextContent).then(function(textContents) {<br>                    // Extract text items from each page<br>                    const resumeString = textContents.map(function(textContent) {<br>                        return textContent.items.map(function(item) {<br>                            return item.str;<br>                        }).join(&#39; &#39;).replace(/\. /g, &#39;.\n&#39;);<br>                    }).join(&#39;\n\n&#39;); // Separate pages by two newlines<br><br>                    // Display the extracted text content<br>                    console.log(JSON.stringify({ resumeString }));<br><br>                    // Filter unwanted characters<br>                    let filteredResumeString = resumeString;<br><br>                    // Set cleaned text into Summernote<br>                    $(&#39;#summernote&#39;).summernote(&#39;code&#39;, filteredResumeString);<br>                });<br>            });<br>        }).catch(function (error) {<br>            console.error(&#39;Error loading PDF:&#39;, error);<br>        });<br>    };<br><br>    reader.readAsArrayBuffer(file);<br>}<br><br><br><br>// Event listener for file input change<br>document.getElementById(&#39;resumeUpload&#39;).addEventListener(&#39;change&#39;, handleFile);<br><br><br>function compressString(input) {<br>    // Convert input string to Uint8Array<br>    const byteArray = pako.deflate(input, { to: &#39;string&#39; });<br>    // Convert compressed Uint8Array back to a string<br>    const compressed = String.fromCharCode.apply(null, byteArray);<br><br>    return compressed;<br>}<br><br>function processResumeUpload(pdfString) {<br>    const apiUrl = &#39;&lt;your api gateway endpoint&gt;&#39;;<br>   <br>    // Create headers for the request<br>    const headers = {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        // Add other headers if required (e.g., Authorization)<br>    };<br><br>    // Prepare the request body<br>    const base64EncodedString = unicodeToBase64(pdfString);<br>    const requestBody = JSON.stringify({ base64EncodedString });<br><br>    // Make a POST request using fetch<br>    fetch(apiUrl, {<br>        method: &#39;POST&#39;,<br>        body: requestBody,<br>        headers: headers<br>    })<br>    .then(response =&gt; {<br>        if (!response.ok) {<br>            throw new Error(&#39;Network response was not ok&#39;);<br>        }<br>        return response.json();<br>    })<br>    .then(data =&gt; {<br>        console.log(&#39;API Response:&#39;, data);<br>        displayJobData(data);<br>        updateStepItems();<br>    })<br>    .catch(error =&gt; {<br>        console.error(&#39;Error sending request:&#39;, error);<br>    });<br>}<br><br>function displayJobData(data) {<br>    // Get the reference to the div where you want to display the data<br>    const apiResponseDiv = document.getElementById(&#39;apiResponse&#39;);<br><br>    // Create a card layout to display the data<br>    const cardContainer = document.createElement(&#39;div&#39;);<br>    cardContainer.className = &#39;card-container&#39;;<br><br>    // Loop through the API response and create a single card<br>    data.forEach((item, index) =&gt; {<br>        const card = document.createElement(&#39;div&#39;);<br>        card.className = &#39;job-card&#39;;<br><br>        const cardTitle = document.createElement(&#39;h3&#39;);<br>        cardTitle.className = &#39;job-card-title&#39;;<br>        cardTitle.textContent = `Job ${index + 1}: ${item.title}`;<br>        card.appendChild(cardTitle);<br><br>        for (const key in item) {<br>            if (key !== &#39;title&#39;) {<br>                const cardDetail = document.createElement(&#39;p&#39;);<br>                cardDetail.className = &#39;job-card-detail&#39;;<br>                cardDetail.innerHTML = `&lt;strong&gt;${key}:&lt;/strong&gt; ${item[key]}`;<br>                card.appendChild(cardDetail);<br>            }<br>        }<br><br>        const cardFooter = document.createElement(&#39;div&#39;);<br>        cardFooter.className = &#39;job-card-footer&#39;;<br>        cardFooter.textContent = &#39;More details...&#39;;<br>        card.appendChild(cardFooter);<br><br>        cardContainer.appendChild(card);<br>    });<br><br>    // Append the card container to the div<br>    apiResponseDiv.innerHTML = &#39;&#39;; // Clear previous content<br>    apiResponseDiv.appendChild(cardContainer);<br>}<br><br>function updateStepItems() {<br>    // Update the step items<br>    document.querySelector(&#39;.step-item.active&#39;).classList.remove(&#39;active&#39;);<br>    document.querySelector(&#39;.step-item:nth-child(2)&#39;).classList.add(&#39;active&#39;);<br>}<br><br>// Function to filter unwanted characters<br>function filterUnwantedCharacters(text) {<br>    // Replace bullet points with empty string<br>    text = text.replace(/•/g, &#39;&#39;);<br>    // Add more replacements as needed for other unwanted characters<br><br>    return text;<br>}<br><br>// Function to encode a Unicode string to Base64<br>function unicodeToBase64(str) {<br>    // Convert Unicode string to Uint8Array<br>    let binaryString = unescape(encodeURIComponent(str));<br>    let bytes = new Uint8Array(binaryString.length);<br>    for (let i = 0; i &lt; binaryString.length; i++) {<br>        bytes[i] = binaryString.charCodeAt(i);<br>    }<br>    // Encode using btoa (Base64)<br>    return btoa(String.fromCharCode.apply(null, bytes));<br>}</pre><h4>Creating the S3 Bucket</h4><p>To get started, we’ll use the AWS Command Line Interface (CLI) to create an S3 bucket for hosting our frontend application. Follow these steps:</p><p>Open your terminal or command prompt and ensure you have the AWS CLI installed and configured with your AWS credentials.</p><p>Run the following command to create a new S3 bucket:</p><pre>aws s3 mb s3://&lt;unique bucket name&gt;</pre><h4>Configuring the Bucket for Website Hosting</h4><p>Next, we’ll enable static website hosting for the S3 bucket:</p><p>Run the following command to configure the bucket for website hosting:</p><pre>aws s3 website s3://&lt;unique bucket name&gt; --index-document index.html --error-document index.html</pre><p>This command sets the index document to index.html and the error document to index.html (recommended for single-page applications).</p><h4>Configure the public access settings for the bucket</h4><pre>aws s3api put-public-access-block --bucket &lt;unique bucket name&gt; --public-access-block-configuration BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false</pre><p>This command ensures that the bucket allows public access, which is necessary for hosting a static website. By default, S3 buckets have some public access blocked to enhance security. However, for a static website, we need to allow public access so that users can view the website content.</p><p>The specific settings in this command allow:</p><ul><li>BlockPublicAcls=false: Allows adding public access control lists (ACLs) to the bucket.</li><li>IgnorePublicAcls=false: Allows honoring any public ACLs that have been applied to the object.</li><li>BlockPublicPolicy=false: Allows applying a bucket policy that grants public access.</li><li>RestrictPublicBuckets=false: Allows unrestricted public access to the bucket.</li></ul><h4>Attach the required bucket policy</h4><p>The bucket policy is necessary because, by default, S3 buckets are private, meaning that only the bucket owner has access to the objects stored in the bucket. To allow public access to the website, we need to create a bucket policy that grants the s3:GetObject permission to the public (represented by the &quot;Principal&quot;: &quot;*&quot;).</p><pre>aws s3api put-bucket-policy --bucket &lt;unique bucket name&gt; --policy &#39;{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: &quot;*&quot;,<br>      &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::&lt;unique bucket name&gt;/*&quot;<br>    }<br>  ]<br>}&#39;</pre><p>The policy statement allows any principal (basically anyone) to perform the s3:GetObject action on any object (represented by the &quot;Resource&quot;: &quot;arn:aws:s3:::&lt;unique bucket name&gt;/*&quot;) within the &lt;unique bucket name&gt; bucket.</p><h4>Uploading the Files</h4><p>With the S3 bucket configured for website hosting, we can now upload the files for our frontend application:</p><p><strong>Upload the files to the S3 bucket using the AWS CLI:</strong></p><p>Navigate into the directory that contain the respective files and folders. i.e. &lt;unique bucket name&gt; in this example</p><pre>&lt;unique bucket name&gt;/<br>├── index.html<br>├── css/<br>│   └── style.css<br>└── js/<br>    └── script.js</pre><pre>aws s3 sync . s3://&lt;unique bucket name&gt;</pre><p>This command will upload all the files in the &lt;unique bucket name&gt; directory to the S3 bucket.</p><p>Alternatively, you can use the AWS Management Console to upload the files by navigating to your S3 bucket and clicking on “Upload”.</p><h4>Accessing Your Website</h4><ol><li>Obtain the website endpoint URL from the S3 bucket’s “Properties” tab in the AWS Management Console (right at the bottom of the page at the time of posting this).</li><li>Copy this URL and paste it into your web browser to access your deployed frontend application.</li></ol><p>You’ve now successfully deployed a simple frontend application hosted on Amazon S3!</p><h3>Conclusion</h3><p>In this blog post, we’ve explored the development and performance of a CV-to-Job Matching tool, comparing implementations in Rust and Python within AWS Lambda. Our analysis revealed Rust’s significant advantages in serverless environments:</p><ol><li>Execution Time: Rust demonstrated substantially faster processing speeds.</li><li>Memory Usage: Rust exhibited more efficient memory management.</li><li>Cold Start Performance: Rusts cold start performance was faster than pythons warm starts.</li><li>CPU Utilization: Rust showed significantly lower CPU usage, indicating higher efficiency.</li><li>Network I/O: Rust displayed superior throughput and consistency in network operations.</li></ol><p>We then walked through the process of building and deploying the Rust version of this tool on AWS, including setting up a Lambda function, integrating with API Gateway, and creating a simple frontend hosted on S3.</p><p>I hope this article has provided valuable insights into leveraging Rust for serverless development, whether you’re looking to optimize performance of existing systems or for exploring new technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3db7a7b4c651" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>