Software Engineer Encyclopedia
0%
Domain 05 · Security & Software Testing · Topic 5.6

Secure Coding: حماية ASP.NET Core API من أخطاء التطبيق الشائعة

Secure Coding — OWASP, API Security and Practical Defenses

مرجع secure coding: validation/encoding، injection، XSS، access control، CSRF/SSRF، path traversal، file uploads، secrets، TLS، logging، dependencies، OWASP API وLLM security.

  • Intermediate
  • ~18 min read
  • 13 sections
  • 9 code examples
  • 1 diagrams
  • 5 questions
  • Priority L1 · Essential
  • ASP.NET Core 10 · .NET 10

المتطلبات قبل ما تبدأ

Web API شغال بقاعدة بيانات (المجالات 03 و04).

مستوى التعمق المطلوب

DEEP IN COMMON RISKSSecurity fundamentals are not optional for a junior backend developer.

01

Secure Coding يبدأ من Threat Model

Security is a property of the whole system
Deep dive

Secure coding مش مجموعة snippets نضيفها بعد ما التطبيق يخلص؛ هو طريقة تفكير في assets و trust boundaries و attackers و entry points و impact. ابدأ بـ Threat Modeling: ما البيانات التي نحميها؟ من يملكها؟ ما الـ trust boundaries؟ أين يدخل user input؟ ما الصلاحيات؟ ما الذي يحدث لو dependency أو provider اتخترق؟

استخدم STRIDE كأداة تفكير: Spoofing، Tampering، Repudiation، Information Disclosure، Denial of Service، Elevation of Privilege. لا تحتاج تعمل threat model ضخم لكل endpoint؛ ابدأ بالعمليات الحساسة مثل login، payments، file uploads، admin actions، multi-tenant data، exports و webhooks.

OWASP Top 10 و OWASP API Security Top 10 قوائم مخاطر تساعدك تراجع broken access control، cryptographic failures، injection، insecure design، misconfiguration، vulnerable components، SSRF، resource consumption، inventory management و unsafe API consumption. القائمة ليست checklist كافية وحدها؛ اربط كل risk بسياق تطبيقك واختبار قابل للتكرار.

Threat Modeling: Assets و Trust Boundaries و Abuse Cases

ابدأ بالأصول: credentials، customer data، payment state، admin operations، model prompts/documents. ارسم data flows وحدد trust boundaries بين browser/API/database/third-party provider/worker. لكل boundary اسأل عن spoofing، tampering، repudiation، information disclosure، denial of service، elevation of privilege. ثم اكتب abuse cases مثل IDOR، refresh replay، mass assignment، SSRF، file upload abuse، prompt injection عند AI features.

رتب المخاطر حسب likelihood/impact، واختر controls قابلة للاختبار: authorization policy، schema validation، output encoding، egress allow-list، upload scanning/limits، rate limiting، audit events، secrets management. Threat model وثيقة حية؛ حدّثها عند إضافة endpoint أو integration أو tenant boundary، ولا تكتفِ بقائمة OWASP عامة.

02

Input Validation و Output Encoding

Treat external input as untrusted
Deep dive

أي input خارج trust boundary غير موثوق: HTTP body/query/path/header، uploaded file، webhook، queue message، LLM output، وحتى data من partner system. Validation تتحقق من الشكل والنطاق والمعنى: type، length، allowed values، ranges، format، cross-field rules. استخدم allow-list أفضل من block-list عندما ممكن.

Validation لا تحل محل output encoding. حتى string صحيحة من منظور business قد تصبح خطرة لو أُدرجت في HTML/JavaScript/SQL/shell/path. Output encoding تعتمد على السياق: HTML text، HTML attribute، JavaScript string، URL component، CSS. استخدم templating framework يعمل encoding تلقائيًا، وتجنب raw HTML rendering إلا بعد sanitization مخصص.

C#Validate request at the boundary
public sealed record CreateProductRequest(
    [property: Required, StringLength(160, MinimumLength = 2)] string Name,
    [property: Range(typeof(decimal), "0.01", "9999999")] decimal Price,
    [property: Range(0, 100000)] int Stock);

