51 Commits

Author SHA1 Message Date
141e9ad646 Write release notes for ConfigKit v1.5.0 2026-12-06 04:42:08 +00:00
85c334e396 Adopt ReleaseKit v0.11.0 and migrate local delivery credentials 2026-12-06 04:00:25 +00:00
89340cee1e Remove completed import planning documents 2026-12-05 22:35:47 +00:00
8d6622722b Resolve literal glob prefixes in a single traversal 2026-12-05 22:11:14 +00:00
b38bd101f2 Resolve symlink target parents in filesystem order 2026-12-05 22:02:16 +00:00
4668d5d7f9 Clarify which native imports inspect symlink targets 2026-12-05 21:55:55 +00:00
ad23955984 Resolve native glob prefix parents through their link targets 2026-12-05 21:55:41 +00:00
2e1a74e8c0 Record repeated glob prefix traversal cost 2026-12-05 21:43:37 +00:00
cda0fa5134 Record directory import integration defect 2026-12-05 21:38:02 +00:00
22a022a9e8 Record absolute import review findings 2026-12-05 21:27:40 +00:00
9d86e3377a Validate external imports and retain distinct glob traversal targets 2026-12-05 21:05:10 +00:00
22f2731e81 Document import scope independently of resource and bootstrap anchors 2026-12-05 20:59:24 +00:00
f7262558c5 Demonstrate shared external configuration imports 2026-12-05 20:57:18 +00:00
6eb0a3f08f Verify external imports across the public loading lifecycle 2026-12-05 20:56:02 +00:00
83b272c116 Retain captured import policy independently of secrets bootstrap 2026-12-05 20:52:29 +00:00
4254b13ff6 Keep overlay access anchored while preserving derived import policy 2026-12-05 20:51:03 +00:00
6e0c5436e9 Provide passive resource contexts for external imported sources 2026-12-05 20:49:30 +00:00
ddb014ca05 Inspect wildcard directories before advancing to parents 2026-12-05 20:48:20 +00:00
30f04dd5e1 Establish glob starting locations before wildcard discovery 2026-12-05 20:46:47 +00:00
9c02607c26 Resolve named and directory imports within their selected filesystem 2026-12-05 20:43:30 +00:00
323728870c Parse import selector roots and share literal path resolution 2026-12-05 20:41:30 +00:00
ae1578494a Resolve host import links in bounded and unbounded access modes 2026-12-05 20:39:53 +00:00
7dd4218f6f Support unbounded host filesystem access 2026-12-05 20:38:31 +00:00
1003a3749a Represent import boundaries independently of context anchors 2026-12-05 20:37:05 +00:00
f75553a7fb Separate import containment from resource anchors 2026-12-05 20:34:01 +00:00
10f5806800 Plan absolute and parent-relative import implementation 2026-12-05 19:35:01 +00:00
8c04dfdaa4 Clarify import context compatibility and glob traversal 2026-12-05 19:20:57 +00:00
ccedd79cad Clarify import path and resource context semantics 2026-12-05 19:16:28 +00:00
19512adfab Settle import path decisions and minor release scope 2026-12-05 19:12:16 +00:00
e2ec298cbc Plan absolute and parent-relative imports 2026-12-05 19:05:54 +00:00
9037fdb74e Remove completed failed-load inspection plans 2026-12-05 18:58:21 +00:00
a44134769f Index source operations during history construction 2026-12-05 17:15:50 +00:00
df7e0eaec5 Clarify inspection access through load errors 2026-12-05 17:11:42 +00:00
447868e285 Record consumption of nested inheritance selectors 2026-12-05 17:11:20 +00:00
1858c9331f Preserve the composed main tier on load failure 2026-12-05 17:09:53 +00:00
57c943a156 Record source history scaling finding 2026-12-05 16:52:55 +00:00
a675d3ab50 Record inspection integration audit findings 2026-12-05 16:48:28 +00:00
36a54ec788 Record failed-load inspection review 2026-12-05 16:32:03 +00:00
729724deba Document failed-load inspection behavior 2026-12-05 16:15:33 +00:00
cb31324243 Demonstrate reporting failed configuration loads 2026-12-05 16:11:40 +00:00
b3bbc16e4b Verify inspection evidence after failed loads 2026-12-05 16:10:23 +00:00
a7053e5aaa Expose inspection views on load errors 2026-12-05 16:07:09 +00:00
40c1d94b35 Retain the last coherent load checkpoint 2026-12-05 16:05:52 +00:00
d159df794a Retain resolved inspection on load failure 2026-12-05 16:02:11 +00:00
cc1cfcc017 Retain decoded and resolver entry inspection 2026-12-05 16:00:18 +00:00
ca35af3a65 Retain source history for inspection 2026-12-05 15:58:38 +00:00
de50550eea Share inspection finalization for load outcomes 2026-12-05 15:55:28 +00:00
34bf78de83 Record inspection of failed configuration loads 2026-12-05 15:53:18 +00:00
0778cfcfd1 Plan inspection across configuration failures 2026-12-05 15:35:35 +00:00
5e0f40636f Settle failed configuration inspection decisions 2026-12-05 15:29:59 +00:00
491ea1e060 Plan inspection of rejected configurations 2026-12-05 15:09:37 +00:00
74 changed files with 3432 additions and 288 deletions

View File

