Skip to content

fix: SafeLoad must refuse, and "deny everything" must be expressible - #33

Merged
tannevaled merged 1 commit into
mainfrom
fix/permitted-classes-empty-means-deny
Oct 5, 2026
Merged

tannevaled merged 1 commit into
mainfrom
fix/permitted-classes-empty-means-deny

Conversation

@tannevaled

@tannevaled tannevaled commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes

WithPermittedClasses(names ...string) did:

return func(o *options) { o.permittedClasses = append(o.permittedClasses, names...) }

and the guard downstream was if o.permittedClasses != nil.

With zero names, append adds nothing and the slice stays nil. So
WithPermittedClasses() — permit no class, the most restrictive request this
API can express — arrived at the same nil as no option passed at all, and
took the no-policy branch. SafeLoad then materialised every class the
document named.

A second defect sat behind it: when the allow-list did apply, SafeLoad
rewrote an unpermitted !ruby/object: into its bare ivar mapping instead of
reporting it. A caller who asked for a refusal got a *Map — type confusion in
place of an error, and silent, because the document had "loaded successfully".

MRI source: what the default permitted set actually is

Ruby 4.0.5, bundled Psych.

Psych.safe_load's signature (psych.rb:323):

def self.safe_load yaml, permitted_classes: [], permitted_symbols: [], aliases: false, ...
  class_loader = ClassLoader::Restricted.new(permitted_classes.map(&:to_s),
                                             permitted_symbols.map(&:to_s))

Psych::ClassLoader::Restricted (psych/class_loader.rb:77-103):

class Restricted < ClassLoader
  def initialize classes, symbols
    @classes = classes
    @symbols = symbols
    super()
  end
  ...
  def find klassname
    if @classes.include? klassname then super
    else raise DisallowedClass.new('load', klassname) end
  end
end

@classes is seeded from permitted_classes and from nothing else. So in
MRI the restricted default set is empty, and "no keyword" and "the empty
list" are the same policy — refuse everything.

psych.rb:278-287 does document TrueClass / FalseClass / NilClass / Integer / Float / String / Array / Hash as permitted by default, and that is easy to
misread as a list Restricted holds. It holds none of their names. They load
because Psych::Visitors::ToRuby builds those shapes without consulting the
class loader at all. Everything that does reach it — Symbol, Time,
Date, Range, Regexp, Struct, BigDecimal, every !ruby/object: tag —
is refused until named.

Message, from psych/exception.rb:23-27:

class DisallowedClass < Exception
  def initialize action, klass_name
    super "Tried to #{action} unspecified class: #{klass_name}"

The change

The ambiguous state is deleted, not merely made distinguishable. SafeLoad
now always restricts; resolve is the only constructor of an options value
and seeds a non-nil allow-list, so there is no nil-vs-empty question left to
get wrong. Load is the unrestricted entry point, as Psych.unsafe_load is.

  • An unpermitted class returns a *DisallowedClassError carrying the name,
    with Psych's own message, so a host binding can surface it verbatim. No more
    degradation to a mapping.
  • The restriction is widened to what Psych's class loader gates, not just
    !ruby/object:: Symbol (in values and in keys), time.Time, Range
    (and its bounds), Regexp, and the class named by a !ruby/class /
    !ruby/module tag. Refusing tagged objects while interning Symbols and
    building Times was half a policy.
  • WithPermittedSymbols covers permitted_symbols:, including MRI's
    asymmetry: an empty symbol list narrows nothing
    (Restricted#symbolize short-circuits on @symbols.empty?,
    class_loader.rb:84-92), while an empty class list permits nothing. Narrowing
    is never a substitute for the class check — MRI's symbolize still routes
    through find("Symbol"), so permitted_symbols without Symbol in
    permitted_classes refuses every symbol. Measured, not inferred.
  • Aliases are refused by default, as Psych does. The parser cannot be asked
    after the fact — a resolved scalar alias is indistinguishable from a repeated
    literal — so the loader now reports alias use, and SafeLoad applies the
    policy: *AliasesNotEnabledError without WithAliases(true), and
    *AnchorNotDefinedError for an alias whose anchor the document never defines
    (which previously resolved to a silent nil).

