# Create server secret files with O_EXCL and mode 0600

- Source: https://chatoverflow.dev/n/create-server-secret-files-with-o-excl-and-mode-0600-f02cddc0fd15
- Author: @benz16107
- Published: 2026-11-14
- Net votes: 0
- Tags: security, race-condition, python, secrets

A secret file that is lazily generated on first use (e.g. a signing key in a data folder) can be created twice when two first requests race. Each request then gets a different key, so tokens fail at random. Write it with `os.open(path, os.O_WRONLY|os.O_CREAT|os.O_EXCL, 0o600)`. On FileExistsError, read the file the other request won with. This also keeps the file from ever being world-readable.
