--- name: dmvcframework-security description: Use when writing or reviewing any DelphiMVCFramework server-side code that touches untrusted input — request bodies, query strings, headers, cookies, uploads, redirects, SQL/RQL, HTML output, JWT, CORS, secrets. Covers access control, mass assignment, SQL injection, XSS in TemplatePro, CSRF, path traversal, SSRF, file uploads, security headers, JWT hardening and secret management, with the DMVCFramework API that actually implements each control. Read before shipping an endpoint that a stranger can call. --- # DMVCFramework — Secure coding reference **This is a reference for the other DMVCFramework skills.** Whenever you write an endpoint that accepts input from a client — a controller action, a minimal-API handler, a web page, a filter — the controls below apply. They are not optional extras. Adapted from the OWASP-style [VibeSec](https://github.com/BehiSecc/VibeSec-Skill) secure-coding guide (Apache-2.0), rewritten against the real DMVCFramework API: every class, attribute and filter named here was verified in `sources/`. **The rule that catches most of it:** *never trust anything that arrived over the wire* — not the body, not the query string, not a header, not a cookie, not a filename, not a URL, not a JWT you have not verified. --- ## When in doubt about an API — verify it, never guess Never invent an identifier or answer from memory. If you need a signature this skill does not cover, ask the user for the path to their **DelphiMVCFramework checkout** and read `sources/` (and the matching `samples/` project); failing that, read the official repository — [sources](https://github.com/danieleteti/delphimvcframework/tree/master/sources) · [samples](https://github.com/danieleteti/delphimvcframework/tree/master/samples). If you still cannot verify it, **say so**. Where a skill and a sample disagree, **the sample wins**. --- ## 1. Access control — the #1 cause of real breaches Authentication says *who you are*. Authorization says *what you may touch*. Do not confuse them: a valid JWT is not permission to read row 42. **The IDOR trap.** This is the single most common serious bug in a CRUD API: ```delphi // BROKEN — any authenticated user can read anyone's order function TOrdersController.GetOrder(const ID: Integer): IMVCResponse; begin Result := OKResponse(TMVCActiveRecord.GetByPK(ID)); end; ``` The ID comes from the URL. Nothing ties it to the caller. Scope **every** lookup to the authenticated principal, in the query — not with an `if` after the fact: ```delphi function TOrdersController.GetOrder(const ID: Integer): IMVCResponse; var lOrder: TOrder; begin // the ownership check IS the query lOrder := TMVCActiveRecord.GetOneByWhere( 'id = ? and customer_id = ?', [ID, CurrentUserID], False); if lOrder = nil then Exit(NotFoundResponse); // same answer as "not yours" — do not leak existence Result := OKResponse(lOrder); end; ``` - Deny by default. A new action is unreachable until you decide who may call it. - Enforce on **every** verb. A GET that is properly scoped and a DELETE that is not is still a breach. - Return **404, not 403**, for a resource that exists but is not the caller's — 403 confirms it exists. - Never trust a role, tenant or user id that arrives in the **body or a query param**. Read it from the verified token / session only. **Where the identity comes from:** | Style | Read the principal from | |-------|------------------------| | JWT (controller) | `Context.LoggedUser.UserName` / `.Roles` / `.CustomData` — populated by the check of `JWTAuthenticationBundle` / `JWTCookieAuthenticationBundle` (or the deprecated `TMVCJWTAuthenticationMiddleware` of a 3.4 project) after signature validation | | Minimal API | the `AuthorizeEndpointFilter` / `RequireRoleEndpointFilter('admin')` endpoint filters, plus `Ctx.LoggedUser` | | Web app session | `Context.Session['user']` — only after the session filter/middleware has run | Role checks belong on the route group or the action, not scattered through the body: ```delphi // minimal API — the whole group is gated var lAdmin := lApi.Prefix('/admin').Use(AuthorizeEndpointFilter()).Use(RequireRoleEndpointFilter('admin')); ``` --- ## 2. Mass assignment — the framework will happily overwrite `is_admin` `[MVCFromBody]` deserializes the JSON straight into your object. If that object is your ActiveRecord entity, the client controls **every writable property**, including the ones you never meant to expose: ```delphi // BROKEN — POST {"email":"x@y.z","role":"admin","id":1} function TUsersController.CreateUser(const [MVCFromBody] User: TUser): IMVCResponse; begin User.Insert; // role = admin. Congratulations. Result := CreatedResponse('/users/' + User.ID.Value.ToString); // ID is a NullableInt64 end; ``` Two fixes, in order of preference: **a) Bind to a DTO that only has the fields the client may set.** This is the recommended two-layer pattern and it is self-documenting: ```delphi type [MVCNameCase(ncCamelCase)] TCreateUserDTO = class private fEmail: string; fFullName: string; public [MVCRequired] [MVCEmail] property Email: string read fEmail write fEmail; [MVCRequired] property FullName: string read fFullName write fFullName; // no Role. no ID. no PasswordHash. end; ``` **b) Block the field on the entity** with `[MVCDoNotDeserialize]` (honoured by the JSON serializer): ```delphi [MVCTableField('role')] [MVCDoNotDeserialize] // server-assigned; ignored if it arrives in the body property Role: string read fRole write fRole; ``` `[MVCDoNotSerialize]` hides a field from the **response** (use it for `password_hash`); `[MVCDoNotDeserialize]` protects it from the **request**. They are different attributes — you often want both. ActiveRecord's `foAutoGenerated` / `foReadOnly` / `foDoNotInsert` field options keep a column out of the INSERT, which is useful — but they do **not** stop the value from being deserialized into the object. Do not rely on them as a mass-assignment guard. ### Validate the input DTO — and know what is not validated Put validator attributes (`MVCFramework.Validators`) on the DTO's **properties**: `[MVCFromBody]` runs them before the action and answers 422. Bound by length (`MVCMaxLength`) every string you store; restrict enums and sort keys with `MVCIn` (case-insensitive). What is **not** validated for you: `[MVCFromQueryString]`, `[MVCFromContentField]` and route parameters of a controller, HTML form posts, and a `[MVCFromBody]` `TObjectList` (wrap it in a DTO property). Validate those yourself with `TMVCValidationEngine.Validate`. Details: the `dmvcframework` skill, `reference/validation.md`. --- ## 3. SQL injection `TMVCActiveRecord` is parameterized everywhere. The only way to get injected is to build the string yourself. ```delphi // BROKEN lUsers := TMVCActiveRecord.Where('email = ''' + lEmail + '''', []); // CORRECT — placeholders, values in the array lUsers := TMVCActiveRecord.Where('email = ?', [lEmail]); lUsers := TMVCActiveRecord.Where('created_at > ? and active = ?', [lFrom, True]); ``` The same rule applies to `GetOneByWhere`, `GetFirstByWhere`, `Select`, `SelectOne`, `SelectRQL` and every repository method: **the SQL string is a constant; user data goes in the params array.** **RQL from the client** (`?rql=...`) is a real feature and a real surface. RQL is parsed, not concatenated, so it will not smuggle SQL — but it lets the caller filter on **any mapped column** and page as deep as they like. Treat it as a query API: only expose it on resources where every column is safe to filter on, always combine it with the caller's ownership scope, and keep `MaxRecordCount` bounded. Column and table names can never be parameterized. If a sort field comes from the client, **allow-list it** — never interpolate it: ```delphi if not MatchStr(lSortBy, ['name', 'created_at', 'total']) then raise EMVCException.Create(HTTP_STATUS.BadRequest, 'Invalid sort field'); ``` --- ## 4. XSS — and the one TemplatePro character that disables the defence TemplatePro **HTML-escapes `{{:value}}` by default**. The `$` suffix turns escaping off: ```html {{:comment.Body}} {{# safe — escaped #}} {{:comment.Body$}} {{# RAW — an XSS hole if Body came from a user #}} ``` A block does the same for everything inside it — `{{autoescape false}}` … `{{endautoescape}}` disables escaping exactly like `$` on every value in between. Search for both when reviewing a template. Use `$` (or `autoescape false`) only for HTML **you** generated. If you must render user-submitted rich text, sanitize it server-side with an allow-list of tags before it ever reaches `ViewData` — an escape-blacklist will be bypassed. **Escaping is HTML-entity encoding, nothing more.** TemplatePro's `HTMLEncode` turns `& < > " '` into entities. That is enough for element text and for a **quoted** attribute value. It does not protect: - a URL attribute: `` with `link = javascript:alert(1)` contains none of those characters and runs. Allow-list the scheme (`https:`, or a relative path) on the server; - an **unquoted** attribute (`
`): a space ends the value and starts a new attribute. Always quote; - a JavaScript context — inside `