guest@websec: ~/websec/r08-where-code-goes/th — zsh — 100×40 เขียนโดย SaKKo YouTube ENTH

guest@websec ~ % man r08-where-code-goes

Controller, Model หรือ Service?

comment ส่วนใหญ่ตอนรีวิวโค้ดในแอป Rails เป็นเรื่องว่าโค้ดอยู่ที่ไหน ไม่ใช่ว่ามันทำงานหรือเปล่า นี่คือวิธีที่เราตัดสินใจ

แยกหน้าที่ให้ชัด: Controller ดูแลเรื่อง HTTP และพารามิเตอร์, Model ดูแลกฎของข้อมูลและรูปทรง JSON, Service ห่อหุ้มการคุยกับระบบภายนอกหรืออัลกอริทึมกลาง (เช่น DirectoryService, TokenService) และ Job รับผิดชอบงานช้าหรืองานที่ต้องลองซ้ำเมื่อเน็ตหลุด
ชั้นรับผิดชอบห้าม
controllerHTTP: params, ใครเรียก, record ไหนที่แตะได้, status code, ใช้ JSON รูปแบบไหนกฎทางธุรกิจ, SQL ที่ซับซ้อนกว่าการ find ธรรมดา, การเรียกระบบภายนอก
modelกฎของข้อมูล: validation, association, สถานะ, ค่าที่คำนวณได้, รูปแบบ JSON, พฤติกรรมระดับ recordอ่าน params, cookie หรือ request; เรียก service ภายนอกโดยตรง
serviceโลกภายนอก (directory ขององค์กร, JWT, payment, S3) หรือ algorithm ที่ไม่มีสถานะ ซ่อนอยู่หลัง API เล็กๆเป็นเจ้าของตาราง; รู้เรื่อง HTTP request
jobside effect ที่ช้าหรือต้อง retry: webhook, email, syncเป็นสิ่งที่ต้องเสร็จก่อน response จึงจะถูกต้อง
concernพฤติกรรมที่หลาย model หรือ controller ใช้ร่วมกัน (SoftDeletable)เป็นที่ทิ้งโค้ดของ model ตัวเดียว

หนึ่ง feature สามชั้น

การ login ของ admin ตรวจรหัสผ่านกับ directory ขององค์กร, sync ข้อมูล user, ตรวจ 2FA และตั้ง cookie นี่คือ feature เดียวกันที่เขียนไม่ดี แล้วตามด้วยแบบที่เขียนจริง:

def create
  client = SomeDirectoryGem::Client.new(host: ENV["DIRECTORY_HOST"], password: ENV["DIRECTORY_PASSWORD"])
  entry = client.login(params[:username], params[:password])      # raw client, raw errors, no timeout
  return render json: { error: "bad login" }, status: 401 unless entry
  user = User.find_or_initialize_by(username: entry["name"].downcase)
  user.email = entry["mail"]
  user.save                                                        # failure silently ignored
  if !user.is_admin then return render json: { error: "no" }, status: 401 end
  totp = ROTP::TOTP.new(user.otp_secret)
  return render json: { error: "bad otp" }, status: 401 unless totp.verify(params[:otp])
  cookies.encrypted[:bearer] = JWT.encode({ ... }, Rails.application.credentials.user_jwt_secret)
  render json: { success: true }
end
# controller: HTTP only
def create
  user = User.authenticate_and_sync!(username, password)        # model
  raise AppAuthenticationError.new("user not admin") unless user.is_admin?
  raise AppAuthenticationError.new("401: Invalid 2FA code") unless user.verify_otp(otp)
  user.reset_authentication_token
  update_cookies(:bearer, user.jwt("bearer"))                    # inherited helper
  render json: { success: true }, status: :created
end

# model: what a User is and does
def self.authenticate_and_sync!(username, password)
  entry = DirectoryService.authenticate!(username, password)    # service
  sync_from_directory!(entry)
end

def verify_otp(code) = !totp.verify(code.to_s.strip, drift_behind: 1).nil?

