<?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 Pathikreet Dutta on Medium]]></title>
        <description><![CDATA[Stories by Pathikreet Dutta on Medium]]></description>
        <link>https://medium.com/@pathikreet-dutta?source=rss-3c432a3850bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TVnlF1yPxR1L1unV</url>
            <title>Stories by Pathikreet Dutta on Medium</title>
            <link>https://medium.com/@pathikreet-dutta?source=rss-3c432a3850bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:28:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pathikreet-dutta/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[Why I’m Rethinking Traditional RBAC for Autonomous AI Agents]]></title>
            <link>https://pathikreet-dutta.medium.com/why-im-rethinking-traditional-rbac-for-autonomous-ai-agents-7904b2771d14?source=rss-3c432a3850bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7904b2771d14</guid>
            <category><![CDATA[ai-security]]></category>
            <category><![CDATA[agentic-ai-architecture]]></category>
            <category><![CDATA[ai-governance]]></category>
            <dc:creator><![CDATA[Pathikreet Dutta]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 17:39:40 GMT</pubDate>
            <atom:updated>2026-03-16T17:39:40.232Z</atom:updated>
            <content:encoded><![CDATA[<p>After months of designing enterprise AI agent systems, I’ve hit a recurring wall: traditional access control models simply don’t fit the reality of how autonomous agents operate. The deeper I dug, the clearer it became that we’re trying to force a square peg into a round hole — applying static, resource-centric permissions to systems whose behavior emerges dynamically through reasoning. Here’s where my thinking has landed, grounded in both hands-on experience and recent research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOvulO5hZUEpklUERRyaXw.png" /></figure><h3>The Core Misalignment: RBAC vs. Non-Deterministic Agents</h3><p>Role-Based Access Control (RBAC) assumes predictable resource needs. You define roles (e.g., “analyst,” “manager”), map them to static resources (databases, APIs), and assume users/stays within those bounds. But AI agents don’t work that way. Their reasoning process <em>determines</em> what resources they need in real time. An agent tasked with “identifying customer churn risks” might autonomously conclude it requires access to support ticket logs, payment histories, and even external social media data — none of which were in its original permission set.</p><p>This creates two untenable outcomes, as highlighted by the Cloud Security Alliance’s recent work on agentic systems:</p><ul><li><strong>Over-permissioning</strong>: Granting broad access “just in case” to cover unpredictable reasoning paths violates least privilege and exponentially increases attack surface.​</li><li><strong>Under-permissioning</strong>: Strictly limiting access to predefined resources blocks agents when their reasoning reveals legitimate, novel tool or data needs mid-workflow — causing silent failures or brittle workarounds.</li></ul><p>Worse, treating agents as mere service accounts ignores their fundamental distinction: service accounts follow pre-scripted workflows (e.g., a nightly backup job), while agents <em>generate their own access requirements through reasoning</em>. An agent authorized to “summarize quarterly sales” might independently decide it needs HR compensation data to explain anomalies — making static RBAC either blind to the new need or complicit in over-permissioning.​</p><h3>Shifting the Problem Plane: From Resource Access to Action Governance</h3><p>Some structure appeared when I flipped the question. Instead of asking, <em>“What resources can this agent access?”</em> I started asking:</p><ul><li><strong>“Who/what is this agent?”</strong> (Establishing verifiable Agent identity)</li><li><strong>“What specific actions is it permitted to take, and under what conditions?”</strong> (Governance through behavior, not static resources)</li></ul><p>This shift resolves the non-determinism problem by focusing on what the agent <em>does</em> rather than trying to predict what it <em>might need</em>. Here’s how I’m structuring this approach:</p><h3>1. Cryptographic Agent Identity as the Foundation (Zero Trust)</h3><p>Agents need non-human, cryptographically verifiable identities distinct from users or service accounts. This isn’t just about initial authentication — it enables continuous validation throughout the agent’s reasoning and execution lifecycle. If an agent’s identity can’t be cryptographically proven at every step, no access grant is trustworthy.</p><h3>2. Action-Scoped Privileges, Not Resource Grants</h3><p>Permissions are tied to <em>specific, pre-defined operations</em> — not broad resource access. For example:</p><ul><li><strong>Permitted</strong>: “Generate and email the monthly sales report to the regional manager”</li><li><strong>Not permitted</strong>: “Query any table in the sales database” or “Make external API calls”</li></ul><p>This implements <em>true least privilege</em>: the agent possesses only the privileges necessary for its immediate, contextual task — nothing more. Critically, for high-risk agents, I strip capabilities like data modification, system administration, or external communications entirely. If an agent literally <em>cannot</em> write to a database or call a sensitive API, no amount of prompt injection or tool chaining can create that capability — the attack surface is reduced to zero for those vectors.​</p><h3>3. Layered Defenses for Deterministic Control</h3><p>To counter reasoning-driven bypass attempts (agents “hacking in” to achieve goals), we can layer these controls:</p><ul><li><strong>Runtime Behavioral Monitoring</strong>: Baselines for expected action sequences, tool usage, and operational velocity. Deviations (e.g., sudden novel API chains or high-frequency requests) trigger intervention.</li><li><strong>Input/Output Guardrails</strong>: Specialized models inspect prompts/responses for injection attempts or PII leakage <em>before</em> they reach the LLM or are returned — Databricks showed this reduces prompt injection success by 90%+ when combined with access limits.</li><li><strong>Reasoning-Trace Logging</strong>: Recording not just <em>what</em> the agent did, but <em>why</em> (its intermediate steps) enables forensic analysis to distinguish legitimate problem-solving from attack sequences.​</li><li><strong>Policy-as-Code Enforcement</strong>: Using languages like Oso Polar or OPA Rego to express context-dependent, action-scoped rules that are testable, versionable, and auditable.​</li></ul><h3>Why This Creates Genuine Security Boundaries</h3><p>By defining the <em>exact set of actions</em> an agent is permitted to perform (and removing all others), we create a hard boundary:</p><ul><li>If “delete customer records” isn’t in the agent’s permitted action set, no amount of reasoning, prompt injection, or tool misuse can make it happen — the capability doesn’t exist in the agent’s execution environment.</li><li>This shifts security from <em>hoping the agent won’t misuse access</em> to <em>ensuring it fundamentally lacks the access to misuse</em>.</li></ul><h3>Practical Tensions I’m Navigating</h3><p>This isn’t theoretical — it’s reshaping how I build agent systems. Key realities I’m wrestling with:</p><ul><li><strong>Action Scope Granularity</strong>: Too broad (“access sales data”) recreates over-permissioning risks; too narrow (“run this exact SQL query”) breaks agent adaptability. I’m mapping common workflows to permitted action patterns to find the sweet spot.​</li><li><strong>Contextual Policy Evolution</strong>: Permissions must adapt to context (e.g., an agent might access PII only during verified customer support tickets, not during general data exploration).</li><li><strong>Agent-to-Agent Security</strong>: Extending identity and action governance to secure interactions in multi-agent systems remains an open challenge.​</li><li><strong>Enterprise IAM Integration</strong>: Leveraging providers like Okta or Azure AD while extending them with agent-specific capabilities requires careful design.</li></ul><h3>Moving Forward: From Concept to Codified Practice</h3><p>This shift isn’t just academic — it’s being actively shaped by frameworks from Oso, Okta, the Cloud Security Alliance, and emerging standards like the OpenID Foundation’s work on agentic identity. My next steps involve:</p><ul><li>Defining and validating action scopes that are both secure and practically useful for complex agent workflows</li><li>Building or adapting tooling for policy-as-code enforcement tailored to AI agent behaviors</li><li>Measuring effectiveness through balanced metrics: security (reduced attack surface, blocked misuse) <em>and</em> utility (agent success rates, workflow completion times)</li></ul><p>The goal isn’t to constrain agent autonomy — it’s to channel it securely so these systems can operate independently <em>without</em> becoming liabilities. If we get this right, we unlock the true promise of agentic AI: systems that reason, adapt, and act with purpose — within boundaries we can trust.</p><p><em>What’s your take? Have you encountered similar access control challenges in your agent implementations? I’m particularly interested in how teams are defining action scopes in practice and where policy-as-code tools are falling short.</em></p><p><em>[This piece reflects my ongoing exploration of secure AI agent design. Part 2 will dive into concrete frameworks for action scope definition and policy enforcement.]</em></p><h3>References</h3><ol><li>Oso: “Why RBAC is Not Enough for AI Agents”<br><a href="https://www.osohq.com/learn/why-rbac-is-not-enough-for-ai-agents">https://www.osohq.com/learn/why-rbac-is-not-enough-for-ai-agents</a></li><li>Protecto: “Role-Based Access Control for AI Agents”<br><a href="https://www.protecto.ai/solutions/agentic-ai-rbac-for-agents/">https://www.protecto.ai/solutions/agentic-ai-rbac-for-agents/</a></li><li>NeuralTrust: “Why AI Agents need RBAC?”<br><a href="https://neuraltrust.ai/blog/rbac-ai-agents">https://neuraltrust.ai/blog/rbac-ai-agents</a></li><li>Oso: “Best Practices of Authorizing AI Agents”<br><a href="https://www.osohq.com/learn/best-practices-of-authorizing-ai-agents">https://www.osohq.com/learn/best-practices-of-authorizing-ai-agents</a></li><li>Token.Security: “Why AI Agent Identity Is the New Control Plane for Enterprise Security”<br><a href="https://www.token.security/blog/why-ai-agent-identity-is-the-new-control-plane-for-enterprise-security">https://www.token.security/blog/why-ai-agent-identity-is-the-new-control-plane-for-enterprise-security</a></li><li>Curity: “Identity and Access Management for AI Agents”<br><a href="https://curity.io/blog/identity-and-access-management-for-AI-agents/">https://curity.io/blog/identity-and-access-management-for-AI-agents/</a></li><li>OpenID Foundation: “Identity Management for Agentic AI” (PDF)<br><a href="https://openid.net/wp-content/uploads/2025/10/Identity-Management-for-Agentic-AI.pdf">https://openid.net/wp-content/uploads/2025/10/Identity-Management-for-Agentic-AI.pdf</a></li><li>Okta: “What is AI agent identity? Securing autonomous systems”<br><a href="https://www.okta.com/identity-101/what-is-ai-agent-identity/">https://www.okta.com/identity-101/what-is-ai-agent-identity/</a></li><li>Cloud Security Alliance: “Agentic AI Identity and Access Management: A New Approach”<br><a href="https://www.cloudsecurityalliance.org/artifacts/agentic-ai-identity-and-access-management-a-new-approach">https://www.cloudsecurityalliance.org/artifacts/agentic-ai-identity-and-access-management-a-new-approach</a></li><li>LinkedIn: “The ‘Service Account’ Trap: Why Treating AI Agents as just another…”<br><a href="https://www.linkedin.com/pulse/service-account-trap-why-treating-ai-agents-just-another-filip-verloy-etfve">https://www.linkedin.com/pulse/service-account-trap-why-treating-ai-agents-just-another-filip-verloy-etfve</a></li><li>Databricks: “Mitigating The Risk of Prompt Injection for AI Agents on Databricks”<br><a href="https://www.databricks.com/blog/mitigating-risk-prompt-injection-ai-agents-databricks">https://www.databricks.com/blog/mitigating-risk-prompt-injection-ai-agents-databricks</a></li><li>OpenAI: “Designing AI agents to resist prompt injection”<br><a href="https://openai.com/index/designing-agents-to-resist-prompt-injection/">https://openai.com/index/designing-agents-to-resist-prompt-injection/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7904b2771d14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying the Agentic AI Landscape: LLM-Based Agents, Model Context Protocol (MCP), and Beyond]]></title>
            <link>https://pathikreet-dutta.medium.com/demystifying-the-agentic-ai-landscape-llm-based-agents-model-context-protocol-mcp-and-beyond-16673216909b?source=rss-3c432a3850bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/16673216909b</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Pathikreet Dutta]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 06:58:39 GMT</pubDate>
            <atom:updated>2025-09-14T06:58:39.427Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Pathikreet Dutta</em></p><h3>Introduction</h3><p>The agentic AI landscape is rapidly evolving, with <strong>LLM-based agents</strong> now capable of sophisticated, autonomous workflows. A key enabler of this shift is the <strong>Model Context Protocol (MCP)</strong>, which standardizes how LLMs access external data, tools, and resources. This post explores how MCP works, how it fits into agentic AI architectures, and how it helps reduce hallucinations by giving LLMs reliable, structured access to the world.</p><h3>What is Agentic AI?</h3><p><strong>Agentic AI</strong> refers to systems that are goal driven where LLMs or other models can:</p><ul><li>Autonomously plan and execute tasks,</li><li>Interact with users and systems,</li><li>Adapt to new information and goals.</li><li>Unlike static automation, agentic AI leverages dynamic reasoning, decision-making, and tool use.</li></ul><h3>The Model Context Protocol (MCP): A Universal Context Bridge</h3><p>MCP is an open protocol for exposing capabilities — like tools, data resources, and prompts — from “servers” to AI “hosts” that mediate LLM interactions. It aims to simplify capability discovery and invocation across diverse backends without locking into a single vendor or SDK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*pmE5emd3YWAmeDEn.png" /></figure><h3>Key Roles in MCP</h3><ul><li><strong>Host Application(AI Agent)</strong>: The agent runtime that integrates an LLM and orchestrates external capability use through an MCP client.</li><li><strong>MCP Client</strong>: Discovers server capabilities, negotiates protocol version and supported features during initialization, and invokes tools/resources/prompts.</li><li><strong>MCP Server</strong>: A modular provider exposing tools, resources, and prompts over the MCP interface; each server can wrap a database, file system, API, or specific tool.</li><li><strong>Orchestration</strong>: The host, guided by model outputs, instructs the MCP client to request context, tools, or data as needed; the model itself does not directly speak MCP.</li><li><strong>Communication</strong>: JSON-RPC 2.0 encodes requests, responses, and notifications over stdio or streamable HTTP/SSE transports.</li></ul><h3>How it works</h3><ul><li><strong>Capability discovery</strong>: The host queries connected servers to enumerate available tools/resources and supported features.</li><li><strong>Invocation and I/O</strong>: The host invokes tools with structured inputs and processes structured outputs (commonly JSON), enabling validation and deterministic routing.</li><li><strong>Transport</strong>: Requests, responses, and notifications follow a standardized schema (e.g., JSON-RPC 2.0 at the wire level), though the LLM itself typically interacts through the host rather than speaking the protocol directly.</li><li><strong>Extensibility</strong>: Multiple servers can be connected to a single host, and servers can internally call other services; chaining across servers is an architectural pattern rather than a protocol requirement.</li></ul><h3>Architectural patterns with MCP</h3><ul><li><em>Single host, multiple servers</em>: An agent runtime connects to several MCP servers (e.g., database access, file system, CRM), selecting capabilities per task.</li><li><em>Orchestrator-in-host</em>: Orchestration logic — planning, tool selection, retries, and validation — usually lives in the host, which can coordinate calls across servers.</li><li><em>Composable services</em>: A server may aggregate other services behind a single MCP interface, but this is a design choice, not mandated by MCP.</li><li><em>Deployment note</em>: Servers can be local via stdio or remote via streamable HTTP/SSE, with standard HTTP authentication and recommended OAuth flows for remote deployments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwDP2cTJnM00CjIZuRVFmQ.png" /><figcaption>Agentic AI Simplified Workflow</figcaption></figure><h3>Building Reliable Agentic AI with MCP</h3><p>Build reliable Agentic AI by connecting an agentic host to external systems via MCP servers that expose tools, resources, and prompts over an open, JSON-RPC–based protocol.</p><h4>Improving reliability and reducing hallucination</h4><ul><li><em>Grounded calls</em>: Invoking external tools/data can reduce hallucinations by anchoring outputs to evidence, but the effect size depends on retrieval, validation, and routing; hosts must implement these controls.</li><li><em>Structured outputs</em>: Tool responses are structured (e.g., JSON), supporting schema checks, type validation, and post-processing that improve determinism and auditability.</li><li><em>Dynamic Capability Discovery</em>: The AI agent learns exactly which tools/resources/prompts are available and their schemas, removing ambiguity about what exists and how to call it thus simplifying routing.</li></ul><blockquote><em>Note</em>: While MCP enables grounding and structure, reduction of hallucination depends on the host’s orchestration policies, validation, and how results are surfaced to the model.</blockquote><h4>Illustrative workflow</h4><ul><li><em>Request</em>: “Summarize the latest internal AI research.”</li><li><em>Discovery</em>: Host client uses tools/list and resources/list to enumerate a “papers” database tool/resource.</li><li><em>Retrieval and checks</em>: Host invokes the list-latest-papers tool, validates against the declared schema, and optionally filters/normalizes fields.</li><li><em>Grounded summarization</em>: Host adds retrieved records as context and prompts the model to summarize with citations.</li><li><em>Action</em>: Host invokes an email or ticketing MCP server with explicit parameters and logs the action.</li></ul><h4>Security, Consent, and Control</h4><p>MCP is designed with <strong>user consent, privacy, and security</strong> in mind:</p><ul><li><em>Explicit access</em>: Servers expose specific capabilities; the host decides if and when to invoke them, often gated by user consent and policy.</li><li><em>Data minimization</em>: Hosts should pass only needed parameters and redact or tokenize sensitive fields.</li><li>Audit/logging: Record capability discovery, tool invocations, parameters (appropriately redacted), results, and the initiating user for traceability; this is strongly recommended given demonstrated security risks like tool poisoning and code-execution abuse.</li></ul><h3>Conclusion</h3><p>MCP provides a consistent interface for hosts to discover and invoke external capabilities, helping agents perform grounded, auditable actions. Servers generally act as capability providers, while orchestration and policy live in the host. Used with validation and governance, MCP supports scalable and more reliable agentic AI without prescribing a single runtime or toolchain.</p><h3>Final Thoughts</h3><p><em>Agentic AI</em> is not science fiction. With MCP as a backbone, we can give language model agents safe, structured, and expansive access to the world.<br>The result? Smarter, safer, and far more useful AIs — ready for whatever you invent next.</p><h3>Further Reading</h3><ul><li><a href="http://modelcontextprotocol.io/">http://modelcontextprotocol.io/</a></li><li><a href="https://huggingface.co/learn/mcp-course/en/unit1/capabilities">https://huggingface.co/learn/mcp-course/en/unit1/capabilities</a></li><li><a href="https://arxiv.org/abs/2104.07567">https://arxiv.org/abs/2104.07567</a></li><li><a href="https://python.langchain.com/docs/">LangChain Documentation</a></li><li><a href="https://platform.openai.com/docs/guides/function-calling">OpenAI Function Calling</a></li><li><a href="https://www.pinecone.io/">Pinecone Vector Database</a></li><li><a href="https://devblogs.microsoft.com/blog/can-you-build-agent2agent-communication-on-mcp-yes">https://devblogs.microsoft.com/blog/can-you-build-agent2agent-communication-on-mcp-yes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16673216909b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure OIC APIs with OAuth2 using IDCS & OCI API Gateway]]></title>
            <link>https://pathikreet-dutta.medium.com/secure-oic-apis-with-oauth2-using-idcs-oci-api-gateway-dc487847b0ed?source=rss-3c432a3850bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc487847b0ed</guid>
            <category><![CDATA[oracle-integration-cloud]]></category>
            <category><![CDATA[oracle-cloud]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Pathikreet Dutta]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 12:53:27 GMT</pubDate>
            <atom:updated>2021-11-11T12:53:27.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*V3hf429h5t5hfNyqP1WI2A.png" /><figcaption>OAuth 2.0 Sequence of activities</figcaption></figure><p>Whenever we build any REST API on <strong>Oracle Integration Cloud (OIC)</strong>, one of the most underrated subjects of discussion is security of the APIs.</p><p>To secure REST APIs created in OIC, we can use either Basic authentication with service accounts or <a href="https://oauth.net/2/">OAuth 2.0</a> by leveraging <strong>Identity Cloud Service (IDCS)</strong>. We can configure IDCS to protect OIC REST API endpoints directly and thus there is no absolute need to use OCI API Gateway. But we had our reasons to leverage OCI API Gateway as mentioned below:</p><ul><li>With API Gateway, we are able to easily send the access logs to OCI Logging for easy log analytics. Also, it is very useful for metering your APIs, in case you are looking at monetizing your APIs.</li><li>With any suite of heterogeneous APIs, there are scenarios when a single task is achieved by multiple back end services (Microservices). In such cases, we can leverage OCI API Gateway to have a single front or facade for the entire task, also known as the <strong>API-Facade</strong> design pattern.</li><li>With OCI API Gateway, we also get the luxury of abstracting the actual OIC host name from other third parties.</li><li>OCI API Gateway also provides with a root CA TLS certificate by default, even if we do not specify a custom domain.</li><li>Using direct OAuth 2 with OIC and IDCS, we cannot limit access of the token to certain APIs. So anyone with a valid token, will be able to access all of the OIC REST APIs, which is not a secure design.</li></ul><h3>Methodologies</h3><p>To secure any OIC API using OAuth2.0 with IDCS and OCI API Gateway, there are a couple of design methodologies:</p><ul><li>Add OAuth 2 authentication and authorization on the OCI API Gateway layer and invoke the back end OIC APIs with basic credentials as Authorization header.</li><li>Use OAuth2 for both the OCI API Gateway layer as well as the OIC layer.</li></ul><p>The second option is more complex and involves the use of a custom authorization function as described here in this <a href="https://www.ateam-oracle.com/post/how-to-implement-an-oci-api-gateway-authorization-fn-in-nodejs-that-accesses-oci-resources">Oracle blog post</a> and is not in scope of this article.</p><p>We are going to see how to secure the APIs using the first methodology here.</p><h3>Prerequisites</h3><p>Before going any further, the follow should be completed.</p><ul><li>You have to use an identity provider (like IDCS, Auth0, AD, etc.) that can issue a <strong>JSON Web Tokens (JWT)</strong>.</li><li>Provision OCI API Gateway service as documented in this <a href="https://www.oracle.com/webfolder/technetwork/tutorials/infographics/oci_apigw_gs_quickview/apigw_quickview_top/apigw_quickview/index.html">Oracle Quick Start</a>.</li><li>Configure Authentication policy on you API Gateway deployment. Step by step detailed information is provided in this great <a href="https://mytechretreat.com/complete-guide-how-to-configure-oauth-2-0-with-jwt-idcs-on-oci-api-gateway/">guide</a>.</li></ul><h3>Setup</h3><p>Now that you have your OAuth2 setup done and Authentication policy is configured on OCI API Gateway deployment, we can go ahead and create the back end routes to OIC REST APIs with the Basic Authentication header.</p><blockquote>Login to <strong>OCI Console</strong> → <strong>Developer Services</strong> → <strong>API Management</strong> → <strong>Gateways</strong> → Select the Gateway → <strong>Deployments </strong>→ Select the Deployment → Click on Edit</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qas32OvG1Xlx1aKRL_P-Kg.png" /><figcaption>Routes Screen</figcaption></figure><blockquote>Click on <strong>Show Route Request Policies → Header Transformations → </strong>Click on <strong>Add → </strong>Set the header name as <strong>Authorization → </strong>Set the value as base64 encoded basic credentials. <strong>Format :</strong> Base64Encode(UserName:Password)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3cYpn8zvKtlx6se3J9N0Q.png" /></figure><blockquote><strong>Note :</strong> In OIC, it is mandatory to have an authentication mechanism. OIC does not allow turning off the authentication mechanism.</blockquote><p>Now we can add up to 50 different routes in the same deployment and we would need to add this Basic credentials in the Header transformation section of each route to authorize each API call.</p><p>Now if you save this and try to invoke the API by concatenating the endpoint of the deployment with the route path and the OAuth credentials, you should be able to see the response from your back end OIC REST APIs in Postman or any other API Client.</p><h3>Access Restriction</h3><p>As mentioned above, there is another very important benefit to using OCI API Gateway. We can restrict access to certain APIs using the OAuth scopes in API Gateway deployment itself.</p><p>To achieve the same, first make a list of all the scopes that have been exposed in the IDCS Resource Server Application.</p><blockquote>Now, go to <strong>OCI Console</strong> → <strong>Developer Services</strong> → <strong>API Management</strong> → <strong>Gateways</strong> → Select the Gateway → <strong>Deployments </strong>→ Select the Deployment → Click on Edit → Click on Edit in the <strong>Authentication Request Policy</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99PejBzaL0KhRGHp4n-_Cg.png" /></figure><blockquote>Click on the highlighted <strong>Show Advanced Options → </strong>Add <strong>scope </strong>as the Claim Key → Add all the scope values that we had copied earlier from IDCS Resource Application as separate entries in Claim Values → Click on <strong>Apply Changes</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IJp7w9mgu1LcupW6vw5qA.png" /></figure><blockquote><strong>Note:</strong> Currently we can only add up to 5 Claim Values.</blockquote><p>Go to the Next page → Click on <strong>Show Route Request Policies → Authorization → </strong>Click on <strong>Add → </strong>Select <strong>Any </strong>from the <strong>Type </strong>drop down → Add the scope from the above list that would have access to this route path → Click on <strong>Save Changes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVo_TAc7QD8-A_rXMCKx-Q.png" /></figure><p>Now we have successfully restricted access to the “/test” API. Clients who have access to the “/helloworld:read” scope as part of their client setup in IDCS Client Application will be able to access this API. All other clients, will get a <strong>HTTP 401 Unauthorized</strong> error.</p><h3>Conclusion</h3><p>With OCI API Gateway, we get a very powerful service which is cloud native and has very good support with other OCI Services. Due to the agnostic nature of the OCI API Gateway service, it helps in a very rapid setup of APIs and securing them is a breeze.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc487847b0ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Runtime Context object to access HTTP resources and pass custom configuration params to…]]></title>
            <link>https://pathikreet-dutta.medium.com/using-runtime-context-object-to-access-http-resources-and-pass-custom-configuration-params-to-2377ae6b6137?source=rss-3c432a3850bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2377ae6b6137</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[fn-project]]></category>
            <category><![CDATA[oracle-function]]></category>
            <category><![CDATA[oci]]></category>
            <dc:creator><![CDATA[Pathikreet Dutta]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 12:23:08 GMT</pubDate>
            <atom:updated>2021-05-08T09:26:52.412Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Runtime Context object to access HTTP resources and pass custom configuration params to Oracle FaaS (fn project)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*fyDbI4t9c8lT-WHo1zW9ew.png" /></figure><p>Oracle Functions is based on Fn Project. Fn Project is an open source, container native, serverless platform that can be run anywhere — any cloud or on-premises. Fn Project is easy to use, extensible, and performant. You can download and install the open source distribution of Fn Project, develop and test a function locally, and then use the same tooling to deploy that function to Oracle Functions.</p><p>You can access Oracle Functions using the Console, the CLI, and the REST API. You can invoke the functions you deploy to Oracle Functions using the Fn CLI or the OCI CLI or the OCI SDKs or by making signed HTTP requests or from other Oracle Cloud Services(see <a href="https://docs.oracle.com/en-us/iaas/Content/Functions/Tasks/functionsintegratingwithother.htm">how</a>).</p><p>The code in functions you deploy to Oracle Functions will typically require values for different parameters. Some pre-defined parameters are available to your functions as environment variables. But you’ll often want your functions to use parameters that you’ve defined yourself. Or you might even have a use case to access the HTTP resources. For example, you might have to access OCI Object storage to read / write some files. Or you might have to read the incoming HTTP request or set a custom response header or HTTP status code.</p><p>Here comes the Runtime Context Object to the rescue. This Context object (<strong>ctx</strong>) is an optional parameter that can be passed by the fn code to the callback function defined to handle the request.</p><p>In this article, we will learn how to leverage the ctx object in NodeJS. In NodeJS, a new function is initialized with a wrapper application called <em>func.js</em> by default. The image shows the creation of a new function and the contents of the wrapper function <em>func.js</em> that is generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*1CClkT7YHBMWpfWG-Sychg.png" /><figcaption>Credit: <a href="https://technology.amis.nl/author/lucas-jellema/"><em>Lucas Jellema</em></a></figcaption></figure><p>The <em>input</em> parameter that is defined in the callback function will be provided by the Fn framework when a request is handled. This parameter contains the HTTP Body of the request, typically JSON content in a POST request.</p><p>If we want to leverage the runtime context object (<strong>ctx</strong>), then we will need to add another <em>optional</em> input parameter to the callback function as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*J-0Euqj573iXqtk7JbvZmw.png" /><figcaption>Credit: <a href="https://technology.amis.nl/author/lucas-jellema/"><em>Lucas Jellema</em></a></figcaption></figure><p>This ctx object contains the complete Function invocation details. Click <a href="https://github.com/fnproject/fdk-node#function-context">here</a> for complete docs. The ctxobject contains other context information about the request such as:</p><ul><li>ctx.config : An Object containing function config variables (both environment and user defined) (read only)</li><li>ctx.headers : an object containing input headers for the event as lists of strings (read only)</li><li>ctx.deadline : a Date object indicating when the function call must be processed by</li><li>ctx.callID : The call ID of the current call</li><li>ctx.fnID : The Function ID of the current function</li><li>ctx.memory : Amount of ram in MB allocated to this function</li><li>ctx.contentType : The incoming request content type (if set, otherwise null)</li><li>ctx.setResponseHeader(key,values...) : Sets a response header to one or more values</li><li>ctx.addResponseHeader(key,values...) : Appends values to an existing response header</li><li>ctx.responseContentType : set/read the response content type of the function (read/write)</li><li>ctx.httpGateway : The HTTP Gateway context for this function (if set)</li></ul><p>As mentioned earlier, for this article we will cover 2 different use cases:</p><ol><li>Accessing HTTP resources and setting custom HTTP response codes.</li><li>Passing custom configuration parameters to function.</li></ol><h3>Accessing HTTP resources and setting custom HTTP response code</h3><p>To access HTTP resources (headers, method, etc.) we can leverage the HTTPGatewayContext(hctx) object from the Context(ctx) object. The HTTPGatewayContext object has a similar interface to Context but accesses only the HTTP headers of the function:</p><ul><li>hctx.requestURL : Get the http request URL of the function as received by the gateway (null if not set)</li><li>hctx.method : Get the HTTP request method used to invoke the gateway</li><li>hctx.headers : Get the HTTP headers of the incoming request (read-only)</li><li>hctx.statusCode : Set the the HTTP status code of the HTTP response</li><li>hctx.setResponseHeader(key,values..) : Set custom response headers as key/value pairs</li><li>hctx.addResponseHeader(key,values) : Set/add response header</li></ul><p>We can access/read the HTTP headers, for example “Authorization”, using the hctx.headers method of the HTTPGatewayContext object as depicted below in the snippet:</p><pre>const fdk=require(&#39;<a href="http://twitter.com/fnproject/fdk">@fnproject/fdk</a>&#39;);</pre><pre>fdk.handle(function(input, ctx){<br>  <br>  let hctx = ctx.httpGateway;<br>  console.log(&quot;Request URL&quot; , hctx.requestURL);<br>  <br>  console.log(&quot;Authorization header:&quot; , hctx.getHeader(&quot;Authorization&quot;));<br>  console.log( hctx.headers); // prints e.g. { &quot;Content-Type&quot;: [&quot;application/json&quot;],&quot;Accept&quot;:[&quot;application/json&quot;,&quot;text/plain&quot;] } <br>});</pre><p>We can also set the outbound response headers and the HTTP status code can be modified in a similar way:</p><pre>const fdk=require(&#39;@fnproject/fdk&#39;);<br><br>fdk.handle(function(input, ctx){<br>    let hctx = ctx.httpGateway;<br><br>   hctx.setResponseHeader(&quot;Location&quot;,&quot;http://example.com&quot;);<br>   hctx.statusCode = 201;<br>});</pre><p>Being able to set a custom HTTP response code is particularly helpful in custom validation and error handling within the function code. Let me explain the above statement.</p><p>If you invoke an Fn code via the signed HTTP request in OCI, Fn framework returns a HTTP response code in line with the execution of the Fn Code. This means that Fn server will throw back a HTTP response code just like any other HTTP server would. Now consider a use case where you need to call another REST based third party from within the Fn code. That third party API will return an HTTP response code. But Fn framework will not propagate the response code that it received from the third party. Instead it will overwrite that with its own response code. For example, your third party API can return a response code of 201 for a successful scenario, but the Fn framework will always return a status of 200 to your caller in this scenario. Thus you are not aware of the actual response code from the third party in your caller application.</p><p>To mitigate this roadblock, again HTTPGatewayContext object comes to play. We can leverage the hctx.statusCode method and set the response code received from the third party API in it. The Fn framework will then set this as a custom HTTP response header with the name as Fn-Http-Status.</p><p>Similarly, you can leverage the above technique for data validations and error handling as well. See below:</p><pre>const fdk=require(&#39;<a href="http://twitter.com/fnproject/fdk">@fnproject/fdk</a>&#39;);<br>const httpRequest = require(&#39;https&#39;);</pre><pre>fdk.handle(async (input, ctx) =&gt; {<br> let hctx = ctx.httpGateway;<br> let data = {<br>  title: &#39;foo&#39;,<br>  body: &#39;bar&#39;,<br>  userId: 1,<br>   };<br> <br> try{<br>  // Call ThirdParty API<br>  console.log(&#39;Calling Third Party API&#39;);<br>  const apiRes = await callThirdParty(data, &quot;<a href="https://jsonplaceholder.typicode.com/posts">https://jsonplaceholder.typicode.com/posts</a>&quot;, &quot;POST&quot;);<br>  <br>  //Set &quot;Fn-Http-Status&quot; as a custom HTTP response header<br>  hctx.statusCode = apiRes.status;<br>  return apiRes.payload;<br> } catch (error) {<br>  console.log(&#39;Promise Rejected Reason :: &#39;, error);<br>  //Set &quot;Fn-Http-Status&quot; Code as a response header<br>  hctx.statusCode = 500;<br>  return {<br>   &#39;Errors&#39;: {<br>    &#39;Error&#39;: [<br>     {<br>      &#39;ReasonCode&#39;: &#39;ORACLE-FN_INTERNAL_ERR&#39;,<br>      &#39;Description&#39;: error.stack<br>     }<br>    ]<br>   }<br>  };<br> }<br>});</pre><pre>async function callThirdParty(payload, uri, httpMethod) {<br>  return new Promise(function (resolve, reject) {<br>    let responseData = &#39;&#39;;<br>    <br>    var requestHeaders = {<br>      &#39;Content-Type&#39;: &#39;application/json; charset=UTF-8&#39;,<br>      &#39;Accept&#39;: &#39;application/json&#39;<br>    };<br>    <br>    const options = {<br>      method: httpMethod,<br>      headers: requestHeaders<br>    };</pre><pre>const request = httpRequest.request(uri, options, response =&gt; {<br>      console.log(&#39;Status : &#39;, response.statusCode);<br>      //console.log(&#39;Headers : &#39;, response.headers);</pre><pre>response.on(&#39;data&#39;, dataChunk =&gt; {<br>        responseData += dataChunk;<br>      });</pre><pre>response.on(&#39;end&#39;, () =&gt; {<br>        //console.log(&#39;Response :: &#39;, responseData);<br>        try {<br>          var apiResponse = {<br>            &#39;status&#39;: response.statusCode,<br>            &#39;headers&#39;: response.headers,<br>            &#39;payload&#39;: JSON.parse(responseData)<br>          };<br>          resolve(apiResponse);<br>        } catch (error) {<br>          //Handle all Non JSON responses returned for HTTP 5xx <br>          var errorResponse = {<br>            &#39;status&#39;: response.statusCode,<br>            &#39;error&#39;: error,<br>            &#39;payload&#39;: responseData<br>          };<br>          reject(errorResponse);<br>        }<br>        <br>      });<br>    });</pre><pre>request.on(&#39;error&#39;, error =&gt; {<br>      console.log(&#39;ERROR :: &#39;, error);<br>      reject(error);<br>    });</pre><pre>request.write(JSON.stringify(payload));<br>    request.end();<br>  });<br>};</pre><blockquote>Full example code repository: <a href="https://github.com/pathikreet/ocifunctions/tree/master/NodeJS/FnRuntimeContextSample">https://github.com/pathikreet/ocifunctions/tree/master/NodeJS/FnRuntimeContextSample</a></blockquote><h3>Passing custom configuration parameters to function</h3><p>While developing any solution or product, you might have come across a use cases to have some constant parameters that can be used across the application or the function.</p><p>Let us consider a use case where you need to connect to the OCI Private Object Storage to read/write a file in the Object Storage. Details on how to connect to OCI Private Object Storage from your running Fn container is not in scope of this article. In a nutshell you will need to use <em>Resource Principal</em> made available to your running functions container by OCI. Full demo code base for the same is attached below.</p><p>So to connect to OCI Object storage, the constant parameters that will be needed across all instances of your Fn container are <em>namespace</em> and <em>bucketName.</em> We can define these 2 constants a configuration parameters on either,</p><ul><li>application-wide, meaning they are passed to every function in an application</li><li>function-specific, meaning they are passed to the particular function for which they are defined (function-specific parameters override application-wide parameters with the same name)</li></ul><p>To create custom configuration parameters, you can use:</p><ul><li>the config: section of a function&#39;s func.yaml file, to define function-specific custom configuration parameters</li><li>the Console and the Fn Project CLI, to define both application-wide and function-specific custom configuration parameters</li></ul><p>Oracle Functions combines all the custom configuration parameters (both application-wide and function-specific) in the application into a single, serially-encoded configuration object with a maximum allowable size of 4Kb.</p><p>In this article, we will describe how to set custom configuration parameters using the OCI Console and subsequently how to access them in the Fn code using the ctx object.</p><blockquote>To check how to add configuration parameters using the Fn Project CLI or the OCI API click <a href="https://docs.oracle.com/en-us/iaas/Content/Functions/Tasks/functionspassingconfigparams.htm#usingfncli">here</a></blockquote><h4>Setting Configuration parameters using the OCI Console</h4><p>To specify custom configuration parameters to pass to functions using the Console:</p><ol><li>Log in to the Console as a functions developer.</li><li>In the Console, open the navigation menu. Under <strong>Solutions and Platform</strong>, go to <strong>Developer Services</strong> and click <strong>Functions</strong>.</li><li>Select the region you are using with Oracle Functions. Oracle recommends that you use the same region as the Docker registry that’s specified in the Fn Project CLI context (see <a href="https://docs.oracle.com/en-us/iaas/Content/Functions/Tasks/functionscreatefncontext.htm#Create_an_Fn_Project_CLI_Context_to_Connect_to_Oracle_Cloud_Infrastructure">6. Create an Fn Project CLI Context to Connect to Oracle Cloud Infrastructure</a>).</li><li>Select the compartment specified in the Fn Project CLI context (see <a href="https://docs.oracle.com/en-us/iaas/Content/Functions/Tasks/functionscreatefncontext.htm#Create_an_Fn_Project_CLI_Context_to_Connect_to_Oracle_Cloud_Infrastructure">6. Create an Fn Project CLI Context to Connect to Oracle Cloud Infrastructure</a>). The <strong>Applications</strong> page shows the applications defined in the compartment.</li><li>Click the name of the application containing functions to which you want to pass custom configuration parameters:</li><li>To pass one or more custom configuration parameters to every function in the application, click <strong>Configuration</strong> to see the <strong>Configuration</strong> section for the application.</li><li>To pass one or more custom configuration parameters to a particular function, click the function’s name to see the <strong>Configuration</strong> section for the function.</li><li>In the <strong>Configuration</strong> section, specify details for the first custom configuration parameter:</li><li><strong>Key: </strong>The name of the custom configuration parameter. The name must only contain alphanumeric characters and underscores, and must not start with a number. For example, namespace</li><li><strong>Value: </strong>A value for the custom configuration parameter. The value must only contain printable unicode characters. For example, jdoe</li><li>Click the plus button to save the new custom configuration parameter.</li><li>Oracle Functions combines the key-value pairs for all the custom configuration parameters (both application-wide and function-specific) in the application into a single, serially-encoded configuration object with a maximum allowable size of 4Kb. You cannot save the new custom configuration parameter if the size of the serially-encoded configuration object would be greater than 4Kb.</li><li>(Optional) Enter additional custom configuration parameters as required.</li></ol><h4>Accessing Custom Configuration parameters inside the Fn container</h4><p>Once the configuration parameters are set, we now need to access/read the configuration parameter from the same Context object by leveraging the ctx.config method.</p><p>We have set 2 custom configuration parameters as namespace and bucketName. Please check the snippet below on how to read and print them:</p><pre>const fdk=require(&#39;<a href="http://twitter.com/fnproject/fdk">@fnproject/fdk</a>&#39;);</pre><pre>fdk.handle(async (input, ctx) =&gt; {<br> let config = ctx.config;<br> <br> console.log(&#39;OCI Namespace : &#39;, config.namespace);<br> console.log(&#39;OCI Bucket Name : &#39;, config.bucketName);<br> <br>});</pre><p>Both application-wide and function configuration parameters can be accessed by the above mentioned technique using the ctx.config object.</p><blockquote>Full example code repository: <a href="https://github.com/pathikreet/ocifunctions/tree/master/NodeJS/OCIRestRPAuth">https://github.com/pathikreet/ocifunctions/tree/master/NodeJS/OCIRestRPAuth</a></blockquote><p>Happy Learning !!!</p><p><a href="https://technology.amis.nl/oracle-cloud/reading-query-parameters-in-get-requests-to-project-fn-functions-and-oracle-functions-as-a-service">https://technology.amis.nl/oracle-cloud/reading-query-parameters-in-get-requests-to-project-fn-functions-and-oracle-functions-as-a-service</a></p><ul><li><a href="https://github.com/fnproject/docs">fnproject/docs</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/Functions/Tasks/functionspassingconfigparams.htm">Passing Custom Configuration Parameters to Functions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2377ae6b6137" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Oracle Function without Fn CLI (Using Docker) in NodeJS]]></title>
            <link>https://pathikreet-dutta.medium.com/create-oracle-function-without-fn-cli-using-docker-in-nodejs-be1a13f28a26?source=rss-3c432a3850bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/be1a13f28a26</guid>
            <category><![CDATA[fn-project]]></category>
            <category><![CDATA[oracle-cloud]]></category>
            <category><![CDATA[oci]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[oracle-function]]></category>
            <dc:creator><![CDATA[Pathikreet Dutta]]></dc:creator>
            <pubDate>Fri, 19 Feb 2021 13:03:56 GMT</pubDate>
            <atom:updated>2021-05-08T09:31:50.280Z</atom:updated>
            <content:encoded><![CDATA[<p>Oracle Function(Function) is a fully managed, multi-tenant, highly scalable, on-demand, Functions-as-a-Service platform. It is built on enterprise-grade Oracle Cloud Infrastructure(OCI) and powered by the Fn Project open source engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*j9wUq3ZNC43QoTG2.png" /></figure><p>The serverless and elastic architecture of Oracle Functions means there’s no infrastructure administration or software administration for you to perform. You don’t provision or maintain compute instances, and operating system software patches and upgrades are applied automatically. Oracle Functions simply ensures your app is highly-available, scalable, secure, and monitored. With Oracle Functions, you can write code in Java, Python, Node, Go, and Ruby (and for advanced use cases, bring your own Dockerfile, and Graal VM). You can then deploy your code, call it directly or trigger it in response to events, and get billed only for the resources consumed during the execution.</p><p>Now there are multiple ways in which a Function can be created in OCI as listed below :</p><ol><li>Using the OCI Console.</li><li>Using the Fn-cli and OCI-cli in your local machine.</li><li>Using Cloud Shell.</li><li>Using Custom Dockerfile.</li></ol><p>Now, consider a use case, where you do not have admin rights on your local machine and you cannot install the Fn-cli and OCI-cli on it. In this scenario you would need to use the OCI CloudShell. But here also, you would need to write the entire function code in the VIM editor in CloudShell as you will not be able to install any IDE. This brings us a difficult situation, as we all know how hard it is to code in pure text without the help of any IDE or intellisense.</p><p>In this article we will be learning exactly how to overcome the difficulty mentioned above.</p><p>To accomplish this we need to understand how exactly fn creates / deploys a function. Broadly speaking, deployment has the following steps:</p><ol><li>Fn Project CLI “<em>fn deploy</em>” command starts the process.</li><li>Fn builds a Docker image (along with some meta data) from the <em>func.yaml</em> file.</li><li>Pushes the generated Docker image to the Docker Registry.</li><li>Adds the function to the application in OCI.</li></ol><p>Refer to this <a href="https://docs.cloud.oracle.com/en-us/iaas/Content/Functions/Concepts/functionshowitworks.htm">documentation</a> for more information.</p><p>From the above breakdown, we can understand that we do not need Docker installed to create a function. Instead on applying the “<em>fn deploy</em>” or “<em>fn build</em>” command, the fn-cli builds the Docker image internally using metadata from the func.yaml file present in the classpath. Below is the default Dockerfile generated by fn-cli using the func.yaml file for a sample hello-world application in NodeJS.</p><pre>FROM fnproject/node:dev as build-stage<br>WORKDIR /function<br>ADD package.json /function/<br>RUN npm install<br><br>FROM fnproject/node<br>WORKDIR /function<br>ADD . /function/<br>COPY --from=build-stage /function/node_modules/ /function/node_modules/<br>ENTRYPOINT [&quot;node&quot;, &quot;func.js&quot;]</pre><p>If we take a close look at the default Dockerfile, we can see that fn runtime pushes all content to a directory named “<em>/function</em>” inside the Docker image.</p><p>Now that we understand how fn runtime creates a Docker image, we can mimic the process ourselves in a custom Dockerfile and use the Docker Runtime in our local machine to generate a Docker image on the same lines as generated by fn runtime itself. The diagram below illustrates this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*Lx9B4aQHC77yjgUY9pmUnA.png" /><figcaption>Alternate Design Principal to create a Function</figcaption></figure><p>As we can see in the image above, we do not need any of fn-cli or oci-cli on our local machines. Only if we have Docker installed in our local machines, we can leverage the power of any IDE like VS Code to write our NodeJS serverless code and use Docker cli to build the image. Once the image is built we can push the image to Oracle Cloud Infrastructure Registry (OCIR), which is the Docker repository for all Oracle Cloud resources. This will enable us to use any IDE, which is very efficient while coding in any language and also enables us to strategize and resolve any advanced use cases that may arise. In a way making code development even more <strong>container native</strong> as there is no need to use any kind of SDKs.</p><p>Enough of theory banter, lets see how it works in reality :)</p><p>Using your favourite IDE, let us create a new NodeJS project and name it “NodeFnSample-Docker”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAhgkI6cQ5jEmBdg1_tx5g.png" /></figure><p>Now, we need to mimic the way fn runtime creates a function directory structure. Essentially, a NodeJS function has the following files in its root directory:</p><ol><li>func.js</li><li>func.yaml</li><li>package.json</li></ol><p>Lets go ahead and create all these 3 files. Firstly create a file called “func.js” and write the following code in it:</p><pre>const fdk = require(&#39;<a href="http://twitter.com/fnproject/fdk">@fnproject/fdk</a>&#39;);</pre><pre>fdk.handle(async (input) =&gt; {<br>    let name = &quot;World&quot;;</pre><pre>    if(input &amp;&amp; input.name){<br>        name = input.name;<br>    }<br> <br>    return {<br>        &#39;response&#39;: &quot;Hello &quot;+ name,<br>        &#39;currentTime&#39;: currentDateTime()<br>    }<br>})</pre><pre>/**<br> * Function to get the current DateTime<br> * <a href="http://twitter.com/returns">@returns</a> current Date<br> */<br>function currentDateTime() {<br>    return new Date();<br>}</pre><p>Now lets create the “func.yaml” file with the following code in it. This is the metadata file:</p><pre>schema_version: 20180708<br>name: node-sample-docker-fn<br>version: 0.0.1<br>runtime: docker<br>format: http-stream<br>memory: 512<br>timeout: 120<br>idle_timeout: 1800</pre><p>Notice that we have specified the “runtime” attribute as “docker”. This is important as it tells the fn runtime that this function is based on a pre created Docker image and that fn <strong>does not</strong> need to build an image.</p><p>Next we will create the “package.json” file which is basically a metadata file for any NodeJS project. Below is the content of the file in our application:</p><pre>{<br>  &quot;name&quot;: &quot;node-sample-docker-fn&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;,<br>  &quot;description&quot;: &quot;NodeJS Code for Oracle Fn to be created with Docker Image&quot;,<br>  &quot;main&quot;: &quot;func.js&quot;,<br>  &quot;author&quot;: &quot;Pathikreet Dutta&quot;,<br>  &quot;license&quot;: &quot;Apache-2.0&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;<a href="http://twitter.com/fnproject/fdk">@fnproject/fdk</a>&quot;: &quot;&gt;=0.0.19&quot;,<br>    &quot;fs&quot;: &quot;0.0.1-security&quot;,<br>    &quot;node-forge&quot;: &quot;^0.10.0&quot;<br>  },<br>  &quot;bundledDependencies&quot;: [<br>    &quot;node-forge&quot;,<br>    &quot;fs&quot;<br>  ],<br>  &quot;config&quot;: {<br>    &quot;bin&quot;: &quot;bin&quot;,<br>    &quot;name&quot;: &quot;NodeDockerSampleFn&quot;<br>  }<br>}</pre><p>Now if you need to use any additional modules for development, then you can very well add those modules here in the package.json, just like you would do in your usual NodeJS projects.</p><p>Once the above 3 files are created, now we will be doing the main task that is needed for the above design principle to work. We will now create the “Dockerfile” with the below content:</p><pre>FROM node:14</pre><pre>#Create a working directory<br>WORKDIR /function</pre><pre># Install app dependencies<br># A wildcard is used to ensure both package.json AND package-lock.json are copied<br># where available (npm@5+)<br>COPY package*.json ./<br>RUN npm install</pre><pre># Copy all artifacts including generated ones<br>COPY . /function/</pre><pre>CMD [ &quot;node&quot;, &quot;func.js&quot; ]</pre><p>With this Dockerfile we are basically doing what fn runtime does internally. Now build an image from this codebase with following command:</p><pre>docker build --pull --rm -f &quot;NodeFnSample-Docker\Dockerfile&quot; -t iad.ocir.io/&lt;tenancy-namespace&gt;/&lt;OCIR-repo&gt;/node-sample-docker-fn:0.0.1</pre><blockquote>You should have Docker runtime installed and running on your local machine before executing the above command</blockquote><p>If you take a close look at the docker command, you would notice that the image section is little different than usual. The general docker build image command syntax is as follows:</p><pre>docker build --pull --rm -f &lt;Dockerfile&gt; -t &lt;image&gt;:&lt;tag&gt;</pre><p>As we are using OCIR as our Docker repository, the Image syntax for OCIR is as follows:</p><pre>&lt;region-prefix&gt;.ocir.io/&lt;tenancy-namespace&gt;/&lt;OCIR-repo&gt;/&lt;image-name&gt;:&lt;tag&gt;</pre><p>One the image is built and available in your local machine, you can then login to OCIR from your local machine and push the image to the repo.</p><blockquote>To work with OCIR, you would first need to generate an Auth Token from the OCI Console. Please refer <a href="https://docs.oracle.com/en-us/iaas/Content/Functions/Tasks/functionsgenerateauthtokens.htm">here</a> for more information.</blockquote><blockquote><em>Login to Docker</em></blockquote><blockquote>docker login &lt;region-code&gt;.ocir.io (in my case docker login iad.ocir.io)</blockquote><blockquote>username: &lt;tenancy-namespace&gt;/user (where &lt;tenancy-namespace&gt; is the auto-generated Object Storage namespace string of the tenancy in which to create repositories (as shown on the Tenancy Information page) and password is the generated Auth Token.</blockquote><pre>docker push iad.ocir.io/&lt;tenancy-namespace&gt;/&lt;OCIR_repo&gt;/node-sample-docker-fn:0.0.1</pre><p>On successfully pushing the image to OCIR, you can then login to OCIR and see the image listed there as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrpwVE71rx_v8K_F_GBUSg.png" /><figcaption>OCIR</figcaption></figure><p>Once the Image is pushed and available in OCIR, we can then refer to <a href="https://docs.oracle.com/en-us/iaas/Content/Functions/Tasks/functionscreatingfunctions.htm">Creating Functions from Existing Docker Images</a> to create a function in OCI.</p><p>Out of the 2 ways described in the above Oracle Doc, i personally like to use the OCI CloudShell to create my functions using the following command:</p><pre>fn create function &lt;app-name&gt; &lt;function-name&gt; iad.ocir.io/&lt;tenancy-namespace&gt;/&lt;OCIR_repo&gt;/node-sample-docker-fn:0.0.1</pre><pre>&lt;function-name&gt; = node-sample-docker-fn</pre><p>Now your function is created and ready to be invoked using any method that you prefer. Lets try to invoke the newly created function from OCI CloudShell itself using the following command:</p><pre>echo &#39;{&quot;name&quot;: &quot;Pathikreet&quot;}&#39; | fn invoke &lt;app-name&gt; node-sample-docker-fn --content-type application/json | jq</pre><p>The response from function is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5b-8_Ghj2S-0InvBvn__Q.png" /><figcaption>Function Response</figcaption></figure><p>And voila, we did achieve to create a function without the hassle of installing oci-cli, fn-cli and also we achieved our goal of being completely agnostic of technology in our design principle. Although we have showcased a NodeJS example here, you can very well write the code in any language of your choice, as long as you can create the Dockerfile on the same lines as created above. This was our serverless code is both language and platform agnostic.</p><blockquote>Sample Code : <a href="https://github.com/pathikreet/ocifunctions/tree/master/NodeJS/NodeFnSample-Docker">https://github.com/pathikreet/ocifunctions/tree/master/NodeJS/NodeFnSample-Docker</a></blockquote><p>Happy Learning !!!</p><h3>References</h3><ul><li><a href="https://fnproject.io/tutorials/ContainerAsFunction/">Creating a Function from a Docker Image</a></li><li><a href="https://www.oracle.com/webfolder/technetwork/tutorials/infographics/oci_faas_gettingstarted_quickview/functions_quickview_top/functions_quickview/index.html">Quick Start Guides</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/Functions/Concepts/functionsoverview.htm">Overview of Functions</a></li><li><a href="https://blogs.oracle.com/cloud-infrastructure/oracle-functions-announcing-samples-repository-and-quick-start-with-cloud-shell">Oracle Functions: Announcing Samples Repository and Quick Start with Cloud Shell</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be1a13f28a26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>