Course outline

Django / Reliable application workflows / Lesson 14

File uploads and controlled access

Accept an uploaded file through a form while defining storage, validation and download authorization boundaries.

About 24 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Bind files and fields to a Django form.
  • Design validation and storage for untrusted uploads.
  • Test permitted and rejected upload and download paths.
  • Bind and validate untrusted file uploads with a server-owned storage identity.
  • Authorize delivery and test database, storage, and cleanup failures as separate boundaries.

Define the upload contract

An uploaded file is untrusted data even when a browser supplies a familiar filename or content type. Specify who may upload, allowed formats, size limits, retention and who may download. Keep application static assets separate from user media. Validate according to the file’s intended use and consider the risk of parsing hostile content; an extension or declared MIME type is not a complete content verification strategy.

Bind the file and the other fields

Django exposes uploaded files through request.FILES for an appropriately encoded submission. The fragment binds both POST data and files to an existing form. Its template must use multipart/form-data and include the normal CSRF protection for a session-backed form. Reject invalid input before processing it, and return field errors that help the user correct the request without reflecting unsafe internal details.

python Bind an existing upload form
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
    uploaded = form.cleaned_data['file']
    # Apply the application's storage and authorization policy.

The form and its validation are application-specific. The fragment does not save or authorize a file.

Choose storage and a server-owned identity

Use the configured storage system rather than constructing a filesystem path from the original filename. Generate or choose an application-controlled storage key, and keep the original name only as untrusted metadata if needed. Storage and database writes can fail independently, so define cleanup and reconciliation for orphaned files or missing objects. Limit incoming requests at appropriate infrastructure and application boundaries; a form validation error alone may happen after upload data has arrived.

Authorize every download

The example sketches an authenticated download of an existing document object and checks its policy before opening storage. The application must define the model and policy; the fragment is not a complete endpoint. A hard-to-guess path does not replace authorization. Set safe response headers appropriate to the content and deployment, and avoid serving user-controlled content from a context where it can execute as trusted application code.

python Sketch a policy-checked download
from django.http import FileResponse, HttpResponseForbidden

if not can_download(request.user, document):
    return HttpResponseForbidden()
return FileResponse(document.file.open('rb'), as_attachment=True)

The model, policy and storage setup must exist. The response is illustrative and requires an application-specific safe delivery design.

Exercise failure and ownership

In an isolated storage backend, test a valid small synthetic upload, an invalid type, an oversized file and a missing file. Check that denied or invalid requests do not leave unintended database rows or storage objects. Test an authorized download and a different user’s denied request. Simulate storage failure and verify the documented cleanup path; a fake storage test does not prove the production server’s request-size limits.

Define who can upload and what happens to the bytes

An uploaded file is untrusted even when its name and declared content type look familiar. Define the allowed actor, operation, formats, size, retention, and download audience before choosing a storage backend. A synthetic application may accept one PDF no larger than 2048 kilobytes and keep it in private storage, but that is a fixture policy, not a universal rule. File extension and client-declared MIME type are metadata controlled by the sender; content validation must be appropriate to the intended format and use. Parsing hostile content or making it available on the application's origin can create additional risks.

Keep application static assets separate from user media. Limit upload size at the infrastructure and application layers because a form validation failure can occur after data has already reached the server. Decide whether separate malware inspection, quarantine, or moderation is required before serving an accepted file. A format check does not certify that the file is harmless. The Django 5.2 fragments here assume the stated form, storage, policies, and disposable synthetic fixtures; they are illustrative and non-runnable. No real file, configured application disk, or external provider was accessed.

Bind both fields and files, then validate deliberately

A browser upload form needs multipart/form-data, and the view binds both request.POST and request.FILES to the form. The file appears in cleaned_data only after the form has accepted it under its declared rules. Define what happens for a missing file, wrong content, excessive size, and empty or duplicated fields. Validate and authorize before handing the object to domain or storage work. Browser-side restrictions are helpful feedback but do not replace server checks; a client can send a request without using the page.

