Laravel in production
Sign in

Topics

Backend

Tools & DevOps

All guides

Search

Topics

Practice

Architecture · Laravel in production

From Laravel to Laravel Rust. Day 3: Rust reads the PHP session

Author: Volodymyr Pichkurov Published: 11 min read
Laravel Rust Laravel Rust

For two days Rust dealt only with strangers and robots: the view counter had no idea who you were, and the git hook knew nothing but a token. Today, for the first time, Rust looks at a real, live person logged into the site. Logged in through PHP. With PHP's cookie, PHP's session and PHP's encryption key.

Spoiler: Rust recognized the user on the very first request. The really interesting part turned out to be everything around it: the middleware PHP runs silently and that you rarely give a second thought.


In short

  • What we move: the suggestions in the "invite to team" field: GET /{locale}/admin/teams/{team}/search?q=….
  • What is new: Rust reads the PHP session — the cookie, the sessions table, login_web_… — and checks everything the auth, verified, CheckBlocked, feature:zones and throttle:60,1 middleware check.
  • The result: 53 scenarios. In 33, PHP and Rust answered byte for byte the same; the 20 unusual ones Rust deliberately handed to PHP; mismatches — zero.
  • The price: Rust now has the same APP_KEY as PHP. And the list of honest differences is at the end.

Test subject number three

A team owner types the beginning of a name or a profile address into the "Who to invite?" field. 250 ms after the last keystroke, the page asks the server:

http
GET /ru/admin/teams/01m8yzr3tvbcknaf8xc84n3n6v/search?q=ann
Accept: application/json
Cookie: devsense-session=eyJpdiI6…

…and gets back up to eight people:

json
{"people":[{"slug":"percent-ann","name":"100% Ann"},{"slug":"anna-under","name":"Anna_Under"}]}

Why this route is the perfect candidate for sessions day:

  • read-only — it writes nothing and leaves the session alone;
  • hit often — every pause in typing fires it; this is not a page someone opens once a day;
  • login required — there is no way around the PHP session here;
  • mistakes are cheap — if the suggestions do not arrive, the field still works: you can type the profile address by hand.

How PHP knows who you are

In PHP it is one line: $request->user(). Underneath it is a chain Laravel walks through on every request:

  1. EncryptCookies decrypts the devsense-session cookie with APP_KEY and checks the prefix: hmac_sha1(cookie name + "v2"), so the value of one cookie cannot be slipped into another.
  2. StartSession takes the resulting 40 characters as the session id and reads the row from the sessions table.
  3. The database driver stores the payload as base64(json) (we have 'serialization' => 'json').
  4. SessionGuard looks for the user id under the key login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d. The tail is sha1('Illuminate\Auth\SessionGuard'). Yes, literally a hash of the class name.

Back at the start of the series we built a small php-compat crate for exactly this. Today it finally goes to work. Here is the whole chain in Rust:

rust
pub async fn user_id(request: &Request) -> laravel::Result<Option<i64>> {
    let name = cookie_name();
    let Some(cookie) = request.cookie(&name) else {
        return Ok(None);
    };
    let Ok(encrypter) = request.encrypter() else {
        return Ok(None);
    };
    let Some(id) = php::decrypt_cookie(&name, &cookie, encrypter) else {
        return Ok(None);
    };
    if !is_valid_id(&id) {
        return Ok(None);
    }
    let Some(row) = db::table("sessions")
        .select(["payload", "last_activity"])
        .filter(col("id").eq(&id))
        .first::<SessionRow>()
        .await?
    else {
        return Ok(None);
    };
    if !is_fresh(i64::from(row.last_activity), unix_now(), lifetime_minutes()) {
        return Ok(None);
    }
    let Some(attributes) = php::decode_session_payload(&row.payload) else {
        return Ok(None);
    };
    Ok(php::logged_in_user(&attributes, "web")
        .as_ref()
        .and_then(user_id_of))
}

Notice how many return Ok(None) there are. That is not sloppiness, it is a principle: any doubt means "I don't know who this is". And on this route, "I don't know" means "let PHP answer".

A couple of subtleties that are easy to miss:

  • Our own routes, without the web group. In Laravel Rust, the web group starts its own session, its own cookies and CSRF. We do not need that, and it would even get in the way: the session here belongs to PHP. So the route is registered through routing.routes(…) — no groups, no session, no prefix. On a route like that, request.cookie() returns the raw encrypted value, and we decrypt it ourselves.
  • Lifetime. PHP considers a session dead if last_activity is older than SESSION_LIFETIME minutes. Rust does the same, but it also hands the last 5 seconds before that boundary to PHP: the clocks of two processes are not obliged to tick in perfect sync.
  • Rust keeps its hands off the session. It does not extend last_activity, does not issue new cookies, does not log anyone out. Login, logout, "remember me" and password changes all stay in PHP.

Five middleware PHP runs silently

Here is how the route is declared in PHP:

