packages feed

figment 0.2.0.0 → 0.3.0.0

raw patch · 42 files changed

+1517/−1149 lines, 42 filesdep ~basedep ~directoryPVP ok

version bump matches the API change (PVP)

Dependency ranges changed: base, directory

API changes (from Hackage documentation)

+ Figment: Secret :: a -> Secret a
+ Figment: TooManyBytes :: !Int -> ErrorKind
+ Figment: [revealSecret] :: Secret a -> a
+ Figment: defaultMaxBytes :: Int
+ Figment: maxBytes :: Limits -> Int
+ Figment: newtype Secret a
+ Figment: withMaxBytes :: Int -> Limits -> Either ConfigError Limits
+ Figment.Decode: Secret :: a -> Secret a
+ Figment.Decode: [revealSecret] :: Secret a -> a
+ Figment.Decode: instance Figment.Decode.FromConfig a => Figment.Decode.FromConfig (Figment.Decode.Secret a)
+ Figment.Decode: instance Figment.Decode.FromConfigKey GHC.Num.Integer.Integer
+ Figment.Decode: instance Figment.Decode.FromConfigKey GHC.Types.Int
+ Figment.Decode: instance GHC.Classes.Eq a => GHC.Classes.Eq (Figment.Decode.Secret a)
+ Figment.Decode: instance GHC.Internal.Show.Show (Figment.Decode.Secret a)
+ Figment.Decode: newtype Secret a
+ Figment.Decode: suggestAt :: Int -> Text -> [Text] -> [Text]
+ Figment.Error: TooManyBytes :: !Int -> ErrorKind
+ Figment.Limits: defaultMaxBytes :: Int
+ Figment.Limits: maxBytes :: Limits -> Int
+ Figment.Limits: withMaxBytes :: Int -> Limits -> Either ConfigError Limits

Files