app.MapPost("/products", async (
    CreateProductRequest request, IValidator<CreateProductRequest> validator,
    CancellationToken ct) =>
{
    var validation = await validator.ValidateAsync(request, ct);
    if (!validation.IsValid)
        return Results.ValidationProblem(validation.ToDictionary());
    // Domain layer still enforces business invariants.
    return Results.Created("/products/1", new { request.Name });
});

الـ validation على DTO لا تكفي وحدها: domain model لازم يحمي invariants، و database constraints تحمي data integrity عند concurrent writes أو مصادر كتابة أخرى. لا تقبل client-supplied fields مثل IsAdmin أو TenantId أو PriceAfterDiscount كحقائق موثوقة.

Mass Assignment و Property-Level Authorization

Mass assignment يحدث عندما API تربط request body مباشرة بـ entity أو تعمل SetValues على كل properties. attacker قد يرسل IsAdmin=true أو IsPaid=true أو TenantId حتى لو UI لا تعرضها. استخدم request DTOs محددة للحقول المسموح بها، ثم طبق domain methods. authorization يجب أن تشمل field-level/property-level decisions لو بعض fields تتطلب privilege أعلى.

C#Explicit mapping prevents over-posting
public sealed record UpdateProfileRequest(string DisplayName, string Phone);

var user = await users.GetAsync(currentUserId, ct);
user.ChangeDisplayName(request.DisplayName);
user.ChangePhone(request.Phone);
// Never bind request directly to the persistence entity.
await users.SaveAsync(user, ct);

راجع bulk update/import endpoints أيضًا؛ mapping عام من JSON إلى entity قد يتجاوز authorization. في multi-tenant systems لا تسمح client بتغيير tenant ownership حتى لو field موجودة في database.

Trust Boundaries و Input Validation و Output Encoding

Input Untrusted boundary Validate Schema + business rules Encode Context-aware output Persist Parameterized commands
Secure input handling

كل input يأتي من خارج trust boundary: route, query, headers, cookies, files, webhook payloads، وحتى data من service أخرى. Validation تتحقق أن البيانات مطابقة للعقد business/schema؛ encoding يضمن أن القيمة تُعرض بأمان في context معين. لا تخلط بينهما. HTML encoding لا يحمي JavaScript string context تلقائيًا، و SQL parameterization لا يحمي dynamic table/column names.

SSRF يحصل عندما يطلب server URL يتحكم فيه المستخدم؛ قيّد schemes والـ hosts، امنع الوصول إلى loopback/private/link-local metadata ranges، وتعامل مع redirects و DNS rebinding. Deserialization لبيانات غير موثوقة يجب أن تستخدم allowlisted types و safe formats، وتجنب polymorphic type activation غير المقيد.

C#Practical engineering example
// Parameterize values; allowlist identifiers that cannot be parameters.
var allowedSorts = new Dictionary<string, string>
{
    ["name"] = "Name",
    ["price"] = "Price",
    ["created"] = "CreatedAt"
};
if (!allowedSorts.TryGetValue(sortBy, out var column))
    return Results.BadRequest();

var sql = $"SELECT Id, Name, Price FROM dbo.Products ORDER BY [{column}]";
// Values in WHERE clauses must still be SQL parameters.

الـ identifier هنا آمن فقط لأنه اختير من allowlist ثابتة لا من input مباشرة. لا تسمح للمستخدم بإرسال اسم عمود raw. استخدم parameterized commands لكل values. في Razor/HTML استخدم encoding الافتراضي ولا تلجأ إلى Html.Raw لبيانات المستخدم.

03

SQL Injection و Command Injection

Keep data separate from executable syntax
Deep dive

SQL injection تحصل عندما input المستخدم يغير معنى SQL syntax. الحل الأساسي parameterized queries/ORM parameterization، وليس محاولة إزالة quotes أو منع كلمات SQL. لا تبنِ SQL بدمج values. Dynamic identifiers تحتاج allow-list ثابتة؛ parameters لا تمثل أسماء tables/columns أو keywords.

C#Parameterized SQL
var user = await db.Users
    .SingleOrDefaultAsync(x => x.Email == normalizedEmail, ct);

// ADO.NET alternative:
await using var command = new SqlCommand(
    "SELECT Id FROM dbo.Users WHERE Email = @Email", connection);
command.Parameters.Add("@Email", SqlDbType.NVarChar, 320).Value = email;

