
Hardening Rust APIs Against Mass Assignment and Over-Posting
What mass assignment looks like in Rust
Mass assignment happens when a handler accepts a broad object from the client and applies it too directly to internal state. The danger is not Rust itself; it is the shape of your API.
Consider a user profile update endpoint. A developer might be tempted to deserialize JSON into a full User struct and persist it:
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
id: u64,
email: String,
display_name: String,
role: String,
is_admin: bool,
}
If the handler accepts this structure from the client, an attacker can send:
{
"id": 42,
"email": "victim@example.com",
"display_name": "Victim",
"role": "admin",
"is_admin": true
}
Even if your UI never sends role or is_admin, the API may still accept them unless you explicitly prevent it.
The core defense is simple:
- Never deserialize untrusted input directly into privileged domain objects
- Use separate request DTOs with only the fields the client is allowed to set
- Apply updates field-by-field, not by wholesale replacement
Why this is a security issue
Mass assignment is especially dangerous in systems with:
- user profile updates
- account registration
- admin panels
- multi-tenant resource updates
- partial PATCH endpoints
- ORMs or persistence layers that accept structs directly
The impact can include:
| Vulnerable field | Typical abuse |
|---|---|
role | privilege escalation |
is_admin | bypass authorization checks |
owner_id | resource hijacking |
account_status | re-enabling disabled accounts |
billing_plan | unauthorized feature access |
The issue often appears during rapid development when the same struct is reused across layers. That reuse feels efficient, but it couples external input to internal trust boundaries.
Use separate types for external input and internal state
The safest pattern is to define a request type that contains only client-editable fields. Keep privileged fields out of that type entirely.
Example: safe profile update model
use serde::Deserialize;
#[derive(Deserialize)]
struct UpdateProfileRequest {
display_name: Option<String>,
bio: Option<String>,
}
Your internal model can remain richer:
struct User {
id: u64,
email: String,
display_name: String,
bio: Option<String>,
role: Role,
is_admin: bool,
}
enum Role {
User,
Moderator,
Admin,
}
The request type is intentionally narrow. If the client sends role or is_admin, Serde will ignore them by default unless you configure otherwise. But do not rely on that alone as your only defense; the more important protection is that your handler never uses those fields because they do not exist in the request type.
Apply updates explicitly
A secure update handler should load the current record, then selectively apply only allowed changes.
fn apply_profile_update(user: &mut User, req: UpdateProfileRequest) {
if let Some(display_name) = req.display_name {
user.display_name = display_name;
}
if let Some(bio) = req.bio {
user.bio = Some(bio);
}
}
This approach has several advantages:
- it documents exactly what is mutable
- it prevents accidental assignment of privileged fields
- it makes code review easier
- it supports validation per field
If a new field is added later, it will not become writable unless someone explicitly updates the request type and the apply function.
Reject unknown fields when appropriate
By default, Serde ignores unknown fields in many deserialization scenarios. That can be useful for forward compatibility, but it may also hide malicious or mistaken input. For security-sensitive endpoints, consider rejecting unknown fields.
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct UpdateProfileRequest {
display_name: Option<String>,
bio: Option<String>,
}
With deny_unknown_fields, a request like this fails:
{
"display_name": "Alice",
"is_admin": true
}
This is valuable when:
- the endpoint is security-sensitive
- the API should be strict and predictable
- you want to detect client bugs early
- you want to reduce ambiguity in request handling
When not to use it
There are cases where strict rejection is inconvenient, such as:
- public APIs that evolve frequently
- clients that send extra metadata
- compatibility layers where unknown fields should be tolerated
In those cases, keep the narrow request type, but decide deliberately whether unknown fields should be ignored or rejected.
Design create and update flows separately
A common mistake is using one struct for both registration and profile editing. That often leads to fields being writable in the wrong context.
Bad pattern
#[derive(Deserialize)]
struct UserForm {
email: String,
display_name: String,
role: Option<String>,
is_admin: Option<bool>,
}
This type is too broad for public input. Even if some fields are optional, their presence invites misuse.
Better pattern
Use distinct types:
#[derive(Deserialize)]
struct RegisterRequest {
email: String,
display_name: String,
password: String,
}
#[derive(Deserialize)]
struct UpdateProfileRequest {
display_name: Option<String>,
bio: Option<String>,
}
Then keep administrative changes in a separate, authenticated endpoint with its own request type and authorization checks.
This separation makes your security model clearer:
| Operation | Request type | Who can call it |
|---|---|---|
| Register account | RegisterRequest | anonymous users |
| Update profile | UpdateProfileRequest | authenticated user |
| Change role | ChangeRoleRequest | administrators only |
Validate before applying changes
Even allowed fields need validation. Mass assignment is about which fields can be set, but validation is about what values are acceptable.
For example:
fn validate_display_name(name: &str) -> Result<(), &'static str> {
if name.trim().is_empty() {
return Err("display_name cannot be empty");
}
if name.len() > 50 {
return Err("display_name too long");
}
Ok(())
}
Then combine validation with update logic:
fn apply_profile_update(user: &mut User, req: UpdateProfileRequest) -> Result<(), &'static str> {
if let Some(display_name) = req.display_name {
validate_display_name(&display_name)?;
user.display_name = display_name;
}
if let Some(bio) = req.bio {
if bio.len() > 280 {
return Err("bio too long");
}
user.bio = Some(bio);
}
Ok(())
}
This keeps business rules close to the mutation point and avoids trusting client input just because it passed deserialization.
Be careful with ORMs and persistence helpers
Some Rust database libraries make it easy to map structs to rows. That convenience can become dangerous if you pass a client-derived struct straight into an update query.
For example, an ORM-style update that writes every field in a struct can accidentally persist privileged attributes if the struct is too broad.
Safer persistence strategy
- use a narrow update struct
- map fields explicitly to columns
- update only selected columns
- keep server-owned fields out of client input types
A good rule is: if the client should not be able to set a field, that field should not appear in the request model at all.
Handle partial updates carefully
PATCH endpoints are a common place for over-posting bugs because they often accept flexible input. The flexibility is useful, but it must be constrained.
A secure partial update flow usually looks like this:
- Deserialize into a narrow patch struct
- Reject unknown fields if the endpoint is strict
- Validate each provided field
- Apply only the fields present
- Persist the updated record
Example patch structure
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PatchUserRequest {
display_name: Option<String>,
bio: Option<String>,
}
This pattern avoids the temptation to accept a full user object with many optional fields. Optional does not mean safe; it only means the field may be omitted. If the field is present and privileged, it is still dangerous.
Common mistakes to avoid
1. Reusing database models as request models
A database row struct often contains fields that should never be client-controlled. Do not expose it directly.
2. Using serde(flatten) on untrusted input
Flattening can make request shapes harder to reason about and may accidentally merge fields from multiple sources. Keep request models explicit.
3. Allowing generic “update everything” endpoints
Endpoints that accept arbitrary JSON and merge it into stored state are high risk. Prefer explicit schemas.
4. Relying on frontend forms for security
Client-side forms are not a security boundary. Attackers can craft requests manually.
5. Forgetting authorization after validation
A field being syntactically valid does not mean the caller is allowed to change it. Authorization must be checked separately.
A practical checklist for Rust developers
Use this checklist when designing an endpoint:
- Does the request type contain only fields the caller may set?
- Are privileged fields absent from all public input models?
- Are unknown fields rejected where strictness matters?
- Are updates applied field-by-field rather than by replacement?
- Are values validated before persistence?
- Are authorization checks separate from input validation?
- Are admin-only actions isolated behind dedicated endpoints?
If you can answer yes to all of these, your API is far less likely to suffer from mass assignment.
A secure end-to-end example
Here is a compact example that ties the pattern together:
use serde::Deserialize;
#[derive(Debug)]
struct User {
id: u64,
email: String,
display_name: String,
bio: Option<String>,
is_admin: bool,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct UpdateProfileRequest {
display_name: Option<String>,
bio: Option<String>,
}
fn validate_display_name(name: &str) -> Result<(), &'static str> {
let trimmed = name.trim();
if trimmed.is_empty() {
return Err("display_name cannot be empty");
}
if trimmed.len() > 50 {
return Err("display_name too long");
}
Ok(())
}
fn update_profile(user: &mut User, req: UpdateProfileRequest) -> Result<(), &'static str> {
if let Some(display_name) = req.display_name {
validate_display_name(&display_name)?;
user.display_name = display_name;
}
if let Some(bio) = req.bio {
if bio.len() > 280 {
return Err("bio too long");
}
user.bio = Some(bio);
}
Ok(())
}
Notice what is missing: there is no way for the request to set id, email, or is_admin. That is the point. Security is often strongest when the dangerous option is not available at all.
Conclusion
Mass assignment is a design flaw, not a serialization bug. In Rust, the best defense is to make unsafe states unrepresentable in your public API surface. Use narrow request types, reject unknown fields where appropriate, validate values explicitly, and apply updates field-by-field.
If your code never gives clients access to privileged fields, they cannot over-post them. That simple boundary is one of the most effective security controls you can build into a Rust web service.