130 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
4a7ae664a6 Remove retired roadmap references from development guide 2026-11-21 12:36:10 +00:00
eaace5bd10 Retire completed result inspection roadmaps 2026-11-21 12:33:28 +00:00
174e030dad Write ConfigKit v1.4.0 release notes 2026-11-21 12:32:27 +00:00
1305f2b9e9 Avoid metadata copies during scoped path enumeration 2026-11-21 12:01:47 +00:00
d6fcfc62d9 Clarify result value lookup semantics 2026-11-21 12:01:02 +00:00
ed5d57d061 Preserve terminal values during result lookup 2026-11-21 12:00:29 +00:00
bcee3f866f Record scoped enumeration efficiency finding 2026-11-21 04:33:34 +00:00
a57afc7d69 Record result access review findings 2026-11-21 04:21:25 +00:00
7a9ce01064 Document value access and focused inspection 2026-11-21 04:16:46 +00:00
37f38f3e54 Demonstrate composing two component consumers 2026-11-21 04:13:27 +00:00
ace9f98072 Demonstrate component result handoff 2026-11-21 04:12:15 +00:00
51e15753eb Verify scoped inspection history and provenance 2026-11-21 04:10:56 +00:00
b5e1c11c4a Compare focused inspection views 2026-11-21 04:09:41 +00:00
db743a4b3d Render focused inspection values safely 2026-11-21 04:07:57 +00:00
68a6da2388 Add scoped inspection views 2026-11-21 04:06:45 +00:00
f514936c9c Expose current configuration values 2026-11-21 04:05:27 +00:00
654fe9d306 Add current configuration value navigation 2026-11-21 04:03:37 +00:00
b3799be2fa Remove superseded consumer request 2026-11-21 04:00:27 +00:00
229ad5bfe7 Plan typed result access and focused inspection 2026-11-21 03:54:39 +00:00
afe83a6fd2 Record inspection comparison across application types 2026-11-21 03:37:15 +00:00
86a9060418 Settle canonical reporting scope identity 2026-11-21 03:20:20 +00:00
d11e749428 Settle inspection APIs and review roadmap consistency 2026-11-21 03:17:32 +00:00
4c2620c68b Settle dynamic value traversal using existing type rules 2026-11-21 03:12:59 +00:00
41622c54e0 Settle value access for manually constructed results 2026-11-21 03:07:14 +00:00
48e7f943d9 Add focused inspection to the result access roadmap 2026-11-21 03:00:57 +00:00
472ac551c2 Plan typed value access from configuration results 2026-11-21 02:26:31 +00:00
652ddb649c Clarify repeated bootstrap for prepared sources 2026-11-18 15:17:17 +00:00
a33522ddca Draft ConfigKit v1.3.0 release notes 2026-11-18 15:07:41 +00:00
3f58d44e96 Remove completed secrets bootstrap plans 2026-11-18 15:06:06 +00:00
eeafc356e4 Document and validate configured secrets bootstrap 2026-11-18 01:10:24 +00:00
ab6e610fb7 Verify configured secrets startup handoff 2026-11-18 01:00:16 +00:00
60bcb6ddac Expose configured secrets bootstrap APIs 2026-11-18 00:54:42 +00:00
ea1f2a808d Prepare configured secrets before loading 2026-11-18 00:51:23 +00:00
649a63fff1 Verify captured imports and layered companions 2026-11-18 00:47:56 +00:00
e750b6d423 Preserve captured filesystem contexts during loading 2026-11-18 00:44:59 +00:00
a3c77f32f2 Capture selected host configuration sources 2026-11-18 00:41:44 +00:00
a9c72c1b67 Parse main-scoped secrets bootstrap controls 2026-11-18 00:37:16 +00:00
7b4fcf224a Support overwriting secrets from a directory 2026-11-18 00:29:56 +00:00
df6c3df67d Plan configured secrets bootstrap implementation 2026-11-18 00:26:00 +00:00
fb0560d888 Record explicit configured secrets bootstrap and refine its roadmap 2026-11-18 00:16:53 +00:00
e1336f74e5 Revise secrets roadmap around explicit configuration bootstrap 2026-11-17 22:28:16 +00:00
20a1087e25 Describe main-relative secrets directory support 2026-11-17 21:55:14 +00:00
51ef314415 Write ConfigKit v1.2.1 release notes 2026-11-17 15:54:24 +00:00
00efe90236 Upgrade ReleaseKit to v0.10.0 2026-11-17 15:48:53 +00:00
8aa91e8f0a Upgrade go-yaml to v4.0.0 2026-11-17 15:11:00 +00:00
c1c7e87f2c Write ConfigKit 1.2.0 release notes 2026-11-10 14:54:46 +00:00
99098d2974 Defer single-file overlays and retire the roadmap 2026-11-10 14:53:25 +00:00
3e50388b73 Make overlay version checks file-scoped 2026-11-10 14:34:12 +00:00
22603f0e5b Settle the direct overlay catalog format 2026-11-10 02:56:28 +00:00
5f001cf597 Retire completed companion loading roadmaps 2026-11-10 01:26:41 +00:00
47547bc63e Plan single-file overlays with strict peer composition 2026-11-09 21:34:17 +00:00
ce6005ca2d Share resolved companion contexts by tier 2026-11-09 21:22:46 +00:00
ef420c943b Reuse default import patterns 2026-11-09 21:20:48 +00:00
f0198f865d Validate access to derived host roots 2026-11-09 21:20:02 +00:00
367fe4120f Clarify companion binding ownership 2026-11-09 21:19:05 +00:00
37ea670747 Cover search exhaustion and fallback selection 2026-11-09 21:18:49 +00:00
68de431bb9 Share declaring import assembly 2026-11-09 21:18:16 +00:00
720df98a5a Mark native overlay remediation complete 2026-11-09 21:16:43 +00:00
81c27bb9cd Check native overlay link targets 2026-11-09 21:16:30 +00:00
9a08438769 Record main-relative scalability findings 2026-11-09 21:01:36 +00:00
a05bb94a21 Record main-relative integration audit 2026-11-09 20:59:12 +00:00
d2608e8d56 Record main-relative loading review findings 2026-11-09 20:56:01 +00:00
18af2d2130 Document main-relative companion loading 2026-11-09 20:47:44 +00:00
bc3fc91296 Verify main-relative loading and evidence 2026-11-09 20:44:32 +00:00
08ea01921b Demonstrate main-relative companion loading 2026-11-09 20:41:54 +00:00
761dd0a4e0 Derive selected overlay context from the main input 2026-11-09 20:40:40 +00:00
b93cbb0639 Handle companion imports without a filesystem base 2026-11-09 20:38:55 +00:00
e47960d377 Share import declaration preparation 2026-11-09 18:45:51 +00:00
f0a4bf9bb2 Bind companion inputs to the main context 2026-11-09 18:45:00 +00:00
0a136063da Define main-relative input options 2026-11-09 18:42:09 +00:00
ae0c94d3c6 Plan main-relative companion inputs 2026-11-09 18:39:25 +00:00
c51bea9b4f Adopt upstream documentation, OSS, and release policy updates 2026-11-09 18:31:14 +00:00
132b9ec659 Clarify binding scope and fallback behavior in the companion roadmap 2026-11-09 18:08:17 +00:00
c0bc5e2b73 Settle main-source eligibility for relative context binding 2026-11-09 18:00:31 +00:00
daa0cf9e88 Settle containment and symlink behavior for companion inputs 2026-11-09 17:55:27 +00:00
2ba61d5c7c Settle absent-main behavior for companion inputs 2026-11-09 17:49:08 +00:00
e36740313d Settle the main-relative context binding API 2026-11-09 17:46:31 +00:00
1960304f6f Revise the companion input roadmap around main-derived contexts 2026-11-09 17:33:30 +00:00
26ea24958c Plan main-relative underlays and overlays 2026-11-09 17:01:48 +00:00
137 changed files with 7947 additions and 670 deletions

View File

@@ -50,6 +50,10 @@ Start with one file. Optional features use the same loading and inspection model
references and choose which configuration fields to hide in inspection output.
- [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).
- [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
one result and let each consumer select its own settings and reporting scope.
The [consumer guide](docs/consumers/README.md) walks through these tasks and links
to maintained examples. The [configuration reference](docs/config.md) defines the
@@ -70,7 +74,7 @@ examples](docs/config.md#strict-document-composition) for the details and
exceptions.
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).
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.
// 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.
type LoadError struct{ value *engine.LoadError }

View File