نفس المبدأ ينطبق على shell/process execution و LDAP و NoSQL query construction و template engines. تجنب shelling out بمدخل user؛ لو ضروري، مرر arguments منفصلة عبر API آمنة، استخدم fixed executable/allow-list، وقلل privileges. لا تستخدم ProcessStartInfo.Arguments بدمج نص غير موثوق.

Injection و Serialization و Deserialization Boundaries

Parameterized SQL يمنع data من التحول إلى SQL syntax؛ dynamic identifiers مثل column/order direction لا يمكن parameterize كقيمة، لذلك استخدم allow-list mapping. EF Core LINQ parameterizes values غالبًا، لكن raw SQL و dynamic SQL يحتاجان مراجعة. لا تدمج user input في SQL string. لا تعتمد على escaping يدوي.

Deserialization قد تنتج object graph غير متوقع أو resource exhaustion. استخدم serializers بإعدادات آمنة، schema/version validation، limits على depth/size، ولا تستخدم unsafe polymorphic type activation لمدخلات غير موثوقة. في JSON API، map إلى DTO محدد ثم domain command؛ لا تسمح للعميل يرسل server-managed fields.

04

XSS و CSRF و CORS: لا تخلط التهديدات

Browser attack surfaces
Deep dive

XSS يحدث عندما attacker يحقن script ينفذ في origin موثوق. الدفاع: output encoding، HTML sanitization عند السماح بمحتوى rich text، CSP كطبقة إضافية، تجنب eval/unsafe DOM APIs، و HttpOnly cookies. CSP لا تصلح injection لوحدها لكنها تقلل أثر بعض الهجمات.

CSRF يستغل أن browser يرسل cookies تلقائيًا مع requests. دفاعاته: anti-forgery tokens، SameSite cookies، origin/referrer checks حسب التطبيق، وعدم استخدام GET لتغيير state. CORS لا يحل CSRF؛ CORS يحدد قراءة response من browser script، وليس منع كل request أو side effect.

في JWT داخل Authorization header، CSRF risk يختلف لأن JavaScript عادة تضيف header بنفسها، لكن XSS قد يسرق token أو يستخدمه من نفس origin. في cookie auth، راجع CSRF بشكل صريح. لا تفترض أن HttpOnly يمنع XSS؛ هو يقلل سرقة cookie فقط، وال script الخبيث قد ينفذ requests باسم المستخدم.

CSRF Defense عمليًا في Cookie-Based APIs

لو authentication عبر cookie، browser يرسلها تلقائيًا مع request مطابقة domain/path/samesite. attacker site قد يحاول trigger state-changing request من browser الضحية. لا تستخدم GET/HEAD لتغيير state. في MVC/forms استخدم antiforgery token validation. في SPA cookie auth، احصل على antiforgery token من endpoint موثوق وأرسله في header، مع Origin/Referer checks و SameSite policy مناسبة.

لا تعتبر JSON content type أو custom header حماية كافية وحدها؛ browser CORS/preflight قد يقلل بعض attack paths لكن misconfiguration أو simple request forms تظل مهمة. اختبر actual browser behavior. لو BFF session cookie، CSRF protection مسؤولية BFF حتى لو downstream APIs تستخدم bearer tokens.

05

Broken Access Control و SSRF

Authorize every resource and constrain outbound calls
Deep dive

Broken Access Control يشمل IDOR، privilege escalation، missing function-level authorization، tenant leakage، و mass assignment. كل endpoint تقبل resource id يجب أن تتحقق من owner/tenant/permission. لا تعتمد على إخفاء زر في UI أو صعوبة تخمين ID.

SSRF (Server-Side Request Forgery) يحدث عندما attacker يجعل server يطلب URL يسيطر عليه أو يوجهه إلى internal services/metadata endpoints. لا تقبل arbitrary URL ثم تعمل HttpClient.GetAsync عليه. استخدم allow-list hosts/schemes، امنع private/link-local/loopback IPs حسب use case، تعامل مع DNS rebinding/redirects، وحدد egress network policy و timeouts/response size.

C#Restrict outbound host — simplified allow-list
private static readonly HashSet<string> AllowedHosts =
    ["api.partner.example", "files.partner.example"];