# service: the only code that talks to the directory
class DirectoryService
  def self.authenticate!(username, password)
    entry = client.login(username, password)                     # host, timeouts, secrets: in here only
    raise AppError.new("401: Invalid credentials") unless entry
    { username: entry["name"], email: entry["mail"], display_name: entry["display"] }   # plain hash out
  rescue SomeDirectoryGem::Error => e
    raise AppError.new("Directory unavailable")                 # our error, no internals leaked
  end
end

ทำไมต้องมี service?

  • ประตูเดียวสู่โลกภายนอก การตั้งค่าการเชื่อมต่อ, timeout, credential และการแปลง error ของ directory อยู่ใน DirectoryService ที่เดียว ถ้า directory เปลี่ยน ก็แก้ไฟล์เดียว
  • error ในภาษาของเรา error ด้านเครือข่ายจาก client gem หรือ JWT::DecodeError ถูกแปลงเป็น AppError ซึ่ง API รู้วิธี render อยู่แล้ว
  • ปลอมได้ง่ายใน test DirectoryService.stub :authenticate!, entry do … end: test ของ model และ controller รันได้โดยไม่ต้องมี directory จริง
  • ใช้ซ้ำได้ method ของ service ตัวเดียวกันรันได้จาก controller, job, bin/rails runner หรือ console
  • model ยังคงเป็นเรื่องของข้อมูล การโหลด model ไม่เคยเปิด socket

สไตล์ service ของเรา

class TokenService
  HMAC_SECRET = Rails.application.credentials.dig(:token_service_jwt_secret)   # config read once

  def self.encode(hmac_secret, payload, exp = 8.hours.from_now)                # class methods,
    raise AppError.new("HMAC secret is missing") if hmac_secret.blank?         # no instance state
    data = payload.deep_dup
    data[:exp] = exp.to_i
    data[:iat] = Time.current.to_i
    JWT.encode(data, hmac_secret, "HS256")
  end

  def self.decode(hmac_secret, token)
    raise AppError.new("HMAC secret is missing") if hmac_secret.blank?
    JWT.decode(token, hmac_secret, true, { algorithm: "HS256" }).first.with_indifferent_access   # pin the algorithm
  rescue JWT::DecodeError => e
    raise AppError.new("Invalid token: #{e.message}")                          # translate errors
  end
end

# the model offers a friendly method that uses its own secret
class ClientApplication < ApplicationRecord
  def encode_payload(payload) = TokenService.encode(api_secret, payload)
  def decode_payload(token)   = TokenService.decode(api_secret, token)
end
service คือ class ที่มี method แบบ self. และชื่อลงท้ายด้วย …Service หนึ่งตัวต่อหนึ่งระบบภายนอกหรือหนึ่ง algorithm ห้ามมี UserService ที่รวมทุกอย่างไว้ ตรรกะเกี่ยวกับข้อมูลของ user ให้เป็น method ของ User

job สำหรับ side effect

class ClientApplicationWebhookJob < ApplicationJob
  queue_as :webhooks
  retry_on StandardError, wait: :polynomially_longer, attempts: 5   # network fails; try again

  def perform(client_application_id, event_name, payload)           # pass ids, not objects
    client_app = ClientApplication.find_by(id: client_application_id)
    return if client_app.nil? || client_app.webhook_url.blank?
    token = JWT.encode({ iss: client_app.app_key, aud: client_app.webhook_url, exp: 10.minutes.from_now.to_i, event: event_name, data: payload },
                       client_app.api_secret, "HS256")
    Faraday.post(client_app.webhook_url) { |req| req.headers["Authorization"] = "Bearer #{token}"; req.body = { token:, event: event_name }.to_json }
  end
end

after_commit ของ model แค่เรียก notify_webhook ซึ่งเรียก perform_later API ตอบกลับได้ทันที ฝั่งรับที่ช้าหรือล่มจะไม่ทำให้ endpoint ของเราช้าหรือพัง

ฝึก: ควรอยู่ที่ไหน?

จัดโค้ดให้ถูกที่เลือกชั้นให้แต่ละข้อ