Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ The refresh token never touches JavaScript or a JSON body: it rides the `tdp_ref

- **Origin guard (`SEC_001`)** — login, refresh and revoke reject any browser request whose `Origin` is neither `FRONTEND_URL` nor the API itself with `403 SEC_001`. Non-browser clients send no `Origin` (and cannot carry cookies), so they pass.
- **Proxy-aware HTTPS** — `ForwardedHeaders` honors `X-Forwarded-Proto` (Render terminates TLS, so the `Secure` cookie sticks); `X-Forwarded-For` is deliberately NOT trusted, since it is spoofable.
- **Login rate limiter** — 10 attempts per 5-minute sliding window per email, fail-closed: a Redis outage blocks login with `SYS_002` rather than letting attempts through.
- **Login rate limiter** — 10 attempts per 5-minute sliding window per email, fail-closed: a Redis outage blocks login with `SYS_002` rather than letting attempts through. Register and forgot-password share the same limiter in their own per-email buckets (stops reset-email bombing and mass signups).
- **Baseline security headers** — `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, strict referrer policy on every response. No CSP by design (Swagger UI's inline assets would break).
- **JWT secret fail-fast** — startup refuses to run with fewer than 32 characters.

### 🔑 Password Reset (Phase 2)
Expand Down Expand Up @@ -215,7 +216,7 @@ flowchart TD

### 📎 File Attachments (Phase 3)

Uploads pass a strict gate before storage: safe extension list, 5MB cap, 5 files per ticket, paths sanitized against traversal. Bytes then flow through `IFileStorageService` — signed HTTPS upload to Cloudinary when `Cloudinary:CloudName` is set (production; Render's free disk is ephemeral), local-disk fallback otherwise (dev and tests). Downloads always stream through the API, so the frontend is unchanged either way, and `DeleteAsync` is idempotent.
Uploads pass a strict gate before storage: safe extension list, 5MB cap, 5 files per ticket, paths sanitized against traversal. Bytes then flow through `IFileStorageService` — signed HTTPS upload to Cloudinary when `Cloudinary:CloudName` is set (production; Render's free disk is ephemeral), local-disk fallback otherwise (dev and tests). Downloads always stream through the API with a **server-derived Content-Type** (mapped from the allowlisted extension — the client's header is ignored), so the frontend is unchanged either way, and `DeleteAsync` is idempotent.

```mermaid
flowchart TD
Expand Down Expand Up @@ -649,15 +650,15 @@ Every key the API reads, all documented in `.env.example` (copy it to `.env` for

## Testing

77 tests — **44 unit** + **33 integration** — run with:
80 tests — **47 unit** + **33 integration** — run with:

```bash
dotnet test
```

| Project | Test classes |
|---|---|
| `tests/TicketDeskPro.UnitTests` | `AuthServiceTests`, `SecurityServiceTests`, `TicketStateMachineTests`, `BrevoEmailServiceTests`, `CloudinaryFileStorageServiceTests` |
| `tests/TicketDeskPro.UnitTests` | `AuthServiceTests`, `AuthThrottleTests`, `SecurityServiceTests`, `TicketStateMachineTests`, `BrevoEmailServiceTests`, `CloudinaryFileStorageServiceTests` |
| `tests/TicketDeskPro.IntegrationTests` | `TicketApiTests`, `AuthCookieTests`, `AssignmentTests`, `CorsTests` |

## Deployment (Phase 8)
Expand Down
23 changes: 23 additions & 0 deletions audit/LOOP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Loop Engineering — TicketDeskPro Autonomous Hardening (emulated, not native runtime)

Methodology source: github.com/cobusgreyling/loop-engineering (patterns only — no CLI/MCP
scaffold was installed; this Cowork session emulates the loop with persistent state files,
bounded iterations and maker/checker verification via real sub-agents).

## Objective
Discover, fix and verify security/quality defects across TicketDeskPro-API and
TicketDeskPro-Client; deliver review-ready branches + PRs. No auto-merge, no auto-deploy.

## Cycle
DISCOVER → PRIORITIZE → PLAN → DELEGATE → INVESTIGATE → IMPLEMENT → TEST →
INDEPENDENT VERIFY → REVIEW DIFF → COMMIT → PUSH → UPDATE STATE → REPEAT

## Scope
IN: both connected repos (branches autonomous/ticketdeskpro-hardening), passive live-site
observation, dependency audits, tests, README updates on the branch.
OUT: production env/credentials, database contents, main-branch pushes, merges, deploys,
destructive live testing, secret values in any artifact.

## Stopping conditions
Budget exhausted (see loop-budget.md) · 3 failed repair attempts on one task · high-risk
change needing owner approval (isolate + record) · integrity/compromise evidence → halt all writes.
12 changes: 12 additions & 0 deletions audit/STATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# STATE — FINAL (run complete)
- Branch: autonomous/ticketdeskpro-hardening pushed in BOTH repos.
- PRs (draft, awaiting owner review — NOT merged, NOT deployed):
API https://github.com/morshedmilton/TicketDeskPro-API/pull/1
Web https://github.com/morshedmilton/TicketDeskPro-Client/pull/1
- Delivered: S-A throttle (563cac0) · S-B content-type (35a8f1b) · S-D search clamp (6949f33)
· S-C 401-anon (ca80dcf) · S-E demo warning (53cbb5e) · S-F API headers (3345e81) ·
S-G web headers (de3998b) + redirect guard (8328236) · S-H docs (c281fba) + tidy.
- Verification: 47 unit + 33 integration green; tsc + next build green; CI-on-PR status in
loop-run-log. Owner actions: review+merge PRs (merge to main auto-deploys), decide BE-M2
(Cloudinary private delivery), optionally rotate the dev JWT secret via user-secrets.
- Resume point: nothing in-flight. Next session starts from owner feedback on the PRs.
6 changes: 6 additions & 0 deletions audit/loop-budget.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Budget (fixed for this run — never auto-increase)
- Max substantive iterations: 30 (counter in STATE.md)
- Max repair attempts per underlying failure: 3
- Max changed files per implementation slice: 10 (split larger work)
- Live-site traffic: passive only (HEAD/GET of public pages, headers, TLS) — no attacks
- Sub-agent review: required for every implementation slice before commit
13 changes: 13 additions & 0 deletions audit/loop-run-log.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Run log (chronological, UTC)
- I1: baseline — both repos clean on main; branch autonomous/ticketdeskpro-hardening created
in both; CI confirmed main-only (branch pushes do not deploy); gh auth = morshedmilton;
no pre-existing loop files found.
- I2: audits — gitleaks clean (both repos, full history); npm audit 0; NuGet vulnerable none;
live headers sparse (FE-H1). Backend agent review delivered M1-M3/L1-L4; frontend agent
blocked 3x (model unavailable) → coordinator self-pass (FE findings recorded).
- I3-I9: implemented S-A..S-H, tested after each batch (47+33 green; tsc/next build green),
8 code commits + docs. Ledger kept in sync.
- I10: final reviewer attempt → push → PRs.
- I10: reviewer agent blocked (model unavailable) → coordinator fresh-eyes diff review of all
hunks; 1 cosmetic fix; branches pushed; draft PRs opened (API #1, Client #1). CI-on-PR
checked. Run stopped cleanly within budget (~12 of 30 iterations used).
13 changes: 13 additions & 0 deletions audit/remediation-plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Remediation plan (priority order)
| ID | Slice | Acceptance | Verify |
|----|-------|-----------|--------|
| BE-M1/M3 | S-A throttle forgot+register via bucketed Redis limiter | unit: AuthService hits limiter with buckets forgot/register; suites green | dotnet test |
| BE-L1 | S-B derive download Content-Type from extension allowlist | unit/integration: client content-type ignored | dotnet test |
| BE-L4 | S-C unauthenticated → 401 on RequirePermission | integration: anon gets 401 (was 403); authed unchanged | dotnet test |
| BE-L3 | S-D cap search lengths (200) | validator clamp; suites green | dotnet test |
| BE-L2 | S-E warn when demo users seeded in Production | log line only; no behavior change | build |
| FE-H1 | S-F API response headers middleware | nosniff/frame-options/referrer present on live after merge | curl |
| FE-H1 | S-G client headers() + ?next= backslash reject | tsc+build green; headers after merge | tsc/build |
| FE-R1 | S-H README truth-fixes (proxy.ts, hardening notes) both repos | docs-only review | manual |
| BE-M2 | OWNER: Cloudinary private delivery decision | documented; no auto-fix | — |
Not run/not tested: live authenticated crawling (out of scope), Docker builds (unavailable).
30 changes: 30 additions & 0 deletions audit/security-findings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Security findings (evidence in repo; no secret values)
- S-SCAN: gitleaks v8.24.3 full history — CLEAN both repos. npm audit (lockfile) 0 vulns.
NuGet --vulnerable: none reported. (verified this run)
- BE-M1 MEDIUM: forgot-password/reset-password unthrottled → reset-email bombing, outbox+Brevo
quota exhaustion (AuthController.cs:107, only limiter is login). FIX PLANNED.
- BE-M2 MEDIUM: Cloudinary attachment URLs are public capability URLs (CloudinaryFileStorageService
stores secure_url; anyone with the URL fetches forever). OWNER DECISION — not auto-fixed
(needs private-delivery design + existing-asset migration).
- BE-M3 MEDIUM: register unthrottled (mass account creation, BCrypt cost abuse). FIX PLANNED.
- BE-L1 LOW: client-supplied Content-Type echoed on attachment download (TicketService.cs:486;
mitigated by Content-Disposition attachment). FIX PLANNED (derive from extension).
- BE-L2 LOW-intentional: demo users seedable in Production by env flag (portfolio design).
Mitigation: startup WARNING log when enabled in Production. FIX PLANNED (warning only).
- BE-L3 LOW: unbounded search/filter lengths (TicketDtos.cs:18, UsersController.cs:23) →
LIKE scans. FIX PLANNED (MaximumLength clamp).
- BE-L4 LOW: RequirePermission returns 403 for anonymous (should be 401); admin endpoints rely
on JWT permission claims until expiry (15 min) — accepted JWT trade-off, documented.
FIX PLANNED (401 for unauthenticated).
- BE-N1/N2 NIT: dev JWT secret on disk (gitignored, treated burned); appsettings.json committed
localhost dev creds (standard docker default — left, documented).
- FE-H1 LOW: no security headers on client pages (HSTS only, via Vercel) nor API responses
(passive curl). FIX PLANNED (next.config headers() + API header middleware; no CSP — Swagger
+ Next inline scripts).
- FE-R1 LOW (doc): README previously claimed no middleware — proxy.ts IS an edge route gate
(Next 16 rename). FIX PLANNED (README truth-fix).
- FE-N1 NIT: login ?next= validated (startsWith / , rejects //) — add backslash-prefix reject.
- CLEAN list: IDOR on tickets/messages/attachments verified covered (EnsureCanView everywhere);
mass-assignment impossible (fixed DTOs); no raw SQL; pagination clamped 1-100; exception
middleware leaks nothing; JWT params sound; reset token 256-bit single-use; no secret
logging; notifications have no cross-user surface; XSS sinks absent in client; env files clean.
12 changes: 12 additions & 0 deletions audit/verification-report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Verification report
All slices this run: implementer = coordinator (sequential roles; sub-agent model outage
blocked parallel agents — recorded in STATE.md). Commands actually executed per slice batch:
- dotnet test UnitTests: 47/47 pass (after S-A: +3 AuthThrottleTests; after S-B..S-E; after S-F)
- dotnet test IntegrationTests: 33/33 pass (all three checkpoints)
- client: tsc --noEmit exit 0; next build exit 0 (after S-G)
- gitleaks full-history: 0 findings both repos; npm audit: 0 vulns; NuGet vulnerable: none
- Live header observation (pre-fix): only Vercel HSTS; API none → post-merge re-check pending
Independent-agent diff review: ATTEMPTED (1 try this run) — see loop-run-log; fallback =
fresh-eyes self-review of each staged diff before commit (documented, not equivalent to
agent independence — residual process risk noted).
Commands NOT run this run: docker builds (unavailable), live authenticated crawling (out of scope).
12 changes: 12 additions & 0 deletions src/TicketDeskPro.Api/Filters/RequirePermissionAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ public class RequirePermissionAttribute : Attribute, IAuthorizationFilter

public void OnAuthorization(AuthorizationFilterContext context)
{
// Unauthenticated callers get 401 (missing/expired token), authenticated
// callers without the permission get 403 — the two cases stay distinguishable.
if (context.HttpContext.User.Identity?.IsAuthenticated != true)
{
var unauthEnvelope = ApiResponse<object>.Fail(
[new ApiError(ErrorCodes.InvalidTokenState, "Not authenticated.")],
CorrelationIdMiddleware.GetCorrelationId(context.HttpContext));

context.Result = new ObjectResult(unauthEnvelope) { StatusCode = StatusCodes.Status401Unauthorized };
return;
}

var hasPermission = context.HttpContext.User
.HasClaim(c => c.Type == "permissions" && c.Value == _permission);

Expand Down
27 changes: 24 additions & 3 deletions src/TicketDeskPro.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,15 @@
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
if (db.Database.IsRelational()) // integration tests swap in InMemory, which has no migrations
await db.Database.MigrateAsync();
await DbSeeder.SeedAsync(
db,
includeDemoUsers: app.Environment.IsDevelopment() || app.Configuration.GetValue<bool>("SeedDemoUsers"));
var seedDemoUsers = app.Environment.IsDevelopment() || app.Configuration.GetValue<bool>("SeedDemoUsers");
if (seedDemoUsers && !app.Environment.IsDevelopment())
{
// Portfolio-demo intent, but the credentials are public — shout about it (BE-L2).
app.Logger.LogWarning(
"Demo users are being seeded in {Environment} with well-known public credentials. " +
"Unset SeedDemoUsers for a private production instance.", app.Environment);
}
await DbSeeder.SeedAsync(db, includeDemoUsers: seedDemoUsers);
}

// --- Pipeline (order matters: proxies first so scheme-based logic sees the truth) ---
Expand All @@ -132,6 +138,21 @@ await DbSeeder.SeedAsync(
forwarded.KnownProxies.Clear();
app.UseForwardedHeaders(forwarded);

// Baseline security headers on every response (FE-H1). Deliberately no CSP:
// Swagger UI's inline assets and generic JSON clients would break — revisit if
// a strict frontend proxy ever fronts this API.
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers.Append("X-Content-Type-Options", "nosniff");
context.Response.Headers.Append("X-Frame-Options", "DENY");
context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
return Task.CompletedTask;
});
await next();
});

app.UseMiddleware<CorrelationIdMiddleware>();
app.UseMiddleware<ExceptionHandlingMiddleware>();

Expand Down
5 changes: 5 additions & 0 deletions src/TicketDeskPro.Application/Interfaces/ILoginRateLimiter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ public interface ILoginRateLimiter
/// <summary>Records a login attempt; throws RateLimitedException when the window is full.</summary>
Task CheckAndRecordAsync(string ipAddress, string email, CancellationToken ct = default);

/// <summary>Records an attempt in a named bucket ("login", "forgot", "register") so
/// different auth actions get independent windows per email. Throws RateLimitedException
/// when that bucket's window is full.</summary>
Task CheckAsync(string bucket, string email, CancellationToken ct = default);

/// <summary>Clears the window for this identity after a successful login (FRD §5: "Reset Counter").</summary>
Task ResetAsync(string ipAddress, string email, CancellationToken ct = default);
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ public UserAdminService(

public async Task<UserPageDto> GetPageAsync(string? search, string? roleName, int limit, string? cursor, CancellationToken ct = default)
{
// Unbounded search strings turn the LIKE scan into a cheap DB-CPU lever (BE-L3).
if (search is { Length: > 200 }) search = search[..200];
var page = await _users.GetPageAsync(search, roleName, Math.Clamp(limit, 1, 100), cursor, ct);
return new UserPageDto(page.Items.Select(ToDto).ToList(), page.NextCursor, page.HasMore);
}
Expand Down
7 changes: 7 additions & 0 deletions src/TicketDeskPro.Application/Services/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ public async Task<RegisterResponse> RegisterAsync(RegisterRequest request, Cance
await _registerValidator.EnsureValidAsync(request, ct);

var email = NormalizeEmail(request.Email);
// Bucketed throttle: unauthenticated mass registration would otherwise cost
// nothing but BCrypt work and DB rows (email-keyed, same window as login).
await _rateLimiter.CheckAsync("register", email, ct);

if (await _users.AnyByEmailAsync(email, ct))
throw new ConflictException(ErrorCodes.EmailExists, "A user with this email already exists.");
Expand Down Expand Up @@ -230,6 +233,10 @@ public async Task ForgotPasswordAsync(ForgotPasswordRequest request, Cancellatio
await _forgotPasswordValidator.ValidateAndThrowAsync(request, ct);

var email = NormalizeEmail(request.Email);
// Bucketed throttle: without it anyone could flood a victim's inbox with
// reset emails and burn the whole Brevo free quota via the outbox worker.
await _rateLimiter.CheckAsync("forgot", email, ct);

var user = await _users.GetByEmailWithRolesAsync(email, ct);

if (user is not null)
Expand Down
24 changes: 22 additions & 2 deletions src/TicketDeskPro.Application/Services/TicketService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,22 @@ namespace TicketDeskPro.Application.Services;

public class TicketService : ITicketService
{
public const int MaxAttachmentsPerTicket = 5; // BR-009
public const int MaxAttachmentsPerTicket = 5;

/// <summary>Server-side Content-Type for the allowlisted extensions — the client's
/// value is untrusted input (BE-L1).</summary>
private static string ExtensionContentType(string extension) => extension switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".pdf" => "application/pdf",
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".txt" => "text/plain",
_ => "application/octet-stream"
};

public const long MaxAttachmentBytes = 5 * 1024 * 1024; // BR-009
public static readonly string[] AllowedAttachmentExtensions = [".jpg", ".png", ".gif", ".pdf", ".docx", ".xlsx", ".txt"]; // BR-010

Expand Down Expand Up @@ -86,6 +101,8 @@ public async Task<TicketListResponse> GetListAsync(TicketListQuery query, Cancel
throw new ForbiddenException(ErrorCodes.MissingPermission, "You do not have permission to perform this action."); // US-2.07: deleted view is admin-only

var limit = Math.Clamp(query.Limit, 1, 100);
// Unbounded search strings turn the LIKE scan into a cheap DB-CPU lever (BE-L3).
if (query.Search is { Length: > 200 }) query = query with { Search = query.Search[..200] };
var page = await _tickets.GetPageAsync(limit, query.Cursor, query.Search,
query.Status is null ? null : (int)query.Status,
query.Priority is null ? null : (int)query.Priority,
Expand Down Expand Up @@ -483,7 +500,10 @@ public async Task<TicketAttachmentDto> AddAttachmentAsync(Guid ticketId, Stream
Ticket = ticket,
FileName = safeName,
StoredPath = storedPath,
ContentType = string.IsNullOrWhiteSpace(contentType) ? "application/octet-stream" : contentType,
// The client's Content-Type is untrusted — derive it server-side from the
// (already allowlisted) extension so a .txt uploaded as text/html is
// still served as text/plain (BE-L1).
ContentType = ExtensionContentType(extension),
FileSizeBytes = content.CanSeek ? content.Length : 0,
UploadedById = viewer.Id
};
Expand Down
Loading
Loading