<?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"><channel><title><![CDATA[Kuzma Feskov]]></title><description><![CDATA[Backend notes from production: what worked, what it cost, and what we chose not to build.]]></description><link>https://kuzma-feskov.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:08:28 GMT</lastBuildDate><atom:link href="https://kuzma-feskov.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[One signature between a driver and an admin: hardening Laravel Passport tokens]]></title><description><![CDATA[Laravel Passport never compares the user in a JWT with the token row in the database. How to add that check with no extra queries, and a test that forges a…]]></description><link>https://kuzma-feskov.hashnode.dev/laravel-passport-token-owner-check</link><guid isPermaLink="true">https://kuzma-feskov.hashnode.dev/laravel-passport-token-owner-check</guid><dc:creator><![CDATA[Kuzma Feskov]]></dc:creator><pubDate>Thu, 03 Dec 2026 14:31:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b101cbd70a2877ba1d59262/4ecbfd97-6c73-47a6-b7f5-1231e4c76520.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>One signature between a driver and an admin: hardening Laravel Passport tokens</h1>
<p>On December 2 the NSA asked for a faster move to post-quantum cryptography, and eight large tech companies backed it the same day. Nobody has shown RSA-2048 broken. But it made me ask a narrower question about my own projects: what exactly do we trust a signature for?</p>
<p>I run Laravel Passport on two production platforms: a car marketplace in Israel and a US freight logistics platform. The answer turned out to be: more than I thought.</p>
<h2>How Passport checks an access token</h2>
<p>A Passport access token is a JWT signed with RS256. On every API request the resource server does two things:</p>
<ul>
<li>verifies the signature with the public key;</li>
<li>looks up the token ID (<code>jti</code>) in <code>oauth_access_tokens</code> and checks that it exists and isn't revoked.</li>
</ul>
<p>Then the guard takes the user from the <code>sub</code> claim inside the token:</p>
<pre><code class="language-php">// Laravel\Passport\Guards\TokenGuard
$oauthUserId = $psr-&gt;getAttribute('oauth_user_id'); // the "sub" claim