Do not trust UploadedFile.name or content_type as proof of file content or as a path to open. A real content-inspection strategy depends on the format, the libraries used, and the application's threat model. Bound processing resources, review parser behavior, and handle errors without exposing internal paths or file bytes. If inspection is asynchronous, define a pending state and prevent unapproved downloads until the required result is known. Test the accepted and rejected cases with synthetic files and assert both response and absence or presence of storage and database effects.

Separate server-owned storage identity from display metadata

Use the configured storage API and an application-controlled key or storage-generated name rather than concatenating an original filename into a filesystem path. Keep the original name only as untrusted display metadata when needed, and choose a safe download presentation name. A collision strategy and tenant scope must be explicit, but an unguessable key is not permission. Persist the returned relative storage name with the relevant storage context; do not accept a raw key from a later request as proof of ownership.

Database writes and storage writes are different resources. A database rollback does not automatically remove an object already written to a filesystem or remote store. If storage succeeds but record creation fails, use the known generated key to attempt authorized cleanup; if cleanup fails, record a bounded recoverable orphan task and avoid a false success response. If storage fails first, do not create a record claiming success. Define replacement, deletion, retention, and recovery paths separately and test them on a disposable fake or isolated adapter.

Authorize before opening or issuing access to a file

Resolve the application's Document record in the intended tenant or owner scope and authorize the current actor for that specific object before opening its file. A user who knows a document ID or storage key may reach a record without guessing a filename. Decide whether a forbidden foreign record is denied explicitly or concealed as missing, and apply the disclosure policy consistently. Return a safe attachment response and avoid revealing absolute paths, raw storage errors, or attacker-controlled headers. Serving user content from the main application origin requires careful deployment and content-type policy.

Temporary or signed download URLs, when supported by the selected provider, are bearer capabilities whose recipients may share them until expiry. Authorize issuance and define lifetime, disclosure, and revocation expectations; a later application policy change may not revoke a URL already accepted by a remote store. Never log a full bearer URL or file contents. A FileResponse or storage API fragment is not a complete access design: test permitted owner, denied other user, missing record, and missing object under the actual backend and policy.

Test file and database boundaries independently

Create a disposable matrix for a small accepted synthetic upload, a misleading filename or declared type, an oversized file, missing request.FILES or multipart encoding, a denied actor, a cross-tenant download, a storage failure, and an insert failure after a successful write. Assert the response, Document state, and storage object state separately. Capture any generated storage name from the record or backend rather than fabricating a fixed random filename. Check that denied responses contain neither bytes nor sensitive paths, and that success is reported only after the declared operation completes.

An isolated fake or temporary storage backend can verify the application's intent without touching real files, but it does not prove cloud bucket privacy, provider availability, malware scanning, production request-size limits, or browser behavior. Use separately controlled integration evidence for those boundaries when required. Verify the test database and storage targets are disposable before execution, and keep synthetic content and credentials only. Record the middleware, CSRF, policy, storage backend, and cleanup assumptions; do not claim a live upload or download was executed by reading an illustrative fragment.

20 worked examples

1. Bind form and file

Problem: Bind both form fields and uploaded files for a multipart request.

  1. The multipart parser supplies ordinary fields in POST and the uploaded object in FILES.
  2. The form receives both mappings and can validate its declared fields.
python Django 5.2 upload or storage fragment with synthetic data
form = UploadForm(request.POST, request.FILES)
# Fixture: authorized POST, multipart/form-data, title='Report', file=synthetic.pdf.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: A valid form exposes the file through cleaned_data after is_valid.

Why this result follows: Binding both request sources preserves the upload and its accompanying form data.

2. Missing FILES binding

Problem: Diagnose a required file that the form never receives.

  1. The form receives the field mapping but not the uploaded-file mapping.
  2. Its required file field cannot access the synthetic upload through this binding.
python Django 5.2 upload or storage fragment with synthetic data
form = UploadForm(request.POST)
# Fixture: request.FILES contains synthetic.pdf, but it is not passed to the form.
# The form requires file.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: Validation reports a file error; bind request.FILES as well.

Why this result follows: An uploaded file is not automatically included when only request.POST is passed.

3. Multipart requirement

