<?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 Boudhayan Dev on Medium]]></title>
        <description><![CDATA[Stories by Boudhayan Dev on Medium]]></description>
        <link>https://medium.com/@boudhayan-dev?source=rss-50a2170450a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OReS8iSKgNUM7AlffpTxYg.jpeg</url>
            <title>Stories by Boudhayan Dev on Medium</title>
            <link>https://medium.com/@boudhayan-dev?source=rss-50a2170450a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:22:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@boudhayan-dev/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[The Silent Hijack: How One VPC Endpoint Broke a Public API Call]]></title>
            <link>https://medium.com/swlh/the-silent-hijack-how-one-vpc-endpoint-broke-a-public-api-call-574e9f40535a?source=rss-50a2170450a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/574e9f40535a</guid>
            <category><![CDATA[aws-vpc-endpoints]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-vpc]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Boudhayan Dev]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 14:20:43 GMT</pubDate>
            <atom:updated>2026-04-19T14:20:43.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ckpYCVgSQlDeIgk_5z0Uw.png" /><figcaption>Overview</figcaption></figure><p>So it was that time of the quarter when our team was close to shipping a new service to production.</p><p>A brand new service — fresh code, fresh deployment, fresh everything. It had one job at its core: call an existing API that had been serving traffic in production for a while. Nothing fancy. No breaking changes on the existing API’s side. We had integrated against it on lower environments, tests were green, and we were confident.</p><p>Then we deployed to prod and things started failing.</p><p>The error that showed up in our logs was <strong><em>ACCESS_DENIED</em></strong>. Not a timeout. Not a connection refused. Not a 502. A clean, polite, unambiguous <strong><em>ACCESS_DENIED</em></strong> from the existing API’s API Gateway, telling us that our Lambda was “not authorized” to invoke it.</p><p>This was strange for a few reasons. First, we hadn’t changed anything about the existing API. Second, the existing API had been working perfectly for every other caller. Third, there was no IAM policy involved here — the API Gateway was a <em>public regional</em> one, protected by an IP-based resource policy that simply allowed our corporate IP ranges and denied everything else.</p><p>So if the API wasn’t broken, and our Lambda wasn’t doing anything particularly unusual, why was the API Gateway treating us like we were trying to break in?</p><p><em>Spoiler : It wasn’t the API Gateway. It wasn’t our Lambda either. It was the network in between doing something neither of us had asked it to do.</em></p><p>This blog is the story of how we figured that out — and more importantly, all the things I ended up learning about VPC Endpoints, private DNS, and API Gateway resource policies along the way. <strong>Fair warning: I’m a backend engineer, not a network person.</strong> A lot of what you’ll read here was new to me too. If you’ve ever felt like AWS networking is a dark art that other people understand, this is hopefully the blog that makes at least one corner of it click.</p><p>Let’s begin.</p><h3>The Setup</h3><p>Before we get into the failure itself, let me paint a picture of the setup. It’ll make the rest of the story much easier to follow.</p><p>We operate in a split-account AWS organization. Most teams own their own workload AWS accounts. That’s where their services, VPCs, Lambdas, databases, and API Gateways live. But the actual networking (Transit Gateways, NAT Gateways, public IP allocations, corporate DNS forwarding, Route53 Resolver infrastructure) is owned and managed by a central <strong>Network team</strong>. Every workload VPC peers into the Network team’s account through Transit Gateway attachments, and outbound internet traffic from our VPCs egresses through NAT Gateways that <em>they</em> own.</p><p>This is a pretty common setup at scale, and it has a lot of benefits. Centralized networking, consistent egress IPs, one team owning the IP allowlists that get embedded into partner firewalls, and so on. It also has one very real downside for someone like me: <strong>I don’t have visibility into most of the network layer.</strong> I can see my VPC’s route tables and security groups, but flow logs, NAT Gateway metrics, Transit Gateway route analysis, and Route53 Resolver query logs all live in an AWS account I don’t have read access to. Keep this in mind. It’ll come up later.</p><p>Now, the application setup. Both services involved in our story live in the <strong>same workload AWS account</strong>. Here they are:</p><ol><li><strong>Existing Target API</strong>, running behind a <strong>public regional API Gateway</strong>. This service had been in production for a while. It sat inside <strong>VPC-A</strong>, which was actually in the process of being decommissioned as part of a larger migration effort.</li><li><strong>New Caller Lambda</strong>, the service we were rolling out. This one lived in <strong>VPC-B</strong>, the new VPC that VPC-A’s workloads were being migrated to.</li></ol><p>The target API Gateway had the following resource policy attached to it:</p><pre>{<br>  &quot;Effect&quot;: &quot;Deny&quot;,<br>  &quot;Principal&quot;: { &quot;AWS&quot;: &quot;*&quot; },<br>  &quot;Action&quot;: &quot;execute-api:Invoke&quot;,<br>  &quot;Resource&quot;: &quot;*&quot;,<br>  &quot;Condition&quot;: {<br>    &quot;NotIpAddress&quot;: {<br>      &quot;aws:SourceIp&quot;: [<br>        &quot;203.0.113.0/24&quot;, // example only<br>        &quot;198.51.100.0/24&quot;, // example only<br>        &quot;192.0.2.0/24&quot; // example only<br>      ]<br>    }<br>  }<br>}</pre><p>In plain English: <em>“Deny everything unless the source IP is in this list of corporate office public IP ranges.”</em> This kind of policy is extremely common when an API is intended to be reachable only by internal employees and services connecting through the corporate network.</p><p>Now, you might be wondering:</p><blockquote>Wait — if the Caller Lambda and the Target API Gateway are both internal services in the same AWS account, why go through a public API Gateway at all? Why not just use a private API Gateway with a private custom domain?</blockquote><p>That’s a completely fair question, and honestly, it was our original plan. A private API Gateway fronted by a <strong>private custom domain</strong> (something like target-api.internal.company.corp served from a private hosted zone, resolvable only inside our VPCs) would have been the cleaner long-term design. No public endpoint, no IP allowlisting gymnastics, just internal service-to-service calls over a VPC Endpoint.</p><p>But we had a GA deadline to hit, and building out that private API Gateway path wasn’t something we could squeeze in before ship day. New VPC Endpoint, private custom domain, private hosted zone association, TLS certs from an internal CA, route updates. So we made a conscious tradeoff. For GA, we would use the existing public URL and rely on the fact that our Lambda’s outbound traffic would egress through the Network team’s NAT Gateways, whose public IPs were already in the corporate allowlist. Post-GA, we would migrate to a private API Gateway setup as a follow-up.</p><p>That tradeoff is what set up the bug we’re about to walk through. And if you’ve ever made a similar call, <em>“let’s ship the public path for now, we’ll harden it later”</em>, this story might feel very familiar.</p><p>Here’s the whole setup in one picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZsa-wJ6aSoB99iQQBOl9g.png" /><figcaption>Setup</figcaption></figure><h3>The Symptom</h3><p>Right after the production deployment, the errors started showing up in our Caller Lambda’s logs. The payload looked something like this:</p><pre>ERROR | CallerLambda.handler | Target API responded with error<br>{<br>  &quot;error&quot;: [{<br>    &quot;code&quot;: &quot;ACCESS_DENIED&quot;,<br>    &quot;message&quot;: &quot;User: anonymous is not authorized to perform:<br>                execute-api:Invoke on resource:<br>                arn:aws:execute-api:&lt;region&gt;:&lt;account&gt;:&lt;api-id&gt;/prod/GET/some/path<br>                with an explicit deny in a resource-based policy&quot;<br>  }]<br>}</pre><p>A few things jumped out immediately.</p><p>First, the word “<strong>anonymous</strong>”. This is API Gateway’s way of saying the request was not signed with SigV4, so it had no IAM identity to attach to the caller. That on its own was expected. The Caller Lambda was deliberately not using IAM auth to invoke the Target API. Instead, our contract with the Target API relied on two things, namely, the caller’s source IP being in the corporate allowlist, and an x-api-key header for application-layer authorization through API Gateway&#39;s usage plans. Neither of those involves IAM, so &quot;User: anonymous&quot; was the expected denial wording whenever <em>anything</em> went wrong with this call. It told us the rejection was not an IAM issue, but it didn&#39;t rule out anything else.</p><p>Second, the word “<strong>explicit deny</strong>” and the phrase “<strong>resource-based policy</strong>”. This was the API Gateway telling us, in no uncertain terms, that one of its resource policy statements had actively denied the request. Given the policy we already saw in the previous section, this could only mean one thing: <strong>the source IP that the API Gateway saw was not in the allowlist.</strong></p><p>Third, there was no information in the error about <em>what</em> source IP it had seen. API Gateway’s default error response doesn’t include the evaluated source IP. You can sometimes get that from access logs, but access logs were not enabled on the Target API’s stage. We’ll come back to this later as one of the lessons learned.</p><p>So the working theory in the first fifteen minutes was straightforward:</p><blockquote>The Caller Lambda’s outbound traffic must be egressing with a source IP that is not in the corporate allowlist. Probably a NAT Gateway public IP owned by the Network team’s account. All we need to do is find out what that IP is, and add it to the allowlist.</blockquote><p>Simple enough. Except this theory was about to fall apart fairly quickly, in a way that forced us to look at the problem completely differently.</p><h3>The Investigation</h3><p>With the working theory in hand, the first thing we did was ask the Network team for the public IP of the NAT Gateway that VPC-B egresses through. The answer came back fairly quickly. It was a NAT IP owned by their account, and as expected, it was <em>not</em> in the corporate allowlist on the Target API.</p><p>Great. Hypothesis looked solid. The fix seemed obvious. Add the NAT IP to the allowlist, redeploy the Target API’s resource policy, done.</p><p>Except. Before anyone opened a PR, somebody on the call asked a question that changed the direction of the whole investigation:</p><blockquote><em>“Wait. Wasn’t this Lambda originally deployed in VPC-A during internal testing? Was it working there?”</em></blockquote><p>A short pause. Then we checked the logs from the earlier environment.</p><p>It hadn’t been working there either.</p><p>This single observation was the turning point. If the Lambda had been failing in VPC-A too, then the NAT-Gateway-IP hypothesis could not be the full story. VPC-A’s egress path was different from VPC-B’s. The two VPCs had different route tables, different TGW attachments, and traffic from them hit different NAT Gateways with different public IPs. If the problem were purely a NAT IP mismatch, we would have expected <em>one</em> VPC to work and the other to fail. Not both.</p><p>So we were looking at the same symptom, <strong>ACCESS_DENIED</strong>, showing up in two different VPCs that had two different network paths to the internet. That meant one of two things. Either the resource policy was somehow denying us for a reason unrelated to source IP (unlikely, given the policy was straightforward NotIpAddress), or the two VPCs were both producing source IPs that failed the allowlist check, but for different reasons.</p><p>The second option was weirder and more interesting. So we went looking.</p><h4>Digging into VPC-A</h4><p>VPC-A was the legacy VPC that had been around for a while and had been shared by several teams over its lifetime.</p><p>On a hunch, I opened the VPC Endpoints list. And there it was. An <strong>Interface VPC Endpoint for </strong><strong>com.amazonaws.&lt;region&gt;.execute-api</strong>, sitting in VPC-A, with <strong>private DNS enabled</strong>. It was not something our team had created. It had been provisioned earlier by a different project that also used VPC-A, for reasons unrelated to our service.</p><p>At this point I had to stop and go read the AWS docs carefully, because I genuinely did not know what this VPCE was doing. Here is what I learned, compressed into a few bullets:</p><ul><li>An Interface VPC Endpoint for execute-api is basically a set of ENIs in your VPC that AWS uses to route your traffic to API Gateway <em>privately</em>, without going through the public internet.</li><li>When you create this VPCE with <strong>private DNS enabled</strong>, AWS automatically creates a Route53 private hosted zone in your VPC for the domain execute-api.&lt;region&gt;.amazonaws.com. This private hosted zone contains a wildcard record like *.execute-api.&lt;region&gt;.amazonaws.com that resolves to the VPCE&#39;s ENI private IPs.</li><li>Because private hosted zones take priority over public DNS in a VPC, <strong>any</strong> DNS query inside that VPC that matches *.execute-api.&lt;region&gt;.amazonaws.com resolves to the VPCE&#39;s private IPs. Not just traffic to private API Gateways. Literally any API Gateway hostname.</li><li>The hostname format API Gateway uses for all of its regional endpoints, public or private, is &lt;api-id&gt;.execute-api.&lt;region&gt;.amazonaws.com.</li></ul><p>You can probably see where this is going.</p><p>Our Caller Lambda, while sitting in VPC-A, was making HTTPS calls to the Target API’s public URL. But under the hood, the DNS resolver in VPC-A was intercepting the hostname and returning the VPCE’s private ENI IPs. The Lambda, completely unaware, opened a TLS connection to that private IP instead of to the public API Gateway endpoint. The traffic went through the VPCE. And when it arrived at the Target API Gateway, the aws:SourceIp that the resource policy evaluated was not a NAT IP, not a corporate office IP, but a private 10.x.x.x address belonging to the VPCE&#39;s ENI.</p><p>10.x.x.x was obviously not in the public IP allowlist. The NotIpAddress condition matched. The explicit Deny fired. ACCESS_DENIED.</p><p>This was the root cause in VPC-A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJ5zXqE3aPaAmvAZ2_0QzQ.png" /><figcaption>VPC — A failure path</figcaption></figure><p>The most unsettling part of this was how <em>invisible</em> the whole thing was. Nothing in our Lambda code changed. Nothing in the Target API’s config changed. No routing table was manually edited. From the application’s perspective, it was making an HTTPS call to a public URL. The VPC’s DNS resolver quietly rewrote that into something completely different, and the entire behavior of the network changed. And none of this shows up in your CloudWatch logs or in your application metrics. You only see the final error response.</p><h4>Digging into VPC-B</h4><p>Now the other half. Why did moving to VPC-B not fix this?</p><p>VPC-B was the new VPC, freshly set up. We checked it. No execute-api VPCE. No private hosted zones for *.execute-api. Nothing fancy. Traffic from VPC-B to anything on the internet should take the normal path: Lambda ENI, route table, Transit Gateway, Network team&#39;s NAT Gateway, public internet, AWS edge, API Gateway.</p><p>So we opened the Caller Lambda’s outbound path. Lambda running in VPC-B. DNS query for the Target API’s hostname. This time, no private hosted zone to intercept. The query goes to AWS public DNS, resolves to a real AWS edge IP for the API Gateway. Lambda opens an HTTPS connection. Traffic egresses through VPC-B’s route table, across the TGW, into the Network team’s VPC, out through their NAT Gateway, into the internet, and back to API Gateway.</p><p>The source IP that API Gateway saw in this path was the <strong>NAT Gateway’s public IP</strong>. Which was, per the Network team, <em>their</em> NAT, not a corporate office IP. And therefore not in the Target API’s allowlist.</p><p>Same error. Same deny rule. Completely different path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XP1YLt-aHmpTtWqi23aQPg.png" /><figcaption>VPC — B netowork path</figcaption></figure><p>So now we had the full picture:</p><ul><li>In VPC-A, an execute-api VPCE with private DNS was silently rerouting our call, making the Target API see a private 10.x.x.x source IP.</li><li>In VPC-B, the call was going out through the Network team’s NAT, making the Target API see a NAT public IP that was not in the corporate allowlist.</li></ul><p>Same error message. Same deny rule. Two completely different root causes producing the exact same symptom.</p><p>This is the part of the investigation that I want to linger on for a second, because I think it is the most important lesson in the whole story. When you have two different environments producing the same error, the natural instinct is to assume they share a single cause. Especially when the error message is as specific as “explicit deny in a resource-based policy.” It <em>feels</em> like one thing. It is easy to spend hours chasing a single-root-cause theory that fits most of the evidence but not all of it, because giving up that theory means admitting that you understand the system less well than you thought.</p><p>In our case, the decisive move was not a clever debug trick. It was simply noticing that the timeline did not fit the hypothesis. VPC-A had been failing for days before VPC-B was even provisioned. If it was a NAT IP mismatch, VPC-A should have been working. It wasn’t. That single inconsistency was what pulled us toward the possibility of two different causes.</p><h3>The Fix</h3><p>With both root causes understood, the actual fix was anticlimactic. Which, honestly, is a common theme when debugging is done right. The hard part is diagnosis. Once you understand the problem, the fix is usually short.</p><p>For GA, we had one constraint we could not get around. The Target API’s resource policy could not start accepting arbitrary private IPs or arbitrary NAT Gateway IPs from internal accounts, because that would effectively weaken a security control that a lot of other callers were relying on. The allowlist of corporate public IPs existed for a reason.</p><p>So the fix had two parts.</p><p><strong>First</strong>, in VPC-A, we removed our Lambda from the equation entirely. The Caller Lambda no longer deploys into VPC-A. This neutralizes the execute-api VPCE problem for our service. We did not try to delete the VPCE itself, because it was not ours to delete. It belonged to another project that had legitimate reasons for it to exist.</p><p><strong>Second</strong>, in VPC-B, we worked with the Network team to get VPC-B’s NAT Gateway egress IP added to the Target API’s allowlist. This was a standard ticket for them. The IP was assigned, the allowlist was updated, and the Target API started accepting our calls.</p><p>That was it for GA. Not glamorous, but it unblocked us.</p><p>But this is the part worth pausing on. The GA fix is not the long-term answer, and we knew that going in. Putting an internal Lambda’s NAT Gateway IP into a public IP allowlist is the kind of thing that makes sense under a deadline and feels increasingly strange the longer it stays in place. It blurs the line between “internal service call” and “corporate-employee-from-the-office call.” It creates a future debugging trap for anyone who looks at that allowlist and tries to reason about who is supposed to be in it. It also means that if the Network team ever re-architects their NAT topology, our integration breaks in a way that will not be obvious until it happens.</p><p>So the post-GA plan is the one we originally wanted. A <strong>private API Gateway</strong> in front of the Target service, fronted by a <strong>private custom domain</strong> served from an internal private hosted zone. The Caller Lambda talks to the private domain, traffic stays inside the AWS backbone the whole way, and there is no public endpoint and no IP allowlist involved at all.</p><p>Getting that right requires understanding a few things that are not obvious. How VPC Endpoints actually work. What private_dns_enabled does under the hood. Why vpc_endpoint_ids on the API Gateway is a separate concept from the resource policy. How custom domains interact with DNS resolution in ways that sometimes save you and sometimes bite you.</p><p>That is the rest of this blog.</p><h3>Tools &amp; Observability (What We Learned)</h3><p>Before we get into the deep-dive sections on VPC Endpoints and DNS, I want to talk about the part of this whole exercise that, in hindsight, bothered me the most. We spent a non-trivial amount of time throwing stones in the dark. Forming theories, asking the Network team to confirm things, waiting, asking again. And a lot of that could have been shortened if I had known ahead of time what observability AWS actually provides for this class of problem.</p><p>So this section is less “tools we used” and more “tools I wish I had known about, or had access to, when this started.” If you’re a backend engineer like me and not someone who spends their days inside AWS networking, some of these will be new. I am putting them here because I want the next time this happens (to me or to you) to go faster than it did for me.</p><h4>VPC Flow Logs</h4><p>The single data point that would have collapsed the entire investigation is this: <em>where is the Caller Lambda’s outbound traffic actually going?</em></p><p>VPC Flow Logs answer that question exactly. They record the source IP, destination IP, source port, destination port, protocol, and whether the traffic was accepted or rejected, for every packet crossing the VPC’s ENIs. Had I been able to pull flow logs for VPC-A while the Lambda was failing, I would have seen the Lambda’s ENI sending traffic to an internal 10.x.x.x address (the execute-api VPCE&#39;s ENI) instead of to an external AWS edge IP. That one observation ends the investigation in about thirty seconds.</p><p>The catch, of course, was that flow logs in our setup are owned by the Network team. They live in a CloudWatch log group (or S3 bucket) inside their AWS account, not ours. Asking for a cross-account query on a Friday turned out to be more friction than I had expected. If I could rewind time, I would have asked for query access to flow logs for our workload account’s VPCs as a first step, before anything else.</p><p><strong>Takeaway</strong>: flow logs are the single highest-value tool for questions of the form “where is my traffic actually going.” If you don’t have query access to the flow logs for your VPCs, that is worth fixing before you need them.</p><h4>VPC Reachability Analyzer</h4><p>This one I did not know about at all until someone mentioned it mid-investigation. VPC Reachability Analyzer is a built-in AWS tool that takes two endpoints as input (a source and a destination) and tells you whether traffic can actually flow between them, based on route tables, security groups, NACLs, VPCEs, and peering. It does not send live traffic, it analyzes configuration. Think of it as traceroute, but it traces the <em>intended</em> path based on what AWS is configured to do, not the actual packet.</p><p>For this bug, Reachability Analyzer would have shown that the Caller Lambda’s ENI in VPC-A had a valid network path to the execute-api VPCE, and you could reasonably have inferred from that output that traffic might be flowing through it instead of through the internet gateway.</p><p>Caveat: Reachability Analyzer also needs permissions across all the accounts in the path. So in a split-account setup like ours, getting it to give a full cross-account answer is not trivial. But for debugging within your own workload account, it’s a tool worth remembering.</p><h4>Route53 Resolver Query Logging</h4><p>This is the one that would have most <em>cleanly</em> solved the VPC-A mystery. Route53 Resolver Query Logging captures every DNS query made inside a VPC, along with the resolved answer. If we had this enabled on VPC-A, we would have seen queries for the Target API’s public hostname coming back with a 10.x.x.x private IP answer instead of a public AWS IP. That single log line is a smoking gun. It tells you immediately that DNS resolution is being intercepted by something inside the VPC, which points you straight at the private hosted zone and therefore the VPCE.</p><p>We did not have this enabled on VPC-A. It was not part of the default setup for that VPC. After the fact, I checked, and yes, enabling Resolver Query Logging on a VPC is a fairly lightweight operation that logs to CloudWatch or S3. The volume can be large for busy VPCs, so you probably would not leave it on forever, but it is the kind of thing you would enable selectively when you suspect DNS weirdness is happening.</p><p><strong>Takeaway</strong>: if you ever find yourself in a situation where DNS might be involved and you are not sure, Route53 Resolver Query Logging is how you get an authoritative answer. Put it on your mental list.</p><h4>API Gateway Access Logs</h4><p>The Target API had execution logs enabled, which is what captured the ACCESS_DENIED errors in the first place. What it did <em>not</em> have was <strong>access logs</strong> enabled on the stage. This matters because access logs include variables like $context.identity.sourceIp, which is exactly the IP that API Gateway&#39;s resource policy evaluates. Execution logs do not include this.</p><p>If access logs had been enabled on the Target API’s stage, we would have seen the actual source IP that API Gateway was seeing for each of our denied calls. In VPC-A that would have been a 10.x.x.x address. In VPC-B it would have been the Network team&#39;s NAT IP. The investigation would have looked very different, and in both cases the right hypothesis would have been the first hypothesis.</p><p>Enabling access logs is cheap, so this is now on our list of things to enable on API Gateway stages going forward, especially any stage that has a resource policy doing meaningful authorization work.</p><h4>The honest reality of split-account debugging</h4><p>I want to land this section with a point that I think is relatable for anyone working inside a large AWS org. In a split-account setup, a backend engineer debugging a network-layer issue frequently cannot see half the picture. Flow logs, Transit Gateway route tables, Route53 Resolver configurations, NAT Gateway metrics, and in some cases even the details of the VPC peering you depend on live in accounts you do not have read access to. The practical debug loop becomes: form a hypothesis from what you <em>can</em> see, write a specific question to the Network team in Slack, wait, refine, repeat.</p><p>This is not a complaint. A central networking team is a sane architectural choice at scale, and the alternative (everyone wires up their own NAT and DNS and routing) is worse. But it does change what a good debugging workflow looks like. Instead of “open the console, inspect everything, form a theory,” it becomes “understand the conceptual model well enough to form a <em>specific</em> hypothesis, because the cost of every round trip to another team is high.”</p><p>Which is maybe the best argument for sections like the rest of this blog. Understanding what VPC Endpoints actually do, how private DNS actually works, how API Gateway resource policies actually evaluate source IPs, is not just trivia. In a world where you cannot always see the packets, the mental model <em>is</em> your observability.</p><h3>What a VPC Endpoint Actually Does</h3><p>With the story out of the way, let’s spend the next few sections on the underlying concepts. This is the part I wish I had internalized before any of this started, because each of these ideas shows up in almost every scenario I’ll walk through later.</p><h4>The two-line explanation</h4><p>A <strong>VPC Endpoint</strong> is AWS’s way of letting a service inside your VPC talk to an AWS service (like S3, DynamoDB, Secrets Manager, or API Gateway) without that traffic ever leaving the AWS network. No internet gateway, no NAT, no public IPs involved on the traffic path.</p><p>That is it. Everything else is detail.</p><h4>Two types, and why the difference matters</h4><p>AWS actually has two kinds of VPC Endpoints, and they behave very differently under the hood. For the rest of this blog, we only care about one of them, but it is worth knowing the distinction so you don’t get confused when you read AWS docs.</p><p><strong>Gateway Endpoints</strong> exist for S3 and DynamoDB only. They work by adding a route in your VPC’s route table that sends traffic destined for S3 or DynamoDB to a special target managed by AWS. No ENIs, no private IPs inside your VPC, no DNS changes. The routing is done entirely at the route-table layer.</p><p><strong>Interface Endpoints</strong> exist for basically every other AWS service, including API Gateway (execute-api). They work by creating actual <strong>Elastic Network Interfaces</strong> (ENIs) inside your VPC, one per Availability Zone. Those ENIs get private IP addresses from your VPC&#39;s CIDR block. Traffic destined for the AWS service gets sent to those ENIs, which then proxy it to the actual service over AWS&#39;s internal backbone.</p><p>Everything we care about in this blog uses Interface Endpoints. Whenever I say “VPCE” from here on, I mean Interface Endpoint. If you ever find yourself debugging an S3 VPCE and the behavior feels different, that’s why. Gateway Endpoints play by a completely different rulebook, and the DNS interception story I’m about to walk through does not apply to them at all.</p><h4>What actually gets created when you create an execute-api VPCE</h4><p>When you create an execute-api Interface Endpoint in a VPC, AWS provisions the following resources behind the scenes:</p><ol><li><strong>ENIs in the subnets you select</strong>, one per AZ. These ENIs get private IP addresses from your VPC’s CIDR. They are the actual network landing points for any traffic you route into the VPCE.</li><li><strong>A regional endpoint DNS name</strong> of the form {vpce-id}.execute-api.{region}.vpce.amazonaws.com. This is resolvable via public DNS and always returns the ENIs&#39; private IPs.</li><li><strong>If you enabled private DNS</strong>, also a <strong>Route53 private hosted zone</strong> for the domain execute-api.{region}.amazonaws.com, associated with your VPC, containing a wildcard record that points *.execute-api.{region}.amazonaws.com to the VPCE&#39;s ENI private IPs.</li></ol><p>That last one is the important one. It is quietly the most impactful piece of configuration in this entire story, and it is on by default when you create an execute-api VPCE through the AWS console.</p><p>We will come back to what the private hosted zone does in the next section. For now, just internalize the fact that creating an execute-api VPCE with private DNS enabled also <strong>installs a DNS rewrite rule inside your VPC</strong>. The VPCE itself is the network path, but the private hosted zone is what guides traffic <em>to</em> that path.</p><h4>Why you would create one in the first place</h4><p>There are three reasons people create an execute-api VPCE.</p><p><strong>Reason 1: you are running a Private API Gateway.</strong> A Private API Gateway has no public endpoint at all. The only way any traffic can reach it is through an execute-api VPCE. In this case the VPCE is mandatory, not optional. If you want private APIs, you need VPCEs.</p><p><strong>Reason 2: you want outbound traffic to a regional or public API Gateway to stay on the AWS backbone.</strong> Even for regional/public API Gateways, which are reachable via the internet, you can choose to have your VPC’s traffic to them go through a VPCE instead of through the NAT Gateway and the internet. The main motivations here are security (no traffic on the public internet) and sometimes cost (no NAT Gateway data charges for that traffic).</p><p><strong>Reason 3: compliance or architectural constraints.</strong> Some environments are set up such that VPCs are simply not allowed to have internet egress for certain classes of traffic. In that case, VPCEs are the only way out.</p><p>It is worth noting that <strong>Reason 1 makes the VPCE mandatory</strong>, while Reasons 2 and 3 make it a choice. And for Reasons 2 and 3, enabling private DNS on the VPCE is usually what people want, because they want all API Gateway traffic to automatically prefer the VPCE path without the application having to know anything. But “all API Gateway traffic” means <em>all</em> API Gateway traffic, including traffic to services that have nothing to do with the VPCE. That is the trap.</p><h4>vpc_endpoint_ids vs the resource policy</h4><p>One more concept to land before we move on, because these two often get confused even by people who have been working with API Gateway for a while.</p><p>When you configure a <strong>Private</strong> API Gateway, there are two different places where VPC Endpoints show up, and they mean two completely different things.</p><p>The <strong>vpc_endpoint_ids</strong> (the configuration on the API Gateway itself) controls <strong>DNS resolution</strong>. When you list a VPCE here, AWS adds DNS records inside that VPCE&#39;s private hosted zone so that the API Gateway&#39;s hostname ({api-id}.execute-api.{region}.amazonaws.com) resolves to that VPCE&#39;s ENI IPs. Without this, the API&#39;s hostname does not resolve from inside that VPC. Think of it as: <em>which VPCEs are allowed to discover this API Gateway via DNS.</em></p><p>The <strong>aws:SourceVpce condition in the resource policy</strong> (which is a separate IAM-style policy document attached to the API Gateway) controls <strong>authorization</strong>. Even if a request physically reaches the API Gateway, the resource policy decides whether the invocation is allowed. Think of it as: <em>which VPCEs are authorized to invoke this API.</em></p><p>These two are independent. You can have one without the other, and the failure modes look different.</p><pre>Configuration          | What it controls         | What if missing<br>-----------------------|--------------------------|------------------<br>vpc_endpoint_ids       | DNS resolution           | DNS errors,<br>(on the API Gateway)   | (API hostname → VPCE)    | timeouts<br>-----------------------|--------------------------|------------------<br>aws:SourceVpce         | Authorization            | ACCESS_DENIED<br>(in resource policy)   | (allow/deny by VPCE)     |</pre><p>A VPCE needs to be listed in <strong>both</strong> for the happy path to work. If a request is failing with DNS errors, suspect vpc_endpoint_ids. If it is failing with ACCESS_DENIED, suspect the resource policy. This one distinction saves a lot of debugging time.</p><h3>How Private DNS Override Actually Works</h3><p>We’ve touched on private DNS a few times now without really explaining what it is, mechanically. This section pulls back the curtain. It is shorter than the last one but denser, and understanding it makes the scenario matrix that follows much easier to reason about.</p><h4>The VPC DNS resolver</h4><p>Every VPC has a built-in DNS resolver. It lives at a reserved IP address inside the VPC, specifically at the VPC’s CIDR base plus 2. For a VPC with CIDR 10.0.0.0/16, the resolver is at 10.0.0.2. For 100.65.52.0/24, it is at 100.65.52.2. AWS calls this the <strong>Amazon-provided DNS server</strong>, and it is what every EC2 instance, Lambda ENI, container, and anything else running inside the VPC uses by default for DNS resolution.</p><p>When a resource in the VPC makes a DNS query, the resolver consults its sources in a specific priority order:</p><ol><li><strong>Route53 private hosted zones associated with the VPC.</strong> If any private hosted zone matches the queried hostname, the answer comes from there. No further lookups are performed.</li><li><strong>Route53 Resolver rules.</strong> Custom forwarding rules that redirect certain queries to specific DNS servers (for example, for resolving on-premises hostnames via Direct Connect).</li><li><strong>Public DNS</strong>, as a fallback.</li></ol><p>The critical point: <strong>private hosted zones always win over public DNS</strong>. If a name matches a private hosted zone that is associated with your VPC, the private hosted zone’s answer is what you get. Public DNS is not even queried. The resolver considers the lookup done.</p><p>This is the mechanism that the private DNS setting on a VPCE hooks into.</p><h4>What the private DNS setting actually does</h4><p>When you create an execute-api Interface VPC Endpoint with the private_dns_enabled flag set to true, AWS performs three operations on your behalf:</p><ol><li>It creates a <strong>Route53 private hosted zone</strong> for the domain execute-api.{region}.amazonaws.com.</li><li>It associates that private hosted zone with your VPC.</li><li>It adds a wildcard record: *.execute-api.{region}.amazonaws.com → the VPCE&#39;s ENI private IP addresses.</li></ol><p>From this point forward, <strong>any</strong> DNS query inside that VPC for a name matching *.execute-api.{region}.amazonaws.com resolves to the VPCE&#39;s private IPs. That includes:</p><ul><li>Any private API Gateway in the same region ({private-api-id}.execute-api.{region}.amazonaws.com)</li><li>Any regional or public API Gateway in the same region ({public-api-id}.execute-api.{region}.amazonaws.com)</li><li>Any API Gateway owned by any AWS account, anywhere, as long as its hostname matches the wildcard</li></ul><p>The wildcard does not discriminate. It has no way of knowing whether a given API ID corresponds to a private API, a regional API, your own API, someone else’s API, or an API that the VPCE was never intended to reach. As far as the DNS layer is concerned, they all match the same pattern and all resolve to the same set of private IPs.</p><h4>Why CNAMEs get caught too</h4><p>There is one more wrinkle that is worth understanding, because it is what made our original bug so invisible. The Caller Lambda was not calling {api-id}.execute-api.{region}.amazonaws.com directly. It was calling a custom domain, something that looked like a normal .com hostname. How did the private DNS override catch that?</p><p>The answer is that DNS resolution is <strong>recursive</strong>, and private DNS interception happens at every step of the recursion.</p><p>Here is what the resolver does when you give it a custom domain:</p><pre>Step 1: Query for custom-domain.company.com<br>        → Public DNS returns a CNAME pointing to d-abc123.execute-api.&lt;region&gt;.amazonaws.com</pre><pre>Step 2: Resolver follows the CNAME, now needs to resolve<br>        d-abc123.execute-api.&lt;region&gt;.amazonaws.com<br>        → This name matches the private hosted zone wildcard!<br>        → Returns VPCE ENI private IP: 10.x.x.x</pre><pre>Step 3: Done. Lambda opens HTTPS to 10.x.x.x.</pre><p>The application never sees any of this. It calls the nice-looking custom domain and gets a socket connection to what appears to be a normal HTTPS endpoint. It has no way to know that the resolver, three steps deep into a recursive lookup, got intercepted by a private hosted zone and routed the traffic somewhere completely different.</p><p>This is why the whole thing feels so mysterious when you first encounter it. There is no log line in your application, no warning from the AWS SDK, nothing in the HTTPS handshake that tells you “by the way, this call is going through a VPCE.” The DNS layer just quietly rewrote your target IP and the rest of the stack happily went along with it.</p><h4>The upshot</h4><p>Two sentences worth internalising before we move on to scenarios:</p><ol><li><strong>Private hosted zones associated with a VPC always take priority over public DNS for names they match</strong>, and an execute-api VPCE with private DNS enabled installs a wildcard private hosted zone that matches <em>every</em> API Gateway hostname in the region.</li><li><strong>DNS recursion respects the priority at every step</strong>, which means even custom domains that CNAME into *.execute-api will get rewritten to VPCE IPs, transparently, without the application knowing.</li></ol><p>Those two facts are the foundation for every scenario in the next section.</p><h3>DNS Resolution Scenarios</h3><p>Here is where everything from the last two sections gets applied. Each scenario below is a combination of how a caller reaches an API Gateway and what DNS setup is in place. For each one, I’ll show what happens and whether it works. No storytelling, just the mechanics.</p><p>A quick reminder on the URL shapes involved, because they will come up a lot:</p><ul><li><strong>Default API Gateway URL:</strong> {api-id}.execute-api.{region}.amazonaws.com</li><li><strong>VPCE-specific URL:</strong> {api-id}-{vpce-id}.execute-api.{region}.vpce.amazonaws.com</li><li><strong>Custom domain:</strong> any hostname you own, usually CNAME’d or ALIAS’d to one of the above</li></ul><h4>Scenario 1: Default URL, VPCE with private DNS enabled</h4><p>The happy path for private API Gateways. Caller uses the default URL. VPC has an execute-api VPCE with private DNS enabled.</p><pre>Scenario 1: Default URL, VPCE with private DNS enabled<br>The happy path for private API Gateways.<br>Caller uses the default URL. VPC has an execute-api VPCE with private DNS enabled.</pre><p><strong>Result: Works</strong>, assuming the VPCE is listed in vpc_endpoint_ids and allowed in the resource policy.</p><h4>Scenario 2: Default URL, no VPCE (or private DNS disabled)</h4><p>Caller uses the default URL. VPC has no execute-api VPCE, or has one with private DNS turned off.</p><pre>Caller → default URL<br>       → no private hosted zone to intercept<br>       → resolves via public DNS to public AWS IPs</pre><p>If the target is a <strong>public/regional API Gateway</strong>, this works. Traffic goes out over the internet (via NAT) and reaches the API Gateway normally.</p><p>If the target is a <strong>private API Gateway</strong>, this fails. Private APIs have no publicly routable endpoint. The connection times out or gets refused.</p><p><strong>Result: Works for public APIs, fails for private APIs.</strong></p><h4>Scenario 3: VPCE-specific URL</h4><p>Caller uses the VPCE-specific URL directly.</p><pre>Caller → VPCE-specific URL ({api-id}-{vpce-id}.execute-api.{region}.vpce.amazonaws.com)<br>       → public DNS resolves this to the VPCE&#39;s ENI private IPs<br>       → caller connects directly to those IPs</pre><p>This is the one case where private DNS doesn’t matter at all. The VPCE-specific URL is a public DNS name that always resolves to private IPs. The caller still needs actual network connectivity to those IPs (same VPC, peering, TGW, etc.), but the DNS layer is completely out of the picture.</p><p><strong>Result: Works whenever the caller has network reachability to the VPCE’s ENIs.</strong></p><p>This is also the URL you use when private DNS is intentionally disabled on the VPCE, which is a pattern we’ll see in Scenario 7.</p><h4>Scenario 4: Custom domain → default URL, private DNS enabled in caller’s VPC</h4><p>Caller uses a custom domain. The custom domain’s DNS record (CNAME or ALIAS) points at the API Gateway’s default URL. The caller’s VPC has an execute-api VPCE with private DNS enabled.</p><pre>Caller → custom-domain.com<br>       → resolves to CNAME: {api-id}.execute-api.{region}.amazonaws.com<br>       → private hosted zone intercepts the CNAME target<br>       → returns VPCE ENI private IPs</pre><p>This is CNAME recursion getting caught by private DNS, exactly what we covered in the last section.</p><p><strong>Result: Works.</strong> Same path as Scenario 1, just with a custom domain on top.</p><h4>Scenario 5: Custom domain → default URL, no private DNS in caller’s VPC</h4><p>Same as Scenario 4, but the caller’s VPC has no execute-api VPCE with private DNS.</p><pre>Caller → custom-domain.com<br>       → CNAME: {api-id}.execute-api.{region}.amazonaws.com<br>       → public DNS resolves to public AWS IPs</pre><p>Works for a public API. Fails for a private API, for the same reason as Scenario 2.</p><p><strong>Result: Works for public APIs, fails for private APIs.</strong></p><h4>Scenario 6: Custom domain → VPCE-specific URL</h4><p>Caller uses a custom domain that points directly at the VPCE-specific URL.</p><pre>Caller → custom-domain.com<br>       → CNAME: {api-id}-{vpce-id}.execute-api.{region}.vpce.amazonaws.com<br>       → public DNS resolves to VPCE ENI private IPs</pre><p>This is the pattern people use when they want a stable, pretty custom domain for a private API Gateway without relying on private DNS at all. Any caller that can resolve the custom domain and has network connectivity to the VPCE can reach it.</p><p><strong>Result: Works whenever the caller has network reachability to the VPCE’s ENIs.</strong></p><h4>Scenario 7: VPCE with private DNS disabled, vpc_endpoint_ids still set</h4><p>A trap that looks like it should work but doesn’t, unless you know the workaround.</p><p>The VPC has an execute-api VPCE. private_dns_enabled = false. The VPCE is correctly listed in the API Gateway&#39;s vpc_endpoint_ids. Resource policy allows the VPCE.</p><pre>Caller → default URL<br>       → no private hosted zone (private DNS is off)<br>       → resolves via public DNS to public AWS IPs<br>       → for a private API, there&#39;s no public endpoint<br>       → connection fails</pre><p>The common misunderstanding: “but I added the VPCE to vpc_endpoint_ids, shouldn&#39;t the network path exist?&quot; The network path <em>does</em> exist. The ENIs are there. Traffic sent to them will arrive. The problem is that <strong>DNS doesn&#39;t know to send traffic to them.</strong> Without a private hosted zone, the default URL resolves to public IPs, and no amount of vpc_endpoint_ids configuration changes that.</p><p>To actually use a VPCE with private DNS disabled, you must explicitly use the <strong>VPCE-specific URL</strong> (or a custom domain pointing at it). That bypasses the need for the private hosted zone entirely.</p><p><strong>Result: Fails with the default URL. Works with the VPCE-specific URL.</strong></p><h4>Scenario 8: Conflicting private DNS already exists</h4><p>You try to create an execute-api VPCE with private DNS enabled, and you get:</p><pre>Error: InvalidParameter: private-dns-enabled cannot be set because there is<br>already a conflicting DNS domain for *.execute-api.{region}.amazonaws.com<br>in the VPC</pre><p>This means the private hosted zone for *.execute-api.{region}.amazonaws.com is already associated with your VPC, usually because another team created a VPCE in a different VPC and associated its private hosted zone with yours (commonly done to share a single VPCE across multiple VPCs).</p><p>The fix: set private_dns_enabled = false on your new VPCE, and rely on either the existing private DNS association (if it points at a VPCE your traffic can reach), or the VPCE-specific URL, or a custom domain pointing at the VPCE-specific URL.</p><h4>Scenario 9: Public API call hijacked by a private DNS VPCE in the caller’s VPC</h4><p>This is the scenario from the beginning of this blog, promoted to its own entry because it is the most common production trap.</p><p>Caller makes an HTTPS call to a completely unrelated public API Gateway in the same region. The caller’s VPC happens to have an execute-api VPCE with private DNS enabled, installed for some other reason.</p><pre>Caller → public API URL<br>       → private hosted zone intercepts (because wildcard matches)<br>       → returns local VPCE&#39;s ENI private IPs<br>       → traffic goes through the VPCE<br>       → target API Gateway sees a 10.x.x.x source IP</pre><p>If the target API Gateway has an IP-based resource policy expecting public IPs, it sees a private IP that does not match and rejects the call with ACCESS_DENIED. If the target does not care about source IP at all, the call may actually succeed, but the traffic took an unexpected path.</p><p><strong>Result: Varies.</strong> The call itself may succeed or fail depending on the target’s resource policy. The important thing is that <strong>you have lost control of the path your traffic takes</strong>, and your application has no way to know.</p><h4>Scenario 10: Cross-region calls via VPCE (doesn’t work)</h4><p>A common architectural assumption that turns out to be wrong.</p><p>Caller in eu-central-1 wants to call a private API Gateway in eu-west-2. You try to set up an execute-api VPCE in the caller&#39;s VPC.</p><p>The problem: execute-api VPCEs are <strong>regional</strong>. A VPCE in eu-central-1 only resolves and routes traffic for API Gateways in eu-central-1. It cannot reach an API Gateway in a different region.</p><p>There is no “cross-region VPCE” option. If you need cross-region access to a private API, the options are:</p><ul><li>Deploy a regional API Gateway in each region you need to serve</li><li>Use an intermediary (e.g., a Lambda in the target region that your VPC can reach via other means) to bridge the call</li><li>Reconsider whether the API should be private in the first place</li></ul><p><strong>Result: Fails. No VPCE-only solution.</strong></p><h4>Scenario 11: Peered VPCs with asymmetric VPCE setup</h4><p>Caller is in VPC-X. VPC-X is peered with VPC-Y. VPC-Y has an execute-api VPCE with private DNS enabled. VPC-X does not have its own VPCE.</p><p>Intuition says: “we have peering, so the caller in VPC-X can reach VPC-Y’s VPCE ENIs, so this should work.”</p><p>Partial truth. Peering gives you network-layer (L3) reachability between VPCs. If VPC-X’s caller somehow had the VPCE ENI’s IP address, it could send packets there. But DNS is a separate concern. VPC-X’s resolver does <strong>not</strong> automatically know about the private hosted zone associated with VPC-Y. So when the caller in VPC-X tries to resolve the default API Gateway URL, it gets public IPs, not VPCE IPs. Traffic goes out through the internet (or fails, if the target is private).</p><p>To make this work, you have to explicitly <strong>associate VPC-Y’s private hosted zone with VPC-X</strong> in Route53. Private hosted zones support multi-VPC associations for exactly this purpose. Once associated, DNS in VPC-X also resolves the API Gateway hostname to VPC-Y’s VPCE IPs, and the peering connection carries the actual traffic.</p><p><strong>Result: Fails without explicit private hosted zone association. Works once the zone is associated with both VPCs.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tNqayaMzR-waxVYzlOZmsg.png" /></figure><h3>Spotting This in the Wild</h3><p>If you’ve made it this far, you have enough context to recognize the fingerprints of this class of problem in your own environments. Here is a short checklist I now run through whenever I am about to ship a service that talks to an API Gateway, or whenever a teammate hits an ACCESS_DENIED they cannot explain.</p><p><strong>1. Do any of your VPCs have an execute-api VPCE you did not create?</strong></p><p>Open the VPC Endpoints view in the AWS console and filter by service name. An execute-api VPCE with private DNS enabled affects every API Gateway call made from that VPC, not just calls to the API it was originally intended for. If there is one and your team did not create it, find out who did and what it is for before you ship a service into that VPC.</p><p><strong>2. Does your service call any API Gateway that has an IP-based resource policy?</strong></p><p>IP allowlists are the most common shape of resource policy that fails silently in the presence of a private DNS VPCE. If the target has a NotIpAddress deny, or a SourceIp allow limited to public corporate ranges, and your traffic might be egressing with a private IP or a NAT IP that is not in the list, you have a latent bug waiting to happen.</p><p><strong>3. Is your VPC associated with a private hosted zone for </strong><strong>*.execute-api.{region}.amazonaws.com that you did not create?</strong></p><p>Route53 → Hosted zones → look for the execute-api hosted zone → check “Associated VPCs.” If your VPC is associated with it, some other VPCE’s private DNS is affecting your resolution, even if your VPC does not have its own VPCE. Worth understanding before it surprises you.</p><p><strong>4. If you are building or planning to build a Private API Gateway, have you sorted out DNS resolution for every VPC that needs to call it?</strong></p><p>Remember that DNS is VPC-scoped. A Private API that works in VPC-A does not automatically work in VPC-B, even if VPC-B is peered with VPC-A. You either need a VPCE in VPC-B too, or an explicit private hosted zone association, or a custom domain whose resolution path works in both.</p><p><strong>5. Do you have access (directly or via a teammate) to VPC Flow Logs and Route53 Resolver Query Logs for the VPCs your service runs in?</strong></p><p>If not, this is worth fixing before you actually need them. These are the two logs that answer “where did my traffic go” and “what did DNS resolve to,” and they are invaluable in exactly the situations where your application logs are telling you nothing useful.</p><p><strong>6. Are API Gateway access logs enabled on the stages your service talks to?</strong></p><p>If not, you cannot see the $context.identity.sourceIp that the resource policy is actually evaluating. Which means when an ACCESS_DENIED happens, you are guessing. Enable access logs on any stage that has a meaningful resource policy.</p><p>None of these checks are hard. They take minutes. But they are the kind of thing that is easy to skip when you are shipping fast, and they are exactly the kind of thing that causes a half-day investigation later.</p><h3>Summary</h3><p>If I had to compress the whole story into a few lines, it would be these.</p><p><strong>An execute-api VPCE with private DNS enabled rewrites DNS for every API Gateway hostname in the region</strong>, not just for the one it was created to serve. This is the single most important fact in this blog, and the one I wish I had known before any of this started.</p><p><strong>IP-based resource policies and VPC Endpoints interact in ways that are invisible at the application layer.</strong> Your HTTPS call to a public URL might quietly be routed through a private ENI. Your NAT Gateway IP might not be what API Gateway sees. If a resource policy relies on source IP to make decisions, any VPCE or routing change upstream can flip the answer without anything in your code changing.</p><p><strong>vpc_endpoint_ids and the resource policy serve different jobs.</strong> The first controls DNS resolution, the second controls authorization. Both need to include your VPCE for the happy path to work, and when things fail, the failure mode tells you which one is wrong. DNS errors point at vpc_endpoint_ids. ACCESS_DENIED points at the resource policy.</p><p><strong>Private API Gateways need a VPCE. Always.</strong> There is no public endpoint to fall back to. If your traffic cannot reach the VPCE, it cannot reach the API.</p><p><strong>Custom domains are practically necessary</strong> for anything beyond single-VPC private API consumption. Raw VPCE hostnames and default API Gateway URLs both depend on DNS configuration that does not travel well across VPCs or accounts. A custom domain in an internal hosted zone is what makes private APIs usable at organizational scale.</p><p><strong>In a split-account AWS org, the mental model is your observability.</strong> You will not always have access to flow logs, resolver query logs, TGW route analysis, or NAT metrics. Understanding what the system <em>should</em> be doing is often the only way to form a specific enough hypothesis to ask the right question of the networking team.</p><p>And finally, the meta-lesson from the investigation itself. <strong>When two environments produce the same error, resist the urge to assume a single cause.</strong> Sometimes the universe is just unkind and you have two different bugs that happen to rhyme.</p><p>I hope this was useful. If you got here from a Google search after seeing your own ACCESS_DENIED and wondering what the hell is going on, I hope it saved you an afternoon. If you got here out of curiosity and now know a little more about how VPC Endpoints and API Gateway resource policies actually work under the hood, even better.</p><p>A small confession to close with. I am still a backend engineer, not a network person. I do not claim that everything in this blog is the last word on the subject, and I am sure there are edge cases, nuances, and corner configurations that I have not touched. If you know of one, I would love to hear about it. The comment section is open, and I read every reply.</p><p>Until the next debugging rabbit hole.</p><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=574e9f40535a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-silent-hijack-how-one-vpc-endpoint-broke-a-public-api-call-574e9f40535a">The Silent Hijack: How One VPC Endpoint Broke a Public API Call</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context, Not Chaos: How Our MCP Server Killed the Tab-Switching Tax]]></title>
            <link>https://boudhayan-dev.medium.com/context-not-chaos-how-our-mcp-server-killed-the-tab-switching-tax-13d5fd26e429?source=rss-50a2170450a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/13d5fd26e429</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Boudhayan Dev]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 08:16:42 GMT</pubDate>
            <atom:updated>2025-08-15T08:16:42.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alcUFM6Nsua79HDhGfYmhg.png" /></figure><h4><strong>From Context Chaos to Clarity: How Our MCP Server Transformed Development</strong></h4><p>Every coding session used to begin with digital archaeology. You’d grab ticket JIRA-4821, then open a cascade of browser tabs — Confluence for specifications, JIRA for requirements, GitLab for recent changes, and inevitably, a Slack search for “that conversation” where someone mentioned a critical edge case.</p><p>Sound familiar?</p><p>The problem wasn’t lack of information — it was fragmented context. The ticket said one thing, the Confluence spec another, while the real decision was buried in a Slack thread, and GitLab showed what actually shipped. Developers guessed, QA planned against moving targets, and reviews dragged on with endless clarification questions.</p><p>This context fragmentation didn’t just slow us down — it actively eroded confidence in our decisions. Every PR review became a history lesson. New team members spent weeks just learning where information lived. And worst of all, the same questions kept resurfacing: “<em>Didn’t we decide this already?</em>” “<em>Where was that documented?</em>” “<em>Why did we implement it this way?</em>”</p><h4><strong>The Lightbulb Moment</strong></h4><p>We realised we weren’t facing an AI problem. We were facing a context problem.</p><p>So we built an MCP server that pulls truth from JIRA, Confluence, GitLab, Slack, and Zephyr directly into Cursor IDE. Instead of hunting across tools, Claude 4 retrieves exactly what you need, when you need it — with receipts.</p><p>The transformation was immediate. Let me walk you through what this looks like in practice:</p><p><strong>Before</strong>: You pick up JIRA-4821. You open three tabs. The spec links to an outdated document. There’s a Slack thread where the PM said “we dropped scope B,” but you never saw it. You implement A+B. QA files a bug. Review stalls on “why did we build B?”</p><p><strong>After</strong>: You open JIRA-4821 in Cursor. Claude pulls the Confluence section titled “Scope exclusions,” shows you the exact line where B was dropped, surfaces the latest MR touching that module, and highlights the Zephyr test case that already fails on the edge case you’re about to reintroduce. You implement A, add a guard for the edge case, and reference both in your PR. Review focuses on your implementation, not backstory questions.</p><p>The result? Fewer tabs, fewer misunderstandings, and a dramatic reduction in “can you link me to that?” comments.</p><h4><strong>The Technical Implementation: Building the MCP Bridge</strong></h4><p>Our MCP server isn’t just a simple middleware layer — it’s a carefully orchestrated system designed to handle the complexity of enterprise tools while remaining responsive enough for IDE integration. Here’s what we actually built:</p><p><strong>Core Architecture</strong></p><p>At the heart of our implementation is a TypeScript-based server that implements the Model Context Protocol specification. We chose TypeScript for its strong typing support, which helped us maintain consistency across diverse API schemas. The server exposes a unified interface through which Claude 4 can query our enterprise systems.</p><pre>export class MCPServer {<br>private confluenceClient: ConfluenceClient;<br>private jiraClient: JiraClient;<br>private gitlabClient: GitLabClient;<br>private slackClient: SlackClient;<br>private zephyrClient: ZephyrClient;<br>constructor(config: MCPConfig) {<br>// Initialize clients with authentication<br>this.confluenceClient = new ConfluenceClient(config.confluence);<br>this.jiraClient = new JiraClient(config.jira);<br>// …and so on<br>}<br>// MCP tool handlers that Claude can invoke<br>async handleConfluencePageRequest(pageId: string): Promise&lt;ConfluencePage&gt; {<br>return this.confluenceClient.getPage(pageId);<br>}<br>async handleJiraIssueSearch(jql: string): Promise&lt;JiraIssue[]&gt; {<br>return this.jiraClient.searchIssues(jql);<br>}<br>// Many more tool handlers…<br>}</pre><p><strong>Client Implementations</strong></p><p>Each client is a specialised module that handles:</p><p>1. Authentication and token refresh<br>2. Rate limiting and backoff<br>3. Data normalisation<br>4. Error handling and recovery<br>5. Smart caching with TTL</p><p>For example, our Slack client is particularly sophisticated:</p><pre>export class SlackClient {<br>private tokenManager: TokenManager;<br>private cache: Cache&lt;SlackConversation&gt;;<br>async searchGroupChat(params: {<br>participantNames: string[];<br>keywords?: string[];<br>daysBack?: number;<br>}): Promise&lt;SlackConversation&gt; {<br>// Check cache first<br>const cacheKey = this.generateCacheKey(params);<br>const cached = await this.cache.get(cacheKey);<br>if (cached) return cached;<br>// Resolve user IDs from names<br>const userIds = await this.resolveUserIdsFromNames(params.participantNames);<br>// Find relevant conversations<br>const conversations = await this.findConversationsWithUsers(userIds);<br>// Search messages within timeframe<br>const messages = await this.searchMessagesInConversations(<br>conversations,<br>params.keywords,<br>params.daysBack || 30<br>);<br>// Process and normalize results<br>const result = this.processAndNormalizeMessages(messages);<br>// Cache with TTL<br>await this.cache.set(cacheKey, result, 60 * 15); // 15 minutes<br>return result;<br>}<br>// Many more methods…<br>}</pre><p><strong>Unified Schema Layer</strong></p><p>The key to making this work was our schema normalisation layer. We built a unified data model that maps entities across all systems:</p><pre>// Core entity types<br>export interface Person {<br>id: string;<br>name: string;<br>email: string;<br>aliases: string[]; // Different usernames across systems<br>}<br>export interface Artifact {<br>id: string;<br>type: &#39;ticket&#39; | &#39;document&#39; | &#39;code&#39; | &#39;test&#39; | &#39;conversation&#39;;<br>title: string;<br>content: string;<br>created: Date;<br>modified: Date;<br>author: Person;<br>contributors: Person[];<br>links: ArtifactLink[]; // References to other artifacts<br>}<br>export interface ArtifactLink {<br>targetId: string;<br>targetType: string;<br>relationship: &#39;references&#39; | &#39;implements&#39; | &#39;tests&#39; | &#39;blocks&#39; | &#39;is-blocked-by&#39;;<br>}</pre><p>This schema allowed us to implement cross-tool entity resolution, like finding all conversations related to a ticket, or all code changes implementing a spec section.</p><p><strong>Intelligent Retrieval Strategies<br></strong>We discovered that naive retrieval doesn’t work — Claude’s context window is valuable real estate. We implemented several strategies:</p><p>1. <strong>Progressive disclosure</strong>: Return summaries first, then detailed content on follow-up<br>2. <strong>Entity-centric retrieval</strong>: When asking about a JIRA ticket, automatically fetch linked artifacts<br>3. <strong>Contextual prioritization</strong>: Weigh recency, proximity, and explicit references when ranking results<br>4. <strong>Content chunking</strong>: Break large documents into semantic sections for targeted retrieval</p><p><strong>Observability and Management<br></strong>To manage this complexity, we built comprehensive observability:</p><p>1. A telemetry system tracking latency per client and endpoint<br>2. Circuit breakers that gracefully degrade service per integration<br>3. Token lifecycle management to handle rotation and refresh<br>4. Audit logs for all data access<br>5. Admin dashboard showing system health and usage patterns</p><h4><strong>Under the Hood: What Made This Work</strong></h4><p>Building this wasn’t just about connecting APIs. We discovered four principles that made the difference between “interesting toy” and “game-changing tool”:</p><p>1. <strong>Canonical schema</strong>: We mapped tickets, specs, PRs, tests and incidents into one vocabulary. One person across tools resolves to one identity.</p><p>2. <strong>Targeted retrieval</strong>: Rather than overwhelming Claude with everything, we fetch only what’s relevant to your current file, ticket, or test — on demand, with citations.</p><p>3. <strong>Source-of-truth bias</strong>: Claude grounds answers in retrieved artifacts — snippets from Confluence, JIRA fields, MR diffs, Slack decision threads, Zephyr steps.</p><p>4. <strong>Latency discipline</strong>: IDE requests have hard budgets. We cache with TTLs, stream partials, back off under load, and degrade gracefully per-source.</p><p>The impact was profound. PR discussions shifted from “why are we doing this?” to “how well does this implementation work?” Onboarding stopped being a scavenger hunt. QA could author tests directly from live acceptance criteria and decision threads.</p><h4><strong>The Unexpected Lessons</strong></h4><p>Each integration taught us something unique:</p><p><strong>Confluence isn’t uniform</strong>: Tables, macros, and micro-templates break naive parsing. We built resilient HTML-to-plain extraction with fallbacks, plus per-space transforms to handle the chaos.</p><p>For example, our Confluence client had to:<br>- Extract text from nested tables without losing structure<br>- Handle custom macros that rendered differently per space<br>- Preserve image references and provide metadata for Claude’s vision features<br>- Account for Confluence’s inconsistent heading hierarchy</p><p><strong>JIRA’s truth lives in custom fields</strong>: “Definition of Done,” “Risk,” and “Edge Cases” are often custom. We run field-discovery passes per project and bind by ID rather than name.</p><p>Our JIRA integration includes a field discovery mechanism that:<br>- Maps custom field IDs to semantic meanings<br>- Builds a project-specific schema for each JIRA instance<br>- Updates mappings when field configurations change<br>- Preserves historical values even when fields are renamed</p><p><strong>Slack decisions are buried in replies</strong>: We trim threads to the decision point and include only the message lineage that changed scope or behavior — not the entire conversation.</p><p>Our Slack retrieval had to:<br>- Identify “decision” messages using semantic indicators<br>- Follow threading correctly to maintain conversation context<br>- Filter out chit-chat while preserving critical discussion<br>- Connect user identities across systems (Slack handle to JIRA username)</p><p><strong>GitLab diffs go stale</strong>: Merge refs and pagination can lie by omission. We fetch by SHA, not branch, and re-validate against HEAD before presenting context.</p><p>Our GitLab client handles:<br>- Full commit history for context on code evolution<br>- Proper diff visualisation within the IDE<br>- Branch and commit resolution to exact points in time<br>- File content at specific commits for historical reference</p><p>The biggest surprise? Slack integration. We expected it to be occasionally useful for archaeological purposes. Instead, it became our most-used feature. The best context for “why does this code exist?” lives in chat history, not formal documentation.</p><h4><strong>The New Pains (Because Nothing’s Free)</strong></h4><p>Our MCP server solved many problems but introduced new challenges:</p><p><strong>Permissions and OAuth complexity</strong>: Multiple sources mean multiple failure modes. We tightened scopes, rotated tokens, and added audit logs.</p><p>The authentication architecture alone required:<br>- OAuth flow management for each integrated system<br>- Token rotation and refresh scheduling<br>- Permission scope mapping and validation<br>- Audit trails for all data access<br>- Circuit breakers for auth failures</p><p><strong>Schema drift</strong>: JIRA custom fields and Confluence templates change without notice. We built field discovery and schema versioning to avoid silent breakage.</p><p>Our schema handling includes:<br>- Scheduled schema validation jobs<br>- Alerts for detected changes<br>- Version tracking for backward compatibility<br>- Schema migration paths for seamless updates</p><p><strong>Rate limits and staleness</strong>: Slack/GitLab pagination can yield incomplete results. We pin SHAs, validate against head, and add backpressure and circuit breakers.</p><p>Our rate limit management includes:<br>- Per-integration rate tracking<br>- Adaptive backoff algorithms<br>- Queue prioritization for interactive requests<br>- Background refresh for frequently accessed resources<br>- Clear staleness indicators in the UI</p><p><strong>Hallucination guardrails</strong>: Retrieval is strict — if we don’t have a citation, the assistant says so rather than making things up.</p><p>We implemented:<br>- Citation requirements for all assertions<br>- Confidence scoring for retrieved content<br>- Source attribution for every information snippet<br>- Explicit uncertainty indicators when data is incomplete</p><p>Error handling taught us humility. Enterprise systems have creative ways of failing. Network timeouts, permission changes, API rate limits — our server needed graceful degradation for each integration point. We built fallback paths for each critical feature and made sure users always understood what context might be missing.</p><h4><strong>Beyond Engineering: The Ripple Effects</strong></h4><p>The immediate wins were for developers, but the impact quickly spread:</p><p><strong>QA engineers</strong> started building tests from live artifacts, pulling steps from Confluence, linking to JIRA acceptance criteria, and auto-tagging with recent defects touching the same modules.</p><blockquote>One QA engineer shared: “<em>I used to spend half my day just figuring out what to test. Now I ask Claude to show me ‘all edge cases mentioned in specs or discussions for this feature,’ and I can build comprehensive test plans in minutes.</em>”</blockquote><p><strong>Product managers</strong> discovered their decisions became instantly discoverable where work happens. Specs weren’t static PDFs; they became living, queryable sources.</p><p><strong>DevOps teams</strong> found new workflows for incident management. When on-call engineers got paged, they could immediately ask for “all recent deploys affecting service Z” and get a timeline of changes with commit messages, PR discussions, and linked tickets.</p><h4><strong>The Future Integration Landscape</strong></h4><p>While our current implementation focuses on development tools, we’re already exploring expansions into other domains:</p><p><strong>Customer knowledge integration</strong>: Connecting Salesforce, Zendesk, and product analytics to help product teams understand user needs in context.</p><p><strong>Documentation coherence</strong>: Linking technical documentation, architecture decisions, and implementation details to ensure consistency as systems evolve.</p><p><strong>Learning and onboarding</strong>: Building personalized onboarding paths that adapt based on a new team member’s role and current project focus.</p><p><strong>Cross-functional decision support</strong>: Helping leadership teams trace from strategy documents to implementation details without requiring technical deep dives.</p><p>The pattern is consistent: eliminate context switching, bring information to where decisions happen, and maintain provenance through citations.</p><h4><strong>The Real Win</strong></h4><p>This wasn’t about automating coding. It was about removing the tax on understanding.</p><p>With our MCP server, conversations changed from “<em>where is the truth?</em>” to “<em>is the current decision still correct?</em>” That single shift compounded across engineering, QA, and product — and that’s where the leverage lives.</p><p>We’re not building AI that replaces human judgment. We’re building AI that augments human context, reducing the friction between having an idea and implementing it correctly.</p><p>The next frontier? Expanding beyond engineering. Imagine sales engineers analyzing customer requirements against architecture documents to identify product gaps before demos. Or support teams tracing customer issues through code changes, documentation updates, and team conversations for faster resolution.</p><p>These aren’t grand transformations — they’re practical applications of unified access to enterprise context. The goal remains simple: reducing the friction between having a question and finding a comprehensive answer, regardless of where that information lives.</p><h4><strong>Epilogue: The Context Revolution</strong></h4><p>Looking back, the journey to build our MCP server revealed something profound about knowledge work: the productivity tax we’ve been paying isn’t primarily about tools or talent — it’s about context fragmentation.</p><p>We’ve normalized a world where information lives in dozens of specialized silos, and humans are the integration layer. We tab-switch, copy-paste, and re-explain the same concepts across tools and teams. It’s a tax we’ve accepted for so long that we’ve stopped noticing its cost.</p><p>But that era is ending. The combination of AI assistants and intelligent context retrieval is eliminating this tax. When Claude can instantly pull the exact Confluence page section about feature constraints, alongside the Slack thread where the product manager clarified edge cases, and the GitLab MR that implemented a similar pattern last month — we’re not just saving time. We’re fundamentally changing how knowledge flows through organizations.</p><p>The most exciting part? This is just the beginning. As more teams adopt this pattern, we’ll see new norms around documentation, decision-making, and institutional memory. Knowledge will become more discoverable, decisions more transparent, and teams more aligned — not because we’re enforcing new processes, but because the path of least resistance now leads to better context.</p><p>If you’re building something similar for your team, start small, focus on solving real friction points, and measure the impact not just in time saved, but in confidence gained. The organizations that master context integration won’t just move faster — they’ll make better decisions along the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13d5fd26e429" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic chunking in practice]]></title>
            <link>https://boudhayan-dev.medium.com/semantic-chunking-in-practice-23a8bc33d56d?source=rss-50a2170450a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/23a8bc33d56d</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chunking]]></category>
            <dc:creator><![CDATA[Boudhayan Dev]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 19:26:40 GMT</pubDate>
            <atom:updated>2024-01-03T19:26:40.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KMV5ivYJROwVjWoh" /><figcaption>Photo by <a href="https://unsplash.com/@tamara_photography?utm_source=medium&amp;utm_medium=referral">Tamara Gak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Recap</strong></h3><p>What a year 2023 has been!<br>Busy, happening, and most importantly, filled with breakthroughs in the software development space.</p><p>One such breakthrough — the availability of enterprise-ready <strong>LLMs (Large language models)</strong> has taken the industry by storm and is believed to make greater inroads in the year 2024. LLMs will become mainstream and are going to be infused into every aspect of software and product development. From business AI to gaming, there is not going to be any frontier that will remain untouched by the effects of LLM.</p><p>Good or bad? Only time will tell. The arms race is on and there is no looking back.</p><p>LLMs though are a very interesting topic from a technical perspective. I have been busy trying to keep myself updated on the workings of LLM. As a non-data scientist, it is both intimidating as well as mind-blowing. The capabilities of different LLMs — multimodal/ unimodal etc, various prompting techniques — ReAct, CoT (Chain of thought), etc, RAG — retrieval augmented generation, Fine-tuning……….. the list goes on. I have been fortunate enough to get a chance to work on these topics. The topics are vast and are continuously evolving. No two roadblocks are going to be the same and that&#39;s precisely what keeps the LLM journey so exciting.</p><p>This blog is going to be about one such roadblock — <strong><em>chunking</em></strong>. Or more precisely, semantic chunking of sections of a document so that the data that is fed to the LLMs (as part of prompts) is more precise and meaningful for the context of the prompt.</p><p>Let’s begin.</p><h3>Problem</h3><p>Consider that you are given a document that contains some texts and images, arranged into several sections (could be nested sections too), just like a book/novel/architecture doc.</p><p>In other words, any structured document that you might have come across.</p><p>Now, the ask is to split the document and extract the sections i.e. retain the semantic meaning of the chunks. Before you come up with a solution, here are a few additional restrictions (real life) —</p><ol><li>As outlined, the chunks have to be mapped to sections i.e. you cannot randomly create chunks based on page numbers, length of words/ characters, etc.</li><li>The document does not have an index/table of contents.</li><li>Do not assume the size of the sections. Some of them are a few paragraphs long while some could run into pages.</li><li>Do not assume the start/end positions of the sections in the document. They may / may not start/end at the beginning/end of a page. They could very well start at the middle of the page.</li><li>Do not assume the font size/style of the document. We need to support all and any kinds of documents.</li><li>Needless to say, the document is larger than the context size (max tokens that an LLM prompt can take) of the LLM that you can use (will you ? :P ) for this problem.</li></ol><p>For example, consider a page from a document such as the following —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*IaP2PSqSvr39BfpUZuoEqA.png" /></figure><p>This is a page from the document, which shows the following structure —</p><ol><li>Prologue</li><li>Methodology</li></ol><p>Note: I have ignored Approach 1 and Approach 2 under Methodology as the relative font height is smaller than Methodology, indicating they are child sections. However, if you were to identify the structure of the sections as follows, it would also be right. Ex -</p><ol><li>Prologue</li><li>Methodology</li><li>Approach 1</li><li>Approach 2</li></ol><p>The level of nestedness that you want to identify is left up to you. You can choose to club child sections together as one major section (as example 1) or you could present them as separate sections (as example 2). What is important, is the identification of these sections in the first place.</p><p>Example 1 -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*aEquEvunMt3Mp9DdVjLt3Q.png" /></figure><p>Example 2 -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*YTDAEUAW6ODL2vA8agK3WQ.png" /></figure><p>So, given the above restrictions, how do you go about extracting the sections?</p><p><strong>Note</strong>: It is not expected to achieve 100 % accuracy as the candidate pool for the document is huge.</p><h3>Design</h3><p>As you’d have guessed, the solution is not very straightforward. At least, not something that can be solved with a deterministic algorithm. We are talking about <strong><em>autonomous detection and extraction of sections</em></strong> from a document. As if that was not difficult enough, we also intend the solution to work for any kind of document i.e. font used, style of writing, formatting of content, etc.</p><blockquote>Difficult? Sure. But not impossible. <br>Definitely not, in the era of LLMs.</blockquote><p>Before we attempt the solution, here are a few observations.</p><p><strong>Observation 1 -&gt;</strong> For any well-structured document, the section sizes will follow a pattern i.e. level 1 sections will have the same font size and style say 2X, next level section may have a smaller size — say X, and so on… But they will be consistent across the document.</p><p><strong>Observation 2 -&gt;</strong> Section headers/ titles are typically evenly distributed across the document. They are not clustered at the beginning or only at the end of the document. So throughout the document, there is a good chance to encounter a section title/header.</p><p><strong>Observation 3 -&gt;</strong> Section titles/headers are few as compared to the paragraphs or non-section text in the document.</p><p><strong>Observation 4 -&gt;</strong> Section titles/headers are generally bigger (font size) than the surrounding text and have fewer characters as compared to the surrounding blocks of text.</p><h4>Thats it!<br>As long as we can identify the positions of the section titles/headers in the document, we can extract the blocks of text between 2 subsequent sections and meet our objective.</h4><p>To identify a line as a possible section title/header, we are going to make use of LLM (any LLM should work, used GPT 3.5 for this blog).</p><blockquote>What better than an LLM to make the above deductions for a given document !</blockquote><p>So let us now look at the implementation.</p><h3>Solution</h3><p>Let us start by adding the dependencies. We are going to use Java. To parse the document, we will use the <a href="https://pdfbox.apache.org/">Apache PDFBox</a> library.</p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;org.apache.pdfbox&lt;/groupId&gt;<br> &lt;artifactId&gt;pdfbox&lt;/artifactId&gt;<br> &lt;version&gt;2.0.27&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Now, the default PDF Reader class in the PDFBox library will not provide the metadata that we are interested in i.e. the font size, total characters in the line, and the corresponding lines having the identical metadata. To record these metadata (why ? later) as we pass through the document, we will have to create a custom text parser that will record the same.</p><p>Let us create a model that will capture the font metadata.</p><pre>@Data<br>public class DocumentLineItem {<br>    float positionX;<br>    float positionY;<br>    String content;<br>    int fontHeight;<br>    int totalCharacters;<br><br>    @Override<br>    public String toString(){<br>        return this.content;<br>    }<br>}</pre><p>Now, let us implement the text parser.</p><pre>public class TextParser extends PDFTextStripper {<br><br>    private static final Logger oLogger = LoggerFactory.getLogger(TextParser.class);<br>    private final List&lt;DocumentLineItem&gt; lineItems;<br>    private final int pageStart;<br>    private final int pageEnd;<br>    private final PDDocument docu;<br>    private final float pageHeight;<br>    private int pageCounter;<br><br>    public TextParser(PDDocument document) throws IOException {<br>        this.pageStart = 1;<br>        this.pageEnd = document.getNumberOfPages();<br>        this.docu = document;<br>        this.pageHeight = this.docu.getPage(0).getMediaBox().getHeight();<br>        this.pageCounter = 0;<br>        this.lineItems = new ArrayList&lt;&gt;();<br>    }<br><br>    @Override<br>    protected void writeString(String text, List&lt;TextPosition&gt; textPositions) throws IOException {<br>        super.writeString(text, textPositions);<br>        this.createLineItems(text, textPositions);<br>    }<br><br>    private void createLineItems(String lineText, List&lt;TextPosition&gt; textPositions){<br>        DocumentLineItem documentLineItem = new DocumentLineItem();<br>        documentLineItem.setPositionX(textPositions.get(0).getXDirAdj());<br>        documentLineItem.setPositionY(this.pageCounter*this.pageHeight + textPositions.get(0).getYDirAdj());<br>        documentLineItem.setContent(lineText);<br>        documentLineItem.setFontHeight((int) textPositions.get(0).getHeight());<br>        documentLineItem.setTotalCharacters(lineText.length());<br>        this.lineItems.add(documentLineItem);<br>    }<br><br>    public List&lt;DocumentLineItem&gt; getLineItems() throws ParseException{<br>        try{<br>            for(int i=this.pageStart; i&lt;=this.pageEnd; i++){<br>                this.setStartPage(i);<br>                this.setEndPage(i);<br>                this.getText(this.docu);<br>                this.pageCounter++;<br>            }<br>            return this.lineItems;<br>        } catch (Exception e){<br>            oLogger.error(e.getMessage());<br>            throw new ParseException(&quot;Error reading text line items&quot;);<br>        }<br>    }<br>}</pre><p>We create a <strong>getLineItems() </strong>in the text parser, which invokes the <strong>writeString()</strong> method internally when the <strong>getText() </strong>method is invoked to read the page contents. The text parser creates a list of <strong>DocumentLineItem </strong>which contains information about each line’s —<em> text, font height, total characters, and positions in the document</em>.</p><p>The next step is to use this parser and read the PDF document. Once the list of DocumentLineItem is created, we will feed the info to the LLM to derive the font heights that are possible candidates for the section headers.</p><p>To use LLM, the following information is required -</p><ol><li>The list of all font heights in the document.</li><li>The pattern of font distribution across the entire document. We would also need to pass the total characters + font height for such distribution.</li></ol><p>The LLM can deduce from this pattern, the possible section header font sizes.</p><p>The <strong>list of unique fonts</strong> and the <strong>pattern of</strong> <strong>font variation across the document</strong> can be found using the following code.</p><pre><br>/***<br> The following method return unique set of font heights found in the document<br>*/<br>private List&lt;Integer&gt; getListOfFonts(List&lt;DocumentLineItem&gt; contentLineItems) {<br>    Set&lt;Integer&gt; fontHeights = new TreeSet&lt;&gt;(Comparator.reverseOrder());<br>    for(DocumentLineItem lineItem: contentLineItems) fontHeights.add(lineItem.getFontHeight());<br>    return new ArrayList&lt;&gt;(fontHeights);<br>}<br><br><br>/*** <br>  The following method is used to construct the variation of font across the document<br>  The following section creates a list of font metadata that is fed to the LLM<br>  The data returned by the method preserves the document style by removing the content.<br>*/<br>private String getFontMetadata(List&lt;DocumentLineItem&gt; contentLineItems) throws ParseException{<br>    try{<br>        StringBuilder sb = new StringBuilder();<br>        int currentHeight = contentLineItems.get(0).getFontHeight();<br>        int totalCharacters = contentLineItems.get(0).getTotalCharacters();<br>        int lineCount = 1;<br>        for(int i=1; i&lt;contentLineItems.size(); i++){<br>            DocumentLineItem lineItem = contentLineItems.get(i);<br>            if(lineItem.getFontHeight()!=currentHeight){<br>                sb.append(&quot;Metadata(fontHeight=&quot;).append(currentHeight).append(&quot;, lineCount=&quot;)<br>                        .append(lineCount).append(&quot;, totalCharacters=&quot;).append(totalCharacters).append(&quot;)\n&quot;);<br>                currentHeight = lineItem.getFontHeight();<br>                totalCharacters = lineItem.getTotalCharacters();<br>                lineCount = 1;<br>            } else {<br>                totalCharacters+=lineItem.getTotalCharacters();<br>                lineCount+=1;<br>            }<br>        }<br>        sb.append(&quot;Metadata(fontHeight=&quot;).append(currentHeight).append(&quot;, lineCount=&quot;)<br>                .append(lineCount).append(&quot;, totalCharacters=&quot;).append(totalCharacters).append(&quot;)\n&quot;);<br>        if(currentHeight==-1) throw new ParseException(&quot;Error : No document found for section title detection&quot;);<br>        return sb.toString();<br>    } catch (Exception e){<br>        oLogger.error(&quot;Error constructing font metadata for document - {}&quot;, e.getMessage());<br>        throw new ParseException(&quot;Error constructing font metadata&quot;);<br>    }<br>}</pre><p>Now, once you have the font list and the pattern of font distribution in the document, all that is left is to construct a nice prompt for the LLM to deduce the possible font sizes.</p><p>Following is an example prompt that you can use to deduce the font sizes that are possible candidates for the section headers.</p><pre>OBJECTIVE -<br><br>You are a AI assistant that is an expert at reading documents.<br>You will be provided the metadata information about all the lines that are contained in a document.<br>The objective is to figure out the section headers from the metadata.<br><br>Section Headers:<br>Section headers are basically topic headers that form the starting point of different sections.<br><br>***********************************************************<br><br>You will be provided with a list of metadata in the following structure:<br><br>Metadata(fontHeight=6, lineCount=3, totalCharacters=24)<br>Metadata(fontHeight=5, lineCount=1, totalCharacters=1)<br>Metadata(fontHeight=8, lineCount=1, totalCharacters=4)<br>Metadata(fontHeight=6, lineCount=1, totalCharacters=103)<br><br>and a list of decreasing unique font heights, which indicates all the font sizes that are available in the document :<br><br>[20, 18, 9, 6, 4....]<br><br><br>where,<br><br>fontHeight = height of the given line<br>lineCount = number of consecutive lines that have the same fontHeight<br>totalCharacters = total characters that these consecutive lines contain.<br><br>***********************************************************<br><br>RULES :<br><br>Generally, section headers/ titles have the following properties -<br>1. They are bigger in size than the surrounding text.<br>2. They are few in number compared to the total text that the document contains<br>3. The total characters of such lines are significantly lower as compared to the surrounding lines.<br>4. They are generally evenly spread across the document and not clustered at the beginning or end of the document.<br><br><br>***********************************************************<br><br>OUTPUT RESPONSE :<br><br><br>I want you to utilize the metadata of the fonts and the list of all available font sizes, to give me the possible section (can have sub-sections as well) titles.<br>I want the response as a list of Comma separated font sizes. i.e.<br><br>Ex - [20, 18 ..]<br><br>In the above, 20 and 18 are the font sizes from the metadata list that you consider to be section headers. <br>1. Do not contain any explanation or code.<br>2. Response should be comma separated list of font sizes that are possible sections<br><br><br>Here is the List of all font sizes : <br><br>&lt;&lt;INSERT LIST OF ALL FONTS IN THE DOCUMENT&gt;&gt;<br><br>Here is the list of font metadata for the whole document: <br><br>&lt;&lt;INSERT FONT PATTERN METADATA FOR THE DOCUMENT&gt;&gt;</pre><p>With the above prompt, you will be able to receive a list of font heights, that the LLM constitutes as section headers. We must use a very low value for <strong><em>temperature </em></strong>for this exercise to achieve a high degree of accuracy.</p><p>The response from the LLM can be used as a basis to formulate possible section headers and therefore sections from the document.</p><p>For the document used as an example (see Problem section), the LLM rightly identified font sizes —<strong> 9 and 8 as section headers,</strong> which correspond to <strong>Prologue (9), Methodology (9), Approach 1 (8), and Approach 2 (8).</strong></p><p>Now that we know the section headers, we can extract the section content easily !!!</p><p>Here, let me show you the results.</p><ol><li>Printing out the font heights of each line of the document with their content in the following notation: <strong>FONT_HEIGHT -&gt; CONTENT</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53LHISvT5JCIewTGJt1srA.png" /></figure><p>Keep an eye on the highlighted font sizes.</p><p>2. Now we find out the list of all unique font sizes in the document as well as the font pattern distribution for the whole document (using the <strong>getListOfFonts() </strong>and <strong>getFontMetadata()</strong> methods above).</p><p>Following is the output for the document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*SjO_iWtaJqiQkJ6PNLUgJw.png" /></figure><p>As you can see from the pattern, the <strong>font heights</strong> and the <strong>total characters for successive identical lines</strong> (same font height) are retained. As a result, the overall <strong>font pattern distribution</strong> over the document is retained which will be used in the next stage to deduce the section headers.</p><p>3. Now that we have the above information, we use the LLM prompt to filter the pattern distribution data and extract the font sizes that could be probable section headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAPLck-0bPNpXw43FOkFTw.png" /></figure><p>As you can see from the response, font sizes 9 and 8 are identified as possible section headers based on the pattern distribution. If you recall, font sizes 9 and 8 refer to the section headers highlighted in example 2 in the Problem section.</p><h3>Conclusion</h3><p>I hope this blog gave you an idea of how to leverage LLM to autonomously identify sections from a document. This can help you to prepare meaningful splits of your data for RAG-based use cases or to prepare the vector database contents for embeddings. The efficiency of the solution can be improved by adding more metadata such as font name, style, etc. to the pattern distribution in the prompt.</p><p>Warm Regards!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23a8bc33d56d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Spring Security setup]]></title>
            <link>https://medium.com/swlh/demystifying-spring-security-setup-e0491acc7df7?source=rss-50a2170450a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0491acc7df7</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Boudhayan Dev]]></dc:creator>
            <pubDate>Sat, 01 May 2021 19:05:56 GMT</pubDate>
            <atom:updated>2021-05-01T19:05:56.121Z</atom:updated>
            <content:encoded><![CDATA[<p>The code samples used in this article can be found at the following link :</p><p><a href="https://github.com/boudhayan-dev/security-filter">boudhayan-dev/security-filter</a></p><h3>Background</h3><p>So the previous weekend, I reconnected with an old friend of mine and we found ourselves discussing the Spring framework and its support for application security. Throughout the conversation, I could feel a nagging question lingering at the back of my mind -</p><p><em>Do I </em><strong><em>really </em></strong><em>know how Spring wires up its security infrastructure? Or am I just bluffing? <br>Imposter Syndrome, one might say.</em></p><p>The weekend passed and I resumed my usual work but I could still feel the question looming at the back of my mind. So much so, that I spent an entire afternoon trying to piece together info on Spring security setup. But I soon realized that it will take a little more than an afternoon’s lazy googling to get answers to all my questions.</p><p>So after a good deal of research, here I present a recount of my findings and understanding of how Spring Framework (Spring Boot) <strong><em>Auto-configures </em></strong>Spring Security. I have included code samples and examples from the spring framework library to explain the concept better.</p><p>Happy reading!</p><h3><strong>Security Architecture</strong></h3><p>So first things first, spring-security works through <strong>filters</strong>. If you were to put a debugger in your rest controller methods, you’d see several servlet filters, ex — <em>UsernamePasswordAuthenticationFilter</em>, <em>CsrfFilter</em>, etc (the complete list can be found <a href="https://docs.spring.io/spring-security/site/docs/current/reference/html5/#servlet-security-filters">here</a>) are stacked in a filter chain. Each filter executes its logic and then forwards the incoming request down the filter chain.</p><p>Now, you must be wondering -</p><ol><li><em>How do these individual filters know which filter to call next?</em></li><li><em>How does Spring boot know which set of filters to invoke before passing on the request to the Rest Controllers?</em></li><li><em>Are these sets of filters fixed?</em></li><li><em>What happens when we have different authentication &amp; authorization mechanism in place? Does the list of filters change?</em></li><li><em>If we have multiple authentication mechanisms in place, does it mean that there will be multiple lists of filters? In that case, how does spring boot auto-configure the correct list of filters?</em></li></ol><p>And so on …</p><p>Well, you are not alone. I too had the same doubts and therefore I decided to dig further.</p><p>To understand the setup better, let me add the filter setup diagram from <a href="https://docs.spring.io/spring-security/site/docs/current/reference/html5/#servlet-securityfilterchain">Spring Security Documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*JScorB4xO9feqZuaYTtBXg.png" /><figcaption>Spring Security Architecture</figcaption></figure><p>The important piece of information from the above picture is -</p><ul><li><strong>DelegatingFilterProxy</strong></li><li><strong>FilterChainProxy</strong></li><li><strong>SecurityFilter(s)</strong></li></ul><p>Let me break them down one by one.</p><ol><li><strong>DelegatingFilterProxy — </strong>This is a servlet filter embedded in the spring context. Its job is to delegate the incoming request to a bunch of filters (not managed as spring beans) provided by the Spring web framework and hence the name, DelegatingFilterProxy. We will see later on how Spring Boot constructs this Filter with some code examples.</li><li><strong>FilterChainProxy </strong>— This is another layer of indirection provided by Spring security. This is also a servlet filter whose job is to invoke the relevant filters that would work on the incoming request. Like the DelegatingFilterProxy, it also does not perform any logic. This filter is however provided by the Spring security package.</li><li><strong>SecurityFilter</strong>(s) — This is the most interesting bit in the above chain. This class basically contains a list of actual filters that need to be invoked before the controller can handle the request. It contains filters for example — <em>SecurityContextPersistenceFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, UsernamePasswordAuthenticationFilter etc</em>. when one uses the default security config. FilterChainProxy queries this class to invoke each filter in a loop.<br>There can be multiple SecurityFilterChain, each having its own stack of filters which could be the same or different from the other SecurityFilterChain.</li></ol><blockquote>But how are these filters being constructed? <br>And more importantly how is spring boot auto-configuring all these complex filters in the background?</blockquote><p>To understand the auto-configuration of the entire setup, let me enhance the above diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92ROUlbK-TQaNHB_FSjkjw.png" /><figcaption>Enhanced setup</figcaption></figure><p>The text in bold — <strong>SecurityFilterAutoConfiguration</strong>, <strong>WebSecurityConfiguration</strong> and <strong>WebSecurityConfigurerAdapter</strong> are the java class names that are responsible for the creation of <strong>DelegatingFilterProxy</strong>, <strong>FilterChainProxy </strong>and <strong>SecurityFilterChain</strong> respectively.</p><p>The boxes colored yellow/red are the components that are used in the security filtering part of the request.</p><p>The box in green — <strong>DispatcherServlet </strong>is called once the request is validated by the filter chain.</p><p>Let us explore them one by one.</p><h4><strong>DelegatingFilterProxy</strong></h4><p>This proxy filter is created by spring boot in <strong>SecurityFilterAutoConfiguration</strong> class as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc4f9d5029de7abc030173f5e21230e9/href">https://medium.com/media/dc4f9d5029de7abc030173f5e21230e9/href</a></iframe><p>You’d notice that Spring boot autoconfigures a Bean of the type <strong>DelegatingFilterProxy </strong>via a filter registration class -&gt; <strong>DelegatingFilterProxyRegistrationBean </strong>class. The bean is only created if another bean named -&gt; <strong>springSecurityFilterChain </strong>is found in the classpath.</p><p><strong>springSecurityFilterChain</strong> is an alias for the Spring Security’s <strong>FilterChainProxy </strong>class. It means this filter is optional and only created if we use spring security in our application.</p><p>You’d also notice that while creating this DelegatingFilterProxy Filter, we pass the <strong>springSecurityFilterChain </strong>name in its constructor. It is done, to set the delegation link between the two classes. DelegatingFilterProxy uses this delegation link during runtime to invoke spring security functionality. A snippet of how it is done is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cbe3ab51c5c9dabe8ca443f4232b3a9/href">https://medium.com/media/9cbe3ab51c5c9dabe8ca443f4232b3a9/href</a></iframe><p><strong>this.delegate</strong> refers to the FilterChainProxy Bean.</p><h4>FilterChainProxy</h4><p>Now, let us see how the FilterChainProxy is configured by Spring Security.</p><p><strong>FilterChainProxy </strong>is configured whenever we use the <strong><em>@EnableWebSecurity</em></strong> annotation in the security config. An example of it is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72dc37ace1c8b179a92141a8815b3e4b/href">https://medium.com/media/72dc37ace1c8b179a92141a8815b3e4b/href</a></iframe><p>If you inspect the <strong><em>@EnableWebSecurity </em></strong>annotation further, you&#39;d notice that it imports the class -&gt; <strong>WebSecurityConfiguration, </strong>class. This is where all the magic is happening. The exact code block that is creating the FilterChainProxy is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3bdcb4b690c50c1aae70883f409ccae/href">https://medium.com/media/d3bdcb4b690c50c1aae70883f409ccae/href</a></iframe><p>In a nutshell, this method constructs a bean (<strong>FilterChainProxy</strong>) with the name <strong>springSecurityFilterChain</strong>. While doing so, it configures any SecurityFilterChains available. It also, applies a default <strong>WebSecurityConfigurerAdapter </strong>implementation ( more on it later), if it cannot find. After that, it scans the available web security customizers (used to customize the security filter chain config) and applies them to the instance of <strong>WebSecurity</strong>. In the final step, it invokes the build of the <strong>WebSecurity</strong> instance.</p><p>2 things that might be on your mind now -</p><blockquote>1. What is the role of <strong>WebSecurityConfigurerAdapter?</strong></blockquote><blockquote>2. And, what is this <strong>WebSecurity </strong>class and what function does it perform?</blockquote><p>I&#39;ll provide an answer to these 2 questions in the next sub-section. But for now, we know-how and most importantly, when the FilterChainProxy is configured by Spring Boot.</p><p>If you inspect the <strong>FilterChainProxy </strong>class, you&#39;d notice how it invokes the security filter chains and in turn trigger the stack of security filters. Here is a snippet of the same:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aed82f33b98a74cd3c7f7fd0f54472f2/href">https://medium.com/media/aed82f33b98a74cd3c7f7fd0f54472f2/href</a></iframe><p>Please follow the comments in the above snippet, you&#39;d get the flow easily.</p><p>Let&#39;s move on to the next section.</p><h4>WebSecurityConfigurerAdapter, WebSecurity and HttpSecurity</h4><p>Posed with the above 2 questions, you might be also wondering how is the <strong>SecurityFilterChain</strong> constructed. So, in this sub-section, we will explore the role of -</p><ul><li>WebSecurityConfigurerAdapter</li><li>WebSecurity</li><li>HttpSecurity</li><li>SecurityFilterChain</li></ul><p><strong>WebSecurity </strong>is the configuration class that determines the filters to be applied for a particular web request along with other web request config responsibility. It, in turn, uses, HttpSecurity to achieve path-level filtering.</p><p><strong>HttpSecurity </strong>class defines the list of filters that will be configured. It contains the RequestMatcher instance to decide on filter applicability for a particular incoming request.</p><p>A WebSecurity instance can refer to multiple HttpSecurity instances. Whenever multiple HttpSecurity classes are configured, it ends up creating multiple SecurityFilterChains corresponding to each HttpSecurity instance.</p><p>So in essence, there is a <strong>1:N relationship between WebSecurity and HttpSecurity instances</strong>.</p><p><em>Now, how can we configure the HttpSecurity instances? </em><br>This is where the class -&gt; <strong>WebSecurityConfigurerAdapter </strong>comes to use. This class is used to configure/customize the HttpSecurity instance. We generally override the <strong><em>configure(HttpSecurity http)</em></strong> method of this class in our security configs (See above for attached code snippet).</p><p>So, if we have multiple implementations/multiple classes extending WebSecurityConfigurerAdapter’s configure method, then we are essentially creating multiple SecurityFilterChain.</p><p>To understand the above paragraph of information better and see how all of them fit into the FilterChainProxy filter, here is an image depicting the same:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXCVW_Zdo3qAo1vHmgUT4A.png" /><figcaption>Filter Chain Proxy and child elements</figcaption></figure><p>During <strong>FilterChainProxy’s </strong>instantiation, you’d remember, that it was invoking the <strong><em>build()</em></strong> method on a particular <strong>WebSecurity </strong>instance. This <strong><em>build()</em></strong> method, in turn, invokes the <strong>HttpSecurity </strong>instance’s build() methods. As a result, all the <strong>WebSecurityConfigurerAdapter</strong> config code is applied to HttpSecurity instances and therefore we end up customizing the <strong>SecurityFilterChain</strong>.</p><p>Let me add the relevant snippets of code to demonstrate how it&#39;s playing out in the background. Please read the comments above the following methods to understand the flow of logic better.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11b3fccf7ec3280bfab36d04fe438d7a/href">https://medium.com/media/11b3fccf7ec3280bfab36d04fe438d7a/href</a></iframe><p>The comments above the methods describe the flow of creating multiple security filter chains. From a consumption perspective, all we need to do is extend the <strong>WebSecurityConfigurationAdapter </strong>class and override the <strong>configure()</strong> method.</p><p>If we do not override the <strong>configure()</strong> method, a default filter chain is created as follows :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32acf03234e300b9e6ca278da91835a2/href">https://medium.com/media/32acf03234e300b9e6ca278da91835a2/href</a></iframe><p>Each of these methods on the http object would lead to the addition of respective filters in the <strong>SecurityFilterChain</strong>. Inspect the methods, to know the individual filters being applied.</p><p>Here is a list of default filters that are applied:</p><blockquote>WebAsyncManagerIntegrationFilter<br> SecurityContextPersistenceFilter<br> HeaderWriterFilter<br> CsrfFilter<br> LogoutFilter<br> UsernamePasswordAuthenticationFilter<br> DefaultLoginPageGeneratingFilter<br> DefaultLogoutPageGeneratingFilter<br> BasicAuthenticationFilter<br> RequestCacheAwareFilter<br> SecurityContextHolderAwareRequestFilter<br> AnonymousAuthenticationFilter<br> SessionManagementFilter<br> ExceptionTranslationFilter<br> FilterSecurityInterceptor</blockquote><p>You can enable <strong>DEBUG </strong>log level of the spring security package to track the filters in use.</p><p>So, with this, I have hopefully shown you what are the components involved in setting up the Security Filter chain and how they are interlinked. The initial purpose of the blog is served here.</p><p>But, if you are like me then you&#39;d have thought of playing around with the existing setup and see what interesting things come up.</p><p>So, I did 2 things -</p><ol><li>Create another DelegateFilterProxy Bean with the default one and see what can be achieved in this stage.</li><li>Create multiple Security Filter chains for different parts of our application.</li></ol><h4><strong>Multiple DelegateFilterProxy Beans</strong></h4><p>Multiple DelegateFilterProxy Beans can be helpful when you want to hook your custom filter to the spring context. It can be done either before the Security chain kicks in or after it.</p><p>It is not necessary that you must absolutely invoke your custom filter via DelegateFilterProxy rather than hooking it directly, but it is always an option:)</p><p>In the following example, I have hooked the custom Filter before the Spring security chain. This is particularly useful in the Logging context. There are scenarios, where you&#39;d like to log custom config in the MDC context for every web request. This can be useful while tracing logs in Kibana where you&#39;d be presented with additional context injected via MDC.</p><p><strong>Spring Security’s DelegateFilterProxy filter order is set at the value -100</strong>. Any value lower than this would indicate that it&#39;ll run before the security DelegateFilterProxy. And that&#39;s exactly what we would do here.</p><p>Creating a LogFilter -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6636e5a6ce70d3f6f7b813bb7553efce/href">https://medium.com/media/6636e5a6ce70d3f6f7b813bb7553efce/href</a></iframe><p>And embedding it into custom <strong>DelegateFilterProxy</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/201320398840a135602969c6313547d7/href">https://medium.com/media/201320398840a135602969c6313547d7/href</a></iframe><p>This would configure the <strong>DelegateFilterProxy </strong>with the name <strong>LoggerDelegatingFilterProxy </strong>and would be invoked before the default DelegateFilterProxy that is invoked by Spring Security.</p><h4>Multiple Security Filter Chains</h4><p>In the second use case, I tried creating 2 different SecurityFilterChain that would be invoked on 2 different endpoints of the application.</p><p>Typically, such scenarios would arise when you have got parts of the application that is accessible by one mode of authentication, ex — Username Password and another part of the application that needs to access in a different way, ex — Oauth and the API for these two subsystems have different signatures.</p><p>However, to validate my use case, I just chose to add an extra filter — AuditLogFilter to only one of the SecurityFilterChain. This was to understand whether the setup is correct or not.</p><p>AuditLogFilter -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f15eab00a745a67450cdd85c6a0a953/href">https://medium.com/media/7f15eab00a745a67450cdd85c6a0a953/href</a></iframe><p>And finally, the 2 SecurityFilterChain Config -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78bf6137c2a8213e12d0ad77ff4db211/href">https://medium.com/media/78bf6137c2a8213e12d0ad77ff4db211/href</a></iframe><p>The ManagerConfig is invoked only for manager API endpoints and this is where the AuditLog filter is configured.</p><p>The EmployeeConfig is the default security filter chain minus some filters.</p><p>When you invoke the respective APIs, you&#39;d notice the different set of filters being applied.</p><h3>Conclusion</h3><p>With these two examples, I come to the end of this article. We have seen how the entire spring security architecture is plugged into the Spring framework by Spring boot and how we can customize it.</p><p>I thank you for reading till the end and hope that the information provided here was valuable to you.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0491acc7df7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/demystifying-spring-security-setup-e0491acc7df7">Demystifying Spring Security setup</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop a full-stack webapp using NodeJS and deploy on Heroku]]></title>
            <link>https://medium.com/swlh/develop-a-full-stack-webapp-using-nodejs-and-deploy-on-heroku-52c7a69a0022?source=rss-50a2170450a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/52c7a69a0022</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Boudhayan Dev]]></dc:creator>
            <pubDate>Wed, 25 Dec 2019 13:18:22 GMT</pubDate>
            <atom:updated>2019-12-27T10:42:32.112Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello and welcome to this article where we will learn how to create a full-stack web application using NodeJS and also deploy it on Heroku. Let us get started.</p><p>So before we start coding, let us define what our application will do</p><blockquote>We will create an application (<strong>QuickLinks</strong>) that will let us save our favorite websites and launch them from a single place. The website will be guarded with basic authentication and support — Login and Sign Up process.</blockquote><p>Once we are done, the website will look as follows -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDNxOK0Z6A0RoxbKZU59tw.png" /><figcaption>QuickLinks</figcaption></figure><p>The code can be found here -</p><p><a href="https://github.com/boudhayan-dev/QuickLinks">boudhayan-dev/QuickLinks</a></p><h3>Setting up the project</h3><p>You can either clone the GitHub repository linked above or you can follow along.</p><p>Let us set up the application -</p><pre>npm init -y</pre><p>Let us add all the dependencies -</p><pre>npm i bcrypt-nodejs express mongoose connect-mongo dotenv express-session hbs passport passport-local valid-url</pre><pre>npm i nodemon --save-dev </pre><p>The above dependencies are as follows -</p><ul><li><strong>express = </strong>Express server</li><li><strong>bcrypt-nodejs = </strong>It is used to hash the plain-text password.</li><li><strong>mongoose = </strong>Mongoose package that makes it easy to deal with mongoDB</li><li><strong>connect-mongo = </strong>Used to store the session related information in mongoDB</li><li><strong>dotenv = </strong>Parse environment variables.</li><li><strong>express-session = </strong>Session handling in express.</li><li><strong>hbs = </strong>Handlebars library for server side templating.</li><li><strong>passport =</strong> Library to handle authentication.</li><li><strong>passport-local = </strong>Provides basic authentication strategy.</li><li><strong>valid-url = </strong>Checks if the input is of URI type.</li></ul><h3>Templates</h3><p>Let us design the templates now. We will make use of handlebars templating for designing the web pages. Under the parent directory, create a folder called <strong>templates </strong>and inside that create 2 sub folders called — <strong>partials </strong>and <strong>views. Partials </strong>contains the re-usable components that can be used in different web pages, <strong>Views </strong>contains all the web pages corresponding to our 3 views — Login page, Sign Up page and dashboard.</p><p>The partials are as follows -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b39e7e7d8810952f013291725b4fc12/href">https://medium.com/media/2b39e7e7d8810952f013291725b4fc12/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7443934485ae307823480d4cf80d290/href">https://medium.com/media/d7443934485ae307823480d4cf80d290/href</a></iframe><p>The templates are as follows -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc95c5a6a28c8e7954975cb90eae962/href">https://medium.com/media/3fc95c5a6a28c8e7954975cb90eae962/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/262acb6b65664119ee5e058c1c8684a6/href">https://medium.com/media/262acb6b65664119ee5e058c1c8684a6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cde2b618e9c6b6ed75093875955d946/href">https://medium.com/media/1cde2b618e9c6b6ed75093875955d946/href</a></iframe><p>Few observation on the templates -</p><ul><li>We make use of <a href="https://getbootstrap.com/">bootstrap </a>to render the UI.</li><li>For the links, we are making use of bootstrap’s card layout. In the card, there are fields for — link, name, description and an optional image field. Additionally, we also provide 2 buttons inside each card — delete link and open link.</li><li>Besides the card, we also provide 3 buttons on the profile — Add link, Logout and Delete profile link.</li></ul><h3>Static assets</h3><p>Let us create the css and javascript files now. The static assets are inside the public directory (check GitHub repo link).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68c2bae6d4643134d0096743a9bcb25f/href">https://medium.com/media/68c2bae6d4643134d0096743a9bcb25f/href</a></iframe><p>And now, let us create the javascript file that will handle all the ajax requests and modal handling. Login and SignUp pages are basically modals. So to display them, we need to open the modals when the page is loaded.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79e12dbd093b5bf3dbced4ae9fcbff82/href">https://medium.com/media/79e12dbd093b5bf3dbced4ae9fcbff82/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/402a5b42902a3f5651824abfee27e7cb/href">https://medium.com/media/402a5b42902a3f5651824abfee27e7cb/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f52f32dd0fe698565cc50dbdbab9bca8/href">https://medium.com/media/f52f32dd0fe698565cc50dbdbab9bca8/href</a></iframe><p>Explanation-</p><ul><li>signup.js and login.js contains logic to open the modal on page load.</li><li>dashboard.js contains code for — sending AJAX request to backend when link is deleted (<strong> deleteLink </strong>)and a new link is to be added (<strong>submitForm). </strong>We have not defined the routes yet. Along with the AJAX calls, it also contains a function to convert the image into a Base64 string.</li></ul><h3>Backend</h3><p>Let us start with defining the User model and the Links model. Models are basically representation of documents that you want to persist in MongoDB. We define all the fields and types of attributes in models. User model will be used to store user related information and the links model will store all links related info.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22b0e39d378ea00f5d2a02fa7b6076c1/href">https://medium.com/media/22b0e39d378ea00f5d2a02fa7b6076c1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/558cf1f8727e75c3cdbb243bbc747944/href">https://medium.com/media/558cf1f8727e75c3cdbb243bbc747944/href</a></iframe><p>Links documents will be embedded in the user documents as sub-documents/array of docs. This is done through the use of a <strong>virtual </strong>field. We also define 2 methods — <strong>generateHash </strong>and <strong>validPassword </strong>which are used during the signup and login process. We will see later how passportjs uses these 2 methods to hash the user provided password during sign up process and then validate the password during login process. We make use of bcrypt library here to do the hashing and validation.</p><p>Now, let us define the passport.js configuration for sign up and log in. Check the GitHub link for the location of the file relative to the project directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6186c978c33d7b0a159133387bc3f909/href">https://medium.com/media/6186c978c33d7b0a159133387bc3f909/href</a></iframe><p>There are few things going on here -</p><ul><li><strong>serializeUser </strong>= This method is used by passport.JS to store the client identifier (in this case -&gt; email) in the session table.</li><li><strong>deserializeUser</strong> = It is used by passport to load the actual user based on the serialized content from the database. The deserialized user information is bound to the request object. A new parameter called <strong>user </strong>is attached to it which contains the user info. If the session is not active, then the user field is empty/null.</li><li><strong>local-signup</strong> = This is the sign up strategy. We will see how it is invoked later on. In this strategy, we basically map the incoming payload to username and password field, and then using these 2 fields we query our database to check if an user already exists. If they do, we raise an error — User already exists, otherwise we provision a new user and pass that on to the request.</li><li><strong>local-login</strong> = This is the login strategy. This works similar to the signup strategy. Here as well, we look for the user in the database. If not present, we raise an error — No user exists. If the user exists and password doesn’t match — we raise another error. The password check is done using the <strong>validPassword </strong>method defined earlier. If user exists and password is valid, we pass on the user object to the request.</li></ul><p>Now, with the passport middle ware in place, let us define the application routes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef51c3543fcb73957fec983f1c138113/href">https://medium.com/media/ef51c3543fcb73957fec983f1c138113/href</a></iframe><ul><li><strong>isLoggedIn </strong>= This method is used to check if the current request is authenticated. It is used as a middleware.</li><li><strong>/dashboard</strong> = This endpoint is used to load the user information + links information to be displayed in the dashboard.</li><li><strong>/signup</strong> = It has 2 types of routes. If the request is of type GET, then the signup form is presented. If the request is of type POST, then the local-signup strategy is invoked and the user is logged in after successful sign up.</li><li><strong>/login</strong> = Similar to the above route, this also has a GET and POST endpoint. If the request is of type POST, then the user is authenticated using the local-login strategy. If the login process fails, then the login page is reloaded with the error details.</li><li><strong>/logout</strong> = As the name suggests, this endpoint is used to log out. The user session information is deleted from the database and user is logged out.</li><li><strong>/add</strong> = This endpoint is used to accept link payload from the UI through AJAX request. It validates the link information and if correct,writes into DB. Since, it is a AJAX request, the response type is JSON and not a page render/redirect.</li><li><strong>/deleteLink</strong> = This is used to delete a given link in UI.</li><li><strong>/deleteUserProfile</strong> = This endpoint deletes all the user related information and redirects to the sign up page.</li><li><strong>*</strong> = For every other request, the user is redirected to the dashboard page, if they are logged in. Otherwise, the sign up page, if the user is not logged in.</li></ul><p>Now, we have defined the routes and authentication configuration. What is left now, is the server config. Let us do that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12e4cf8f4c1de82ebe6067dc14960075/href">https://medium.com/media/12e4cf8f4c1de82ebe6067dc14960075/href</a></iframe><p>The app.js file contains all the config needed to start up the server.</p><ul><li><strong>staticPath </strong>= Defines the relative path of static folder (css, js).</li><li><strong>viewsPath</strong> and <strong>partialsPath</strong> defines the path of the views and partials templates.</li><li>We set up the mongoose connection using the <strong>mongoose.connect</strong> method.</li><li>We define the session config using <strong>express-session</strong>. We also define the storage type with that of <strong>mongoDB</strong>. The session is persisted for 15 mins.</li><li>And finally we start the application at the port available.</li></ul><p>Before we start our application, we need to define a .<strong>env </strong>file which contains the 2 fields -</p><pre>DBURL=mondoDB_Connection_URL<br>SECRET=appSecret_for_passport.js_Config</pre><p>If you want to run the app locally, you need to keep a mongodb local instance running. If you don’t have a local mongo installation, you can make use of <a href="https://www.mongodb.com/cloud/atlas">Mongo Atlas</a> to create a free cluster. Replace the <strong>DBURL </strong>value with the connection string.</p><p>Now with that you can run the application by going to the root of the app -</p><pre>node src/app.js</pre><p>This will start the app at localhost:3000. Visit the URL and follow through the sign up process, login and dashboard.</p><h3>Deployment</h3><p>Now, that we have a perfectly functioning local web application. Let us, deploy the app. We will use Heroku for this</p><p><a href="https://www.heroku.com/">Cloud Application Platform | Heroku</a></p><ul><li>Create an account if you don’t have, at Heroku. They have a free tier.</li><li>Now install the Heroku CLI — <a href="https://devcenter.heroku.com/articles/heroku-cli">https://devcenter.heroku.com/articles/heroku-cli</a></li><li>Navigate to the project directory and apply the following commands.</li><li>Login to Heroku -</li></ul><pre>heroku login</pre><ul><li>Create a new web app in Heroku with name <strong>quickLinks</strong></li></ul><pre>heroku create quickLinks</pre><ul><li>Set the config values</li></ul><pre>heroku config:set DBURL=mongodb+srv:....<br>heroku config:set SECRET=appsecret...</pre><ul><li>Push the app to heroku. Heroku uses Git to deploy.</li></ul><pre>git push heroku master</pre><p>With that, you will notice that the app is deployed and you will be provided with the app link.</p><p>I have deployed my copy which can be accessed here —</p><p><a href="https://quick-links-app.herokuapp.com/dashboard">https://quick-links-app.herokuapp.com</a></p><p>You can access the above link and try out the application.</p><p>With that we are at the end of our article. We have seen how easy it is to perform server side rendering, authentication, routing and using database with NodeJs. Not to forget, deploying an actual app on Heroku. I hope this article will be useful for you.</p><p>Regards,</p><p>Boudhayan Dev</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52c7a69a0022" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/develop-a-full-stack-webapp-using-nodejs-and-deploy-on-heroku-52c7a69a0022">Develop a full-stack webapp using NodeJS and deploy on Heroku</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>