<?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 Miraç Deprem on Medium]]></title>
        <description><![CDATA[Stories by Miraç Deprem on Medium]]></description>
        <link>https://medium.com/@mrcdprm?source=rss-d1b9960768fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gel_SKs_A4AA69Pu1A-K_A.png</url>
            <title>Stories by Miraç Deprem on Medium</title>
            <link>https://medium.com/@mrcdprm?source=rss-d1b9960768fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:10:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrcdprm/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[Cookieless Web Analytics: Counting Visitors with a Daily Salt]]></title>
            <link>https://medium.com/@mrcdprm/cookieless-web-analytics-counting-visitors-with-a-daily-salt-14321da9912b?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/14321da9912b</guid>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[web-analytics]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 06:31:01 GMT</pubDate>
            <atom:updated>2026-11-27T06:31:01.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdWJdDWuhtS6Kem2b_4_Zg.png" /></figure><h4>How to count unique visitors without cookies: the daily-salted visitor ID in Nabız, why an unsalted hash is not enough, and the price the method pays.</h4><p>The usual way to count a site’s visitors is to write a cookie into each visitor’s browser: if the same cookie comes back, it is the same person. Easy, but it has a price: a lasting identity that recognises the visitor for days and weeks. While building Nabız, my own web analytics tool, I wanted a way to count unique visitors without cookies and without recognising anyone. This post is about how <strong>cookieless analytics</strong> works, the <strong>daily salt</strong> at its core, and the price the method pays on purpose.</p><h3>The first idea and why it falls short</h3><p>Without a cookie, the visitor has to be recognised from the request itself. Every request already carries two pieces of information: the IP address and the User-Agent string the browser identifies itself with. Combining them and taking a hash is the first idea:</p><pre>visitor = SHA-256(IP + User-Agent)</pre><p>The same person on the same computer produces the same value, and the IP itself is not stored. On paper it looks anonymous. It isn’t.</p><p>IPv4 has about 4.3 billion addresses, and the number of common browser strings is limited. A graphics card can compute billions of SHA-256 hashes per second. Someone holding these hashes can try every IP address in turn and quickly find which hash belongs to which address. An unsalted hash does not hide personal data; it only puts it a little further away.</p><h3>The daily salt</h3><p>The fix is the method tools like Plausible use too: add a random, secret value to the hash that changes every day, a <strong>salt</strong>.</p><pre>visitor = SHA-256(today&#39;s salt ‖ site ‖ IP ‖ User-Agent)</pre><p>The salt is generated on the server: 32 random bytes. It changes three things:</p><ul><li><strong>Without the salt, the hash cannot be reversed.</strong> Trying every IP also requires knowing the salt.</li><li><strong>The next day the salt changes and the old one is deleted.</strong> Who a hash from yesterday belonged to can no longer be computed, not even by the server.</li><li><strong>The site goes into the hash too.</strong> The same person gets two different identities on two different sites; there is no cross-site tracking.</li></ul><p>In Nabız this lives in one package:</p><pre>// Visitor builds a visitor&#39;s identity for today:<br>// the first 8 bytes of SHA-256(salt ‖ site ‖ IP ‖ User-Agent).<br>// IP and User-Agent are used here and discarded; they are never written anywhere.<br>func (k *Keeper) Visitor(ctx context.Context, siteID, ip, userAgent string) (int64, error) {<br>	s, err := k.current(ctx)<br>	if err != nil {<br>		return 0, err<br>	}<br>	h := sha256.New()<br>	h.Write(s)<br>	for _, field := range []string{siteID, ip, userAgent} {<br>		// Each field is prefixed with its length; otherwise (&quot;ab&quot;, &quot;c&quot;) and (&quot;a&quot;, &quot;bc&quot;)<br>		// would give the same bytes and two different visitors could share an identity.<br>		var n [4]byte<br>		binary.BigEndian.PutUint32(n[:], uint32(len(field)))<br>		h.Write(n[:])<br>		h.Write([]byte(field))<br>	}<br>	sum := h.Sum(nil)<br>	// SQLite INTEGER is a signed 64-bit value; the uint64 is converted to int64 as is.<br>	return int64(binary.BigEndian.Uint64(sum[:8])), nil<br>}</pre><p>There is a small but important detail here: before writing the fields one after another, each one is prefixed with its length. Otherwise a site named &quot;ab&quot; with IP &quot;c&quot; and a site &quot;a&quot; with IP &quot;bc&quot; would produce the same bytes. Rare in real data, but making the hash input unambiguous is a cheap guarantee.</p><p>The first 8 bytes of the hash are used because they only need to fit in an SQLite integer column. Among one site’s visitors in one day, the chance of a 64-bit collision is negligible.</p><h3>How the salt rotates</h3><p>There is no separate scheduler. On the first request after the day changes, a new salt is generated, written to the database, and the salts of all other days are deleted. All in one transaction: if it fails halfway, neither is the new salt written nor the old one deleted.</p><pre>// rotate fetches or generates the given day&#39;s salt and deletes the salts of every<br>// other day, all in one transaction: if it fails halfway, nothing changes.<br>func (k *Keeper) rotate(ctx context.Context, day string) ([]byte, error) {<br>	// ...<br>	if _, err := tx.ExecContext(ctx, `DELETE FROM salts WHERE day &lt;&gt; ?`, day); err != nil {<br>		return nil, err<br>	}<br>	return value, tx.Commit()<br>}</pre><p>The salt is kept in memory as well, and when a new one arrives the old one’s bytes are wiped with clear(k.value). The salt is also written to the database because the server may restart during the day: if it lived only in memory, an afternoon update would split that day&#39;s visitors in two.</p><p>The tests pin these behaviours one by one: same day, same identity; next day, a different one; the old salt is deleted; a restart keeps the salt; and 20 requests arriving at the moment the day changes all use the same new salt.</p><h3>Less data leaves the browser in the first place</h3><p>Hashing protects the server side, but what the browser sends matters too. Nabız’s script does not send the full page address, only its path and campaign parameters:</p><pre>// Sent address: only the path and source parameters. Everything after &quot;#&quot; (e.g. the<br>// decryption key in Zarf) and other query values (e.g. ?token=...) never leave the browser.<br>var keep = [&quot;utm_source&quot;, &quot;utm_medium&quot;, &quot;utm_campaign&quot;, &quot;ref&quot;, &quot;source&quot;];</pre><p>A bug taught me this rule. The first version sent location.href, the whole address. In Zarf, my file sharing tool, the decryption key sits in the # part of the address. Had I added Nabız to Zarf, users&#39; file keys would have gone to the analytics server. I had put the key after # precisely so it would never leave the browser; the analytics script would have broken that promise.</p><p>Pages with IDs in their address had a similar issue. In Seans, my cinema site, there is /bookings/&lt;id&gt;; in Casus, room codes are in the address. They would have shown up one by one in the page list of a public dashboard. With the data-mask setting, these pages are sent as a pattern like /bookings/:id; the real ID never leaves the browser, and they are grouped into one row in the dashboard.</p><p>The IP address is not written anywhere either: it is used to compute the visitor identity and the country, then discarded. The access log of the Caddy server in front is turned off as well.</p><h3>The price</h3><p>The method has limits accepted on purpose:</p><ul><li><strong>Returning visitors cannot be measured.</strong> The same person counts as a new visitor the next day. Since the salt changes daily, that is not a bug but the point.</li><li><strong>The day boundary is UTC.</strong> The salt changes at midnight UTC, which is 03:00 in Turkey. Someone browsing at that hour may be counted twice.</li><li><strong>Identical browsers on the same network can look like one person.</strong> Two people in an office with the same IP and the same browser get the same identity. The opposite happens too: if a mobile network changes the IP during the day, one person is counted twice.</li></ul><p>In return, nothing is written to the browser, there is no identity that recognises a person across days, and the data on the server cannot be linked back to anyone once the salt is deleted. That is why no cookie banner is needed.</p><h3>What I took away</h3><ul><li><strong>An unsalted hash is not anonymisation.</strong> When the input space is small, as with IP addresses, the hash can be reversed by trying every value.</li><li><strong>Deleting the salt matters as much as deleting the data.</strong> Privacy rests on the old salt really being gone, which is why rotation is one transaction and the memory is wiped too.</li><li><strong>The fields going into a hash must be unambiguous.</strong> A simple rule such as a length prefix stops two different inputs from producing the same bytes.</li><li><strong>The best data is data never collected.</strong> Limiting what leaves the browser matters as much as protecting the server: a path, not the full address; a pattern, not the ID.</li><li><strong>Every method has a price, and the price should be written down.</strong> No returning visitors is not a gap but a decision made for privacy.</li></ul><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/cerezsiz-web-analitigi-gunluk-tuz"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14321da9912b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Date and Time Zone Pitfalls: Store in UTC, Show the Right Time]]></title>
            <link>https://medium.com/@mrcdprm/date-and-time-zone-pitfalls-store-in-utc-show-the-right-time-e5ffa29468aa?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5ffa29468aa</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[timezone]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 06:31:01 GMT</pubDate>
            <atom:updated>2026-11-25T06:31:01.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXPIULIerJWGexrqwDTiMQ.png" /></figure><h4>A Thursday that shows as Wednesday in New York, the wrong year on New Year’s Day, times compared as text: fixing date and time zone bugs in four projects.</h4><p>Dates and times are among the most underestimated data types in software. Is 2026-10-01 a day or a moment? Which time zone is the server in? Where is the user? When the code does not answer these questions explicitly, the bug often shows up only in some countries, only near midnight, or only on New Year&#39;s Day. This post is about <strong>date and time zone pitfalls</strong> in four of my projects and how I handled each one: a day shift in JavaScript, a city&#39;s wrong clock, a cinema schedule pinned to Istanbul time, storing UTC in C#, and times stored as text in Java.</p><h3>First, two concepts: a moment and a day</h3><p>The distinction behind all of them:</p><ul><li><strong>An instant:</strong> a point that is the same everywhere. The show starts at 18:00 UTC on 14 October 2026. That is 21:00 in Istanbul and 19:00 in London, but the same instant.</li><li><strong>A calendar date or wall-clock time:</strong> tied to a place. Thursday 1 October, due on 20 November. Without a time zone it cannot be turned into an instant.</li></ul><p>Most of the bugs come from mistaking one for the other.</p><h3>1. Weather: Thursday becomes Wednesday in New York</h3><p>The 5-day forecast in my weather app gives a date such as &quot;2026-10-01&quot; for each day. The obvious way to print the weekday:</p><pre>new Intl.DateTimeFormat(&#39;tr&#39;, { weekday: &#39;long&#39; }).format(new Date(&#39;2026-10-01&#39;));</pre><p>A JavaScript quirk kicks in here: a date-only string like &quot;2026-10-01&quot; is parsed as <strong>midnight UTC</strong>, while formatting happens in the user&#39;s time zone. West of UTC, midnight UTC is the evening of the previous day in local time:</p><ul><li><strong>New York</strong> · new Date(&#39;2026-10-01&#39;): Wednesday · Read at noon UTC: Thursday</li><li><strong>Istanbul</strong> · new Date(&#39;2026-10-01&#39;): Thursday · Read at noon UTC: Thursday</li><li><strong>Tokyo</strong> · new Date(&#39;2026-10-01&#39;): Thursday · Read at noon UTC: Thursday</li></ul><p>And another quirk: add a time to the same string without a trailing Z, as in &quot;2026-10-01T00:00&quot;, and it is parsed as <strong>local time</strong> instead. One character changes which time zone the string is read in.</p><p>Here the date is not an instant but a calendar day. The fix is to treat it as a day, not a moment: read it at midday in UTC and format it in UTC. The day stays the same wherever the user is:</p><pre>// The date comes as &quot;2026-09-30&quot;; read at noon UTC, the time zone cannot shift the day<br>return new Intl.DateTimeFormat(settings.lang, { weekday: &#39;long&#39;, timeZone: &#39;UTC&#39; }).format(new Date(`${date}T12:00:00Z`));</pre><h3>2. Weather: the city’s clock stuck at 22:00</h3><p>The same app shows the local time of the selected city. The first version took it from the weather data’s timestamp. Open-Meteo gives current conditions in 15-minute slots, and the timestamp is the start of the slot: at 22:13 it showed 22:00. The timestamp says which moment the data belongs to; it is not the current time.</p><p>The right way is to take the current instant and format it in the city’s time zone. The API returns the city’s IANA time zone, such as Europe/Istanbul or Asia/Kolkata; if the browser does not know that name, the UTC offset in the response is the fallback:</p><pre>export function localTime(forecast, now = Date.now()) {<br>  if (forecast?.timeZone) {<br>    try {<br>      return new Intl.DateTimeFormat(&#39;en-GB&#39;, {<br>        timeZone: forecast.timeZone, hour: &#39;2-digit&#39;, minute: &#39;2-digit&#39;, hourCycle: &#39;h23&#39;,<br>      }).format(now);<br>    } catch {<br>      // A time zone the browser doesn&#39;t know: fall back below<br>    }<br>  }<br>  if (typeof forecast?.utcOffset !== &#39;number&#39;) return null;<br>  return new Date(now + forecast.utcOffset * 1000).toISOString().slice(11, 16);<br>}</pre><p>A time zone name is more reliable than a fixed offset: in a city with daylight saving time the offset changes twice a year, the name does not. The test includes India, with its half-hour offset:</p><pre>assert.equal(localTime({ timeZone: &#39;Europe/Istanbul&#39;, utcOffset: 10800 }, now), &#39;22:13&#39;);<br>assert.equal(localTime({ timeZone: &#39;Asia/Tokyo&#39;, utcOffset: 32400 }, now), &#39;04:13&#39;);<br>assert.equal(localTime({ timeZone: &#39;Asia/Kolkata&#39;, utcOffset: 19800 }, now), &#39;00:43&#39;);</pre><h3>3. Seans: the cinema is in Istanbul, wherever the visitor is</h3><p>In Seans, my cinema booking site, showtimes are stored in UTC. But the cinema is in Istanbul: someone browsing from Berlin should see that the film starts at 21:00 Istanbul time, not a value converted to their computer’s clock. So every date on screen is written in Istanbul time, whatever the visitor’s computer says:</p><pre>// Dates and money, always in Istanbul time and Turkish lira, whatever the visitor&#39;s computer says.<br>const TZ = &#39;Europe/Istanbul&#39;;</pre><pre>export const formatTime = (date, lang) =&gt;<br>  new Intl.DateTimeFormat(locale(lang), { timeZone: TZ, hour: &#39;2-digit&#39;, minute: &#39;2-digit&#39; }).format(new Date(date));</pre><p>Grouping showtimes by day follows the same rule. A show at 22:30 UTC is 01:30 the next day in Istanbul and must appear under the next day in the programme. The day key is built in Istanbul time too:</p><pre>// &quot;2026-10-14&quot; for a date in Istanbul, used to group showtimes by day.<br>export const dayKey = (date) =&gt;<br>  new Intl.DateTimeFormat(&#39;en-CA&#39;, { timeZone: TZ, year: &#39;numeric&#39;, month: &#39;2-digit&#39;, day: &#39;2-digit&#39; }).format(new Date(date));</pre><p>en-CA was picked because it formats a date directly as YYYY-MM-DD.</p><p>When adding a show in the admin panel, the form sends the time with +03:00, and the server accepts only times with an explicit offset. Turkey has had no daylight saving time since 2016, so +03:00 is fixed and a day in Istanbul always starts at 21:00 UTC:</p><pre>startsAt: z.iso.datetime({ offset: true }), // the page sends Istanbul time with &quot;+03:00&quot;</pre><h3>4. Tamirhane: store in UTC, think in Turkey</h3><p>In Tamirhane, my repair shop app, times are DateTimeOffset values and the app works in Turkey time, +03:00. The current time comes from one place:</p><pre>public static class TurkeyTime<br>{<br>    public static readonly TimeSpan Offset = TimeSpan.FromHours(3);</pre><pre>    public static DateTimeOffset Now(TimeProvider clock) =&gt; clock.GetUtcNow().ToOffset(Offset);<br>}</pre><p>The clock is not DateTime.Now but an injected TimeProvider. Tests can set it to any moment, so rules such as the due date cannot be before today are tested against a fixed date.</p><p>PostgreSQL brought a surprise: Npgsql refuses to write a DateTimeOffset with a +03:00 offset into a timestamptz column and accepts only UTC. Everything is stored in UTC in the database anyway; the offset just has to be removed explicitly on the way in. Instead of doing that everywhere, I defined it once for every date field:</p><pre>// PostgreSQL timestamptz accepts only UTC; Turkey time (+03:00) is converted to UTC when written.<br>builder.Properties&lt;DateTimeOffset&gt;().HaveConversion&lt;UtcConverter&gt;();<br>builder.Properties&lt;DateTimeOffset?&gt;().HaveConversion&lt;UtcConverter&gt;();</pre><p>In two places the question what day is it in Turkey? matters:</p><ul><li><strong>Work order numbers</strong> start with the year: 2027-0001. A work order opened at 01:00 Turkey time on 1 January is still 22:00 on 31 December in UTC. Taking the year from UTC would give the first order of the year the previous year&#39;s number. The year comes from Turkey time.</li><li><strong>The due date</strong> is a calendar day, not an instant. So it is stored as a DateOnly, and today is Turkey&#39;s today:</li></ul><pre>var promised = order.Value.Promise(c.PromisedDate, DateOnly.FromDateTime(now.DateTime));</pre><h3>5. Bank Management: times stored as text</h3><p>My banking app in Java uses SQLite. SQLite has no separate date type; times are stored as text and queries compare them as text, for example to find accounts that have matured or transactions after today. ISO-formatted strings also sort correctly in alphabetical order, so this usually works. On one condition: <strong>they must always be written in the same format.</strong></p><p>Java’s LocalDateTime.toString() breaks that condition: when the seconds are zero, it leaves them out.</p><pre>LocalDateTime.of(2026, 10, 9, 9, 0, 0).toString();   // &quot;2026-10-09T09:00&quot;<br>LocalDateTime.of(2026, 10, 9, 9, 0, 5).toString();   // &quot;2026-10-09T09:00:05&quot;</pre><p>The same instant could be written two ways: &quot;2026-10-09T09:00&quot; and &quot;2026-10-09T09:00:00&quot;. As text they are not equal; the shorter one sorts before the longer one. So a query with &gt;= &#39;2026-10-09T09:00:00&#39; could miss a record stored as &quot;...T09:00&quot; for the very same instant.</p><p>The fix is to write every time through one function, always with seconds, and to round the current time to whole seconds:</p><pre>public static String ts(LocalDateTime time) {<br>    return time.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);<br>}</pre><pre>return LocalDateTime.now(clock).truncatedTo(ChronoUnit.SECONDS);</pre><p>The rounding is for the same reason: fractions of a second are sometimes written and sometimes not, which again produces strings of different lengths.</p><h3>What I took away</h3><ul><li><strong>First ask: is this an instant or a day?</strong> An instant is stored in UTC and converted to a time zone for display. A day, such as a birthday, a due date or a forecast day, is kept as a date without a time zone and never turned into an instant.</li><li><strong>The display time zone is a decision.</strong> The city’s time for weather, the cinema’s time for a cinema, the shop’s time for a shop. The user’s computer clock is often not the right answer.</li><li><strong>Today and this year are computed in a time zone.</strong> UTC&#39;s today is not Istanbul&#39;s today; the difference shows at midnight and on New Year&#39;s Day.</li><li><strong>The current time is injected.</strong> A clock from TimeProvider or Clock can be set to any moment in a test.</li><li><strong>Times stored as text are written in one format.</strong> Otherwise the same instant becomes two different strings and comparisons go quietly wrong.</li></ul><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/tarih-saat-dilimi-tuzaklari-utc"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5ffa29468aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Host Header Poisoning: Where Does Your Password Reset Link Point?]]></title>
            <link>https://medium.com/@mrcdprm/host-header-poisoning-where-does-your-password-reset-link-point-f75808385939?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f75808385939</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[password-reset]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 06:31:01 GMT</pubDate>
            <atom:updated>2026-11-23T06:31:01.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jX0OpkU1zfjSlp29H4uidg.png" /></figure><h4>If a reset link is built from the request’s Host header, an attacker can get a valid link to their own site sent to you. The hole I found in Casus and the fix.</h4><p>In most apps, the link in a password reset e-mail is built from the address the request came in on: send the user back to whichever site they came from. It sounds right, but that address is in the hands of whoever sends the request. This post is about the <strong>Host header poisoning</strong> hole I found in Casus, my party game, during the final review before release: how it put the password reset link at risk and how I closed it. I also show how I applied the same lesson from day one in Tamirhane.</p><h3>Where does the link come from?</h3><p>In ASP.NET Core, the short way to build a full URL in a controller is to pass the scheme to Url.Action:</p><pre>// old code<br>Url.Action(nameof(Reset), &quot;Account&quot;, new { userId = account.Id, code = Encode(token) }, Request.Scheme)!;</pre><p>That line produces something like https://spygame.miracdeprem.com/account/reset?userId=...&amp;code=.... The domain part comes from the request&#39;s Host header. So the link starts not with the site&#39;s own address but with <strong>the address the request claims to be for</strong>.</p><p>Host is an ordinary header the browser sends with every request. The browser fills it from the address bar, but an attacker who sends the request from their own program rather than a browser can write any value. If proxies sit in between, headers such as X-Forwarded-Host can play the same role.</p><h3>The attack</h3><p>Password reset works like this: the user enters their e-mail, the site sends a link with a one-time code to that address, and opening the link lets them set a new password. The code itself is safe: unguessable and only in the inbox. The problem is <strong>which address the link carrying it points to</strong>.</p><ol><li>The attacker sends a forgot password request with Ayşe’s e-mail address and puts their own domain in the Host header: evil.example.</li><li>The site generates a real, valid reset code and e-mails Ayşe. The e-mail really comes from Casus; the sender, look and text are right. But the link is <a href="https://evil.example/account/reset?userId=...&amp;code=....">https://evil.example/account/reset?userId=...&amp;code=....</a></li><li>Ayşe clicks it, thinking I didn’t ask for this, but anyway, or out of curiosity. Her browser goes to the attacker’s site and hands over the code in the URL.</li><li>The attacker takes the code to the real site and changes Ayşe’s password.</li></ol><p>The nasty part is that everything the user can check is genuine: the e-mail, the sender, the code. The only fake thing is the link’s domain.</p><h3>Would it have worked in production?</h3><p>That depends on the infrastructure in between. Casus runs on Render with Cloudflare in front, and a request with a made-up Host is rejected before it reaches the app. I tried it while writing this post: a request with a fake Host header got a 403.</p><p>But I did not want a security rule to depend on the hosting platform’s routing details of the day. The platform can change, a proxy that trusts X-Forwarded-Host can be added, the app can run somewhere else. As long as the code itself carried the hole, safety was a coincidence.</p><h3>The fix: the site’s address comes from configuration</h3><p>The principle is simple: the domain of links sent to users comes from the app’s own configuration, not from the request. I put that in one place:</p><pre>/// &lt;summary&gt;<br>/// The site&#39;s own address for links in e-mails and invites. In production it comes from<br>/// PUBLIC_ORIGIN, never from the request: a forged Host header would otherwise put someone<br>/// else&#39;s site in a password-reset e-mail, with a valid token in it.<br>/// &lt;/summary&gt;<br>public static class PublicOrigin<br>{<br>    public static string Of(HttpContext http)<br>    {<br>        var configured = http.RequestServices.GetRequiredService&lt;IConfiguration&gt;()[&quot;PUBLIC_ORIGIN&quot;];<br>        return string.IsNullOrWhiteSpace(configured) ? $&quot;{http.Request.Scheme}://{http.Request.Host}&quot; : configured.TrimEnd(&#39;/&#39;);<br>    }<br>}</pre><p>Links now start with it, and Url.Action only builds the path:</p><pre>PublicOrigin.Of(HttpContext) + Url.Action(nameof(Reset), &quot;Account&quot;, new { userId = account.Id, code = Encode(token) });</pre><p>In local development the setting can stay empty; the request’s address is used then, because there is only one address locally anyway. In production, forgetting the setting would silently bring the hole back. So the app refuses to start without it:</p><pre>if (builder.Environment.IsProduction() &amp;&amp; string.IsNullOrWhiteSpace(builder.Configuration[&quot;PUBLIC_ORIGIN&quot;]))<br>    throw new InvalidOperationException(&quot;PUBLIC_ORIGIN is required in production (e.g. https://spygame.miracdeprem.com).&quot;);</pre><p>As a second layer I limited ASP.NET Core’s AllowedHosts setting to the site&#39;s own addresses, so a request with a Host not on the list never reaches the application code:</p><pre>- key: PUBLIC_ORIGIN<br>  value: &quot;https://spygame.miracdeprem.com&quot;<br>- key: AllowedHosts<br>  value: &quot;spygame.miracdeprem.com;spy-game-87jd.onrender.com&quot;</pre><p>The list also includes the address Render assigned. Render had appended -87jd to the service name because spy-game was taken; in the first release I had listed the name I expected and had to correct it to the real one right after. A list like this is a setting that has to be updated whenever an address changes.</p><p>The same class is used for room invite links, so sharing a room code also produces a link that starts with the site’s own address.</p><h3>The test</h3><p>The test covers an attacker asking for a password reset with a forged host header, and checks that the link in the e-mail starts with the site’s own address:</p><pre>[Fact]<br>public async Task Links_in_emails_use_the_sites_own_address_even_with_a_forged_host()<br>{<br>    var email = NewEmail();<br>    await ConfirmedAccountAsync(NewName(&quot;host&quot;), email);<br>    var attacker = NewBrowser();<br>    attacker.Headers[&quot;X-Forwarded-Host&quot;] = &quot;evil.example&quot;;<br>    await attacker.SubmitAsync(&quot;/account/forgot&quot;, &quot;/account/forgot&quot;, new() { [&quot;Email&quot;] = email });<br>    var html = factory.Emails.To(email)[^1].Html;<br>    Assert.Contains($&quot;href=\&quot;{GameFactory.PublicOrigin}/account/reset?&quot;, html);<br>    Assert.DoesNotContain(&quot;evil.example&quot;, html);<br>}</pre><h3>Tamirhane from day one</h3><p>Having hit this once, I built links from configuration from the first day in Tamirhane, my repair shop app. E-mail links, the customer’s tracking page link and the QR code on the intake receipt all start with the same address. The setting is read once at startup and its format is checked too: it must be a full https:// address with no path or query; http is accepted only locally.</p><pre>if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)<br>    || uri.AbsolutePath != &quot;/&quot; || !string.IsNullOrEmpty(uri.Query)<br>    || !(uri.Scheme == Uri.UriSchemeHttps || (uri.Scheme == Uri.UriSchemeHttp &amp;&amp; uri.IsLoopback)))<br>    throw new InvalidOperationException(<br>        &quot;PUBLIC_ORIGIN geçersiz: \&quot;https://alan.adi\&quot; biçiminde olmalı (http sadece localhost için).&quot;);</pre><h3>What I took away</h3><ul><li><strong>The domain of a link sent to a user must not come from the request.</strong> Host and X-Forwarded-Host are in the sender&#39;s hands. The site&#39;s address is configuration.</li><li><strong>If forgetting a setting could silently bring a hole back, the app should not start without it.</strong> The mistake shows up at release, not months later.</li><li><strong>Protection from the infrastructure is a bonus, not the foundation.</strong> The platform may reject forged requests today; the code still has to be right. A second layer such as AllowedHosts is cheap and harmless.</li><li><strong>The code can be fine while the link it travels in is not.</strong> The reset code was unguessable and single-use; the problem was who it was delivered to.</li></ul><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/host-basligi-zehirleme-sifre-sifirlama"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f75808385939" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Account Pre-Hijacking: Why My First Fix Fell Short]]></title>
            <link>https://medium.com/@mrcdprm/account-pre-hijacking-why-my-first-fix-fell-short-98a24431369f?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a24431369f</guid>
            <category><![CDATA[account-security]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 06:31:01 GMT</pubDate>
            <atom:updated>2026-11-22T22:59:38.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4A6jE-0ScA3qQK0o-nfbFQ.png" /></figure><h4>How someone who signs up first with your address can take over the account: the hole I found in Seans, the first fix that fell short and the real one.</h4><p>A sign-up form with e-mail confirmation looks safe: the account cannot be used until the owner of the address opens the link. But if the code does not clearly answer once the address is confirmed, whose password does the account have?, someone who signs up first with another person’s address can take that account over. This is called <strong>account pre-hijacking</strong>. This post is about how I found it in Seans, my cinema booking site, why my first fix fell short, and how I finally redesigned the sign-up flow.</p><h3>The sign-up flow and the old code</h3><p>The first sign-up flow in Seans was the usual one: the user enters name, e-mail and password, the account is created unconfirmed, a link goes to the address, opening it confirms the address and logs the user in. The form never reveals whether an address is registered; it always says check your e-mail.</p><p>There was an edge case: what if someone signs up again with an unconfirmed address? The first attempt might have had a mistyped password, so sending a new link seemed sensible:</p><pre>if (existing.emailVerifiedAt) {<br>  // confirmed: send the owner a password reset link<br>} else {<br>  // Not confirmed yet: the first registration may have had a typo&#39;d password; resend the link.<br>  const verifyToken = await createEmailToken(db(), existing.id, &#39;VERIFY_EMAIL&#39;);<br>  await mail(existing, &#39;verify&#39;, input.lang, link(&#39;/verify-email&#39;, verifyToken));<br>}</pre><p>With that code, this was possible:</p><ol><li>An attacker signs up with Ayşe’s address and <strong>their own password</strong>. The link goes to Ayşe’s inbox; she doesn’t open it.</li><li>One day Ayşe signs up with her own password. The code sends a new link but <strong>does not change the password</strong>.</li><li>Ayşe opens the link, the address is confirmed, she is logged in and suspects nothing.</li><li>The attacker logs into Ayşe’s account with their own password.</li></ol><h3>First fix: each link carries its own password</h3><p>I found this in the final review before release. My first fix: every sign-up attempt ties its own password to its own link. The link’s database record got the hash of the password chosen in that sign-up, and opening the link set the account’s password to the one the link carried. I turned the scenario into a test: the attacker signs up, Ayşe signs up, the attacker signs up again, <strong>Ayşe opens her own link</strong>. The test was red on the old code and green on the new one.</p><p>The fix was incomplete, and I noticed twelve days later while rereading the code to write this post.</p><h3>Why it was incomplete</h3><p>The test’s assumption says it all: Ayşe opens <strong>her own</strong> link. In reality Ayşe’s inbox held two e-mails: one from her sign-up and one triggered by the attacker. Their subject, text and button were identical. If the attacker signed up <strong>after</strong> Ayşe, the top e-mail was the link carrying the attacker’s password:</p><ol><li>Ayşe signs up with her own password.</li><li>The attacker signs up with Ayşe’s address and their own password. A second link lands in Ayşe’s inbox.</li><li>Ayşe opens the newest e-mail. The account is confirmed with the attacker’s password.</li></ol><p>The send the confirmation e-mail again button led to the same place: that link carried no password and kept the account’s latest one, which could be the attacker’s.</p><p>The root of the bug had not moved: <strong>the account’s password still came from whoever filled in the sign-up form.</strong> I had only changed the answer to which form&#39;s password. As long as the attacker could also decide whose link landed in the inbox, that answer was not safe.</p><h3>The real fix: the inbox owner chooses the password</h3><p>This time I asked the question the other way round: what is the one thing in this flow the attacker cannot reach? Ayşe’s inbox. So every piece of information that decides anything about the account has to be entered after the link in that inbox is opened.</p><p>The sign-up form now asks only for the e-mail address. The account is created with neither a name nor a password:</p><pre>// Not confirmed yet (a first try, or someone else typing this address): nothing about the<br>// account is set here, so a sign-up form cannot plant a name or password on it.<br>const user = existing ?? (await db().user.create({ data: { email: input.email, name: &#39;&#39; } }));<br>const verifyToken = await createEmailToken(db(), user.id, &#39;VERIFY_EMAIL&#39;);<br>await mail(user, &#39;verify&#39;, input.lang, link(&#39;/verify-email&#39;, verifyToken));</pre><p>The link opens a Create your account page where the name and password are chosen. Password rules are checked before the link is used up, so a weak password can be fixed and retried:</p><pre>const record = await findEmailToken(db(), input.token, &#39;VERIFY_EMAIL&#39;);<br>// An address that is already confirmed is set up; a leftover sign-up link must not change it.<br>if (!record || record.user.emailVerifiedAt) throw new AppError(400, &#39;invalid_or_expired_link&#39;);<br>// Check the password before using up the link, so a weak one can be retried.<br>const problem = passwordProblem(input.password, { email: record.user.email, name: input.name });<br>if (problem) throw new AppError(400, problem);<br>const passwordHash = await hashPassword(input.password);</pre><pre>const userId = await consumeEmailToken(db(), input.token, &#39;VERIFY_EMAIL&#39;);<br>if (!userId) throw new AppError(400, &#39;invalid_or_expired_link&#39;);<br>const user = await db().user.update({<br>  where: { id: userId },<br>  data: { name: input.name, passwordHash, emailVerifiedAt: new Date() },<br>});<br>// The address is confirmed: other sign-up links for it are no longer needed.<br>await db().emailToken.deleteMany({ where: { userId: user.id, type: &#39;VERIFY_EMAIL&#39;, usedAt: null } });</pre><p>Now, whichever link in her inbox Ayşe opens, she sets up the account with her own name and password. There is nothing the attacker can write to the account through the sign-up form. The name moved to this page for a reason too: in the old flow, the name the attacker typed appeared in the greeting of the e-mail sent to Ayşe and became the account’s display name.</p><p>Two edge cases the new flow created are covered as well:</p><ul><li><strong>Logging into an account with no password:</strong> if a sign-up was never finished, the account has no password. A login attempt returns the same error as an unknown address and takes the same time; to keep the timing from revealing that the address exists, a password check is run for unknown addresses too.</li><li><strong>Forgot password on an unfinished sign-up:</strong> there is no password to reset, and a reset link would have confirmed the account without a name. In that case the create-account link is sent instead.</li></ul><h3>Tests: both orders this time</h3><p>The lesson of the first fix went into the tests. The attacker can sign up before or after Ayşe, and Ayşe opens the newest e-mail:</p><pre>for (const order of [&#39;attacker first&#39;, &#39;attacker last&#39;]) {<br>  test(`a sign-up with my address by someone else cannot take over my account (${order})`, async () =&gt; {<br>    if (order === &#39;attacker first&#39;) await register(request(app));<br>    await register(request(app)); // my own sign-up<br>    if (order === &#39;attacker last&#39;) await register(request(app));<br>    // The newest e-mail in my inbox may be the one the attacker triggered; I open that one.<br>    const newest = tokenFromMail();<br>    // ...<br>    await complete(request(app), newest).expect(200);<br>    await login(PASSWORD).expect(200);<br>    assert.equal((await login(ATTACKER)).body.error, &#39;invalid_credentials&#39;);<br>  });<br>}</pre><p>There are separate tests for the resent link, for a weak password not using up the link, and for forgot password on an unfinished sign-up. I broke the protections on purpose: removing the name update broke three tests, and removing both the deletion of leftover links and the already set up check broke the two attack tests.</p><h3>Shipping without breaking the live site</h3><p>The change also touched the database schema: a user’s password now had to be allowed to be empty, and the password column on links was no longer needed. Doing both at once would have broken the site for the few minutes of the release. The live old code kept writing to the link column, and the new code could not create a user without a password. So I split the release into steps:</p><ol><li>First, on the live database, I only allowed the password column to be empty. That change works with the old code too.</li><li>I released the new code.</li><li>Once the new code was live, a second, small change removed the unused column. Here the order was reversed: the old code read that column, so dropping it earlier would have broken login on the live site.</li></ol><p>Before each step I backed up the affected tables and tried the change on the test database first.</p><h3>What I took away</h3><ul><li><strong>E-mail confirmation proves the address, not the password.</strong> Everything applied to the account at confirmation time has to come from the person who has access to the inbox. The safest way is to ask for it after the link in that inbox is opened.</li><li><strong>Testing an attack in one order is not enough.</strong> My first test tried the order I chose, not the attacker. If the attacker can choose the order, the test has to try every order.</li><li><strong>A fix can change the symptom instead of the root.</strong> The first fix changed which password but not who decides it.</li><li><strong>A schema change has to be thought through together with the old code still running.</strong> Changes that add or loosen go before the code; changes that remove go after it.</li></ul><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/hesabi-onceden-ele-gecirme-account-pre-hijacking"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a24431369f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python subprocess Pitfalls: Running ffmpeg Safely Without Hanging]]></title>
            <link>https://medium.com/@mrcdprm/python-subprocess-pitfalls-running-ffmpeg-safely-without-hanging-d4777e155b56?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4777e155b56</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[subprocess]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 06:31:02 GMT</pubDate>
            <atom:updated>2026-11-22T22:59:12.700Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqVab2lcf4CsDuk-2Ty4ng.png" /></figure><h4>The risk of shell=True, an unread pipe that freezes the program, pipes left open: what I learned running ffmpeg from Python in my video converter.</h4><p>Running another program from Python looks like one line: subprocess.run(&quot;ffmpeg -i video.mkv video.mp4&quot;, shell=True). Once the program runs for a long time, its progress has to be read, the user picks the file name, and the same program runs hundreds of times, every part of that line becomes a separate problem. This post is about the <strong>Python subprocess pitfalls</strong> I ran into while running ffmpeg in my desktop audio and video converter: commands going through a shell, an unread pipe freezing the program, pipes left open, and file names starting with a dash.</p><h3>What the app does</h3><p>The user picks one or more files, chooses a target format such as MP4, MP3 or WebM, and a quality. For each file the app first inspects it with ffprobe, then converts it with ffmpeg. During conversion it shows a progress bar and the time left, and the user can cancel at any moment. The UI is Tkinter; conversion runs on a separate thread so the window does not freeze.</p><h3>Pitfall 1: handing the command to a shell as text</h3><p>The shortest route is to write the command as one string and run it with shell=True. Then the string is interpreted by cmd.exe on Windows or sh on Linux. The file name sits inside that string, so the shell can read special characters in it as commands. A name like a&quot;; del *.* &amp; &quot;.mp4 closes the quote and slips a new command in. The user picks the file, but they may not have named it: it may have been downloaded or sent by someone.</p><p>The fix is to skip the shell entirely and pass the command as a list. Each item goes to the program as exactly one argument; spaces, quotes or &amp; inside it change nothing:</p><pre># Paths are always absolute: a file name starting with &quot;-&quot; must not look like an option<br>command = [ffmpeg, &quot;-hide_banner&quot;, &quot;-nostdin&quot;, &quot;-loglevel&quot;, &quot;error&quot;, &quot;-i&quot;, str(Path(source).resolve())]<br># ...<br>return command + [&quot;-progress&quot;, &quot;pipe:1&quot;, &quot;-nostats&quot;, &quot;-y&quot;, str(Path(target).resolve())]</pre><p>Two more small protections are in that list:</p><ul><li><strong>Absolute paths:</strong> if a file is named like -y.mp4, ffmpeg may take it for an option. Path(...).resolve() always gives a full path starting with C:\... or /..., so no argument starts with a dash.</li><li><strong>-nostdin:</strong> by default ffmpeg listens for keyboard commands, such as q to stop. It should not wait for or try to read input while running in the background, so that is off. The process is also started with stdin=subprocess.DEVNULL.</li></ul><h3>Pitfall 2: an unread pipe freezes the program</h3><p>To show progress I use ffmpeg’s -progress pipe:1 option. ffmpeg writes lines like these to standard output, stdout:</p><pre>out_time_us=1500000<br>progress=continue</pre><p>The app reads them and computes the percentage. Error messages go to standard error, stderr. To capture both, both are connected to pipes:</p><pre>self.process = subprocess.Popen(<br>    self.command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,<br>    text=True, encoding=&quot;utf-8&quot;, errors=&quot;replace&quot;, creationflags=NO_WINDOW,<br>)</pre><p>There is a nasty trap here. Every pipe has a limited buffer in the operating system. If the main program reads only stdout line by line and ffmpeg writes a lot to stderr meanwhile, the stderr buffer fills up. ffmpeg waits for room to write its next line, but the main program never reads stderr, so the buffer never drains. ffmpeg cannot write to stdout either, and the main program waits for something on stdout. Each waits for the other: a deadlock. The progress bar stops somewhere and the app waits forever.</p><p>With -loglevel error ffmpeg normally writes very little to stderr. But on a damaged file it can write an error line for every frame, so the buffer can fill at exactly the worst moment. I reproduced it with a small experiment on my own machine: a child process that writes 200,000 lines to stderr was still stuck after 5 seconds when stderr was not read, and finished in half a second when it was.</p><p>The fix is to keep reading stderr on a second thread. Only the last 20 lines are kept so memory does not grow; that is enough to understand the error:</p><pre>self.stderr = collections.deque(maxlen=20)  # only the last lines are kept</pre><pre>def _read_stderr(self):<br>    for line in self.process.stderr:<br>        self.stderr.append(line.rstrip())</pre><pre># If the error output is not read separately, the buffer fills up and ffmpeg hangs<br>reader = threading.Thread(target=self._read_stderr, daemon=True)<br>reader.start()</pre><p>Short commands where only the result matters do not have this problem. For a command like ffprobe, subprocess.run(..., capture_output=True) reads both pipes at the same time by itself; that is what I used there, with a timeout:</p><pre>result = subprocess.run(<br>    command, capture_output=True, text=True, encoding=&quot;utf-8&quot;, errors=&quot;replace&quot;,<br>    timeout=PROBE_TIMEOUT_SECONDS, creationflags=NO_WINDOW,<br>)</pre><p>The rule: when output is read line by line with Popen, no pipe may be left unread.</p><h3>Pitfall 3: pipes left open</h3><p>In the first version, two pipes stayed open after every conversion and file handles piled up. Pipes opened by Popen do not close when the process ends; they stay open until the garbage collector removes the Python object. You don&#39;t notice it with one conversion, but over a queue of hundreds of files they accumulate towards the operating system&#39;s limit.</p><p>The fix is two lines:</p><pre>self.process.wait()<br>reader.join(timeout=2)<br>self.process.stdout.close()  # if the pipes are not closed, each conversion leaves a file handle open<br>self.process.stderr.close()</pre><p>The order matters: first wait for the process to end, then for the thread reading stderr to finish, and only then close the pipes. A pipe closed in the other order breaks the thread that is still reading it.</p><h3>Pitfall 4: cancelling and half-written files</h3><p>When the user presses Stop, the process is stopped with terminate(). But the half-written output file stays on disk, and the user may think it is a working video. So on cancel or error the target file is deleted:</p><pre>if self.cancelled:<br>    self._remove_partial_output()<br>    return &quot;cancelled&quot;<br>if self.process.returncode != 0:<br>    self._remove_partial_output()<br>    return classify_error(self.stderr)</pre><p>There is also a timing detail: if the user cancels right as the process is starting, the process object does not exist yet. So the flag is checked again as soon as the process starts:</p><pre>if self.cancelled:  # cancel was pressed just as the process was starting<br>    self.process.terminate()</pre><p>On errors the user never sees ffmpeg’s raw output. The last stderr lines are searched for known phrases such as No space left on device or Permission denied and turned into a clear message.</p><h3>What I took away</h3><ul><li><strong>A list instead of </strong><strong>shell=True.</strong> Every piece of outside text, file names included, should go as exactly one argument. Arguments that could start with a dash should be turned into absolute paths.</li><li><strong>Every pipe connected with </strong><strong>Popen has to be read.</strong> If one is not, its buffer fills and the two processes wait for each other. For short commands, run(capture_output=True) handles this itself.</li><li><strong>Wait for the process, close the pipes.</strong> In a long-running app, small leaks add up.</li><li><strong>When an external program stops, clean up after it:</strong> delete the half-written file and never show the raw error to the user.</li></ul><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/python-subprocess-tuzaklari-ffmpeg"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4777e155b56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Check Then Write: Race Conditions Between Concurrent Requests]]></title>
            <link>https://medium.com/@mrcdprm/check-then-write-race-conditions-between-concurrent-requests-a65c8c3afede?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a65c8c3afede</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 06:31:01 GMT</pubDate>
            <atom:updated>2026-11-22T22:58:19.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_lvSdE5L_oHggkvWDZj1A.png" /></figure><h4>Never selling one seat twice, recording a double-clicked approval once: fixing race conditions with a partial UNIQUE index and PostgreSQL’s xmin.</h4><p>Checking that a seat is free before selling it, or that a quote is still pending before recording a decision, feels natural. The pattern is called <strong>check-then-act</strong>. With one user it always works. When two requests arrive at the same moment, both see free and both write. This post is about how I handled that <strong>race condition</strong> in two projects: with a partial UNIQUE index in my airline reservation system, and with PostgreSQL&#39;s row version, which gives optimistic concurrency, in Tamirhane, my repair shop app.</p><h3>How the race happens</h3><p>Selling a seat goes like this:</p><ol><li>Is seat 17C taken? Ask the database.</li><li>If it is, return an error; if not, write the ticket.</li></ol><p>When two requests run these steps at the same time:</p><ul><li><strong>Time 1</strong> · Request A: Is 17C taken? No. · Request B:</li><li><strong>Time 2</strong> · Request A: · Request B: Is 17C taken? No.</li><li><strong>Time 3</strong> · Request A: Write the ticket. · Request B:</li><li><strong>Time 4</strong> · Request A: · Request B: Write the ticket.</li></ul><p>The check was correct, but B got in between A’s check and A’s write. Result: two passengers in one seat. However carefully the code is written, as long as the time between those two steps is not zero, the race is possible.</p><p>The lasting fix is to enforce the rule <strong>at write time, in a single atomic step</strong>. Databases have their own tools for that.</p><h3>Airline: a partial UNIQUE index</h3><p>My airline reservation system is a desktop app on SQLite. When selling a seat, it first reads the occupied seats and gives a clear error if the chosen one is taken:</p><pre>final Set&lt;String&gt; taken = FlightService.occupied(c, flight.id());<br>// ...<br>if (taken.contains(seat.code()))<br>    throw new AirlineException(&quot;seatTaken&quot;, seat.code());</pre><p>That check exists to give the user a good message. The real rule lives in the database:</p><pre>-- A seat on a flight can be on only one valid ticket: the database blocks double sales too.<br>-- Cancelled tickets (active = 0) are not in the index, so the seat can be sold again.<br>CREATE UNIQUE INDEX IF NOT EXISTS tickets_seat ON tickets(flight_id, seat) WHERE active = 1</pre><p>Two decisions here.</p><p><strong>Why a partial index?</strong> A plain UNIQUE(flight_id, seat) would count cancelled tickets too, and that seat could never be sold again. With WHERE active = 1 the index covers only valid tickets; cancelling a ticket frees the seat.</p><p><strong>Why an index when there is already a check?</strong> In this app, writes go through a single connection and a synchronized method, so two sales inside the app cannot interleave. But that guarantee depends on application code. Another path that touches seats, such as changing a seat, a second program opening the database later, or a new feature written without the lock, would fall outside it. A rule that lives next to the data holds whichever way you come in.</p><p>If the index is violated, the database raises an error; the service catches it and tells the user this seat was just taken instead of showing a technical message:</p><pre>} catch (DataException e) {<br>    // If another operation took the same seat at the same moment, the UNIQUE index blocks it<br>    if (e.isUniqueViolation())<br>        throw new AirlineException(&quot;seatJustTaken&quot;);<br>    throw e;<br>}</pre><p>I wrote the test with requests that really run at the same time. 16 threads wait at a gate to grab the same seat; when the gate opens they all try at once, and exactly one is expected to succeed:</p><pre>final CountDownLatch start = new CountDownLatch(1);<br>for (int i = 0; i &lt; 16; i++) {<br>    results.add(pool.submit(() -&gt; {<br>        start.await();<br>        try {<br>            airline.bookings().book(/* same flight, 17C */);<br>            return true;<br>        } catch (AirlineException e) {<br>            return false;<br>        }<br>    }));<br>}<br>start.countDown();<br>// ...<br>assertEquals(1, ok);</pre><h3>Tamirhane: optimistic concurrency with a row version</h3><p>Tamirhane is a web app on PostgreSQL, and every request opens its own database context. An in-process lock is no use here: two requests arriving together run separately, and there may be more than one server one day.</p><p>The place where the race could happen was quote approval on the customer’s tracking page. If a customer presses Approve the repair twice, or approves in one tab and declines in another, two requests read the work order at the same moment. Both see awaiting approval and both record a decision. Two decisions land in the history, and the work order can end up in the wrong state.</p><p>A UNIQUE index is not a natural fit here, because what needs protecting is not one column but the whole state of the work order. The options:</p><ul><li><strong>Pessimistic locking:</strong> lock the row while reading, with SELECT ... FOR UPDATE. It works, but it means holding a lock on every read and carrying it until the transaction ends.</li><li><strong>Optimistic concurrency:</strong> no lock. At write time, check is the version I read still the same?; if it changed, reject the write.</li></ul><p>When conflicts are rare, optimistic concurrency fits better. Every PostgreSQL row has a system column called xmin: the ID of the transaction that last changed the row. It changes on every update, so it is a ready-made row version. Declaring it as a version column in EF Core takes one line:</p><pre>// Row version (PostgreSQL&#39;s xmin system column): a state change cannot be saved twice at once<br>// (e.g. if a customer double-clicks quote approval, the second request gets a &quot;changed&quot; error).<br>b.Property&lt;uint&gt;(&quot;Version&quot;).IsRowVersion();</pre><p>From then on, when EF Core updates a work order it adds the version it read to the WHERE clause. If another request changed the row in between, the version does not match, the update affects 0 rows and EF Core throws DbUpdateConcurrencyException.</p><p>In Clean Architecture the application layer does not know EF Core, so the infrastructure layer translates the error into its own type:</p><pre>async Task IUnitOfWork.SaveChangesAsync(CancellationToken ct)<br>{<br>    try<br>    {<br>        await SaveChangesAsync(ct);<br>    }<br>    catch (DbUpdateConcurrencyException e)<br>    {<br>        throw new ConcurrencyConflictException(e);<br>    }<br>}</pre><p>The use case turns that into a result, so the user sees a clear message rather than a 500 error:</p><pre>try<br>{<br>    await unitOfWork.SaveChangesAsync(ct);<br>}<br>catch (ConcurrencyConflictException)<br>{<br>    return ApplicationErrors.ConcurrentChange;<br>}</pre><p>In that case the tracking page says that a decision has already been made for this quote and the page shows the latest state. The buttons are also disabled after submitting, but that is only a convenience; the real protection is in the database.</p><p>The test replays the moment two requests read at the same time, using two separate database contexts against a real PostgreSQL:</p><pre>// Two requests read the work order at the same time; both see &quot;awaiting approval&quot;.<br>var a = (await first.Orders.GetByTrackingCodeAsync(code, default))!;<br>var b = (await second.Orders.GetByTrackingCodeAsync(code, default))!;</pre><pre>Assert.True(a.DecideQuote(true, &quot;Ayşe Kaya&quot;, null, Now).IsSuccess);<br>await first.UnitOfWork.SaveChangesAsync(default);</pre><pre>Assert.True(b.DecideQuote(false, &quot;Ayşe Kaya&quot;, null, Now).IsSuccess);<br>await Assert.ThrowsAsync&lt;ConcurrencyConflictException&gt;(() =&gt; second.UnitOfWork.SaveChangesAsync(default));</pre><p>This test does not leave the race to timing. The interleaving is written out step by step, so it gives the same result on every run.</p><h3>How the two fixes differ</h3><ul><li><strong>Protects</strong> · Partial UNIQUE index: One rule: one seat, one ticket · Row version, optimistic concurrency: The whole state of a record</li><li><strong>On conflict</strong> · Partial UNIQUE index: The insert is rejected · Row version, optimistic concurrency: The update is rejected</li><li><strong>Fits when</strong> · Partial UNIQUE index: The rule can be expressed as a column combination · Row version, optimistic concurrency: The rule spans several fields and business logic</li></ul><p>There is a third example in Casus: a room code is saved to Redis in one command with a write only if the key does not exist rule. Same idea: check and write in one atomic step.</p><h3>What I took away</h3><ul><li><strong>Check-then-act is always open to a race.</strong> The check can stay to give the user a good message, but the rule itself has to be enforced atomically at write time.</li><li><strong>Putting the rule next to the data</strong> makes it hold on every path through the app: a UNIQUE or partial index, a row version, write if absent in Redis.</li><li><strong>An in-process lock trusts a single process.</strong> That can be enough on the desktop; on the web, requests run in separate contexts and, later, on separate servers.</li><li><strong>There are two ways to test a race:</strong> threads that really start at the same moment, or a deterministic test that writes the interleaving out step by step. The second one never fails for no reason.</li></ul><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/yaris-durumu-check-then-act"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a65c8c3afede" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Store Money in a Float: Cents, decimal and Rounding Rules]]></title>
            <link>https://medium.com/@mrcdprm/dont-store-money-in-a-float-cents-decimal-and-rounding-rules-bc5399b64604?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc5399b64604</guid>
            <category><![CDATA[floating-points]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 06:31:01 GMT</pubDate>
            <atom:updated>2026-11-22T22:55:37.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDwLp30lic4IF28wDTh47A.png" /></figure><h4>Why 0.1 + 0.2 is not 0.3, and how that becomes an invoice bug. How I stored money as cents, decimal and Decimal across four projects.</h4><p>Everyone who learns to program eventually sees 0.1 + 0.2 come out as 0.30000000000000004. In a calculator that is a small display issue; on an invoice it is a bug: a customer is charged one cent too much or too little, and totals stop matching the sum of their lines. This post is about how I stored <strong>money and decimal numbers</strong> in four of my projects: integer cents in a car rental app, decimal with an explicit rounding rule in a repair shop app, Decimal parsed from strings in a unit converter, and, on purpose, float in a calculator.</p><h3>The problem: binary floating point</h3><p>float and double store numbers in base two. Just as 1/3 goes on forever in base ten, 0.1 goes on forever in base two, so it is stored as the nearest value that fits. Python lets you see the value actually stored:</p><pre>&gt;&gt;&gt; from decimal import Decimal<br>&gt;&gt;&gt; Decimal(0.1)<br>Decimal(&#39;0.1000000000000000055511151231257827021181583404541015625&#39;)<br>&gt;&gt;&gt; 0.1 + 0.2 == 0.3<br>False<br>&gt;&gt;&gt; round(2.675, 2)<br>2.67</pre><p>The last one is the most surprising: 2.675 looks like it should round up, but the value in memory is 2.67499999…, so it rounds down. For money, that means the result can be wrong even when the rounding rule is right.</p><p>There are two correct ways: store money as an <strong>integer in the smallest unit</strong>, or use a <strong>number type that works in base ten</strong>.</p><h3>1. Car rental in C++: integer cents</h3><p>In my car rental app, money is a qint64 number of kuruş, the Turkish cent, everywhere:</p><pre>// Money is stored everywhere as kuruş (an integer):<br>// 1,250.50 TL = 125050. Storing money as floating point brings rounding errors.</pre><p>Integer addition and multiplication never make mistakes. The hard part is division and percentages: where does the fraction of a cent go? I wrote that down explicitly wherever it happens:</p><pre>result.base = dailyPrice * result.days;<br>result.discount = result.base * result.discountPercent / 100; // integer division: fractions of a kuruş are dropped<br>result.total = result.base - result.discount;</pre><p>Integer division drops the fraction. So the discount can come out at most one kuruş lower, and the total always stays consistent as base - discount. Because the rule is written next to the code, nobody has to hunt for why is there a one-kuruş difference a year later.</p><p>Floating point is touched in only two places: when reading the amount a user typed and when printing it. On the way in, it is rounded to the nearest kuruş:</p><pre>qint64 fromLira(double lira)<br>{<br>    return std::llround(lira * 100.0);<br>}</pre><p>The double error never enters a calculation: it is converted to kuruş in the first step and left behind.</p><h3>2. Tamirhane in C#: decimal and rounding per line</h3><p>Quote lines in Tamirhane, my repair shop app, have a quantity, a unit price, a discount and VAT. Here I used decimal. C#&#39;s decimal works in base ten, so it stores 0.1 exactly:</p><pre>Console.WriteLine(0.1 + 0.2);   // 0.30000000000000004  (double)<br>Console.WriteLine(0.1m + 0.2m); // 0.3                  (decimal)</pre><p>decimal does not solve rounding; it only makes it visible. With 20% VAT and a 10% discount, intermediate results fall below a cent and have to be rounded somewhere. I made two decisions.</p><p><strong>Every step is rounded to 2 places, per line:</strong></p><pre>public decimal Gross =&gt; Money(Quantity * UnitPrice);<br>public decimal Discount =&gt; Money(Gross * DiscountRate / 100m);<br>public decimal Net =&gt; Gross - Discount;<br>public decimal Vat =&gt; Money(Net * VatRate / 100m);<br>public decimal Total =&gt; Net + Vat;</pre><p>The quote total is the sum of the rounded lines. I don’t round the total separately, so a customer adding up the lines by hand gets the same number.</p><p><strong>Half a cent rounds away from zero:</strong></p><pre>internal static decimal Money(decimal amount) =&gt; decimal.Round(amount, 2, MidpointRounding.AwayFromZero);</pre><p>That line matters because .NET’s default is different. Without a mode, Math.Round and decimal.Round use banker&#39;s rounding: a value exactly halfway goes to the even neighbour.</p><pre>Math.Round(0.025m, 2);                                // 0.02<br>Math.Round(0.025m, 2, MidpointRounding.AwayFromZero); // 0.03</pre><p>Banker’s rounding is a good choice in statistics, because over many operations the ups and downs balance out. But someone who sees 0.025 TL printed as 0.02 on a receipt will think it is a mistake. I picked the rule people expect on a receipt and pinned it with a test:</p><pre>[Fact]<br>public void Half_kurus_rounds_away_from_zero()<br>{<br>    var order = Diagnosing();</pre><pre>    // 0.25 × 10% = 0.025 → 0.03<br>    var line = order.AddQuoteLine(QuoteLineKind.Part, null, &quot;Vida&quot;, 1, 0.25m, 10, 0).Value;</pre><pre>    Assert.Equal(0.03m, line.Vat);<br>    Assert.Equal(0.28m, line.Total);<br>}</pre><p>In the database, amounts live in PostgreSQL numeric columns, so they stay in base ten there too. When taking a payment, an amount with digits below a cent, like 10.005 TL, is rejected outright; there is a test for that as well.</p><h3>3. Unit converter in Python: factors as strings</h3><p>In the unit converter, every unit has a factor: 1 inch = 0.0254 metres, for example. I used Python’s decimal module, but there is a trap here too: writing Decimal(0.0254) carries the float error straight into the Decimal. So the factors are written as strings:</p><pre># Factors are written as strings so that converting them<br># to Decimal involves no binary floating-point rounding.<br>unit(&quot;in&quot;, &quot;in&quot;, &quot;İnç&quot;, &quot;Inch&quot;, &quot;0.0254&quot;),</pre><p>Exchange rates come from the internet as JSON, and the JSON parser turns numbers into float. There I convert with Decimal(str(value)). str gives the shortest correct representation of a float, so a rate of 34.25 becomes Decimal(&quot;34.25&quot;), not 34.249999….</p><p>When printing a result I round it to 12 significant digits. Rounding happens only for display; the number is carried in full through the calculation.</p><h3>4. Calculator in Python: float on purpose</h3><p>I did not use decimal in the calculator. The reason: scientific functions such as sin, log and square root live in the math module and work on float; Decimal has no equivalent for most of them. This is measurement and science, not money; the real problem is not the calculation but the text the user sees.</p><p>Two small things were enough to avoid showing 0.1 + 0.2 as 0.30000000000000004. The result is printed with 15 significant digits:</p><pre>def format_result(value):<br>    return f&quot;{value:,.15g}&quot;</pre><p>And a result within a billionth of a whole number snaps to it, so that sin(π) shows 0 instead of 1.2e-16:</p><pre>def snap_to_integer(x):<br>    nearest = round(x)<br>    return float(nearest) if abs(x - nearest) &lt; 1e-9 else x</pre><p>That is enough for a calculator, not for money. The difference: in a calculator the error only shows on screen and is fixed in formatting; with money the wrong value gets saved, summed and printed on an invoice.</p><h3>What I took away</h3><ul><li><strong>Money is never stored in </strong><strong>float or </strong><strong>double.</strong> Use either an integer in the smallest unit, cents, or a base-ten type: decimal, Decimal, numeric in the database.</li><li><strong>A base-ten type doesn’t solve rounding; it makes it visible.</strong> Where to round, per line or on the total, and how, away from zero or to even, has to be chosen explicitly and pinned with a test. In .NET the default is banker’s rounding.</li><li><strong>Conversion has to be lossless:</strong> Decimal(&quot;0.1&quot;), not Decimal(0.1). A floating-point value from outside is converted in the first step and never goes back to float inside the calculation.</li><li><strong>An error in display is not an error in calculation.</strong> Formatting is enough for a calculator; not for an invoice.</li></ul><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/para-float-decimal-yuvarlama"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc5399b64604" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Birthday Paradox: Why Random Codes Collide Sooner Than Expected]]></title>
            <link>https://medium.com/@mrcdprm/the-birthday-paradox-why-random-codes-collide-sooner-than-expected-ba6dceb0ce77?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba6dceb0ce77</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 06:31:01 GMT</pubDate>
            <atom:updated>2026-11-22T22:54:25.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJfhkApa9JxwCMq5PM6mmQ.png" /></figure><h4>Six-character codes with 887 million values hit a 50% chance of a collision at 35 thousand codes. How the birthday paradox hit my booking codes and a test.</h4><p>Short random codes are everywhere: booking references called PNRs, game room codes, discount codes, short links. When a 6-character code has hundreds of millions of possible values, two codes coming out the same seems impossible. It isn’t. This post is about how the <strong>birthday paradox</strong> showed up in two of my projects: in my airline reservation system, the code that builds the sample data was almost certain to collide, and in my game Casus a test failed for no visible reason about once every seventy runs.</p><h3>The paradox</h3><p>How many people need to be in a room before the chance that two of them share a birthday passes 50%? Intuition says 183, half a year. The right answer is <strong>23</strong>.</p><p>Intuition goes wrong because the question is not was someone born on my birthday? but do <strong>any two people</strong> share a birthday?. 23 people make 253 different pairs, and every pair is another chance of a match.</p><p>The same maths applies to codes. When you draw n random codes from a space of N possible values:</p><ul><li>Expected number of colliding pairs: <strong>λ ≈ n² / 2N</strong></li><li>Chance of at least one collision: <strong>1 − e^(−λ)</strong></li><li>That chance reaches 50% at about <strong>1.18 × √N</strong> codes.</li></ul><p>The last line is the one that matters: collisions start not at N but at the <strong>square root of N</strong>.</p><h3>The codes</h3><p>Both projects use the same format: 6 characters from a 31-letter alphabet.</p><pre>/** No look-alike characters (0/O, 1/I/L), so a code read out over the phone is not misheard. */<br>public static final String PNR_ALPHABET = &quot;ABCDEFGHJKMNPQRSTUVWXYZ23456789&quot;;<br>public static final int PNR_LENGTH = 6;</pre><p>3¹⁶ = 887,503,681, about 887 million values. Its square root is about <strong>29,800</strong>. So with around 35 thousand codes, the chance that two of them match is 50%.</p><h3>Airline: the sample data was almost certain to collide</h3><p>My airline reservation system generates sample data on first launch so the app looks real: past and future flights, occupied seats, cancellations. That means about 75 thousand bookings, each with a random PNR.</p><p>The numbers:</p><ul><li><strong>Codes 5,000</strong> · Expected colliding pairs: 0.014 · At least one collision: 1.4%</li><li><strong>Codes 35,000</strong> · Expected colliding pairs: 0.69 · At least one collision: 50%</li><li><strong>Codes 75,000</strong> · Expected colliding pairs: 3.17 · At least one collision: <strong>95.8%</strong></li></ul><p>The pnr column has a UNIQUE constraint. So if the codes had been generated blindly, setup would very likely have stopped halfway and the app would have failed on first launch. Looking at 887 million values it was easy to say they won&#39;t collide; doing the maths turned that around.</p><p>The fix lives in two places. While generating sample data, the codes already used are kept in memory and a repeated code is drawn again:</p><pre>private static String unique(Set&lt;String&gt; used, Supplier&lt;String&gt; generator) {<br>    String code;<br>    do {<br>        code = generator.get();<br>    } while (!used.add(code));<br>    return code;<br>}</pre><p>For a new booking while the app is running, the code is looked up in the database and redrawn if it exists:</p><pre>for (int attempt = 0; attempt &lt; 20; attempt++) {<br>    final String code = pnr ? Codes.pnr(airline.random()) : Codes.ticketNumber(airline.random());<br>    try (PreparedStatement ps = c.prepareStatement(existsSql)) {<br>        ps.setString(1, code);<br>        if (!ps.executeQuery().next())<br>            return code;<br>    }<br>}<br>throw new IllegalStateException(&quot;Benzersiz kod üretilemedi&quot;); // could not generate a unique code</pre><p>The UNIQUE constraint stays: if anything goes wrong between the check and the insert, the database has the last word.</p><h3>Casus: a test that failed once every seventy runs</h3><p>In Casus, creating a room generates a 6-character room code, and friends join with it. To test the generator I had written: generate 5,000 codes, all of them must be different.</p><p>The test passed most of the time and failed now and then. The code had no bug; the test’s expectation was wrong. The first row of the table above is exactly this case: with 5,000 codes the chance of at least one collision is 1.4%, roughly once every 70 runs. A test that fails at random does more harm than one that never fails: after a while nobody believes the red.</p><p>I rewrote the test around the statistics:</p><pre>// Birthday paradox: among 5,000 codes from 887 million, a single repeat happens about 1.4%<br>// of the time (creating a room then just draws again). A broken generator repeats far more.<br>var codes = Enumerable.Range(0, 5000).Select(_ =&gt; RoomCode.Generate(random)).ToHashSet();<br>Assert.True(codes.Count &gt;= 4997, $&quot;{5000 - codes.Count} repeats&quot;);</pre><p>Up to 3 repeats are allowed. With 0.014 repeats expected, the chance of 4 or more is about 1.6 in a billion, so the test no longer fails for nothing. But if the generator breaks, say it never uses half of the alphabet or always starts from the same seed, repeats are counted in the hundreds and the test goes red immediately.</p><p>In the running system a collision is not an error, just a normal case. A room is saved to Redis with a write only if the key does not exist rule, and a taken code means another try:</p><pre>public Task&lt;bool&gt; CreateAsync(Room room) =&gt;<br>    Db.StringSetAsync(StoreKeys.Room(room.Code), GameJson.Write(room), StoreKeys.RoomLifetime, When.NotExists);</pre><pre>for (var attempt = 0; attempt &lt; MaxCodeAttempts; attempt++)<br>{<br>    var room = RoomEngine.Create(RoomCode.Generate(random), /* ... */);<br>    if (await rooms.CreateAsync(room)) return (null, room.Code);<br>}<br>return (&quot;try_again&quot;, null); // ten taken codes in a row: practically never</pre><p>I used one atomic operation instead of check, then write so that two rooms created at the same moment cannot get the same code. With a separate check and write, both could see the code as free and both could write it.</p><h3>Why I didn’t make the codes longer</h3><p>A longer code means fewer collisions, but people read these codes on a phone, say them out loud and type them by hand. 6 characters is comfortable; 10 is not. Handling collisions with retries and a uniqueness rule is cheaper than handling them with length.</p><p>Collisions and guessability are also separate problems. A collision is two codes come out the same; guessing is someone finds another person’s code. The defence against guessing has three parts: a secure random source, which means SecureRandom in Java and a cryptographic generator in C#, codes that are not sequential, and a limit on attempts. In the airline app a PNR alone is not enough: it is asked together with the passenger&#39;s surname, and failed attempts trigger a wait.</p><h3>What I took away</h3><ul><li><strong>Random codes start colliding around √N.</strong> For 887 million values that is about 30 thousand. If the number of codes will get anywhere near that, a collision is not a possibility but an expected event.</li><li><strong>Uniqueness should rest on a rule, not on randomness:</strong> UNIQUE in the database, write if absent in Redis, and a retry when the code is taken.</li><li><strong>Tests involving randomness are written with statistics.</strong> Instead of no repeats at all, compute the expected value and set a bound that catches a broken generator without ever failing a healthy one by accident.</li></ul><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/dogum-gunu-paradoksu-rastgele-kod-cakismasi"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba6dceb0ce77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Real Client IP Behind a Proxy: X-Forwarded-For and a Rate Limit That Didn’t Work]]></title>
            <link>https://medium.com/@mrcdprm/the-real-client-ip-behind-a-proxy-x-forwarded-for-and-a-rate-limit-that-didnt-work-87d3c11a592e?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/87d3c11a592e</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 06:31:01 GMT</pubDate>
            <atom:updated>2026-11-22T22:53:35.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3dH61SM0jgTkue_Vq9B2w.png" /></figure><h4>Two rate limits behind Render and Cloudflare failed in production: one never filled up, one fell to a fake header. Which X-Forwarded-For value to trust.</h4><p>Adding a per-IP rate limit to a web app looks easy: take the address the request came from, count its requests per minute, return 429 once it goes over. When the app runs behind a proxy, that first step, the address the request came from, is not as simple as it sounds. This post is about two rate limits in two of my projects that did not work on the live site. One never filled up; the other could be bypassed completely with a fake header. Both had the same root cause: <strong>which value of the X-Forwarded-For header to trust.</strong></p><h3>What client address means behind a proxy</h3><p>Most of my server-side projects on free tiers run on Render, and Render sits behind Cloudflare. A visitor’s request reaches the app like this:</p><pre>visitor  →  Cloudflare server  →  Render proxy  →  app</pre><p>The connection the app sees comes from Render’s proxy, not from the visitor. Proxies carry the visitor’s address in the X-Forwarded-For header. Each proxy <strong>appends</strong> the address it received the request from:</p><pre>X-Forwarded-For: &lt;whatever the visitor wrote&gt;, &lt;visitor&gt;, &lt;Cloudflare server&gt;</pre><p>That list has two properties:</p><ol><li><strong>The leftmost values are in the client’s hands.</strong> A visitor can send their own X-Forwarded-For header. Proxies do not remove it; they only append to it.</li><li><strong>Counting from the right gets you to trustworthy values,</strong> but only as many as there are known proxies. Without knowing which proxy wrote what, no value can be trusted.</li></ol><h3>Bug 1: the limit never filled up in Crypto Toolkit, ASP.NET Core</h3><p>Crypto Toolkit had a limit of 300 requests per minute per IP. To get the right address behind Render’s proxy, I turned on ASP.NET Core’s ForwardedHeaders middleware. I did not know the proxy&#39;s address in advance, so I cleared the known proxy lists:</p><pre>builder.Services.Configure&lt;ForwardedHeadersOptions&gt;(options =&gt;<br>{<br>    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;<br>    options.KnownIPNetworks.Clear();<br>    options.KnownProxies.Clear();<br>});</pre><p>With this setup the middleware takes the <strong>rightmost</strong> value as the client address. Everything worked locally and in the tests. In the final review before release I sent 320 parallel requests to the live site and did not get a single 429.</p><p>The reason: the rightmost value was not the visitor but the Cloudflare server that passed the request to Render. Cloudflare has many servers, and one visitor’s requests can go through different ones. Every Cloudflare address opened its own counter, so no counter ever reached the limit. The rate limit existed in the code but not in production.</p><h3>Bug 2: a fake header bypassed it in KVKK Document Assistant, Python</h3><p>KVKK Document Assistant is a FastAPI app served by uvicorn. So that the links it generated would use https, I let uvicorn read proxy headers and told it to trust every proxy:</p><pre>uvicorn app.main:app --proxy-headers --forwarded-allow-ips=&#39;*&#39;</pre><p>With every address treated as a trusted proxy, uvicorn took the <strong>leftmost</strong> value as the client address, and that value was the one the visitor wrote. In the final review I sent requests to the live site, each with a different made-up X-Forwarded-For: despite a limit of 20 documents per 10 minutes, 22 out of 22 requests went through. Every request could pretend to be someone else.</p><p>The two bugs look like opposites: one trusted the rightmost value, the other the leftmost. What they share is that in both I picked a value without knowing who wrote which part of the list.</p><h3>I measured before fixing</h3><p>Instead of guessing which header carried what, I added a temporary diagnostic endpoint to the KVKK project. It showed every IP-related header as the request reached the app. Sending requests to the live site from my own connection, with and without a fake header, I saw:</p><ul><li>X-Forwarded-For: the value I wrote on the left, then my real address, then a Cloudflare server on the right.</li><li>CF-Connecting-IP: always my real address.</li></ul><p>Cloudflare writes the visitor’s real address into CF-Connecting-IP itself. If a visitor tries to send that header, Cloudflare rejects the request with a 403; I tried that on the live site too. In this setup, it was the only value nobody could fake.</p><h3>The fix</h3><p>The rate limit reads CF-Connecting-IP. When it is missing, which happens on local runs, it falls back to the direct connection address:</p><pre>public static class ClientIp<br>{<br>    public const string CloudflareHeader = &quot;CF-Connecting-IP&quot;;</pre><pre>    public static string Of(HttpContext context)<br>    {<br>        var header = context.Request.Headers[CloudflareHeader].ToString();<br>        if (IPAddress.TryParse(header, out var address)) return address.ToString();<br>        return context.Connection.RemoteIpAddress?.ToString() ?? &quot;unknown&quot;;<br>    }<br>}</pre><p>The Python side follows the same logic:</p><pre>def client_ip(request: Request) -&gt; str:<br>    cf = request.headers.get(&quot;cf-connecting-ip&quot;, &quot;&quot;).strip()<br>    if cf:<br>        return cf<br>    return request.client.host if request.client else &quot;unknown&quot;</pre><p>I kept uvicorn’s --proxy-headers, because without it the links the app generated turned into http. That setting now only matters for the scheme; the rate limit never looks at X-Forwarded-For.</p><p>After the fix I repeated the same tests on the live site. On KVKK the fake headers no longer helped and the 21st request got a 429. I applied the same fix to Casus and Sahaf, which also run on Render behind Cloudflare, and tested Casus on the live site as well.</p><h3>A different setup, a different right answer</h3><p>CF-Connecting-IP is not the right answer everywhere, only where Cloudflare is in front. My cookieless analytics tool Nabız runs on my own server on Oracle Cloud, behind Caddy. There is no Cloudflare in front, and Caddy appends the address it received the request from. So Nabız has a different rule, and two different addresses:</p><pre>// clientIP: Caddy arkasındaysak (-trust-proxy) X-Forwarded-For&#39;un son değeri,<br>// yani Caddy&#39;nin kendi eklediği adres; değilse doğrudan bağlantının adresi.<br>// İstemcinin kendi yazdığı sahte değerler listenin başında kalır, onlara bakmayız.</pre><p>Behind Caddy, the last value is the one Caddy added; the client’s fake values stay at the start of the list and are ignored.</p><ul><li><strong>The last value for the rate limit:</strong> the one Caddy appended, which nobody can fake.</li><li><strong>The first value for counting unique visitors:</strong> when a site serves the Nabız script from its own domain, through Vercel for example, the last value is Vercel’s address and every visitor would count as one person. The first value can be faked, but the worst outcome is a slightly inflated count; nobody’s data leaks and the limit is not bypassed.</li></ul><p>Zarf runs behind Caddy on the same machine. I put the Caddy setting that preserves X-Forwarded-For only in Nabız&#39;s block; writing it globally would have changed how Zarf reads addresses too.</p><h3>What I took away</h3><ul><li><strong>X-Forwarded-For is a list, and its left side belongs to the client.</strong> Settings that mean trust every proxy, like --forwarded-allow-ips=&#39;*&#39; or KnownProxies.Clear(), make you pick the wrong value from it.</li><li><strong>The right value depends on the setup.</strong> With Cloudflare in front, the header Cloudflare writes; with my own proxy in front, the last value that proxy appended. I don’t write this code without knowing how many proxies there are and what each one writes.</li><li><strong>This bug is invisible locally.</strong> There is no proxy on my machine, and the tests talk to the app directly. I found both bugs in the final review before release by sending requests to the live site. Since then, every project’s final review tests the rate limit on the live site once with a fake header and once with parallel requests.</li></ul><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/proxy-arkasinda-gercek-ip-x-forwarded-for"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87d3c11a592e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Turkish I Problem: How Case Conversion Broke in Five of My Projects]]></title>
            <link>https://medium.com/@mrcdprm/the-turkish-i-problem-how-case-conversion-broke-in-five-of-my-projects-d6f290dfac51?source=rss-d1b9960768fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6f290dfac51</guid>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[unicode]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Miraç Deprem]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 06:31:02 GMT</pubDate>
            <atom:updated>2026-11-22T22:53:11.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emiBSiTz04RwpaseoArXgA.png" /></figure><h4>In Turkish, lower-case I is ı and upper-case i is İ. The bugs this caused in five of my projects in Java, JavaScript, Python and C#, and how I fixed them.</h4><p>Anyone who builds software for Turkish users runs into the same bug sooner or later: case conversion. In English, I and i are one pair. Turkish has two pairs: the dotless I-ı and the dotted İ-i. Most programming languages convert case with English rules by default, and some use the language of the machine they run on. Both choices break in the wrong place. This post is about the <strong>Turkish I problem</strong>: how I hit it in five of my projects, in five different shapes, and how I fixed each one in Java, JavaScript, Python and C#.</p><h3>The problem in one table</h3><ul><li><strong>I to lower case</strong> · English rule: i · Turkish rule: ı</li><li><strong>i to upper case</strong> · English rule: I · Turkish rule: İ</li><li><strong>İ to lower case</strong> · English rule: i plus a combining dot, two characters · Turkish rule: i</li></ul><p>Any code that lowercases a string and compares it with another one can trip over this table: search, category matching, email addresses, file extensions, protocol keywords. The nasty part is that English test data never shows it.</p><h3>1. Java: the INBOX folder became ınbox</h3><p>My email client shows an icon for each folder: inbox, sent, trash. An IMAP server names the inbox INBOX. The code lowercased the folder name and looked for words like inbox, sent and trash.</p><p>In Java, toLowerCase() without an argument uses the machine&#39;s default locale. On a Turkish Windows install that is Turkish, and &quot;INBOX&quot;.toLowerCase() returns &quot;ınbox&quot;. Because of the dotless ı, nothing matched and the inbox had no icon. The code that picks server settings from an email address had the same problem: for someone who typed their address in capitals, GMAIL.COM became gmaıl.com and the Gmail preset was never found.</p><p>The fix is to ask for the locale-independent rule explicitly for technical strings:</p><pre>// Locale.ROOT: with Turkish rules &quot;INBOX&quot; -&gt; &quot;ınbox&quot; (dotless ı)<br>final String name = fullName.toLowerCase(Locale.ROOT);</pre><p>I made it a rule: Locale.ROOT for machine text such as folder names, domain names and protocol words; Turkish rules for Turkish text shown to people.</p><h3>2. JavaScript: the wrong letter in Hangman</h3><p>In my Hangman game, players can also type letters on the keyboard. In the Turkish game, a player who presses I means ı. JavaScript&#39;s toLowerCase() ignores language entirely and always turns I into i. Had I used it, a player hunting for the word KIŞ, which means winter, would press I, the game would check for i, and the player would lose a life for a wrong letter. Having been bitten by this in the email client, I used toLocaleLowerCase with an explicit language from the start:</p><pre>export function normalizeLetter(input, lang) {<br>  if (typeof input !== &#39;string&#39; || [...input].length !== 1) return null;<br>  const letter = input.toLocaleLowerCase(lang);<br>  return ALPHABETS[lang].includes(letter) ? letter : null;<br>}</pre><p>The game can also be played in English, so the language is not fixed; it is the game’s current language. The capital letters in the letter boxes go through toLocaleUpperCase(lang) for the same reason, otherwise the i in a Turkish word would show up as I. The tests check both languages:</p><pre>assert.equal(normalizeLetter(&#39;I&#39;, &#39;tr&#39;), &#39;ı&#39;);<br>assert.equal(normalizeLetter(&#39;İ&#39;, &#39;tr&#39;), &#39;i&#39;);<br>assert.equal(normalizeLetter(&#39;I&#39;, &#39;en&#39;), &#39;i&#39;);</pre><h3>3. JavaScript: typing kadikoy did not find Kadıköy</h3><p>City search in my weather app uses two services. Open-Meteo’s geocoding is fast for world cities, but it did not handle the Turkish ı and could not find Kadıköy, a district of Istanbul. So I added Photon, which is built on OpenStreetMap, for Turkish provinces and districts.</p><p>I had to compare the results from both services with what the user typed. On a phone, someone may type kadikoy or KADIKÖY. So I wrote a function that folds text into one comparable form:</p><pre>export function foldText(value) {<br>  return value<br>    .toLocaleLowerCase(&#39;tr&#39;)<br>    .normalize(&#39;NFD&#39;) // ş → s + cedilla; the marks are removed on the next line<br>    .replace(/[̀-ͯ]/g, &#39;&#39;)<br>    .replace(/ı/g, &#39;i&#39;);<br>}</pre><p>The order matters. Lowercasing with Turkish rules first gets I → ı and İ → i right. Then NFD, the Unicode decomposition, splits letters such as ş, ö and ü into a base letter plus a mark, and the marks are removed. Finally ı becomes i, because ı does not decompose: it is a letter of its own. The test:</p><pre>assert.equal(foldText(&#39;ŞANLIURFA&#39;), &#39;sanliurfa&#39;);<br>assert.equal(foldText(&#39;ısparta&#39;), foldText(&#39;Isparta&#39;));<br>assert.equal(foldText(&#39;Kadıköy&#39;), &#39;kadikoy&#39;);</pre><h3>4. Python: the name İrem became Irem</h3><p>My KVKK Document Assistant masks people’s names in a document before a language model ever sees it, and puts fake names in their place. While looking names up in a dictionary and writing the fake ones, I ran into two Python behaviours:</p><pre>&gt;&gt;&gt; &quot;İ&quot;.lower()<br>&#39;i̇&#39;          # i + combining dot (U+0307), two characters<br>&gt;&gt;&gt; &quot;irem&quot;.capitalize()<br>&#39;Irem&#39;</pre><p>The first broke matching an all-caps İREM against irem in the dictionary: the lowercased text looks the same but carries an extra invisible character. The second wrote Irem instead of İrem in the fake data and in email text.</p><p>Python’s standard library has no language-aware case conversion, so I wrote two small functions:</p><pre>def tr_lower(word: str) -&gt; str:<br>    return word.replace(&quot;I&quot;, &quot;ı&quot;).replace(&quot;İ&quot;, &quot;i&quot;).lower()</pre><pre>def tr_capitalize(word: str) -&gt; str:<br>    if not word:<br>        return word<br>    first = {&quot;i&quot;: &quot;İ&quot;, &quot;ı&quot;: &quot;I&quot;}.get(word[0], word[0].upper())<br>    return first + tr_lower(word[1:])</pre><p>In this project a miss was expensive: a name that failed to match could reach the model unmasked. So the tests generate every name in lower case, upper case, with Turkish suffixes and without Turkish letters, and check that none of them gets through unmasked.</p><h3>5. C#: searching ip13 did not find IP13</h3><p>The stock page in Tamirhane searches by part code or name. Part names are Turkish, like Şarj soketi and iPhone 13 ekran paneli, while codes like IP13-SCR use English letters. The first version searched case-insensitively with the Turkish culture. Typing şarj found Şarj soketi, but typing ip13 did not find IP13-SCR: under Turkish rules the capital of i is İ, so ip13 and IP13 are not the same word.</p><p>Switching to the invariant culture was no fix either; then ince would not find İnce kablo. Real data has both kinds of text side by side, so a match under either rule counts:</p><pre>// In Turkish the capital of &quot;i&quot; is &quot;İ&quot;: Turkish rules alone would not find &quot;IP13-SCR&quot; for &quot;ip13&quot;.<br>// Codes use English letters, names are Turkish; a match under either rule counts.<br>private static bool Contains(string text, string query) =&gt;<br>    Turkish.IndexOf(text, query, CompareOptions.IgnoreCase) &gt;= 0<br>    || CultureInfo.InvariantCulture.CompareInfo.IndexOf(text, query, CompareOptions.IgnoreCase) &gt;= 0;</pre><p>The test covers both kinds together:</p><pre>[InlineData(&quot;ip13&quot;, &quot;iPhone 13 ekran paneli&quot;)] // Turkish rules: &quot;i&quot; ≠ &quot;I&quot;; codes are still found<br>[InlineData(&quot;şarj&quot;, &quot;Şarj soketi USB-C&quot;)]<br>[InlineData(&quot;ŞARJ&quot;, &quot;Şarj soketi USB-C&quot;)]</pre><h3>What I took away</h3><p>All five bugs come down to one question: <strong>whose text is this?</strong></p><ul><li><strong>Machine text</strong>, meaning folder names, domains, file extensions, part codes and protocol words: the locale-independent rule. Locale.ROOT in Java, InvariantCulture in C#, plain toLowerCase() in JavaScript.</li><li><strong>Human text</strong>, meaning names, words and cities: the rule of the text’s language, passed explicitly. Locale.forLanguageTag(&quot;tr&quot;) in Java, toLocaleLowerCase(&#39;tr&#39;) in JavaScript, tr-TR in C#, a hand-written function in Python.</li><li><strong>Search over both:</strong> either check both rules, or fold the text into one form without diacritics.</li></ul><p>And one testing rule: every test for a function that changes case should contain at least one I, one İ and one ı. Those three letters catch, on the first run, the bugs English test data never sees.</p><p><em>Originally published at </em><a href="https://www.miracdeprem.com/en/blog/turkce-i-sorunu-buyuk-kucuk-harf"><em>miracdeprem.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6f290dfac51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>