Problem: Identify a browser form that cannot send a file correctly.

  1. The form declares multipart encoding for file submission.
  2. The token tag supplies the configured browser-request CSRF field for the internal POST.
html Django 5.2 upload or storage fragment with synthetic data
<form method="post" enctype="multipart/form-data">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Upload</button>
</form>
{# Fixture: internal route and CSRF middleware configured. #}

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The browser can submit file and field data under the stated setup.

Why this result follows: Multipart encoding and CSRF address different prerequisites of this upload workflow.

4. Missing required file

Problem: Reject a bound request with no uploaded object.

  1. The bound form receives no uploaded object for its required file field.
  2. Validation reports the missing file before storage is invoked.
python Django 5.2 upload or storage fragment with synthetic data
form = UploadForm({'title': 'Report'}, {})
valid = form.is_valid()
# Fixture: file is required; no file mapping entry exists.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: valid is False and file has an error.

Why this result follows: A required file rule prevents the operation from assuming an absent upload exists.

5. Size limit

Problem: Reject a synthetic file above the declared maximum.

  1. The file’s reported size exceeds the application limit in this fixture.
  2. The field cleaning method raises a controlled validation error.
python Django 5.2 upload or storage fragment with synthetic data
def clean_file(self):
    uploaded = self.cleaned_data['file']
    if uploaded.size > 2048 * 1024:
        raise forms.ValidationError('File is too large.')
    return uploaded
# Fixture: file size is 3000 KB.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The form is invalid and the storage step is skipped.

Why this result follows: An application size rule bounds accepted input, though infrastructure limits are also needed.

6. Misleading filename

Problem: Do not infer safe PDF content solely from an extension.

  1. The filename and declared type conflict in the stated request.
  2. The application must apply its reviewed content-validation policy rather than trusting either alone.
text Django 5.2 upload or storage fragment with synthetic data
filename: invoice.pdf
client content_type: image/png
application policy: inspect allowed content; reject mismatches
// Synthetic upload metadata; no file parser is executed.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The mismatch is rejected under this fixture policy.

Why this result follows: Client-controlled metadata is not a complete content-verification mechanism.

7. Inspection pending

Problem: Keep an accepted upload unavailable until required scanning completes.

  1. Passing form checks does not establish that the content is harmless.
  2. The product’s separate inspection rule keeps the object unavailable while pending.
text Django 5.2 upload or storage fragment with synthetic data
form validation: passes format and size
malware inspection: pending
download policy: deny until approved
// Synthetic lifecycle trace; no scanner runs.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The document remains pending and cannot be downloaded as approved.

Why this result follows: Format validation and malware inspection address different risks and states.

8. Server-owned name

Problem: Store an upload using the configured storage API rather than a client path.

  1. The application supplies a server-controlled candidate storage name.
  2. The storage backend returns the actual stored name, which the record should retain.
python Django 5.2 upload or storage fragment with synthetic data
name = storage.save('documents/generated-key.pdf', uploaded)
# Fixture: key is chosen by the server; storage backend is private and disposable.
# Store the returned name on the Document record.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The Document stores the returned relative name.

Why this result follows: Storage identity is independent of an untrusted original display filename.

9. Traversal-shaped filename

Problem: Keep ../private.pdf from selecting a storage location.

  1. The original filename is treated as untrusted metadata.
  2. The storage call uses the server-owned name rather than joining the client path.
python Django 5.2 upload or storage fragment with synthetic data
original_name = uploaded.name
name = storage.save('documents/server-key.pdf', uploaded)
# Fixture: original_name='../private.pdf'; storage key is server-controlled.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The requested object name remains documents/server-key.pdf.

Why this result follows: Separating display metadata from storage identity prevents this input from choosing the write path.

10. Storage failure before record

Problem: Avoid a success record when saving the object raises.

  1. The storage operation fails before the record creation statement.
  2. The view returns the controlled failure and does not claim a successful Document.
python Django 5.2 upload or storage fragment with synthetic data
try:
    name = storage.save(server_key, uploaded)
except OSError:
    return HttpResponse('Upload unavailable', status=503)
Document.objects.create(storage_name=name)
# Fixture: storage raises before returning a name.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The response is 503 and no success record is created.

Why this result follows: The storage result must be known before a record can truthfully represent the object.

11. Record failure after storage

Problem: Attempt cleanup when a stored object has no committed record.

  1. The object write succeeds before the database insert fails.
  2. The cleanup uses the returned server-owned name to remove the orphan in this fixture.
python Django 5.2 upload or storage fragment with synthetic data
name = storage.save(server_key, uploaded)
try:
    Document.objects.create(storage_name=name)
except Exception:
    storage.delete(name)  # fixture: cleanup succeeds
    raise
# Illustrative failure boundary; application reports safely.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: No success response is returned and the object is deleted.

Why this result follows: A database failure does not automatically roll back a separate storage write.

12. Cleanup failure

Problem: Record recoverable orphan work when deletion also fails.

  1. The object remains because the first cleanup attempt failed.
  2. The application records enough safe identity for a later authorized reconciliation attempt.
text Django 5.2 upload or storage fragment with synthetic data
storage write: succeeds with name K
Document insert: fails
cleanup delete K: fails
recovery: record a bounded orphan task for K
// Synthetic failure trace; no file contents are logged.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The request is not reported as success; orphan K remains tracked.

Why this result follows: Explicit recovery makes an unresolved cross-resource failure visible instead of silently losing it.

13. Authorize before opening

Problem: Check document access before reading private bytes.

  1. The policy rejects the actor for the resolved document.
  2. The return occurs before the file is opened in this view path.
python Django 5.2 upload or storage fragment with synthetic data
document = get_object_or_404(Document, pk=document_id)
if not can_download(request.user, document):
    return HttpResponseForbidden()
return FileResponse(document.file.open('rb'), as_attachment=True)
# Fixture: synthetic actor is denied.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The response is 403 and no bytes are sent.

Why this result follows: A storage name does not grant permission to the current requester.

14. Scoped foreign document

Problem: Conceal another tenant’s known document identifier.

  1. The lookup searches the actor’s tenant scope.
  2. The foreign document is not returned for subsequent delivery.
python Django 5.2 upload or storage fragment with synthetic data
document = get_object_or_404(Document.objects.filter(tenant=request.user.tenant), pk=document_id)
# Fixture: actor tenant=7; document 42 belongs to tenant 8; policy conceals foreign records.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The configured missing-resource response contains no file bytes.

Why this result follows: A known identifier cannot bypass the application’s scoped lookup and policy boundary.

15. Allowed attachment

Problem: Return an authorized synthetic file as an attachment.

  1. The object policy permits the actor.
  2. FileResponse is constructed only after the check with an application-chosen filename.
python Django 5.2 upload or storage fragment with synthetic data
if not can_download(request.user, document):
    return HttpResponseForbidden()
return FileResponse(document.file.open('rb'), as_attachment=True, filename='report.pdf')
# Fixture: actor allowed; object exists; safe delivery policy configured.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The allowed response is an attachment named report.pdf.

Why this result follows: A controlled presentation name and policy check protect separate parts of the delivery contract.

16. Missing storage object

Problem: Handle an authorized record whose file is absent.

  1. The actor passes the policy but storage cannot open the object.
  2. The missing-object branch returns the declared safe missing-resource response.
python Django 5.2 upload or storage fragment with synthetic data
if not can_download(request.user, document):
    return HttpResponseForbidden()
try:
    return FileResponse(document.file.open('rb'), as_attachment=True)
except FileNotFoundError:
    raise Http404('Document unavailable')
# Fixture: record exists; object is missing.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The response is 404 without file bytes or an absolute path.

Why this result follows: Record existence and authorization do not guarantee that the separate storage object exists.

17. Denied cross-user test

Problem: Check that another user receives no private file.

  1. The request targets a known synthetic document belonging to another user.
  2. The assertions check denial and absence of the test file bytes.
python Django 5.2 upload or storage fragment with synthetic data
response = client.get('/documents/42/download/')
assert response.status_code == 403
assert b'synthetic private bytes' not in response.content
# Fixture: logged-in non-owner; policy returns 403; disposable storage.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The response is 403 and does not contain the private content.

Why this result follows: A direct negative request verifies enforcement beyond a hard-to-guess storage name.

18. Temporary URL capability

Problem: Recognize a shared temporary URL as a bearer capability.

  1. The application authorized A when it issued the URL.
  2. Under the stated provider contract, B may use the forwarded capability until expiry.
text Django 5.2 upload or storage fragment with synthetic data
issued URL: private object, expires in 5 minutes
authorized user A forwards it to B before expiry
provider contract: bearer URL accepted until expiry
// Synthetic trace; no provider is contacted.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: B may access the object while the URL remains valid.

Why this result follows: An expiring link limits time but does not inherently identify the person presenting it.

19. Fake storage evidence

Problem: Classify what a temporary storage test establishes.

  1. The test confines its synthetic upload to a temporary storage target.
  2. It does not exercise cloud bucket policy, real provider availability, or production request limits.
python Django 5.2 upload or storage fragment with synthetic data
with override_settings(MEDIA_ROOT=temporary_directory):
    response = client.post('/documents/', {'file': synthetic_file})
    # Assert the recorded storage name and object in this disposable directory.
# Fixture: no cloud provider is contacted.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: Application storage behavior is tested only in the isolated backend.

Why this result follows: A disposable storage fixture supports its own application boundary, not untested cloud guarantees.

20. Safe failure response

Problem: Avoid reflecting a private storage path in an upload error.

  1. The application reports a bounded failure category.
  2. The public JSON omits the internal storage path and file contents.
python Django 5.2 upload or storage fragment with synthetic data
try:
    save_document(uploaded)
except StorageError:
    logger.warning('document_storage_failed', extra={'category': 'write_failed'})
    return JsonResponse({'error': 'upload unavailable'}, status=503)
# Fixture: synthetic storage exception contains an internal path.

Illustrative fragment requiring the stated isolated form, policy, and disposable storage fixture; it has not been executed here.

Expected result: The caller receives 503 without the synthetic path.

Why this result follows: Safe error mapping separates operational diagnosis from sensitive storage details.

Common errors and fixes

The form never receives the file

Why it happens
The form is missing multipart encoding or the view omits request.FILES.
How to fix it
Bind both request.POST and request.FILES and fix the template encoding.
Prevent it next time
Test a real multipart request with a synthetic file.

A different user can download a file

Why it happens
The application relies only on an obscure filename.
How to fix it
Authorize access to the specific object before opening storage.
Prevent it next time
Test owner and non-owner requests.

A failed database write leaves an orphan file

Why it happens
Storage and database changes have separate failure boundaries.
How to fix it
Implement cleanup or reconciliation appropriate to the storage backend.
Prevent it next time
Inject a failure and inspect both database and storage.

20 practice exercises

1. An uploaded file is named invoice.pdf but declares an image content type. What should happen?

Show hint

The name and declared content type are both client-controlled metadata.

Show worked solution

Apply the application’s allowed-format and content-validation policy rather than trusting either the name or declared type. Reject mismatches where required and test the resulting storage and database state.

Apply the application’s reviewed allowed-format and content-validation policy to the synthetic upload rather than trusting either invoice.pdf or the declared image type alone. Reject a mismatch when the policy requires it, and check both storage and database state after rejection. A format check is not a complete malware guarantee.

Check your solution

  • The mismatch follows the declared validation policy.
  • No unintended object or record remains after rejection.

2. A user knows another user’s storage key. Is that enough to permit a download?

Show hint

A storage key does not establish permission to the document.

Show worked solution

No. Resolve the application record and authorize the requester for that object before opening it. Test both a permitted owner and a denied other user, and avoid revealing the storage path in the denial.

Resolve the application record under the intended scope and authorize the actual requester for that object before opening storage or issuing a capability. Test an allowed owner and a denied synthetic non-owner who knows the identifier, and avoid revealing the storage path or bytes in the denial.

Check your solution

  • Authorization precedes opening the object.
  • The denied response contains no private bytes or path.

3. A browser upload form submits a file and title. What template and view bindings are required?

Show hint

File data has a separate request mapping.

Show worked solution

Use multipart/form-data in the internal POST form and bind the form with both request.POST and request.FILES. Include the configured CSRF token and validate the form before processing the file. Test a real synthetic multipart submission in an isolated client and check the approved cleaned fields.

Check your solution

  • The template uses multipart encoding.
  • The form receives POST and FILES.

4. A required uploaded file is missing from a bound request. Define feedback and state checks.

Show hint

Reject before storage work.

Show worked solution

Bind the empty file mapping, assert a field error under the application contract, and confirm that no object or Document record was created in disposable storage and database fixtures. Add a valid small-file control and keep authorization constant so the test isolates the missing-file boundary.

Check your solution

  • The file field reports an error.
  • No success object or record exists.

5. A file named invoice.pdf declares an image content type. How should the application decide?

Show hint

Both name and declared type are untrusted.

Show worked solution

Apply the application’s allowed-format and content-inspection policy rather than accepting either metadata value as definitive. If the reviewed policy rejects the synthetic mismatch, assert an actionable validation error and no unintended storage or database record. A format check does not prove malware clearance.

Check your solution

  • The mismatch follows the declared content policy.
  • Rejected input leaves no success artifact.

6. A synthetic upload exceeds a 2048 KB application limit. Design a safe rejection test.

Show hint

The size rule is only one layer of limits.

Show worked solution

Submit an oversized synthetic file through an isolated multipart client as an authorized actor, assert the form error, and verify that no Document or stored object remains. Also review infrastructure request limits because application validation can happen after upload data arrives. Test a permitted boundary case separately.

Check your solution

  • The oversized file is rejected.
  • No success record or object remains.

7. A client supplies ../private.pdf as the original filename. How should storage identity be chosen?

Show hint

Display metadata must not become a path.

Show worked solution

Use a server-controlled or storage-generated name under the intended private location, retain the returned relative name, and treat the original name only as untrusted metadata if required. Test the traversal-shaped synthetic name and confirm it does not choose or escape the storage path. Do not expose it unescaped in headers.

Check your solution

  • The client name does not choose the key.
  • The stored name remains in the intended scope.

8. An upload passes type and size checks but scanning is required. What state should be tested?

Show hint

Acceptance is not malware clearance.

Show worked solution

Place the object in the application’s defined pending or quarantine state until the separate inspection completes, and deny normal download before approval. Test validation success, pending access denial, and the approved or rejected inspection outcome with synthetic files. Do not claim that a MIME or extension check proves harmless content.

Check your solution

  • Pending content is not served as approved.
  • Inspection outcome changes state according to policy.

9. Storage fails before a Document record is created. Specify response and state assertions.

Show hint

A failed object write cannot support a success record.

Show worked solution

Use a controlled failing storage adapter, submit an otherwise valid authorized upload, and assert the documented safe failure response. Verify that no database record claims the file exists and that no unintended object remains. Avoid logging file bytes, credentials, or raw internal storage paths.

Check your solution

  • The failure response is controlled.
  • No success record is persisted.

10. The object write succeeds but the database insert fails. Design cleanup and recovery.

Show hint

A database rollback does not remove the separate object.

Show worked solution

Track the returned server-owned storage name and attempt cleanup when the record cannot commit. If deletion fails, record a bounded recoverable orphan task and retry according to the application policy. Test both cleanup outcomes in disposable storage and ensure the client does not receive a false success.

Check your solution

  • Cleanup is attempted for the generated object.
  • Failed cleanup remains visible for reconciliation.

11. A user knows another user’s storage key. Is that enough to download the file?

Show hint

Possession of a key is not authorization.

Show worked solution

Resolve the application Document under the intended scope and authorize the requester for that actual object before opening it or issuing a temporary link. Test an allowed owner and a denied synthetic non-owner with a known identifier, asserting no bytes or sensitive path in the denial.

Check your solution

  • The document policy is checked first.
  • The denied user receives no file bytes.

12. A document record exists but its object is missing. Define a safe download response.

Show hint

Record existence does not prove object availability.

Show worked solution

After checking access, handle a missing object according to the documented contract, for example a controlled 404 without exposing absolute paths or raw storage exceptions. Test an allowed synthetic user with an absent object and verify no bytes are returned. Distinguish this from a denied actor.

Check your solution

  • The missing object has a defined response.
  • No internal path or bytes are exposed.

13. A private document is served through a public media URL. Explain the access risk.

Show hint

A direct public route may bypass the view.

Show worked solution

A user who obtains the URL may access the object without the application’s per-document policy, even if the filename is difficult to guess. Choose a private storage and authorized delivery design for confidential material, and test direct access and cross-user requests in an approved isolated environment.

Check your solution

  • The public exposure is identified.
  • Authorized delivery is enforced separately.

14. A user-controlled file is served from the application’s trusted origin. What needs review?

Show hint

Uploaded content can execute in an unsafe serving context.

Show worked solution

Review Django’s user-uploaded-content security guidance and design storage origin, content type, attachment behavior, and browser protections for the accepted formats. Do not assume a filename or MIME declaration makes content safe. Test synthetic files and headers in a controlled environment without exposing real user data.

Check your solution

  • The serving origin and headers are reviewed.
  • Untrusted content is not treated as application code.

15. A temporary file URL is issued after authorization and then forwarded. Explain the exposure.

Show hint

The URL may be a bearer capability.

Show worked solution

Under a provider’s bearer-link contract, a forwarded live URL may be usable by someone other than the originally authorized actor until expiry. Define lifetime, delivery, logging, and revocation expectations with the actual storage provider. Test unauthorized issuance and an allowed case without publishing a real secret URL.

Check your solution

  • The sharing window is acknowledged.
  • Lifetime and revocation policy are defined.

16. A replacement object is stored but updating the Document fails. Design the recovery test.

Show hint

Old and new objects have different roles.

Show worked solution

Keep the record pointing to the old valid object until the replacement record change succeeds under the application contract. On failure attempt cleanup of the new generated object and record an orphan task if deletion fails. Assert record state, both temporary objects, and absence of a false success response.

Check your solution

  • The original record remains usable.
  • The new orphan is cleaned or tracked.

17. A record deletion succeeds but object deletion fails. What operational contract is needed?

Show hint

The two resources fail independently.

Show worked solution

Define an authorized recoverable deletion task, bounded retries, retention and audit behavior, and a way to observe unresolved objects without logging contents or secrets. Test the storage failure and verify the application does not falsely claim complete erasure. Do not assume deleting a database row deletes the remote object.

Check your solution

  • The unresolved object is tracked.
  • The reported outcome follows the deletion contract.

18. A test uses a temporary media directory and passes. What production evidence is missing?

Show hint

A disposable backend is not the cloud service.

Show worked solution

The test can establish application behavior and cleanup in that directory but not production bucket privacy, temporary URL semantics, provider availability, or server upload-size limits. Use separately approved isolated integration evidence for those boundaries when required, and record the storage backend and settings used.

Check your solution

  • The local storage test is described narrowly.
  • Provider and server limits are tested separately.

19. A denied download response includes the private storage path. Design a regression test.

Show hint

Denial must not leak bytes or internal location.

Show worked solution

Create a synthetic foreign-owned document, request it as a denied user, and assert the configured forbidden or concealed response plus absence of file bytes and the stored path. Include an allowed-owner control and inspect logs for safe categories rather than sensitive paths.

Check your solution

  • The denied response contains no bytes or path.
  • The allowed owner can use the intended path.

20. A test expects a fixed random filename after upload. How should it verify the generated identity?

Show hint

Capture the actual returned storage name.

Show worked solution

After a successful synthetic upload, read the stored name from the created Document or controlled backend and assert that the disposable storage contains the corresponding object under the intended directory. Verify that the original client filename did not choose the key and that ownership is correct. Do not fabricate an exact random name.

Check your solution

  • The recorded name refers to the stored object.
  • The client filename does not control identity.

Key takeaways

  • Uploaded files remain untrusted across validation, storage and delivery.
  • Test authorization and cleanup at both database and storage boundaries.
  • A client filename, declared type, storage key, and access permission are different trust decisions.
  • Database rollback does not automatically remove a separately stored object.
  • A fake storage backend does not prove production privacy, provider behavior, or upload limits.

Official references