<overview>
OWASP API Security Top 10 checklist adapted for SmartStack (.NET/ASP.NET Core). This is DIFFERENT from the OWASP Top 10 (web application vulnerabilities) -- this list targets API-specific threats.

Use this reference when reviewing API controllers, especially those exposed to external clients or public-facing APIs.
</overview>

<api1_bola>
## API1 - Broken Object Level Authorization (BOLA/IDOR)

**Risk:** Users access other users' resources by manipulating object IDs in requests.

**SmartStack check:**
- [ ] All queries filter by `TenantId` (EF Core global filters active)
- [ ] `[RequirePermission]` on every endpoint
- [ ] No raw `Guid` from URL used directly without ownership verification

```csharp
// BAD: IDOR vulnerability - any authenticated user can access any order
[HttpGet("{id}")]
public async Task<ActionResult<OrderDto>> Get(Guid id)
{
    var order = await _context.Orders.FindAsync(id);
    return Ok(order);
}

// GOOD: Tenant filter via EF Core global filter + explicit check
[HttpGet("{id}")]
[RequirePermission(Permissions.Orders.Read)]
public async Task<ActionResult<OrderDto>> Get(Guid id)
{
    var order = await _context.Orders
        .FirstOrDefaultAsync(o => o.Id == id); // Global filter ensures TenantId match
    if (order is null) return NotFound();
    return Ok(order.ToDto());
}
```

**Detection pattern:**
```bash
grep -rE "FindAsync\(id\)|Find\(id\)" --include="*.cs" | grep -v "TenantId"
```
</api1_bola>

<api2_broken_auth>
## API2 - Broken Authentication

**Risk:** Weak authentication mechanisms allow attackers to impersonate users.

**SmartStack check:**
- [ ] `[Authorize]` on all controllers (except explicit `[AllowAnonymous]`)
- [ ] JWT tokens validated with issuer, audience, and expiration
- [ ] Refresh token rotation implemented
- [ ] Failed login attempts tracked and rate-limited

**Detection pattern:**
```bash
grep -rL "\[Authorize\]" --include="*Controller.cs" | grep -v "AuthController"
```
</api2_broken_auth>

<api3_broken_property_auth>
## API3 - Broken Object Property Level Authorization

**Risk:** Users modify properties they shouldn't have access to (mass assignment).

**SmartStack check:**
- [ ] DTOs separate from entities (no direct entity binding)
- [ ] `CreateDto` and `UpdateDto` contain only writable fields
- [ ] Sensitive properties (TenantId, CreatedById, Role) NOT in DTOs
- [ ] No `[FromBody] Entity` binding (always use DTOs)

```csharp
// BAD: Mass assignment - user can set their own Role
[HttpPut("{id}")]
public async Task<ActionResult> Update(Guid id, [FromBody] User user) { ... }

// GOOD: DTO limits writable fields
[HttpPut("{id}")]
[RequirePermission(Permissions.Users.Update)]
public async Task<ActionResult> Update(Guid id, [FromBody] UpdateUserDto dto) { ... }

public record UpdateUserDto(string Name, string Email); // No Role, no TenantId
```
</api3_broken_property_auth>

<api4_unrestricted_consumption>
## API4 - Unrestricted Resource Consumption

**Risk:** No rate limiting allows API abuse, DDoS, or resource exhaustion.

**SmartStack check:**
- [ ] Rate limiting middleware configured (`Microsoft.AspNetCore.RateLimiting`)
- [ ] Pagination enforced on list endpoints (max page size)
- [ ] File upload size limits set
- [ ] Query complexity limits (no unbounded `Include()`)

```csharp
// BAD: No pagination limit - can request entire database
[HttpGet]
public async Task<ActionResult<List<OrderDto>>> GetAll([FromQuery] int pageSize = 1000000) { ... }

// GOOD: Enforced max page size
[HttpGet]
public async Task<ActionResult<PaginatedResult<OrderDto>>> GetAll(
    [FromQuery] int page = 1,
    [FromQuery] int pageSize = 20)
{
    pageSize = Math.Min(pageSize, 100); // Hard cap
    ...
}
```
</api4_unrestricted_consumption>

<api5_broken_function_auth>
## API5 - Broken Function Level Authorization

**Risk:** Regular users access admin-level API functions.

**SmartStack check:**
- [ ] Admin endpoints use `administration.*` permissions
- [ ] Application-based routing enforced (Administration, Support, etc.)
- [ ] System account protection (UserType.System, UserType.LocalAdmin)
- [ ] No permission bypass via direct URL manipulation

