Module 4 of 5Free to explore

Code Review and Architectural Patterns

2 hoursTheory and practiceMedium

Study-time guide: 15 min reading and analysis, 65 min core exercises, 40 min review and deliverable. Additional external-platform execution is estimated separately.

Review an operation across its trust boundary

A useful security review examines how untrusted data influences an important operation. Separating controller, service, and repository classes does not guarantee a correct authorization decision. Follow the request to the state change and identify where the application establishes identity, selects an object, and permits fields.

Our original project service stores a name and an owner. Users may rename their own projects, but must not claim unrelated records or replace ownership. The initial implementation called project.update(request_json). Even a valid read authorization check does not solve mass assignment: a client can supply fields the developer did not intend to make editable.

A small, testable operation contract

The following example runs with standard Python. It demonstrates one operation’s constraints; a real service additionally needs schema validation, transactional updates, and a subject obtained from a verified session.

def rename_project(subject_id, project, patch):
    if project['owner'] != subject_id:
        raise PermissionError('not the project owner')
    if set(patch) != {'name'}:
        raise ValueError('only name may be changed')
    name = patch['name']
    if not isinstance(name, str) or not 1 <= len(name) <= 80:
        raise ValueError('invalid name')
    return {**project, 'name': name}

project = {'id': 42, 'owner': 7, 'name': 'Training'}
renamed = rename_project(7, project, {'name': 'Lab notes'})
assert renamed['owner'] == 7
assert project['name'] == 'Training'
try:
    rename_project(7, project, {'name': 'New', 'owner': 8})
except ValueError:
    print('protected field rejected')
else:
    raise AssertionError('mass assignment was accepted')

Ownership is checked against the original object, and the editable field set is defined by the server. Returning a new object makes state changes easy to observe in this local example. A database implementation must also handle concurrency: ownership may change between a read and an update. Appropriate protection depends on transactions, conditional writes, and the data model rather than the name of an architectural pattern.

Do not accept subject_id from a client request body. Do not treat a frontend validator as sufficient protection. A centralized authorization policy helps only when every handler invokes it with the correct resource. An export or bulk-update endpoint may bypass a well-written check in the main handler.

Exercise: review an actual change

Add a local case for user 8 and demonstrate that the unrelated project remains unchanged. Add an empty name and an unknown field. Draw the PATCH request path through its handler, policy, and storage operation; mark the identity source and atomic update boundary. Identify an alternative operation to inspect: export, bulk renaming, or administrative editing.

Acceptance criteria: protected fields are rejected; failed operations do not mutate the starting state; an unrelated subject is denied; the same rule applies through alternative endpoints. A review comment must explain impact and a concrete validation step rather than simply asking for “more security.”

Work deliverable

Submit the safer operation contract, five negative cases, and a short map of paths that can write data. Compare your reasoning with OWASP Authorization and OWASP ASVS.

Lesson: review the operation’s contract

Read project as a dictionary containing identifier, owner, and name. patch contains submitted changes. set(patch) obtains field names rather than values. Comparing it with {'name'} allows exactly the intended field, preventing simultaneous ownership modification. Name type and length validation protect the input contract; they do not replace authorization to edit the object.

{**project, 'name': name} creates a new dictionary with a replaced name. The original stays unchanged, making failure behavior easier to check. A real application’s database write is a separate step. If another transaction changes ownership after authorization, the result depends on concurrency handling. Review therefore asks which state was checked and which state is written, not merely where an if exists.

Save the example as rename_lab.py and run it with Python 3 or the appropriate Windows launcher. Record actual output and file version. Add a foreign-subject denial using try/except PermissionError, then confirm the original remains unchanged. Add empty, excessive-length, and wrong-type names. Each failure should correspond to the intended condition rather than a malformed test call.

Practice extension: write an actionable comment

“Insecure” is insufficient. Describe the path: a client controls owner, a generic update saves it, and a later request passes the new-owner check. Recommend server-defined editable fields and a test for attempted ownership changes. Identify where the decision applies: main PATCH, bulk operations, and administrative endpoints may have distinct but explicit rules.

For a negative control, remove the field restriction in a separate copy and submit owner. Show which test detects expanded behavior. Use synthetic objects, not real user accounts. The local function does not establish that a production handler gets its subject from a verified session; add that integration-review item.

Separate finding, correction, and evidence in the final review. Bind each finding to operation and version, and each correction to a test. A Russian team can use its normal issue format with owner, deadline, and acceptance conditions. Controller, service, and repository labels do not constitute security by themselves. Another developer should reproduce your observation without calling you; clarify cases and steps before handing over the review.

Try the idea yourself

Where to put a check

Change the conditions and observe this training model. It runs in your browser and does not change your computer.

A team is preparing a release. Enable the independent checks and see what remains unknown.

Observation

Choose conditions above to see an explanation of the result.

Independent exercise · Russian

Оператор издательства корректирует тираж до отправки заказа в типографию. Днём доступен редактор заказа, ночью заказы правит пакетная задача. Оба пути вызывают один репозиторий. В январе 2027 года команда добавляет конкурентное редактирование.

Evidence

Заказ 82 принадлежит филиалу В, находится в состоянии «черновик», имеет версию 6. Экран проверяет филиал и состояние, затем вызывает save(номер, тираж). Пакетная задача вызывает тот же save напрямую. Утверждение заказа также увеличивает версию.

Assignment

Напишите один блокирующий комментарий ревью с предложением общего контракта. Покажите ожидаемый результат, если утверждение успело изменить версию между открытием формы и сохранением.

Compare your reasoning

Обе операции корректировки должны передавать проверенный филиал и ожидаемую версию в общий метод. Менять можно только тираж, если одновременно совпали номер, филиал, версия и состояние черновика. Проверка условий и обновление происходят атомарно. Если уже записана версия 7, изменено ноль строк, тираж сохранён прежним, оператор получает сообщение о необходимости обновить заказ. Отдельный положительный пример должен менять тираж черновика версии 6 ровно один раз.

Personal practice environment

Check an excerpt, find matching lines and compute the SHA-256 of the original text. Temporary data expires after 30 minutes or when you close the environment.