+ ADRs/026-jail-unsafeperformio.md view
@@ -0,0 +1,25 @@+# ADR 026 — The one `unsafePerformIO`: the jail's process-wide lock++Status: Accepted | Rule relaxed: ENGINEERING_STANDARD §1.7 (no `unsafePerformIO`)++## Context+`Figment.Jail.withJail` changes the process working directory and+environment, which are global. Concurrent jails would corrupt each other, so+they must be serialised by a lock that exists once per process.++## Decision+`Figment.Jail` defines its lock with the standard top-level+`unsafePerformIO (newMVar ())` and a `NOINLINE` pragma. It is the only use in+the library (`.hlint.yaml` allows it in that module and nowhere else).++## Alternatives tried+- Passing a lock in as an argument: every test would have to share one value,+  which defeats the purpose of a drop-in `withJail`.+- `System.IO.Unsafe` free designs (file locks): heavier, platform dependent,+  and no more correct within one process.++## Consequences+The idiom is safe because the initialiser has no inputs and `NOINLINE`+guarantees one instance. The cleaner fix is to move `Jail` out of the main+library into a test-support sublibrary, where the exception would no longer+reach production users; that is tracked as a follow-up.
CHANGELOG.md view
@@ -1,5 +1,66 @@ # Changelog +## 0.3.0.0 — 2026-11-28++Hardening release. It follows 0.2.0.0 and contains everything merged after+the `v0.2.0.0` tag. It is a major version under the PVP because the public+`ErrorKind` type gained a constructor (`TooManyBytes`), which breaks+exhaustive pattern matches in user code.++### Hardening (source)++- Error rendering now escapes control, bidirectional and zero-width characters+  in every message, hint and type description, not just keys and file names.+- A leading byte-order mark is ignored in JSON and TOML input.+- TOML: the linear pre-scan also counts structural tokens and rejects a+  document with more than `5 * maxNodes` of them as `TooManyNodes`, before+  toml-parser builds its whole syntax tree.++### Fixed (Windows)++- `Figment.Jail`: a rooted path such as `/x` (not "absolute" on Windows, but+  one that makes `</>` discard the jail directory) is now refused.++### Added+- `Secret a`: a wrapper whose decode errors never quote the value and whose+  `Show` prints `Secret <redacted>`. Use it for passwords and tokens.+- `FromConfigKey` instances for `Int` and `Integer`, so `Map Int a` decodes.+- Environment and CLI values: structured values obey `maxBytes` and+  `maxNodes`; duplicate keys in an inline table are reported; `\uXXXX`+  escapes decode and unknown escapes are no longer silently dropped.+- Date-time decoders accept a space between date and time (RFC 3339).+- The CLI provider names options as mapped by a custom `keyMap`.+- `base` upper bound widened to `< 4.23` (GHC 9.14). Dependencies may not+  support GHC 9.14 yet; it is tested in CI as an experimental job only.+- `TooManyBytes` error kind and a per-source size limit: `maxBytes`,+  `withMaxBytes`, `defaultMaxBytes` (32 MiB by default). Files larger than+  the limit are never opened for reading; other sources are checked before+  parsing.+- A linear pre-scan that rejects deeply bracketed TOML before the parser+  builds it.+- Error text escaping: control characters, line and paragraph separators+  and bidirectional overrides in keys, file names and messages can no+  longer forge report lines; reports show at most 100 errors.+- Handle guards in `Figment.Jail`: nested jails, use after the jail ends+  and paths that escape the jail are errors instead of hangs or silent+  misbehaviour.+- `SECURITY.md`, `CONTRIBUTING.md`, issue and pull request templates,+  `.hlint.yaml`, and ADR 026 (the `unsafePerformIO` in `Figment.Jail`).++### Changed+- `load` now evaluates each provider's result inside its exception+  handler, so an exception hidden in a lazily built value becomes an+  `IoError` instead of escaping later.+- A YAML mapping may contain at most one merge key (`<<`); a second is a+  `DuplicateKey` error.+- YAML parsing gives up as soon as the event stream exceeds the node or+  depth limit instead of buffering all of it.+- Unreadable locations during the upward search for a file are reported+  instead of being treated as an absent file.+- Suggestions for unknown fields are computed with bounded work.+- `ENGINEERING_STANDARD.md` is no longer shipped in the source+  distribution (it remains in the repository).+ ## 0.2.0.0 — 2026-10-22  A breaking redesign, following a forensic audit of 0.1
− ENGINEERING_STANDARD.md
@@ -1,856 +0,0 @@-# The Haskell Engineering Standard--**Status: binding.** This document is the constitution for any Haskell-codebase it governs — read and applied *before* the first module is-written, not retrofitted afterward. It applies equally to AI-authored and-human-authored code, and to AI or human review of either. Where a request-conflicts with this document, follow this document and say so explicitly.--**Precedence when principles conflict**, highest first:-1. Correctness / totality — a fast or elegant function that can go wrong-   silently loses to a slower one that can't go wrong at all.-2. Safety of representation — illegal states must stay unrepresentable-   even at the cost of a more verbose type.-3. Architectural clarity — a boundary that makes the system easier to-   reason about beats a shortcut that makes today's diff smaller.-4. Performance — addressed deliberately, with evidence, never guessed at-   the expense of 1–3.-5. Brevity — the last thing optimized for, never the first.-------## Part 0 — Foundational Design Principles, in Haskell Terms--Classic software-design principles are usually stated in OOP vocabulary.-They still hold; they just cash out differently without classes and-inheritance. State them this way so there's no ambiguity about what they-mean here.--### 0.1 Single Responsibility Principle-One module, one reason to change. A module that both parses a format and-knows how to render one has two responsibilities wearing one name; split-it. The test: describe the module's job in one sentence with no "and."--### 0.2 Open/Closed Principle-A system should be open to extension without modifying proven code. In-Haskell this is a genuine design choice with two valid, opposite-shaped-answers — pick the right one deliberately, per extension axis:-- **Closed sum + exhaustive pattern match**, when the set of cases is-  owned and finite (e.g. the source formats *this* project supports).-  Adding a case is a compile error at every site that needs updating —-  extension is "open" in the sense that the compiler *guides* the change,-  even though the type itself is closed.-- **Typeclass or record-of-functions ("Handle") boundary**, when the set-  of cases is genuinely open to third parties (e.g. a plugin renderer a-  downstream consumer supplies). Extension happens with zero edits to-  existing code.--Never blend the two on the same axis of variation — decide, per-extension point, which discipline governs it, and document the choice.--### 0.3 Liskov Substitution — restated as typeclass law-abidance-Any two instances of the same typeclass must satisfy the same laws.-A `Monoid` instance whose `mappend` isn't associative, an `Eq` instance-that isn't reflexive, an `Ord` instance inconsistent with its `Eq` — these-are the Haskell equivalent of a subtype that violates its supertype's-contract. State each instance's laws in a comment and, wherever practical,-test them with a law-checking library (`hspec-hedgehog`, `checkers`).--### 0.4 Interface Segregation-Typeclasses (and Handle records) should be as small as the caller actually-needs. A function should be constrained by the narrowest capability it-uses — `(Monad m) => ...` rather than `(MonadIO m, MonadState S m,-MonadReader R m) => ...` when only `Monad` is actually exercised. A fat-typeclass or a fat Handle forces every implementation to satisfy-capabilities most call sites never touch.--### 0.5 Dependency Inversion — the Handle pattern-Haskell has no interfaces in the OOP sense; the idiomatic equivalent of-"depend on abstractions, not concretions" is passing a small record of-functions (a **Handle**) into pure or effect-polymorphic code, rather than-having that code import a concrete `IO`-performing module directly.--```haskell--- | The core logic depends on this shape, not on any concrete backend.-data StorageHandle m = StorageHandle-  { loadDocument :: DocId -> m (Either MirrorError Document)-  , saveDocument :: DocId -> Document -> m (Either MirrorError ())-  }---- | Pure with respect to *how* storage happens — swap the Handle for--- tests (an in-memory Map) without touching this function.-republish :: Monad m => StorageHandle m -> DocId -> m (Either MirrorError ())-```-This is what makes core logic testable without spinning up real I/O, and-it is preferred over a typeclass when only one concrete instance is ever-needed per call site (a Handle is simpler; a typeclass is for genuine-ad hoc polymorphism across many types).--### 0.6 DRY — with its correct limit stated explicitly-Duplication of *knowledge* (the same invariant, checked two different-ways in two places) must be eliminated — that's what the shared-"raw → validated" translation layer and the shared smart constructors in-Part 2 exist to prevent. Duplication of *code that happens to look-similar but encodes unrelated decisions* should **not** be merged. Two-functions that currently have the same three lines but answer different-questions are not a DRY violation — collapsing them creates a false-coupling that will need to be un-collapsed the moment the two decisions-diverge. When in doubt: ask whether the two call sites would ever need to-change independently. If yes, don't merge them.--### 0.7 KISS and YAGNI-Implement the mechanism the current, real requirement needs — not the one-a hypothetical future requirement might need. An error constructor,-typeclass, or extension point is added in the same change that makes it-reachable, never speculatively (this is also stated in Part 1 as a-closed-vocabulary rule, because it's load-bearing there too). Prefer the-simplest technique in Part 3's toolkit that fully closes the problem;-reach for a more powerful technique (GADT, existential, type family) only-once the simpler one is demonstrably insufficient, and say why in a-comment when you do.--### 0.8 Law of Demeter-A function should not reach through more than one level of a nested-record/structure to get what it needs. If `renderPage` needs-`documentMeta.author.displayName`, that's a sign `documentMeta` should-expose `authorDisplayName` directly, or the caller should be handed the-narrower value it actually needs rather than the whole tree. This keeps-refactors local: changing how `author` is represented shouldn't ripple-into every renderer that happens to reach through it.--### 0.9 Composition over inheritance — the Haskell default-There is no inheritance to avoid reaching for; the discipline instead is-to build behavior by composing small, independent pieces (function-composition, typeclass constraints, monad transformers, or simple value-composition) rather than by building one large record or one large-typeclass that tries to be everything. If a type is accumulating-unrelated fields "because it's convenient to have them all in one place,"-that's the inheritance instinct resurfacing in record form — split it.--### 0.10 Principle of Least Power-Give every function the least expressive type that still lets it do its-job. A function that doesn't need `IO` shouldn't have it in its-signature. A function that only reads state shouldn't be typed to allow-writes. A typeclass constraint should name the weakest class in the-hierarchy that suffices (`Foldable` instead of a concrete `[]`, when only-folding is needed). Least power at the type level is what makes a-signature trustworthy on sight — the type is a promise about what the-function *cannot* do, not just what it does.--### 0.11 Compatibility is a promise about the boundary, not the internals-Preserve backward compatibility for a module's public API where-practical — don't churn an external signature for cosmetic reasons; see-2.13 for how this is enforced through versioning. That promise applies-only to the boundary. Internally, continuously review and simplify type-and module design: refactor implementations freely, delete dead-abstractions, and collapse a type that turned out more general than-needed, as long as the public shape either stays put or moves behind a-deliberate version bump. Stability and simplification aren't in tension-once it's clear which side of the export list each applies to.-------## Part 1 — Language Principles (never violated)--### 1.1 Every function is total, or its type says it isn't-No partial functions. Never use: `head`, `tail`, `last`, `init`,-`fromJust`, `(!!)`, non-exhaustive pattern matches, `error`, `undefined`,-or incomplete `case`/`if` chains on a closed type. If a function can fail,-its type says so — `Maybe a` for one reason, `Either e a` when the reason-needs to be named. `-Wall -Werror -Wincomplete-uni-patterns--Wincomplete-record-updates -Wpartial-fields` are mandatory, not optional.--### 1.2 Illegal states are unrepresentable, not merely rejected-Prefer a type that cannot hold invalid data over a type that can, plus a-validator. This is the single most important habit in this document and-recurs throughout Part 3's toolkit — see especially 3.1–3.4.--### 1.3 Cross-field invariants are enforced once, at construction-If correctness depends on a relationship between two or more fields (e.g.-"every row has the same width"), the constructor is not exported; the-only way to obtain a value is a smart constructor returning-`Either err a`. Once constructed, the value is trusted everywhere-downstream — never re-checked. (Full treatment in 3.3.)--### 1.4 Closed domains are closed types, not strings-Any finite, known set of alternatives is a sum type — never a-`Text`/`String` compared against literals. A value outside the closed set-is a compile-time impossibility, not a runtime "unrecognised value"-string.--### 1.5 Errors are a closed, structured vocabulary-One sum type per failure category, each constructor documented with *why-it exists* and *what can produce it*. No stringly-typed errors, no-catch-all `OtherError Text`. A constructor is added only in the same-change that makes it reachable.--### 1.6 Purity is pushed to the edges-Business logic is pure. `IO` is confined to a thin shell at the-boundary — reading input, writing output, catching foreign-library-exceptions and converting them into the structured error type-immediately. A function is never `IO`-typed merely because a library it-calls can throw; catch and convert at that call site.--### 1.7 No implicit escape hatches-No `unsafePerformIO`, no `Debug.Trace` in committed code, no `Show`-based-serialization used as data interchange, no orphan instances (an instance-lives next to the type or next to the class, never floating in an-unrelated module).--### 1.8 Explicit over implicit, always-No global mutable state (`IORef`s reached for reflexively instead of-threading state explicitly), no reliance on typeclass resolution doing-something surprising (`OverlappingInstances`, `IncoherentInstances` are-red flags requiring explicit justification), no reflection-like tricks to-avoid writing an explicit case. If a reader has to run the code mentally-to know what will happen, it's too implicit.--### 1.9 Immutability is the default, not an aspiration-Data is immutable unless a specific, profiled reason calls for a mutable-cell (`IORef`, `STRef`, `MVar`, a mutable vector). Local transformations-use record-update syntax and pure recursion, not accumulation into a-mutable variable "for convenience." This is distinct from 1.8's ban on-*global* mutable state — 1.9 is the default even for a value that never-leaves a single function.--### 1.10 Referential transparency is the target, not just a byproduct of purity-An expression's value must not depend on when, how many times, or in-what order it's evaluated — this is what makes equational reasoning-possible: a sub-expression can be replaced by its value, memoized, or-lifted out and shared, without changing the program's meaning.-`unsafePerformIO` and any hidden mutable state breaks this, which is why-1.7 bans the former outright rather than merely discouraging it.--### 1.11 Zero dead code, zero empty stubs — strictly enforced-Nothing unreachable is committed: no unused top-level bindings, no-commented-out blocks "kept just in case," no functions exported but-never called anywhere in the codebase or its public API surface.-`-Wunused-top-binds -Wunused-local-binds -Wunused-matches` are treated-as errors, and a dead-code detector (`weeder`) runs in CI alongside-`hlint`. Equally strict in the other direction: a function is either-fully implemented or does not exist in the merged code — no-`someFunction = undefined`, no `error "TODO"`, no placeholder that-type-checks but panics if called. If a capability isn't ready, its-call site isn't merged either; half-built scaffolding is worse than an-honest absence, because it compiles clean and looks finished.-------## Part 2 — Software Architecture (never violated)--### 2.1 One canonical intermediate representation-When a problem involves multiple input or output formats converging on-shared logic, there is exactly **one** internal representation every-input funnels into and every output funnels out of. Format-specific logic-lives only in the thin translation layer at each edge; core logic is-written once, against the IR.--### 2.2 Validation is staged, not scattered-Recovering *shape* is kept separate from checking *content validity*. Use-a shared "raw → validated" translation layer if multiple producers reach-the same validation step — write the validation once, share it.--### 2.3 Errors are layered to match pipeline stages-The top-level error type is a closed sum of closed sums, one case per-pipeline stage. A function's return type tells you unambiguously which-stage produced a failure without inspecting a string.--### 2.4 Recursive structures carry an explicit resource bound-Any recursive data type that hostile or careless input could nest-arbitrarily deep gets an explicit, threaded depth/size limit at every-point of recursive descent, applied **uniformly** across every stage-capable of producing that nesting — not just the one someone happened to-think of first.--### 2.5 Module boundaries are drawn by responsibility, enforced by exports-Each module has one reason to change (0.1). Constructors and functions-that could violate an invariant if exported freely are **not** exported.-`-Wmissing-export-lists` is mandatory. A module's export list is its-contract.--### 2.6 Dependency direction is acyclic and points at the core-Format-specific / adapter modules depend on the core IR module; the core-never imports outward. This is hexagonal architecture stated in Haskell-terms: a pure core, with parsers/renderers/storage/network as adapters at-the boundary, wired in either via closed dispatch (0.2) or a Handle/-typeclass (0.5) — never via the core reaching outward to call them-directly.--### 2.7 Extensibility mechanism is chosen deliberately, per axis, and documented-See 0.2. State, in the relevant module's Haddock, whether a given-extension point is closed-by-design (compiler-enforced exhaustiveness) or-open-by-design (Handle/typeclass) — and don't let a "just this once"-exception blur the line without updating the documentation to match.--### 2.8 Every architectural claim has a mechanical check behind it-"This module is total" is checked by `-Wincomplete-patterns -Werror`.-"This invariant holds for every value of this type" is checked by a-property test. A claim without an enforcement mechanism is a wish, not a-property of the code, and must not be described as though it were-guaranteed.--### 2.9 Testing is part of the architecture, not an afterthought-Property-based tests are a *design tool*, not just a QA step — writing-the property before/alongside the implementation ("for any input, output-satisfies X") is often what reveals whether the type actually needs a-smart constructor. Regression tests are named after the specific defect-they guard, not "test5." Unit tests exercise the pure core directly,-never through an `IO` shell, because the core is pure and testable in-isolation by construction (1.6, 0.5) — if a test needs `IO` to exercise-core logic, that's a signal the architecture leaked an effect it didn't-need to.--### 2.10 Organise modules by domain, not by technical utility-Group modules by what they mean in the problem (`Document`,-`Pipeline`, `Rendering.Html`), not by what kind of thing they technically-are (`Utils`, `Helpers`, `Common`, `Types`). A grab-bag `Utils.hs` is a-confession that some piece of logic was never given a real owner — it-belongs in whichever domain module actually needs it, even at the cost-of a small amount of near-duplicate code across two domains (0.6).--### 2.11 Depend on the fewest, best-maintained libraries the problem needs-Prefer an established, actively maintained library over a hand-rolled-equivalent — including for 4.2's named algorithms: if a well-maintained-library already implements the algorithm correctly, depend on it rather-than re-proving it in-house (4.7), unless the dependency itself becomes-the risk (parsing untrusted input, licensing, supply-chain exposure).-Every dependency joins the trusted computing base; add one deliberately,-not by default, and prefer one well-chosen library over three overlapping-ones that each cover part of the same need.--### 2.12 Builds are deterministic and reproducible-Pin dependency versions (`cabal.project.freeze` or an equivalent-lockfile, a fixed Stackage resolver) so the same commit produces the same-build, today and a year from now. A build that silently picks up a newer-transitive dependency on every fresh checkout undermines every other-guarantee in this document — a passing property test says little if next-week's build compiles different code underneath it.--### 2.13 Package and module versioning follows the PVP, deliberately-Follow the Haskell Package Versioning Policy: a breaking change to any-exported signature bumps the major version; anything else does not.-Combined with 0.11 — a public signature changes only behind a deliberate-version bump, never as the silent side effect of an unrelated refactor.--### 2.14 Code is portable by default-Avoid unnecessary dependence on a specific OS, filesystem layout, or-compiler version beyond what the problem genuinely requires. Use-portable path/file libraries (`filepath`, `directory`) instead of-hardcoded separators or absolute paths; note any genuine, unavoidable-platform dependency explicitly in the module that has it, rather than-letting it surface later as a mysterious build failure somewhere else.--### 2.15 Errors live in a dedicated module, and every message is descriptive-The closed error vocabulary (1.5, 2.3) is defined in its own module,-separate from the domain logic that raises it — one place a reviewer or-a new contributor goes to see the entire universe of ways the system can-fail. Every constructor's rendered message names the specific thing that-went wrong and, wherever the information is available, the specific-input or location that caused it (a file path, a line number, a field-name) — never a bare "invalid input" or "something went wrong." A vague-error message is a silent failure wearing an error type; it satisfies-1.5's letter while missing its point.-------## Part 3 — The Haskell Type-System Toolkit: What to Reach For, and When--Use the least powerful tool in this list that fully solves the problem-(0.7, 0.10). Escalate only when the simpler tool genuinely can't express-the invariant, and say so in a comment when you escalate.--### 3.1 Algebraic data types — the default, reach for first-Sum types for closed alternatives, product types (records) for "all of-these together." This is the baseline for making illegal states-unrepresentable: a value that can only be one of N well-defined shapes,-never a partially-filled record with a `Maybe` flag simulating a variant.--```haskell--- Bad: simulates a sum type with a flag and nullable fields.-data Shape = Shape { isCircle :: Bool, radius :: Maybe Double-                    , width :: Maybe Double, height :: Maybe Double }---- Good: the type itself rules out "circle with a width."-data Shape = Circle Double | Rectangle Double Double-```--### 3.2 Newtypes — eliminate primitive obsession at zero runtime cost-Any domain concept represented as a bare `Text`, `Int`, or `Double` that-could be confused with another value of the same primitive type gets a-`newtype`. `UserId`, `DocId`, and `SessionId` should not all be `Text`-that the compiler will happily let you swap by accident.--```haskell-newtype UserId = UserId Text deriving (Eq, Ord, Show)-newtype DocId  = DocId  Text deriving (Eq, Ord, Show)--- lookupDoc :: UserId -> DocId -> ...   -- now a compile error to swap them-```--### 3.3 Smart constructors + opaque exports — the standard invariant-enforcement mechanism-Whenever a value's validity depends on content, not just shape (a-rectangular table, a syntactically valid URL, non-empty-after-trimming-text), the type's constructor is unexported and the *only* way to build-one is a function returning `Either err a`. This is not optional-whenever 1.2/1.3 apply — it is the mechanism those principles are-implemented with.--```haskell-module M (Percentage, mkPercentage, unPercentage) where--newtype Percentage = UnsafePercentage Double deriving (Eq, Ord, Show)--mkPercentage :: Double -> Either ValidationError Percentage-mkPercentage x-  | x >= 0 && x <= 100 = Right (UnsafePercentage x)-  | otherwise          = Left (OutOfRange x)--unPercentage :: Percentage -> Double-unPercentage (UnsafePercentage x) = x-```--### 3.4 Phantom types — compile-time-only tags with zero runtime cost-Use a type parameter that never appears on the right-hand side of any-constructor to carry a *static* fact about a value — "this text has been-escaped," "this ID belongs to a draft, not a published document" — that-the compiler checks but that costs nothing at runtime.--```haskell-data Status = Draft | Published--newtype DocRef (s :: Status) = DocRef Text--publish :: DocRef 'Draft -> IO (DocRef 'Published)--- A published-only operation now cannot even type-check against a draft.-notifySubscribers :: DocRef 'Published -> IO ()-```--### 3.5 GADTs — when different constructors need different result types-Reach for a GADT when a plain ADT would force every constructor to share-one result type even though they logically produce different types, and-you'd otherwise be compensating with an unsafe cast or a partial-extraction function. Typed embedded languages/ASTs, and safety-indexed-wrappers (a value's constructors *are* its safety guarantee) are the-canonical use case.--```haskell-data Expr a where-  IntLit  :: Int -> Expr Int-  BoolLit :: Bool -> Expr Bool-  Add     :: Expr Int -> Expr Int -> Expr Int-  If      :: Expr Bool -> Expr a -> Expr a -> Expr a--eval :: Expr a -> a          -- total: GADT rules out ill-typed terms-eval (IntLit n)  = n-eval (BoolLit b) = b-eval (Add x y)   = eval x + eval y-eval (If c t e)  = if eval c then eval t else eval e-```-Without the GADT, `eval :: Expr -> SomeValue` would need a runtime type-check and a partial extraction (`asInt`, `asBool`) — exactly the-partiality Part 1 prohibits. The GADT moves that check to compile time.--### 3.6 Existential types — last resort, justify explicitly-Use `forall`/existentials only when you genuinely need a heterogeneous-collection of values that share a common interface but whose concrete-type doesn't matter (e.g. a list of "anything renderable"). Existentials-throw away the very type information Part 1–3 spend so much effort-preserving, so treat reaching for one as a flag: state in a comment-*why* the concrete type must be forgotten here and why a closed sum-(3.1) or typeclass-constrained polymorphic function isn't sufficient-instead.--### 3.7 Typeclasses — principled overloading with laws, not ad hoc dispatch-A typeclass is appropriate when multiple types share genuinely the same-abstract operation *and* that operation obeys stated laws (0.3). It is-not a substitute for a Handle (0.5) when there's only ever one-implementation live at a call site, and it is not a way to fake-function overloading for otherwise-unrelated operations. Every-non-trivial typeclass ships with its laws stated in a Haddock comment,-and law-checking tests where a library exists for the class in question.--### 3.8 DataKinds / kind signatures — promote a value to the type level only when the compiler needs it there-Use `DataKinds` when a value genuinely needs to participate in a-type-level distinction (as in 3.4's `Status` kind). Don't promote a value-to the type level "for elegance" if a plain runtime value moving through-an `Either`/smart-constructor already closes the same hole — that's-reaching for 3.4–3.5's power where 3.1/3.3 would fully suffice (0.7).--### 3.9 mtl-style constraints / effect boundaries — dependency inversion at the type level-When a function needs several capabilities (state, config, failure)-without being locked to one concrete monad stack, constrain it-polymorphically (`(MonadReader Config m, MonadError MirrorError m) => ...`)-rather than hardcoding `ReaderT Config (ExceptT MirrorError IO) a`. This-is 0.5's dependency inversion applied to effects: the function states-what it needs, not which stack provides it, and can be run over a pure-test stack and a real `IO` stack without being rewritten. Reach for a-full effect system (`polysemy`/`effectful`/`fused-effects`) only once-the mtl-style constraint set is unwieldy in practice — not by default.--### 3.10 Free monads / tagless-final — advanced, use only when interpreter-swapping is a real requirement-These let business logic be written once and interpreted multiple ways-(a real backend, an in-memory test double, a dry-run/audit log). They are-powerful and legitimately useful, but they add real conceptual and-compile-time cost. Reach for them only when the Handle pattern (0.5)-genuinely can't express the needed flexibility — e.g. when the *sequence-of operations itself* needs to be inspected or optimized before-execution, not just when-swapped. Justify the choice in the module's-Haddock when used.--### 3.11 Refinement types (Liquid Haskell) — optional, for the highest-stakes invariants only-When a smart constructor's `Either`-returning runtime check would be-better as a statically checked refinement (e.g. "this index is always-in bounds," "this list is always sorted"), Liquid Haskell annotations-can move the proof obligation to compile time, checked by an SMT solver.-This is an opt-in escalation for the small number of invariants where-the cost of getting it wrong is high enough to justify the tooling-overhead — not a default for every smart constructor in the codebase.--### 3.12 Type aliases document; they don't protect — don't mistake one for the other-`type CustomerId = Text` buys readability and nothing else: the compiler-still lets a bare `Text` meant as an email address flow anywhere a-`CustomerId` is expected. Reach for `type` only as genuine shorthand for-a long, repeated type expression. The moment two values sharing an-underlying representation must not be interchangeable, that's `newtype`-territory (3.2), not `type`.--### 3.13 Use the standard abstractions idiomatically; prefer the weakest one that suffices-Write code against `Functor`, `Applicative`, `Monad`, `Foldable`, and-`Traversable` using their standard combinators (`fmap`, `traverse`,-`sequence`, `for_`) rather than reimplementing their effect by hand —-4.1's combinator discipline applied to the handful of classes that recur-constantly. Prefer `Applicative` over `Monad` whenever the computation's-structure doesn't actually depend on a previous result: an `Applicative`-signature is a stronger, more honest claim ("these effects are-independent of each other") than a `Monad` signature over the same code,-and it composes and parallelizes better as a direct consequence.--### 3.14 Parametric polymorphism internally; concrete types at the boundary-Prefer a polymorphic type (`Foldable t => t a -> ...`) inside a module-where it genuinely generalizes the logic without adding constraint--solving noise (0.10). At a module's public boundary — the functions in-its export list — prefer concrete, specific types over polymorphism for-its own sake: `Document -> Either MirrorError Html` is easier to consume,-produces clearer type errors at the call site, and is easier to reason-about than a signature generalized over a typeclass nobody outside the-module will ever instantiate differently.--### 3.15 Linear types — when a resource's usage discipline is itself the invariant-Where correctness depends not just on a value's shape but on *how many-times and in what order* it is used — a file handle that must be closed-exactly once, a protocol token that must not be duplicated or silently-dropped — `LinearTypes` let the compiler enforce that usage discipline-the same way GADTs (3.5) enforce shape. Treat this as a specialized,-last-resort-among-first-resorts tool: reach for it only when the-resource-usage invariant can't be adequately captured by a Handle (0.5)-plus ordinary discipline, since linear types add real signature-level-complexity everywhere the resource is touched.-------## Part 4 — Code Style: Algorithmic, Not Improvised--Every non-trivial piece of control flow is either a **named combinator**-or a **named, published algorithm** — so a reader verifies it by-recognition, not by re-deriving it line by line. This is not a request-for brevity or point-free cleverness; point-free style is permitted only-where it reveals structure (4.4), and is otherwise prohibited.--### 4.1 Name the recursion scheme before writing the recursion-| Shape | Combinator |-|---|---|-| Consume a structure, build one value | `foldr` / `foldl'` |-| Produce a stream from a seed until done | `unfoldr` |-| Structure-preserving traversal with effects | `traverse` / `mapM` |-| Map while threading accumulator state | `mapAccumL` / `mapAccumR` |-| Repeated application until a fixed point | `until` / `iterate` + `takeWhile` |-| Group / partition by a predicate | `span`, `break`, `groupBy`, `partition` |--Hand-written recursion is reserved for logic with no existing combinator-shape — and even then, the Haddock states which scheme it approximates-and why no combinator fits.--### 4.2 If a published algorithm solves the exact problem, implement that algorithm, by name-Don't reinvent a heuristic that happens to converge on a known-algorithm's answer — implement the known algorithm and cite it (Kahn's-algorithm for topological order, Pratt parsing for precedence-based-expression parsing, Myers' algorithm for sequence diffing, and so on).-Naming it lets a reviewer check the implementation against a reference-instead of re-establishing correctness from first principles.--### 4.3 Match complexity to access pattern-`Map`/`Set` for lookup-heavy code, not a linearly scanned `[a]`; `Seq`-for append/index-heavy code, not a repeatedly reversed list. Do not,-conversely, reach for a more sophisticated algorithm than the problem-needs (0.7) — correct complexity for the real access pattern, not-maximal sophistication for its own sake.--### 4.4 Point-free style only when it reveals structure-`f = g . h` is preferred over an explicit lambda only when the-composition itself is the insight worth stating. If it requires the-reader to mentally re-expand it to check what's happening, write it-pointfully. Never chain more than two or three compositions without a-named intermediate.--### 4.5 Every exported function is one lemma-If a function's body doesn't fit in roughly 15–20 lines, it's not one-claim, it's several — split it and name each part. A long `case` across-a closed type is fine (it's exhaustiveness, not sprawl); a long sequence-of unrelated steps is not.--### 4.6 The type signature is the theorem; the Haddock states the invariant, not the procedure-**Bad:** `-- loops through the list and picks out the valid rows`-**Good:** `-- | The only way to obtain a 'Table': every row, header-included, is checked against the first row's width. On success, the-result's rectangularity is guaranteed for every later consumer.`--### 4.7 Reuse a proven library's implementation of a named algorithm before writing your own-4.2 says to implement a named, published algorithm rather than an ad hoc-heuristic. The stronger version: if a well-maintained library already-provides that exact algorithm correctly, depend on it (2.11) instead of-re-implementing it. Reserve a from-scratch implementation for the case-where no adequate library exists, or where this codebase's handling of-untrusted input specifically requires an implementation whose safety-properties can be independently audited (Part 5).--### 4.8 Consistent naming conventions, applied without exception-One convention per category: types and constructors in `UpperCamelCase`,-functions and fields in `lowerCamelCase`, module names mirror their file-path. Smart constructors are named `mkX` (3.3); unsafe or internal-only-constructors are prefixed `Unsafe` or kept unexported entirely. A reader-should be able to predict a name's category from its case alone, without-opening the module that defines it.--### 4.9 Laziness is exploited on purpose; strictness is added on evidence-Rely on laziness deliberately for what it's actually good at — infinite-or self-referential structures, short-circuiting, decoupling production-from consumption — and treat an unexplained space leak as a bug to-diagnose, not a tax to accept. Add strictness annotations (`!` on-fields, `seq`, `foldl'` over `foldl`, `BangPatterns`) only where-profiling, not intuition, has shown a real leak or a real cost.-Premature strictness is the same unjustified complexity 0.7 already-prohibits, just approached from the performance direction instead of the-abstraction direction.--### 4.10 Recursion over unbounded input is stack-safe — strictly enforced-Beyond 2.4's bound on adversarial nesting, any function that folds or-recurses over a structure whose size is driven by ordinary, legitimate-input (a large file, a long list) must not blow the stack. Use-`foldl'`/`foldMap'`-style strict folds instead of `foldr`/lazy `foldl`-for large accumulations, prefer combinators with known stack behavior-(4.1's table) over bespoke recursion, and make any genuinely necessary-hand-written recursive function tail-recursive with a strict-accumulator. A function that works in tests on small fixtures but is-never checked against a realistically large input is not verified to be-stack-safe — add a large-input case specifically to catch this (5.4).--### 4.11 Known space-leak patterns are avoided by construction-The recurring, well-documented sources of Haskell space leaks are treated-as defects, not idiosyncrasies to tolerate: unbounded thunk buildup from-lazy accumulation (`foldl` on a large list, a lazy `State`/`Writer`-accumulator never forced), quadratic-blowup string/list concatenation-(repeated `(++)` instead of a builder or `Data.Text.Builder`/`Seq`),-holding onto the head of a list or a whole lazy `ByteString`/`Text` far-longer than needed because one small part of it is still referenced, and-unbounded lazy I/O. Each is a specific, nameable pattern (not a vague-"Haskell can leak" caveat), and each has a specific, standard fix — apply-the fix at the point the pattern is introduced, not after a production-memory graph shows it.-------## Part 5 — Verification and Enforcement--### 5.1 Mandatory compiler flags-```--Wall -Wcompat -Werror--Wincomplete-uni-patterns -Wincomplete-record-updates--Wmissing-export-lists -Wunused-imports -Wunused-top-binds--Wunused-local-binds -Wunused-matches--Wredundant-constraints -Wpartial-fields -Widentities-```--### 5.2 Banned outright (lint-enforced)-`head`, `tail`, `fromJust`, `(!!)`, `error`, `undefined`,-`unsafePerformIO`, `Debug.Trace.*` in committed code, partial record-field accessors, `OverlappingInstances`/`IncoherentInstances` without-explicit written justification, and any unreachable code flagged by-`weeder` (1.11).--### 5.3 Formatting is enforced, not a matter of taste-`ormolu` or `fourmolu` runs as a CI check alongside `hlint`, so a diff is-never mixed style-only noise and substantive change, and no two-contributors — human or AI — drift into different house styles over-time.--### 5.4 Tests are exhaustive, including outliers — strictly enforced-A test suite that only exercises the happy path is incomplete by-definition, not merely light. For every function with a bounded or-partially-bounded domain, tests cover: the empty/zero/minimum case, the-single-element case, the maximum or a realistically large case (4.10),-known adjacent-to-boundary values (off-by-one candidates), malformed or-adversarial input for anything crossing a trust boundary (2.4), and, via-property-based testing, a generator wide enough that these outliers are-sampled rather than hand-picked and potentially forgotten. "It passes on-the examples I thought of" is not exhaustive; "the generator's shrinker-was pointed at this class of input and found nothing" is closer to what-this rule requires.--### 5.5 Every stated invariant needs a property test in the same change that introduces it-A Haddock claim ("output is always escaped," "result is always-rectangular," "instance obeys the Monoid laws") ships with a-QuickCheck/Hedgehog property checking exactly that claim, in the same-diff — not as an afterthought.--### 5.6 Benchmarking is part of the test suite, not a side activity-Every module on a path that matters for real-world input size (parsers,-renderers, anything called per-request) has a `criterion` (or-equivalent) benchmark checked in alongside its tests, run in CI with-regression thresholds, not just on demand before a release. This is the-evidence 4.9 requires before adding a strictness annotation, and the-mechanism that makes "performance is addressed deliberately, with-evidence" (the precedence rule at the top of this document) an actual-practice rather than a stated intention. A change that regresses a-benchmark beyond its threshold is treated the same as a failing test.--### 5.7 Known bugs from comparable prior art are pre-empted, not rediscovered-Before implementing a component that has established prior art (a DOCX-parser, a Markdown renderer, an HTML escaper, a diff algorithm), the-issue tracker and changelog of at least one or two comparable existing-projects are reviewed for the specific bug classes they've hit historically-— parser desync on a particular malformed input, an escaping bypass, a-resource-exhaustion vector, an off-by-one in a boundary case. Each-applicable bug class gets a named regression test *written before or-alongside the first implementation*, not added reactively after the same-bug is independently rediscovered in this codebase. This research is-recorded (a short note or linked issue) so the next contributor can see-which known failure modes were already checked, rather than re-doing the-same archaeology or, worse, assuming it was never done.--### 5.8 Two-pass self-audit for AI-authored code-After writing a function, re-read its own Haddock claim and check, line-by line, whether the implementation actually establishes it. Do not-trust a comment written in the same pass that wrote the code. State-explicitly if a claimed invariant is *not* fully established, rather-than leaving an inaccurate guarantee in place.--### 5.9 Deviations are recorded, not silent-If a rule in this document is knowingly not followed for a specific,-justified reason (performance-critical hot path, a library's API forces-an escape hatch), record it as a short Architecture Decision Record next-to the code — what rule was relaxed, why, and what was tried first — so-it reads as a deliberate, reviewed exception, not an oversight.--------## Part 6 — Before the Project Starts: Setup Checklist--Put this in place *before* the first feature module is written.--- [ ] `cabal`/`hpack` project skeleton with the Part 5 GHC flags set as a-      shared `common warnings` stanza, applied to every component-      (library, executable, tests) — not opt-in per module.-- [ ] `hlint` configured with the Part 5 ban-list as errors, not-      suggestions, wired into CI.-- [ ] Module skeleton drawn along the hexagonal boundary of 2.6 up-      front: a `Core`/`Domain` area (pure, IR-centered) and an-      `Adapters` area (parsers, renderers, storage, network) — so the-      dependency direction is structural from commit one, not something-      to "clean up later."-- [ ] A single canonical IR module identified and agreed before any-      format-specific or adapter-specific module is started (2.1).-- [ ] The closed-vocabulary error type (2.3) scaffolded before the first-      failure case is needed, with the reachability discipline (1.5)-      stated in its own Haddock.-- [ ] Test framework wired for both example-based (hspec) and-      property-based (QuickCheck/Hedgehog) tests from the first-      commit, with the rule from 2.9 (tests exercise the pure core-      directly) established as the default shape, and an explicit-      outlier/boundary-case checklist template for new test modules (5.4).-- [ ] Benchmark harness (`criterion` or equivalent) wired into CI with-      regression thresholds before the first performance-relevant module-      is merged, not added retroactively once something feels slow (5.6).-- [ ] For each planned component with established prior art, the known-      bug classes from at least one or two comparable projects' issue-      trackers reviewed and logged before implementation begins, with a-      named regression test planned for each applicable one (5.7).-- [ ] This document itself checked into the repository (e.g.-      `ENGINEERING_STANDARD.md`) and referenced from the project's-      `README` and from any AI-agent configuration file (`CLAUDE.md`,-      `.cursorrules`, or equivalent), so it is loaded as context-      automatically rather than depended on being remembered.-------## Pre-submission Checklist--Before presenting any Haskell code written or edited under this-standard, confirm each of the following, explicitly:--- [ ] Single responsibility per module; no "and" needed to describe it (0.1)-- [ ] Extension axis for this change identified as closed-sum or-      Handle/typeclass, and consistent with existing choice (0.2, 2.7)-- [ ] Any new typeclass instance obeys its class's laws (0.3)-- [ ] Typeclass/Handle constraints are the narrowest that suffice (0.4, 0.10)-- [ ] New effectful dependency passed as a Handle or mtl-style-      constraint, not imported and called directly (0.5, 3.9)-- [ ] No duplicated *invariant logic*; deliberate, justified duplication-      of unrelated-but-similar code left alone (0.6)-- [ ] No speculative generality — the mechanism added matches a real,-      current requirement (0.7)-- [ ] No structure reached through more than one level deep (0.8)-- [ ] No partial functions; every failure path is typed (1.1)-- [ ] Illegal states are unrepresentable, not just checked (1.2, 3.1)-- [ ] Cross-field invariants enforced once, at construction, via an-      unexported constructor (1.3, 3.3)-- [ ] Closed domains are sum types, not strings (1.4)-- [ ] Errors are structured and layered by pipeline stage (1.5, 2.3)-- [ ] `IO` confined to the edges; core logic pure and independently-      testable (1.6, 2.9)-- [ ] Considered whether a newtype, phantom type, or GADT would close a-      hole more cheaply than a runtime check (3.2, 3.4, 3.5) — and, if-      an existential was used, justified why a closed sum couldn't (3.6)-- [ ] Single canonical IR respected if multiple formats are involved (2.1)-- [ ] Recursive structures have an explicit depth/size bound, applied-      uniformly across every stage capable of producing the nesting (2.4)-- [ ] Module exports only what's safe to export (2.5)-- [ ] No hand-rolled recursion where a named combinator applies (4.1)-- [ ] Known algorithms implemented and cited by name, not reinvented (4.2)-- [ ] Every function is one lemma, ~15–20 lines or fewer (4.5)-- [ ] Every non-trivial comment states an invariant, not a procedure (4.6)-- [ ] A named algorithm's proven library implementation used in-      preference to a from-scratch one, where a good one exists (4.7)-- [ ] Naming follows the standard convention for its category (4.8)-- [ ] Any new strictness annotation is backed by profiling evidence, not-      intuition (4.9)-- [ ] No new mutable local state where pure recursion/record-update would-      do (1.9)-- [ ] New module placed by domain, not dropped into a `Utils`/`Common`-      catch-all (2.10)-- [ ] Any new dependency is deliberate, well-maintained, and not-      duplicating an existing one (2.11)-- [ ] `type` alias not used where a `newtype` boundary was actually-      needed (3.12)-- [ ] `Applicative` used instead of `Monad` where the effects are-      genuinely independent (3.13)-- [ ] Public boundary functions use concrete types; polymorphism kept-      internal to where it earns its constraints (3.14)-- [ ] No dead code, no `undefined`/stub placeholders merged (1.11, 5.2)-- [ ] Error messages name the specific thing and location that failed;-      errors live in their own dedicated module (2.15)-- [ ] Any function over unbounded legitimate input is checked-      tail-recursive/strict-accumulator and tested on a large input (4.10)-- [ ] Checked against the named space-leak patterns — no `foldl` on a-      large structure, no repeated `(++)`, nothing holding a large-      structure alive longer than needed (4.11)-- [ ] New tests cover the boundary/empty/maximum/adversarial cases, not-      only the happy path (5.4)-- [ ] A benchmark exists and is checked in for any change on a-      performance-relevant path (5.6)-- [ ] For new prior-art-backed components, comparable projects' known-      bug classes were checked and pre-empted with a named test (5.7)-- [ ] Every claimed invariant has a matching property test (5.5)-- [ ] Self-audited: implementation re-checked against its own stated-      claim, in a separate pass (5.8)-- [ ] Any knowing deviation from this document recorded as a short ADR,-      not left silent (5.9)
README.md view
@@ -193,9 +193,22 @@  ## Safety -* **Limits** (`F.defaultLimits`: depth 64, one million values; override-  with `F.withLimits`) are enforced inside every parser, so a hostile-  `[[[[...` megabyte is rejected at depth 65 without being built.+* **Limits** (`F.defaultLimits`: depth 64, one million values, 32 MiB per+  source; override with `F.withLimits` and `F.withMaxBytes`) are enforced+  inside the JSON and YAML parsers and on structured environment and+  command-line values, so a hostile `[[[[...` megabyte is rejected at+  depth 65 without being built. TOML is the exception: its parser builds+  the whole document before figment sees a value, so TOML is guarded by a+  linear pre-scan (bracket depth and a token count) and the size limit+  rather than a per-value budget. Lower `maxBytes` if you read TOML you do+  not trust.+* **Secrets**: wrap a field in `F.Secret` (`password :: Secret Text`) and a+  decode failure never quotes the value; `show` prints+  `Secret <redacted>`. Other fields' errors do quote the offending value+  (truncated), so do not decode a password into an `Int`.+* **Reports are escaped**: control, bidirectional and zero-width characters+  in keys, file names, messages and hints are rendered as `\u{...}`, so a+  hostile name cannot forge extra lines in an error report. * No exception escapes `load`: I/O and parse failures are errors, and a   synchronous exception thrown by a third-party provider becomes an   `IoError` (asynchronous exceptions are re-thrown, as they must be).@@ -239,9 +252,11 @@ cabal bench ``` -Supported compilers: GHC 9.10 and 9.12.+Supported compilers: GHC 9.10 and 9.12, tested in CI on Linux, macOS and+Windows. GHC 9.14 is tried in CI as an experimental job; it will be+supported once the dependencies (notably `scientific`) allow it. -Version 0.2.0.0 is a breaking redesign of 0.1; see the changelog. The+Version 0.2.0.0 was a breaking redesign of 0.1; 0.3.0.0 is a hardening release (see the changelog). The source distribution also contains the design record: `ADRs/` (decisions 016 onwards apply to 0.2) and `docs/audit-remediation.md` (each problem found in 0.1, how it was fixed, and the test that pins it).
docs/audit-remediation.md view
@@ -53,7 +53,8 @@  ## Not done (and why) -- **hlint / formatter in CI.** No hlint binary exists for the platform+- **hlint / formatter in CI.** (0.3.0.0: `.hlint.yaml` and advisory CI jobs added; make them blocking once the code is clean.)+  Original note: No hlint binary exists for the platform   this release was prepared on, so a lint gate could not be run locally   before adding it. Recommended next step: add a `haskell-actions/hlint-run`   job and fourmolu once the code has been formatted once.
figment.cabal view
@@ -1,6 +1,6 @@ cabal-version:      3.0 name:               figment-version:            0.2.0.0+version:            0.3.0.0 synopsis:           Layered configuration with provenance, profiles and complete error reports description:   A Haskell take on Rust's figment. Combine configuration from files@@ -18,7 +18,7 @@ license-file:       LICENSE author:             Sabrinathan Nair maintainer:         bombay.boyz@hotmail.com-copyright:          (c) 2026 Bombay-Boyz+copyright:          (c) 2026 Sabrinathan Nair homepage:           https://github.com/Bombay-Boyz/Figment bug-reports:        https://github.com/Bombay-Boyz/Figment/issues category:           Configuration@@ -27,7 +27,6 @@ extra-doc-files:   README.md   CHANGELOG.md-  ENGINEERING_STANDARD.md   ADRs/*.md   docs/*.md extra-source-files:@@ -87,9 +86,12 @@   other-modules:     Figment.Internal.Budget     Figment.Internal.Nest+    Figment.Internal.Number+    Figment.Internal.Text+    Figment.Internal.TomlScan     Figment.Internal.ValueParser   build-depends:-      base        >= 4.20   && < 4.22+      base        >= 4.20   && < 4.23     , aeson       >= 2.2    && < 2.3     , bytestring  >= 0.11   && < 0.13     , conduit     >= 1.3    && < 1.4@@ -121,6 +123,7 @@     Figment.Test.Cli     Figment.Test.Errors     Figment.Test.Adversarial+    Figment.Test.Hardening     Figment.Test.Readme     Figment.Test.Tutorial   build-depends:@@ -130,6 +133,7 @@     , bytestring     , containers     , deepseq+    , directory     , filepath     , tasty        >= 1.4  && < 1.6     , tasty-golden >= 2.3  && < 2.4@@ -153,4 +157,4 @@     , criterion  >= 1.6 && < 1.7     , deepseq     , text-  ghc-options:      -threaded -rtsopts+  ghc-options:      -threaded -rtsopts "-with-rtsopts=-T"
src/Figment.hs view
@@ -97,6 +97,7 @@   , genericDecoder   , Tagged (..)   , taggedMetadata+  , Secret (..)   , RelativePath (..)   , relative   , ViaAeson (..)@@ -160,9 +161,12 @@     -- * Limits   , Limits   , mkLimits+  , withMaxBytes   , defaultLimits+  , defaultMaxBytes   , maxDepth   , maxNodes+  , maxBytes   ) where  import Data.Functor.Identity (Identity (..))
src/Figment/Core.hs view
@@ -39,12 +39,15 @@   , focus   ) where -import Control.Exception (SomeAsyncException, SomeException (..), displayException, fromException, throwIO, try)+import Control.DeepSeq (force)+import Control.Exception (SomeAsyncException, SomeException (..), displayException, evaluate, fromException, throwIO, try) import Data.Foldable (toList)+import Data.List.NonEmpty (NonEmpty (..)) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe, isJust) import Data.Monoid (Last (..))+import Data.Semigroup (sconcat) import Data.Sequence (Seq) import qualified Data.Sequence as Seq import qualified Data.Text as Text@@ -168,8 +171,15 @@     -- ^ every provider, in order   , loadedLimits :: !Limits     -- ^ the limits the sources were read with+  , loadedView :: Value+    -- ^ the merged view of the selected profile (see 'selected'); computed+    -- once, on first use, instead of on every query   } +-- | The only way to build a 'Loaded': derives the cached view.+mkLoaded :: Profile -> Map Profile Dict -> [Metadata] -> Limits -> Loaded+mkLoaded prof dat srcs lim = Loaded prof dat srcs lim (selectView prof dat)+ -- | Run every provider, in order. Failures do not stop the load: all of -- them are collected and reported together. load :: Figment -> IO (Either ConfigErrors Loaded)@@ -182,13 +192,23 @@       combined = foldl' (\acc (s, d) -> coalesceData (stepOrder s) acc (retagData (stepMeta s) d)) Map.empty oks       hinted = foldl' (\acc s -> maybe acc (coalesceProfile (stepOrder s) acc) (stepProfile s)) Default steps       chosen = fromMaybe hinted (getLast (figSelect fig))-  pure $ case errs of-    (e : es) -> Left (foldl' (<>) e es)-    [] -> Right (Loaded chosen combined (map stepMeta steps) lim)+  case errs of+    (e : es) -> pure (Left (sconcat (e :| es)))+    [] -> do+      -- Evaluate everything now: a loaded configuration holds no thunks+      -- (so nothing keeps a source's original tree alive) and nothing can+      -- throw later, outside this function.+      evaluated <- evaluate (force combined)+      let !loaded = mkLoaded chosen evaluated (map stepMeta steps) lim+      pure (Right loaded) +-- | Run one provider. Its result is evaluated /inside/ the exception+-- handler: providers commonly return lazily built values (@pure (parse x)@),+-- and an exception hidden in such a value must become an error here, not+-- escape later from whoever first inspects the configuration. runStep :: Limits -> Step -> IO (Either ConfigErrors (Map Profile Dict)) runStep lim s = do-  r <- try (stepRun s lim)+  r <- try (stepRun s lim >>= evaluate . force)   case r of     Right (Left es) -> pure (Left (fmap' es))     Right ok -> pure ok@@ -207,19 +227,24 @@ bare (SomeException e) = displayException e  retagData :: Metadata -> Map Profile Dict -> Map Profile Dict-retagData m = Map.mapWithKey (\p d -> fmap (retag m p) d)+retagData m = Map.mapWithKey (\p d -> Map.map (retag m p) d)  instance Provider Figment where   metadata _ = named "Figment"-  provide _ fig = fmap loadedData <$> load fig+  -- A nested figment that sets no limits of its own is read with the+  -- limits of the figment that contains it, so tightening the outer limits+  -- also constrains every figment nested inside it.+  provide lim fig = fmap loadedData <$> load fig {figLimitsOpt = Last (Just (fromMaybe lim (getLast (figLimitsOpt fig))))}   providerProfile = getLast . figSelect  -- | The configuration of the selected profile: 'Default', then the -- selected profile, then 'Global', each merged over the previous. selected :: Loaded -> Value-selected l =-  let get p = Map.findWithDefault Map.empty p (loadedData l)-      prof = loadedProfile l+selected = loadedView++selectView :: Profile -> Map Profile Dict -> Value+selectView prof dat =+  let get p = Map.findWithDefault Map.empty p dat       base = get Default       withSel = if prof == Default || prof == Global then base else coalesceDict Merge base (get prof)       final = coalesceDict Merge withSel (get Global)@@ -227,7 +252,7 @@  -- | Choose another profile without re-reading any source. reselect :: Profile -> Loaded -> Loaded-reselect p l = l {loadedProfile = p}+reselect p l = mkLoaded p (loadedData l) (loadedSources l) (loadedLimits l)  -- | Every profile with data. profiles :: Loaded -> [Profile]@@ -248,7 +273,7 @@ -- | Re-root every profile at the given key path (Rust: @focus@). -- Profiles in which the path is absent or not a dictionary become empty. focus :: Path -> Loaded -> Loaded-focus p l = l {loadedData = Map.mapMaybe sub (loadedData l)}+focus p l = mkLoaded (loadedProfile l) (Map.mapMaybe sub (loadedData l)) (loadedSources l) (loadedLimits l)   where     sub d = case lookupPath p (mkValue (Dict d)) of       Just (Value _ (Dict d')) -> Just d'
src/Figment/Decode.hs view
@@ -47,22 +47,26 @@     -- * Magic types   , Tagged (..)   , taggedMetadata+  , Secret (..)   , RelativePath (..)   , relative     -- * Internals shared with "Figment.Partial"   , missingFieldError   , suggest+  , suggestAt   ) where -import Data.Char (isUpper, toLower)+import Data.Char (isDigit, isLower, isUpper, toLower) import Data.Int (Int16, Int32, Int64, Int8) import Data.Kind (Type)+import Data.List (sortOn) import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.List.NonEmpty as NE import Data.Map.Strict (Map)-import qualified Data.Map.Lazy as LMap import qualified Data.Map.Strict as Map-import Data.Maybe (fromMaybe, mapMaybe)+import Data.Maybe (fromMaybe) import Data.Proxy (Proxy (..))+import Data.Semigroup (sconcat) import Data.Scientific (Scientific) import qualified Data.Scientific as Sci import Data.Sequence (Seq)@@ -75,6 +79,7 @@ import Data.Time.Format.ISO8601 (ISO8601, iso8601ParseM) import Data.Vector (Vector) import qualified Data.Vector as Vector+import qualified Data.Vector.Unboxed as U import Data.Word (Word16, Word32, Word64, Word8) import GHC.Generics import GHC.TypeLits (ErrorMessage (..), TypeError)@@ -243,10 +248,10 @@       prof = ctxProfile c       ways = [ "`" <> interpolate m prof p <> "` in " <> metaName m <> maybe "" ((" " <>) . renderSource) (metaSource m)              | m <- ctxSources c ]-      hint = case ways of-        [] -> []-        [w] -> ["no source sets it; it can be set as " <> w]-        _ -> ["no source sets it; it can be set as " <> Text.intercalate ", " (init ways) <> ", or " <> last ways]+      hint = case NE.nonEmpty ways of+        Nothing -> []+        Just (w :| []) -> ["no source sets it; it can be set as " <> w]+        Just ws -> ["no source sets it; it can be set as " <> Text.intercalate ", " (NE.init ws) <> ", or " <> NE.last ws]   in ConfigError (MissingField name) p (Just prof) Nothing Nothing hint  ------------------------------------------------------------------------@@ -270,7 +275,18 @@  instance FromConfigKey Text where fromConfigKey = Right instance FromConfigKey [Char] where fromConfigKey = Right . Text.unpack+instance FromConfigKey Int where fromConfigKey = integralKey+instance FromConfigKey Integer where fromConfigKey = integralKey +integralKey :: Integral a => Text -> Either Text a+integralKey t = case Text.unpack t of+  ('-' : ds) | validDigits ds -> Right (negate (digits ds))+  ds | validDigits ds -> Right (digits ds)+  _ -> Left "an integer key"+  where+    validDigits ds = not (Prelude.null ds) && length ds <= 18 && all isDigit ds+    digits = foldl (\a d -> a * 10 + fromIntegral (fromEnum d - 48)) 0+ ------------------------------------------------------------------------ -- Scalars @@ -320,14 +336,35 @@  unboundedInteger :: Decoder Integer unboundedInteger = decodeIntegral $ \s ->-  if Sci.base10Exponent s > 4096+  if tooManyDigits s     then Left "an integer with at most ~4096 digits"     else Right (truncate s) +-- | Does the integral value have more than about 4096 decimal digits?+-- Checks the coefficient as well as the exponent, so a long literal such+-- as a megabyte of digits is rejected like @1e5000@ is.+tooManyDigits :: Scientific -> Bool+tooManyDigits s =+  e > 4096+    || abs c >= digitsLimit+    || (e > 0 && abs c * 10 ^ e >= digitsLimit)+  where+    e = Sci.base10Exponent s+    c = Sci.coefficient s++digitsLimit :: Integer+digitsLimit = 10 ^ (4096 :: Int)+ realFloatD :: RealFloat a => Decoder a realFloatD = Decoder $ \c v -> case unDecoder (numberD "a number") c v of   Failure e -> Failure e-  Success (Finite s) -> Success (Sci.toRealFloat s)+  Success (Finite s)+    -- a finite literal that overflows the target type is an error, not a+    -- silent infinity+    | isInfinite x -> valueError c v "a number within the range of the type"+    | otherwise -> Success x+    where+      x = Sci.toRealFloat s   Success PosInfinity -> Success (1 / 0)   Success NegInfinity -> Success (-1 / 0)   Success NaN -> Success (0 / 0)@@ -338,8 +375,9 @@  instance FromConfig Char where   fromConfig = Decoder $ \c v -> case unDecoder textual c v of-    Success t | Text.length t == 1 -> Success (Text.head t)-    Success _ -> valueError c v "a single character"+    Success t+      | Just (ch, rest) <- Text.uncons t, Text.null rest -> Success ch+      | otherwise -> valueError c v "a single character"     Failure e -> Failure e   listDecoder = Text.unpack <$> textual @@ -444,7 +482,7 @@ isoD :: ISO8601 t => Text -> Decoder t isoD what = Decoder $ \c v -> case unDecoder textual c v of   Failure e -> Failure e-  Success t -> case iso8601ParseM (Text.unpack (Text.strip t)) of+  Success t -> case iso8601ParseM (spaceToT (Text.strip t)) of     Just x -> Success x     Nothing -> valueError c v ("an ISO 8601 " <> what) @@ -456,13 +494,57 @@   fromConfig = Decoder $ \c v -> case unDecoder textual c v of     Failure e -> Failure e     Success t ->-      let s = Text.unpack (Text.strip t)-      in case (iso8601ParseM s, iso8601ParseM s) of-           (Just z, _) -> Success (zonedTimeToUTC z)-           (_, Just u) -> Success u-           _ -> valueError c v "an ISO 8601 date-time with offset"+      let s = spaceToT (Text.strip t)+      in case iso8601ParseM s of+           Just z -> Success (zonedTimeToUTC z)+           Nothing -> case iso8601ParseM s of+             Just u -> Success u+             Nothing -> valueError c v "an ISO 8601 date-time with offset" +-- | RFC 3339 allows a space where ISO 8601 has the @T@ separator+-- (@2024-01-02 03:04:05@). Only a space directly after a @yyyy-mm-dd@ date+-- is replaced.+spaceToT :: Text -> String+spaceToT t = case Text.splitAt 10 t of+  (d, rest)+    | Just (' ', time) <- Text.uncons rest+    , not (Text.null time)+    , isDate (Text.unpack d) -> Text.unpack d <> "T" <> Text.unpack time+  _ -> Text.unpack t+  where+    isDate [y1, y2, y3, y4, '-', m1, m2, '-', d1, d2] = all isDigit [y1, y2, y3, y4, m1, m2, d1, d2]+    isDate _ = False+ ------------------------------------------------------------------------+-- Secrets++-- | A value that must never appear in a report. Decoding failures name+-- the expected type but never quote what was found, and 'Show' prints a+-- placeholder. Use it for passwords, tokens and keys:+--+-- > data Db = Db { host :: Text, password :: Secret Text }+newtype Secret a = Secret {revealSecret :: a}+  deriving newtype (Eq)++instance Show (Secret a) where+  showsPrec _ _ = showString "Secret <redacted>"++instance FromConfig a => FromConfig (Secret a) where+  fromConfig = Decoder $ \c v -> case unDecoder (fromConfig :: Decoder a) c v of+    Success a -> Success (Secret a)+    Failure es -> Failure (redact es)+    where+      redact es = case map (single . hide) (errorList es) of+        x : xs -> foldl (<>) x xs+        [] -> es+      hide e = e {errorKind = hideKind (errorKind e)}+      hideKind = \case+        InvalidType _ ex -> InvalidType "a hidden value" ex+        InvalidValue _ ex -> InvalidValue "a hidden value" ex+        Message _ -> Message "invalid secret value"+        k -> k++------------------------------------------------------------------------ -- Magic types  -- | A value together with its provenance: which provider, which@@ -535,13 +617,27 @@ kebabCase :: String -> String kebabCase = separate '-' +-- | Insert the separator at word boundaries: before an uppercase letter+-- that follows a lowercase letter or digit, and before the last capital of+-- an acronym that is followed by a lowercase letter. @dbURL@ becomes+-- @db_url@, @HTTPServer@ becomes @http_server@, @useHTTPS@ becomes+-- @use_https@. separate :: Char -> String -> String-separate sep = go True+separate sep = go Nothing   where     go _ [] = []-    go start (c : cs)-      | isUpper c = (if start then [] else [sep]) ++ toLower c : go False cs-      | otherwise = c : go False cs+    go prev (c : cs)+      | isUpper c = [sep | boundary] ++ toLower c : go (Just c) cs+      | otherwise = c : go (Just c) cs+      where+        boundary = case prev of+          Nothing -> False+          Just p+            | isLower p || isDigit p -> True+            | isUpper p -> case cs of+                (n : _) -> isLower n+                [] -> False+            | otherwise -> False  -- | Derive a decoder from a 'Generic' instance: records are dictionaries, enums are strings (matched case-insensitively), other sums are externally tagged (@{ Variant = payload }@), newtypes unwrap, positional constructors are arrays. genericDecoder :: (Generic a, GDecode (Rep a)) => Options -> Decoder a@@ -631,51 +727,86 @@ recordD :: Options -> [Text] -> (DecodeContext -> Dict -> Result a) -> Decoder a recordD o known fields = Decoder $ \c v -> case valueNode v of   Dict m ->-    let unknownErrs =-          [ errorAt c {ctxPath = ctxPath c /. k} x (UnknownField k (suggest k known))-          | rejectUnknownFields o-          , (k, x) <- Map.toList m-          , k `notElem` known+    let knownSet = Set.fromList known+        unknown = [kv | rejectUnknownFields o, kv@(k, _) <- Map.toList m, not (k `Set.member` knownSet)]+        unknownErrs =+          [ errorAt c {ctxPath = ctxPath c /. k} x (UnknownField k (suggestAt i k known))+          | (i, (k, x)) <- zip [0 ..] unknown           ]-        unknownR = case unknownErrs of-          [] -> Success ()-          (e : es) -> Failure (foldl (<>) e es)-    in unknownR *> fields c m+        unknownR = case NE.nonEmpty unknownErrs of+          Nothing -> Success ()+          Just es -> Failure (sconcat es)+     in unknownR *> fields c m   _ -> typeError c v "a dictionary"  -- | Candidates within a small edit distance, best first.+--+-- Suggestions are a courtesy, so their cost is bounded: keys longer than+-- 'maxSuggestLength' get none, and candidates whose length differs too much+-- to be within range are skipped without computing a distance. suggest :: Text -> [Text] -> [Text]-suggest k known =-  let scored = mapMaybe (\cand -> let d = editDistance (Text.unpack k) (Text.unpack cand)-                                  in if d <= max 1 (Text.length cand `div` 3) then Just (d, cand) else Nothing) known-  in map snd (take 3 (sortOn' fst scored))+suggest k known+  | Text.compareLength k maxSuggestLength == GT = []+  | otherwise = map snd (take 3 (sortOn fst scored))   where-    sortOn' f = foldr ins []-      where ins x [] = [x]-            ins x (y : ys) | f x <= f y = x : y : ys-                           | otherwise = y : ins x ys+    lk = Text.length k+    scored =+      [ (d, cand)+      | cand <- known+      , let lc = Text.length cand+            limit = max 1 (lc `div` 3)+      , abs (lk - lc) <= limit -- the distance is at least the length difference+      , let d = editDistance k cand+      , d <= limit+      ] +-- | 'suggest' for the @i@th unknown key of a record (counting from 0). Only+-- the first 'suggestionBudget' unknown keys receive suggestions, so a+-- document full of typos costs a bounded amount of work to report.+suggestAt :: Int -> Text -> [Text] -> [Text]+suggestAt i k known+  | i >= suggestionBudget = []+  | otherwise = suggest k known++-- | Longest key (in characters) that is compared against field names.+maxSuggestLength :: Int+maxSuggestLength = 64++-- | How many unknown keys per record are given suggestions.+suggestionBudget :: Int+suggestionBudget = 32+ -- | Optimal string alignment distance (Levenshtein plus adjacent--- transpositions, so @hots@ is one edit from @host@).-editDistance :: String -> String -> Int-editDistance a b = table LMap.! (la, lb)+-- transpositions, so @hots@ is one edit from @host@). Runs in+-- O(length a * length b) time and O(length b) space: one unboxed row at a+-- time, never the whole table.+editDistance :: Text -> Text -> Int+editDistance a b+  | la == 0 = lb+  | lb == 0 = la+  | otherwise = U.last (snd (foldl' step (row0, row0) [1 .. la]))   where-    la = length a-    lb = length b-    av = Vector.fromList a-    bv = Vector.fromList b-    table = LMap.fromList [((i, j), cell i j) | i <- [0 .. la], j <- [0 .. lb]]-    get i j = table LMap.! (i, j)-    cell i 0 = i-    cell 0 j = j-    cell i j =-      let ca = av Vector.! (i - 1)-          cb = bv Vector.! (j - 1)-          cost = if ca == cb then 0 else 1-          base = minimum [get (i - 1) j + 1, get i (j - 1) + 1, get (i - 1) (j - 1) + cost]-      in if i > 1 && j > 1 && ca == bv Vector.! (j - 2) && av Vector.! (i - 2) == cb-           then min base (get (i - 2) (j - 2) + 1)-           else base+    av = U.fromList (Text.unpack a) :: U.Vector Char+    bv = U.fromList (Text.unpack b) :: U.Vector Char+    la = U.length av+    lb = U.length bv+    row0 = U.enumFromN 0 (lb + 1) :: U.Vector Int++    -- (row i-2, row i-1) -> (row i-1, row i)+    step (!prev2, !prev1) i = (prev1, cur)+      where+        ca = av U.! (i - 1)+        cur = U.constructN (lb + 1) cell+        cell built+          | j == 0 = i+          | i > 1 && j > 1 && ca == bv U.! (j - 2) && av U.! (i - 2) == cb =+              min base (prev2 U.! (j - 2) + 1)+          | otherwise = base+          where+            j = U.length built+            cb = bv U.! (j - 1)+            cost = if ca == cb then 0 else 1+            base = minimum [prev1 U.! j + 1, built U.! (j - 1) + 1, prev1 U.! (j - 1) + cost]  class GFields (f :: Type -> Type) where   gfields :: Options -> DecodeContext -> Dict -> Result (f x)
src/Figment/Error.hs view
@@ -28,6 +28,7 @@ import qualified Data.Text as Text import GHC.Generics (Generic) +import Figment.Internal.Text (escapeControl) import Figment.Metadata import Figment.Path import Figment.Profile@@ -43,6 +44,9 @@     -- ^ nesting deeper than the configured limit (the limit is carried)   | TooManyNodes !Int     -- ^ more values than the configured limit (the limit is carried)+  | TooManyBytes !Int+    -- ^ a source larger than the configured size limit (the limit, in+    -- bytes, is carried)   | DuplicateKey !Text     -- ^ the same key appears twice in one dictionary of one source   | KeyConflict !Text !Text@@ -131,22 +135,23 @@ -- | The one-line description of an error kind. describeKind :: ErrorKind -> Text describeKind = \case-  IoError t -> "could not read source: " <> t-  SyntaxError t -> "syntax error: " <> t+  IoError t -> "could not read source: " <> escapeControl t+  SyntaxError t -> "syntax error: " <> escapeControl t   DepthExceeded n -> "nesting exceeds the depth limit of " <> tshow n   TooManyNodes n -> "source contains more than the limit of " <> tshow n <> " values"+  TooManyBytes n -> "source is larger than the limit of " <> tshow n <> " bytes"   DuplicateKey k -> "duplicate key " <> tick k   KeyConflict a b -> tick a <> " conflicts with " <> tick b     <> ": one sets a value where the other needs a dictionary"-  InvalidType actual expected -> "invalid type: found " <> actual <> ", expected " <> expected-  InvalidValue actual expected -> "invalid value: found " <> actual <> ", expected " <> expected-  InvalidLength n expected -> "invalid length " <> tshow n <> ", expected " <> expected+  InvalidType actual expected -> "invalid type: found " <> escapeControl actual <> ", expected " <> escapeControl expected+  InvalidValue actual expected -> "invalid value: found " <> escapeControl actual <> ", expected " <> escapeControl expected+  InvalidLength n expected -> "invalid length " <> tshow n <> ", expected " <> escapeControl expected   MissingField f -> "missing field " <> tick f   UnknownField f _ -> "unknown field " <> tick f   UnknownVariant v valid -> "unknown variant " <> tick v <> ", expected one of "     <> Text.intercalate ", " (map tick valid)-  Message t -> t-  InvalidArgument t -> "invalid argument: " <> t+  Message t -> escapeControl t+  InvalidArgument t -> "invalid argument: " <> escapeControl t  -- | A multi-line, human-oriented rendering: --@@ -158,7 +163,7 @@   Text.intercalate "\n" $     ("error: " <> describeKind (errorKind e))       : location-      ++ map ("  = hint: " <>) (suggestions ++ errorHints e)+      ++ map (("  = hint: " <>) . escapeControl) (suggestions ++ errorHints e)   where     suggestions = case errorKind e of       UnknownField _ (s : ss) -> ["did you mean " <> Text.intercalate " or " (map tick (s : ss)) <> "?"]@@ -175,8 +180,8 @@       _ -> ""     sourcePart = case errorMetadata e of       Nothing -> ""-      Just m -> " in " <> metaName m <> case metaSource m of-        Just s -> " " <> renderSource s <> posSuffix+      Just m -> " in " <> escapeControl (metaName m) <> case metaSource m of+        Just s -> " " <> escapeControl (renderSource s) <> posSuffix         Nothing -> posWords     posSuffix = case errorPos e of       Just (Pos l c) -> ":" <> tshow l <> ":" <> tshow c@@ -192,15 +197,30 @@       in ["  --> " <> line]  -- | Render every error, separated by blank lines, with a count header--- when there is more than one.+-- when there is more than one. At most 'renderLimit' errors are shown,+-- followed by the number that were left out, so a pathological source+-- cannot produce an unreadable (or enormous) report. renderErrors :: ConfigErrors -> Text renderErrors (ConfigErrors (e :| [])) = renderError e renderErrors (ConfigErrors es) =   tshow (length es) <> " configuration errors:\n\n"-    <> Text.intercalate "\n\n" (map renderError (NE.toList es))+    <> Text.intercalate "\n\n" (map renderError shown)+    <> omitted+  where+    (shown, rest) = splitAt renderLimit (NE.toList es)+    omitted+      | null rest = ""+      | otherwise = "\n\n... and " <> tshow (length rest) <> " more errors not shown" +-- | The most errors 'renderErrors' prints.+renderLimit :: Int+renderLimit = 100++-- | Quote a piece of data for a message. Control characters are escaped, so+-- a key or file name chosen by someone else cannot forge extra lines or+-- terminal escape sequences in a report. tick :: Text -> Text-tick t = "`" <> t <> "`"+tick t = "`" <> escapeControl t <> "`"  tshow :: Show a => a -> Text tshow = Text.pack . show
src/Figment/Internal/Budget.hs view
@@ -9,8 +9,12 @@   , enterContainer   , throwB   , askLimits+  , checkBytes   ) where +import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+ import Figment.Error import Figment.Limits import Figment.Metadata (Pos)@@ -60,3 +64,9 @@   if depth > maxDepth l     then Left (withPos pos (atPath p (configError (DepthExceeded (maxDepth l)))))     else Right ((), n)++-- | Reject a source larger than 'maxBytes' before anything is parsed.+checkBytes :: Limits -> ByteString -> Either ConfigError ()+checkBytes lim bs+  | BS.length bs > maxBytes lim = Left (configError (TooManyBytes (maxBytes lim)))+  | otherwise = Right ()
src/Figment/Internal/Nest.hs view
@@ -31,7 +31,7 @@   let (tree, errs) = foldl' step (Map.empty, []) entries   in case fromErrorList (reverse errs) of        Just es -> Left es-       Nothing -> Right (fmap toValue tree)+       Nothing -> Right (Map.map toValue tree)   where     step (tree, errs) (name, ks, v) = case insert root name ks v tree of       Left e -> (tree, e : errs)@@ -57,4 +57,4 @@         Left (atPath (path /. k) (configError (KeyConflict other name)))      toValue (Leaf _ v) = v-    toValue (Branch _ m) = mkValue (Dict (fmap toValue m))+    toValue (Branch _ m) = mkValue (Dict (Map.map toValue m))
+ src/Figment/Internal/Number.hs view
@@ -0,0 +1,35 @@+-- | Fast conversion of long digit strings to 'Integer'.+--+-- @read@ and @Numeric.readHex@ fold digit by digit, which is quadratic+-- in the number of digits; a configuration source can legitimately be+-- tens of megabytes of digits in a single scalar. Splitting the text in+-- halves lets GMP's sub-quadratic multiplication do the work.+module Figment.Internal.Number+  ( integerFromDigits+  ) where++import Data.Char (digitToInt)+import Data.Text (Text)+import qualified Data.Text as Text++-- | @integerFromDigits base digits@ for @base@ 8, 10 or 16. The caller+-- guarantees every character is a digit of the base (as checked with+-- 'Data.Char.isDigit', 'Data.Char.isOctDigit' or 'Data.Char.isHexDigit').+-- The empty text is 0.+integerFromDigits :: Int -> Text -> Integer+integerFromDigits base = go+  where+    b = toInteger base+    -- digits that always fit in an Int (< 2^62)+    chunk = case base of+      16 -> 15+      8 -> 20+      _ -> 18+    small = toInteger . Text.foldl' (\acc c -> acc * base + digitToInt c) (0 :: Int)+    go t+      | Text.compareLength t chunk /= GT = small t+      | otherwise =+          let n = Text.length t+              h = n `div` 2+              (hi, lo) = Text.splitAt h t+           in go hi * b ^ (n - h) + go lo
+ src/Figment/Internal/Text.hs view
@@ -0,0 +1,64 @@+-- | Text helpers shared by the error renderer, key paths and the+-- environment/command-line providers.+--+-- Everything figment prints about a configuration source (keys, file+-- names, variant names) is data that may have been written by someone+-- else. 'escapeControl' makes sure such data can never forge extra lines+-- or terminal escape sequences in a rendered report.+module Figment.Internal.Text+  ( needsEscape+  , escapeChar+  , escapeControl+  , isUndecodable+  , stripBom+  ) where++import Data.Char (isControl, ord)+import Data.Text (Text)+import qualified Data.Text as Text+import Numeric (showHex)++-- | Characters that must never appear raw in a rendered message: control+-- characters (including newline, escape, DEL and the C1 range), the Unicode+-- line and paragraph separators, and the bidirectional overrides and+-- isolates used for "trojan source" style spoofing.+needsEscape :: Char -> Bool+needsEscape c =+  isControl c+    || c == '\x2028'+    || c == '\x2029'+    || (c >= '\x202A' && c <= '\x202E')+    || (c >= '\x2066' && c <= '\x2069')+    || (c >= '\x200B' && c <= '\x200F') -- zero-width space/joiners, LRM, RLM+    || (c >= '\x2060' && c <= '\x2064') -- word joiner, invisible operators+    || c == '\x061C' -- Arabic letter mark+    || c == '\xFEFF' -- zero-width no-break space / BOM++-- | The escaped spelling of one character: @\\n@, @\\r@, @\\t@, otherwise+-- @\\u{hex}@. Total on every 'Char'.+escapeChar :: Char -> Text+escapeChar = \case+  '\n' -> "\\n"+  '\r' -> "\\r"+  '\t' -> "\\t"+  c -> "\\u{" <> Text.pack (showHex (ord c) "") <> "}"++-- | Replace every 'needsEscape' character by its escaped spelling.+-- Returns the argument unchanged (no copy) when nothing needs escaping.+escapeControl :: Text -> Text+escapeControl t+  | Text.any needsEscape t = Text.concatMap (\c -> if needsEscape c then escapeChar c else Text.singleton c) t+  | otherwise = t++-- | GHC decodes bytes that are not valid in the locale encoding (for+-- environment variables and arguments) into the range U+DC80..U+DCFF.+-- 'Data.Text.pack' would silently turn those into U+FFFD, so callers use+-- this predicate to reject such input instead of corrupting it.+isUndecodable :: Char -> Bool+isUndecodable c = c >= '\xDC80' && c <= '\xDCFF'++-- | Drop one leading byte-order mark, if present.+stripBom :: Text -> Text+stripBom t = case Text.uncons t of+  Just ('\xFEFF', r) -> r+  _ -> t
+ src/Figment/Internal/TomlScan.hs view
@@ -0,0 +1,109 @@+-- | A linear pre-scan that rejects absurdly nested TOML before the+-- (non-streaming) TOML parser is asked to build it.+--+-- toml-parser parses a whole document into a syntax tree before figment+-- sees a single value, so a megabyte of @[[[[...@ would be fully built+-- before the depth limit could apply. This scan counts unclosed @[@ and+-- @{@ outside strings and comments in O(n) time and O(1) space.+module Figment.Internal.TomlScan+  ( bracketOverflow+  , Overflow (..)+  , scanOverflow+  ) where++import Data.Text (Text)+import qualified Data.Text as Text++import Figment.Metadata (Pos (..))++data Mode+  = Normal+  | Comment+  | Basic -- ^ @"…"@+  | Literal -- ^ @'…'@+  | MultiBasic -- ^ @"""…"""@+  | MultiLiteral -- ^ @'''…'''@++-- | @bracketOverflow limit text@ is the position of the first @[@ or @{@+-- that raises the bracket nesting above @limit@, if any. Brackets inside+-- strings and comments do not count. Table headers (@[a]@, @[[a]]@) count+-- like any other bracket while they are open, so callers should pass the+-- depth limit plus two to avoid rejecting valid documents.+bracketOverflow :: Int -> Text -> Maybe Pos+bracketOverflow limit txt = snd <$> scanOverflow limit maxBound txt++-- | Why a document was rejected before parsing.+data Overflow = TooDeep | TooBig+  deriving stock (Eq, Show)++-- | @scanOverflow depthLimit tokenLimit text@: like 'bracketOverflow', and+-- also rejects a document with more than @tokenLimit@ structural characters+-- (@=@, @,@, @[@, @{@, @.@) outside strings and comments. Every value in a+-- TOML document needs at least one such character per five values it+-- creates, so a limit of @5 * maxNodes@ never rejects a document that the+-- node budget would accept, but stops a huge document before toml-parser+-- builds its whole syntax tree.+scanOverflow :: Int -> Int -> Text -> Maybe (Overflow, Pos)+scanOverflow limit tokLimit txt = go Normal 0 0 0 txt+  where+    go :: Mode -> Int -> Int -> Int -> Text -> Maybe (Overflow, Pos)+    go !mode !depth !toks !off t = case Text.uncons t of+      Nothing -> Nothing+      Just (c, rest) -> case mode of+        Normal -> case c of+          '#' -> go Comment depth toks (off + 1) rest+          '"'+            | "\"\"" `Text.isPrefixOf` rest -> go MultiBasic depth toks (off + 3) (Text.drop 2 rest)+            | otherwise -> go Basic depth toks (off + 1) rest+          '\''+            | "''" `Text.isPrefixOf` rest -> go MultiLiteral depth toks (off + 3) (Text.drop 2 rest)+            | otherwise -> go Literal depth toks (off + 1) rest+          _+            | c == '[' || c == '{' ->+                if depth + 1 > limit+                  then Just (TooDeep, posAt off)+                  else tok (depth + 1)+            | c == ']' || c == '}' -> go Normal (max 0 (depth - 1)) toks (off + 1) rest+            | c == '=' || c == ',' || c == '.' -> tok depth+            | otherwise -> go Normal depth toks (off + 1) rest+            where+              tok d'+                | toks + 1 > tokLimit = Just (TooBig, posAt off)+                | otherwise = go Normal d' (toks + 1) (off + 1) rest+        Comment+          | c == '\n' -> go Normal depth toks (off + 1) rest+          | otherwise -> go Comment depth toks (off + 1) rest+        Basic -> case c of+          '\\' -> go Basic depth toks (off + 1 + skipped rest) (Text.drop 1 rest)+          '"' -> go Normal depth toks (off + 1) rest+          '\n' -> go Normal depth toks (off + 1) rest -- unterminated: the real parser reports it+          _ -> go Basic depth toks (off + 1) rest+        Literal -> case c of+          '\'' -> go Normal depth toks (off + 1) rest+          '\n' -> go Normal depth toks (off + 1) rest+          _ -> go Literal depth toks (off + 1) rest+        MultiBasic -> case c of+          '\\' -> go MultiBasic depth toks (off + 1 + skipped rest) (Text.drop 1 rest)+          '"'+            | "\"\"" `Text.isPrefixOf` rest ->+                -- the closing delimiter may be preceded by up to two content quotes+                let after = Text.drop 2 rest+                    k = Text.length (Text.takeWhile (== '"') (Text.take 2 after))+                 in go Normal depth toks (off + 3 + k) (Text.drop k after)+          _ -> go MultiBasic depth toks (off + 1) rest+        MultiLiteral -> case c of+          '\''+            | "''" `Text.isPrefixOf` rest ->+                let after = Text.drop 2 rest+                    k = Text.length (Text.takeWhile (== '\'') (Text.take 2 after))+                 in go Normal depth toks (off + 3 + k) (Text.drop k after)+          _ -> go MultiLiteral depth toks (off + 1) rest++    -- an escape consumes the next character too (if there is one)+    skipped r = if Text.null r then 0 else 1++    posAt off =+      let before = Text.take off txt+          line = 1 + Text.count "\n" before+          col = 1 + Text.length (snd (Text.breakOnEnd "\n" before))+       in Pos line col
src/Figment/Internal/ValueParser.hs view
@@ -19,7 +19,7 @@   , parseNumber   ) where -import Data.Char (isDigit, isSpace)+import Data.Char (isDigit, isHexDigit, isSpace) import qualified Data.Map.Strict as Map import Data.Scientific (scientific) import Data.Text (Text)@@ -27,6 +27,7 @@ import qualified Data.Vector as Vector  import Figment.Error+import Figment.Internal.Number (integerFromDigits) import Figment.Limits import Figment.Value @@ -34,23 +35,34 @@ -- nested beyond the depth limit; any syntax problem falls back to the -- string. parseValue :: Limits -> Text -> Either ConfigError Value-parseValue lim raw = case top of-  Left (Limit e) -> Left e-  Left NoParse -> Right (rawTagged (String raw))-  Right n -> Right (rawTagged n)+parseValue lim raw+  | Text.compareLength raw (maxBytes lim) == GT = Left (configError (TooManyBytes (maxBytes lim)))+  | otherwise = case top of+      Left (Limit e) -> Left e+      Left NoParse -> Right (rawTagged (String raw))+      Right n+        | countNodes n > maxNodes lim -> Left (configError (TooManyNodes (maxNodes lim)))+        | otherwise -> Right (rawTagged n)   where     trimmed = Text.strip raw     rawTagged n = Value untagged {tagRaw = Just raw} n-    top-      | Text.null trimmed = Right (String raw)-      | otherwise = case Text.head trimmed of-          c | c == '[' || c == '{' || c == '"' || c == '\'' ->-                case structured lim 1 trimmed of-                  Right (v, rest) | Text.null (Text.strip rest) -> Right (valueNode v)-                  Right _ -> Left NoParse-                  Left e -> Left e-          _ -> Right (scalarNode raw trimmed)+    top = case Text.uncons trimmed of+      Nothing -> Right (String raw)+      Just (c, _)+        | c == '[' || c == '{' || c == '"' || c == '\'' ->+            case structured lim 1 trimmed of+              Right (v, rest) | Text.null (Text.strip rest) -> Right (valueNode v)+              Right _ -> Left NoParse+              Left e -> Left e+        | otherwise -> Right (scalarNode raw trimmed) +-- | The number of values in a node (itself included).+countNodes :: Node -> Int+countNodes = \case+  Array xs -> 1 + sum (Vector.map (countNodes . valueNode) xs)+  Dict m -> 1 + sum (Map.map (countNodes . valueNode) m)+  _ -> 1+ data Failure = NoParse | Limit ConfigError  -- | A bare scalar: boolean, number, or the text itself.@@ -72,8 +84,9 @@   Just ('{', rest) -> do     guardDepth     (kvs, rest') <- pairs rest-    pure (mkValue (Dict (Map.fromList kvs)), rest')-  Just ('"', rest) -> first' string (quotedDouble "" rest)+    d <- uniqueKeys kvs+    pure (mkValue (Dict d), rest')+  Just ('"', rest) -> first' string (quotedDouble [] rest)   Just ('\'', rest) -> first' string (quotedSingle rest)   Just _ ->     let (tok, rest) = Text.break (`elem` (",]}" :: String)) t@@ -129,26 +142,58 @@             _ -> Left NoParse      key s = case Text.uncons (Text.stripStart s) of-      Just ('"', rest) -> quotedDouble "" rest+      Just ('"', rest) -> quotedDouble [] rest       Just ('\'', rest) -> quotedSingle rest       _ ->         let (k, rest) = Text.span (\c -> not (isSpace c) && c `notElem` ("=:,{}[]" :: String)) (Text.stripStart s)         in if Text.null k then Left NoParse else Right (k, rest) +    -- a duplicate key is reported, as in every file format+    uniqueKeys = go Map.empty+      where+        go m [] = Right m+        go m ((k, v) : more)+          | Map.member k m = Left (Limit (configError (DuplicateKey k)))+          | otherwise = go (Map.insert k v m) more+     first' f r = fmap (\(a, rest) -> (f a, rest)) r -quotedDouble :: Text -> Text -> P Text-quotedDouble acc s = case Text.uncons s of-  Nothing -> Left NoParse-  Just ('"', rest) -> Right (acc, rest)-  Just ('\\', rest) -> case Text.uncons rest of-    Just (c, rest') -> case c of-      'n' -> quotedDouble (Text.snoc acc '\n') rest'-      't' -> quotedDouble (Text.snoc acc '\t') rest'-      'r' -> quotedDouble (Text.snoc acc '\r') rest'-      _ -> quotedDouble (Text.snoc acc c) rest'-    Nothing -> Left NoParse-  Just (c, rest) -> quotedDouble (Text.snoc acc c) rest+-- | The body of a double-quoted string, after the opening quote. Runs+-- without escapes are sliced, not appended character by character: the+-- accumulator is a list of chunks, so the whole parse is linear in the+-- length of the input.+quotedDouble :: [Text] -> Text -> P Text+quotedDouble acc s =+  let (chunk, rest) = Text.break (\c -> c == '"' || c == '\\') s+      -- continue after an escape, having produced the text @e@+      next e more = quotedDouble (e : chunk : acc) more+      unicode n r =+        let (hex, more) = Text.splitAt n r+            code = integerFromDigits 16 hex+            ok = Text.length hex == n && Text.all isHexDigit hex+         in if ok && code <= 0x10FFFF && not (code >= 0xD800 && code <= 0xDFFF)+              then next (Text.singleton (toEnum (fromInteger code))) more+              else Left NoParse+   in case Text.uncons rest of+        Just ('"', rest') -> Right (Text.concat (reverse (chunk : acc)), rest')+        Just (_, rest') -> case Text.uncons rest' of -- a backslash+          Just ('u', r) -> unicode 4 r+          Just ('U', r) -> unicode 8 r+          Just (c, rest'') -> case simpleEscape c of+            Just e -> next e rest''+            Nothing -> Left NoParse -- unknown escape: not a valid string+          Nothing -> Left NoParse+        Nothing -> Left NoParse+  where+    simpleEscape = \case+      'n' -> Just "\n"+      't' -> Just "\t"+      'r' -> Just "\r"+      'b' -> Just "\b"+      'f' -> Just "\f"+      '"' -> Just "\""+      '\\' -> Just "\\"+      _ -> Nothing  quotedSingle :: Text -> P Text quotedSingle s =@@ -188,8 +233,8 @@               _ -> (1, r)         in if Text.null ds || not (Text.all isDigit ds) || Text.length ds > 9              then Nothing-             else Just (sgn * read (Text.unpack ds) :: Int)+             else Just (sgn * fromInteger (integerFromDigits 10 ds) :: Int)       _ -> Nothing-    let coeff = read (Text.unpack (intPart <> fracPart)) :: Integer+    let coeff = integerFromDigits 10 (intPart <> fracPart)         signed = if neg then negate coeff else coeff     pure (Finite (scientific signed (expo - Text.length fracPart)))
src/Figment/Jail.hs view
@@ -6,6 +6,12 @@ -- and the environment are process-global), so jailed tests are safe -- under a parallel test runner. Tests that do not use a jail should not -- touch the working directory or the environment.+--+-- The t'Jail' handle is only valid inside the 'withJail' that created it:+-- using it afterwards, or starting a jail from inside a jail on the same+-- thread (which could never acquire the lock), throws an 'IOError' with an+-- explanation instead of misbehaving or hanging. Paths given to+-- 'createFile' and friends must stay inside the jail. module Figment.Jail   ( Jail   , withJail@@ -19,77 +25,131 @@   , clearEnv   ) where +import Control.Concurrent (ThreadId, myThreadId) import Control.Concurrent.MVar (MVar, newMVar, withMVar)-import Control.Exception (bracket, bracket_)+import Control.Exception (bracket, bracket_, finally, throwIO)+import Control.Monad (unless, when) import qualified Data.ByteString as BS+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.List (isPrefixOf)+import qualified Data.Map.Strict as Map import Data.Text (Text) import qualified Data.Text.Encoding as TE import System.Directory (createDirectoryIfMissing, getCurrentDirectory, setCurrentDirectory) import qualified System.Environment as Env-import System.FilePath (takeDirectory, (</>))+import qualified System.Environment.Blank as Blank+import System.FilePath (splitDirectories, takeDirectory, (</>)) import System.IO.Temp (withSystemTempDirectory) import System.IO.Unsafe (unsafePerformIO)  -- | A handle on the running jail.-newtype Jail = Jail+data Jail = Jail   { jailDirectory :: FilePath     -- ^ the temporary directory (also the working directory)+  , jailAlive :: IORef Bool   } --- The one piece of global state: a lock serialising jails. Standard--- top-level-MVar idiom; NOINLINE guarantees a single MVar.-jailLock :: MVar ()-jailLock = unsafePerformIO (newMVar ())-{-# NOINLINE jailLock #-}+-- The one piece of global state: the lock serialising jails, and the+-- thread that currently holds it (so a nested jail fails fast instead of+-- waiting for itself). Standard top-level idiom; NOINLINE guarantees a+-- single instance.+data Globals = Globals+  { gLock :: MVar ()+  , gHolder :: IORef (Maybe ThreadId)+  } +globals :: Globals+globals = unsafePerformIO (Globals <$> newMVar () <*> newIORef Nothing)+{-# NOINLINE globals #-}+ -- | Run an action in a fresh jail; see the module header. withJail :: (Jail -> IO a) -> IO a-withJail act = withMVar jailLock $ \() ->-  withSystemTempDirectory "figment-jail" $ \dir ->-    bracket Env.getEnvironment restoreEnv $ \_ ->-      bracket getCurrentDirectory setCurrentDirectory $ \_ ->-        bracket_ (setCurrentDirectory dir) (pure ()) (act (Jail dir))+withJail act = do+  me <- myThreadId+  holder <- readIORef (gHolder globals)+  when (holder == Just me) $+    throwIO (userError "Figment.Jail.withJail: jails cannot be nested (this thread is already inside one)")+  withMVar (gLock globals) $ \() ->+    bracket_ (writeIORef (gHolder globals) (Just me)) (writeIORef (gHolder globals) Nothing) $+      withSystemTempDirectory "figment-jail" $ \dir -> do+        alive <- newIORef True+        bracket Env.getEnvironment restoreEnv $ \_ ->+          bracket getCurrentDirectory setCurrentDirectory $ \_ -> do+            setCurrentDirectory dir+            act (Jail dir alive) `finally` writeIORef alive False   where     restoreEnv saved = do-      now <- Env.getEnvironment-      mapM_ (Env.unsetEnv . fst) [kv | kv@(k, _) <- now, k `notElem` map fst saved]-      mapM_ (uncurry Env.setEnv) [kv | kv <- saved, lookup (fst kv) now /= Just (snd kv)]+      now <- Map.fromList <$> Env.getEnvironment+      let before = Map.fromList saved+      mapM_ Env.unsetEnv [k | k <- Map.keys now, not (k `Map.member` before)]+      -- 'Blank.setEnv' (unlike 'Env.setEnv') keeps a variable whose+      -- original value was the empty string instead of unsetting it+      mapM_ (\(k, v) -> Blank.setEnv k v True) [(k, v) | (k, v) <- saved, Map.lookup k now /= Just v] +-- | Fail unless the jail is still running.+live :: Jail -> IO ()+live j = do+  ok <- readIORef (jailAlive j)+  unless ok $ throwIO (userError "Figment.Jail: the Jail handle was used after its withJail returned")++-- | The path inside the jail, refusing anything that would leave it: a+-- relative path may not climb out with @..@, and an absolute path must+-- already be inside the jail directory (as the paths returned by+-- 'createFile' and 'createDirectory' are).+inside :: Jail -> FilePath -> IO FilePath+inside j rel = do+  live j+  let target = jailDirectory j </> rel+      parts = splitDirectories rel+      root = splitDirectories (jailDirectory j)+      -- Judge the path that will actually be used, not the one that was+      -- asked for. '</>' discards the jail directory when @rel@ is rooted+      -- (@/x@, @\\x@, @C:\\x@, @C:x@), and what counts as rooted differs+      -- between platforms: on Windows @/x@ is neither 'isAbsolute' nor does+      -- it have a drive, yet '</>' still treats it as rooted.+      contained = root `isPrefixOf` splitDirectories target+  unless (contained && ".." `notElem` parts) $+    throwIO (userError ("Figment.Jail: path escapes the jail: " ++ rel))+  pure target+ -- | Write a UTF-8 file, relative to the jail directory. createFile :: Jail -> FilePath -> Text -> IO FilePath-createFile (Jail dir) rel contents = do-  let path = dir </> rel+createFile j rel contents = do+  path <- inside j rel   createDirectoryIfMissing True (takeDirectory path)   BS.writeFile path (TE.encodeUtf8 contents)   pure path  -- | Write raw bytes (e.g. deliberately invalid UTF-8). createBinaryFile :: Jail -> FilePath -> BS.ByteString -> IO FilePath-createBinaryFile (Jail dir) rel contents = do-  let path = dir </> rel+createBinaryFile j rel contents = do+  path <- inside j rel   createDirectoryIfMissing True (takeDirectory path)   BS.writeFile path contents   pure path --- | Run an action with another working directory (restored afterwards).+-- | Run an action with another working directory, given relative to the+-- jail directory (restored afterwards). inDirectory :: Jail -> FilePath -> IO a -> IO a-inDirectory _ d act = bracket getCurrentDirectory setCurrentDirectory (\_ -> setCurrentDirectory d >> act)+inDirectory j d act = do+  dir <- inside j d+  bracket getCurrentDirectory setCurrentDirectory (\_ -> setCurrentDirectory dir >> act)  -- | Create a directory (and parents) inside the jail. createDirectory :: Jail -> FilePath -> IO FilePath-createDirectory (Jail dir) rel = do-  let path = dir </> rel+createDirectory j rel = do+  path <- inside j rel   createDirectoryIfMissing True path   pure path  -- | Set an environment variable for the duration of the jail. (As with "System.Environment", setting the empty string unsets it.) setEnv :: Jail -> String -> String -> IO ()-setEnv _ = Env.setEnv+setEnv j k v = live j >> Env.setEnv k v  -- | Unset an environment variable for the duration of the jail. unsetEnv :: Jail -> String -> IO ()-unsetEnv _ = Env.unsetEnv+unsetEnv j k = live j >> Env.unsetEnv k  -- | Remove every environment variable (restored when the jail ends). clearEnv :: Jail -> IO ()-clearEnv _ = Env.getEnvironment >>= mapM_ (Env.unsetEnv . fst)+clearEnv j = live j >> Env.getEnvironment >>= mapM_ (Env.unsetEnv . fst)
src/Figment/Limits.hs view
@@ -2,9 +2,12 @@ module Figment.Limits   ( Limits   , mkLimits+  , withMaxBytes   , defaultLimits+  , defaultMaxBytes   , maxDepth   , maxNodes+  , maxBytes   ) where  import Control.DeepSeq (NFData)@@ -13,28 +16,51 @@  import Figment.Error --- | Bounds enforced /inside/ every parser figment ships (not after the--- fact), so a hostile source is rejected before it can exhaust memory.--- The constructor is hidden: obtain values via 'mkLimits'.+-- | Bounds enforced while a source is read, so that a hostile or+-- accidentally enormous source is rejected before it can exhaust memory.+-- The constructor is hidden: obtain values via 'mkLimits' and+-- 'withMaxBytes'.+--+-- * the size of a source is checked /before/ it is parsed (files are read+--   incrementally and abandoned as soon as they exceed 'maxBytes');+-- * nesting depth and the number of values are checked /while/ the tree is+--   built (JSON, environment and command-line values), or on the parser's+--   intermediate form (TOML, YAML), which is itself bounded by 'maxBytes'. data Limits = Limits   { maxDepth :: !Int     -- ^ maximum container nesting (the root dictionary is depth 1)   , maxNodes :: !Int     -- ^ maximum number of values per source, counting YAML alias     -- expansions (defeats \"billion laughs\")+  , maxBytes :: !Int+    -- ^ maximum size of one source in bytes   }   deriving stock (Eq, Show, Generic)   deriving anyclass (NFData) --- | Both limits must be positive.+-- | Depth and node limits, with the default size limit+-- ('defaultMaxBytes'). Both must be positive; adjust the size with+-- 'withMaxBytes'. mkLimits :: Int -> Int -> Either ConfigError Limits mkLimits d n-  | d <= 0 = Left (bad "maxDepth" d)-  | n <= 0 = Left (bad "maxNodes" n)-  | otherwise = Right (Limits d n)-  where-    bad name v = configError (InvalidArgument (name <> " must be positive, got " <> Text.pack (show v)))+  | d <= 0 = Left (invalid "maxDepth" d)+  | n <= 0 = Left (invalid "maxNodes" n)+  | otherwise = Right (Limits d n defaultMaxBytes) --- | Depth 64, one million values (ADR 001, ADR 017).+-- | Replace the size limit. It must be positive.+withMaxBytes :: Int -> Limits -> Either ConfigError Limits+withMaxBytes b l+  | b <= 0 = Left (invalid "maxBytes" b)+  | otherwise = Right l {maxBytes = b}++invalid :: Text.Text -> Int -> ConfigError+invalid name v =+  configError (InvalidArgument (name <> " must be positive, got " <> Text.pack (show v)))++-- | Depth 64, one million values, 32 MiB per source (ADR 001, ADR 017). defaultLimits :: Limits-defaultLimits = Limits 64 1000000+defaultLimits = Limits 64 1000000 defaultMaxBytes++-- | 32 MiB: far above any hand-written configuration file.+defaultMaxBytes :: Int+defaultMaxBytes = 32 * 1024 * 1024
src/Figment/Partial.hs view
@@ -37,6 +37,8 @@ import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as Map+import Data.Semigroup (sconcat)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import GHC.Generics@@ -210,12 +212,15 @@ -- | Unknown-field check, accumulated together with the field results. recordCheck :: Options -> [Text] -> DecodeContext -> Dict -> Result a -> Result a recordCheck o known c m fields =-  let unknown =-        [ single (atValue c {ctxPath = ctxPath c /. key} x (UnknownField key (suggest key known)))-        | rejectUnknownFields o, (key, x) <- Map.toList m, key `notElem` known ]-  in case unknown of-       [] -> fields-       (e : es) -> Failure (foldl (<>) e es) <* fields+  let knownSet = Set.fromList known+      unknown = [kv | rejectUnknownFields o, kv@(key, _) <- Map.toList m, not (key `Set.member` knownSet)]+      errs =+        [ single (atValue c {ctxPath = ctxPath c /. key} x (UnknownField key (suggestAt i key known)))+        | (i, (key, x)) <- zip [0 ..] unknown+        ]+   in case NE.nonEmpty errs of+        Nothing -> fields+        Just es -> Failure (sconcat es) <* fields  atValue :: DecodeContext -> Value -> ErrorKind -> ConfigError atValue c x kind =
src/Figment/Path.hs view
@@ -20,7 +20,7 @@   ) where  import Control.DeepSeq (NFData)-import Data.Char (isAlphaNum, isDigit)+import Data.Char (chr, digitToInt, isAlphaNum, isDigit, isHexDigit) import Data.Foldable (toList) import Data.Sequence (Seq, (|>)) import qualified Data.Sequence as Seq@@ -28,6 +28,8 @@ import qualified Data.Text as Text import GHC.Generics (Generic) +import Figment.Internal.Text (escapeChar, needsEscape)+ -- | One step into a configuration tree. data Segment   = Key !Text   -- ^ a dictionary key@@ -87,7 +89,9 @@  -- | Render a path: keys joined with @.@, indices as @[n]@, and keys that -- are not plain identifiers double-quoted. The root renders as the empty--- text. @parsePath . renderPath == Right@.+-- text. Control characters inside quoted keys are written as escapes+-- (@\\n@, @\\r@, @\\t@, @\\u{hex}@), so a rendered path is always a single+-- printable line. @parsePath . renderPath == Right@. renderPath :: Path -> Text renderPath (Path s) = go True (toList s)   where@@ -109,7 +113,9 @@     plain c = isAlphaNum c || c == '_' || c == '-'     esc '"' = "\\\""     esc '\\' = "\\\\"-    esc c = Text.singleton c+    esc c+      | needsEscape c = escapeChar c+      | otherwise = Text.singleton c  -- | Parse the syntax produced by 'renderPath'. parsePath :: Text -> Either Text Path@@ -129,14 +135,13 @@       Just ('[', rest) -> do         let (ds, rest') = Text.span isDigit rest         case Text.uncons rest' of-          Just (']', rest'') | not (Text.null ds) ->-            more (Index (read (Text.unpack ds)) : acc) rest''+          Just (']', rest'') | Just i <- parseIndex ds -> more (Index i : acc) rest''           _ -> Left ("malformed index in path " <> quoted t0)       Just (c, _) -> Left ("unexpected " <> Text.pack (show c) <> " in path " <> quoted t0)      keySeg t = case Text.uncons t of       Just ('[', _) -> idxFirst t-      Just ('"', rest) -> quotedKey "" rest+      Just ('"', rest) -> quotedKey [] rest       _ ->         let (k, rest) = Text.span (\c -> c /= '.' && c /= '[') t         in if Text.null k@@ -147,16 +152,53 @@       Just ('[', rest) ->         let (ds, rest') = Text.span isDigit rest         in case Text.uncons rest' of-             Just (']', rest'') | not (Text.null ds) -> Right (Index (read (Text.unpack ds)), rest'')+             Just (']', rest'') | Just i <- parseIndex ds -> Right (Index i, rest'')              _ -> Left ("malformed index in path " <> quoted t0)       _ -> Left ("malformed path " <> quoted t0) -    quotedKey acc t = case Text.uncons t of-      Nothing -> Left ("unterminated quoted key in path " <> quoted t0)-      Just ('"', rest) -> Right (Key acc, rest)-      Just ('\\', rest) -> case Text.uncons rest of-        Just (c, rest') -> quotedKey (Text.snoc acc c) rest'-        Nothing -> Left ("dangling escape in path " <> quoted t0)-      Just (c, rest) -> quotedKey (Text.snoc acc c) rest+    -- linear in the length of the key: runs without escapes are sliced, not+    -- copied character by character+    quotedKey acc t =+      let (chunk, rest) = Text.break (\c -> c == '"' || c == '\\') t+       in case Text.uncons rest of+            Nothing -> Left ("unterminated quoted key in path " <> quoted t0)+            Just ('"', rest') -> Right (Key (Text.concat (reverse (chunk : acc))), rest')+            Just (_, rest') -> case Text.uncons rest' of+              Nothing -> Left ("dangling escape in path " <> quoted t0)+              Just ('n', r) -> quotedKey ("\n" : chunk : acc) r+              Just ('r', r) -> quotedKey ("\r" : chunk : acc) r+              Just ('t', r) -> quotedKey ("\t" : chunk : acc) r+              Just ('u', r) -> case unicodeEscape r of+                Just (ch, r') -> quotedKey (Text.singleton ch : chunk : acc) r'+                Nothing -> Left ("malformed \\u{...} escape in path " <> quoted t0)+              Just (c, r) -> quotedKey (Text.singleton c : chunk : acc) r      quoted x = "`" <> x <> "`"++-- | A non-negative array index that fits an 'Int'. Longer digit strings are+-- rejected instead of silently wrapping around (as @read@ would).+parseIndex :: Text -> Maybe Int+parseIndex ds+  | Text.null ds = Nothing+  | Text.compareLength ds 19 == GT = Nothing+  | n > toInteger (maxBound :: Int) = Nothing+  | otherwise = Just (fromInteger n)+  where+    n = Text.foldl' (\acc c -> acc * 10 + toInteger (digitToInt c)) 0 ds++-- | The @{hex}@ part of a @\\u{hex}@ escape: one to six hex digits naming a+-- Unicode scalar value.+unicodeEscape :: Text -> Maybe (Char, Text)+unicodeEscape r = case Text.uncons r of+  Just ('{', r1) ->+    let (hex, r2) = Text.span isHexDigit r1+        v = Text.foldl' (\acc c -> acc * 16 + digitToInt c) 0 hex+     in case Text.uncons r2 of+          Just ('}', r3)+            | not (Text.null hex)+            , Text.compareLength hex 6 /= GT+            , v <= 0x10FFFF+            , v < 0xD800 || v > 0xDFFF ->+                Just (chr v, r3)+          _ -> Nothing+  _ -> Nothing
src/Figment/Provider/Cli.hs view
@@ -28,6 +28,7 @@   , Arg (..)   ) where +import Data.Bifunctor (first) import qualified Data.Map.Strict as Map import Data.Text (Text) import qualified Data.Text as Text@@ -36,6 +37,7 @@ import Figment.Core import Figment.Error import Figment.Internal.Nest+import Figment.Internal.Text (isUndecodable) import Figment.Internal.ValueParser (parseValue) import Figment.Limits import Figment.Metadata@@ -49,19 +51,28 @@   , cliKeyMap :: Text -> Text   , cliParsed :: Bool   , cliProfile :: Profile+  , cliCustomKeys :: Bool+    -- ^ a custom 'keyMap' is in use, so key names are shown as mapped+  , cliInvalid :: [Int]+    -- ^ positions (from 1) of arguments that are not valid UTF-8   }  -- | A CLI provider over the given arguments. cli :: [Text] -> Cli-cli args = Cli args (Text.replace "-" "_") True Default+cli args = Cli args (Text.replace "-" "_") True Default False []  -- | The arguments of the running process. cliFromProcess :: IO Cli-cliFromProcess = cli . map Text.pack <$> getArgs+cliFromProcess = do+  raw <- getArgs+  -- bytes that are not valid UTF-8 arrive as U+DC80..U+DCFF, which+  -- 'Text.pack' would silently replace; remember them so they are reported+  let invalid = [i | (i, a) <- zip [1 ..] raw, any isUndecodable a]+  pure (cli (map Text.pack raw)) {cliInvalid = invalid}  -- | How each key segment is mapped (default: dashes to underscores). keyMap :: (Text -> Text) -> Cli -> Cli-keyMap f c = c {cliKeyMap = f}+keyMap f c = c {cliKeyMap = f, cliCustomKeys = True}  -- | Do not parse values: every value is a string. unparsedCli :: Cli -> Cli@@ -104,25 +115,38 @@           in if any Text.null segs then Nothing else Just segs  instance Provider Cli where-  metadata _ =-    withInterpolater (\_ p -> "--" <> Text.intercalate "." [Text.replace "_" "-" k | Key k <- segments p]) $+  metadata c =+    withInterpolater (\_ p -> "--" <> Text.intercalate "." [shown k | Key k <- segments p]) $       named "command-line arguments"+    where+      -- the default key map turned @-@ into @_@; undo that for display+      -- (a custom map cannot be undone in general, so its keys show as mapped)+      shown k = if cliCustomKeys c then k else Text.replace "_" "-" k   provide lim c = pure $     let args = parseArgs c-        malformed = [ atPath root (configError (SyntaxError ("malformed option `" <> a <> "`"))) | Malformed a <- args ]+        -- messages name an option, never echo its value (it may be a secret)+        malformed = [ atPath root (configError (SyntaxError ("malformed option `" <> argName a <> "`"))) | Malformed a <- args ]+        invalid = [ atPath root (configError (SyntaxError ("command-line argument " <> Text.pack (show i) <> " is not valid UTF-8 (or the process locale is not a UTF-8 locale)"))) | i <- cliInvalid c ]         entries = concatMap (entry lim c) args-        failures = malformed ++ [e | Left e <- entries]+        failures = malformed ++ invalid ++ [e | Left e <- entries]     in case fromErrorList failures of          Just es -> Left es          Nothing -> Map.singleton (cliProfile c) <$> nest LastWins [x | Right x <- entries] +-- | The option as the user typed it, without any @=value@: what error+-- messages call the argument.+argName :: Text -> Text+argName = Text.takeWhile (/= '=')+ entry :: Limits -> Cli -> Arg -> [Either ConfigError (Text, [Text], Value)] entry lim c = \case   Option a segs (Just v)-    | cliParsed c -> [(a, segs, ) <$> parseValue lim v]-    | otherwise -> [Right (a, segs, Value untagged {tagRaw = Just v} (String v))]-  Option a segs Nothing -> [Right (a, segs, flag True)]-  NegatedFlag a segs -> [Right (a, segs, flag False)]+    | cliParsed c -> [(argName a, segs, ) <$> first (at segs) (parseValue lim v)]+    | otherwise -> [Right (argName a, segs, Value untagged {tagRaw = Just v} (String v))]+  Option a segs Nothing -> [Right (argName a, segs, flag True)]+  NegatedFlag a segs -> [Right (argName a, segs, flag False)]   _ -> []   where     flag b = Value untagged {tagRaw = Just (if b then "true" else "false")} (Bool b)+    -- errors about one option are located at its key+    at segs = atPath (fromSegments (map Key segs))
src/Figment/Provider/Env.hs view
@@ -35,9 +35,11 @@   , envVariableName   ) where +import Data.Bifunctor (first) import Data.List (sortOn) import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import System.Environment (getEnvironment)@@ -45,6 +47,7 @@ import Figment.Core import Figment.Error import Figment.Internal.Nest+import Figment.Internal.Text (isUndecodable) import Figment.Internal.ValueParser (parseValue) import Figment.Metadata import Figment.Path@@ -130,7 +133,7 @@ keyOf :: Env -> Text -> Maybe [Text] keyOf e name = do   rest <- stripPrefixCI (envPrefix e) name-  k <- foldl (\acc f -> acc >>= f) (Just rest) (envChain e)+  k <- foldl' (\acc f -> acc >>= f) (Just rest) (envChain e)   let k' = if envLower e then Text.toLower k else k       segs = Text.splitOn "." k'   if Text.null k' || any Text.null segs then Nothing else Just segs@@ -145,18 +148,30 @@     withInterpolater (\_ p -> envVariableName e p) $       named (if Text.null (envPrefix e) then "environment variables" else "environment variables (prefix " <> envPrefix e <> ")")   provide lim e = do-    vars <- case envSnapshot e of-      Just vs -> pure vs-      Nothing -> map (\(k, v) -> (Text.pack k, Text.pack v)) <$> getEnvironment+    -- GHC decodes bytes that are not valid UTF-8 into U+DC80..U+DCFF, and+    -- 'Text.pack' would silently turn those into U+FFFD. Remember which+    -- variables are affected so they can be reported instead of corrupted.+    (vars, undecodable) <- case envSnapshot e of+      Just vs -> pure (vs, Set.empty)+      Nothing -> do+        environment <- getEnvironment+        pure+          ( [(Text.pack k, Text.pack v) | (k, v) <- environment]+          , Set.fromList [Text.pack k | (k, v) <- environment, any isUndecodable k || any isUndecodable v]+          )     let relevant =           [ (name, ks, val)           | (name, val) <- sortOn fst vars           , not (envIgnoreEmpty e && Text.null val)           , Just ks <- [keyOf e name]           ]-        parsed = [ (name, ks, ) <$> parse val | (name, ks, val) <- relevant ]-        parse val-          | envParsed e = parseValue lim val+        -- errors about one variable are located at its key, so the report+        -- names the variable+        at ks = atPath (fromSegments (map Key ks))+        parsed = [ (name, ks, ) <$> parse name ks val | (name, ks, val) <- relevant ]+        parse name ks val+          | name `Set.member` undecodable = Left (at ks (configError (SyntaxError "the value is not valid UTF-8 (or the process locale is not a UTF-8 locale)")))+          | envParsed e = first (at ks) (parseValue lim val)           | otherwise = Right (Value untagged {tagRaw = Just val} (String val))         failures = [ err | Left err <- parsed ]     pure $ case fromErrorList failures of
src/Figment/Provider/Format.hs view
@@ -22,8 +22,10 @@ import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as TE-import System.Directory (doesFileExist, getCurrentDirectory, makeAbsolute)+import System.Directory (doesDirectoryExist, getCurrentDirectory, getFileSize, makeAbsolute) import System.FilePath (isRelative, takeDirectory, (</>))+import System.IO (IOMode (ReadMode), hFileSize, withBinaryFile)+import System.IO.Error (isPermissionError)  import Figment.Core import Figment.Error@@ -100,19 +102,24 @@     FromFile p search -> do       found <- locate search p       case found of-        Nothing+        Left e ->+          -- the place the file would be could not even be inspected+          pure (Left (single (withMetadata (Just (baseMetadata d Nothing)) (configError (IoError (Text.pack (show e)))))))+        Right Nothing           | dataRequired d ->               pure (Left (single (withMetadata (Just (baseMetadata d Nothing))                 (configError (IoError ("file not found: " <> Text.pack p                   <> (if search && isRelative p then " (searched the working directory and its parents)" else "")))))))           | otherwise -> pure (Right Map.empty)-        Just resolved -> do+        Right (Just resolved) -> do           let meta = baseMetadata d (Just resolved)-          r <- try (BS.readFile resolved)+          r <- try (readBounded (maxBytes lim) resolved)           case r of             Left (e :: IOException) ->               pure (Left (single (withMetadata (Just meta) (configError (IoError (Text.pack (show e)))))))-            Right bytes -> parseWith meta bytes+            Right TooBig ->+              pure (Left (single (withMetadata (Just meta) (configError (TooManyBytes (maxBytes lim))))))+            Right (Contents bytes) -> parseWith meta bytes     where       parseWith meta bytes = do         parsed <- formatParse (dataFormat d) lim bytes@@ -121,13 +128,13 @@           Right v -> case valueNode v of             Dict top               | dataNested d -> splitProfiles meta top-              | otherwise -> Right (Map.singleton (dataProfile d) (fmap (retag meta (dataProfile d)) top))+              | otherwise -> Right (Map.singleton (dataProfile d) (Map.map (retag meta (dataProfile d)) top))             n -> Left (single (withMetadata (Just meta) (withPos (tagPos (valueTag v))                    (configError (InvalidType (describe n) "a dictionary at the top level")))))        splitProfiles meta top =         let one (k, v) = case valueNode v of-              Dict d' -> let p = profile k in Right (p, fmap (retag meta p) d')+              Dict d' -> let p = profile k in Right (p, Map.map (retag meta p) d')               n -> Left (withMetadata (Just meta) (withPos (tagPos (valueTag v))                      (atPath (root /. k) (configError (InvalidType (describe n) "a dictionary (nested files map profile names to dictionaries)")))))             results = map one (Map.toList top)@@ -137,18 +144,67 @@  -- | Find a file, optionally searching parent directories. Returns an -- absolute path.-locate :: Bool -> FilePath -> IO (Maybe FilePath)+--+-- Absence is @Right Nothing@. A failure to even look for the file (for+-- instance a permission error on the working directory) is a @Left@: an+-- unreadable location is reported, never mistaken for an absent file that+-- would silently leave the defaults in force. Only an unreadable+-- /ancestor/ of the working directory is skipped when searching upwards.+locate :: Bool -> FilePath -> IO (Either IOException (Maybe FilePath)) locate search p-  | search && isRelative p = getCurrentDirectory >>= go+  | search && isRelative p = getCurrentDirectory >>= first   | otherwise = do-      ok <- doesFileExist p-      if ok then Just <$> makeAbsolute p else pure Nothing+      r <- probeFile p+      case r of+        Left e -> pure (Left e)+        Right True -> Right . Just <$> makeAbsolute p+        Right False -> pure (Right Nothing)   where-    go dir = do-      let candidate = dir </> p-      ok <- doesFileExist candidate-      if ok-        then pure (Just candidate)+    first dir = do+      r <- probeFile (dir </> p)+      case r of+        Left e -> pure (Left e)+        Right True -> pure (Right (Just (dir </> p)))+        Right False -> up dir+    up dir =+      let parent = takeDirectory dir+       in if parent == dir+            then pure (Right Nothing)+            else do+              r <- probeFile (parent </> p)+              case r of+                Right True -> pure (Right (Just (parent </> p)))+                _ -> up parent++-- | Is there a regular file (or something that is not a directory) at the+-- path? Distinguishes "no" from "could not tell because of permissions".+probeFile :: FilePath -> IO (Either IOException Bool)+probeFile p = do+  r <- try (getFileSize p)+  case r of+    Right _ -> Right . not <$> doesDirectoryExist p+    Left e+      | isPermissionError e -> pure (Left e)+      | otherwise -> pure (Right False)++data ReadOutcome = Contents !ByteString | TooBig++-- | Read a file, giving up as soon as it is known to exceed @limit@ bytes.+-- A regular file larger than the limit is never opened for reading; any+-- other file (a pipe, a device) is read in chunks and abandoned at the+-- limit, so memory use is bounded by the limit whatever the file claims.+readBounded :: Int -> FilePath -> IO ReadOutcome+readBounded limit path = withBinaryFile path ReadMode $ \h -> do+  size <- try (hFileSize h)+  case size of+    Right (n :: Integer) | n > toInteger limit -> pure TooBig+    Right _ -> loop h 0 []+    Left (_ :: IOException) -> loop h 0 []+  where+    loop h !total acc = do+      chunk <- BS.hGetSome h 65536+      if BS.null chunk+        then pure (Contents (BS.concat (reverse acc)))         else-          let parent = takeDirectory dir-          in if parent == dir then pure Nothing else go parent+          let total' = total + BS.length chunk+           in if total' > limit then pure TooBig else loop h total' (chunk : acc)
src/Figment/Provider/Json.hs view
@@ -11,8 +11,10 @@ import Data.Aeson.Decoding.Tokens import qualified Data.Aeson.Key as Key import Data.ByteString (ByteString)+import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BC import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe) import qualified Data.Text as Text import qualified Data.Vector as Vector @@ -29,11 +31,14 @@  -- | Parse a JSON document, enforcing the limits. parseJson :: Limits -> ByteString -> Either ConfigError Value-parseJson lim bs = runBudget lim $ do-  (v, rest) <- value 1 root (Tok.bsToTokens bs)-  if BC.all (`elem` (" \t\r\n" :: String)) rest-    then pure v-    else throwB (configError (SyntaxError "unexpected characters after the JSON value"))+parseJson lim bs0 = checkBytes lim bs0 *> runBudget lim parse+  where+    bs = fromMaybe bs0 (BS.stripPrefix (BS.pack [0xEF, 0xBB, 0xBF]) bs0)+    parse = do+      (v, rest) <- value 1 root (Tok.bsToTokens bs)+      if BC.all (`elem` (" \t\r\n" :: String)) rest+        then pure v+        else throwB (configError (SyntaxError "unexpected characters after the JSON value"))  syntax :: Path -> String -> Budget a syntax p e = throwB (atPath p (configError (SyntaxError (Text.pack e))))
src/Figment/Provider/Toml.hs view
@@ -19,6 +19,8 @@  import Figment.Error import Figment.Internal.Budget+import Figment.Internal.Text (stripBom)+import Figment.Internal.TomlScan (Overflow (..), scanOverflow) import Figment.Limits import Figment.Metadata (Pos (..)) import Figment.Path@@ -32,9 +34,20 @@ -- | Parse a TOML document, enforcing the limits. parseToml :: Limits -> ByteString -> Either ConfigError Value parseToml lim bs = do+  checkBytes lim bs   txt <- case TE.decodeUtf8' bs of     Left e -> Left (configError (SyntaxError ("invalid UTF-8: " <> Text.pack (show e))))-    Right t -> Right t+    Right t -> Right (stripBom t)+  -- toml-parser builds its whole syntax tree before figment sees a single+  -- value, so a pathologically nested document is rejected here, by one+  -- linear pass, before the parser is asked to build it. Table headers+  -- count as brackets while open, hence the allowance of two.+  let depthCap = if maxDepth lim >= maxBound - 2 then maxBound else maxDepth lim + 2+      tokCap = if maxNodes lim >= maxBound `div` 5 then maxBound else 5 * maxNodes lim+  case scanOverflow depthCap tokCap txt of+    Just (TooDeep, at) -> Left (withPos (Just at) (configError (DepthExceeded (maxDepth lim))))+    Just (TooBig, at) -> Left (withPos (Just at) (configError (TooManyNodes (maxNodes lim))))+    Nothing -> Right ()   exprs <- case T.parseRawToml txt of     Left (T.Located p msg) -> Left (withPos (Just (pos p)) (configError (SyntaxError (Text.pack msg))))     Right es -> Right es
src/Figment/Provider/Yaml.hs view
@@ -16,18 +16,18 @@ import Control.Exception (try) import Data.ByteString (ByteString) import Data.Char (isDigit, isHexDigit, isOctDigit)-import Data.Conduit (runConduitRes, (.|))-import qualified Data.Conduit.List as CL+import Data.Conduit (ConduitT, await, runConduitRes, (.|)) import qualified Data.Map.Strict as Map import Data.Map.Strict (Map) import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as TE import qualified Data.Vector as Vector-import Numeric (readHex, readOct) import qualified Text.Libyaml as Y  import Figment.Error+import Figment.Internal.Budget (checkBytes)+import Figment.Internal.Number (integerFromDigits) import Figment.Internal.ValueParser (parseNumber) import Figment.Limits import Figment.Metadata (Pos (..))@@ -41,16 +41,59 @@  -- | Parse a YAML document, enforcing the limits. parseYaml :: Limits -> ByteString -> IO (Either ConfigError Value)-parseYaml lim bs = do-  r <- try (runConduitRes (Y.decodeMarked bs .| CL.consume))-  pure $ case r of-    Left (Y.YamlException msg) -> Left (configError (SyntaxError (Text.pack msg)))-    Left (Y.YamlParseException problem ctx mark) ->-      Left (withPos (Just (markPos mark))-        (configError (SyntaxError (Text.pack (problem ++ (if null ctx then "" else " " ++ ctx))))))-    Right [] -> Right emptyDict-    Right events -> fst <$> runY document (YState events Map.empty (maxNodes lim)) lim+parseYaml lim bs = case checkBytes lim bs of+  Left e -> pure (Left e)+  Right () -> do+    r <- try (runConduitRes (Y.decodeMarked bs .| collectEvents lim))+    pure $ case r of+      Left (Y.YamlException msg) -> Left (configError (SyntaxError (Text.pack msg)))+      Left (Y.YamlParseException problem ctx mark) ->+        Left (withPos (Just (markPos mark))+          (configError (SyntaxError (Text.pack (problem ++ (if null ctx then "" else " " ++ ctx))))))+      Right (Left e) -> Left e+      Right (Right []) -> Right emptyDict+      Right (Right events) -> fst <$> runY document (YState events Map.empty (maxNodes lim)) lim +-- | Gather the events of the stream, but give up the moment the stream is+-- known to break a limit, rather than materialising all of it first.+--+-- * nesting is counted from the start/end events, so a hostile+--   @[[[[...@ is rejected at depth 'maxDepth' + 1, however long it is;+-- * every value the document builds is a node charged against 'maxNodes',+--   and each event is a value, a key (at most one per value) or the end+--   of a container (at most one per container), so a document within the+--   node limit has at most @3 * maxNodes@ events (plus the stream and+--   document framing). More than that cannot be within the limit.+--+-- Together with the size limit this bounds the memory held here, whatever+-- the input.+collectEvents+  :: Monad m+  => Limits+  -> ConduitT Y.MarkedEvent o m (Either ConfigError [Y.MarkedEvent])+collectEvents lim = go (0 :: Int) (0 :: Int) []+  where+    cap+      | maxNodes lim > (maxBound - 16) `div` 3 = maxBound+      | otherwise = 3 * maxNodes lim + 16+    go !depth !count acc = do+      me <- await+      case me of+        Nothing -> pure (Right (reverse acc))+        Just ev@(Y.MarkedEvent e start _)+          | count >= cap ->+              pure (Left (withPos (Just (markPos start)) (configError (TooManyNodes (maxNodes lim)))))+          | depth' > maxDepth lim ->+              pure (Left (withPos (Just (markPos start)) (configError (DepthExceeded (maxDepth lim)))))+          | otherwise -> go depth' (count + 1) (ev : acc)+          where+            depth' = case e of+              Y.EventSequenceStart {} -> depth + 1+              Y.EventMappingStart {} -> depth + 1+              Y.EventSequenceEnd -> depth - 1+              Y.EventMappingEnd -> depth - 1+              _ -> depth+ markPos :: Y.YamlMark -> Pos markPos m = Pos (Y.yamlLine m + 1) (Y.yamlColumn m + 1) @@ -170,7 +213,7 @@         Y.EventMappingStart _ _ anchor -> do           spendY 1 p at           depthCheck d p at-          (m, size, height) <- mappingPairs Map.empty [] 1 0+          (m, size, height) <- mappingPairs Map.empty [] False 1 0           let a = Anchored (Value untagged {tagPos = Just at} (Dict m)) size (height + 1)           remember anchor a           pure a@@ -193,9 +236,11 @@           Anchored v s h <- node (d + 1) (p /# i)           sequenceItems (i + 1) (v : acc) (size + s) (max height h) -    -- explicit pairs, then merge-key sources (applied underneath)-    mappingPairs :: Dict -> [Dict] -> Int -> Int -> YP (Dict, Int, Int)-    mappingPairs acc merges size height = do+    -- explicit pairs, then merge-key sources (applied underneath). The Bool+    -- records that a merge key has been seen: a mapping may have only one,+    -- like any other key.+    mappingPairs :: Dict -> [Dict] -> Bool -> Int -> Int -> YP (Dict, Int, Int)+    mappingPairs acc merges seenMerge size height = do       me <- next       case me of         Just (Y.MarkedEvent Y.EventMappingEnd _ _) ->@@ -204,16 +249,19 @@           let kat = markPos kstart           key <- decodeText p kat bytes           if key == "<<" && style `elem` [Y.Plain, Y.PlainNoTag, Y.Any]-            then do-              Anchored v s h <- node (d + 1) (p /. key)-              srcs <- mergeSources kat v-              mappingPairs acc (merges ++ srcs) (size + s) (max height (h - 1))+            then+              if seenMerge+                then failY (withPos (Just kat) (atPath (p /. key) (configError (DuplicateKey key))))+                else do+                  Anchored v s h <- node (d + 1) (p /. key)+                  srcs <- mergeSources kat v+                  mappingPairs acc srcs True (size + s) (max height (h - 1))             else               if Map.member key acc                 then failY (withPos (Just kat) (atPath (p /. key) (configError (DuplicateKey key))))                 else do                   Anchored v s h <- node (d + 1) (p /. key)-                  mappingPairs (Map.insert key v acc) merges (size + s) (max height h)+                  mappingPairs (Map.insert key v acc) merges seenMerge (size + s) (max height h)         Just (Y.MarkedEvent _ kstart _) ->           syntaxAt p (markPos kstart) "only scalar mapping keys are supported"         Nothing -> failY (atPath p (configError (SyntaxError "unexpected end of YAML input")))@@ -261,15 +309,13 @@ coreInt :: Text -> Maybe Number coreInt t   | Just r <- Text.stripPrefix "0x" t, not (Text.null r), Text.all isHexDigit r =-      Just (Finite (fromInteger (fst (head' (readHex (Text.unpack r))))))+      Just (Finite (fromInteger (integerFromDigits 16 r)))   | Just r <- Text.stripPrefix "0o" t, not (Text.null r), Text.all isOctDigit r =-      Just (Finite (fromInteger (fst (head' (readOct (Text.unpack r))))))+      Just (Finite (fromInteger (integerFromDigits 8 r)))   | otherwise =       let body = maybe t id (Text.stripPrefix "-" t <> Text.stripPrefix "+" t)       in if not (Text.null body) && Text.all isDigit body then parseNumber t else Nothing-  where-    head' (x : _) = x-    head' [] = (0, "")+  coreFloat :: Text -> Maybe Number coreFloat t
src/Figment/Value.hs view
@@ -41,6 +41,7 @@ import qualified Data.Text as Text import Data.Vector (Vector) import qualified Data.Vector as Vector+import qualified Data.Vector.Mutable as MVector import GHC.Generics (Generic)  import Figment.Metadata@@ -134,33 +135,50 @@ numberFromScientific :: Scientific -> Number numberFromScientific = Finite +-- | Rebuild a tree, applying a function to every tag.+--+-- The rebuild is /strict/: when the result is forced, every node has been+-- built. ('fmap' over a 'Data.Map.Strict.Map' or a boxed 'Vector.Vector' is+-- lazy in the elements, and would leave a thunk per child that keeps the+-- original tree alive until it is touched.)+mapTags :: (Tag -> Tag) -> Value -> Value+mapTags f = go+  where+    go (Value t n) = Value (f t) (goNode n)+    goNode (Array xs) = Array (mapVector' go xs)+    goNode (Dict d) = Dict (Map.map go d)+    goNode n = n++-- | 'Vector.map' that evaluates every element before the vector is+-- returned.+mapVector' :: (a -> b) -> Vector a -> Vector b+mapVector' f v = Vector.create $ do+  mv <- MVector.new (Vector.length v)+  Vector.iforM_ v $ \i x -> let y = f x in y `seq` MVector.write mv i y+  pure mv+ -- | Fill in missing provenance (never overwrite: values coming from a -- nested t'Figment.Core.Figment' keep their original source). retag :: Metadata -> Profile -> Value -> Value-retag m p = go+retag m p = mapTags fill   where-    go (Value t n) = Value (fill t) (goNode n)+    jm = Just m+    jp = Just p     fill t = t-      { tagMeta = maybe (Just m) Just (tagMeta t)-      , tagProfile = maybe (Just p) Just (tagProfile t)+      { tagMeta = case tagMeta t of Nothing -> jm; old -> old+      , tagProfile = case tagProfile t of Nothing -> jp; old -> old       }-    goNode (Array xs) = Array (fmap go xs)-    goNode (Dict d) = Dict (fmap go d)-    goNode n = n  -- | Overwrite the metadata of every node (used by providers that learn -- their final metadata, e.g. a resolved file path, only when reading). setTagMeta :: Metadata -> Value -> Value-setTagMeta m = go+setTagMeta m = mapTags (\t -> t {tagMeta = jm})   where-    go (Value t n) = Value t {tagMeta = Just m} (goNode n)-    goNode (Array xs) = Array (fmap go xs)-    goNode (Dict d) = Dict (fmap go d)-    goNode n = n+    jm = Just m  -- | Follow a path. lookupPath :: Path -> Value -> Maybe Value-lookupPath p v0 = foldl step (Just v0) (segments p)+lookupPath p v0 = foldl' step (Just v0) (segments p)   where     step Nothing _ = Nothing     step (Just (Value _ (Dict d))) (Key k) = Map.lookup k d@@ -196,12 +214,9 @@   Dict _ -> "a dictionary"   where     preview t-      | Text.length t > 40 = Text.take 40 t <> "..."+      | Text.compareLength t 40 == GT = Text.take 40 t <> "..."       | otherwise = t  -- | Remove all provenance (for comparing data only). stripTags :: Value -> Value-stripTags (Value _ n) = Value untagged $ case n of-  Array xs -> Array (fmap stripTags xs)-  Dict d -> Dict (fmap stripTags d)-  other -> other+stripTags = mapTags (const untagged)
test/Figment/Test/Cli.hs view
@@ -47,7 +47,8 @@     , testCase "structural conflicts are errors" $ do         r <- loadCli ["--db=x", "--db.host=y"]         case r of-          Left es -> map errorKind (errorList es) @?= [KeyConflict "--db=x" "--db.host=y"]+          -- conflicts name the options, never their values (which may be secrets)+          Left es -> map errorKind (errorList es) @?= [KeyConflict "--db" "--db.host"]           Right _ -> assertFailure "expected a conflict"     , testCase "keys are not lower-cased" $ do         l <- ok ["--Name=x"]
test/Figment/Test/Decode.hs view
@@ -11,6 +11,7 @@ import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map.Strict as Map import Data.Text (Text)+import System.FilePath (normalise, takeDirectory, (</>)) import qualified Data.Text as Text import Data.Time (Day, fromGregorian) import Data.Word (Word16)@@ -153,8 +154,8 @@           Right (WithTagged s d) -> do             taggedValue s @?= "x"             taggedPath s @?= keyPath "secret"-            fmap metaSource (taggedMetadata s) @?= Just (Just (FileSource path))-            relative d @?= dirOf path <> "/data"+            fmap metaSource (taggedMetadata s) @?= Just (Just (FileSource (normalise path)))+            relative d @?= takeDirectory (normalise path) </> "data"           Left e -> assertFailure (Text.unpack (renderErrors e))     , testCase "ISO dates, NonEmpty, tuples" $ do         r <- decodeJ "{\"d\":\"2024-02-29\"}"@@ -177,7 +178,6 @@           Right v -> assertFailure (show v)     ]   where-    dirOf = reverse . drop 1 . dropWhile (/= '/') . reverse  withTmpToml :: (FilePath -> IO a) -> IO a withTmpToml k = Jail.withJail $ \j ->
test/Figment/Test/Env.hs view
@@ -96,6 +96,24 @@         case extract l :: Either ConfigErrors Outer of           Left es -> assertBool (Text.unpack (renderErrors es)) ("`APP_DB__PORT`" `Text.isInfixOf` renderErrors es)           Right v -> assertFailure (show v)+    , testCase "R5: duplicate keys in an inline table are reported" $ do+        r <- env [("APP_M", "{a = 1, a = 2}")] (prefixed "APP_")+        either (map errorKind . errorList) (const []) r @?= [DuplicateKey "a"]+    , testCase "R5: \\u escapes decode and unknown escapes are not silently dropped" $ do+        l <- ok [("APP_A", "\"caf\\u00e9\""), ("APP_B", "\"x\\qy\"")] (prefixed "APP_")+        node "a" l @?= Just (String "caf\233")+        node "b" l @?= Just (String "\"x\\qy\"")+    , testCase "R3: structured env values obey the node and byte limits" $ do+        let big = "[" <> Text.replicate 50 "1," <> "1]"+        r <- load (withLimits (either (const defaultLimits) id (mkLimits 64 10)) (from (Env.fromList [("APP_L", big)] (prefixed "APP_"))))+        either (map errorKind . errorList) (const []) r @?= [TooManyNodes 10]+    , testCase "S1: a Secret never shows the value in decode errors or Show" $ do+        l <- ok [("APP_PASSWORD", "hunter2")] (prefixed "APP_")+        case extractAt (keyPath "password") l :: Either ConfigErrors (Secret Int) of+          Left es -> assertBool (Text.unpack (renderErrors es)) (not ("hunter2" `Text.isInfixOf` renderErrors es))+          Right v -> assertFailure (show v)+        extractAt (keyPath "password") l @?= Right (Secret ("hunter2" :: Text))+        show (Secret ("hunter2" :: Text)) @?= "Secret <redacted>"     , testCase "reads the real process environment" $ Jail.withJail $ \j -> do         Jail.clearEnv j         Jail.setEnv j "JAILED_HOST" "real"
test/Figment/Test/Errors.hs view
@@ -3,14 +3,16 @@ module Figment.Test.Errors (tests) where  import qualified Data.ByteString.Lazy as BL+import qualified Data.ByteString.Lazy.Char8 as BLC import Data.Function ((&)) import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as TE import GHC.Generics (Generic) import Data.Word (Word16)+import System.FilePath ((</>)) import Test.Tasty-import Test.Tasty.Golden (goldenVsString)+import Test.Tasty.Golden.Advanced (goldenTest)  import Figment import qualified Figment.Provider.Env as Env@@ -38,30 +40,43 @@       Left es -> renderErrors es       Right v -> Text.pack ("unexpected success: " ++ show v) -golden :: String -> IO Text -> TestTree-golden n act = goldenVsString n ("test/golden/" ++ n ++ ".txt") (BL.fromStrict . TE.encodeUtf8 . (<> "\n") <$> act)+-- | @golden dir name action@: the golden files live in @dir@, which must be+-- absolute. 'Jail' changes the process working directory while a jail test+-- runs and the suite runs its tests in parallel, so a relative path would be+-- looked up in the wrong directory whenever the two overlap.+golden :: FilePath -> String -> IO Text -> TestTree+golden dir n act = goldenTest n (BL.readFile path) (BL.fromStrict . TE.encodeUtf8 . (<> "\n") <$> act) cmp (BL.writeFile path)+  where+    path = dir </> (n ++ ".txt")+    -- compare ignoring carriage returns, so a Windows checkout that+    -- converted the golden file to CRLF still matches+    norm = BL.filter (/= 13)+    cmp expected actual+      | norm expected == norm actual = pure Nothing+      | otherwise = pure (Just ("actual output:\n" ++ BLC.unpack actual)) -tests :: TestTree-tests =+-- | The argument is the absolute path of the @test/golden@ directory.+tests :: FilePath -> TestTree+tests dir =   testGroup     "errors (golden)"-    [ golden "decode-many" $+    [ golden dir "decode-many" $         report $           new             & merge (fromText toml "[db]\nhost = \"h\"\nport = 70000\nhots = 1\n")             & merge (Env.fromList [("APP_LEVEL", "verbose")] (prefixed "APP_"))-    , golden "missing" $+    , golden dir "missing" $         report $           new             & merge (fromText json "{\"db\":{\"host\":\"h\",\"port\":1},\"level\":\"Info\"}")             & merge (Env.fromList [] (prefixed "APP_") & Env.split "__")             & merge (cli [])-    , golden "load-failures" $+    , golden dir "load-failures" $         report $           new             & merge (fromText yaml "a: 1\na: 2\n")             & merge (fromText toml "x = \n")             & merge (Env.fromList [("APP_DB", "1"), ("APP_DB__HOST", "2")] (prefixed "APP_" & Env.split "__"))-    , golden "single" $+    , golden dir "single" $         report (new & merge (fromText json "{\"name\":\"n\",\"db\":{\"host\":\"h\",\"port\":\"x\"},\"level\":\"Debug\"}"))     ]
test/Figment/Test/Figment.hs view
@@ -5,6 +5,7 @@ import Data.Function ((&)) import qualified Data.Map.Strict as Map import Data.Text (Text)+import System.FilePath (normalise) import qualified Data.Text as Text import GHC.Generics (Generic) import GHC.Stack (SrcLoc (..))@@ -76,7 +77,7 @@     , testCase "metadata records where the provider was added" $ do         l <- loadOk (from (fromText json "{\"name\":\"x\",\"port\":1}"))         case loadedSources l of-          [m] -> fmap srcLocFile (metaAddedAt m) @?= Just "test/Figment/Test/Figment.hs"+          [m] -> fmap (normalise . srcLocFile) (metaAddedAt m) @?= Just (normalise "test/Figment/Test/Figment.hs")           other -> assertFailure (show other)     , testCase "findValue / contains / findMetadata / extractAt / focus" $ do         l <- loadOk (from (fromText json "{\"db\":{\"host\":\"h\",\"port\":5}}"))
+ test/Figment/Test/Hardening.hs view
@@ -0,0 +1,321 @@+-- | Regression tests for resource exhaustion, error containment and+-- diagnostics hygiene: one group per class of problem, each written so+-- that the behaviour it pins would fail (or time out) on the code it+-- replaced.+--+-- Timing tests use generous timeouts: they distinguish linear from+-- quadratic behaviour by orders of magnitude, not by percentages.+module Figment.Test.Hardening (tests) where++import Control.Exception (bracket_, evaluate, try)+import Data.Either (isLeft)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import System.Info (os)+import qualified Data.Text as Text+import GHC.Generics (Generic)+import qualified System.Environment as Env+import qualified System.Environment.Blank as Blank+import Test.Tasty+import Test.Tasty.HUnit++import Figment+import Figment.Error (addHints, configError)+import qualified Figment.Jail as Jail+import Figment.Path (fromSegments)+import qualified Figment.Provider.Cli as Cli+import qualified Figment.Provider.Env as Env++-- helpers ---------------------------------------------------------------++kinds :: Figment -> IO [ErrorKind]+kinds f = either (map errorKind . errorList) (const []) <$> load f++limits :: Int -> Int -> Limits+limits d n = either (const defaultLimits) id (mkLimits d n)++bytes :: Int -> Limits -> Limits+bytes n l = either (const l) id (withMaxBytes n l)++-- | Fail the test if it takes longer than the given number of seconds.+within :: Int -> TestTree -> TestTree+within secs = localOption (mkTimeout (fromIntegral secs * 1000000))++-- | A provider whose result hides an exception in a lazily built value.+data Lazy = LazyWhole | LazyInside++instance Provider Lazy where+  metadata _ = named "lazy provider"+  provide _ LazyWhole = pure (error "boom: hidden in the whole result")+  provide _ LazyInside = pure (Right (Map.singleton Default (Map.singleton "k" (error "boom: hidden in a value"))))++data Strict = Strict {host :: Text, port :: Int}+  deriving stock (Eq, Show, Generic)++instance FromConfig Strict where+  fromConfig = genericDecoder defaultOptions {rejectUnknownFields = True}++-- | Assert that a text contains a fragment, showing the text otherwise.+includes :: Text -> Text -> Assertion+includes haystack needle =+  (needle `Text.isInfixOf` haystack) @? ("expected " ++ show needle ++ " in:\n" ++ Text.unpack haystack)++tests :: TestTree+tests =+  testGroup+    "hardening"+    [ sizeLimits+    , containment+    , linearTime+    , nestedLimits+    , diagnostics+    , numbers+    , jail+    ]++-- 1. a source's size is bounded before it is parsed -----------------------++sizeLimits :: TestTree+sizeLimits =+  testGroup+    "size limit"+    [ testCase "the default is 32 MiB and is visible" $ do+        maxBytes defaultLimits @?= defaultMaxBytes+        defaultMaxBytes @?= 32 * 1024 * 1024+    , testCase "withMaxBytes validates" $ do+        isLeft (withMaxBytes 0 defaultLimits) @? "zero is rejected"+        isLeft (withMaxBytes (-1) defaultLimits) @? "negative is rejected"+    , testCase "JSON over the limit is rejected, at the limit accepted" $ do+        let doc = "{\"a\":\"0123456789\"}" -- 18 bytes+        kinds (withLimits (bytes 17 defaultLimits) (from (fromText json doc))) >>= (@?= [TooManyBytes 17])+        kinds (withLimits (bytes 18 defaultLimits) (from (fromText json doc))) >>= (@?= [])+    , testCase "YAML over the limit is rejected" $+        kinds (withLimits (bytes 5 defaultLimits) (from (fromText yaml "a: 1234567\n"))) >>= (@?= [TooManyBytes 5])+    , testCase "TOML over the limit is rejected" $+        kinds (withLimits (bytes 5 defaultLimits) (from (fromText toml "a = 1234567\n"))) >>= (@?= [TooManyBytes 5])+    , testCase "a file over the limit is rejected without being parsed" $+        Jail.withJail $ \j -> do+          _ <- Jail.createFile j "big.json" ("{\"a\":\"" <> Text.replicate 1000 "x" <> "\"}")+          k <- kinds (withLimits (bytes 100 defaultLimits) (from (fileExact json "big.json")))+          k @?= [TooManyBytes 100]+    , testCase "a file within the limit still loads" $+        Jail.withJail $ \j -> do+          _ <- Jail.createFile j "ok.json" "{\"a\":1}"+          kinds (withLimits (bytes 100 defaultLimits) (from (fileExact json "ok.json"))) >>= (@?= [])+    , testCase "the error says what the limit was" $ do+        r <- load (withLimits (bytes 3 defaultLimits) (from (fromText json "{\"a\":1}")))+        either renderErrors (const "") r `includes` "source is larger than the limit of 3 bytes"+    , within 20 $ testCase "YAML with far too many events is abandoned early" $ do+        let doc = "a: [" <> Text.intercalate "," (replicate 200000 "1") <> "]\n"+        kinds (withLimits (limits 64 100) (from (fromText yaml doc))) >>= (@?= [TooManyNodes 100])+    , within 20 $ testCase "a very deep YAML flow sequence is abandoned at the depth limit" $+        kinds (from (fromText yaml ("a: " <> Text.replicate 500000 "[" <> "\n"))) >>= (@?= [DepthExceeded 64])+    , testCase "brackets inside TOML strings and comments are not nesting" $ do+        let doc = Text.unlines+              [ "a = \"" <> Text.replicate 300 "[" <> "\""+              , "b = '" <> Text.replicate 300 "{" <> "'"+              , "# " <> Text.replicate 300 "[" +              , "c = \"\"\"", Text.replicate 300 "[", "\"\"\""+              , "d = [[1], [2]]"+              ]+        kinds (from (fromText toml doc)) >>= (@?= [])+    ]++-- 2. nothing escapes load ---------------------------------------------------++containment :: TestTree+containment =+  testGroup+    "exceptions never escape load"+    [ testCase "a provider whose whole result is a hidden exception" $ do+        r <- load (from LazyWhole)+        case fmap (map errorKind . errorList) (either Right (const (Left ())) r) of+          Right [IoError t] -> t `includes` "boom"+          other -> assertFailure ("expected one IoError, got " ++ show other)+    , testCase "a provider with an exception hidden inside a value" $ do+        r <- load (from LazyInside)+        case fmap (map errorKind . errorList) (either Right (const (Left ())) r) of+          Right [IoError t] -> t `includes` "boom"+          other -> assertFailure ("expected one IoError, got " ++ show other)+    , testCase "later steps still run and their errors are reported too" $ do+        k <- kinds (merge (fromText json "{") (from LazyWhole))+        length k @?= 2+    ]++-- 3. linear, not quadratic, time -------------------------------------------++linearTime :: TestTree+linearTime =+  testGroup+    "linear time"+    [ within 10 $ testCase "a 200k-character quoted environment value" $ do+        let v = "\"" <> Text.replicate 200000 "a" <> "\""+        l <- load (from (Env.fromList [("APP_X", v)] (prefixed "APP_"))) >>= either (assertFailure . Text.unpack . renderErrors) pure+        t <- either (assertFailure . Text.unpack . renderErrors) pure (extractAt (keyPath "x") l)+        Text.length t @?= 200000+    , within 10 $ testCase "a 200k-character quoted command-line value" $ do+        let v = "\"" <> Text.replicate 200000 "a" <> "\""+        l <- load (from (Cli.cli ["--x=" <> v])) >>= either (assertFailure . Text.unpack . renderErrors) pure+        t <- either (assertFailure . Text.unpack . renderErrors) pure (extractAt (keyPath "x") l)+        Text.length t @?= 200000+    , within 20 $ testCase "50,000 unknown keys are reported quickly" $ do+        let keys = Text.intercalate "," ["\"k" <> Text.pack (show i) <> "\":0" | i <- [1 .. 50000 :: Int]]+            doc = "{\"host\":\"h\",\"port\":1," <> keys <> "}"+        l <- load (from (fromText json doc)) >>= either (assertFailure . Text.unpack . renderErrors) pure+        case extract l :: Either ConfigErrors Strict of+          Left es -> do+            length (errorList es) @?= 50000+            n <- evaluate (Text.length (renderErrors es))+            (n > 0) @? "renders"+          Right _ -> assertFailure "unknown keys should be rejected"+    , within 20 $ testCase "a 1 MB unknown key is not compared against field names" $ do+        let doc = "{\"host\":\"h\",\"port\":1,\"" <> Text.replicate 1000000 "x" <> "\":0}"+        l <- load (from (fromText json doc)) >>= either (assertFailure . Text.unpack . renderErrors) pure+        case extract l :: Either ConfigErrors Strict of+          Left es -> map errorKind (errorList es) @?= [UnknownField (Text.replicate 1000000 "x") []]+          Right _ -> assertFailure "unknown key should be rejected"+    , within 20 $ testCase "a 200k-digit hexadecimal YAML integer" $+        kinds (from (fromText yaml ("a: 0x" <> Text.replicate 200000 "f" <> "\n"))) >>= (@?= [])+    , within 20 $ testCase "a single YAML mapping with a duplicate merge key is rejected, not quadratic" $ do+        let doc = Text.unlines ("base: &a {x: 1}" : "m:" : replicate 20000 "  <<: *a")+        k <- kinds (from (fromText yaml doc))+        k @?= [DuplicateKey "<<"]+    , testCase "reports show at most 100 errors and count the rest" $ do+        let keys = Text.intercalate "," ["\"k" <> Text.pack (show i) <> "\":0" | i <- [1 .. 1000 :: Int]]+        l <- load (from (fromText json ("{\"host\":\"h\",\"port\":1," <> keys <> "}"))) >>= either (assertFailure . Text.unpack . renderErrors) pure+        case extract l :: Either ConfigErrors Strict of+          Left es -> do+            let r = renderErrors es+            r `includes` "1000 configuration errors"+            r `includes` "... and 900 more errors not shown"+          Right _ -> assertFailure "unknown keys should be rejected"+    , testCase "suggestions still work for typos" $ do+        l <- load (from (fromText json "{\"hots\":\"h\",\"port\":1}")) >>= either (assertFailure . Text.unpack . renderErrors) pure+        case extract l :: Either ConfigErrors Strict of+          Left es -> renderErrors es `includes` "did you mean `host`"+          Right _ -> assertFailure "typo should be rejected"+    ]++-- 4. nested figments honour the outer limits -------------------------------++nestedLimits :: TestTree+nestedLimits =+  testGroup+    "nested figments"+    [ testCase "tight outer limits constrain an inner figment that sets none" $ do+        let inner = from (fromText json "{\"a\":[[[[1]]]]}")+        kinds (withLimits (limits 2 1000) (from inner)) >>= (@?= [DepthExceeded 2])+    , testCase "an inner figment's own limits are kept" $ do+        let inner = withLimits (limits 10 1000) (from (fromText json "{\"a\":[[[[1]]]]}"))+        kinds (withLimits (limits 2 1000) (from inner)) >>= (@?= [])+    ]++-- 5. diagnostics ----------------------------------------------------------++diagnostics :: TestTree+diagnostics =+  testGroup+    "diagnostics"+    [ testCase "control characters in keys cannot forge report lines" $ do+        let doc = "{\"host\":\"h\",\"port\":1,\"" <> "x\\n  --> key `admin` in trusted.toml\\u001b[31mFAKE" <> "\":0}"+        l <- load (from (fromText json doc)) >>= either (assertFailure . Text.unpack . renderErrors) pure+        case extract l :: Either ConfigErrors Strict of+          Left es -> do+            let r = renderErrors es+            ('\ESC' `Text.elem` r) @?= False+            ("\n  --> key `admin`" `Text.isInfixOf` r) @?= False+            r `includes` "\\n"+          Right _ -> assertFailure "unknown key should be rejected"+    , testCase "paths with control characters round-trip" $ do+        let p = fromSegments [Key "a\nb\ESC\DEL\t\"\\", Index 3, Key "", Key "\x202E"]+        parsePath (renderPath p) @?= Right p+        any (`elem` ['\n', '\ESC', '\DEL', '\t']) (Text.unpack (renderPath p)) @?= False+    , testCase "array indices that do not fit an Int are rejected, not wrapped" $ do+        isLeft (parsePath "a[18446744073709551616]") @? "2^64"+        isLeft (parsePath "a[9223372036854775808]") @? "2^63"+        parsePath "a[9223372036854775807]" @?= Right (fromSegments [Key "a", Index maxBound])+    , testCase "command-line messages never echo option values" $ do+        k <- load (from (Cli.cli ["--db=hunter2", "--db.host=h"]))+        case k of+          Left es -> ("hunter2" `Text.isInfixOf` renderErrors es) @?= False+          Right _ -> assertFailure "a scalar and a table at the same key should conflict"+    , testCase "an environment variable error names the variable" $ do+        let deep = Text.replicate 100 "[" <> Text.replicate 100 "]"+        r <- load (from (Env.fromList [("APP_DEEP", deep)] (prefixed "APP_")))+        case r of+          Left es -> renderErrors es `includes` "APP_DEEP"+          Right _ -> assertFailure "should exceed the depth limit"+    , testCase "snake_case keeps acronyms together" $ do+        map snakeCase ["maxConnections", "dbURL", "HTTPServer", "useHTTPS", "userID", "XMLParser", "parseXMLFile", "port2Num", "Port"]+          @?= ["max_connections", "db_url", "http_server", "use_https", "user_id", "xml_parser", "parse_xml_file", "port2_num", "port"]+    ]++-- 6. numbers --------------------------------------------------------------++numbers :: TestTree+numbers =+  testGroup+    "numbers"+    [ testCase "a finite literal that overflows Double is an error, not infinity" $ do+        l <- load (from (fromText json "{\"x\":1e999}")) >>= either (assertFailure . Text.unpack . renderErrors) pure+        isLeft (extractAt (keyPath "x") l :: Either ConfigErrors Double) @? "1e999 is out of range for Double"+        isLeft (extractAt (keyPath "x") l :: Either ConfigErrors Float) @? "1e999 is out of range for Float"+    , testCase "ordinary doubles are unaffected" $ do+        l <- load (from (fromText json "{\"x\":1.5e300}")) >>= either (assertFailure . Text.unpack . renderErrors) pure+        extractAt (keyPath "x") l @?= (Right 1.5e300 :: Either ConfigErrors Double)+    , testCase "an integer with thousands of digits is bounded by its digits, not only its exponent" $ do+        let digits n = Text.replicate n "9"+        big <- load (from (fromText json ("{\"x\":" <> digits 5000 <> "}"))) >>= either (assertFailure . Text.unpack . renderErrors) pure+        isLeft (extractAt (keyPath "x") big :: Either ConfigErrors Integer) @? "5000 digits is too many"+        ok <- load (from (fromText json ("{\"x\":" <> digits 4000 <> "}"))) >>= either (assertFailure . Text.unpack . renderErrors) pure+        (either (const 0) (\n -> length (show (n :: Integer))) (extractAt (keyPath "x") ok)) @?= 4000+    ]++-- 7. the jail ------------------------------------------------------------++jail :: TestTree+jail =+  testGroup+    "jail"+    [ testCase "nested jails fail fast instead of deadlocking" $+        Jail.withJail $ \_ -> do+          r <- tryIO (Jail.withJail (\_ -> pure ()))+          isLeft r @? "the inner withJail throws"+    , testCase "a handle cannot be used after its jail" $ do+        j <- Jail.withJail pure+        r <- tryIO (Jail.createFile j "late.txt" "x")+        isLeft r @? "createFile after the jail throws"+        r' <- tryIO (Jail.setEnv j "FIGMENT_LATE" "x")+        isLeft r' @? "setEnv after the jail throws"+    , testCase "paths may not leave the jail" $+        Jail.withJail $ \j -> do+          isLeft <$> tryIO (Jail.createFile j "../outside.txt" "x") >>= (@? "parent directory refused")+          isLeft <$> tryIO (Jail.createFile j "/tmp/figment-outside.txt" "x") >>= (@? "absolute path refused")+          _ <- Jail.createFile j "sub/inside.txt" "x"+          pure ()+    , testCase "an environment variable that was empty before the jail is empty after it" $+        -- Windows cannot hold an empty variable: setting one removes it.+        if os == "mingw32" then pure () else bracket_ (Blank.setEnv "FIGMENT_HARDENING_EMPTY" "" True) (Env.unsetEnv "FIGMENT_HARDENING_EMPTY") $ do+          Jail.withJail $ \j -> Jail.setEnv j "FIGMENT_HARDENING_EMPTY" "changed"+          Env.lookupEnv "FIGMENT_HARDENING_EMPTY" >>= (@?= Just "")+    , testCase "S2: custom messages and hints cannot forge lines or hide characters" $ do+        let e = addHints ["h\nforged\x202Ex"] (configError (Message "a\nb\x200Bc\xFEFFd"))+            out = renderError e+        assertBool (Text.unpack out) (not (Text.any (`elem` ['\x200B', '\x202E', '\xFEFF']) out))+        length (Text.lines out) @?= 3+    , testCase "R1: a TOML document with far too many tokens is rejected before parsing" $ do+        let doc = Text.concat (replicate 200 "a = 1\n")+        kinds (withLimits (limits 64 10) (from (fromText toml doc))) >>= (@?= [TooManyNodes 10])+    , testCase "R1: dotted keys and commas count towards the pre-scan" $ do+        let doc = "a = [" <> Text.replicate 200 "1," <> "1]\n"+        kinds (withLimits (limits 64 10) (from (fromText toml doc))) >>= (@?= [TooManyNodes 10])+    , testCase "C4: a byte-order mark before JSON is ignored" $ do+        r <- load (from (fromText json "\xFEFF{\"a\":1}"))+        either (const Nothing) (Just . (extractAt (keyPath "a") :: Loaded -> Either ConfigErrors Int)) r @?= Just (Right 1)+    , testCase "variables set inside a jail are gone after it" $ do+        Jail.withJail $ \j -> Jail.setEnv j "FIGMENT_HARDENING_TMP" "x"+        Env.lookupEnv "FIGMENT_HARDENING_TMP" >>= (@?= Nothing)+    ]+  where+    tryIO :: IO a -> IO (Either IOError a)+    tryIO = try
test/Figment/Test/Providers.hs view
@@ -87,6 +87,17 @@       case kinds es of         [SyntaxError _] -> pure ()         other -> assertFailure (show other)+  , testCase "C6: a space separates date and time (RFC 3339)" $ do+      l <- expectOk (from (fromText json "{\"t\":\"2024-01-02 03:04:05\",\"u\":\"2024-01-02 03:04:05Z\"}"))+      extractAt (keyPath "t") l @?= Right (read "2024-01-02 03:04:05" :: LocalTime)+      extractAt (keyPath "u") l @?= Right (read "2024-01-02 03:04:05 UTC" :: UTCTime)+  , testCase "C2: maps with integer keys" $ do+      l <- expectOk (from (fromText json "{\"m\":{\"1\":\"a\",\"-2\":\"b\"}}"))+      extractAt (keyPath "m") l @?= Right (Map.fromList [(1 :: Int, "a" :: Text), (-2, "b")])+      l2 <- expectOk (from (fromText json "{\"m\":{\"x\":\"a\"}}"))+      case (extractAt (keyPath "m") l2 :: Either ConfigErrors (Map.Map Int Text)) of+        Left _ -> pure ()+        Right v -> assertFailure (show v)   , testCase "big and precise numbers survive exactly" $ do       l <- expectOk (from (fromText json "{\"n\":123456789012345678901234567890.123456789}"))       fmap (valueNode) (findValue (keyPath "n") l) @?= Just (Num (Finite 123456789012345678901234567890.123456789))
test/Figment/Test/Tutorial.hs view
@@ -10,6 +10,7 @@ import Data.Function ((&)) import qualified Data.Map.Strict as Map import Data.Text (Text)+import System.FilePath ((</>)) import qualified Data.Text as Text import GHC.Generics (Generic) import Test.Tasty@@ -209,7 +210,7 @@         l <- ok (F.from (F.fileExact F.toml path))         case F.extract l of           Right (Paths d t) -> do-            F.relative d @?= Jail.jailDirectory j <> "/conf/data"+            F.relative d @?= (Jail.jailDirectory j </> "conf" </> "data")             fmap F.metaName (F.taggedMetadata t) @?= Just "TOML file"           Left e -> assertFailure (Text.unpack (F.renderErrors e))     , testCase "§10 partial" $ do
test/Spec.hs view
@@ -1,5 +1,7 @@ module Main (main) where +import System.Directory (getCurrentDirectory)+import System.FilePath ((</>)) import Test.Tasty  import qualified Figment.Test.Adversarial as Adversarial@@ -8,6 +10,7 @@ import qualified Figment.Test.Env as Env import qualified Figment.Test.Errors as Errors import qualified Figment.Test.Figment as Figment+import qualified Figment.Test.Hardening as Hardening import qualified Figment.Test.MergeLaws as MergeLaws import qualified Figment.Test.Partial as Partial import qualified Figment.Test.Providers as Providers@@ -15,7 +18,9 @@ import qualified Figment.Test.Tutorial as Tutorial  main :: IO ()-main =+main = do+  -- resolved before any test runs: Jail changes the working directory+  goldenDir <- (</> ("test" </> "golden")) <$> getCurrentDirectory   defaultMain $     testGroup       "figment"@@ -26,8 +31,9 @@       , Providers.tests       , Env.tests       , Cli.tests-      , Errors.tests+      , Errors.tests goldenDir       , Adversarial.tests+      , Hardening.tests       , Readme.tests       , Tutorial.tests       ]
− test/golden/err-configuration.txt
@@ -1,1 +0,0 @@-ConfigurationError "Depth" "must be a positive Int"
− test/golden/err-decode.txt
@@ -1,1 +0,0 @@-DecodeError (Path [Key "port"]) "expected Int, got String"
− test/golden/err-depth.txt
@@ -1,1 +0,0 @@-DepthExceeded (Path [Key "a",Key "b",Key "3"]) (UnsafeDepth 64)
− test/golden/err-missing.txt
@@ -1,1 +0,0 @@-MissingKey (Path [Key "host"])
− test/golden/err-source.txt
@@ -1,1 +0,0 @@-SourceError "config.toml" "unexpected token at line 3"
− test/golden/err-validation.txt
@@ -1,1 +0,0 @@-ValidationError (Path []) "port must be in 1..65535"