Foundations to FrontierPart IV: Algorithms and systemsBezhig

C17: Security boundaries, usable interfaces, and professional responsibility

5 exercises, each with a complete solution. 1 figure. 1 code listing.

On this page
  1. A. Prerequisites and observable goals
  2. B. The central question: which assumptions may an adversary violate?
  3. C. Input validation and output encoding solve different problems
  4. D. Use established security mechanisms without inventing cryptography
  5. E. Human factors are part of correctness
  6. F. Worked authorization boundary
  7. G. Independent practice
  8. H. Complete solutions: C17
  9. I. Retention and readiness

A. Prerequisites and observable goals#

Before

C03 ownership; C11 data constraints; C12 protocols; C14 testing and communication.

After

Construct a small threat model, distinguish authentication from authorization, apply context-appropriate input/output handling, and document privacy, accessibility, and operational limits.

Level: Degree core; defensive and authorized work only. The lab is not a secure production service.

B. The central question: which assumptions may an adversary violate?#

A threat model identifies assets, actors, entry points, trust boundaries, and possible failures or abuse. For a game account service, assets include account control, inventory integrity, private messages, and service availability. Inputs may come from modified clients, stale sessions, compromised dependencies, or accidental operator mistakes. A friendly user interface is not a security boundary; the server must validate the action independently.

Least privilege gives a component only the access needed for its job. A statistics exporter does not need permission to change inventory. A deployment token should not be reused as a database administrator password. Separating privileges limits the consequences of a defect, though it does not prevent every compromise. Threat modeling should include recovery: how are credentials revoked, data restored, and affected users informed?

Authentication establishes an identity under some mechanism. Authorization decides what that identity may do to a particular resource. A valid login does not imply permission to read another person’s records. The lab’s role is assumed to come from trusted server-side state, not a client-supplied admin=true field. Without that assumption, the simple authorization check has no meaningful protection.

Where trust begins. Everything left of the dashed line can be changed by whoever controls the client, so the server repeats every check itself: who is asking, whether they may do this, and whether the request is well-formed. Only then does it act. Section F works one such boundary.

C. Input validation and output encoding solve different problems#

Validation checks whether an input belongs to the allowed domain: a quantity is an integer in a range, a body is small enough, or an identifier names a permitted resource. Parsing turns bytes into a structured representation. Neither automatically makes that representation safe in every later context.

Parameterized SQL separates query structure from values. A string parameter remains data rather than being pasted into SQL syntax. Escaping HTML text prevents characters such as < and & from being interpreted as markup in that context. HTML text escaping is not SQL parameterization, JavaScript string encoding, or URL validation. Choose the defense for the actual interpretation boundary instead of using one generic “sanitize” function everywhere. [OWASP]

Memory safety concerns whether accesses respect allocation bounds, lifetimes, and valid ownership. C++ RAII and standard containers reduce manual resource mistakes, but do not make every pointer, iterator, or concurrent access safe. A bounds-checked access is useful only if the object’s lifetime is still valid. Compiler diagnostics and sanitizers find classes of errors on analyzed or executed paths; passing them is not a complete exploit-resistance proof.

D. Use established security mechanisms without inventing cryptography#

Encryption, signatures, password hashing, and random-token generation have different purposes. Use maintained cryptographic libraries and appropriate high-level constructions; do not invent a cipher or substitute a general-purpose hash for password storage. Correct algorithms can still be undermined by key exposure, nonce misuse, insecure randomness, or a mistaken trust model. This book deliberately does not implement a custom cryptographic primitive or a production login flow.

Secrets should not be committed to source control, embedded in a mobile client as if they were confidential, or printed in logs. Use environment-appropriate secret management and separate development from production credentials. Rotating a leaked secret matters even after deleting its current file because copies may remain in history or logs. Dependency review includes provenance, update policy, transitive components, and license obligations; a package’s popularity is not a security guarantee.

A defensive test should remain on owned or explicitly authorized systems and use synthetic data. Tests of malformed inputs, permission boundaries, and rate limits are valuable without targeting strangers’ services. J03 binds to loopback and uses a temporary synthetic inventory precisely to keep its exercises bounded.

E. Human factors are part of correctness#

An interface can prevent or invite mistakes. A destructive action should identify the affected resource and make consequences clear. Error messages should say what the user can do next without exposing secrets or internal stack traces. A disabled-looking button that still activates is a functional defect, not merely visual polish. In engine tools, distinguish saving an asset from publishing a production change and make undo boundaries explicit.

Accessibility includes keyboard operation, visible focus, programmatic labels, alternatives to color-only distinctions, readable contrast, and understandable status messages. These help users with different abilities and input devices and also improve debugging and automation. WCAG 2.2 is a public technical reference; this small lab does not perform a complete conformance audit. A screen reader label and a successful keyboard test are useful evidence, not a blanket accessibility certification. [WCAG]

Privacy requires deciding which data is necessary, how long it is retained, who can access it, and how it is deleted or corrected. Collecting everything “for future analytics” creates risks without a defined benefit. Synthetic fixtures keep this book’s labs reproducible without exposing real customers. Logs and model-training datasets need the same data-governance attention as database tables.

Professional responsibility includes reporting uncertainty, documenting known limitations, and not overstating verification. A benchmark from one machine is not a universal speed claim. An educational controller is not validated vehicle software. A license file grants permissions under conditions; inspect the actual license for code and assets you use and seek qualified advice for consequential legal questions. This chapter teaches an engineering review habit, not legal advice.

F. Worked authorization boundary#

Policy: an authenticated member may read their own note; an authenticated administrator may read any note; unknown roles are denied. A missing or empty actor identity is unauthenticated. The note owner and actor are compared as canonical server-side identifiers. A role outside the two allowed values is rejected rather than treated as an administrator by default.

For actor ada, owner ada, role member, allow. For actor ben, the same owner, and role member, deny. For actor ben with trusted role admin, allow. For an absent actor with role admin, deny: a role string alone is not an authenticated identity. After authorization, encode note text for an HTML paragraph. The encoded display must not become executable markup.

The implementation does not manage sessions, passwords, transport security, audit retention, multi-tenant administration, or revocation. Those nonrequirements prevent confusing a policy-function test with a complete identity system.

G. Independent practice#

F foundation C standard course work T transfer S optional stretch L runnable lab or project. Attempt the complete set before opening its solutions.

C17.01FSolution

Explain the difference between proving a user is logged in and proving they may modify a particular inventory record. Give one server-side condition needed for the second decision.

C17.02CSolution

A developer concatenates a display name into an SQL query and later places that name into an HTML page. Identify the appropriate separate defense at each boundary. Why is one generic string replacement inadequate?

C17.03CSolution

Write a small threat model for a CSV upload tool: name two assets, two untrusted-input risks, and two concrete controls. Keep the test plan local and use no real personal data.

C17.04TSolution

A delete button is identified only by a red icon, has no keyboard focus, and shows “error” after a failed operation. Propose a more usable and accessible interaction, and state what evidence would still be needed before claiming broad accessibility compliance.

C17.05LabSolution

Implement starters/security_lab.py. Enforce the stated member/administrator policy with deny-by-default behavior and escape note text for an HTML paragraph only after authorization. Test unauthenticated users, unknown roles, cross-owner access, and markup-shaped input. State the trust assumptions and excluded production responsibilities.

Optional small hints

For C17.02, ask which interpreter consumes the string next. For C17.05, a trusted role is an input assumption; accepting a caller’s self-declared role is not authentication.

H. Complete solutions: C17#

Compare the first step where your work differs. A corrected answer is not yet an independent success.

C17.01Show solution

Identity and permission answer different questions

A login mechanism establishes an identity. Modifying an inventory record also requires a policy tying that identity to the record or to an authorized administrative action. A server might require that the authenticated account owns the character and that the requested change follows a valid game transaction. Trusting a client-supplied account identifier without checking ownership bypasses this boundary. Even the owner should not be allowed to invent arbitrary inventory quantities when the game requires server-authoritative state changes.

Back to C17.01
C17.02Show solution

Preserve structure at each interpretation boundary

Use bound parameters for SQL values so the database receives query syntax separately from the display name. When rendering into HTML text, use an HTML text encoder such as the standard library’s escaping function. SQL and HTML have different grammars; replacing a quote or deleting a semicolon cannot establish safety in both. Other contexts, such as JavaScript source or a URL attribute, require their own safe construction rules. Validation of acceptable names may supplement these measures but does not replace context-appropriate handling.

Back to C17.02
C17.03Show solution

A bounded defensive model

Assets can be service availability and integrity of computed reports. Risks include an oversized upload exhausting memory and malformed numeric values contaminating statistics or crashing an unhandled path. Controls include a byte/row limit enforced before unbounded accumulation and strict field parsing with finite-value checks and clear error handling. Tests use generated files near the size limit, a wrong header, NaN, and a negative latency. A local temporary directory prevents touching production data. Additional concerns such as spreadsheet-formula interpretation matter only if the tool later exports to a context that executes such formulas; document that boundary rather than assuming CSV is universally inert.

Back to C17.03
C17.04Show solution

Make action, state, and recovery understandable

Give the control a visible text label and an accessible name, support keyboard focus and activation, and do not rely on red alone to communicate danger. Identify the item to be deleted and offer an appropriate confirmation or undo mechanism. On failure, preserve the user’s context and explain a safe next action, such as retrying after connectivity returns, without claiming deletion succeeded. Test keyboard operation, focus order, assistive-technology output, contrast, and status announcements across relevant screens and devices. A local redesign does not establish conformance of the entire application to all applicable criteria.

Back to C17.04
C17.05Show solution

Complete policy and display example

The reference denies missing identities and unknown roles before checking ownership. Administrator access assumes the role was established by trusted server logic. The renderer uses HTML escaping only for text placed inside a paragraph; it is not a general sanitizer or a secure authentication framework.

code/solutions/security_lab.pyPython
"""C17.05: authorization policy and escaped display, not authentication."""
from html import escape

def may_read(actor: str | None, owner: str, role: str) -> bool:
    if actor is None or not actor:
        return False
    if role not in {"member", "admin"}:
        return False
    return role == "admin" or actor == owner

def render_note(actor: str | None, owner: str, role: str, text: str) -> str:
    if not may_read(actor, owner, role):
        raise PermissionError("access denied")
    # html.escape is for HTML text context, not JavaScript or SQL contexts.
    return "<p>" + escape(text, quote=True) + "</p>"

if __name__ == "__main__":
    print(render_note("learner", "learner", "member", "x < y"))
Back to C17.05

I. Retention and readiness#

Retrieve C03 lifetimes, C11 parameters and constraints, and C14 evidence-based claims. Advance when you can identify the trust boundary in a code review and distinguish a tested policy function from a secure deployed system. Continue with threat-model reviews and accessibility testing on an isolated development copy of a project, never by changing production as a classroom exercise.