@@ -2,7 +2,7 @@ package configkit
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;
// Present distinguishes absence from explicit null. Redacted reports hiding
// based on sensitivity from either load. Mappings compare by key; a changed
@@ -40,6 +40,10 @@ func Diff[T any](left, right *Result[T]) ([]Difference, error) {
if err != nil {
return nil, err
}
return fromEngineDifferences(values), nil
}
func fromEngineDifferences(values []engine.Difference) []Difference {
differences := make([]Difference, len(values))
for index, value := range values {
differences[index] = Difference{
@@ -49,5 +53,5 @@ func Diff[T any](left, right *Result[T]) ([]Difference, error) {
HiddenChanged: value.HiddenChanged,
}
}
return differences, nil
return differences
}

View File

@@ -1,6 +1,6 @@
# ADR 0004: Use secret references and explicit environment bootstrap
Status: accepted
Status: superseded by [ADR 0023](0023-explicit-configured-secrets-bootstrap.md).
Date: 2026-09-06

View File

@@ -2,7 +2,10 @@
## Status
Accepted and implemented. The
Accepted and implemented. Extended by
[ADR 0024](0024-compare-inspection-views-across-application-types.md) for inspection
view comparison across application Go types. The existing same-type comparison
API continues to follow this decision. The
[configuration contract](../config.md#effective-configuration-diffs) owns current
behavior. Completed planning and remediation records are preserved in Git
history at `1c2610c` under `docs/roadmap/`.

View File

@@ -0,0 +1,50 @@
# ADR 0022: Bind Companion Contexts After Main Selection
## Status
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
2026-11-09
## Context
Applications choose a main-file search and may also declare companion imports
and a selected overlay. The main directory is only known after discovery, so
supplying every dependent context before loading duplicates selection or requires
a preliminary load. ADR 0019 keeps main discovery explicit and inside loading.
## Decision
Extend layered loading to bind application-declared non-file underlays to the
resolved main context after acquisition. An explicit underlay context overrides
the binding, and an explicit fallback or require-base option controls absence.
Selected layered overlays choose an explicit context, the resolved main context,
or a fallback in that order. Derived and fallback lookup use the context base;
the inherited root continues to bound containment. Ordinary and explicit
overlay lookup retain their established root-relative behavior.
Applications remain responsible for choosing searches, import declarations,
and overlay names. Selection failures are terminal; no second search or
application context callback is introduced.
## Alternatives Considered
- Require applications to discover the main file separately. This repeats
discovery and may run a complete load more than once.
- Implicitly scan conventional companion directories. This would impose
application-specific conventions without an explicit declaration.
- Add only a relative file constructor. This would not cover mapping or bytes
sources with existing import, placement, and composition rules.
## Consequences
The load owns the resolved binding and keeps namespace, containment, source
identity, and handle lifetime in the existing acquisition lifecycle. A missing
base skips optional imports while preserving the declaring payload; required
imports and require-base retain explicit failures. The configuration contract
and public declarations describe the observable rules.

View File

@@ -0,0 +1,60 @@
# ADR 0023: Keep Configured Secrets Bootstrap Explicit
## Status
Accepted. Supersedes [ADR 0004](0004-secret-references-and-explicit-bootstrap.md).
## Date
2026-11-18
## Context
Applications may discover their main configuration file during startup and keep
secret files beside it. Requiring applications to discover and parse that file
separately duplicates ConfigKit's work. Some deployments also need secret files
to replace environment values that are already set.
## Decision
Keep secrets as typed references to environment-variable names. Resolve surviving
references and keep credential values out of configuration trees, history, and
inspection. Applications own credential use.
Directory bootstrap remains a separate startup operation that the application
must call explicitly. Ordinary configuration loading never writes the process
environment. The application may supply the directory directly or authorize
bootstrap from settings in the selected main document. Imports, underlays,
overlays, and later application processing do not choose those settings.
When bootstrap uses the main document, ConfigKit selects and captures that
document and its filesystem context for subsequent loading. This keeps bootstrap
and loading tied to the same main contents and location. It does not snapshot
later imports, resources, or the environment.
Preserve existing environment variables by default, including empty values.
Allow an explicit overwrite choice. An application-supplied choice takes
precedence over the main document's choice, including an explicit choice to
preserve existing values.
Keep bootstrap reports separate from later secret-lookup evidence. Report
writes, skips, and partial failures without credential values. Bootstrap offers
no rollback or transaction across environment variables and no protection
against concurrent environment mutation. General environment-variable
configuration overlays remain outside this model.
## Alternatives Considered
- Leave discovery and parsing to applications. This preserves duplicate startup
infrastructure and can select different main contents for bootstrap and loading.
- Run bootstrap inside ordinary loading. This hides process mutation in an
operation applications may repeat or run concurrently.
- Always preserve existing environment values. This keeps one precedence rule
but prevents deployments from explicitly choosing provisioned files instead.
## Consequences
Applications retain control of startup ordering and environment writes.
ConfigKit owns main-source capture, bounded secret-file loading, and safe
reporting. A later configuration failure leaves completed bootstrap writes in
place. Existing callers retain the preservation default.

View File

@@ -0,0 +1,51 @@
# ADR 0024: Compare Inspection Views Across Application Types
## Status
Accepted.
## Date
2026-11-20
## Context
An application can load configuration once and share the result with libraries.
Each library needs to inspect its own section while the application chooses the
Go type that holds the complete configuration.
[ADR 0010](0010-effective-configuration-diff.md) provides comparison between
results with the same Go configuration type. A shared inspection view lets a
library compare configurations without knowing that application type.
## Decision
Provide inspection views that compare saved configuration values from successful
loads regardless of the original application Go types. Views being compared
select the same location within their respective configurations.
ConfigKit owns comparison and redaction. Use the saved load snapshots and the
equality, sequence comparison, and sensitive-value handling established by
ADR 0010. Report changes that overlap the selected location, retaining original
application paths and any containing changes.
This decision extends ADR 0010. The existing same-type comparison API continues
to follow that decision.
## Alternatives Considered
- **Require matching application Go types.** This follows the existing API's
restriction but adds type checks or application-specific adapters to a shared
inspection view.
- **Let libraries implement comparison.** This gives libraries control but
duplicates ConfigKit's comparison and redaction rules.
## Consequences
Libraries can offer configuration comparison through one inspection interface
across applications. Applications retain ownership of their Go configuration
types and presentation.
A reported change to a containing value may include configuration outside the
selected section. The view provides a reporting focus, with the existing
redaction rules applied to all returned values.

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

@@ -75,6 +75,8 @@ or the supported directory presets, then pass it to `SearchConfig`. Search
descriptions are immutable and reusable; each load resolves dynamic directories
and checks current candidate files again. `Searches` is ordered concatenation.
It preserves the supplied description order and does not deduplicate candidates.
Layered companion inputs can use the selected main's context without a second
search, as described under [layered loading](#layered-loading).
`NamedFilenames` selects `<application>.yml`, then `<application>.yaml`.
`GenericFilenames` selects `config.yml`, `config.yaml`, `main.yml`, then
@@ -143,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
inside `Root`. A selected host file rejects an explicit `BaseDir` or native
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
source IDs, paths, placement, metadata origins, and resource context. Missing
@@ -210,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
`imports` declaration still requires imports to be enabled. `NoSource` may enable
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
omit `BaseDir` to use that root as its internal import base; a native context
requires its namespace, `BaseDir`, and `Root`. Supplied context is validated even
filesystem context: a host context supplies an absolute existing `BaseDir`,
`Root`, or both. BaseDir alone also supplies the resource/overlay anchor and
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
context. `NoSource` accepts overrides and remains absent rather than contributing
an empty document.
@@ -224,6 +229,13 @@ describe the configuration as it was when the load finished. Returned source,
diagnostic, and metadata records are copies; changing them cannot change later
queries. Separate loads return independently owned configuration and records.
`Result.Value` selects trusted current Go values by configuration path, including
resolved secrets and zero values without input. It uses ordinary Go assignment:
maps, slices, and pointers can share state with `Config`. Availability does not
establish input presence; use metadata for that distinction. Capture owned
runtime settings before later mutations invalidate the relationship to saved
inspection evidence. A manually constructed result also supports value lookup.
Every source, options, schema, version, defaults, decode, resolution, or
validation failure returns a nil result and a `*LoadError`. Successful results
contain caller-owned `Config`, detached `Metadata`, a defensive source list,
@@ -247,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
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
`Load` finishes its work before returning. Success means input assembly,
@@ -316,13 +359,34 @@ typed configuration before application resolution. Syntax, strict-composition,
inheritance, and decoding errors cannot be masked by a CLI override. Resolution,
secret lookup, validation, and publication run once on the resulting values.
An active layered overlay requires `LayeredOptions.OverlayFilesystem` explicitly,
independent of the main source's namespace. Its name and root-relative lookup
follow the selected-overlay rules below; inactive overlays ignore the context.
An active layered overlay selects `OverlayFilesystem` first, then the resolved
main context, then `OverlayFallback`. An invalid selected context fails without
trying another. An inactive overlay ignores both supplied contexts.
The same path in a different filesystem namespace is not a repeated file.
Ordinary `Load` infers overlay context from sources that provide one; with
`NoSource`, it requires the explicit `Options.Filesystem` context.
An underlay `Input.MainRelative` requests the resolved main context for a
non-file source. An explicit `Input.Filesystem` overrides it entirely. File,
native file, and search underlays cannot use an active binding, nor can the
main input bind to itself. `MainRelative()` creates a fresh default description.
The binding does not enable imports. If the main has no usable context, its
`Fallback` is selected if supplied; otherwise optional imports are skipped and
the input's own payload remains. Required named targets, directory and glob
selections fail without a base, while an empty `path: []` remains a no-op.
`RequireBase` requires a usable main or fallback context even without imports.
Invalid declarations still fail, and skipped imports create no search evidence.
Selected main failures never trigger fallback or a second discovery attempt.
Derived contexts preserve the main namespace, optional import boundary and
resource/overlay anchor, while lookup starts at its resolved base. A host file's
base is its canonical target directory, including when the selected filename is
a symlink. Explicit Root bounds parent-relative and absolute imports without
moving that base. Explicit non-file, absent-main and fallback host contexts may
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).
Source IDs follow acquisition order—main and its depth-first imports, then each
underlay tier's inputs and depth-first imports, then overlay and CLI—even though
history follows precedence order. Default main-version checking happens after
@@ -564,10 +628,15 @@ resolution query follows the callback's lifetime guard. Queries perform no
filesystem access. Obtain IDs from exact origin locations rather than guessing
one context for a composite origin or an application-derived value.
`ResourceContext.FS` is rooted at the source's configured root, and `BaseDir`
is its slash-relative directory inside that root. This includes imported
`ResourceContext.FS` uses the load context's resource anchor for contained sources,
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
files, and byte, reader, or mapping inputs with an explicit 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
resource, join `BaseDir` with the application resource name using slash-path
operations and open that path through `FS`.
@@ -714,11 +783,11 @@ historical classification. Redaction empties `Text` while retaining presence
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
decision and the [development guide](development.md#baseline-validation) for
the completed implementation and remediation records in Git history.
development validation guidance.
### 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 |
| --- | --- |
@@ -728,6 +797,7 @@ Use inspection to understand a completed load without reading the files again:
| Inspect earlier values as safe YAML | `Explain` or `WriteExplanation` |
| Show the saved final configuration as safe YAML | `WriteEffective` |
| Compare final values from two loads | `Diff` |
| Focus reporting on one location | `InspectSubtree` |
For example, suppose a typed default sets `workers` to `2`, the main input
supplies `workers: 3`, and an overlay supplies `workers: 4`. The final value is
@@ -736,6 +806,16 @@ earlier default and main contributions. `History` returns attribution records;
`Explain` adds their before/after values. Changing `result.Config.Workers` later
does not change any of these saved inspection results.
An `Inspection` view focuses reporting on a canonical JSON Pointer location.
Its `HistoricalPaths` includes observed paths at or below that location and
`WriteEffective` renders the selected frozen value with original sensitivity.
An absent scope can be selected, but has no effective output. Explicit metadata
and explanation queries keep native application paths and may address values
outside the focus; source catalogs and resource contexts remain available for
the whole load. This is a reporting focus, not a confidentiality boundary. Numeric
key and index spellings with the same pointer select the same focus, while
explicit queries preserve their normal path intent.
#### Presence, origins, and historical paths
`Result.Metadata()` describes every final configuration path. Queries retain explicit
@@ -851,9 +931,11 @@ translated to a fixed safe error. There is no unredacted rendering option and
ConfigKit performs no implicit logging.
`Result.Config` is the explicit trusted boundary and contains ordinary typed values,
including secrets. Metadata records, diagnostics, and load errors contain no
configuration values. Explanation snapshots deliberately expose non-secret
configuration history after applying the redaction contract below. Applications
including secrets. Metadata and diagnostics do not embed configuration snapshots.
`LoadError.Error()` does not render diagnostic messages or input values. Explicitly
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
because ConfigKit cannot infer and sanitize secrets embedded in arbitrary application
prose.
@@ -989,6 +1071,15 @@ uninitialized results return an error with no records. A failed `Load` retains
its normal nil-result/`LoadError` behavior, which callers handle before invoking
`Diff`.
`Inspection.Diff` compares focused views at the same canonical location, even
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
the focus. Because sequences and structural replacements can be atomic, an
ancestor record may reflect a change outside the selected value. Different
scopes or unavailable views return an error and no records. Whole-result
`Diff[T]` remains restricted to results of the same Go type.
## Typed secret references
There are three separate tasks when working with credentials:
@@ -997,7 +1088,7 @@ There are three separate tasks when working with credentials:
| --- | --- |
| Read a credential from an environment variable | A typed `Secret` field whose YAML value is the variable's name |
| Hide a configuration value in inspection output | A `configkit:"secret"` tag or `Definition.Sensitive` |
| Populate environment variables from local files before loading | An explicit `LoadSecretsIntoEnvironment` call |
| Populate environment variables from local files before loading | An explicit [secrets bootstrap](#explicit-secrets-directory-bootstrap) call |
For example, YAML `api_key: DEMO_API_KEY` names an environment variable. Its
credential is available to trusted application code through `Secret.Value()`
@@ -1029,8 +1120,8 @@ its effective source location for diagnostics. Each unique name is read with
`os.LookupEnv` once per load. Validation can inspect the credential through the
deliberately named `Value()` accessor and distinguish success with `IsResolved()`.
Later loads read the environment again, and cloned defaults are rebuilt from names
so a previously resolved result cannot retain a stale credential. `Load` never
writes to the environment.
so a previously resolved result cannot retain a stale credential. `Load` and
`LoadLayered` never write to the environment.
Credential bytes are held only in the per-load lookup state and the trusted returned
configuration, and are returned only by `Value`. Secret formatting uses a safe
@@ -1056,17 +1147,82 @@ reference state without printing its value.
## Explicit secrets-directory bootstrap
If an application stores credentials in files, it can call this helper before
loading configuration. A file named `DEMO_API_KEY` containing the dummy text
If an application stores credentials in files, it can explicitly bootstrap
them before loading configuration. A file named `DEMO_API_KEY` containing the dummy text
`example-value` supplies environment variable `DEMO_API_KEY`. YAML can then
refer to that variable with `api_key: DEMO_API_KEY`. Applications that already
receive environment variables do not need this file step.
Existing environment variables take priority over files. If `DEMO_API_KEY` is
already set to an empty string, its file is skipped and it stays empty. A later
By default existing environment variables take priority over files. If
`DEMO_API_KEY` is already set to an empty string, its file is skipped and it stays empty. A later
required `Secret` reference will still fail on that empty value. File bootstrap
accepting an empty file is different from a required reference resolving to an
empty credential.
empty credential. `LoadSecretsIntoEnvironmentWithOptions` accepts
`SecretsOptions{Overwrite: true}` to replace existing values explicitly.
For a directory selected by the main file, call
`LoadSecretsIntoEnvironmentFromConfig` with a host `File` or `SearchConfig`
source before `Load` or `LoadLayered`. The main document may declare:
```yaml
config:
secrets_dir: secrets
secrets_overwrite: false
```
`secrets_dir` is a nonempty relative host path, interpreted literally relative
to the selected main file's canonical directory. Its canonical target must be
inside the main filesystem root; a contained directory symlink is allowed.
Parent-relative paths can reach other directories inside an explicitly wider
root. Rooted, absolute, and host volume-qualified paths are invalid. `secrets_overwrite`
is a Boolean and defaults to false. A non-nil Go `Overwrite` option wins over
the YAML value, including an explicit false. Invalid declarations fail even
when Go supplies an override. Overwrite without a directory is a no-op.
Only the main document root owns these controls. Imports and underlays reject
them with source-local import diagnostics; selected overlays reject them as
overlay directives. Nested application `config` mappings and data assembled at
the application root by placement, defaults, CLI, or resolution remain ordinary
data. Normal `Load` and `LoadLayered` validate and consume main controls whether
imports are enabled or disabled, but never bootstrap or write the environment.
Each load resolves typed secret names from the environment at the usual point.
The companion accepts at most one `SecretsFromConfigOptions`, including an
optional host `FilesystemContext`. It selects and parses the main once, validates
the bootstrap controls, and completes directory bootstrap before returning a
prepared source. It does not run import acquisition, version checks, decoding,
resolution, or validation. It loads every eligible directory entry, including
names unused by the application's typed schema. A main with no directory still
returns a prepared source and empty report. `NoSource` or an exhausted optional
search returns `NoSource` and an empty report. Explicit absent-input context
continues to follow the normal absent-host-context rules. The helper also accepts
a previously prepared source, reusing its captured main and explicitly performing
bootstrap again.
The prepared source is a reusable snapshot of the selected main document,
including its unconsumed controls, byte count, canonical file identity, base,
resource/overlay/bootstrap anchor, and independent import boundary. A later load
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
load clones the document, creates its own source IDs
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
captured context. A later host context with Root omitted preserves the captured
import policy, including explicit containment captured during preparation. An
explicit Root canonically equal to the captured anchor retains containment or
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.
The helper returns a non-nil report on every attempt and a zero, unusable source
on error. Discovery, source, parse, control, and preparation-context failures
return `*LoadError` with available source records and source-local diagnostics.
Directory inspection, reads, and environment writes return `*SecretsError`.
An invalid directory declaration uses `secrets.invalid_path`; a non-Boolean
overwrite declaration uses `secrets.invalid_value`. Later loading failures do
not undo bootstrap effects or change its report. Multiple options fail before
acquisition or writes.
Read the report even when the helper returns an error:
@@ -1079,18 +1235,20 @@ Read the report even when the helper returns an error:
Render the returned `SecretsReport` separately from a later configuration load.
It contains filenames, paths, and statuses, not credential contents. The
[maintained startup example](../examples/consumers/consumers_test.go) shows how to
keep bootstrap and configuration reports together in the application.
[configured startup example](../examples/consumers/secrets.go) prepares a source
for either loading entry point; its [test](../examples/consumers/secrets_test.go)
shows both handoffs. The [direct-directory example](../examples/consumers/consumers_test.go)
shows how to keep bootstrap and configuration reports together.
### Preflight, limits, and partial writes
`LoadSecretsIntoEnvironment(directory)` is a separate, opt-in startup operation.
It is never called by `Load`, is not a YAML option, and does not participate in
configuration validation. Applications choose the native directory path and
should invoke the operation once before starting concurrent work. The selected
path may itself be a symlink; ConfigKit resolves it to an existing canonical
directory before examining
its immediate entries.
All bootstrap helpers are separate, opt-in startup operations. They are never
called by a configuration load and do not perform configuration validation.
Applications own startup ordering and should invoke bootstrap before concurrent
work or other process-environment mutation. The direct helpers accept a native
directory path; the configured helper resolves the declared path as described
above. The selected path may itself be a symlink; ConfigKit resolves it to an
existing canonical directory before examining its immediate entries.
The bootstrap enumerates at most 1,024 entries, including dot-prefixed entries.
Entries whose names begin with `.` (files, directories, or symlinks, such as `.git`
@@ -1098,16 +1256,18 @@ and `.gitignore`) are ignored before name or metadata validation, are never open
and are omitted from the report. Remaining entries are sorted by filename; each
must have an ASCII environment-variable name and be a regular, nonsymlink
file. Metadata for all remaining entries is validated before file content is read
or process state is changed. Existing environment variables win, including variables whose
value is empty; their files are not opened. Each eligible file is limited to 1 MiB,
and eligible content is limited to 8 MiB in total. ConfigKit removes exactly one
or process state is changed. In preservation mode existing environment variables
win, including variables whose value is empty; their files are not opened. In
overwrite mode their files are read and applied as well. Each eligible file is
limited to 1 MiB, and eligible content is limited to 8 MiB in total. ConfigKit removes exactly one
terminal LF or CRLF, preserves all other whitespace, accepts an empty value, and
rejects NUL bytes.
All eligible files are read successfully before application begins. Presence is
checked again immediately before each `os.Setenv`: a variable populated since
preflight is skipped. A write failure stops application without rollback, so prior
writes remain and later eligible entries are `not_applied`. This operation is not
All required files are read successfully before application begins. In
preservation mode presence is checked again immediately before each `os.Setenv`:
a variable populated since preflight is skipped. Overwrite mode applies the
staged value regardless of presence. A write failure stops application without
rollback, so prior writes remain and later eligible entries are `not_applied`. This operation is not
atomic and does not provide compare-and-set semantics for concurrent environment
mutation.
@@ -1115,9 +1275,11 @@ mutation.
records with `loaded`, `skipped_existing`, `not_applied`, or `failed` status.
`ExistingEmpty` distinguishes an empty existing winner. `SecretsReport.WriteTo`
renders only quoted names, canonical paths, statuses, and that empty-state flag;
it never retains or renders file contents. Failures return the non-nil partial
report with a `*SecretsError` containing detached `secrets.*` diagnostics and no
raw filesystem or environment error chain. Applications should retain the report
it never retains or renders file contents. Directory and environment failures
return the non-nil partial report with a `*SecretsError` containing detached
`secrets.*` diagnostics and no raw filesystem or environment error chain.
Configured main-preparation failures return `*LoadError` as described above.
Applications should retain the report
alongside the later configuration result and explicitly present blocked and failed
files when appropriate; ConfigKit stores no implicit global report.
@@ -1489,12 +1651,15 @@ claim records rather than mutating or aliasing an input document.
`Options.Overlay` selects at most one overlay by name. Names must match
`[a-zA-Z0-9_-]+`; they are not paths. The empty name and exact lowercase name
`default` select no overlay, and `overlays/default.yml` is never loaded implicitly.
Every other name resolves only to `<configuration-root>/overlays/<name>.yml`, with
For ordinary loads and explicit layered overlay contexts, every other name resolves
to `<configuration-root>/overlays/<name>.yml`, with
no extension fallback, case normalization, inheritance between overlay files,
or overlay stack. A selected missing overlay is an error.
For a layered main-derived or fallback context, lookup instead starts at the
resolved base directory; the configured root still bounds containment.
With `NoSource`, the main input stays absent and the explicit filesystem context
supplies the overlay root. The overlay is recorded as the first acquired source
With ordinary `Load` and `NoSource`, the main input stays absent and the explicit
filesystem context supplies the overlay root. The overlay is recorded as the first acquired source
when no other source exists. Host contexts may use the root-only form described
under [single-source loading](#single-source-loading); native contexts retain
their complete namespace, base, and root requirements.
@@ -1504,6 +1669,10 @@ base import graph is composed and its schema version is checked, but before defa
and typed decoding. Overlay bytes, nodes, and source records count toward the same
aggregate limits as base inputs. Its canonical path must remain within the configured
root and must not duplicate a file already present in the base graph.
For native filesystems that implement `fs.ReadLinkFS`, these checks resolve
link targets in the selected namespace. For other native filesystems, the
checks use namespace-relative paths and reads follow that filesystem's
ordinary behavior.
Collection destinations follow the
[collection operation and presence rules](#strict-document-composition) above.
@@ -1629,6 +1798,8 @@ config:
Each selected document follows the same strict combination rules. A missing
optional input can be absent; invalid declarations, unreadable selected files,
and conflicting settings still fail loading.
Main-relative underlays follow the same import rules once a context is selected;
their no-base behavior is described under [layered loading](#layered-loading).
| Option | `path` | `dir` | `glob` |
| --- | --- | --- | --- |
@@ -1643,8 +1814,10 @@ rules below explain absence, patterns, placement, and ordering.
### Declaration and selection rules
Imports are opt-in. With `Options.Imports` enabled, a document may use its root
`config` mapping for `imports` and `sequences` controls. Ordinary `Load` may use
`sequences` without enabling imports, but an `imports` field still requires
`config` mapping for `imports` and `sequences` controls. The main root may also
declare the [secrets bootstrap controls](#explicit-secrets-directory-bootstrap).
Ordinary `Load` may use `sequences` and main bootstrap controls without enabling
imports, but an `imports` field still requires
`Options.Imports`. ConfigKit removes recognized root controls before application
decoding. Each imports sequence item is a mapping with exactly one `path`,
`dir`, or `glob` selector. `path` and `dir` accept a string or a list of strings;
@@ -1676,8 +1849,16 @@ The [mounted-root example](../examples/consumers/config_controls_test.go) shows
an imported payload becoming application-root `config`. Inspection YAML can
contain that data and retains its existing lack of a reloadability guarantee.
Path declarations use slash-separated relative paths. Absolute paths and network
URLs are invalid. Each path resolves from its declaring file's canonical directory.
Path, directory and glob selectors accept absolute and parent-relative paths.
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
there are no named targets to be missing. A nonempty required path list verifies
every named target, including targets later excluded from selection.
@@ -1702,7 +1883,16 @@ walks only directories selected by preceding segments, and reads wildcard
directories in bounded batches. Every examined entry consumes the separate visit
budget, including nonmatches. Literal components are explicit path components;
`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
application-owned load-wide policy for enabled imports in the main source,
@@ -1803,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
with default or explicit `required: false` contributes nothing.
For host files, the configuration root defaults to the selected file's
canonical directory. A host file may supply `FilesystemContext.Root` to widen
that root but may not supply `BaseDir` or a native `FS`. Byte, reader, and
mapping inputs with host context must provide both `BaseDir` and `Root` as
absolute existing directories. For `Filesystem.File`, the default root is `.`
in its namespace and the base is the selected file's directory. An explicit
context must use the same `Filesystem` namespace and may set `Root` to contain
the file and its base; it may not supply `BaseDir`. Byte, reader, and mapping
inputs with native context provide both `BaseDir` and `Root` as slash-relative
`fs.ValidPath` directories in `FS` (`.` means its root), with the base inside
the root. Context paths are checked even when imports and overlays are
inactive. Diagnostic labels, including URI-looking labels, never imply
filesystem paths. Nonregular targets are rejected before opening to avoid
blocking on FIFOs; post-open regular-file checks remain in place under the
stable-input assumption. ConfigKit canonicalizes symlinks, checks containment
with relative paths, and opens the canonical root-relative target through a
library-owned root handle. Contained relative or absolute symlink targets are
accepted; escapes are rejected. Canonical paths define identity, so hard links
at distinct paths remain distinct sources. Native filesystems use slash-path
operations. Where the supplied `fs.FS` implements `fs.ReadLinkFS`, ConfigKit
uses that capability to inspect and resolve discovered links; otherwise it
follows the filesystem's ordinary `fs.FS` behavior. ConfigKit does not require
every native filesystem to expose link inspection, and native filesystem
behavior is not a general sandbox guarantee. Imports stay in their selected
namespace and root.
For host files, imports are unbounded by default, subject to ordinary filesystem
access and the existing admission and resource budgets. `FilesystemContext.Root`
explicitly bounds canonical targets, including links and transitive imports.
The selected file and base must be inside that root. A selected file determines
its own base and rejects BaseDir or native FS. Its canonical directory remains
the default resource/overlay/bootstrap anchor even when imports can reach beyond
it. Existing valid configurations and resource coordinates remain compatible;
applications preserving the earlier containment scope explicitly set Root.
Byte, reader and mapping host inputs require an absolute existing BaseDir even
for absolute-only selectors. Root is optional; omission uses BaseDir as the
resource/overlay/bootstrap anchor with unbounded imports. Explicit Root must be
an existing directory containing the base. Context paths are checked even when
imports and overlays are inactive. Diagnostic labels, including URI-looking
labels, never imply filesystem paths or a working-directory base.
For `Filesystem.File`, the default root is `.` in its namespace and the base is
the selected file's directory. An explicit context must use the same Filesystem
namespace and may set Root to contain the file and base; it may not supply
BaseDir. Synthetic native inputs still supply both BaseDir and Root as
slash-relative fs.ValidPath directories in FS, with the base inside the root.
There is no host fallback from a native namespace.
Nonregular targets are rejected before opening to avoid blocking on FIFOs;
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
sites. A previously visited canonical path is `import.repeated` and reports both

View File

@@ -24,12 +24,41 @@ 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) |
| 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) |
| 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) |
| 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) and the [startup 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) |
| Investigate a rejected load | [Failed-load reporting](#failed-load-reporting) |
| Hand one result to library consumers | [Component handoff](#component-handoff) |
| 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
Register application and library rules in one definition, then load once and
pass the whole result to each consumer. A consumer can select its named settings
with `Value`, assert its own type, and follow effective field origins through
`Metadata` and `SourceContext` to capture resources. It owns any runtime copy it
needs. The maintained [one-library example](../../examples/consumers/result_component.go)
shows registration, underlay defaults, handoff, and a focused inspection facade;
the [two-library example](../../examples/consumers/result_composition.go) composes
callbacks and identity registrations for two consumers.
Views focus reports while explicit metadata and explanation queries retain native
application-root paths. See the [configuration contract](../config.md#layered-metadata)
for ownership, scope, and frozen inspection behavior.
## Choosing a loading entry point
- Use [`Load`](../../lifecycle.go) with one source for an ordinary configuration.
@@ -38,7 +67,8 @@ Start with one file, then choose the tasks your application needs:
- Use `LoadLayered` when several inputs should supply lower-priority defaults
beneath the main source. Each underlay group combines its inputs strictly.
Each [`Input`](../../layered.go) owns its source, filesystem, destination, and
import choice. The overlay filesystem context is selected independently in
import choice. Set `Input.MainRelative` on a companion underlay to use the
main input's filesystem context. Overlay context selection belongs to
[`LayeredOptions`](../../layered.go).
- Load-wide rules belong to [`Options`](../../lifecycle.go) or
[`LayeredOptions`](../../layered.go): the application definition (including
@@ -53,6 +83,19 @@ file and layered cases. For import-focused adoption, see the
[prompt catalog](../../examples/consumers/prompt_catalog.go); for explicit
discovery composed with sequences, see the
[sequence catalog](../../examples/consumers/sequence_catalog.go).
For discovered main files with companion imports and an overlay, see the
[main-relative example](../../examples/consumers/main_relative.go).
## Configured secrets startup
Call [`PrepareStartup`](../../examples/consumers/secrets.go) with a host file
or search source and the selected containment root, then handle its report and
error before loading. Pass the returned source to ordinary `Load`, or place it
in the main `Input` for `LoadLayered`; the [maintained test](../../examples/consumers/secrets_test.go)
shows both. Preparation is explicit and loads eligible files even when their
names are used only by another SDK. The application owns startup ordering and
handling partial effects. See the [configuration contract](../config.md#explicit-secrets-directory-bootstrap)
for controls, overwrite precedence, errors, and source reuse.
## Happy path
@@ -101,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
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
Applications choose the search conventions and their precedence, then pass the
@@ -517,7 +573,7 @@ focused behavioral owner:
| `Load`, `NoSource`, validation, versions, resolution, `SecretEnv`, overrides, and explanation | Executable examples in [`example_test.go`](../../example_test.go) |
| Source/import/selected-overlay pipeline rules and artifact defaults | Narratio-shaped executable example and fixture |
| Canonical module objects and dynamic option handling | WeatherReporter- and Notarius-shaped examples and migration tests |
| `LoadSecretsIntoEnvironment`, bootstrap reporting, typed lookup, CLI explanation | `Example_weatherStartup` |
| Secrets bootstrap, prepared ordinary and layered sources, typed lookup | [`TestConfiguredSecretsStartup`](../../examples/consumers/secrets_test.go) and `Example_weatherStartup` |
| Native filesystem, grouped underlays, programmatic mapping, retained resource context | `Example_nativeFilesystem`, `Example_layeredCatalog`, and their focused consumer tests |
| Literal input destinations, root-default compatibility, and mounted peer collections | `Example_inputDestination`, `LoadCollectionBundle`, and `destinations_test.go` |
| Named sibling inheritance, presence, and derivation | `Example_inheritedPresets` and `TestPresetCatalogOneLoadAndDerivation` |

View File

@@ -54,10 +54,13 @@ Accepted decisions:
- [Check source versions with one shared policy](adr/0013-shared-source-version-checks.md)
- [Own YAML semantics behind a private parser boundary](adr/0002-own-yaml-semantics.md)
- [Preserve presence and record application resolution](adr/0003-preserve-presence-and-resolution-history.md)
- [Secret references and explicit bootstrap](adr/0004-secret-references-and-explicit-bootstrap.md)
- [Explicit configured secrets bootstrap](adr/0023-explicit-configured-secrets-bootstrap.md)
- [Explicit overrides and safe explanation](adr/0005-explicit-overrides-and-safe-explanation.md)
- [Keep the public facade root-owned](adr/0006-public-facade.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)
- [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)
- [Share dependency-ready ordering](adr/0015-shared-dependency-ready-ordering.md)
- [Separate import selection controls](adr/0016-independent-import-controls.md)
@@ -66,181 +69,18 @@ Accepted decisions:
- [Keep main-file discovery explicit and composable](adr/0019-explicit-configuration-discovery.md)
- [Scope configuration controls to document roots](adr/0020-document-root-controls.md)
- [Match registered records during resolution inspection](adr/0021-sequence-resolution-correspondence.md)
- [Bind companion contexts after main selection](adr/0022-main-relative-context.md)
For cross-cutting changes, follow every applicable row. Completed implementation
and remediation plans are preserved in Git history at `cb5b435`; use current
contracts and the component overview for ongoing work. For example:
```sh
git show cb5b435:docs/roadmap/remediation.md
```
For cross-cutting changes, follow every applicable row. Use current contracts
and the component overview for ongoing work.
Release-candidate, publication, and verification work follows the operational
[release procedure](release.md). Its module-selected ReleaseKit `publish`
invocation validates the committed candidate and publishes only the intended
tag; those release checks remain distinct from the everyday development check.
The completed string-and-integer schema-version implementation and remediation
records are preserved in Git history at `244104f`. The
[configuration contract](config.md#application-schema-versions) owns current behavior.
The completed source-origins and public-facade roadmaps, implementation plan, and
resolved review findings are preserved in Git history at `5760614`, for example
`git show 5760614:docs/roadmap/remediation.md`. The earlier source-origins staged
plan remains at `28e7fc5:docs/roadmap/implementation.md`. Current resolution
behavior belongs to the [configuration contract](config.md#recorded-application-resolution),
and current facade ownership belongs to the [component overview](internal/overview.md).
## Baseline validation
The completed field-level sequence resolution roadmap, implementation plan, and
resolved audit findings are preserved in Git history at `7e53863` under
`docs/roadmap/`. For example:
```sh
git show 7e53863:docs/roadmap/implementation.md
git show 7e53863:docs/roadmap/remediation.md
```
The [configuration contract](config.md#recorded-application-resolution) owns
current resolution behavior, and [ADR 0021](adr/0021-sequence-resolution-correspondence.md)
records the correspondence decision.
The completed filesystem-source and underlay roadmap, original feature request,
implementation plan, and resolved remediation record are preserved in Git history
at `b604aa1` under `docs/roadmap/`. Current behavior belongs to the
[configuration contract](config.md#layered-loading). Built-in sibling
inheritance is now part of the [configuration contract](config.md#sibling-inheritance).
The completed request, roadmap, plan, and resolved review findings are preserved
in Git history at `83c59ea` under `docs/roadmap/`.
The completed overlay rename plan and release-workflow simplification record are
preserved in Git history at `73ce6e9` under `docs/roadmap/`. Current overlay
behavior belongs to the [configuration contract](config.md#selected-overlays),
and release operations belong to the [release procedure](release.md).
The completed ReleaseKit adoption, startup performance request and experiments,
benchmark evidence, performance audit, implementation plan, and remediation
record are preserved in Git history at `8e91a2b` under `docs/roadmap/`. For example:
```sh
git show 8e91a2b:docs/roadmap/startup-benchmark.md
```
Remaining optimization candidates belong to
[future performance experiments](roadmap/future.md#3-performance-experiments).
The completed effective-configuration diff roadmap, implementation plan, and
resolved review findings are preserved in Git history at `1c2610c` under
`docs/roadmap/`. The
[configuration contract](config.md#effective-configuration-diffs) owns current
comparison and disclosure behavior, and
[ADR 0010](adr/0010-effective-configuration-diff.md) records the decision.
The completed input-destination, relative-import-destination, and shared
source-version roadmaps, associated consumer request, implementation plan, and
resolved review findings are preserved in Git history at `e4270c9` under
`docs/roadmap/`. For example:
```sh
git show e4270c9:docs/roadmap/implementation.md
git show e4270c9:docs/roadmap/remediation.md
```
Current behavior belongs to the configuration contract's
[input destinations](config.md#input-destinations),
[imports](config.md#explicit-imports), and
[shared source-version checks](config.md#shared-source-version-checks) sections.
Explicit sequence-item placement, collection operations, identity registration,
and final registered-identity validation are owned by the
[strict composition](config.md#strict-document-composition) section;
[imports](config.md#explicit-imports) owns acquisition and scheduling. The
[maintained sequence catalog](consumers/README.md#identified-prompt-sequences)
shows the consumer boundary, and [ADR 0017](adr/0017-collection-sequence-policy.md)
records the collection decision.
The completed sequence-composition roadmap, implementation plan, and resolved
remediation record are preserved in Git history at `008d2ba` under
`docs/roadmap/`. For example:
```sh
git show 008d2ba:docs/roadmap/sequence-composition.md
git show 008d2ba:docs/roadmap/implementation.md
git show 008d2ba:docs/roadmap/remediation.md
```
The completed import-discovery roadmap, implementation plan, and resolved
remediation record are preserved in Git history at `5747ec4` under
`docs/roadmap/`. For example:
```sh
git show 5747ec4:docs/roadmap/imports.md
git show 5747ec4:docs/roadmap/implementation.md
git show 5747ec4:docs/roadmap/remediation.md
```
The subsequent import-integration audit and completed remediation record are
preserved at `6903c9e:docs/roadmap/remediation.md`; retrieve them with
`git show 6903c9e:docs/roadmap/remediation.md`.
The completed sequence-identity/collection-policy roadmap and implementation
plan are preserved in Git history at `d0a605a`:
```sh
git show d0a605a:docs/roadmap/sequences.md
git show d0a605a:docs/roadmap/implementation.md
```
Current behavior belongs to the configuration contract's
[strict composition](config.md#strict-document-composition),
[sibling inheritance](config.md#sibling-inheritance), and
[CLI overrides](config.md#explicit-cli-overrides) sections.
The completed remediation record, including the algorithm-audit findings, is
preserved at `ea46001:docs/roadmap/remediation.md`.
The completed configuration-discovery roadmap, implementation plan, and
remediation record are preserved in Git history at `0369111`, for example
`git show 0369111:docs/roadmap/remediation.md`. Current behavior belongs to
[configuration discovery](config.md#configuration-discovery); the public
[discovery declarations](../discovery.go) own the Go API.
The completed consolidation proposal, implementation plan, and resolved audit
findings are preserved in Git history at `34cbc0d` under `docs/roadmap/`. For
example:
```sh
git show 34cbc0d:docs/roadmap/implementation.md
git show 34cbc0d:docs/roadmap/remediation.md
```
Potential enhancements are tracked in [future features](roadmap/future.md).
The completed audit-remediation, internal-boundary simplification, shared-history,
and public API cleanup roadmaps, reviews, and resolved findings are preserved at
`68400ff` under `docs/roadmap/`. For example:
```sh
git show 68400ff:docs/roadmap/api.md
git show 68400ff:docs/roadmap/remediation.md
```
Their earlier completed implementation plans are preserved at
`bb5540b:docs/roadmap/implementation.md` (audit remediation),
`f6d54a0:docs/roadmap/implementation.md` (internal-boundary simplification), and
`07e4ae5:docs/roadmap/implementation.md` (shared history). The plan at
`68400ff:docs/roadmap/implementation.md` records the public API cleanup.
Current behavior and migration information belong to the
[configuration contract](config.md), public declaration comments, and
[consumer guide](consumers/README.md#pre-v1-public-api-cleanup).
The consolidated audit, including
findings, evidence, and settled scope decisions, is preserved at
`453da68:docs/roadmap/audit.md`; the original nine reports are preserved at
`ecd5d5d` under `docs/roadmap/`. Retrieve the consolidated record with:
```sh
git show 453da68:docs/roadmap/audit.md
```
Install the Go version required by `go.mod` or a compatible newer toolchain.
Acquire declared dependencies explicitly before entering an offline
development or validation environment:
@@ -292,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'` |
| 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'` |
| 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'` |
@@ -302,11 +143,13 @@ code changes. Use the component overview to find the corresponding implementatio
| Input and relative-import destinations, mounted sources, and source ownership | [Destination engine tests](../internal/engine/destination_test.go), [tier tests](../internal/engine/destination_tiers_test.go), [import traversal and version tests](../internal/engine/destination_import_test.go), [accounting tests](../internal/engine/destination_accounting_test.go), [lifecycle inspection tests](../internal/engine/destination_import_lifecycle_test.go), [public source/error tests](../facade_destination_test.go), [resource contexts](../facade_resource_context_test.go), and [consumer examples](../examples/consumers/destinations_test.go) | `go test ./internal/engine -run 'Destination\|Import\|Glob\|Mounted'`, `go test . -run 'Destination\|Import\|SourceContext\|FacadeMounted'`, 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'` |
| 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'` |
| 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'` |
| Passive resource contexts | [Engine contexts](../internal/engine/resource_context_test.go), [public contexts](../facade_resource_context_test.go) | `go test ./internal/engine -run 'Resource'` and `go test . -run 'SourceContext'` |
| Secrets, bootstrap, redaction, explanation | [References](../internal/engine/secret_reference_test.go), [bootstrap](../internal/engine/secrets_test.go), [rendering](../internal/engine/render_test.go), [explanation](../internal/engine/explain_test.go) | `go test ./internal/engine -run 'Secret\|Bootstrap\|Effective\|Explain\|Explanation\|History\|Sensitivity'` |
| Secrets, bootstrap, redaction, explanation | [References](../internal/engine/secret_reference_test.go), [directory bootstrap](../internal/engine/secrets_test.go), [configured preparation](../internal/engine/secrets_from_config_test.go), [public handoff](../facade_secrets_handoff_test.go), [consumer example](../examples/consumers/secrets_test.go), [rendering](../internal/engine/render_test.go), [explanation](../internal/engine/explain_test.go) | `go test ./internal/engine -run 'Secret\|Bootstrap\|Effective\|Explain\|Explanation\|History\|Sensitivity'`, `go test . -run 'Secrets\|Bootstrap'`, and `go test ./examples/consumers -run 'ConfiguredSecrets'` |
| Effective configuration diff | [Engine comparison and masking tests](../internal/engine/diff_test.go), [engine operation tests](../internal/engine/diff_operation_test.go), [root facade tests](../facade_diff_test.go), and [consumer examples](../examples/consumers/diff_test.go) | `go test ./internal/engine -run 'Diff\|Explain\|History\|Secret\|Independent'`, `go test . -run 'Diff\|FacadeInspection\|PublicFacadeBoundary\|DependencyImportBoundary'`, `go test ./examples/consumers`, and `go test . -run '^ExampleDiff$'` |
| Consumer examples and migration fixtures | [Consumer tests](../examples/consumers/consumers_test.go), [native, layered, and ordinary relative-import examples](../examples/consumers/layered_test.go), [mounted collection examples](../examples/consumers/destinations_test.go), [API examples](../example_test.go) | `go test ./examples/consumers` and `go test . -run '^Example'` |
| Assembly and layered scaling evidence | [Assembly benchmarks](../internal/engine/assembly_bench_test.go), [layered benchmarks](../internal/engine/underlay_bench_test.go) | `go test ./internal/engine -run '^$' -bench '^BenchmarkUnderlay' -benchmem`; repeat with `^BenchmarkCompose` and `^BenchmarkOverlay` |

View File

@@ -15,23 +15,47 @@ selection in `import_selection.go` preserves a normalized
namespace path separately from canonical access identity: overlapping roots
coalesce the same candidate spelling in that namespace, while aliases reached
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
patterns to discovered names, and form a set union of matching candidates across
overlapping roots. Exclusions are applied as set difference after discovery and
candidate normalization. They do not suppress discovery or resource errors.
Layered assembly passes the resolved main context to underlay acquisition.
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.
Contextless bindings prepare declaration policies and assemble the declaring
payload without opening filesystem access or recording selection evidence.
Selected contexts use the existing acquisition and handle lifecycle.
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
load, including placement wrappers, and its canonical path participates in
cycle and repeated-source checks. Imports are still acquired live; layered
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
context checks are owned by
[`prepared_source.go`](../../internal/engine/prepared_source.go) and
[`filesystem_context.go`](../../internal/engine/filesystem_context.go).
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
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.
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
acquisition operation closes its live handles before composition. Native sources
use `fs.ReadLinkFS` inspection when supplied; otherwise traversal follows the
capabilities and behavior of the provided `fs.FS`, without claiming a general
sandbox guarantee. `source_context.go` derives passive resource contexts from
resolved sources for later caller-owned reads; those records do not retain live
acquisition handles.
resolved sources for later caller-owned reads. Contained sources keep the legacy
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
tracks active links for cycle detection and reuses successfully completed link
@@ -42,6 +66,26 @@ directory can be treated as optional, while enumeration and close failures
remain selection errors, including errors from the standard `fs.ReadDir`
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`:
it advances literal and patterned segments, reads directories, unions and sorts
candidates, validates final targets, then applies exclusions and requiredness.

View File

@@ -11,7 +11,7 @@ Implemented component owners:
explicitly selected configuration discovery. A search resolves once during
shared acquisition; the selected concrete file or absent-input state then
follows the existing composition, metadata, and resource-context lifecycle.
It also owns grouped strict composition, recursive precedence assembly,
It also owns main-relative context selection, grouped strict composition, recursive precedence assembly,
per-input mapping and sequence-item placement, YAML collection declarations
and operations for identified sequences, and application identity registrations for strict
composition, inheritance, and final validation. It applies the selected
@@ -45,6 +45,12 @@ Implemented component owners:
- Root `Diff` and `Difference` provide the public comparison boundary and
convert detached engine records to root-owned paths and snapshots; consumer
examples own presentation of the safe changed regions.
- `Result.Value` delegates current Go-value navigation to an operation-local
engine schema builder and existing field/path bindings. Root `Inspection`
wraps an engine view borrowing the frozen inspection and canonical scope;
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/yaml` is the sole upstream YAML adapter and parser/dumper boundary.
- Engine mechanism tests own source, composition, inheritance, decoding,
@@ -119,12 +125,30 @@ share one assembly handoff that applies collection declarations and projects
only that tier's source/version evidence; the caller keeps main-version
protection and its projection explicit. Live
filesystem access handles are confined to acquisition and closed there. Resolved
filesystem facts used to authorize access are separate from passively retained
resource contexts. Non-import validation retains those facts on `assembledInput`
filesystem facts separate an optional import boundary from the lookup base and
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
[`filesystem_context.go`](../../internal/engine/filesystem_context.go) and
[`source_context.go`](../../internal/engine/source_context.go).
Explicit configured bootstrap uses
[`prepared_source.go`](../../internal/engine/prepared_source.go) to share host
discovery and bounded parsing with acquisition. It stores a read-only main tree,
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)
validates just the bootstrap controls and calls the shared directory worker.
Acquisition checks any later explicit context against the captured facts before
imports or overlays, then applies normal source and aggregate accounting.
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
normalization in [`import_selection.go`](../../internal/engine/import_selection.go),
source reading and traversal admission in
@@ -168,6 +192,16 @@ pre-secret admission boundary, [`prepareInspectionHistory`](../../internal/engin
freezes that builder and counts the retained document roots before secret lookup
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
selection in [`history_select.go`](../../internal/engine/history_select.go)
drives metadata history, explanation, and historical-path membership; the model

View File

@@ -2,9 +2,9 @@
## Standard Repository Policies
Material: `docs/policy/release.md`, adapted from
`e833faddf120c789a9b45348edaf75720de16348`; `docs/policy/meta.md`, `docs/policy/oss.md`,
`docs/policy/documentation.md`, `docs/policy/agents.md`,
Material: `docs/policy/documentation.md`, `docs/policy/oss.md`, and
`docs/policy/release.md`, adapted from
`b339ad0427a50e43a68b932a6a9f4669cc0f6252`; `docs/policy/meta.md`, `docs/policy/agents.md`,
`docs/policy/architecture.md`, `docs/policy/testing.md`; root `AGENTS.md`; and the
Policy Reading Guide in `docs/development.md`, adapted from
`d84a38ebab26f048cafbe59a2246700c35d29843` for this repository.
@@ -16,16 +16,16 @@ SPDX-License-Identifier: CC-BY-SA-4.0
License and notices: [CC BY-SA 4.0](licenses/CC-BY-SA-4.0.txt) |
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/LICENSE) |
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/LICENSE).
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/b339ad0427a50e43a68b932a6a9f4669cc0f6252/COPYRIGHT) |
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/b339ad0427a50e43a68b932a6a9f4669cc0f6252/LICENSE).
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843).
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348).
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/b339ad0427a50e43a68b932a6a9f4669cc0f6252).
## go-yaml v4
Selected module: `go.yaml.in/yaml/v4` at `v4.0.0-rc.6`.
Selected module: `go.yaml.in/yaml/v4` at `v4.0.0`.
Copyright 2011-2019 Canonical Ltd
@@ -37,7 +37,7 @@ SPDX-License-Identifier: Apache-2.0 AND MIT
License and notices: [Apache 2.0](licenses/Apache-2.0.txt) |
[MIT](licenses/MIT.txt) |
[NOTICE](https://github.com/yaml/go-yaml/blob/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125/NOTICE) |
[LICENSE](https://github.com/yaml/go-yaml/blob/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125/LICENSE).
[NOTICE](https://github.com/yaml/go-yaml/blob/f2f9563503f11b7a60da0c532175dcc693ce8d5a/NOTICE) |
[LICENSE](https://github.com/yaml/go-yaml/blob/f2f9563503f11b7a60da0c532175dcc693ce8d5a/LICENSE).
[Source](https://github.com/yaml/go-yaml/tree/1c17b9cee72bf81ae73a8be50fbd7dd3a9985125).
[Source](https://github.com/yaml/go-yaml/tree/f2f9563503f11b7a60da0c532175dcc693ce8d5a).

View File

@@ -151,6 +151,11 @@ initialization, and resource checks. See the [configuration discovery
contract](../config.md#configuration-discovery) and [ADR
0019](../adr/0019-explicit-configuration-discovery.md).
The layered loader may bind application-selected dependent locations after main
selection. Applications still choose search conventions and must explicitly
select an overlay. [ADR 0022](../adr/0022-main-relative-context.md) records
the deferred context decision.
The engine applies each input's mapping destination within the existing source
assembly, applies immediate-parent-relative YAML destinations to imports, and
retains each effective placement with source identity and inspection records;
@@ -173,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)
owns observable behavior; [ADR 0015](../adr/0015-shared-dependency-ready-ordering.md)
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
invoke it during startup, and it reports writes, skips and partial failures. It
must never run implicitly as part of configuration loading.
@@ -183,8 +193,10 @@ network provider into the library.
Configuration loading is a synchronous, complete-on-return operation. A successful
load provides the final configuration and inspection metadata after the configured
processing and validation phases complete. A failed load reports diagnostics and
returns no usable partial result. The normal application pattern is one load near
processing and validation phases complete. A failed load returns a nil result and
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.
ConfigKit releases its library-owned loading handles before returning and remains
@@ -306,17 +318,20 @@ metadata, and effective inspection must agree, including application resolution
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,
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).
Detailed syntax and operation tables belong to the
[current configuration contract](../config.md).
The frozen inspection boundary also supports comparing completed same-type
results without reopening sources or rerunning the load lifecycle. The
The frozen inspection boundary supports comparing completed same-type results
and focused views across application root types and load outcomes without reopening sources or
rerunning the load lifecycle. The
[configuration contract](../config.md#effective-configuration-diffs) owns
comparison and disclosure behavior, the [component overview](../internal/overview.md)
owns implementation responsibility, and [ADR 0010](../adr/0010-effective-configuration-diff.md)
records the accepted decision.
and [ADR 0024](../adr/0024-compare-inspection-views-across-application-types.md)
record the comparison decisions. [ADR 0025](../adr/0025-inspect-failed-configuration-loads.md)
extends inspection to available failure checkpoints.
## Collection Identity And Combination
@@ -400,9 +415,14 @@ Secret values enter configuration through typed environment-name references;
literal credentials are not a supported configuration convention. Only an explicit
accessor exposes a resolved credential to application code. Credential bytes must
never enter composition trees, history, or inspection. General environment-variable
configuration overlays are an explicit non-goal. Bootstrap must preserve already
set variables, including empty ones, and report blocked files without contents.
See [ADR 0004](../adr/0004-secret-references-and-explicit-bootstrap.md).
configuration overlays are an explicit non-goal. Bootstrap preserves already
set variables by default, including empty ones, and reports blocked files without
contents. Explicit overwrite and main-document-directed bootstrap are available
as separate startup operations. A prepared main retains its selected document
and passive filesystem context without retaining secret-file contents or open
handles. [ADR 0023](../adr/0023-explicit-configured-secrets-bootstrap.md) records
the decision; the [configuration contract](../config.md#explicit-secrets-directory-bootstrap)
owns current behavior.
Secrets must be considered throughout error handling and inspection. Library
renderers must apply secret classification, and parser errors must not be

View File

@@ -1,10 +1,10 @@
# Documentation Policy
**Base Policy Version:** 1.11
**Base Policy Version:** 1.12
**Last Updated**: 2026-10-16
**Last Updated**: 2026-11-09
**Upstream Source:** [Standard Repository Policies](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/documentation.md)
**Upstream Source:** [Standard Repository Policies](https://gitea.maximumdirect.net/eric/policy/src/commit/b339ad0427a50e43a68b932a6a9f4669cc0f6252/docs/policy/documentation.md)
## Purpose
@@ -91,7 +91,7 @@ secret values.
| Consumer guidance for the public Go API | `docs/consumers/` | Task-oriented public Go API usage, minimal examples, and consumer responsibilities. | Go symbol contracts, configuration semantics, and internal implementation detail. |
| Inventory of implemented internal packages | `docs/internal/overview.md` | Implemented packages and components, responsibilities, and links to focused internal docs. | Normative architecture, contributor reading policy, external contracts. |
| Behavior and architecture of internal packages | Other files under `docs/internal/` | Implementation flow, collaborators, state transitions, package-local guarantees and failures, and relevant tests. | Global architecture invariants, configuration definitions and defaults, external schemas, operator procedures. |
| Architectural decision records | `docs/adr/` | Significant decisions, context, alternatives, rationale, consequences, and supersession history. | Current behavior reference, implementation status, task sequencing. |
| Architectural decision records | `docs/adr/` | Records of significant architectural decisions and supporting rationale. | Ordinary design choices, current behavior reference, implementation status, task sequencing. |
| Potential future features | `docs/roadmap/future.md` | Candidate enhancements and open questions for future consideration. | Rejected proposals, architectural decisions, task execution, and current behavior. |
| Future implementation plans | Task-specific files under `docs/roadmap/` | Unfinished work, sequencing, acceptance, and progress; completed plans retire during release preparation. | Implemented behavior and ADR rationale. |
| Release-note history | `docs/releases/` | One checked-in summary per source release under the procedure; the note at its immutable tag is the release record. | Current commands, behavior, contracts, and compatibility definitions. |
@@ -157,10 +157,16 @@ Use sequentially numbered ADR filenames such as
Treat the decision content of an accepted ADR as immutable. When a decision
changes, create a new ADR and update the earlier ADR's status to superseded.
ADRs should be reserved for major architectural decisions, such as ownership
boundaries, large-scale architectural features, or invariants that rise to
the level of architectural significance. Routine choices, implementation
decisions, and rejected suggestions do not warrant an ADR unless they
otherwise represent a significant architectural decision.
Rejected architectural alternatives and significant architectural exclusions
belong in ADRs. Roadmaps preserve plausible future work, not rejected product
ideas. Routine choices and rejected suggestions need no ADR unless they
represent a significant architectural decision.
ideas.
## Maintenance

View File

@@ -1,10 +1,10 @@
# Open Source Licensing And Attribution Policy
**Base Policy Version:** 1.8
**Base Policy Version:** 1.9
**Last Updated**: 2026-09-28
**Last Updated**: 2026-11-09
**Upstream Source:** [Standard Repository Policies](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/docs/policy/oss.md)
**Upstream Source:** [Standard Repository Policies](https://gitea.maximumdirect.net/eric/policy/src/commit/b339ad0427a50e43a68b932a6a9f4669cc0f6252/docs/policy/oss.md)
## ConfigKit Applicability
@@ -74,8 +74,9 @@ individual packages.
Use the upstream [application COPYRIGHT example](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/examples/licensing/application/COPYRIGHT)
or [library COPYRIGHT example](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/examples/licensing/library/COPYRIGHT)
to create the project’s root `COPYRIGHT` file.
Use verified project names, contribution years, and copyright holders.
to create the project’s root `COPYRIGHT` file. Use the examples as provided,
without discretionary modification, unless otherwise instructed. Substitute
verified project names, contribution years, and copyright holders.
For another selected license, adapt the grant, SPDX expression, disclaimer, and
text references together to reflect the author's selected grant.

View File

@@ -1,10 +1,10 @@
# Release Policy
**Base Policy Version:** 1.6
**Base Policy Version:** 1.7
**Last Updated**: 2026-10-09
**Last Updated**: 2026-11-09
**Upstream Source:** [Standard Repository Policies](https://gitea.maximumdirect.net/eric/policy/src/commit/e833faddf120c789a9b45348edaf75720de16348/docs/policy/release.md)
**Upstream Source:** [Standard Repository Policies](https://gitea.maximumdirect.net/eric/policy/src/commit/b339ad0427a50e43a68b932a6a9f4669cc0f6252/docs/policy/release.md)
## Purpose
@@ -110,6 +110,10 @@ For releases at or after `v1.0.0`:
minimum as described below; and
- a patch release may make backward-compatible fixes.
In this context, "backward-compatible" means only that pre-existing, valid
configurations will continue to work following the release. Behavior need not
remain strictly identical.
Before `v1.0.0`, a minor release may change a documented public, operational,
configuration, data, integration, or compatibility contract when the release
note explains the impact and required consumer action. A patch release must

View File

@@ -103,17 +103,29 @@ go list -m go.maximumdirect.net/releasekit
go tool releasekit version
```
This repository selects ReleaseKit v0.8.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
status to 1. ReleaseKit's child Go commands
use the `go` found on `PATH` with `GOTOOLCHAIN=local`; keep the selected
executable first on `PATH` through the publication command.
If Go is configured for cross-compilation, select the host for the release
session before preparing or running the CLI:
```sh
release_host_os=$(go env GOHOSTOS)
release_host_arch=$(go env GOHOSTARCH)
export GOOS="$release_host_os" GOARCH="$release_host_arch"
```
ReleaseKit still selects the Linux compilation targets from the profile.
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` is unset or blank; a nonblank environment value takes
precedence. The file path resolves from the repository root, and ReleaseKit
trims surrounding whitespace from its contents. Keep credentials out of release
`.releasekit/gitea-token` with owner-only permissions. The profile selects it through
`delivery.credentials.local.token_file`. Local delivery uses this file exclusively;
environment tokens do not override it. The file path resolves from the repository
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
`forbidden_files` check also rejects a committed token at that exact path;
it does not scan other files or history. Source publication uses Git
@@ -128,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
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
Choose a stable version that has not been used locally or on the publication
@@ -257,10 +281,11 @@ available locally:
```sh
release_version=v1.0.0
git switch --detach "$release_version"
git switch --detach "$release_version" && git status --short
```
After preparing the tool in that tagged checkout:
Proceed once the switch succeeds and the status output is empty. After
preparing the tool in that tagged checkout:
```sh
go tool releasekit deliver "$release_version"
@@ -310,9 +335,11 @@ regardless of the CLI's credential-redacted diagnostic output.
Reconciliation observes the captured endpoint and exact tag object using current
supported Git transport settings. It does not load the current profile, require
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
another CLI supporting the saved record format, including format 2 where exact
non-UTF-8 endpoint/path bytes were retained.
hosted delivery. It needs no clean candidate checkout. Use a CLI supporting the
saved record's format: ReleaseKit v0.11.0 writes format 3, which includes source
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 |
| --- | --- |

54
docs/releases/v1.2.0.md Normal file
View File

@@ -0,0 +1,54 @@
# ConfigKit v1.2.0
`LoadLayered` can now use the resolved main configuration's filesystem context
to find companion imports and the selected overlay in a single load. For example,
an application that discovers `/srv/campaign/config.yml` can import fragments
from `/srv/campaign/prompts/` and apply
`/srv/campaign/overlays/production.yml`, regardless of its working directory.
## Main-relative companion inputs
Set `Input.MainRelative` to `MainRelative()` on a non-file underlay to use the
main input's resolved context. Enable imports separately and declare the files
or directories to load. A concrete `Input.Filesystem` takes precedence over the
binding. The derived context keeps the main input's filesystem namespace and
containment root, with lookup starting at its resolved base directory.
When the main supplies no usable context, the companion can use a
`MainRelativeContext.Fallback`. Otherwise, optional imports are skipped and
the companion's own configuration still contributes. Required imports that
need targets fail, and `RequireBase` requires a usable context even when imports
are disabled. Skipped imports produce no filesystem search evidence.
The consumer example combines embedded defaults, operator imports, and a selected
overlay. [Example](../../examples/consumers/main_relative.go) ·
[Layered loading contract](../config.md#layered-loading)
## Overlay lookup and filesystem checks
`LoadLayered` now looks for a selected overlay using `OverlayFilesystem`, the
resolved main context, or `OverlayFallback`, in that order. Derived and fallback
lookups start at the context's base directory. Explicit overlay contexts and
ordinary `Load` use their existing root-relative lookup. A selected overlay
must exist in the chosen context.
Native overlays resolve symlink targets when the filesystem exposes link
inspection. This catches targets outside the configured root and aliases of
already acquired files in the same namespace. Derived standalone host contexts
now check root access the same way explicit contexts do. [Overlay contract](../config.md#selected-overlays)
## Upgrade notes
Use keyed Go literals when constructing `Input` and `LayeredOptions`. Both
types gained fields, so existing positional literals need updating. The minimum
consumer Go version is 1.27.0.
Internally, imports with and without a filesystem base share root placement
and accounting. Directory import policies reuse default patterns, and companions
in the same tier share one derived context.
The repository also adopted upstream documentation, licensing, and release
policy updates, including clearer guidance on when to write an ADR and what
compatibility means for existing configurations. [Repository policies](../policy/meta.md)
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.0/COPYRIGHT) | [LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.0/LICENSE) | [ATTRIBUTION](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.0/docs/oss/attribution.md)

11
docs/releases/v1.2.1.md Normal file
View File

@@ -0,0 +1,11 @@
# ConfigKit v1.2.1
ConfigKit now uses the stable go-yaml v4.0.0 release in place of v4.0.0-rc.6.
Existing Go code and configuration files require no changes. The minimum
consumer Go version remains 1.27.0.
The maintainer release workflow now uses ReleaseKit v0.10.0, which updates
Markdown validation dependencies and includes fixes for publication recovery
and hosted release retries.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.1/COPYRIGHT) | [LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.1/LICENSE) | [ATTRIBUTION](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.1/docs/oss/attribution.md)

50
docs/releases/v1.3.0.md Normal file
View File

@@ -0,0 +1,50 @@
# ConfigKit v1.3.0
Applications can now bootstrap secrets from a directory declared in a discovered
main configuration file, then load that same captured document. Explicit
overwrite options support deployments that give provisioned secret files
priority over existing environment variables.
## Configured secrets startup
Call `LoadSecretsIntoEnvironmentFromConfig` with a host `File` or `SearchConfig`
source. The selected main file can declare:
```yaml
config:
secrets_dir: secrets
secrets_overwrite: true
```
The helper resolves the directory relative to the main file's canonical
directory, within its filesystem root, and bootstraps all eligible entries.
It returns a secrets report and a prepared source. Pass that source to `Load`,
or use it as the main `Input.Source` for `LoadLayered`.
The prepared source retains the selected main contents and filesystem context
for reuse. Later loads acquire imports and look up environment values at their
normal lifecycle points. `SecretsFromConfigOptions.Filesystem` can select a
wider host root during preparation. An explicit context supplied to a later
load must resolve to the captured context. [Startup example](../../examples/consumers/secrets.go) · [Configuration contract](../config.md#explicit-secrets-directory-bootstrap)
## Explicit overwrite policy
Overwrite defaults to false, preserving existing variables including empty
ones. YAML `secrets_overwrite: true` enables replacement during configured
bootstrap. A non-nil `SecretsFromConfigOptions.Overwrite` takes precedence over
YAML, including an explicit false.
For an application-supplied directory, use
`LoadSecretsIntoEnvironmentWithOptions` with `SecretsOptions{Overwrite: true}`.
Existing `LoadSecretsIntoEnvironment(directory)` calls retain their preservation
behavior and exact Go function signature.
Bootstrap runs through an explicit helper call before configuration loading.
Reports describe writes, skips, and partial failures without credential contents.
A later configuration failure leaves completed environment writes in place.
Ordinary `Load` and `LoadLayered` consume the main controls and resolve typed
secret references from the environment. [Bootstrap and failure handling](../config.md#preflight-limits-and-partial-writes)
Consumers require Go 1.27.0 or later.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.3.0/COPYRIGHT) | [LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.3.0/LICENSE) | [ATTRIBUTION](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.3.0/docs/oss/attribution.md)

58
docs/releases/v1.4.0.md Normal file
View File

@@ -0,0 +1,58 @@
# ConfigKit v1.4.0
Applications can now load configuration once and pass the complete result to
libraries that select their own typed settings and reporting scope. The new APIs
reuse the original load's provenance, resource contexts, and frozen inspection
state.
## Current typed values
`Result.Value(path)` selects a current Go value without requiring the consumer
to know the application's root configuration type. It uses ConfigKit's existing
field bindings and semantic paths, preserving named types, terminal pointers,
and resolved `Secret` values. A present nil value succeeds; unavailable paths
return false. Lookup also works with manually constructed results and returns
terminal values without conversion or revalidation.
This is trusted access with ordinary Go assignment semantics: maps, slices, and
pointers can share state with `Result.Config`. Later caller changes are visible
to lookup, while inspection continues to describe the completed load. Consumers
remain responsible for capturing any owned runtime settings they need.
[Value API](../../result_value.go) · [Ownership contract](../config.md#completion-and-resource-lifetime)
## Focused inspection
`Result.InspectSubtree(path)` returns a non-generic `Inspection` view. It renders
the selected frozen value with existing redaction, enumerates observed paths
within the scope, and forwards explanations, metadata, source records, and
resource contexts using native application paths.
A valid absent scope can be selected for history and comparison. Rendering an
absent effective value returns an error without output; explicit null renders
normally. Numeric key and index spellings with the same canonical JSON Pointer
select the same reporting location. Explicit queries retain their normal path
intent and can address values outside the focus. Source catalogs and ancestor
evidence remain available: the view is a reporting focus, not an isolation
boundary. Scoped path enumeration avoids copying unrelated effective metadata.
[Inspection API](../../inspection_view.go) · [Inspection contract](../config.md#layered-metadata)
`Inspection.Diff` compares views selecting the same location, including views
from different application root Go types. It uses the existing whole-snapshot
comparison and paired redaction, then retains differences at, below, or above
the focus. Sequences remain atomic: a retained ancestor difference can reflect
changes outside the selected descendant. Uninitialized views and mismatched
scopes return an error without records. Existing same-type `Diff[T]` is unchanged.
[Comparison contract](../config.md#effective-configuration-diffs)
The maintained [one-library](../../examples/consumers/result_component.go) and
[two-library](../../examples/consumers/result_composition.go) examples demonstrate
registration, one-load handoff, owned settings capture, and resource lookup from
effective source origins. [Consumer guidance](../consumers/README.md#component-handoff)
## Compatibility
These APIs are additive. Existing loading, composition, inspection, and shared
source-version behavior remains unchanged; existing callers need no migration.
The Go consumer minimum remains 1.27.0.
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/COPYRIGHT) | [LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/LICENSE) | [ATTRIBUTION](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/oss/attribution.md)

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

@@ -102,3 +102,29 @@ string equality must not be presented as semantic equality.
Keeping `Path` solely as an opaque query/building value remains an alternative.
No current contract changes or implementation commitment follow from this entry;
a comparison operation can be added compatibly later.
## 5. Single-file named overlays
Status: deferred. Consider supporting a single `overlays.yml` containing named
overlay bodies alongside the existing
[selected-overlay directory convention](../config.md#selected-overlays).
This would let small applications keep their overlays in one file. Planning was
tabled because the added semantics outweighed the immediate convenience; the
draft is preserved at `3e50388:docs/roadmap/overlays.md`.
The draft selected a direct name-to-body mapping, strict peer composition when
both storage forms contribute to the selected name, and file-level version
checks using the application's existing rule and mode. These provide a starting
point for reconsideration, not an implementation commitment.
### Questions to resolve before implementation
- Where should collection controls live: within each named body or at catalog
level, and how should that interact with document-root control ownership?
- How should configured version metadata paths coexist with overlay names,
including nested paths and modes that do not check overlay versions?
- Which semantic checks should apply to unselected bodies?
- Should `.yaml` also be recognized, and how should multiple matching files
interact?
- How should catalog lookup be enabled without disrupting successful loads that
previously ignored an adjacent `overlays.yml`?

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"
)
//go:embed testdata/native-source testdata/layered-bundle testdata/collection-bundle testdata/ordinary-imports testdata/source-version
//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
// BundledConfig is a small configuration loaded directly from an embedded file.

View File

@@ -0,0 +1,47 @@
package consumers
import (
"io/fs"
"path/filepath"
configkit "go.maximumdirect.net/configkit"
)
// CompanionConfig demonstrates independently bundled and operator prompt tiers.
type CompanionConfig struct {
Mode string `yaml:"mode"`
Prompts []CompanionPrompt `yaml:"prompts"`
}
type CompanionPrompt struct {
ID string `yaml:"id"`
Text string `yaml:"text"`
Note string `yaml:"note"`
}
// LoadCompanionConfig discovers a main file and binds operator imports and the
// selected overlay to its directory while retaining the embedded catalog tier.
func LoadCompanionConfig(mainPath, overlay string) (*configkit.Result[CompanionConfig], error) {
files, err := fs.Sub(bundledFiles, "testdata/main-relative-bundle")
if err != nil {
return nil, err
}
bundle := configkit.NewFilesystem("bundled catalog", files)
absolute, err := filepath.Abs(mainPath)
if err != nil {
return nil, err
}
declarations := map[string]any{"config": map[string]any{"imports": []any{
map[string]any{"path": "prompts.yml", "destination": []any{"prompts"}, "placement": "sequence-item"},
map[string]any{"dir": "operator", "recursive": true, "pattern": []any{"*.yml", "*.yaml"}, "destination": []any{"prompts"}, "placement": "sequence-item"},
}}}
main := configkit.SearchConfig("", configkit.Searches(configkit.SearchPaths(absolute)), configkit.SearchOptions{Required: true})
return configkit.LoadLayered(configkit.Input{Source: main}, configkit.LayeredOptions[CompanionConfig]{
Underlays: []configkit.Underlay{
{Inputs: []configkit.Input{{Source: bundle.File("catalog.yml")}}},
{Inputs: []configkit.Input{{Source: configkit.Mapping("operator imports", declarations), Imports: true, MainRelative: configkit.MainRelative()}}},
},
Overlay: overlay,
Definition: configkit.Definition[CompanionConfig]{SequenceIdentities: []configkit.SequenceIdentity{configkit.SequenceIdentityAt(configkit.Keys("prompts"), "id")}},
})
}

View File

@@ -0,0 +1,86 @@
package consumers_test
import (
"fmt"
"os"
"path/filepath"
"testing"
configkit "go.maximumdirect.net/configkit"
"go.maximumdirect.net/configkit/examples/consumers"
)
func Example_mainRelativeCompanions() {
result, err := consumers.LoadCompanionConfig(fixture("main-relative", "main.yml"), "live")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result.Config.Mode, result.Config.Prompts)
// Output: overlay [{shared operator replacement } {bundled bundled text } {local local text transitive detail}]
}
func TestMainRelativeStrictPeers(t *testing.T) {
root := t.TempDir()
for name, contents := range map[string]string{
"main.yml": "mode: main\n", "prompts.yml": "id: duplicate\ntext: first\n", "operator/second.yml": "id: duplicate\ntext: second\n",
} {
file := filepath.Join(root, name)
if err := os.MkdirAll(filepath.Dir(file), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(file, []byte(contents), 0600); err != nil {
t.Fatal(err)
}
}
_, err := consumers.LoadCompanionConfig(filepath.Join(root, "main.yml"), "")
if err == nil {
t.Fatal("duplicate peer identities succeeded")
}
for _, d := range err.(*configkit.LoadError).Diagnostics() {
if d.Code == configkit.CodeComposeConflict {
return
}
}
t.Fatalf("diagnostics = %#v", err.(*configkit.LoadError).Diagnostics())
}
func TestMainRelativeOptionalResources(t *testing.T) {
for _, tc := range []struct {
name string
file, directory, empty bool
count int
}{
{"neither", false, false, false, 2}, {"file", true, false, false, 3},
{"directory", false, true, false, 3}, {"both", true, true, false, 4}, {"empty directory", false, false, true, 2},
} {
t.Run(tc.name, func(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "main.yml"), []byte("mode: main\n"), 0600); err != nil {
t.Fatal(err)
}
if tc.file {
if err := os.WriteFile(filepath.Join(root, "prompts.yml"), []byte("id: file\ntext: file\n"), 0600); err != nil {
t.Fatal(err)
}
}
if tc.directory || tc.empty {
if err := os.Mkdir(filepath.Join(root, "operator"), 0700); err != nil {
t.Fatal(err)
}
}
if tc.directory {
if err := os.WriteFile(filepath.Join(root, "operator", "item.yaml"), []byte("id: directory\ntext: directory\n"), 0600); err != nil {
t.Fatal(err)
}
}
result, err := consumers.LoadCompanionConfig(filepath.Join(root, "main.yml"), "")
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if len(result.Config.Prompts) != tc.count {
t.Fatalf("prompts = %#v", result.Config.Prompts)
}
})
}
}

View File

@@ -0,0 +1,122 @@
package consumers
import (
"errors"
"io"
"io/fs"
"path"
"slices"
"strings"
configkit "go.maximumdirect.net/configkit"
)
// ComponentSettings is a library-owned configuration type embedded by an application.
type ComponentSettings struct {
Name string `yaml:"name"`
Resource string `yaml:"resource"`
Token string `yaml:"token"`
Entries []ComponentItem `yaml:"entries"`
}
// ComponentItem is one identified library setting.
type ComponentItem struct {
ID string `yaml:"id"`
Resource string `yaml:"resource"`
}
// ComponentApplication is the application-owned root for this example.
type ComponentApplication struct {
Component ComponentSettings `yaml:"component"`
}
// ComponentResult is the small interface required by the library at handoff.
type ComponentResult interface {
Value(configkit.Path) (any, bool)
Metadata() configkit.Metadata
SourceContext(string) (configkit.ResourceContext, bool)
}
// ComponentRuntime contains settings and captured resource data owned by the library.
type ComponentRuntime struct {
Settings ComponentSettings
Resource []byte
}
// ComponentDefinition registers library behavior through an application field selector.
func ComponentDefinition[T any](selectSettings func(*T) *ComponentSettings) configkit.Definition[T] {
component := configkit.Keys("component")
return configkit.Definition[T]{
SequenceIdentities: []configkit.SequenceIdentity{configkit.SequenceIdentityAt(component.Key("entries"), "id")},
Resolve: func(root *T, resolution *configkit.Resolution) error {
settings := selectSettings(root)
configkit.Default(resolution, component.Key("name"), &settings.Name, "default component", "use component default")
configkit.Normalize(resolution, component.Key("name"), &settings.Name, strings.TrimSpace(settings.Name), "trim component name")
return nil
},
Validate: func(root *T, validation *configkit.Validation) {
if selectSettings(root).Name == "" {
validation.Error(component.Key("name"), "component name is required")
}
},
Sensitive: func(path configkit.Path) bool { return path.String() == "/component/token" },
}
}
// LoadComponentApplication assembles one application load with bundled underlay defaults.
func LoadComponentApplication(source configkit.Source) (*configkit.Result[ComponentApplication], error) {
return configkit.LoadLayered(configkit.Input{Source: source}, configkit.LayeredOptions[ComponentApplication]{
Underlays: []configkit.Underlay{{Inputs: []configkit.Input{{Source: configkit.Bytes("component defaults", []byte("component: {entries: [{id: default}]}\n"))}}}},
Definition: ComponentDefinition(func(root *ComponentApplication) *ComponentSettings { return &root.Component }),
})
}
// NewComponent accepts the entire result, selects library settings, and captures
// a resource relative to the effective field's original source.
func NewComponent(result ComponentResult) (ComponentRuntime, error) {
value, ok := result.Value(configkit.Keys("component"))
settings, typed := value.(ComponentSettings)
if !ok || !typed {
return ComponentRuntime{}, errors.New("component settings unavailable")
}
settings.Entries = slices.Clone(settings.Entries)
info, ok := result.Metadata().Lookup(configkit.Keys("component", "resource"))
if !ok || len(info.Origin.Locations) != 1 {
return ComponentRuntime{}, errors.New("component resource origin unavailable")
}
context, ok := result.SourceContext(info.Origin.Locations[0].SourceID)
if !ok {
return ComponentRuntime{}, errors.New("component resource context unavailable")
}
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, settings.Resource))
if err != nil {
return ComponentRuntime{}, err
}
return ComponentRuntime{Settings: settings, Resource: data}, nil
}
// ComponentInspection is a library-owned facade over one selected reporting view.
type ComponentInspection struct{ view configkit.Inspection }
// InspectComponent selects the library's conventional reporting scope once.
func InspectComponent(result interface {
InspectSubtree(configkit.Path) (configkit.Inspection, bool)
}) (ComponentInspection, bool) {
view, ok := result.InspectSubtree(configkit.Keys("component"))
return ComponentInspection{view: view}, ok
}
// WriteEffective renders the frozen component safely.
func (i ComponentInspection) WriteEffective(output io.Writer) error {
return i.view.WriteEffective(output)
}
// Explain forwards native application paths without changing their meaning.
func (i ComponentInspection) Explain(path configkit.Path) (configkit.Explanation, bool) {
return i.view.Explain(path)
}
// Diff compares two frozen component views.
func (i ComponentInspection) Diff(other ComponentInspection) ([]configkit.Difference, error) {
return i.view.Diff(other.view)
}

View File

@@ -0,0 +1,57 @@
package consumers
import (
"bytes"
"strings"
"testing"
"testing/fstest"
configkit "go.maximumdirect.net/configkit"
)
func TestComponentHandoff(t *testing.T) {
filesystem := configkit.NewFilesystem("application", fstest.MapFS{
"config/main.yml": &fstest.MapFile{Data: []byte("component: {name: ' example ', resource: asset.txt, token: disposable-canary}\n")},
"config/asset.txt": &fstest.MapFile{Data: []byte("resource data")},
})
result, err := LoadComponentApplication(filesystem.File("config/main.yml"))
if err != nil {
t.Fatal(err)
}
runtime, err := NewComponent(result)
if err != nil {
t.Fatal(err)
}
if runtime.Settings.Name != "example" || len(runtime.Settings.Entries) != 1 || runtime.Settings.Entries[0].ID != "default" || string(runtime.Resource) != "resource data" {
t.Fatalf("component runtime = %#v", runtime)
}
runtime.Settings.Entries[0].ID = "runtime change"
if result.Config.Component.Entries[0].ID != "default" {
t.Fatal("runtime settings share the result's slice")
}
entries, found := result.Metadata().Lookup(configkit.Keys("component", "entries"))
if !result.Metadata().IsExplicit(configkit.Keys("component", "resource")) || !found || entries.Origin.Layer != configkit.LayerUnderlay {
t.Fatal("presence did not retain source distinction")
}
view, ok := InspectComponent(result)
if !ok {
t.Fatal("component view unavailable")
}
var output bytes.Buffer
if err := view.WriteEffective(&output); err != nil {
t.Fatal(err)
}
if strings.Contains(output.String(), "disposable-canary") || !strings.Contains(output.String(), "example") {
t.Fatalf("unsafe report: %s", output.String())
}
if _, ok := view.Explain(configkit.Keys("component", "resource")); !ok {
t.Fatal("resource explanation unavailable")
}
if diff, err := view.Diff(view); err != nil || len(diff) != 0 {
t.Fatalf("view diff = %#v, %v", diff, err)
}
_, err = LoadComponentApplication(configkit.Bytes("invalid.yml", []byte("component: {name: ' '}\n")))
if err == nil {
t.Fatal("component validation did not fail")
}
}

View File

@@ -0,0 +1,86 @@
package consumers
import (
"errors"
"strings"
configkit "go.maximumdirect.net/configkit"
)
// AuditSettings is a second library's independent configuration type.
type AuditSettings struct {
Enabled bool `yaml:"enabled"`
Rules []AuditRule `yaml:"rules"`
}
// AuditRule has an identity used by the application's assembly policy.
type AuditRule struct {
ID string `yaml:"id"`
}
// ComposedApplication combines application and two library settings.
type ComposedApplication struct {
Label string `yaml:"label"`
Component ComponentSettings `yaml:"component"`
Audit AuditSettings `yaml:"audit"`
}
// AuditResult is the smaller interface needed by the audit consumer.
type AuditResult interface {
Value(configkit.Path) (any, bool)
}
// NewAuditSettings takes a copy of the second library's settings.
func NewAuditSettings(result AuditResult) (AuditSettings, error) {
value, ok := result.Value(configkit.Keys("audit"))
settings, typed := value.(AuditSettings)
if !ok || !typed {
return AuditSettings{}, errors.New("audit settings unavailable")
}
settings.Rules = append([]AuditRule(nil), settings.Rules...)
return settings, nil
}
func auditDefinition[T any](selectSettings func(*T) *AuditSettings) configkit.Definition[T] {
audit := configkit.Keys("audit")
return configkit.Definition[T]{
SequenceIdentities: []configkit.SequenceIdentity{configkit.SequenceIdentityAt(audit.Key("rules"), "id")},
Resolve: func(root *T, resolution *configkit.Resolution) error {
configkit.Default(resolution, audit.Key("enabled"), &selectSettings(root).Enabled, true, "enable audit by default")
return nil
},
Validate: func(root *T, validation *configkit.Validation) {
if selectSettings(root).Enabled && len(selectSettings(root).Rules) == 0 {
validation.Error(audit.Key("rules"), "enabled audit requires a rule")
}
},
}
}
// LoadComposedApplication applies application and library callbacks in order in
// one load. A placed component input remains an ordinary underlay.
func LoadComposedApplication(main, component configkit.Input) (*configkit.Result[ComposedApplication], error) {
componentRules := ComponentDefinition(func(root *ComposedApplication) *ComponentSettings { return &root.Component })
auditRules := auditDefinition(func(root *ComposedApplication) *AuditSettings { return &root.Audit })
identities := append(componentRules.SequenceIdentities, auditRules.SequenceIdentities...)
definition := configkit.Definition[ComposedApplication]{
SequenceIdentities: identities,
Sensitive: componentRules.Sensitive,
Resolve: func(root *ComposedApplication, resolution *configkit.Resolution) error {
configkit.Normalize(resolution, configkit.Keys("label"), &root.Label, strings.TrimSpace(root.Label), "trim application label")
if err := componentRules.Resolve(root, resolution); err != nil {
return err
}
return auditRules.Resolve(root, resolution)
},
Validate: func(root *ComposedApplication, validation *configkit.Validation) {
if root.Label == "" {
validation.Error(configkit.Keys("label"), "application label is required")
}
componentRules.Validate(root, validation)
auditRules.Validate(root, validation)
},
}
component.Destination = configkit.Keys("component")
return configkit.LoadLayered(main, configkit.LayeredOptions[ComposedApplication]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{component}}}, Definition: definition})
}

View File

@@ -0,0 +1,69 @@
package consumers
import (
"io/fs"
"path"
"testing"
"testing/fstest"
configkit "go.maximumdirect.net/configkit"
)
func TestComposedConsumersShareOneLoad(t *testing.T) {
filesystem := configkit.NewFilesystem("components", fstest.MapFS{
"config/component.yml": &fstest.MapFile{Data: []byte("name: ' component '\nresource: asset.txt\nentries:\n - {id: parent, resource: asset.txt}\n - {id: child, extends: {id: parent}}\n")},
"config/asset.txt": &fstest.MapFile{Data: []byte("shared asset")},
})
component := configkit.Input{Source: filesystem.File("config/component.yml")}
load := func(main string) *configkit.Result[ComposedApplication] {
t.Helper()
result, err := LoadComposedApplication(configkit.Input{Source: configkit.Bytes("app.yml", []byte(main))}, component)
if err != nil {
t.Fatal(err)
}
return result
}
first := load("label: ' app '\naudit: {enabled: false, rules: [{id: first}]}\n")
second := load("label: second\naudit: {rules: [{id: second}]}\n")
componentRuntime, err := NewComponent(first)
if err != nil {
t.Fatal(err)
}
audit, err := NewAuditSettings(first)
if err != nil {
t.Fatal(err)
}
if first.Config.Label != "app" || componentRuntime.Settings.Name != "component" || string(componentRuntime.Resource) != "shared asset" || audit.Enabled || audit.Rules[0].ID != "first" {
t.Fatalf("first result = %#v %#v", componentRuntime, audit)
}
secondAudit, err := NewAuditSettings(second)
if err != nil || !secondAudit.Enabled || secondAudit.Rules[0].ID != "second" || audit.Enabled {
t.Fatalf("second audit = %#v, %v", secondAudit, err)
}
resource := configkit.Keys("component", "entries").Index(1).Key("resource")
info, ok := first.Metadata().Lookup(resource)
if !ok || len(info.Origin.Inheritance) == 0 || len(info.Origin.Locations) == 0 {
t.Fatalf("inherited origin = %#v, %v", info, ok)
}
context, ok := first.SourceContext(info.Origin.Locations[0].SourceID)
if !ok {
t.Fatal("resource context unavailable")
}
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, first.Config.Component.Entries[1].Resource))
if err != nil || string(data) != "shared asset" {
t.Fatalf("inherited resource = %q, %v", data, err)
}
_, err = LoadComposedApplication(configkit.Input{Source: configkit.Bytes("invalid.yml", []byte("label: app\naudit: {rules: [{id: same}, {id: same}]}\n"))}, component)
if err == nil {
t.Fatal("duplicate audit identities accepted")
}
badComponent := configkit.Input{Source: configkit.Bytes("bad-component.yml", []byte("name: good\nentries: [{id: duplicate}, {id: duplicate}]\n"))}
_, err = LoadComposedApplication(configkit.Input{Source: configkit.Bytes("app.yml", []byte("label: app\naudit: {rules: [{id: valid}]}\n"))}, badComponent)
if err == nil {
t.Fatal("duplicate component identities accepted")
}
_, err = LoadComposedApplication(configkit.Input{Source: configkit.Bytes("invalid.yml", []byte("label: ' '\naudit: {rules: [{id: valid}]}\n"))}, component)
if err == nil {
t.Fatal("application validation did not run")
}
}

View File

@@ -0,0 +1,18 @@
package consumers
import configkit "go.maximumdirect.net/configkit"
// StartupConfig demonstrates an environment-backed credential and ordinary data.
type StartupConfig struct {
Name string `yaml:"name"`
Token configkit.Secret `yaml:"token"`
}
// PrepareStartup performs the explicit bootstrap once and returns a captured
// main that can be passed to either Load or LoadLayered as its main source.
// The caller should handle a non-nil report even if preparation fails.
func PrepareStartup(main configkit.Source, root string) (*configkit.SecretsReport, configkit.Source, error) {
return configkit.LoadSecretsIntoEnvironmentFromConfig(main, configkit.SecretsFromConfigOptions{
Filesystem: &configkit.FilesystemContext{Root: root},
})
}

View File

@@ -0,0 +1,41 @@
package consumers_test
import (
"os"
"path/filepath"
"testing"
configkit "go.maximumdirect.net/configkit"
"go.maximumdirect.net/configkit/examples/consumers"
)
func TestConfiguredSecretsStartup(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "secrets"), 0o700); err != nil {
t.Fatal(err)
}
const name = "CONFIGKIT_EXAMPLE_STARTUP_SECRET"
t.Setenv(name, "")
if err := os.WriteFile(filepath.Join(root, "secrets", name), []byte("example-value\n"), 0o600); err != nil {
t.Fatal(err)
}
main := filepath.Join(root, "main.yml")
if err := os.WriteFile(main, []byte("config: {secrets_dir: secrets, secrets_overwrite: true}\nname: app\ntoken: "+name+"\n"), 0o600); err != nil {
t.Fatal(err)
}
search := configkit.SearchConfig("app", configkit.SearchPaths(main))
report, prepared, err := consumers.PrepareStartup(search, root)
if err != nil || len(report.Entries()) != 1 || report.Entries()[0].Status != configkit.SecretFileLoaded {
t.Fatalf("prepare = %#v, %v", report, err)
}
ordinary, err := configkit.Load[consumers.StartupConfig](prepared)
if err != nil || ordinary.Config.Name != "app" || ordinary.Config.Token.Value() != "example-value" {
t.Fatalf("ordinary load = %#v, %v", ordinary, err)
}
layered, err := configkit.LoadLayered(configkit.Input{Source: prepared}, configkit.LayeredOptions[consumers.StartupConfig]{
Underlays: []configkit.Underlay{{Inputs: []configkit.Input{{Source: configkit.Bytes("defaults", []byte("name: default\n"))}}}},
})
if err != nil || layered.Config.Name != "app" || layered.Config.Token.Value() != "example-value" {
t.Fatalf("layered load = %#v, %v", layered, err)
}
}

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,7 @@
mode: embedded
prompts:
- id: shared
text: embedded text
note: replaced
- id: bundled
text: bundled text

View File

@@ -0,0 +1 @@
mode: main

View File

@@ -0,0 +1,5 @@
config:
imports:
- path: ../../shared/extra.yml
id: local
text: local text

View File

@@ -0,0 +1 @@
mode: overlay

View File

@@ -0,0 +1,2 @@
id: shared
text: operator replacement

View File

@@ -0,0 +1 @@
note: transitive detail

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

@@ -1,6 +1,8 @@
package configkit_test
import (
"errors"
"os"
"strings"
"testing"
"testing/fstest"
@@ -8,6 +10,72 @@ import (
configkit "go.maximumdirect.net/configkit"
)
func TestMainBootstrapControlsAreConsumedWithoutEnvironmentWrites(t *testing.T) {
t.Setenv("CONFIGKIT_CONTROL_SENTINEL", "unchanged")
type nested struct {
Config struct {
Directory string `yaml:"secrets_dir"`
} `yaml:"config"`
}
type app struct {
Service nested `yaml:"service"`
}
for _, imports := range []bool{false, true} {
body := "config: {secrets_dir: missing, secrets_overwrite: true}\nservice: {config: {secrets_dir: ordinary}}\n"
fs := configkit.NewFilesystem("bundle", fstest.MapFS{"main.yml": {Data: []byte(body)}})
result, err := configkit.Load[app](fs.File("main.yml"), configkit.Options[app]{Imports: imports})
if err != nil || result.Config.Service.Config.Directory != "ordinary" || os.Getenv("CONFIGKIT_CONTROL_SENTINEL") != "unchanged" {
t.Fatalf("imports %v: result = %#v, error = %v", imports, result, err)
}
}
}
func TestBootstrapControlsRejectMisplacedAndMalformedValues(t *testing.T) {
for _, test := range []struct {
name, body string
code configkit.Code
path string
}{
{"directory", "config: {secrets_dir: null}\n", configkit.CodeSecretsInvalidPath, "/config/secrets_dir"},
{"overwrite", "config: {secrets_overwrite: 'false'}\n", configkit.CodeSecretsInvalidValue, "/config/secrets_overwrite"},
} {
t.Run(test.name, func(t *testing.T) {
_, err := configkit.Load[struct{}](configkit.Bytes("main", []byte(test.body)))
var loadErr *configkit.LoadError
if !errors.As(err, &loadErr) || len(loadErr.Diagnostics()) != 1 || loadErr.Diagnostics()[0].Code != test.code || loadErr.Diagnostics()[0].Path.String() != test.path || loadErr.Diagnostics()[0].Primary == nil {
t.Fatalf("error = %#v", err)
}
})
}
fs := configkit.NewFilesystem("bundle", fstest.MapFS{
"main.yml": {Data: []byte("config: {imports: [{path: other.yml}]}\n")},
"other.yml": {Data: []byte("config: {secrets_overwrite: false}\n")},
})
_, err := configkit.Load[struct{}](fs.File("main.yml"), configkit.Options[struct{}]{Imports: true})
var loadErr *configkit.LoadError
if !errors.As(err, &loadErr) || len(loadErr.Diagnostics()) != 1 || loadErr.Diagnostics()[0].Code != configkit.CodeImportInvalid || loadErr.Diagnostics()[0].Path.String() != "/config/secrets_overwrite" {
t.Fatalf("import error = %#v", err)
}
_, err = configkit.LoadLayered(configkit.Input{Source: configkit.Bytes("main", []byte("{}\n"))}, configkit.LayeredOptions[struct{}]{
Underlays: []configkit.Underlay{{Inputs: []configkit.Input{{Source: configkit.Bytes("underlay", []byte("config: {secrets_dir: secrets}\n"))}}}},
})
if !errors.As(err, &loadErr) || len(loadErr.Diagnostics()) != 1 || loadErr.Diagnostics()[0].Code != configkit.CodeImportInvalid {
t.Fatalf("underlay error = %#v", err)
}
overlays := configkit.NewFilesystem("overlays", fstest.MapFS{
"main.yml": {Data: []byte("{}\n")},
"overlays/dev.yml": {Data: []byte("config: {secrets_overwrite: false}\n")},
})
_, err = configkit.Load[struct{}](overlays.File("main.yml"), configkit.Options[struct{}]{Overlay: "dev"})
if !errors.As(err, &loadErr) || len(loadErr.Diagnostics()) != 1 || loadErr.Diagnostics()[0].Code != configkit.CodeOverlayDirective || loadErr.Diagnostics()[0].Primary == nil {
t.Fatalf("overlay error = %#v", err)
}
_, err = configkit.Load[struct{}](configkit.Bytes("main", []byte("config: {imports: [], secrets_overwrite: false}\n")))
if !errors.As(err, &loadErr) || len(loadErr.Diagnostics()) != 1 || loadErr.Diagnostics()[0].Code != configkit.CodeImportDisabled {
t.Fatalf("disabled imports error = %#v", err)
}
}
func TestDocumentRootControlsAndNestedApplicationConfig(t *testing.T) {
type settings struct {
Imports string `yaml:"imports"`

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

@@ -0,0 +1,96 @@
package configkit_test
import (
"strings"
"testing"
configkit "go.maximumdirect.net/configkit"
)
func TestInspectionViewDiff(t *testing.T) {
type first struct {
Component map[string]any `yaml:"component"`
Sibling string `yaml:"sibling"`
Items []string `yaml:"items"`
}
type second struct {
Component map[string]any `yaml:"component"`
Sibling string `yaml:"sibling"`
Items []string `yaml:"items"`
}
left, err := configkit.Load[first](configkit.Bytes("left.yml", []byte("component: {name: before, gone: null}\nsibling: old\nitems: [a, b]\n")))
if err != nil {
t.Fatal(err)
}
right, err := configkit.Load[second](configkit.Bytes("right.yml", []byte("component: {name: after, added: null}\nsibling: new\nitems: [a, c]\n")))
if err != nil {
t.Fatal(err)
}
lv, _ := left.InspectSubtree(configkit.Keys("component"))
rv, _ := right.InspectSubtree(configkit.Keys("component"))
diff, err := lv.Diff(rv)
if err != nil || len(diff) != 3 || diff[0].Path.String() != "/component/added" || diff[1].Path.String() != "/component/gone" || diff[2].Path.String() != "/component/name" {
t.Fatalf("component diff = %#v, %v", diff, err)
}
if diff[0].Left.Present || !diff[0].Right.Present || !diff[1].Left.Present || diff[1].Right.Present {
t.Fatalf("null and absence = %#v", diff)
}
sequenceLeft, _ := left.InspectSubtree(configkit.Keys("items").Index(0))
sequenceRight, _ := right.InspectSubtree(configkit.Keys("items", "0"))
diff, err = sequenceLeft.Diff(sequenceRight)
if err != nil || len(diff) != 1 || diff[0].Path.String() != "/items" {
t.Fatalf("sequence ancestor = %#v, %v", diff, err)
}
missingLeft, _ := left.InspectSubtree(configkit.Keys("absent"))
missingRight, _ := right.InspectSubtree(configkit.Keys("absent"))
if diff, err = missingLeft.Diff(missingRight); err != nil || len(diff) != 0 {
t.Fatalf("absent diff = %#v, %v", diff, err)
}
if diff, err = lv.Diff(missingRight); err == nil || diff != nil {
t.Fatalf("mismatched diff = %#v, %v", diff, err)
}
if diff, err = (configkit.Inspection{}).Diff(lv); err == nil || diff != nil {
t.Fatalf("zero diff = %#v, %v", diff, err)
}
rootLeft, _ := left.InspectSubtree(configkit.Path{})
rootRight, _ := right.InspectSubtree(configkit.Path{})
if diff, err = rootLeft.Diff(rootRight); err != nil || len(diff) != 5 {
t.Fatalf("root diff = %#v, %v", diff, err)
}
if diff, err = lv.Diff(lv); err != nil || len(diff) != 0 {
t.Fatalf("equal diff = %#v, %v", diff, err)
}
}
func TestInspectionViewDiffRedactionAndShape(t *testing.T) {
load := func(input string, sensitive bool) *configkit.Result[map[string]any] {
t.Helper()
result, err := configkit.Load(configkit.Bytes("view.yml", []byte(input)), configkit.Options[map[string]any]{Definition: configkit.Definition[map[string]any]{Sensitive: func(path configkit.Path) bool { return sensitive && path.String() == "/component" }}})
if err != nil {
t.Fatal(err)
}
return result
}
left := load("component: {token: disposable-canary-left}\n", true)
right := load("component: {token: disposable-canary-right}\n", false)
lv, _ := left.InspectSubtree(configkit.Keys("component", "token"))
rv, _ := right.InspectSubtree(configkit.Keys("component", "token"))
diff, err := lv.Diff(rv)
if err != nil || len(diff) != 1 || !diff[0].Left.Redacted || !diff[0].Right.Redacted || !diff[0].HiddenChanged || strings.Contains(diff[0].Left.YAML+diff[0].Right.YAML, "disposable-canary") {
t.Fatalf("sensitive diff = %#v, %v", diff, err)
}
removed := load("other: public\n", false)
removedView, _ := removed.InspectSubtree(configkit.Keys("component", "token"))
diff, err = lv.Diff(removedView)
if err != nil || len(diff) != 1 || diff[0].Right.Present || !diff[0].Left.Redacted || strings.Contains(diff[0].Left.YAML, "disposable-canary") {
t.Fatalf("sensitive removal = %#v, %v", diff, err)
}
left = load("component: {'0': old}\n", false)
right = load("component: [new]\n", false)
lv, _ = left.InspectSubtree(configkit.Keys("component", "0"))
rv, _ = right.InspectSubtree(configkit.Keys("component").Index(0))
diff, err = lv.Diff(rv)
if err != nil || len(diff) != 1 || diff[0].Path.String() != "/component" {
t.Fatalf("shape diff = %#v, %v", diff, err)
}
}

View File

@@ -0,0 +1,134 @@
package configkit_test
import (
"bytes"
"io/fs"
"path"
"reflect"
"strings"
"testing"
"testing/fstest"
configkit "go.maximumdirect.net/configkit"
)
func TestInspectionViewHistoryAndResourceOwnership(t *testing.T) {
filesystem := configkit.NewFilesystem("component", fstest.MapFS{
"config/settings.yml": &fstest.MapFile{Data: []byte("entries:\n parent: {resource: asset.txt, removed: old}\n child: {extends: parent}\nsibling: retained\n")},
"config/asset.txt": &fstest.MapFile{Data: []byte("asset contents")},
})
load := func() *configkit.Result[map[string]any] {
t.Helper()
result, err := configkit.LoadLayered(configkit.Input{Source: filesystem.File("config/settings.yml"), Destination: configkit.Keys("component")}, configkit.LayeredOptions[map[string]any]{Definition: configkit.Definition[map[string]any]{
Resolve: func(current *map[string]any, resolution *configkit.Resolution) error {
child := (*current)["component"].(map[string]any)["entries"].(map[string]any)["child"].(map[string]any)
delete(child, "removed")
resolution.RecordNormalization(configkit.Keys("component", "entries", "child", "removed"), "remove old setting")
return nil
},
}})
if err != nil {
t.Fatal(err)
}
return result
}
result, other := load(), load()
scope := configkit.Keys("component", "entries", "child")
view, ok := result.InspectSubtree(scope)
if !ok {
t.Fatal("view unavailable")
}
removed := scope.Key("removed")
resource := scope.Key("resource")
paths := []string{}
for _, p := range view.HistoricalPaths() {
paths = append(paths, p.String())
}
if !strings.Contains(strings.Join(paths, ","), removed.String()) {
t.Fatalf("removed history missing: %v", paths)
}
if _, ok := view.Metadata().Lookup(removed); ok {
t.Fatal("removed value is effective")
}
explanation, ok := view.Explain(removed)
if !ok || explanation.Effective.Present || len(explanation.History) == 0 {
t.Fatalf("removed explanation = %#v, %v", explanation, ok)
}
if len(view.Metadata().History(removed)) == 0 {
t.Fatal("removed history missing")
}
info, ok := view.Metadata().Lookup(resource)
if !ok || len(info.Origin.Locations) == 0 || len(info.Origin.Inheritance) == 0 {
t.Fatalf("inherited origin = %#v, %v", info, ok)
}
id := info.Origin.Locations[0].SourceID
context, ok := view.SourceContext(id)
if !ok {
t.Fatal("source context missing")
}
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, "asset.txt"))
if err != nil || string(data) != "asset contents" {
t.Fatalf("resource = %q, %v", data, err)
}
if _, ok := view.Source(id); !ok {
t.Fatal("source containing sibling missing")
}
before := bytes.Buffer{}
if err := view.WriteEffective(&before); err != nil {
t.Fatal(err)
}
otherView, _ := other.InspectSubtree(scope)
child := result.Config["component"].(map[string]any)["entries"].(map[string]any)["child"].(map[string]any)
child["resource"] = "changed"
if value, _ := result.Value(resource); value != "changed" {
t.Fatalf("current value = %v", value)
}
after := bytes.Buffer{}
if err := view.WriteEffective(&after); err != nil || !bytes.Equal(before.Bytes(), after.Bytes()) {
t.Fatalf("view changed = %q, %v", after.String(), err)
}
if diff, err := view.Diff(otherView); err != nil || len(diff) != 0 {
t.Fatalf("frozen diff = %#v, %v", diff, err)
}
info.Origin.Locations[0].SourceID = "changed"
again, _ := view.Metadata().Lookup(resource)
if again.Origin.Locations[0].SourceID != id {
t.Fatal("metadata was not detached")
}
explanation.Effective.YAML = "changed"
againExplanation, _ := view.Explain(removed)
if reflect.DeepEqual(explanation, againExplanation) {
t.Fatal("explanation was not detached")
}
}
func TestInspectionViewHistoricalNumericScope(t *testing.T) {
result, err := configkit.Load(configkit.Bytes("shape.yml", []byte("component: {'0': {old: value}}\n")), configkit.Options[map[string]any]{Definition: configkit.Definition[map[string]any]{
Resolve: func(current *map[string]any, resolution *configkit.Resolution) error {
(*current)["component"] = []any{map[string]any{"new": "value"}}
resolution.RecordNormalization(configkit.Keys("component"), "change shape")
return nil
},
}})
if err != nil {
t.Fatal(err)
}
key, _ := result.InspectSubtree(configkit.Keys("component", "0"))
index, _ := result.InspectSubtree(configkit.Keys("component").Index(0))
if !reflect.DeepEqual(key.HistoricalPaths(), index.HistoricalPaths()) {
t.Fatal("numeric reporting scopes differ")
}
var paths []string
for _, p := range key.HistoricalPaths() {
paths = append(paths, p.String())
}
if !strings.Contains(strings.Join(paths, ","), "/component/0/old") || !strings.Contains(strings.Join(paths, ","), "/component/0/new") {
t.Fatalf("shape history = %v", paths)
}
if _, ok := key.Metadata().Lookup(configkit.Keys("component", "0", "new")); ok {
t.Fatal("explicit key query changed intent")
}
if _, ok := key.Metadata().Lookup(configkit.Keys("component").Index(0).Key("new")); !ok {
t.Fatal("index query failed")
}
}

View File

@@ -0,0 +1,153 @@
package configkit_test
import (
"bytes"
"errors"
"reflect"
"strings"
"testing"
configkit "go.maximumdirect.net/configkit"
)
func TestInspectionViewScopeAndQueries(t *testing.T) {
result, err := configkit.Load[map[string]any](configkit.Bytes("view.yml", []byte("a: {child: one}\nab: two\nitems: [{name: first}]\n'a/b': {'': value}\n")))
if err != nil {
t.Fatal(err)
}
view, ok := result.InspectSubtree(configkit.Keys("a"))
if !ok {
t.Fatal("view unavailable")
}
var paths []string
for _, path := range view.HistoricalPaths() {
paths = append(paths, path.String())
}
if !reflect.DeepEqual(paths, []string{"/a", "/a/child"}) {
t.Fatalf("scope paths = %#v", paths)
}
if _, ok := view.Metadata().Lookup(configkit.Keys("ab")); !ok {
t.Fatal("metadata filtered")
}
if _, ok := view.Explain(configkit.Keys("ab")); !ok {
t.Fatal("native query filtered")
}
var output bytes.Buffer
if err := view.WriteExplanation(&output, configkit.Keys("ab")); err != nil {
t.Fatal(err)
}
if len(view.Sources()) != len(result.Sources()) || len(view.Sources()) == 0 {
t.Fatal("sources filtered")
}
if _, ok := view.Source(view.Sources()[0].ID); !ok {
t.Fatal("source unavailable")
}
if _, ok := result.InspectSubtree(configkit.Keys("absent")); !ok {
t.Fatal("absent scope rejected")
}
if _, ok := result.InspectSubtree(configkit.Path{}.Index(-1)); ok {
t.Fatal("invalid scope accepted")
}
keyScope, _ := result.InspectSubtree(configkit.Keys("items", "0"))
indexScope, _ := result.InspectSubtree(configkit.Keys("items").Index(0))
if !reflect.DeepEqual(keyScope.HistoricalPaths(), indexScope.HistoricalPaths()) {
t.Fatal("numeric scope differs")
}
escaped, _ := result.InspectSubtree(configkit.Keys("a/b", ""))
if got := escaped.HistoricalPaths(); len(got) != 1 || got[0].String() != "/a~1b/" {
t.Fatalf("escaped scope = %#v", got)
}
root, _ := result.InspectSubtree(configkit.Path{})
if !reflect.DeepEqual(root.HistoricalPaths(), result.Metadata().HistoricalPaths()) {
t.Fatal("root scope filtered")
}
}
type viewFailWriter struct{}
func (viewFailWriter) Write([]byte) (int, error) { return 0, errors.New("write failed") }
func TestInspectionViewWriteEffective(t *testing.T) {
options := configkit.Options[map[string]any]{Definition: configkit.Definition[map[string]any]{
Sensitive: func(path configkit.Path) bool { return path.String() == "/private" || path.String() == "/nested/token" },
Resolve: func(current *map[string]any, resolution *configkit.Resolution) error {
delete(*current, "removed")
resolution.RecordNormalization(configkit.Keys("removed"), "remove")
return nil
},
}}
result, err := configkit.Load(configkit.Bytes("view.yml", []byte("private: {child: canary-private}\nnested: {token: canary-token, name: public}\nitems: [zero, one]\n'0': numeric\n'null': null\nremoved: earlier\n")), options)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
path configkit.Path
contains string
absent string
fails bool
}{
{configkit.Path{}, "public", "canary-token", false},
{configkit.Keys("nested"), "public", "canary-token", false},
{configkit.Keys("private", "child"), "REDACTED", "canary-private", false},
{configkit.Keys("items"), "one", "", false},
{configkit.Keys("items").Index(1), "one", "", false},
{configkit.Path{}.Index(0), "numeric", "", false},
{configkit.Keys("null"), "null", "", false},
{configkit.Keys("removed"), "", "", true},
{configkit.Keys("missing"), "", "", true},
} {
view, ok := result.InspectSubtree(tc.path)
if !ok {
t.Fatal("view unavailable")
}
var out bytes.Buffer
err := view.WriteEffective(&out)
if (err != nil) != tc.fails || (tc.fails && out.Len() != 0) || (tc.contains != "" && !strings.Contains(out.String(), tc.contains)) || (tc.absent != "" && strings.Contains(out.String(), tc.absent)) {
t.Errorf("%s: %q, %v", tc.path.String(), out.String(), err)
}
}
view, _ := result.InspectSubtree(configkit.Keys("nested"))
result.Config["nested"] = "changed"
var out bytes.Buffer
if err := view.WriteEffective(&out); err != nil || !strings.Contains(out.String(), "public") {
t.Fatalf("frozen output = %q, %v", out.String(), err)
}
if err := view.WriteEffective(viewFailWriter{}); err == nil {
t.Fatal("writer error lost")
}
if err := view.WriteEffective(nil); err == nil {
t.Fatal("nil writer accepted")
}
if err := (configkit.Inspection{}).WriteEffective(&bytes.Buffer{}); err == nil {
t.Fatal("zero view accepted")
}
}
func TestInspectionViewUnavailable(t *testing.T) {
var result *configkit.Result[map[string]any]
if _, ok := result.InspectSubtree(configkit.Path{}); ok {
t.Fatal("nil result accepted")
}
if _, ok := (&configkit.Result[map[string]any]{}).InspectSubtree(configkit.Path{}); ok {
t.Fatal("manual result accepted")
}
var view configkit.Inspection
if len(view.HistoricalPaths()) != 0 || view.Sources() != nil {
t.Fatal("zero view returned records")
}
if _, ok := view.Metadata().Lookup(configkit.Path{}); ok {
t.Fatal("zero metadata")
}
if _, ok := view.Source("source-1"); ok {
t.Fatal("zero source")
}
if _, ok := view.SourceContext("source-1"); ok {
t.Fatal("zero source context")
}
if _, ok := view.Explain(configkit.Path{}); ok {
t.Fatal("zero explanation")
}
if err := view.WriteExplanation(&bytes.Buffer{}, configkit.Path{}); err == nil {
t.Fatal("zero explanation rendering")
}
}

View File

@@ -0,0 +1,253 @@
package configkit_test
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
configkit "go.maximumdirect.net/configkit"
)
func TestMainRelativeStandaloneRejectsInaccessibleHostRoot(t *testing.T) {
root := t.TempDir()
mainPath := filepath.Join(root, "main.yml")
if err := os.WriteFile(mainPath, []byte("count: 1\n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Chmod(root, 0100); err != nil {
t.Skipf("cannot set search-only permissions: %v", err)
}
t.Cleanup(func() {
if err := os.Chmod(root, 0700); err != nil {
t.Error(err)
}
})
handle, err := os.OpenRoot(root)
if err == nil {
_ = handle.Close()
t.Skip("host allows opening this search-only directory")
}
if !errors.Is(err, os.ErrPermission) {
t.Fatalf("open root = %v, want permission denied", err)
}
if _, err := os.ReadFile(mainPath); err != nil {
t.Skipf("main must remain readable by name: %v", err)
}
main := configkit.Input{Source: configkit.File(mainPath)}
for _, tc := range []struct {
name string
filesystem *configkit.FilesystemContext
}{
{name: "derived"},
{name: "explicit", filesystem: &configkit.FilesystemContext{Root: root, BaseDir: root}},
} {
t.Run(tc.name, func(t *testing.T) {
underlay := configkit.Input{
Source: configkit.Bytes("companion", []byte("{}\n")),
MainRelative: &configkit.MainRelativeContext{RequireBase: true},
Filesystem: tc.filesystem,
}
_, err := configkit.LoadLayered(main, configkit.LayeredOptions[layeredFacadeConfig]{
Underlays: []configkit.Underlay{{Inputs: []configkit.Input{underlay}}},
})
var failure *configkit.LoadError
if !errors.As(err, &failure) {
t.Fatalf("error = %v, want a load error", err)
}
diagnostics := failure.Diagnostics()
if len(diagnostics) != 1 || diagnostics[0].Code != configkit.CodeImportPermission {
t.Fatalf("diagnostics = %#v, want import.permission", diagnostics)
}
})
}
}
func TestMainRelativeDiscoveryAndEvidence(t *testing.T) {
root := t.TempDir()
first, second := filepath.Join(root, "first"), filepath.Join(root, "second")
for _, dir := range []string{first, second} {
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "main.yml"), []byte("count: 1\n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "fragment.yml"), []byte("settings: {selected: "+filepath.Base(dir)+"}\n"), 0600); err != nil {
t.Fatal(err)
}
}
binding := configkit.MainRelative()
underlay := configkit.Input{Source: configkit.Bytes("declaration", []byte("config: {imports: [{path: fragment.yml}]}\n")), Imports: true, MainRelative: binding}
for _, test := range []struct {
name string
paths []string
want string
}{
{"first", []string{filepath.Join(first, "main.yml"), filepath.Join(second, "main.yml")}, "first"},
{"later", []string{filepath.Join(root, "missing.yml"), filepath.Join(second, "main.yml")}, "second"},
} {
t.Run(test.name, func(t *testing.T) {
var callbacks int
result, err := configkit.LoadLayered(configkit.Input{Source: configkit.SearchConfig("", configkit.SearchPaths(test.paths...))}, configkit.LayeredOptions[layeredFacadeConfig]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{underlay}}}, Definition: configkit.Definition[layeredFacadeConfig]{Validate: func(*layeredFacadeConfig, *configkit.Validation) { callbacks++ }}})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if result.Config.Settings["selected"] != test.want || callbacks != 1 {
t.Fatalf("config = %#v, callbacks = %d", result.Config, callbacks)
}
sources := result.Sources()
if len(sources) != 3 || sources[0].Layer != configkit.LayerMain || sources[1].Layer != configkit.LayerUnderlay || sources[2].Layer != configkit.LayerUnderlay || sources[2].UnderlayIndex != 1 || filepath.Base(sources[2].Path) != "fragment.yml" || sources[1].Path != "" {
t.Fatalf("sources = %#v", sources)
}
if _, ok := result.SourceContext(sources[1].ID); !ok {
t.Fatal("bound synthetic source lacks context")
}
if _, ok := result.SourceContext(sources[2].ID); !ok {
t.Fatal("import source lacks context")
}
})
}
}
func TestMainRelativeSyntheticMainContexts(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "fragment.yml"), []byte("settings: {selected: synthetic}\n"), 0600); err != nil {
t.Fatal(err)
}
ctx := &configkit.FilesystemContext{Root: root, BaseDir: root}
mainSources := []configkit.Source{configkit.Bytes("main bytes", []byte("count: 1\n")), configkit.Reader("main reader", strings.NewReader("count: 1\n")), configkit.Mapping("main mapping", map[string]any{"count": 1})}
for _, source := range mainSources {
input := configkit.Input{Source: configkit.Bytes("underlay", []byte("config: {imports: [{path: fragment.yml}]}\n")), Imports: true, MainRelative: configkit.MainRelative()}
result, err := configkit.LoadLayered(configkit.Input{Source: source, Filesystem: ctx}, configkit.LayeredOptions[layeredFacadeConfig]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{input}}}})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if result.Config.Settings["selected"] != "synthetic" {
t.Fatalf("config = %#v", result.Config)
}
}
}
func TestMainRelativeSelectedMainFailureIsTerminal(t *testing.T) {
root := t.TempDir()
bad, good := filepath.Join(root, "bad.yml"), filepath.Join(root, "good.yml")
if err := os.WriteFile(bad, []byte("count: [\n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(good, []byte("count: 1\n"), 0600); err != nil {
t.Fatal(err)
}
called := false
input := configkit.Input{Source: configkit.Bytes("underlay", []byte("count: 3\n")), MainRelative: &configkit.MainRelativeContext{Fallback: &configkit.FilesystemContext{Root: root, BaseDir: root}}}
_, err := configkit.LoadLayered(configkit.Input{Source: configkit.SearchConfig("", configkit.SearchPaths(bad, good))}, configkit.LayeredOptions[layeredFacadeConfig]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{input}}}, Definition: configkit.Definition[layeredFacadeConfig]{Validate: func(*layeredFacadeConfig, *configkit.Validation) { called = true }}})
if err == nil || called {
t.Fatalf("error = %v, callback = %v", err, called)
}
}
func TestMainRelativeSourceVersionEvidence(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "main.yml"), []byte("version: 1\ncount: 1\n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "fragment.yml"), []byte("version: 2\nsettings: {loaded: fragment}\n"), 0600); err != nil {
t.Fatal(err)
}
input := configkit.Input{Source: configkit.Bytes("companion", []byte("version: 3\nconfig: {imports: [{path: fragment.yml}]}\n")), Imports: true, MainRelative: configkit.MainRelative()}
type versioned struct {
Version int `yaml:"version"`
Count int `yaml:"count"`
Settings map[string]string `yaml:"settings"`
}
definition := configkit.Definition[versioned]{Version: &configkit.VersionRule{Path: configkit.Keys("version"), Check: func(configkit.Version, *configkit.Validation) error { return nil }}}
result, err := configkit.LoadLayered(configkit.Input{Source: configkit.File(filepath.Join(root, "main.yml"))}, configkit.LayeredOptions[versioned]{Definition: definition, SourceVersionMode: configkit.SourceVersionModeRequired, Underlays: []configkit.Underlay{{Inputs: []configkit.Input{input}}}})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
sources := result.Sources()
if len(sources) != 3 {
t.Fatalf("sources = %#v", sources)
}
for i, want := range []string{"1", "3", "2"} {
evidence := sources[i].VersionEvidence
if evidence == nil || evidence.Version.Text != want || evidence.Location == nil || evidence.Location.SourceID != sources[i].ID {
t.Fatalf("version evidence = %#v", sources)
}
}
}
func TestMainRelativeOptionalSearchExhaustion(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "overlays"), 0700); err != nil {
t.Fatal(err)
}
for name, content := range map[string]string{
"fragment.yml": "settings: {companion: loaded}\n",
"overlays/live.yml": "count: 9\n",
} {
if err := os.WriteFile(filepath.Join(root, name), []byte(content), 0600); err != nil {
t.Fatal(err)
}
}
search := configkit.SearchConfig("", configkit.SearchPaths(filepath.Join(root, "absent.yml")))
missing := filepath.Join(root, "missing-fallback")
fallback := &configkit.FilesystemContext{Root: missing, BaseDir: missing}
for _, tc := range []struct {
name string
mainContext *configkit.FilesystemContext
bindingFallback *configkit.FilesystemContext
overlayFallback *configkit.FilesystemContext
overlay string
wantCount int
wantSources int
}{
{name: "skip without context", wantCount: 3, wantSources: 1},
{
name: "root-only main context wins", mainContext: &configkit.FilesystemContext{Root: root},
bindingFallback: fallback, overlayFallback: fallback, overlay: "live", wantCount: 9, wantSources: 3,
},
{name: "selected missing companion fallback", bindingFallback: fallback},
{name: "selected missing overlay fallback", overlay: "live", overlayFallback: fallback},
} {
t.Run(tc.name, func(t *testing.T) {
underlay := configkit.Input{
Source: configkit.Bytes("companion", []byte("count: 3\nconfig: {imports: [{path: fragment.yml}]}\n")),
Imports: true, MainRelative: &configkit.MainRelativeContext{Fallback: tc.bindingFallback},
}
result, err := configkit.LoadLayered(
configkit.Input{Source: search, Filesystem: tc.mainContext},
configkit.LayeredOptions[layeredFacadeConfig]{
Underlays: []configkit.Underlay{{Inputs: []configkit.Input{underlay}}},
Overlay: tc.overlay, OverlayFallback: tc.overlayFallback,
},
)
if tc.wantSources == 0 {
if err == nil {
t.Fatal("missing selected fallback succeeded")
}
diagnostics := err.(*configkit.LoadError).Diagnostics()
if len(diagnostics) != 1 || diagnostics[0].Code != configkit.CodeImportInvalid {
t.Fatalf("diagnostics = %#v", diagnostics)
}
return
}
if err != nil {
t.Fatal(err)
}
sources := result.Sources()
if result.Config.Count != tc.wantCount || len(sources) != tc.wantSources {
t.Fatalf("config = %#v, sources = %#v", result.Config, sources)
}
if sources[0].Layer != configkit.LayerUnderlay || len(sources[0].EmptyImportSelections) != 0 {
t.Fatalf("declaring source = %#v", sources[0])
}
if tc.mainContext != nil && (result.Config.Settings["companion"] != "loaded" || sources[2].Layer != configkit.LayerOverlay) {
t.Fatalf("config = %#v, sources = %#v", result.Config, sources)
}
})
}
}

View File

@@ -0,0 +1,45 @@
package configkit_test
import (
"testing"
configkit "go.maximumdirect.net/configkit"
)
func TestMainRelativeOptions(t *testing.T) {
if configkit.MainRelative() == configkit.MainRelative() {
t.Fatal("binding descriptions must be distinct")
}
invalid := &configkit.FilesystemContext{BaseDir: "relative", Root: "relative"}
cases := []struct {
name string
main configkit.Input
underlay configkit.Input
overlay string
overlayContext, fallback *configkit.FilesystemContext
wantError bool
}{
{name: "binding on main", main: configkit.Input{Source: configkit.NoSource(), MainRelative: configkit.MainRelative()}, wantError: true},
{name: "binding on file", underlay: configkit.Input{Source: configkit.File("missing"), MainRelative: configkit.MainRelative()}, wantError: true},
{name: "invalid fallback", underlay: configkit.Input{Source: configkit.NoSource(), MainRelative: &configkit.MainRelativeContext{Fallback: invalid}}, wantError: true},
{name: "shadowed binding", underlay: configkit.Input{Source: configkit.NoSource(), Filesystem: &configkit.FilesystemContext{Root: t.TempDir()}, MainRelative: &configkit.MainRelativeContext{Fallback: invalid}}},
{name: "inactive overlay fallback", fallback: invalid},
{name: "invalid explicit overlay", overlay: "test", overlayContext: invalid, fallback: &configkit.FilesystemContext{Root: t.TempDir(), BaseDir: t.TempDir()}, wantError: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
main := tc.main
if tc.name != "binding on main" {
main.Source = configkit.NoSource()
}
opts := configkit.LayeredOptions[layeredFacadeConfig]{Overlay: tc.overlay, OverlayFilesystem: tc.overlayContext, OverlayFallback: tc.fallback}
if tc.name == "binding on file" || tc.name == "invalid fallback" || tc.name == "shadowed binding" {
opts.Underlays = []configkit.Underlay{{Inputs: []configkit.Input{tc.underlay}}}
}
_, err := configkit.LoadLayered(main, opts)
if (err != nil) != tc.wantError {
t.Fatalf("error = %v, want error %v", err, tc.wantError)
}
})
}
}

View File

@@ -0,0 +1,260 @@
package configkit_test
import (
"os"
"path/filepath"
"testing"
"testing/fstest"
configkit "go.maximumdirect.net/configkit"
)
func TestMainRelativeCompanion(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "main.yml"), []byte("count: 3\n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "extra.yml"), []byte("settings: {companion: host}\n"), 0600); err != nil {
t.Fatal(err)
}
binding := configkit.MainRelative()
companion := configkit.Input{Source: configkit.Bytes("companions", []byte("config: {imports: [{path: extra.yml}]}\n")), Imports: true, MainRelative: binding}
result, err := configkit.LoadLayered(configkit.Input{Source: configkit.File(filepath.Join(dir, "main.yml"))}, configkit.LayeredOptions[layeredFacadeConfig]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{companion}}}})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if result.Config.Count != 3 || result.Config.Settings["companion"] != "host" {
t.Fatalf("configuration = %#v", result.Config)
}
native := configkit.NewFilesystem("bundle", fstest.MapFS{"dir/main.yml": &fstest.MapFile{Data: []byte("count: 4\n")}, "dir/extra.yml": &fstest.MapFile{Data: []byte("settings: {companion: native}\n")}})
result, err = configkit.LoadLayered(configkit.Input{Source: native.File("dir/main.yml")}, configkit.LayeredOptions[layeredFacadeConfig]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{companion}}}})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if result.Config.Count != 4 || result.Config.Settings["companion"] != "native" {
t.Fatalf("configuration = %#v", result.Config)
}
}
func TestMainRelativeContextSelection(t *testing.T) {
root := t.TempDir()
base := filepath.Join(root, "main")
if err := os.Mkdir(base, 0700); err != nil {
t.Fatal(err)
}
for path, value := range map[string]string{"main/main.yml": "count: 1\n", "main/extra.yml": "settings: {value: derived}\n", "extra.yml": "settings: {value: fallback}\n"} {
if err := os.WriteFile(filepath.Join(root, path), []byte(value), 0600); err != nil {
t.Fatal(err)
}
}
link := filepath.Join(root, "link.yml")
if err := os.Symlink(filepath.Join(base, "main.yml"), link); err != nil {
t.Fatal(err)
}
companion := configkit.Input{Source: configkit.Bytes("companion", []byte("config: {imports: [{path: extra.yml}]}\n")), Imports: true, MainRelative: &configkit.MainRelativeContext{Fallback: &configkit.FilesystemContext{Root: root, BaseDir: root}}}
opts := configkit.LayeredOptions[layeredFacadeConfig]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{companion}}}}
result, err := configkit.LoadLayered(configkit.Input{Source: configkit.File(link), Filesystem: &configkit.FilesystemContext{Root: root}}, opts)
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if got := result.Config.Settings["value"]; got != "derived" {
t.Fatalf("derived value = %q", got)
}
result, err = configkit.LoadLayered(configkit.Input{Source: configkit.NoSource()}, opts)
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if got := result.Config.Settings["value"]; got != "fallback" {
t.Fatalf("fallback value = %q", got)
}
}
func TestMainRelativeWithoutBase(t *testing.T) {
tests := []struct {
name, source string
requireBase bool
wantCode configkit.Code
}{
{"optional", "config: {imports: [{path: missing.yml}]}\ncount: 7\n", false, ""},
{"required", "config: {imports: [{path: missing.yml, required: true}]}\n", false, configkit.CodeImportMissing},
{"required directory", "config: {imports: [{dir: missing, required: true}]}\n", false, configkit.CodeImportMissing},
{"required glob", "config: {imports: [{glob: '*.yml', required: true}]}\n", false, configkit.CodeImportMissing},
{"empty required", "config: {imports: [{path: [], required: true}]}\ncount: 7\n", false, ""},
{"base required", "count: 7\n", true, configkit.CodeOptionsInvalid},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := configkit.Input{Source: configkit.Bytes("companion", []byte(test.source)), Imports: true, MainRelative: &configkit.MainRelativeContext{RequireBase: test.requireBase}}
result, err := configkit.LoadLayered(configkit.Input{Source: configkit.NoSource()}, configkit.LayeredOptions[layeredFacadeConfig]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{input}}}})
if test.wantCode != "" {
if err == nil {
t.Fatal("expected failure")
}
for _, d := range err.(*configkit.LoadError).Diagnostics() {
if d.Code == test.wantCode {
return
}
}
t.Fatalf("diagnostics: %#v", err.(*configkit.LoadError).Diagnostics())
}
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if result.Config.Count != 7 {
t.Fatalf("config = %#v", result.Config)
}
if sources := result.Sources(); len(sources) != 1 || len(sources[0].EmptyImportSelections) != 0 {
t.Fatalf("sources = %#v", sources)
}
})
}
}
func TestMainRelativeWithoutBaseSequenceItem(t *testing.T) {
type item struct {
Name string `yaml:"name"`
}
type config struct {
Items []item `yaml:"items"`
}
input := configkit.Input{Source: configkit.Bytes("item", []byte("config: {imports: [{path: missing.yml}]}\nname: example\n")), Imports: true, MainRelative: configkit.MainRelative(), Destination: configkit.Keys("items"), PlacementMode: configkit.PlacementModeSequenceItem}
result, err := configkit.LoadLayered(configkit.Input{Source: configkit.NoSource()}, configkit.LayeredOptions[config]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{input}}}})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if len(result.Config.Items) != 1 || result.Config.Items[0].Name != "example" {
t.Fatalf("config = %#v", result.Config)
}
}
func TestMainRelativeWithoutBaseImportDefaults(t *testing.T) {
required := true
tests := []struct {
name, source string
imports bool
requireBase bool
code configkit.Code
}{
{"default required", "config: {imports: [{path: missing.yml}]}\n", true, false, configkit.CodeImportMissing},
{"malformed", "config: {imports: [{path: 42}]}\n", true, false, configkit.CodeImportInvalid},
{"imports disabled", "config: {imports: [{path: missing.yml}]}\n", false, false, configkit.CodeImportDisabled},
{"base required without imports", "count: 1\n", false, true, configkit.CodeOptionsInvalid},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := configkit.Input{Source: configkit.Bytes("companion", []byte(test.source)), Imports: test.imports, MainRelative: &configkit.MainRelativeContext{RequireBase: test.requireBase}}
_, err := configkit.LoadLayered(configkit.Input{Source: configkit.NoSource()}, configkit.LayeredOptions[layeredFacadeConfig]{ImportDefaults: configkit.ImportDefaults{Required: &required}, Underlays: []configkit.Underlay{{Inputs: []configkit.Input{input}}}})
if err == nil {
t.Fatal("expected failure")
}
for _, diagnostic := range err.(*configkit.LoadError).Diagnostics() {
if diagnostic.Code == test.code {
return
}
}
t.Fatalf("diagnostics = %#v", err.(*configkit.LoadError).Diagnostics())
})
}
}
func TestLayeredOverlayContextSelection(t *testing.T) {
root := t.TempDir()
base := filepath.Join(root, "base")
for _, dir := range []string{filepath.Join(root, "overlays"), filepath.Join(base, "overlays")} {
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
}
for path, content := range map[string]string{"base/main.yml": "count: 1\n", "base/overlays/test.yml": "count: 2\n", "overlays/test.yml": "count: 3\n"} {
if err := os.WriteFile(filepath.Join(root, path), []byte(content), 0600); err != nil {
t.Fatal(err)
}
}
main := configkit.Input{Source: configkit.File(filepath.Join(base, "main.yml")), Filesystem: &configkit.FilesystemContext{Root: root}}
result, err := configkit.LoadLayered(main, configkit.LayeredOptions[layeredFacadeConfig]{Overlay: "test"})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if result.Config.Count != 2 {
t.Fatalf("derived overlay = %d", result.Config.Count)
}
result, err = configkit.LoadLayered(main, configkit.LayeredOptions[layeredFacadeConfig]{Overlay: "test", OverlayFilesystem: &configkit.FilesystemContext{Root: root, BaseDir: base}})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if result.Config.Count != 3 {
t.Fatalf("explicit overlay = %d", result.Config.Count)
}
result, err = configkit.LoadLayered(configkit.Input{Source: configkit.NoSource()}, configkit.LayeredOptions[layeredFacadeConfig]{Overlay: "test", OverlayFallback: &configkit.FilesystemContext{Root: root, BaseDir: base}})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if result.Config.Count != 2 {
t.Fatalf("fallback overlay = %d", result.Config.Count)
}
}
func TestLayeredOverlayNativeContext(t *testing.T) {
filesystem := configkit.NewFilesystem("bundle", fstest.MapFS{
"dir/main.yml": &fstest.MapFile{Data: []byte("count: 1\n")},
"dir/overlays/test.yml": &fstest.MapFile{Data: []byte("count: 9\n")},
})
main := configkit.Input{Source: filesystem.File("dir/main.yml"), Filesystem: &configkit.FilesystemContext{Root: ".", FS: &filesystem}}
result, err := configkit.LoadLayered(main, configkit.LayeredOptions[layeredFacadeConfig]{Overlay: "test"})
if err != nil {
t.Fatalf("%v: %#v", err, err.(*configkit.LoadError).Diagnostics())
}
if result.Config.Count != 9 {
t.Fatalf("config = %#v", result.Config)
}
_, err = configkit.LoadLayered(main, configkit.LayeredOptions[layeredFacadeConfig]{Overlay: "missing", OverlayFallback: &configkit.FilesystemContext{Root: ".", BaseDir: ".", FS: &filesystem}})
if err == nil {
t.Fatal("missing selected overlay succeeded")
}
for _, diagnostic := range err.(*configkit.LoadError).Diagnostics() {
if diagnostic.Code == configkit.CodeOverlayMissing {
return
}
}
t.Fatalf("diagnostics = %#v", err.(*configkit.LoadError).Diagnostics())
}
func TestLayeredOverlayNativeLinks(t *testing.T) {
for _, tc := range []struct {
name, mainPath, target string
want configkit.Code
}{
{"outside root", "scope/main.yml", "../../outside.yml", configkit.CodeOverlayOutsideRoot},
{"overlay aliases main", "scope/main.yml", "../main.yml", configkit.CodeOverlayRepeated},
{"main aliases overlay target", "scope/alias.yml", "../target.yml", configkit.CodeOverlayRepeated},
{"contained overlay", "scope/main.yml", "../target.yml", ""},
} {
t.Run(tc.name, func(t *testing.T) {
native := configkit.NewFilesystem("bundle", fstest.MapFS{
"scope/main.yml": {Data: []byte("count: 1\n")},
"scope/alias.yml": {Data: []byte("target.yml"), Mode: os.ModeSymlink},
"scope/target.yml": {Data: []byte("count: 7\n")},
"scope/overlays/test.yml": {Data: []byte(tc.target), Mode: os.ModeSymlink},
"outside.yml": {Data: []byte("count: 9\n")},
})
main := configkit.Input{Source: native.File(tc.mainPath), Filesystem: &configkit.FilesystemContext{Root: "scope", FS: &native}}
result, err := configkit.LoadLayered(main, configkit.LayeredOptions[layeredFacadeConfig]{Overlay: "test"})
if tc.want != "" {
if err == nil {
t.Fatal("overlay link unexpectedly loaded")
}
diagnostics := err.(*configkit.LoadError).Diagnostics()
if len(diagnostics) != 1 || diagnostics[0].Code != tc.want {
t.Fatalf("diagnostics = %#v, want %v", diagnostics, tc.want)
}
return
}
if err != nil {
t.Fatal(err)
}
if result.Config.Count != 7 || result.Sources()[1].Path != "scope/target.yml" {
t.Fatalf("config = %#v, sources = %#v", result.Config, result.Sources())
}
})
}
}

187
facade_result_value_test.go Normal file
View File

@@ -0,0 +1,187 @@
package configkit_test
import (
"bytes"
"reflect"
"strings"
"testing"
configkit "go.maximumdirect.net/configkit"
)
type valueName string
type valueKey string
type valueEmbedded struct{ Label valueName }
type valueCodec struct{ Text string }
func (valueCodec) MarshalText() ([]byte, error) { panic("codec called during lookup") }
func (*valueCodec) UnmarshalText([]byte) error { panic("codec called during lookup") }
type valueConfig struct {
Embedded *valueEmbedded `yaml:",inline"`
Extra map[valueKey]any `yaml:",inline"`
List []string `yaml:"list"`
Array [2]int `yaml:"array"`
Dynamic any `yaml:"dynamic"`
Codec valueCodec `yaml:"codec"`
Pointer *valueEmbedded `yaml:"pointer"`
Nil *valueEmbedded `yaml:"nil"`
Ignored string `yaml:"-"`
private string
}
func TestResultValueCurrentNavigation(t *testing.T) {
var missing *configkit.Result[valueConfig]
if _, ok := missing.Value(configkit.Path{}); ok {
t.Fatal("nil result")
}
var nilMap map[string]int
result := &configkit.Result[valueConfig]{Config: valueConfig{
Embedded: &valueEmbedded{Label: "named"}, Extra: map[valueKey]any{"a/b": nil, "": nilMap, "0": 7},
List: []string{"first"}, Array: [2]int{1, 2}, Dynamic: map[string]any{"list": []any{valueEmbedded{Label: "dynamic"}}}, Pointer: &valueEmbedded{Label: "pointer"},
}}
parsed, _ := configkit.ParsePath("/dynamic/list/0/label")
parsedKey, _ := configkit.ParsePath("/0")
if got, ok := result.Value(configkit.Path{}); !ok || !reflect.DeepEqual(got, result.Config) {
t.Fatalf("root = %#v, %v", got, ok)
}
pointer, ok := result.Value(configkit.Keys("dynamic", "list").Index(0))
if !ok || pointer.(valueEmbedded).Label != "dynamic" {
t.Fatalf("struct terminal = %#v, %v", pointer, ok)
}
for _, tc := range []struct {
path configkit.Path
want any
ok bool
}{
{configkit.Keys("label"), valueName("named"), true},
{configkit.Keys("a/b"), nil, true}, {configkit.Keys(""), nilMap, true},
{parsedKey, 7, true}, {configkit.Path{}.Index(0), nil, false},
{configkit.Keys("list").Index(0), "first", true}, {configkit.Keys("list", "0"), nil, false},
{configkit.Keys("list").Index(1), nil, false}, {configkit.Keys("list").Index(-1), nil, false},
{parsed, valueName("dynamic"), true}, {configkit.Keys("ignored"), nil, false}, {configkit.Keys("private"), nil, false},
{configkit.Keys("codec"), valueCodec{}, true}, {configkit.Keys("codec", "text"), nil, false},
{configkit.Keys("nil"), (*valueEmbedded)(nil), true}, {configkit.Keys("nil", "label"), nil, false},
{configkit.Keys("pointer", "label"), valueName("pointer"), true},
} {
got, ok := result.Value(tc.path)
if ok != tc.ok || !reflect.DeepEqual(got, tc.want) {
t.Errorf("%s: got %#v, %v; want %#v, %v", tc.path.String(), got, ok, tc.want, tc.ok)
}
}
copyValue, _ := result.Value(configkit.Keys("array"))
array := copyValue.([2]int)
array[0] = 9
listValue, _ := result.Value(configkit.Keys("list"))
listValue.([]string)[0] = "changed"
mapValue, _ := result.Value(configkit.Keys("dynamic"))
mapValue.(map[string]any)["added"] = true
pointerValue, _ := result.Value(configkit.Keys("pointer"))
pointerValue.(*valueEmbedded).Label = "changed"
if result.Config.Array[0] != 1 || result.Config.List[0] != "changed" {
t.Fatal("assignment ownership differs")
}
if result.Config.Dynamic.(map[string]any)["added"] != true {
t.Fatal("map assignment did not preserve alias")
}
if result.Config.Pointer.Label != "changed" {
t.Fatal("pointer assignment did not preserve alias")
}
result.Config.Embedded = nil
if _, ok := result.Value(configkit.Keys("label")); ok {
t.Fatal("nil inline pointer")
}
result.Config.Dynamic = make(chan int)
if _, ok := result.Value(configkit.Keys("dynamic")); !ok {
t.Fatal("unsupported terminal unavailable")
}
if _, ok := result.Value(configkit.Keys("dynamic", "x")); ok {
t.Fatal("unsupported value traversed")
}
}
func TestResultValueFrozenInspectionAndSecret(t *testing.T) {
t.Setenv("CONFIGKIT_VALUE_TEST_SECRET", "disposable-value-canary")
type settings struct {
Name string `yaml:"name"`
Count int `yaml:"count"`
Token configkit.Secret `yaml:"token"`
}
result, err := configkit.Load[settings](configkit.Bytes("settings.yml", []byte("name: before\ntoken: CONFIGKIT_VALUE_TEST_SECRET\n")))
if err != nil {
t.Fatal(err)
}
if got, ok := result.Value(configkit.Keys("count")); !ok || got != 0 || result.Metadata().IsExplicit(configkit.Keys("count")) {
t.Fatalf("default = %#v, %v", got, ok)
}
secret, ok := result.Value(configkit.Keys("token"))
if !ok || secret.(configkit.Secret).Value() != "disposable-value-canary" {
t.Fatal("resolved secret unavailable")
}
result.Config.Name = "after"
if got, _ := result.Value(configkit.Keys("name")); got != "after" {
t.Fatalf("current value = %v", got)
}
var output bytes.Buffer
if err := result.WriteEffective(&output); err != nil {
t.Fatal(err)
}
if !strings.Contains(output.String(), "before") || strings.Contains(output.String(), "after") || strings.Contains(output.String(), "disposable-value-canary") {
t.Fatalf("frozen output = %s", output.String())
}
}
func TestResultValueReturnsTerminalsWithoutSchemaValidation(t *testing.T) {
type terminal struct {
A int `yaml:"same"`
B int `yaml:"same"`
}
want := terminal{A: 1, B: 2}
cases := []struct {
name string
lookup func(configkit.Path) (any, bool)
path configkit.Path
}{
{"map", (&configkit.Result[map[string]terminal]{Config: map[string]terminal{"item": want}}).Value, configkit.Keys("item")},
{"slice", (&configkit.Result[[]terminal]{Config: []terminal{want}}).Value, configkit.Path{}.Index(0)},
{"array", (&configkit.Result[[1]terminal]{Config: [1]terminal{want}}).Value, configkit.Path{}.Index(0)},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, ok := tc.lookup(tc.path)
if !ok || got != want {
t.Fatalf("terminal = %#v, %v", got, ok)
}
if _, ok := tc.lookup(tc.path.Key("same")); ok {
t.Fatal("ambiguous containing bindings accepted")
}
})
}
// A post-load replacement need not itself satisfy the load-time schema.
result, err := configkit.Load[map[string]any](configkit.Bytes("dynamic.yml", []byte("{}")))
if err != nil {
t.Fatal(err)
}
result.Config["dynamic"] = struct {
Child terminal `yaml:"child"`
Good int `yaml:"good"`
}{Child: want, Good: 3}
for _, tc := range []struct {
path configkit.Path
want any
}{
{configkit.Keys("dynamic", "child"), want},
{configkit.Keys("dynamic", "good"), 3},
} {
got, ok := result.Value(tc.path)
if !ok || got != tc.want {
t.Fatalf("%s = %#v, %v", tc.path.String(), got, ok)
}
}
if _, ok := result.Value(configkit.Keys("dynamic", "child", "same")); ok {
t.Fatal("ambiguous dynamic child accepted navigation")
}
if _, err := configkit.Load[map[string]terminal](configkit.NoSource()); err == nil {
t.Fatal("Load accepted an invalid element schema")
}
}

View File

@@ -0,0 +1,103 @@
package configkit_test
import (
"errors"
"os"
"path/filepath"
"testing"
configkit "go.maximumdirect.net/configkit"
)
var _ func(string) (*configkit.SecretsReport, error) = configkit.LoadSecretsIntoEnvironment
func TestFacadeSecretsOptionsAndConfiguredPrecedence(t *testing.T) {
root := t.TempDir()
directory := filepath.Join(root, "secrets")
if err := os.Mkdir(directory, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(directory, "CONFIGKIT_FACADE_SECRET"), []byte("replacement\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("CONFIGKIT_FACADE_SECRET", "old")
report, err := configkit.LoadSecretsIntoEnvironmentWithOptions(directory, configkit.SecretsOptions{Overwrite: true})
if err != nil || len(report.Entries()) != 1 || report.Entries()[0].Status != configkit.SecretFileLoaded || os.Getenv("CONFIGKIT_FACADE_SECRET") != "replacement" {
t.Fatalf("direct report = %#v, error = %v", report, err)
}
for _, test := range []struct {
name, setting, want string
overwrite *bool
}{
{"default", "", "old", nil},
{"yaml true", " secrets_overwrite: true\n", "replacement", nil},
{"false overrides true", " secrets_overwrite: true\n", "old", facadeBool(false)},
{"true overrides false", " secrets_overwrite: false\n", "replacement", facadeBool(true)},
} {
t.Run(test.name, func(t *testing.T) {
t.Setenv("CONFIGKIT_FACADE_SECRET", "old")
main := filepath.Join(root, "main.yml")
if err := os.WriteFile(main, []byte("config:\n secrets_dir: secrets\n"+test.setting+"value: original\n"), 0o600); err != nil {
t.Fatal(err)
}
var report *configkit.SecretsReport
var prepared configkit.Source
var err error
if test.overwrite == nil {
report, prepared, err = configkit.LoadSecretsIntoEnvironmentFromConfig(configkit.File(main))
} else {
report, prepared, err = configkit.LoadSecretsIntoEnvironmentFromConfig(configkit.File(main), configkit.SecretsFromConfigOptions{Overwrite: test.overwrite})
}
if err != nil || report == nil || len(report.Entries()) != 1 || os.Getenv("CONFIGKIT_FACADE_SECRET") != test.want {
t.Fatalf("report = %#v, error = %v", report, err)
}
if err := os.WriteFile(main, []byte("value: changed\n"), 0o600); err != nil {
t.Fatal(err)
}
loaded, err := configkit.Load[struct {
Value string `yaml:"value"`
}](prepared)
if err != nil || loaded.Config.Value != "original" {
t.Fatalf("prepared load = %#v, error = %v", loaded, err)
}
})
}
}
func facadeBool(value bool) *bool { return &value }
func TestFacadeSecretsFromConfigErrorsKeepPublicEvidence(t *testing.T) {
root := t.TempDir()
directReport, directErr := configkit.LoadSecretsIntoEnvironmentWithOptions(filepath.Join(root, "missing"), configkit.SecretsOptions{Overwrite: true})
var directFailure *configkit.SecretsError
if directReport == nil || !errors.As(directErr, &directFailure) || len(directFailure.Diagnostics()) != 1 || directFailure.Diagnostics()[0].Code != configkit.CodeSecretsMissing {
t.Fatalf("direct report = %#v, error = %#v", directReport, directErr)
}
main := filepath.Join(root, "main.yml")
if err := os.WriteFile(main, []byte("config: {secrets_overwrite: invalid}\n"), 0o600); err != nil {
t.Fatal(err)
}
report, prepared, err := configkit.LoadSecretsIntoEnvironmentFromConfig(configkit.File(main), configkit.SecretsFromConfigOptions{Overwrite: facadeBool(false)})
var loadErr *configkit.LoadError
if report == nil || len(report.Entries()) != 0 || !errors.As(err, &loadErr) || len(loadErr.Sources()) != 1 || len(loadErr.Diagnostics()) != 1 || loadErr.Diagnostics()[0].Code != configkit.CodeSecretsInvalidValue || loadErr.Diagnostics()[0].Primary == nil || loadErr.Diagnostics()[0].Primary.SourceID != loadErr.Sources()[0].ID {
t.Fatalf("preparation report = %#v, error = %#v", report, err)
}
if _, err := configkit.Load[struct{}](prepared); err == nil {
t.Fatal("failed preparation returned a usable source")
}
report, _, err = configkit.LoadSecretsIntoEnvironmentFromConfig(configkit.File(main), configkit.SecretsFromConfigOptions{}, configkit.SecretsFromConfigOptions{})
if report == nil || !errors.As(err, &loadErr) || len(loadErr.Diagnostics()) != 1 || loadErr.Diagnostics()[0].Code != configkit.CodeOptionsInvalid || len(loadErr.Sources()) != 0 {
t.Fatalf("multiple options report = %#v, error = %#v", report, err)
}
if err := os.WriteFile(main, []byte("config: {secrets_dir: missing}\n"), 0o600); err != nil {
t.Fatal(err)
}
report, prepared, err = configkit.LoadSecretsIntoEnvironmentFromConfig(configkit.File(main))
var secretsErr *configkit.SecretsError
if report == nil || !errors.As(err, &secretsErr) || len(secretsErr.Diagnostics()) != 1 || secretsErr.Diagnostics()[0].Code != configkit.CodeSecretsMissing {
t.Fatalf("directory report = %#v, error = %#v", report, err)
}
if _, err := configkit.Load[struct{}](prepared); err == nil {
t.Fatal("failed bootstrap returned a usable source")
}
}

View File

@@ -0,0 +1,230 @@
package configkit_test
import (
"errors"
"io/fs"
"os"
"path/filepath"
"strconv"
"sync"
"testing"
configkit "go.maximumdirect.net/configkit"
)
type startupHandoffConfig struct {
Main string `yaml:"main"`
Imported string `yaml:"imported"`
Underlay string `yaml:"underlay"`
Overlay string `yaml:"overlay"`
Asset string `yaml:"asset"`
Token configkit.Secret `yaml:"token"`
}
func TestConfiguredSecretsStartupHandoff(t *testing.T) {
root := t.TempDir()
other := t.TempDir()
t.Chdir(other)
write := func(name, contents string) string {
t.Helper()
file := filepath.Join(root, name)
if err := os.MkdirAll(filepath.Dir(file), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(file, []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
return file
}
const tokenName = "CONFIGKIT_HANDOFF_TOKEN"
const sdkName = "CONFIGKIT_HANDOFF_SDK_ONLY"
const emptyName = "CONFIGKIT_HANDOFF_EMPTY"
t.Setenv(tokenName, "previous")
t.Setenv(sdkName, "previous-sdk")
t.Setenv(emptyName, "")
write("app/secrets/"+tokenName, "bootstrap-token\n")
write("app/secrets/"+sdkName, "bootstrap-sdk\n")
write("app/secrets/"+emptyName, "bootstrap-empty\n")
write("app/fragment.yml", "imported: before\n")
write("app/lower.yml", "underlay: companion\n")
write("app/overlays/dev.yml", "overlay: selected\n")
write("app/asset.txt", "resource-data")
main := write("app/main.yml", "config: {secrets_dir: secrets, secrets_overwrite: true, imports: [{path: fragment.yml}]}\nmain: captured\nasset: asset.txt\ntoken: "+tokenName+"\n")
candidate := filepath.Join(root, "app", "earlier.yml")
search := configkit.SearchConfig("app", configkit.SearchPaths(candidate, main))
report, prepared, err := configkit.LoadSecretsIntoEnvironmentFromConfig(search, configkit.SecretsFromConfigOptions{Filesystem: &configkit.FilesystemContext{Root: root}})
if err != nil || report == nil || len(report.Entries()) != 3 || os.Getenv(tokenName) != "bootstrap-token" || os.Getenv(sdkName) != "bootstrap-sdk" || os.Getenv(emptyName) != "bootstrap-empty" {
t.Fatalf("prepare report = %#v, error = %v", report, err)
}
for _, entry := range report.Entries() {
if entry.Status != configkit.SecretFileLoaded {
t.Fatalf("bootstrap entry = %#v", entry)
}
}
options := configkit.Options[startupHandoffConfig]{Imports: true}
first, err := configkit.Load[startupHandoffConfig](prepared, options)
if err != nil || first.Config.Main != "captured" || first.Config.Imported != "before" || first.Config.Token.Value() != "bootstrap-token" {
t.Fatalf("first load = %#v, %v", first, err)
}
write("app/main.yml", "main: changed\n")
write("app/earlier.yml", "main: different-candidate\n")
write("app/fragment.yml", "imported: after\n")
if err := os.Setenv(tokenName, "later-token"); err != nil {
t.Fatal(err)
}
second, err := configkit.Load[startupHandoffConfig](prepared, options)
if err != nil || second.Config.Main != "captured" || second.Config.Imported != "after" || second.Config.Token.Value() != "later-token" || first.Config.Imported != "before" || first.Config.Token.Value() != "bootstrap-token" {
t.Fatalf("subsequent load = %#v, %v", second, err)
}
sources := second.Sources()
canonicalMain, err := filepath.EvalSymlinks(main)
if err != nil {
t.Fatal(err)
}
if len(sources) != 2 || sources[0].Kind != configkit.SourceKindFile || sources[0].Path != canonicalMain || sources[0].ID != "source-1" || sources[1].ID != "source-2" {
t.Fatalf("sources = %#v", sources)
}
sources[0].Label = "modified"
if second.Sources()[0].Label == "modified" || first.Sources()[0].Label == "modified" {
t.Fatal("source evidence is shared")
}
context, ok := second.SourceContext("source-1")
if !ok || context.BaseDir != "app" {
t.Fatalf("source context = %#v, %v", context, ok)
}
if data, err := fs.ReadFile(context.FS, "app/asset.txt"); err != nil || string(data) != "resource-data" {
t.Fatalf("resource = %q, %v", data, err)
}
underlay := configkit.Input{Source: configkit.Bytes("companion", []byte("config: {imports: [{path: lower.yml}]}\n")), Imports: true, MainRelative: configkit.MainRelative()}
layered, err := configkit.LoadLayered(configkit.Input{Source: prepared, Imports: true, Filesystem: &configkit.FilesystemContext{Root: root}}, configkit.LayeredOptions[startupHandoffConfig]{
Underlays: []configkit.Underlay{{Inputs: []configkit.Input{underlay}}}, Overlay: "dev",
})
if err != nil || layered.Config.Underlay != "companion" || layered.Config.Overlay != "selected" || layered.Config.Imported != "after" {
t.Fatalf("layered load = %#v, %v", layered, err)
}
_, err = configkit.LoadLayered(configkit.Input{Source: prepared, Filesystem: &configkit.FilesystemContext{Root: filepath.Join(root, "app")}}, configkit.LayeredOptions[startupHandoffConfig]{})
var loadErr *configkit.LoadError
if !errors.As(err, &loadErr) || len(loadErr.Diagnostics()) == 0 || loadErr.Diagnostics()[0].Code != configkit.CodeOptionsInvalid || os.Getenv(tokenName) != "later-token" {
t.Fatalf("incompatible context error = %v", err)
}
_, err = configkit.Load[startupHandoffConfig](prepared, configkit.Options[startupHandoffConfig]{Imports: true, Definition: configkit.Definition[startupHandoffConfig]{Validate: func(_ *startupHandoffConfig, validation *configkit.Validation) {
validation.Error(configkit.Keys("main"), "invalid startup setting")
}}})
if !errors.As(err, &loadErr) || os.Getenv(tokenName) != "later-token" || os.Getenv(sdkName) != "bootstrap-sdk" || len(report.Entries()) != 3 {
t.Fatalf("later validation error = %v, report = %#v", err, report)
}
var group sync.WaitGroup
errorsFound := make(chan error, 8)
for range 8 {
group.Go(func() {
loaded, err := configkit.Load[startupHandoffConfig](prepared, options)
if err != nil {
errorsFound <- err
} else if loaded.Config.Main != "captured" || loaded.Config.Token.Value() != "later-token" {
errorsFound <- errors.New("captured source produced unexpected values")
}
})
}
group.Wait()
close(errorsFound)
for err := range errorsFound {
t.Error(err)
}
}
func TestConfiguredSecretsPreservesExistingEmptyValue(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "secrets"), 0o700); err != nil {
t.Fatal(err)
}
const name = "CONFIGKIT_HANDOFF_PRESERVED_EMPTY"
t.Setenv(name, "")
if err := os.WriteFile(filepath.Join(root, "secrets", name), []byte("replacement"), 0o600); err != nil {
t.Fatal(err)
}
main := filepath.Join(root, "main.yml")
if err := os.WriteFile(main, []byte("config: {secrets_dir: secrets}\nmain: value\n"), 0o600); err != nil {
t.Fatal(err)
}
report, _, err := configkit.LoadSecretsIntoEnvironmentFromConfig(configkit.File(main))
if err != nil || len(report.Entries()) != 1 || report.Entries()[0].Status != configkit.SecretFileSkippedExisting || !report.Entries()[0].ExistingEmpty || os.Getenv(name) != "" {
t.Fatalf("report = %#v, error = %v", report, err)
}
}
func TestOrdinaryLoadingNeverBootstrapsSecrets(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "secrets"), 0o700); err != nil {
t.Fatal(err)
}
const name = "CONFIGKIT_NO_AUTOMATIC_BOOTSTRAP"
t.Setenv(name, "existing")
if err := os.WriteFile(filepath.Join(root, "secrets", name), []byte("replacement"), 0o600); err != nil {
t.Fatal(err)
}
main := filepath.Join(root, "main.yml")
if err := os.WriteFile(main, []byte("config: {secrets_dir: secrets, secrets_overwrite: true}\nmain: ordinary\n"), 0o600); err != nil {
t.Fatal(err)
}
type ordinaryConfig struct {
Main string `yaml:"main"`
}
if _, err := configkit.Load[ordinaryConfig](configkit.File(main)); err != nil {
t.Fatal(err)
}
if _, err := configkit.LoadLayered(configkit.Input{Source: configkit.File(main)}, configkit.LayeredOptions[ordinaryConfig]{}); err != nil {
t.Fatal(err)
}
if os.Getenv(name) != "existing" {
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)
}
})
}
}

8
go.mod
View File

@@ -2,12 +2,12 @@ module go.maximumdirect.net/configkit
go 1.27.0
require go.yaml.in/yaml/v4 v4.0.0-rc.6
require go.yaml.in/yaml/v4 v4.0.0
require (
github.com/yuin/goldmark/v2 v2.1.6 // indirect
go.maximumdirect.net/releasekit v0.8.0 // indirect
golang.org/x/mod v0.40.0 // indirect
github.com/yuin/goldmark/v2 v2.1.16 // indirect
go.maximumdirect.net/releasekit v0.11.0 // indirect
golang.org/x/mod v0.43.0 // indirect
)
tool go.maximumdirect.net/releasekit/cmd/releasekit

16
go.sum
View File

@@ -1,8 +1,8 @@
github.com/yuin/goldmark/v2 v2.1.6 h1:igy0q9JcqovoFXFx/XjtU8sHVhcUHavPj2sA3EoKJUE=
github.com/yuin/goldmark/v2 v2.1.6/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ=
go.maximumdirect.net/releasekit v0.8.0 h1:hSaHPbUI7tAhnolfbu7UMj2fvmm9FGBY+jhkygdbxR0=
go.maximumdirect.net/releasekit v0.8.0/go.mod h1:QE4BLrAhVJTzi+/YTcVl21K/qZp9ojRLg5kuoy3Zb44=
go.yaml.in/yaml/v4 v4.0.0-rc.6 h1:1h7H1ohdUh93/FyE4YaDa1Zh64K6VVbjF4K6WUxMtH4=
go.yaml.in/yaml/v4 v4.0.0-rc.6/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
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=
go.maximumdirect.net/releasekit v0.11.0 h1:QjRfi+DLwMdRASkQf0pAA17nzWZ+LMk5qZg6Oj9SJQU=
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/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=

143
inspection_view.go Normal file
View File

@@ -0,0 +1,143 @@
package configkit
import (
"io"
"go.maximumdirect.net/configkit/internal/engine"
)
// Inspection is a reporting view of a frozen load checkpoint, whether the load
// succeeded or failed. Its scope filters enumeration; explicit queries and
// source records retain their native paths.
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
// an absent location. Equivalent key and index spellings select the same scope.
// Nil, manually constructed results and invalid paths cannot produce a view.
func (r *Result[T]) InspectSubtree(path Path) (Inspection, bool) {
if r == nil {
return Inspection{}, false
}
view, ok := engine.NewInspectionView(r.inspection, toEnginePath(path))
return Inspection{view: view}, ok
}
// 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()} }
// HistoricalPaths returns observed paths at or beneath the reporting scope.
func (i Inspection) HistoricalPaths() []Path {
values := i.view.HistoricalPaths()
paths := make([]Path, len(values))
for index := range values {
paths[index] = fromEnginePath(values[index])
}
return paths
}
// WriteEffective renders the saved value at the reporting scope with its
// original sensitivity. Unavailable values and nil writers return an error;
// writer errors can leave partial output.
func (i Inspection) WriteEffective(output io.Writer) error { return i.view.WriteEffective(output) }
// Diff compares frozen views at the same canonical scope, including differences
// at an ancestor when the existing comparison treats that ancestor atomically.
// Views may come from different root Go types. Unavailable or mismatched views
// 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) {
values, err := i.view.Diff(other.view)
if err != nil {
return nil, err
}
return fromEngineDifferences(values), nil
}
// Sources returns the full detached source catalog.
func (i Inspection) Sources() []SourceInfo {
values := i.view.Inspection().Sources()
if values == nil {
return nil
}
result := make([]SourceInfo, len(values))
for index := range values {
result[index] = fromEngineSourceInfo(values[index])
}
return result
}
// Source returns a detached record from the full source catalog.
func (i Inspection) Source(id string) (SourceInfo, bool) {
value, ok := i.view.Inspection().Source(id)
return fromEngineSourceInfo(value), ok
}
// SourceContext returns the borrowed resource context for an acquired source.
func (i Inspection) SourceContext(id string) (ResourceContext, bool) {
value, ok := i.view.Inspection().SourceContext(id)
return ResourceContext{FS: value.FS, BaseDir: value.BaseDir}, ok
}
// Explain queries a native path, whether or not it lies within the scope.
func (i Inspection) Explain(path Path) (Explanation, bool) {
value, ok := i.view.Inspection().Explain(toEnginePath(path))
return fromEngineExplanation(value), ok
}
// WriteExplanation renders an explicit native path using the frozen load.
func (i Inspection) WriteExplanation(output io.Writer, path Path) error {
return i.view.Inspection().WriteExplanation(output, toEnginePath(path))
}

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

@@ -20,6 +20,8 @@ type tierAcquisitionState struct {
type inputAcquisitionRequest struct {
input loadInput
resolved *resolvedFilesystemContext
withoutBase bool
role sourceVersionRole
directiveContext rootDirectiveContext
protectionRule *VersionRule
@@ -33,27 +35,23 @@ type importAcquisitionRequest struct {
}
func acquireInput(request inputAcquisitionRequest, policy acquisitionPolicy, state *acquisitionState, tier *tierAcquisitionState) (assembledInput, []Diagnostic) {
if request.withoutBase && request.input.mainRelative.RequireBase {
return assembledInput{}, []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "main-relative input requires a filesystem base")}
}
source := request.input.source
destination := request.input.destination
accounting := state.accounting
versionState := state.versionState
sourceID := "source-" + strconv.Itoa(accounting.sources+1)
selectedSource := source
selectedSource, failedSource, selectionDiagnostics := selectInputSource(source, sourceID, request.input.filesystem)
if len(selectionDiagnostics) != 0 {
if failedSource != nil {
failedSource.Destination = destination.clone()
failedSource.placementMode = request.input.placementMode
}
return assembledInput{source: selectedSource, sources: sourceInfos(failedSource), versionState: versionState, accounting: accounting}, selectionDiagnostics
}
if source.kind == sourceSearch {
resolved, failedSource, diagnostics := resolveSearchInput(source, sourceID, defaultDiscoveryDirectoryHelpers(), defaultDiscoveryHostProbe())
if len(diagnostics) != 0 {
if failedSource != nil {
failedSource.Destination = destination.clone()
failedSource.placementMode = request.input.placementMode
}
return assembledInput{source: resolved, sources: sourceInfos(failedSource), versionState: versionState, accounting: accounting}, diagnostics
}
selectedSource = resolved
if request.input.filesystem != nil {
if diagnostics := filesystemOptionDiagnostics(selectedSource, request.input.filesystem); len(diagnostics) != 0 {
return assembledInput{source: selectedSource, versionState: versionState, accounting: accounting}, diagnostics
}
}
if selectedSource.kind == sourceNone && activeOverlay(request.ordinaryOverlay) && request.input.filesystem == nil {
return assembledInput{source: selectedSource, versionState: versionState, accounting: accounting}, []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "NoSource overlays require explicit filesystem context")}
}
@@ -80,6 +78,13 @@ func acquireInput(request inputAcquisitionRequest, policy acquisitionPolicy, sta
}
return input, diagnostics
}
if selectedSource.captured != nil {
resolved, diagnostic := resolveFilesystemContext(selectedSource, request.input.filesystem, parsed, tier.hostToken)
if diagnostic != nil {
return input, []Diagnostic{*diagnostic}
}
request.resolved = &resolved
}
directiveContext := request.directiveContext
if directiveContext == 0 {
directiveContext = rootDirectiveContextImportsOnly
@@ -101,7 +106,12 @@ func acquireInput(request inputAcquisitionRequest, policy acquisitionPolicy, sta
return input, diagnostics
}
request.input.source = selectedSource
if request.input.imports && selectedSource.kind != sourceNone {
if request.input.imports && selectedSource.kind != sourceNone && request.withoutBase {
input, diagnostics = acquireContextlessInput(input, request, versionProcessing, policy)
if len(diagnostics) != 0 {
return input, diagnostics
}
} else if request.input.imports && selectedSource.kind != sourceNone {
importRequest := importAcquisitionRequest{input: request, main: parsed, processing: versionProcessing}
input.composition, input.sources, input.resolvedFilesystem, diagnostics = acquireImportedInput(importRequest, &policy, state, tier)
if len(diagnostics) != 0 {
@@ -126,6 +136,14 @@ func acquireStandaloneInput(input assembledInput, request inputAcquisitionReques
if processing != nil {
input.document = processing.payload
}
if request.resolved != nil {
if input.source.captured == nil || request.input.filesystem != nil {
if diagnostic := validateResolvedFilesystemContext(*request.resolved); diagnostic != nil {
return input, []Diagnostic{*diagnostic}
}
}
input.resolvedFilesystem = request.resolved
}
if request.input.filesystem != nil && (input.source.kind == sourceNone || !activeOverlay(request.ordinaryOverlay)) {
resolved, diagnostic := validateFilesystemContext(input.source, request.input.filesystem, parsed, tier.hostToken)
if diagnostic != nil {

View File

@@ -0,0 +1,72 @@
package engine
import "go.maximumdirect.net/configkit/internal/document"
func acquireContextlessInput(input assembledInput, request inputAcquisitionRequest, processing *sourceVersionProcessingResult, policy acquisitionPolicy) (assembledInput, []Diagnostic) {
parsed := input.parsed
var body *document.Node
var declarations []importDeclarationSpec
var sequences []sequenceDeclarationSpec
var diagnostics []Diagnostic
if processing != nil {
body, declarations = processing.payload, processing.imports
sequences = cloneSequenceDeclarations(processing.sequences)
} else {
body, declarations, diagnostics = splitImportDirectives(parsed.document, request.role)
}
destination := request.input.destination
localDestination := destination
if request.input.placementMode == PlacementModeSequenceItem {
localDestination = Path{}
}
if len(diagnostics) == 0 {
var policies []resolvedImportPolicy
policies, diagnostics = prepareImportDeclarations(declarations, policy.importDefaults, localDestination)
if len(diagnostics) == 0 {
for i, spec := range declarations {
if !policies[i].required || spec.selector == importSelectorPath && len(spec.paths) == 0 {
continue
}
site := spec.fieldSites["path"]
if spec.selector == importSelectorPath && len(spec.selectorSites) != 0 {
site = spec.selectorSites[0]
}
if spec.selector == importSelectorDirectory {
site = spec.fieldSites["dir"]
}
if spec.selector == importSelectorGlob {
site = spec.fieldSites["glob"]
}
diagnostics = []Diagnostic{{Code: CodeImportMissing, Severity: SeverityError, Path: site.path.clone(), Message: "import cannot be selected because no filesystem base is available", Primary: cloneLocation(&site.location)}}
break
}
}
}
if len(diagnostics) != 0 {
if request.input.placementMode == PlacementModeSequenceItem {
diagnostics = prependCompositionDiagnosticPaths(diagnostics, destination.Index(0))
}
return input, diagnostics
}
accounting, limits := input.accounting, policy.importLimits
if diagnostic := chargeDeclaringImport(parsed, accounting, limits); diagnostic != nil {
return input, []Diagnostic{*diagnostic}
}
key := importKeyForMainSource(parsed.source)
root := acquiredContribution{
source: cloneSourceInfo(*parsed.source), payload: body, identity: key,
role: importRoleMain, scopeOwner: key, processing: processing, sequenceDeclarations: sequences,
}
scope, diagnostic := prepareDeclaringImportScope(root, accounting, limits)
if diagnostic != nil {
return input, []Diagnostic{*diagnostic}
}
scope, diagnostic = finalizeDeclaringImportScope(scope, root, accounting, limits)
if diagnostic != nil {
return input, []Diagnostic{*diagnostic}
}
input.document = body
input.composition = &composedDocument{acquisition: []acquisitionScope{scope}, importGraph: newImportInclusionGraph(), inputBytes: accounting.bytes, inputNodes: accounting.nodes}
input.acquisition = cloneAcquisitionScopes(input.composition.acquisition)
return input, nil
}

View File

@@ -129,7 +129,7 @@ parent: true
betaPath := writeImportFile(t, directory, "fragments/b.yml", "beta: true\n")
main := parseImportMain(t, mainPath)
_, declarations, diagnostics := splitImportDirectives(main.document)
_, declarations, diagnostics := splitImportDirectives(main.document, sourceVersionMain)
if len(diagnostics) != 0 {
t.Fatalf("main directive diagnostics = %#v", diagnostics)
}

View File

@@ -15,6 +15,15 @@ import (
type LoadError struct {
diagnostics []Diagnostic
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.

View File

@@ -2,6 +2,7 @@ package engine
import (
"reflect"
"runtime"
"testing"
"go.maximumdirect.net/configkit/internal/document"
@@ -18,7 +19,7 @@ records:
configkit: {imports: [{path: absent.yaml}]}
_configkit: ordinary
`)
extracted, diagnostics := extractRootDirectives(root, rootDirectiveContextSource)
extracted, diagnostics := extractRootDirectives(root, rootDirectiveContextSource, sourceVersionContribution)
if len(diagnostics) != 0 || len(extracted.imports) != 1 {
t.Fatalf("extraction = %#v, diagnostics = %#v", extracted, diagnostics)
}
@@ -59,7 +60,7 @@ func TestDocumentRootControlValidation(t *testing.T) {
{"bad imports", "config: {imports: wrong}\n", CodeImportInvalid, "/config/imports"},
} {
t.Run(test.name, func(t *testing.T) {
_, diagnostics := extractRootDirectives(parseRootDirectiveDocument(t, test.input), rootDirectiveContextSource)
_, diagnostics := extractRootDirectives(parseRootDirectiveDocument(t, test.input), rootDirectiveContextSource, sourceVersionContribution)
if len(diagnostics) == 0 || diagnostics[0].Code != test.code || diagnostics[0].Path.String() != test.path {
t.Fatalf("diagnostics = %#v", diagnostics)
}
@@ -87,7 +88,101 @@ func TestDocumentRootControlGuards(t *testing.T) {
if got := overlayDirectiveDiagnostics(sequences, Path{}, true); len(got) != 0 {
t.Fatalf("overlay sequences diagnostics = %#v", got)
}
if _, got := extractRootDirectives(sequences, rootDirectiveContextImportsOnly); len(got) == 0 || got[0].Code != CodeSequenceInvalid {
if _, got := extractRootDirectives(sequences, rootDirectiveContextImportsOnly, sourceVersionContribution); len(got) == 0 || got[0].Code != CodeSequenceInvalid {
t.Fatalf("imports-only extraction diagnostics = %#v", got)
}
}
func TestBootstrapControlExtraction(t *testing.T) {
root := parseRootDirectiveDocument(t, "config:\n imports: invalid\n secrets_dir: ../secrets\n secrets_overwrite: false\n")
settings, diagnostics := extractBootstrapSettings(root)
if len(diagnostics) != 0 || !settings.directoryDeclared || settings.directory != "../secrets" || !settings.overwriteDeclared || settings.overwrite || settings.directoryLocation.Line != 3 || settings.overwriteLocation.Line != 4 {
t.Fatalf("settings = %#v, diagnostics = %#v", settings, diagnostics)
}
if _, diagnostics := extractRootDirectives(root, rootDirectiveContextSource, sourceVersionMain); len(diagnostics) == 0 {
t.Fatal("normal extraction did not validate unrelated import grammar")
}
for _, test := range []struct {
input string
code Code
path string
}{
{"config: {secrets_dir: ''}", CodeSecretsInvalidPath, "/config/secrets_dir"},
{"config: {secrets_dir: /absolute}", CodeSecretsInvalidPath, "/config/secrets_dir"},
{"config: {secrets_dir: null}", CodeSecretsInvalidPath, "/config/secrets_dir"},
{"config: {secrets_dir: 123}", CodeSecretsInvalidPath, "/config/secrets_dir"},
{"config: {secrets_overwrite: null}", CodeSecretsInvalidValue, "/config/secrets_overwrite"},
{"config: {secrets_overwrite: 'true'}", CodeSecretsInvalidValue, "/config/secrets_overwrite"},
{"config: invalid", CodeImportInvalid, "/config"},
} {
t.Run(test.input, func(t *testing.T) {
root := parseRootDirectiveDocument(t, test.input+"\n")
_, preparation := extractBootstrapSettings(root)
_, normal := extractRootDirectives(root, rootDirectiveContextSource, sourceVersionMain)
for _, got := range [][]Diagnostic{preparation, normal} {
if len(got) != 1 || got[0].Code != test.code || got[0].Path.String() != test.path || got[0].Primary == nil || got[0].Primary.Line != 1 {
t.Fatalf("diagnostics = %#v", got)
}
}
})
}
}
func TestBootstrapDirectoryRejectsWindowsRootedPaths(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("host path syntax differs")
}
for _, path := range []string{`C:relative`, `\rooted`} {
root := parseRootDirectiveDocument(t, "config: {secrets_dir: '"+path+"'}\n")
_, diagnostics := extractBootstrapSettings(root)
if len(diagnostics) != 1 || diagnostics[0].Code != CodeSecretsInvalidPath {
t.Fatalf("path %q: %#v", path, diagnostics)
}
}
}
func TestBootstrapControlsRequireMainSource(t *testing.T) {
root := parseRootDirectiveDocument(t, "config: {secrets_dir: secrets, secrets_overwrite: true}\nvalue: ordinary\n")
for _, context := range []rootDirectiveContext{rootDirectiveContextSource, rootDirectiveContextLayered} {
main, diagnostics := extractRootDirectives(root, context, sourceVersionMain)
if len(diagnostics) != 0 || len(main.body.Mapping) != 1 || main.body.Mapping[0].Key != "value" {
t.Fatalf("main extraction = %#v, diagnostics = %#v", main, diagnostics)
}
_, diagnostics = extractRootDirectives(root, context, sourceVersionContribution)
if len(diagnostics) != 2 || diagnostics[0].Code != CodeImportInvalid || diagnostics[1].Code != CodeImportInvalid {
t.Fatalf("contribution diagnostics = %#v", diagnostics)
}
}
_, diagnostics := extractRootDirectives(root, rootDirectiveContextOverlay, sourceVersionContribution)
if len(diagnostics) != 2 || diagnostics[0].Code != CodeOverlayDirective || diagnostics[1].Code != CodeOverlayDirective {
t.Fatalf("overlay diagnostics = %#v", diagnostics)
}
for _, name := range []string{"secrets_dir", "secrets_overwrite"} {
if !sourceVersionControlOverlap(root, Keys("config", name)) {
t.Errorf("version overlap not detected for %s", name)
}
}
}
func TestBootstrapControlsKeepSourceVersionChecksInLoad(t *testing.T) {
root := parseRootDirectiveDocument(t, "config: {secrets_dir: secrets, secrets_overwrite: false}\nversion: 1\n")
called := false
rule := &VersionRule{Path: Keys("version"), Check: func(Version, *Validation) error {
called = true
return nil
}}
if _, diagnostics := extractBootstrapSettings(root); len(diagnostics) != 0 || called {
t.Fatalf("preparation diagnostics = %#v, checker called = %v", diagnostics, called)
}
result := processSourceVersionWithDirectiveContext(root, rule, sourceVersionMain, Path{}, sourceVersionModeRequired, rootDirectiveContextSource)
if len(result.diagnostics) != 0 || !called {
t.Fatalf("load diagnostics = %#v, checker called = %v", result.diagnostics, called)
}
for _, name := range []string{"secrets_dir", "secrets_overwrite"} {
rule.Path = Keys("config", name)
result = processSourceVersionWithDirectiveContext(root, rule, sourceVersionMain, Path{}, sourceVersionModeRequired, rootDirectiveContextSource)
if len(result.diagnostics) != 1 || result.diagnostics[0].Code != CodeVersionError {
t.Errorf("overlap %s diagnostics = %#v", name, result.diagnostics)
}
}
}

View File

@@ -1,7 +1,8 @@
package engine
import (
"path"
"os"
"path/filepath"
"strings"
"go.maximumdirect.net/configkit/internal/document"
@@ -24,15 +25,71 @@ type rootDirectiveExtraction struct {
sequences []sequenceDeclarationSpec
}
func splitImportDirectives(root *document.Node) (*document.Node, []importDeclarationSpec, []Diagnostic) {
extracted, diagnostics := extractRootDirectives(root, rootDirectiveContextImportsOnly)
// bootstrapSettings retains only source-local control facts, never credentials.
type bootstrapSettings struct {
directoryDeclared bool
directory string
directoryLocation document.Location
overwriteDeclared bool
overwrite bool
overwriteLocation document.Location
}
// extractBootstrapSettings validates only the controls needed for preparation;
// normal loading remains responsible for the rest of the directive grammar.
func extractBootstrapSettings(root *document.Node) (bootstrapSettings, []Diagnostic) {
var settings bootstrapSettings
if root == nil || root.Kind != document.Mapping {
return settings, nil
}
for _, entry := range root.Mapping {
if entry.Key != directiveKey {
continue
}
if entry.Value == nil || entry.Value.Kind != document.Mapping {
return settings, []Diagnostic{nodeImportDiagnostic(CodeImportInvalid, Keys(directiveKey), "configuration directive must be a mapping", entry.Value)}
}
var diagnostics []Diagnostic
for _, field := range entry.Value.Mapping {
if field.Key == "secrets_dir" || field.Key == "secrets_overwrite" {
if diagnostic := parseBootstrapField(&settings, field); diagnostic != nil {
diagnostics = append(diagnostics, *diagnostic)
}
}
}
return settings, canonicalDiagnostics(diagnostics)
}
return settings, nil
}
func parseBootstrapField(settings *bootstrapSettings, entry document.Entry) *Diagnostic {
value := entry.Value
fieldPath := Keys(directiveKey, entry.Key)
if entry.Key == "secrets_dir" {
if value == nil || value.Kind != document.String || value.Text == "" || os.IsPathSeparator(value.Text[0]) || filepath.IsAbs(value.Text) || filepath.VolumeName(value.Text) != "" {
diagnostic := nodeImportDiagnostic(CodeSecretsInvalidPath, fieldPath, "secrets directory must be a nonempty relative host path", value)
return &diagnostic
}
settings.directoryDeclared, settings.directory, settings.directoryLocation = true, value.Text, value.Location
return nil
}
if value == nil || value.Kind != document.Boolean {
diagnostic := nodeImportDiagnostic(CodeSecretsInvalidValue, fieldPath, "secrets overwrite setting must be a Boolean", value)
return &diagnostic
}
settings.overwriteDeclared, settings.overwrite, settings.overwriteLocation = true, value.Text == "true", value.Location
return nil
}
func splitImportDirectives(root *document.Node, role sourceVersionRole) (*document.Node, []importDeclarationSpec, []Diagnostic) {
extracted, diagnostics := extractRootDirectives(root, rootDirectiveContextImportsOnly, role)
if len(diagnostics) != 0 {
return nil, nil, diagnostics
}
return extracted.body, extracted.imports, nil
}
func extractRootDirectives(root *document.Node, context rootDirectiveContext) (rootDirectiveExtraction, []Diagnostic) {
func extractRootDirectives(root *document.Node, context rootDirectiveContext, role sourceVersionRole) (rootDirectiveExtraction, []Diagnostic) {
if root == nil {
return rootDirectiveExtraction{}, nil
}
@@ -43,7 +100,7 @@ func extractRootDirectives(root *document.Node, context rootDirectiveContext) (r
continue
}
directiveIndex = index
extracted, diagnostics := parseRootDirectiveBlock(entry.Value, Keys(directiveKey), context)
extracted, diagnostics := parseRootDirectiveBlock(entry.Value, Keys(directiveKey), context, role)
if len(diagnostics) != 0 {
return rootDirectiveExtraction{}, diagnostics
}
@@ -56,7 +113,7 @@ func extractRootDirectives(root *document.Node, context rootDirectiveContext) (r
return rootDirectiveExtraction{body: body}, nil
}
func parseRootDirectiveBlock(node *document.Node, directivePath Path, context rootDirectiveContext) (rootDirectiveExtraction, []Diagnostic) {
func parseRootDirectiveBlock(node *document.Node, directivePath Path, context rootDirectiveContext, role sourceVersionRole) (rootDirectiveExtraction, []Diagnostic) {
if node == nil || node.Kind != document.Mapping {
return rootDirectiveExtraction{}, []Diagnostic{nodeImportDiagnostic(CodeImportInvalid, directivePath, "configuration directive must be a mapping", node)}
}
@@ -89,6 +146,19 @@ func parseRootDirectiveBlock(node *document.Node, directivePath Path, context ro
parsed, issues := parseSequenceDeclarationDirective(entry.Value, fieldPath)
extracted.sequences = append(extracted.sequences, parsed...)
diagnostics = append(diagnostics, issues...)
case "secrets_dir", "secrets_overwrite":
if role != sourceVersionMain || context == rootDirectiveContextOverlay {
code := CodeImportInvalid
if context == rootDirectiveContextOverlay {
code = CodeOverlayDirective
}
diagnostics = append(diagnostics, nodeImportDiagnostic(code, fieldPath, "secrets bootstrap controls are only permitted in the main document", entry.Value))
continue
}
var settings bootstrapSettings
if diagnostic := parseBootstrapField(&settings, entry); diagnostic != nil {
diagnostics = append(diagnostics, *diagnostic)
}
default:
diagnostics = append(diagnostics, nodeImportDiagnostic(CodeImportInvalid, fieldPath, "configuration directive field is not recognized", entry.Value))
}
@@ -154,10 +224,10 @@ func fragmentVersionClaimWithIndex(root *document.Node, rule *VersionRule, sourc
}
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 !hasImportScheme(value)
return filepath.IsAbs(value) || !hasImportScheme(value)
}
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,28 +12,35 @@ func validateFilesystemContext(source Source, context *FilesystemContext, main p
if diagnostic != nil {
// Keep absent-input validation's existing diagnostic while sharing
// 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"
}
return resolvedFilesystemContext{}, diagnostic
}
if diagnostic := validateResolvedFilesystemDirectories(resolved); diagnostic != nil {
if diagnostic := validateResolvedFilesystemContext(resolved); diagnostic != nil {
return resolvedFilesystemContext{}, diagnostic
}
if resolved.native != nil {
return resolved, nil
return resolved, nil
}
func validateResolvedFilesystemContext(resolved resolvedFilesystemContext) *Diagnostic {
if diagnostic := validateResolvedFilesystemDirectories(resolved); diagnostic != nil {
return diagnostic
}
if resolved.native != nil || resolved.rootPath == "" {
return nil
}
root, err := os.OpenRoot(resolved.rootPath)
if err != nil {
value := globFilesystemDiagnostic(err, "configuration root could not be opened", Location{})
value.Primary = nil
return resolvedFilesystemContext{}, &value
return &value
}
if err := root.Close(); err != nil {
value := importDiagnostic(CodeImportRead, "configuration root could not be closed", nil)
return resolvedFilesystemContext{}, &value
return &value
}
return resolved, nil
return nil
}
func filesystemOptionDiagnostics(source Source, context *FilesystemContext) []Diagnostic {
@@ -44,8 +51,8 @@ func filesystemOptionDiagnostics(source Source, context *FilesystemContext) []Di
if context.FS != nil {
return absentFilesystemOptionDiagnostics(context)
}
// A selected host file can derive its root; absence requires an
// explicit root. Check that compatibility only after selection.
// A selected host file derives its base; absence can use an explicit
// base or root. Check compatibility after selection.
if context.BaseDir != "" && !filepath.IsAbs(context.BaseDir) {
return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "filesystem base directory must be an absolute host path")}
}
@@ -67,14 +74,14 @@ func filesystemOptionDiagnostics(source Source, context *FilesystemContext) []Di
return []Diagnostic{optionDiagnostic(CodeOptionsInvalid, "filesystem root must be a slash-relative valid path")}
}
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")}
}
if context.FS != nil {
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")}
}
} 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")}
}
}
@@ -86,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) {
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 nil

View File

@@ -30,8 +30,8 @@ type resourceIdentity struct {
occurrence *namespaceToken
}
// filesystemAccess is a load-scoped view of either a contained host root or a
// borrowed native filesystem. Names are canonical host paths or fs.FS paths.
// filesystemAccess is a load-scoped view of bounded or unbounded host access,
// or a borrowed native filesystem. Names are canonical host paths or fs.FS paths.
type filesystemAccess struct {
rootPath string
root *os.Root
@@ -41,6 +41,9 @@ type filesystemAccess struct {
}
func openHostAccess(rootPath string) (*filesystemAccess, error) {
if rootPath == "" {
return &filesystemAccess{token: &namespaceToken{}}, nil
}
root, err := os.OpenRoot(rootPath)
if err != nil {
return nil, err
@@ -83,7 +86,7 @@ func (a *filesystemAccess) dir(name string) string {
func (a *filesystemAccess) contains(name string) bool {
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) {
return false
@@ -112,6 +115,12 @@ func (a *filesystemAccess) relative(name string) (string, error) {
}
return name, nil
}
if a.rootPath == "" {
if !filepath.IsAbs(name) {
return "", fs.ErrInvalid
}
return name, nil
}
relative, err := filepath.Rel(a.rootPath, name)
if err != nil || filepath.IsAbs(relative) || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return "", fs.ErrInvalid
@@ -127,6 +136,9 @@ func (a *filesystemAccess) stat(name string) (fs.FileInfo, error) {
if err != nil {
return nil, err
}
if a.root == nil {
return os.Stat(relative)
}
return a.root.Stat(relative)
}
@@ -138,6 +150,9 @@ func (a *filesystemAccess) open(name string) (fs.File, error) {
if err != nil {
return nil, err
}
if a.root == nil {
return os.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,14 +9,18 @@ import (
)
type resolvedFilesystemContext struct {
native *nativeNamespace
hostToken *namespaceToken
rootPath string
basePath string
mainPath string
native *nativeNamespace
hostToken *namespaceToken
rootPath string
importRoot string
basePath string
mainPath string
}
func resolveFilesystemContext(source Source, context *FilesystemContext, main parsedSource, hostToken *namespaceToken) (resolvedFilesystemContext, *Diagnostic) {
if source.captured != nil {
return resolveCapturedFilesystemContext(source, context, main, hostToken)
}
if source.kind == sourceNone && context != nil {
return resolveAbsentFilesystemContext(context)
}
@@ -26,28 +30,67 @@ func resolveFilesystemContext(source Source, context *FilesystemContext, main pa
return resolveHostFilesystemContext(source, context, main, hostToken)
}
func resolveCapturedFilesystemContext(source Source, context *FilesystemContext, main parsedSource, hostToken *namespaceToken) (resolvedFilesystemContext, *Diagnostic) {
captured := source.captured
resolved := resolvedFilesystemContext{hostToken: hostToken, rootPath: captured.rootPath, importRoot: captured.importRoot, basePath: captured.basePath, mainPath: captured.mainPath}
if context == nil {
return resolved, nil
}
if context.FS != nil || context.BaseDir != "" {
value := optionDiagnostic(CodeOptionsInvalid, "prepared source requires a compatible host filesystem context")
return resolvedFilesystemContext{}, &value
}
if context.Root == "" {
return resolved, nil
}
// 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")
return resolvedFilesystemContext{}, &value
}
resolved.importRoot = root
return resolved, nil
}
func sameHostPath(left, right string) bool {
return containedPath(left, right) && containedPath(right, left)
}
func resolveAbsentFilesystemContext(context *FilesystemContext) (resolvedFilesystemContext, *Diagnostic) {
if context.FS != nil {
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 {
value := importDiagnostic(CodeImportInvalid, "configuration root could not be canonicalized", nil)
return resolvedFilesystemContext{}, &value
}
basePath := rootPath
resolved := resolvedFilesystemContext{rootPath: rootPath, basePath: rootPath}
if context.Root != "" {
resolved.importRoot = rootPath
}
if context.BaseDir != "" {
basePath, err = canonicalExistingPath(context.BaseDir)
resolved.basePath, err = canonicalExistingPath(context.BaseDir)
if err != nil {
value := importDiagnostic(CodeImportInvalid, "import base directory could not be canonicalized", nil)
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)
return resolvedFilesystemContext{}, &value
}
return resolvedFilesystemContext{rootPath: rootPath, basePath: basePath}, nil
return resolved, nil
}
func resolveNativeFilesystemContext(source Source, context *FilesystemContext) (resolvedFilesystemContext, *Diagnostic) {
@@ -69,6 +112,7 @@ func resolveNativeFilesystemContext(source Source, context *FilesystemContext) (
return resolvedFilesystemContext{}, &value
}
resolved.native = namespace
resolved.importRoot = resolved.rootPath
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)
return resolvedFilesystemContext{}, &value
@@ -106,13 +150,14 @@ func resolveHostFilesystemContext(source Source, context *FilesystemContext, mai
return resolvedFilesystemContext{}, &value
}
resolved.rootPath = rootPath
resolved.importRoot = rootPath
}
} else {
if context == nil || context.BaseDir == "" || context.Root == "" {
value := optionDiagnostic(CodeOptionsInvalid, "byte and reader imports require absolute base and root directories")
if context == nil || context.BaseDir == "" {
value := optionDiagnostic(CodeOptionsInvalid, "synthetic imports require an absolute base directory")
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")
return resolvedFilesystemContext{}, &value
}
@@ -122,7 +167,11 @@ func resolveHostFilesystemContext(source Source, context *FilesystemContext, mai
value := importDiagnostic(CodeImportInvalid, "import base directory could not be canonicalized", nil)
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 {
value := importDiagnostic(CodeImportInvalid, "configuration root could not be canonicalized", nil)
return resolvedFilesystemContext{}, &value
@@ -144,6 +193,9 @@ func containsNativePath(root, name string) bool {
func validateResolvedFilesystemDirectories(resolved resolvedFilesystemContext) *Diagnostic {
for _, directory := range []string{resolved.rootPath, resolved.basePath} {
if directory == "" {
continue
}
var info fs.FileInfo
var err error
if resolved.native != nil {
@@ -165,7 +217,7 @@ func openResolvedFilesystemAccess(resolved resolvedFilesystemContext) (*filesyst
access.label = resolved.native.label
return access, nil
}
access, err := openHostAccess(resolved.rootPath)
access, err := openHostAccess(resolved.importRoot)
if err != nil {
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 (
"errors"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
@@ -37,7 +38,12 @@ func (a *filesystemAccess) importEntryTarget(name string, entry fs.DirEntry, fol
}
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 {
return importEntryTarget{}, err
}
@@ -52,8 +58,11 @@ func (a *filesystemAccess) importEntryTarget(name string, entry fs.DirEntry, fol
if err != nil {
return importEntryTarget{}, err
}
resolvedPath := filepath.Join(a.rootPath, filepath.FromSlash(resolved))
info, err = a.root.Stat(filepath.FromSlash(resolved))
resolvedPath := filepath.FromSlash(resolved)
if a.root != nil {
resolvedPath = filepath.Join(a.rootPath, resolvedPath)
}
info, err = a.stat(resolvedPath)
if err != nil {
return importEntryTarget{}, err
}
@@ -127,16 +136,46 @@ type importLinkFrame struct {
}
type importLinkOperations struct {
pathRoot func(string) string
lstat func(string) (fs.FileInfo, error)
readlink func(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) {
frames := []importLinkFrame{{pending: strings.Split(name, "/")}}
resolved := ""
return resolveImportLinkPathFrom("", name, operations)
}
// 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{})
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 {
frame := &frames[len(frames)-1]
if len(frame.pending) == 0 {
@@ -144,12 +183,20 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
if resolved == "" {
resolved = "."
}
completed[frame.link] = resolved
completed[frame.link] = resolvedLink{resolved, resolvedInfo}
delete(active, frame.link)
}
frames = frames[:len(frames)-1]
if frame.link != "" && len(frames) == 1 && operations.visit != nil {
if err := visit(resolvedInfo); err != nil {
return "", err
}
}
continue
}
if resolvedInfo != nil && !resolvedInfo.IsDir() {
return "", fs.ErrInvalid
}
segment := frame.pending[0]
frame.pending = frame.pending[1:]
candidate := path.Join(resolved, segment)
@@ -160,12 +207,22 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
if err != nil {
return "", err
}
if info.Mode()&fs.ModeSymlink == 0 {
resolved = candidate
if operations.readlink == nil || info.Mode()&fs.ModeSymlink == 0 {
resolved, resolvedInfo = candidate, info
if len(frames) == 1 {
if err := visit(info); err != nil {
return "", err
}
}
continue
}
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
}
if _, exists := active[candidate]; exists {
@@ -180,8 +237,10 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
return "", err
}
active[candidate] = struct{}{}
frames = append(frames, importLinkFrame{pending: strings.Split(targetPath, "/"), link: candidate})
resolved = ""
root, pending := split(targetPath)
frames = append(frames, importLinkFrame{pending: pending, link: candidate})
resolved = root
resolvedInfo = nil
}
if resolved == "" {
resolved = "."
@@ -190,30 +249,78 @@ func resolveImportLinkPath(name string, operations importLinkOperations) (string
}
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 {
// 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{
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) {
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) {
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) {
var targetPath string
if filepath.IsAbs(target) {
relative, err := filepath.Rel(access.rootPath, filepath.Clean(target))
if err != nil {
targetPath := filepath.ToSlash(target)
if !filepath.IsAbs(target) {
// Do not Join/Clean here: a link before .. must resolve first.
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
}
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
},
@@ -228,7 +335,11 @@ func resolveNativeImportPath(access *filesystemAccess, filesystem fs.ReadLinkFS,
if !fs.ValidPath(name) || !access.contains(name) {
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) {
// Ancestors of a multi-component root are resolution prefixes, not
// 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, "/") {
return "", errImportPathOutsideRoot
}
targetPath := path.Clean(path.Join(path.Dir(candidate), target))
if !fs.ValidPath(targetPath) || !access.contains(targetPath) {
targetPath := path.Dir(candidate) + "/" + target
clean := path.Clean(targetPath)
if !fs.ValidPath(clean) || !access.contains(clean) {
return "", errImportPathOutsideRoot
}
return targetPath, nil
},
})
}
}
func isImportLinkCycle(err error) bool {

View File

@@ -313,3 +313,45 @@ func (f *countingReadLinkFS) ReadLink(name string) (string, error) {
f.readLinks++
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"
"io/fs"
"path"
"slices"
"path/filepath"
"sort"
"strings"
)
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
// 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) {
@@ -26,24 +33,40 @@ func selectGlobImportCandidates(access *filesystemAccess, basePath string, spec
if accounting == nil {
accounting = &importAccounting{}
}
rootPath := normalizedImportCandidatePath(access, basePath)
candidates := []selectedImportCandidate{{path: rootPath, accessPath: basePath, site: site}}
for index, segment := range segments {
candidates, prefixLength, diagnostics := globStartingCandidates(access, basePath, spec.glob, segments, site)
if len(diagnostics) != 0 {
return importSelection{}, diagnostics
}
for index := prefixLength; index < len(segments); index++ {
segment := segments[index]
last := index == len(segments)-1
literal, patterned := globLiteralSegment(segment)
// nextByPath is the set union of candidates reached from each matching
// parent at this segment; final exclusions below are set difference.
nextByPath := make(map[string]selectedImportCandidate)
nextByPath := make(map[globCandidateKey]selectedImportCandidate)
for _, parent := range candidates {
if !patterned {
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)
if len(diagnostics) != 0 {
return importSelection{}, diagnostics
}
if !missing {
nextByPath[candidate.path] = candidate
nextByPath[globCandidateKey{candidate.path, candidate.accessPath}] = candidate
}
continue
}
@@ -61,7 +84,7 @@ func selectGlobImportCandidates(access *filesystemAccess, basePath string, spec
return importSelection{}, []Diagnostic{*diagnostic}
}
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)
}
func candidatesFromMap(candidates map[string]selectedImportCandidate) []selectedImportCandidate {
paths := make([]string, 0, len(candidates))
for candidatePath := range candidates {
paths = append(paths, candidatePath)
}
slices.Sort(paths)
result := make([]selectedImportCandidate, 0, len(paths))
for _, candidatePath := range paths {
result = append(result, candidates[candidatePath])
func candidatesFromMap(candidates map[globCandidateKey]selectedImportCandidate) []selectedImportCandidate {
result := make([]selectedImportCandidate, 0, len(candidates))
for _, candidate := range candidates {
result = append(result, candidate)
}
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
}
@@ -237,7 +261,8 @@ func validGlobPattern(pattern string) ([]string, bool) {
if !validImportPath(pattern) {
return nil, false
}
segments := strings.Split(pattern, "/")
_, remainder := splitImportSelectorRoot(pattern)
segments := strings.Split(remainder, "/")
for _, segment := range segments {
if segment == "" || hasRecursiveStars(segment) {
return nil, false
@@ -293,3 +318,118 @@ func globFilesystemDiagnostic(err error, message string, location Location) Diag
}
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 {
files fstest.MapFS
opened []string
files fstest.MapFS
opened []string
failStat string
}
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) {
if name == filesystem.failStat {
return nil, fs.ErrPermission
}
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 adjacent stars", pattern: "empty/value**.yml", 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: "missing parent escape", pattern: "../missing/*.yml", code: CodeImportOutsideRoot},
{name: "parent discovery escape", pattern: "../*/*.yml", code: CodeImportOutsideRoot},
{name: "unmatched", pattern: "empty/*.yml", code: CodeImportMissing},
}
for _, test := range tests {
@@ -107,8 +107,12 @@ func TestLoadGlobImportsRejectInvalidAndUnmatchedPatterns(t *testing.T) {
if err := os.Mkdir(filepath.Join(directory, "empty"), 0o755); err != nil {
t.Fatal(err)
}
mainPath := writeGlobRoot(t, directory, test.pattern, test.code == CodeImportMissing)
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true}, test.code)
pattern := test.pattern
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)
}
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" {
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"})
if err != nil || defaultsOnly == nil {
t.Fatalf("default overlay with NoSource = %#v, %v", defaultsOnly, err)
@@ -301,7 +305,7 @@ func TestNoSourceImportsAndFilesystemContext(t *testing.T) {
context FilesystemContext
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: "missing root directory", context: FilesystemContext{Root: filepath.Join(directory, "missing")}, code: CodeImportInvalid},
{name: "base outside root", context: FilesystemContext{BaseDir: outside, Root: directory}, code: CodeImportOutsideRoot},

View File

@@ -1,6 +1,7 @@
package engine
import (
"errors"
"testing"
"go.maximumdirect.net/configkit/internal/document"
@@ -113,6 +114,17 @@ func TestLoadHistoryBudgetUsesExactRetainedNodeCount(t *testing.T) {
if rejectedValidations != 0 {
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) {

View File

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

View File

@@ -53,6 +53,7 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin
if len(applications) == 0 && len(records) == 0 {
return
}
operations := newSourceOperationIndex(builder.model)
applicationsBySource := make(map[string]historyPayloadRef)
applicationsByLayer := make(map[Layer][]historyPayloadRef)
for index := range applications {
@@ -88,7 +89,7 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin
owned.hasApplicationRef = true
}
for displacedIndex, displaced := range record.displaced {
if sourceOriginRepresentedByOperation(builder.model, displaced.path, displaced.origin) {
if operations.contains(builder.model, displaced.path, displaced.origin) {
continue
}
definitionPayload := payload
@@ -110,12 +111,13 @@ func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origin
})
}
for _, introduced := range record.introduced {
builder.addObservation(historyObservation{
id := builder.addObservation(historyObservation{
path: introduced.path, phase: historyPhaseSources, payload: payload,
reportedPath: record.change.Path, role: historyRoleOperation,
afterPresent: true, sensitive: introduced.sensitive,
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) {
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
}
payload := builder.addSourceSummary(path, origin)
@@ -191,22 +193,72 @@ func sourceApplicationOrigin(application historyApplication, node *document.Node
return origin
}
func sourceOriginRepresentedByOperation(model *historyModel, path Path, origin Origin) bool {
for _, observationID := range model.observationsByPointer[path.String()] {
observation := model.observations[observationID]
if observation.phase != historyPhaseSources || observation.role != historyRoleOperation {
// sourceOperationIndex is local to source evidence construction. It indexes only
// completed after-operation facts, narrowing attribution checks by source ID.
// General observation lists also contain all contributions at a path and grow
// 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
}
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
}
operationOrigin, ok := model.resolveAttribution(observation.attributionRef)
if !ok {
continue
}
if originRepresentedByChange(path, origin, Change{
Path: observation.reportedPath, Origin: operationOrigin.origin,
}) {
attribution, _ := model.resolveAttribution(observation.attributionRef)
if originRepresentedByChange(path, origin, Change{Path: observation.reportedPath, Origin: attribution.origin}) {
return true
}
}

View File

@@ -38,26 +38,30 @@ func acquireImportedInput(request importAcquisitionRequest, policy *acquisitionP
source := request.input.input.source
context := request.input.input.filesystem
main := request.main
resolved, diagnostic := resolveFilesystemContext(source, context, main, tier.hostToken)
if diagnostic != nil {
return nil, sourceInfos(main.source), nil, []Diagnostic{*diagnostic}
resolved := request.input.resolved
if resolved == nil {
value, diagnostic := resolveFilesystemContext(source, context, main, tier.hostToken)
if diagnostic != nil {
return nil, sourceInfos(main.source), nil, []Diagnostic{*diagnostic}
}
resolved = &value
}
if resolved.native == nil {
if diagnostic := validateResolvedFilesystemDirectories(resolved); diagnostic != nil {
if diagnostic := validateResolvedFilesystemDirectories(*resolved); diagnostic != nil {
return nil, sourceInfos(main.source), nil, []Diagnostic{*diagnostic}
}
}
access, err := openResolvedFilesystemAccess(resolved)
access, err := openResolvedFilesystemAccess(*resolved)
if err != nil {
diagnostic := globFilesystemDiagnostic(err, "configuration root could not be opened", Location{})
diagnostic.Primary = nil
return nil, sourceInfos(main.source), nil, []Diagnostic{diagnostic}
}
composition, sources, diagnostics := acquireImportedWithAccess(request, policy, state, tier, access, resolved)
composition, sources, diagnostics := acquireImportedWithAccess(request, policy, state, tier, access, *resolved)
if len(diagnostics) != 0 {
return composition, sources, nil, diagnostics
}
return composition, sources, &resolved, nil
return composition, sources, resolved, nil
}
func acquireImportedWithAccess(request importAcquisitionRequest, policy *acquisitionPolicy, loadState *acquisitionState, tier *tierAcquisitionState, access *filesystemAccess, resolved resolvedFilesystemContext) (*composedDocument, []SourceInfo, []Diagnostic) {
@@ -85,7 +89,7 @@ func acquireImportedWithAccess(request importAcquisitionRequest, policy *acquisi
_ = closeAccess()
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)
if err != nil || !info.IsDir() {
_ = closeAccess()
@@ -107,9 +111,6 @@ func acquireImportedWithAccess(request importAcquisitionRequest, policy *acquisi
_ = closeAccess()
return nil, sourceInfos(main.source), []Diagnostic{importRepeatedDiagnostic(Location{SourceID: main.source.ID}, previous, importRoute{})}
}
accounting.sources++
accounting.bytes += main.bytes
accounting.nodes += countInputNodes(main.document)
directiveContext := request.input.directiveContext
if directiveContext == 0 {
directiveContext = rootDirectiveContextImportsOnly
@@ -120,7 +121,6 @@ func acquireImportedWithAccess(request importAcquisitionRequest, policy *acquisi
request.input.directiveContext = directiveContext
state := importTraversal{
access: access, request: request, policy: policy, state: loadState, tier: tier,
scope: acquisitionScope{owner: mainNodeKey, destination: destination.clone()},
sources: []SourceInfo{mainInfo},
active: make(map[resourceIdentity]int),
importGraph: newImportInclusionGraph(),
@@ -129,11 +129,10 @@ func acquireImportedWithAccess(request importAcquisitionRequest, policy *acquisi
state.itemScope = true
state.itemPrefix = destination.clone()
state.itemFallback = destination.clone()
state.scope.destination = Path{}
state.sources[0] = cloneSourceInfo(mainInfo)
}
if diagnostic := state.checkInitialLimits(); diagnostic != nil {
if diagnostic := chargeDeclaringImport(main, accounting, limits); diagnostic != nil {
_ = closeAccess()
return nil, cloneSourceInfos(state.sources), []Diagnostic{*diagnostic}
}
@@ -157,33 +156,20 @@ func acquireImportedWithAccess(request importAcquisitionRequest, policy *acquisi
declarations = processing.imports
sequenceDeclarations = cloneSequenceDeclarations(processing.sequences)
} else {
body, declarations, diagnostics = splitImportDirectives(main.document)
body, declarations, diagnostics = splitImportDirectives(main.document, request.input.role)
}
root := acquiredContribution{
source: cloneSourceInfo(mainInfo), payload: body, identity: mainNodeKey,
role: importRoleMain, scopeOwner: mainNodeKey, processing: processing,
sequenceDeclarations: sequenceDeclarations,
}
if len(diagnostics) == 0 {
if mainIsItem {
state.scope.contributions = append(state.scope.contributions, acquiredContribution{
source: cloneSourceInfo(mainInfo), identity: mainNodeKey, role: importRoleMain,
scopeOwner: mainNodeKey, payload: body, document: body, processing: processing,
sequenceDeclarations: cloneSequenceDeclarations(sequenceDeclarations),
})
diagnostics = state.walkDeclarations(basePath, declarations, 0, Path{}, 0)
scope, diagnostic := prepareDeclaringImportScope(root, accounting, limits)
if diagnostic != nil {
diagnostics = []Diagnostic{*diagnostic}
} else {
_, placed, err := placeDocument(body, destination, body.Location, maxDocumentDepth, maxDocumentNodes)
placementNodes := destinationWrapperNodeCount(destination)
if err != nil {
diagnostics = []Diagnostic{sourceDiagnostic(CodeSourceLimitExceeded, main.source.ID, "configuration exceeds the source depth or node limit after destination placement")}
} else if accounting.nodes+placementNodes > limits.nodes {
diagnostics = []Diagnostic{importDiagnostic(CodeImportLimitExceeded, "configuration exceeds the aggregate node limit", nil)}
} else {
accounting.nodes += placementNodes
state.scope.contributions = append(state.scope.contributions, acquiredContribution{
source: cloneSourceInfo(mainInfo), payload: body, document: placed,
identity: mainNodeKey, role: importRoleMain, scopeOwner: mainNodeKey,
destination: destination.clone(), processing: processing,
sequenceDeclarations: cloneSequenceDeclarations(sequenceDeclarations),
})
diagnostics = state.walkDeclarations(basePath, declarations, 0, destination, 0)
}
state.scope = scope
diagnostics = state.walkDeclarations(basePath, declarations, 0, scope.destination, 0)
}
}
if len(diagnostics) == 0 {
@@ -200,19 +186,8 @@ func acquireImportedWithAccess(request importAcquisitionRequest, policy *acquisi
if closeErr != nil {
return nil, cloneSourceInfos(state.sources), []Diagnostic{importDiagnostic(CodeImportRead, "configuration root could not be closed", nil)}
}
acquisition := state.scope
if mainIsItem {
localScope := state.scope
acquisition = acquisitionScope{
owner: mainNodeKey, destination: destination.clone(),
contributions: []acquiredContribution{{
source: cloneSourceInfo(mainInfo), payload: body, identity: mainNodeKey,
role: importRoleMain, scopeOwner: mainNodeKey, destination: destination.clone(),
processing: processing, sequenceDeclarations: cloneSequenceDeclarations(sequenceDeclarations), pendingItem: &localScope,
}},
}
}
if diagnostic := reservePendingItemPlacements(&acquisition, limits, accounting); diagnostic != nil {
acquisition, diagnostic := finalizeDeclaringImportScope(state.scope, root, accounting, limits)
if diagnostic != nil {
return nil, cloneSourceInfos(state.sources), []Diagnostic{*diagnostic}
}
return &composedDocument{
@@ -221,35 +196,27 @@ func acquireImportedWithAccess(request importAcquisitionRequest, policy *acquisi
}, cloneSourceInfos(state.sources), nil
}
func (s *importTraversal) checkInitialLimits() *Diagnostic {
if s.state.accounting.sources > s.policy.importLimits.sources {
value := importDiagnostic(CodeImportLimitExceeded, "configuration exceeds the source-count limit", nil)
return &value
}
if s.state.accounting.bytes > s.policy.importLimits.bytes {
value := importDiagnostic(CodeImportLimitExceeded, "configuration exceeds the aggregate byte limit", nil)
return &value
}
if s.state.accounting.nodes > s.policy.importLimits.nodes {
value := importDiagnostic(CodeImportLimitExceeded, "configuration exceeds the aggregate node limit", nil)
return &value
}
return nil
}
func (s *importTraversal) walkDeclarations(basePath string, declarations []importDeclarationSpec, depth int, parentDestination Path, sourceIndex int) []Diagnostic {
func prepareImportDeclarations(declarations []importDeclarationSpec, defaults ImportDefaults, parentDestination Path) ([]resolvedImportPolicy, []Diagnostic) {
policies := make([]resolvedImportPolicy, len(declarations))
for index, spec := range declarations {
policy, diagnostics := resolveImportPolicy(spec, s.policy.importDefaults)
policy, diagnostics := resolveImportPolicy(spec, defaults)
if len(diagnostics) != 0 {
return diagnostics
return nil, diagnostics
}
if policy.placement == PlacementModeSequenceItem && len(appendDestination(parentDestination, policy.destination).segments) == 0 {
site := spec.fieldSites["placement"]
return []Diagnostic{{Code: CodeImportInvalid, Severity: SeverityError, Path: site.path.clone(), Message: "sequence-item placement requires a nonempty destination", Primary: cloneLocation(&site.location)}}
return nil, []Diagnostic{{Code: CodeImportInvalid, Severity: SeverityError, Path: site.path.clone(), Message: "sequence-item placement requires a nonempty destination", Primary: cloneLocation(&site.location)}}
}
policies[index] = policy
}
return policies, nil
}
func (s *importTraversal) walkDeclarations(basePath string, declarations []importDeclarationSpec, depth int, parentDestination Path, sourceIndex int) []Diagnostic {
policies, diagnostics := prepareImportDeclarations(declarations, s.policy.importDefaults, parentDestination)
if len(diagnostics) != 0 {
return diagnostics
}
for index, spec := range declarations {
policy := policies[index]
var selection importSelection

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

@@ -285,3 +285,58 @@ func importedVersionClaim(documents []*document.Node, scope acquisitionScope, co
}
return nil
}
// The declaring payload contributes once even when there are no admitted imports.
func chargeDeclaringImport(parsed parsedSource, accounting *importAccounting, limits importLimits) *Diagnostic {
accounting.sources++
accounting.bytes += parsed.bytes
accounting.nodes += countInputNodes(parsed.document)
if accounting.sources > limits.sources {
value := importDiagnostic(CodeImportLimitExceeded, "configuration exceeds the source-count limit", nil)
return &value
}
if accounting.bytes > limits.bytes {
value := importDiagnostic(CodeImportLimitExceeded, "configuration exceeds the aggregate byte limit", nil)
return &value
}
if accounting.nodes > limits.nodes {
value := importDiagnostic(CodeImportLimitExceeded, "configuration exceeds the aggregate node limit", nil)
return &value
}
return nil
}
func prepareDeclaringImportScope(root acquiredContribution, accounting *importAccounting, limits importLimits) (acquisitionScope, *Diagnostic) {
scope := acquisitionScope{owner: root.identity}
if root.source.placementMode == PlacementModeSequenceItem {
root.document = root.payload
} else {
destination := root.source.Destination
_, placed, err := placeDocument(root.payload, destination, root.payload.Location, maxDocumentDepth, maxDocumentNodes)
if err != nil {
diagnostic := sourceDiagnostic(CodeSourceLimitExceeded, root.source.ID, "configuration exceeds the source depth or node limit after destination placement")
return acquisitionScope{}, &diagnostic
}
placementNodes := destinationWrapperNodeCount(destination)
if accounting.nodes+placementNodes > limits.nodes {
diagnostic := importDiagnostic(CodeImportLimitExceeded, "configuration exceeds the aggregate node limit", nil)
return acquisitionScope{}, &diagnostic
}
accounting.nodes += placementNodes
root.document, root.destination = placed, destination.clone()
scope.destination = destination.clone()
}
scope.contributions = []acquiredContribution{root}
return scope, nil
}
func finalizeDeclaringImportScope(scope acquisitionScope, root acquiredContribution, accounting *importAccounting, limits importLimits) (acquisitionScope, *Diagnostic) {
if root.source.placementMode == PlacementModeSequenceItem {
root.destination = root.source.Destination.clone()
localScope := scope
root.pendingItem = &localScope
scope = acquisitionScope{owner: root.identity, destination: root.destination.clone(), contributions: []acquiredContribution{root}}
}
diagnostic := reservePendingItemPlacements(&scope, limits, accounting)
return scope, diagnostic
}

View File

@@ -25,21 +25,19 @@ func selectNamedImportCandidates(access *filesystemAccess, basePath string, spec
normalized := make([]selectedImportCandidate, 0, len(spec.paths))
seen := make(map[string]struct{}, len(spec.paths))
for index, relative := range spec.paths {
accessPath := access.join(basePath, relative)
candidatePath := accessPath
if access.native == nil {
candidatePath = filepath.ToSlash(filepath.Clean(accessPath))
site := spec.fieldSites["path"]
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)
if _, exists := seen[candidatePath]; exists {
continue
}
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})
}
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))
seenRoots := make(map[string]struct{}, len(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)
if _, exists := seenRoots[candidatePath]; exists {
continue
}
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})
}
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,
}
}
// 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
glob string
globSegments []string
globRoot string
required *bool
recursive *bool
follow *bool
@@ -124,7 +125,8 @@ func resolveImportPolicy(spec importDeclarationSpec, defaults ImportDefaults) (r
if spec.patternSet {
policy.pattern = cloneStrings(spec.pattern)
} else {
policy.pattern = cloneStrings(defaults.Pattern)
// Defaults belong to the load's snapshot. Selectors only read them.
policy.pattern = defaults.Pattern
}
}
if spec.depthSet && !policy.recursive {
@@ -326,6 +328,7 @@ func parseImportSelectorValue(spec *importDeclarationSpec, field string, node *d
return &diagnostic
}
spec.glob, spec.globSegments = node.Text, segments
spec.globRoot, _ = splitImportSelectorRoot(node.Text)
}
return nil
}

View File

@@ -232,7 +232,7 @@ func parseImportSpecsYAML(t *testing.T, declarations string) ([]importDeclaratio
if len(diagnostics) != 0 {
return nil, diagnostics
}
extracted, diagnostics := extractRootDirectives(parsed.document, rootDirectiveContextSource)
extracted, diagnostics := extractRootDirectives(parsed.document, rootDirectiveContextSource, sourceVersionContribution)
if len(diagnostics) != 0 {
return nil, diagnostics
}

View File

@@ -252,7 +252,7 @@ func TestLoadImportDirectiveValidationAndTemporaryGlobGate(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
directory := t.TempDir()
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)
}
}, 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},
}
for _, test := range tests {
@@ -869,8 +869,12 @@ settings: {root: retained}
if test.code == CodeImportMissing {
required = "\n required: true"
}
mainPath := writeImportFile(t, directory, "main.yml", "config:\n imports:\n - path: \""+test.path+"\""+required+"\n")
requireLoadCode(t, File(mainPath), Options[importTestConfig]{Imports: true}, test.code)
selectedPath := test.path
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)
}
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) {
@@ -1332,7 +1336,7 @@ func TestImportedParseAndDecodeDiagnosticsKeepTheirSource(t *testing.T) {
func TestOptionalImportDoesNotSuppressUnsafeOrUnreadableTargets(t *testing.T) {
directory := t.TempDir()
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")
if err := os.Chmod(locked, 0); err != nil {
@@ -1558,6 +1562,6 @@ func parseImportSpecificationYAML(input string) ([]importDeclarationSpec, []Diag
if len(diagnostics) != 0 {
return nil, diagnostics
}
_, declarations, diagnostics := splitImportDirectives(parsed.document)
_, declarations, diagnostics := splitImportDirectives(parsed.document, sourceVersionMain)
return declarations, diagnostics
}

View File

@@ -85,6 +85,13 @@ func TestLoadedConfigurationIsSeparateFromInspection(t *testing.T) {
if loaded.Inspection == 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"
var effective bytes.Buffer

View File

@@ -0,0 +1,75 @@
package engine
import (
"errors"
"io"
yamladapter "go.maximumdirect.net/configkit/internal/yaml"
)
// InspectionView borrows an inspection and selects a canonical reporting scope.
type InspectionView struct {
inspection *Inspection
scope Path
}
func NewInspectionView(inspection *Inspection, scope Path) (InspectionView, bool) {
if inspection == nil || !scope.valid() {
return InspectionView{}, false
}
normalized, err := ParsePath(scope.String())
if err != nil {
return InspectionView{}, false
}
return InspectionView{inspection: inspection, scope: normalized}, true
}
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) {
if v.inspection == nil || other.inspection == nil || v.scope.String() != other.scope.String() {
return nil, errors.New("configkit: diff inspection scope unavailable or mismatched")
}
values, err := Diff(v.inspection, other.inspection)
if err != nil {
return nil, err
}
var result []Difference
for _, value := range values {
if pathContains(v.scope, value.Path) || pathContains(value.Path, v.scope) {
result = append(result, value)
}
}
return result, nil
}
func (v InspectionView) WriteEffective(output io.Writer) error {
if v.inspection == nil || v.inspection.final == nil || output == nil {
return errEffectiveUnavailable
}
node, ok := documentAtPathWithLookup(v.inspection.final, v.scope, v.inspection.documentLookup())
if !ok {
return errEffectiveUnavailable
}
return yamladapter.Write(output, redactedDocument(node, v.inspection.secrets, v.scope))
}
func (v InspectionView) HistoricalPaths() []Path {
if v.inspection == nil {
return nil
}
var paths []Path
for _, path := range v.inspection.metadata.HistoricalPaths() {
if pathContains(v.scope, path) {
paths = append(paths, path)
}
}
return paths
}

View File

@@ -7,10 +7,16 @@ type Input struct {
Source Source
Imports bool
Filesystem *FilesystemContext
MainRelative *MainRelativeContext
Destination Path
PlacementMode PlacementMode
}
type MainRelativeContext struct {
Fallback *FilesystemContext
RequireBase bool
}
// Underlay contains strictly composed contributions at one precedence tier.
type Underlay struct{ Inputs []Input }
@@ -22,6 +28,7 @@ type LayeredOptions[T any] struct {
Underlays []Underlay
Overlay string
OverlayFilesystem *FilesystemContext
OverlayFallback *FilesystemContext
Overrides []Override
}
@@ -37,13 +44,14 @@ func LoadLayered[T any](main Input, secrets SecretBinding, supplied ...LayeredOp
}
request := loadRequest[T]{
main: loadInput{
source: main.Source, imports: main.Imports, filesystem: main.Filesystem,
source: main.Source, imports: main.Imports, filesystem: main.Filesystem, mainRelative: main.MainRelative,
destination: main.Destination.clone(), placementMode: main.PlacementMode,
},
definition: options.Definition, sourceVersionMode: options.SourceVersionMode,
importDefaults: options.ImportDefaults,
overlay: options.Overlay,
overlayFilesystem: options.OverlayFilesystem,
overlayFallback: options.OverlayFallback,
overrides: append([]Override(nil), options.Overrides...),
underlays: make([]loadGroup, len(options.Underlays)),
}
@@ -51,7 +59,7 @@ func LoadLayered[T any](main Input, secrets SecretBinding, supplied ...LayeredOp
request.underlays[index].inputs = make([]loadInput, len(underlay.Inputs))
for inputIndex, input := range underlay.Inputs {
request.underlays[index].inputs[inputIndex] = loadInput{
source: input.Source, imports: input.Imports, filesystem: input.Filesystem,
source: input.Source, imports: input.Imports, filesystem: input.Filesystem, mainRelative: input.MainRelative,
destination: input.Destination.clone(), placementMode: input.PlacementMode,
}
}

Some files were not shown because too many files have changed in this diff Show More