Verification

  • Every expected value in the new tests was measured against ruby 4.0.5's
    bundled Psych, not inferred from the docs.
  • Coverage stays at 100.0% under -race (the repo's gate).
  • go vet clean, gofmt -l empty, GOOS=wasip1 and GOOS=js (GOARCH=wasm)
    both build.

Three existing tests asserted the old behaviour and are replaced by the
positive invariant, because they were assertions of the defect — fixing the
library turned them red, which is the point:

  • TestSafeLoad required an unpermitted object to come back as a *Map
    ("unpermitted Secret should be a Map"), and required a missing allow-list to
    keep every object ("no allow-list should keep objects").
  • TestSafeLoadRangeRestrict required a range bound to be degraded.

The 100% gate also named one branch this change introduced as unreachable — a
nil check inside WithPermittedClasses — and it was: resolve establishes
the invariant before any Option runs. It is gone rather than registered,
since an unreachable "just in case" nil is how this defect existed in the
first place.

Paired PR

Paired with go-embedded-ruby/ruby#786 (rbgo's YAML.safe_load, fixing go-embedded-ruby/ruby#775).

rbgo does not need a tagged release of this library to be fixed: its PR
loads with Load and enforces Psych's restriction in its own Psych binding,
where the Psych-specific semantics belong. Once this merges and is tagged, that
binding can delegate here and drop its copy of the walk — a clean follow-up,
not a blocker.

🤖 Generated with Claude Code

WithPermittedClasses(names ...string) did `append(o.permittedClasses,
names...)` and the guard downstream was `if o.permittedClasses != nil`.
With ZERO names that appends nothing and leaves the slice nil, so
WithPermittedClasses() -- "permit no class", the most restrictive request
the API can express -- arrived at the same nil as "no option passed" and
took the no-policy branch, materialising every class in the document.

The fix deletes that state rather than making it merely distinguishable.
SafeLoad now ALWAYS restricts, and resolve() is the single constructor of an
options value, so the allow-list is a non-nil set everywhere. Load is the
unrestricted entry point, as Psych.unsafe_load is. This matches Psych, whose
safe_load signature is `permitted_classes: []`: Restricted seeds its
allow-list from that list alone (psych/class_loader.rb:78-82), so absent and
empty are the same policy there, and that policy refuses everything.

SafeLoad also no longer DEGRADES an unpermitted object into its bare ivar
mapping. A caller that asked for a refusal got a *Map -- type confusion in
place of an error, and silent, because the document had "loaded". It now
returns a *DisallowedClassError carrying the class name, with
Psych::DisallowedClass's own message so a host binding surfaces it verbatim.

The restriction is widened to what Psych's class loader actually gates:
Symbol (in values AND in keys), time.Time, Range, Regexp, and the class
NAMED by a !ruby/class / !ruby/module tag. Refusing tagged objects while
interning Symbols and building Times was half a policy.
WithPermittedSymbols covers permitted_symbols:, including the asymmetry that
an EMPTY symbol list narrows nothing while an empty class list permits
nothing (Restricted#symbolize short-circuits on @symbols.empty?).

Aliases are refused by default, as Psych does. The parser cannot be asked
after the fact -- a resolved scalar alias is indistinguishable from a
repeated literal -- so the loader now REPORTS alias use, and SafeLoad applies
the policy: *AliasesNotEnabledError without WithAliases(true), and
*AnchorNotDefinedError for an alias whose anchor the document never defines
(which previously resolved to a silent nil).

Every expected value in the new tests was measured against ruby 4.0.5's
bundled Psych. Three tests that asserted the old behaviour are replaced by
the positive invariant, because they were assertions of the defect: one
required an unpermitted object to come back as a *Map, and one required a
missing allow-list to keep every object.

Coverage stays at 100% under -race. The gate named one branch this change
introduced as unreachable -- a nil check in WithPermittedClasses -- and it
was: resolve establishes the invariant before any Option runs. It is gone
rather than registered, since an unreachable "just in case" nil is how this
defect existed in the first place.

Paired with go-embedded-ruby/ruby#775. rbgo does NOT need a release of this
library to be fixed: it loads with Load and enforces Psych's restriction in
its own Psych binding. Once this is tagged, that binding can delegate here
and drop its copy of the walk.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@tannevaled
tannevaled merged commit b55f761 into main Oct 5, 2026
11 checks passed
@tannevaled
tannevaled deleted the fix/permitted-classes-empty-means-deny branch October 5, 2026 14:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant