PeaBox Lab › PeaLang › Learn › Chapter 8 › Lesson 4

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:

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.

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.

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.

ControlPurpose
Destination allowlistPrevents requests to unintended hosts or internal services.
Timeout and deadlineBounds waiting and prevents stalled workflows.
Response size limitProtects memory and output budgets.
Status handlingSeparates success, client error, server error, and rate limiting.
Content-type and schema validationRejects unexpected or malformed responses.
Bounded retriesAvoids 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:

GoalAppropriate class of toolCommon error
Detect accidental changeChecksum or hashAssuming a plain hash proves authenticity.
Prove integrity and originDigital signature or authenticated codeVerifying only a hash supplied by the same untrusted source.
Protect confidentialityAuthenticated encryptionEncrypting without integrity protection.
Store passwordsDedicated password-hashing facilityUsing a fast general hash.
Generate secrets or tokensCryptographically secure randomnessUsing 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.

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.

AreaRepresentative tests
Filesmissing, empty, oversized, malformed, unreadable, replaced, and interrupted-write cases
Pathsparent traversal, absolute input, separators, long components, link policy, and case differences
HTTPtimeout, retry exhaustion, redirect, error status, oversized body, invalid schema, and cancellation
Cryptographyvalid and tampered input, wrong key, malformed encoding, and expired metadata
Loggingredaction, field limits, denied logging, and stable reason codes
Concurrencycancellation, 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.

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.

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

MistakeCorrection
Building paths by string concatenationUse path facilities and confirm confinement to an approved base.
Reading an entire unbounded fileApply size limits and parse incrementally when appropriate.
Overwriting output in placeWrite a complete temporary result and replace deliberately.
Calling any URL supplied by inputUse destination allowlists and validated identifiers.
Omitting timeoutsSet per-request and overall deadlines.
Retrying every failureRetry only transient, safe operations with bounds.
Using a plain hash as proof of originVerify an authenticated signature or code.
Logging request bodies or tokensLog redacted, bounded, structured fields.
Testing against live servicesUse deterministic fakes and synthetic data.
Starting unbounded parallel tasksCap concurrency and enforce aggregate budgets.
Depending on completion orderCollect and order results by explicit keys.

4.14 Diagnostic workflow

4.15 Guided practice

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

Required tests

Deliverables

Acceptance criteria

4.17 Review questions

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.

← Previous Next →