A stale callback: menu versions and authorization when the action runs

Tie current permission, request version and an action receipt together in a MySQL/InnoDB transaction when an old Telegram button remains available.

An old invitation by a closed gate represents an action whose permission must be checked again.
An old invitation by a closed gate represents an action whose permission must be checked again.

The “Confirm request” button remains in the message. When the bot displayed it, the reader had the required permission and the request was awaiting a decision. Since then, an administrator has revoked access, another process has changed the request, or the person has opened a new menu. The old message can still be clicked. The button looks the same, but the conditions for using it have changed.

For navigation, the consequence may be a return to the current list. An application action has a higher cost: it changes stored data. Consider a fictional request to receive a book. The only action moves it from waiting to confirmed. The example involves no payment, real message, or external service. The task is to connect permission, the request's current version, and the recorded result in one controlled operation.

A button carries intent

In Telegram, a callback contains the sender, a query identifier, and the button data. The documentation warns that the current message may no longer contain a button with those data. The button's visible presence or previous availability therefore does not constitute authorization. A verified bot context and a current rule for the specific action are required. CallbackQuery description.

The server determines the bot and site context. The person's identity comes from the verified incoming message, not a user=... string inside callback_data. Delivery authenticity and permission to confirm a request answer different questions. Even a correctly received callback can represent a forbidden action.

The teaching model supports only buttons in messages that the bot sent to a chat. Inline messages require separate context binding; a missing chat ID is not replaced with a shared value here. A convenient fallback at that point would create a shared context for different situations.

A short token, a complete server record

Instead of packing permissions into the button, we use a random opaque token. On the server, it maps to the bot, site, person, chat, request, expected version, menu generation, permission generation, and expiry. Once issued, the record is not reassigned to another request.

$token = 'act:' . rtrim(
    strtr(base64_encode(random_bytes(24)), '+/', '-_'),
    '='
);

Encoding produces 36 ASCII bytes including the prefix. This fits the callback_data limit in the InlineKeyboardButton contract. The source of randomness is random_bytes. Such a token is difficult to guess, but knowing it still does not replace a permission check.

The table stores a hash of the token, not a ready-to-send string. Access to the table is also restricted: hashing does not make the record public. An ordinary error log does not need the raw token. An internal refusal reason and a processing identifier with a defined retention period are enough to investigate a problem.

The lifetime in our exercise is 300 seconds. This is our own rule, not a Telegram limit. The condition now >= expires_at means refusal, including at the exact boundary. Time for this check is read after acquiring the required row locks: merely starting a MySQL transaction does not mean that waiting has ended. Waiting must not preserve a right that has expired in the meantime.

Three versions protect different things

The request version changes with its domain state. The menu generation indicates whether a particular view is current. The permission generation changes when authority changes. One shared counter would hide the reason why an old action is no longer valid.

Value When it changes Consequence for the old button
Request version The request was edited or already confirmed Do not apply the old intent to the new state
Menu generation A new menu was issued for this context Suggest opening the current menu
Permission generation Permission was revoked or granted again Require a new button

The last row is a deliberate model choice. If access is revoked and later restored, old tokens do not come back to life. A newly authorized action receives a new record. A product can choose another policy, but it must define that policy explicitly instead of accidentally inheriting it from checking a single boolean.

Matching request identifiers on two sites do not mean the same object. Every request lookup includes the site, and the token is also checked against the bot, person, and chat. This keeps knowledge of a local number from becoming a way to cross another context's boundary.

The check must cover the transition itself

An unreliable sequence looks like this: read permission, finish that read, and later change the request separately. Permission can be revoked between those steps. Repeating the same check elsewhere merely narrows the window if the change still happens outside a shared boundary.

In the example, permissions, requests, and receipts live in one MySQL 8.4 schema using InnoDB tables; PHP connects through native PDO MySQL. The operation's boundary comes from a transaction and locking reads of current rows, not a global exclusion of other writers. The handler and permission revocation must coordinate their locks on shared rows: starting a transaction is insufficient, and an ordinary snapshot read under REPEATABLE READ does not replace a current locking read. After the checks, the handler changes the request and records the result in the same transaction.

The update also includes the expected state and version:

UPDATE demo_requests
SET state = 'confirmed', version = version + 1
WHERE site_id = ? AND request_id = ?
  AND state = 'waiting' AND version = ?;

Exactly one changed row is required to continue. The receipt and history entry are added in the same transaction. Failure at any later step must not leave a confirmed request without a record of its effect.

This makes the rule to validate permissions on every request concrete. If policy lives in another service, the local transaction alone no longer provides this boundary. A different contract is then required: for example, an authoritative decision with a version, applied atomically against that version. Adding a cached allowed=true does not solve the problem.

Two orders that must remain distinct

Consider permission revocation and a button click as two concurrent operations.

If revocation acquires the required permission-row lock first and commits, the callback performs a current locking read after waiting and sees the refusal. The request remains waiting; there is no new receipt or history entry. The old permission from when the menu was displayed is not used.

If the callback acquires the required row locks first, sees a valid permission, and commits confirmation, revocation can happen afterward. The request is already confirmed. Revocation prohibits subsequent actions but does not retrospectively cancel a past one. Cancellation requires a separate domain transition with its own conditions.

The order is determined by persisted operations, not when the button appeared or when the person touched the screen. A callback's time in a queue does not reserve its previous permissions either. That is why the check must happen during execution, when the command reaches the authoritative store.

Clicking again does not create another effect

The receipt key includes the bot and the callback query identifier. A fingerprint of the bound intent is stored alongside it. Repeating the same key with a different button creates a conflict instead of transferring the previous success to another request.

There is a second boundary: one token does not receive two successful receipts. A person can click the button again, and the new click will have a different query key. Checking only the delivery key would miss that situation. The token receipt and expected request version together protect the specific intent and domain transition.

Even a replay first undergoes current context, expiry, and permission checks. After access is revoked, the response does not disclose the stored result to another person or someone who is no longer authorized. The previous effect remains in the database: a neutral refusal on replay does not mean it has been undone.

If commit acknowledgement is lost, the action cannot be declared either successful or definitely unexecuted. The example returns an uncertain result. Recovery reads the stored state or retries the same intent with the same key; creating a new token “to be safe” can conceal the first effect.

The user response must state the known result

For a button that is outdated, belongs to someone else, or is forbidden, this message is enough: “Action unavailable. Open the current menu.” There is no need to explain whether someone else's request exists or who can access it. Internal reasons may differ while the external wording stays the same.

Acknowledging a callback ends Telegram's waiting indicator; it is not a receipt from our database. Success text is therefore prepared only after a known commit. If a response must be sent earlier, it can report only that processing is underway. The teaching code returns a response plan, but it does not call the Telegram API or establish that the text was delivered.

How to reproduce the access boundary

Reproducing the PHP/MySQL example requires MySQL 8.4 and the pdo_mysql extension. Tests use the shared App\Infrastructure\MysqlLab helper in the guarded disposable MySQL fixture; commands requiring the database run through bash fixtures/mysql_labs/run.sh. The helper migrator explicitly creates the schema before the business transaction begins, while assertions and the handler use DML connections without CREATE, ALTER, or DROP. This is neither an automatic data copy from the old SQLite database nor an atomic schema upgrade: MySQL DDL can cause an implicit commit.

The two orders require separate native connections sharing the same schema. The invariants are these: if revocation completes first, the request remains waiting, version 1, without receipts or history; if confirmation completes first, it is confirmed, version 2, with one receipt and one history entry, and later revocation does not erase that effect. Separate checks cover context, the expiry boundary, replay, key conflicts, and rejection of malformed UTF-8 before SQL. MySQL errors 1205 and 1213 are not authorization refusals: ActionStore::confirm() catches Throwable, attempts rollback if the transaction it started is still active, and returns storage_unknown rather than propagating the native error to the caller. Successful rollback is not guaranteed. There is no automatic retry: recovery retries the operation with the same token and callback query key or reconciles persisted state. The InnoDB error-handling documentation distinguishes their consequences; the old SQLite waiting measurements do not apply here.

This model has a clear boundary: one MySQL schema with InnoDB tables and a short state change. It does not guarantee a single external delivery, run a real bot, or model every possible access policy. Its useful property is a specific place where current permission meets current state. An old message may remain for a long time; the action decision is made anew at that point.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/CallbackActionLab
  1. Symfony Core Editing a published article: how to avoid losing another edit
  2. Distribution One webhook for several bots: choosing the right context
  3. Distribution Repeated Telegram updates: avoiding a repeated local action

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article