static Uri ValidatePartnerUri(string raw)
{
    if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri) ||
        uri.Scheme != Uri.UriSchemeHttps ||
        !AllowedHosts.Contains(uri.IdnHost))
        throw new ValidationException("Destination is not allowed.");
    return uri;
}

ده دفاع أولي وليس SSRF library كاملة؛ في production راجع redirects و DNS resolution و IP ranges وال proxy behavior. لو المطلوب اختيار document من user، الأفضل تقبل document ID وتجيب الملف من storage داخلي بدل URL حر.

SSRF Defense: Redirects و DNS Rebinding و Metadata IPs

Allow-list hostname وحدها قد لا تكفي إذا DNS يتغير أو redirect يوجه إلى internal address. في integrations الحساسة، disable automatic redirects أو افحص كل redirect target، resolve DNS وتحقق من IP ranges، امنع loopback/private/link-local/metadata ranges حسب الحاجة، وطبق outbound firewall/egress proxy. لا تسمح arbitrary schemes مثل file:// أو gopher://.

Cloud metadata endpoints قد تكشف credentials لو server يطلبها. لا تعتمد على منع عنوان IP واحد فقط؛ cloud/provider ranges تختلف، و DNS rebinding قد يبدل resolution. أفضل تصميم أن client يرسل partner ID أو document ID، والسيرفر يختار endpoint من trusted config بدل URL حر.

06

Path Traversal و File Upload Security

Never trust file names or MIME claims
Deep dive

Path traversal يحصل لما input مثل ../../secrets.txt يهرب من directory مقصودة. لا تستخدم user filename كـ path مباشرة. أنشئ storage key عشوائيًا، خزن original filename كـ metadata بعد normalization، وتأكد canonical resolved path يظل داخل root. امنع overwrite و symlinks attacks حسب platform/storage.

File upload defense: حد أقصى للحجم والعدد، allow-list للامتدادات والـ content types، فحص magic bytes وليس MIME header فقط، malware scanning عند الحاجة، تخزين خارج web root أو object storage private، عدم تنفيذ الملفات، وتقديم download عبر authorization endpoint. افحص archive bombs و decompression limits و image parser vulnerabilities.

C#Generate a safe storage name
var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
var allowed = new HashSet<string> { ".pdf", ".png", ".jpg" };
if (!allowed.Contains(extension))
    return Results.BadRequest("File type is not allowed.");
if (file.Length is <= 0 or > 10 * 1024 * 1024)
    return Results.BadRequest("Invalid file size.");

var storageName = $"{Guid.NewGuid():N}{extension}";
await using var stream = File.Create(Path.Combine(privateStorageRoot, storageName));
await file.CopyToAsync(stream, ct);

المثال لا يغني عن magic-byte validation و malware scanning و authorization. لا تجعل الملفات private بمجرد إن اسم directory صعب التخمين؛ تحقق من permission عند كل download.

File Upload Advanced: Archive Bombs و Content Disarm

ملف صغير مضغوط قد يفك إلى حجم هائل (zip bomb)، أو يحتوي nested archives/huge dimensions. حدد compressed size و expanded size و entry count و nesting depth و CPU/time budget. لا تفك archive في web root. image decoders و PDF parsers قد تحتوي vulnerabilities؛ حدّث libraries واعزل parsing في worker/container محدود privileges.

Content-Type يرسله client ويمكن تزويره. افحص magic bytes، extension allow-list، parser success، antivirus/CDR حسب risk. لا تثق في SVG/HTML uploads كصور؛ قد تحتوي active content. عند download، استخدم Content-Disposition مناسبًا و X-Content-Type-Options nosniff، وتأكد من authorization لكل file.

SSRF و File Upload: حدود الشبكة والملفات

SSRF يحدث عندما server يجلب URL يحدده user ويمكنه الوصول إلى metadata endpoints أو internal services. لا يكفي block قائمة domains نصية؛ امنع private/link-local IP ranges بعد DNS resolution، تعامل مع redirects، DNS rebinding، IPv4/IPv6، و egress firewall. استخدم allow-list hosts ثابتة عندما use case يسمح، ولا تمرر arbitrary URL إلى HttpClient.

File upload: حد أقصى للحجم، allow-list extension/content type، افحص file signature وليس MIME header فقط، خزّن خارج web root أو object storage private، استخدم random names، antivirus/content scanning عند الحاجة، وامنع path traversal/archive bombs. لا تثق في filename أو image dimensions. downloads تحتاج authorization و Content-Disposition و safe content type.

07

Secrets Management و HTTPS/TLS و Password Security

Protect credentials and data in transit
Deep dive

Secrets تشمل DB passwords، API keys، signing keys، SMTP credentials، webhook secrets و encryption keys. لا تضعها في Git أو Docker image أو logs. استخدم user-secrets للتطوير المحلي، environment/secret manager أو Key Vault في deployment، و rotation مع least privilege. لا تستخدم نفس credential لكل environments.

HTTPS/TLS يحمي confidentiality/integrity أثناء النقل. استخدم HTTPS redirect/HSTS في production، certificates صحيحة، لا تتجاوز certificate validation، وحدد TLS policy وفق platform/security baseline. Internal service-to-service traffic يحتاج TLS أو network trust controls مناسبة؛ «داخل VPC» لا يعني آمن تلقائيًا.

Password security: استخدم Identity password hasher، MFA للحسابات الحساسة، rate limiting و lockout، password reset tokens محدودة، ولا ترسل password في email أو logs. لا تفرض تغييرات دورية بلا سبب إذا لم توجد مؤشرات compromise؛ ركز على كلمات مرور طويلة، breached-password screening، و MFA.

Secrets Rotation و Incident Response

Secret rotation يجب تكون قابلة للتنفيذ من غير downtime غير ضروري: support old/new key فترة overlap، deploy consumers، switch issuer/clients، ثم revoke old key. signing key compromise يتطلب revoke/rotate و token invalidation strategy، وليس فقط تغيير appsettings. database password leak يتطلب credential rotation ومراجعة access logs.

عند secret leak: لا تكتفِ بحذف commit؛ rotate/revoke فورًا، حدد scope/affected systems، افحص logs/audit، راجع access، وأبلغ الأطراف حسب policy. امنع secret من الظهور في CI output و container layers و debug dumps. secret scanning في repository history مهم لأن Git history تحتفظ بالقيمة القديمة.

08

Sensitive Logging و Secure Error Responses

Observability without leaking secrets
Deep dive

Logs تساعد incident response لكنها قد تصبح data breach. لا تسجل password، access/refresh token، session cookie، full card number، secret key، أو personal data غير لازمة. اعمل structured logging مع redaction، correlation ID، actor/resource/action/result. Audit logs للعمليات الحساسة لها access/retention policy.

Client error response يجب أن تكون مفيدة دون كشف stack traces أو SQL text أو filesystem paths أو internal hostnames. استخدم Problem Details موحدًا، وخزن exception details في protected logs. لا تبتلع exception وتعيد 200؛ ولا تعرض exception.Message مباشرة لو قد تحتوي connection string أو query details.

C#Global exception handling — safe response
app.UseExceptionHandler();
app.MapGet("/example", () => throw new InvalidOperationException("Internal detail"));

// Configure IExceptionHandler / ProblemDetails centrally.
// Client receives a generic 500 + trace identifier;
// detailed exception is logged server-side with sensitive data redacted.

Secrets و Logging و Error Handling

لا تسجل passwords أو tokens أو cookies أو connection strings أو payment data. استخدم structured logs مع allow-listed fields و redaction middleware. Error response للمستخدم يجب أن يكون stable ومختصرًا مع correlation ID؛ stack trace والتفاصيل تبقى في secured logs. لا ترجع raw exception أو SQL text للعميل.

Secrets تحتاج source of truth آمن، least privilege، rotation، expiration monitoring، ومنع الظهور في build artifacts. لا تستخدم secrets كـ configuration عادية في Git. عند suspected exposure، revoke/rotate أولًا، ثم افحص audit logs وحدد blast radius؛ حذف secret من latest commit لا يزيلها من history أو artifacts.

Secrets و Logging و Dependency Supply Chain

Secret management لا يعني وضع key في environment variable فقط؛ يلزم lifecycle: creation، access control، rotation، revocation، audit، و incident response. استخدم managed secret store عند توفره، وامنح service identity أقل صلاحية. لا تضع connection strings أو signing keys أو API tokens في Git أو Docker image layers أو logs.