@@ -50,6 +50,8 @@ Start with one file. Optional features use the same loading and inspection model
references and choose which configuration fields to hide in inspection output. references and choose which configuration fields to hide in inspection output.
- [Inspect a load](docs/config.md#layered-metadata): examine sources, presence, - [Inspect a load](docs/config.md#layered-metadata): examine sources, presence,
history, safe YAML output, or [changes between two loads](docs/config.md#effective-configuration-diffs). history, safe YAML output, or [changes between two loads](docs/config.md#effective-configuration-diffs).
- [Investigate a rejected load](docs/consumers/README.md#failed-load-reporting):
inspect available evidence while retaining its diagnostics and failure status.
- [Hand settings to libraries](docs/consumers/README.md#component-handoff): share - [Hand settings to libraries](docs/consumers/README.md#component-handoff): share
one result and let each consumer select its own settings and reporting scope. one result and let each consumer select its own settings and reporting scope.
@@ -72,7 +74,7 @@ examples](docs/config.md#strict-document-composition) for the details and
exceptions. exceptions.
Loading finishes before the call returns. ConfigKit then stays inactive until you Loading finishes before the call returns. ConfigKit then stays inactive until you
call it again; inspection uses the saved result. See call it again; inspection uses saved load evidence. See
[completion and resource lifetime](docs/config.md#completion-and-resource-lifetime). [completion and resource lifetime](docs/config.md#completion-and-resource-lifetime).
The [architecture goals](docs/policy/architecture.md#success-criteria) and The [architecture goals](docs/policy/architecture.md#success-criteria) and

View File

@@ -7,6 +7,8 @@ import (
) )
// LoadError reports safe structured diagnostics for a failed configuration load. // LoadError reports safe structured diagnostics for a failed configuration load.
// InspectSubtree provides a reporting view when a coherent snapshot is available;
// the error remains the load's outcome and no execution result is returned.
// It intentionally does not expose or unwrap parser and application errors. // It intentionally does not expose or unwrap parser and application errors.
type LoadError struct{ value *engine.LoadError } type LoadError struct{ value *engine.LoadError }

View File

@@ -2,7 +2,7 @@ package configkit
import "go.maximumdirect.net/configkit/internal/engine" import "go.maximumdirect.net/configkit/internal/engine"
// Difference describes one changed value or subtree between two successful loads. // Difference describes one changed value or subtree between two inspection snapshots.
// Left is the earlier value and Right is the later value. Snapshots are copies; // Left is the earlier value and Right is the later value. Snapshots are copies;
// Present distinguishes absence from explicit null. Redacted reports hiding // Present distinguishes absence from explicit null. Redacted reports hiding
// based on sensitivity from either load. Mappings compare by key; a changed // based on sensitivity from either load. Mappings compare by key; a changed

View File

@@ -2,7 +2,10 @@
## Status ## Status
Accepted. Accepted. The inherited import-containment provision is partially superseded by
[ADR 0026](0026-optional-host-import-containment.md), which separates optional
import containment from resource and overlay anchors. The context-selection and
overlay-binding decisions continue to apply.
## Date ## Date

View File

@@ -0,0 +1,74 @@
# ADR 0025: Inspect Failed Configuration Loads
## Status
Accepted.
## Date
2026-12-05
## Context
Applications need to explain rejected configuration using the evidence produced
by the same load. Diagnostics identify failures, while values, history, and
source information help operators understand how those failures arose. A load
can fail after producing a coherent configuration candidate, even though it
cannot return a successful execution result.
[ADR 0003](0003-preserve-presence-and-resolution-history.md) and
[ADR 0005](0005-explicit-overrides-and-safe-explanation.md) establish retained
history and safe explanation. [ADR 0008](0008-complete-on-return-loading.md)
describes synchronous loading and cleanup. Inspection should preserve those
boundaries while making available evidence independent of validation outcome.
## Decision
Keep returning a nil result and the existing error on load failure. A LoadError
may expose a frozen reporting snapshot through `InspectSubtree`, using the same
Inspection interface available from a successful result. Inspection does not
change the error outcome, resume processing, rerun callbacks, or reload inputs.
Select the latest coherent, admissible candidate already produced by the load:
the main tier, composed sources, inherited sources, decoded values, overridden
values, resolved values, or validated values. Identify the represented checkpoint
on the view. Earlier acquisition, parsing, schema, and composition failures can
have no view; retained-history limits can prevent a candidate from being retained
or require an earlier available candidate. Raw-source checkpoints do not invent
typed defaults or partially completed work. A failure in final validation reports
the candidate supplied to the validator, including when that callback mutates it.
Reuse existing classification, history, source evidence, passive resource
contexts, rendering, and redaction. Classification must finish before a view is
exposed. Only contexts actually established are available; the error's source
catalog remains consistent with its view. Loading handles are released before
return as before.
Extend [ADR 0010](0010-effective-configuration-diff.md) and
[ADR 0024](0024-compare-inspection-views-across-application-types.md) to allow
comparison of available inspection views regardless of load outcome or
checkpoint. Matching scopes, structural equality, atomic sequences, ancestor
changes, and paired redaction retain their existing semantics. Comparison does
not compare diagnostic status. The existing same-type result comparison remains
unchanged.
## Alternatives considered
- **Restrict inspection to successful loads.** This withholds useful evidence
precisely when operators need to diagnose rejected configuration.
- **Reload with validation disabled.** A second invocation can observe different
inputs and repeat callbacks, and does not faithfully describe the failed load.
- **Expose partial mutable processing state.** Incomplete work and callback edits
can misrepresent the candidate and its origins. Coherent frozen checkpoints
preserve the existing reporting boundary.
- **Introduce a reduced failure reporting API.** This duplicates presentation
and disclosure rules that the existing inspection interface already supplies.
## Consequences
Applications can use one reporting interface for available evidence from both
successful and failed loads while continuing to handle errors normally. An
earlier checkpoint describes only the work completed through that point; it is
not proof of validation or of later successful processing. Existing source and
history limits continue to apply, and unavailable snapshots do not erase the
original diagnostics.

View File

@@ -0,0 +1,81 @@
# ADR 0026: Separate Import Containment from Resource Anchors
## Status
Accepted. Partially supersedes the inherited import-containment provision of
[ADR 0022](0022-main-relative-context.md).
## Date
2026-12-05
## Context
Applications need to import shared configuration outside the main file's
directory. The relative lookup base, import boundary, and passive resource root
serve different purposes. Treating the main directory as all three prevents
ordinary shared-file layouts and couples import access to resource coordinates.
[ADR 0019](0019-explicit-configuration-discovery.md) keeps main selection explicit.
[ADR 0016](0016-independent-import-controls.md) separates import selection controls,
and [ADR 0015](0015-shared-dependency-ready-ordering.md) owns dependency ordering.
Broader path selection can use these existing loading responsibilities.
## Decision
Host imports have no implicit containment boundary. Absolute YAML selectors name
host paths, and relative selectors use the declaring source's canonical directory.
An explicit FilesystemContext.Root retains canonical containment for every
transitive import. Synthetic host sources require an explicit BaseDir and may
omit Root. An absent input with BaseDir alone uses that base without inferring
the process working directory.
Within a supplied filesystem, leading-slash YAML selectors start at its namespace
root. Relative selectors use the declaring source's namespace directory. The
selected namespace and any explicit root continue to bound access; native Go
path arguments and filesystem symlink targets retain their existing syntax.
Apply this interpretation to path, directory, and glob selectors. Establish a
glob's literal starting location before wildcard discovery, then inspect each
segment in order, including parent segments following wildcards. Preserve source
identity, admission, dependency ordering, budgets, composition, and inspection.
Represent the optional import boundary separately from the existing resource,
overlay, and bootstrap anchor and the lookup base. Derived main-relative inputs
inherit those independent facts. Contained sources retain their existing passive
resource coordinates; an external unbounded host source uses its own canonical
directory as its passive resource root. This root does not constrain imports.
Captured main sources retain their import policy separately. Omitting a later
root preserves that policy; a compatible explicit root may narrow an unbounded
capture at its resource anchor. Existing incompatible-context errors remain.
Overlay lookup retains its established anchor and containment. Configured secrets
bootstrap retains its separate relative-only, anchored access under
[ADR 0023](0023-explicit-configured-secrets-bootstrap.md). Loading remains
synchronous and complete on return as described by
[ADR 0008](0008-complete-on-return-loading.md), releasing loading handles before
return and exposing passive resource contexts.
## Alternatives Considered
- Retain implicit main-directory containment and require callers to widen Root.
This leaves shared layouts dependent on redundant context setup.
- Widen every context root to the host root. This changes existing resource,
overlay, and bootstrap coordinates along with import access.
- Add a public permission switch. The existing explicit Root already expresses
intentional containment.
- Add a separate acquisition pipeline for absolute imports. This duplicates
admission, accounting, link handling, and lifecycle responsibilities.
## Consequences
This is an additive minor-release feature: existing valid configurations, public
signatures, explicit roots, and resource coordinates remain compatible. Default
host import scope deliberately becomes broader. Applications requiring the
previous containment boundary specify Root explicitly.
The access owner supports bounded host, unbounded host, and native namespace
operations. These use ordinary filesystem facilities and the existing stable-input
assumptions; the change establishes no sandbox or concurrent-mutation guarantee.
The roadmap owns implementation progress until canonical contracts are updated.

View File

@@ -145,7 +145,8 @@ from attempted search directories. The same root-only context can accompany a
search that selects a file: the selected file determines its base and must be search that selects a file: the selected file determines its base and must be
inside `Root`. A selected host file rejects an explicit `BaseDir` or native inside `Root`. A selected host file rejects an explicit `BaseDir` or native
filesystem context. Invalid context fails without resuming selection. Layered filesystem context. Invalid context fails without resuming selection. Layered
overlays keep their independent `OverlayFilesystem` requirement. overlays select an explicit context, the resolved main context, or their fallback
in the order described under [layered loading](#layered-loading).
When a search selects a file, inspection reports that actual file with ordinary When a search selects a file, inspection reports that actual file with ordinary
source IDs, paths, placement, metadata origins, and resource context. Missing source IDs, paths, placement, metadata origins, and resource context. Missing
@@ -212,9 +213,11 @@ CLI coordinates remain rooted at the application root. Ordinary `Load` recognize
source-root collection declarations whether or not imports are enabled; an source-root collection declarations whether or not imports are enabled; an
`imports` declaration still requires imports to be enabled. `NoSource` may enable `imports` declaration still requires imports to be enabled. `NoSource` may enable
imports, but it has no main declarations to traverse. It accepts an explicit imports, but it has no main declarations to traverse. It accepts an explicit
filesystem context: a host context requires an absolute existing `Root` and may filesystem context: a host context supplies an absolute existing `BaseDir`,
omit `BaseDir` to use that root as its internal import base; a native context `Root`, or both. BaseDir alone also supplies the resource/overlay anchor and
requires its namespace, `BaseDir`, and `Root`. Supplied context is validated even leaves imports unbounded; Root alone supplies both base and explicit boundary.
An explicitly empty context is invalid and never selects the working directory.
A native context requires its namespace, `BaseDir`, and `Root`. Supplied context is validated even
when imports are disabled. An active ordinary overlay requires this explicit when imports are disabled. An active ordinary overlay requires this explicit
context. `NoSource` accepts overrides and remains absent rather than contributing context. `NoSource` accepts overrides and remains absent rather than contributing
an empty document. an empty document.
@@ -256,6 +259,37 @@ placement available when loading failed, which may be incomplete; it does not
promise a record for every attempted source. Nil or zero-valued errors and empty promise a record for every attempted source. Nil or zero-valued errors and empty
or unknown IDs return false. or unknown IDs return false.
`LoadError.InspectSubtree(path)` obtains the same reporting view as a successful
result when the failing invocation retained a coherent snapshot. The Boolean
reports snapshot availability and path validity, not whether that path is present
or whether loading succeeded. An absent scope is valid. The error and its
diagnostics remain authoritative; no typed execution result is returned. Queries
use retained evidence without reopening sources or rerunning callbacks. The view
and error share the same conservatively sanitized source catalog, and resource
contexts are available only where they were established.
`Inspection.Stage()` identifies the processing completed for the snapshot:
| Value | Represented state |
| --- | --- |
| `main` | Completed main tier before later tiers or selected overlay. |
| `composed` | Completed source and overlay composition, before inheritance. |
| `inherited` | Completed structural inheritance, before typed defaults and decoding. |
| `decoded` | Decoded typed values before CLI assignments. |
| `overridden` | Values after CLI assignments, before application resolution. |
| `resolved` | Values after recorded resolution, before successful final validation. |
| `validated` | A successful load's completed inspection. |
The first three represent source trees without invented defaults. Failed phases
do not contribute partial changes: a resolver failure exposes its entry candidate,
and a validator failure exposes the candidate presented to it, even when the
validator mutates it. A resolved view does not assert successful secret lookup,
final identity checking, or validation. Earlier failures can have diagnostics
and sources without a view. With absent input there is no raw source checkpoint,
although decoding defaults can produce a typed snapshot. Existing history limits
can prevent a view or select an earlier admissible checkpoint; the original error
and diagnostics remain unchanged. The zero view's stage is empty.
### Completion and resource lifetime ### Completion and resource lifetime
`Load` finishes its work before returning. Success means input assembly, `Load` finishes its work before returning. Success means input assembly,
@@ -344,12 +378,13 @@ selections fail without a base, while an empty `path: []` remains a no-op.
Invalid declarations still fail, and skipped imports create no search evidence. Invalid declarations still fail, and skipped imports create no search evidence.
Selected main failures never trigger fallback or a second discovery attempt. Selected main failures never trigger fallback or a second discovery attempt.
Derived contexts preserve the main namespace and containment root, while lookup Derived contexts preserve the main namespace, optional import boundary and
starts at its resolved base. A host file's base is its canonical target directory, resource/overlay anchor, while lookup starts at its resolved base. A host file's
including when the selected filename is a symlink. A wider root permits contained base is its canonical target directory, including when the selected filename is
parent-relative imports without moving the lookup base. Explicit non-file and a symlink. Explicit Root bounds parent-relative and absolute imports without
absent-main contexts can provide a base; an absent host input may use its root as moving that base. Explicit non-file, absent-main and fallback host contexts may
base. An unused fallback is not opened or checked for existence. See the use BaseDir alone; a root-only absent context uses Root as its base. An unused
fallback is not opened or checked for existence. See the
[consumer example](../examples/consumers/main_relative.go). [consumer example](../examples/consumers/main_relative.go).
Source IDs follow acquisition order—main and its depth-first imports, then each Source IDs follow acquisition order—main and its depth-first imports, then each
@@ -593,8 +628,13 @@ resolution query follows the callback's lifetime guard. Queries perform no
filesystem access. Obtain IDs from exact origin locations rather than guessing filesystem access. Obtain IDs from exact origin locations rather than guessing
one context for a composite origin or an application-derived value. one context for a composite origin or an application-derived value.
`ResourceContext.FS` is rooted at the source's configured root, and `BaseDir` `ResourceContext.FS` uses the load context's resource anchor for contained sources,
is its slash-relative directory inside that root. This includes imported and `BaseDir` is the source directory relative to that anchor using slash paths.
An unbounded external host import instead uses its own canonical directory as
its passive resource root, with BaseDir `.`. That resource root does not bound
the source's transitive imports. BaseDir-only synthetic host contexts use that
base as their resource anchor. Explicit-root and native coordinates retain their
configured roots. This includes imported
sources, selected overlays, host files even without enabled imports, native sources, selected overlays, host files even without enabled imports, native
files, and byte, reader, or mapping inputs with an explicit or main-derived context. CLI and files, and byte, reader, or mapping inputs with an explicit or main-derived context. CLI and
contextless synthetic inputs have no resource context. To open a relative contextless synthetic inputs have no resource context. To open a relative
@@ -743,11 +783,11 @@ historical classification. Redaction empties `Text` while retaining presence
and null state. Returned copies are detached; evidence does not reopen inputs. and null state. Returned copies are detached; evidence does not reopen inputs.
Consult [ADR 0013](adr/0013-shared-source-version-checks.md) for the accepted Consult [ADR 0013](adr/0013-shared-source-version-checks.md) for the accepted
decision and the [development guide](development.md#baseline-validation) for decision and the [development guide](development.md#baseline-validation) for
the completed implementation and remediation records in Git history. development validation guidance.
### Layered metadata ### Layered metadata
Use inspection to understand a completed load without reading the files again: Use inspection to understand an available snapshot without reading the files again:
| Need | API to use | | Need | API to use |
| --- | --- | | --- | --- |
@@ -891,9 +931,11 @@ translated to a fixed safe error. There is no unredacted rendering option and
ConfigKit performs no implicit logging. ConfigKit performs no implicit logging.
`Result.Config` is the explicit trusted boundary and contains ordinary typed values, `Result.Config` is the explicit trusted boundary and contains ordinary typed values,
including secrets. Metadata records, diagnostics, and load errors contain no including secrets. Metadata and diagnostics do not embed configuration snapshots.
configuration values. Explanation snapshots deliberately expose non-secret `LoadError.Error()` does not render diagnostic messages or input values. Explicitly
configuration history after applying the redaction contract below. Applications requested inspection snapshots, including those obtained from a load error, can
expose non-secret current and historical values under the same redaction rules.
Applications
must still keep source labels, resolution reasons, and diagnostic messages value-free must still keep source labels, resolution reasons, and diagnostic messages value-free
because ConfigKit cannot infer and sanitize secrets embedded in arbitrary application because ConfigKit cannot infer and sanitize secrets embedded in arbitrary application
prose. prose.
@@ -1030,7 +1072,8 @@ its normal nil-result/`LoadError` behavior, which callers handle before invoking
`Diff`. `Diff`.
`Inspection.Diff` compares focused views at the same canonical location, even `Inspection.Diff` compares focused views at the same canonical location, even
when their application root Go types differ. It compares the complete frozen when their application root Go types, checkpoints, or load outcomes differ. It
compares represented values rather than diagnostic status. It compares the complete frozen
snapshots with the same paired redaction and retains records at, below, or above snapshots with the same paired redaction and retains records at, below, or above
the focus. Because sequences and structural replacements can be atomic, an the focus. Because sequences and structural replacements can be atomic, an
ancestor record may reflect a change outside the selected value. Different ancestor record may reflect a change outside the selected value. Different
@@ -1158,16 +1201,18 @@ bootstrap again.
The prepared source is a reusable snapshot of the selected main document, The prepared source is a reusable snapshot of the selected main document,
including its unconsumed controls, byte count, canonical file identity, base, including its unconsumed controls, byte count, canonical file identity, base,
and containment root. A later load neither rediscovers nor rereads the main resource/overlay/bootstrap anchor, and independent import boundary. A later load
and does not repeat bootstrap; it reads imports and resources when accessed and neither rediscovers nor rereads the main and does not repeat bootstrap; it reads imports and resources when accessed and
looks up secrets anew. The main's source record retains `SourceKindFile`. Each looks up secrets anew. The main's source record retains `SourceKindFile`. Each
load clones the document, creates its own source IDs load clones the document, creates its own source IDs
and records, and applies normal input accounting. No file handle or secret-file and records, and applies normal input accounting. No file handle or secret-file
contents remain in the prepared source. With no later context, loading uses the contents remain in the prepared source. With no later context, loading uses the
captured context. A supplied later host context must resolve to the same root, captured context. A later host context with Root omitted preserves the captured
base, and main path; equivalent path spellings and root symlink aliases are import policy, including explicit containment captured during preparation. An
accepted. Native contexts, a file `BaseDir`, and different roots fail with explicit Root canonically equal to the captured anchor retains containment or
`options.invalid`. A caller needing another root prepares the original source narrows an unbounded capture. Equivalent path spellings and root symlink aliases
are accepted without reselecting the main. Native contexts, a file `BaseDir`, and
different roots fail with `options.invalid`. A caller needing another root prepares the original source
again. These rules apply to ordinary options and layered main inputs. again. These rules apply to ordinary options and layered main inputs.
The helper returns a non-nil report on every attempt and a zero, unusable source The helper returns a non-nil report on every attempt and a zero, unusable source
@@ -1804,8 +1849,16 @@ The [mounted-root example](../examples/consumers/config_controls_test.go) shows
an imported payload becoming application-root `config`. Inspection YAML can an imported payload becoming application-root `config`. Inspection YAML can
contain that data and retains its existing lack of a reloadability guarantee. contain that data and retains its existing lack of a reloadability guarantee.
Path declarations use slash-separated relative paths. Absolute paths and network Path, directory and glob selectors accept absolute and parent-relative paths.
URLs are invalid. Each path resolves from its declaring file's canonical directory. Absolute host selectors name host paths directly; relative selectors use the
declaring file's canonical directory, including for transitive external imports.
Synthetic and absent contexts use their selected base. Within a supplied `fs.FS`,
a leading `/` selects from that namespace's root; relative paths use the declaring
source's namespace directory. Targets must remain addressable within that
namespace and any explicit Root. This YAML syntax does not change the
slash-relative `fs.ValidPath` syntax of native Go source/context arguments.
Network URLs and schemes remain invalid; supported host volume roots are paths.
There is no shell expansion, environment substitution or remote fetching.
An empty `path: []` selects nothing; it succeeds even when `required: true` because An empty `path: []` selects nothing; it succeeds even when `required: true` because
there are no named targets to be missing. A nonempty required path list verifies there are no named targets to be missing. A nonempty required path list verifies
every named target, including targets later excluded from selection. every named target, including targets later excluded from selection.
@@ -1830,7 +1883,16 @@ walks only directories selected by preceding segments, and reads wildcard
directories in bounded batches. Every examined entry consumes the separate visit directories in bounded batches. Every examined entry consumes the separate visit
budget, including nonmatches. Literal components are explicit path components; budget, including nonmatches. Literal components are explicit path components;
`follow` and `hidden` filter only wildcard-discovered entries. `exclude` filters `follow` and `hidden` filter only wildcard-discovered entries. `exclude` filters
final candidate basenames. final candidate basenames. Absolute roots and the longest literal prefix select
the starting location before wildcard discovery. For Root `/allowed/config`,
`/allowed/config/fragments/*.yml` starts in its contained fragments directory;
ancestors used only to resolve that prefix are not discovery directories. Every
actual discovery/traversal target remains subject to containment. Literal
components are inspected in order, so a missing directory before `..` cannot be
cleaned away. After a wildcard, `..` advances from each inspected matched
directory, preserving link targets and access failures. For example,
`services/*/../shared/*.yml` expands `*` before traversing its parent. A fully
literal glob follows named-file requiredness and regular-file checks.
`Options.ImportDefaults` and `LayeredOptions.ImportDefaults` provide one `Options.ImportDefaults` and `LayeredOptions.ImportDefaults` provide one
application-owned load-wide policy for enabled imports in the main source, application-owned load-wide policy for enabled imports in the main source,
@@ -1931,31 +1993,50 @@ Physical paths continue to resolve from the file that declares each import.
An actual empty mapping contributes an empty item, while an unmatched declaration An actual empty mapping contributes an empty item, while an unmatched declaration
with default or explicit `required: false` contributes nothing. with default or explicit `required: false` contributes nothing.
For host files, the configuration root defaults to the selected file's For host files, imports are unbounded by default, subject to ordinary filesystem
canonical directory. A host file may supply `FilesystemContext.Root` to widen access and the existing admission and resource budgets. `FilesystemContext.Root`
that root but may not supply `BaseDir` or a native `FS`. Byte, reader, and explicitly bounds canonical targets, including links and transitive imports.
mapping inputs with host context must provide both `BaseDir` and `Root` as The selected file and base must be inside that root. A selected file determines
absolute existing directories. For `Filesystem.File`, the default root is `.` its own base and rejects BaseDir or native FS. Its canonical directory remains
in its namespace and the base is the selected file's directory. An explicit the default resource/overlay/bootstrap anchor even when imports can reach beyond
context must use the same `Filesystem` namespace and may set `Root` to contain it. Existing valid configurations and resource coordinates remain compatible;
the file and its base; it may not supply `BaseDir`. Byte, reader, and mapping applications preserving the earlier containment scope explicitly set Root.
inputs with native context provide both `BaseDir` and `Root` as slash-relative
`fs.ValidPath` directories in `FS` (`.` means its root), with the base inside Byte, reader and mapping host inputs require an absolute existing BaseDir even
the root. Context paths are checked even when imports and overlays are for absolute-only selectors. Root is optional; omission uses BaseDir as the
inactive. Diagnostic labels, including URI-looking labels, never imply resource/overlay/bootstrap anchor with unbounded imports. Explicit Root must be
filesystem paths. Nonregular targets are rejected before opening to avoid an existing directory containing the base. Context paths are checked even when
blocking on FIFOs; post-open regular-file checks remain in place under the imports and overlays are inactive. Diagnostic labels, including URI-looking
stable-input assumption. ConfigKit canonicalizes symlinks, checks containment labels, never imply filesystem paths or a working-directory base.
with relative paths, and opens the canonical root-relative target through a
library-owned root handle. Contained relative or absolute symlink targets are For `Filesystem.File`, the default root is `.` in its namespace and the base is
accepted; escapes are rejected. Canonical paths define identity, so hard links the selected file's directory. An explicit context must use the same Filesystem
at distinct paths remain distinct sources. Native filesystems use slash-path namespace and may set Root to contain the file and base; it may not supply
operations. Where the supplied `fs.FS` implements `fs.ReadLinkFS`, ConfigKit BaseDir. Synthetic native inputs still supply both BaseDir and Root as
uses that capability to inspect and resolve discovered links; otherwise it slash-relative fs.ValidPath directories in FS, with the base inside the root.
follows the filesystem's ordinary `fs.FS` behavior. ConfigKit does not require There is no host fallback from a native namespace.
every native filesystem to expose link inspection, and native filesystem
behavior is not a general sandbox guarantee. Imports stay in their selected Nonregular targets are rejected before opening to avoid blocking on FIFOs;
namespace and root. post-open regular-file checks remain in place under the stable-input assumption.
Host canonical paths define identity, so hard links at distinct paths remain
distinct sources. Unbounded host access uses ordinary OS operations; explicit
containment uses a library-owned root handle. Host links may reach external
locations under unbounded access; explicit Root still bounds their canonical
targets. Discovered-link follow controls remain independent of containment.
Native named-file imports delegate access to the supplied fs.FS. Directory and
glob traversal use fs.ReadLinkFS to inspect links when that capability is supplied;
otherwise they follow the filesystem's ordinary capabilities. ConfigKit's native
link-target inspection rejects absolute symlink targets. YAML leading-slash
selector rewriting applies only to selectors, not to filesystem symlink targets.
These facilities provide no additional sandbox or concurrent-filesystem mutation
guarantee.
Import widening does not widen selected-overlay lookup or configured secrets
bootstrap. Those continue using the legacy anchor and their own contracts.
[ADR 0026](adr/0026-optional-host-import-containment.md) records the separation;
the maintained [external-import example](../examples/consumers/external_imports_test.go)
and [YAML illustration](../examples/consumers/testdata/external-imports/main.yml)
show a one-load consumer workflow.
An active-stack repeat is `import.cycle` and reports the complete cycle's import An active-stack repeat is `import.cycle` and reports the complete cycle's import
sites. A previously visited canonical path is `import.repeated` and reports both sites. A previously visited canonical path is `import.repeated` and reports both

View File

@@ -24,13 +24,26 @@ Start with one file, then choose the tasks your application needs:
| Load one file | [Happy path](#happy-path) and the [README example](../../README.md#load-a-configuration-file) | | Load one file | [Happy path](#happy-path) and the [README example](../../README.md#load-a-configuration-file) |
| Supply fixed defaults and check application rules | [Defaults and application rules](#defaults-and-application-rules) | | Supply fixed defaults and check application rules | [Defaults and application rules](#defaults-and-application-rules) |
| Add bundled defaults beneath application settings | [Native filesystem and layered input](#native-filesystem-and-layered-input) | | Add bundled defaults beneath application settings | [Native filesystem and layered input](#native-filesystem-and-layered-input) |
| Import a shared external file | [YAML illustration](../../examples/consumers/testdata/external-imports/main.yml) and the [one-load resource example](../../examples/consumers/external_imports_test.go) |
| Select files or an overlay | [Discovery](#explicit-main-file-discovery), [import defaults](#import-defaults-and-selection-inspection), and the [overlay reference](../config.md#selected-overlays) | | Select files or an overlay | [Discovery](#explicit-main-file-discovery), [import defaults](#import-defaults-and-selection-inspection), and the [overlay reference](../config.md#selected-overlays) |
| Reuse settings or combine record lists | [Inheritance](#named-sibling-inheritance) and [identified sequences](#identified-prompt-sequences) | | Reuse settings or combine record lists | [Inheritance](#named-sibling-inheritance) and [identified sequences](#identified-prompt-sequences) |
| Handle credentials | [Typed-secret reference](../config.md#typed-secret-references), [configured startup](#configured-secrets-startup), and the [direct-directory example](../../examples/consumers/consumers_test.go) | | Handle credentials | [Typed-secret reference](../config.md#typed-secret-references), [configured startup](#configured-secrets-startup), and the [direct-directory example](../../examples/consumers/consumers_test.go) |
| Inspect sources, earlier values, or changes | [Inspect a completed load](#inspect-a-completed-load) and [diffs](#effective-configuration-diffs) | | Inspect sources, earlier values, or changes | [Inspect a completed load](#inspect-a-completed-load) and [diffs](#effective-configuration-diffs) |
| Investigate a rejected load | [Failed-load reporting](#failed-load-reporting) |
| Hand one result to library consumers | [Component handoff](#component-handoff) | | Hand one result to library consumers | [Component handoff](#component-handoff) |
| Upgrade an existing consumer | [Migration guidance](#intentional-migration-changes) | | Upgrade an existing consumer | [Migration guidance](#intentional-migration-changes) |
## Shared external configuration
The [external-import example](../../examples/consumers/external_imports_test.go)
loads the [illustrated main](../../examples/consumers/testdata/external-imports/main.yml)
and a shared file, including its own relative import, in one ordinary load.
It follows the resource field's origin to select its SourceContext. The test also
shows deliberate containment with FilesystemContext.Root. See the
[import contract](../config.md#explicit-imports) for host and namespace-root
selectors and the [resource contract](../config.md#source-resource-contexts)
for coordinates and lifetime.
## Component handoff ## Component handoff
Register application and library rules in one definition, then load once and Register application and library rules in one definition, then load once and
@@ -131,6 +144,19 @@ Add imports, a selected overlay, or explicitly set CLI values through options
only when needed. An overlay changes configuration; choosing an LLM, report, or only when needed. An overlay changes configuration; choosing an LLM, report, or
execution profile remains application logic. execution profile remains application logic.
### Failed-load reporting
Handle the load error before using configuration. When it is a `*LoadError`,
`InspectSubtree` can provide the same reporting view as a result, including a
checkpoint that identifies how much processing completed. Keep the diagnostics
and failure status even when a view is available. Some early failures have no
view; source and diagnostic evidence can still be available.
The [failed-load example](../../examples/consumers/failure_inspection.go)
uses one invocation, reports an imported rejected value and its original source,
and shares show/explain presentation across successful and failed loads. See
the [checkpoint contract](../config.md#results-and-failures) for availability.
## Explicit main-file discovery ## Explicit main-file discovery
Applications choose the search conventions and their precedence, then pass the Applications choose the search conventions and their precedence, then pass the

View File

@@ -59,6 +59,8 @@ Accepted decisions:
- [Keep the public facade root-owned](adr/0006-public-facade.md) - [Keep the public facade root-owned](adr/0006-public-facade.md)
- [Compare frozen effective configuration snapshots](adr/0010-effective-configuration-diff.md) - [Compare frozen effective configuration snapshots](adr/0010-effective-configuration-diff.md)
- [Compare inspection views across application types](adr/0024-compare-inspection-views-across-application-types.md) - [Compare inspection views across application types](adr/0024-compare-inspection-views-across-application-types.md)
- [Inspect failed configuration loads](adr/0025-inspect-failed-configuration-loads.md)
- [Separate import containment from resource anchors](adr/0026-optional-host-import-containment.md)
- [Place inputs at literal application mapping paths](adr/0011-input-destinations.md) - [Place inputs at literal application mapping paths](adr/0011-input-destinations.md)
- [Share dependency-ready ordering](adr/0015-shared-dependency-ready-ordering.md) - [Share dependency-ready ordering](adr/0015-shared-dependency-ready-ordering.md)
- [Separate import selection controls](adr/0016-independent-import-controls.md) - [Separate import selection controls](adr/0016-independent-import-controls.md)
@@ -130,6 +132,7 @@ code changes. Use the component overview to find the corresponding implementatio
| --- | --- | --- | | --- | --- | --- |
| YAML syntax, diagnostics, parser limits | [Adapter tests](../internal/yaml/parse_test.go), [source translation](../internal/engine/parse_test.go) | `go test ./internal/yaml` and `go test ./internal/engine -run '^TestParseSource'` | | YAML syntax, diagnostics, parser limits | [Adapter tests](../internal/yaml/parse_test.go), [source translation](../internal/engine/parse_test.go) | `go test ./internal/yaml` and `go test ./internal/engine -run '^TestParseSource'` |
| File/reader access, imports, globs, containment | [Import internals](internal/imports.md), [source acquisition](../internal/engine/source_test.go), [FIFO](../internal/engine/source_fifo_test.go), [import traversal](../internal/engine/imports_test.go), [import evidence](../internal/engine/import_evidence_test.go), [relative destinations](../internal/engine/destination_import_test.go), [globs](../internal/engine/glob_test.go) | `go test ./internal/engine -run 'Source\|Import\|Glob\|Filesystem\|Nonregular\|RegularFile'` | | File/reader access, imports, globs, containment | [Import internals](internal/imports.md), [source acquisition](../internal/engine/source_test.go), [FIFO](../internal/engine/source_fifo_test.go), [import traversal](../internal/engine/imports_test.go), [import evidence](../internal/engine/import_evidence_test.go), [relative destinations](../internal/engine/destination_import_test.go), [globs](../internal/engine/glob_test.go) | `go test ./internal/engine -run 'Source\|Import\|Glob\|Filesystem\|Nonregular\|RegularFile'` |
| Absolute/parent-relative imports and external resource contexts | [Public lifecycle](../facade_absolute_import_test.go), [acquisition](../internal/engine/absolute_import_test.go), [glob roots](../internal/engine/glob_root_test.go), and [consumer example](../examples/consumers/external_imports_test.go) | `go test . -run AbsoluteImport`, `go test ./internal/engine -run 'Absolute\|External\|SelectGlob'`, and `go test ./examples/consumers` |
| Explicit main-file discovery and absent-input loading | [Candidate selection](../internal/engine/discovery_test.go), [load integration](../internal/engine/discovery_load_test.go), [public facade](../facade_discovery_test.go), and maintained [catalog](../examples/consumers/sequence_catalog_test.go) and [preset](../examples/consumers/discovery_test.go) examples | `go test ./internal/engine -run 'Discovery\|Search'`, `go test . -run 'Search'`, and `go test ./examples/consumers -run 'WorkingDirectoryPreset\|SequenceCatalog'` | | Explicit main-file discovery and absent-input loading | [Candidate selection](../internal/engine/discovery_test.go), [load integration](../internal/engine/discovery_load_test.go), [public facade](../facade_discovery_test.go), and maintained [catalog](../examples/consumers/sequence_catalog_test.go) and [preset](../examples/consumers/discovery_test.go) examples | `go test ./internal/engine -run 'Discovery\|Search'`, `go test . -run 'Search'`, and `go test ./examples/consumers -run 'WorkingDirectoryPreset\|SequenceCatalog'` |
| Import defaults, empty-selection evidence, and dependency-ready ordering | [Defaults and facade evidence](../facade_import_defaults_test.go), [engine import evidence](../internal/engine/import_evidence_test.go), [scheduler](../internal/engine/dependency_order_test.go), [scheduling integrations](../internal/engine/imports_test.go) | `go test ./internal/engine -run 'Import\|ScheduleDependencies\|Inheritance'`, `go test . -run 'ImportDefaults\|FacadeImport'`, and `go test ./examples/consumers` | | Import defaults, empty-selection evidence, and dependency-ready ordering | [Defaults and facade evidence](../facade_import_defaults_test.go), [engine import evidence](../internal/engine/import_evidence_test.go), [scheduler](../internal/engine/dependency_order_test.go), [scheduling integrations](../internal/engine/imports_test.go) | `go test ./internal/engine -run 'Import\|ScheduleDependencies\|Inheritance'`, `go test . -run 'ImportDefaults\|FacadeImport'`, and `go test ./examples/consumers` |
| Native filesystem and mapping sources | [Native acquisition](../internal/engine/native_filesystem_test.go), [filesystem facade](../facade_filesystem_test.go), [mapping facade](../facade_mapping_test.go) | `go test ./internal/engine -run 'NativeFilesystem'` and `go test . -run 'TestFacade'` | | Native filesystem and mapping sources | [Native acquisition](../internal/engine/native_filesystem_test.go), [filesystem facade](../facade_filesystem_test.go), [mapping facade](../facade_mapping_test.go) | `go test ./internal/engine -run 'NativeFilesystem'` and `go test . -run 'TestFacade'` |
@@ -141,6 +144,7 @@ code changes. Use the component overview to find the corresponding implementatio
| Shared source-version modes and evidence | [Engine source-version tests](../internal/engine/source_version_test.go), [public facade tests](../facade_source_version_mode_test.go), and [consumer example tests](../examples/consumers/layered_test.go) | `go test ./internal/engine -run 'SourceVersion'`, `go test . -run 'SourceVersion'`, and `go test ./examples/consumers` | | Shared source-version modes and evidence | [Engine source-version tests](../internal/engine/source_version_test.go), [public facade tests](../facade_source_version_mode_test.go), and [consumer example tests](../examples/consumers/layered_test.go) | `go test ./internal/engine -run 'SourceVersion'`, `go test . -run 'SourceVersion'`, and `go test ./examples/consumers` |
| Schema, defaults, projection, cloning | [Implementation flow](internal/overview.md#implementation-flow), [schema](../internal/engine/schema_test.go), [decoding](../internal/engine/decode_test.go), [projection and typed cloning](../internal/engine/projection_test.go) | `go test ./internal/engine -run 'Schema\|Decode\|Projection\|Clone\|Inline\|CompareDocument'` | | Schema, defaults, projection, cloning | [Implementation flow](internal/overview.md#implementation-flow), [schema](../internal/engine/schema_test.go), [decoding](../internal/engine/decode_test.go), [projection and typed cloning](../internal/engine/projection_test.go) | `go test ./internal/engine -run 'Schema\|Decode\|Projection\|Clone\|Inline\|CompareDocument'` |
| Current values and focused inspection | [Value tests](../facade_result_value_test.go), [view tests](../facade_inspection_view_test.go), [comparison tests](../facade_inspection_diff_test.go), and [history integration](../facade_inspection_history_test.go) | `go test . -run 'TestResultValue\|TestInspectionView'` and `go test ./internal/engine -run 'TestResultValue\|Diff\|History'` | | Current values and focused inspection | [Value tests](../facade_result_value_test.go), [view tests](../facade_inspection_view_test.go), [comparison tests](../facade_inspection_diff_test.go), and [history integration](../facade_inspection_history_test.go) | `go test . -run 'TestResultValue\|TestInspectionView'` and `go test ./internal/engine -run 'TestResultValue\|Diff\|History'` |
| Failed-load inspection and checkpoints | [Public failure views](../facade_failure_inspection_test.go), [evidence parity](../facade_failure_evidence_test.go), and [engine failure paths](../internal/engine/failure_inspection_test.go) | `go test . -run 'TestLoadErrorInspection\|TestFailureInspection'` and `go test ./internal/engine -run 'TestFailed\|TestFailureInspection\|TestSourceInspection\|TestLoadHistoryBudget'` |
| Lifecycle, resolution, validation, callback ownership | [Loading](../internal/engine/load_test.go), [resolution](../internal/engine/resolution_test.go), [validation](../internal/engine/validation_test.go), [ownership](../internal/engine/callback_ownership_test.go), [independence](../internal/engine/independence_test.go) | `go test ./internal/engine -run 'Load\|Resolution\|Validation\|Validator\|Hook\|Callback\|Parallel'` | | Lifecycle, resolution, validation, callback ownership | [Loading](../internal/engine/load_test.go), [resolution](../internal/engine/resolution_test.go), [validation](../internal/engine/validation_test.go), [ownership](../internal/engine/callback_ownership_test.go), [independence](../internal/engine/independence_test.go) | `go test ./internal/engine -run 'Load\|Resolution\|Validation\|Validator\|Hook\|Callback\|Parallel'` |
| Resolution sequence matching and inspection | [Correspondence](../internal/engine/resolution_correspondence_test.go), [auditing and history](../internal/engine/resolution_compare_test.go), [public integration](../facade_resolution_sequences_test.go) | `go test ./internal/engine -run 'Resolution\|History\|Explain\|Sensitivity'` and `go test . -run 'Resolution\|SequenceIdentity\|Diff'` | | Resolution sequence matching and inspection | [Correspondence](../internal/engine/resolution_correspondence_test.go), [auditing and history](../internal/engine/resolution_compare_test.go), [public integration](../facade_resolution_sequences_test.go) | `go test ./internal/engine -run 'Resolution\|History\|Explain\|Sensitivity'` and `go test . -run 'Resolution\|SequenceIdentity\|Diff'` |
| Paths, metadata, provenance | [Paths](../internal/engine/path_test.go), [metadata](../internal/engine/metadata_test.go), [provenance](../internal/engine/provenance_test.go) | `go test ./internal/engine -run 'Path\|Metadata\|Provenance\|Queries'` | | Paths, metadata, provenance | [Paths](../internal/engine/path_test.go), [metadata](../internal/engine/metadata_test.go), [provenance](../internal/engine/provenance_test.go) | `go test ./internal/engine -run 'Path\|Metadata\|Provenance\|Queries'` |

View File

@@ -15,13 +15,17 @@ selection in `import_selection.go` preserves a normalized
namespace path separately from canonical access identity: overlapping roots namespace path separately from canonical access identity: overlapping roots
coalesce the same candidate spelling in that namespace, while aliases reached coalesce the same candidate spelling in that namespace, while aliases reached
through distinct spellings retain separate inclusion routes for admission. through distinct spellings retain separate inclusion routes for admission.
Glob parent traversal also retains distinct physical targets when link routes
normalize to the same lexical spelling, so neither branch disappears before
discovery and admission finish.
Directory searches walk each distinct normalized root once, apply all filename Directory searches walk each distinct normalized root once, apply all filename
patterns to discovered names, and form a set union of matching candidates across patterns to discovered names, and form a set union of matching candidates across
overlapping roots. Exclusions are applied as set difference after discovery and overlapping roots. Exclusions are applied as set difference after discovery and
candidate normalization. They do not suppress discovery or resource errors. candidate normalization. They do not suppress discovery or resource errors.
Layered assembly passes the resolved main context to underlay acquisition. Layered assembly passes the resolved main context to underlay acquisition.
Derived inputs retain the main's filesystem location and namespace. The Derived inputs retain the main namespace, lookup base, resource anchor and
independent optional import boundary. The
receiving tier supplies its own host token and tracks repeated sources. receiving tier supplies its own host token and tracks repeated sources.
Contextless bindings prepare declaration policies and assemble the declaring Contextless bindings prepare declaration policies and assemble the declaring
payload without opening filesystem access or recording selection evidence. payload without opening filesystem access or recording selection evidence.
@@ -31,7 +35,7 @@ A captured host main enters the same parsed-source and import traversal handoff
as an ordinarily selected file. Its original bytes and nodes are charged once per as an ordinarily selected file. Its original bytes and nodes are charged once per
load, including placement wrappers, and its canonical path participates in load, including placement wrappers, and its canonical path participates in
cycle and repeated-source checks. Imports are still acquired live; layered cycle and repeated-source checks. Imports are still acquired live; layered
main-relative consumers receive the captured base and root, while each tier main-relative consumers receive the captured base, anchor and import policy, while each tier
continues to use its own namespace token and repetition state. The capture and continues to use its own namespace token and repetition state. The capture and
context checks are owned by context checks are owned by
[`prepared_source.go`](../../internal/engine/prepared_source.go) and [`prepared_source.go`](../../internal/engine/prepared_source.go) and
@@ -41,14 +45,17 @@ Directory traversal tracks canonical directories on the active traversal path.
It adds an identity when descending and removes it when the frame is popped, so It adds an identity when descending and removes it when the frame is popped, so
only a back-edge to an active directory is a traversal cycle; a later alias is only a back-edge to an active directory is a traversal cycle; a later alias is
not mistaken for one. This is separate from import dependency-cycle detection. not mistaken for one. This is separate from import dependency-cycle detection.
For host sources, discovery uses rooted `Lstat` and canonical containment. Host discovery dispatches to ordinary OS Lstat/Readlink for unbounded imports,
or rooted operations with canonical containment for an explicit boundary.
`filesystem_context.go` owns resolved access facts and live access setup; the `filesystem_context.go` owns resolved access facts and live access setup; the
acquisition operation closes its live handles before composition. Native sources acquisition operation closes its live handles before composition. Native sources
use `fs.ReadLinkFS` inspection when supplied; otherwise traversal follows the use `fs.ReadLinkFS` inspection when supplied; otherwise traversal follows the
capabilities and behavior of the provided `fs.FS`, without claiming a general capabilities and behavior of the provided `fs.FS`, without claiming a general
sandbox guarantee. `source_context.go` derives passive resource contexts from sandbox guarantee. `source_context.go` derives passive resource contexts from
resolved sources for later caller-owned reads; those records do not retain live resolved sources for later caller-owned reads. Contained sources keep the legacy
acquisition handles. anchor and coordinates; external unbounded host sources use their own canonical
directory as a passive root. Those roots never constrain transitive acquisition
and retain no live handles.
Host and native link bindings share one iterative link-frame evaluator. It Host and native link bindings share one iterative link-frame evaluator. It
tracks active links for cycle detection and reuses successfully completed link tracks active links for cycle detection and reuses successfully completed link
@@ -59,6 +66,26 @@ directory can be treated as optional, while enumeration and close failures
remain selection errors, including errors from the standard `fs.ReadDir` remain selection errors, including errors from the standard `fs.ReadDir`
fallback. fallback.
`filesystem_context.go` separates rootPath (resource/overlay/bootstrap anchor),
basePath (relative lookup), and importRoot (optional host containment, or native
namespace boundary). An empty host importRoot is no path to canonicalize or open.
`filesystem_access.go` owns bounded host, unbounded host and borrowed native
operation dispatch; host accesses preserve their tier token across directories.
Overlay setup explicitly selects the legacy anchor as its access root. Configured
bootstrap also uses the captured legacy anchor, independently of importRoot.
Literal selector resolution in `import_selection.go` distinguishes host absolute
paths, native namespace-root selectors, and relative bases before candidate
normalization. Glob roots are separated from pattern segments without whole-pattern
cleaning. The longest literal prefix is consumed by one invocation of the shared
link evaluator from its resolved base. A component visitor performs directory,
access and containment checks as the cursor advances, preserving lexical source
spelling separately from resolved traversal coordinates. This avoids restarting
ancestor resolution at every literal component and permits resolution ancestors
of explicit roots without enumerating them. Parent segments after wildcards
advance from inspected matched directories, retaining lexical candidates separately
from physical access paths.
Glob selection keeps traversal coordination in `selectGlobImportCandidates`: Glob selection keeps traversal coordination in `selectGlobImportCandidates`:
it advances literal and patterned segments, reads directories, unions and sorts it advances literal and patterned segments, reads directories, unions and sorts
candidates, validates final targets, then applies exclusions and requiredness. candidates, validates final targets, then applies exclusions and requiredness.

View File

@@ -49,6 +49,8 @@ Implemented component owners:
engine schema builder and existing field/path bindings. Root `Inspection` engine schema builder and existing field/path bindings. Root `Inspection`
wraps an engine view borrowing the frozen inspection and canonical scope; wraps an engine view borrowing the frozen inspection and canonical scope;
it reuses history enumeration, document redaction, and whole-result diff. it reuses history enumeration, document redaction, and whole-result diff.
Both results and load errors can select a view; the error retains only frozen
reporting evidence and established passive contexts.
- `internal/document` owns the parser-independent ordered tree and cloning. - `internal/document` owns the parser-independent ordered tree and cloning.
`internal/yaml` is the sole upstream YAML adapter and parser/dumper boundary. `internal/yaml` is the sole upstream YAML adapter and parser/dumper boundary.
- Engine mechanism tests own source, composition, inheritance, decoding, - Engine mechanism tests own source, composition, inheritance, decoding,
@@ -123,8 +125,12 @@ share one assembly handoff that applies collection declarations and projects
only that tier's source/version evidence; the caller keeps main-version only that tier's source/version evidence; the caller keeps main-version
protection and its projection explicit. Live protection and its projection explicit. Live
filesystem access handles are confined to acquisition and closed there. Resolved filesystem access handles are confined to acquisition and closed there. Resolved
filesystem facts used to authorize access are separate from passively retained filesystem facts separate an optional import boundary from the lookup base and
resource contexts. Non-import validation retains those facts on `assembledInput` legacy resource/overlay/bootstrap anchor. `filesystem_access.go` dispatches bounded
host operations through os.Root, unbounded host operations through ordinary OS
calls, and native operations through the borrowed namespace. Passive source
contexts keep contained coordinates and use each external unbounded host source's
canonical directory as its resource root; they do not limit transitive imports. Non-import validation retains those facts on `assembledInput`
for passive-context construction and ordinary-overlay handling: see for passive-context construction and ordinary-overlay handling: see
[`filesystem_context.go`](../../internal/engine/filesystem_context.go) and [`filesystem_context.go`](../../internal/engine/filesystem_context.go) and
[`source_context.go`](../../internal/engine/source_context.go). [`source_context.go`](../../internal/engine/source_context.go).
@@ -132,12 +138,16 @@ for passive-context construction and ordinary-overlay handling: see
Explicit configured bootstrap uses Explicit configured bootstrap uses
[`prepared_source.go`](../../internal/engine/prepared_source.go) to share host [`prepared_source.go`](../../internal/engine/prepared_source.go) to share host
discovery and bounded parsing with acquisition. It stores a read-only main tree, discovery and bounded parsing with acquisition. It stores a read-only main tree,
byte count, and canonical path facts; each load clones the tree and assigns its byte count, canonical path facts and independent import policy; each load clones
the tree and assigns its
own source ID. [`secrets_from_config.go`](../../internal/engine/secrets_from_config.go) own source ID. [`secrets_from_config.go`](../../internal/engine/secrets_from_config.go)
validates just the bootstrap controls and calls the shared directory worker. validates just the bootstrap controls and calls the shared directory worker.
Acquisition checks any later explicit context against the captured facts before Acquisition checks any later explicit context against the captured facts before
imports or overlays, then applies normal source and aggregate accounting. imports or overlays, then applies normal source and aggregate accounting.
Captured state contains no access handles or secret-file values. Captured state contains no access handles or secret-file values. Omitted later
roots preserve captured import policy; compatible explicit roots can narrow an
unbounded capture. Bootstrap and overlays continue using the legacy anchor.
[ADR 0026](../adr/0026-optional-host-import-containment.md) records that separation.
Import responsibilities are split across candidate selection and path Import responsibilities are split across candidate selection and path
normalization in [`import_selection.go`](../../internal/engine/import_selection.go), normalization in [`import_selection.go`](../../internal/engine/import_selection.go),
@@ -182,6 +192,16 @@ pre-secret admission boundary, [`prepareInspectionHistory`](../../internal/engin
freezes that builder and counts the retained document roots before secret lookup freezes that builder and counts the retained document roots before secret lookup
and validation. and validation.
On eligible failure exits, the engine freezes the latest admissible source,
decoded, or resolver-entry history prefix. Source prefixes reuse the same source
and inheritance producers without a typed baseline; failure-only fallback tries
earlier candidates when the retained-node budget prevents a newer view. The
shared finalizer in [`load_result.go`](../../internal/engine/load_result.go)
classifies sensitivity and attaches source records, contexts, diagnostics, and
known resolved references for both outcomes. Failure views use the error's
conservatively sanitized source catalog. [ADR 0025](../adr/0025-inspect-failed-configuration-loads.md)
records the decision.
The frozen model is shared by `Metadata` and `Inspection`. Its shape-aware The frozen model is shared by `Metadata` and `Inspection`. Its shape-aware
selection in [`history_select.go`](../../internal/engine/history_select.go) selection in [`history_select.go`](../../internal/engine/history_select.go)
drives metadata history, explanation, and historical-path membership; the model drives metadata history, explanation, and historical-path membership; the model

View File

@@ -178,6 +178,11 @@ dependency-ready scheduling within their existing scopes; acquisition order and
precedence-tier boundaries remain distinct. The [configuration contract](../config.md#explicit-imports) precedence-tier boundaries remain distinct. The [configuration contract](../config.md#explicit-imports)
owns observable behavior; [ADR 0015](../adr/0015-shared-dependency-ready-ordering.md) owns observable behavior; [ADR 0015](../adr/0015-shared-dependency-ready-ordering.md)
and [ADR 0016](../adr/0016-independent-import-controls.md) record the decisions. and [ADR 0016](../adr/0016-independent-import-controls.md) record the decisions.
Host imports use an optional explicit containment boundary, separate from the
relative lookup base and resource/overlay/bootstrap anchor. Native imports stay
in their selected namespace. Broader import access must not widen overlays or
secrets bootstrap or change existing contained resource coordinates.
[ADR 0026](../adr/0026-optional-host-import-containment.md) records this decision.
The explicit secrets-directory bootstrap is a narrow, opt-in exception: applications The explicit secrets-directory bootstrap is a narrow, opt-in exception: applications
invoke it during startup, and it reports writes, skips and partial failures. It invoke it during startup, and it reports writes, skips and partial failures. It
must never run implicitly as part of configuration loading. must never run implicitly as part of configuration loading.
@@ -188,8 +193,10 @@ network provider into the library.
Configuration loading is a synchronous, complete-on-return operation. A successful Configuration loading is a synchronous, complete-on-return operation. A successful
load provides the final configuration and inspection metadata after the configured load provides the final configuration and inspection metadata after the configured
processing and validation phases complete. A failed load reports diagnostics and processing and validation phases complete. A failed load returns a nil result and
returns no usable partial result. The normal application pattern is one load near diagnostics, and may retain an inspectable coherent checkpoint as reporting
evidence. Inspection does not turn failure into successful configuration. The
normal application pattern is one load near
startup; applications may explicitly initiate additional loads. startup; applications may explicitly initiate additional loads.
ConfigKit releases its library-owned loading handles before returning and remains ConfigKit releases its library-owned loading handles before returning and remains
@@ -311,19 +318,20 @@ metadata, and effective inspection must agree, including application resolution
changes; see [ADR 0003](../adr/0003-preserve-presence-and-resolution-history.md). changes; see [ADR 0003](../adr/0003-preserve-presence-and-resolution-history.md).
Safe historical values and an explanation renderer are part of the implemented contract, Safe historical values and an explanation renderer are part of the implemented contract,
including superseded/deleted paths and effective source attribution. Inspection including superseded/deleted paths and effective source attribution. Inspection
must agree with the final typed snapshot and apply historical sensitivity rules. must agree with the represented snapshot and apply historical sensitivity rules.
See [ADR 0005](../adr/0005-explicit-overrides-and-safe-explanation.md). See [ADR 0005](../adr/0005-explicit-overrides-and-safe-explanation.md).
Detailed syntax and operation tables belong to the Detailed syntax and operation tables belong to the
[current configuration contract](../config.md). [current configuration contract](../config.md).
The frozen inspection boundary supports comparing completed same-type results The frozen inspection boundary supports comparing completed same-type results
and focused views across application root types without reopening sources or and focused views across application root types and load outcomes without reopening sources or
rerunning the load lifecycle. The rerunning the load lifecycle. The
[configuration contract](../config.md#effective-configuration-diffs) owns [configuration contract](../config.md#effective-configuration-diffs) owns
comparison and disclosure behavior, the [component overview](../internal/overview.md) comparison and disclosure behavior, the [component overview](../internal/overview.md)
owns implementation responsibility, and [ADR 0010](../adr/0010-effective-configuration-diff.md) owns implementation responsibility, and [ADR 0010](../adr/0010-effective-configuration-diff.md)
and [ADR 0024](../adr/0024-compare-inspection-views-across-application-types.md) and [ADR 0024](../adr/0024-compare-inspection-views-across-application-types.md)
record the accepted decisions. record the comparison decisions. [ADR 0025](../adr/0025-inspect-failed-configuration-loads.md)
extends inspection to available failure checkpoints.
## Collection Identity And Combination ## Collection Identity And Combination

View File

@@ -103,7 +103,7 @@ go list -m go.maximumdirect.net/releasekit
go tool releasekit version go tool releasekit version
``` ```
This repository selects ReleaseKit v0.10.0. `go tool releasekit` preserves the This repository selects ReleaseKit v0.11.0. `go tool releasekit` preserves the
tool's exit status and publication report; `go run` maps a nonzero child exit tool's exit status and publication report; `go run` maps a nonzero child exit
status to 1. ReleaseKit's child Go commands status to 1. ReleaseKit's child Go commands
use the `go` found on `PATH` with `GOTOOLCHAIN=local`; keep the selected use the `go` found on `PATH` with `GOTOOLCHAIN=local`; keep the selected
@@ -121,10 +121,11 @@ export GOOS="$release_host_os" GOARCH="$release_host_arch"
ReleaseKit still selects the Linux compilation targets from the profile. ReleaseKit still selects the Linux compilation targets from the profile.
For hosted delivery, save the Gitea API token in the ignored local file For hosted delivery, save the Gitea API token in the ignored local file
`.releasekit/gitea-token` with owner-only permissions. The profile uses it when `.releasekit/gitea-token` with owner-only permissions. The profile selects it through
`RELEASEKIT_GITEA_TOKEN` is unset or blank; a nonblank environment value takes `delivery.credentials.local.token_file`. Local delivery uses this file exclusively;
precedence. The file path resolves from the repository root, and ReleaseKit environment tokens do not override it. The file path resolves from the repository
trims surrounding whitespace from its contents. Keep credentials out of release root, and ReleaseKit trims surrounding whitespace from its contents. A missing,
unreadable, or blank selected file is an error. Keep credentials out of release
notes, diagnostic labels, command arguments, and commits. The selected notes, diagnostic labels, command arguments, and commits. The selected
`forbidden_files` check also rejects a committed token at that exact path; `forbidden_files` check also rejects a committed token at that exact path;
it does not scan other files or history. Source publication uses Git it does not scan other files or history. Source publication uses Git
@@ -139,6 +140,18 @@ git ls-remote ssh://git@forge.maximumdirect.net:22222/base-layer/configkit.git H
Publication requires explicit authorization. Local implementation commits do Publication requires explicit authorization. Local implementation commits do
not authorize a push or release. not authorize a push or release.
For optional setup diagnostics before choosing a version or writing a note:
```sh
go tool releasekit validate --offline --operation publication --operation go
```
This inspects working configuration, Git publication settings and the Go
toolchain without contacting remotes or loading delivery credentials. It does
not run tests, check dependency-cache completeness or replace candidate validation.
It is not a release prerequisite. ConfigKit does not configure CI rehearsal;
the release process continues without waiting for CI.
## 2. Prepare and commit the candidate ## 2. Prepare and commit the candidate
Choose a stable version that has not been used locally or on the publication Choose a stable version that has not been used locally or on the publication
@@ -322,9 +335,11 @@ regardless of the CLI's credential-redacted diagnostic output.
Reconciliation observes the captured endpoint and exact tag object using current Reconciliation observes the captured endpoint and exact tag object using current
supported Git transport settings. It does not load the current profile, require supported Git transport settings. It does not load the current profile, require
the original `HEAD`, rerun candidate validation, change tags, or contact Gitea the original `HEAD`, rerun candidate validation, change tags, or contact Gitea
hosted delivery. It needs no clean candidate checkout. Use ReleaseKit v0.8.0 or hosted delivery. It needs no clean candidate checkout. Use a CLI supporting the
another CLI supporting the saved record format, including format 2 where exact saved record's format: ReleaseKit v0.11.0 writes format 3, which includes source
non-UTF-8 endpoint/path bytes were retained. and version identity, and also reads formats 1 and 2. Older CLIs cannot read
format 3; use the current tool for new attempts. Format 2 retains exact non-UTF-8
endpoint/path bytes.
| Reconciliation status | Meaning and next action | | Reconciliation status | Meaning and next action |
| --- | --- | | --- | --- |

70
docs/releases/v1.5.0.md Normal file
View File

@@ -0,0 +1,70 @@
# ConfigKit v1.5.0
Applications can now inspect rejected configuration through the same reporting
interface used for successful loads. Imports also support absolute paths and
shared files outside the main configuration directory, with explicit containment
available when needed.
## Inspect rejected configuration
`LoadError.InspectSubtree(path)` returns an `Inspection` view when a failed load
retained a coherent snapshot. Consumers can render values, explain their origins,
inspect history and resource contexts, and compare views across successful and
failed loads using the existing redaction rules. Inspection does not reopen
sources or rerun callbacks.
The new `Inspection.Stage()` identifies the processing completed for a snapshot,
from main-tier composition through validation. Failed phases do not contribute
partial changes: a failing resolver exposes its entry candidate, and a failing
validator exposes the candidate presented to it. Early failures and existing
history limits can leave no view available; callers must check availability.
Loading still returns a nil result and an error on failure. A reporting view
does not turn rejected configuration into a successful execution result, and the
original diagnostics remain authoritative.
[Checkpoint contract](../config.md#results-and-failures) · [Inspection API](../../inspection_view.go) · [Consumer example](../../examples/consumers/failure_inspection.go)
## Absolute and parent-relative imports
Enabled host imports now accept absolute paths and paths outside the main
configuration directory. Relative selectors resolve from the declaring file's
canonical directory, including within imported external files. The same rules
apply to `path`, `dir`, and `glob` selectors. Host byte, reader, and mapping inputs
can supply `FilesystemContext.BaseDir` without a `Root`.
**Host imports are unbounded by default.** Applications relying on the former
default containment should explicitly set `FilesystemContext.Root` to the main
file's canonical directory. An explicit root bounds canonical targets, including
symlinks and transitive imports. Existing explicit roots retain containment.
Within a supplied `fs.FS`, a leading `/` starts at that namespace's root.
Imports remain in the selected namespace; Go source and context arguments retain
their slash-relative path syntax.
External host sources receive resource contexts rooted at their own canonical
directories. Existing contained-source resource coordinates remain supported.
Import widening leaves selected-overlay lookup and configured secrets-bootstrap
boundaries unchanged. Prepared main sources retain their captured import policy;
a later compatible explicit root can narrow an unbounded capture.
[Import contract](../config.md#explicit-imports) · [Resource contexts](../config.md#source-resource-contexts) · [Consumer example](../../examples/consumers/external_imports_test.go)
## Fixes and maintenance
- Resolve parent components inside symlink targets in filesystem order for host
imports and inspected native glob prefixes, avoiding selection of the wrong
directory.
- Preserve the completed main-tier snapshot when a later load phase fails, and
record consumption of nested inheritance selectors in inspection history.
- Reduce repeated source-history searches and literal glob-prefix traversal.
- Adopt ReleaseKit v0.11.0 and update local delivery credentials and optional
readiness diagnostics in the [release procedure](../release.md).
## Compatibility
The new APIs and import forms are additive. Existing valid configurations remain
supported; applications requiring the earlier implicit import boundary should
set an explicit root as described above. Composition, precedence, source-version
checks, and ordinary loading's environment behavior remain unchanged. The Go
consumer minimum remains 1.27.0.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.5.0/COPYRIGHT) | [LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.5.0/LICENSE) | [ATTRIBUTION](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.5.0/docs/oss/attribution.md)

View File

@@ -0,0 +1,76 @@
package consumers
import (
"errors"
"io/fs"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"testing"
configkit "go.maximumdirect.net/configkit"
)
func TestExternalSharedImports(t *testing.T) {
t.Parallel()
root := t.TempDir()
app, shared := filepath.Join(root, "app"), filepath.Join(root, "shared")
for _, directory := range []string{app, shared} {
if err := os.Mkdir(directory, 0700); err != nil {
t.Fatal(err)
}
}
fixture := func(name string) string {
t.Helper()
data, err := bundledFiles.ReadFile("testdata/external-imports/" + name)
if err != nil {
t.Fatal(err)
}
return string(data)
}
write := func(name, contents string) {
t.Helper()
if err := os.WriteFile(name, []byte(contents), 0600); err != nil {
t.Fatal(err)
}
}
sharedConfig := filepath.Join(shared, "config.yml")
main := filepath.Join(app, "main.yml")
write(main, strings.ReplaceAll(fixture("main.yml"), "/srv/shared/config.yml", strconv.Quote(sharedConfig)))
write(sharedConfig, fixture("config.yml"))
write(filepath.Join(shared, "extra.yml"), fixture("extra.yml"))
write(filepath.Join(shared, "message.txt"), "shared template")
type configuration struct {
Name string `yaml:"name"`
Template string `yaml:"template"`
Format string `yaml:"format"`
}
// One ordinary load handles both the absolute import and its relative import.
result, err := configkit.Load[configuration](configkit.File(main), configkit.Options[configuration]{Imports: true})
if err != nil {
t.Fatal(err)
}
if result.Config.Name != "application" || result.Config.Format != "plain" {
t.Fatalf("configuration=%#v", result.Config)
}
info, ok := result.Metadata().Lookup(configkit.Keys("template"))
if !ok || len(info.Origin.Locations) != 1 {
t.Fatalf("template origin=%#v", info)
}
context, ok := result.SourceContext(info.Origin.Locations[0].SourceID)
if !ok {
t.Fatal("template source context unavailable")
}
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, result.Config.Template))
if err != nil || string(data) != "shared template" {
t.Fatalf("template=%q, %v", data, err)
}
// An application can deliberately retain containment at its main directory.
_, err = configkit.Load[configuration](configkit.File(main), configkit.Options[configuration]{Imports: true, Filesystem: &configkit.FilesystemContext{Root: app}})
var failure *configkit.LoadError
if !errors.As(err, &failure) || failure.Diagnostics()[0].Code != configkit.CodeImportOutsideRoot {
t.Fatalf("contained load=%v", err)
}
}

View File

@@ -0,0 +1,102 @@
package consumers
import (
"errors"
"fmt"
"io"
configkit "go.maximumdirect.net/configkit"
)
// BackendConfiguration is an application-owned configuration.
type BackendConfiguration struct {
Storage struct {
Backend string `yaml:"backend"`
} `yaml:"storage"`
}
// ConfigurationInspector is the reporting interface shared by results and errors.
type ConfigurationInspector interface {
InspectSubtree(configkit.Path) (configkit.Inspection, bool)
}
// BackendReport retains reporting evidence and diagnostics from one load.
type BackendReport struct {
Inspection configkit.Inspection
Available bool
Diagnostics []configkit.Diagnostic
storage configkit.Inspection
hasStorage bool
}
// InspectBackend loads once and preserves the original error along with any
// available inspection. Imports are enabled for the application's source.
func InspectBackend(source configkit.Source) (BackendReport, error) {
result, err := configkit.Load(source, configkit.Options[BackendConfiguration]{
Imports: true,
Definition: configkit.Definition[BackendConfiguration]{Validate: func(value *BackendConfiguration, validation *configkit.Validation) {
if value.Storage.Backend != "local" && value.Storage.Backend != "memory" {
validation.Error(configkit.Keys("storage", "backend"), "unsupported storage backend")
}
}},
})
var provider ConfigurationInspector = result
var diagnostics []configkit.Diagnostic
if err != nil {
var failure *configkit.LoadError
if !errors.As(err, &failure) {
return BackendReport{}, err
}
provider, diagnostics = failure, failure.Diagnostics()
}
view, ok := provider.InspectSubtree(configkit.Path{})
storage, hasStorage := provider.InspectSubtree(configkit.Keys("storage"))
return BackendReport{Inspection: view, Available: ok, Diagnostics: diagnostics, storage: storage, hasStorage: hasStorage}, err
}
// WriteConfigurationReport uses the same show and explain operations for a
// successful result or a failed load. Paths in explanations remain native.
func WriteConfigurationReport(output io.Writer, provider ConfigurationInspector) error {
root, ok := provider.InspectSubtree(configkit.Path{})
if !ok {
_, err := fmt.Fprintln(output, "Configuration inspection unavailable")
return err
}
if _, err := fmt.Fprintf(output, "Configuration checkpoint: %s\n", root.Stage()); err != nil {
return err
}
focus, ok := provider.InspectSubtree(configkit.Keys("storage"))
if !ok {
return errors.New("storage inspection unavailable")
}
if err := focus.WriteEffective(output); err != nil {
return err
}
return focus.WriteExplanation(output, configkit.Keys("storage", "backend"))
}
// WriteBackendReport renders retained evidence and any original diagnostics.
func WriteBackendReport(output io.Writer, report BackendReport) error {
if err := configkit.WriteDiagnostics(output, report.Diagnostics); err != nil {
return err
}
return WriteConfigurationReport(output, savedInspection{report.Inspection, report.Available, report.storage, report.hasStorage})
}
type savedInspection struct {
view configkit.Inspection
available bool
storage configkit.Inspection
hasStorage bool
}
func (saved savedInspection) InspectSubtree(path configkit.Path) (configkit.Inspection, bool) {
switch path.String() {
case "":
return saved.view, saved.available
case "/storage":
return saved.storage, saved.hasStorage
default:
return configkit.Inspection{}, false
}
}

View File

@@ -0,0 +1,60 @@
package consumers
import (
"bytes"
"errors"
"strings"
"testing"
"testing/fstest"
configkit "go.maximumdirect.net/configkit"
)
func TestBackendReportRetainsFailedLoadEvidence(t *testing.T) {
files := fstest.MapFS{
"main.yml": &fstest.MapFile{Data: []byte("config: {imports: [{path: storage.yml}]}\n")},
"storage.yml": &fstest.MapFile{Data: []byte("storage: {backend: unsupported}\n")},
}
filesystem := configkit.NewFilesystem("application", files)
report, err := InspectBackend(filesystem.File("main.yml"))
var failure *configkit.LoadError
if !errors.As(err, &failure) || !report.Available || len(report.Diagnostics) == 0 {
t.Fatalf("report = %#v, error = %v", report, err)
}
info, found := report.Inspection.Metadata().Lookup(configkit.Keys("storage", "backend"))
if !found || len(info.Origin.Locations) == 0 {
t.Fatalf("origin missing: %#v", info)
}
source, found := report.Inspection.Source(info.Origin.Locations[0].SourceID)
if !found || !strings.HasSuffix(source.Label, "storage.yml") {
t.Fatalf("source = %#v", source)
}
files["storage.yml"].Data = []byte("storage: {backend: local}\n")
var output bytes.Buffer
if err := WriteBackendReport(&output, report); err != nil {
t.Fatal(err)
}
if !strings.Contains(output.String(), "unsupported") || !strings.Contains(output.String(), "resolved") || !strings.Contains(output.String(), "storage.yml") {
t.Fatalf("report lost original evidence: %q", output.String())
}
success, err := configkit.Load[BackendConfiguration](configkit.Bytes("ok.yml", []byte("storage: {backend: local}\n")))
if err != nil {
t.Fatal(err)
}
output.Reset()
if err := WriteConfigurationReport(&output, success); err != nil || !strings.Contains(output.String(), "validated") {
t.Fatalf("successful report = %q, %v", output.String(), err)
}
}
func TestBackendReportExplainsUnavailableInspection(t *testing.T) {
report, err := InspectBackend(configkit.Bytes("bad.yml", []byte("[\n")))
if err == nil || report.Available || len(report.Diagnostics) == 0 {
t.Fatalf("report = %#v, error = %v", report, err)
}
var output bytes.Buffer
if err := WriteBackendReport(&output, report); err != nil || !strings.Contains(output.String(), "inspection unavailable") {
t.Fatalf("early failure report = %q, %v", output.String(), err)
}
}

View File

@@ -9,7 +9,7 @@ import (
configkit "go.maximumdirect.net/configkit" configkit "go.maximumdirect.net/configkit"
) )
//go:embed testdata/native-source testdata/layered-bundle testdata/collection-bundle testdata/ordinary-imports testdata/source-version testdata/main-relative-bundle //go:embed testdata/native-source testdata/layered-bundle testdata/collection-bundle testdata/ordinary-imports testdata/source-version testdata/main-relative-bundle testdata/external-imports
var bundledFiles embed.FS var bundledFiles embed.FS
// BundledConfig is a small configuration loaded directly from an embedded file. // BundledConfig is a small configuration loaded directly from an embedded file.

View File

@@ -0,0 +1,5 @@
config:
imports:
- path: extra.yml
required: true
template: message.txt

View File

@@ -0,0 +1 @@
format: plain

View File

@@ -0,0 +1,5 @@
config:
imports:
- path: /srv/shared/config.yml
required: true
name: application

View File

@@ -0,0 +1,126 @@
package configkit_test
import (
"bytes"
"errors"
configkit "go.maximumdirect.net/configkit"
"io/fs"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"testing"
)
func TestAbsoluteImportMountedInheritanceAndFailureInspection(t *testing.T) {
t.Parallel()
root := t.TempDir()
write := func(name, content string) string {
t.Helper()
file := filepath.Join(root, name)
if err := os.MkdirAll(filepath.Dir(file), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(file, []byte(content), 0600); err != nil {
t.Fatal(err)
}
return file
}
fragment := write("shared/fragment.yml", "parent: {resource: asset.txt, enabled: false, count: 0}\n")
write("shared/asset.txt", "external resource")
main := write("app/main.yml", "config:\n imports:\n - path: "+strconv.Quote(fragment)+"\n destination: [entries]\nentries:\n child: {extends: parent}\n")
load := func(reject bool) configkit.Inspection {
options := configkit.Options[inheritedConfiguration]{Imports: true, Definition: configkit.Definition[inheritedConfiguration]{
Sensitive: func(p configkit.Path) bool { return strings.HasSuffix(p.String(), "/resource") },
Validate: func(_ *inheritedConfiguration, v *configkit.Validation) {
if reject {
v.Error(configkit.Keys("entries", "child"), "rejected")
}
},
}}
result, err := configkit.Load(configkit.File(main), options)
if reject {
var failure *configkit.LoadError
if result != nil || !errors.As(err, &failure) {
t.Fatalf("rejected=%v, %v", result, err)
}
view, ok := failure.InspectSubtree(configkit.Path{})
if !ok {
t.Fatal("missing failed inspection")
}
return view
}
if err != nil {
t.Fatal(err)
}
if child := result.Config.Entries["child"]; child.Resource != "asset.txt" || child.Enabled || child.Count != 0 {
t.Fatalf("child=%#v", child)
}
view, ok := result.InspectSubtree(configkit.Path{})
if !ok {
t.Fatal("missing accepted inspection")
}
return view
}
accepted, rejected := load(false), load(true)
if difference, err := accepted.Diff(rejected); err != nil || len(difference) != 0 {
t.Fatalf("failure changed evidence=%#v, %v", difference, err)
}
for _, view := range []configkit.Inspection{accepted, rejected} {
resource := configkit.Keys("entries", "child", "resource")
info, ok := view.Metadata().Lookup(resource)
if !ok || len(info.Origin.Locations) == 0 || len(info.Origin.Inheritance) == 0 {
t.Fatalf("inherited origin=%#v", info)
}
id := info.Origin.Locations[0].SourceID
context, ok := view.SourceContext(id)
if !ok || context.BaseDir != "." {
t.Fatalf("external context=%#v, %v", context, ok)
}
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, "asset.txt"))
if err != nil || string(data) != "external resource" {
t.Fatalf("resource=%q, %v", data, err)
}
sources := view.Sources()
if len(sources) != 2 || sources[1].ID != id || sources[1].Destination.String() != "/entries" {
t.Fatalf("placement=%#v", sources)
}
explanation, ok := view.Explain(resource)
if !ok || len(explanation.History) == 0 || !explanation.Effective.Redacted {
t.Fatalf("explanation=%#v", explanation)
}
var output bytes.Buffer
if err := view.WriteEffective(&output); err != nil || strings.Contains(output.String(), "asset.txt") {
t.Fatalf("unsafe inspection=%q, %v", output.String(), err)
}
}
}
func TestAbsoluteImportUsesSourceVersionProcessing(t *testing.T) {
t.Parallel()
root := t.TempDir()
child := filepath.Join(root, "versioned.yml")
if err := os.WriteFile(child, []byte("version: v1\nvalue: imported\n"), 0600); err != nil {
t.Fatal(err)
}
main := filepath.Join(t.TempDir(), "main.yml")
if err := os.WriteFile(main, []byte("config: {imports: [{path: "+strconv.Quote(child)+"}]}\nversion: v1\n"), 0600); err != nil {
t.Fatal(err)
}
checked := 0
result, err := configkit.Load[map[string]any](configkit.File(main), configkit.Options[map[string]any]{Imports: true, SourceVersionMode: configkit.SourceVersionModeIfPresent, Definition: configkit.Definition[map[string]any]{Version: &configkit.VersionRule{Path: configkit.Keys("version"), Check: func(version configkit.Version, _ *configkit.Validation) error {
checked++
if version.Text != "v1" {
return errors.New("unexpected version")
}
return nil
}}}})
if err != nil {
t.Fatal(err)
}
sources := result.Sources()
if checked != 2 || len(sources) != 2 || sources[1].VersionEvidence == nil || sources[1].VersionEvidence.Version.Text != "v1" || result.Config["value"] != "imported" {
t.Fatalf("checks=%d, sources=%#v, config=%#v", checked, sources, result.Config)
}
}

View File

@@ -0,0 +1,76 @@
package configkit_test
import (
"bytes"
"errors"
"strings"
"testing"
"testing/fstest"
ck "go.maximumdirect.net/configkit"
)
func TestFailureMainCheckpointUsesLowerCollectionPolicy(t *testing.T) {
files := fstest.MapFS{
"main.yml": {Data: []byte("config: {imports: [{path: a.yml}, {path: b.yml}]}\n")},
"a.yml": {Data: []byte("items: [{id: a, value: first}]\n")},
"b.yml": {Data: []byte("items: [{id: b, value: second}]\n")},
}
filesystem := ck.NewFilesystem("checkpoint", files)
main := ck.Input{Source: filesystem.File("main.yml"), Imports: true}
lower := ck.Underlay{Inputs: []ck.Input{{Source: ck.Bytes("lower", []byte("config:\n sequences: [{destination: [items], key: id}]\nitems: [{id: lower, value: base}]\n"))}}}
options := ck.LayeredOptions[map[string]any]{Underlays: []ck.Underlay{lower}, OverlayFilesystem: &ck.FilesystemContext{FS: &filesystem, Root: ".", BaseDir: "."}}
if _, err := ck.LoadLayered(main, options); err != nil {
t.Fatal(err)
}
for _, boundary := range []string{"overlay", "underlay", "version"} {
t.Run(boundary, func(t *testing.T) {
opts := options
switch boundary {
case "overlay":
opts.Overlay = "missing"
case "underlay":
opts.Underlays = append([]ck.Underlay{lower}, ck.Underlay{Inputs: []ck.Input{{Source: ck.Bytes("bad", []byte("[\n"))}}})
case "version":
opts.Definition.Version = &ck.VersionRule{Path: ck.Keys("version"), Check: func(_ ck.Version, v *ck.Validation) error { v.Error(ck.Keys("version"), "rejected"); return nil }}
}
result, err := ck.LoadLayered(main, opts)
var failure *ck.LoadError
if result != nil || !errors.As(err, &failure) {
t.Fatalf("result=%v error=%v", result, err)
}
view, ok := failure.InspectSubtree(ck.Path{})
if !ok || view.Stage() != ck.InspectionStageMain {
t.Fatalf("available=%v stage=%s", ok, view.Stage())
}
var output bytes.Buffer
if err := view.WriteEffective(&output); err != nil {
t.Fatal(err)
}
if !strings.Contains(output.String(), "first") || !strings.Contains(output.String(), "second") || strings.Contains(output.String(), "base") {
t.Fatalf("wrong main snapshot: %s", &output)
}
for index, label := range []string{"a.yml", "b.yml"} {
path := ck.Keys("items").Index(index).Key("value")
info, found := view.Metadata().Lookup(path)
if !found || len(info.Origin.Locations) == 0 || len(view.Metadata().History(path)) == 0 {
t.Fatalf("missing evidence at %s", path)
}
source, found := view.Source(info.Origin.Locations[0].SourceID)
if !found || !strings.HasSuffix(source.Label, label) {
t.Fatalf("wrong source: %#v", source)
}
}
})
}
for _, invalid := range []string{"items: [{id: a}, {id: a}]\n", "items: [{other: a}]\n"} {
_, err := ck.LoadLayered(ck.Input{Source: ck.Bytes("invalid", []byte(invalid))}, options)
var failure *ck.LoadError
if !errors.As(err, &failure) {
t.Fatal("expected composition failure")
}
if _, ok := failure.InspectSubtree(ck.Path{}); ok {
t.Fatal("failed main composition was presented as completed")
}
}
}

View File

@@ -0,0 +1,256 @@
package configkit_test
import (
"bytes"
"errors"
"io/fs"
"path"
"reflect"
"strings"
"testing"
"testing/fstest"
configkit "go.maximumdirect.net/configkit"
)
func TestFailureInspectionMatchesAcceptedEvidence(t *testing.T) {
filesystem := configkit.NewFilesystem("bundle", fstest.MapFS{
"config/main.yml": &fstest.MapFile{Data: []byte("config: {imports: [{path: fragment.yml}]}\nentries:\n parent: {resource: asset.txt, token: current-canary, removed: historical-canary}\n child: {extends: parent}\n")},
"config/fragment.yml": &fstest.MapFile{Data: []byte("extra: imported\n")},
"config/asset.txt": &fstest.MapFile{Data: []byte("asset")},
"overlays/testing.yml": &fstest.MapFile{Data: []byte("mode: overlay\n")},
})
load := func(reject bool) (configkit.Inspection, *map[string]any) {
t.Helper()
var retained *map[string]any
options := configkit.LayeredOptions[map[string]any]{
Underlays: []configkit.Underlay{{Inputs: []configkit.Input{{Source: configkit.Mapping("defaults", map[string]any{"mode": "underlay"})}}}},
Overlay: "testing", OverlayFilesystem: &configkit.FilesystemContext{Root: ".", BaseDir: ".", FS: &filesystem},
Overrides: []configkit.Override{{Path: configkit.Keys("mode"), Value: "cli", Flag: "--mode"}},
Definition: configkit.Definition[map[string]any]{
Sensitive: func(p configkit.Path) bool {
return strings.HasSuffix(p.String(), "/token") || strings.HasSuffix(p.String(), "/removed")
},
Resolve: func(current *map[string]any, resolution *configkit.Resolution) error {
retained = current
child := (*current)["entries"].(map[string]any)["child"].(map[string]any)
delete(child, "removed")
resolution.RecordNormalization(configkit.Keys("entries", "child", "removed"), "remove")
return nil
},
Validate: func(_ *map[string]any, validation *configkit.Validation) {
if reject {
validation.Error(configkit.Keys("mode"), "rejected")
}
},
},
}
result, err := configkit.LoadLayered(configkit.Input{Source: filesystem.File("config/main.yml"), Imports: true}, options)
var provider inspectionProvider
if reject {
var failure *configkit.LoadError
if result != nil || !errors.As(err, &failure) {
t.Fatalf("failed load = %v, %v", result, err)
}
provider = failure
} else {
if err != nil {
t.Fatal(err)
}
provider = result
}
view, ok := provider.InspectSubtree(configkit.Path{})
if !ok {
t.Fatal("inspection unavailable")
}
return view, retained
}
accepted, _ := load(false)
rejected, retained := load(true)
if diff, err := accepted.Diff(rejected); err != nil || len(diff) != 0 {
t.Fatalf("equal snapshots differ: %#v, %v", diff, err)
}
var before, acceptedOutput bytes.Buffer
if err := rejected.WriteEffective(&before); err != nil {
t.Fatal(err)
}
if err := accepted.WriteEffective(&acceptedOutput); err != nil {
t.Fatal(err)
}
if before.String() != acceptedOutput.String() || strings.Contains(before.String(), "canary") || !strings.Contains(before.String(), "cli") {
t.Fatalf("different or unsafe output: %q / %q", before.String(), acceptedOutput.String())
}
removed := configkit.Keys("entries", "child", "removed")
explanation, found := rejected.Explain(removed)
if !found || explanation.Effective.Present || len(explanation.History) == 0 {
t.Fatalf("removed history: %#v", explanation)
}
var rendered bytes.Buffer
if err := rejected.WriteExplanation(&rendered, removed); err != nil || strings.Contains(rendered.String(), "canary") {
t.Fatalf("unsafe history: %q, %v", rendered.String(), err)
}
resource := configkit.Keys("entries", "child", "resource")
info, found := rejected.Metadata().Lookup(resource)
if !found || len(info.Origin.Locations) == 0 || len(info.Origin.Inheritance) == 0 {
t.Fatalf("resource origin: %#v", info)
}
id := info.Origin.Locations[0].SourceID
context, found := rejected.SourceContext(id)
if !found {
t.Fatal("resource context unavailable")
}
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, "asset.txt"))
if err != nil || string(data) != "asset" {
t.Fatalf("resource = %q, %v", data, err)
}
info.Origin.Locations[0].SourceID = "changed"
again, _ := rejected.Metadata().Lookup(resource)
if again.Origin.Locations[0].SourceID != id {
t.Fatal("metadata aliases retained evidence")
}
(*retained)["mode"] = "changed"
var after bytes.Buffer
if err := rejected.WriteEffective(&after); err != nil || !bytes.Equal(before.Bytes(), after.Bytes()) {
t.Fatalf("snapshot changed: %q, %v", after.String(), err)
}
if !reflect.DeepEqual(accepted.HistoricalPaths(), rejected.HistoricalPaths()) {
t.Fatal("history inventory differs across outcomes")
}
}
func TestFailureInspectionRetainsDynamicSensitivityAcrossValidatorMutation(t *testing.T) {
type tagged struct {
Token string `yaml:"token" configkit:"secret"`
}
type plain struct {
Token string `yaml:"token"`
}
type settings struct {
Dynamic any `yaml:"dynamic"`
}
result, err := configkit.Load(configkit.Bytes("input.yml", []byte("dynamic: {token: original-canary}\n")), configkit.Options[settings]{Definition: configkit.Definition[settings]{
Resolve: func(value *settings, resolution *configkit.Resolution) error {
value.Dynamic = tagged{Token: "original-canary"}
resolution.RecordNormalization(configkit.Keys("dynamic"), "set typed value")
return nil
},
Validate: func(value *settings, validation *configkit.Validation) {
validation.Error(configkit.Keys("dynamic"), "rejected")
value.Dynamic = plain{Token: "original-canary"}
},
}})
var failure *configkit.LoadError
if result != nil || !errors.As(err, &failure) {
t.Fatalf("failed load = %v, %v", result, err)
}
view, ok := failure.InspectSubtree(configkit.Keys("dynamic"))
if !ok {
t.Fatal("view unavailable")
}
var output bytes.Buffer
if err := view.WriteEffective(&output); err != nil || strings.Contains(output.String(), "original-canary") {
t.Fatalf("dynamic sensitivity lost: %q, %v", output.String(), err)
}
var semantic, mutation bool
for _, diagnostic := range failure.Diagnostics() {
semantic = semantic || diagnostic.Code == configkit.CodeValidateError
mutation = mutation || diagnostic.Code == configkit.CodeValidateMutation
}
if !semantic || !mutation {
t.Fatalf("diagnostics = %#v", failure.Diagnostics())
}
}
func TestFailureInspectionDiffAcrossCheckpointsAndTypes(t *testing.T) {
type numeric struct {
Value int `yaml:"value"`
}
type textual struct {
Value string `yaml:"value"`
}
_, err := configkit.Load[numeric](configkit.Bytes("invalid.yml", []byte("value: wrong\n")))
var failure *configkit.LoadError
if !errors.As(err, &failure) {
t.Fatal(err)
}
failed, ok := failure.InspectSubtree(configkit.Keys("value"))
if !ok || failed.Stage() != configkit.InspectionStageInherited {
t.Fatalf("failed checkpoint = %q", failed.Stage())
}
accepted, err := configkit.Load[textual](configkit.Bytes("valid.yml", []byte("value: wrong\n")))
if err != nil {
t.Fatal(err)
}
valid, _ := accepted.InspectSubtree(configkit.Keys("value"))
if diff, err := failed.Diff(valid); err != nil || len(diff) != 0 {
t.Fatalf("same value across types = %#v, %v", diff, err)
}
changed, err := configkit.Load(configkit.Bytes("changed.yml", []byte("value: sensitive-canary\n")), configkit.Options[textual]{Definition: configkit.Definition[textual]{
Sensitive: func(p configkit.Path) bool { return p.String() == "/value" },
}})
if err != nil {
t.Fatal(err)
}
changedView, _ := changed.InspectSubtree(configkit.Keys("value"))
diff, err := failed.Diff(changedView)
if err != nil || len(diff) != 1 || !diff[0].Left.Redacted || !diff[0].Right.Redacted || !diff[0].HiddenChanged || strings.Contains(diff[0].Right.YAML, "canary") {
t.Fatalf("paired redaction = %#v, %v", diff, err)
}
}
func TestFailureInspectionKeepsConservativeVersionEvidence(t *testing.T) {
type settings struct {
Version string `yaml:"version"`
Value string `yaml:"value"`
}
result, err := configkit.Load(configkit.Bytes("input.yml", []byte("version: VERSION_CANARY\nvalue: present\n")), configkit.Options[settings]{
SourceVersionMode: configkit.SourceVersionModeIfPresent,
Definition: configkit.Definition[settings]{
Version: &configkit.VersionRule{Path: configkit.Keys("version"), Check: func(configkit.Version, *configkit.Validation) error { return nil }},
Validate: func(_ *settings, validation *configkit.Validation) {
validation.Error(configkit.Keys("value"), "rejected")
},
},
})
var failure *configkit.LoadError
if result != nil || !errors.As(err, &failure) {
t.Fatalf("failed load = %v, %v", result, err)
}
view, ok := failure.InspectSubtree(configkit.Path{})
if !ok || !reflect.DeepEqual(view.Sources(), failure.Sources()) {
t.Fatal("failure sources differ from view")
}
sources := view.Sources()
if len(sources) != 1 || sources[0].VersionEvidence == nil || !sources[0].VersionEvidence.Redacted || sources[0].VersionEvidence.Version.Text != "" {
t.Fatalf("version evidence not conservatively redacted: %#v", sources)
}
}
func TestFailureInspectionRetainsSecretReferenceBeforeValidatorMutation(t *testing.T) {
type settings struct {
Token configkit.Secret `yaml:"token"`
}
t.Setenv("CONFIGKIT_INSPECTION_TEST_SECRET", "credential-canary")
result, err := configkit.Load(configkit.Bytes("input.yml", []byte("token: CONFIGKIT_INSPECTION_TEST_SECRET\n")), configkit.Options[settings]{Definition: configkit.Definition[settings]{
Validate: func(value *settings, validation *configkit.Validation) {
validation.Error(configkit.Keys("token"), "rejected")
value.Token = configkit.SecretEnv("OTHER_SECRET")
},
}})
var failure *configkit.LoadError
if result != nil || !errors.As(err, &failure) {
t.Fatalf("failed load = %v, %v", result, err)
}
view, ok := failure.InspectSubtree(configkit.Keys("token"))
if !ok {
t.Fatal("view unavailable")
}
explanation, ok := view.Explain(configkit.Keys("token"))
if !ok || explanation.SecretReference == nil || explanation.SecretReference.Name != "CONFIGKIT_INSPECTION_TEST_SECRET" {
t.Fatalf("original reference missing: %#v", explanation)
}
var output bytes.Buffer
if err := view.WriteEffective(&output); err != nil || strings.Contains(output.String(), "credential-canary") || strings.Contains(output.String(), "OTHER_SECRET") {
t.Fatalf("validator mutation leaked into output: %q, %v", output.String(), err)
}
}

View File

@@ -0,0 +1,87 @@
package configkit_test
import (
"bytes"
"errors"
"reflect"
"testing"
configkit "go.maximumdirect.net/configkit"
)
type inspectionProvider interface {
InspectSubtree(configkit.Path) (configkit.Inspection, bool)
}
func TestLoadErrorInspectionUsesSharedView(t *testing.T) {
type settings struct {
Items []string `yaml:"items"`
Other string `yaml:"other"`
}
input := configkit.Bytes("input.yml", []byte("items: [first, second]\nother: evidence\n"))
options := configkit.Options[settings]{Definition: configkit.Definition[settings]{
Validate: func(_ *settings, v *configkit.Validation) { v.Error(configkit.Keys("other"), "rejected") },
}}
result, err := configkit.Load(input, options)
var failure *configkit.LoadError
if result != nil || !errors.As(err, &failure) || len(failure.Diagnostics()) == 0 {
t.Fatalf("failed load = %v, %v", result, err)
}
var provider inspectionProvider = failure
root, ok := provider.InspectSubtree(configkit.Path{})
if !ok || root.Stage() != configkit.InspectionStageResolved {
t.Fatalf("failed root checkpoint = %q, %v", root.Stage(), ok)
}
if !reflect.DeepEqual(root.Sources(), failure.Sources()) {
t.Fatal("failure and view source catalogs differ")
}
key, ok := provider.InspectSubtree(configkit.Keys("items", "0"))
if !ok {
t.Fatal("numeric key scope unavailable")
}
index, ok := provider.InspectSubtree(configkit.Keys("items").Index(0))
if !ok || !reflect.DeepEqual(key.HistoricalPaths(), index.HistoricalPaths()) {
t.Fatal("equivalent numeric scopes disagree")
}
if _, ok := key.Explain(configkit.Keys("other")); !ok {
t.Fatal("outside native query unavailable")
}
if _, ok := provider.InspectSubtree(configkit.Keys("absent")); !ok {
t.Fatal("absent scope rejected")
}
if _, ok := provider.InspectSubtree(configkit.Path{}.Index(-1)); ok {
t.Fatal("invalid scope accepted")
}
var out bytes.Buffer
if err := key.WriteEffective(&out); err != nil || out.String() != "first\n" {
t.Fatalf("failed view output = %q, %v", out.String(), err)
}
success, err := configkit.Load[settings](input)
if err != nil {
t.Fatal(err)
}
provider = success
successView, ok := provider.InspectSubtree(configkit.Path{})
if !ok || successView.Stage() != configkit.InspectionStageValidated {
t.Fatalf("successful checkpoint = %q, %v", successView.Stage(), ok)
}
}
func TestLoadErrorInspectionUnavailable(t *testing.T) {
for _, failure := range []*configkit.LoadError{nil, {}} {
if _, ok := failure.InspectSubtree(configkit.Path{}); ok {
t.Fatal("unavailable error accepted")
}
}
_, err := configkit.Load[map[string]any](configkit.Bytes("bad.yml", []byte("[\n")))
var failure *configkit.LoadError
if !errors.As(err, &failure) {
t.Fatal(err)
}
if _, ok := failure.InspectSubtree(configkit.Path{}); ok {
t.Fatal("malformed input produced inspection")
}
if (configkit.Inspection{}).Stage() != "" {
t.Fatal("zero view has checkpoint")
}
}

View File

@@ -0,0 +1,75 @@
package configkit_test
import (
"errors"
"testing"
ck "go.maximumdirect.net/configkit"
)
func TestInheritanceSelectorConsumptionAcrossOutcomes(t *testing.T) {
type settings struct {
Count int `yaml:"count"`
Items []map[string]any `yaml:"items"`
}
for _, outcome := range []struct {
name, count string
stage ck.InspectionStage
}{
{"decode failure", "invalid", ck.InspectionStageInherited},
{"validation failure", "0", ck.InspectionStageResolved},
{"success", "0", ck.InspectionStageValidated},
} {
t.Run(outcome.name, func(t *testing.T) {
input := "config:\n sequences: [{destination: [items], key: id}]\ncount: " + outcome.count + "\nitems:\n - {id: parent, width: 5}\n - {id: child, extends: {id: parent}, width: 20}\n"
definition := ck.Definition[settings]{}
if outcome.name == "validation failure" {
definition.Validate = func(_ *settings, v *ck.Validation) { v.Error(ck.Keys("count"), "rejected") }
}
result, err := ck.Load(ck.Bytes("selector", []byte(input)), ck.Options[settings]{Definition: definition})
var provider inspectionProvider
if outcome.name == "success" {
if err != nil {
t.Fatal(err)
}
provider = result
} else {
var failure *ck.LoadError
if result != nil || !errors.As(err, &failure) {
t.Fatalf("result=%v error=%v", result, err)
}
provider = failure
}
view, ok := provider.InspectSubtree(ck.Path{})
if !ok || view.Stage() != outcome.stage {
t.Fatalf("view available=%v stage=%s", ok, view.Stage())
}
control := ck.Keys("items").Index(1).Key("extends")
for _, query := range []ck.Path{control, control.Key("id")} {
explanation, found := view.Explain(query)
if !found || explanation.Effective.Present || len(explanation.History) < 2 {
t.Fatalf("missing removal at %s: %#v", query, explanation)
}
last := explanation.History[len(explanation.History)-1]
if !last.Before.Present || last.After.Present || last.Origin.Operation != ck.ChangeInheritance {
t.Fatalf("wrong removal: %#v", last)
}
history := view.Metadata().History(query)
if len(history) == 0 {
t.Fatal("missing metadata history")
}
change := history[len(history)-1]
if change.Path.String() != control.String() || change.Origin.Operation != ck.ChangeInheritance {
t.Fatalf("wrong operation: %#v", change)
}
observed := false
for _, path := range view.HistoricalPaths() {
observed = observed || path.String() == query.String()
}
if !observed {
t.Fatalf("historical path missing: %s", query)
}
}
})
}
}

View File

@@ -5,6 +5,7 @@ import (
"io/fs" "io/fs"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"sync" "sync"
"testing" "testing"
@@ -178,3 +179,52 @@ func TestOrdinaryLoadingNeverBootstrapsSecrets(t *testing.T) {
t.Fatal("ordinary loading changed the environment") t.Fatal("ordinary loading changed the environment")
} }
} }
func TestConfiguredSecretsPreservesImportAndBootstrapScopes(t *testing.T) {
root := t.TempDir()
app := filepath.Join(root, "app")
if err := os.MkdirAll(filepath.Join(app, "secrets"), 0700); err != nil {
t.Fatal(err)
}
const name = "CONFIGKIT_EXTERNAL_IMPORT_BOOTSTRAP"
t.Setenv(name, "previous")
if err := os.WriteFile(filepath.Join(app, "secrets", name), []byte("disposable-token\n"), 0600); err != nil {
t.Fatal(err)
}
external := filepath.Join(root, "external.yml")
if err := os.WriteFile(external, []byte("imported: external\n"), 0600); err != nil {
t.Fatal(err)
}
main := filepath.Join(app, "main.yml")
contents := "config:\n secrets_dir: secrets\n secrets_overwrite: true\n imports: [{path: " + strconv.Quote(external) + "}]\ntoken: " + name + "\n"
if err := os.WriteFile(main, []byte(contents), 0600); err != nil {
t.Fatal(err)
}
report, prepared, err := configkit.LoadSecretsIntoEnvironmentFromConfig(configkit.File(main), configkit.SecretsFromConfigOptions{})
if err != nil || len(report.Entries()) != 1 {
t.Fatalf("bootstrap=%#v, %v", report, err)
}
loaded, err := configkit.Load[startupHandoffConfig](prepared, configkit.Options[startupHandoffConfig]{Imports: true})
if err != nil || loaded.Config.Imported != "external" || loaded.Config.Token.Value() != "disposable-token" {
t.Fatalf("load=%#v, %v", loaded, err)
}
// A relative declaration through an external symlink retains bootstrap's
// original anchor even though ordinary imports can reach that directory.
if err := os.Rename(filepath.Join(app, "secrets"), filepath.Join(root, "secrets")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(root, "secrets"), filepath.Join(app, "secrets")); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
_, _, err = configkit.LoadSecretsIntoEnvironmentFromConfig(configkit.File(main), configkit.SecretsFromConfigOptions{})
if err == nil {
t.Fatal("default bootstrap escaped its anchor")
}
_, prepared, err = configkit.LoadSecretsIntoEnvironmentFromConfig(configkit.File(main), configkit.SecretsFromConfigOptions{Filesystem: &configkit.FilesystemContext{Root: root}})
if err != nil {
t.Fatal(err)
}
if _, err := configkit.Load[startupHandoffConfig](prepared, configkit.Options[startupHandoffConfig]{Imports: true}); err != nil {
t.Fatal(err)
}
}

View File

@@ -0,0 +1,66 @@
package configkit_test
import (
"errors"
"fmt"
"testing"
ck "go.maximumdirect.net/configkit"
)
func TestRepeatedTierHistoryKeepsOneEventPerReplacement(t *testing.T) {
values := []int{3, 5, 8, 13, 21, 34, 55, 89}
var tiers []ck.Underlay
for _, value := range values {
tiers = append(tiers, ck.Underlay{Inputs: []ck.Input{{Source: ck.Bytes(fmt.Sprintf("tier-%d", value), []byte(fmt.Sprintf("setting: %d\n", value)))}}})
}
for _, reject := range []bool{false, true} {
t.Run(fmt.Sprintf("reject=%t", reject), func(t *testing.T) {
definition := ck.Definition[map[string]int]{}
if reject {
definition.Validate = func(_ *map[string]int, v *ck.Validation) { v.Error(ck.Keys("setting"), "rejected") }
}
result, err := ck.LoadLayered(ck.Input{Source: ck.NoSource()}, ck.LayeredOptions[map[string]int]{Underlays: tiers, Definition: definition})
var provider inspectionProvider
if reject {
var failure *ck.LoadError
if result != nil || !errors.As(err, &failure) {
t.Fatalf("result=%v error=%v", result, err)
}
provider = failure
} else {
if err != nil {
t.Fatal(err)
}
provider = result
}
view, ok := provider.InspectSubtree(ck.Path{})
if !ok {
t.Fatal("inspection unavailable")
}
path := ck.Keys("setting")
explanation, found := view.Explain(path)
history := view.Metadata().History(path)
if !found || len(history) != len(tiers) || len(explanation.History) != len(tiers) {
t.Fatalf("duplicated or missing history: metadata=%#v explanation=%#v", history, explanation)
}
previous := ck.ValueSnapshot{}
for i, event := range explanation.History {
if event.Before != previous {
t.Fatalf("broken chronology at %d: %#v", i, event)
}
previous = event.After
if len(history[i].Origin.Locations) != 1 {
t.Fatalf("wrong attribution: %#v", history[i])
}
source, found := view.Source(history[i].Origin.Locations[0].SourceID)
if !found || source.Label != fmt.Sprint("tier-", values[i]) {
t.Fatalf("wrong source at %d: %#v", i, source)
}
}
if previous != explanation.Effective {
t.Fatalf("history does not reach effective value: %#v", explanation)
}
})
}
}

2
go.mod
View File

@@ -6,7 +6,7 @@ require go.yaml.in/yaml/v4 v4.0.0
require ( require (
github.com/yuin/goldmark/v2 v2.1.16 // indirect github.com/yuin/goldmark/v2 v2.1.16 // indirect
go.maximumdirect.net/releasekit v0.10.0 // indirect go.maximumdirect.net/releasekit v0.11.0 // indirect
golang.org/x/mod v0.43.0 // indirect golang.org/x/mod v0.43.0 // indirect
) )

4
go.sum
View File

@@ -1,7 +1,7 @@
github.com/yuin/goldmark/v2 v2.1.16 h1:MXvCVo+Cb2SVJ5cwJUzXetDjI7HECRJCkcqylEQtcJo= github.com/yuin/goldmark/v2 v2.1.16 h1:MXvCVo+Cb2SVJ5cwJUzXetDjI7HECRJCkcqylEQtcJo=
github.com/yuin/goldmark/v2 v2.1.16/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ= github.com/yuin/goldmark/v2 v2.1.16/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ=
go.maximumdirect.net/releasekit v0.10.0 h1:3GOgaIigXTkvYaRkntWZASE//2NTR1+IhkoKmt64aJo= go.maximumdirect.net/releasekit v0.11.0 h1:QjRfi+DLwMdRASkQf0pAA17nzWZ+LMk5qZg6Oj9SJQU=
go.maximumdirect.net/releasekit v0.10.0/go.mod h1:cT5NZNEcf7SKDx4MPG40YNK9V4bNyIxcLLFuNlbGQ90= go.maximumdirect.net/releasekit v0.11.0/go.mod h1:cT5NZNEcf7SKDx4MPG40YNK9V4bNyIxcLLFuNlbGQ90=
go.yaml.in/yaml/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw= go.yaml.in/yaml/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw=
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=

View File

@@ -6,10 +6,52 @@ import (
"go.maximumdirect.net/configkit/internal/engine" "go.maximumdirect.net/configkit/internal/engine"
) )
// Inspection is a reporting view of a completed load. Its scope filters // Inspection is a reporting view of a frozen load checkpoint, whether the load
// enumeration; explicit queries and source records retain their native paths. // succeeded or failed. Its scope filters enumeration; explicit queries and
// source records retain their native paths.
type Inspection struct{ view engine.InspectionView } type Inspection struct{ view engine.InspectionView }
// InspectionStage identifies the completed processing represented by a view.
// It does not indicate the error location or whether a load succeeded.
type InspectionStage string
// Inspection checkpoints describe completed processing: main-tier composition,
// all source composition, inheritance, decoding, overrides, resolution, and
// validation, respectively. The first three retain source trees before typed
// defaults. A resolved view does not imply successful secret lookup, identity
// checking, or validation.
const (
InspectionStageMain InspectionStage = "main"
InspectionStageComposed InspectionStage = "composed"
InspectionStageInherited InspectionStage = "inherited"
InspectionStageDecoded InspectionStage = "decoded"
InspectionStageOverridden InspectionStage = "overridden"
InspectionStageResolved InspectionStage = "resolved"
InspectionStageValidated InspectionStage = "validated"
)
// Stage returns the represented checkpoint, or an empty string for a zero view.
func (i Inspection) Stage() InspectionStage {
switch i.view.Stage() {
case engine.InspectionStageMain:
return InspectionStageMain
case engine.InspectionStageComposed:
return InspectionStageComposed
case engine.InspectionStageInherited:
return InspectionStageInherited
case engine.InspectionStageDecoded:
return InspectionStageDecoded
case engine.InspectionStageOverridden:
return InspectionStageOverridden
case engine.InspectionStageResolved:
return InspectionStageResolved
case engine.InspectionStageValidated:
return InspectionStageValidated
default:
return ""
}
}
// InspectSubtree selects a canonical JSON Pointer reporting location, including // InspectSubtree selects a canonical JSON Pointer reporting location, including
// an absent location. Equivalent key and index spellings select the same scope. // an absent location. Equivalent key and index spellings select the same scope.
// Nil, manually constructed results and invalid paths cannot produce a view. // Nil, manually constructed results and invalid paths cannot produce a view.
@@ -21,7 +63,19 @@ func (r *Result[T]) InspectSubtree(path Path) (Inspection, bool) {
return Inspection{view: view}, ok return Inspection{view: view}, ok
} }
// Metadata returns the unfiltered metadata of the completed load. // InspectSubtree selects a canonical JSON Pointer reporting location from a
// failed load's available frozen snapshot. Equivalent key and index spellings
// select the same scope; an absent location is valid. Nil or zero errors,
// unavailable snapshots, and invalid paths cannot produce a view.
func (e *LoadError) InspectSubtree(path Path) (Inspection, bool) {
if e == nil || e.value == nil {
return Inspection{}, false
}
view, ok := engine.NewInspectionView(e.value.Inspection(), toEnginePath(path))
return Inspection{view: view}, ok
}
// Metadata returns the unfiltered metadata of the represented checkpoint.
func (i Inspection) Metadata() Metadata { return Metadata{value: i.view.Inspection().Metadata()} } func (i Inspection) Metadata() Metadata { return Metadata{value: i.view.Inspection().Metadata()} }
// HistoricalPaths returns observed paths at or beneath the reporting scope. // HistoricalPaths returns observed paths at or beneath the reporting scope.
@@ -42,7 +96,8 @@ func (i Inspection) WriteEffective(output io.Writer) error { return i.view.Write
// Diff compares frozen views at the same canonical scope, including differences // Diff compares frozen views at the same canonical scope, including differences
// at an ancestor when the existing comparison treats that ancestor atomically. // at an ancestor when the existing comparison treats that ancestor atomically.
// Views may come from different root Go types. Unavailable or mismatched views // Views may come from different root Go types. Unavailable or mismatched views
// return an error without records. // return an error without records. Comparison is independent of checkpoint and
// load outcome and does not compare diagnostics.
func (i Inspection) Diff(other Inspection) ([]Difference, error) { func (i Inspection) Diff(other Inspection) ([]Difference, error) {
values, err := i.view.Diff(other.view) values, err := i.view.Diff(other.view)
if err != nil { if err != nil {

View File

@@ -0,0 +1,85 @@
package engine
import (
"path/filepath"
"strconv"
"testing"
"testing/fstest"
)
func TestExternalNamedAndDirectoryImportAcquisition(t *testing.T) {
t.Parallel()
root := canonicalTestPath(t, t.TempDir())
first := writeImportFile(t, root, "shared/first.yml", "config:\n imports: [{path: nested/second.yml}]\nitems: {first: one}\n")
writeImportFile(t, root, "shared/nested/second.yml", "items: {second: two}\n")
for _, entry := range []struct{ name, selector string }{
{"absolute", "path: " + strconv.Quote(first)},
{"parent relative", "path: ../shared/first.yml"},
{"path union", "path: [" + strconv.Quote(first) + ", ../shared/first.yml]"},
{"directory", "dir: " + strconv.Quote(filepath.Dir(first)) + "\n pattern: first.yml"},
} {
t.Run(entry.name, func(t *testing.T) {
main := writeImportFile(t, root, "app/main.yml", "config:\n imports:\n - "+entry.selector+"\n required: true\nitems: {main: selected}\n")
request := testImportRequest(File(main), nil, parseImportMain(t, main), Path{}, nil, nil)
_, sources, diagnostics := testAcquireImportWithLimits(request, defaultImportLimits())
if len(diagnostics) != 0 || len(sources) != 3 {
t.Fatalf("sources=%#v, diagnostics=%#v", sources, diagnostics)
}
if sources[1].Path != first || sources[2].Path != filepath.Join(filepath.Dir(first), "nested", "second.yml") {
t.Fatalf("sources=%#v", sources)
}
request.input.input.filesystem = &FilesystemContext{Root: filepath.Dir(main)}
_, _, diagnostics = testAcquireImportWithLimits(request, defaultImportLimits())
if len(diagnostics) == 0 || diagnostics[0].Code != CodeImportOutsideRoot {
t.Fatalf("bounded diagnostics=%#v", diagnostics)
}
})
}
}
func TestAbsoluteImportAdmissionAndAbsence(t *testing.T) {
t.Parallel()
root := canonicalTestPath(t, t.TempDir())
first := writeImportFile(t, root, "shared/first.yml", "items: {first: one}\n")
for _, entry := range []struct {
name, imports string
code Code
}{
{name: "optional missing", imports: " - path: " + strconv.Quote(filepath.Join(root, "missing.yml"))},
{name: "required missing", imports: " - path: " + strconv.Quote(filepath.Join(root, "missing.yml")) + "\n required: true", code: CodeImportMissing},
{name: "repeated spelling", imports: " - path: " + strconv.Quote(first) + "\n - path: ../shared/first.yml", code: CodeImportRepeated},
{name: "cycle", imports: " - path: " + strconv.Quote(filepath.Join(root, "app/main.yml")), code: CodeImportCycle},
} {
t.Run(entry.name, func(t *testing.T) {
main := writeImportFile(t, root, "app/main.yml", "config:\n imports:\n"+entry.imports+"\n")
_, _, diagnostics := testAcquireImportWithLimits(testImportRequest(File(main), nil, parseImportMain(t, main), Path{}, nil, nil), defaultImportLimits())
if entry.code == "" {
if len(diagnostics) != 0 {
t.Fatal(diagnostics)
}
return
}
if len(diagnostics) == 0 || diagnostics[0].Code != entry.code {
t.Fatalf("diagnostics=%#v", diagnostics)
}
})
}
}
func TestNativeRootNamedAndDirectoryImports(t *testing.T) {
t.Parallel()
for _, selector := range []string{"path: /shared/part.yml", "dir: /shared\n pattern: part.yml"} {
filesystem := fstest.MapFS{
"app/main.yml": &fstest.MapFile{Data: []byte("config:\n imports:\n - " + selector + "\n")},
"shared/part.yml": &fstest.MapFile{Data: []byte("config:\n imports: [{path: ../neighbor.yml}]\nitems: {shared: part}\n")},
"neighbor.yml": &fstest.MapFile{Data: []byte("items: {neighbor: transitive}\n")},
}
result, err := testLoad[importTestConfig](filesystemFile(newNativeNamespace("bundle", filesystem), "app/main.yml"), Options[importTestConfig]{Imports: true})
if err != nil {
t.Fatal(err)
}
if result.Config.Items["shared"] != "part" || result.Config.Items["neighbor"] != "transitive" {
t.Fatalf("items = %#v", result.Config.Items)
}
}
}

View File

@@ -15,6 +15,15 @@ import (
type LoadError struct { type LoadError struct {
diagnostics []Diagnostic diagnostics []Diagnostic
sources []SourceInfo sources []SourceInfo
inspection *Inspection
}
// Inspection returns the frozen reporting snapshot retained by the failed load.
func (e *LoadError) Inspection() *Inspection {
if e == nil {
return nil
}
return e.inspection
} }
// Error implements error without rendering diagnostic messages or input values. // Error implements error without rendering diagnostic messages or input values.

View File

@@ -2,7 +2,6 @@ package engine
import ( import (
"os" "os"
"path"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -225,10 +224,10 @@ func fragmentVersionClaimWithIndex(root *document.Node, rule *VersionRule, sourc
} }
func validImportPath(value string) bool { func validImportPath(value string) bool {
if value == "" || strings.TrimSpace(value) != value || path.IsAbs(value) || strings.HasPrefix(value, "//") { if value == "" || strings.TrimSpace(value) != value {
return false return false
} }
return !hasImportScheme(value) return filepath.IsAbs(value) || !hasImportScheme(value)
} }
func hasImportScheme(value string) bool { func hasImportScheme(value string) bool {

View File

@@ -0,0 +1,232 @@
package engine
import (
"bytes"
"errors"
"strings"
"testing"
)
func TestFailedLoadRetainsDecodedOrResolverEntry(t *testing.T) {
type settings struct {
Count int `yaml:"count"`
Label string `yaml:"label"`
}
tests := []struct {
name string
overrides []Override
resolve func(*settings, *Resolution) error
checkpoint InspectionStage
wantCount string
wantLabel string
}{
{
name: "failed override batch",
overrides: []Override{
{Path: Keys("label"), Value: "changed", Flag: "label"},
{Path: Keys("count"), Value: "invalid", Flag: "count"},
},
checkpoint: InspectionStageDecoded, wantCount: "count: 3", wantLabel: "label: original",
},
{
name: "resolver error",
overrides: []Override{{Path: Keys("label"), Value: "cli", Flag: "label"}},
resolve: func(value *settings, _ *Resolution) error {
value.Label = "failed-edit"
return errors.New("reject")
},
checkpoint: InspectionStageOverridden, wantCount: "count: 3", wantLabel: "label: cli",
},
{
name: "unrecorded resolver mutation",
overrides: []Override{{Path: Keys("label"), Value: "cli", Flag: "label"}},
resolve: func(value *settings, _ *Resolution) error {
value.Label = "failed-edit"
return nil
},
checkpoint: InspectionStageOverridden, wantCount: "count: 3", wantLabel: "label: cli",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
result, err := testLoad(Bytes("input.yml", []byte("count: 3\nlabel: original\n")), Options[settings]{
Definition: Definition[settings]{Resolve: test.resolve}, Overrides: test.overrides,
})
var failure *LoadError
if result != nil || !errors.As(err, &failure) || failure.Inspection() == nil {
t.Fatalf("failed load: result=%v error=%v", result, err)
}
view, ok := NewInspectionView(failure.Inspection(), Path{})
if !ok || view.Stage() != test.checkpoint {
t.Fatalf("inspection checkpoint = %q, available=%v", view.Stage(), ok)
}
var output bytes.Buffer
if err := view.WriteEffective(&output); err != nil {
t.Fatal(err)
}
if !strings.Contains(output.String(), test.wantCount) || !strings.Contains(output.String(), test.wantLabel) || strings.Contains(output.String(), "failed-edit") {
t.Fatalf("wrong entry values: %q", output.String())
}
info, found := view.Inspection().Metadata().Lookup(Keys("label"))
if !found || (test.checkpoint == InspectionStageOverridden && info.Origin.Layer != LayerCLI) || (test.checkpoint == InspectionStageDecoded && info.Origin.Layer != LayerMain) {
t.Fatalf("wrong label origin: %#v", info)
}
if explanation, found := view.Inspection().Explain(Keys("label")); !found || len(explanation.History) == 0 {
t.Fatalf("missing entry history: %#v", explanation)
}
})
}
}
func TestFailedFinalValidationRetainsValidatorInput(t *testing.T) {
type settings struct {
Value string `yaml:"value"`
}
result, err := testLoad(Bytes("input.yml", []byte("value: before\n")), Options[settings]{Definition: Definition[settings]{
Validate: func(value *settings, validation *Validation) {
validation.Error(Keys("value"), "rejected")
value.Value = "after"
},
}})
var failure *LoadError
if result != nil || !errors.As(err, &failure) || failure.Inspection() == nil {
t.Fatalf("failed load: result=%v error=%v", result, err)
}
view, _ := NewInspectionView(failure.Inspection(), Path{})
if view.Stage() != InspectionStageResolved {
t.Fatalf("inspection checkpoint = %q", view.Stage())
}
var output bytes.Buffer
if err := view.WriteEffective(&output); err != nil || !strings.Contains(output.String(), "before") || strings.Contains(output.String(), "after") {
t.Fatalf("validator entry output = %q, %v", output.String(), err)
}
var semantic, mutation bool
for _, diagnostic := range failure.Diagnostics() {
semantic = semantic || diagnostic.Code == CodeValidateError
mutation = mutation || diagnostic.Code == CodeValidateMutation
}
if !semantic || !mutation {
t.Fatalf("missing diagnostics: %#v", failure.Diagnostics())
}
}
func TestFailedSecretLookupRetainsOnlyResolvedReferences(t *testing.T) {
type settings struct {
Good Secret `yaml:"good"`
Bad Secret `yaml:"bad"`
}
result, err := testLoadWithSecretLookup(Bytes("input.yml", []byte("good: GOOD_SECRET\nbad: MISSING_SECRET\n")), func(name string) (string, bool) {
return "credential-canary", name == "GOOD_SECRET"
}, Options[settings]{})
var failure *LoadError
if result != nil || !errors.As(err, &failure) || failure.Inspection() == nil {
t.Fatalf("failed load: result=%v error=%v", result, err)
}
inspection := failure.Inspection()
good, ok := inspection.Explain(Keys("good"))
if !ok || good.SecretReference == nil || good.SecretReference.Name != "GOOD_SECRET" {
t.Fatalf("resolved reference missing: %#v", good)
}
bad, ok := inspection.Explain(Keys("bad"))
if !ok || bad.SecretReference != nil {
t.Fatalf("unresolved reference was reported as resolved: %#v", bad)
}
var output bytes.Buffer
if err := inspection.WriteEffective(&output); err != nil || strings.Contains(output.String(), "credential-canary") {
t.Fatalf("credential in report: %q, %v", output.String(), err)
}
}
func TestFailedFinalIdentityRetainsResolvedInspection(t *testing.T) {
type item struct {
ID string `yaml:"id"`
}
type settings struct {
Items []item `yaml:"items"`
}
definition := DefinitionWithSequenceIdentityRegistrations(Definition[settings]{
Defaults: func() settings { return settings{Items: []item{{ID: "same"}, {ID: "same"}}} },
}, []SequenceIdentityRegistrationInput{{ExactPath: pathPointer(Keys("items")), IdentityFields: []string{"id"}}})
result, err := testLoad(NoSource(), Options[settings]{Definition: definition})
var failure *LoadError
if result != nil || !errors.As(err, &failure) || failure.Inspection() == nil {
t.Fatalf("identity failure: result=%v error=%v", result, err)
}
view, _ := NewInspectionView(failure.Inspection(), Path{})
if view.Stage() != InspectionStageResolved {
t.Fatalf("identity checkpoint = %q", view.Stage())
}
if info, found := failure.Inspection().Metadata().Lookup(Keys("items").Index(1).Key("id")); !found || info.Origin.Layer != LayerDefault {
t.Fatalf("default identity missing: %#v", info)
}
}
func TestFailureInspectionCheckpointsAcrossLoadPaths(t *testing.T) {
type settings struct {
Version string `yaml:"version"`
Value int `yaml:"value"`
Parent struct {
Value int `yaml:"value"`
} `yaml:"parent"`
Child struct {
Value int `yaml:"value"`
} `yaml:"child"`
}
version := &VersionRule{Path: Keys("version"), Check: func(_ Version, validation *Validation) error {
validation.Error(Keys("version"), "unsupported")
return nil
}}
tests := []struct {
name string
request loadRequest[settings]
checkpoint InspectionStage
contains string
}{
{name: "malformed source", request: loadRequest[settings]{main: loadInput{source: Bytes("main", []byte("[\n"))}}, checkpoint: ""},
{name: "main version", request: loadRequest[settings]{main: loadInput{source: Bytes("main", []byte("version: bad\nvalue: 3\n"))}, definition: Definition[settings]{Version: version}}, checkpoint: InspectionStageMain, contains: "value: 3"},
{name: "layer failure", request: loadRequest[settings]{main: loadInput{source: Bytes("main", []byte("value: 3\n"))}, underlays: []loadGroup{{inputs: []loadInput{{source: Bytes("bad", []byte("[\n"))}}}}}, checkpoint: InspectionStageMain, contains: "value: 3"},
{name: "inheritance failure", request: loadRequest[settings]{main: loadInput{source: Bytes("main", []byte("child: {extends: missing}\n"))}}, checkpoint: InspectionStageComposed, contains: "extends: missing"},
{name: "decode failure", request: loadRequest[settings]{main: loadInput{source: Bytes("main", []byte("value: wrong\n"))}}, checkpoint: InspectionStageInherited, contains: "value: wrong"},
{name: "no source override preflight", request: loadRequest[settings]{main: loadInput{source: NoSource()}, overrides: []Override{{Path: Path{}, Value: 1, Flag: "value"}}}, checkpoint: ""},
}
for _, test := range tests {
for _, ordinary := range []bool{true, false} {
if ordinary && len(test.request.underlays) != 0 {
continue
}
name := test.name
if ordinary {
name += " ordinary"
} else {
name += " layered"
}
t.Run(name, func(t *testing.T) {
var result *Loaded[settings]
var err error
if ordinary {
result, err = loadWithSecretLookup(test.request.main.source, testSecretBinding(), nil, Options[settings]{Definition: test.request.definition, Overrides: test.request.overrides})
} else {
result, err = loadGroupedWithSecretLookup(test.request, testSecretBinding(), nil)
}
var failure *LoadError
if result != nil || !errors.As(err, &failure) {
t.Fatalf("expected failure: result=%v err=%v", result, err)
}
if test.checkpoint == "" {
if failure.Inspection() != nil {
t.Fatal("unexpected inspection")
}
return
}
view, ok := NewInspectionView(failure.Inspection(), Path{})
if !ok || view.Stage() != test.checkpoint {
t.Fatalf("checkpoint = %q, available = %v", view.Stage(), ok)
}
var output bytes.Buffer
if err := view.WriteEffective(&output); err != nil || !strings.Contains(output.String(), test.contains) {
t.Fatalf("output = %q, %v", output.String(), err)
}
})
}
}
}

View File

@@ -12,7 +12,7 @@ func validateFilesystemContext(source Source, context *FilesystemContext, main p
if diagnostic != nil { if diagnostic != nil {
// Keep absent-input validation's existing diagnostic while sharing // Keep absent-input validation's existing diagnostic while sharing
// root/base derivation with overlay and resource-context handling. // root/base derivation with overlay and resource-context handling.
if source.kind == sourceNone && context.FS == nil && diagnostic.Code == CodeImportOutsideRoot { if source.kind == sourceNone && context != nil && context.FS == nil && diagnostic.Code == CodeImportOutsideRoot {
diagnostic.Message = "import base must stay inside the configuration root" diagnostic.Message = "import base must stay inside the configuration root"
} }
return resolvedFilesystemContext{}, diagnostic return resolvedFilesystemContext{}, diagnostic
@@ -27,7 +27,7 @@ func validateResolvedFilesystemContext(resolved resolvedFilesystemContext) *Diag
if diagnostic := validateResolvedFilesystemDirectories(resolved); diagnostic != nil { if diagnostic := validateResolvedFilesystemDirectories(resolved); diagnostic != nil {
return diagnostic return diagnostic
} }
if resolved.native != nil { if resolved.native != nil || resolved.rootPath == "" {
return nil return nil
} }
root, err := os.OpenRoot(resolved.rootPath) root, err := os.OpenRoot(resolved.rootPath)
@@ -51,8 +51,8 @@ func filesystemOptionDiagnostics(source Source, context *FilesystemContext) []Di
if context.FS != nil { if context.FS != nil {
return absentFilesystemOptionDiagnostics(context) return absentFilesystemOptionDiagnostics(context)
} }
// A selected host file can derive its root; absence requires an // A selected host file derives its base; absence can use an explicit
// explicit root. Check that compatibility only after selection. // base or root. Check compatibility after selection.
if context.BaseDir != "" && !filepath.IsAbs(context.BaseDir) { if context.BaseDir != "" && !filepath.IsAbs(context.BaseDir) {
return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "filesystem base directory must be an absolute host path")} return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "filesystem base directory must be an absolute host path")}
} }
@@ -74,14 +74,14 @@ func filesystemOptionDiagnostics(source Source, context *FilesystemContext) []Di
return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "filesystem root must be a slash-relative valid path")} return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "filesystem root must be a slash-relative valid path")}
} }
case sourceBytes, sourceReader, sourceMapping: case sourceBytes, sourceReader, sourceMapping:
if context.BaseDir == "" || context.Root == "" { if context.BaseDir == "" || context.FS != nil && context.Root == "" {
return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "byte and reader filesystem context requires base and root directories")} return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "byte and reader filesystem context requires base and root directories")}
} }
if context.FS != nil { if context.FS != nil {
if context.FS.namespace == nil || !fs.ValidPath(context.BaseDir) || !fs.ValidPath(context.Root) { if context.FS.namespace == nil || !fs.ValidPath(context.BaseDir) || !fs.ValidPath(context.Root) {
return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "filesystem base and root must be slash-relative valid paths")} return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "filesystem base and root must be slash-relative valid paths")}
} }
} else if !filepath.IsAbs(context.BaseDir) || !filepath.IsAbs(context.Root) { } else if !filepath.IsAbs(context.BaseDir) || context.Root != "" && !filepath.IsAbs(context.Root) {
return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "byte and reader filesystem base and root directories must be absolute")} return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "byte and reader filesystem base and root directories must be absolute")}
} }
} }
@@ -93,7 +93,7 @@ func absentFilesystemOptionDiagnostics(context *FilesystemContext) []Diagnostic
if context.FS.namespace == nil || nilFilesystem(context.FS.namespace.filesystem) || context.BaseDir == "" || context.Root == "" || !fs.ValidPath(context.BaseDir) || !fs.ValidPath(context.Root) { if context.FS.namespace == nil || nilFilesystem(context.FS.namespace.filesystem) || context.BaseDir == "" || context.Root == "" || !fs.ValidPath(context.BaseDir) || !fs.ValidPath(context.Root) {
return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "native filesystem context requires a namespace, base, and root directory")} return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "native filesystem context requires a namespace, base, and root directory")}
} }
} else if context.Root == "" || !filepath.IsAbs(context.Root) || context.BaseDir != "" && !filepath.IsAbs(context.BaseDir) { } else if context.Root == "" && context.BaseDir == "" || context.Root != "" && !filepath.IsAbs(context.Root) || context.BaseDir != "" && !filepath.IsAbs(context.BaseDir) {
return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "absent-input filesystem root and base directories must be absolute host paths")} return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "absent-input filesystem root and base directories must be absolute host paths")}
} }
return nil return nil