php
Route::prefix('{locale}')
    ->whereIn('locale', SetLocale::SUPPORTED_LOCALES)
    ->middleware(SetLocale::class)
    ->group(function () {
        // …
        Route::prefix('admin')->middleware(['auth', 'verified', 'can:access-admin'])->group(function () {
            // …
            Route::middleware('feature:zones')->prefix('teams')->controller(TeamController::class)->group(function () {
                // …
                Route::get('/{team}/search', 'search')->middleware('throttle:60,1')->name('admin.teams.search');

Plus the web group with its TrimStrings, ConvertEmptyStringsToNull, CheckBlocked and the binding of {team} to a model by public_id. Each of them has its own answer to a "bad" request: a redirect to login, 401, 403, 404 with the exception text, an HTML error page…

We could have replicated all of them. We went another way: Rust answers only the common case and hands everything else to PHP.

Situation Who answers
A logged-in owner or admin of an existing team Rust
Rate limit exceeded and the client expects JSON Rust (429)
A guest, no cookie, a foreign key, a dead session PHP
A blocked account (PHP also logs it out) PHP
E-mail not verified PHP
A regular team member, someone else's or a non-existent team PHP
Unknown locale, Zones turned off PHP
A suspicious q (more on that in the next section) PHP

The user never sees any of this: nginx intercepts the 503 from Rust and sends the same request to PHP. Rust does not need to know how PHP logs out blocked users — it simply does not take that case on.


The treacherous ?q=

What could be hard about one query string parameter? In PHP the controller does this:

php
$q = is_string($request->query('q')) ? $request->query('q') : '';

But three others have already had their go at it before that:

  • the PHP parser: q=a&q=b is b (the last one wins), while q[]=ann is already an array, and the controller gets an empty string;
  • TrimStrings: trims whitespace at the edges, using a regular expression with \s and the /u flag, plus U+FEFF, U+200B and U+200E;
  • ConvertEmptyStringsToNull: an empty string becomes null.

Replicating the PHP parser in Rust is not hard, so we did: + is a space, %71 is q, spaces at the start of a parameter name are dropped. But wherever PHP might behave in a non-obvious way, Rust honestly passes:

rust
pub fn trimmed(q: &str) -> Option<String> {
    let ascii = [' ', '\t', '\n', '\x0B', '\x0C', '\r'];
    let q = q.trim_matches(ascii);
    if q.contains('\0') {
        return None;
    }
    let unsure = |c: char| {
        (!c.is_ascii() && c.is_whitespace()) || matches!(c, '\u{FEFF}' | '\u{200B}' | '\u{200E}')
    };
    if q.chars().next().is_some_and(unsure) || q.chars().next_back().is_some_and(unsure) {
        return None;
    }
    Some(q.to_owned())
}

A non-breaking space at the start of the query? An array instead of a string? Bytes that do not add up to UTF-8? None — and the request goes to PHP. A normal person will not type anything like that. And if they do, they get exactly the same answer as before.


The search itself: almost letter for letter

The search logic in PHP fits on one screen:

php
$exact = User::query()->where('slug', $query)->where('is_blocked', false)->whereNotNull('email_verified_at')
    ->whereNotIn('id', $memberIds)->get(['id', 'name', 'slug', 'is_anonymous']);

$public = User::query()->listedInDirectory()->where('is_anonymous', false)->whereNotNull('email_verified_at')
    ->whereNotIn('id', $memberIds)
    ->where(fn ($q) => $q->whereRaw('lower(slug) like ?', [$escaped.'%'])->orWhereRaw('lower(name) like ?', ['%'.$escaped.'%']))
    ->orderBy('name')->limit(8)->get(['id', 'name', 'slug', 'is_anonymous']);

First comes an exact match on the profile address — that is how even private profiles are found, if you know their address. Then public profiles by the beginning of the address or part of the name.

In Rust it is the same SQL, only the conditions are typed and team members are excluded with a subquery:

rust
let public: Vec<Person> = db::table("users")
    .select(columns)
    // listedInDirectory()
    .filter(col("is_public").eq(true))
    .filter(col("is_approved").eq(true))
    .filter(col("is_blocked").eq(false))
    .filter(col("is_anonymous").eq(false))
    .filter(col("email_verified_at").is_not_null())
    .filter(col("id").is_not_in(members()))
    .filter(db::raw!("lower(slug) like {prefix}") | db::raw!("lower(name) like {part}"))
    .order_by("name")
    .limit(MAX_PEOPLE as u64)
    .get()
    .await?;

db::raw! with {prefix} and {part} is not string interpolation but query parameters, just like ? in PHP. And % and _ in user input are escaped beforehand by the same function as in PHP: 100% searches for literally "100%", not "anything that starts with 100".

One trap turned up in the User model:

php
/**
 * URL-friendly slug derived from name if the slug column is empty.
 */
public function getSlugAttribute(?string $value): string
{
    return $value ?: Str::slug($this->name);
}

If a person has no profile address, PHP makes one up from their name on the fly — with transliteration. We did not replicate Str::slug in Rust for the sake of a rare case: if a person without a slug shows up in the results, the whole response is handed to PHP.


Byte for byte: \/ and \u0410

The first comparison of the responses turned up something amusing. PHP:

json
{"people":[{"slug":"anna-testova","name":"\u0410\u043d\u043d\u0430 \u0422\u0435\u0441\u0442\u043e\u0432\u0430"}]}

Rust via serde_json:

json
{"people":[{"slug":"anna-testova","name":"Анна Тестова"}]}

It is the same JSON. The browser could not care less. But PHP's json_encode without flags escapes everything outside ASCII as \uXXXX, and a slash as \/. We wanted to compare responses byte for byte, with no "well, it's the same thing", so we escape the string exactly the way PHP does:

rust
pub fn php_json_string(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 2);
    out.push('"');
    for c in value.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '/' => out.push_str("\\/"),
            '\u{8}' => out.push_str("\\b"),
            '\u{C}' => out.push_str("\\f"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_ascii() && (c as u32) >= 0x20 => out.push(c),
            c => {
                let mut units = [0u16; 2];
                for unit in c.encode_utf16(&mut units) {
                    out.push_str(&format!("\\u{unit:04x}"));
                }
            }
        }
    }
    out.push('"');
    out
}

An emoji in a name becomes two surrogate halves, \ud83d\ude00, just like in PHP. That is covered by the tests.


The check: 53 scenarios

Same setup as on day two, but with a twist: we needed real PHP sessions. So the sessions for the test users were created by PHP itself — with its own Session\Store and its own database driver — and the cookies were encrypted by its own Encrypter. The key was single-use, generated only for this check: both PHP and Rust got it through an environment variable, and the real APP_KEY never took part.

Then — identical requests to both services:

What we checked Result
Case, spaces at the edges, +, a repeated q, Cyrillic, %, _, \, a slash, an emoji in a name, 1, 60 and 61 characters ✅ 33 byte-for-byte matches
The exact address of an anonymous, private, blocked and unverified profile ✅ match
Two different locales, the limit of 8 people, team members never show up in the results ✅ match
A guest, a garbage cookie, blocked, unverified, a regular member, someone else's team → PHP
An unknown team, an id in upper case, the xx locale → PHP
q[]=, %FF, a non-breaking space, a person without a slug in the results → PHP

33 matches, 20 times "let PHP answer", 0 mismatches. The headers matched too: Cache-Control: no-store, private, X-RateLimit-Limit: 60 and X-RateLimit-Remaining.

We checked the rate limit separately: 60 requests in a row — 200, the sixty-first — 429 {"message":"Too Many Attempts."}, just like PHP.


Honest differences

  • Rust does not extend the session. On every request PHP updates last_activity and reissues the session cookie and XSRF-TOKEN. Rust does not. For suggestions that is no big deal: the team page itself is served through PHP and keeps the session alive. But routes where a person may work for a long time with Rust alone will need a solution.
  • Rate limits are counted separately and differently. PHP uses a fixed one-minute window, Laravel Rust uses a token bucket. So PHP's Retry-After may be 42 while Rust's is 1: the quota comes back gradually. And the counters are not shared: if Rust hands a request to PHP, PHP counts it once more.
  • A 429 without JSON is PHP's job. If the client does not ask for JSON, PHP answers with an HTML error page. We do not replicate it: such a request goes to PHP.
  • APP_KEY now lives in two places. This is a direct consequence of "Rust reads the PHP cookie". Rust's .env is locked down with chmod 600, but the surface for a key leak has grown — and that needs to be understood.
  • Rust's SESSION_LIFETIME cannot be longer than PHP's. Otherwise Rust would accept a session that PHP already considers dead. The value is copied from PHP, not invented.

The scoreboard

  • A new php_session module: who is logged in, by the PHP cookie and table. Ready for the next routes.
  • The route: searching for people to invite to a team. Rust answers the common case, PHP all the others.
  • Tests: 7 new unit tests — from parsing ?q= to JSON escaping.
  • On the server: APP_KEY and SESSION_LIFETIME from PHP go into Rust's .env, a restart, one more location in nginx. Until the restart, Rust cannot decrypt the cookie and honestly hands everything to PHP — so the order of the steps does not matter.

What comes next

Day 4 — queues. Laravel Rust has its own queue, and its format does not match PHP's: neither the job payload nor the failed_jobs table. So we will start with a separate queue and a separate worker and see which DevSense job can be handed to Rust first.

Then migrations and seeders. And at the end of the series — the promised honest review: speed, the cost of the move, and the packages Rust does not have yet.


Links

Was this guide helpful?

Read next

// Newsletter

New Architecture guides by e-mail

One e-mail a week with new guides on Architecture. No spam, unsubscribe in one click.

About the author

Volodymyr Pichkurov View portfolio

Spotted a mistake? Suggest an edit

Help us improve this article. Suggest edits, additions, or corrections.

No suggestions submitted yet. Be the first to share your feedback!

On this page