Part II — Intermediate Development · Chapter 8 · Lesson 4 of 6 · 10 min read
Lesson 4: Files, Paths, HTTP, Cryptography, Logging, Testing, and Concurrency
Lesson level: Intermediate
Purpose. Use the standard-library modules that interact with the environment—storage, networks, secrets, observability, verification, and parallel work—without losing least privilege, determinism, bounded resource use, or safe failure behavior.
Learning objectives
By the end of this lesson, you will be able to:
- Separate pure logic from adapters that cross capability boundaries.
- Validate, normalize, and confine file paths before using them.
- Read and write files with explicit size limits and safe replacement patterns.
- Design bounded, validated HTTP interactions with explicit failure handling.
- Use cryptographic facilities for integrity, signing, hashing, and secret handling appropriately.
- Produce structured logs that support diagnosis without leaking sensitive data.
- Write deterministic tests for library-facing code and use controlled concurrency.
4.1 Capability boundaries
Files, paths, HTTP, cryptography, logging, and concurrency are not ordinary computation. They touch resources outside the script’s own values and may require explicit host grants, resource budgets, or deployment policy. A capability may be denied, limited, audited, or unavailable on a particular host.
The recommended structure is a pure core surrounded by narrow adapters. The core accepts and returns portable values. Each adapter owns one capability, validates every input crossing into it, enforces limits, converts low-level failures into stable application outcomes, and releases resources deterministically.
Release note. Function names in examples are illustrative. Verify exact module names, option names, permissions, and failure behavior in the standard-library documentation and manifest for the installed release.
4.2 Files: define the resource contract
Before reading or writing a file, define the purpose, location policy, maximum size, encoding, expected format, and required capability. A file is external data: validate its existence, type, size, content, and format before trusting it.
- Prefer reading a bounded amount of data rather than an unlimited file.
- Decode text with an explicit encoding.
- Parse structured content with the JSON or CSV parser, then validate it.
- Treat missing, unreadable, empty, truncated, and oversized files as distinct cases.
- Close or release handles on every success and failure path.
4.3 Safe writing
Writing partial output over an existing file can corrupt it if an error or interruption occurs. A safer pattern writes a complete temporary file in the permitted directory, verifies it, and then replaces the destination using the platform’s documented atomic or near-atomic operation when available.
Do not write secrets to world-readable locations, include credentials in generated artifacts, or overwrite user data unless the contract explicitly authorizes it. Report the outcome as a stable status without exposing sensitive paths or contents.
4.4 Paths are security-sensitive text
A path string can contain separators, relative segments, links, platform-specific forms, encoded characters, and unexpectedly long components. Use the standard path facilities rather than manual string concatenation or splitting.
- Define an approved base directory.
- Join only validated relative components.
- Normalize the result using the platform-aware path module.
- Confirm that the normalized result remains inside the approved base.
- Check file type, permissions, and link policy as required.
- Return generic errors that do not reveal unrelated directory structure.
Never accept a user-supplied absolute path or parent-directory traversal where only a file name or approved identifier is intended. Prefer opaque identifiers mapped to approved locations by trusted configuration.
4.5 HTTP as an unreliable dependency
A network request can fail because of denied capability, invalid destination, DNS or connection errors, timeout, TLS failure, redirects, error status, oversized responses, malformed content, rate limits, or partial outages. Treat every remote response as untrusted input.
| Control | Purpose |
|---|---|
| Destination allowlist | Prevents requests to unintended hosts or internal services. |
| Timeout and deadline | Bounds waiting and prevents stalled workflows. |
| Response size limit | Protects memory and output budgets. |
| Status handling | Separates success, client error, server error, and rate limiting. |
| Content-type and schema validation | Rejects unexpected or malformed responses. |
| Bounded retries | Avoids amplifying outages. |
4.6 Retries, idempotency, and cancellation
Retry only operations that are safe to repeat or protected by an idempotency mechanism. Use a bounded number of attempts, backoff, and an overall deadline. Honor cancellation so abandoned work stops promptly.
Do not retry validation errors, authorization failures, or malformed requests as though they were transient. Record attempt count and final reason code without including credentials or sensitive payloads.
4.7 Credentials and request construction
Do not place tokens, passwords, or private keys in source code, examples, query strings, or logs. Obtain secrets through approved secret providers or host configuration, scope them narrowly, and redact them before any diagnostic output. Build URLs and query values with the standard encoding facilities instead of string concatenation.
4.8 Cryptography: use the right primitive
Cryptography is not a general-purpose text transformation. Choose a primitive according to the security goal:
| Goal | Appropriate class of tool | Common error |
|---|---|---|
| Detect accidental change | Checksum or hash | Assuming a plain hash proves authenticity. |
| Prove integrity and origin | Digital signature or authenticated code | Verifying only a hash supplied by the same untrusted source. |
| Protect confidentiality | Authenticated encryption | Encrypting without integrity protection. |
| Store passwords | Dedicated password-hashing facility | Using a fast general hash. |
| Generate secrets or tokens | Cryptographically secure randomness | Using ordinary pseudo-random helpers. |
Never invent cryptographic formats or algorithms. Use the standard-library facilities, documented parameters, and project security guidance. Compare secret values with constant-time facilities when provided, and keep keys out of logs, test fixtures, and source control.
4.9 Logging for diagnosis, not disclosure
Logs are part of the system’s security surface. A useful log event is structured, timestamped by a controlled source, associated with a correlation identifier, and limited to the fields needed for diagnosis.
- Use stable event names and reason codes.
- Include levels consistently: error for failed operations, warning for recoverable risk, information for significant state changes, and debug for controlled diagnostics.
- Redact secrets, tokens, personal data, and full request or response bodies.
- Bound message and field sizes.
- Never rely on log text as an application protocol.
- Treat log injection as an input-handling problem and encode user-controlled values appropriately.
When logging is denied, rate-limited, or unavailable, the business result should follow the documented contract rather than failing unpredictably.
4.10 Testing library-facing code
Reliable tests isolate the core from external effects. Use synthetic data, temporary locations created by the test harness, injected clocks, fake transports, and deterministic random seeds. Test both permitted and denied capabilities.
| Area | Representative tests |
|---|---|
| Files | missing, empty, oversized, malformed, unreadable, replaced, and interrupted-write cases |
| Paths | parent traversal, absolute input, separators, long components, link policy, and case differences |
| HTTP | timeout, retry exhaustion, redirect, error status, oversized body, invalid schema, and cancellation |
| Cryptography | valid and tampered input, wrong key, malformed encoding, and expired metadata |
| Logging | redaction, field limits, denied logging, and stable reason codes |
| Concurrency | cancellation, failure propagation, bounded parallelism, and deterministic result ordering |
A test that depends on real external services, the wall clock, or scheduling accidents is a diagnostic experiment, not a dependable regression test.
4.11 Concurrency without chaos
Concurrent work can reduce waiting but increases the number of states to reason about. Start with sequential correctness. Add concurrency only when independent operations are bounded, ordered results are defined, and shared state is minimized.
- Define the maximum number of concurrent tasks.
- Give the whole operation a deadline and propagate cancellation.
- Pass immutable or portable inputs to each task.
- Collect results by explicit identifiers, not completion order.
- Decide whether one failure cancels the group or is collected with the others.
- Release resources in every task path.
- Sort or otherwise normalize output when determinism matters.
Never use concurrency to bypass resource limits. Parallel HTTP requests, file reads, and output generation still consume the same budgets and may need aggregate limits.
4.12 Integrated example: bounded file-and-service enrichment
A utility reads a bounded list of synthetic identifiers from an approved input file, requests metadata for each from an allowlisted service, verifies a response signature, and writes a deterministic report.
- Check that the file, HTTP, cryptography, logging, and concurrency capabilities are available.
- Resolve the input path inside the approved base directory.
- Read the file with a size limit and parse it with the appropriate parser.
- Validate each identifier and cap the number of tasks.
- Run bounded concurrent requests under one deadline.
- Validate status, size, content type, schema, and signature for each response.
- Redact logs and keep secrets out of reports.
- Write the report through a temporary file and controlled replacement.
Invariants. Every input identifier maps to exactly one result or one stable failure; unauthorized paths and destinations are never accessed; no secret appears in output; and the report is deterministic for identical inputs and mocked responses.
4.13 Common mistakes and corrections
| Mistake | Correction |
|---|---|
| Building paths by string concatenation | Use path facilities and confirm confinement to an approved base. |
| Reading an entire unbounded file | Apply size limits and parse incrementally when appropriate. |
| Overwriting output in place | Write a complete temporary result and replace deliberately. |
| Calling any URL supplied by input | Use destination allowlists and validated identifiers. |
| Omitting timeouts | Set per-request and overall deadlines. |
| Retrying every failure | Retry only transient, safe operations with bounds. |
| Using a plain hash as proof of origin | Verify an authenticated signature or code. |
| Logging request bodies or tokens | Log redacted, bounded, structured fields. |
| Testing against live services | Use deterministic fakes and synthetic data. |
| Starting unbounded parallel tasks | Cap concurrency and enforce aggregate budgets. |
| Depending on completion order | Collect and order results by explicit keys. |
4.14 Diagnostic workflow
- Identify the capability or layer: permission, path, file, network, response validation, cryptography, logging, test harness, or concurrency.
- Confirm that the required capability was requested and granted.
- Check resource limits and deadlines.
- Reduce the operation to the smallest synthetic reproduction.
- Distinguish transient from permanent failure.
- Inspect redacted diagnostics rather than raw sensitive data.
- Verify cleanup and cancellation behavior.
- Add a regression test for the failing condition.
4.15 Guided practice
- Design a path policy that accepts a report identifier and returns a file inside an approved reports directory.
- Choose the failure categories for a missing, oversized, malformed, and unreadable configuration file.
- Specify timeout, retry, and response-size rules for a metadata lookup.
- Explain why checksum comparison alone is insufficient when the checksum comes from the same untrusted source as the download.
- Define a redaction policy for a log event containing a request identifier, user label, and bearer token.
- List test cases for an interrupted file replacement.
- Design a bounded concurrent workflow for twenty independent lookups with a concurrency limit of four.
- Explain how deterministic ordering is preserved when tasks finish in different orders.
4.16 Hands-on lab: Build a permission-aware verified fetcher
Scenario. Build a PeaLang utility that reads synthetic resource identifiers from an approved local file, fetches synthetic metadata through an injected transport, verifies each response with a test signature, and writes a deterministic report. Use mocked network responses and generated test keys only; do not use real secrets or live services.
Required behavior
- Declare the capabilities needed for file access, network access, logging, cryptography, and concurrency.
- Confine all input and output paths to approved directories.
- Enforce file-size, identifier-count, response-size, and concurrency limits.
- Validate every identifier and construct each request through approved encoding helpers.
- Apply per-request timeouts and one overall deadline with cancellation.
- Retry only transient failures, using a bounded retry policy.
- Verify response status, content type, schema, and signature.
- Redact every log event and exclude secrets from reports.
- Return one stable result or failure per identifier in deterministic order.
- Write the report through a temporary file and controlled replacement.
Required tests
- valid run with all responses succeeding;
- denied file, network, logging, cryptography, and concurrency capabilities;
- path traversal and absolute-path attempts;
- missing, empty, oversized, and malformed input files;
- timeout, transient error followed by success, and retry exhaustion;
- oversized, malformed, wrong-type, and unsigned responses;
- tampered payload and wrong test key;
- cancellation during concurrent work;
- out-of-order task completion;
- interrupted report writing;
- log redaction and denied logging.
Deliverables
- source, synthetic data, mock transport, and generated test keys;
- a capability and limits matrix;
- boundary contracts for input, response, report, and log events;
- expected and actual results for every test;
- a short threat note covering path, network, secret, and resource risks.
Acceptance criteria
- No operation occurs without its documented capability.
- No path or destination outside policy is accessed.
- Every request, task, and file operation is bounded.
- Every identifier produces exactly one deterministic outcome.
- Unauthenticated or tampered responses are rejected.
- No secret or sensitive payload appears in logs or reports.
- All external effects are replaceable in tests.
4.17 Review questions
- Why should capability-using code be isolated in narrow adapters?
- What checks keep a resolved path inside an approved directory?
- Why is writing a temporary file and replacing the destination safer than in-place overwrite?
- Which controls limit the risk of an HTTP request?
- When is retrying inappropriate?
- Why does a hash alone not prove origin?
- What should a safe log event contain, and what should it omit?
- How do fakes and synthetic data improve tests?
- Why must concurrent results be ordered by explicit keys?
- How can parallel work accidentally bypass resource limits?
4.18 Applied challenge
Extend the fetcher with a resumable batch mode. The utility must record a bounded, redacted checkpoint of completed identifiers, avoid repeating completed work, detect a tampered checkpoint, and produce the same final report whether the run completes once or resumes after an injected failure. Add tests for cancellation, partial writes, duplicate identifiers, stale checkpoints, and out-of-order completion.
Lesson summary
Environment-facing standard-library modules require stronger discipline than pure computation. Files and paths need confinement, bounded reads, and safe replacement. HTTP needs allowlists, deadlines, validation, and careful retries. Cryptography must match the security goal and use approved facilities. Logging should be structured, bounded, and redacted. Tests should isolate external effects with synthetic data and deterministic fakes. Concurrency should be bounded, cancellable, and deterministic in output.
Transition to Lesson 5
The next lesson consolidates these ideas into explicit models for capability permissions and safe usage patterns, including requesting, auditing, denying, and testing permissions.
Lesson status: Ready for review.