$user = $this-&gt;provider-&gt;retrieveById($oauthUserId);
</code></pre>
<p>The database row for that <code>jti</code> also has a <code>user_id</code>. Passport never compares the two. The only thing that ties the user in the token to the token in the database is the signature.</p>
<h2>This isn't a Passport bug</h2>
<p>That's how JWT is meant to work. The signature guarantees that nobody changed the claims, so there's no reason to check them again. The <code>jti</code> lookup exists only so that tokens can be revoked.</p>
<p>The model holds as long as nobody else can sign. Two ways that stops being true:</p>
<ul>
<li><strong>The key leaks.</strong> Private keys end up in repositories, CI variables, backups, <code>.env</code> files copied between servers, laptops of people who left. This happens far more often than a broken algorithm.</li>
<li><strong>The algorithm breaks.</strong> Unlikely tomorrow, but that's exactly what this week's statements are about.</li>
</ul>
<p>Either way, the attack is simple. Log in as any user, take your own valid token, put someone else's ID into <code>sub</code>, sign it. The <code>jti</code> is real and not revoked, the signature is valid, and you are now the admin. On a logistics platform that's the dispatcher who can reassign a load. On a marketplace it's someone else's listings and messages.</p>
<h2>The fix: check the owner, not only the ID</h2>
<p>If the <code>jti</code> row must belong to the same user and client as the claims, a forged signature alone gets you nothing. You'd need someone else's <code>jti</code>, which is 80 random hex characters that only exist inside that person's real token. If you can steal the real token, you didn't need to forge anything.</p>
<p>Passport already loads that row on every request. So the check doesn't need a new query, only a bit more from the existing one.</p>
<p><strong>1. The repository keeps the row it already fetches.</strong></p>
<pre><code class="language-php">class AccessTokenRepository extends \Laravel\Passport\Bridge\AccessTokenRepository
{
    private ?Token $checkedToken = null;

    public function isAccessTokenRevoked(string $tokenId): bool
    {
        $this-&gt;checkedToken = Passport::token()-&gt;newQuery()
            -&gt;whereKey($tokenId)
            -&gt;where('revoked', false)
            -&gt;first(['id', 'user_id', 'client_id']);

        return $this-&gt;checkedToken === null;
    }

    public function getCheckedToken(): ?Token
    {
        return $this-&gt;checkedToken;
    }
}
</code></pre>
<p><strong>2. A validator compares that row with the claims.</strong></p>
<pre><code class="language-php">class BearerTokenOwnerValidator extends BearerTokenValidator
{
    public function __construct(private AccessTokenRepository $tokenRepository)
    {
        parent::__construct($tokenRepository);
    }

    public function validateAuthorization(ServerRequestInterface $request): ServerRequestInterface
    {
        $request = parent::validateAuthorization($request);

        $token = $this-&gt;tokenRepository-&gt;getCheckedToken();

        $isSameToken = (string) $token?-&gt;id === (string) $request-&gt;getAttribute('oauth_access_token_id');
        $isSameUser = (string) $token?-&gt;user_id === (string) $request-&gt;getAttribute('oauth_user_id');
        $isSameClient = (string) $token?-&gt;client_id === (string) $request-&gt;getAttribute('oauth_client_id');

        if (!$isSameToken || !$isSameUser || !$isSameClient) {
            throw OAuthServerException::accessDenied('Access token could not be verified');
        }

        return $request;
    }
}
</code></pre>
<p><strong>3. The resource server gets the validator.</strong> Passport builds it in a protected method of its service provider, so a subclass of the provider can replace it cleanly:</p>
<pre><code class="language-php">class PassportServiceProvider extends \Laravel\Passport\PassportServiceProvider
{
    protected function registerResourceServer(): void
    {
        $this-&gt;app-&gt;singleton(ResourceServer::class, function ($container) {
            $tokenRepository = $container-&gt;make(AccessTokenRepository::class);

            return new ResourceServer(
                $tokenRepository,
                $this-&gt;makeCryptKey('public'),
                new BearerTokenOwnerValidator($tokenRepository)
            );
        });
    }
}
</code></pre>
<p>The same repository instance goes to the server and to the validator, so the validator reads the row the server has just loaded.</p>
<h2>Proving it</h2>
<p>I didn't want to trust my reading of the code, so I reproduced the attack. With the real private key I signed two tokens: one honest, one with the same <code>jti</code> and another user's ID in <code>sub</code>. All of it ran inside a database transaction that was rolled back.</p>
<table>
<thead>
<tr>
<th></th>
<th>honest token</th>
<th>forged <code>sub</code></th>
</tr>
</thead>
<tbody><tr>
<td>plain Passport</td>
<td>200, own profile</td>
<td><strong>200, the other user's profile</strong></td>
</tr>
<tr>
<td>with the owner check</td>
<td>200, own profile</td>
<td><strong>401</strong></td>
</tr>
</tbody></table>
<p>The regression test does the same thing: it logs in, forges the token, and first asserts that the stock Passport validator <em>accepts</em> it. Without that step a 401 could come from anything, a blocked account for example, and the test would prove nothing. With the check switched off, the test fails with "received 200".</p>
<h2>What it costs</h2>
<p><strong>Queries.</strong> I counted them on a profile request: 25 queries before, 25 after, one of them to <code>oauth_access_tokens</code> in both cases. Before it was <code>select exists(...)</code>, now it's <code>select id, user_id, client_id ... limit 1</code>. Same primary-key lookup.</p>
<p><strong>Maintenance.</strong> The fix extends internal Passport and league/oauth2-server classes. Every Passport upgrade now needs a look at <code>registerResourceServer()</code> and <code>validateAuthorization()</code>. The test is there to catch a silent break.</p>
<p><strong>Client credentials tokens.</strong> Machine tokens have no user in the row, so they fail the owner check. Neither project uses them for API access. If yours does, skip the user comparison when <code>user_id</code> is empty and the client is the owner.</p>
<p><strong>Statelessness.</strong> Strictly speaking, the JWT now works like an opaque token with a database lookup. But Passport tokens were never stateless: the revocation check already hit the database on every request.</p>
<h2>What didn't need it</h2>
<p>Refresh tokens and authorization codes in Passport aren't signed with RSA. They're encrypted with the application key (AES), so neither an RSA break nor a leaked Passport key lets anyone forge them. A leaked <code>APP_KEY</code> is a different story, and a good reason to look at where that one lives too.</p>
<h2>Takeaway</h2>
<p>Before planning a migration to post-quantum algorithms, find out what your signature is the <em>only</em> guard for. In our case it was one comparison Passport doesn't make, and adding it cost nothing.</p>
<p>Which part of your auth would fall if one key leaked?</p>
]]></content:encoded></item><item><title><![CDATA[Our database doesn't answer list queries. Manticore does.]]></title><description><![CDATA[In most projects I've seen, the database is the center of everything, and a search engine gets added later for the search box. On two production platforms…]]></description><link>https://kuzma-feskov.hashnode.dev/our-database-doesn-t-answer-list-queries-manticore-does</link><guid isPermaLink="true">https://kuzma-feskov.hashnode.dev/our-database-doesn-t-answer-list-queries-manticore-does</guid><dc:creator><![CDATA[Kuzma Feskov]]></dc:creator><pubDate>Wed, 02 Dec 2026 13:48:09 GMT</pubDate><content:encoded><![CDATA[<p>In most projects I've seen, the database is the center of everything, and a search engine gets added later for the search box. On two production platforms I've been doing it the other way round for years, and it works much better.</p>
<p>Manticore Search is our read layer. Every list, filter, counter and search in the admin panel goes to Manticore. The database keeps the data safe. Manticore answers the questions.</p>
<h2>The pattern</h2>
<p>A list request goes like this:</p>
<pre><code>UI request → Manticore: filters, sorting, paging → IDs + total count
           → database: SELECT ... WHERE id IN (...) by primary key
           → response