Logs قد تحتوي PII أو credentials أو session identifiers. استخدم structured logging مع redaction، ولا تسجل Authorization header أو password reset URL. Supply-chain security تشمل تثبيت versions، مراجعة transitive dependencies، vulnerability scanning، و SBOM/signing حسب حساسية المنتج.

C#Practical engineering example
// Avoid logging the full request or credential-bearing headers.
logger.LogInformation(
    "Payment request {RequestId} for order {OrderId} received",
    requestId, orderId);

// Keep secrets outside source control and load through configuration providers.
var apiKey = configuration["Payments:ApiKey"]
    ?? throw new InvalidOperationException("Payment key is not configured");

لا تطبع قيمة apiKey في exception أو health endpoint. اعمل rotation بخطة تسمح بفترة overlap بين المفتاح القديم والجديد إن كان المزود يدعم ذلك. راجع package updates دوريًا، لكن اختبر breaking changes في CI قبل deployment.

09

Dependency Vulnerabilities و Supply Chain

Know what you ship
Deep dive

كل NuGet package و base image و GitHub Action جزء من supply chain. راجع package source، publisher، release cadence، CVEs، transitive dependencies، license، و maintainer activity. استخدم lock files حيث مناسب، حدّث security patches، وامنع packages غير الضرورية. لا تعتمد على أن package مشهور يعني آمن.

BashUseful .NET dependency checks
dotnet list package --vulnerable --include-transitive
dotnet list package --outdated

dotnet restore --locked-mode

أضف Dependabot/Renovate أو tooling مشابه لفتح تحديثات، لكن راجع changelog و breaking changes وشغّل tests. افحص container images و OS packages، استخدم minimal/distroless images عند ملاءمة runtime، ولا تعمل run as root. secret scanning يجب أن يعمل على commits/history، لأن حذف secret من آخر commit لا يلغي تسربه السابق؛ rotate secret فورًا.

10

Security Headers

Defense in depth for browsers
Practical

HSTS يطلب من browser استخدام HTTPS للموقع. CSP تحدد مصادر scripts/styles/images وغيرها وتقلل XSS impact. X-Content-Type-Options: nosniff تمنع MIME sniffing في سياقات معينة. Referrer-Policy تحدد مقدار referrer الذي يرسل. frame-ancestors في CSP تساعد ضد clickjacking.

لا تنسخ CSP عامة من الإنترنت؛ ابدأ report-only، افهم scripts/fonts/third-party dependencies، ثم enforce. تجنب unsafe-inline/unsafe-eval كلما أمكن، واستخدم nonce/hash. HSTS preload و includeSubDomains قرارات واسعة التأثير؛ تأكد من كل subdomains قبل تفعيلها.

11

OWASP API Security و LLM Application Risks

Modern API and AI-specific threats
Deep dive

API Security تركز على object-level authorization (BOLA/IDOR)، broken authentication، property-level authorization/mass assignment، unrestricted resource consumption، function-level authorization، SSRF، misconfiguration، inventory/versioning، unsafe consumption of third-party APIs. كل endpoint وكل field وكل expensive operation يحتاج threat review.

LLM-enabled applications تضيف مخاطر: Prompt Injection من user أو retrieved documents، sensitive information disclosure، insecure output handling، excessive agency/tools، overreliance، vector/embedding weaknesses، data poisoning، model denial-of-service و supply chain. تعامل مع model output كـ untrusted input: validate schema، authorize tool calls server-side، لا تمنح model credentials مباشرة، واستخدم allow-listed tools و human approval للعمليات عالية الأثر.

RAG ACL لازم تطبق قبل أو أثناء retrieval، لا بعد إرسال chunks إلى model. لا تعتمد على prompt يقول «تجاهل التعليمات الخبيثة» كحاجز أمني. افصل instructions عن retrieved content، قلل data exposure، وسجل tool invocation و source citations مع privacy controls.

API Resource Consumption و Abuse Controls

ضع limits على request body size، pagination page size، upload size، query complexity، export rows، report duration، concurrent jobs، GraphQL depth/cost، image dimensions و LLM token budget. Rate limiting وحده لا يمنع request واحدة ضخمة أو query مكلفة جدًا. استخدم timeout، cancellation، concurrency bulkheads، quotas per tenant، و budget alerts.