```csharp
// BAD: Missing permission - any authenticated user can delete
[HttpDelete("{id}")]
[Authorize]
public async Task<ActionResult> Delete(Guid id) { ... }

// GOOD: Explicit permission check
[HttpDelete("{id}")]
[RequirePermission(Permissions.Administration.Users.Delete)]
public async Task<ActionResult> Delete(Guid id) { ... }
```
</api5_broken_function_auth>

<api6_business_flow>
## API6 - Unrestricted Access to Sensitive Business Flows

**Risk:** Automated abuse of business processes (mass account creation, coupon abuse).

**SmartStack check:**
- [ ] Rate limiting on sensitive endpoints (registration, password reset)
- [ ] CAPTCHA or bot detection on public-facing forms
- [ ] Business flow monitoring and alerting
- [ ] Idempotency keys for payment/creation operations
</api6_business_flow>

<api7_ssrf>
## API7 - Server-Side Request Forgery (SSRF)

**Risk:** Attacker makes the server send requests to internal resources.

**SmartStack check:**
- [ ] No user-supplied URLs passed to `HttpClient` without validation
- [ ] Webhook URLs validated against allowlist
- [ ] Internal network ranges blocked (127.0.0.1, 10.x, 192.168.x)

```csharp
// BAD: SSRF - user controls the URL
[HttpPost("fetch")]
public async Task<ActionResult> Fetch([FromBody] string url)
{
    var response = await _httpClient.GetAsync(url);
    return Ok(await response.Content.ReadAsStringAsync());
}

// GOOD: Validate against allowlist
[HttpPost("webhook")]
public async Task<ActionResult> ConfigureWebhook([FromBody] WebhookDto dto)
{
    if (!_webhookValidator.IsAllowedDomain(dto.Url))
        return BadRequest("URL domain not allowed");
    ...
}
```
</api7_ssrf>

<api8_misconfiguration>
## API8 - Security Misconfiguration

**Risk:** Default configs, verbose errors, missing security headers expose attack surface.

**SmartStack check:**
- [ ] Security headers configured (see security-checklist.md A02)
- [ ] Error responses don't expose stack traces in production
- [ ] CORS restricted to known origins (no `AllowAnyOrigin` in production)
- [ ] Swagger/OpenAPI disabled in production
- [ ] Debug mode off in production (`ASPNETCORE_ENVIRONMENT=Production`)

**Detection pattern:**
```bash
grep -rE "AllowAnyOrigin|EnableDetailedErrors|DeveloperExceptionPage" --include="*.cs"
```
</api8_misconfiguration>

<api9_inventory>
## API9 - Improper Inventory Management

**Risk:** Old or undocumented API endpoints remain exposed without security.

**SmartStack check:**
- [ ] All controllers have `[NavRoute]` attribute (discoverable)
- [ ] Deprecated endpoints marked with `[Obsolete]`
- [ ] `[ProducesResponseType]` on every endpoint (API documentation)
- [ ] No orphan controllers without matching permissions
</api9_inventory>

<api10_unsafe_consumption>
## API10 - Unsafe Consumption of APIs

**Risk:** Application blindly trusts data from third-party APIs.

**SmartStack check:**
- [ ] External API responses validated/deserialized with typed DTOs
- [ ] Timeout and retry policies on `HttpClient` (Polly)
- [ ] Circuit breaker pattern for unreliable external services
- [ ] External data sanitized before storage
</api10_unsafe_consumption>

<severity_mapping>
## Mapping to SmartStack SEC-xxx Categories

| OWASP API | SmartStack Check | Severity |
|-----------|-----------------|----------|
| API1 BOLA | SEC-001: Missing tenant filter | blocking |
| API2 Auth | SEC-002: Missing [Authorize] | blocking |
| API3 Property Auth | SEC-003: Entity binding (mass assignment) | critical |
| API4 Resource | SEC-004: No pagination limit | warning |
| API5 Function Auth | SEC-005: Missing [RequirePermission] | blocking |
| API6 Business Flow | SEC-006: No rate limit on sensitive ops | warning |
| API7 SSRF | SEC-007: Unvalidated URL in HttpClient | blocking |
| API8 Misconfig | SEC-008: CORS/Debug/Headers | critical |
| API9 Inventory | SEC-009: Undocumented endpoint | info |
| API10 Unsafe API | SEC-010: Unvalidated external data | warning |
</severity_mapping>

<sources>
- [OWASP API Security Top 10 (2023)](https://owasp.org/API-Security/editions/2023/en/0x11-t10/)
- [OWASP API Security Project](https://owasp.org/www-project-api-security/)
- SmartStack RBAC and Multi-tenant documentation
</sources>
