Все статьи
-
Защита от перечисления учётных записей в формах входа, регистрации и сброса пароля
Любое различие в ответе для существующей и несуществующей учётной записи — текст сообщения, HTTP-статус, перенаправление, время — позволяет атакующему составить список действительных пользователей для атаки. Возвращайте одинаковое общее сообщение и один и тот же статус, выполняйте одинаковую работу в обеих ветвях, переносите различающую информацию в письмо и ограничивайте частоту, чтобы остаточные различия нельзя было измерять в массовом масштабе.
-
SLIs for queues and batch jobs: age of the oldest message, freshness, coverage and last success
Request-driven services measure availability and latency; queues and batch jobs need different indicators: how old the oldest unprocessed item is, what proportion of data is fresher than a threshold, what proportion of scheduled runs completed within their window, and when the job last succeeded. This methodology derives them from the pipeline SLIs in the SRE workbook.
-
Checking a served TLS certificate chain and its expiry from the command line with openssl
openssl s_client with -servername and -showcerts prints the certificates a server actually sends, which the manual describes as not a verified chain; openssl x509 reads subject, issuer, SANs and the notAfter date of each one, and openssl verify -untrusted rebuilds the chain against a trust store. Check every hostname, and IPv4 and IPv6 separately.
-
Schema conventions for a new PostgreSQL database: names, identifiers, timestamps and text
Decide a handful of conventions before the first migration: lower-case snake_case names that never need quoting, one id strategy applied everywhere, timestamptz for every point in time with created_at on every table, text instead of varchar(n), and explicit NOT NULL and foreign keys; write them down so every later migration follows them.
-
When should a team split a monolith into services?
Open question: which observable signals (deployment coupling, team boundaries, scaling needs, incident patterns) have preceded successful extractions of services from a monolith, and which extractions were later reversed?
-
Обучение со смешанной точностью: autocast, масштабирование потери и численные пределы
Смешанная точность назначает операциям подходящие форматы чисел с плавающей точкой. Autocast и масштабирование потери решают разные задачи; выигрыш требует численной проверки и измерений на целевом оборудовании.
-
Проверка результатов инструментов и найденных фрагментов моделью решений перед включением в контекст агента
Протокол размещения быстрого типизированного классификатора между агентом и его входными данными: одним запросом оценивать каждый найденный фрагмент или результат инструмента на релевантность, противоречия и скрытые инструкции, отбрасывать или помечать их в коде и сверять цитаты с источником, считая такую проверку фильтром, на который всё же может влиять враждебный текст.
-
Обобщённые функции и декораторы с TypeVar, ParamSpec и синтаксисом PEP 695
Переменная типа связывает типы параметров и возвращаемых значений. Скобки PEP 695 (def f[T](...)) заменяют ручные объявления TypeVar; верхняя граница и ограничение набором типов имеют разную семантику, а ParamSpec позволяет декоратору сохранить сигнатуру оборачиваемой функции, не стирая её до Callable[..., Any].
-
Convert timestamps to UTC at the boundary
Reject ambiguous timestamps, convert aware instants to UTC and preserve the original timezone when local scheduling semantics matter.
-
A parcel delivery time log: order, dispatch, tracking and door timestamps on one row, with the carrier's scan and the observed arrival kept apart
A proposed record-only protocol for logging each parcel's timeline as timestamps in the RFC 3339 Internet Date/Time Format with UTC offsets, taken from the order confirmation, the dispatch notice, the carrier's tracking events and the household's own note of the arrival, with the carrier, service, delivery place and each attempt recorded; the carrier's delivered scan and the observed arrival are separate columns, and no carrier comparison or delivery-time claim is made.
-
Querying the systemd journal with journalctl: unit, boot, priority, time range and JSON output
journalctl can filter the systemd journal by unit, boot, priority and time range and emit machine-readable output, but only if the journal is configured to persist across reboots. This methodology covers precise queries, persistent storage, and the size caps in journald.conf.
-
Null и отсутствующие поля в JSON API
Отсутствующее поле, поле со значением null и поле с пустым значением — три разных сообщения, и следует указать, какие из них различает API. В merge patch RFC 7396 null означает удаление, ProtoJSON считает null отсутствием значения и не выводит его, а руководство Google по JSON опускает пустые и null-свойства, если нет смысловой причины их сохранить.
-
Эмбеддинги как тип данных: векторы фиксированной длины, функция расстояния и требования к столбцу
Эмбеддинг — вектор чисел с плавающей точкой фиксированной длины, созданный конкретной моделью; он имеет смысл только с расстоянием, для которого модель обучалась, и рядом с векторами той же версии модели. При хранении нужно записывать размерность, идентификатор модели и расстояние, а запросы означают точный или приближённый поиск ближайших соседей.
-
Ловушки двоичного поиска: переполнение середины и ошибки границ на единицу
Двоичный поиск короток, но в нём общеизвестно легко ошибиться: (low + high) / 2 переполняет целые фиксированной разрядности, включённые и исключённые границы путаются, а дубликаты требуют решить, какой индекс вернуть. Используйте библиотеку или монотонный предикат с полуоткрытыми интервалами и проверяйте края.
-
Verifying Stripe webhook signatures: Stripe-Signature, timestamp tolerance and secret rotation
Stripe sends a Stripe-Signature header shaped like t=<timestamp>,v1=<hex signature>, computed as HMAC-SHA256 over the string "{timestamp}.{raw body}" keyed with the whole whsec_ endpoint secret. Stripe's libraries reject signatures whose timestamp is more than five minutes (300 seconds) old by default, and while a rolled secret is kept alive (up to 24 hours) the header carries one v1 value per active secret.
-
Checking whether a database migration rehearsal represents the target state
Assess whether an isolated migration test exercised the schema and data conditions that matter for the intended deployment, rather than only proving the migration works on an empty database.
-
Writing shell scripts that fail safely
Use set -euo pipefail, quote every expansion, prefer [[ ]] and arrays, check tools with ShellCheck, and avoid parsing ls; a script that stops on the first error is easier to trust than one that continues.
-
Identifying an unknown Linux host before changing anything on it
Before an agent or operator changes configuration on a Linux machine it did not build, it should establish the distribution, kernel, virtualization or container status, init system, package manager and mandatory access control state — each with one cheap, non-destructive command.
-
CDN cache keys and purging: what identifies a cached object and how to invalidate it
A cache stores responses under a key built at minimum from method and target URI, extended by request headers named in Vary; CDNs add scheme, host and query string and let you customise the key at the cost of sharding. Purging by URL only hits objects whose key matches exactly, so tag responses (for example Fastly's Surrogate-Key header) to purge groups reliably.
-
Checkpointing a long agent task: progress files, idempotent steps and resumption
How an agent working through a multi-step task should record progress so that a crash, a context reset or a hand-over resumes at the last completed step without repeating side effects: a plan with numbered steps, a progress file updated after each step with evidence, idempotency keys for external writes, and a resumption procedure that verifies state before continuing.
Машиночитаемо: JSON