لا تسمح pageSize=10000000 أو regex غير bounded أو user-supplied sort expression. ضع default/max page size، cursor pagination للبيانات الكبيرة، query timeout مناسب، و response compression limits. للـ LLM APIs حدد max input/output tokens، tool call budget، per-user spend limits و request timeout.

LLM Prompt Injection و Tool Security بالتفصيل

Prompt injection قد تأتي مباشرة من user أو غير مباشرة من web page/PDF/vector chunk. model قد يخلط retrieved content بالتعليمات ويحاول استدعاء tool أو إخراج secrets. لا تعتمد على delimiters أو system prompt كحاجز أمني كامل. طبّق least privilege: model لا يحصل على DB connection أو cloud credentials، بل يطلب tool call من server orchestrator.

كل tool call تحتاج schema validation، authorization على user/tenant/resource، argument allow-list، rate limit، timeout، audit، وربما human approval. افصل read tools عن write tools. العمليات عالية الأثر مثل refund/delete/send email لا تنفذ لمجرد أن model طلبها؛ تحقق من user intent و policy مستقلًا.

في RAG، tenant/ACL filter يطبق قبل retrieval، document content يعتبر untrusted، citations يجب تربط answer بالمصدر الفعلي، و data exfiltration tests يجب تغطي malicious documents. لا تسمح model يقرر tenant id أو access scope من النص. اختبر prompt injection في user query و retrieved docs و tool responses.

12

Security Review Checklist

Before every production release
Practical
  • كل input validated وكل output encoded حسب السياق.
  • كل database access parameterized، وكل dynamic identifier allow-listed.
  • كل resource عليه owner/tenant/permission checks.
  • CSRF/XSS/SSRF/path traversal/file upload threats تمت مراجعتها.
  • Secrets خارج source/image/logs، وتمت rotation بعد أي leak.
  • HTTPS/TLS و security headers مضبوطة وفق التطبيق.
  • Error responses لا تكشف internals، والـ logs لا تحتوي secrets.
  • Dependencies و container images يتم فحصها وتحديثها.
  • Rate limits و resource limits تحمي العمليات المكلفة.
  • LLM tools و RAG retrieval لها authorization/validation.
  • اختبارات negative paths و security regression موجودة.
13

اختبر فهمك

Knowledge check
Practical
هل input validation تمنع XSS وحدها؟
لا؛ output encoding/sanitization حسب سياق العرض ضرورية، لأن valid text قد يصبح script خطيرًا في HTML/JavaScript.
لماذا لا يكفي UUID لمنع IDOR؟
لأن authorization يجب أن يتحقق من owner/tenant/permission حتى لو identifier صعب التخمين.
ما الفرق بين CSRF و CORS؟
CSRF يستغل إرسال credentials تلقائيًا لإحداث action؛ CORS يحدد browser script access لقراءة cross-origin responses.
لماذا arbitrary URL fetching خطر؟
قد يتحول إلى SSRF ويجعل server يصل إلى internal services أو cloud metadata endpoints.
هل Prompt Injection تحلها system prompt قوية؟
لا؛ تحتاج tool authorization، data isolation، output validation، least privilege، و human approval حسب المخاطر.
↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

خريطة التغطية: 22 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapInput Validation§01
RoadmapOutput Encoding§01
RoadmapSQL Injection§01
RoadmapCross-Site Scripting (XSS)§01
RoadmapBroken Access Control§01
RoadmapCSRF and SSRF Concepts§01
RoadmapPath Traversal§01
RoadmapFile Upload Security§01
RoadmapSecrets Management§01
RoadmapHTTPS and TLS§01
RoadmapPassword Security§01
RoadmapSensitive-Data Logging§01
RoadmapSecure Error Responses§01
RoadmapDependency Vulnerabilities§01
RoadmapOWASP Top 10§01
RoadmapThreat Modeling Basics§01
SuggestedOWASP API Security Top 10§01
SuggestedSecurity headers (CSP, HSTS, X-Content-Type-Options)§01
SuggestedDependency scanning (dotnet list package --vulnerable, Dependabot)§01
SuggestedSecret scanning and user-secrets§07
SuggestedOWASP Top 10 for LLM Applications§11
SuggestedContainer image scanning§09

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس