Kai Nakamura

62 code snips · on codesnips 3 months

Security Engineer and ethical hacker with 11+ years building secure software and hardening production systems. Expert in application security, secure authentication, cloud...

nginx
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'nonce-$request_id'; style-src 'self' https://fonts.googleapis.com 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com data:; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; object-src 'none'" always;

Content Security Policy header design for modern web apps

csp http-headers browser-security
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
from defusedxml.ElementTree import fromstring

payload = request.data.decode('utf-8')
root = fromstring(payload)
invoice_number = root.findtext('invoice_number')

XXE safe XML parsing with external entity resolution disabled

xxe xml parsing
by Kai Nakamura 1 tab
ruby
require 'ipaddr'
require 'resolv'

uri = URI.parse(params[:url])
allowed_hosts = %w[images.example-cdn.com api.partner.com]

SSRF mitigation with URL allowlists and egress controls

ssrf network-security secure-coding
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
ruby
allowed_types = ['image/png', 'image/jpeg', 'application/pdf']
uploaded = params.require(:document)

raise ActionController::BadRequest, 'file too large' if uploaded.size > 10.megabytes
raise ActionController::BadRequest, 'type not allowed' unless allowed_types.include?(uploaded.content_type)

Hardening file uploads with MIME checks and storage isolation

file-uploads validation malware
by Kai Nakamura 1 tab
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
class Rack::Attack
  throttle('logins/ip', limit: 5, period: 20.seconds) do |request|
    request.ip if request.path == '/users/sign_in' && request.post?
  end

  throttle('password_reset/email', limit: 3, period: 15.minutes) do |request|

Rate limiting abusive clients with Rack::Attack

rate-limiting rack-attack brute-force
by Kai Nakamura 1 tab
javascript
import { sha256 } from './crypto.js';

const codeVerifier = crypto.randomUUID() + crypto.randomUUID();
sessionStorage.setItem('pkce_verifier', codeVerifier);

const digest = await sha256(codeVerifier);

OAuth 2.0 Authorization Code with PKCE for public clients

oauth2 oidc pkce
by Kai Nakamura 1 tab
ruby
payload = {
  sub: user.id,
  iss: 'https://auth.example.com',
  aud: 'codesnips-api',
  exp: 15.minutes.from_now.to_i,
  iat: Time.now.to_i,

JWT issuance and verification without common footguns

jwt authentication api
by Kai Nakamura 2 tabs
python
from argon2 import PasswordHasher

password_hasher = PasswordHasher(
    time_cost=3,
    memory_cost=65536,
    parallelism=4,

Password hashing with Argon2 and bcrypt migration paths

passwords argon2 bcrypt
by Kai Nakamura 1 tab
ruby
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :authenticate_user!
end

CSRF protection for Rails and JSON APIs

csrf rails api
by Kai Nakamura 2 tabs