16 KiB
Full Codebase Cleanup And Hardening Plan
This document is a decision-complete implementation plan for the current full-codebase audit findings. It is a planning document only. Implementation should proceed in stages and should not change unrelated behavior.
The goal is to polish and harden the public and internal code paths without expanding Scriptorium's scope. Keep the existing package boundaries unless a stage explicitly calls for a helper extraction.
Guiding Decisions
- Treat configured
fs.FSroots as real containment boundaries for public source options. - Keep local directory-backed CLI behavior compatible unless this plan explicitly names a change.
- Keep HTTP
serveminimal, but safe by default against accidental large request, file, and response bodies. - Do not add HTTP authentication in this cleanup pass.
- Do not add new dependencies.
- Document only implemented behavior outside
docs/roadmap/.
Stage 1: Enforce Source-Root Containment For fs.FS Prompt And Schema Sources
Problem:
Public source options such as WithPromptFS(fsys, root) and WithSchemaFS(fsys, root) describe root as the source boundary, but prompt content_file and schema path resolution can clean .. paths above that root when the supplied fs.FS is broader than the configured root.
Decision:
For public fs.FS source options, the configured root is a containment boundary. Prompt content_file paths and schema paths must resolve inside that root. Absolute paths and relative traversal that escape the root are invalid.
Implementation:
- Add a small shared internal helper for
fs.FSpath resolution.- Prefer
internal/filecatalogif the helper naturally belongs with existing clean/display path utilities. - Inputs should include a source root and a user path.
- It should trim whitespace, clean slash paths with
path.Clean, reject empty paths where the caller requires a file, reject absolute paths, and reject any path whose clean form escapes the clean root. - Use path-component checks, not string-prefix checks alone.
- Return both the resolved
fs.FSpath and a display path when useful for errors.
- Prefer
- Update
internal/promptdeffsRepositorycontent-file loading.content_file: ./local.tmplbeside the prompt should continue to work.- Nested prompt files should keep the existing relative-to-prompt-file behavior.
content_filevalues that escape the configuredWithPromptFSroot should return a prompt-load error.
- Update
internal/validateFSValidatorschema resolution.WithSchemaFS(fsys, root)should allow schema paths insideroot.WithSchemaFile(path)should keep the existing single-file behavior: promptschema_pathmust match the selected file's base name.- Schema paths that escape the configured root should return validation/schema-load errors.
- Preserve directory-backed compatibility unless a failing test reveals an inconsistency that must be fixed.
WithPromptFile(path)should continue resolvingcontent_filevalues relative to the selected prompt file's directory.Config.SchemaDir/ CLI--schema-dirshould keep documented behavior, including absoluteschema_pathsupport, because these are operator-controlled local filesystem paths.
Tests:
- Add
internal/promptdeftests forfs.FScontent_filetraversal:- sibling file inside root succeeds;
- nested file inside root succeeds;
../outside.tmplfrom a prompt under the root is rejected;- absolute-style
/outside.tmplis rejected.
- Add public package tests through
WithPromptFSproving escapedcontent_filereturnsErrPromptLoad. - Add
internal/validatetests forWithSchemaFStraversal:- schema inside root succeeds;
../outside.schema.jsonis rejected;- absolute-style paths are rejected.
- Keep existing
WithSchemaFiletests passing.
Documentation:
- Update
docs/consumers/pkg-scriptorium.mdto state thatWithPromptFSandWithSchemaFSroots are containment boundaries. - Update
docs/config.mdonly if directory-backed behavior changes. Otherwise leave its local-directory schema-path behavior intact. - Update
docs/internal/adapters.mdif shared source-resolution behavior is documented there.
Stage 2: Add HTTP Request, Artifact, And Response Size Limits
Problem:
HTTP serve decodes request bodies directly from r.Body, reads file artifacts fully into memory, and serializes generated artifact bodies fully into the response. This is acceptable for trusted small local use, but it is not hardened against accidental or hostile large inputs.
Decision:
Add configurable HTTP size limits with conservative defaults. Limits apply only to HTTP serve; CLI run and render keep existing direct filesystem behavior.
Default limits:
server.max_request_bytes: 16 MiB.server.max_artifact_bytes: 16 MiB.server.max_response_bytes: 16 MiB.
Use 0 to disable a specific limit only where this is consistent with existing config style. Negative values are invalid config.
Implementation:
- Add default constants in
internal/defaults. - Extend app config in
internal/config.- Add
server.max_request_bytes. - Add
server.max_artifact_bytes. - Add
server.max_response_bytes. - Apply built-in defaults, config-file values, and CLI overrides according to existing precedence.
- Reject negative values.
- Add
- Add
serveCLI overrides.--max-request-bytes--max-artifact-bytes--max-response-bytes- Keep these flags scoped to
serve.
- Extend HTTP handler construction.
- Add
httpadapter.HandlerOptionswith request and response limit fields. - Keep
httpadapter.NewHandler(runner)as a default constructor for existing tests and callers. - Add
httpadapter.NewHandlerWithOptions(runner, options)forservewiring. NewHandler(runner)should apply built-in defaults.NewHandlerWithOptions(runner, options)should use the supplied values exactly, so0means disabled after config validation.
- Add
- Limit request decoding.
- Wrap
r.Bodywithhttp.MaxBytesReaderwhenmax_request_bytes > 0. - Return
413 request_too_largewhen decoding fails due to size. - Continue returning
400 invalid_jsonfor malformed JSON. - Ensure the decoder rejects trailing JSON tokens if it does not already.
- Wrap
- Limit HTTP file artifact reads.
- Add a max-bytes option to the restricted HTTP artifact reader.
- Use
os.Open,Stat, andio.LimitReaderor equivalent instead of unboundedos.ReadFilefor restricted HTTP file reads. - If a file exceeds the configured limit, return a specific artifact error that maps to
413 artifact_too_large. - Keep inline artifact bodies covered by the request-body limit.
- Limit HTTP response artifact bodies.
- Build the response DTO, marshal it to JSON bytes, and compare the final encoded response size against
max_response_byteswhen the limit is positive. - Return
413 response_too_largewhen the encoded response exceeds the configured limit. - Do not truncate successful artifacts silently.
- Apply the same encoded-response check when
include_raw_outputis true.
- Build the response DTO, marshal it to JSON bytes, and compare the final encoded response size against
Tests:
- Config tests:
- defaults are applied;
- config file values load;
- CLI overrides win;
- negative values are rejected.
- CLI tests:
serveparses the three flags;runandrenderdo not gain these flags.
- HTTP tests:
- oversized request body returns
413 request_too_large; - malformed JSON below the limit still returns
400 invalid_json; - successful request below the limit still works;
- oversized generated artifact returns the configured too-large error;
include_raw_outputdoes not bypass response limits.
- oversized request body returns
- Artifact tests:
- restricted file reader accepts files at or below the limit;
- restricted file reader rejects files above the limit;
- unlimited mode with
0keeps existing behavior.
Documentation:
- Update
docs/config.mdwith the new server limit fields and defaults. - Update
docs/cli.mdwith the newserveflags. - Update
docs/integrations/http-api.mdwith413errors. - Update
docs/operations.mdwith sizing guidance. - Update
docs/troubleshooting.mdwith common size-limit failures. - Update
docs/internal/adapters.mdwith the HTTP limit boundary.
Stage 3: Harden OpenAICompatibleProfile ExtraParams Copying
Problem:
OpenAICompatibleProfile currently deep-copies ExtraParams through the general internal copy helper. Cyclic caller-provided maps can recurse indefinitely before WithProfiles can validate and return ErrInvalidConfig.
Decision:
OpenAICompatibleProfile is a convenience constructor, not a validator. It must not recursively walk caller-provided ExtraParams. Validation and safe deep copying belong in WithProfiles through the existing public JSON validation path.
Implementation:
- Change
OpenAICompatibleProfileto use a shallow map copy forExtraParams.- Copy only the top-level
map[string]any. - Do not recursively copy nested values.
- Do not call
copyAnyMapfrom this constructor.
- Copy only the top-level
- Keep
WithProfilesvalidation and deep-copy behavior unchanged.- Unsupported values, non-finite numbers, non-string map keys, and cycles should still return
ErrInvalidConfig.
- Unsupported values, non-finite numbers, non-string map keys, and cycles should still return
- Review
copyAnyMapcall sites.- Keep it for trusted internal-to-public conversions where values come from already-decoded JSON-like data.
- Do not use it for untrusted public caller input before validation.
- Add a short comment near the constructor if needed to clarify that recursive validation is intentionally deferred.
Tests:
- Add a public package test where
OpenAICompatibleProfilereceives cyclicExtraParams.- The constructor must return promptly.
NewEngine(..., WithProfiles(profile))must returnErrInvalidConfig.
- Add a test proving non-cyclic nested
ExtraParamsstill work throughWithProfiles. - Keep existing mutation-isolation tests passing.
Documentation:
- No user-facing behavior change is required if existing docs already state that
WithProfilesvalidatesExtraParams. - Update docs only if constructor behavior is currently described as validating or deep-copying recursively.
Stage 4: Redact Provider Non-2xx Response Bodies From Default Errors
Problem:
The OpenAI-compatible client includes a trimmed provider response body snippet in ErrUnexpectedStatus. CLI and library callers may log this error. Provider error bodies can include prompt fragments, schema details, request IDs, or other sensitive operational data.
Decision:
Default errors should include the provider status code but not the response body. Do not add a debug mode in this pass unless an existing debug/logging surface already supports it.
Implementation:
- Change the non-2xx error returned by
internal/llm.OpenAICompatibleClient.- Keep wrapping
ErrUnexpectedStatus. - Include
status=<code>. - Do not include response body text.
- Keep wrapping
- Drain and close the response body safely enough for normal HTTP client reuse.
- It is acceptable to read and discard a small bounded amount if needed.
- Do not store or return the discarded content.
- Review tests that assert the old body-snippet behavior and update them.
- Review CLI, HTTP, and public package error mapping.
- HTTP should remain generic and not leak provider details.
- CLI/library errors should retain enough status context to diagnose provider failures.
Tests:
- Update
internal/llmnon-2xx tests:errors.Is(err, ErrUnexpectedStatus)remains true;- the status code appears in the error string;
- the provider response body does not appear in the error string.
- Add a regression test with a body containing distinctive sensitive-looking text and assert it is absent.
Documentation:
- Update
docs/integrations/openai-compatible-chat.mdto remove the claim thatErrUnexpectedStatusincludes a response body snippet. - Update troubleshooting docs only if they currently instruct users to inspect provider body snippets.
Stage 5: Clarify Artifact-Root Symlink Semantics
Problem:
The restricted HTTP artifact reader uses lexical path containment before reading the file. Symlinks inside the artifact root are followed by the operating system. This is documented, but the phrase "must stay inside the root" can be overread as a strict realpath guarantee.
Decision:
Keep symlink-following behavior for this cleanup pass, but make the code and docs explicit that containment is lexical and relies on the artifact root not being writable by untrusted users. This avoids a potentially breaking change for deployments that intentionally use symlinks.
Implementation:
- Rename or comment the restricted reader's path-resolution helper to make the lexical nature clear.
- Add tests documenting current symlink behavior where the platform supports symlinks.
- A symlink inside the root to a file outside the root is followed.
- The test should skip cleanly if symlink creation is unavailable.
- Keep traversal rejection tests for
..and absolute paths outside the root. - Do not introduce
filepath.EvalSymlinksin this pass.
Documentation:
- Update
docs/config.md,docs/operations.md,docs/integrations/http-api.md, anddocs/internal/adapters.mdto say:- lexical traversal outside the root is rejected;
- symlinks inside the root are followed;
- the artifact root must not be writable by untrusted users.
- Avoid wording that implies strict realpath containment unless the implementation changes to enforce it.
Future option:
If strict filesystem containment becomes required, add an opt-in or replacement mode that resolves both the configured root and requested file with filepath.EvalSymlinks before reading, rejects symlink escapes, and documents any compatibility impact.
Stage 6: Align CLI Help And Documentation
Problem:
The serve usage text omits --artifact-root, even though the flag exists. New limit flags from Stage 2 also need to appear consistently in CLI help and docs.
Decision:
Keep CLI help concise but complete for supported flags.
Implementation:
- Update
printUsageininternal/adapter/cli.- Include
--artifact-root DIRin theserveusage line. - Include the new size-limit flags from Stage 2.
- Keep the line readable; splitting long usage text into multiple lines is acceptable if tests are updated.
- Include
- Update CLI tests that assert usage output.
- Confirm
docs/cli.mdmatches actual flags.
Tests:
- Add or update CLI usage tests to assert that
servehelp mentions:--artifact-root;--max-request-bytes;--max-artifact-bytes;--max-response-bytes.
Documentation:
- Update
docs/cli.mdand any command examples affected by line wrapping or flag additions.
Stage 7: Final Verification
Run the full verification set after all stages:
go test ./...
go vet ./...
go run ./examples/go-library/prepare
go run ./cmd/scriptorium render \
--config ./examples/config.yml \
--prompt generic.markdown_summary \
--input transcript=./examples/fixtures/transcript.md \
--input glossary=./examples/fixtures/glossary.yml \
--format json
Also run targeted packages while implementing each stage:
go test ./internal/promptdef ./internal/validate ./internal/filecatalog
go test ./internal/artifact ./internal/adapter/http ./internal/adapter/cli ./internal/config
go test .
Non-Goals
- Do not collapse internal packages merely to reduce package count.
- Do not add HTTP authentication or authorization.
- Do not remove HTTP file inputs.
- Do not change public request/result type names or method signatures.
- Do not change CLI
runorrenderlocal file-input behavior. - Do not silently truncate request, artifact, provider, or response bodies.
- Do not accept raw API keys through config files, profile files, CLI flags, or HTTP payloads.
Assumptions
- Public
fs.FSroots are intended to be narrower than the supplied filesystem and should therefore be enforced. - The initial HTTP size-limit defaults are intentionally conservative and can be tuned by operators.
- Provider response-body diagnostics are less important than safe default error handling.
- Symlink compatibility is more important than strict realpath containment for the immediate cleanup pass, provided documentation is explicit.