</code></pre>
<p>Manticore returns only the IDs of the current page and the total count. The database then fetches those rows by primary key, which is the cheapest query a relational database can run.</p>
<p>What disappears from the database side:</p>
<ul>
<li>12-JOIN queries with dynamic WHERE clauses built from whatever the user clicked;</li>
<li>indexes for every filter combination the UI can produce;</li>
<li><code>COUNT(*)</code> over the same heavy query, just to draw the pager.</li>
</ul>
<h2>It's still SQL</h2>
<p>Manticore speaks SQL over the MySQL protocol, and that matters more than it sounds. You use a regular MySQL driver and normal SELECTs. You debug queries in the same client you use for the database. Nobody on the team has to learn a new query language or a JSON DSL.</p>
<p>For Laravel I maintain an open-source query builder for Manticore, so queries look the same as for a regular database. (Link in the end.)</p>
<h2>What we moved out of the database</h2>
<p><strong>Faceted filtering.</strong> Every filter in the UI shows a live counter: "Status: Delivered (128)". Each counter has to be calculated with all the other filters applied except its own, otherwise selecting a value would zero out the rest of its options. In SQL that's a heavy GROUP BY per filter. In Manticore it's one batch of queries with FACET, sent in a single round trip.</p>
<pre><code class="language-sql">SELECT id FROM orders WHERE status IN (2,3) AND carrier_id = 15 LIMIT 0,50
  FACET status FACET carrier_id;
</code></pre>
<p><strong>Access control.</strong> The rules for which rows a user is allowed to see are compiled into Manticore filters. The list, the counters and the search all respect them automatically, because they all go through the same place.</p>
<p><strong>Geo search.</strong> "Within N miles of this ZIP code" is just one more filter: compute the distance with <code>GEODIST()</code> and filter on it, together with everything else.</p>
<p><strong>Full-text search across entities.</strong> One denormalised index instead of <code>LIKE '%...%'</code> over several tables.</p>
<h2>The cost: a real-time indexer</h2>
<p>Nothing is free. The index has to stay in sync with the database.</p>
<p>We don't run a background job that scans everything on a schedule. Synchronisation happens on change: when a service updates a record, it writes the updated document to the index right away. It's code you have to maintain, and every new field means thinking "does the index need it?".</p>
<p>For us that's a much smaller problem than a database struggling every time someone opens a list with eight filters.</p>
<h2>The index is derived data</h2>
<p>This is the part I like most. The index contains nothing that isn't in the database.</p>
<ul>
<li>If Manticore crashes, or we need to move it to another server, we reindex from the database.</li>
<li>We don't back up the index and we don't replicate it.</li>
<li>Manticore runs happily in a container for the same reason: there's nothing valuable inside.</li>
</ul>
<p>With really large data a full reindex can take hours. Two things help:</p>
<ol>
<li>Manticore supports <code>mysqldump</code>, so you can dump the index and restore it much faster than rebuilding it from scratch.</li>
<li>We split reindexing into parts. First we restore the minimum the system needs to work, which takes a few minutes. The rest is reindexed in the background while people already use the system.</li>
</ol>
<p>And a document is searchable as soon as it's inserted. After a restore you don't wait for indexes to build or optimise: Manticore merges data in the background and queries keep working at full speed.</p>
<h2>When I wouldn't do this</h2>
<ul>
<li>Small admin panels with a couple of filters. A database with the right indexes is enough, and an extra moving part isn't worth it.</li>
<li>Data that has to be consistent the very moment it's written. There is a short window between the database write and the index update. For lists and counters it doesn't matter. For balances it would.</li>
</ul>
<h2>Summary</h2>
<p>The database keeps the data safe. Manticore answers the queries. If something goes wrong with the search layer, we just rebuild it.</p>
<p>Do you use a search engine as the main read layer, or only for the search box? Where did it bite you?</p>
<hr />
<p>Laravel query builder for Manticore: <a href="https://github.com/kvf77/manticore-query-builder">https://github.com/kvf77/manticore-query-builder</a></p>
]]></content:encoded></item></channel></rss>