چکلیست سختسازی (Hardening) امنیت API: ورودی، هدرهای خروجی، پردازش، پایش و CI/CD
"Define what the application accepts and reject values outside those rules. Do not try to recognize every malicious string." — OWASP Cheat Sheet Series, Input Validation Cheat Sheet
خلاصه: API سختشده در مرزهایش رفتار قابل پیشبینی دارد: فقط متد، نوع رسانه، اندازه و ساختاری را میپذیرد که برای آن طراحی شده است. بقیهٔ درخواستها کد وضعیت درست و قالب خطای یکسان میگیرند؛ همهٔ پاسخها هدرهای خروجی یکسان دارند. نه رد پشته (Stack trace) بیرون میرود نه راز؛ کلاینت کند کنار گذاشته میشود و هر درخواست یک خط لاگ با شناسهٔ درخواست (Request id) و دادههای حساس پوشاندهشده دارد. وابستگی آسیبپذیر، راز لورفته یا پرچم debug اشتباه هم جلوی انتشار را میگیرد. این فصل چکلیست «API Security Best Practices» از roadmap.sh را به زنجیرهٔ میانافزار (Middleware) قابل اجرای Go و معادل Laravel 13 تبدیل میکند. هر رفتار تست دارد و خروجی واقعی اسکریپت ممیزی curl روی سرور Go در آزمایشگاه آمده است. تمرکز: گروههای ورودی، پردازش، خروجی، پایش و CI/CD را به کنترل اجرایی تبدیل میکنیم؛ احراز هویت (Authentication)، JWT، کنترل دسترسی (Access Control) و OAuth به فصل تخصصی ارجاع دارند. اعتبارسنجی با فهرست مجاز (Allow-list validation)، قرارداد مبتنی بر طرحواره (Schema-first) و سقف عمق JSON مشخص میکنند چه چیزی وارد برنامه شود. مذاکرهٔ محتوا (Content negotiation)، هدر Allow و کدهای 405، 406، 413 و 415 مرز HTTP را روشن میکنند؛ http.MaxBytesReader سقف بدنه را هنگام خواندن اعمال میکند. هدرهای امنیتی، حذف اثرانگشت (Fingerprinting)، قالب جزئیات خطا (Problem Details) مطابق RFC 9457 و خاموشبودن APP_DEBUG خروجی را کنترل میکنند. مهلت زمانی (Timeout)، Slowloris، پیشدرخواست (Preflight) و اعتبارنامههای CORS نیز بررسی میشوند. شناسهٔ همبستگی (Correlation id)، پوشاندن داده (Redaction)، اطلاعات هویتی شخصی (PII)، ثبت متمرکز لاگ و هشداردهی در کنار IDS/IPS و WAF قرار میگیرند. در لبهٔ شبکه، Kong، Envoy، APISIX و Nginx و اعتبارسنجی OpenAPI را داریم؛ در CI، اسکن وابستگی، SAST، DAST و اسکن رازها با govulncheck، composer audit و قواعد بازبینی کد. راهبرد بازگشت (Rollback)، استقرار Blue-green، پرچم قابلیت (Feature flag) و فهرست API حلقه را کامل میکنند. هدف یادگیری: اسکریپت ممیزی curl را روی یک API اجرا کنید؛ هر خط FAIL را به یک بند چکلیست وصل کنید و در لایهٔ درست ببندید: Middlewareهای Go یعنی harden.SecurityHeaders، AllowMethods، JSONOnly، LimitBody، DecodeJSON، Recover، RequestID، AccessLog، CORS و NewServer؛ تنظیمها و Middlewareهای Laravel یعنی SecurityHeaders، EnforceJsonApi، config/cors.php، APP_DEBUG=false و tap پوشانندهٔ Monolog؛ دستور gateway مثل client_max_body_size در Nginx، request-size-limiting در Kong، request_headers_timeout در Envoy و request-validation در APISIX؛ یا Gate در CI با govulncheck، composer audit، gitleaks و ZAP baseline.
موضوع این فصل Hardening است: کنترلهای مشترکی که هر endpoint، مستقل از کارش، دریافت میکند. دستهبندی خطرهای API، شامل BOLA، BOPLA، BFLA، مصرف نامحدود منابع، جریان کسبوکار، فهرست و مصرف ناامن، در OWASP API Security Top 10 آمده است. آسیبپذیری داخل handler، شامل injection، XSS، CSRF، SSRF، XXE و آپلود، در OWASP Top 10 است. کلید API، امضای HMAC درخواست و امضای webhook در کلیدهای API، امضای درخواست و webhook قرار دارند. گذرواژه، MFA و نشست در احراز هویت، توکن در JWT عمیق، دسترسی تفویضشده در OAuth 2.0 و OIDC، و کنترل نرخ در محدودیت نرخ توضیح داده شدهاند. برای TLS به TLS در عمل و تکامل HTTP، برای فرایند تحویل و رخداد به Secure SDLC، و برای سازوکار Go به Middlewareها و سرور و کلاینت HTTP در Go بروید.
نقشهٔ صفحه
| اگر دنبال این هستید | بروید به |
|---|---|
| گروههای چکلیست، کدها و هدرها در سه جدول | همهچیز در یک دقیقه |
| چرا علاوه بر کد امن، چکلیست لازم است | چرا وجود دارد |
| roadmap.sh، برگههای OWASP و RFC کدها | از کجا آمده |
| تمام ۵۰ بند، با پیادهسازی یا پیوند | چکلیست بندبهبند |
| فهرست مجاز، Schema-first و عمق JSON | اعتبارسنجی ورودی |
پاسخ 405 و هدر Allow، متد TRACE و override | فهرست مجاز متد |
پاسخهای 415 و 406، هدرهای Content-Type و Accept | اعتبارسنجی نوع محتوا |
پاسخ 413، MaxBytesReader و بدنهٔ chunked | سقف بدنه |
| ارسال توکن در هدر بهجای URL | هدر Authorization |
| کاربرد nosniff، frame options، CSP، HSTS، Referrer-Policy و no-store | هدرهای امنیتی |
حذف Server، X-Powered-By و اعلان نسخه | اثرانگشت |
| RFC 9457، کد درست و حذف Stack trace | پاسخ خطا |
| فهرست مجاز پاسخ، شمارهٔ کارت و فیلد داخلی | حذف دادهٔ حساس از پاسخ |
خاموشکردن APP_DEBUG، pprof و صفحهٔ debug | خاموشبودن debug |
| مقابله با Slowloris و Timeout خواندن، نوشتن، بیکاری و handler | Timeoutها |
Preflight، Access-Control-Allow-Credentials و Vary: Origin | CORS |
| شناسهٔ درخواست و همبستگی، Redaction و PII | ثبت لاگ |
| لاگ متمرکز، هشدار، IDS/IPS و WAF | پایش |
| Kong، Envoy، APISIX، Nginx و اعتبارسنجی OpenAPI | درگاه API |
| کنترل با SAST، DAST، SCA، اسکن راز و بازبینی | Gateهای CI/CD |
| بازگشت با Blue-green و Feature flag | راهبرد بازگشت |
| ثبت و تعیین مسئول تمام endpointها | فهرست API |
| XML entity، آپلود، SSRF، کار async و UUID | پردازش در فصلهای تخصصی |
| ترتیب Middleware، کدها، تنظیمها و پیشفرضها | سازوکار |
| کد اجرایی | Go، Laravel، لبهٔ شبکه |
| بستن یافتههای آزمون نفوذ | حل مسئلههای کلاسیک |
| انتخاب لایهٔ مناسب هر کنترل | انتخاب |
| از مونولیت تا سیستم توزیعشده | در معماری |
| تمرین عملی با خروجی واقعی | آزمایشگاه |
همهچیز در یک دقیقه
گروههای چکلیست. roadmap.sh پنجاه بند را در نه گروه قرار میدهد. چهار گروه Input، Processing، Output و Monitoring کنترل مشترک کد هستند و این فصل آنها را پیاده میکند. CI & CD و Access Control بین این فصل و لبه تقسیم میشوند؛ Authentication، JWT و OAuth فصلهای خودشان را دارند.
| گروه | در برابر چه چیزی محافظت میکند | بندهای معمول | محل توضیح |
|---|---|---|---|
| Input | درخواست خارج از طراحی API | فهرست مجاز متد، اعتبارسنجی Content-Type و ورودی، هدر Authorization، gateway | ورودی، متد، مذاکره، سقف بدنه |
| Processing | کار پرهزینه، ناامن یا افشاکننده | Authentication روی endpoint، حذف شناسهٔ شخصی از URL، خاموشی XML entity expansion، آپلود از CDN، کار سنگین async، debug خاموش | Debug، Timeout، پیوندها |
| Output | برداشت اشتباه مرورگر و نشت داده | nosniff، X-Frame-Options: deny، Content-Security-Policy: default-src 'none'، حذف هدر اثرانگشت، نوع محتوای اجباری، حذف راز، کد درست | هدرها، اثرانگشت، خطا، دادهٔ خروجی |
| Monitoring | حملهای که کسی نمیبیند | لاگ متمرکز، agent، هشدار، نبود دادهٔ حساس در لاگ، IDS/IPS | لاگ، پایش |
| CI & CD | انتشار حفرهٔ شناختهشده | تست، بازبینی بدون تأیید خود، تحلیل امنیت، بررسی وابستگی، Rollback | CI/CD، بازگشت |
| Access Control | دسترسی ناخواسته در شبکه | کنترل نرخ، HTTPS و HSTS، حذف فهرست دایرکتوری، IP مجاز برای API خصوصی | HSTS، gateway، پیوندها |
| Authentication | ورود ضعیف | Authentication استاندارد، رمزنگاری آماده، سقف تلاش و jail، رمزگذاری دادهٔ حساس | فصلهای تخصصی |
| JWT | توکن جعلی یا حجیم | راز قوی، الگوریتم از backend، TTL کوتاه، نبود راز در payload | فصلهای تخصصی |
| OAuth | سرقت code و token | بررسی سروری redirect_uri، code flow، state و scope | فصلهای تخصصی |
کدهایی که API سختشده واقعاً میفرستد. همه در قالب application/problem+json مطابق RFC 9457، همراه هدر امنیتی و شناسهٔ درخواست ارسال میشوند.
| کد | نام در RFC 9110 | زمان ارسال | فرستنده در زنجیرهٔ Go |
|---|---|---|---|
| 400 | Bad Request | JSON خراب، فیلد ناشناخته، عمق زیاد، دادهٔ اضافی انتهای بدنه | DecodeJSON |
| 401 | Unauthorized | اعتبارنامهٔ نامعتبر یا غایب | Middleware احراز هویت در فصل مرتبط |
| 403 | Forbidden | هویت معتبر ولی فاقد مجوز؛ Preflight از origin بیگانه | لایهٔ policy؛ CORS |
| 404 | Not Found | Route ناشناخته یا شناسهٔ خارج از فهرست مجاز | ServeMux، handler |
| 405 | Method Not Allowed | متد خارج از فهرست یا Route؛ همواره با Allow | AllowMethods، ServeMux |
| 406 | Not Acceptable | Accept تمام نوعهای تولیدی API را رد میکند | JSONOnly |
| 413 | Content Too Large | بدنه بزرگتر از سقف، چه اعلامشده چه جریانیافته | LimitBody، DecodeJSON |
| 415 | Unsupported Media Type | بدنه دارد ولی application/json نیست | JSONOnly |
| 422 | Unprocessable Content | JSON درست با مقدارهای نامعتبر | اعتبارسنجی handler |
| 429 | Too Many Requests | عبور از سقف نرخ | Gateway یا limiter در فصل مرتبط |
| 500 | Internal Server Error | Panic یا خطای غیرمنتظره؛ بدون Stack trace | Recover |
| 503 | Service Unavailable | پایان Timeout handler | http.TimeoutHandler |
هدر خروجی API با JSON. مقدارها از برگههای REST Security و HTTP Headers در OWASP هستند؛ Middlewareهای Go و Laravel همینها را میفرستند.
| هدر | مقدار | چه چیزی را متوقف میکند |
|---|---|---|
X-Content-Type-Options | nosniff | حدس مرورگر که JSON را HTML یا script بداند |
Content-Security-Policy | default-src 'none'; frame-ancestors 'none' | script، style، image یا framing هنگام رندر احتمالی پاسخ |
X-Frame-Options | DENY | Framing در مرورگر قدیمی فاقد frame-ancestors |
Cache-Control | no-store | نگهداشتن دادهٔ شخصی در cache مشترک و دکمهٔ بازگشت |
Referrer-Policy | no-referrer | نشت URL به شخص ثالث |
Strict-Transport-Security | max-age=63072000; includeSubDomains فقط HTTPS | SSL stripping در مراجعهٔ بعد |
Content-Type | application/json یا application/problem+json، تعیینشده توسط سرور | ابهام MIME؛ هرگز از Accept کپی نمیشود |
Server، X-Powered-By | حذفشده | تشخیص نسخه از اثرانگشت |
چرا وجود دارد
بیشتر نفوذهای API ترفند پیچیده نمیخواهند. یک endpoint کافی است که متدی تستنشده را بپذیرد، بدنهاش سقف نداشته باشد، debug را روشن گذاشته باشد، هدر لازم را نفرستد یا توکن را در لاگ نگه دارد. همهٔ اینها پیشفرضاند: net/http نه Timeout دارد نه سقف بدنه؛ PHP بدون تنظیم مخالف X-Powered-By اضافه میکند؛ Nginx نسخه را چاپ میکند؛ config/cors.php منتشرشدهٔ Laravel با 'allowed_origins' => ['*'] شروع میشود؛ افزونهٔ تازهٔ CORS در Kong هم بدون تعیین origin همه را میپذیرد. پیشفرض برای «بار اول کار کند» انتخاب شده، نه برای دوام در اینترنت. این کنترلهای مشترک باید در یک زنجیرهٔ Middleware، یک پیکربندی gateway و یک Pipeline باشند؛ تکرارشان در تکتک handlerها احتمال فراموشی را بالا میبرد.
| انتخاب | سود | هزینه |
|---|---|---|
| پذیرش همه و رد فقط بدهای شناختهشده؛ فهرست ممنوع (Denylist) | روز اول چیزی خراب نمیشود | هر ترفند جدید راه دورزدن جدید است؛ encoding فهرست را دور میزند |
| پذیرش فقط مطابق قرارداد؛ فهرست مجاز (Allow-list) | ورودی ناشناخته به کد کسبوکار نمیرسد | قرارداد باید نوشته شود: OpenAPI، DTO و قواعد |
| کنترل در هر handler | محلی و صریح | در endpoint شمارهٔ 40 فراموش میشود؛ کدها ناسازگارند |
| کنترل در یک زنجیرهٔ Middleware | همهٔ Routeها پوشش میگیرند؛ یکبار تست کافی است | ترتیب مهم است؛ ترتیب غلط لایه را بیصدا بیاثر میکند |
| کنترل فقط در gateway | یک محل برای سرویسهای متعدد | فراخوان داخلی از gateway عبور نمیکند؛ برنامه هنوز به ورودی اعتماد دارد |
| Gateway و برنامه؛ دفاع در عمق (Defence in depth) | باگ یک لایه را دیگری میگیرد | دو پیکربندی باید هماهنگ بمانند |
| خطای پرجزئیات | debug سریع | Stack trace، SQL و مسیر فایل در اختیار مهاجم |
| خطای عمومی با شناسهٔ درخواست | نشت ندارد؛ پشتیبانی خط لاگ را پیدا میکند | Pipeline لاگ باید شناسه را نگه دارد و index کند |
تصویری از زندگی روزمره. دبیرخانهٔ شرکت از هر کسی نامه میگیرد، اما فقط پاکت خطاب به واحد موجود، در قالب پشتیبانیشده و زیر سقف وزن را میپذیرد: فهرست Route، نوع رسانه و اندازهٔ بدنه. در را برای کسی که یک ساعت صرف تحویل یک نامه میکند باز نمیگذارد: Timeout. نامهٔ خروجی پاکت و مهر یکسان دارد: هدرها. یادداشت داخلی به آن منگنه نمیشود: حذف دادهٔ حساس. نامهٔ ردشده با برگهٔ استاندارد و شمارهٔ پیگیری برمیگردد: Problem Details و Request id؛ نقشهٔ گاوصندوق همراهش نیست: Stack trace. دفتر ثبت، شمارهٔ پیگیری، فرستنده و نتیجه را نگه میدارد، نه محتوای نامهٔ محرمانه: Redaction. در ادامه به همین دبیرخانه برمیگردیم.
سه بدفهمی از همین ابتدا
- «هدر امنیتی برای وبسایت است؛ API من JSON میدهد.» OWASP REST میگوید: "if the API is only consumed by non-browser clients (e.g. mobile apps, server-to-server calls, command-line tools), most of these headers will have no effect since they are directives for browsers." اما API قابل دسترسی از مرورگر، از SPA تا بازکردن URL توسط توسعهدهنده یا صفحهٔ مهاجم، در معرض framing، sniffing یا cache است. هزینهٔ هدر ناچیز است؛ روی تمام پاسخها، از جمله خطا، بفرستید.
- «Framework ورودی را اعتبارسنجی میکند.» Framework ورودی را parse میکند؛ نمیداند
quantityباید بین ۱ و ۱۰۰ باشد،skuچه قالبی دارد یاroleاصلاً نباید پذیرفته شود. Input Validation Cheat Sheet: "Converting text to an integer only establishes a type: it does not establish an acceptable quantity." - «Gateway همهاش را انجام میدهد.» Gateway دیوار اول خوبی برای اندازه، نرخ، TLS و Schema است؛ اما فراخوان داخلی، health check اشتباه یا ingress دوم آن را دور میزند. تنها برنامه میداند کدام فیلد حساس است. این فصل همهٔ کنترلها را در برنامه نشان میدهد و در لبه کنترلهای کمهزینه را تکرار میکند.
از کجا آمده
- roadmap.sh «API Security Best Practices» طبق front matter در ۲۰۲۳-۰۲-۲۱ منتشر شده و خود را "Detailed list of best practices to make your APIs secure" معرفی میکند: پنجاه بند در نه گروه. صفحهٔ roadmap.sh سمت کلاینت رندر میشود؛ دادهٔ این فصل از repo به نام
developer-roadmap، پوشهٔsrc/data/best-practices/api-security/گرفته شده است:api-security.jsonبرای عنوان و گروه و یک فایل Markdown برای متن هر بند. commit برابر2571a7cاست، چون پوشه بعداً از شاخهٔ پیشفرض repo، که اکنونnilbuild/developer-roadmapاست، حذف شده است. عبارت بندهای جدول بعد نقلقول مستقیم همان داده است. - OWASP Cheat Sheet Series همراه دقیق چکلیست است: REST Security برای فهرست متد و 405، نوع محتوا و 415/406، اندازه و 413، جدول هدر API، خطای عمومی، CORS، دادهٔ حساس در URL و جدول کدها؛ همچنین HTTP Headers، Input Validation، Error Handling، Logging، Transport Layer Security، Content Security Policy و HTML5 Security برای CORS. در اختلافها هر دو کنترل را داریم: roadmap میگوید
X-Frame-Options: deny؛ OWASP آن را "Legacy header superseded by Content-Security-Policy: frame-ancestors 'none'" میداند، اما برای مرورگر قدیمی همچنان توصیه میکند. - کد وضعیت در RFC 9110، HTTP Semantics سال ۲۰۲۲، تعریف شده است. نام 413 از "Payload Too Large" در RFC 7231 به "Content Too Large" و نام 422 به "Unprocessable Content" تغییر کرده است. دربارهٔ 405 میگوید: "The origin server MUST generate an Allow header field". تابع
http.StatusText(413)در Go هنوز "Request Entity Too Large" از RFC 2616 را برمیگرداند؛ به همین علت خط وضعیت آزمایشگاه باtitleخطا فرق دارد. - جزئیات خطا (Problem Details) در RFC ۷۸۰۷ سال ۲۰۱۶ با
application/problem+jsonتعریف شد. RFC 9457 سال ۲۰۲۳ میگوید "obsoletes RFC 7807" و همان اعضا را نگه میدارد:type،title،status،detail،instanceو extensionها. - HSTS در RFC ۶۷۹۷ سال ۲۰۱۲ است. بخش 7.2 دلیل بررسی TLS در Middleware است: "An HSTS Host MUST NOT include the STS header field in HTTP responses conveyed over non-secure transport."
- Go از نسخهٔ 1.0 تابع
http.MaxBytesReaderدارد؛ در 1.19 خطای دارای نوع*http.MaxBytesErrorاضافه شد: "will now return the defined error type MaxBytesError when its read limit is exceeded". Go 1.22 الگوی متد را بهServeMuxافزود: "Registering a handler with a method, like "POST /items/create", restricts invocations of the handler to requests with the given method"؛ متد اشتباه نیز 405 همراهAllowمیگیرد. ماژولgo 1.24را هدف میگیرد و با Go 1.27.4 تست شده است. - OWASP API Security Top ۱۰ سال ۲۰۲۳ خطرهای کاهشیافته با این کنترلها را نام میبرد: API4:2023 Unrestricted Resource Consumption برای اندازه و Timeout، API8:2023 Security Misconfiguration برای هدر، CORS، debug و خطای پرجزئیات، و API9:2023 Improper Inventory Management. شرح خود خطرها در OWASP API Security Top 10 است.
چکلیست، بندبهبند
هر بند roadmap.sh با گروه و محل پیادهسازی یا فصل تخصصی آمده است. در فصلهای تخصصی و بندهای پردازش برای هرکدام یک جمله داریم. سطر «پیوند» عمدی است؛ آن فصلها از ظرفیت یک چکلیست عمیقتر میشوند. متن ستون بند، نقلقول مستقیم roadmap.sh است.
| گروه | بند roadmap.sh | اینجا یا پیوند | محل |
|---|---|---|---|
| Authentication | Avoid 'Basic Authentication', use standard (e.g. JWT) | پیوند | Authentication |
| Authentication | Do not reinvent the wheel in authentication mechanisms | پیوند | Authentication |
| Authentication | Use 'Max Retry' and jail features in Login | پیوند محدودیت نرخ | Rate limiting |
| Authentication | Use encryption on all sensitive data | پیوند | Cryptography in practice |
| JWT | Use good JWT Secret to make brute force attacks difficult | پیوند | JWT deep dive |
| JWT | Do not extract the algorithm from the header, use backend | پیوند | JWT deep dive |
| JWT | Make token expiration (TTL, RTTL) as short as possible | پیوند | JWT deep dive |
| JWT | Avoid storing sensitive data in JWT payload | پیوند | JWT deep dive |
| JWT | Keep the payload small to reduce the size of the JWT | پیوند | JWT deep dive |
| Access Control | Limit requests (throttling) to avoid DDoS / Brute Force | پیوند محدودیت نرخ | Rate limiting, DDoS |
| Access Control | Use HTTPS on server side and secure ciphers | پیوند | TLS in practice |
| Access Control | Use HSTS header with SSL to avoid SSL Strip attacks | اینجا | Security headers |
| Access Control | Turn off directory listings | اینجا در لبه | Fingerprinting, At the edge |
| Access Control | Private APIs to be only accessible from safe listed IPs | اینجا در لبه و پیوند | At the edge, API keys and IP allow-lists |
| OAuth | Always validate redirect_uri on server-side | پیوند | OAuth 2.0 and OIDC |
| OAuth | Avoid response_type=token and try to exchange for code | پیوند | OAuth 2.0 and OIDC |
| OAuth | Use state parameter to prevent CSRF attacks | پیوند | OAuth 2.0 and OIDC |
| OAuth | Have default scope, and validate scope for each application | پیوند | OAuth 2.0 and OIDC |
| Input | Use proper HTTP methods for the operation | اینجا | HTTP method allow-list |
| Input | Validate content-type on request header | اینجا | Content-Type and Accept |
| Input | Validate user input to avoid common vulnerabilities | اینجا | Input validation |
| Input | Use standard Authorization header for sensitive data | اینجا | Authorization header |
| Input | Use only server-side encryption | پیوند | Cryptography in practice |
| Input | Use an API Gateway for caching, Rate Limit policies etc | اینجا در لبه | API gateway |
| Processing | Check if all the endpoints are protected behind authentication | پیوند؛ روش توضیح داده شده، در این ماژول پیاده نشده | API inventory, OWASP API Security Top 10 |
| Processing | Avoid user's personal ID in the resource URLs | پیوند | OWASP API Top 10 (BOLA) |
| Processing | Prefer using UUID over auto-increment IDs | پیوند | Processing items |
| Processing | Disable entity parsing if you are parsing XML to avoid XXE attacks | پیوند | OWASP Top 10 (XXE) |
| Processing | Disable entity expansion if using XML, YML or any other language | پیوند | OWASP Top 10 (XXE) |
| Processing | Use CDN for file uploads | پیوند Hardening آپلود | File uploads, S3 and CDN |
| Processing | Avoid HTTP blocking if you are using huge amount of data | Timeout اینجا و پیوند | Timeouts, Processing items |
| Processing | Make sure to turn the debug mode off in production | اینجا | Debug mode off |
| Processing | Use non-executable stacks when available | پیوند | Processing items |
| Output | Send X-Content-Type-Options: nosniff header | اینجا | Security headers |
| Output | Send X-Frame-Options: deny header | اینجا | Security headers |
| Output | Send Content-Security-Policy: default-src 'none' header | اینجا | Security headers |
| Output | Remove fingerprinting headers (i.e. x-powered-by etc) | اینجا | Fingerprinting |
| Output | Force content-type for your response | اینجا | Content-Type and Accept |
| Output | Avoid returning sensitive data (credentials, sec. tokens etc) | اینجا | No sensitive data in responses |
| Output | Return proper response codes as per the operation | اینجا | Error responses |
| CI & CD | Audit your design and implementation with unit/integration tests | اینجا | Go tests, Lab |
| CI & CD | Use a code review process and disregard self-approval | اینجا | CI/CD gates |
| CI & CD | Continuously run security analysis on your code | اینجا و پیوند | CI/CD gates, Secure SDLC |
| CI & CD | Check your dependencies for known vulnerabilities | اینجا | CI/CD gates |
| CI & CD | Design a rollback solution for deployments | اینجا و پیوند | Rollback strategy |
| Monitoring | Use centralized logins for all services and components | لاگ اینجا و پیوند SSO | Monitoring, OAuth 2.0, OIDC and SSO |
| Monitoring | Use agents to monitor all requests, responses and errors | اینجا | Logging |
| Monitoring | Use alerts for SMS, Slack, Email, Kibana, Cloudwatch, etc. | اینجا | Monitoring |
| Monitoring | Ensure that you aren't logging any sensitive data | اینجا | Logging |
| Monitoring | Use an IDS and/or IPS system to monitor everything | مفهوم اینجا و پیوند | Monitoring, DDoS and network security |
دو نکتهٔ واژگانی: "Use centralized logins" در گروه Monitoring است و صفحهٔ جزئیاتش دو موضوع دارد: ورود یکپارچه (SSO) بین سرویسها با عبارت "set up a single sign-on (SSO) system ... using protocols like OAuth or SAML" که در OAuth 2.0، OIDC و SSO است؛ و "centralized logging tools like ELK stack, Splunk, or Graylog" که در پایش پیاده میشود. «پیوند محافظ SSRF» هم به این معناست که چکلیست بند SSRF ندارد، ولی هر API واکشیکنندهٔ URL به محافظ هنگام اتصال در OWASP Top 10، بخش SSRF و API7:2023 در OWASP API Security Top 10 نیاز دارد.
کاتالوگ مفاهیم
اعتبارسنجی ورودی: فهرست مجاز، Schema-first، عمق و طرحوارهٔ JSON حیاتی
به زبان ساده: شکل دقیق درخواست معتبر را بنویسید: فیلد، نوع، طول، بازه و قالب. هرچه بیرون آن است پیش از اجرای کد کسبوکار رد شود. دنبال فهرستکردن تمام چیزهای بد نباشید.
بدفهمی رایج: «اعتبارسنجی (Validation) برای جلوگیری از SQL injection است.» تزریق در محل مصرف داده متوقف میشود: placeholder و encoding؛ OWASP Top 10. کار Validation هم محدودتر است هم گستردهتر: درخواست را داخل قرارداد نگه میدارد تا کد کسبوکار فقط مقدار مورد انتظار ببیند و شکست کمهزینه باشد. هشدار OWASP: "Removing suspicious characters can change meaning and still does not provide query parameterization or output encoding."
تعریف: اعتبارسنجی با فهرست مجاز (Allow-list validation) طبق OWASP، "Define what the application accepts and reject values outside those rules"، هر فیلد را با قاعدهٔ مثبت میسنجد: نوع، طول، بازه، قالب با regex مهارشده به \A…\z، مقدارهای شمارشی و مجموعهٔ نام فیلد مجاز. قرارداد مبتنی بر طرحواره (Schema-first) یعنی قرارداد، سند OpenAPI 3.x یا JSON Schema یا protobuf، پیش از کد نوشته شود و gateway و برنامه هر دو آن را اعتبارسنجی کنند. اعتبارسنجی عمق و طرحوارهٔ JSON (JSON depth and schema validation) محدودیت parser را اضافه میکند. OWASP: "Apply request size limits before buffering or parsing input, and configure parser limits such as maximum nesting depth"؛ زیرا "A schema check after parsing cannot protect a parser that has already exhausted resources." ترتیب اجرا: سقف اندازه ← parse با سقف عمق ← رد فیلد ناشناخته و دادهٔ انتهایی ← قواعد فیلد ← قواعد کسبوکار.
1 POST /v1/orders Content-Type: application/json Content-Length: 61
2 LimitBody 64 KiB cap -> 413 if larger
3 checkDepth tokens scanned, depth <= 16 -> 400 "JSON nested too deeply"
4 Decode DisallowUnknownFields -> 400 unknown field "price"
5 Decode one value, no trailing data -> 400 "body must contain a single JSON value"
6 validate() sku ^[A-Z0-9-]{3,32}$, 1 <= quantity <= 100, currency in {EUR, USD}
7 -> 422 with errors{sku, quantity, currency}
8 handler business rules (stock, price) on values it can trustسناریوی واقعی: کلاینت موبایل "quantity": -5 میفرستد و مبلغ سفارش به بازپرداخت بدل میشود؛ بدنهٔ JSON با صد هزار آرایهٔ تودرتو CPU را در parser بازگشتی مشغول میکند؛ mapper سهلگیر "price": 0 اضافی را میپذیرد، یعنی انتساب انبوه (Mass assignment) در OWASP Top 10؛ یا sku دارای newline وارد CSV میشود و import انبار را خراب میکند.
| لایه | ابزار فهرست مجاز | فیلد ناشناخته | عمق / اندازه |
|---|---|---|---|
Go encoding/json | نوع struct و validate() خودتان | Decoder.DisallowUnknownFields() | سقف اندازه ندارد؛ maxNestingDepth = 10000 داخلی؛ افزودن MaxBytesReader و پیمایش عمق token |
| کتابخانههای Go | tagهای go-playground/validator، santhosh-tekuri/jsonschema، Validation درخواست با kin-openapi | Schema با additionalProperties: false | maxLength و maxItems در Schema |
| Laravel | Form Request با rules()، Rule::in، regex، between و $request->validated() | validated() بیصدا حذف میکند؛ با hook به نام after() رد کنید | post_max_size، ValidatePostSize و سقف وبسرور |
| OpenAPI در لبه | Kong OAS Validation نسخهٔ Enterprise، request-validation در APISIX، Envoy با validator خارجی | additionalProperties: false | client-control و max_body_size در APISIX؛ request-size-limiting در Kong |
اصلاح / روش استفاده: در Go، DecodeJSON و متد validate() برگردانندهٔ خطاهای فیلد؛ در Laravel، StoreOrderRequest با hook به نام after() برای رد کلید ناشناخته؛ در لبه، request-validation در APISIX با همان JSON Schema. شکست Validation را در سطح info با Request id لاگ کنید؛ برگهٔ REST میگوید: "Assume that someone who is performing hundreds of failed input validations per second is up to no good."
فهرست مجاز متد HTTP و 405 Method Not Allowed حیاتی
به زبان ساده: هر Route فقط متدهایی را پاسخ میدهد که برایشان ساخته شده است. بقیه، حتی متدی که امروز ضرری ندارد، 405 و فهرست متدهای مجاز میگیرند.
بدفهمی رایج: «متد ناشناخته به handler پیشفرض میرسد.» همین عبور باگ است. handler پذیرندهٔ هر متد روی /v1/orders/42، درخواست DELETE، TRACE یا FOO ساختگی را به خواندن بدل میکند؛ سرور «قبل» دقیقاً چنین است. Framework پشتیبان X-HTTP-Method-Override هم اجازه میدهد POST پشت proxy محدودکنندهٔ POST به DELETE تبدیل شود. OWASP این را دستکاری متد (Verb tampering) مینامد.
تعریف: برگهٔ REST Security میگوید: "Apply an allowlist of permitted HTTP Methods e.g. GET, POST, PUT." و "Reject all requests not matching the allowlist with HTTP response code 405 Method not allowed." طبق RFC 9110 بخش 15.5.6، پاسخ 405 باید هدر Allow با متدهای پشتیبانیشدهٔ منبع داشته باشد. دو لایه داریم: فهرست عمومی که TRACE، CONNECT، متدهای WebDAV و هدر override را رد کند؛ و الگوی هر Route مانند GET /v1/orders/{id} و POST /v1/orders. فهرست متد همچنین مسئلهٔ مجوز (Authorization) است: "Make sure the caller is authorized to use the incoming HTTP method on the resource collection, action, and record."
1 TRACE /v1/orders/6f1c... AllowMethods: TRACE not in {GET, HEAD, POST, OPTIONS}
2 -> 405, Allow: GET, HEAD, POST, OPTIONS, problem+json
3 POST /v1/orders/6f1c... AllowMethods: ok -> ServeMux: only "GET /v1/orders/{id}"
4 -> 405, Allow: GET, HEAD (set by ServeMux), rewritten to problem+json
5 POST /v1/orders/6f1c... X-HTTP-Method-Override: DELETE
6 -> 400 "method override headers are not accepted"سناریوی واقعی: TRACE هدر Authorization را بازتاب میداد؛ همان cross-site tracing روی stack قدیمی. در Laravel، Route::any() عملیات تغییردهندهٔ وضعیت را به GET باز کرده بود و ربات پیشنمایش لینک آن را اجرا کرد. یا gateway روی /reports فقط GET را مجاز میدانست ولی برنامه X-HTTP-Method-Override: DELETE را میپذیرفت.
| محصول | رفتار پیشفرض | فهرست مجاز متد |
|---|---|---|
Go ServeMux از 1.22 | الگوی متد؛ متد غلط روی مسیر شناختهشده → 405 و Allow با http.Error با text/plain | الگوی هر Route؛ Middleware عمومی برای بقیه |
| Router در Laravel | متد غلط روی URI شناختهشده → MethodNotAllowedHttpException با 405 و Allow | Route::get/post/...؛ پرهیز از Route::any و Route::match(['*']) |
| Nginx | تمام متدها را به upstream میفرستد | limit_except GET POST OPTIONS { deny all; }؛ GET شامل HEAD است؛ OPTIONS برای Preflight لازم است؛ بقیه 403 میگیرند نه 405 |
| Kong | فیلد methods در Route تطبیق را محدود میکند؛ عدم تطبیق → 404 از router | methods: [GET, POST] در Route |
| Envoy | تطبیق Route با هدر :method | matcher در headers برای :method |
اصلاح / روش استفاده: AllowMethods و الگوهای متد در Go؛ Route::get/Route::post صریح در Laravel و renderer خطا در bootstrap/app.php که Allow استثنا را نگه میدارد. تست Go وجود Allow را در تمام پاسخهای 405 بررسی میکند.
اعتبارسنجی Content-Type با 415 و Accept با 406 حیاتی
به زبان ساده: درخواست دارای بدنه باید اعلام کند JSON است و واقعاً هم JSON باشد. به کلاینتی که فقط XML میخواهد بگویید فقط JSON دارید. تعیین Content-Type پاسخ با سرور است، نه کلاینت.
بدفهمی رایج: «هر درخواست بدون Content-Type را رد کن.» GET بدون بدنه نیازی به این هدر ندارد؛ ردش بیدلیل کلاینت را میشکند. برگهٔ REST دقیق میگوید: "For requests with a body, require a supported Content-Type according to the endpoint contract and reject unsupported media types with 415 Unsupported Media Type. Do not require Content-Type solely for requests without a body. Reserve 406 Not Acceptable for response content negotiation." اشتباه دوم بازتاب هدر است: "Do NOT simply copy the Accept header to the Content-type header of the response."
تعریف: در اعتبارسنجی نوع محتوا (Content-Type validation)، برای بدنه با Content-Length مثبت یا chunked، نوع رسانه را با mime.ParseMediaType بخوانید؛ application/json لازم است و اگر charset داده شده فقط charset=utf-8 پذیرفته شود. در غیر این صورت 415 Unsupported Media Type بدهید. RFC 9110 بخش 15.5.16 دربارهٔ هدر پاسخ Accept میگوید "can be used to indicate" چه نوعی کار میکرد. در اعتبارسنجی پذیرش (Accept validation)، کیفیت application/json از خاصترین بازهٔ منطبق گرفته میشود؛ RFC 9110 بخش 12.5.1: "the most specific reference has precedence". بنابراین application/json بر application/* و آن بر */* مقدم است و application/json;q=0, */*;q=1، JSON را رد میکند. پارامترهای غیر q هم باید با نمایش پاسخ بخوانند: application/json;profile=v2 با application/json ساده منطبق نیست؛ پس application/json;profile=v2;q=1, application/json;q=0 پاسخ 406 میگیرد. ولی charset=utf-8 منطبق است، چون JSON با UTF-8 است. وزن از 0 تا 1 با حداکثر سه رقم اعشار است؛ q=NaN، q=inf یا q=1e0 باعث نادیدهگرفتن آن بازه میشود. کیفیت نهایی صفر یا نبود تطبیق یعنی 406 Not Acceptable. فقط application/problem+json کافی نیست، چون پاسخ موفق application/json است؛ عبارت RFC: "and the server is unwilling to supply a default representation". این سازوکار مذاکرهٔ محتوا (Content negotiation) است. بند "Force content-type for your response" نیمهٔ خروجی را میگوید: Content-Type را همیشه خودتان تعیین کنید.
1 POST /v1/orders Content-Type: text/plain body {"sku":"MUG-01"}
2 JSONOnly: body present, media type text/plain -> 415, Accept: application/json
3 POST /v1/orders (chunked, no Content-Type)
4 JSONOnly: ContentLength == -1 means body -> 415
5 GET /v1/orders/6f1c... Accept: application/xml
6 JSONOnly: no JSON range with q > 0 -> 406
7 GET /v1/orders/6f1c... Accept: text/html, */*;q=0.1
8 */* with q=0.1 accepted -> 200 application/jsonسناریوی واقعی: endpoint علاوه بر JSON، application/x-www-form-urlencoded را parse میکرد؛ فرم HTML سایت دیگر، بدون Preflight برای این نوع، با cookie کاربر به آن POST میکرد. endpoint دارای XML که کسی Content-Type آن را بررسی نکرده بود درگاه XXE شد. سروری هم Accept: text/html را در Content-Type کپی کرد و صفحهٔ مهاجم توانست خطای JSON حاوی ورودی بازتابی را HTML رندر کند.
| محصول | بررسی Content-Type | بررسی Accept |
|---|---|---|
| کتابخانهٔ استاندارد Go | ندارد؛ json.Decoder هر بایتی را میخواند | ندارد |
| زنجیرهٔ Go این فصل | JSONOnly: پاسخ 415 و Accept | JSONOnly: پاسخ 406، q-value با تقدم خاصترین بازه |
| Laravel | $request->isJson()؛ 415 خودکار ندارد | $request->accepts() با اولین بازهٔ منطبق true میدهد و q و تقدم را نادیده میگیرد (InteractsWithContentTypes::accepts)؛ EnforceJsonApi::jsonQuality() قواعد Go را اعمال میکند؛ استثنا بر اساس "based on the Accept header" به JSON یا HTML رندر میشود |
| APISIX | header_schema در request-validation | همان افزونه |
| Kong | OAS Validation نسخهٔ Enterprise با content در requestBody سند | نوعهای محتوای پاسخ در سند |
اصلاح / روش استفاده: JSONOnly در Go و EnforceJsonApi در گروه api در Laravel. تابع shouldRenderJsonWhen تمام خطاهای api/* را حتی برای درخواست HTML به JSON بدل میکند.
سقف اندازهٔ بدنه، 413 Content Too Large و MaxBytesReader حیاتی
به زبان ساده: بزرگترین بدنهٔ موجه برای هر endpoint را تعیین کنید و همانجا خواندن را قطع کنید؛ چه کلاینت طول را از قبل گفته باشد چه نگفته باشد.
بدفهمی رایج: «Content-Length را بررسی میکنم؛ امن هستم.» درخواست قطعهای (Chunked) هدر Content-Length را ندارد؛ در Go مقدار ContentLength == -1 است. کلاینت هم میتواند طول کم اعلام کند و ارسال را ادامه دهد. محدودیت واقعی reader شمارندهٔ بایت، یعنی http.MaxBytesReader، است؛ بررسی هدر فقط راه رد سریع است.
تعریف: برگهٔ REST: "Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large." نام RFC 9110، 413 Content Too Large است و سرور اجازه دارد اتصال را ببندد. در Go، http.MaxBytesReader(w, r.Body, n) طبق مستندات "is similar to io.LimitReader but is intended for limiting the size of incoming request bodies"؛ خواندن بیش از سقف *http.MaxBytesError با متن "http: request body too large" میدهد. همچنین "If possible, it tells the ResponseWriter to close the connection after the limit has been reached." بخش آخر فقط وقتی کار میکند که writer ساختهشدهٔ net/http را بدهید: پیام بستن از طریق متد exportنشدهٔ نوع پاسخ سرور است و wrapper روی ResponseWriter آن را بیصدا پنهان میکند. LimitBody تا درونیترین writer پایین میرود؛ هر wrapper زنجیره Unwrap() دارد. تست روی اتصال واقعی نشان میدهد سرور آن را میبندد.
1 client: POST /v1/orders Transfer-Encoding: chunked (no Content-Length)
2 LimitBody: r.ContentLength == -1, no fast-path reject; Body = MaxBytesReader(innermost(w), Body, 64 KiB)
3 handler: io.ReadAll reads 64 KiB + 1 byte
4 MaxBytesReader: returns *http.MaxBytesError, marks the connection to close
5 DecodeJSON: errors.As(err, *MaxBytesError) -> 413 problem "request body too large"
6 server: sends 413 with Connection: close, stops reading the attacker's streamسناریوی واقعی: آپلود ۲ GB به endpoint JSON در io.ReadAll buffer شد و pod با کمبود حافظه یا OOM کشته شد؛ API4:2023. endpoint ورود لاگ JSON بدون سقف ارزانترین DoS پلتفرم شد. در برنامهٔ Laravel هم PHP مقدار post_max_size=8M داشت، ولی پیشفرض client_max_body_size 1m در Nginx درخواست معتبر ۲ MB را با صفحهٔ HTML و 413 رد کرد که کلاینت موبایل نمیتوانست parse کند.
| لایه | تنظیم | پیشفرض | پاسخ |
|---|---|---|---|
Go net/http | http.MaxBytesReader برای هر handler | هیچ سقف بدنهای ندارد | کد شما تعیین میکند؛ اینجا 413 با Problem Details |
هدرهای Go net/http | Server.MaxHeaderBytes | DefaultMaxHeaderBytes = 1 << 20 معادل ۱ MB | 431 Request Header Fields Too Large |
| PHP | post_max_size، upload_max_filesize | "8M" و "2M" در فهرست ini سایت php.net | Middleware عمومی ValidatePostSize در Laravel استثنا میدهد |
| Nginx | client_max_body_size | 1m | "413 (Request Entity Too Large)"، صفحهٔ HTML |
| Kong | request-size-limiting با allowed_payload_size، size_unit، require_content_length | ۱۲۸ megabytes | 413 |
| Envoy | envoy.filters.http.buffer با max_request_bytes | فیلد الزامی | 413 |
| APISIX | client-control با max_body_size بر حسب بایت | تنظیمنشده | 413 |
اصلاح / روش استفاده: LimitBody و DecodeJSON در Go؛ LimitRequestBody در Laravel برای سقف Route زیر post_max_size؛ دیوار بیرونی در gateway، مثلاً client_max_body_size 64k در locationهای JSON در Nginx. سقف را برای هر endpoint انتخاب کنید: ۶۴ KiB برای سفارش، بزرگتر فقط در Route لازم. آپلود مستقیم به object storage میرود؛ آپلود فایل، S3 و CDN.
اعتبارنامه در هدر Authorization، نه URL مهم
به زبان ساده: توکن، کلید API و گذرواژه در هدر، یا بدنهٔ POST، جابهجا میشوند؛ هرگز در رشتهٔ پرسوجو (Query string) نیستند، چون URL همهجا ثبت میشود.
بدفهمی رایج: «TLS، Query string را رمز میکند؛ پس ?api_key= اشکالی ندارد.» TLS سیم را محافظت میکند؛ سپس URL در access log تمام proxyها، gateway، CDN، تاریخچهٔ مرورگر و هدر Referer میماند. برگهٔ REST: "Passwords, security tokens, and API keys should not appear in the URL, as this can be captured in web server logs, which makes them intrinsically valuable."
تعریف: هدر استاندارد درخواست Authorization را به کار ببرید؛ Authorization: Bearer <token> برای Bearer tokenهای OAuth مطابق RFC 6750 است. scheme کلید API در کلید API و امضای درخواست آمده است. بند roadmap میگوید "Use standard Authorization header for sensitive data" و گروه Authentication اضافه میکند "Avoid 'Basic Authentication', use standard (e.g. JWT)". سمت سرور هدر را لاگ نکنید، پیش از ارسال به ثالث حذف کنید و فقط path را ثبت کنید، نه query؛ در این صورت کلاینت بدرفتارِ فرستندهٔ ?access_token= هم توکن را وارد لاگ شما نمیکند.
1 bad: GET /v1/orders?access_token=sk_live_9f... -> nginx access.log, CDN log, Referer
2 good: GET /v1/orders Authorization: Bearer sk_live_9f...
3 AccessLog writes path=/v1/orders (no query), no headers
4 NewLogger ReplaceAttr: key "authorization" -> "[REDACTED]" even if a developer logs itسناریوی واقعی: توکن magic link در URL از طریق Referer به script تحلیلگر فرستاده شد؛ کلید API شریک در query برای تمام خوانندگان لاگ CDN قابل مشاهده بود؛ مهندس پشتیبانی URL حاوی توکن را در ticket چسباند.
اصلاح / روش استفاده: کلاینت Authorization میفرستد؛ AccessLog در Go فقط r.URL.Path را ثبت میکند و NewLogger کلیدهای authorization، token، access_token و api_key را میپوشاند. tap به نام RedactSensitiveData در Laravel همین کار را برای context در Monolog میکند. همراهش Referrer-Policy: no-referrer بفرستید.
هدرهای امنیتی API: nosniff، frame options، CSP، HSTS، Referrer-Policy و no-store حیاتی
به زبان ساده: مجموعهٔ ثابتی از هدر پاسخ به مرورگر میگوید نوع محتوا را حدس نزند، API را در frame نگذارد یا محتوایش را اجرا نکند، پاسخ را cache نکند، URL را لو ندهد و فقط HTTPS به کار ببرد. یکبار در Middleware، برای تمام پاسخها تنظیم کنید.
بدفهمی رایج: «هدر فقط در صفحهٔ HTML مهم است.» پاسخ API میتواند مستقیم در tab باز شود، در frame صفحهٔ مهاجم قرار گیرد، بهخاطر markup داخل رشتهٔ JSON بهصورت HTML تشخیص داده شود یا در cache مشترک بماند. برگهٔ REST از Cache-Control: no-store، Content-Security-Policy: frame-ancestors 'none'، Content-Type، Strict-Transport-Security، X-Content-Type-Options: nosniff و X-Frame-Options: DENY نام میبرد که "should be included in all API responses that may be consumed by browser clients". همچنین Content-Security-Policy: default-src 'none' و Referrer-Policy: no-referrer را دفاع در عمق برای پاسخ قابل رندر میداند.
تعریف و مقدارها:
| هدر | مقدار API | دلیل و منبع |
|---|---|---|
X-Content-Type-Options | nosniff | "prevents browsers from performing MIME sniffing, and inappropriately interpreting responses as HTML" از OWASP REST |
X-Frame-Options | DENY | "Legacy header superseded by Content-Security-Policy: frame-ancestors 'none'"؛ برای مرورگر قدیمی حفظ میشود؛ roadmap: "Send X-Frame-Options: deny header" |
Content-Security-Policy | default-src 'none'; frame-ancestors 'none' | بارگیری منبع و frame کردن پاسخ ممنوع؛ MDN: "default-src is a fallback for all other fetch directives" |
Cache-Control | no-store | "Instructs compliant private and shared HTTP caches not to store the response" از OWASP؛ MDN دربارهٔ no-cache: "does not mean "don't cache"" |
Referrer-Policy | no-referrer | "Non-HTML responses should not trigger additional requests" از OWASP؛ پیشفرض مرورگر strict-origin-when-cross-origin طبق MDN |
Strict-Transport-Security | max-age=63072000; includeSubDomains | فقط HTTPS به مدت ۲ سال؛ طبق RFC 6797 بخش 7.2 نباید روی HTTP ساده فرستاده شود |
Permissions-Policy | camera=(), microphone=(), geolocation=(), payment=() | قابلیت مرورگر را هنگام رندر غیرفعال میکند؛ مثال OWASP REST |
Content-Type | تعیینشده توسط سرور | "If not specified or if specified incorrectly, a browser might attempt to guess the content type" از OWASP REST |
1 handler sets Content-Type: application/json; writes {"id":"...","sku":"<img src=x onerror=...>"}
2 without nosniff: an old browser opened directly may sniff and render HTML
3 with nosniff + CSP default-src 'none': no sniffing; even if rendered, no script, no image
4 attacker page: <iframe src="https://api.example/v1/me"> -> frame-ancestors 'none' blocks it
5 shared proxy cache: Cache-Control: no-store -> /v1/me is never stored for the next userسناریوی واقعی: fallback بدپیکربندیشده پارامتر query را در صفحهٔ خطای text/html بازتاب داد و XSS بازتابی روی دامنهٔ API، مشترک در cookie با برنامه، ساخت. Proxy شرکتی /v1/me کاربر اول را cache کرد و به بعدی داد. URL بازنشانی گذرواژه هم از Referer نشت کرد.
| محصول | پیشفرض | تنظیم مجموعهٔ هدر API |
|---|---|---|
Go net/http | ندارد؛ فقط http.Error، هدر X-Content-Type-Options: nosniff میافزاید | harden.SecurityHeaders |
| Laravel 13 | برای Routeهای API ندارد | SecurityHeaders در ابتدای stack عمومی، بیرون HandleCors؛ یا bepsvpt/secure-headers، README نسخهٔ 9.1.1: "Supported Laravel Version 5.1 ~ 13.x"؛ CSP با spatie/laravel-csp: "requires PHP 8.3 or higher and Laravel 12 or 13" |
| Nginx | ندارد | add_header Name value always;؛ پارامتر always از 1.7.5 با قاعدهٔ "regardless of the response code"؛ ارثبری فقط "if and only if there are no add_header directives defined on the current level" |
| Kong | ندارد | افزونهٔ response-transformer با config.add.headers |
| Envoy | ندارد | response_headers_to_add روی Route یا virtual host |
| APISIX | ندارد | response-rewrite با headers.set |
اصلاح / روش استفاده: SecurityHeaders در Go، با HSTS فقط وقتی r.TLS != nil یا proxy مورد اعتماد X-Forwarded-Proto: https بگوید. در Laravel، SecurityHeaders را در ابتدای stack عمومی، بیرون HandleCors و ValidatePostSize قرار دهید تا Preflight و پاسخهای 404/405/413/500 نیز هدر بگیرند؛ feature test، Preflight را میسنجد. محتوای ثابت هدر را از لبه میگیرد. ممیزی curl هر مقدار را بررسی میکند.
اثرانگشت: حذف هدرهای Server و X-Powered-By مهم
به زبان ساده: نسخهٔ وبسرور، زبان و Framework را روی هر پاسخ اعلام نکنید؛ این اطلاعات قدم اول تطبیق stack با فهرست CVE را برای مهاجم آماده میکند.
بدفهمی رایج: «حذف هدر stack را پنهان میکند.» فقط ارزانترین نشانه را حذف میکند. OWASP HTTP Headers: "Remember that attackers have other means of fingerprinting the server technology"؛ شکل صفحهٔ خطا، cookie مثل laravel_session، اثرانگشت TLS و زمانبندی هم نشانهاند. انجامش دهید چون رایگان است و نسخه را از گزارش scanner حذف میکند؛ آن را دفاع کامل حساب نکنید.
تعریف: اثرانگشت (Fingerprinting) تشخیص نرمافزار و نسخه از پاسخ است. نشتهای معمول: Server با nginx/1.18.0 یا Apache/2.4.41 (Ubuntu)، X-Powered-By با PHP/8.1.2 یا Express، X-AspNet-Version، X-Runtime، نسخه در صفحهٔ خطای پیشفرض و فهرست دایرکتوری؛ roadmap: "Turn off directory listings". توصیهٔ OWASP برای Server: "Remove this header or set non-informative values"؛ برای X-Powered-By: "Remove all X-Powered-By headers." حذف باید هنگام نوشتن رخ دهد؛ handler داخلی یا upstream آنها را پس از اجرای middleware شما تنظیم میکند.
1 before: Server: orders-api/0.9.1 (go1.22.1; linux) X-Powered-By: academy-framework/2.3
2 attacker: search "go1.22.1 net/http CVE" -> pick an advisory fixed in a later release
3 after: stripWriter deletes Server, X-Powered-By, X-AspNet-Version, X-Runtime at WriteHeader
4 edge: nginx server_tokens off; proxy_hide_header X-Powered-By| محصول | خروجی پیشفرض | روش خاموشکردن |
|---|---|---|
| Nginx | Server: nginx/1.x.y و نسخه در صفحهٔ خطا با server_tokens on | server_tokens off; که Server: nginx را نگه میدارد؛ proxy_hide_header X-Powered-By; برای upstream؛ Nginx از قبل Server، Date، X-Pad و X-Accel-... بالادستی را پنهان میکند |
| PHP | X-Powered-By: PHP/8.x | expose_php = Off در php.ini؛ header_remove('X-Powered-By') |
Go net/http | هدر Server ندارد | اقدامی لازم نیست؛ افزودهٔ handler و upstream را حذف کنید |
| Envoy | server: envoy | server_header_transformation: PASS_THROUGH یا تعیین server_name؛ پیشفرض OVERWRITE: "Overwrite any Server header with the contents of server_name" |
| Kong | Server: kong/x.y و Via | تنظیم headers در kong.conf، اینجا بررسی نشده؛ response-transformer و remove.headers برای upstream |
| APISIX | Server: APISIX/x.y | response-rewrite با headers.remove؛ server_tokens در پیکربندی Nginx متعلق به APISIX، اینجا بررسی نشده |
اصلاح / روش استفاده: stripWriter در SecurityHeaders برای Go؛ SecurityHeaders و expose_php = Off در Laravel؛ بلوک Nginx در لبه. با curl -sI تست کنید و اگر Server رقم داشت CI را شکست دهید.
پاسخ خطا: RFC 9457، کد درست و نبود Stack trace حیاتی
به زبان ساده: هر خطا کد وضعیت درست، شکل JSON یکسان و شمارهٔ پیگیری دارد. جزئیات اتفاق داخلی با همان شماره در لاگ میماند.
بدفهمی رایج: «خطای دقیق به کلاینت کمک میکند درخواست را درست کند.» جزئیات درخواست مفید است، مثل "quantity": "must be between 1 and 100". جزئیات سرور، یعنی Stack trace، SQL، مسیر فایل، نام کتابخانه و IP داخلی، فقط به مهاجم کمک میکند. REST: "Do not pass technical details (e.g. call stacks or other internal hints) to the client." بخش 5 RFC 9457: "Generators providing links to occurrence information are encouraged to avoid making implementation details such as a stack dump available through the HTTP interface".
تعریف: جزئیات خطا (Problem Details) در RFC 9457 شامل Content-Type: application/problem+json و شیء JSON با type از جنس URI است؛ about:blank یعنی فقط کد وضعیت. title کوتاه و بین رخدادها ثابت، status کپی کد HTTP، detail ویژهٔ این رخداد و امن برای کلاینت، و instance اعضای دیگرند. عضو افزوده (Extension member) اینجا request_id و errors برای خطای فیلد است. کد وضعیت درست (Correct status codes) یعنی قاعدهٔ REST: "don't just use 200 for success or 404 for error" و هشدار "Do not return 200 with an empty body when an API key is missing or invalid". خانوادهٔ 4xx یعنی کلاینت میتواند اصلاح کند؛ 5xx یعنی مشکل از ماست. Panic و exception را در بیرونیترین handler بگیرید، Stack trace را با Request id لاگ کنید و Problem عمومی برگردانید.
1 handler panics: "db: connection refused at 10.0.3.7:5432 user=orders_rw"
2 Recover: recover() -> log.Error("panic", request_id=647202a4..., stack="goroutine 33 [running]: ...")
3 Recover: WriteProblem(500, "internal error")
4 client: {"type":"about:blank","title":"Internal Server Error","status":500,
5 "detail":"internal error","request_id":"647202a4b7fd59f1cd5f3315"}
6 support: grep request_id=647202a4b7fd59f1cd5f3315 in the central log -> full stackسناریوی واقعی: صفحهٔ 500، connection string در Postgres همراه گذرواژه را چاپ کرد؛ API8:2023. endpointها «پیدا نشد» را گاهی 200 با {}، گاهی 404 با HTML و گاهی 400 با متن میدادند؛ کلاینت شکست Authentication را «داده ندارد» فهمید و حساب خالی نمایش داد. تفاوت 404 و 403 روی اشیای دیگران هم وجود شناسهٔ سفارش را لو داد؛ برای شیئی که کاربر نباید از وجودش خبر داشته باشد 404 بدهید.
| Stack | خطای پیشفرض | پشتیبانی Problem Details |
|---|---|---|
Go net/http | http.Error: نوع text/plain و متن وضعیت؛ سرور Panic را لاگ و اتصال را قطع میکند | داخلی ندارد؛ harden.WriteProblem و بازنویسی ProblemErrors |
| Laravel 13 | برای درخواست JSON، {"message": ...}؛ با APP_DEBUG=true شامل exception، file، line و trace | $exceptions->render(...) سفارشی در bootstrap/app.php |
| Symfony / API Platform | Problem JSON برای منابع API Platform | داخلی در API Platform |
| Nginx | صفحهٔ HTML دارای نسخه، مگر server_tokens off | error_page و return با JSON برای هر کد |
| Kong / APISIX | JSON به شکل {"message": ...} | قالب خطای سفارشی؛ اینجا نشان داده نشده |
اصلاح / روش استفاده: WriteProblem، ProblemErrors و Recover در Go. Wrapper به نام ProblemErrors خطاهای متن سادهٔ 404/405 از ServeMux و 503 از TimeoutHandler را هم به Problem تبدیل میکند. در Laravel، renderer در bootstrap/app.php.
حذف دادهٔ حساس از پاسخ: فهرست مجاز خروجی حیاتی
به زبان ساده: پاسخ از فهرست صریح فیلد ساخته میشود، نه از serialise کردن سطر پایگاه داده. ستون تازه خصوصی میماند تا کسی خلافش را تصمیم بگیرد.
بدفهمی رایج: «Frontend فیلد را نشان نمیدهد؛ مشکلی نیست.» فیلد داخل JSON است و هرکس با network tab مرورگر یا curl آن را میخواند. این BOPLA یا API3:2023، یعنی افشای بیشازحد داده (Excessive data exposure)، در OWASP API Security Top 10 است؛ این فصل کنترل اجرایی آن را دارد.
تعریف: شیء انتقال دادهٔ پاسخ (Response DTO) فهرست مجاز خروجی است: struct در Go با JSON tag فقط روی فیلد عمومی، یا JsonResource::toArray در Laravel. roadmap: "Avoid returning sensitive data (credentials, sec. tokens etc)". دادهٔ حساس شامل اعتبارنامه، توکن، hash گذرواژه، شمارهٔ کامل کارت، امتیاز داخلی، دادهٔ دیگر کاربران، شناسه و hostname داخلی است. از کارت حداکثر چهار رقم آخر را نمایش دهید؛ اینجا قاعدهٔ دقیق نمایش PCI DSS نقل نشده است.
1 storage struct: ID, SKU, Quantity, CardNumber, RiskScore
2 before: json.Encode(order) -> {"card_number":"4111111111111111","risk_score":0.12,...}
3 after: orderView{ID, SKU, Quantity, CardLast: last 4} -> {"card_last4":"1111",...}
4 test: response must not contain "card_number" or the full PANاصلاح / روش استفاده: orderView در app.go همراه تستی که شمارهٔ کارت را در پاسخ جستوجو کند؛ در Laravel، OrderResource و $hidden روی model بهعنوان لایهٔ دوم، و feature test با assertJsonMissingPath('card_number').
خاموشبودن debug: APP_DEBUG، pprof و صفحههای debug حیاتی
به زبان ساده: Production هرگز خروجی debug ندارد. بهتر از آن: فرایند Production با debug روشن اصلاً بالا نیاید.
بدفهمی رایج: «فقط یک ساعت برای بررسی روشنش کردیم.» یک ساعت برای scanner کافی است. مستندات Laravel: "If the variable is set to true in production, you risk exposing sensitive configuration values to your application's end users." بند Processing در roadmap: "Make sure to turn the debug mode off in production".
تعریف: حالت اشکالزدایی خاموش (Debug mode off) یعنی در Laravel، APP_DEBUG=false و APP_ENV=production. در config/app.php مقدار 'debug' => (bool) env('APP_DEBUG', false) است؛ نبود متغیر هم امن است. در PHP، display_errors=Off. در Go، import به نام net/http/pprof روی mux عمومی نباشد؛ این import مسیر /debug/pprof/ را روی http.DefaultServeMux ثبت میکند. خطای پرجزئیات ندهید و ابزار Telescope، Debugbar و Ignition نصب نباشد یا دسترسی محدود داشته باشد. محافظ خاموشی debug (Debug-off guard) بررسی هنگام راهاندازی است که با خطا اجرای فرایند را متوقف میکند.
1 $ APP_ENV=production APP_DEBUG=true ./apiserver -addr 127.0.0.1:18490
2 2026/11/29 12:59:12 unsafe production configuration: debug mode is on
3 exit=1 (real run, see Lab)
4 Laravel: AppServiceProvider::boot throws RuntimeException when isProduction() && config('app.debug')| Stack | کلید debug | محافظ |
|---|---|---|
| Laravel 13 | APP_DEBUG در .env؛ cache با php artisan config:cache | بررسی در AppServiceProvider؛ جستوجوی manifest استقرار در CI |
| PHP | display_errors، display_startup_errors، expose_php | بررسی php -i هنگام ساخت Image |
| Go | پرچم خودتان؛ import دارای side effect در net/http/pprof | harden.Config.Validate()؛ pprof روی listener جدا در localhost |
| Django / Spring برای مقایسه | DEBUG=True؛ endpointهای Actuator | بررسی settings؛ management.endpoints.web.exposure.include |
اصلاح / روش استفاده: Config.Validate در main برنامهٔ Go و AppServiceProvider در Laravel. اطلاعات debug حذف نمیشود؛ با کلید Request id داخل لاگ میماند.
Timeoutها: خواندن، نوشتن، بیکاری، Slowloris و Timeout handler حیاتی
به زبان ساده: هر مرحلهٔ اتصال Timeout دارد: دریافت هدر، دریافت بدنه، اجرای handler، نوشتن پاسخ و انتظار درخواست بعدی. بدون Timeout، چند کلاینت کند تمام اتصالها را اشغال میکنند.
بدفهمی رایج: «WriteTimeout، handler کند را متوقف میکند.» WriteTimeout پس از پایان Timeout اتصال را میبندد، اما handler ادامه میدهد و کلاینت بهجای کد وضعیت reset میبیند. برای کار handler از http.TimeoutHandler یا Timeout context و برای اتصال از Timeout سرور استفاده کنید. اشتباه دوم از راهنمای Cloudflare برای Go 1.6–1.8 آمده که میگوید TimeoutHandler پاسخ "a 504 Gateway Timeout" میدهد؛ source فعلی net/http میگوید "responds with a 503 Service Unavailable error" و آزمایشگاه هم همین را نشان میدهد.
تعریف: فیلدهای http.Server طبق توضیح source: ReadHeaderTimeout یعنی "is the amount of time allowed to read request headers"؛ ReadTimeout یعنی "is the maximum duration for reading the entire request, including the body" و "most users will prefer to use ReadHeaderTimeout". WriteTimeout یعنی "is the maximum duration before timing out writes of the response. It is reset whenever a new request's header is read". IdleTimeout یعنی "is the maximum amount of time to wait for the next request when keep-alives are enabled". صفر همیشه بهمعنای خاموش نیست: ReadHeaderTimeout صفر به ReadTimeout برمیگردد؛ "If zero, the value of ReadTimeout is used". IdleTimeout صفر هم همین fallback را دارد؛ فقط اگر ReadTimeout هم صفر یا منفی باشد سقفی نیست. ReadTimeout یا WriteTimeout صفر برای همان فیلد یعنی بدون Timeout. بنابراین http.Server{ReadTimeout: 10 * time.Second} از قبل هدر و بیکاری را به ده ثانیه محدود میکند، ولی http.Server صفر که http.ListenAndServe میسازد هیچ سقفی ندارد. حملهٔ اتصال کند (Slowloris) هدر را بایتبهبایت میفرستد و تمام نمیکند؛ دفاع آن ReadHeaderTimeout است. در Timeout هدر، Go بدون پاسخ اتصال را میبندد؛ isCommonNetReadError: "don't reply". Nginx پس از client_header_timeout، با پیشفرض شصت ثانیه، 408 میدهد. بند "Avoid HTTP blocking if you are using huge amount of data" همین منطق را برای کار میگوید: کار طولانی به صف برود و 202 برگردد.
1 t=0.0s slowloris: connect; send "GET / HTTP/1.1\r\nHost: x\r\nX-Slow: 1\r\n" and stop
2 no ReadHeaderTimeout: connection open forever; 10,000 of them exhaust file descriptors
3 ReadHeaderTimeout=200ms (test): t=0.2s server closes; client reads EOF, 0 bytes
4 t=0.0s GET /v1/lab/slow (handler sleeps 5s, honours ctx)
5 t=1.0s TimeoutHandler: ctx cancelled, 503 written, ProblemErrors turns it into problem+json| مرحله | Go http.Server یا helper | Nginx | Envoy |
|---|---|---|---|
| هدر | ReadHeaderTimeout؛ قطع بیپاسخ؛ صفر به ReadTimeout برمیگردد | client_header_timeout 60s و 408 | request_headers_timeout پیشفرض خاموش؛ "should be configured in the presence of untrusted downstreams" |
| تمام درخواست / بدنه | ReadTimeout | client_body_timeout 60s؛ فاصلهٔ دو خواندن، نه کل بدنه | request_timeout پیشفرض خاموش |
| Handler | http.TimeoutHandler با 503، context.WithTimeout | proxy_read_timeout به سمت upstream | timeout در Route |
| نوشتن پاسخ | WriteTimeout | send_timeout | stream_idle_timeout |
| بیکاری Keep-alive | IdleTimeout با fallback به ReadTimeout | keepalive_timeout | common_http_protocol_options.idle_timeout |
| اندازهٔ هدر | MaxHeaderBytes پیشفرض ۱ MB → 431 | large_client_header_buffers | max_request_headers_kb |
اصلاح / روش استفاده: در Go، NewServer با DefaultTimeouts: پنج ثانیه هدر، ده ثانیه خواندن، پانزده ثانیه نوشتن، شصت ثانیه بیکاری و هشت ثانیه handler؛ همراه WithHandlerTimeout. Laravel پشت PHP-FPM و Nginx اجرا میشود؛ آنجا request_terminate_timeout در FPM، max_execution_time در PHP و دستورهای Nginx جدول بالا را تنظیم کنید.
CORS: پیشدرخواست، اعتبارنامه و فهرست صریح origin مهم
به زبان ساده: هدرهای CORS به مرورگر میگویند کدام وبسایت دیگر حق خواندن پاسخ API با JavaScript را دارد. این حق را به فهرست کوتاهی از originهای دقیق بدهید؛ وقتی cookie در میان است، «هرکس درخواست کرد» مجاز نیست.
بدفهمی رایج: «CORS از API من محافظت میکند.» CORS فقط خواندن صفحه در مرورگر را کنترل میکند؛ curl، سرورها و script مهاجم بیرون مرورگر نادیدهاش میگیرند. این مجوز خواندن است، نه احراز هویت (Authentication). اشتباه مخالف بدتر است: بازتاب هر Origin در Access-Control-Allow-Origin همراه Access-Control-Allow-Credentials: true، دادهٔ کاربر واردشده را برای هر وبسایت خواندنی میکند.
تعریف: برای درخواست «غیرساده»، مثل متد غیر GET/HEAD/POST، یا Content-Type: application/json یا هدر سفارشی، مرورگر اول پیشدرخواست (Preflight) میفرستد: OPTIONS با Origin، Access-Control-Request-Method و Access-Control-Request-Headers. پاسخ سرور شامل Access-Control-Allow-Origin با یک origin دقیق، -Methods، -Headers، -Max-Age و در صورت مجازبودن cookie یا HTTP auth، هدر Access-Control-Allow-Credentials: true است. MDN: "When responding to a credentialed requests request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the * wildcard." هدر Vary: Origin لازم است تا cache مجوز یک origin را به دیگری ندهد. OWASP REST: "Disable CORS headers if cross-domain calls are not supported/expected." سازوکار cookie، SameSite و CORS در نشست وب، cookie و CORS است.
1 browser on https://shop.example: OPTIONS /v1/orders Origin: https://shop.example
2 Access-Control-Request-Method: POST
3 CORS: origin in allow-list, POST allowed -> 204, ACAO: https://shop.example, ACAC: true, Max-Age: 600
4 browser sends POST with the cookie; reads the 201
5 page on https://evil.example: same preflight -> 403, no ACAO; the browser never sends the POST
6 https://shop.example.evil.example: exact match fails (no suffix or regex matching)| محصول | پیشفرض | دام |
|---|---|---|
Laravel 13 با HandleCors عمومی | config/cors.php منتشرشده: 'allowed_origins' => ['*']، 'supports_credentials' => false، 'paths' => ['api/*', 'sanctum/csrf-cookie'] | روشنکردن supports_credentials بدون جایگزینی * |
افزونهٔ cors در Kong | credentials برابر false؛ توضیح Schema: "If you don't specify any allowed domains, all origins are allowed." | فهرست خالی origins |
| Go stdlib | CORS را مدیریت نمیکند | بازتاب دستی Origin |
| Envoy | فیلتر CORS و policy به نام cors برای Route | allow_origin_string_match با prefix منطبق بر زیردامنهٔ مهاجم |
افزونهٔ cors در APISIX | allow_origins: "*"؛ اینجا بررسی نشده | allow_credential: true با * |
اصلاح / روش استفاده: CORS در Go با origin دقیق، Vary: Origin و 403 برای Preflight بیگانه؛ config/cors.php در Laravel با فهرست حاوی FRONTEND_URL.
ثبت لاگ: Request id، Correlation id، Redaction و PII حیاتی
به زبان ساده: هر درخواست یک خط ساختاریافته با شناسه دارد؛ همان شناسه در هدر به کلاینت برمیگردد. راز و دادهٔ شخصی پیش از نوشتن خط پوشانده میشوند.
بدفهمی رایج: «همهچیز را لاگ کن؛ بعداً فیلتر میکنیم.» هرچه ثبت کنید به log shipper، محل مرکزی، backup و terminal مهندسان کپی میشود. OWASP Logging دربارهٔ شناسهٔ نشست، access token، دادهٔ شخصی حساس و بعضی PIIها، گذرواژه، connection string پایگاه داده، کلید رمزگذاری و دادهٔ بانکی و کارت میگوید: "should usually not be recorded directly in the logs, but instead should be removed, masked, sanitized, hashed, or encrypted". roadmap کوتاهتر میگوید: "Ensure that you aren't logging any sensitive data."
تعریف: شناسهٔ درخواست (Request id) یک درخواست در یک سرویس را مشخص میکند؛ شناسهٔ همبستگی (Correlation id) یا "Interaction identifier" در OWASP یک عمل کاربر را میان سرویسها دنبال میکند. وقتی gateway، X-Request-ID را تولید کند و هر سرویس فقط در صورت قالب درست و دریافت از hop مورد اعتماد آن را حفظ و ارسال کند، یک شناسه هر دو نقش را دارد. traceparent در W3C همین کار را برای trace میکند. پوشاندن داده (Redaction) مقدار را بر اساس کلیدهایی مثل authorization، password، token، email و card_number در logger جایگزین میکند؛ حتی log.Info("login", "password", p) توسعهدهنده هم [REDACTED] مینویسد. اطلاعات هویتی شخصی در لاگ (PII in logs) علاوه بر امنیت مسئلهٔ حریم خصوصی است؛ GDPR ایمیل داخل لاگ را دادهٔ شخصی میداند. فقط path را بنویسید، نه Query string و نه بدنهٔ درخواست. REST هشدار میدهد: "Take care of log injection attacks by sanitizing log data beforehand". Regex شناسهٔ درخواست، ^[A-Za-z0-9._-]{8,64}$، همین پاکسازی را برای تنها مقدار کلاینتی حاضر در تمام خطها انجام میدهد.
1 gateway: X-Request-ID: gw-7f3a9c2e (generated at the edge)
2 orders (trustIncoming=true): keeps gw-7f3a9c2e, logs {"request_id":"gw-7f3a9c2e","path":"/v1/orders","status":201}
3 orders -> payments: forwards X-Request-ID: gw-7f3a9c2e
4 client sends X-Request-ID: "abc\nlevel=ERROR msg=fake" -> fails the regex, replaced by a new id
5 log line: {"level":"WARN","msg":"http_request","request_id":"...","method":"GET","path":"/v1/orders","status":401}
6 query string ?access_token=... and the Authorization header never appearجدول رخداد امنیتی، لاگ را برای هشدار و ممیزی قابل پرسوجو میکند. این نمونه PostgreSQL است؛ همین شکل در log store مثل Loki یا OpenSearch هم کاربرد دارد:
CREATE TABLE security_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
request_id text NOT NULL CHECK (request_id ~ '^[A-Za-z0-9._-]{8,64}$'),
event text NOT NULL CHECK (event IN ('auth.failed', 'authz.denied', 'input.rejected', 'cors.denied', 'panic')),
status smallint NOT NULL,
client_ip inet NOT NULL,
route text NOT NULL, -- path pattern, never the raw URL with its query
actor_hash text -- HMAC of the user id, not the email
);
CREATE INDEX security_events_ip_time ON security_events (client_ip, occurred_at DESC);
-- Alert rule: more than 100 rejected inputs or failed logins from one IP in 5 minutes.
SELECT client_ip, count(*) AS events
FROM security_events
WHERE occurred_at > now() - interval '5 minutes'
AND event IN ('auth.failed', 'input.rejected')
GROUP BY client_ip
HAVING count(*) > 100
ORDER BY events DESC;| Stack | شناسهٔ درخواست | Redaction |
|---|---|---|
Go log/slog از 1.21 | Middleware و مقدار context؛ هدر X-Request-ID | HandlerOptions.ReplaceAttr بر اساس کلید در harden.NewLogger |
| Laravel 13 | Context::add('request_id', ...)؛ context طبق مستندات "is automatically appended as metadata to any log entries"؛ مثال مستندات از Log::withContext و هدر Request-Id استفاده میکند | tap کانال با processor در Monolog، یعنی RedactSensitiveData |
| Nginx | متغیر $request_id و proxy_set_header X-Request-ID $request_id | log_format سفارشی بدون $args و $http_authorization |
| Envoy | پیشفرض x-request-id میسازد | قالب access log بدون هدر حساس |
| OpenTelemetry | traceparent و trace id | processorهای attributes و redaction در Collector |
اصلاح / روش استفاده: RequestID، AccessLog و NewLogger در Go؛ AssignRequestId و RedactSensitiveData در Laravel. تصویر کامل مشاهدهپذیری، metrics، trace و Pipeline لاگ، در مشاهدهپذیری است.
پایش: لاگ متمرکز، هشدار، IDS/IPS و WAF مهم
به زبان ساده: لاگ همهٔ سرویسها یکجا میرود؛ چند قاعده با دیدن الگوی حمله انسان را خبر میکنند؛ حسگر شبکه و فایروال وب هم چیزهایی را میبینند که برنامه نمیبیند.
بدفهمی رایج: «لاگ داریم، پس پایش داریم.» OWASP Top 10:2025 نام A09 را به "Security Logging and Alerting Failures" تغییر داد؛ لاگی که کسی نمیخواند چیزی تشخیص نمیدهد. هشدار به آستانه، مسئول و دستورالعمل رسیدگی (Runbook) نیاز دارد.
تعریف: ثبت متمرکز لاگ (Centralised logging) یعنی ارسال خطهای JSON از همهٔ سرویسها و gateway به یک محل، مانند Elasticsearch/OpenSearch با Kibana، Loki با Grafana، CloudWatch Logs یا Datadog، همراه نگهداری و محدودیت دسترسی. هشداردهی (Alerting) قواعد روی همین داده است؛ roadmap: "Use alerts for SMS, Slack, Email, Kibana, Cloudwatch, etc.". نمونهها: جهش 401/403 برای IP یا حساب، جهش 413/415/400 نشانهٔ اسکن، هر رخداد panic و نرخ 5xx. سامانهٔ تشخیص و جلوگیری از نفوذ (IDS/IPS) ترافیک را برای امضای حملهٔ شناختهشده میبیند؛ Suricata، Snort و همتای ابری مثل AWS GuardDuty برای تشخیص. IDS هشدار میدهد؛ IPS مسدود میکند. فایروال برنامهٔ وب (WAF) جلوی API، مثل AWS WAF، Cloudflare WAF، ModSecurity با OWASP Core Rule Set یا Coraza، payload عمومی حمله را مسدود و قواعد نرخ و جغرافیا را اعمال میکند. سپر مفیدی است، ولی جای کنترلهای بالا را نمیگیرد. جزئیات شبکه در DDoS و امنیت شبکه است.
1 09:00:00-09:00:40 4,200 x POST /v1/login from 203.0.113.9 -> 401 (auth.failed)
2 09:00:40 alert rule "auth.failed > 100 / 5 min per IP" fires -> Slack #sec-oncall + PagerDuty
3 09:01:10 on-call: WAF rule blocks 203.0.113.9; rate limit tightened for /v1/login
4 09:05:00 incident ticket with the request ids of the first and last events| سیگنال | منبع | هشدار |
|---|---|---|
| جهش 401/403 | status در access log و security_events | بیش از 100 برای IP یا حساب در ۵ دقیقه |
| جهش 400/413/415/422 | Access log | Scanner یا fuzzer؛ بیش از 500 برای IP در ۵ دقیقه |
رخداد panic | Error log | هر رخداد، به تفکیک release |
| نرخ 5xx | Metrics | بیش از 1 % به مدت ۵ دقیقه |
| Route تازه با پاسخ 200 | اختلاف Inventory | هر Route خارج از سند OpenAPI |
| امضای حملهٔ شناختهشده | IDS/IPS و WAF | بر اساس شدت قاعده |
درگاه API: Kong، Envoy، APISIX، Nginx و اعتبارسنجی OpenAPI در لبه مهم
به زبان ساده: Gateway جلوی همهٔ سرویسها قواعد ارزان و یکسان را پیش از رسیدن ترافیک به کد اعمال میکند: TLS، اندازه، Timeout، نرخ، هدر پاکیزه و در صورت نیاز قرارداد OpenAPI.
بدفهمی رایج: «با Gateway سرویس میتواند به ورودی اعتماد کند.» فراخوان داخلی، job و ingress دیگر هم به سرویس میرسند؛ فقط سرویس قواعد کسبوکار و فیلد حساس را میشناسد. بند roadmap، "Use an API Gateway for caching, Rate Limit policies etc"، در جزئیات آن را "a centralized point of control for managing and securing API traffic" مینامد: محل کنترل، نه جایگزین برنامه.
تعریف: درگاه API (API gateway) مثل Kong، gateway مبتنی بر Envoy، Apache APISIX، Nginx یا gateway ابری، TLS را خاتمه میدهد، هویت و نرخ را کنترل میکند، Route میکند، هدر تغییر میدهد و لاگ مینویسد. اعتبارسنجی OpenAPI در لبه (OpenAPI validation at the edge) پیش از ارسال، مسیر، متد، پارامتر و Schema بدنه را با سند منتشرشده میسنجد. ابزارها: OAS Validation فقط در Kong Gateway Enterprise؛ request-validation در APISIX برای JSON Schema هدر و بدنه، با rejected_code پیشفرض 400؛ Envoy با external authorization یا validator مبتنی بر WASM. نتیجهٔ Schema-first همین است: یک سند، مستندات، تولید کلاینت، Validation در gateway و تست قرارداد را هدایت میکند. معماری BFF و service mesh در API gateway، BFF و service mesh است.
1 client -> CDN/WAF (TLS, bot rules) -> gateway -> orders service
2 gateway: request-size-limiting 64 KB -> 413; OAS validation: unknown path -> 404, bad body -> 400
3 gateway: rate limit 100/min per key -> 429 (see rate limiting)
4 gateway: response-transformer removes Server, X-Powered-By; adds nosniff
5 orders: the Go chain runs again (defence in depth): headers, 405/406/413/415, validation| موضوع | Kong | Envoy | APISIX | Nginx |
|---|---|---|---|---|
| سقف بدنه | request-size-limiting با allowed_payload_size، پیشفرض ۱۲۸ MB | buffer filter با max_request_bytes → 413 | client-control با max_body_size | client_max_body_size پیشفرض 1m → 413 |
| Timeout هدر | افزونه نیست؛ تنظیم Nginx در Kong، اینجا نشان داده نشده | request_headers_timeout | قالب پیکربندی Nginx | client_header_timeout با 60s → 408 |
| حذف اثرانگشت | response-transformer با remove.headers | server_header_transformation | response-rewrite با headers.remove | server_tokens off، proxy_hide_header |
| افزودن هدر | response-transformer با add.headers | response_headers_to_add | response-rewrite با headers.set | add_header ... always |
| اعتبارسنجی OpenAPI | OAS Validation نسخهٔ Enterprise | validator خارجی | request-validation با JSON Schema | داخلی ندارد |
| CORS | افزونهٔ cors؛ origin خالی یعنی همه | فیلتر CORS | افزونهٔ cors | add_header دستی |
پیکربندیهای مشخص در لبهٔ شبکه آمدهاند.
Gateهای CI/CD: اسکن وابستگی، SAST، DAST، رازها و قواعد بازبینی حیاتی
به زبان ساده: Pipeline وقتی وابستگی دارای آسیبپذیری شناختهشده، راز commitشده، الگوی مشکوک scanner، تست امنیتی ناموفق یا بازبینی توسط خود نویسنده وجود دارد، merge یا deploy را رد میکند.
بدفهمی رایج: «Scanner داریم، پس پوشش داریم.» هر ابزار یک چیز میبیند: SAST الگوی کد، SCA نسخهٔ وابستگی، اسکن راز رشته و DAST برنامهٔ در حال اجرا را. هیچکدام نبود بررسی مجوز در منطق کسبوکار را نمیبیند؛ تست و بازبینی برای همیناند. Scanner گزارشدهندهای که build را شکست نمیدهد فقط تزئین است.
تعریف:
- اسکن وابستگی (Dependency scanning / SCA): دستور
govulncheck ./...در Go که "only surfaces vulnerabilities that actually affect you, based on which functions in your code are transitively calling vulnerable functions"؛ وcomposer auditدر PHP با کد خروج "0 No issues; 1 Found packages matching dependency policies" و گزینههای--locked،--no-devو--abandoned=fail. Dependabot یا Renovate هم PR بهروزرسانی میسازند. - آزمون امنیتی ایستا (SAST): تحلیل source با gosec، staticcheck، semgrep و PHPStan/Psalm با قواعد امنیتی.
- اسکن رازها (Secrets scanning): gitleaks، با تعریف "a tool for detecting secrets like passwords, API keys, and tokens in git repos, files, and whatever else". دستور
gitleaks gitتاریخچه وgitleaks dirدایرکتوری را میبیند؛detectوprotectدر v8.19.0 منسوخ شدهاند. GitHub secret scanning و push protection هم در همین دستهاند. - آزمون امنیتی پویا (DAST): اسکن استقرار staging در حال اجرا؛ OWASP ZAP baseline با
zap-baseline.py -t <url>و خروج "0: Success"، "1: At least 1 FAIL"، "2: At least one WARN and no FAILs" و "3: Any other failure". ممیزی curl این فصل یک DAST کوچک و قطعی برای همین چکلیست است. - قواعد بازبینی کد (Code review rules): roadmap میگوید "Use a code review process and disregard self-approval". حفاظت شاخه با حداقل یک تأیید از فردی جز نویسنده، CODEOWNERS برای مسیر حساس مثل Middleware، auth و
config/cors.php، status check الزامی و نبود bypass مدیر. - تستها: بند "Audit your design and implementation with unit/integration tests"؛ هر Middleware این فصل تست دارد، در قالب تست واحد (Unit test) و تست یکپارچگی (Integration test).
1 PR opened -> gofmt/vet, go test -race, php artisan test (unit + integration)
2 -> gosec, semgrep, PHPStan (SAST)
3 -> govulncheck ./..., composer audit --locked (SCA, fail on findings)
4 -> gitleaks git --redact (secrets)
5 review -> CODEOWNERS approval, author cannot approve
6 merge -> deploy to staging -> audit.sh + ZAP baseline (DAST) -> promoteسازوکار runner، cache و محیطها در Pipelineهای CI/CD؛ فرایند مدلسازی تهدید، SBOM و پاسخ به رخداد در Secure SDLC است.
راهبرد بازگشت: Blue-green، Canary و Feature flag تکمیلی
به زبان ساده: قبل از deploy بدانید چطور در چند دقیقه برمیگردید، حتی اگر انتشار جدید پایگاه داده را تغییر داده باشد.
بدفهمی رایج: «بازگشت یعنی انتشار دوبارهٔ Image قبلی.» فقط وقتی درست است که نسخهٔ قبلی داده و پیام نوشتهشدهٔ نسخهٔ جدید را بفهمد. اصلاح امنیتی فاقد بازگشت امن، اصلاحی است که کسی جرئت انتشار سریعش را ندارد.
تعریف: roadmap: "Design a rollback solution for deployments." استقرار دو محیطی (Blue-green) دو محیط یکسان دارد؛ ترافیک را جابهجا و در شکست برمیگردانید. انتشار تدریجی آزمایشی (Canary) چند درصد ترافیک را به نسخهٔ تازه میدهد، خطا و سیگنال امنیتی را میسنجد، سپس سهم را زیاد میکند. پرچم قابلیت (Feature flag) کد را خاموش تحویل میدهد، رفتار را برای tenant روشن میکند و بدون deploy خاموش میکند؛ کلید توقف قابلیت آسیبپذیر هم هست. تغییر پایگاه داده از گسترش و جمعکردن (Expand-and-contract) استفاده میکند تا دو نسخه روی یک Schema کار کنند. جزئیات در راهبردهای استقرار و مهاجرت Schema.
فهرست API: هیچ endpoint بیحساب نماند تکمیلی
به زبان ساده: تمام Routeها در تمام نسخهها و محیطها، مسئولشان و محافظشان را فهرست کنید. endpoint ناشناخته هیچکدام از کنترلهای بالا را نمیگیرد.
بدفهمی رایج: «سند OpenAPI همان Inventory است.» سند فقط چیزهایی را دارد که کسی به یاد داشته بنویسد. فهرست API یا API inventory باید از استقرار واقعی، Routeهای کد، gateway و نامهای DNS، تولید و با سند مقایسه شود؛ وگرنه /v1 مستندنشده و میزبان staging همان موارد گمشدهاند.
تعریف: API9:2023 Improper Inventory Management نسخهٔ فراموششده، مثل /v1 زنده بعد از /v2، میزبان debug و staging و Route مستندنشده را پوشش میدهد. روش اجرایی: فهرست را از کد تولید کنید؛ تست go روی الگوهای ServeMux یا php artisan route:list --json. در CI با OpenAPI مقایسه کنید و بررسی کنید هر Route خارج از فهرست عمومی صریح Middleware احراز هویت دارد؛ بند "Check if all the endpoints are protected behind authentication". ماژول Go این فصل لایهٔ Authentication ندارد؛ آن در احراز هویت است. پس این تست اینجا پیاده نشده و روش را توضیح میدهیم، نه کد تحویلی. فرایند Inventory در OWASP API Security Top 10 و نسخهبندی در نسخهبندی API آمده است.
بندهای پردازش در فصلهای تخصصی: XML entity، آپلود، SSRF، کار async، UUID و stack تکمیلی
- تجزیه و گسترش موجودیت XML (XML entity parsing and expansion): بندهای "Disable entity parsing if you are parsing XML to avoid XXE attacks" و "Disable entity expansion if using XML, YML or any other language". امنترین گزینه نپذیرفتن XML است؛ اعتبارسنجی Content-Type همین کار را میکند. در غیر این صورت XXE در OWASP Top 10 را ببینید.
encoding/xmlدر Go موجودیت خارجی را resolve نمیکند. - آپلود از CDN (Uploads via CDN)، بند "Use CDN for file uploads": URL ازپیشامضاشده مستقیم به object storage، اسکن و سرو از دامنهٔ جدا؛ آپلود فایل، S3 و CDN.
- محافظ SSRF: هر API که URL کلاینت را fetch میکند به بررسی IP هنگام connect نیاز دارد؛ OWASP Top 10، SSRF.
- جلوگیری از انتظار HTTP برای دادهٔ حجیم: job را بپذیرید،
202 Acceptedو URL وضعیت بدهید و در worker پردازش کنید؛ تلاش مجدد به Idempotency در API نیاز دارد. - UUID بهجای شناسهٔ auto-increment و نبود شناسهٔ شخصی در URL: شناسهٔ حدسناپذیر پیمایش را کم میکند، ولی مجوز (Authorization) نیست. اصلاح اصلی بررسی شیء در BOLA است؛ OWASP API Security Top 10. Handler این فصل فقط شناسهٔ همشکل UUID میپذیرد و برای بقیه 404 میدهد.
- پشتهٔ غیرقابل اجرا (Non-executable stack): ویژگی compiler و OS، مثل NX bit و
-z noexecstack، که برای binary Go و buildهای مدرن PHP پیشفرض روشن است. Hardening کانتینر، root فقطخواندنی و ممنوعیت privilege تازه، در امنیت کانتینر است.
فصلهای تخصصی: Authentication، JWT، OAuth، محدودیت نرخ و TLS تکمیلی
- احراز هویت (Authentication) با سازوکار استاندارد، بدون رمزنگاری دستساز، سقف تلاش و jail: گذرواژه، MFA و نشست.
- JWT با راز قوی، الگوریتم ثابت سمت سرور، TTL کوتاه و payload کوچک بدون راز: JWT عمیق.
- OAuth با تطبیق دقیق
redirect_uri، code flow و PKCE بهجایresponse_type=token،stateو scope: OAuth 2.0، OIDC و SSO. - کنترل نرخ (Throttling) با token bucket، sliding window، سقف توزیعشده و 429 همراه
Retry-After: محدودیت نرخ. - TLS و HSTS، نسخه، cipher suite، گواهی و HSTS preload: TLS در عمل و تکامل HTTP؛ ارتباط سرویسها در Mutual TLS.
- کلید API، امضای HMAC و فهرست IP مجاز برای API خصوصی: کلیدهای API، امضای درخواست و webhook.
سازوکار
ترتیب Middleware و دلیل اهمیتش
harden.Chain(h, a, b, c) به شکل a(b(c(h))) اجرا میشود. اولین میانافزار (Middleware) درخواست را اول و پاسخ را آخر میبیند. ترتیب app.New یک قاعده دارد: هر چیزی که باید روی پاسخ ردشده هم اعمال شود، بیرون لایهٔ ردکننده قرار میگیرد.
| جایگاه | Middleware | دلیل |
|---|---|---|
| 1 | RequestID | شناسه پیش از هر ثبت لاگ یا رد درخواست باید موجود باشد |
| 2 | AccessLog | تمام نتیجهها، شامل رد و Panic تبدیلشده به 500، ثبت میشوند |
| 3 | SecurityHeaders | هدر پیش از نوشتن لایهٔ داخلی تنظیم؛ اثرانگشت هنگام نوشتن حذف میشود |
| 4 | ProblemErrors | خطای متن سادهٔ ServeMux و TimeoutHandler پاییندست را بازنویسی میکند |
| 5 | Recover | Panic تمام لایههای پایین، حتی Panic دوبارهپرتابشدهٔ TimeoutHandler را میگیرد |
| 6 | CORS | Preflight با OPTIONS قبل از رد احتمالی در بررسی متد و نوع رسانه پاسخ میگیرد |
| 7 | AllowMethods | رد عمومی کمهزینه با 405 پیش از هر خواندن |
| 8 | JSONOnly | پاسخ 406/415 پیش از خواندن بدنه |
| 9 | LimitBody | پیش از دستزدن هر reader بدنه را میپوشاند؛ writer واقعی net/http را بیرون میکشد |
| 10 | WithHandlerTimeout | Timeout و لغو context برای routing و handler |
| 11 | ServeMux | الگوی متد و مقدار path؛ برای بقیه 404/405 |
تستها دو دام را میگیرند. Wrapper روی ResponseWriter بدون Unwrap()، قابلیتهای http.ResponseController و پیام بستن MaxBytesReader را پنهان میکند؛ TestLimitClosesConnectionThroughWrappers اگر LimitBody، writer پوشیده را بدهد شکست میخورد. همچنین Middleware هدر داخل Recover یا بعد از router، پاسخ 500 و 404 را بدون هدر میگذارد؛ TestEveryResponseIsHardened این را ثابت میکند.
کدها، نامها و فرستندهٔ هرکدام
| کد | نام RFC 9110 | Go http.StatusText | منبع Laravel / Symfony | فرستنده در این فصل |
|---|---|---|---|---|
| 400 | Bad Request | Bad Request | BadRequestHttpException | DecodeJSON و method override |
| 403 | Forbidden | Forbidden | AuthorizationException → 403 | CORS برای Preflight بیگانه |
| 404 | Not Found | Not Found | NotFoundHttpException، ModelNotFoundException | ServeMux و فهرست مجاز شناسه |
| 405 | Method Not Allowed | Method Not Allowed | MethodNotAllowedHttpException با Allow | AllowMethods، ServeMux |
| 406 | Not Acceptable | Not Acceptable | سفارشی، EnforceJsonApi | JSONOnly |
| 408 | Request Timeout | Request Timeout | مصداق ندارد | client_header_timeout در Nginx؛ Go بیپاسخ میبندد |
| 413 | Content Too Large | Request Entity Too Large | PostTooLargeException؛ اینجا بررسی نشده | LimitBody، DecodeJSON |
| 415 | Unsupported Media Type | Unsupported Media Type | سفارشی، EnforceJsonApi | JSONOnly |
| 422 | Unprocessable Content | Unprocessable Entity | ValidationException | validate() در handler |
| 429 | Too Many Requests | Too Many Requests | ThrottleRequestsException | Rate limiter در فصل مرتبط |
| 431 | Request Header Fields Too Large | Request Header Fields Too Large | مصداق ندارد | سرور Go هنگام عبور از MaxHeaderBytes |
| 500 | Internal Server Error | Internal Server Error | هر Throwable گرفتهنشده | Recover |
| 501 | Not Implemented | Not Implemented | مصداق ندارد | سرور Go برای Transfer-Encoding پشتیبانینشده |
| 503 | Service Unavailable | Service Unavailable | جریان MaintenanceModeException | http.TimeoutHandler |
متن خطاهایی که باید بشناسید: http: request body too large از *http.MaxBytesError؛ json: unknown field "price" از DisallowUnknownFields که به متن امن unknown field "price" نگاشت میشود؛ و http: Handler timeout از http.ErrHandlerTimeout که Write در handler پس از فعالشدن TimeoutHandler برمیگرداند.
تنظیمهای دقیق
| تنظیم | محل | مقدار این فصل |
|---|---|---|
http.MaxBytesReader | Handler در Go / LimitBody | ۶۴ KiB؛ در تست ۱ KiB |
Decoder.DisallowUnknownFields | Go encoding/json | روشن |
MaxJSONDepth | harden | 16؛ سقف داخلی stdlib برابر 10000 |
Server.ReadHeaderTimeout | Go | 5s |
Server.ReadTimeout | Go | 10s |
Server.WriteTimeout | Go | 15s |
Server.IdleTimeout | Go | 60s |
Server.MaxHeaderBytes | Go | ۳۲ KiB؛ پیشفرض ۱ MB |
http.TimeoutHandler | Go | 8s؛ در سرور آزمایشگاه 1s |
max-age در HSTS | هر دو | 63072000، معادل ۲ سال؛ includeSubDomains؛ فقط TLS |
APP_DEBUG، APP_ENV | .env در Laravel | false، production |
expose_php، display_errors | php.ini | Off، Off |
post_max_size | php.ini | بالاتر از بزرگترین سقف Route؛ ValidatePostSize عمومی |
config/cors.php | Laravel | allowed_origins صریح، supports_credentials برابر true، max_age برابر 600 |
trustProxies(at: ...) | bootstrap/app.php در Laravel | فقط CIDR متعادلکنندهٔ بار |
client_max_body_size | Nginx | 64k برای locationهای JSON |
client_header_timeout، client_body_timeout | Nginx | 10s، 10s |
server_tokens | Nginx | off |
allowed_payload_size، size_unit | request-size-limiting در Kong | 64، kilobytes |
request_headers_timeout | Envoy HCM | 5s |
max_body_size | client-control در APISIX | 65536 |
پیشفرض محصولها که باید تغییر کنند
| محصول | پیشفرض | حالت سختشده |
|---|---|---|
Go http.Server | تمام Timeoutها صفر؛ با ReadTimeout صفر، fallback هدر و بیکاری هم صفر و همه نامحدودند؛ هدر ۱ MB، بدنه نامحدود | harden.NewServer و LimitBody |
Go http.ListenAndServe | http.Server صفر میسازد | برای listener عمومی هرگز استفاده نکنید |
Laravel config/cors.php | allowed_origins برابر *، credentials برابر false | origin صریح |
Laravel config/app.php | 'debug' => (bool) env('APP_DEBUG', false) | حفظ شود؛ در .env محیط Production هرگز true نگذارید |
| PHP | expose_php در بسیاری buildهای توزیعها روشن است؛ تکتک بررسی نشدهاند | Off |
| Nginx | client_max_body_size 1m، server_tokens on، client_header_timeout 60s | سقف هر location، مقدار off و Timeout کوتاهتر |
Kong request-size-limiting | ۱۲۸ MB، require_content_length برابر false | سقف هر Route؛ require_content_length جایی که کلاینت همیشه طول میفرستد |
Kong cors | origins خالی یعنی تمام originها | origin صریح |
| Envoy HCM | server_header_transformation: OVERWRITE با server: envoy؛ request_headers_timeout خاموش؛ stream_idle_timeout برابر ۵ دقیقه | تعیین Timeout هدر؛ عبور یا خالیکردن هدر server |
APISIX request-validation | رد با 400 | حفظ شود؛ rejected_msg را رشتهٔ Problem JSON کنید |
Go
قبل: یک handler، بدون چکلیست
نسخهٔ ساده در حالت موفق کار میکند و ۲۹ مورد از ۳۱ بررسی ممیزی را شکست میدهد؛ آزمایشگاه. هر متد سفارش را میخواند؛ تمام رکورد با شمارهٔ کارت serialise میشود؛ Accept در Content-Type کپی میشود؛ بدنه نامحدود است؛ handler مربوط به Panic Stack trace را چاپ میکند؛ خط لاگ URL و هدر Authorization دارد و Timeout نداریم.
// Package before is the same orders API written the way many first versions
// are: it works, and it fails almost every item of the checklist.
package before
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"runtime/debug"
"strings"
)
type order struct {
ID string `json:"id"`
SKU string `json:"sku"`
Quantity int `json:"quantity"`
CardNumber string `json:"card_number"` // the whole record is serialised
RiskScore float64 `json:"risk_score"`
}
// New returns the naive handler. Debug output is "temporarily" on.
func New() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "orders-api/0.9.1 (go1.22.1; linux)")
w.Header().Set("X-Powered-By", "academy-framework/2.3")
defer func() {
if v := recover(); v != nil {
// "Helpful" error page: the panic text and the whole stack.
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "panic: %v\n\n%s", v, debug.Stack())
}
}()
// Logs the full URL, query string and Authorization header.
log.Printf("%s %s auth=%q", r.Method, r.URL.String(), r.Header.Get("Authorization"))
switch {
case r.URL.Path == "/v1/lab/panic":
panic("db: connection refused at 10.0.3.7:5432 user=orders_rw")
case strings.HasPrefix(r.URL.Path, "/v1/orders/") && r.Method != http.MethodPost:
// Any method reads the order: GET, TRACE, DELETE, FOO.
id := strings.TrimPrefix(r.URL.Path, "/v1/orders/")
o := order{ID: id, SKU: "MUG-01", Quantity: 2, CardNumber: "4111111111111111", RiskScore: 0.12}
w.Header().Set("Content-Type", r.Header.Get("Accept")) // copies Accept
_ = json.NewEncoder(w).Encode(o)
case r.URL.Path == "/v1/orders":
// No size limit, any Content-Type, unknown fields ignored.
body, _ := io.ReadAll(r.Body)
var o order
if err := json.Unmarshal(body, &o); err != nil {
http.Error(w, "json.Unmarshal into before.order: "+err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK) // 200 instead of 201
_ = json.NewEncoder(w).Encode(o)
default:
w.WriteHeader(http.StatusOK) // "not found" as an empty 200
}
})
}package before
import (
"net/http/httptest"
"strings"
"testing"
)
// These tests pass: they document what the naive version gets wrong.
func TestBeforeFailsTheChecklist(t *testing.T) {
h := New()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("TRACE", "/v1/orders/42", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "4111111111111111") {
t.Fatalf("expected TRACE to be served with the full card number")
}
if rec.Header().Get("Server") == "" || rec.Header().Get("X-Powered-By") == "" {
t.Fatalf("expected fingerprinting headers")
}
if rec.Header().Get("X-Content-Type-Options") != "" {
t.Fatalf("expected no security headers")
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/v1/lab/panic", nil))
if !strings.Contains(rec.Body.String(), "goroutine") || !strings.Contains(rec.Body.String(), "10.0.3.7") {
t.Fatalf("expected the stack trace and the internal address in the body")
}
rec = httptest.NewRecorder()
big := `{"sku":"` + strings.Repeat("A", 1<<20) + `"}`
r := httptest.NewRequest("POST", "/v1/orders", strings.NewReader(big))
r.Header.Set("Content-Type", "text/plain")
h.ServeHTTP(rec, r)
if rec.Code != 200 {
t.Fatalf("expected a 1 MiB text/plain body to be accepted, got %d", rec.Code)
}
}بعد: زنجیرهٔ Middleware
یک package به نام harden، یک فایل برای هر گروه چکلیست و همگی با کتابخانهٔ استاندارد (go 1.24). زنجیره و helper بازکردن wrapper:
// Package harden is the API security checklist as a Go middleware chain.
// Each file implements one checklist group; Chain wires them in order.
package harden
import "net/http"
// Middleware wraps a handler.
type Middleware func(http.Handler) http.Handler
// Chain applies middlewares so that the first one listed is the outermost:
// Chain(h, a, b, c) serves a(b(c(h))).
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
// unwrapper is implemented by every ResponseWriter wrapper in this package,
// so http.ResponseController and MaxBytesReader can reach the real writer.
type unwrapper interface{ Unwrap() http.ResponseWriter }
// innermost returns the writer created by net/http, below all wrappers.
func innermost(w http.ResponseWriter) http.ResponseWriter {
for {
u, ok := w.(unwrapper)
if !ok {
return w
}
w = u.Unwrap()
}
}خروجی: هدرهای امنیتی و حذف اثرانگشت هنگام نوشتن:
package harden
import (
"net/http"
"strconv"
)
// HeaderOptions configures SecurityHeaders.
type HeaderOptions struct {
// HSTSMaxAge in seconds; 0 disables HSTS. RFC 6797 section 7.2: the header
// MUST NOT be sent over non-secure transport, so it is only set on TLS
// requests (or when TrustForwardedProto and X-Forwarded-Proto is https).
HSTSMaxAge int
TrustForwardedProto bool
}
// apiHeaders is the OWASP REST Security Cheat Sheet set for JSON APIs that
// may be read by browsers.
var apiHeaders = map[string]string{
"Cache-Control": "no-store",
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer",
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()",
}
// fingerprintHeaders are removed at write time, after every inner handler
// (or a reverse-proxied upstream) had its chance to set them.
var fingerprintHeaders = []string{"Server", "X-Powered-By", "X-AspNet-Version", "X-Runtime"}
// SecurityHeaders sets the output headers of the checklist and strips
// fingerprinting headers.
func SecurityHeaders(opt HeaderOptions) Middleware {
hsts := ""
if opt.HSTSMaxAge > 0 {
hsts = "max-age=" + strconv.Itoa(opt.HSTSMaxAge) + "; includeSubDomains"
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
for k, v := range apiHeaders {
h.Set(k, v)
}
if hsts != "" && isHTTPS(r, opt.TrustForwardedProto) {
h.Set("Strict-Transport-Security", hsts)
}
next.ServeHTTP(&stripWriter{ResponseWriter: w}, r)
})
}
}
func isHTTPS(r *http.Request, trustProxy bool) bool {
if r.TLS != nil {
return true
}
return trustProxy && r.Header.Get("X-Forwarded-Proto") == "https"
}
type stripWriter struct {
http.ResponseWriter
done bool
}
func (s *stripWriter) strip() {
if s.done {
return
}
s.done = true
for _, k := range fingerprintHeaders {
s.Header().Del(k)
}
}
func (s *stripWriter) WriteHeader(code int) {
s.strip()
s.ResponseWriter.WriteHeader(code)
}
func (s *stripWriter) Write(b []byte) (int, error) {
s.strip()
return s.ResponseWriter.Write(b)
}
func (s *stripWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }خروجی: Problem Details مطابق RFC 9457 و بازنویسی خطای متن سادهٔ خود net/http:
package harden
import (
"encoding/json"
"net/http"
"strings"
)
// Problem is an RFC 9457 problem details object. RequestID and Errors are
// extension members; nothing else about the failure leaves the server.
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
RequestID string `json:"request_id,omitempty"`
Errors map[string]string `json:"errors,omitempty"`
}
// HTTPError is returned by helpers (DecodeJSON) and turned into a Problem.
type HTTPError struct {
Status int
Detail string
Errors map[string]string
}
func (e *HTTPError) Error() string { return e.Detail }
// RFC 9110 names; net/http.StatusText still uses the older RFC 7231 phrases
// for 413 ("Request Entity Too Large") and 422 ("Unprocessable Entity").
var titles = map[int]string{
http.StatusRequestEntityTooLarge: "Content Too Large",
http.StatusUnprocessableEntity: "Unprocessable Content",
}
func title(status int) string {
if t, ok := titles[status]; ok {
return t
}
return http.StatusText(status)
}
// WriteProblem writes an application/problem+json response. The detail must
// be safe for the client: no stack traces, SQL, file paths or secrets.
func WriteProblem(w http.ResponseWriter, r *http.Request, status int, detail string, fieldErrors map[string]string) {
p := Problem{
Type: "about:blank",
Title: title(status),
Status: status,
Detail: detail,
RequestID: RequestIDFrom(r.Context()),
Errors: fieldErrors,
}
h := w.Header()
h.Del("Content-Length")
h.Set("Content-Type", "application/problem+json")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Cache-Control", "no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(p)
}
// WriteError maps an error from a helper to a problem response.
func WriteError(w http.ResponseWriter, r *http.Request, err error) {
if he, ok := err.(*HTTPError); ok {
WriteProblem(w, r, he.Status, he.Detail, he.Errors)
return
}
WriteProblem(w, r, http.StatusInternalServerError, "internal error", nil)
}
// ProblemErrors rewrites plain-text error responses produced by net/http
// itself (ServeMux 404/405 via http.Error, TimeoutHandler 503) into problem
// details, so every rejection has the same shape and no default text leaks.
func ProblemErrors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(&problemWriter{ResponseWriter: w, r: r}, r)
})
}
type problemWriter struct {
http.ResponseWriter
r *http.Request
wrote bool
swallowing bool
}
func (p *problemWriter) WriteHeader(code int) {
if p.wrote {
return
}
p.wrote = true
ct := p.Header().Get("Content-Type")
if code >= 400 && (ct == "" || strings.HasPrefix(ct, "text/plain")) {
p.swallowing = true
WriteProblem(p.ResponseWriter, p.r, code, "", nil)
return
}
p.ResponseWriter.WriteHeader(code)
}
func (p *problemWriter) Write(b []byte) (int, error) {
if !p.wrote {
p.WriteHeader(http.StatusOK)
}
if p.swallowing {
return len(b), nil // drop net/http's default text body
}
return p.ResponseWriter.Write(b)
}
func (p *problemWriter) Unwrap() http.ResponseWriter { return p.ResponseWriter }ورودی: فهرست مجاز متد HTTP:
package harden
import (
"net/http"
"strings"
)
// AllowMethods is the global HTTP method allow-list. Anything else (TRACE,
// CONNECT, made-up verbs, method-override tricks) gets 405 with an Allow
// header, as RFC 9110 section 15.5.6 requires. Per-route methods are
// enforced again by ServeMux patterns such as "POST /v1/orders".
func AllowMethods(methods ...string) Middleware {
allowed := make(map[string]bool, len(methods))
for _, m := range methods {
allowed[m] = true
}
allow := strings.Join(methods, ", ")
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !allowed[r.Method] {
w.Header().Set("Allow", allow)
WriteProblem(w, r, http.StatusMethodNotAllowed, "method not allowed", nil)
return
}
// Method override headers let a POST pretend to be a DELETE in
// some frameworks; this API never honours them.
if r.Header.Get("X-HTTP-Method-Override") != "" || r.Header.Get("X-HTTP-Method") != "" {
WriteProblem(w, r, http.StatusBadRequest, "method override headers are not accepted", nil)
return
}
next.ServeHTTP(w, r)
})
}
}ورودی: اعتبارسنجی Content-Type و Accept:
package harden
import (
"mime"
"net/http"
"regexp"
"strconv"
"strings"
)
// JSONOnly enforces the content contract of a JSON API:
// - a request that carries a body must declare Content-Type
// application/json (charset utf-8 only), else 415 Unsupported Media Type;
// - the Accept header, if present, must give application/json a quality
// above zero via its most specific matching range, else 406 Not
// Acceptable.
//
// The response Content-Type is always set by the server, never copied from
// the Accept header.
func JSONOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !acceptsJSON(r.Header.Values("Accept")) {
WriteProblem(w, r, http.StatusNotAcceptable, "this API only produces application/json", nil)
return
}
if hasBody(r) {
mt, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
cs := strings.ToLower(params["charset"])
if err != nil || mt != "application/json" || (cs != "" && cs != "utf-8") {
// RFC 9110 15.5.16: Accept in a 415 response lists what would work.
w.Header().Set("Accept", "application/json")
WriteProblem(w, r, http.StatusUnsupportedMediaType, "send application/json", nil)
return
}
}
next.ServeHTTP(w, r)
})
}
// hasBody reports whether the request carries content: a positive
// Content-Length, or an unknown length (chunked transfer coding).
func hasBody(r *http.Request) bool {
return r.ContentLength > 0 || r.ContentLength == -1
}
// acceptsJSON applies RFC 9110 section 12.5.1 for the one representation
// this API produces, application/json (UTF-8, no other parameters):
// - a range matches only if its type/subtype matches AND every non-q
// parameter matches the representation, so "application/json;profile=v2"
// does not match plain JSON (charset=utf-8 does: JSON is UTF-8);
// - among matching ranges the most specific wins (type/subtype with
// parameters > type/subtype > type/* > */*), and its q is the quality;
// - q must follow the RFC grammar (0 to 1, at most three decimals);
// a malformed weight makes that range ignored;
// - q=0 means "not acceptable".
//
// application/problem+json does not count: success bodies are
// application/json, so a client that only accepts problem documents gets 406.
func acceptsJSON(values []string) bool {
if len(values) == 0 {
return true // no Accept header means any media type is acceptable
}
best, q := -1, 0.0 // specificity of the best match so far, and its q
for _, v := range values {
for _, part := range strings.Split(v, ",") {
mt, params, err := mime.ParseMediaType(strings.TrimSpace(part))
if err != nil {
continue
}
spec := -1
switch mt {
case "application/json":
spec = 2
case "application/*":
spec = 1
case "*/*":
spec = 0
}
if spec < 0 {
continue
}
f := 1.0
for k, pv := range params {
switch {
case k == "q":
if !qValue.MatchString(pv) {
spec = -1 // malformed weight: ignore this range
} else {
f, _ = strconv.ParseFloat(pv, 64)
}
case spec == 2 && k == "charset" && strings.EqualFold(pv, "utf-8"):
spec = 3 // matches our representation and is more specific
default:
spec = -1 // a parameter our representation does not have
}
if spec < 0 {
break
}
}
if spec < 0 || spec < best {
continue
}
if spec > best || f > q { // more specific wins; same specificity: highest q
best, q = spec, f
}
}
}
return best >= 0 && q > 0
}
// qValue is the RFC 9110 section 12.4.2 weight grammar:
// qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
var qValue = regexp.MustCompile(`^(0(\.[0-9]{0,3})?|1(\.0{0,3})?)$`)ورودی: سقف اندازهٔ بدنه:
package harden
import "net/http"
// LimitBody caps the request body. A declared Content-Length above the limit
// is rejected before the handler runs; a chunked or lying body is cut by
// http.MaxBytesReader, which makes the decoder fail with *http.MaxBytesError
// (mapped to 413 by DecodeJSON).
func LimitBody(maxBytes int64) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ContentLength > maxBytes {
w.Header().Set("Connection", "close")
WriteProblem(w, r, http.StatusRequestEntityTooLarge, "request body too large", nil)
return
}
// Pass the writer created by net/http: MaxBytesReader can only
// tell the server to close the connection after the limit is
// hit when it sees that writer, not one of our wrappers.
r.Body = http.MaxBytesReader(innermost(w), r.Body, maxBytes)
next.ServeHTTP(w, r)
})
}
}ورودی: decode سختگیرانهٔ JSON با سقف عمق:
package harden
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
)
// MaxJSONDepth is far below encoding/json's own hard limit (10000 levels in
// encoding/json/scanner.go); no request body of this API nests deeper.
const MaxJSONDepth = 16
// DecodeJSON reads one JSON object into dst with strict rules: the body is
// already capped by LimitBody, nesting is limited, unknown fields and
// trailing data are rejected. Errors are *HTTPError with a client-safe
// detail and the right status (400, 413).
func DecodeJSON(r *http.Request, dst any) error {
body, err := io.ReadAll(r.Body)
if err != nil {
var mbe *http.MaxBytesError
if errors.As(err, &mbe) {
return &HTTPError{Status: http.StatusRequestEntityTooLarge, Detail: "request body too large"}
}
return &HTTPError{Status: http.StatusBadRequest, Detail: "could not read body"}
}
if err := checkDepth(body, MaxJSONDepth); err != nil {
return err
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return &HTTPError{Status: http.StatusBadRequest, Detail: clientSafe(err)}
}
if dec.More() {
return &HTTPError{Status: http.StatusBadRequest, Detail: "body must contain a single JSON value"}
}
if _, err := dec.Token(); err != io.EOF {
return &HTTPError{Status: http.StatusBadRequest, Detail: "body must contain a single JSON value"}
}
return nil
}
// checkDepth walks the tokens once and rejects documents nested deeper than
// max, before any allocation into Go values.
func checkDepth(body []byte, max int) error {
dec := json.NewDecoder(bytes.NewReader(body))
depth := 0
for {
tok, err := dec.Token()
if err == io.EOF {
return nil
}
if err != nil {
return &HTTPError{Status: http.StatusBadRequest, Detail: "malformed JSON"}
}
if d, ok := tok.(json.Delim); ok {
switch d {
case '{', '[':
depth++
if depth > max {
return &HTTPError{Status: http.StatusBadRequest, Detail: "JSON nested too deeply"}
}
case '}', ']':
depth--
}
}
}
}
// clientSafe keeps the useful part of a decode error (which field, which
// type) and drops Go type names of internal structs.
func clientSafe(err error) string {
var ute *json.UnmarshalTypeError
var se *json.SyntaxError
switch {
case errors.As(err, &ute):
return "field " + ute.Field + " has the wrong type"
case errors.As(err, &se), errors.Is(err, io.ErrUnexpectedEOF):
return "malformed JSON"
case strings.HasPrefix(err.Error(), "json: unknown field "):
return "unknown field " + strings.TrimPrefix(err.Error(), "json: unknown field ")
case errors.Is(err, io.EOF):
return "empty body"
default:
return "invalid JSON body"
}
}پردازش: Panic به خطای عمومی 500 بدل و Stack trace وارد لاگ میشود:
package harden
import (
"fmt"
"log/slog"
"net/http"
"runtime/debug"
)
// Recover turns a panic into a 500 problem response. The stack trace goes to
// the server log with the request id; the client only sees the id, which
// support can look up. With debug on (never in production, see Config) the
// panic value is added to the detail.
func Recover(log *slog.Logger, debugMode bool) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
v := recover()
if v == nil {
return
}
if v == http.ErrAbortHandler {
panic(v) // net/http's own signal to abort the response
}
log.ErrorContext(r.Context(), "panic",
slog.String("request_id", RequestIDFrom(r.Context())),
slog.String("panic", fmt.Sprint(v)),
slog.String("stack", string(debug.Stack())),
)
detail := "internal error"
if debugMode {
detail = fmt.Sprint(v)
}
WriteProblem(w, r, http.StatusInternalServerError, detail, nil)
}()
next.ServeHTTP(w, r)
})
}
}پردازش: محافظ خاموشی debug:
package harden
import (
"errors"
"fmt"
)
// Config is the part of the service configuration the checklist cares about.
type Config struct {
Env string // "production", "staging", "local"
Debug bool // verbose errors (panic text in problem details)
ExposePprof bool // net/http/pprof on the public listener
MaxBodyBytes int64
}
// ErrUnsafeConfig is returned by Validate; main refuses to start on it.
var ErrUnsafeConfig = errors.New("unsafe production configuration")
// Validate is the debug-off guard: a production process with debug output,
// profiling on the public port or no body limit does not start at all.
func (c Config) Validate() error {
if c.Env != "production" {
return nil
}
switch {
case c.Debug:
return fmt.Errorf("%w: debug mode is on", ErrUnsafeConfig)
case c.ExposePprof:
return fmt.Errorf("%w: pprof is exposed", ErrUnsafeConfig)
case c.MaxBodyBytes <= 0:
return fmt.Errorf("%w: no request body size limit", ErrUnsafeConfig)
}
return nil
}پردازش: Timeoutهای سرور و Timeout handler:
package harden
import (
"net/http"
"time"
)
// Timeouts for an internet-facing JSON API. In http.Server a zero
// ReadTimeout or WriteTimeout means no timeout, and a zero ReadHeaderTimeout
// or IdleTimeout falls back to ReadTimeout; set all of them explicitly.
type Timeouts struct {
ReadHeader time.Duration // headers must arrive in this time (slowloris)
Read time.Duration // whole request, including the body
Write time.Duration // from end of headers to end of response
Idle time.Duration // keep-alive wait for the next request
Handler time.Duration // http.TimeoutHandler: 503 after this
}
// DefaultTimeouts are conservative values for small JSON requests.
var DefaultTimeouts = Timeouts{
ReadHeader: 5 * time.Second,
Read: 10 * time.Second,
Write: 15 * time.Second,
Idle: 60 * time.Second,
Handler: 8 * time.Second,
}
// NewServer returns an http.Server with every timeout and the header size
// limit set. Handler deadlines are applied by WithHandlerTimeout.
func NewServer(addr string, h http.Handler, t Timeouts) *http.Server {
return &http.Server{
Addr: addr,
Handler: h,
ReadHeaderTimeout: t.ReadHeader,
ReadTimeout: t.Read,
WriteTimeout: t.Write,
IdleTimeout: t.Idle,
MaxHeaderBytes: 32 << 10, // 32 KiB instead of the 1 MB default
}
}
// WithHandlerTimeout cancels the request context and answers 503 Service
// Unavailable when the handler runs longer than d. The body is rewritten
// into a problem by ProblemErrors.
func WithHandlerTimeout(d time.Duration) Middleware {
return func(next http.Handler) http.Handler {
return http.TimeoutHandler(next, d, "")
}
}مرورگر: CORS با فهرست مجاز صریح:
package harden
import (
"net/http"
"strings"
)
// CORSOptions is an explicit allow-list. There is no wildcard mode: an API
// that sends cookies or Authorization from a browser must name its origins.
type CORSOptions struct {
Origins []string // exact origins, e.g. "https://shop.example"
Methods []string // methods a preflight may ask for
Headers []string // request headers a preflight may ask for
AllowCredentials bool
MaxAgeSeconds string
}
// CORS answers preflights and adds CORS headers for allowed origins only.
// Requests without an Origin header (curl, server-to-server) pass through
// untouched: CORS is a browser read permission, not authentication.
func CORS(o CORSOptions) Middleware {
origins := map[string]bool{}
for _, v := range o.Origins {
origins[v] = true
}
methods := map[string]bool{}
for _, m := range o.Methods {
methods[m] = true
}
headers := map[string]bool{}
for _, h := range o.Headers {
headers[strings.ToLower(h)] = true
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
next.ServeHTTP(w, r)
return
}
h := w.Header()
h.Add("Vary", "Origin") // caches must key on Origin
preflight := r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != ""
if !origins[origin] {
if preflight {
WriteProblem(w, r, http.StatusForbidden, "origin not allowed", nil)
return
}
next.ServeHTTP(w, r) // no CORS headers: the browser hides the response
return
}
h.Set("Access-Control-Allow-Origin", origin) // echo only after the allow-list check
if o.AllowCredentials {
h.Set("Access-Control-Allow-Credentials", "true")
}
if !preflight {
h.Set("Access-Control-Expose-Headers", RequestIDHeader)
next.ServeHTTP(w, r)
return
}
if !methods[r.Header.Get("Access-Control-Request-Method")] {
WriteProblem(w, r, http.StatusForbidden, "method not allowed for CORS", nil)
return
}
for _, rh := range strings.Split(r.Header.Get("Access-Control-Request-Headers"), ",") {
if rh = strings.TrimSpace(strings.ToLower(rh)); rh != "" && !headers[rh] {
WriteProblem(w, r, http.StatusForbidden, "header not allowed for CORS", nil)
return
}
}
h.Set("Access-Control-Allow-Methods", strings.Join(o.Methods, ", "))
h.Set("Access-Control-Allow-Headers", strings.Join(o.Headers, ", "))
if o.MaxAgeSeconds != "" {
h.Set("Access-Control-Max-Age", o.MaxAgeSeconds)
}
w.WriteHeader(http.StatusNoContent)
})
}
}پایش: Request id و access log با دادهٔ حساس پوشاندهشده:
package harden
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
"regexp"
)
type ctxKey int
const requestIDKey ctxKey = 0
// RequestIDHeader is echoed on every response and logged on every line.
const RequestIDHeader = "X-Request-ID"
// An incoming id is only reused when it comes from a trusted proxy and is
// short and boring: never let a client write arbitrary bytes into your logs.
var validID = regexp.MustCompile(`^[A-Za-z0-9._-]{8,64}$`)
// RequestID assigns a request id (the correlation id of this hop). With
// trustIncoming, a well-formed id set by the gateway is kept so one id
// follows the call across services.
func RequestID(trustIncoming bool) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get(RequestIDHeader)
if !trustIncoming || !validID.MatchString(id) {
id = newID()
}
w.Header().Set(RequestIDHeader, id)
ctx := context.WithValue(r.Context(), requestIDKey, id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// RequestIDFrom returns the id stored by RequestID, or "".
func RequestIDFrom(ctx context.Context) string {
id, _ := ctx.Value(requestIDKey).(string)
return id
}
func newID() string {
b := make([]byte, 12)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}package harden
import (
"io"
"log/slog"
"net/http"
"strings"
"time"
)
// sensitiveKeys are attribute names whose values never reach a log line.
var sensitiveKeys = map[string]bool{
"authorization": true, "cookie": true, "set-cookie": true, "password": true,
"token": true, "access_token": true, "refresh_token": true, "api_key": true,
"secret": true, "card_number": true, "email": true,
}
// NewLogger returns a JSON slog logger whose handler redacts sensitive
// attributes wherever they appear, including inside groups.
func NewLogger(w io.Writer) *slog.Logger {
return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if sensitiveKeys[strings.ToLower(a.Key)] {
return slog.String(a.Key, "[REDACTED]")
}
return a
},
}))
}
// AccessLog writes one structured line per request: request id, method,
// path WITHOUT the query string (queries carry tokens and PII), status,
// size and duration. Bodies and headers are never logged.
func AccessLog(log *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(sw, r)
level := slog.LevelInfo
if sw.status >= 500 {
level = slog.LevelError
} else if sw.status == http.StatusUnauthorized || sw.status == http.StatusForbidden {
level = slog.LevelWarn // feed for brute-force and BOLA alerts
}
log.LogAttrs(r.Context(), level, "http_request",
slog.String("request_id", RequestIDFrom(r.Context())),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", sw.status),
slog.Int("bytes", sw.bytes),
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
)
})
}
}
type statusWriter struct {
http.ResponseWriter
status int
bytes int
wrote bool
}
func (s *statusWriter) WriteHeader(code int) {
if !s.wrote {
s.status, s.wrote = code, true
}
s.ResponseWriter.WriteHeader(code)
}
func (s *statusWriter) Write(b []byte) (int, error) {
s.wrote = true
n, err := s.ResponseWriter.Write(b)
s.bytes += n
return n, err
}
func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }API متصلکنندهٔ همهٔ بخشها، همراه DTO خروجی و Validation با فهرست مجاز:
// Package app is a small orders API wired through the hardening chain.
package app
import (
"encoding/json"
"log/slog"
"net/http"
"regexp"
"time"
"academy/api-security-hardening-checklist/harden"
)
// Options configures New.
type Options struct {
Config harden.Config
Log *slog.Logger
Timeouts harden.Timeouts
Origins []string
Lab bool // registers /v1/lab/* routes used by the audit script
}
// New returns the API with the full middleware chain, outermost first.
func New(o Options) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.HandleFunc("GET /v1/orders/{id}", getOrder)
mux.HandleFunc("POST /v1/orders", createOrder)
if o.Lab {
mux.HandleFunc("GET /v1/lab/panic", func(http.ResponseWriter, *http.Request) {
panic("db: connection refused at 10.0.3.7:5432 user=orders_rw")
})
mux.HandleFunc("GET /v1/lab/slow", func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(5 * time.Second):
writeJSON(w, http.StatusOK, map[string]string{"status": "late"})
case <-r.Context().Done(): // TimeoutHandler cancelled us
}
})
}
return harden.Chain(mux,
harden.RequestID(false), // monitoring: correlation id first
harden.AccessLog(o.Log), // monitoring: one redacted line per request
harden.SecurityHeaders(harden.HeaderOptions{HSTSMaxAge: 63072000}), // output
harden.ProblemErrors, // output: RFC 9457 for net/http's own errors
harden.Recover(o.Log, o.Config.Debug), // processing: no stack traces out
harden.CORS(harden.CORSOptions{ // browsers: explicit origins only
Origins: o.Origins,
Methods: []string{"GET", "POST"},
Headers: []string{"Content-Type", "Authorization", "X-Request-ID"},
AllowCredentials: true,
MaxAgeSeconds: "600",
}),
harden.AllowMethods("GET", "HEAD", "POST", "OPTIONS"), // input: method allow-list
harden.JSONOnly, // input: 415 / 406
harden.LimitBody(o.Config.MaxBodyBytes), // input: 413
harden.WithHandlerTimeout(o.Timeouts.Handler), // processing: 503 after the deadline
)
}
// order is the stored record; orderView is what leaves the API. Internal
// fields never get a JSON tag on the public type.
type order struct {
ID string
SKU string
Quantity int
CardNumber string
RiskScore float64
}
type orderView struct {
ID string `json:"id"`
SKU string `json:"sku"`
Quantity int `json:"quantity"`
CardLast string `json:"card_last4"`
}
var (
uuidRe = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
skuRe = regexp.MustCompile(`^[A-Z0-9-]{3,32}$`)
)
func getOrder(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if !uuidRe.MatchString(id) { // allow-list: a UUID or nothing
harden.WriteProblem(w, r, http.StatusNotFound, "", nil)
return
}
o := order{ID: id, SKU: "MUG-01", Quantity: 2, CardNumber: "4111111111111111", RiskScore: 0.12}
writeJSON(w, http.StatusOK, orderView{ID: o.ID, SKU: o.SKU, Quantity: o.Quantity, CardLast: o.CardNumber[len(o.CardNumber)-4:]})
}
type createOrderInput struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
Currency string `json:"currency"`
}
func (in createOrderInput) validate() map[string]string {
errs := map[string]string{}
if !skuRe.MatchString(in.SKU) {
errs["sku"] = "must match ^[A-Z0-9-]{3,32}$"
}
if in.Quantity < 1 || in.Quantity > 100 {
errs["quantity"] = "must be between 1 and 100"
}
if in.Currency != "EUR" && in.Currency != "USD" {
errs["currency"] = "must be EUR or USD"
}
return errs
}
func createOrder(w http.ResponseWriter, r *http.Request) {
var in createOrderInput
if err := harden.DecodeJSON(r, &in); err != nil {
harden.WriteError(w, r, err)
return
}
if errs := in.validate(); len(errs) > 0 {
harden.WriteProblem(w, r, http.StatusUnprocessableEntity, "validation failed", errs)
return
}
id := "6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f"
w.Header().Set("Location", "/v1/orders/"+id)
writeJSON(w, http.StatusCreated, orderView{ID: id, SKU: in.SKU, Quantity: in.Quantity})
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}سرور آزمایشگاه که با debug روشن در Production بالا نمیآید:
// Command apiserver runs the hardened API (or the "before" version) on a
// local port for the curl audit lab.
package main
import (
"flag"
"log"
"net/http"
"os"
"time"
"academy/api-security-hardening-checklist/app"
"academy/api-security-hardening-checklist/before"
"academy/api-security-hardening-checklist/harden"
)
func main() {
addr := flag.String("addr", "127.0.0.1:18488", "listen address")
mode := flag.String("mode", "after", "after (hardened) or before (naive)")
flag.Parse()
cfg := harden.Config{
Env: os.Getenv("APP_ENV"),
Debug: os.Getenv("APP_DEBUG") == "true",
MaxBodyBytes: 64 << 10, // 64 KiB: the largest valid order is far smaller
}
if err := cfg.Validate(); err != nil {
log.Fatal(err) // debug-off guard: refuse to start
}
var h http.Handler
if *mode == "before" {
h = before.New()
srv := &http.Server{Addr: *addr, Handler: h} // no timeouts at all
log.Fatal(srv.ListenAndServe())
}
t := harden.DefaultTimeouts
t.Handler = time.Second // short so the lab can show the 503 quickly
h = app.New(app.Options{
Config: cfg,
Log: harden.NewLogger(os.Stderr),
Timeouts: t,
Origins: []string{"https://shop.example"},
Lab: true,
})
log.Fatal(harden.NewServer(*addr, h, t).ListenAndServe())
}تستهایی که هر بند را ثابت میکنند
هر رفتار بالا تست دارد؛ آموزندهترینها اینجا آمدهاند. در تست سرتاسری (End-to-end test)، هر پاسخ، موفق یا 405، 413، 415، 422، 404، 500 و 503، هدر دارد و اثرانگشت ندارد؛ هر رد هم application/problem+json است:
package app
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"academy/api-security-hardening-checklist/harden"
)
const orderURL = "/v1/orders/6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f"
func newAPI(logs io.Writer) http.Handler {
t := harden.DefaultTimeouts
t.Handler = 200 * time.Millisecond
return New(Options{
Config: harden.Config{Env: "production", MaxBodyBytes: 1024},
Log: harden.NewLogger(logs),
Timeouts: t,
Origins: []string{"https://shop.example"},
Lab: true,
})
}
func req(method, url, ctype, body string) *http.Request {
var b io.Reader
if body != "" {
b = strings.NewReader(body)
}
r := httptest.NewRequest(method, url, b)
if ctype != "" {
r.Header.Set("Content-Type", ctype)
}
return r
}
// Every response, success or rejection, carries the output headers, a
// request id, and no fingerprint; every rejection is problem+json.
func TestEveryResponseIsHardened(t *testing.T) {
cases := []struct {
name string
r *http.Request
want int
}{
{"get order", req("GET", orderURL, "", ""), 200},
{"create order", req("POST", "/v1/orders", "application/json", `{"sku":"MUG-01","quantity":2,"currency":"EUR"}`), 201},
{"TRACE", req("TRACE", orderURL, "", ""), 405},
{"route method", req("POST", orderURL, "application/json", `{}`), 405},
{"text/plain body", req("POST", "/v1/orders", "text/plain", `{}`), 415},
{"oversized body", req("POST", "/v1/orders", "application/json", `{"sku":"`+strings.Repeat("A", 2048)+`"}`), 413},
{"unknown field", req("POST", "/v1/orders", "application/json", `{"sku":"MUG-01","quantity":1,"currency":"EUR","price":0}`), 400},
{"invalid values", req("POST", "/v1/orders", "application/json", `{"sku":"x","quantity":0,"currency":"BTC"}`), 422},
{"not a uuid", req("GET", "/v1/orders/1%20OR%201=1", "", ""), 404},
{"unknown route", req("GET", "/.env", "", ""), 404},
{"panic", req("GET", "/v1/lab/panic", "", ""), 500},
{"handler timeout", req("GET", "/v1/lab/slow", "", ""), 503},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
rec := httptest.NewRecorder()
newAPI(io.Discard).ServeHTTP(rec, c.r)
h := rec.Header()
if rec.Code != c.want {
t.Fatalf("status %d, want %d: %s", rec.Code, c.want, rec.Body.String())
}
for _, k := range []string{"X-Content-Type-Options", "Cache-Control", "Content-Security-Policy", "X-Frame-Options", "X-Request-ID"} {
if h.Get(k) == "" {
t.Errorf("missing %s", k)
}
}
if h.Get("Server") != "" || h.Get("X-Powered-By") != "" {
t.Errorf("fingerprint headers present")
}
if c.want >= 400 && h.Get("Content-Type") != "application/problem+json" {
t.Errorf("rejection Content-Type %q", h.Get("Content-Type"))
}
if strings.Contains(rec.Body.String(), "goroutine") || strings.Contains(rec.Body.String(), "10.0.3.7") {
t.Errorf("internal detail leaked: %s", rec.Body.String())
}
})
}
}
func TestResponseHasNoSensitiveFields(t *testing.T) {
rec := httptest.NewRecorder()
newAPI(io.Discard).ServeHTTP(rec, req("GET", orderURL, "", ""))
var m map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &m); err != nil {
t.Fatal(err)
}
if _, ok := m["card_number"]; ok || strings.Contains(rec.Body.String(), "4111111111111111") {
t.Fatalf("full card number in response: %s", rec.Body.String())
}
if _, ok := m["RiskScore"]; ok {
t.Fatalf("internal field in response")
}
if m["card_last4"] != "1111" {
t.Fatalf("view: %v", m)
}
}
func TestCreateReturns201WithLocation(t *testing.T) {
rec := httptest.NewRecorder()
newAPI(io.Discard).ServeHTTP(rec, req("POST", "/v1/orders", "application/json", `{"sku":"MUG-01","quantity":2,"currency":"EUR"}`))
if rec.Code != 201 || !strings.HasPrefix(rec.Header().Get("Location"), "/v1/orders/") {
t.Fatalf("%d %v", rec.Code, rec.Header())
}
}
func TestValidationProblemListsFields(t *testing.T) {
rec := httptest.NewRecorder()
newAPI(io.Discard).ServeHTTP(rec, req("POST", "/v1/orders", "application/json", `{"sku":"x","quantity":0,"currency":"BTC"}`))
var p harden.Problem
_ = json.Unmarshal(rec.Body.Bytes(), &p)
if p.Title != "Unprocessable Content" || len(p.Errors) != 3 {
t.Fatalf("%+v", p)
}
}
func TestPanicIsLoggedWithStackServerSide(t *testing.T) {
var logs bytes.Buffer
rec := httptest.NewRecorder()
newAPI(&logs).ServeHTTP(rec, req("GET", "/v1/lab/panic", "", ""))
if !strings.Contains(logs.String(), "goroutine") || !strings.Contains(logs.String(), rec.Header().Get("X-Request-ID")) {
t.Fatalf("logs: %s", logs.String())
}
}هدرها، شامل HSTS فقط روی TLS با httptest.NewTLSServer و حذف اثرانگشت بعد از تنظیم Server: nginx/1.18.0 توسط handler داخلی:
package harden
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestSecurityHeadersAndFingerprintStripping(t *testing.T) {
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// An inner handler or a proxied upstream sets fingerprinting headers
// AFTER the middleware ran; they must still be gone.
w.Header().Set("Server", "nginx/1.18.0")
w.Header().Set("X-Powered-By", "PHP/8.1.2")
okHandler.ServeHTTP(w, r)
})
h := SecurityHeaders(HeaderOptions{HSTSMaxAge: 63072000})(inner)
rec := do(t, h, httptest.NewRequest("GET", "/v1/orders", nil))
want := map[string]string{
"Cache-Control": "no-store",
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer",
}
for k, v := range want {
if got := rec.Header().Get(k); got != v {
t.Errorf("%s = %q, want %q", k, got, v)
}
}
for _, k := range []string{"Server", "X-Powered-By"} {
if v := rec.Header().Get(k); v != "" {
t.Errorf("%s leaked: %q", k, v)
}
}
if v := rec.Header().Get("Strict-Transport-Security"); v != "" {
t.Errorf("HSTS sent over plain HTTP (RFC 6797 7.2 forbids it): %q", v)
}
}
func TestHSTSOnlyOverTLS(t *testing.T) {
srv := httptest.NewTLSServer(SecurityHeaders(HeaderOptions{HSTSMaxAge: 63072000})(okHandler))
defer srv.Close()
resp, err := srv.Client().Get(srv.URL + "/")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if got := resp.Header.Get("Strict-Transport-Security"); got != "max-age=63072000; includeSubDomains" {
t.Fatalf("HSTS over TLS = %q", got)
}
}
func TestHSTSBehindTrustedProxy(t *testing.T) {
h := SecurityHeaders(HeaderOptions{HSTSMaxAge: 300, TrustForwardedProto: true})(okHandler)
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("X-Forwarded-Proto", "https")
if got := do(t, h, r).Header().Get("Strict-Transport-Security"); got != "max-age=300; includeSubDomains" {
t.Fatalf("HSTS behind TLS-terminating proxy = %q", got)
}
}سقف بدنه: طول اعلامشده، بدنهٔ chunked و بستن اتصال از میان wrapperها روی socket واقعی:
package harden
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func decodeHandler(w http.ResponseWriter, r *http.Request) {
var v map[string]any
if err := DecodeJSON(r, &v); err != nil {
WriteError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func TestDeclaredLengthRejectedBeforeHandler(t *testing.T) {
called := false
h := LimitBody(1024)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true }))
r := httptest.NewRequest("POST", "/v1/orders", bytes.NewReader(make([]byte, 4096)))
rec := do(t, h, r)
if rec.Code != 413 || called {
t.Fatalf("status %d, handler called %v; want 413 without calling the handler", rec.Code, called)
}
if p := problemOf(t, rec); p.Title != "Content Too Large" {
t.Fatalf("title %q, want the RFC 9110 name", p.Title)
}
}
func TestChunkedBodyCutByMaxBytesReader(t *testing.T) {
h := LimitBody(1024)(http.HandlerFunc(decodeHandler))
big := `{"a":"` + strings.Repeat("x", 4096) + `"}`
r := httptest.NewRequest("POST", "/v1/orders", strings.NewReader(big))
r.ContentLength = -1 // unknown length, as with Transfer-Encoding: chunked
if rec := do(t, h, r); rec.Code != 413 {
t.Fatalf("chunked oversize: %d, want 413", rec.Code)
}
}
// Over a real connection, the limit must still reach net/http's own writer
// through the wrappers (stripWriter, statusWriter), so the server closes the
// connection instead of draining an attacker's endless body.
func TestLimitClosesConnectionThroughWrappers(t *testing.T) {
h := Chain(http.HandlerFunc(decodeHandler),
AccessLog(NewLogger(io.Discard)), SecurityHeaders(HeaderOptions{}), LimitBody(1024))
srv := httptest.NewServer(h)
defer srv.Close()
pr, pw := io.Pipe()
go func() {
_, _ = pw.Write([]byte(`{"a":"` + strings.Repeat("x", 8192)))
_ = pw.Close()
}()
req, _ := http.NewRequest("POST", srv.URL+"/", pr) // chunked: length unknown
req.Header.Set("Content-Type", "application/json")
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 413 {
t.Fatalf("status %d, want 413", resp.StatusCode)
}
if !resp.Close {
t.Fatalf("server kept the connection open after the body limit was hit")
}
}جدول مذاکره: 415، 406، q-value و chunked بدون نوع:
package harden
import (
"io"
"net/http/httptest"
"strings"
"testing"
)
func TestJSONOnly(t *testing.T) {
cases := []struct {
name, method, ctype, accept, body string
chunked bool
want int
}{
{"json body", "POST", "application/json", "", `{}`, false, 200},
{"json utf-8", "POST", "application/json; charset=utf-8", "application/json", `{}`, false, 200},
{"text/plain body", "POST", "text/plain", "", `{}`, false, 415},
{"form body", "POST", "application/x-www-form-urlencoded", "", `a=1`, false, 415},
{"xml body", "POST", "application/xml", "", `<a/>`, false, 415},
{"latin1 charset", "POST", "application/json; charset=iso-8859-1", "", `{}`, false, 415},
{"missing content-type", "POST", "", "", `{}`, false, 415},
{"chunked without type", "POST", "", "", `{}`, true, 415},
{"GET without body needs no type", "GET", "", "", ``, false, 200},
{"accept xml only", "GET", "", "application/xml", ``, false, 406},
{"accept json q=0", "GET", "", "application/json;q=0, text/html", ``, false, 406},
{"accept wildcard", "GET", "", "text/html, */*;q=0.1", ``, false, 200},
{"accept problem+json only", "GET", "", "application/problem+json", ``, false, 406},
{"explicit json q=0 beats wildcard", "GET", "", "application/json;q=0, application/problem+json;q=0, */*;q=1", ``, false, 406},
{"specific json beats application/* q=0", "GET", "", "application/*;q=0, application/json", ``, false, 200},
{"wildcard q=0", "GET", "", "*/*;q=0", ``, false, 406},
{"application/* accepted", "GET", "", "application/*;q=0.5", ``, false, 200},
{"json with params", "GET", "", "application/json; charset=utf-8", ``, false, 200},
{"malformed q ignored", "GET", "", "application/json;q=abc", ``, false, 406},
{"q=NaN ignored", "GET", "", "application/json;q=NaN", ``, false, 406},
{"q=1e0 ignored", "GET", "", "application/json;q=1e0", ``, false, 406},
{"q=inf ignored", "GET", "", "application/json;q=inf", ``, false, 406},
{"q above 1 ignored", "GET", "", "application/json;q=1.5", ``, false, 406},
{"q four decimals ignored", "GET", "", "application/json;q=0.1234", ``, false, 406},
{"malformed json q falls back to wildcard", "GET", "", "application/json;q=NaN, */*;q=0.2", ``, false, 200},
{"q=0.001 accepted", "GET", "", "application/json;q=0.001", ``, false, 200},
{"profile range does not match plain json", "GET", "", "application/json;profile=v2;q=1, application/json;q=0", ``, false, 406},
{"profile range alone", "GET", "", "application/json;profile=v2", ``, false, 406},
{"profile range does not hide wildcard", "GET", "", "application/json;profile=v2, */*", ``, false, 200},
{"charset utf-8 is more specific", "GET", "", "application/json;q=0, application/json;charset=utf-8", ``, false, 200},
{"charset latin1 does not match", "GET", "", "application/json;charset=iso-8859-1", ``, false, 406},
}
h := JSONOnly(okHandler)
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
var body io.Reader
if c.body != "" {
body = strings.NewReader(c.body)
}
r := httptest.NewRequest(c.method, "/v1/orders", body)
if c.chunked {
r.ContentLength = -1
}
if c.ctype != "" {
r.Header.Set("Content-Type", c.ctype)
}
if c.accept != "" {
r.Header.Set("Accept", c.accept)
}
rec := do(t, h, r)
if rec.Code != c.want {
t.Fatalf("status %d, want %d", rec.Code, c.want)
}
if c.want == 415 && rec.Header().Get("Accept") != "application/json" {
t.Fatalf("415 without Accept response header")
}
if c.want >= 400 {
problemOf(t, rec)
}
})
}
}Slowloris روی اتصال TCP خام، Timeout handler و فیلدهای سرور:
package harden
import (
"bufio"
"io"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestNewServerSetsEveryTimeout(t *testing.T) {
s := NewServer(":0", okHandler, DefaultTimeouts)
if s.ReadHeaderTimeout == 0 || s.ReadTimeout == 0 || s.WriteTimeout == 0 || s.IdleTimeout == 0 {
t.Fatalf("a zero timeout means no timeout: %+v", s)
}
if s.MaxHeaderBytes != 32<<10 {
t.Fatalf("MaxHeaderBytes %d", s.MaxHeaderBytes)
}
}
// A slowloris client sends a header line and then nothing. With
// ReadHeaderTimeout set, Go closes the connection without a response
// (nginx would answer 408); without it the connection stays open.
func TestSlowlorisHeaderTimeout(t *testing.T) {
srv := httptest.NewUnstartedServer(okHandler)
srv.Config.ReadHeaderTimeout = 200 * time.Millisecond
srv.Start()
defer srv.Close()
conn, err := net.Dial("tcp", srv.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
_, _ = io.WriteString(conn, "GET / HTTP/1.1\r\nHost: x\r\nX-Slow: 1\r\n") // never finishes
_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
start := time.Now()
n, err := bufio.NewReader(conn).Read(make([]byte, 1))
if err != io.EOF || n != 0 {
t.Fatalf("read %d bytes, err %v; want a silent close (EOF)", n, err)
}
if el := time.Since(start); el > 2*time.Second {
t.Fatalf("closed after %v; ReadHeaderTimeout not applied", el)
}
}
func TestHandlerTimeoutIs503Problem(t *testing.T) {
slow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done() // a well-behaved handler stops when cancelled
})
h := Chain(slow, ProblemErrors, WithHandlerTimeout(50*time.Millisecond))
rec := do(t, h, httptest.NewRequest("GET", "/v1/report", nil))
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status %d, want 503 (http.TimeoutHandler)", rec.Code)
}
problemOf(t, rec)
}Redaction و شناسهٔ درخواست امن در برابر تزریق لاگ:
package harden
import (
"bytes"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestAccessLogLineIsRedacted(t *testing.T) {
var buf bytes.Buffer
log := NewLogger(&buf)
h := Chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}), RequestID(false), AccessLog(log))
r := httptest.NewRequest("GET", "/v1/orders?access_token=sk_live_SECRET&email=ana@example.com", nil)
r.Header.Set("Authorization", "Bearer sk_live_SECRET")
rec := do(t, h, r)
line := buf.String()
if strings.Contains(line, "sk_live_SECRET") || strings.Contains(line, "ana@example.com") {
t.Fatalf("secret or PII in log: %s", line)
}
var m map[string]any
if err := json.Unmarshal([]byte(line), &m); err != nil {
t.Fatal(err)
}
if m["path"] != "/v1/orders" || m["status"] != float64(401) || m["level"] != "WARN" {
t.Fatalf("unexpected line: %s", line)
}
if m["request_id"] != rec.Header().Get(RequestIDHeader) {
t.Fatalf("log request_id %v != response header %q", m["request_id"], rec.Header().Get(RequestIDHeader))
}
}
func TestLoggerRedactsSensitiveAttributes(t *testing.T) {
var buf bytes.Buffer
NewLogger(&buf).Info("login",
slog.String("user_id", "42"),
slog.String("password", "hunter2"),
slog.Group("req", slog.String("Authorization", "Bearer abc.def.ghi")),
)
out := buf.String()
for _, leak := range []string{"hunter2", "abc.def.ghi"} {
if strings.Contains(out, leak) {
t.Fatalf("leaked %q: %s", leak, out)
}
}
if !strings.Contains(out, `"user_id":"42"`) {
t.Fatalf("non-sensitive attribute lost: %s", out)
}
}package harden
import (
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
)
func echoID(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(RequestIDFrom(r.Context())))
}
func TestRequestIDGenerated(t *testing.T) {
rec := do(t, RequestID(false)(http.HandlerFunc(echoID)), httptest.NewRequest("GET", "/", nil))
id := rec.Header().Get(RequestIDHeader)
if !regexp.MustCompile(`^[0-9a-f]{24}$`).MatchString(id) || rec.Body.String() != id {
t.Fatalf("header %q, context %q", id, rec.Body.String())
}
}
func TestRequestIDIncoming(t *testing.T) {
cases := []struct {
name, in string
trust bool
reused bool
}{
{"untrusted client id ignored", "gw-7f3a9c2e", false, false},
{"trusted gateway id kept", "gw-7f3a9c2e", true, true},
{"log injection replaced", "abc\nlevel=ERROR msg=fake", true, false},
{"oversized replaced", strings.Repeat("a", 65), true, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set(RequestIDHeader, c.in)
got := do(t, RequestID(c.trust)(http.HandlerFunc(echoID)), r).Header().Get(RequestIDHeader)
if (got == c.in) != c.reused {
t.Fatalf("got %q, reused=%v, want reused=%v", got, got == c.in, c.reused)
}
})
}
}تستهای باقیمانده، methods_test.go، jsonin_test.go، recover_test.go، cors_test.go، config_test.go و problem_test.go، در همان دایرکتوری هستند.
نگاه Go
- زنجیرهٔ میانافزار Go (Go middleware chain): Middleware تابع
func(http.Handler) http.Handlerاست. Framework ترتیب را تعیین نمیکند؛ ترتیب یک فراخوانیChainهمان طراحی امنیت است. Wrapperهایhttp.ResponseWriterبایدUnwrap() http.ResponseWriterداشته باشند؛http.ResponseControllerاز Go 1.20 از آن استفاده میکند. بدون آن قابلیتها از لایههای پایین پنهان میشوند. الگوهای بیشتر در Middlewareهای Go. ServeMuxاز Go 1.22 فهرست متد هر Route را با الگو مثل"POST /v1/orders"اعمال میکند؛GET، متدHEADرا هم ثبت میکند. متد غلط روی مسیر شناختهشده 405 وAllowمیگیرد؛ بدنه ازhttp.Errorوtext/plainاست، دلیل وجودProblemErrorsهمین است.http.ErrorمقدارContent-Type: text/plain; charset=utf-8وX-Content-Type-Options: nosniffرا تنظیم وContent-Lengthرا حذف میکند. برای ابزار داخلی مناسب است، برای API متعهد به قالب خطای واحد کافی نیست.- سقف بدنه:
http.MaxBytesReaderبا خطای دارای نوع*http.MaxBytesErrorاز 1.19. تابعio.LimitReaderبیصدا قطع میکند و بدنهٔ بزرگ را به خطای گمراهکنندهٔ syntax در JSON بدل میکند، نه 413. - Timeout: در
http.Server، صفر درReadTimeout/WriteTimeoutیعنی بدون Timeout؛ صفر درReadHeaderTimeoutیاIdleTimeoutبهReadTimeoutبرمیگردد و فقط با صفر بودن آن نامحدود است. هر چهار را صریح تنظیم کنید.ReadHeaderTimeoutدفاع Slowloris و خواستهٔ linter امنیتی gosec G112 در کنارgo vetاست.http.TimeoutHandlerپاسخ 503 میدهد و context درخواست را لغو میکند؛ handler بایدr.Context()را به پایگاه داده و کلاینت HTTP بدهد. برای endpoint جریاندار، Timeout هر درخواست باhttp.NewResponseController(w).SetReadDeadlineوSetWriteDeadlineاز Go 1.20 تنظیم میشود. Handshake روی listener TLS هم محدود است؛tlsHandshakeTimeoutدرserver.go: "returns the minimum of any positive ReadHeaderTimeout, ReadTimeout, or WriteTimeout". - ثبت لاگ (Logging):
log/slogاز Go 1.21 باReplaceAttrبرای Redaction؛ کلیدها اینجا بدون حساسیت به بزرگی حروف مقایسه میشوند چون توسعهدهنده همAuthorizationمینویسد همauthorization. - JSON:
encoding/jsonسقف اندازه ندارد و سقف تودرتویی داخلی ده هزار است.DisallowUnknownFieldsو بررسی دادهٔ انتهایی باdec.More()و سپسToken()برگردانندهٔio.EOF، decode را سختگیر میکنند. کار رویencoding/json/v2باGOEXPERIMENT=jsonv2آزمایشی در Go 1.25 پیشفرضها را تغییر میدهد؛ این ماژول روی v1 میماند. - ابزارها:
govulncheck ./...برای SCA آگاه از دسترسیپذیری،gosec ./...با G112 برای نبودReadHeaderTimeoutو G114 برایhttp.ListenAndServeبدون Timeout، وgo test -race.
Laravel
مثال: Middleware، CORS، محافظ debug، Problem Details و Redaction
هدر خروجی و حذف اثرانگشت در ابتدای stack عمومی، تا HandleCors برای Preflight و دیگر بازگشتهای زودهنگام را بپوشاند:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Output headers for a JSON API (OWASP REST Security Cheat Sheet set) and
* removal of fingerprinting headers. Prepended to the global stack (before
* HandleCors) so preflights and error responses (404, 405, 413, 500) get
* the headers too.
*/
class SecurityHeaders
{
private const HEADERS = [
'Cache-Control' => 'no-store',
'Content-Security-Policy' => "default-src 'none'; frame-ancestors 'none'",
'X-Content-Type-Options' => 'nosniff',
'X-Frame-Options' => 'DENY',
'Referrer-Policy' => 'no-referrer',
'Permissions-Policy' => 'camera=(), microphone=(), geolocation=(), payment=()',
];
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
foreach (self::HEADERS as $name => $value) {
$response->headers->set($name, $value);
}
// RFC 6797: never send HSTS over plain HTTP. isSecure() honours
// X-Forwarded-Proto only from proxies listed in trustProxies().
if ($request->isSecure()) {
$response->headers->set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains');
}
// PHP adds X-Powered-By itself unless php.ini has expose_php=Off;
// header_remove() covers the SAPI header, the bag covers the rest.
$response->headers->remove('X-Powered-By');
$response->headers->remove('Server');
header_remove('X-Powered-By');
return $response;
}
}پاسخ 415 و 406 برای گروه api؛ router از قبل 405 با Allow را انجام میدهد:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* 415 for a body that is not application/json, 406 for an Accept header
* that excludes JSON. Laravel's router already answers 405 (with Allow) for
* a method the route does not define.
*/
class EnforceJsonApi
{
public function handle(Request $request, Closure $next): Response
{
// Not $request->accepts(): it returns true as soon as any listed range
// matches, ignoring q=0 and precedence (InteractsWithContentTypes).
if ($request->headers->has('Accept')
&& self::jsonQuality((string) $request->headers->get('Accept')) <= 0.0) {
return $this->problem($request, 406, 'This API only produces application/json.');
}
$hasBody = (int) $request->headers->get('Content-Length', '0') > 0
|| $request->headers->has('Transfer-Encoding');
if ($hasBody && ! $request->isJson()) {
return $this->problem($request, 415, 'Send application/json.')
->header('Accept', 'application/json');
}
return $next($request);
}
/**
* RFC 9110 12.5.1 for application/json (UTF-8, no other parameters):
* the most specific matching range sets the quality; ranges with other
* parameters do not match; malformed q values make a range ignored.
*/
public static function jsonQuality(string $accept): float
{
$best = -1;
$quality = 0.0;
foreach (explode(',', $accept) as $range) {
$parts = array_map('trim', explode(';', $range));
$type = strtolower(array_shift($parts));
$specificity = match ($type) {
'application/json' => 2,
'application/*' => 1,
'*/*' => 0,
default => -1,
};
$q = 1.0;
foreach ($parts as $param) {
[$name, $value] = array_pad(array_map('trim', explode('=', $param, 2)), 2, '');
$name = strtolower($name);
$value = trim($value, '"');
if ($name === 'q' && preg_match('/\A(0(\.[0-9]{0,3})?|1(\.0{0,3})?)\z/', $value) === 1) {
$q = (float) $value;
} elseif ($specificity === 2 && $name === 'charset' && strcasecmp($value, 'utf-8') === 0) {
$specificity = 3;
} else {
$specificity = -1; // malformed q or a parameter JSON does not have
break;
}
}
if ($specificity < 0 || $specificity < $best) {
continue;
}
if ($specificity > $best || $q > $quality) {
[$best, $quality] = [$specificity, $q];
}
}
return $best >= 0 ? $quality : 0.0;
}
private function problem(Request $request, int $status, string $detail): Response
{
return response()->json([
'type' => 'about:blank',
'title' => Response::$statusTexts[$status],
'status' => $status,
'detail' => $detail,
'request_id' => $request->attributes->get('request_id'),
], $status, ['Content-Type' => 'application/problem+json']);
}
}سقف بدنهٔ هر Route پایینتر از post_max_size:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Per-route body cap, stricter than php.ini post_max_size (which the global
* ValidatePostSize middleware enforces). Usage: ->middleware('body.limit:65536').
* The web server limit (nginx client_max_body_size) must be the outer wall:
* PHP-FPM has already received the body by the time this runs.
*/
class LimitRequestBody
{
public function handle(Request $request, Closure $next, int $maxBytes = 65536): Response
{
$declared = (int) $request->headers->get('Content-Length', '0');
if ($declared > $maxBytes || strlen($request->getContent()) > $maxBytes) {
return response()->json([
'type' => 'about:blank',
'title' => 'Content Too Large',
'status' => 413,
'detail' => 'Request body too large.',
], 413, ['Content-Type' => 'application/problem+json', 'Connection' => 'close']);
}
return $next($request);
}
}شناسهٔ درخواست از طریق Context، تا هر خط لاگ و job صفشده آن را داشته باشد:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
/**
* Request id / correlation id. Context::add() makes Laravel append it to
* every log entry and to queued jobs dispatched during this request.
*/
class AssignRequestId
{
public function handle(Request $request, Closure $next): Response
{
$incoming = (string) $request->headers->get('X-Request-ID', '');
// Keep the gateway's id only if it is short and boring; a client
// must not be able to write newlines or megabytes into the logs.
$id = preg_match('/\A[A-Za-z0-9._-]{8,64}\z/', $incoming) === 1
? $incoming
: (string) Str::uuid();
$request->attributes->set('request_id', $id);
Context::add('request_id', $id);
$response = $next($request);
$response->headers->set('X-Request-ID', $id);
return $response;
}
}Redaction بهصورت tap کانال لاگ:
<?php
namespace App\Logging;
use Illuminate\Log\Logger;
use Monolog\LogRecord;
/**
* Logging channel tap: a Monolog processor that masks secrets and PII in
* the context and extra arrays before any handler formats the record.
* config/logging.php: 'tap' => [App\Logging\RedactSensitiveData::class].
*/
class RedactSensitiveData
{
private const KEYS = [
'authorization', 'cookie', 'set-cookie', 'password', 'password_confirmation',
'token', 'access_token', 'refresh_token', 'api_key', 'secret', 'card_number', 'email',
];
public function __invoke(Logger $logger): void
{
foreach ($logger->getHandlers() as $handler) {
$handler->pushProcessor(fn (LogRecord $record): LogRecord => $record->with(
context: $this->redact($record->context),
extra: $this->redact($record->extra),
));
}
}
private function redact(array $data): array
{
foreach ($data as $key => $value) {
if (is_string($key) && in_array(strtolower($key), self::KEYS, true)) {
$data[$key] = '[REDACTED]';
} elseif (is_array($value)) {
$data[$key] = $this->redact($value);
}
}
return $data;
}
}Validation با فهرست مجاز و رد فیلد ناشناخته:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
/**
* Allow-list validation: type, length, range and format per field, and
* unknown fields are an error instead of being silently dropped.
*/
class StoreOrderRequest extends FormRequest
{
private const FIELDS = ['sku', 'quantity', 'currency'];
public function rules(): array
{
return [
'sku' => ['required', 'string', 'regex:/\A[A-Z0-9-]{3,32}\z/'],
'quantity' => ['required', 'integer', 'between:1,100'],
'currency' => ['required', Rule::in(['EUR', 'USD'])],
];
}
public function after(): array
{
return [
function (Validator $validator) {
foreach (array_diff(array_keys($this->all()), self::FIELDS) as $unknown) {
$validator->errors()->add($unknown, 'Unknown field.');
}
},
];
}
}فهرست مجاز خروجی:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* The output allow-list: only these keys leave the API, whatever columns
* the model gains later (card_number, risk_score, internal_notes ...).
*/
class OrderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->uuid,
'sku' => $this->sku,
'quantity' => $this->quantity,
'card_last4' => substr((string) $this->card_number, -4),
];
}
}<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreOrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;
class OrderController extends Controller
{
public function show(Order $order): OrderResource
{
// Route model binding by uuid (see Order::getRouteKeyName); ownership
// checks belong to the policy layer, not to this checklist.
Gate::authorize('view', $order);
return new OrderResource($order);
}
public function store(StoreOrderRequest $request): JsonResponse
{
$order = $request->user()->orders()->create($request->validated());
return (new OrderResource($order))
->response()
->setStatusCode(201)
->header('Location', route('orders.show', $order));
}
}متد صریح و Middleware هر Route:
<?php
use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;
// Explicit verbs only: no Route::any(), no Route::match() with '*'.
// A wrong verb on a known URI gets 405 with an Allow header from the router.
Route::middleware(['auth:sanctum', 'throttle:api', 'body.limit:65536'])
->prefix('v1')
->group(function () {
Route::get('orders/{order:uuid}', [OrderController::class, 'show'])
->whereUuid('order')
->name('orders.show');
Route::post('orders', [OrderController::class, 'store'])->name('orders.store');
});سیمکشی، proxy مورد اعتماد، JSON برای هر خطای API و رندر RFC 9457:
<?php
use App\Http\Middleware\AssignRequestId;
use App\Http\Middleware\EnforceJsonApi;
use App\Http\Middleware\LimitRequestBody;
use App\Http\Middleware\SecurityHeaders;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Global and outermost: prepend() puts these before HandleCors,
// ValidatePostSize and maintenance mode, so CORS preflights and those
// early rejections still pass back through SecurityHeaders.
$middleware->prepend(SecurityHeaders::class);
$middleware->prepend(AssignRequestId::class); // now first of all
$middleware->api(prepend: [EnforceJsonApi::class]);
$middleware->alias(['body.limit' => LimitRequestBody::class]);
// Only the load balancer may set X-Forwarded-* (isSecure, client IP).
$middleware->trustProxies(at: ['10.0.0.0/8']);
})
->withExceptions(function (Exceptions $exceptions): void {
// API errors are always JSON, whatever the Accept header says.
$exceptions->shouldRenderJsonWhen(
fn (Request $request, Throwable $e) => $request->is('api/*') || $request->expectsJson()
);
// RFC 9457 problem details; stack traces stay in the log.
$exceptions->render(function (Throwable $e, Request $request) {
// Render callbacks run before Laravel's own AuthenticationException
// handling, so 401 must be mapped here or it would become a 500.
if (! $request->is('api/*') || $e instanceof HttpResponseException) {
return null; // default rendering
}
$status = match (true) {
$e instanceof AuthenticationException => 401,
$e instanceof ValidationException => 422,
$e instanceof HttpExceptionInterface => $e->getStatusCode(),
default => 500,
};
$problem = [
'type' => 'about:blank',
'title' => Response::$statusTexts[$status] ?? 'Error',
'status' => $status,
'request_id' => $request->attributes->get('request_id'),
];
if ($e instanceof ValidationException) {
$problem['errors'] = $e->errors();
}
if (config('app.debug')) {
$problem['detail'] = $e->getMessage(); // local only, see AppServiceProvider
}
$headers = $e instanceof HttpExceptionInterface ? $e->getHeaders() : []; // keeps Allow on 405
$headers['Content-Type'] = 'application/problem+json';
return response()->json($problem, $status, $headers);
});
})->create();محافظ خاموشی debug:
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use RuntimeException;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Debug-off guard: a production process with APP_DEBUG=true does
// not boot, so the Ignition/whoops page can never reach a client.
if ($this->app->isProduction() && config('app.debug')) {
throw new RuntimeException('APP_DEBUG must be false in production.');
}
JsonResource::withoutWrapping();
// The 'api' limiter used by routes/api.php (throttle:api): 60 requests
// a minute per user, or per IP for unauthenticated calls -> 429.
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}فایل سختگیرانهٔ config/cors.php؛ ابتدا با php artisan config:publish cors منتشرش کنید:
<?php
// Published with `php artisan config:publish cors`. The framework default is
// 'allowed_origins' => ['*'] with supports_credentials false; an API that a
// browser calls with cookies (Sanctum SPA) must list its origins instead.
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['GET', 'POST'],
'allowed_origins' => [env('FRONTEND_URL', 'https://shop.example')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['Content-Type', 'Authorization', 'X-Request-ID', 'X-XSRF-TOKEN'],
'exposed_headers' => ['X-Request-ID'],
'max_age' => 600,
'supports_credentials' => true,
];Feature testها برای همان رفتارهای تست Go:
<?php
namespace Tests\Feature;
use App\Http\Middleware\EnforceJsonApi;
use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use RuntimeException;
use Tests\TestCase;
class ApiHardeningTest extends TestCase
{
use RefreshDatabase;
public function test_every_api_response_has_the_output_headers(): void
{
$response = $this->getJson('/api/v1/orders/'.fake()->uuid());
$response->assertStatus(401) // unauthenticated: 401, not 500
->assertHeader('Content-Type', 'application/problem+json')
->assertHeader('X-Content-Type-Options', 'nosniff')
->assertHeader('X-Frame-Options', 'DENY')
->assertHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'")
->assertHeaderMissing('X-Powered-By')
->assertHeaderMissing('Strict-Transport-Security');
// Symfony may append "private" to Cache-Control; no-store is what counts.
$this->assertStringContainsString('no-store', (string) $response->headers->get('Cache-Control'));
$this->assertNotEmpty($response->headers->get('X-Request-ID'));
}
public function test_wrong_verb_is_405_with_allow(): void
{
$response = $this->deleteJson('/api/v1/orders')
->assertStatus(405)
->assertHeader('Content-Type', 'application/problem+json');
// RFC 9110: a 405 MUST list the supported methods.
$this->assertStringContainsString('POST', (string) $response->headers->get('Allow'));
}
public function test_cors_preflight_carries_the_security_headers(): void
{
$response = $this->call('OPTIONS', '/api/v1/orders', [], [], [], [
'HTTP_ORIGIN' => 'https://shop.example',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertTrue($response->isSuccessful());
$response->assertHeader('Access-Control-Allow-Origin', 'https://shop.example')
->assertHeader('X-Content-Type-Options', 'nosniff')
->assertHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'");
}
public function test_non_json_body_is_415(): void
{
$this->actingAs(User::factory()->create())
->call('POST', '/api/v1/orders', [], [], [], ['CONTENT_TYPE' => 'text/plain', 'HTTP_ACCEPT' => 'application/json'], '{"sku":"MUG-01"}')
->assertStatus(415);
}
public function test_accept_without_json_is_406(): void
{
$this->get('/api/v1/orders/'.fake()->uuid(), ['Accept' => 'application/xml'])
->assertStatus(406);
}
public function test_accept_precedence_matches_the_go_rules(): void
{
$cases = [
'application/json;q=0, */*;q=1' => 0.0,
'application/json;profile=v2;q=1, application/json;q=0' => 0.0,
'application/problem+json' => 0.0,
'application/json;q=NaN' => 0.0,
'application/json;q=1e0' => 0.0,
'application/*;q=0, application/json' => 1.0,
'text/html, */*;q=0.1' => 0.1,
'application/json;q=0, application/json;charset=utf-8' => 1.0,
];
foreach ($cases as $accept => $want) {
$this->assertSame($want, EnforceJsonApi::jsonQuality($accept), $accept);
}
}
public function test_unknown_fields_and_bad_values_are_422(): void
{
$this->actingAs(User::factory()->create())
->postJson('/api/v1/orders', ['sku' => 'x', 'quantity' => 0, 'currency' => 'BTC', 'price' => 0])
->assertStatus(422)
->assertJsonStructure(['errors' => ['sku', 'quantity', 'currency', 'price']]);
}
public function test_response_never_contains_the_card_number(): void
{
$user = User::factory()->create();
$order = Order::factory()->for($user)->create(['card_number' => '4111111111111111']);
$this->actingAs($user)->getJson('/api/v1/orders/'.$order->uuid)
->assertOk()
->assertJsonMissingPath('card_number')
->assertJsonPath('card_last4', '1111');
}
public function test_server_errors_do_not_leak_traces(): void
{
config(['app.debug' => false]);
Route::middleware('api')->get('/api/v1/lab/panic', function () {
throw new RuntimeException('db: connection refused at 10.0.3.7:5432 user=orders_rw');
});
$response = $this->getJson('/api/v1/lab/panic')
->assertStatus(500)
->assertHeader('Content-Type', 'application/problem+json')
->assertJsonMissingPath('trace')
->assertJsonMissingPath('exception')
->assertJsonMissingPath('file')
->assertJsonMissingPath('detail');
foreach (['10.0.3.7', 'orders_rw', 'RuntimeException', '.php'] as $leak) {
$this->assertStringNotContainsString($leak, $response->getContent());
}
$this->assertNotEmpty($response->json('request_id'));
}
public function test_unknown_route_is_a_problem_404(): void
{
$this->getJson('/api/v1/orders/not-a-uuid')
->assertStatus(404)
->assertHeader('Content-Type', 'application/problem+json');
}
}کانال لاگ استفادهکننده از tap در config/logging.php:
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
'tap' => [App\Logging\RedactSensitiveData::class],
],اگر package را ترجیح میدهید، بستهٔ secure-headers یعنی bepsvpt/secure-headers جای Middleware سفارشی SecurityHeaders را میگیرد:
// composer require bepsvpt/secure-headers
// php artisan vendor:publish --provider="Bepsvpt\SecureHeaders\SecureHeadersServiceProvider"
->withMiddleware(function (Middleware $middleware): void {
$middleware->append(\Bepsvpt\SecureHeaders\SecureHeadersMiddleware::class);
})نگاه Laravel
- میانافزار Laravel (Laravel middleware) از Laravel 11+ در
bootstrap/app.phpثبت میشود:$middleware->append()وprepend()برای stack عمومی،$middleware->api(prepend: [...])برای گروهapi، و$middleware->alias([...])برای Middleware پارامتردار Route مثلbody.limit:65536. stack عمومی پیشفرض طبق مستندات شاملValidatePathEncoding،InvokeDeferredCallbacks،TrustProxies،HandleCors،PreventRequestsDuringMaintenance،ValidatePostSize،TrimStringsوConvertEmptyStringsToNullاست.TrustHostsکامنت شده و فعالکردنش با$middleware->trustHosts()برای ردHostجعلی ارزش دارد. - CORS داخلی است: "Laravel can automatically respond to CORS OPTIONS HTTP requests with values that you configure"، از طریق
HandleCors. تا وقتیconfig/cors.phpرا منتشر و ویرایش نکردهاید پیشفرضها باز هستند. - APP_DEBUG تعیین میکند پاسخ exception شامل class، فایل، خط و trace باشد؛ در مستندات ذخیرهشده فراتر از عبارت "how much information about an error is actually displayed to the user" بررسی نشده است.
php artisan config:cacheمقدار را ثابت میکند؛ مقدار غلط تا بازسازی cache میماند. - خطاها: Laravel بر اساس "based on the Accept header of the request" بین HTML و JSON انتخاب میکند.
shouldRenderJsonWhenبرایapi/*JSON را اجباری میکند. callback به نامrenderدرbootstrap/app.phpمحل واحد تولید RFC 9457 و حفظAllowازMethodNotAllowedHttpException::getHeaders()است. Callbackهای render پیش از رسیدگی داخلی بهAuthenticationExceptionوHttpResponseExceptionاجرا میشوند؛Handler::renderدر 13.x ابتداrenderViaCallbacksرا صدا میزند. پس callback خودش شکست Authentication را به 401 نگاشت میکند و برایHttpResponseExceptionمقدارnullمیدهد؛ بدون این شاخه هر فراخوان فاقد هویت 500 میشود. - اعتبارسنجی (Validation):
$request->validated()کلید ناشناخته را بیصدا حذف میکند. برای Mass assignment امن است ولی باگ کلاینت و probing را پنهان میکند؛ hook به نامafter()آنها را 422 گزارش میکند. - ثبت لاگ (Logging):
Context::add()برای شناسهای که باید در تمام خطها و jobهای صف باشد؛Context::addHidden()برای مقداری که باید همراه job برود ولی هرگز لاگ نشود؛ processor در Monolog از طریقtapکانال برای Redaction. - لبه و PHP: Laravel پشت Nginx، یا Caddy یا FrankenPHP/Octane، اجرا میشود. سقف بدنه، Timeout هدر و
server_tokensآنجا هستند؛expose_php = Offدرphp.ini. در CI ازcomposer auditو برای بررسی ایستا از Enlightn یا Larastan استفاده کنید.
در لبه: پیکربندی gateway
همان کنترلها، یک لایه زودتر. مقدارها با برنامه هماهنگاند تا درخواست ردشده در لبه، در برنامه هم رد شود.
Nginx جلوی Laravel با PHP-FPM یا سرویس Go:
server {
listen 443 ssl;
server_name api.example.com;
server_tokens off; # "Server: nginx" without the version
autoindex off; # no directory listings
client_header_timeout 10s; # slowloris: 408 after 10s without full headers
client_body_timeout 10s; # between two body reads
client_max_body_size 64k; # 413 above 64 KiB on JSON routes
keepalive_timeout 60s;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Content-Security-Policy "default-src 'none'; frame-ancestors 'none'" always;
add_header Referrer-Policy "no-referrer" always;
add_header Cache-Control "no-store" always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
location /v1/ {
limit_except GET POST OPTIONS { deny all; } # GET implies HEAD; OPTIONS for CORS preflights; others 403
proxy_hide_header X-Powered-By; # Server is already hidden from the upstream
proxy_set_header X-Request-ID $request_id;
proxy_pass http://orders;
}
location /internal/ {
allow 10.0.0.0/8; # private API: safe-listed IPs only
deny all;
proxy_pass http://orders;
}
}قاعدهٔ ارثبری add_header را فراموش نکنید: اگر location خودش add_header داشته باشد تمام موارد سطح server را از دست میدهد. Nginx 1.29.3 گزینهٔ add_header_inherit را برای تغییر این رفتار افزود.
Kong با پیکربندی اعلانی و افزونههای متنباز؛ Schemaها در فایلهای ذخیرهشدهٔ schema.lua هستند:
_format_version: "3.0"
services:
- name: orders
url: http://orders:8080
routes:
- name: orders-v1
paths: ["/v1"]
methods: ["GET", "HEAD", "POST", "OPTIONS"]
plugins:
- name: request-size-limiting
config:
allowed_payload_size: 64
size_unit: kilobytes
require_content_length: false
- name: response-transformer
config:
remove:
headers: ["Server", "X-Powered-By"]
add:
headers:
- "X-Content-Type-Options:nosniff"
- "Cache-Control:no-store"
- "Content-Security-Policy:default-src 'none'; frame-ancestors 'none'"
- name: cors
config:
origins: ["https://shop.example"] # empty would allow all origins
methods: ["GET", "POST"]
headers: ["Content-Type", "Authorization", "X-Request-ID"]
credentials: true
max_age: 600Envoy، بخشی از HTTP connection manager:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: ingress_http
server_header_transformation: PASS_THROUGH # default OVERWRITE sends "server: envoy"
request_headers_timeout: 5s # disabled by default
request_timeout: 15s
stream_idle_timeout: 30s # default 5 minutes
http_filters:
- name: envoy.filters.http.buffer
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.Buffer
max_request_bytes: 65536 # 413 above this
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
route_config:
response_headers_to_add:
- header: { key: X-Content-Type-Options, value: nosniff }
- header: { key: Cache-Control, value: no-store }
response_headers_to_remove: ["x-powered-by"]APISIX، یک Route با Validation بر اساس JSON Schema در لبه:
{
"uri": "/v1/orders",
"methods": ["POST"],
"plugins": {
"client-control": { "max_body_size": 65536 },
"request-validation": {
"header_schema": {
"type": "object",
"required": ["Content-Type"],
"properties": { "Content-Type": { "type": "string", "pattern": "^application/json" } }
},
"body_schema": {
"type": "object",
"additionalProperties": false,
"required": ["sku", "quantity", "currency"],
"properties": {
"sku": { "type": "string", "pattern": "^[A-Z0-9-]{3,32}$" },
"quantity": { "type": "integer", "minimum": 1, "maximum": 100 },
"currency": { "type": "string", "enum": ["EUR", "USD"] }
}
},
"rejected_code": 400
},
"response-rewrite": {
"headers": {
"set": { "X-Content-Type-Options": "nosniff", "Cache-Control": "no-store" },
"remove": ["Server", "X-Powered-By"]
}
}
},
"upstream": { "type": "roundrobin", "nodes": { "orders:8080": 1 } }
}این بلوکها بر پایهٔ مستندات دستور و Schema افزونههای ذخیرهشدهٔ فصل نوشته شدهاند: moduleهای core، headers و proxy در Nginx؛ فایلهای schema.lua در Kong؛ http_connection_manager.proto، buffer.proto و route.proto در Envoy؛ و صفحههای client-control، request-validation و response-rewrite در APISIX. روی gateway زنده اجرا نشدهاند، چون در محیط تهیهٔ مثال Docker وجود نداشت. همچنین با nginx -t، deck validate، envoy --mode validate یا APISIX Admin API اعتبارسنجی نشدهاند؛ آنها را نمونهٔ مورد انتظار بدانید، نه اجرای تأییدشده.
حل مسئلههای کلاسیک
یافتهٔ آزمون نفوذ: افشای نسخه با Server و X-Powered-By
گزارش روی تمام پاسخها Server: nginx/1.18.0 و X-Powered-By: PHP/8.1.2 را نشان میدهد؛ صفحهٔ 404 Nginx هم نسخه دارد.
| راهحل | روش | مزیت | هزینه / محدودیت |
|---|---|---|---|
| لبه | server_tokens off، proxy_hide_header X-Powered-By | یک تغییر برای همهٔ برنامههای پشت آن | Server: nginx میماند؛ ترافیک داخلی پوشش ندارد |
| PHP | expose_php = Off | حذف هدر از مبدأ | بازسازی Image لازم است |
| برنامه | حذف هنگام نوشتن توسط SecurityHeaders | upstreamهایی که برنامه proxy میکند هم پوشش دارند | باید بیرون handlerها باشد |
| بررسی CI | curl -sI در ممیزی؛ شکست با وجود رقم در Server | بازگشت باگ پیدا میشود | فقط URLهایی که script میشناسد |
یافتهٔ آزمون نفوذ: Stack trace و connection string در پاسخ 500
درخواست خراب به /api/v1/orders صفحهٔ Ignition یا whoops، یا متن Panic در Go، را با میزبان و کاربر پایگاه داده برگرداند. به این ترتیب اصلاح کنید: APP_DEBUG=false و محافظ boot در Laravel یا Config.Validate در Go؛ renderer مطابق RFC 9457 که هرگز getMessage() را در Production وارد پاسخ نکند؛ Middleware به نام Recover در بیرونیترین محل؛ سپس تعویض اعتبارنامهٔ لورفته، چون تمام مدت نمایش صفحه عمومی بوده است. بررسی curl با عنوان "500 without stack trace or internal address" را اضافه کنید.
رخداد: بدنهٔ JSON با اندازهٔ ۱۰ MB، podها را از کار انداخت
باگ کلاینت یا مهاجم، آرایهٔ بزرگ JSON را به endpoint دارای io.ReadAll و سپس json.Unmarshal فرستاد. حافظه به سه برابر اندازهٔ بدنه رسید و podها با OOM کشته شدند.
| راهحل | روش | مزیت | هزینه / محدودیت |
|---|---|---|---|
| سقف gateway | client_max_body_size 64k در Nginx، request-size-limiting در Kong | اصلاً به برنامه نمیرسد | باید برای هر Route باشد؛ خطای Nginx بهصورت HTML است |
LimitBody | رد سریع با Content-Length و MaxBytesReader | Chunked و کلاینت دروغگو را میگیرد؛ 413 با Problem Details | انتخاب اندازه برای هر Route |
| سقف عمق | checkDepth پیش از decode | بمب تودرتویی کمحجم را متوقف میکند | یک پیمایش token اضافی |
| Decode جریاندار | json.Decoder روی بدنهٔ محدودشده برای آرایه | حافظهٔ ثابت برای فهرست بزرگ | کد بیشتر |
رخداد: هزاران اتصال بیکار، سرویس Go دیگر اتصال نمیپذیرد
ss -tn هزاران اتصال ESTABLISHED از چند IP نشان میدهد که هدر ناقص فرستادهاند. سرویس از http.ListenAndServe(":8080", mux) بدون Timeout استفاده میکرد. اصلاح: harden.NewServer با ReadHeaderTimeout که TestSlowlorisHeaderTimeout اثباتش میکند، بهعلاوهٔ IdleTimeout و Timeout هدر gateway در جلو. قواعد gosec G112/G114 در CI مانع برگشت باگ شوند.
یافته: Bearer token در access log
یکپارچگی شریک ?access_token= میفرستاد و لاگ Nginx و برنامه آن را نود روز نگه داشت. اصلاح: اعتبارنامهٔ Query string را در gateway رد یا حذف کنید؛ فقط r.URL.Path را لاگ کنید و logger بر اساس کلید Redaction کند؛ شریک را به Authorization: Bearer منتقل کنید. سپس توکن ذخیرهشده را افشاشده بدانید: باطلش کنید و indexهای لاگ، همراه backupها، را پاک کنید.
یافته: CORS هر Origin را همراه credentials بازتاب میدهد
Access-Control-Allow-Origin مقدار Origin درخواست را کپی میکرد و Access-Control-Allow-Credentials: true فعال بود؛ هر وبسایت میتوانست /v1/me کاربر واردشده را بخواند.
| راهحل | روش | مزیت | هزینه / محدودیت |
|---|---|---|---|
| فهرست دقیق | CORSOptions.Origins، allowed_origins در Laravel | به origin بیگانه مجوز داده نمیشود | هر Frontend تازه تغییر config میخواهد |
| بدون credentials | توکن در Authorization از SPA، بدون cookie | اشتباه CORS دیگر نشست را افشا نمیکند | مسئولیت ذخیرهٔ توکن به SPA میرود |
| origin یکسان | سرو SPA و API زیر یک origin از gateway | اصلاً CORS لازم نیست | کار routing در لبه |
یافته: TRACE و PUT روی API فقطخواندنی فعالاند
Scanner دید TRACE درخواست، شامل Authorization، را بازتاب میدهد و PUT /v1/orders/42 پاسخ 200 دارد. اصلاح: AllowMethods عمومی، الگوی متد هر Route، limit_except در Nginx و تست پاسخ 405 همراه Allow برای هر متد استفادهنشده.
آزمون و Gateهای CI
یک job در GitHub Actions که گروه CI & CD را به بررسی شکستپذیر تبدیل میکند. نسخهها متعلق به زمان نگارش مثالاند؛ نسخهٔ خودتان را pin کنید:
name: security
on: [pull_request]
jobs:
go:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- uses: actions/setup-go@v5
with: { go-version: "1.27" }
- run: test -z "$(gofmt -l .)" && go vet ./... && go test -race -count=1 ./...
- run: go run golang.org/x/vuln/cmd/govulncheck@latest ./... # SCA, fails on reachable vulns
- run: go run github.com/securego/gosec/v2/cmd/gosec@latest ./... # SAST (G112, G114, ...)
- uses: gitleaks/gitleaks-action@v2 # secrets scanning
env: { GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" }
php:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: composer install --no-interaction --prefer-dist
- run: composer audit --locked --abandoned=fail # exit 1 on advisories
- run: php artisan test
dast:
needs: [go]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: bash docs/snippets/system-design/api-security-hardening-checklist/go/audit/audit.sh https://staging.example.com
- run: docker run -t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://staging.example.comحفاظت شاخه قواعد بازبینی را کامل میکند: بررسیهای security الزامی باشند؛ یک تأیید CODEOWNER لازم باشد؛ با commit تازه تأیید قدیمی لغو شود؛ نویسنده و مدیر اجازهٔ bypass نداشته باشند. Workflow بالا مورد انتظار است و اینجا اجرا نشده؛ در محیط تهیهٔ مثال CI runner وجود نداشت.
انتخاب
| وضعیت | کنترل اصلی | تکنیک مکمل | دلیل |
|---|---|---|---|
| هر API عمومی JSON | زنجیرهٔ Go یا Middlewareهای Laravel این فصل | همان قواعد در gateway | دفاع در عمق؛ برنامه آخرین لایهای است که همهٔ فراخوانها را میبیند |
| سرویسهای متعدد با تیم مستقل | Gateway برای اندازه، Timeout، هدر و نرخ | کتابخانهٔ Middleware مشترک برای هر زبان | لبه یکسان؛ Validation کسبوکار در سرویس میماند |
| API شریک یا عمومی دارای قرارداد | سند OpenAPI و Schema-first | Validation در لبه با APISIX یا Kong Enterprise و DTO در کد | رد پیش از هزینه؛ سند و کد از هم منحرف نمیشوند |
| SPA مرورگر روی origin دیگر | فهرست دقیق CORS | Credentials فقط در نیاز به cookie؛ Vary: Origin | CORS مجوز خواندن به سایت نامبرده است |
| فقط سروربهسرور | هیچ هدر CORS | mTLS یا درخواست امضاشده | بدون مرورگر CORS لازم نیست؛ هویت مهمتر است |
| آپلود بزرگ | Presigned URL به object storage | سقف اندازه و نوع در presign | بدنهٔ بزرگ از API دور میماند |
| گزارش یا export طولانی | 202، job و URL وضعیت | کلید Idempotency | هیچ handler چند دقیقه اجرا نمیشود |
| پشت proxy خاتمهدهندهٔ TLS | HSTS از لبه یا با TrustForwardedProto | trustProxies(at: ...) | پشت proxy مقدار r.TLS برابر nil است |
| لاگ دارای PII | Redaction در logger | Hash شناسهٔ کاربر، نگهداری کوتاه | لاگ همهجا کپی میشود |
| هر repo | govulncheck / composer audit و gitleaks در CI | Renovate یا Dependabot | CVE شناختهشده و کلید لورفته ارزانترین حملهاند |
| انتشار همراه تغییر Schema | مهاجرت Expand-and-contract | Blue-green یا Canary، Feature flag | بازگشت باید ممکن باشد |
در معماری: از یک فرایند تا سیستم توزیعشده
مونولیت: یک فرایند، یک پایگاه داده
یک زنجیرهٔ Middleware تمام Routeها را میپوشاند. مثال: مونولیت (Monolith) در Laravel پشت یک Nginx؛ SecurityHeaders و AssignRequestId در ابتدای stack عمومی، EnforceJsonApi در گروه api، فایل config/cors.php با origin برنامهٔ SPA، مقدار APP_DEBUG=false با محافظ هنگام boot، و Nginx با client_max_body_size، server_tokens off و Timeout هدر. ممیزی روی staging در هر deploy اجرا میشود. دشواری فقط استثناهاست، مثل Route آپلود با سقف بزرگتر؛ برای آن Middleware پارامتردار Route میگذاریم، نه قاعدهٔ عمومی ضعیفتر.
مونولیت ماژولار: مرز بدون شبکه
در مونولیت ماژولار (Modular monolith)، ماژولها لبهٔ HTTP مشترک دارند و زنجیره یکی است، اما هرکدام مالک DTO و Validation خودند. مثال: Orders و Billing در یک binary از Go، Routeهایشان را از طریق app.New روی یک ServeMux ثبت میکنند. ماژول نباید با ثبت روی http.DefaultServeMux، تابع Chain را دور بزند؛ قاعدهٔ lint یا تست الگوهای mux آن را الزام میکند. DTO پاسخ داخل ماژول است؛ پس Billing نمیتواند فیلد کارت را از endpoint متعلق به Orders که invoice را در خود دارد نشت دهد.
ریزسرویسها: هر پیکان یک تصمیم است
در ریزسرویسها (Microservices)، gateway کنترل یکسان لبه را اعمال میکند: TLS، HSTS، اندازه، Timeout هدر، نرخ، CORS برای SPA و حذف اثرانگشت؛ X-Request-ID را هم میسازد. هر سرویس زنجیرهٔ خودش را دارد، چون فراخوانندهٔ داخلی (Internal caller) از gateway نمیگذرد. نمونهٔ جریان: مرورگر ← Kong با request-size-limiting برابر ۶۴ KB، cors و response-transformer ← orders با زنجیرهٔ Go و RequestID(trustIncoming: true) برای حفظ شناسهٔ gateway، Validation و Problem Details ← payments روی mTLS با همان X-Request-ID. لاگ هر سه در یک index قرار میگیرد و با شناسه به هم مرتبط میشود. هر سرویس فهرست Route را صادر میکند؛ CI اجتماع آنها را با Routeهای gateway و سندهای OpenAPI میسنجد؛ همان API inventory. جای gateway در API gateway، BFF و service mesh و هویت سرویس در Mutual TLS است.
دادهٔ توزیعشده: Replica، Cache و Region
هدرهای Hardening با هر cache بین راه تعامل دارند. برای پاسخ شخصی، Cache-Control: no-store باید به CDN و proxy مشترک برسد؛ وگرنه /v1/me کاربر اول به بعدی میرسد. endpoint عمومی غیرشخصی میتواند صریحاً cache را با public, max-age=60 فعال کند؛ آنوقت برای هر هدر تغییردهندهٔ پاسخ، از جمله Origin در CORS، باید Vary داشته باشد. Problem Details و Request id باید از CDN سالم عبور کنند؛ بعضی CDNها بدنهٔ 5xx را با HTML خود عوض میکنند، پس عبور خطای origin را تنظیم کنید. لاگ چند منطقه (Region) برای مرتبطشدن به مبنای زمان یکسان، UTC و RFC 3339، و قالب شناسهٔ واحد نیاز دارد. Redaction باید پیش از عبور لاگ از مرز Region دارای قواعد متفاوت اقامت داده انجام شود.
مسیر رشد: 1x، 10x و 100x
| مقیاس | چه چیز تغییر میکند |
|---|---|
| 1x؛ یک برنامه، یک تیم | زنجیرهٔ Middleware یا Middlewareهای Laravel، سقف Nginx، CI با govulncheck/composer audit/gitleaks، ممیزی curl روی staging |
| 10x؛ چند سرویس و تیم | Gateway با Kong، Envoy یا APISIX مالک کنترل لبه؛ کتابخانهٔ Hardening مشترک هر زبان؛ لاگ متمرکز و هشدار؛ OpenAPI هر سرویس و مقایسه در CI برای Inventory؛ ZAP baseline در staging |
| 100x؛ پلتفرم چندمنطقهای | قرارداد Schema-first با Validation در لبه؛ policy-as-code برای gateway؛ مدیریت مرکزی WAF و IDS/IPS؛ Pipeline لاگ هر Region با Redaction در مبدأ؛ مسئول امنیت و CODEOWNERS برای کتابخانهٔ Hardening؛ Canary با سنجهٔ امنیت بهعنوان محرک Rollback |
آزمایشگاه
مراحل ۱ تا ۵ در تهیهٔ این مثال روی ماشین macOS با Go 1.27.4، نسخهٔ 3.2.57 از /bin/bash و curl اجرا شدهاند؛ تاریخ اجرا ۲۰۲۶-۱۱-۲۹ است. خروجی جز در محل علامتخورده بدون ویرایش آمده است. مراحل ۶ تا ۹ مورد انتظارند و اجرا نشدهاند؛ محیط تهیهٔ مثال برنامهٔ Laravel، Docker و scanner نصبشده نداشت.
۱. قالببندی، vet و تست ماژول؛ اجرای واقعی:
$ cd docs/snippets/system-design/api-security-hardening-checklist/go
$ gofmt -l . && go vet ./...
$ go test -race -count=1 ./...
ok academy/api-security-hardening-checklist/app
ok academy/api-security-hardening-checklist/before
? academy/api-security-hardening-checklist/cmd/apiserver [no test files]
ok academy/api-security-hardening-checklist/hardenزمانها حذف شدهاند. go test -v پنجاه تست و زیرتست موفق در harden و هجده مورد در app و before میشمارد.
۲. سرور سختشده را بالا بیاورید و ممیزی را اجرا کنید؛ اجرای واقعی. پورت ۱۸۴۸۸ برای جلوگیری از تداخل انتخاب شد. binary در دایرکتوری موقت ساخته شد و اینجا با /tmp/apiserver نشان داده میشود:
$ go build -o /tmp/apiserver ./cmd/apiserver
$ APP_ENV=production /tmp/apiserver -addr 127.0.0.1:18488 &
$ bash audit/audit.sh http://127.0.0.1:18488
== Output: security headers on GET /v1/orders/6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f
PASS X-Content-Type-Options contains nosniff
PASS X-Frame-Options contains DENY
PASS Content-Security-Policy contains default-src 'none'
PASS Cache-Control contains no-store
PASS Referrer-Policy contains no-referrer
PASS Server absent
PASS X-Powered-By absent
SKIP Strict-Transport-Security (plain HTTP: RFC 6797 forbids HSTS here)
PASS Content-Type is application/json
PASS X-Request-ID present
PASS no sensitive fields in body
== Input: methods, media types, size, schema
PASS TRACE -> 405
PASS 405 carries Allow
PASS POST text/plain -> 415
PASS Accept: application/xml -> 406
PASS 2 MiB body (Content-Length) -> 413
PASS 2 MiB body (chunked) -> 413
PASS JSON nested 100 deep -> 400
PASS unknown field price -> 400
PASS invalid values -> 422
PASS valid order -> 201
== Processing: errors and timeouts
PASS handler panic -> 500
PASS 500 is application/problem+json
PASS 500 without stack trace or internal address
PASS GET /.env -> 404
PASS 404 is application/problem+json
PASS 405 is application/problem+json
PASS 415 is application/problem+json
PASS slow handler cut by the deadline -> 503
== CORS
PASS preflight from allowed origin -> 204
PASS ACAO echoes the allowed origin only
PASS no ACAO for a foreign origin
== Result: 31 passed, 0 failed, 1 skipped
$ echo $?
0خود script با bash 3.2 سازگار است؛ خروجی شناسهٔ درخواست و زمان ندارد، پس دو اجرا خطهای یکسان چاپ میکنند:
#!/usr/bin/env bash
# audit.sh - curl audit of an API against the hardening checklist.
# Usage: audit.sh http://127.0.0.1:18488 (exit 1 if any check fails)
# Works with bash 3.2 (macOS) and GNU or BSD tools. Prints no ids or times,
# so two runs against the same server give the same output.
# Environment (defaults fit the Go lab server):
# API_PREFIX=/v1 e.g. /api/v1 for Laravel
# ORDER_ID=<uuid> an order that exists and the caller may read
# AUTH_HEADER= e.g. "Authorization: Bearer <token>" (never logged)
# UNKNOWN_FIELD_CODE=400 Laravel's StoreOrderRequest answers 422
# DEEP_JSON_CODE=400 Go's depth limit; Laravel's validation answers 422
# LAB_ROUTES=1 0 skips the /lab/panic and /lab/slow checks
# ORIGIN=https://shop.example an origin the CORS allow-list contains
set -u
BASE=${1:-http://127.0.0.1:18488}
P=${API_PREFIX:-/v1}
ORDER=$P/orders/${ORDER_ID:-6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f}
UNKNOWN=${UNKNOWN_FIELD_CODE:-400}
DEEP=${DEEP_JSON_CODE:-400}
LAB=${LAB_ROUTES:-1}
ORIGIN=${ORIGIN:-https://shop.example}
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
pass=0 fail=0 skip=0
ok() { pass=$((pass + 1)); printf 'PASS %s\n' "$1"; }
bad() { fail=$((fail + 1)); printf 'FAIL %s (%s)\n' "$1" "$2"; }
skp() { skip=$((skip + 1)); printf 'SKIP %s (%s)\n' "$1" "$2"; }
# req NAME [curl args...]: stores status in $TMP/NAME.code, headers, body.
req() {
n=$1; shift
if [ -n "${AUTH_HEADER:-}" ]; then set -- -H "$AUTH_HEADER" "$@"; fi
curl -s -o "$TMP/$n.body" -D "$TMP/$n.hdr" -w '%{http_code}' "$@" >"$TMP/$n.code" 2>/dev/null
}
code() { cat "$TMP/$1.code"; }
hdr() { tr -d '\r' <"$TMP/$1.hdr" | grep -i "^$2:" | head -1 | cut -d: -f2- | sed 's/^ *//'; }
body_has() { grep -q -- "$2" "$TMP/$1.body"; }
expect_code() { # NAME WANT LABEL
got=$(code "$1")
if [ "$got" = "$2" ]; then ok "$3 -> $2"; else bad "$3 -> $2" "got $got"; fi
}
expect_problem() { # NAME LABEL
ct=$(hdr "$1" Content-Type)
case "$ct" in
application/problem+json*) ok "$2 is application/problem+json" ;;
*) bad "$2 is application/problem+json" "Content-Type: ${ct:-none}" ;;
esac
}
echo "== Output: security headers on GET $ORDER"
req get "$BASE$ORDER"
for pair in "X-Content-Type-Options|nosniff" "X-Frame-Options|DENY" \
"Content-Security-Policy|default-src 'none'" "Cache-Control|no-store" \
"Referrer-Policy|no-referrer"; do
name=${pair%%|*}; want=${pair#*|}; got=$(hdr get "$name")
case "$got" in
*"$want"*) ok "$name contains $want" ;;
*) bad "$name contains $want" "got '${got:-absent}'" ;;
esac
done
for name in Server X-Powered-By; do
got=$(hdr get "$name")
if [ -z "$got" ]; then ok "$name absent"; else bad "$name absent" "got '$got'"; fi
done
case "$BASE" in
https:*) if [ -n "$(hdr get Strict-Transport-Security)" ]; then ok "HSTS present"; else bad "HSTS present" "absent"; fi ;;
*) skp "Strict-Transport-Security" "plain HTTP: RFC 6797 forbids HSTS here" ;;
esac
case "$(hdr get Content-Type)" in
application/json*) ok "Content-Type is application/json" ;;
*) bad "Content-Type is application/json" "got '$(hdr get Content-Type)'" ;;
esac
if [ -n "$(hdr get X-Request-ID)" ]; then ok "X-Request-ID present"; else bad "X-Request-ID present" "absent"; fi
if body_has get card_number; then bad "no sensitive fields in body" "card_number returned"; else ok "no sensitive fields in body"; fi
echo "== Input: methods, media types, size, schema"
req trace -X TRACE "$BASE$ORDER"
expect_code trace 405 "TRACE"
if [ -n "$(hdr trace Allow)" ]; then ok "405 carries Allow"; else bad "405 carries Allow" "no Allow header"; fi
req ctype -X POST -H 'Content-Type: text/plain' --data '{"sku":"MUG-01"}' "$BASE$P/orders"
expect_code ctype 415 "POST text/plain"
req accept -H 'Accept: application/xml' "$BASE$ORDER"
expect_code accept 406 "Accept: application/xml"
head -c 2097152 /dev/zero | tr '\0' 'A' >"$TMP/big.json"
req big -X POST -H 'Content-Type: application/json' --data-binary @"$TMP/big.json" "$BASE$P/orders"
expect_code big 413 "2 MiB body (Content-Length)"
req chunked -X POST -H 'Content-Type: application/json' -H 'Transfer-Encoding: chunked' --data-binary @"$TMP/big.json" "$BASE$P/orders"
expect_code chunked 413 "2 MiB body (chunked)"
deep=$(printf '%0.s[' $(seq 1 100))$(printf '%0.s]' $(seq 1 100))
req deep -X POST -H 'Content-Type: application/json' --data "$deep" "$BASE$P/orders"
expect_code deep "$DEEP" "JSON nested 100 deep"
req unknown -X POST -H 'Content-Type: application/json' --data '{"sku":"MUG-01","quantity":1,"currency":"EUR","price":0}' "$BASE$P/orders"
expect_code unknown "$UNKNOWN" "unknown field price"
req invalid -X POST -H 'Content-Type: application/json' --data '{"sku":"x","quantity":0,"currency":"BTC"}' "$BASE$P/orders"
expect_code invalid 422 "invalid values"
req created -X POST -H 'Content-Type: application/json' --data '{"sku":"MUG-01","quantity":2,"currency":"EUR"}' "$BASE$P/orders"
expect_code created 201 "valid order"
echo "== Processing: errors and timeouts"
if [ "$LAB" = 1 ]; then
req panic "$BASE$P/lab/panic"
expect_code panic 500 "handler panic"
expect_problem panic "500"
if body_has panic goroutine || body_has panic 10.0.3.7; then bad "500 without stack trace or internal address" "leaked"; else ok "500 without stack trace or internal address"; fi
else
skp "handler panic -> 500" "LAB_ROUTES=0"
fi
req notfound -H 'Accept: application/json' "$BASE/.env"
expect_code notfound 404 "GET /.env"
expect_problem notfound "404"
expect_problem trace "405"
expect_problem ctype "415"
if [ "$LAB" = 1 ]; then
req slow --max-time 4 "$BASE$P/lab/slow"
expect_code slow 503 "slow handler cut by the deadline"
else
skp "slow handler cut by the deadline" "LAB_ROUTES=0"
fi
echo "== CORS"
req pre -X OPTIONS -H "Origin: $ORIGIN" -H 'Access-Control-Request-Method: POST' "$BASE$P/orders"
expect_code pre 204 "preflight from allowed origin"
if [ "$(hdr pre Access-Control-Allow-Origin)" = "$ORIGIN" ]; then ok "ACAO echoes the allowed origin only"; else bad "ACAO echoes the allowed origin only" "got '$(hdr pre Access-Control-Allow-Origin)'"; fi
req evil -X OPTIONS -H 'Origin: https://evil.example' -H 'Access-Control-Request-Method: POST' "$BASE$P/orders"
if [ -z "$(hdr evil Access-Control-Allow-Origin)" ]; then ok "no ACAO for a foreign origin"; else bad "no ACAO for a foreign origin" "got '$(hdr evil Access-Control-Allow-Origin)'"; fi
echo "== Result: $pass passed, $fail failed, $skip skipped"
[ "$fail" -eq 0 ]Script با متغیرهای محیطی API_PREFIX، ORDER_ID، AUTH_HEADER، UNKNOWN_FIELD_CODE، DEEP_JSON_CODE، LAB_ROUTES و ORIGIN تنظیم میشود. Probe مربوط به /.env هدر Accept: application/json میفرستد تا Laravel خطای Problem JSON رندر کند؛ پیشفرضها مناسب سرور Go هستند. اجرای واقعی دوم روی همان Go، با Routeهای آزمایشگاهی خاموش و هدر Authorization ارسالشده است؛ API آزمایشگاهی Go آن را نادیده میگیرد. فقط عنوان بخش و خط SKIP آمده؛ تمام خطهای دیگر مانند اجرای پیشفرض PASS هستند. همین متغیرها سازگاری با Laravel را فراهم میکنند؛ مرحلهٔ ۷ مورد انتظار و اجرانشده است:
$ LAB_ROUTES=0 AUTH_HEADER='Authorization: Bearer lab-token' bash audit/audit.sh http://127.0.0.1:18488
== Output: security headers on GET /v1/orders/6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f
SKIP Strict-Transport-Security (plain HTTP: RFC 6797 forbids HSTS here)
== Input: methods, media types, size, schema
== Processing: errors and timeouts
SKIP handler panic -> 500 (LAB_ROUTES=0)
SKIP slow handler cut by the deadline (LAB_ROUTES=0)
== CORS
== Result: 27 passed, 0 failed, 3 skipped
$ echo $?
0۳. همان script روی سرور «قبل»، اجرای واقعی: بیستونه بررسی از سیویک مورد شکست میخورند. هر FAIL یک بند چکلیست است.
$ /tmp/apiserver -mode before -addr 127.0.0.1:18489 &
$ bash audit/audit.sh http://127.0.0.1:18489
== Output: security headers on GET /v1/orders/6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f
FAIL X-Content-Type-Options contains nosniff (got 'absent')
FAIL X-Frame-Options contains DENY (got 'absent')
FAIL Content-Security-Policy contains default-src 'none' (got 'absent')
FAIL Cache-Control contains no-store (got 'absent')
FAIL Referrer-Policy contains no-referrer (got 'absent')
FAIL Server absent (got 'orders-api/0.9.1 (go1.22.1; linux)')
FAIL X-Powered-By absent (got 'academy-framework/2.3')
SKIP Strict-Transport-Security (plain HTTP: RFC 6797 forbids HSTS here)
FAIL Content-Type is application/json (got '*/*')
FAIL X-Request-ID present (absent)
FAIL no sensitive fields in body (card_number returned)
== Input: methods, media types, size, schema
FAIL TRACE -> 405 (got 200)
FAIL 405 carries Allow (no Allow header)
FAIL POST text/plain -> 415 (got 200)
FAIL Accept: application/xml -> 406 (got 200)
FAIL 2 MiB body (Content-Length) -> 413 (got 500)
FAIL 2 MiB body (chunked) -> 413 (got 500)
FAIL JSON nested 100 deep -> 400 (got 500)
FAIL unknown field price -> 400 (got 200)
FAIL invalid values -> 422 (got 200)
FAIL valid order -> 201 (got 200)
== Processing: errors and timeouts
PASS handler panic -> 500
FAIL 500 is application/problem+json (Content-Type: text/plain; charset=utf-8)
FAIL 500 without stack trace or internal address (leaked)
FAIL GET /.env -> 404 (got 200)
FAIL 404 is application/problem+json (Content-Type: none)
FAIL 405 is application/problem+json (Content-Type: */*)
FAIL 415 is application/problem+json (Content-Type: text/plain; charset=utf-8)
FAIL slow handler cut by the deadline -> 503 (got 200)
== CORS
FAIL preflight from allowed origin -> 204 (got 500)
FAIL ACAO echoes the allowed origin only (got '')
PASS no ACAO for a foreign origin
== Result: 2 passed, 29 failed, 1 skipped
$ echo $?
1پاسخ سرور «قبل» به TRACE و Panic، اجرای واقعی؛ بدنهٔ Panic پس از اولین frameها قطع و home directory در مسیر فایل با … جایگزین شده است:
$ curl -si -X TRACE http://127.0.0.1:18489/v1/orders/42
HTTP/1.1 200 OK
Content-Type: */*
Server: orders-api/0.9.1 (go1.22.1; linux)
X-Powered-By: academy-framework/2.3
Date: Sun, 29 Nov 2026 09:29:02 GMT
Content-Length: 91
{"id":"42","sku":"MUG-01","quantity":2,"card_number":"4111111111111111","risk_score":0.12}
$ curl -s http://127.0.0.1:18489/v1/lab/panic | head -6
panic: db: connection refused at 10.0.3.7:5432 user=orders_rw
goroutine 70 [running]:
runtime/debug.Stack()
/opt/homebrew/Cellar/go/1.27.4/libexec/src/runtime/debug/stack.go:26 +0x64
academy/api-security-hardening-checklist/before.New.func1.1()۴. پاسخ سرور سختشده به همان درخواستها؛ اجرای واقعی با curl -si. شناسهٔ درخواست در هر اجرا فرق میکند:
$ curl -si http://127.0.0.1:18488/v1/lab/panic
HTTP/1.1 500 Internal Server Error
Cache-Control: no-store
Content-Security-Policy: default-src 'none'; frame-ancestors 'none'
Content-Type: application/problem+json
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
Referrer-Policy: no-referrer
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Request-Id: 647202a4b7fd59f1cd5f3315
Date: Sun, 29 Nov 2026 09:29:12 GMT
Content-Length: 134
{"type":"about:blank","title":"Internal Server Error","status":500,"detail":"internal error","request_id":"647202a4b7fd59f1cd5f3315"}
$ head -c 100000 /dev/zero | tr '\0' 'A' > 100k.json # a 100,000-byte body, above the 64 KiB limit
$ curl -si -X POST -H "Content-Type: application/json" --data-binary @100k.json http://127.0.0.1:18488/v1/orders
HTTP/1.1 413 Request Entity Too Large
Cache-Control: no-store
Connection: close
Content-Security-Policy: default-src 'none'; frame-ancestors 'none'
Content-Type: application/problem+json
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
Referrer-Policy: no-referrer
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Request-Id: ea0cd1f3b6fe09d1e0b2dff0
Date: Sun, 29 Nov 2026 09:29:12 GMT
Content-Length: 138
{"type":"about:blank","title":"Content Too Large","status":413,"detail":"request body too large","request_id":"ea0cd1f3b6fe09d1e0b2dff0"}به تفاوت خط وضعیت 413 Request Entity Too Large از http.StatusText در Go و عنوان Problem برابر Content Too Large از RFC 9110، و نیز Connection: close دقت کنید. Stack trace مربوط به Panic در stderr سرور بهصورت یک خط JSON با همان request_id ثبت شد.
۵. محافظ خاموشی debug؛ اجرای واقعی:
$ APP_ENV=production APP_DEBUG=true /tmp/apiserver -addr 127.0.0.1:18490
2026/11/29 12:59:12 unsafe production configuration: debug mode is on
$ echo $?
1۶. مورد انتظار، اجرانشده: اسکن وابستگی و کد ماژول Go.
$ go run golang.org/x/vuln/cmd/govulncheck@latest ./...
No vulnerabilities found.
$ go run github.com/securego/gosec/v2/cmd/gosec@latest ./...گزارش govulncheck به نسخهٔ toolchain و ماژولها وابسته است؛ advisory مربوط به stdlib که بعد از Go 1.27.4 اصلاح شده باشد اینجا با call path ظاهر میشود. انتظار میرود gosec شاخهٔ «قبل» در cmd/apiserver/main.go را، بهخاطر http.Server فاقد ReadHeaderTimeout، با G112 علامت بزند. خروجی دقیق به نسخهٔ gosec بستگی دارد و اینجا درج نشده است.
۷. مورد انتظار، اجرانشده: برنامهٔ Laravel 13 با فایلهای PHP این فصل، اجرای قبلی php artisan config:publish cors و نصب Sanctum:
$ php artisan test --filter=ApiHardeningTest
PASS Tests\Feature\ApiHardeningTest
✓ every api response has the output headers
✓ wrong verb is 405 with allow
✓ non json body is 415
✓ accept without json is 406
✓ unknown fields and bad values are 422
✓ response never contains the card number
✓ cors preflight carries the security headers
✓ server errors do not leak traces
✓ unknown route is a problem 404
Tests: 9 passed
$ composer audit --locked
No security vulnerability advisories found.
$ API_PREFIX=/api/v1 ORDER_ID=<uuid of a seeded order> AUTH_HEADER='Authorization: Bearer <sanctum token>' \
UNKNOWN_FIELD_CODE=422 DEEP_JSON_CODE=422 LAB_ROUTES=0 bash audit.sh https://app.test۸. مورد انتظار، اجرانشده: اسکن راز. دستور gitleaks git -v در repo هر یافته را با فایل، خط و قاعده چاپ میکند. کلید جعلی مثل AKIA بهعلاوهٔ شانزده نویسه در فایل تست اضافه کنید تا گزارش شود. gitleaks git --redact راز را از لاگ CI بیرون نگه میدارد.
۹. مورد انتظار، اجرانشده: DAST روی staging. دستور docker run -t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://staging.example.com طبق مستندات ZAP با صفر، یک برای FAIL، دو برای فقط WARN یا سه برای خطای دیگر خارج میشود. با تنظیم هدرها، قواعد مرتبط با هدر از WARN به PASS میروند.
آزمایش بیشتر: ReadHeaderTimeout را در server_test.go صفر کنید و شکست TestSlowlorisHeaderTimeout پس از سه ثانیه را ببینید؛ innermost(w) را در bodylimit.go با w عوض کنید و شکست TestLimitClosesConnectionThroughWrappers را ببینید. هر دو تغییر هنگام تهیهٔ مثال امتحان شده و مطابق انتظار شکست خوردهاند. جابهجایی SecurityHeaders به زیر AllowMethods در app.go نیز باید هدرهای مورد TRACE در TestEveryResponseIsHardened را حذف کند؛ این تغییر امتحان نشده است.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| هدر امنیتی برای API با JSON کاری نمیکند | برای curl اثری ندارد؛ با ورود مرورگر مهم میشود و هزینهای ندارد؛ OWASP REST: "all API responses that may be consumed by browser clients" |
بررسی Content-Length بدنه را محدود میکند | Chunked طول ندارد؛ محدودیت واقعی MaxBytesReader یا سقف buffer در gateway است |
| 405 فقط یک کد است | طبق RFC 9110 باید Allow داشته باشد؛ بدون فهرست عمومی متد، فعل ناشناخته به handler میرسد |
هر درخواست Content-Type میخواهد | فقط درخواست دارای بدنه؛ OWASP: "Do not require Content-Type solely for requests without a body" |
WriteTimeout، handler کند را متوقف میکند | اتصال را میبندد؛ handler ادامه میدهد؛ http.TimeoutHandler یا deadline در context لازم است |
http.TimeoutHandler پاسخ 504 میدهد | source فعلی net/http پاسخ 503 Service Unavailable میدهد؛ عدد 504 در نوشتههای قدیمی منسوخ است |
| Go به Slowloris پاسخ 408 میدهد | هنگام Timeout خواندن هدر اتصال را بیپاسخ میبندد؛ Nginx پاسخ 408 میدهد |
| HSTS روی تمام پاسخها لازم است | RFC 6797 ارسال آن روی HTTP ساده را ممنوع میکند؛ فقط روی TLS یا از لبهٔ خاتمهدهندهٔ TLS |
| CORS محافظ API است | مجوز خواندن سایتها برای مرورگر است؛ کلاینت غیرمرورگر نادیده میگیرد |
Access-Control-Allow-Origin: * با credentials کار میکند | مرورگر رد میکند؛ بازتاب بعدی Origin توسط توسعهدهنده بدتر است؛ origin دقیق بنویسید |
حذف Server، stack را مخفی میکند | فقط ارزانترین نشانه حذف میشود؛ OWASP: مهاجمان "have other means of fingerprinting" |
| Debug برای بررسی سریع Production اشکال ندارد | یک عبور scanner برای برداشت صفحه کافی است؛ Laravel دربارهٔ "sensitive configuration values" هشدار میدهد |
| ثبت کل درخواست به پاسخ رخداد کمک میکند | توکن و PII را در تمام محلهای لاگ تکثیر میکند؛ شناسه و نتیجه را ثبت و بر اساس کلید Redaction کنید |
| Gateway اعتبارسنجی میکند؛ سرویس لازم ندارد | فراخوان داخلی از gateway نمیگذرد؛ قواعد کسبوکار و فیلد حساس را فقط سرویس میداند |
| Scanner در CI یعنی امنیت | SAST، SCA، اسکن راز و DAST هرکدام بخشی را میبینند؛ نبود مجوز را نمیبینند؛ یافته باید build را شکست دهد |
برگهٔ تقلب
| موضوع | چیزی که باید حفظ باشید |
|---|---|
| ترتیب زنجیره | Request id ← access log ← هدر ← بازنویسی Problem ← recover ← CORS ← فهرست متد ← فقط JSON ← سقف بدنه ← Timeout handler ← router |
| متد | فهرست عمومی و الگوی هر Route؛ 405 با Allow؛ رد هدر method override |
| نوع رسانه | بدنه دارد → application/json لازم است، وگرنه 415 و Accept؛ Accept بدون JSON → 406؛ هرگز Accept را در Content-Type کپی نکنید |
| اندازهٔ بدنه | رد سریع با Content-Length و http.MaxBytesReader با writer واقعی net/http؛ 413؛ سقف gateway در بیرون |
| JSON | سقف عمق پیش از decode، DisallowUnknownFields، یک مقدار، سپس قواعد فیلد با 422 |
| هدر | nosniff، DENY، default-src 'none'; frame-ancestors 'none'، no-store، no-referrer و HSTS فقط روی TLS |
| اثرانگشت | حذف Server و X-Powered-By هنگام نوشتن؛ server_tokens off؛ expose_php = Off |
| خطا | RFC 9457 با application/problem+json، Request id و بدون Stack trace؛ 4xx برای خطای کلاینت، 5xx برای ما |
| پاسخ | DTO خروجی یا JsonResource؛ model ذخیرهسازی را serialise نکنید |
| Debug | Production با debug روشن نباید شروع شود؛ Config.Validate و AppServiceProvider |
| Timeout | ReadHeaderTimeout، ReadTimeout، WriteTimeout، IdleTimeout، TimeoutHandler با 503؛ صفر هدر/بیکاری به ReadTimeout برمیگردد، صفر خواندن/نوشتن یعنی بدون Timeout؛ هر چهار را تعیین کنید |
| CORS | origin دقیق، Vary: Origin، credentials فقط با origin صریح، 403 برای Preflight بیگانه |
| لاگ | یک خط JSON در هر درخواست؛ path بدون query؛ Redaction بر اساس کلید؛ Request id در هر خط و هدر پاسخ |
| CI | govulncheck، composer audit --locked، gosec/semgrep، gitleaks، ZAP baseline و audit.sh روی staging، بازبینی CODEOWNERS |
| انتشار | برنامهٔ Rollback پیش از deploy: Blue-green یا Canary، Feature flag و مهاجرت Expand-and-contract |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا LimitBody بهجای w، مقدار innermost(w) را به http.MaxBytesReader میدهد؟ مهم
پاسخ
پاسخ: MaxBytesReader با فراخوانی متدی exportنشده روی نوع پاسخ خود net/http به سرور میگوید پس از عبور از سقف اتصال را ببندد. Wrapperهایی مثل stripWriter و statusWriter آن متد را ندارند؛ پیام بیصدا گم میشود و سرور ممکن است تخلیهٔ بدنهٔ مهاجم را ادامه دهد. هر wrapper زنجیره Unwrap() دارد و innermost تا writer واقعی پایین میرود؛ با دادن w، تست TestLimitClosesConnectionThroughWrappers شکست میخورد. سقف بدنه.
۲ — آیا GET بدون Content-Type پاسخ 415 میگیرد؟ POST با Transfer-Encoding: chunked بدون این هدر چطور؟ حیاتی
پاسخ
پاسخ: GET عبور میکند چون بدنه ندارد؛ OWASP: "Do not require Content-Type solely for requests without a body." اما POST با Transfer-Encoding: chunked بدنه با طول نامعلوم دارد؛ در Go مقدار ContentLength == -1 است. پس باید application/json را اعلام کند؛ بدون آن 415 با هدر پاسخ Accept: application/json میگیرد. Content-Type و Accept.
۳ — پاسخ 405 چه چیزی باید داشته باشد و دو لایهٔ تولیدکنندهٔ آن کداماند؟ حیاتی
پاسخ
پاسخ: طبق RFC 9110، سرور مبدأ باید هدر Allow با فهرست متدهای پشتیبانیشده بفرستد. در Go، AllowMethods متد خارج از فهرست عمومی، مثل TRACE، CONNECT و متد ساختگی، را رد میکند. الگوهای ServeMux هم متد غلط روی مسیر شناختهشده را رد میکنند؛ مثل POST روی GET /v1/orders/{id}. سپس ProblemErrors پاسخ متن سادهٔ 405 را به Problem JSON تبدیل میکند و Allow را حفظ میکند. فهرست متد.
۴ — چرا سرور آزمایشگاه HSTS نمیفرستد و پشت متعادلکنندهٔ بار خاتمهدهندهٔ TLS چگونه آن را میفرستید؟ مهم
پاسخ
پاسخ: RFC 6797 بخش 7.2: "An HSTS Host MUST NOT include the STS header field in HTTP responses conveyed over non-secure transport." آزمایشگاه روی HTTP سادهٔ localhost است؛ script برای HSTS مقدار SKIP میدهد. پشت متعادلکنندهٔ بار، r.TLS برابر nil است؛ HSTS را در لبه تنظیم کنید یا TrustForwardedProto در Go و trustProxies(at: ...) همراه $request->isSecure() در Laravel را فعال کنید تا X-Forwarded-Proto: https از proxy مورد اعتماد معتبر باشد. هدرهای امنیتی.
۵ — کدام فیلد http.Server جلوی Slowloris را میگیرد، Go هنگام فعالشدن چه میفرستد و تفاوتش با Nginx چیست؟ حیاتی
پاسخ
پاسخ: ReadHeaderTimeout. اگر هدر بهموقع نرسد Go بدون نوشتن پاسخ اتصال را میبندد؛ "common net read error" با قاعدهٔ "don't reply"، و تست EOF با صفر بایت میخواند. در Nginx، client_header_timeout با پیشفرض شصت ثانیه پاسخ 408 Request Timeout میدهد. با صفر بودن همهٔ Timeoutهای http.Server، چند هزار کلاینت کند میتوانند تمام اتصالها را نگه دارند. Timeoutها.
۶ — http.TimeoutHandler چه کدی میدهد و چرا WriteTimeout جای آن را نمیگیرد؟ مهم
پاسخ
پاسخ: طبق source فعلی net/http، پاسخ 503 Service Unavailable میدهد؛ نوشتههای قدیمی 504 میگویند. Context درخواست را هم لغو میکند تا handler درستنوشتهشده متوقف شود. WriteTimeout فقط اتصال را پس از Timeout میبندد؛ کلاینت reset میگیرد و handler همچنان کار میکند و منابع نگه میدارد. هر دو لازماند: Timeout handler برای کار و Timeout سرور برای socket. Timeoutها.
۷ — API پاسخ {"error": "pq: password authentication failed for user orders_rw"} را با کد 200 میدهد؛ ایرادها چیست؟ حیاتی
پاسخ
پاسخ: کد اشتباه است؛ شکست باید 500 باشد، نه 200، و کلاینت نمیتواند موفقیت را از شکست تشخیص دهد. بدنه نام driver و کاربر پایگاه داده را لو میدهد، شکل Problem Details ندارد و احتمالاً Request id برای ارتباط با لاگ هم ندارد. خطا را در بیرونیترین لایه بگیرید، با شناسه لاگ کنید و application/problem+json با کد 500، detail عمومی و request_id برگردانید. RFC 9457 دربارهٔ افشای جزئیات پیادهسازی هشدار میدهد. پاسخ خطا.
۸ — چرا بدنهٔ JSON با اندازهٔ ۲۰ KB هم خطرناک است و کدام بررسی آن را میگیرد؟ مهم
پاسخ
پاسخ: بیست کیلوبایت نویسهٔ [ یعنی ده هزار سطح تودرتویی؛ parser بازگشتی و پردازش بعدی، مانند Validation، Logging و serialise دوباره، میتواند stack یا CPU را از پا درآورد و سقف اندازه متوجه نشود. OWASP: "configure parser limits such as maximum nesting depth". تابع checkDepth یکبار tokenها را پیمایش میکند و پیش از decode، عمق بیشتر از MaxJSONDepth یعنی شانزده را با 400 رد میکند؛ سقف داخلی Go ده هزار است. اعتبارسنجی ورودی.
۹ — SPA برای فراخوان cross-origin به cookie نیاز دارد؛ پاسخ دقیق Preflight چیست و چه چیزی هرگز نباید در آن باشد؟ حیاتی
پاسخ
پاسخ: Access-Control-Allow-Origin با یک origin دقیق پس از بررسی فهرست مجاز، Access-Control-Allow-Credentials: true، متد و هدر مجاز، Max-Age و Vary: Origin. هرگز * را با credentials ندهید؛ MDN: سرور "must specify an origin ... instead of specifying the * wildcard". همچنین هرگز Origin را بدون بررسی بازتاب ندهید، چون به هر وبسایت دسترسی دادهٔ کاربر میدهد. CORS.
۱۰ — چه چیزهایی نباید در access log باشند و نمونههای Go و Laravel چطور این را الزام میکنند؟ حیاتی
پاسخ
پاسخ: توکن، کلید API، شناسهٔ نشست، گذرواژه، دادهٔ کارت، connection string و دادهٔ شخصی مثل ایمیل؛ بخش "Data to exclude" در OWASP Logging Cheat Sheet. در Go، AccessLog فقط r.URL.Path بدون Query string و بدون هدر را ثبت میکند و ReplaceAttr در NewLogger هر کلید حساس را هرجا باشد به [REDACTED] بدل میکند. در Laravel، tap به نام RedactSensitiveData یک processor در Monolog میافزاید که همان کلیدها را در context و extra میپوشاند. ثبت لاگ.
۱۱ — چهار نوع بررسی امنیت CI این فصل و یک ابزار برای هرکدام را نام ببرید. مهم
پاسخ
پاسخ: اسکن وابستگی یا SCA با govulncheck آگاه از دسترسیپذیری و composer audit با خروج یک در صورت یافته. SAST با gosec، قاعدهٔ G112 برای نبود ReadHeaderTimeout، semgrep و PHPStan. اسکن راز با gitleaks و gitleaks git. DAST با OWASP ZAP baseline و audit.sh این فصل روی staging؛ در کنارشان تأیید CODEOWNERS و ممنوعیت تأیید توسط خود نویسنده لازم است. Gateهای CI/CD.
۱۲ — چرا UUID در URL اصلاح بند "Avoid user's personal ID in the resource URLs" نیست؟ تکمیلی
پاسخ
پاسخ: شناسهٔ حدسناپذیر پیمایش را سخت میکند، ولی شناسه از لاگ، لینک مشترک یا پاسخ API دیگر لو میرود. پس از دانستن آن، نبود بررسی مجوز شیء همچنان شیء را به هرکس میدهد. کنترل اصلی بررسی مالکیت در هر درخواست است؛ BOLA یا API1:2023 در OWASP API Security Top 10. UUID لایهٔ دوم است. بندهای پردازش.
۱۳ — همپوشانی X-Frame-Options: DENY و frame-ancestors 'none' چیست و چرا هر دو را میفرستیم؟ تکمیلی
پاسخ
پاسخ: هر دو framing را ممنوع میکنند. OWASP، X-Frame-Options را "Legacy header superseded by Content-Security-Policy: frame-ancestors 'none'" مینامد و میگوید "Still recommended for compatibility with older browsers that do not support CSP Level 2". چکلیست roadmap هم صریحاً X-Frame-Options: deny میخواهد. ارسال هر دو چند بایت هزینه دارد و نیاز scanner و کلاینت قدیمی را پوشش میدهد. هدرهای امنیتی.
واژهنامه
| اصطلاح | معنا |
|---|---|
| چکلیست امنیت API (API security checklist) | کنترلهای مشترک هر endpoint؛ اینجا فهرست "API Security Best Practices" از roadmap.sh با ۵۰ بند و ۹ گروه |
| سختسازی (Hardening) | تغییر پیشفرض تا فقط رفتار مورد نظر ممکن باشد |
| اعتبارسنجی با فهرست مجاز (Allow-list validation) | پذیرش فقط مطابق قاعدهٔ مثبت نوع، طول، بازه، قالب و نام فیلد؛ رد تمام بقیه |
| فهرست ممنوع (Denylist) | رد مقدار بد شناختهشده؛ شکننده است و اینجا استفاده نمیشود |
| قرارداد مبتنی بر طرحواره (Schema-first) | نوشتن OpenAPI یا JSON Schema قبل از کد و Validation در برنامه و لبه |
| OpenAPI | شرح ماشینخوان API با HTTP: مسیر، متد، پارامتر و Schema |
| اعتبارسنجی OpenAPI در لبه (OpenAPI validation at the edge) | بررسی درخواست با سند OpenAPI در gateway پیش از ارسال |
| اعتبارسنجی عمق و طرحوارهٔ JSON (JSON depth and schema validation) | سقف تودرتویی و بررسی ساختار ورودی، فیلد و نوع و additionalProperties: false |
| فهرست مجاز متد HTTP (HTTP method allow-list) | متدهای پذیرفتهشدهٔ API یا Route؛ بقیه 405 میگیرند |
| 405 Method Not Allowed | متد شناختهشده ولی پشتیبانینشده برای منبع؛ باید Allow داشته باشد |
هدر Allow | فهرست متدهای پشتیبانیشدهٔ منبع؛ الزامی در 405 |
| تغییر متد (Method override) | X-HTTP-Method-Override و مشابه آن برای ادعای متدی دیگر؛ اینجا رد میشود |
| اعتبارسنجی Content-Type (Content-Type validation) | الزام بدنه به اعلام نوع رسانهٔ پشتیبانیشده |
| 415 Unsupported Media Type | قالب محتوای درخواست پشتیبانی نمیشود |
| اعتبارسنجی Accept (Accept validation) | بررسی پذیرش نوع رسانهٔ تولیدی API توسط کلاینت |
| 406 Not Acceptable | مطابق Accept هیچ نمایش قابل قبولی وجود ندارد |
| سقف بدنهٔ درخواست (Request body size limit) | بیشترین بایت بدنه که Route میخواند |
| 413 Content Too Large | نام RFC 9110 برای بدنهٔ بزرگ؛ قبلاً Payload Too Large / Request Entity Too Large |
| MaxBytesReader | reader در net/http برای سقف بدنه و بازگرداندن *http.MaxBytesError |
| 431 Request Header Fields Too Large | هدر بزرگتر از MaxHeaderBytes |
| هدر Authorization | هدر استاندارد اعتبارنامه، مثل توکن Bearer و schemeهای دیگر |
| هدرهای امنیتی (Security headers) | هدر پاسخ فعالکنندهٔ محافظت مرورگر |
| X-Content-Type-Options nosniff | مرورگر فقط به Content-Type اعلامشده اعتماد کند و sniff نکند |
| X-Frame-Options | کنترل قدیمی framing با DENY؛ جایگزینش frame-ancestors است |
| Content-Security-Policy | policy مرورگر برای منابع قابل بارگیری؛ default-src 'none' همه را برای پاسخ API میبندد |
frame-ancestors | directive در CSP برای تعیین مجازبودن frame کردن پاسخ |
| Strict-Transport-Security (HSTS) | مرورگر تا max-age ثانیه فقط HTTPS استفاده کند؛ ارسال فقط روی TLS |
| Referrer-Policy | کنترل URL ارسالشده در Referer؛ برای API مقدار no-referrer |
| Cache-Control no-store | directive منع ذخیرهٔ پاسخ در cache |
| Permissions-Policy | غیرفعالکردن قابلیت مرورگر مثل دوربین و geolocation برای پاسخ |
| اثرانگشت (Fingerprinting) | تشخیص نرمافزار و نسخه از پاسخ |
| Server / X-Powered-By | هدرهای معمول افشاکنندهٔ نسخهٔ وبسرور و زبان |
| جزئیات خطا (Problem Details، RFC 9457) | قالب استاندارد application/problem+json با type، title، status، detail و instance |
| عضو افزوده (Extension member) | فیلد اضافی Problem مثل request_id و errors |
| کد وضعیت درست (Correct status codes) | کد دارای معنای درست؛ 4xx کلاینت، 5xx سرور؛ هرگز 200 برای شکست |
| Stack trace | Stack trace هنگام خطا؛ فقط لاگ سمت سرور، هرگز پاسخ |
| شیء انتقال دادهٔ خروجی (Output DTO) | نوع صریح فیلدهای خروجی API؛ view struct در Go یا JsonResource در Laravel |
| حالت اشکالزدایی (Debug mode) | خروجی خطای پرجزئیات و ابزار توسعه؛ APP_DEBUG در Laravel |
| محافظ خاموشی debug (Debug-off guard) | بررسی startup که Production با debug روشن را متوقف میکند |
APP_DEBUG | متغیر محیطی Laravel برای config('app.debug') |
| Timeout | deadline هر مرحلهٔ اتصال: هدر، خواندن، نوشتن، بیکاری و handler |
ReadHeaderTimeout | سقف Go برای دریافت هدر؛ دفاع Slowloris |
IdleTimeout | سقف انتظار درخواست بعدی در Keep-alive در Go |
| حملهٔ اتصال کند (Slowloris) | نگهداشتن اتصال با ارسال بسیار کند هدر |
http.TimeoutHandler | wrapper در Go که پس از deadline پاسخ 503 میدهد و context را لغو میکند |
| اشتراک منابع میانمبدأ (CORS) | Cross-Origin Resource Sharing؛ هدرهای تعیین origin مجاز به خواندن پاسخ در مرورگر |
| پیشدرخواست (Preflight) | درخواست OPTIONS مرورگر برای اجازهٔ درخواست cross-origin غیرساده |
| اعتبارنامههای CORS (Credentials) | Cookie یا HTTP auth در cross-origin؛ نیازمند origin دقیق و Access-Control-Allow-Credentials: true |
Vary: Origin | اعلام وابستگی پاسخ به هدر Origin برای cache |
| شناسهٔ درخواست (Request id) | شناسهٔ یک درخواست؛ بازگشت در X-Request-ID و ثبت در هر خط لاگ |
| شناسهٔ همبستگی (Correlation id) | دنبالکردن یک عمل کاربر بین سرویسها؛ اغلب همان Request id |
| پوشاندن داده (Redaction) | ماسککردن مقدار حساس پیش از ثبت لاگ |
| اطلاعات هویتی شخصی در لاگ (PII in logs) | ایمیل، نام و شناسهٔ ثبتشده؛ باید کمینه و پوشانده شوند |
| ثبت متمرکز لاگ (Centralised logging) | ارسال لاگ همهٔ سرویسها به محل قابل جستوجوی مشترک |
| هشداردهی (Alerting) | قواعد لاگ یا metric برای خبرکردن انسان با Slack، PagerDuty یا SMS |
| سامانهٔ تشخیص / جلوگیری از نفوذ (IDS/IPS) | بررسی ترافیک برای امضای حمله |
| فایروال برنامهٔ وب (WAF) | فیلتر HTTP بر اساس قاعده، مثل OWASP Core Rule Set |
| درگاه API (API gateway) | Reverse proxy متمرکزکنندهٔ TLS، auth، سقف، routing و policy هدر؛ Kong، Envoy، APISIX و Nginx |
| Kong | Gateway مبتنی بر Nginx/OpenResty با request-size-limiting، response-transformer و cors |
| Envoy | Proxy لایهٔ 7 مستقل یا داخل mesh؛ Timeout و گزینهٔ هدر در HTTP connection manager |
| APISIX | Gateway از Apache با request-validation، client-control و response-rewrite |
| Nginx | وبسرور و reverse proxy با client_max_body_size، server_tokens و add_header |
| میانافزار Laravel (Laravel middleware) | class دارای handle() ثبتشده در bootstrap/app.php؛ عمومی، گروه و alias |
| بستهٔ secure-headers | bepsvpt/secure-headers؛ تنظیم هدر امنیتی Laravel از فایل config |
| زنجیرهٔ میانافزار Go (Go middleware chain) | ترکیب مرتب تابعهای func(http.Handler) http.Handler |
| اسکریپت ممیزی curl (curl audit script) | audit.sh؛ بررسیهای قطعی curl برای چکلیست، قابل استفاده بهعنوان DAST کوچک |
| اسکن وابستگی (Dependency scanning / SCA) | سنجش وابستگی با پایگاه دادهٔ آسیبپذیری |
govulncheck | Scanner آسیبپذیری Go آگاه از دسترسیپذیری تابع |
composer audit | بررسی package نصبشده برای advisory، رهاشدگی و بدافزار |
| آزمون امنیتی ایستا (SAST) | تحلیل source با gosec، semgrep و PHPStan |
| آزمون امنیتی پویا (DAST) | تست برنامهٔ در حال اجرا با OWASP ZAP |
| اسکن رازها (Secrets scanning) | یافتن اعتبارنامهٔ commitشده با gitleaks یا GitHub secret scanning |
| قواعد بازبینی کد (Code review rules) | حفاظت شاخه، تأیید الزامی فردی جز نویسنده و CODEOWNERS |
| راهبرد بازگشت (Rollback strategy) | روش برنامهریزیشدهٔ برگرداندن سریع انتشار، شامل تغییر داده |
| استقرار دو محیطی (Blue-green) | دو محیط؛ جابهجایی ترافیک برای deploy و بازگرداندن برای Rollback |
| پرچم قابلیت (Feature flags) | کلید زمان اجرا برای روشن یا خاموشکردن رفتار بدون deploy |
| فهرست API (API inventory) | فهرست نگهداریشدهٔ تمام endpointها، نسخهها و میزبانها با مسئول و محافظ |
منابع
- roadmap.sh, API Security Best Practices: https://roadmap.sh/best-practices/api-security; دادهٔ منبع استفادهشده (commit
2571a7c): api-security.json, api-security.md - OWASP Cheat Sheet Series: REST Security, REST Assessment, HTTP Headers, Input Validation, Error Handling, Logging, Transport Layer Security, Content Security Policy, HTML5 Security (CORS)
- OWASP API Security Top 10 2023: list, API8:2023 Security Misconfiguration
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110; RFC 9457, Problem Details for HTTP APIs: https://www.rfc-editor.org/rfc/rfc9457; RFC 6797, HTTP Strict Transport Security: https://www.rfc-editor.org/rfc/rfc6797
- MDN: X-Content-Type-Options, X-Frame-Options, Content-Security-Policy, Strict-Transport-Security, Referrer-Policy, Cache-Control, Server, CORS, 405, 406, 413, 415
- Go source و یادداشت انتشار: net/http request.go (MaxBytesReader), net/http server.go (Server timeouts, TimeoutHandler, Error), net/http status.go, net/http responsecontroller.go, encoding/json scanner.go, Go 1.19, Go 1.20, Go 1.21, Go 1.22, Go 1.25
- Go vulnerability management and govulncheck: https://go.dev/doc/security/vuln/, tutorial
- Cloudflare blog, The complete guide to Go net/http timeouts (منبع ثانویه، نوشتهشده برای Go 1.6–1.8): https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts/
- Laravel 13: Middleware, Routing (CORS), Configuration (debug mode), Errors, Logging, Context, Validation, Requests, Eloquent API resources, Deployment; فایل Framework به نام
config/cors.php: https://github.com/laravel/framework/blob/13.x/config/cors.php - bepsvpt/secure-headers: https://github.com/bepsvpt/secure-headers; spatie/laravel-csp: https://github.com/spatie/laravel-csp
- Kong plugins: Request Size Limiting, Response Transformer, CORS, OAS Validation; طرحوارهها: request-size-limiting, response-transformer, cors
- Envoy: HTTP connection manager proto, HTTP header manipulation, Buffer filter proto, Route proto
- Apache APISIX plugins: request-validation, response-rewrite, client-control
- Nginx: ngx_http_core_module, ngx_http_headers_module, ngx_http_proxy_module
- Composer CLI (audit): https://getcomposer.org/doc/03-cli.md; OWASP ZAP baseline scan: https://www.zaproxy.org/docs/docker/baseline-scan/; gitleaks: https://github.com/gitleaks/gitleaks; gosec: https://github.com/securego/gosec and rules