guest@websec: ~/websec/r10-testing/th — zsh — 100×40 เขียนโดย SaKKo YouTube ENTH

guest@websec ~ % man r10-testing

การทดสอบ API

เราทดสอบด้วย Minitest ซึ่งเป็นค่าเริ่มต้นของ Rails model test ตรวจกฎ ส่วน integration test เรียก endpoint จริงผ่าน named route helper แล้วตรวจ status และ JSON

ทดสอบกฎข้อมูลใน Model Test และทดสอบทุก API Endpoint แบบครบวงจรด้วย Integration Test ผ่าน Named Helper ให้ครบทั้งกรณีปกติ, 401 ไม่ได้ล็อกอิน, 403 ไม่มีสิทธิ์, 404 ข้ามบริษัท (IDOR) และ 400 ข้อมูลผิดรูปแบบ

โครงสร้าง

test/
├── test_helper.rb                     # loads Rails, fixtures :all, parallel workers
├── support/admin_integration_test.rb  # base class for admin endpoint tests
├── fixtures/*.yml                     # sample rows, one file per table
├── models/role_test.rb                # ActiveSupport::TestCase
├── services/token_service_test.rb
└── controllers/api/v1/admin/roles_controller_test.rb   # ActionDispatch::IntegrationTest
ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"
require_relative "support/admin_integration_test"

module ActiveSupport
  class TestCase
    parallelize(workers: :number_of_processors)
    fixtures :all
  end
end

Fixture

# test/fixtures/client_applications.yml
one:
  name: HR Portal
  app_key: key_one
  api_secret: secret_one

# test/fixtures/roles.yml
one:
  client_application: one          # refer to another fixture by label; Rails fills the uuid
  name: MyString1
  status: active

ทุก test เริ่มต้นด้วยแถวเหล่านี้ที่โหลดไว้ใน transaction ซึ่งจะถูก rollback เมื่อจบ อ่านค่าด้วย roles(:one), client_applications(:one)

model test

require "test_helper"

class RoleTest < ActiveSupport::TestCase
  def setup
    @client_app = client_applications(:one)
    @client_app.permissions.create!(name: "reports:view")
  end

  test "is invalid when permissions contain strings not in client_application.permissions" do
    role = @client_app.roles.new(name: "intruder", permissions: ["reports:view", "admin:destroy"])

    assert_not role.valid?
    assert_includes role.errors[:permissions], "contains invalid permissions: admin:destroy"
  end
end

integration test

require "test_helper"

class Api::V1::Admin::RolesControllerTest < AdminIntegrationTest
  setup do
    @admin_user = users(:one)
    @client_application = client_applications(:one)
    @role_one = roles(:one)
  end

  # ============================================================================
  # POST #create
  # ============================================================================

  test "POST #create creates a role and sets client_application_id from the URL" do
    sign_in_as_admin(@admin_user) do
      assert_difference -> { @client_application.roles.count }, 1 do
        post api_v1_admin_client_application_roles_url(client_application_id: @client_application.id),
             params: { role: { name: "Content Manager", permissions: [] } }
      end

      assert_response :created
      json_response = JSON.parse(response.body)
      created_role = Role.find(json_response["role"]["id"])
      assert_equal @client_application.id, created_role.client_application_id
      assert_equal created_role.as_admin_json.as_json, json_response["role"]
    end
  end

  test "POST #create returns 400 when the role key is missing" do
    sign_in_as_admin(@admin_user) do
      post api_v1_admin_client_application_roles_url(client_application_id: @client_application.id),
           params: { name: "Direct Param" }

      assert_response :bad_request
      assert_equal "ActionController::ParameterMissing", response.parsed_body["type"]
    end
  end
end
ส่วนทำอะไร
post …_url(…), params:, headers:ส่ง request จริงผ่าน routing, middleware, filter และ action
assert_response :createdตรวจ status (:ok, :not_found, :bad_request…)
JSON.parse(response.body) / response.parsed_bodyJSON ในรูป Hash ที่ key เป็น string
assert_difference -> { … }, 1 doพิสูจน์ว่ามีแถวถูกสร้าง (หรือไม่ถูกสร้าง ด้วย assert_no_difference)
record.reloadอ่านใหม่หลัง update เพื่อตรวจสิ่งที่ถูกบันทึก
x.as_admin_json.as_jsonเทียบกับ serializer ของ model เอง test จะได้ไม่ต้อง hard-code ทุก field

named path ใน test

integration test มี route helper ให้ใช้ ให้ใช้มันแทนการพิมพ์ URL เอง เลือก route ใดก็ได้ด้านล่างเพื่อดูการเรียก helper และบรรทัด test โดย id ที่จำเป็นถูกเติมจาก path ให้แล้ว:

route → helper → testคลิกที่แถว
  • เปลี่ยนชื่อได้อย่างปลอดภัย: เปลี่ยน path ใน routes.rb แล้วทุก test ตามไปเอง ถ้าลบ route ออก test จะล้มเหลวอย่างชัดเจนด้วย NoMethodError แทนที่จะได้ 404 เงียบๆ
  • อธิบายตัวเองได้: ส่วนที่จำเป็นเป็น keyword argument การเห็น client_application_id: ในการเรียกจึงบอกได้ว่ามีการซ้อนกัน
  • ใช้ _url ใน test (ข้อตกลงของเรา) แต่ _path ก็ใช้ได้ query param ใส่ใน helper (api_v1_admin_users_url(page: 2)) หรือใน params: สำหรับ GET

test helper ของเรา

AdminIntegrationTest

class AdminIntegrationTest < ActionDispatch::IntegrationTest
  DEFAULT_CUSTOM_HEADER = "XMLHttpRequest"

  # every write request gets X-Requested-With automatically...
  [:post, :put, :patch, :delete].each do |method_name|
    define_method(method_name) do |url, **args|
      args[:headers] ||= {}
      unless args.delete(:skip_custom_header)          # ...unless a test opts out
        args[:headers]["X-Requested-With"] ||= DEFAULT_CUSTOM_HEADER
      end
      super(url, **args)
    end
  end
end

# negative test:
post api_v1_admin_client_applications_url, params: {...}, skip_custom_header: true
assert_response :forbidden

login โดยไม่ใช้ระบบ login จริง

def sign_in_as_admin(user)
  Api::AppController.define_method(:fetch_cookies) { |_type| "mock_jwt_token" }   # any cookie
  User.stub :find_by_jwt, user do                                                 # resolves to this user
    user.stub :is_admin?, true do
      user.stub :jwt, "refreshed_mock_jwt_token" do
        yield
      end
    end
  end
ensure
  Api::AppController.remove_method(:fetch_cookies) if Api::AppController.instance_methods(false).include?(:fetch_cookies)
end

stub ของ Minitest แทนที่ method เฉพาะภายใน block ส่วน set_current_user และ check_permissions ตัวจริงยังทำงาน ตรรกะการตรวจสิทธิ์จึงถูกทดสอบจริง

test ของ client API

setup do
  @client_application = client_applications(:one)
  @headers = {
    "X-App-Key" => @client_application.app_key,
    "X-App-Secret" => JWT.encode({ sub: @client_application.app_key }, @client_application.api_secret, "HS256"),
  }
end

test "GET #index returns unauthorized when authentication headers are missing" do
  get api_v1_client_roles_url
  assert_response :unauthorized
end

การรัน test

สิ่งที่ต้องทดสอบในทุก endpoint

  • กรณีปกติ: status, JSON ตรงกับ as_*_json, ฐานข้อมูลเปลี่ยนจริง
  • validation ไม่ผ่าน → 400 พร้อม details และ assert_no_difference
  • ไม่มี key ที่ห่อข้อมูล → 400 ParameterMissing
  • ไม่พบ id → 404; id ของ parent อื่น → 404 (IDOR)
  • ไม่ได้ login → 401; login แล้วแต่ไม่มีสิทธิ์ → 403
  • เปลี่ยนสถานะไม่ได้ → 400 AASM::InvalidTransition

ลองเช็กความเข้าใจ

ทำไม controller test ของเราถึงเรียก api_v1_admin_client_application_roles_url(client_application_id: id) แทน "/api/v1/admin/client_applications/#{id}/roles"?

พิมพ์ผิดใน string จะได้ 404 เงียบๆ แต่ helper จะ raise NoMethodError หรือ UrlGenerationError

จะทดสอบว่า POST ที่ไม่มี X-Requested-With ถูกปฏิเสธได้อย่างไร โดยใช้ AdminIntegrationTest?

post ที่ถูก override จะเพิ่ม header ให้ เว้นแต่จะเลือกไม่ใช้ด้วย skip_custom_header: true