python 5 lines · 1 tab

XXE safe XML parsing with external entity resolution disabled

Kai Nakamura Apr 2026
1 tab
from defusedxml.ElementTree import fromstring

payload = request.data.decode('utf-8')
root = fromstring(payload)
invoice_number = root.findtext('invoice_number')
1 file · python Explain with highlit

XML is still a problem when parsers are left in permissive mode. I disable external entities, refuse network fetches, and prefer simpler formats unless XML is required by an external integration. Attackers love parser defaults that nobody revisited after the project started.


Related snips

ruby
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]

sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first

SQL injection prevention with unsafe and safe query patterns

sql-injection owasp database
by Kai Nakamura 3 tabs
ruby
RegistrationSchema = Dry::Schema.Params do
  required(:email).filled(:string, format?: URI::MailTo::EMAIL_REGEXP)
  required(:password).filled(:string, min_size?: 12)
  optional(:marketing_opt_in).filled(:bool)
  optional(:country).filled(:string, included_in?: %w[US CA GB AU])
end

Input validation with allowlists and explicit schemas

input-validation schemas secure-coding
by Kai Nakamura 1 tab
ruby
raw_token = SecureRandom.urlsafe_base64(32)
token_digest = Digest::SHA256.hexdigest(raw_token)

PasswordReset.create!(
  user: user,
  token_digest: token_digest,

Secure random token generation for sessions and recovery flows

randomness tokens authentication
by Kai Nakamura 1 tab
python
import psycopg

with psycopg.connect(conninfo) as connection:
    with connection.cursor() as cursor:
        cursor.execute(
            'SELECT id, email FROM users WHERE email = %s',

Parameterized queries in Python with psycopg

python sql-injection psycopg
by Kai Nakamura 1 tab
ruby
base_path = Rails.root.join('storage', 'exports').realpath
requested = base_path.join(params[:filename].to_s).cleanpath

unless requested.to_s.start_with?(base_path.to_s) && requested.file?
  raise ActionController::RoutingError, 'Not Found'
end

Preventing path traversal in download endpoints

path-traversal file-security secure-coding
by Kai Nakamura 1 tab
rust
use std::collections::HashMap;

#[derive(Debug, PartialEq)]
pub enum LogLevel {
    Info,
    Warn,

Streaming Log File Aggregation With Buffered Line Iteration in Rust

rust streaming file-io
by codesnips 3 tabs

Share this code

Here's the card — post it anywhere.

XXE safe XML parsing with external entity resolution disabled — share card
Link copied