Skip to content

Commit 9182fa1

Browse files
roc-opsclaude
andauthored
fix(yang): enforce pattern, enum/identityref, integers, choice/case and wrong-level paths (#126)
* fix(yang): reject fractional numbers in integer leaves (#50) validateValueType accepted any float64 for int/uint kinds, so 12.5 validated against a uint8 leaf. RFC 7950 9.2 integer types admit whole numbers only. A whole float64 (what a JSON round trip makes of an int) is still accepted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(yang): type-check leaves under choice/case (#59) Field lookups used schemaEntry.Dir[name] directly, so a leaf under a choice/case came back as a 'not defined' warning and was never checked. choice and case are schema-only nodes (RFC 7950 7.9); the lookup now descends through them, including nested choices and shorthand cases. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(yang): check enumeration and identityref membership (#56) Enum and identityref leaves accepted any string, so a union with an enum member accepted anything. An enum value must now be one of the declared names (RFC 7950 9.6). An identityref value must name an identity derived from the base, the base itself excluded (RFC 7950 9.10.2), in the RFC 7951 6.8 JSON form: 'module:identity', with the module optional only for an identity in the leaf's own module. Errors name the bad value and the allowed set instead of reporting an 'invalid type string'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(yang): enforce pattern restrictions (#55) A leaf's pattern statements were a TODO, so any string passed. They are now checked with XSD regex semantics (RFC 7950 9.4.5): the whole value must match, all patterns must hold, and 'modifier invert-match' inverts one. The XSD expression is translated to an anchored RE2 regexp: ^ and $ are literals, '.' excludes \n and \r, and \d, \s and \w get their XSD (Unicode) meaning. goyang drops the modifier, so it is recovered from the parsed statements. Patterns RE2 can't express (\i, \c, Unicode block escapes, class subtraction, a negated class with \S or \w) are reported as a warning, once per Validate call, instead of passing silently. A union member's patterns decide whether a value belongs to that member. The translator is checked against yangson 1.7.9 (what Python TTP uses); the three differing cases follow XSD, where elementpath hands \s and \w to Python's re unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(yang): fail a yang= path that names none of the group's fields (#57) A path one level too high (the container instead of the list each match maps to) turned every field into a 'not defined' warning and returned Valid=true, so nothing was checked. When the data has fields and none of them is defined under the path (or the path names a leaf), Validate now adds one error for the group, naming the fields and suggesting the child paths that do define them. A path matching some fields keeps the old behaviour: unknown fields stay warnings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: CHANGELOG entry for stricter YANG validation (#50, #55, #56, #57, #59) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * build(editor): rebuild WASM with stricter YANG validation So the editor validates yang= groups the same way as the library after #50, #55, #56, #57 and #59. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1ed4ea0 commit 9182fa1

10 files changed

Lines changed: 1213 additions & 31 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@ All notable changes to GoTTP will be documented in this file.
1313
### Changed (breaking: matching)
1414
- **Indented template lines match the exact indent**: a template line's leading whitespace was turned into `[ \t]+`, so a line indented by two spaces also matched data indented by one space, four spaces or a tab. Python TTP rebuilds the indent verbatim, and gottp now does the same: two spaces match exactly two spaces, and a tab matches only a tab. Unindented lines are unchanged, and so is whitespace inside a line, which still matches any run of spaces and tabs. Templates that relied on the loose match need their indent to match the data. Templates saved with `SaveCompiledTemplate` keep the regex they were compiled with until they are compiled again. (#30)
1515

16+
### Changed (stricter YANG validation)
17+
These fixes make `ParseWithValidation` report problems it used to pass, so output that was `Valid=true` can now be `Valid=false`. Parsed data is unchanged; only `ValidationResults` differ.
18+
- **Integer leaves reject fractional numbers**: `12.5` no longer validates as a `uint8` (RFC 7950 9.2). A whole `float64` such as `12.0` (what a JSON round trip makes of an int) is still accepted. (#50)
19+
- **`pattern` is enforced**: a string leaf must match all its patterns as a whole value, with XSD regex semantics (RFC 7950 9.4.5), and `modifier invert-match` is honoured. Patterns RE2 can't express (`\i`, `\c`, `\p{IsBlock}`, class subtraction) give a warning, once per group, instead of passing silently. (#55)
20+
- **Enumeration and identityref membership is checked**: an enum leaf takes only its declared names, and an identityref only an identity derived from its base, in the RFC 7951 `module:identity` form (the module may be left out for an identity in the leaf's own module). A `union` with an enum member no longer accepts any string. (#56)
21+
- **A `yang=` path at the wrong level is an error**: when none of a group's fields is defined under its path (for example the container instead of the list each match maps to), the result is `Valid=false` with one error that suggests the right path, instead of `Valid=true` with only warnings. (#57)
22+
- **Leaves under `choice`/`case` are validated**: they were reported as "not defined" warnings and never type-checked. (#59)
23+
1624
## [v0.1.13] - 2026-09-03
1725

1826
### Fixed

‎editor/gottp.wasm‎

67.6 KB
Binary file not shown.

‎editor/js/gottp.wasm‎

67.6 KB
Binary file not shown.

‎internal/yang/errors.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ type ValidationError struct {
1010
Field string
1111
Line int
1212
Column int
13+
14+
once bool // a warning reported once per Validate call, not per item
1315
}
1416

1517
// Error implements the error interface
@@ -36,4 +38,3 @@ func (r *ValidationResult) HasErrors() bool {
3638
func (r *ValidationResult) HasWarnings() bool {
3739
return len(r.Warnings) > 0
3840
}
39-

‎internal/yang/module.go‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@ type ModuleSet struct {
1313
mu sync.RWMutex
1414
modules map[string]*yang.Module
1515
schemas map[string]*yang.Entry
16-
mset *yang.Modules // Shared Modules instance for dependency resolution
17-
addedModules map[string]bool // Track which modules we've added (for error messages)
18-
prefixToModule map[string]string // Map prefix to module name (e.g., "cms" -> "example-cable-modem-state")
16+
mset *yang.Modules // Shared Modules instance for dependency resolution
17+
addedModules map[string]bool // Track which modules we've added (for error messages)
18+
prefixToModule map[string]string // Map prefix to module name (e.g., "cms" -> "example-cable-modem-state")
19+
patternUses map[string]patternUse // pattern string -> whether it is used with invert-match
1920
}
2021

2122
// NewModuleSet creates a new empty ModuleSet
@@ -99,6 +100,10 @@ func (ms *ModuleSet) ProcessAllModules() error {
99100
return fmt.Errorf("failed to process YANG modules: %s", strings.Join(errorMsgs, "; "))
100101
}
101102

103+
ms.patternUses = make(map[string]patternUse)
104+
collectPatternModifiers(ms.mset.Modules, ms.patternUses)
105+
collectPatternModifiers(ms.mset.SubModules, ms.patternUses)
106+
102107
// Update stored modules and schemas after processing
103108
for name, module := range ms.mset.Modules {
104109
ms.modules[name] = module
@@ -117,6 +122,16 @@ func (ms *ModuleSet) ProcessAllModules() error {
117122
return nil
118123
}
119124

125+
// patternModifier reports whether pattern p carries "modifier invert-match"
126+
// in the loaded modules, and whether it is ambiguous because it is used both
127+
// with and without it.
128+
func (ms *ModuleSet) patternModifier(p string) (invert, ambiguous bool) {
129+
ms.mu.RLock()
130+
defer ms.mu.RUnlock()
131+
use := ms.patternUses[p]
132+
return use == patternInverted, use == patternPlain|patternInverted
133+
}
134+
120135
// GetModule retrieves a module by name
121136
func (ms *ModuleSet) GetModule(name string) (*yang.Module, bool) {
122137
ms.mu.RLock()
@@ -161,6 +176,7 @@ func (ms *ModuleSet) Clear() {
161176
ms.addedModules = make(map[string]bool)
162177
ms.prefixToModule = make(map[string]string)
163178
ms.mset = yang.NewModules() // Reset the shared Modules instance
179+
ms.patternUses = nil
164180
}
165181

166182
// FindSchemaByPath finds a schema entry by YANG path

‎internal/yang/pattern.go‎

Lines changed: 293 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,293 @@
1+
package yang
2+
3+
import (
4+
"fmt"
5+
"regexp"
6+
"strings"
7+
"sync"
8+
9+
"github.com/openconfig/goyang/pkg/yang"
10+
)
11+
12+
// YANG pattern statements (RFC 7950 9.4.5) are XML Schema regular
13+
// expressions (XSD 1.0 Part 2, Appendix F). They differ from Go's RE2:
14+
//
15+
// - a pattern matches the whole value; there are no anchors, so ^ and $
16+
// are ordinary characters;
17+
// - "." excludes only \n and \r;
18+
// - \d, \s and \w are Unicode-aware (\w is everything except punctuation,
19+
// separators and "other" characters, so it excludes '_');
20+
// - XSD has \i, \c, Unicode block escapes (\p{IsBasicLatin}) and character
21+
// class subtraction ([a-z-[aeiou]]), which RE2 can't express.
22+
//
23+
// xsdToRE2 translates the subset RE2 can express and returns an error
24+
// naming the construct otherwise.
25+
26+
// Replacements for XSD multi-character escapes. "in" is the text to use
27+
// inside a positive character class; complement is set when the escape is
28+
// the complement of a set, which RE2 can't put inside another class.
29+
var xsdClassEscapes = map[byte]struct {
30+
out string // replacement outside a character class
31+
in string // set members, for use inside a class
32+
complement bool // in is the set to exclude, not include
33+
}{
34+
'd': {`\p{Nd}`, `\p{Nd}`, false},
35+
'D': {`\P{Nd}`, `\P{Nd}`, false},
36+
's': {`[ \t\n\r]`, ` \t\n\r`, false},
37+
'S': {`[^ \t\n\r]`, ` \t\n\r`, true},
38+
'w': {`[^\p{P}\p{Z}\p{C}]`, `\p{P}\p{Z}\p{C}`, true},
39+
'W': {`[\p{P}\p{Z}\p{C}]`, `\p{P}\p{Z}\p{C}`, false},
40+
}
41+
42+
// XSD single-character escapes (\n, \r, \t and the metacharacters).
43+
const xsdSingleEscapes = `nrt\|.-^?*+{}()[]`
44+
45+
// xsdToRE2 translates an XSD regular expression to an anchored Go regexp.
46+
func xsdToRE2(p string) (string, error) {
47+
var b strings.Builder
48+
b.WriteString(`\A(?:`)
49+
for i := 0; i < len(p); i++ {
50+
c := p[i]
51+
switch c {
52+
case '\\':
53+
if i+1 >= len(p) {
54+
return "", fmt.Errorf("trailing backslash")
55+
}
56+
esc, n, err := translateEscape(p[i+1:], false)
57+
if err != nil {
58+
return "", err
59+
}
60+
b.WriteString(esc.out)
61+
i += n
62+
case '[':
63+
cls, n, err := translateClass(p[i:])
64+
if err != nil {
65+
return "", err
66+
}
67+
b.WriteString(cls)
68+
i += n - 1
69+
case '.':
70+
b.WriteString(`[^\n\r]`)
71+
case '^', '$':
72+
b.WriteByte('\\')
73+
b.WriteByte(c)
74+
case '(':
75+
if i+1 < len(p) && p[i+1] == '?' {
76+
return "", fmt.Errorf("'(?' is not XSD regex syntax")
77+
}
78+
b.WriteByte(c)
79+
default:
80+
b.WriteByte(c)
81+
}
82+
}
83+
b.WriteString(`)\z`)
84+
return b.String(), nil
85+
}
86+
87+
type translatedEscape struct {
88+
out string
89+
in string
90+
complement bool
91+
}
92+
93+
// translateEscape translates the escape that follows a backslash. s starts
94+
// after the backslash; n is the number of bytes of s consumed.
95+
func translateEscape(s string, inClass bool) (translatedEscape, int, error) {
96+
c := s[0]
97+
if e, ok := xsdClassEscapes[c]; ok {
98+
return translatedEscape{e.out, e.in, e.complement}, 1, nil
99+
}
100+
if strings.IndexByte(xsdSingleEscapes, c) >= 0 {
101+
esc := `\` + string(c)
102+
return translatedEscape{esc, esc, false}, 1, nil
103+
}
104+
switch c {
105+
case 'p', 'P':
106+
end := strings.IndexByte(s, '}')
107+
if len(s) < 2 || s[1] != '{' || end < 0 {
108+
return translatedEscape{}, 0, fmt.Errorf("malformed \\%c escape", c)
109+
}
110+
name := s[2:end]
111+
if strings.HasPrefix(name, "Is") {
112+
return translatedEscape{}, 0, fmt.Errorf("block escape \\%c{%s} (a Unicode block) is not supported by RE2", c, name)
113+
}
114+
esc := s[:end+1]
115+
return translatedEscape{`\` + esc, `\` + esc, false}, end + 1, nil
116+
case 'i', 'I', 'c', 'C':
117+
return translatedEscape{}, 0, fmt.Errorf("XML name escape \\%c is not supported by RE2", c)
118+
}
119+
return translatedEscape{}, 0, fmt.Errorf("unknown escape \\%c", c)
120+
}
121+
122+
// translateClass translates the character class at the start of s and
123+
// returns the number of bytes consumed.
124+
func translateClass(s string) (string, int, error) {
125+
i := 1
126+
negated := false
127+
if i < len(s) && s[i] == '^' {
128+
negated = true
129+
i++
130+
}
131+
var members strings.Builder
132+
var complements []string
133+
for first := true; ; first = false {
134+
if i >= len(s) {
135+
return "", 0, fmt.Errorf("unterminated character class")
136+
}
137+
c := s[i]
138+
switch {
139+
case c == ']' && !first:
140+
i++
141+
return buildClass(negated, members.String(), complements, s[:i])
142+
case c == '-' && i+1 < len(s) && s[i+1] == '[':
143+
return "", 0, fmt.Errorf("character class subtraction is not supported by RE2")
144+
case c == '\\':
145+
if i+1 >= len(s) {
146+
return "", 0, fmt.Errorf("trailing backslash")
147+
}
148+
esc, n, err := translateEscape(s[i+1:], true)
149+
if err != nil {
150+
return "", 0, err
151+
}
152+
if esc.complement {
153+
complements = append(complements, esc.in)
154+
} else {
155+
members.WriteString(esc.in)
156+
}
157+
i += 1 + n
158+
case c == '[' || c == '^':
159+
// Literal in XSD; escaped so RE2 doesn't read [:alpha:].
160+
members.WriteByte('\\')
161+
members.WriteByte(c)
162+
i++
163+
default:
164+
members.WriteByte(c)
165+
i++
166+
}
167+
}
168+
}
169+
170+
func buildClass(negated bool, members string, complements []string, src string) (string, int, error) {
171+
if len(complements) == 0 {
172+
if negated {
173+
return "[^" + members + "]", len(src), nil
174+
}
175+
return "[" + members + "]", len(src), nil
176+
}
177+
if negated {
178+
// [^a\w] is (not a) and (not \w): an intersection RE2 can't write.
179+
return "", 0, fmt.Errorf("negated character class %s with \\S or \\w is not supported by RE2", src)
180+
}
181+
alts := make([]string, 0, len(complements)+1)
182+
if members != "" {
183+
alts = append(alts, "["+members+"]")
184+
}
185+
for _, c := range complements {
186+
alts = append(alts, "[^"+c+"]")
187+
}
188+
return "(?:" + strings.Join(alts, "|") + ")", len(src), nil
189+
}
190+
191+
// compiledPattern is a translated, compiled YANG pattern, or the reason it
192+
// can't be checked.
193+
type compiledPattern struct {
194+
re *regexp.Regexp
195+
err error
196+
}
197+
198+
var patternCache sync.Map // XSD pattern -> *compiledPattern
199+
200+
func compilePattern(p string) *compiledPattern {
201+
if cp, ok := patternCache.Load(p); ok {
202+
return cp.(*compiledPattern)
203+
}
204+
cp := &compiledPattern{}
205+
if expr, err := xsdToRE2(p); err != nil {
206+
cp.err = err
207+
} else if cp.re, err = regexp.Compile(expr); err != nil {
208+
cp.err = fmt.Errorf("RE2 rejects the translation: %v", err)
209+
}
210+
actual, _ := patternCache.LoadOrStore(p, cp)
211+
return actual.(*compiledPattern)
212+
}
213+
214+
// patternFailure is a pattern a value failed, for an error message.
215+
type patternFailure struct {
216+
pattern string
217+
invert bool
218+
}
219+
220+
// checkPatterns checks s against every pattern of yangType (RFC 7950
221+
// 9.4.5: all must hold). It returns the first pattern that fails. Patterns
222+
// that can't be checked are skipped; uncheckablePatterns reports them.
223+
func (v *Validator) checkPatterns(s string, yangType *yang.YangType) (patternFailure, bool) {
224+
for _, p := range yangType.Pattern {
225+
cp := compilePattern(p)
226+
if cp.err != nil {
227+
continue
228+
}
229+
invert, ambiguous := v.moduleSet.patternModifier(p)
230+
if ambiguous {
231+
continue
232+
}
233+
if cp.re.MatchString(s) == invert {
234+
return patternFailure{p, invert}, false
235+
}
236+
}
237+
return patternFailure{}, true
238+
}
239+
240+
// uncheckablePatterns describes the patterns of yangType (and of its union
241+
// members) that can't be checked.
242+
func (v *Validator) uncheckablePatterns(yangType *yang.YangType) []string {
243+
if yangType == nil {
244+
return nil
245+
}
246+
var out []string
247+
for _, p := range yangType.Pattern {
248+
if cp := compilePattern(p); cp.err != nil {
249+
out = append(out, fmt.Sprintf("pattern '%s' cannot be checked: %v", p, cp.err))
250+
} else if _, ambiguous := v.moduleSet.patternModifier(p); ambiguous {
251+
out = append(out, fmt.Sprintf("pattern '%s' cannot be checked: the loaded modules use it both with and without 'modifier invert-match'", p))
252+
}
253+
}
254+
for _, member := range yangType.Type {
255+
out = append(out, v.uncheckablePatterns(member)...)
256+
}
257+
return out
258+
}
259+
260+
// collectPatternModifiers records which pattern strings carry
261+
// "modifier invert-match". goyang flattens a type's patterns to strings and
262+
// drops the modifier, so it is recovered from the parsed statements.
263+
func collectPatternModifiers(mods map[string]*yang.Module, into map[string]patternUse) {
264+
var walk func(s *yang.Statement)
265+
walk = func(s *yang.Statement) {
266+
if s == nil {
267+
return
268+
}
269+
if s.Keyword == "pattern" {
270+
use := patternPlain
271+
for _, sub := range s.SubStatements() {
272+
if sub.Keyword == "modifier" && sub.Argument == "invert-match" {
273+
use = patternInverted
274+
}
275+
}
276+
into[s.Argument] |= use
277+
}
278+
for _, sub := range s.SubStatements() {
279+
walk(sub)
280+
}
281+
}
282+
for _, m := range mods {
283+
walk(m.Source)
284+
}
285+
}
286+
287+
// patternUse records how a pattern string is used across the loaded modules.
288+
type patternUse uint8
289+
290+
const (
291+
patternPlain patternUse = 1 << iota // used without invert-match
292+
patternInverted // used with invert-match
293+
)

0 commit comments

Comments
 (0)