View File

@@ -30,8 +30,8 @@ type resourceIdentity struct {
occurrence *namespaceToken occurrence *namespaceToken
} }
// filesystemAccess is a load-scoped view of either a contained host root or a // filesystemAccess is a load-scoped view of bounded or unbounded host access,
// borrowed native filesystem. Names are canonical host paths or fs.FS paths. // or a borrowed native filesystem. Names are canonical host paths or fs.FS paths.
type filesystemAccess struct { type filesystemAccess struct {
rootPath string rootPath string
root *os.Root root *os.Root
@@ -41,6 +41,9 @@ type filesystemAccess struct {
} }
func openHostAccess(rootPath string) (*filesystemAccess, error) { func openHostAccess(rootPath string) (*filesystemAccess, error) {
if rootPath == "" {
return &filesystemAccess{token: &namespaceToken{}}, nil
}
root, err := os.OpenRoot(rootPath) root, err := os.OpenRoot(rootPath)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -83,7 +86,7 @@ func (a *filesystemAccess) dir(name string) string {
func (a *filesystemAccess) contains(name string) bool { func (a *filesystemAccess) contains(name string) bool {
if a.native == nil { if a.native == nil {
return containedPath(a.rootPath, filepath.Clean(name)) return filepath.IsAbs(name) && (a.rootPath == "" || containedPath(a.rootPath, filepath.Clean(name)))
} }
if !fs.ValidPath(name) || !fs.ValidPath(a.rootPath) { if !fs.ValidPath(name) || !fs.ValidPath(a.rootPath) {
return false return false
@@ -112,6 +115,12 @@ func (a *filesystemAccess) relative(name string) (string, error) {
} }
return name, nil return name, nil
} }
if a.rootPath == "" {
if !filepath.IsAbs(name) {
return "", fs.ErrInvalid
}
return name, nil
}
relative, err := filepath.Rel(a.rootPath, name) relative, err := filepath.Rel(a.rootPath, name)
if err != nil || filepath.IsAbs(relative) || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) { if err != nil || filepath.IsAbs(relative) || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return "", fs.ErrInvalid return "", fs.ErrInvalid
@@ -127,6 +136,9 @@ func (a *filesystemAccess) stat(name string) (fs.FileInfo, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
if a.root == nil {
return os.Stat(relative)
}
return a.root.Stat(relative) return a.root.Stat(relative)
} }
@@ -138,6 +150,9 @@ func (a *filesystemAccess) open(name string) (fs.File, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
if a.root == nil {
return os.Open(relative)
}
return a.root.Open(relative) return a.root.Open(relative)
} }

View File

@@ -0,0 +1,78 @@
package engine
import (
"errors"
"io"
"io/fs"
"path/filepath"
"testing"
)
func TestHostAccessModes(t *testing.T) {
t.Parallel()
anchor := canonicalTestPath(t, t.TempDir())
external := canonicalTestPath(t, t.TempDir())
file := writeImportFile(t, external, "fragment.yml", "value: external\n")
token := &namespaceToken{}
for _, bounded := range []bool{false, true} {
name := "unbounded"
boundary := ""
if bounded {
name = "bounded"
boundary = anchor
}
t.Run(name, func(t *testing.T) {
access, err := openResolvedFilesystemAccess(resolvedFilesystemContext{rootPath: anchor, basePath: anchor, importRoot: boundary, hostToken: token})
if err != nil {
t.Fatal(err)
}
defer access.close()
if access.token != token {
t.Fatal("host namespace was replaced")
}
if access.contains(file) == bounded {
t.Fatalf("contains external = %v", access.contains(file))
}
info, err := access.stat(file)
if bounded {
if err == nil {
t.Fatal("bounded stat escaped root")
}
if _, err := access.open(file); err == nil {
t.Fatal("bounded open escaped root")
}
return
}
if err != nil || !info.Mode().IsRegular() {
t.Fatalf("external stat = %v, %v", info, err)
}
opened, err := access.open(file)
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(opened)
if err != nil || string(data) != "value: external\n" {
t.Fatalf("read = %q, %v", data, err)
}
if err := opened.Close(); err != nil {
t.Fatal(err)
}
count := 0
if err := access.readDirectory(external, func(fs.DirEntry) bool { count++; return true }); err != nil || count != 1 {
t.Fatalf("directory count=%d, error=%v", count, err)
}
if err := access.readDirectory(filepath.Join(external, "missing"), func(fs.DirEntry) bool { return true }); !missingDirectoryOpen(err) {
t.Fatalf("missing directory = %v", err)
}
if _, err := access.open("relative.yml"); !errors.Is(err, fs.ErrInvalid) {
t.Fatalf("relative host open = %v", err)
}
if access.root != nil {
t.Fatal("unbounded access retained root handle")
}
if err := access.close(); err != nil {
t.Fatal(err)
}
})
}
}

View File

@@ -9,11 +9,12 @@ import (
) )
type resolvedFilesystemContext struct { type resolvedFilesystemContext struct {
native *nativeNamespace native *nativeNamespace
hostToken *namespaceToken hostToken *namespaceToken
rootPath string rootPath string
basePath string importRoot string
mainPath string basePath string
mainPath string
} }
func resolveFilesystemContext(source Source, context *FilesystemContext, main parsedSource, hostToken *namespaceToken) (resolvedFilesystemContext, *Diagnostic) { func resolveFilesystemContext(source Source, context *FilesystemContext, main parsedSource, hostToken *namespaceToken) (resolvedFilesystemContext, *Diagnostic) {
@@ -31,7 +32,7 @@ func resolveFilesystemContext(source Source, context *FilesystemContext, main pa
func resolveCapturedFilesystemContext(source Source, context *FilesystemContext, main parsedSource, hostToken *namespaceToken) (resolvedFilesystemContext, *Diagnostic) { func resolveCapturedFilesystemContext(source Source, context *FilesystemContext, main parsedSource, hostToken *namespaceToken) (resolvedFilesystemContext, *Diagnostic) {
captured := source.captured captured := source.captured
resolved := resolvedFilesystemContext{hostToken: hostToken, rootPath: captured.rootPath, basePath: captured.basePath, mainPath: captured.mainPath} resolved := resolvedFilesystemContext{hostToken: hostToken, rootPath: captured.rootPath, importRoot: captured.importRoot, basePath: captured.basePath, mainPath: captured.mainPath}
if context == nil { if context == nil {
return resolved, nil return resolved, nil
} }
@@ -39,13 +40,17 @@ func resolveCapturedFilesystemContext(source Source, context *FilesystemContext,
value := optionDiagnostic(CodeOptionsInvalid, "prepared source requires a compatible host filesystem context") value := optionDiagnostic(CodeOptionsInvalid, "prepared source requires a compatible host filesystem context")
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
// The source record carries the captured canonical main path, so this does if context.Root == "" {
// not follow the original filename again after preparation. return resolved, nil
explicit, diagnostic := resolveHostFilesystemContext(source, context, main, hostToken) }
if diagnostic != nil || !sameHostPath(explicit.rootPath, resolved.rootPath) || !sameHostPath(explicit.basePath, resolved.basePath) || !sameHostPath(explicit.mainPath, resolved.mainPath) { // Check only the supplied root. Captured main identity and base remain
// usable after deletion or retargeting of the original main filename.
root, err := canonicalExistingPath(context.Root)
if err != nil || !sameHostPath(root, captured.rootPath) {
value := optionDiagnostic(CodeOptionsInvalid, "prepared source requires a compatible host filesystem context") value := optionDiagnostic(CodeOptionsInvalid, "prepared source requires a compatible host filesystem context")
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
resolved.importRoot = root
return resolved, nil return resolved, nil
} }
@@ -57,24 +62,35 @@ func resolveAbsentFilesystemContext(context *FilesystemContext) (resolvedFilesys
if context.FS != nil { if context.FS != nil {
return resolveNativeFilesystemContext(Source{kind: sourceNone}, context) return resolveNativeFilesystemContext(Source{kind: sourceNone}, context)
} }
rootPath, err := canonicalExistingPath(context.Root) if context.Root == "" && context.BaseDir == "" {
value := optionDiagnostic(CodeOptionsInvalid, "absent-input filesystem context requires a base or root directory")
return resolvedFilesystemContext{}, &value
}
anchor := context.Root
if anchor == "" {
anchor = context.BaseDir
}
rootPath, err := canonicalExistingPath(anchor)
if err != nil { if err != nil {
value := importDiagnostic(CodeImportInvalid, "configuration root could not be canonicalized", nil) value := importDiagnostic(CodeImportInvalid, "configuration root could not be canonicalized", nil)
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
basePath := rootPath resolved := resolvedFilesystemContext{rootPath: rootPath, basePath: rootPath}
if context.Root != "" {
resolved.importRoot = rootPath
}
if context.BaseDir != "" { if context.BaseDir != "" {
basePath, err = canonicalExistingPath(context.BaseDir) resolved.basePath, err = canonicalExistingPath(context.BaseDir)
if err != nil { if err != nil {
value := importDiagnostic(CodeImportInvalid, "import base directory could not be canonicalized", nil) value := importDiagnostic(CodeImportInvalid, "import base directory could not be canonicalized", nil)
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
} }
if !containedPath(rootPath, basePath) { if resolved.importRoot != "" && !containedPath(resolved.importRoot, resolved.basePath) {
value := importDiagnostic(CodeImportOutsideRoot, "selected source and import base must stay inside the configuration root", nil) value := importDiagnostic(CodeImportOutsideRoot, "selected source and import base must stay inside the configuration root", nil)
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
return resolvedFilesystemContext{rootPath: rootPath, basePath: basePath}, nil return resolved, nil
} }
func resolveNativeFilesystemContext(source Source, context *FilesystemContext) (resolvedFilesystemContext, *Diagnostic) { func resolveNativeFilesystemContext(source Source, context *FilesystemContext) (resolvedFilesystemContext, *Diagnostic) {
@@ -96,6 +112,7 @@ func resolveNativeFilesystemContext(source Source, context *FilesystemContext) (
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
resolved.native = namespace resolved.native = namespace
resolved.importRoot = resolved.rootPath
if !containsNativePath(resolved.rootPath, resolved.basePath) || resolved.mainPath != "" && !containsNativePath(resolved.rootPath, resolved.mainPath) { if !containsNativePath(resolved.rootPath, resolved.basePath) || resolved.mainPath != "" && !containsNativePath(resolved.rootPath, resolved.mainPath) {
value := importDiagnostic(CodeImportOutsideRoot, "selected source and import base must stay inside the configuration root", nil) value := importDiagnostic(CodeImportOutsideRoot, "selected source and import base must stay inside the configuration root", nil)
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
@@ -133,13 +150,14 @@ func resolveHostFilesystemContext(source Source, context *FilesystemContext, mai
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
resolved.rootPath = rootPath resolved.rootPath = rootPath
resolved.importRoot = rootPath
} }
} else { } else {
if context == nil || context.BaseDir == "" || context.Root == "" { if context == nil || context.BaseDir == "" {
value := optionDiagnostic(CodeOptionsInvalid, "byte and reader imports require absolute base and root directories") value := optionDiagnostic(CodeOptionsInvalid, "synthetic imports require an absolute base directory")
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
if !filepath.IsAbs(context.BaseDir) || !filepath.IsAbs(context.Root) { if !filepath.IsAbs(context.BaseDir) || context.Root != "" && !filepath.IsAbs(context.Root) {
value := optionDiagnostic(CodeOptionsInvalid, "byte and reader import base and root directories must be absolute") value := optionDiagnostic(CodeOptionsInvalid, "byte and reader import base and root directories must be absolute")
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
@@ -149,7 +167,11 @@ func resolveHostFilesystemContext(source Source, context *FilesystemContext, mai
value := importDiagnostic(CodeImportInvalid, "import base directory could not be canonicalized", nil) value := importDiagnostic(CodeImportInvalid, "import base directory could not be canonicalized", nil)
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
} }
resolved.rootPath, err = canonicalExistingPath(context.Root) resolved.rootPath = resolved.basePath
if context.Root != "" {
resolved.rootPath, err = canonicalExistingPath(context.Root)
resolved.importRoot = resolved.rootPath
}
if err != nil { if err != nil {
value := importDiagnostic(CodeImportInvalid, "configuration root could not be canonicalized", nil) value := importDiagnostic(CodeImportInvalid, "configuration root could not be canonicalized", nil)
return resolvedFilesystemContext{}, &value return resolvedFilesystemContext{}, &value
@@ -171,6 +193,9 @@ func containsNativePath(root, name string) bool {
func validateResolvedFilesystemDirectories(resolved resolvedFilesystemContext) *Diagnostic { func validateResolvedFilesystemDirectories(resolved resolvedFilesystemContext) *Diagnostic {
for _, directory := range []string{resolved.rootPath, resolved.basePath} { for _, directory := range []string{resolved.rootPath, resolved.basePath} {
if directory == "" {
continue
}
var info fs.FileInfo var info fs.FileInfo
var err error var err error
if resolved.native != nil { if resolved.native != nil {
@@ -192,7 +217,7 @@ func openResolvedFilesystemAccess(resolved resolvedFilesystemContext) (*filesyst
access.label = resolved.native.label access.label = resolved.native.label
return access, nil return access, nil
} }
access, err := openHostAccess(resolved.rootPath) access, err := openHostAccess(resolved.importRoot)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -0,0 +1,64 @@
package engine
import (
"path/filepath"
"testing"
)
func TestHostFilesystemContextFacts(t *testing.T) {
t.Parallel()
base := canonicalTestPath(t, t.TempDir())
other := canonicalTestPath(t, t.TempDir())
mainPath := writeImportFile(t, base, "main.yml", "value: main\n")
for _, entry := range []struct {
name string
source Source
context *FilesystemContext
main parsedSource
root, lookup, bound string
code Code
}{
{name: "selected default", source: File(mainPath), main: parsedSource{source: &SourceInfo{Path: mainPath}}, root: base, lookup: base},
{name: "selected bounded", source: File(mainPath), context: &FilesystemContext{Root: base}, main: parsedSource{source: &SourceInfo{Path: mainPath}}, root: base, lookup: base, bound: base},
{name: "synthetic base", source: Bytes("main", nil), context: &FilesystemContext{BaseDir: base}, main: parsedSource{source: &SourceInfo{}}, root: base, lookup: base},
{name: "absent base", source: NoSource(), context: &FilesystemContext{BaseDir: base}, root: base, lookup: base},
{name: "absent root", source: NoSource(), context: &FilesystemContext{Root: base}, root: base, lookup: base, bound: base},
{name: "outside base", source: NoSource(), context: &FilesystemContext{BaseDir: other, Root: base}, code: CodeImportOutsideRoot},
} {
t.Run(entry.name, func(t *testing.T) {
if entry.context != nil {
if diagnostics := filesystemOptionDiagnostics(entry.source, entry.context); len(diagnostics) != 0 {
t.Fatal(diagnostics)
}
}
got, diagnostic := validateFilesystemContext(entry.source, entry.context, entry.main, nil)
if entry.code != "" {
if diagnostic == nil || diagnostic.Code != entry.code {
t.Fatalf("diagnostic = %v", diagnostic)
}
return
}
if diagnostic != nil {
t.Fatal(diagnostic)
}
if got.rootPath != entry.root || got.basePath != entry.lookup || got.importRoot != entry.bound {
t.Fatalf("context = %#v", got)
}
})
}
}
func TestSearchBaseOnlyContextDependsOnSelection(t *testing.T) {
t.Parallel()
base := t.TempDir()
main := writeImportFile(t, base, "main.yml", "value: main\n")
options := Options[discoveryLoadConfig]{Filesystem: &FilesystemContext{BaseDir: base}}
if _, err := testLoad(SearchConfig("", Paths(filepath.Join(base, "missing.yml"))), options); err != nil {
t.Fatal(err)
}
// Once a file is selected, its directory owns the base. Selection is terminal.
if loaded, err := testLoad(SearchConfig("", Paths(main)), options); err == nil || loaded != nil {
t.Fatalf("selected = %v, %v", loaded, err)
}
}

View File

@@ -3,6 +3,7 @@ package engine
import ( import (
"errors" "errors"
"io/fs" "io/fs"
"os"
"path" "path"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -37,7 +38,12 @@ func (a *filesystemAccess) importEntryTarget(name string, entry fs.DirEntry, fol
} }
relative = filepath.Join(filepath.FromSlash(resolvedParent), filepath.Base(relative)) relative = filepath.Join(filepath.FromSlash(resolvedParent), filepath.Base(relative))
} }
info, err := a.root.Lstat(relative) var info fs.FileInfo
if a.root == nil {
info, err = os.Lstat(relative)
} else {
info, err = a.root.Lstat(relative)
}
if err != nil { if err != nil {
return importEntryTarget{}, err return importEntryTarget{}, err
} }
@@ -52,8 +58,11 @@ func (a *filesystemAccess) importEntryTarget(name string, entry fs.DirEntry, fol
if err != nil { if err != nil {
return importEntryTarget{}, err return importEntryTarget{}, err
} }
resolvedPath := filepath.Join(a.rootPath, filepath.FromSlash(resolved)) resolvedPath := filepath.FromSlash(resolved)
info, err = a.root.Stat(filepath.FromSlash(resolved)) if a.root != nil {
resolvedPath = filepath.Join(a.rootPath, resolvedPath)
}
info, err = a.stat(resolvedPath)
if err != nil { if err != nil {
return importEntryTarget{}, err return importEntryTarget{}, err
} }
@@ -127,16 +136,46 @@ type importLinkFrame struct {
} }
type importLinkOperations struct { type importLinkOperations struct {
pathRoot func(string) string
lstat func(string) (fs.FileInfo, error) lstat func(string) (fs.FileInfo, error)
readlink func(string) (string, error) readlink func(string) (string, error)
normalizeTarget func(string, string) (string, error) normalizeTarget func(string, string) (string, error)
// visit observes completed input components, not components of link targets.
visit func(string, fs.FileInfo) error
} }
func resolveImportLinkPath(name string, operations importLinkOperations) (string, error) { func resolveImportLinkPath(name string, operations importLinkOperations) (string, error) {
frames := []importLinkFrame{{pending: strings.Split(name, "/")}} return resolveImportLinkPathFrom("", name, operations)
resolved := "" }
// base is an already resolved directory. Link expansions still start in their
// own root coordinates and use the same active/completed frame state.
func resolveImportLinkPathFrom(base, name string, operations importLinkOperations) (string, error) {
split := func(name string) (string, []string) {
root := ""
if operations.pathRoot != nil {
root = operations.pathRoot(name)
}
return root, strings.Split(strings.TrimPrefix(name, root), "/")
}
resolved, pending := split(name)
if resolved == "" {
resolved = base
}
visit := func(info fs.FileInfo) error {
if operations.visit == nil {
return nil
}
return operations.visit(resolved, info)
}
frames := []importLinkFrame{{pending: pending}}
active := make(map[string]struct{}) active := make(map[string]struct{})
completed := make(map[string]string) var resolvedInfo fs.FileInfo
type resolvedLink struct {
path string
info fs.FileInfo
}
completed := make(map[string]resolvedLink)
for len(frames) > 0 { for len(frames) > 0 {
frame := &frames[len(frames)-1] frame := &frames[len(frames)-1]
if len(frame.pending) == 0 { if len(frame.pending) == 0 {
@@ -144,12 +183,20 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
if resolved == "" { if resolved == "" {
resolved = "." resolved = "."
} }
completed[frame.link] = resolved completed[frame.link] = resolvedLink{resolved, resolvedInfo}
delete(active, frame.link) delete(active, frame.link)
} }
frames = frames[:len(frames)-1] frames = frames[:len(frames)-1]
if frame.link != "" && len(frames) == 1 && operations.visit != nil {
if err := visit(resolvedInfo); err != nil {
return "", err
}
}
continue continue
} }
if resolvedInfo != nil && !resolvedInfo.IsDir() {
return "", fs.ErrInvalid
}
segment := frame.pending[0] segment := frame.pending[0]
frame.pending = frame.pending[1:] frame.pending = frame.pending[1:]
candidate := path.Join(resolved, segment) candidate := path.Join(resolved, segment)
@@ -160,12 +207,22 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
if err != nil { if err != nil {
return "", err return "", err
} }
if info.Mode()&fs.ModeSymlink == 0 { if operations.readlink == nil || info.Mode()&fs.ModeSymlink == 0 {
resolved = candidate resolved, resolvedInfo = candidate, info
if len(frames) == 1 {
if err := visit(info); err != nil {
return "", err
}
}
continue continue
} }
if target, ok := completed[candidate]; ok { if target, ok := completed[candidate]; ok {
resolved = target resolved, resolvedInfo = target.path, target.info
if len(frames) == 1 {
if err := visit(resolvedInfo); err != nil {
return "", err
}
}
continue continue
} }
if _, exists := active[candidate]; exists { if _, exists := active[candidate]; exists {
@@ -180,8 +237,10 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
return "", err return "", err
} }
active[candidate] = struct{}{} active[candidate] = struct{}{}
frames = append(frames, importLinkFrame{pending: strings.Split(targetPath, "/"), link: candidate}) root, pending := split(targetPath)
resolved = "" frames = append(frames, importLinkFrame{pending: pending, link: candidate})
resolved = root
resolvedInfo = nil
} }
if resolved == "" { if resolved == "" {
resolved = "." resolved = "."
@@ -190,30 +249,78 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
} }
func resolveHostImportPath(access *filesystemAccess, name string) (string, error) { func resolveHostImportPath(access *filesystemAccess, name string) (string, error) {
return resolveImportLinkPath(filepath.ToSlash(name), hostImportLinkOperations(access)) if access.root == nil && !filepath.IsAbs(name) {
return "", fs.ErrInvalid
}
resolved, err := resolveImportLinkPath(filepath.ToSlash(name), hostImportLinkOperations(access))
if err != nil || access.root == nil {
return resolved, err
}
if filepath.IsAbs(filepath.FromSlash(resolved)) {
relative, err := access.relative(filepath.FromSlash(resolved))
if err != nil {
return "", errImportPathOutsideRoot
}
return filepath.ToSlash(relative), nil
}
if !withinPortableRoot(resolved) {
return "", errImportPathOutsideRoot
}
return resolved, nil
} }
func hostImportLinkOperations(access *filesystemAccess) importLinkOperations { func hostImportLinkOperations(access *filesystemAccess) importLinkOperations {
// Absolute target components may include resolution prefixes outside Root.
// Use the live root for contained names and ordinary host inspection for
// those prefixes; target admission remains bounded by canonical identity.
rootedName := func(candidate string) (string, bool) {
name := filepath.FromSlash(candidate)
if access.root == nil {
return name, false
}
if !filepath.IsAbs(name) {
return name, true
}
if relative, err := access.relative(name); err == nil {
return relative, true
}
return name, false
}
return importLinkOperations{ return importLinkOperations{
pathRoot: func(name string) string {
if !filepath.IsAbs(filepath.FromSlash(name)) {
return ""
}
return filepath.ToSlash(filepath.VolumeName(filepath.FromSlash(name))) + "/"
},
lstat: func(candidate string) (fs.FileInfo, error) { lstat: func(candidate string) (fs.FileInfo, error) {
return access.root.Lstat(filepath.FromSlash(candidate)) name, rooted := rootedName(candidate)
if rooted {
return access.root.Lstat(name)
}
return os.Lstat(name)
}, },
readlink: func(candidate string) (string, error) { readlink: func(candidate string) (string, error) {
return access.root.Readlink(filepath.FromSlash(candidate)) name, rooted := rootedName(candidate)
if rooted {
return access.root.Readlink(name)
}
return os.Readlink(name)
}, },
normalizeTarget: func(candidate, target string) (string, error) { normalizeTarget: func(candidate, target string) (string, error) {
var targetPath string targetPath := filepath.ToSlash(target)
if filepath.IsAbs(target) { if !filepath.IsAbs(target) {
relative, err := filepath.Rel(access.rootPath, filepath.Clean(target)) // Do not Join/Clean here: a link before .. must resolve first.
if err != nil { targetPath = path.Dir(candidate) + "/" + targetPath
}
if access.root != nil {
if filepath.IsAbs(filepath.FromSlash(targetPath)) {
if !containedPath(access.rootPath, filepath.Clean(filepath.FromSlash(targetPath))) {
return "", errImportPathOutsideRoot
}
} else if !withinPortableRoot(path.Clean(targetPath)) {
return "", errImportPathOutsideRoot return "", errImportPathOutsideRoot
} }
targetPath = path.Clean(filepath.ToSlash(relative))
} else {
targetPath = path.Clean(path.Join(path.Dir(candidate), filepath.ToSlash(target)))
}
if !withinPortableRoot(targetPath) {
return "", errImportPathOutsideRoot
} }
return targetPath, nil return targetPath, nil
}, },
@@ -228,7 +335,11 @@ func resolveNativeImportPath(access *filesystemAccess, filesystem fs.ReadLinkFS,
if !fs.ValidPath(name) || !access.contains(name) { if !fs.ValidPath(name) || !access.contains(name) {
return "", fs.ErrInvalid return "", fs.ErrInvalid
} }
return resolveImportLinkPath(name, importLinkOperations{ return resolveImportLinkPath(name, nativeImportLinkOperations(access, filesystem))
}
func nativeImportLinkOperations(access *filesystemAccess, filesystem fs.ReadLinkFS) importLinkOperations {
return importLinkOperations{
lstat: func(candidate string) (fs.FileInfo, error) { lstat: func(candidate string) (fs.FileInfo, error) {
// Ancestors of a multi-component root are resolution prefixes, not // Ancestors of a multi-component root are resolution prefixes, not
// selected targets. Complete paths and link targets remain contained. // selected targets. Complete paths and link targets remain contained.
@@ -242,13 +353,14 @@ func resolveNativeImportPath(access *filesystemAccess, filesystem fs.ReadLinkFS,
if target == "" || strings.HasPrefix(target, "/") { if target == "" || strings.HasPrefix(target, "/") {
return "", errImportPathOutsideRoot return "", errImportPathOutsideRoot
} }
targetPath := path.Clean(path.Join(path.Dir(candidate), target)) targetPath := path.Dir(candidate) + "/" + target
if !fs.ValidPath(targetPath) || !access.contains(targetPath) { clean := path.Clean(targetPath)
if !fs.ValidPath(clean) || !access.contains(clean) {
return "", errImportPathOutsideRoot return "", errImportPathOutsideRoot
} }
return targetPath, nil return targetPath, nil
}, },
}) }
} }
func isImportLinkCycle(err error) bool { func isImportLinkCycle(err error) bool {

View File

@@ -313,3 +313,45 @@ func (f *countingReadLinkFS) ReadLink(name string) (string, error) {
f.readLinks++ f.readLinks++
return f.links.ReadLink(name) return f.links.ReadLink(name)
} }
func TestUnboundedHostLinkInspection(t *testing.T) {
root := canonicalTestPath(t, t.TempDir())
external := canonicalTestPath(t, t.TempDir())
file := writeImportFile(t, external, "part.yml", "value: linked\n")
for name, target := range map[string]string{"external": external, "self": "self", "first": "second", "second": "first"} {
if err := os.Symlink(target, filepath.Join(root, name)); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
}
access, err := openHostAccess("")
if err != nil {
t.Fatal(err)
}
defer access.close()
selected := filepath.Join(root, "external")
target, err := access.importEntryTarget(selected, nil, false)
if err != nil || !target.symlink || target.dir {
t.Fatalf("unfollowed target=%#v, %v", target, err)
}
target, err = access.importEntryTarget(selected, nil, true)
if err != nil || !target.dir || target.identity != external {
t.Fatalf("followed target=%#v, %v", target, err)
}
got, err := resolveHostImportPath(access, filepath.Join(selected, "part.yml"))
if err != nil || filepath.FromSlash(got) != file {
t.Fatalf("intermediate absolute link=%q, %v", got, err)
}
for _, name := range []string{"self", "first"} {
if _, err := resolveHostImportPath(access, filepath.Join(root, name)); !errors.Is(err, errImportDirectoryLinkCycle) {
t.Fatalf("cycle %s=%v", name, err)
}
}
bounded, err := openHostAccess(root)
if err != nil {
t.Fatal(err)
}
defer bounded.close()
if _, err := bounded.importEntryTarget(selected, nil, true); !errors.Is(err, errImportPathOutsideRoot) {
t.Fatalf("bounded external target=%v", err)
}
}

View File

@@ -4,13 +4,20 @@ import (
"errors" "errors"
"io/fs" "io/fs"
"path" "path"
"slices" "path/filepath"
"sort" "sort"
"strings" "strings"
) )
const globReadBatch = 128 const globReadBatch = 128
// A parent step can give distinct link targets the same lexical spelling.
// Keep both coordinates until traversal and source admission have completed.
type globCandidateKey struct {
lexical string
physical string
}
// selectGlobImportCandidates expands path components while retaining the // selectGlobImportCandidates expands path components while retaining the
// lexical spelling used for filtering and later source admission. // lexical spelling used for filtering and later source admission.
func selectGlobImportCandidates(access *filesystemAccess, basePath string, spec importDeclarationSpec, policy resolvedImportPolicy, limits importLimits, accounting *importAccounting) (importSelection, []Diagnostic) { func selectGlobImportCandidates(access *filesystemAccess, basePath string, spec importDeclarationSpec, policy resolvedImportPolicy, limits importLimits, accounting *importAccounting) (importSelection, []Diagnostic) {
@@ -26,24 +33,40 @@ func selectGlobImportCandidates(access *filesystemAccess, basePath string, spec
if accounting == nil { if accounting == nil {
accounting = &importAccounting{} accounting = &importAccounting{}
} }
rootPath := normalizedImportCandidatePath(access, basePath) candidates, prefixLength, diagnostics := globStartingCandidates(access, basePath, spec.glob, segments, site)
candidates := []selectedImportCandidate{{path: rootPath, accessPath: basePath, site: site}} if len(diagnostics) != 0 {
for index, segment := range segments { return importSelection{}, diagnostics
}
for index := prefixLength; index < len(segments); index++ {
segment := segments[index]
last := index == len(segments)-1 last := index == len(segments)-1
literal, patterned := globLiteralSegment(segment) literal, patterned := globLiteralSegment(segment)
// nextByPath is the set union of candidates reached from each matching // nextByPath is the set union of candidates reached from each matching
// parent at this segment; final exclusions below are set difference. // parent at this segment; final exclusions below are set difference.
nextByPath := make(map[string]selectedImportCandidate) nextByPath := make(map[globCandidateKey]selectedImportCandidate)
for _, parent := range candidates { for _, parent := range candidates {
if !patterned { if !patterned {
childPath := access.join(parent.path, literal) childPath := access.join(parent.path, literal)
childAccessPath := access.join(parent.accessPath, literal) parentAccessPath := parent.accessPath
if literal == ".." {
target, err := access.importEntryTarget(parent.accessPath, nil, true)
if err != nil {
return importSelection{}, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob parent directory could not be inspected")}
}
if !target.dir {
continue
}
if target.identity != "" {
parentAccessPath = target.identity
}
}
childAccessPath := access.join(parentAccessPath, literal)
candidate, missing, diagnostics := explicitGlobCandidate(access, basePath, childPath, childAccessPath, site, last) candidate, missing, diagnostics := explicitGlobCandidate(access, basePath, childPath, childAccessPath, site, last)
if len(diagnostics) != 0 { if len(diagnostics) != 0 {
return importSelection{}, diagnostics return importSelection{}, diagnostics
} }
if !missing { if !missing {
nextByPath[candidate.path] = candidate nextByPath[globCandidateKey{candidate.path, candidate.accessPath}] = candidate
} }
continue continue
} }
@@ -61,7 +84,7 @@ func selectGlobImportCandidates(access *filesystemAccess, basePath string, spec
return importSelection{}, []Diagnostic{*diagnostic} return importSelection{}, []Diagnostic{*diagnostic}
} }
if selected { if selected {
nextByPath[candidate.path] = candidate nextByPath[globCandidateKey{candidate.path, candidate.accessPath}] = candidate
} }
} }
} }
@@ -220,16 +243,17 @@ func globCandidateDiagnostic(err error, location Location, message string) Diagn
return globFilesystemDiagnostic(err, message, location) return globFilesystemDiagnostic(err, message, location)
} }
func candidatesFromMap(candidates map[string]selectedImportCandidate) []selectedImportCandidate { func candidatesFromMap(candidates map[globCandidateKey]selectedImportCandidate) []selectedImportCandidate {
paths := make([]string, 0, len(candidates)) result := make([]selectedImportCandidate, 0, len(candidates))
for candidatePath := range candidates { for _, candidate := range candidates {
paths = append(paths, candidatePath) result = append(result, candidate)
}
slices.Sort(paths)
result := make([]selectedImportCandidate, 0, len(paths))
for _, candidatePath := range paths {
result = append(result, candidates[candidatePath])
} }
sort.Slice(result, func(i, j int) bool {
if result[i].path != result[j].path {
return result[i].path < result[j].path
}
return result[i].accessPath < result[j].accessPath
})
return result return result
} }
@@ -237,7 +261,8 @@ func validGlobPattern(pattern string) ([]string, bool) {
if !validImportPath(pattern) { if !validImportPath(pattern) {
return nil, false return nil, false
} }
segments := strings.Split(pattern, "/") _, remainder := splitImportSelectorRoot(pattern)
segments := strings.Split(remainder, "/")
for _, segment := range segments { for _, segment := range segments {
if segment == "" || hasRecursiveStars(segment) { if segment == "" || hasRecursiveStars(segment) {
return nil, false return nil, false
@@ -293,3 +318,118 @@ func globFilesystemDiagnostic(err error, message string, location Location) Diag
} }
return importDiagnostic(code, message, &location) return importDiagnostic(code, message, &location)
} }
// globStartingCandidates inspects the literal prefix before wildcard discovery.
// Ancestors of an explicit root are resolution prefixes, never discovery roots.
func globStartingCandidates(access *filesystemAccess, base, pattern string, segments []string, site importFieldSite) ([]selectedImportCandidate, int, []Diagnostic) {
root, _ := splitImportSelectorRoot(pattern)
start := base
if root != "" {
start = root
if access.native != nil {
if root != "/" {
return nil, 0, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "glob root is outside the selected namespace")}
}
start = "."
}
}
prefixAccess := *access
if access.native != nil {
prefixAccess.rootPath = "."
} else {
prefixAccess.rootPath, prefixAccess.root = "", nil
}
candidate := selectedImportCandidate{path: normalizedImportCandidatePath(access, start), accessPath: start, site: site}
literals := make([]string, 0, len(segments))
for _, segment := range segments {
literal, patterned := globLiteralSegment(segment)
if patterned {
break
}
literals = append(literals, literal)
}
if len(literals) != 0 {
baseTarget, err := prefixAccess.importEntryTarget(start, nil, true)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil, len(literals), nil
}
return nil, 0, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob starting directory could not be inspected")}
}
if !baseTarget.dir {
return nil, len(literals), nil
}
resolvedBase := baseTarget.identity
if resolvedBase == "" {
resolvedBase = start
}
operations := hostImportLinkOperations(&prefixAccess)
if access.native != nil {
if links, ok := access.native.(fs.ReadLinkFS); ok {
operations = nativeImportLinkOperations(&prefixAccess, links)
} else {
operations = importLinkOperations{lstat: prefixAccess.stat}
}
}
index := 0
operations.visit = func(physical string, info fs.FileInfo) error {
literal := literals[index]
lexical, err := resolveLiteralImportSelector(&prefixAccess, candidate.path, literal)
if err != nil {
return err
}
accessPath := physical
if access.native != nil && literal != ".." {
// Keep native source spelling; resolved identities guide traversal.
accessPath = access.join(candidate.accessPath, literal)
}
// Retain filesystem access errors as well as link inspection errors.
if access.native != nil {
if _, err := prefixAccess.canonical(accessPath); err != nil {
return err
}
} else if _, err := prefixAccess.stat(physical); err != nil {
return err
}
if !globResolutionPrefixAllowed(access, physical) {
return errImportPathOutsideRoot
}
if index < len(segments)-1 && !info.IsDir() {
return fs.ErrNotExist
}
candidate = selectedImportCandidate{path: normalizedImportCandidatePath(access, lexical), accessPath: accessPath,
label: relativeImportLabel(access, base, lexical), site: site}
index++
return nil
}
_, err = resolveImportLinkPathFrom(resolvedBase, strings.Join(literals, "/"), operations)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil, len(literals), nil
}
return nil, 0, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob prefix could not be inspected")}
}
}
consumed := len(literals)
if !access.contains(candidate.accessPath) || !access.contains(candidate.path) {
return nil, 0, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "glob discovery starts outside the configuration root")}
}
// Native links preserve their namespace spelling; inspect with the actual
// boundary once the literal prefix has entered the selected root.
if access.native != nil {
if _, err := access.importEntryTarget(candidate.accessPath, nil, true); err != nil {
return nil, 0, []Diagnostic{globCandidateDiagnostic(err, site.location, "glob starting location could not be inspected")}
}
}
return []selectedImportCandidate{candidate}, consumed, nil
}
func globResolutionPrefixAllowed(access *filesystemAccess, name string) bool {
if access.contains(name) {
return true
}
if access.native != nil {
return containsNativePath(name, access.rootPath)
}
return access.rootPath != "" && containedPath(filepath.FromSlash(name), access.rootPath)
}

View File

@@ -0,0 +1,60 @@
package engine
import (
"path/filepath"
"strconv"
"testing"
"testing/fstest"
)
func TestAbsoluteGlobLiteralStartingLocations(t *testing.T) {
t.Parallel()
hostRoot := canonicalTestPath(t, t.TempDir())
file := writeImportFile(t, hostRoot, "workspace/allowed/fragments/one.yml", "value: one\n")
boundary := filepath.Join(hostRoot, "workspace", "allowed")
host, err := openHostAccess(boundary)
if err != nil {
t.Fatal(err)
}
defer host.close()
native := newNativeAccess(fstest.MapFS{"workspace/allowed/fragments/one.yml": &fstest.MapFile{Data: []byte("value: one\n")}}, "workspace/allowed", &namespaceToken{})
for _, mode := range []struct {
name string
access *filesystemAccess
base, root, want string
}{
{"host", host, boundary, filepath.ToSlash(boundary), filepath.ToSlash(file)},
{"native", native, "workspace/allowed", "/workspace/allowed", "workspace/allowed/fragments/one.yml"},
} {
t.Run(mode.name, func(t *testing.T) {
for _, pattern := range []string{mode.root + "/fragments/*.yml", mode.root + "/fragments/one.yml"} {
selection, diagnostics := selectGlobForTestWithDiagnostics(t, mode.access, mode.base, " - glob: "+strconv.Quote(pattern)+"\n required: true\n")
if len(diagnostics) != 0 || len(selection.candidates) != 1 || selection.candidates[0].path != mode.want {
t.Fatalf("pattern %q: selection=%#v, diagnostics=%#v", pattern, selection, diagnostics)
}
}
for _, entry := range []struct {
pattern string
required bool
code Code
}{
{mode.root + "/missing/*.yml", false, ""},
{mode.root + "/missing/*.yml", true, CodeImportMissing},
{mode.root + "/missing/../fragments/*.yml", true, CodeImportMissing},
{mode.root + "/../../*/*.yml", true, CodeImportOutsideRoot},
} {
declaration := " - glob: " + strconv.Quote(entry.pattern) + "\n required: " + strconv.FormatBool(entry.required) + "\n"
selection, diagnostics := selectGlobForTestWithDiagnostics(t, mode.access, mode.base, declaration)
if entry.code == "" {
if len(diagnostics) != 0 || len(selection.candidates) != 0 {
t.Fatalf("optional missing=%#v, %#v", selection, diagnostics)
}
continue
}
if len(diagnostics) == 0 || diagnostics[0].Code != entry.code {
t.Fatalf("pattern %q diagnostics=%#v", entry.pattern, diagnostics)
}
}
})
}
}

View File

@@ -189,8 +189,9 @@ func selectGlobForTestWithDiagnostics(t *testing.T, access *filesystemAccess, ba
} }
type observedGlobFilesystem struct { type observedGlobFilesystem struct {
files fstest.MapFS files fstest.MapFS
opened []string opened []string
failStat string
} }
func (filesystem *observedGlobFilesystem) Open(name string) (fs.File, error) { func (filesystem *observedGlobFilesystem) Open(name string) (fs.File, error) {
@@ -199,5 +200,105 @@ func (filesystem *observedGlobFilesystem) Open(name string) (fs.File, error) {
} }
func (filesystem *observedGlobFilesystem) Stat(name string) (fs.FileInfo, error) { func (filesystem *observedGlobFilesystem) Stat(name string) (fs.FileInfo, error) {
if name == filesystem.failStat {
return nil, fs.ErrPermission
}
return fs.Stat(filesystem.files, name) return fs.Stat(filesystem.files, name)
} }
func TestSelectGlobInspectsWildcardBeforeParent(t *testing.T) {
t.Parallel()
filesystem := &observedGlobFilesystem{files: fstest.MapFS{
"services/unit/marker": &fstest.MapFile{},
"services/shared/one.yml": &fstest.MapFile{Data: []byte("value: one\n")},
"services/irrelevant": &fstest.MapFile{},
}}
access := newNativeAccess(filesystem, ".", &namespaceToken{})
declaration := " - glob: services/*/../shared/*.yml\n required: true\n"
selection, diagnostics := selectGlobForTestWithDiagnostics(t, access, ".", declaration)
if len(diagnostics) != 0 || !equalStrings(selectedPaths(selection), []string{"services/shared/one.yml"}) {
t.Fatalf("selection=%#v, diagnostics=%#v", selection, diagnostics)
}
filesystem.failStat = "services/unit"
_, diagnostics = selectGlobForTestWithDiagnostics(t, access, ".", declaration+" exclude: '*.yml'\n")
if len(diagnostics) == 0 || diagnostics[0].Code != CodeImportPermission {
t.Fatalf("matched directory failure=%#v", diagnostics)
}
missing := selectGlobForTest(t, access, ".", " - glob: services/absent*/../shared/*.yml\n")
if len(missing.candidates) != 0 {
t.Fatalf("unmatched wildcard was cleaned away: %#v", missing)
}
}
func TestSelectGlobParentUsesMatchedLinkTarget(t *testing.T) {
root := canonicalTestPath(t, t.TempDir())
writeImportFile(t, root, "targets/unit/marker", "marker")
file := writeImportFile(t, root, "targets/shared/one.yml", "value: one\n")
if err := os.MkdirAll(filepath.Join(root, "services"), 0700); err != nil {
t.Fatal(err)
}
if err := os.Symlink("../targets/unit", filepath.Join(root, "services", "alias")); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
host, err := openHostAccess(root)
if err != nil {
t.Fatal(err)
}
defer host.close()
native := newNativeAccess(os.DirFS(root), ".", &namespaceToken{})
for _, mode := range []struct {
name string
access *filesystemAccess
base, want string
}{
{"host", host, root, file}, {"native", native, ".", "targets/shared/one.yml"},
} {
t.Run(mode.name, func(t *testing.T) {
for _, pattern := range []string{"services/*/../shared/*.yml", "services/alias/../shared/*.yml"} {
selection, diagnostics := selectGlobForTestWithDiagnostics(t, mode.access, mode.base, " - glob: "+pattern+"\n required: true\n")
if len(diagnostics) != 0 || len(selection.candidates) != 1 || selection.candidates[0].accessPath != mode.want {
t.Fatalf("pattern %q: selection=%#v, diagnostics=%#v", pattern, selection, diagnostics)
}
}
selection := selectGlobForTest(t, mode.access, mode.base, " - glob: services/*/../shared/*.yml\n follow: false\n")
if len(selection.candidates) != 0 {
t.Fatalf("unfollowed link selected=%#v", selection)
}
})
}
}
func TestSelectGlobRetainsDistinctPhysicalParents(t *testing.T) {
root := canonicalTestPath(t, t.TempDir())
for _, branch := range []string{"one", "two"} {
writeImportFile(t, root, branch+"/unit/marker", "marker")
writeImportFile(t, root, branch+"/shared/"+branch+".yml", "value: "+branch+"\n")
}
if err := os.Mkdir(filepath.Join(root, "services"), 0700); err != nil {
t.Fatal(err)
}
for alias, target := range map[string]string{"a": "../one/unit", "b": "../two/unit"} {
if err := os.Symlink(target, filepath.Join(root, "services", alias)); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
}
access, err := openHostAccess(root)
if err != nil {
t.Fatal(err)
}
defer access.close()
for _, mode := range []struct {
name string
access *filesystemAccess
base string
}{
{"host", access, root}, {"native", newNativeAccess(os.DirFS(root), ".", &namespaceToken{}), "."},
} {
t.Run(mode.name, func(t *testing.T) {
selection := selectGlobForTest(t, mode.access, mode.base, " - glob: services/*/../shared/*.yml\n required: true\n")
if len(selection.candidates) != 2 {
t.Fatalf("distinct physical parents coalesced: %#v", selection)
}
})
}
}

View File

@@ -96,9 +96,9 @@ func TestLoadGlobImportsRejectInvalidAndUnmatchedPatterns(t *testing.T) {
{name: "recursive star segment", pattern: "empty/**/value.yml", code: CodeImportInvalid}, {name: "recursive star segment", pattern: "empty/**/value.yml", code: CodeImportInvalid},
{name: "recursive adjacent stars", pattern: "empty/value**.yml", code: CodeImportInvalid}, {name: "recursive adjacent stars", pattern: "empty/value**.yml", code: CodeImportInvalid},
{name: "trailing separator", pattern: "empty/", code: CodeImportInvalid}, {name: "trailing separator", pattern: "empty/", code: CodeImportInvalid},
{name: "absolute", pattern: "/tmp/*.yml", code: CodeImportInvalid}, {name: "absolute outside root", code: CodeImportOutsideRoot},
{name: "URL", pattern: "https://example.invalid/*.yml", code: CodeImportInvalid}, {name: "URL", pattern: "https://example.invalid/*.yml", code: CodeImportInvalid},
{name: "missing parent escape", pattern: "../missing/*.yml", code: CodeImportOutsideRoot}, {name: "parent discovery escape", pattern: "../*/*.yml", code: CodeImportOutsideRoot},
{name: "unmatched", pattern: "empty/*.yml", code: CodeImportMissing}, {name: "unmatched", pattern: "empty/*.yml", code: CodeImportMissing},
} }
for _, test := range tests { for _, test := range tests {
@@ -107,8 +107,12 @@ func TestLoadGlobImportsRejectInvalidAndUnmatchedPatterns(t *testing.T) {
if err := os.Mkdir(filepath.Join(directory, "empty"), 0o755); err != nil { if err := os.Mkdir(filepath.Join(directory, "empty"), 0o755); err != nil {
t.Fatal(err) t.Fatal(err)
} }
mainPath := writeGlobRoot(t, directory, test.pattern, test.code == CodeImportMissing) pattern := test.pattern
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true}, test.code) if test.name == "absolute outside root" {
pattern = filepath.ToSlash(filepath.Join(t.TempDir(), "*.yml"))
}
mainPath := writeGlobRoot(t, directory, pattern, test.code == CodeImportMissing)
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true, Filesystem: &FilesystemContext{Root: directory}}, test.code)
}) })
} }
@@ -185,7 +189,7 @@ func TestLoadGlobImportsConfineSymlinkDirectories(t *testing.T) {
t.Skipf("symlinks unavailable: %v", err) t.Skipf("symlinks unavailable: %v", err)
} }
mainPath := writeGlobRoot(t, root, "linked/*.yml", false) mainPath := writeGlobRoot(t, root, "linked/*.yml", false)
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true}, CodeImportOutsideRoot) requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true, Filesystem: &FilesystemContext{Root: root}}, CodeImportOutsideRoot)
}) })
} }
@@ -253,7 +257,7 @@ func TestFilesystemContextIsValidatedWithoutImportsOrActiveOverlay(t *testing.T)
if err != nil || result.Config.Items["root"] != "memory" { if err != nil || result.Config.Items["root"] != "memory" {
t.Fatalf("byte filesystem context = %#v, %v", result, err) t.Fatalf("byte filesystem context = %#v, %v", result, err)
} }
requireLoadCode(t, Bytes("memory.yml", []byte("{}\n")), Options[importTestConfig]{Filesystem: &FilesystemContext{BaseDir: directory}}, CodeOptionsInvalid) requireLoadCode(t, Bytes("memory.yml", []byte("{}\n")), Options[importTestConfig]{Filesystem: &FilesystemContext{Root: directory}}, CodeOptionsInvalid)
defaultsOnly, err := testLoad[importTestConfig](NoSource(), Options[importTestConfig]{Overlay: "default"}) defaultsOnly, err := testLoad[importTestConfig](NoSource(), Options[importTestConfig]{Overlay: "default"})
if err != nil || defaultsOnly == nil { if err != nil || defaultsOnly == nil {
t.Fatalf("default overlay with NoSource = %#v, %v", defaultsOnly, err) t.Fatalf("default overlay with NoSource = %#v, %v", defaultsOnly, err)
@@ -301,7 +305,7 @@ func TestNoSourceImportsAndFilesystemContext(t *testing.T) {
context FilesystemContext context FilesystemContext
code Code code Code
}{ }{
{name: "missing root", context: FilesystemContext{BaseDir: directory}, code: CodeOptionsInvalid}, {name: "empty context", context: FilesystemContext{}, code: CodeOptionsInvalid},
{name: "relative root", context: FilesystemContext{Root: "."}, code: CodeOptionsInvalid}, {name: "relative root", context: FilesystemContext{Root: "."}, code: CodeOptionsInvalid},
{name: "missing root directory", context: FilesystemContext{Root: filepath.Join(directory, "missing")}, code: CodeImportInvalid}, {name: "missing root directory", context: FilesystemContext{Root: filepath.Join(directory, "missing")}, code: CodeImportInvalid},
{name: "base outside root", context: FilesystemContext{BaseDir: outside, Root: directory}, code: CodeImportOutsideRoot}, {name: "base outside root", context: FilesystemContext{BaseDir: outside, Root: directory}, code: CodeImportOutsideRoot},

View File

@@ -1,6 +1,7 @@
package engine package engine
import ( import (
"errors"
"testing" "testing"
"go.maximumdirect.net/configkit/internal/document" "go.maximumdirect.net/configkit/internal/document"
@@ -113,6 +114,17 @@ func TestLoadHistoryBudgetUsesExactRetainedNodeCount(t *testing.T) {
if rejectedValidations != 0 { if rejectedValidations != 0 {
t.Fatalf("validation ran before history rejection: %d calls", rejectedValidations) t.Fatalf("validation ran before history rejection: %d calls", rejectedValidations)
} }
var failure *LoadError
if !errors.As(err, &failure) || failure.Inspection() == nil {
t.Fatal("history rejection lost an admissible earlier checkpoint")
}
view, ok := NewInspectionView(failure.Inspection(), Path{})
if !ok || view.Stage() == InspectionStageValidated || view.Stage() == InspectionStageResolved {
t.Fatalf("history rejection checkpoint = %q, available=%v", view.Stage(), ok)
}
if retainedInspectionNodeCountForTest(failure.Inspection()) > want-1 {
t.Fatal("fallback inspection exceeds the retained-node budget")
}
} }
func TestHistoryNodeBudgetIncludesFinalInspectionProjection(t *testing.T) { func TestHistoryNodeBudgetIncludesFinalInspectionProjection(t *testing.T) {

View File

@@ -65,22 +65,26 @@ func (builder *historyBuilder) observeInheritanceControl(payload historyPayloadR
node, before := builder.scratchAt(control.path) node, before := builder.scratchAt(control.path)
selections := resolveInheritanceAttribution(operation, control.path) selections := resolveInheritanceAttribution(operation, control.path)
var attributionRef historyAttributionRef = noHistoryAttribution var attributionRef historyAttributionRef = noHistoryAttribution
var sensitive bool
if before && node != nil {
sensitive = node.Sensitive
}
if len(selections) != 0 { if len(selections) != 0 {
selection := selections[0] selection := selections[0]
attributionRef = builder.addAttribution(selection.origin, nil, selection.dependencies) attributionRef = builder.addAttribution(selection.origin, nil, selection.dependencies)
} }
ref := payload ref := payload
ref.substep = operationIndex * 2 ref.substep = operationIndex * 2
builder.addObservation(historyObservation{ observe := func(path Path, value *document.Node) {
path: control.path, phase: historyPhaseInheritance, payload: ref, builder.addObservation(historyObservation{
reportedPath: control.path, role: historyRoleControl, path: path, phase: historyPhaseInheritance, payload: ref,
beforePresent: before, sensitive: sensitive, reportedPath: control.path, role: historyRoleControl,
attributionRef: attributionRef, beforePresent: before, sensitive: value != nil && value.Sensitive,
}) attributionRef: attributionRef,
})
}
if before {
walkDocument(node, control.path, observe)
} else {
observe(control.path, nil)
}
replaceHistoryPath(&builder.scratch, control.path, nil) replaceHistoryPath(&builder.scratch, control.path, nil)
} }

View File

@@ -53,6 +53,7 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin
if len(applications) == 0 && len(records) == 0 { if len(applications) == 0 && len(records) == 0 {
return return
} }
operations := newSourceOperationIndex(builder.model)
applicationsBySource := make(map[string]historyPayloadRef) applicationsBySource := make(map[string]historyPayloadRef)
applicationsByLayer := make(map[Layer][]historyPayloadRef) applicationsByLayer := make(map[Layer][]historyPayloadRef)
for index := range applications { for index := range applications {
@@ -88,7 +89,7 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin
owned.hasApplicationRef = true owned.hasApplicationRef = true
} }
for displacedIndex, displaced := range record.displaced { for displacedIndex, displaced := range record.displaced {
if sourceOriginRepresentedByOperation(builder.model, displaced.path, displaced.origin) { if operations.contains(builder.model, displaced.path, displaced.origin) {
continue continue
} }
definitionPayload := payload definitionPayload := payload
@@ -110,12 +111,13 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin
}) })
} }
for _, introduced := range record.introduced { for _, introduced := range record.introduced {
builder.addObservation(historyObservation{ id := builder.addObservation(historyObservation{
path: introduced.path, phase: historyPhaseSources, payload: payload, path: introduced.path, phase: historyPhaseSources, payload: payload,
reportedPath: record.change.Path, role: historyRoleOperation, reportedPath: record.change.Path, role: historyRoleOperation,
afterPresent: true, sensitive: introduced.sensitive, afterPresent: true, sensitive: introduced.sensitive,
attributionRef: attribution, attributionRef: attribution,
}) })
operations.add(builder.model, id)
} }
} }
@@ -124,7 +126,7 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin
} }
walkDocument(root, Path{}, func(path Path, node *document.Node) { walkDocument(root, Path{}, func(path Path, node *document.Node) {
origin, found := origins[path.String()] origin, found := origins[path.String()]
if !found || origin.Layer == "" || sourceOriginRepresentedByOperation(builder.model, path, origin) { if !found || origin.Layer == "" || operations.contains(builder.model, path, origin) {
return return
} }
payload := builder.addSourceSummary(path, origin) payload := builder.addSourceSummary(path, origin)
@@ -191,22 +193,72 @@ func sourceApplicationOrigin(application historyApplication, node *document.Node
return origin return origin
} }
func sourceOriginRepresentedByOperation(model *historyModel, path Path, origin Origin) bool { // sourceOperationIndex is local to source evidence construction. It indexes only
for _, observationID := range model.observationsByPointer[path.String()] { // completed after-operation facts, narrowing attribution checks by source ID.
observation := model.observations[observationID] // General observation lists also contain all contributions at a path and grow
if observation.phase != historyPhaseSources || observation.role != historyRoleOperation { // with every replacement; scanning those lists per replacement is quadratic.
type sourceOperationIndex struct {
byPath map[string][]int
bySource map[sourceOperationSource][]int
}
type sourceOperationSource struct {
pointer string
sourceID string
}
func newSourceOperationIndex(model *historyModel) *sourceOperationIndex {
index := &sourceOperationIndex{
byPath: make(map[string][]int),
bySource: make(map[sourceOperationSource][]int),
}
for id := range model.observations {
index.add(model, id)
}
return index
}
func (index *sourceOperationIndex) add(model *historyModel, id int) {
if id < 0 {
return
}
observation := model.observations[id]
if observation.phase != historyPhaseSources || observation.role != historyRoleOperation || !observation.afterPresent {
return
}
attribution, ok := model.resolveAttribution(observation.attributionRef)
if !ok {
return
}
pointer := observation.path.String()
index.byPath[pointer] = append(index.byPath[pointer], id)
seen := make(map[string]struct{}, len(attribution.origin.Locations))
for _, location := range attribution.origin.Locations {
if _, found := seen[location.SourceID]; found {
continue continue
} }
if !observation.afterPresent || !sameConcreteHistoryPath(path, observation.path) { seen[location.SourceID] = struct{}{}
key := sourceOperationSource{pointer: pointer, sourceID: location.SourceID}
index.bySource[key] = append(index.bySource[key], id)
}
}
func (index *sourceOperationIndex) contains(model *historyModel, path Path, origin Origin) bool {
pointer := path.String()
candidates := index.byPath[pointer]
if len(origin.Locations) != 0 {
// Every representing origin must include this source, for both exact and
// ancestor replacements. The full predicate still checks all locations,
// contributor traces, layers, operations and concrete path shapes.
candidates = index.bySource[sourceOperationSource{pointer: pointer, sourceID: origin.Locations[0].SourceID}]
}
for _, id := range candidates {
observation := model.observations[id]
if !sameConcreteHistoryPath(path, observation.path) {
continue continue
} }
operationOrigin, ok := model.resolveAttribution(observation.attributionRef) attribution, _ := model.resolveAttribution(observation.attributionRef)
if !ok { if originRepresentedByChange(path, origin, Change{Path: observation.reportedPath, Origin: attribution.origin}) {
continue
}
if originRepresentedByChange(path, origin, Change{
Path: observation.reportedPath, Origin: operationOrigin.origin,
}) {
return true return true
} }
} }

View File

@@ -89,7 +89,7 @@ func acquireImportedWithAccess(request importAcquisitionRequest, policy *acquisi
_ = closeAccess() _ = closeAccess()
return nil, sourceInfos(main.source), []Diagnostic{importDiagnostic(CodeImportOutsideRoot, "selected source and import base must stay inside the configuration root", nil)} return nil, sourceInfos(main.source), []Diagnostic{importDiagnostic(CodeImportOutsideRoot, "selected source and import base must stay inside the configuration root", nil)}
} }
for _, directory := range []string{access.rootPath, basePath} { for _, directory := range []string{resolved.rootPath, basePath} {
info, err := access.stat(directory) info, err := access.stat(directory)
if err != nil || !info.IsDir() { if err != nil || !info.IsDir() {
_ = closeAccess() _ = closeAccess()

View File

@@ -0,0 +1,61 @@
package engine
import (
"os"
"path/filepath"
"strconv"
"testing"
)
func TestImportsResolveParentsInsideLinkTargets(t *testing.T) {
root := canonicalTestPath(t, t.TempDir())
writeImportFile(t, root, "external/b/unit/marker", "")
writeImportFile(t, root, "external/a/shared/part.yml", "value: wrong\n")
want := writeImportFile(t, root, "external/b/shared/part.yml", "value: intended\n")
if err := os.Symlink("../b/unit", filepath.Join(root, "external/a/link")); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
alias := filepath.Join(root, "external/alias")
for _, absolute := range []bool{false, true} {
target := "a/link/../shared"
if absolute {
target = filepath.Join(root, "external/a/link") + "/../shared"
}
if err := os.Symlink(target, alias); err != nil {
t.Fatal(err)
}
for _, bounded := range []bool{false, true} {
var context *FilesystemContext
if bounded {
context = &FilesystemContext{Root: root}
}
for _, selector := range []string{"dir: " + strconv.Quote(alias) + ", pattern: '*.yml'", "glob: " + strconv.Quote(alias+"/*.yml"), "path: " + strconv.Quote(alias+"/part.yml")} {
main := writeImportFile(t, root, "app/main.yml", "config: {imports: [{"+selector+", required: true}]}\n")
result, err := testLoad[map[string]string](File(main), Options[map[string]string]{Imports: true, Filesystem: context})
if err != nil {
t.Fatalf("absolute=%v bounded=%v selector=%s: %v", absolute, bounded, selector, err)
}
sources := result.Inspection.Sources()
if result.Config["value"] != "intended" || len(sources) != 2 || sources[1].Path != want {
t.Fatalf("absolute=%v bounded=%v selector=%s: value=%v sources=%#v", absolute, bounded, selector, result.Config, sources)
}
}
}
if !absolute {
// A fully literal native glob must retain filesystem link semantics
// while its prefix cursor uses resolved coordinates internally.
writeImportFile(t, root, "app/main.yml", "config: {imports: [{glob: /external/alias/part.yml, required: true}]}\n")
namespace := newNativeNamespace("fixture", os.DirFS(root))
result, err := testLoad[map[string]string](filesystemFile(namespace, "app/main.yml"), Options[map[string]string]{Imports: true})
if err != nil {
t.Fatal(err)
}
if result.Config["value"] != "intended" || result.Inspection.Sources()[1].Path != "external/alias/part.yml" {
t.Fatalf("native result=%#v", result.Config)
}
}
if err := os.Remove(alias); err != nil {
t.Fatal(err)
}
}
}

View File

@@ -25,21 +25,19 @@ func selectNamedImportCandidates(access *filesystemAccess, basePath string, spec
normalized := make([]selectedImportCandidate, 0, len(spec.paths)) normalized := make([]selectedImportCandidate, 0, len(spec.paths))
seen := make(map[string]struct{}, len(spec.paths)) seen := make(map[string]struct{}, len(spec.paths))
for index, relative := range spec.paths { for index, relative := range spec.paths {
accessPath := access.join(basePath, relative) site := spec.fieldSites["path"]
candidatePath := accessPath if index < len(spec.selectorSites) {
if access.native == nil { site = spec.selectorSites[index]
candidatePath = filepath.ToSlash(filepath.Clean(accessPath))
} }
accessPath, err := resolveLiteralImportSelector(access, basePath, relative)
if err != nil {
return importSelection{}, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "import selector is outside the configuration root")}
}
candidatePath := normalizedImportCandidatePath(access, accessPath)
if _, exists := seen[candidatePath]; exists { if _, exists := seen[candidatePath]; exists {
continue continue
} }
seen[candidatePath] = struct{}{} seen[candidatePath] = struct{}{}
var site importFieldSite
if index < len(spec.selectorSites) {
site = spec.selectorSites[index]
} else {
site = spec.fieldSites["path"]
}
normalized = append(normalized, selectedImportCandidate{path: candidatePath, accessPath: accessPath, label: relativeImportLabel(access, basePath, accessPath), site: site}) normalized = append(normalized, selectedImportCandidate{path: candidatePath, accessPath: accessPath, label: relativeImportLabel(access, basePath, accessPath), site: site})
} }
sort.Slice(normalized, func(left, right int) bool { sort.Slice(normalized, func(left, right int) bool {
@@ -67,16 +65,19 @@ func selectDirectoryImportCandidates(access *filesystemAccess, basePath string,
roots := make([]selectedImportCandidate, 0, len(spec.paths)) roots := make([]selectedImportCandidate, 0, len(spec.paths))
seenRoots := make(map[string]struct{}, len(spec.paths)) seenRoots := make(map[string]struct{}, len(spec.paths))
for index, relative := range spec.paths { for index, relative := range spec.paths {
accessPath := access.join(basePath, relative) site := spec.fieldSites["dir"]
if index < len(spec.selectorSites) {
site = spec.selectorSites[index]
}
accessPath, err := resolveLiteralImportSelector(access, basePath, relative)
if err != nil {
return importSelection{}, []Diagnostic{*importSelectionDiagnostic(site, CodeImportOutsideRoot, "import selector is outside the configuration root")}
}
candidatePath := normalizedImportCandidatePath(access, accessPath) candidatePath := normalizedImportCandidatePath(access, accessPath)
if _, exists := seenRoots[candidatePath]; exists { if _, exists := seenRoots[candidatePath]; exists {
continue continue
} }
seenRoots[candidatePath] = struct{}{} seenRoots[candidatePath] = struct{}{}
site := spec.fieldSites["dir"]
if index < len(spec.selectorSites) {
site = spec.selectorSites[index]
}
roots = append(roots, selectedImportCandidate{path: candidatePath, accessPath: accessPath, site: site}) roots = append(roots, selectedImportCandidate{path: candidatePath, accessPath: accessPath, site: site})
} }
sort.Slice(roots, func(left, right int) bool { return roots[left].path < roots[right].path }) sort.Slice(roots, func(left, right int) bool { return roots[left].path < roots[right].path })
@@ -403,3 +404,36 @@ func importSelectionDiagnostic(site importFieldSite, code Code, message string)
Message: message, Primary: &location, Message: message, Primary: &location,
} }
} }
// splitImportSelectorRoot separates a path root without cleaning wildcard segments.
func splitImportSelectorRoot(selector string) (string, string) {
if filepath.IsAbs(selector) {
root := selector[:len(filepath.VolumeName(selector))+1]
return root, selector[len(root):]
}
if strings.HasPrefix(selector, "/") {
return "/", strings.TrimPrefix(selector, "/")
}
return "", selector
}
// resolveLiteralImportSelector interprets YAML paths in the selected namespace.
// Link resolution and source admission remain with the existing target owners.
func resolveLiteralImportSelector(access *filesystemAccess, base, selector string) (string, error) {
var name string
if access.native != nil {
if strings.HasPrefix(selector, "/") {
name = path.Clean(strings.TrimPrefix(selector, "/"))
} else {
name = path.Join(base, selector)
}
} else if filepath.IsAbs(selector) {
name = filepath.Clean(selector)
} else {
name = access.join(base, selector)
}
if !access.contains(name) {
return "", errImportPathOutsideRoot
}
return name, nil
}

View File

@@ -0,0 +1,77 @@
package engine
import (
"errors"
"path/filepath"
"testing"
"testing/fstest"
)
func TestLiteralImportSelectorCoordinates(t *testing.T) {
t.Parallel()
anchor := canonicalTestPath(t, t.TempDir())
external := canonicalTestPath(t, t.TempDir())
host, err := openHostAccess("")
if err != nil {
t.Fatal(err)
}
defer host.close()
bounded, err := openHostAccess(anchor)
if err != nil {
t.Fatal(err)
}
defer bounded.close()
native := newNativeAccess(fstest.MapFS{}, ".", &namespaceToken{})
nativeBounded := newNativeAccess(fstest.MapFS{}, "allowed", &namespaceToken{})
for _, entry := range []struct {
name string
access *filesystemAccess
base, selector, want string
outside bool
}{
{name: "host absolute", access: host, base: anchor, selector: filepath.Join(external, "part.yml"), want: filepath.Join(external, "part.yml")},
{name: "host parent", access: host, base: filepath.Join(anchor, "nested"), selector: "../part.yml", want: filepath.Join(anchor, "part.yml")},
{name: "host bounded", access: bounded, base: anchor, selector: filepath.Join(external, "part.yml"), outside: true},
{name: "host literal", access: host, base: anchor, selector: "literal*.yml", want: filepath.Join(anchor, "literal*.yml")},
{name: "native root", access: native, base: "app", selector: "/shared/part.yml", want: "shared/part.yml"},
{name: "native parent", access: native, base: "app", selector: "../shared/part.yml", want: "shared/part.yml"},
{name: "native escape", access: native, base: "app", selector: "../../part.yml", outside: true},
{name: "native bounded root", access: nativeBounded, base: "allowed/app", selector: "/allowed/part.yml", want: "allowed/part.yml"},
{name: "native bounded escape", access: nativeBounded, base: "allowed/app", selector: "/shared/part.yml", outside: true},
} {
t.Run(entry.name, func(t *testing.T) {
got, err := resolveLiteralImportSelector(entry.access, entry.base, entry.selector)
if entry.outside {
if !errors.Is(err, errImportPathOutsideRoot) {
t.Fatalf("outside error = %v", err)
}
return
}
if err != nil || got != entry.want {
t.Fatalf("resolved = %q, %v; want %q", got, err, entry.want)
}
})
}
}
func TestImportSelectorRootGrammar(t *testing.T) {
t.Parallel()
for _, pattern := range []string{"/shared/*.yml", "../shared/*.yml", "/shared/literal\\*.yml"} {
if _, ok := validGlobPattern(pattern); !ok {
t.Errorf("rejected %q", pattern)
}
}
for _, pattern := range []string{"", "https://example.test/*.yml", "/shared/**/*.yml", "/shared//*.yml", "/shared/[broken"} {
if _, ok := validGlobPattern(pattern); ok {
t.Errorf("accepted %q", pattern)
}
}
root, rest := splitImportSelectorRoot("/shared/*/../part.yml")
if root != "/" || rest != "shared/*/../part.yml" {
t.Fatalf("root=%q, rest=%q", root, rest)
}
literal, patterned := globLiteralSegment("literal\\*.yml")
if patterned || literal != "literal*.yml" {
t.Fatalf("escaped literal=%q, patterned=%v", literal, patterned)
}
}

View File

@@ -28,6 +28,7 @@ type importDeclarationSpec struct {
selectorSites []importFieldSite selectorSites []importFieldSite
glob string glob string
globSegments []string globSegments []string
globRoot string
required *bool required *bool
recursive *bool recursive *bool
follow *bool follow *bool
@@ -327,6 +328,7 @@ func parseImportSelectorValue(spec *importDeclarationSpec, field string, node *d
return &diagnostic return &diagnostic
} }
spec.glob, spec.globSegments = node.Text, segments spec.glob, spec.globSegments = node.Text, segments
spec.globRoot, _ = splitImportSelectorRoot(node.Text)
} }
return nil return nil
} }

View File

@@ -252,7 +252,7 @@ func TestLoadImportDirectiveValidationAndTemporaryGlobGate(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
directory := t.TempDir() directory := t.TempDir()
mainPath := writeImportFile(t, directory, "main.yml", test.body) mainPath := writeImportFile(t, directory, "main.yml", test.body)
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true}, test.code) requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true, Filesystem: &FilesystemContext{Root: directory}}, test.code)
}) })
} }
} }
@@ -856,7 +856,7 @@ settings: {root: retained}
t.Fatal(err) t.Fatal(err)
} }
}, code: CodeSourceNotRegular}, }, code: CodeSourceNotRegular},
{name: "absolute", path: "/tmp/configkit.yml", code: CodeImportInvalid}, {name: "absolute outside root", code: CodeImportOutsideRoot},
{name: "network URL", path: "https://example.invalid/config.yml", code: CodeImportInvalid}, {name: "network URL", path: "https://example.invalid/config.yml", code: CodeImportInvalid},
} }
for _, test := range tests { for _, test := range tests {
@@ -869,8 +869,12 @@ settings: {root: retained}
if test.code == CodeImportMissing { if test.code == CodeImportMissing {
required = "\n required: true" required = "\n required: true"
} }
mainPath := writeImportFile(t, directory, "main.yml", "config:\n imports:\n - path: \""+test.path+"\""+required+"\n") selectedPath := test.path
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true}, test.code) if test.name == "absolute outside root" {
selectedPath = filepath.ToSlash(filepath.Join(t.TempDir(), "external.yml"))
}
mainPath := writeImportFile(t, directory, "main.yml", "config:\n imports:\n - path: \""+selectedPath+"\""+required+"\n")
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true, Filesystem: &FilesystemContext{Root: directory}}, test.code)
}) })
} }
} }
@@ -1245,7 +1249,7 @@ func TestLoadImportsCanonicalSymlinksAndKeepsHardLinksDistinct(t *testing.T) {
t.Skipf("symlinks unavailable: %v", err) t.Skipf("symlinks unavailable: %v", err)
} }
mainPath := writeImportFile(t, root, "main.yml", "config: {imports: [{path: escape.yml}]}\n") mainPath := writeImportFile(t, root, "main.yml", "config: {imports: [{path: escape.yml}]}\n")
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true}, CodeImportOutsideRoot) requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true, Filesystem: &FilesystemContext{Root: root}}, CodeImportOutsideRoot)
}) })
t.Run("hard links are path identities", func(t *testing.T) { t.Run("hard links are path identities", func(t *testing.T) {
@@ -1332,7 +1336,7 @@ func TestImportedParseAndDecodeDiagnosticsKeepTheirSource(t *testing.T) {
func TestOptionalImportDoesNotSuppressUnsafeOrUnreadableTargets(t *testing.T) { func TestOptionalImportDoesNotSuppressUnsafeOrUnreadableTargets(t *testing.T) {
directory := t.TempDir() directory := t.TempDir()
mainPath := writeImportFile(t, directory, "outside.yml", "config: {imports: [{path: ../missing.yml}]}\n") mainPath := writeImportFile(t, directory, "outside.yml", "config: {imports: [{path: ../missing.yml}]}\n")
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true}, CodeImportOutsideRoot) requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true, Filesystem: &FilesystemContext{Root: directory}}, CodeImportOutsideRoot)
locked := writeImportFile(t, directory, "locked.yml", "settings: {root: locked}\n") locked := writeImportFile(t, directory, "locked.yml", "settings: {root: locked}\n")
if err := os.Chmod(locked, 0); err != nil { if err := os.Chmod(locked, 0); err != nil {

View File

@@ -85,6 +85,13 @@ func TestLoadedConfigurationIsSeparateFromInspection(t *testing.T) {
if loaded.Inspection == nil { if loaded.Inspection == nil {
t.Fatal("inspection is nil") t.Fatal("inspection is nil")
} }
view, ok := NewInspectionView(loaded.Inspection, Path{})
if !ok || view.Stage() != InspectionStageValidated {
t.Fatalf("successful inspection checkpoint = %q, available = %v", view.Stage(), ok)
}
if (InspectionView{}).Stage() != "" || (*LoadError)(nil).Inspection() != nil {
t.Fatal("unavailable inspection unexpectedly has a checkpoint")
}
loaded.Config.Value = "mutated" loaded.Config.Value = "mutated"
var effective bytes.Buffer var effective bytes.Buffer

View File

@@ -26,6 +26,13 @@ func NewInspectionView(inspection *Inspection, scope Path) (InspectionView, bool
func (v InspectionView) Inspection() *Inspection { return v.inspection } func (v InspectionView) Inspection() *Inspection { return v.inspection }
func (v InspectionView) Stage() InspectionStage {
if v.inspection == nil {
return ""
}
return v.inspection.stage
}
func (v InspectionView) Diff(other InspectionView) ([]Difference, error) { func (v InspectionView) Diff(other InspectionView) ([]Difference, error) {
if v.inspection == nil || other.inspection == nil || v.scope.String() != other.scope.String() { if v.inspection == nil || other.inspection == nil || v.scope.String() != other.scope.String() {
return nil, errors.New("configkit: diff inspection scope unavailable or mismatched") return nil, errors.New("configkit: diff inspection scope unavailable or mismatched")

View File

@@ -37,9 +37,9 @@ type Options[T any] struct {
PlacementMode PlacementMode PlacementMode PlacementMode
} }
// FilesystemContext supplies filesystem roots for imports and overlays. For an // FilesystemContext transports the public filesystem selection. Host Root is
// absent host input, Root is required and BaseDir may be omitted to use Root as // optional import containment; BaseDir alone supplies a synthetic/absent base
// the import base. Native contexts still require both BaseDir and Root. // and resource anchor. Synthetic native contexts still require both directories.
type FilesystemContext struct { type FilesystemContext struct {
BaseDir string BaseDir string
Root string Root string
@@ -84,8 +84,22 @@ type Loaded[T any] struct {
Inspection *Inspection Inspection *Inspection
} }
// InspectionStage identifies the completed processing represented by a snapshot.
type InspectionStage string
const (
InspectionStageMain InspectionStage = "main"
InspectionStageComposed InspectionStage = "composed"
InspectionStageInherited InspectionStage = "inherited"
InspectionStageDecoded InspectionStage = "decoded"
InspectionStageOverridden InspectionStage = "overridden"
InspectionStageResolved InspectionStage = "resolved"
InspectionStageValidated InspectionStage = "validated"
)
// Inspection owns frozen load snapshots and detached query state. // Inspection owns frozen load snapshots and detached query state.
type Inspection struct { type Inspection struct {
stage InspectionStage
metadata Metadata metadata Metadata
history *historyModel history *historyModel
sources []SourceInfo sources []SourceInfo
@@ -246,11 +260,12 @@ func executeLoadRequest[T any](request loadRequest[T], secrets SecretBinding, lo
} }
input.document = input.composition.root input.document = input.composition.root
} }
mainCandidate := input
if request.sourceVersionMode == sourceVersionModeDefault && request.ordinary { if request.sourceVersionMode == sourceVersionModeDefault && request.ordinary {
versionDiagnostics := checkVersion(request.definition.Version, input.document) versionDiagnostics := checkVersion(request.definition.Version, input.document)
accumulator.add(versionDiagnostics...) accumulator.add(versionDiagnostics...)
if hasErrors(versionDiagnostics) { if hasErrors(versionDiagnostics) {
return nil, accumulator.loadError() return nil, sourceFailure(schema, request.definition.Secret, input, []sourceCheckpoint{{mainCandidate, InspectionStageMain}}, policy.sequencePolicy, historyLimit, &accumulator)
} }
} }
if request.ordinary { if request.ordinary {
@@ -263,14 +278,15 @@ func executeLoadRequest[T any](request loadRequest[T], secrets SecretBinding, lo
accumulator.sources = input.sources accumulator.sources = input.sources
accumulator.add(diagnostics...) accumulator.add(diagnostics...)
if hasErrors(diagnostics) { if hasErrors(diagnostics) {
return nil, accumulator.loadError() return nil, sourceFailure(schema, request.definition.Secret, input, []sourceCheckpoint{{mainCandidate, InspectionStageMain}}, policy.sequencePolicy, historyLimit, &accumulator)
} }
composedCandidate := input
request.effectiveVersion = versionState.effectiveRule request.effectiveVersion = versionState.effectiveRule
if request.ordinary && input.parsed.source != nil { if request.ordinary && input.parsed.source != nil {
input, diagnostics = completeOrdinaryResourceContexts(input, request.main) input, diagnostics = completeOrdinaryResourceContexts(input, request.main)
if len(diagnostics) != 0 { if len(diagnostics) != 0 {
accumulator.add(diagnostics...) accumulator.add(diagnostics...)
return nil, accumulator.loadError() return nil, sourceFailure(schema, request.definition.Secret, input, []sourceCheckpoint{{composedCandidate, InspectionStageComposed}, {mainCandidate, InspectionStageMain}}, policy.sequencePolicy, historyLimit, &accumulator)
} }
} }
var expanded bool var expanded bool
@@ -278,7 +294,7 @@ func executeLoadRequest[T any](request loadRequest[T], secrets SecretBinding, lo
input, effectiveVersion, expanded, diagnostics = expandStructuralInheritance(input, request.protectionVersion(), policy.sequencePolicy) input, effectiveVersion, expanded, diagnostics = expandStructuralInheritance(input, request.protectionVersion(), policy.sequencePolicy)
if len(diagnostics) != 0 { if len(diagnostics) != 0 {
accumulator.add(diagnostics...) accumulator.add(diagnostics...)
return nil, accumulator.loadError() return nil, sourceFailure(schema, request.definition.Secret, input, []sourceCheckpoint{{composedCandidate, InspectionStageComposed}, {mainCandidate, InspectionStageMain}}, policy.sequencePolicy, historyLimit, &accumulator)
} }
if expanded { if expanded {
request.effectiveVersion = effectiveVersion request.effectiveVersion = effectiveVersion
@@ -293,7 +309,7 @@ func executeLoadRequest[T any](request loadRequest[T], secrets SecretBinding, lo
preparedOverrides, diagnostics := preparePostStructuralOverrides(base, input.sources, request.overrides, request.protectionVersion(), defaultImportLimits()) preparedOverrides, diagnostics := preparePostStructuralOverrides(base, input.sources, request.overrides, request.protectionVersion(), defaultImportLimits())
accumulator.add(diagnostics...) accumulator.add(diagnostics...)
if hasErrors(diagnostics) { if hasErrors(diagnostics) {
return nil, accumulator.loadError() return nil, sourceFailure(schema, request.definition.Secret, input, []sourceCheckpoint{{input, InspectionStageInherited}, {composedCandidate, InspectionStageComposed}, {mainCandidate, InspectionStageMain}}, policy.sequencePolicy, historyLimit, &accumulator)
} }
input.sources = preparedOverrides.sources input.sources = preparedOverrides.sources
accumulator.sources = input.sources accumulator.sources = input.sources
@@ -303,7 +319,7 @@ func executeLoadRequest[T any](request loadRequest[T], secrets SecretBinding, lo
decoded, diagnostics := decodeLoadInput(schema, decodeDefinition, input) decoded, diagnostics := decodeLoadInput(schema, decodeDefinition, input)
accumulator.add(diagnostics...) accumulator.add(diagnostics...)
if len(diagnostics) != 0 { if len(diagnostics) != 0 {
return nil, accumulator.loadError() return nil, sourceFailure(schema, request.definition.Secret, input, []sourceCheckpoint{{input, InspectionStageInherited}, {composedCandidate, InspectionStageComposed}, {mainCandidate, InspectionStageMain}}, policy.sequencePolicy, historyLimit, &accumulator)
} }
decodeContext := decodeContext{} decodeContext := decodeContext{}
if decodeDefinition.Version != nil { if decodeDefinition.Version != nil {
@@ -314,41 +330,65 @@ func executeLoadRequest[T any](request loadRequest[T], secrets SecretBinding, lo
for _, issue := range issues { for _, issue := range issues {
accumulator.add(diagnosticFromDecodeIssue(issue)) accumulator.add(diagnosticFromDecodeIssue(issue))
} }
return nil, accumulator.loadError() metadata := metadataFromDecodedInput(input, decoded)
inspection, _ := preparePrefixInspection(metadata, decoded.final, historyPhasePreCLI, newRetainedNodeCounter(historyLimit))
if inspection == nil {
return nil, sourceFailure(schema, request.definition.Secret, input, []sourceCheckpoint{{input, InspectionStageInherited}, {composedCandidate, InspectionStageComposed}, {mainCandidate, InspectionStageMain}}, policy.sequencePolicy, historyLimit, &accumulator)
}
return nil, finishFailureInspection(schema, request.definition.Secret, input, inspection, nil, &accumulator, InspectionStageDecoded)
} }
postDecode := preparePostDecodeOverrideContext(input, decoded, assigned) postDecode := preparePostDecodeOverrideContext(input, decoded, assigned)
resolved, diagnostics := resolveLoadInput(schema, request.definition, input, postDecode, request.sequencePolicy) resolved, diagnostics := resolveLoadInput(schema, request.definition, input, postDecode, request.sequencePolicy)
accumulator.add(diagnostics...) accumulator.add(diagnostics...)
if hasErrors(diagnostics) { if hasErrors(diagnostics) {
return nil, accumulator.loadError() inspection, _ := preparePrefixInspection(postDecode.metadata, postDecode.decoded.final, historyPhasePostCLI, newRetainedNodeCounter(historyLimit))
if inspection == nil {
metadata := metadataFromDecodedInput(input, decoded)
inspection, _ = preparePrefixInspection(metadata, decoded.final, historyPhasePreCLI, newRetainedNodeCounter(historyLimit))
if inspection != nil {
return nil, finishFailureInspection(schema, request.definition.Secret, input, inspection, nil, &accumulator, InspectionStageDecoded)
}
return nil, sourceFailure(schema, request.definition.Secret, input, []sourceCheckpoint{{input, InspectionStageInherited}, {composedCandidate, InspectionStageComposed}, {mainCandidate, InspectionStageMain}}, policy.sequencePolicy, historyLimit, &accumulator)
}
return nil, finishFailureInspection(schema, request.definition.Secret, input, inspection, nil, &accumulator, InspectionStageOverridden)
} }
counter := newRetainedNodeCounter(historyLimit) counter := newRetainedNodeCounter(historyLimit)
inspection, admitted := prepareInspectionHistory(resolved, counter) inspection, admitted := prepareInspectionHistory(resolved, counter)
if !admitted { if !admitted {
accumulator.add(Diagnostic{Code: CodeHistoryLimitExceeded, Severity: SeverityError, Message: "retained configuration history exceeds the node limit"}) accumulator.add(Diagnostic{Code: CodeHistoryLimitExceeded, Severity: SeverityError, Message: "retained configuration history exceeds the node limit"})
return nil, accumulator.loadError() prefix := preparePostDecodeOverrideContext(input, decoded, assigned)
earlier, _ := preparePrefixInspection(prefix.metadata, prefix.decoded.final, historyPhasePostCLI, newRetainedNodeCounter(historyLimit))
if earlier != nil {
return nil, finishFailureInspection(schema, request.definition.Secret, input, earlier, nil, &accumulator, InspectionStageOverridden)
}
metadata := metadataFromDecodedInput(input, decoded)
earlier, _ = preparePrefixInspection(metadata, decoded.final, historyPhasePreCLI, newRetainedNodeCounter(historyLimit))
if earlier != nil {
return nil, finishFailureInspection(schema, request.definition.Secret, input, earlier, nil, &accumulator, InspectionStageDecoded)
}
return nil, sourceFailure(schema, request.definition.Secret, input, []sourceCheckpoint{{input, InspectionStageInherited}, {composedCandidate, InspectionStageComposed}, {mainCandidate, InspectionStageMain}}, policy.sequencePolicy, historyLimit, &accumulator)
} }
// Detach resolver-borrowed values before reference mutation or validation. // Detach resolver-borrowed values before reference mutation or validation.
configuration, ownershipIssue := detachLoadConfiguration(schema, resolved.configuration, cloneUnresolvedSecrets) configuration, ownershipIssue := detachLoadConfiguration(schema, resolved.configuration, cloneUnresolvedSecrets)
if ownershipIssue != nil { if ownershipIssue != nil {
accumulator.add(*ownershipIssue) accumulator.add(*ownershipIssue)
return nil, accumulator.loadError() return nil, finishFailureInspection(schema, request.definition.Secret, input, inspection, nil, &accumulator, InspectionStageResolved)
} }
secretResolution := resolveSecretReferences(reflect.ValueOf(&configuration).Elem(), schema, resolved.referenceInput, lookup) secretResolution := resolveSecretReferences(reflect.ValueOf(&configuration).Elem(), schema, resolved.referenceInput, lookup)
accumulator.add(secretResolution.diagnostics...) accumulator.add(secretResolution.diagnostics...)
if hasErrors(secretResolution.diagnostics) { if hasErrors(secretResolution.diagnostics) {
return nil, accumulator.loadError() return nil, finishFailureInspection(schema, request.definition.Secret, input, inspection, secretResolution.references, &accumulator, InspectionStageResolved)
} }
identityDiagnostics := validateFinalSequenceIdentities(resolved.referenceInput, policy.sequencePolicy) identityDiagnostics := validateFinalSequenceIdentities(resolved.referenceInput, policy.sequencePolicy)
accumulator.add(identityDiagnostics...) accumulator.add(identityDiagnostics...)
if hasErrors(identityDiagnostics) { if hasErrors(identityDiagnostics) {
return nil, accumulator.loadError() return nil, finishFailureInspection(schema, request.definition.Secret, input, inspection, secretResolution.references, &accumulator, InspectionStageResolved)
} }
if request.definition.Validate != nil { if request.definition.Validate != nil {
diagnostics = runValidation(&configuration, request.definition.Validate, schema, resolved.final, resolved.referenceInput, secretResolution.lookups) diagnostics = runValidation(&configuration, request.definition.Validate, schema, resolved.final, resolved.referenceInput, secretResolution.lookups)
accumulator.add(diagnostics...) accumulator.add(diagnostics...)
if hasErrors(diagnostics) { if hasErrors(diagnostics) {
return nil, accumulator.loadError() return nil, finishFailureInspection(schema, request.definition.Secret, input, inspection, secretResolution.references, &accumulator, InspectionStageResolved)
} }
} }
resolved.configuration = configuration resolved.configuration = configuration

View File

@@ -6,6 +6,10 @@ import (
// assembledInput is the source/document handoff across schema and version checks. // assembledInput is the source/document handoff across schema and version checks.
type assembledInput struct { type assembledInput struct {
// Layered main evidence is retained before precedence mutates the assembly.
mainTier *composedDocument
mainTierAttempted bool
mainTierPolicy collectionPolicyScope
source Source source Source
parsed parsedSource parsed parsedSource
document *document.Node document *document.Node
@@ -96,7 +100,8 @@ func applyInputLayers(source Source, filesystem *FilesystemContext, overlay stri
if len(diagnostics) != 0 { if len(diagnostics) != 0 {
return input, diagnostics return input, diagnostics
} }
assembly := newAssemblyAccumulator(composition) // Preserve the completed main tier if selected-overlay assembly fails.
assembly := newAssemblyAccumulator(cloneComposedDocument(composition))
resolved, diagnostic := resolveOrdinaryOverlayFilesystem(source, filesystem, input.parsed, input.resolvedFilesystem) resolved, diagnostic := resolveOrdinaryOverlayFilesystem(source, filesystem, input.parsed, input.resolvedFilesystem)
if diagnostic != nil { if diagnostic != nil {
return input, []Diagnostic{*diagnostic} return input, []Diagnostic{*diagnostic}

View File

@@ -133,6 +133,9 @@ func assembleLayeredInput[T any](request loadRequest[T], input assembledInput, p
return input, diagnostics return input, diagnostics
} }
} }
if assembly != nil {
input.mainTierPolicy = assembly.current.collectionPolicies
}
} }
mainPresent := input.document != nil || input.composition != nil || len(input.acquisition) != 0 mainPresent := input.document != nil || input.composition != nil || len(input.acquisition) != 0
@@ -143,11 +146,13 @@ func assembleLayeredInput[T any](request loadRequest[T], input assembledInput, p
lower = assembly.current.collectionPolicies lower = assembly.current.collectionPolicies
} }
var diagnostics []Diagnostic var diagnostics []Diagnostic
input.mainTierAttempted = true
mainComposition, diagnostics = compositionForInputWithPolicies(input, lower, policy.sequencePolicy) mainComposition, diagnostics = compositionForInputWithPolicies(input, lower, policy.sequencePolicy)
if len(diagnostics) != 0 { if len(diagnostics) != 0 {
return input, diagnostics return input, diagnostics
} }
} }
input.mainTier = mainComposition
var versionDiagnostics []Diagnostic var versionDiagnostics []Diagnostic
if request.sourceVersionMode == sourceVersionModeDefault { if request.sourceVersionMode == sourceVersionModeDefault {
var mainRoot *document.Node var mainRoot *document.Node
@@ -190,6 +195,9 @@ func assembleLayeredInput[T any](request loadRequest[T], input assembledInput, p
assembly.current.inputBytes = state.accounting.bytes assembly.current.inputBytes = state.accounting.bytes
assembly.current.inputNodes = state.accounting.nodes assembly.current.inputNodes = state.accounting.nodes
if activeOverlay(request.overlay) { if activeOverlay(request.overlay) {
if assembly.current == input.mainTier {
assembly = newAssemblyAccumulator(cloneComposedDocument(assembly.current))
}
var resolved resolvedFilesystemContext var resolved resolvedFilesystemContext
var diagnostic *Diagnostic var diagnostic *Diagnostic
useBase := false useBase := false

View File

@@ -109,24 +109,132 @@ func prepareInspectionHistory[T any](resolved resolvedLoad[T], counter *retained
return inspection, true return inspection, true
} }
// prepareSourceInspection retains only the source and completed inheritance
// evidence represented by input; it does not construct typed defaults.
func prepareSourceInspection(input assembledInput, counter *retainedNodeCounter) (*Inspection, bool) {
if input.document == nil {
return nil, false
}
metadata := Metadata{fields: make(map[string]FieldInfo), historyBuilder: newHistoryBuilder()}
var origins map[string]Origin
if input.inheritance != nil {
origins = input.inheritance.origins
} else if input.composition != nil {
origins = input.composition.origins
}
walkDocument(input.document, Path{}, func(path Path, node *document.Node) {
origin, found := origins[path.String()]
if !found && node.Location.SourceID != "" {
origin = Origin{Layer: LayerMain, Locations: []Location{publicLocation(node.Location)}}
}
metadata.fields[path.String()] = FieldInfo{Explicit: true, Null: node.Kind == document.Null, Origin: cloneOrigin(origin)}
})
observeSourcePrefix(metadata.historyBuilder, input)
observation := historyPhaseSources
if input.inheritance != nil {
observation = historyPhaseInheritance
}
sealMetadataHistory(&metadata, input.document, observation)
inspection := &Inspection{metadata: metadata, history: metadata.historyModel, final: input.document}
if !addInspectionHistory(counter, inspection) {
return nil, false
}
return inspection, true
}
func preparePrefixInspection(metadata Metadata, final *document.Node, observation historyPhase, counter *retainedNodeCounter) (*Inspection, bool) {
sealMetadataHistory(&metadata, final, observation)
inspection := &Inspection{metadata: metadata, history: metadata.historyModel, final: final}
if !addInspectionHistory(counter, inspection) {
return nil, false
}
return inspection, true
}
func finishFailureInspection(schema *schemaDescriptor, predicate func(Path) bool, input assembledInput, inspection *Inspection, references map[string]string, accumulator *diagnosticAccumulator, checkpoint InspectionStage) *LoadError {
failure := accumulator.loadError()
if inspection == nil {
return failure
}
var evidence []*sourceVersionEvidence
if input.versionState != nil {
evidence = input.versionState.evidence
}
finishInspection(schema, predicate, evidence, input.contexts, inspection, references, accumulator, failure, checkpoint)
failure.inspection = inspection
return failure
}
type sourceCheckpoint struct {
input assembledInput
stage InspectionStage
}
// sourceFailure chooses the newest admissible source checkpoint without
// changing the diagnostics from the load that failed.
func sourceFailure(schema *schemaDescriptor, predicate func(Path) bool, current assembledInput, candidates []sourceCheckpoint, policy sequencePolicy, limit int, accumulator *diagnosticAccumulator) *LoadError {
for _, candidate := range candidates {
input := candidate.input
input.contexts = current.contexts
input.versionState = current.versionState
if candidate.stage == InspectionStageMain && current.mainTierAttempted {
if current.mainTier == nil {
continue
}
input.composition, input.document = current.mainTier, current.mainTier.root
}
if input.document == nil && len(input.acquisition) == 0 && (input.composition == nil || input.composition.root == nil) {
continue
}
if input.composition == nil || input.composition.root == nil {
composition, diagnostics := compositionForInputWithPolicies(input, current.mainTierPolicy, policy)
if len(diagnostics) != 0 || composition == nil || composition.root == nil {
continue
}
input.composition, input.document = composition, composition.root
}
if input.document == nil {
input.document = input.composition.root
}
inspection, admitted := prepareSourceInspection(input, newRetainedNodeCounter(limit))
if admitted {
return finishFailureInspection(schema, predicate, input, inspection, nil, accumulator, candidate.stage)
}
}
return accumulator.loadError()
}
func publishLoadResult[T any](schema *schemaDescriptor, definition Definition[T], resolved resolvedLoad[T], inspection *Inspection, references map[string]string, accumulator *diagnosticAccumulator) (*Loaded[T], error) { func publishLoadResult[T any](schema *schemaDescriptor, definition Definition[T], resolved resolvedLoad[T], inspection *Inspection, references map[string]string, accumulator *diagnosticAccumulator) (*Loaded[T], error) {
// A read-only validator can replace a value with an equal borrowed object. // A read-only validator can replace a value with an equal borrowed object.
// Detach without re-reading the environment or discarding validated state. // Detach without re-reading the environment or discarding validated state.
configuration, issue := detachLoadConfiguration(schema, resolved.configuration, cloneValidatedSecrets) configuration, issue := detachLoadConfiguration(schema, resolved.configuration, cloneValidatedSecrets)
if issue != nil { if issue != nil {
accumulator.add(*issue) accumulator.add(*issue)
return nil, accumulator.loadError() failure := accumulator.loadError()
finishInspection(schema, definition.Secret, resolved.versionEvidence, resolved.contexts, inspection, references, accumulator, failure, InspectionStageResolved)
failure.inspection = inspection
return nil, failure
} }
finishInspection(schema, definition.Secret, resolved.versionEvidence, resolved.contexts, inspection, references, accumulator, nil, InspectionStageValidated)
return &Loaded[T]{Config: configuration, Inspection: inspection}, nil
}
func finishInspection(schema *schemaDescriptor, predicate func(Path) bool, evidence []*sourceVersionEvidence, contexts map[string]ResourceContext, inspection *Inspection, references map[string]string, accumulator *diagnosticAccumulator, failure *LoadError, checkpoint InspectionStage) {
metadata := inspection.metadata metadata := inspection.metadata
secrets := classifySecretPathsWithEvidence(schema, definition.Secret, metadata, resolved.versionEvidence) secrets := classifySecretPathsWithEvidence(schema, predicate, metadata, evidence)
sources := sourceInfosWithVersionEvidence(accumulator.sources, resolved.versionEvidence, secrets, false) var sources []SourceInfo
if failure != nil {
sources = failure.sources
} else {
sources = sourceInfosWithVersionEvidence(accumulator.sources, evidence, secrets, false)
}
inspection.stage = checkpoint
inspection.metadata = metadata inspection.metadata = metadata
inspection.sources = sources inspection.sources = sources
inspection.contexts = cloneResourceContexts(resolved.contexts) inspection.contexts = cloneResourceContexts(contexts)
inspection.diagnostics = canonicalDiagnostics(accumulator.diagnostics) inspection.diagnostics = canonicalDiagnostics(accumulator.diagnostics)
inspection.secrets = secrets inspection.secrets = secrets
inspection.secretReferences = cloneSecretReferences(references) inspection.secretReferences = cloneSecretReferences(references)
return &Loaded[T]{Config: configuration, Inspection: inspection}, nil
} }
func diagnosticFromSchemaIssue(issue *schemaIssue) Diagnostic { func diagnosticFromSchemaIssue(issue *schemaIssue) Diagnostic {

View File

@@ -1,6 +1,8 @@
package engine package engine
import ( import (
"path/filepath"
"strconv"
"testing" "testing"
"testing/fstest" "testing/fstest"
) )
@@ -42,3 +44,53 @@ func TestMainRelativeSharesAcquisitionBudget(t *testing.T) {
t.Fatalf("diagnostics = %#v", diagnostics) t.Fatalf("diagnostics = %#v", diagnostics)
} }
} }
func TestMainRelativeUnboundedImportsAndAnchoredOverlay(t *testing.T) {
t.Parallel()
root := canonicalTestPath(t, t.TempDir())
external := writeImportFile(t, root, "shared/external.yml", "items: {external: shared}\n")
main := writeImportFile(t, root, "app/main.yml", "config:\n imports: [{path: "+strconv.Quote(external)+"}]\nitems: {main: selected}\n")
writeImportFile(t, root, "app/extra.yml", "items: {companion: local}\n")
writeImportFile(t, root, "app/overlays/test.yml", "items: {overlay: app}\n")
writeImportFile(t, root, "overlays/test.yml", "items: {overlay: outer}\n")
base := filepath.Dir(main)
companion := Input{Source: Bytes("companion", []byte("config: {imports: [{path: extra.yml}]}\n")), Imports: true, MainRelative: &MainRelativeContext{Fallback: &FilesystemContext{BaseDir: base}}}
options := LayeredOptions[importTestConfig]{Underlays: []Underlay{{Inputs: []Input{companion}}}, Overlay: "test", OverlayFallback: &FilesystemContext{BaseDir: base}}
for _, entry := range []struct {
name string
main Input
}{
{"discovered", Input{Source: SearchConfig("", Paths(main)), Imports: true}},
{"optional exhausted", Input{Source: SearchConfig("", Paths(filepath.Join(root, "missing.yml")))}},
{"root-only absent", Input{Source: NoSource(), Filesystem: &FilesystemContext{Root: base}}},
} {
t.Run(entry.name, func(t *testing.T) {
result, err := LoadLayered(entry.main, testSecretBinding(), options)
if err != nil {
t.Fatal(err)
}
if result.Config.Items["companion"] != "local" || result.Config.Items["overlay"] != "app" {
t.Fatalf("items=%#v", result.Config.Items)
}
if entry.name == "discovered" && result.Config.Items["external"] != "shared" {
t.Fatal("external main import missing")
}
for _, source := range result.Inspection.Sources() {
if source.Label == "companion" {
context, ok := result.Inspection.SourceContext(source.ID)
if !ok || context.BaseDir != "." {
t.Fatalf("derived resource context=%#v, %v", context, ok)
}
}
}
})
}
// Explicit input contexts override the inherited main context.
override := writeImportFile(t, root, "override/extra.yml", "items: {companion: explicit}\n")
companion.Filesystem = &FilesystemContext{BaseDir: filepath.Dir(override)}
options.Underlays = []Underlay{{Inputs: []Input{companion}}}
result, err := LoadLayered(Input{Source: File(main), Imports: true}, testSecretBinding(), options)
if err != nil || result.Config.Items["companion"] != "explicit" {
t.Fatalf("explicit companion=%#v, %v", result, err)
}
}

View File

@@ -144,15 +144,19 @@ func (m Metadata) hasHistoricalPath(path Path) bool {
} }
func freezeMetadataHistory(m *Metadata, final *document.Node) { func freezeMetadataHistory(m *Metadata, final *document.Node) {
finalizeEffectiveMetadataPaths(m, final)
builder := m.historyBuilder builder := m.historyBuilder
if builder == nil || !builder.prefixReady { if builder == nil || !builder.prefixReady {
panic("configkit: metadata history prefix is not ready") panic("configkit: metadata history prefix is not ready")
} }
sealMetadataHistory(m, final, historyPhaseResolution)
}
func sealMetadataHistory(m *Metadata, final *document.Node, observation historyPhase) {
finalizeEffectiveMetadataPaths(m, final)
builder := m.historyBuilder
builder.model.final = final builder.model.final = final
// A resolver may change dynamic field tags without changing canonical values // Include represented paths and sensitivity even without a later operation.
// or producing a resolution snapshot. Always observe the final classification. builder.observeDocument(final, observation)
builder.observeDocument(final, historyPhaseResolution)
m.historyModel = builder.freeze() m.historyModel = builder.freeze()
m.historyBuilder = nil m.historyBuilder = nil
} }

View File

@@ -18,24 +18,8 @@ func preparePostDecodeOverrideContext(input assembledInput, before decodedConfig
after.origins = cloneOrigins(assigned.origins) after.origins = cloneOrigins(assigned.origins)
after.final = document.Clone(assigned.final) after.final = document.Clone(assigned.final)
metadata := metadataFromDecoded(before) metadata := metadataFromDecodedInput(input, before)
cliRecords := overrideMetadataRecords(before, assigned.overrides) cliRecords := overrideMetadataRecords(before, assigned.overrides)
applications := structuralHistoryApplications(input)
var structuralOverlays []overlayRecord
if input.inheritance != nil && input.composition != nil {
structuralOverlays = input.composition.overlays
metadata.historyBuilder.setScratch(input.composition.root)
metadata.historyBuilder.observeSourceEvidence(input.composition.root, input.composition.origins, applications, structuralOverlays)
metadata.historyBuilder.setScratch(input.composition.root)
metadata.historyBuilder.observeInheritanceEvidence(input.inheritance.operations)
} else if input.composition != nil {
structuralOverlays = input.composition.overlays
metadata.historyBuilder.setScratch(input.composition.root)
metadata.historyBuilder.observeSourceEvidence(input.composition.root, input.composition.origins, applications, structuralOverlays)
} else if len(applications) != 0 {
metadata.historyBuilder.observeSourceEvidence(input.document, nil, applications, nil)
}
metadata.historyBuilder.observePreCLICheckpoint(before.final, before.origins)
var postDecodeApps []historyApplication var postDecodeApps []historyApplication
for _, override := range assigned.overrides { for _, override := range assigned.overrides {
postDecodeApps = append(postDecodeApps, historyApplication{ postDecodeApps = append(postDecodeApps, historyApplication{
@@ -82,6 +66,31 @@ func preparePostDecodeOverrideContext(input assembledInput, before decodedConfig
} }
} }
func metadataFromDecodedInput(input assembledInput, decoded decodedConfiguration) Metadata {
metadata := metadataFromDecoded(decoded)
observeSourcePrefix(metadata.historyBuilder, input)
metadata.historyBuilder.observePreCLICheckpoint(decoded.final, decoded.origins)
return metadata
}
func observeSourcePrefix(builder *historyBuilder, input assembledInput) {
applications := structuralHistoryApplications(input)
var structuralOverlays []overlayRecord
if input.inheritance != nil && input.composition != nil {
structuralOverlays = input.composition.overlays
builder.setScratch(input.composition.root)
builder.observeSourceEvidence(input.composition.root, input.composition.origins, applications, structuralOverlays)
builder.setScratch(input.composition.root)
builder.observeInheritanceEvidence(input.inheritance.operations)
} else if input.composition != nil {
structuralOverlays = input.composition.overlays
builder.setScratch(input.composition.root)
builder.observeSourceEvidence(input.composition.root, input.composition.origins, applications, structuralOverlays)
} else if len(applications) != 0 {
builder.observeSourceEvidence(input.document, nil, applications, nil)
}
}
func overrideMetadataRecords(before decodedConfiguration, overrides []preparedOverride) []overlayRecord { func overrideMetadataRecords(before decodedConfiguration, overrides []preparedOverride) []overlayRecord {
if len(overrides) == 0 { if len(overrides) == 0 {
return nil return nil

View File

@@ -7,6 +7,7 @@ import (
"path/filepath" "path/filepath"
"reflect" "reflect"
"runtime" "runtime"
"strconv"
"testing" "testing"
"testing/fstest" "testing/fstest"
) )
@@ -101,3 +102,43 @@ func TestCapturedMainUsesCanonicalTargetAfterSymlinkChanges(t *testing.T) {
t.Fatalf("load = %#v, %v", loaded, err) t.Fatalf("load = %#v, %v", loaded, err)
} }
} }
func TestCapturedImportBoundaryCompatibility(t *testing.T) {
t.Parallel()
root := canonicalTestPath(t, t.TempDir())
external := writeImportFile(t, t.TempDir(), "external.yml", "items: {external: retained}\n")
main := writeImportFile(t, root, "app/main.yml", "config: {imports: [{path: "+strconv.Quote(external)+"}]}\n")
for _, bounded := range []bool{false, true} {
var initial *FilesystemContext
anchor := filepath.Dir(main)
if bounded {
initial = &FilesystemContext{Root: root}
anchor = root
}
prepared, _, diagnostics := captureHostMain(File(main), initial)
if len(diagnostics) != 0 {
t.Fatal(diagnostics)
}
for _, later := range []*FilesystemContext{nil, {}, {Root: anchor}} {
loaded, err := testLoad[importTestConfig](prepared, Options[importTestConfig]{Imports: true, Filesystem: later})
wantBound := bounded || later != nil && later.Root != ""
if !wantBound {
if err != nil || loaded.Config.Items["external"] != "retained" {
t.Fatalf("unbounded capture=%#v, %v", loaded, err)
}
} else {
var failure *LoadError
if !errors.As(err, &failure) || failure.Diagnostics()[0].Code != CodeImportOutsideRoot {
t.Fatalf("bounded=%v, later=%#v: %v", bounded, later, err)
}
}
}
for _, later := range []*FilesystemContext{{Root: t.TempDir()}, {BaseDir: anchor}, {FS: filesystemPointer(NewFilesystem("native", fstest.MapFS{}))}} {
_, err := testLoad[importTestConfig](prepared, Options[importTestConfig]{Filesystem: later})
var failure *LoadError
if !errors.As(err, &failure) || failure.Diagnostics()[0].Code != CodeOptionsInvalid {
t.Fatalf("incompatible later=%#v: %v", later, err)
}
}
}
}

View File

@@ -4,11 +4,12 @@ import "go.maximumdirect.net/configkit/internal/document"
// capturedHostSource contains immutable, passive facts about one selected file. // capturedHostSource contains immutable, passive facts about one selected file.
type capturedHostSource struct { type capturedHostSource struct {
document *document.Node document *document.Node
bytes int64 bytes int64
mainPath string mainPath string
basePath string basePath string
rootPath string rootPath string
importRoot string
} }
// selectInputSource shares discovery and post-selection option checks with // selectInputSource shares discovery and post-selection option checks with
@@ -67,7 +68,7 @@ func captureHostMain(source Source, context *FilesystemContext) (Source, []Sourc
} }
selected.captured = &capturedHostSource{ selected.captured = &capturedHostSource{
document: parsed.document, bytes: parsed.bytes, mainPath: resolved.mainPath, document: parsed.document, bytes: parsed.bytes, mainPath: resolved.mainPath,
basePath: resolved.basePath, rootPath: resolved.rootPath, basePath: resolved.basePath, rootPath: resolved.rootPath, importRoot: resolved.importRoot,
} }
return selected, sourceInfos(parsed.source), nil return selected, sourceInfos(parsed.source), nil
} }

View File

@@ -4,8 +4,10 @@ import (
"errors" "errors"
"io/fs" "io/fs"
"os" "os"
"path"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strconv"
"strings" "strings"
"testing" "testing"
"testing/fstest" "testing/fstest"
@@ -370,3 +372,70 @@ func TestDirectorySelectorsTreatMissingOnOpenAsOptional(t *testing.T) {
}) })
} }
} }
func TestExternalImportResourceContexts(t *testing.T) {
t.Parallel()
root := canonicalTestPath(t, t.TempDir())
external := writeImportFile(t, root, "shared/fragment.yml", "config:\n imports: [{path: ../other/extra.yml}]\nitems: {external: resource.txt}\n")
writeImportFile(t, root, "shared/resource.txt", "external resource")
writeImportFile(t, root, "other/extra.yml", "items: {transitive: retained}\n")
main := writeImportFile(t, root, "app/main.yml", "config:\n imports:\n - path: "+strconv.Quote(external)+"\n - path: fragments/contained.yml\nitems: {main: resource.txt}\n")
writeImportFile(t, root, "app/fragments/contained.yml", "items: {contained: resource.txt}\n")
writeImportFile(t, root, "app/fragments/resource.txt", "contained resource")
writeImportFile(t, root, "app/resource.txt", "main resource")
check := func(inspection *Inspection) {
t.Helper()
for _, entry := range []struct{ key, base, content string }{
{"main", ".", "main resource"}, {"contained", "fragments", "contained resource"}, {"external", ".", "external resource"},
} {
info, ok := inspection.Metadata().Lookup(Keys("items", entry.key))
if !ok || len(info.Origin.Locations) == 0 {
t.Fatalf("origin missing: %#v", info)
}
context, ok := inspection.SourceContext(info.Origin.Locations[0].SourceID)
if !ok || context.BaseDir != entry.base {
t.Fatalf("%s context=%#v, %v", entry.key, context, ok)
}
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, "resource.txt"))
if err != nil || string(data) != entry.content {
t.Fatalf("%s resource=%q, %v", entry.key, data, err)
}
}
}
options := Options[importTestConfig]{Imports: true, Definition: Definition[importTestConfig]{Resolve: func(_ *importTestConfig, resolution *Resolution) error {
context, ok := resolution.SourceContext("source-2")
if !ok {
return errors.New("missing external context during resolution")
}
if _, err := fs.ReadFile(context.FS, "resource.txt"); err != nil {
return err
}
return nil
}}}
result, err := testLoad(File(main), options)
if err != nil {
t.Fatal(err)
}
if result.Config.Items["transitive"] != "retained" {
t.Fatal("resource root constrained transitive import")
}
check(result.Inspection)
options.Definition.Validate = func(_ *importTestConfig, validation *Validation) { validation.Error(Keys("items"), "rejected") }
_, err = testLoad(File(main), options)
var failure *LoadError
if !errors.As(err, &failure) || failure.Inspection() == nil {
t.Fatalf("failed inspection=%v", err)
}
check(failure.Inspection())
synthetic, err := testLoad[importTestConfig](Bytes("synthetic", []byte("items: {own: resource.txt}\n")), Options[importTestConfig]{Filesystem: &FilesystemContext{BaseDir: filepath.Dir(main)}})
if err != nil {
t.Fatal(err)
}
context, ok := synthetic.Inspection.SourceContext("source-1")
if !ok || context.BaseDir != "." {
t.Fatalf("synthetic context=%#v, %v", context, ok)
}
if data, err := fs.ReadFile(context.FS, "resource.txt"); err != nil || string(data) != "main resource" {
t.Fatalf("synthetic resource=%q, %v", data, err)
}
}

View File

@@ -51,6 +51,8 @@ func resolveOrdinaryOverlayFilesystem(source Source, context *FilesystemContext,
} }
func openSelectedOverlayAccess(resolved resolvedFilesystemContext) (*filesystemAccess, *Diagnostic) { func openSelectedOverlayAccess(resolved resolvedFilesystemContext) (*filesystemAccess, *Diagnostic) {
// Overlay lookup remains bounded by the legacy anchor, independently of imports.
resolved.importRoot = resolved.rootPath
access, err := openResolvedFilesystemAccess(resolved) access, err := openResolvedFilesystemAccess(resolved)
if err != nil { if err != nil {
value := globFilesystemDiagnostic(err, "configuration root could not be opened for the selected overlay", Location{}) value := globFilesystemDiagnostic(err, "configuration root could not be opened for the selected overlay", Location{})

View File

@@ -19,12 +19,6 @@ func contextsForResolvedSources(resolved *resolvedFilesystemContext, sources []S
if resolved.native != nil { if resolved.native != nil {
filesystem = resolved.native.filesystem filesystem = resolved.native.filesystem
} }
var rooted fs.FS
if filesystem != nil {
rooted = rootedNativeFS{filesystem: filesystem, root: rootPath}
} else {
rooted = rootedHostFS{root: rootPath}
}
result := make(map[string]ResourceContext, len(sources)) result := make(map[string]ResourceContext, len(sources))
for _, acquired := range sources { for _, acquired := range sources {
base := basePath base := basePath
@@ -35,6 +29,16 @@ func contextsForResolvedSources(resolved *resolvedFilesystemContext, sources []S
base = filepath.Dir(acquired.Path) base = filepath.Dir(acquired.Path)
} }
} }
resourceRoot := rootPath
if filesystem == nil && resolved.importRoot == "" && !containedPath(resourceRoot, base) {
resourceRoot = base
}
var rooted fs.FS
if filesystem != nil {
rooted = rootedNativeFS{filesystem: filesystem, root: resourceRoot}
} else {
rooted = rootedHostFS{root: resourceRoot}
}
var relative string var relative string
if filesystem != nil { if filesystem != nil {
if !containsNativePath(rootPath, base) { if !containsNativePath(rootPath, base) {
@@ -49,12 +53,12 @@ func contextsForResolvedSources(resolved *resolvedFilesystemContext, sources []S
} }
} }
} else { } else {
if !containedPath(rootPath, base) { if !containedPath(resourceRoot, base) {
value := importDiagnostic(CodeImportOutsideRoot, "source base is outside the configuration root", nil) value := importDiagnostic(CodeImportOutsideRoot, "source base is outside the configuration root", nil)
return nil, &value return nil, &value
} }
var err error var err error
relative, err = filepath.Rel(rootPath, base) relative, err = filepath.Rel(resourceRoot, base)
if err != nil { if err != nil {
value := importDiagnostic(CodeImportInvalid, "source base could not be addressed in the configuration root", nil) value := importDiagnostic(CodeImportInvalid, "source base could not be addressed in the configuration root", nil)
return nil, &value return nil, &value

View File

@@ -0,0 +1,106 @@
package engine
import (
"bytes"
"reflect"
"strings"
"testing"
)
func TestSourceInspectionRetainsRawOverlayHistoryAndSensitivity(t *testing.T) {
type settings struct {
Count int `yaml:"count"`
Private map[string]string `yaml:"private" configkit:"secret"`
Default string `yaml:"default"`
}
base := parseCompositionDocument(t, "source-1", "count: 1\nprivate: {token: old-canary}\n")
composed, diagnostics := composeDocuments(base)
if len(diagnostics) != 0 {
t.Fatal(diagnostics)
}
overlay := parseCompositionDocument(t, "source-2", "count: invalid\nprivate: {token: new-canary}\n")
composed, diagnostics = overlayDocuments(composed, overlay)
if len(diagnostics) != 0 {
t.Fatal(diagnostics)
}
input := assembledInput{document: composed.root, composition: composed}
schema, issue := buildSchema(reflect.TypeFor[settings](), testSecretBinding())
if issue != nil {
t.Fatal(issue)
}
definition := Definition[settings]{Defaults: func() settings { return settings{Default: "invented"} }}
if _, diagnostics := decodeLoadInput(schema, definition, input); len(diagnostics) == 0 {
t.Fatal("expected the raw count to fail typed decoding")
}
inspection, ok := prepareSourceInspection(input, newRetainedNodeCounter(historyNodeLimit))
if !ok {
t.Fatal("source inspection unavailable")
}
accumulator := &diagnosticAccumulator{}
failure := accumulator.loadError()
finishInspection(schema, nil, nil, nil, inspection, nil, accumulator, failure, InspectionStageInherited)
if _, found := inspection.Metadata().Lookup(Keys("default")); found {
t.Fatal("source inspection invented a default")
}
var output bytes.Buffer
if err := inspection.WriteEffective(&output); err != nil {
t.Fatal(err)
}
if !strings.Contains(output.String(), "count: invalid") || strings.Contains(output.String(), "canary") {
t.Fatalf("unsafe or incorrect effective output: %s", output.String())
}
explanation, found := inspection.Explain(Keys("private", "token"))
if !found || len(explanation.History) < 2 {
t.Fatalf("missing displaced history: %#v", explanation)
}
for _, event := range explanation.History {
if strings.Contains(event.Before.YAML+event.After.YAML, "canary") {
t.Fatalf("unredacted history: %#v", event)
}
}
info, found := inspection.Metadata().Lookup(Keys("count"))
if !found || !info.Explicit || len(info.Origin.Locations) == 0 || info.Origin.Locations[0].SourceID != "source-2" {
t.Fatalf("wrong source origin: %#v", info)
}
if _, ok := prepareSourceInspection(input, newRetainedNodeCounter(0)); ok {
t.Fatal("source inspection bypassed history budget")
}
}
func TestSourceInspectionRetainsCompletedInheritance(t *testing.T) {
type entry struct {
Count int `yaml:"count"`
}
type settings struct {
Parent entry `yaml:"parent"`
Child entry `yaml:"child"`
}
root := parseCompositionDocument(t, "source-1", "parent: {count: invalid}\nchild: {extends: parent}\n")
composed, diagnostics := composeDocuments(root)
if len(diagnostics) != 0 {
t.Fatal(diagnostics)
}
input, _, expanded, diagnostics := expandStructuralInheritance(assembledInput{document: composed.root, composition: composed}, nil, sequencePolicy{})
if !expanded || len(diagnostics) != 0 {
t.Fatalf("inheritance: expanded=%v diagnostics=%v", expanded, diagnostics)
}
schema, issue := buildSchema(reflect.TypeFor[settings](), testSecretBinding())
if issue != nil {
t.Fatal(issue)
}
if _, diagnostics := decodeLoadInput(schema, Definition[settings]{}, input); len(diagnostics) == 0 {
t.Fatal("expected inherited invalid value to fail decoding")
}
inspection, ok := prepareSourceInspection(input, newRetainedNodeCounter(historyNodeLimit))
if !ok {
t.Fatal("source inspection unavailable")
}
explanation, found := inspection.Explain(Keys("child", "count"))
if !found || !strings.Contains(explanation.Effective.YAML, "invalid") || len(explanation.History) == 0 {
t.Fatalf("inherited value or history unavailable: %#v", explanation)
}
info, found := inspection.Metadata().Lookup(Keys("child", "count"))
if !found || !info.Explicit || len(info.Origin.Inheritance) == 0 {
t.Fatalf("inherited origin unavailable: %#v", info)
}
}

View File

@@ -64,6 +64,10 @@ func TestValidationRejectsUnknownStructPaths(t *testing.T) {
}, },
}}) }})
assertLoadDiagnostic(t, result, err, CodeValidateInvalidPath) assertLoadDiagnostic(t, result, err, CodeValidateInvalidPath)
var failure *LoadError
if !errors.As(err, &failure) || failure.Inspection() == nil {
t.Fatalf("invalid validation path lost inspection: %v", err)
}
} }
func TestValidationMutationFailsWithoutPublishingResult(t *testing.T) { func TestValidationMutationFailsWithoutPublishingResult(t *testing.T) {

View File

@@ -90,7 +90,8 @@ type ImportDefaults struct {
// Options contains the application definition and per-load input selections. // Options contains the application definition and per-load input selections.
// Imports enables traversal of source-root declarations; an absent source has // Imports enables traversal of source-root declarations; an absent source has
// no main declarations to traverse. Controls are interpreted before placement, // no main declarations to traverse. Host imports are unbounded unless Root is
// explicit; native imports stay in the selected namespace. Controls precede placement,
// while nested and assembled application config values remain data. Overlay selects one fixed // while nested and assembled application config values remain data. Overlay selects one fixed
// overlay and requires filesystem context for NoSource. Overrides contain only // overlay and requires filesystem context for NoSource. Overrides contain only
// values explicitly supplied by an application CLI. // values explicitly supplied by an application CLI.
@@ -117,12 +118,18 @@ type Options[T any] struct {
SourceVersionMode SourceVersionMode SourceVersionMode SourceVersionMode
} }
// FilesystemContext supplies roots for imports and overlays. With FS nil, // FilesystemContext supplies filesystem lookup, import containment and resource
// BaseDir and Root use absolute host paths. For NoSource, Root is required and // anchors. With FS nil, synthetic sources require an absolute existing BaseDir;
// BaseDir may be omitted to use Root as the import base. With FS set, BaseDir // Root is optional and explicitly bounds host imports when supplied. Without
// and Root use slash-relative paths in that namespace ("." denotes its root). // Root, host imports may reach other host paths. A selected file derives its
// File sources derive BaseDir from the selected file; a native file's explicit // own BaseDir and rejects a supplied one. Its directory is the default resource,
// Root limits its scope. // overlay and secrets-bootstrap anchor, independently of import containment.
// NoSource may supply BaseDir alone, Root alone (also used as its base), or both;
// an empty supplied context does not establish a working-directory default.
// With FS set, BaseDir and Root remain slash-relative fs.ValidPath directories
// in that namespace ("." denotes its root). Synthetic native inputs require both;
// native files derive their base and default Root to ".". YAML leading-slash
// selectors start at the namespace root; Go context paths remain slash-relative.
type FilesystemContext struct { type FilesystemContext struct {
BaseDir string BaseDir string
Root string Root string

View File

@@ -19,6 +19,8 @@
"base_url": "https://forge.maximumdirect.net", "base_url": "https://forge.maximumdirect.net",
"owner": "base-layer", "owner": "base-layer",
"repository": "configkit", "repository": "configkit",
"token_file": ".releasekit/gitea-token" "credentials": {
"local": {"token_file": ".releasekit/gitea-token"}
}
} }
} }

View File

@@ -113,7 +113,8 @@ func LoadSecretsIntoEnvironmentWithOptions(directory string, options SecretsOpti
// SecretsFromConfigOptions configures preparation of a host main source. // SecretsFromConfigOptions configures preparation of a host main source.
type SecretsFromConfigOptions struct { type SecretsFromConfigOptions struct {
// Filesystem selects the main file's host containment root when supplied. // Filesystem selects the main host context. Its Root bounds bootstrap;
// omitted Root keeps bootstrap at the selected main directory.
Filesystem *FilesystemContext Filesystem *FilesystemContext
// Overwrite, when non-nil, overrides the main document's Boolean setting. // Overwrite, when non-nil, overrides the main document's Boolean setting.
// A nil value uses that setting, or false when it is absent. // A nil value uses that setting, or false when it is absent.
@@ -128,7 +129,9 @@ type SecretsFromConfigOptions struct {
// NoSource and an optional search with no match return NoSource and an empty // NoSource and an optional search with no match return NoSource and an empty
// report. The returned source owns a reusable main-document snapshot and its // report. The returned source owns a reusable main-document snapshot and its
// host context; imports and environment lookup remain part of each later load. // host context; imports and environment lookup remain part of each later load.
// A later explicit host context must match the captured root and base. // A later omitted Root preserves captured import policy. A supplied compatible
// Root at the captured anchor retains or narrows import containment; a different
// root, supplied BaseDir or native filesystem is incompatible.
// At most one options value is accepted. A non-nil report accompanies every // At most one options value is accepted. A non-nil report accompanies every
// result. Preparation failures return *LoadError; directory or environment // result. Preparation failures return *LoadError; directory or environment
// failures return *SecretsError. Any error returns a zero Source and does not // failures return *SecretsError. Any error returns a zero Source and does not