File-SOPS

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

    refusal itself is unchanged. (k197)

0.003     2026-09-03 16:02:56Z
  - DATA LOSS: multi-document YAML is read and written: decrypt returns an
    ArrayRef of HashRefs for a stream (one document stays a HashRef), encrypt
    accepts one, extract takes document => $n, and one MAC spans all documents.
    A stream used to be silently reduced to its last document on write. (k31)
  - New ENV (dotenv) and INI format handlers (format => 'env' | 'ini'), full
    round-trips against sops in both directions, comments included. (k36, k37)
  - A "True"/"False" string and the non-finite spellings .inf/.Inf/.INF/+.inf/
    -.inf/.nan/.NaN are written double-quoted, as sops writes them, instead of
    bare (where Go read a boolean or a float back). (k99)
  - decrypt_file and edit write those same spellings quoted too, so decrypt_file
    is a faithful inverse of what sops wrote instead of flipping such a leaf back
    to a float or boolean on the next encrypt. (k186)
  - The four encryption rules (unencrypted_suffix, encrypted_suffix,
    unencrypted_regex, encrypted_regex) are usable as arguments to encrypt and
    encrypt_file, or carried via metadata => $meta.
  - New method encrypt_in_place: encrypt a single file atomically, permissions
    preserved.
  - New method edit: decrypt, open $EDITOR, re-encrypt; returns 0 when nothing

docs/adr/0006-floats-are-emitted-in-a-form-that-parses-back-to-the-same-double.md  view on Meta::CPAN

  and are then consistently wrong together — so the walk lives in
  `File::SOPS::Encrypted` next to `value_to_bytes` and `_sv_kind`, and the
  format handlers supply only the round-trip predicate and the carrier.
- **The carrier is format-specific.** YAML uses `Scalar::Util::dualvar($nv,
  $text)`; JSON uses `Math::BigFloat->new($text, undef, undef)` with a
  dedicated `allow_bignum` encoder instance.
- **The walk runs on a copy of the tree, at emit time, after the digest.** A
  `Math::BigFloat` leaf is a blessed reference, so `detect_type` would call it
  `str` and `value_to_bytes` would write the wrong bytes. The carriers must
  never be visible to the MAC walk.
- **`NaN`, `+Inf`, `-Inf` and `-0` are excluded** and keep exactly today's
  behaviour. They are a different defect with different answers per format —
  YAML `-0.0` has no representation that works, JSON has none for the
  non-finite values at all — and they belong to k62.

  **Amended by k62 — `-0` is no longer excluded, because the premise
  above was wrong.** "YAML `-0.0` has no representation that works" was
  derived, not measured: the reasoning was that the canonical text `-0` is
  resolved by Go's yaml.v3 as an *integer*, digested as `0`, and so still
  mismatches a digest of `-0`. That much is true. What nobody tried was any
  other spelling. Measured against sops 3.13.3, one document per spelling,

docs/adr/0006-floats-are-emitted-in-a-form-that-parses-back-to-the-same-double.md  view on Meta::CPAN

  is what ADR 0005 was paid for. `t/24` section 3 pins it and section 9 pins
  the new behaviour.

  **Neither implementation could write this value before.** `sops -e` on a
  plaintext `-0.0` emits `-0` and then rejects its own file with exit 51, in
  YAML *and* in JSON. So `-0.0` is not "the bytes sops writes"; it is the only
  spelling both implementations read back as the double the digest covers.
  There is consequently no sops→us fixture for this value, and the test says
  so rather than inventing one.

  `NaN`, `+Inf` and `-Inf` stay excluded, and k59 has since made them
  unreachable on the encrypt path anyway (`assert_representable` refuses
  them); only the plaintext emitters can still reach the walk with one.

  **Amended by k72 — the READ side dropped the same sign, and no longer
  does.** The amendment above carried a negative zero *out* of the library;
  `File::SOPS::Encrypted::_deserialize_value` was still losing it on the way
  *in*. It converted a `type:float` plaintext with `$data + 0.0`, which is
  positive zero twice over: Perl's `grok_number` settles the text `-0` as an
  **integer** zero, which has no sign to keep, and IEEE round-to-nearest makes
  even a genuine `-0.0 + 0.0` come out `+0.0`. Go's

docs/adr/0006-floats-are-emitted-in-a-form-that-parses-back-to-the-same-double.md  view on Meta::CPAN

  both go through the same `emit`. That closes the silent-corruption path
  above. `extract` is untouched — it hands the caller an NV, and any
  stringification of that still loses the digits; see k61.
- The two format handlers each grew a predicate and a carrier. They are not a
  duplicated conversion — the conversion is one call in one module — but they
  are two places that must both be updated if a third format handler appears.

### What changes for existing callers

Nothing, for every value that works today: `1.0`, `0.5`, `1e+20`, `1e-20`,
`-0.0` in JSON, `NaN` in YAML all emit the same bytes as before, verified case
by case against the binary. Documents that already fail — the 16/17-digit
floats — start working. No API, no argument and no error message changes.

A caller who was relying on File::SOPS writing `0.3` where sops writes
`0.30000000000000004` was relying on a document neither implementation could
read.

Under the k72 amendment a caller that read an encrypted `-0` back out of
`decrypt` gets `-0.0` where it used to get `+0.0`. `==`, `<` and `sprintf
"%s"` cannot tell the two apart in Perl — `print -0.0` writes `0` — so this is

docs/adr/0006-floats-are-emitted-in-a-form-that-parses-back-to-the-same-double.md  view on Meta::CPAN

## Rejected alternatives

**Derive the digest from the document instead of from the tree** (k58
option b). This inverts ADR 0001, which states that the reparse "supplies order
and nothing else… Nothing YAML::PP produces reaches the digest as data, so a
divergence in how it *represents* a scalar cannot change a MAC". Option (b)
makes that representation the digest's data source, and the two parsers do
diverge: of 29 YAML scalars tested, `YAML::XS` (libyaml, YAML 1.1) and
`YAML::PP` (YAML 1.2 core) resolve **7** differently — `0o17` (`0o17` vs `15`),
`0x1f` (`0x1f` vs `31`), `NULL` and `Null` (string vs undef), `.inf` (`.inf` vs
`+Inf`), `.nan` (`.nan` vs `NaN`), `Inf` (`+Inf` vs `Inf`). It would trade one
wrong-value class for seven. It is also structurally awkward on the encrypt
side, where the digest goes *into* the document as `sops.mac` and so would need
emit → reparse → hash → re-emit, and where encrypted leaves are digested over
plaintext that is not in the document at all — a digest with two sources.
Decisively: it does not fix the bug, it ratifies it. A digest over what the
emitter wrote means storing `0.3` where the caller passed
`0.30000000000000004`, with the document verifying and nothing reported. That
is precisely the `edit` behaviour this ADR removes.

**Refuse a float that does not survive its own emitter** (option c), by analogy

docs/adr/0010-extract-returns-a-float-that-prints-all-its-digits.md  view on Meta::CPAN

**bare number** — measured, byte-identical to the bare-NV document for the
17-digit case, `sops -d` exit 0 with a number read back. The restriction above
still stands, and for the reason the *second* row gives: a dualvar in a tree
still changes what gets written at the magnitudes where `value_to_bytes`'s
positional spelling differs from the emitter's exponent one (`1e300`, `1e20`,
`1e-7`, …, in **both** formats). Those documents are correct — measured, exit 0
and the same double — but they are not the bytes the same value produces
without the dualvar, which is reason enough to keep it out of the trees this
library builds.

- **A non-finite float is returned unchanged.** `NaN`, `+Inf` and `-Inf` are
  `value_to_bytes`'s wire spellings, not a number's decimal; they are already
  `$NO_AGREED_FORM` to the emitters, and `assert_representable` refuses them on
  the encrypt path.

### The spelling is the wire's, which is not always sops's

`value_to_bytes` writes Go's `strconv.FormatFloat(v, 'f', -1, 64)` — shortest
round-tripping digits, **always positional**. `sops -d --extract` prints the
value's YAML/JSON *serialization*, which switches to an exponent at the
magnitudes Go's `%g` does. Measured, same document, sops 3.13.3, **YAML**:

docs/adr/0013-a-yaml-spelling-the-go-parser-resolves-differently-is-refused.md  view on Meta::CPAN

| source | this library | document | Go reads | `sops -d` |
|---|---|---|---|---|
| `0755` | `int` 755 | `0755` | 493 | **exit 51** |
| `010` | `int` 10 | `010` | 8 | **exit 51** |
| `017` | `int` 17 | `017` | 15 | **exit 51** |
| `-010` / `+010` | `int` -10 / 10 | as written | -8 / 8 | **exit 51** |
| `0o10` / `0O10` / `0o7` / `0o0` | `str` | as written | 8 / 8 / 7 / 0 | **exit 51** |
| `0x1f` / `0X1F` / `-0x1f` | `str` | as written | 31 / 31 / -31 | **exit 51** |
| `0b101` / `0b0` | `str` | as written | 5 / 0 | **exit 51** |
| `1_000` / `0_7` / `0_` / `685_230.15` / `1_0.5` | `str` | as written | 1000 / 7 / 0 / 685230.15 / 10.5 | **exit 51** |
| `.inf` `.Inf` `.INF` `+.inf` `-.inf` `.nan` `.NaN` | `str` | as written | ±Inf / NaN | **exit 51** |
| `Null` / `NULL` | `str` | as written | null | **exit 51** |
| `TRUE` / `FALSE` | `str` | as written | true / false | **exit 51** |
| `2015-01-01` | `str` | as written | a time, rendered `2015-01-01T00:00:00Z` | **exit 51** |
| `2015-1-2`, `2015-01-01 12:00:00`, `2015-01-01t12:00:00Z` | `str` | as written | a time, rendered otherwise | **exit 51** |

and, in the same run and by the same mechanism, the rows that **agree**:

| source | this library | Go reads | `sops -d` |
|---|---|---|---|
| `007` / `00` / `000` | `int` 7 / 0 / 0 | octal 7 / 0 / 0 | exit 0 |

docs/adr/0023-a-yaml-literal-that-overflows-a-double-is-a-string-not-a-float.md  view on Meta::CPAN

| `2**1024 - 2**970 - 1` | `type:float`, wire `1.7976931348623157e+308` |
| `2**1024 - 2**970` | **`type:str`**, wire verbatim |

**Perl flips at the same token.** `YAML::XS` returns the first as a finite NV of
`1.7976931348623157e308` and the second as `+Inf`. Go's `ErrRange` and Perl's NV
going non-finite are one IEEE-754 condition, so the model this decision needs
does not have to be invented — it is already in the SV.

### The same mechanism, a second class of spellings

`Inf inf INF Infinity infinity NaN nan NAN -Inf +Inf -inf +inf -nan` come back
from `YAML::XS` the same way: `SVf_NOK` set, `SVf_POK` set, NV non-finite. sops
leaves every one of them a `type:str` and writes it verbatim, exit 0. They are
not a separate ticket; they are the same defect reached by a different spelling,
and the same repair covers them.

### What was broken, counted

20 documents, each `keep: x` plus one of the 10 overflow literals or 10
spellings in an unencrypted slot, written by `sops -e` and read back by
`sops -d` (exit 0 for all 20). At c8eee80:

| direction | before | after |
|---|---|---|
| `sops -e` → `File::SOPS->decrypt` | **3 of 20 read** | 20 of 20 |
| `File::SOPS->encrypt` → `sops -d` | **0 of 20 written** (20 croaks) | 20 of 20, `type:str` as sops writes |

The three that read are `NaN`, `-Inf` and `+Inf`, and they read by coincidence:
`FormatFloat` happens to render those three doubles as the very text the source
token used. Every other spelling digested `+Inf` where Go digested the token.

### Why the predicate cannot retype a leaf Go reads as a float

This is the claim the whole change rests on, and it was verified against the
binary rather than argued.

The only tokens go-yaml resolves to a real non-finite float are the twelve in
`Format::YAML`'s `%GO_CONSTANT`: `.inf .Inf .INF +.inf +.Inf +.INF -.inf -.Inf
-.INF .nan .NaN .NAN`. **`YAML::XS` hands back every one of them `SVf_POK`
only** — a plain string, no NV — so none of them can fire a predicate that
requires `SVf_NOK`. Measured both ways:

| set | size | `sops -e` says | fires the predicate |
|---|---|---|---|
| `%GO_CONSTANT`'s inf/nan tokens | 12 | `type:float` | **0 of 12** |
| tokens the predicate fires on | 29 | `type:str`, all 29 | 29 of 29 |

The 29 are the whole firing set of an 80-token sweep of every shape libyaml
resolves numerically at overflow magnitude — decimal integers, exponent floats,

docs/adr/0023-a-yaml-literal-that-overflows-a-double-is-a-string-not-a-float.md  view on Meta::CPAN

**The two sets are disjoint, with the binary as the witness.**

## Decision

**`File::SOPS::Format::YAML::parse` replaces a leaf whose NV is non-finite with
its own string half, so that the rest of the distribution is handed the leaf
go-yaml sees.**

The walk runs after the `sops` section is split off and before `parse` returns.
Its predicate is the SV and never the text (ADR 0002): a defined, unreferenced
scalar with **public** `SVf_NOK` and **public** `SVf_POK` set, whose NV is `NaN`
or `±Inf`. The replacement is a plain copy of the scalar's PV. Nothing numifies
anything — `B` reads the NV and the PV out of the SV's own slots — so the walk
cannot retype a caller's scalar the way a numeric comparison on it would
(k32).

Three things this deliberately is not:

- **It is not a loosened guard.** The non-finite refusal from k59 is
  untouched, and a caller who hands `encrypt` a real `9**9**9` still gets it
  (measured, 6 of 6 croaks before and after, encrypted and unencrypted slot

docs/adr/0023-a-yaml-literal-that-overflows-a-double-is-a-string-not-a-float.md  view on Meta::CPAN

and every **value** from the parsed tree, so a retyped leaf reaches the digest
through the side the walk has already corrected. YAML::PP loads all 29 firing
tokens plus the twelve constants and yields a scalar wherever YAML::XS yields
one: 0 structural mismatches in 32, so the parallel walk still pairs up.

## Consequences

### Wire bytes that move

A YAML leaf whose literal libyaml resolved to a non-finite double. Its digest
input changes from `+Inf` / `-Inf` / `NaN` to the literal's own text, and its
`type:` from `float` to `str` — which is what sops writes for the same document.
27 of 105 corpus rows move, and **every one of them is a row whose
`value_to_bytes` was `+Inf`, `-Inf` or `NaN`**. Nothing that worked moves: the
twelve `%GO_CONSTANT` spellings, a quoted `"1e400"`, `1e-400`, `-0`, `5e-324`,
`1.7976931348623157e308` and the rounding neighbour one bit below the threshold
are all byte-identical before and after.

### The unencrypted slot comes out quoted where sops writes it bare

`YAML::XS` quotes a string its own resolver would read as a number, so
`v_unencrypted: 1e400` is written `v_unencrypted: '1e400'` where sops writes it
bare. Both spellings are a **string** to both parsers, so the digest is the same
text either way and `sops -d` exits 0 on both (measured, 20 of 20).

docs/adr/0023-a-yaml-literal-that-overflows-a-double-is-a-string-not-a-float.md  view on Meta::CPAN


### `!!float 1e400` is retyped with the rest

`YAML::XS` strips the tag and hands back the same non-finite NV, so an
explicitly tagged literal takes the same path and becomes a string. sops does
not agree — but it does not accept the input either: `sops -e` on that document
is exit 2, `yaml: cannot decode !!str `1e400` as a !!float`. The divergence is
therefore only in the permissive direction, on a document the reference refuses
outright, and narrowing it would cost a tag-aware parse for no reachable case.

### `x_unencrypted: NaN` and `x_unencrypted: -Inf` return something different

A caller who reads such a document out of `decrypt` or `extract` used to get a
real Perl `NaN` / `-Inf`. They now get the strings `'NaN'` and `'-Inf'`.

**This is the correction, not the breakage.** sops reads a string in that slot,
digests those four characters, and hands its own callers a string; we were the
only one of the two implementations that read a number there. The old value was
also not usable: of the thirteen spellings in that class, ten failed
verification outright, and the three that verified did so only because
`FormatFloat` happened to render their double as the source text. What changes
for a caller is that a slot which mostly could not be read at all now reads, and
reads what the other implementation reads.

### What changes for existing callers

| input | before | after |
|---|---|---|
| YAML, `1e400` / 401 digits / `Inf` / `NaN` in an **unencrypted** slot | MAC verification failed on read; croak on write | reads and writes, `type:str`, as sops does |
| the same in an **encrypted** slot | croak (`assert_representable` runs before encryption) | `type:str`, the literal verbatim — sops's own token |
| `decrypt` / `extract` of such a slot | a real Perl `Inf` / `NaN`, on the three documents that read at all | the literal's text |
| an **encrypted** `type:float` whose plaintext is `+Inf` / `-Inf` / `NaN` | a real Perl non-finite float | **unchanged** — byte-identical doubles, measured `000000000000f07f` / `f0ff` / `f8ff` before and after |
| `encrypt(data => { v => 9**9**9 })` | croak (k59) | **unchanged** — croak |
| a bare `.inf` in an unencrypted slot | MAC verification failed | **unchanged** — k105 |
| `1e-400` | `type:int`, digest `0` | **unchanged** — k106 |
| JSON, any of the above | croak | **unchanged** — croak, which is what sops does |

### Cost

One tree walk per YAML parse, reading two flags per scalar leaf. It carries its
own visited set, because a recursive YAML anchor (`root: &a` / `b: *a`) really
does come back from `YAML::XS` as a cycle; that keeps this walk terminating and

docs/adr/0026-a-plain-yaml-infinity-is-the-float-go-yaml-reads.md  view on Meta::CPAN

  table below was measured here against sops 3.13.3 at `/tmp/sops`; nothing is
  inherited from the ticket, and two of the ticket's premises did not survive
  the measurement (see "What the ticket had wrong").
- Date: 2026-08-21
- Tags: float, yaml, wire-format, interop, parser, mac
- Resolves k105
- Depends on ADR 0001 (order and values come from two different parses, and a
  leaf repaired in the parse reaches the digest through the side that was
  repaired), ADR 0002 (the type comes from the SV — which is why this decision
  needs an authority *outside* the SV, and says so), ADR 0006 (`+Inf` / `-Inf` /
  `NaN` as a non-finite float's digest text), ADR 0013 and ADR 0017 (`%GO_CONSTANT`,
  the Go resolution model, which already holds the answer and is re-verified
  here) and ADR 0023, whose walk this one runs after and whose stated
  disjointness it has to keep true
- Does **not** touch the non-finite guard from k59 in
  `Encrypted::assert_representable`. A measurement that says the guard is now
  too wide for one scalar shape is in "What this leaves broken", and is filed
  rather than acted on

## Context

docs/adr/0026-a-plain-yaml-infinity-is-the-float-go-yaml-reads.md  view on Meta::CPAN

four characters and Go's covers four different ones.

### What sops actually writes, measured

Twelve spellings, one `sops -e` per row, both slots, sops 3.13.3:

| source | `sops -e` | encrypted slot | unencrypted wire | MAC plaintext |
|---|---|---|---|---|
| `.inf` `.Inf` `.INF` `+.inf` `+.Inf` `+.INF` | exit 0 | `type:float`, plaintext `+Inf` | **`.inf`** | `+Inf` |
| `-.inf` `-.Inf` `-.INF` | exit 0 | `type:float`, plaintext `-Inf` | **`-.inf`** | `-Inf` |
| `.nan` `.NaN` `.NAN` | exit 0 | `type:float`, plaintext `NaN` | **`.nan`** | `NaN` |

The MAC plaintext was read out of each document's own `mac:` field and matched
against a digest computed here, not inferred. Two things follow.

`%GO_CONSTANT` in `Format::YAML` is **right**, verified against the binary
rather than against its source: all twelve map to exactly the bytes sops digests.

And **sops normalises nine of the twelve spellings away.** Only `.inf`, `-.inf`
and `.nan` can appear in a document sops wrote, which is the same shape as
ADR 0013's `mode: 0755` → `493` — except that there the normalisation removed

docs/adr/0026-a-plain-yaml-infinity-is-the-float-go-yaml-reads.md  view on Meta::CPAN


### The oracle

`YAML::PP` — already this distribution's second parser (ADR 0001) — answers it.
Its Core schema resolves a scalar to a non-finite number **iff** the scalar was
written plain and its token is one of the twelve. Measured, three ways:

| probe | rows | resolves non-finite |
|---|---|---|
| the twelve `%GO_CONSTANT` tokens, plain | 12 | **12** |
| nine near-miss spellings (`.INf` `.iNF` `.Nan` `.NAn` `+.nan` `-.nan` `-.NAN` `.infinity` `.Infinity`) and the bare `Inf` / `inf` / `NaN` class | 12 | **0** |
| the twelve, single- or double-quoted | 24 | **0** |

The near-miss row is the one that matters: every one of those twelve is a
`type:str` to sops, digested verbatim, and read correctly here today. YAML::PP
declines all of them, so the oracle's boundary and sops's boundary are the same
boundary.

Four edge cases, on the **wire** document rather than the plaintext, because
that is what the read path sees:

docs/adr/0026-a-plain-yaml-infinity-is-the-float-go-yaml-reads.md  view on Meta::CPAN

   and whose text is one of the twelve. Only past both is `YAML::PP` asked for
   anything;
3. **asks the document.** `YAML::PP` (Core schema) loads the same raw content,
   the `sops` branch is dropped from its tree too, and the two trees are walked
   in parallel;
4. **replaces only where both sides agree.** The `YAML::XS` leaf must be a
   defined, unreferenced scalar with public `SVf_POK` and neither public
   `SVf_NOK` nor public `SVf_IOK` — a plain string, read off the SV, nothing
   numified (ADR 0002, k32) — whose text is a key of `%GO_CONSTANT`. The
   `YAML::PP` leaf at the same position must be a scalar with public `SVf_NOK`
   whose NV is `NaN` or `±Inf`. The replacement is
   `dualvar($double, $token)`: the double derived from `%GO_CONSTANT`'s own
   byte string, so there is one token list and not two, and the token taken
   from the document, so every emitter writes back exactly what it read;
5. **fails safe.** Replacements are collected and applied only if the parallel
   walk completed with the two trees structurally identical. A `YAML::PP` that
   dies, a shape mismatch, a missing key — any of them and **nothing** is
   replaced, which is today's behaviour and today's MAC error.

### Why a dualvar and not a plain infinity

Both make the digest right. The dualvar also makes the **document** right.

`value_to_bytes` reads the numeric half either way, so the digest is `+Inf`
from both. What differs is what an emitter writes: measured, `YAML::XS` writes a
bare non-finite NV as `Inf` / `-Inf` / `NaN` — tokens go-yaml resolves as
**strings** — and writes `dualvar(+Inf, '.inf')` as `.inf`, the token sops
itself writes. So `decrypt_file` of such a document reproduces sops's own
plaintext byte for byte, and its output re-encrypts to the same value it came
from, where a plain infinity would have degraded to the string `Inf` on the
first plaintext round-trip.

It is also what ADR 0011's carrier already does one layer down: a float leaf
whose string half is the text the document contains.

### What the ticket had wrong

docs/adr/0026-a-plain-yaml-infinity-is-the-float-go-yaml-reads.md  view on Meta::CPAN


## Consequences

### Wire bytes that move

None on the write path. `File::SOPS` still cannot *create* a document with a
bare `.inf` in a MAC-covered slot — ADR 0013 refuses it for a caller-supplied
string, and the non-finite guard refuses it for the dualvar this walk produces.

On the read path, a plain `%GO_CONSTANT` token in an unencrypted YAML slot goes
into the digest as `+Inf` / `-Inf` / `NaN` instead of as its own text. That is
what sops digests for the same document, and it is the entire fix.

### What changes for existing callers

| input | before | after |
|---|---|---|
| sops-written YAML, bare `.inf` / `-.inf` / `.nan` in an **unencrypted** slot | MAC verification failed | reads; the leaf is a float whose text is the token |
| the same, hand-written `.Inf` `.INF` `+.inf` `-.INF` `.NAN` … (nine spellings sops normalises away, reachable only in a file sops did not write) | MAC verification failed | reads |
| the same slot holding a **quoted** `".inf"` | reads, `'.inf'` | **unchanged** — still the string, still verifies |
| `.INf` `.iNF` `+.nan` `.infinity` `Inf` `NaN` and the rest of the near misses | reads, a string | **unchanged** |
| an **encrypted** `type:float` whose plaintext is `+Inf` | a real Perl infinity | **unchanged** |
| a **plaintext** YAML parsed by `encrypt_file` | ADR 0013's refusal, naming the key path | **unchanged** — the walk does not run |
| `decrypt` / `extract` of a repaired slot | never returned | a `dualvar`: `+Inf` numerically, `.inf` as text |
| `decrypt_file` of such a document | never got that far | writes `v_unencrypted: .inf`, byte-identical to `sops -d` |
| `rotate` / `edit` of such a document | croak, `MAC verification failed` | croak, the non-finite guard, **naming the key path** |
| a YAML literal that overflows a double (`1e400`) | ADR 0023's string | **unchanged** — not a `%GO_CONSTANT` token, so this walk never sees it |

### What this leaves broken, and why it is filed rather than fixed

A document this now reads still cannot be written back. `_compute_mac` runs

docs/adr/0031-a-non-finite-float-that-carries-go-yamls-own-token-is-written.md  view on Meta::CPAN


The croak is k59's non-finite guard in `Encrypted::assert_representable`,
reached through `_compute_mac`'s leaf sweep. So the library had a document class
it could read and not write — and the advice in the message ("store the value as
a string") leads straight back to ADR 0013's refusal, because the string `.inf`
is written bare in YAML and Go reads a float out of it.

### The guard's premise, and where it stops holding

k59 refuses every non-finite float on the encrypt path because
`value_to_bytes` writes `+Inf` / `-Inf` / `NaN` — Go's `strconv.FormatFloat`
text, and what the digest covers — while the emitters write something else for
the same double. Re-measured here, unencrypted YAML slot, one document per row:

| leaf | document | Go digests | `sops -d` |
|---|---|---|---|
| bare `9**9**9` | `Inf` | `Inf` | **exit 51** |
| bare `-9**9**9` | `-Inf` | `-Inf` | exit 0, **read back as a string** |
| bare `NaN` | `NaN` | `NaN` | exit 0, **read back as a string** |
| `dualvar(+Inf, '.inf')` | `.inf` | `+Inf` | **exit 0, read back as a float** |

The premise holds for a bare NV — and the two exit-0 rows are worse than the
exit-51 one, not better: the file verifies while the leaf has silently stopped
being a number. It does **not** hold for the fourth row, which is the shape
ADR 0026 produces. There the document says what sops itself would have written
and the digest covers what sops itself would have digested.

The full corpus, twelve `%GO_CONSTANT` tokens as `dualvar($double, $token)`,
two slots, two formats, 48 documents, guard bypassed:

docs/adr/0031-a-non-finite-float-that-carries-go-yamls-own-token-is-written.md  view on Meta::CPAN

- **The 48-row corpus above**, twelve tokens × two slots × two formats, each row
  a real `File::SOPS->encrypt` handed to `sops -d`, before (guard bypassed) and
  after. After: the 12 YAML unencrypted rows are exit 0 and byte-identical to
  the bypassed run; the other 36 croak, naming the key path, and put no file on
  disk.
- **The round trip**, `sops -e` → `File::SOPS->rotate` → `sops -d`, for the three
  spellings `sops -e` actually writes: **3 of 3 exit 0**, wire byte-identical,
  where all three croaked before.
- **A 36-row refusal corpus** — three bare NVs and six mismatched or near-miss
  dualvars (`banana`, `.INf`, `-.inf` on a `+Inf`, `.inf` on a `-Inf`, `.inf` on
  a `NaN`, `+Inf` on a `+Inf`) × two slots × two formats. Every one of them was
  refused before this change and is refused after it. Nine of those rows were
  `sops -d` exit 0 with the guard bypassed, and each of those nine had silently
  retyped the leaf from a float to a string — which is why they stay refused
  rather than being repaired.
- **ADR 0013's guard as a second line of defence**, called directly on five
  leaves: it accepts the matching token, refuses all three contradictions and
  the near miss, and accepts `banana` — the row that decides how tight the gate
  has to be.
- `prove -lr t/` was 1062/1062 at 5536313 and is **1080/1080** with the new file
  and the two replaced claims in `t/42` (47 files; the suite is 1100/1100 with

docs/adr/0031-a-non-finite-float-that-carries-go-yamls-own-token-is-written.md  view on Meta::CPAN

`canonical_float_tree` gains one hash lookup per walk (`exists $tree->{sops}`)
and one more argument through a walk that already carried six; the string half
is read only for a leaf already known to be non-finite, of which three exist.

## Consequences

### Wire bytes that move

One document class, and only where it could not be written at all before: an
unencrypted YAML slot holding a `%GO_CONSTANT` token now reaches the document as
that token, with the digest covering `+Inf` / `-Inf` / `NaN`. That is what sops
writes and what sops digests for the same document.

Nothing else moves. No document this library could write before is written
differently.

### What changes for existing callers

| input | before | after |
|---|---|---|
| `rotate` / `encrypt` of a sops-written YAML document with a bare `.inf` / `-.inf` / `.nan` in an **unencrypted** slot | croak, the non-finite guard | **written**, `sops -d` exit 0, wire byte-identical |

docs/adr/0034-a-plain-scalar-is-resolved-the-same-way-on-every-parse.md  view on Meta::CPAN

non-finite float, and gated that repair on the document carrying a `sops:`
section. The gate's argument, quoted from its own "Rejected alternatives":

> A worse message for no gain, since neither path can write the document.

Both halves have since stopped being true, and the second one stopped being
true in this repository, three commits ago.

**ADR 0031 made the document writable.** An unencrypted YAML slot holding one
of the twelve tokens now reaches the file as that token, with the digest
covering `+Inf` / `-Inf` / `NaN`. So the gate was not choosing between two
errors any more; it was choosing an error over a document.

**And the two parses disagreed about identical bytes.** Measured at 0da0170,
one document per row, sops 3.13.3:

| step | `.inf` | `-.inf` | `.nan` |
|---|---|---|---|
| `sops -e` | exit 0, wire `.inf` | exit 0, wire `-.inf` | exit 0, wire `.nan` |
| `File::SOPS->decrypt_file` | writes `v_unencrypted: .inf` | `-.inf` | `.nan` |
| `File::SOPS->encrypt_file` **of that same file** | **croak** | **croak** | **croak** |

docs/adr/0034-a-plain-scalar-is-resolved-the-same-way-on-every-parse.md  view on Meta::CPAN

  Our wire keeps the source spelling for all twelve; sops's own emitter
  normalises the nine it does not write down to `.inf` / `-.inf` / `.nan`, which
  is why `sops -d` prints the normalised token for a document whose wire says
  `+.INF`. For the three spellings `sops -e` itself writes, our wire and sops's
  are byte-identical.
- **JSON: 24 rows, 0 move.** `.inf` is not JSON and the parse refuses it before
  anything here is reached; a quoted `".inf"` is the string it always was.
- **The rows that must not move**, every one a document sops writes and reads:
  the twelve tokens single- and double-quoted (24), the twelve near misses
  (`.INf` `.iNF` `.Nan` `.NAn` `+.nan` `-.nan` `-.NAN` `.infinity` `.Infinity`
  `Inf` `inf` `NaN`), the leaves that merely contain the bytes (`config.info`,
  `.infrastructure`), ADR 0023's overflow class (`1e400`, `1e309`) and the
  ordinary numbers (`0`, `007`, `3.14`, `-0.0`, `1e3`). **None moves.**
- `prove -lr t/` was 1100/1100 at 0da0170 (49 files) and is **1116/1116** (50
  files) with the new file and the two replaced claims below.
  `SOPS_BIN=/tmp/sops prove -l t/04-interop.t` is **32/32, executed rather than
  skipped**, before and after.
- **Counter-check:** `t/49-plain-infinity-survives-the-plaintext-round-trip.t`
  run against the unpatched 0da0170 with `perl -I` and no `use lib` in the file
  — **9 of its 16 subtests and 115 assertions fail**, and every one of the seven
  that pass is a must-not-move section (the quoted tokens, the near misses, the

docs/adr/0034-a-plain-scalar-is-resolved-the-same-way-on-every-parse.md  view on Meta::CPAN

still discards the whole repair if `YAML::PP` refuses the document or the two
trees disagree about its shape. `t/41` and `t/43` (the recursive anchor and the
alias bomb) pass unchanged.

## Consequences

### Wire bytes that move

One document class, in one direction: a **plaintext** YAML document holding a
plain `%GO_CONSTANT` token in an unencrypted slot now encrypts to a file that
states that token and whose digest covers `+Inf` / `-Inf` / `NaN`. That is what
`sops -e` writes and digests for the same plaintext, and for the three spellings
sops itself writes the bytes are identical.

Nothing else moves. No document this library could write before is written
differently, and no encrypted slot's bytes change in any row.

### What changes for existing callers

| input | before | after |
|---|---|---|
| `edit` of a sops-written YAML document with a bare `.inf` / `-.inf` / `.nan` in an **unencrypted** slot, editing any key | croak, ADR 0013's guard, **the edit destroyed** | **written**, `sops -d` exit 0, the leaf byte-identical |
| `encrypt_file` / `encrypt_in_place` of a **plaintext** holding the same, any of the twelve spellings | croak | **written**, `sops -d` exit 0 |
| `decrypt_file` → `encrypt_file` of this library's own output for such a document | croak | **round-trips** |
| the same token in an **encrypted** slot of a plaintext | written as `type:str` holding the token | **croak**, naming the key path (k122) |
| a **quoted** `".inf"` / `'.inf'` anywhere | the string, both slots | **unchanged** |
| `.INf` `.iNF` `+.nan` `.infinity` `Inf` `NaN` and the rest of the near misses | a string | **unchanged** |
| `config.info`, `.infrastructure`, `1e400`, `007`, `-0.0` | as they were | **unchanged** |
| any **JSON** document, either slot | as it was | **unchanged** |
| `decrypt` / `extract` / `rotate` of a wire document | ADR 0026 and ADR 0031's behaviour | **unchanged** — the gate only ever excluded plaintext |
| `Format::YAML->parse` called directly on a plaintext | the token as a string | the float, carrying the token as its text |

### What this leaves broken, and why it is filed rather than fixed

- **`edit` still silently retypes a non-finite float in an ENCRYPTED slot.**
  Such a leaf decrypts to a real Perl infinity, which this emitter writes into
  the plaintext as a bare `Inf` / `-Inf` / `NaN` — tokens go-yaml reads as
  **strings**, and correctly so. The editor is shown `Inf`, the string `Inf`
  comes back, and the leaf is re-encrypted as a `type:str`. Measured: the file
  is written, nothing is said, `sops -d` exit 0, and `sops edit` on the same
  document keeps it a `type:float`. This ADR's repair cannot reach it — `Inf`
  is not a `%GO_CONSTANT` token, and must not become one, because a user who
  types `Inf` really does mean the string. The fix is at the **emit**, where
  the information is actually destroyed, and it needs `Encrypted.pm`:
  `_canonical_floats` short-circuits a non-finite leaf with `return $node`
  before any handler hook is reached, so the YAML handler's `carrier` never
  sees it, and putting the decision in the handler would be a second copy of

docs/adr/0037-a-non-finite-float-is-written-as-a-token-or-not-at-all.md  view on Meta::CPAN

  anything in the repository changed.
- Date: 2026-08-21
- Tags: float, yaml, json, editor, wire-format, interop, mac
- Resolves k134. Files k140 (a contradictory string half in a
  plaintext emit) for what it deliberately leaves alone, and adds a measured
  note to k122, whose stated premise did not survive this measurement.
- Depends on ADR 0026 (which taught the parse to read a plain token back as the
  float go-yaml resolves), ADR 0031 (whose gate, table and verdict this reuses
  unchanged, and whose `return $node` short-circuit this replaces), ADR 0034
  (which made the repair run on every parse, and is what closes the circle),
  ADR 0006 (`+Inf` / `-Inf` / `NaN` as a non-finite float's digest text),
  ADR 0013 and ADR 0017 (the foreign-resolution guard, still the verdict) and
  ADR 0002 (the type comes from the SV; nothing here reads a leaf's text to
  decide what it is)
- Does **not** touch `Encrypted::encrypt_value`'s refusal of a non-finite float
  in an encrypted slot. That is k122, it is what stops this change from
  closing the `edit` round trip, and it is named in "What this leaves broken"
  with the measurement that reopens it

## Context

ADR 0034 closed the **unencrypted** half of the plaintext round trip: a plain
`.inf` in an unencrypted slot now survives `decrypt_file`, `edit` and
`encrypt_file`. The **encrypted** half was filed at the same time, and it is
worse, because it says nothing. Reproduced at 4aa9ace, sops 3.13.3, one
document per row, key `secret` in an encrypted slot:

| step | `.inf` | `-.inf` | `.nan` |
|---|---|---|---|
| `sops -e` | `type:float`, plaintext `+Inf` | `type:float` | `type:float` |
| `sops -d` | `secret: .inf` | `secret: -.inf` | `secret: .nan` |
| `File::SOPS->decrypt_file` | **`secret: Inf`** | **`secret: -Inf`** | **`secret: NaN`** |
| `File::SOPS->edit`, editing an unrelated key | returns 1, wire **`type:str`** | returns 1, **`type:str`** | returns 1, **`type:str`** |
| `sops edit`, same document, same editor | exit 0, wire unchanged, `type:float` | exit 0, `type:float` | exit 0, `type:float` |

No error, no warning, and `sops -d` reads the rewritten file at exit 0 — stating
a string where the document held a number. A user who edits a completely
unrelated key silently loses the type of a leaf they never touched.

### The mechanism, and where the information is destroyed

The encrypted leaf decrypts to a real Perl infinity: a scalar whose only form is
its number. `YAML::XS::Dump` writes such a scalar as a bare `Inf` / `-Inf` /
`NaN` — tokens go-yaml resolves as **strings**, and correctly so, which is why
ADR 0026's repair cannot reach them and must not learn to. So the editor is
shown `Inf`, the string `Inf` comes back, `detect_type` says `str`, and the leaf
is re-encrypted as `type:str`.

The loss happens at the **emit**. By the time the plaintext is reparsed there is
nothing left to recover: `Inf` really is the string `Inf` to every reader,
including sops.

The ticket's claim about where the short-circuit sits was verified first, since
the whole assignment rests on it. `Encrypted::_canonical_floats` reaches

```perl
if ($text =~ $NO_AGREED_FORM) {
    return $node unless _carries_go_non_finite_token($node, $text);
```

for a bare non-finite NV and returns before any handler hook runs. Measured with
a `canonical_float_tree` call whose three callbacks record being called: for
`+Inf`, `-Inf` and `NaN`, **none of `roundtrips`, `carrier` or `reject_scalar`
is invoked**, and the leaf leaves the walk as the bare NV it arrived as. So no
handler can see this leaf, and no fix in `Format::YAML` alone can reach it.

### JSON is not the same defect — it is a worse one

The ticket describes a retyping. Measured, JSON loses the value outright:

| document, `secret` encrypted, JSON wire | before |
|---|---|
| `File::SOPS->decrypt_file` | writes **`"secret": null`** |

docs/adr/0037-a-non-finite-float-is-written-as-a-token-or-not-at-all.md  view on Meta::CPAN

### The target form, measured rather than chosen

`sops -d` on an encrypted `type:float` writes the token, in the one spelling per
value that `sops -e` itself writes. Twelve `sops -e` runs, three plaintexts, both
wire formats:

| plaintext | wire | `sops -d --output-type yaml` | `sops -d --output-type json` |
|---|---|---|---|
| `.inf` | `type:float`, plaintext `+Inf` | **`secret: .inf`**, exit 0 | exit 4 |
| `-.inf` | `type:float`, plaintext `-Inf` | **`secret: -.inf`**, exit 0 | exit 4 |
| `.nan` | `type:float`, plaintext `NaN` | **`secret: .nan`**, exit 0 | exit 4 |

Both rows of the JSON column are the same for a YAML wire document and for a
JSON one — measured, six documents, all six exit 4. **JSON is not a wire format
sops refuses; it is an output format sops cannot produce.** There is therefore
no reference answer to copy for a JSON plaintext, and this ADR has to give one
of its own. It gives sops's: refuse, and say why.

And `.inf` is exactly what ADR 0026's repair reads back as a float — which since
ADR 0034 it does on **every** parse, plaintext included. The circle closes on
bytes that were already there.

docs/adr/0037-a-non-finite-float-is-written-as-a-token-or-not-at-all.md  view on Meta::CPAN


- **The ticket's rows, YAML.** `sops -e` → `decrypt_file`, three spellings: the
  leaf line goes from **0 of 3** byte-identical to `sops -d`'s to **3 of 3**.
  `sops -e` → `edit` of an unrelated key: three silent `type:str` rewrites
  become three croaks naming the key path, with the wire left untouched at
  `type:float`.
- **The ticket's rows, JSON.** `decrypt_file` writes `"secret": null` before and
  croaks after; `edit` silently replaces the `ENC[...]` with a bare unencrypted
  `null` before and croaks after. `sops -d --output-type json` and `sops edit`
  are exit 4 on the same three documents, before and after.
- **The circle.** `emit` → `parse` of a bare `+Inf` / `-Inf` / `NaN` in a
  plaintext YAML document: before, the leaf comes back a `str` (and for `+Inf`
  the digest text moves from `+Inf` to `Inf`); after, it comes back a **`float`**
  whose `value_to_bytes` is the text it went in as, for all three, with the
  document's own token as its string half.
- **ADR 0034's 24-row plaintext corpus**, twelve tokens × two slots through
  `encrypt_file` and handed to `sops -d`: 12 written / 12 exit 0 in the
  unencrypted slot and 12 croak in the encrypted one, **identical before and
  after**.
- **ADR 0031's 12-row encrypt-path table** (bare NV, the matching dualvar, the
  three contradictions, the near miss and `banana`, two formats): **identical
  before and after**, message for message.
- **15 must-not-move parse-and-emit rows**: the three tokens quoted, seven near
  misses (`.INf` `.iNF` `+.nan` `.infinity` `Inf` `inf` `NaN`), `config.info`,
  `1e400`, `3.14`, `-0.0` and `007`. **None moves.**
- **`mac_only_encrypted`**, both formats: unchanged, no new warning.
- **Nested leaves**: an infinity inside an array and three levels down a hash
  are written as tokens in YAML and refused in JSON with the path (`list:1`) in
  the message.
- `prove -lr t/` was **1157/1157 at 5ed2dc0** (52 files) and is **1172/1172**
  (53 files) with the new file and the two replaced claims below, no other test
  edited.
  `SOPS_BIN=/tmp/sops prove -l t/04-interop.t` is **32/32, executed rather than
  skipped**, before and after.

docs/adr/0037-a-non-finite-float-is-written-as-a-token-or-not-at-all.md  view on Meta::CPAN

of the *same* library is wider than the difference between the two, which is the
honest reading of a change that adds nothing to the path a finite float takes.

## Consequences

### Wire bytes that move

**No encrypted document's bytes move.** The change is entirely in what a
*plaintext* emit writes, and in one leaf class: a non-finite float with no string
half of its own. In YAML it reaches the file as `.inf` / `-.inf` / `.nan`
instead of `Inf` / `-Inf` / `NaN`, which is what `sops -d` writes for the same
document. In JSON nothing reaches the file, because the call croaks.

The knock-on for the **encrypted** wire is a refusal, not different bytes:
`edit` of such a document now croaks where it used to rewrite the leaf as
`type:str`.

### What changes for existing callers

| input | before | after |
|---|---|---|
| `decrypt_file` of a YAML document with an encrypted `type:float` `+Inf` / `-Inf` / `NaN` | writes `Inf` / `-Inf` / `NaN` | **writes `.inf` / `-.inf` / `.nan`**, byte-identical to `sops -d` |
| `edit` of the same document, editing any key | returns 1, the leaf silently becomes `type:str` | **croak**, naming the key path; the file is untouched and the edit is lost (k122, k123) |
| `decrypt_file` of a **JSON** document with such a leaf | writes `"secret": null` | **croak**, naming the key path — as `sops -d --output-type json` refuses it, exit 4 |
| `edit` of that JSON document | returns 1, the `ENC[...]` is replaced by a bare unencrypted `null` | **croak**; `sops edit` refuses the same document, exit 4 |
| `decrypt` / `extract` of either | the float | **unchanged** — nothing here is on the read path |
| `Format::YAML->emit` called directly with a bare infinity | `Inf` | `.inf` |
| `Format::JSON->emit` called directly with a bare infinity | `null` | **croak** |
| a non-finite float in an **unencrypted** YAML slot, any of ADR 0026's twelve tokens | ADR 0031 and ADR 0034's behaviour | **unchanged**, all 24 rows |
| `dualvar(+Inf, 'banana')` / `'.INf'` / `'-.inf'`, either slot, either format | croak on the encrypt path, its own text on a plaintext emit | **unchanged** |
| a bare `9**9**9` passed to `encrypt` / `encrypt_file` | croak, `assert_representable` | **unchanged** |
| a quoted `".inf"`, a near miss, `1e400`, `007`, `-0.0` | as they were | **unchanged** |

docs/adr/0038-a-resolver-divergence-is-answered-by-whether-sops-reads-back-what-it-wrote.md  view on Meta::CPAN

22 written here, **all 22 byte-identical to what sops wrote and all 22
`sops -d` exit 0**; 28 refused by the foreign-resolution guard. The 28 split
along the ticket boundary, and the split is the finding:

| refused | what sops writes from the same plaintext | is the refusal right? |
|---|---|---|
| `0755`, `!!int 0755`, `010` (k127) | `493`, `493`, `8` — resolved, spelling gone | **yes** — sops never writes the spelling we are refusing |
| `2026-08-21`, `2001-12-14t…`, `!!timestamp 2026-08-21` (k128) | `2026-08-21T00:00:00Z` etc. — normalised | **yes** — same reason |
| 22 **string** leaves (k135) | the same string, **double-quoted**, `sops -d` exit 0 | **no** — sops writes exactly those bytes |

The 22 are `".inf" ".Inf" ".INF" "+.inf" "-.inf" ".nan" ".NaN"`, `"1_000"
"0_7" "685_230.15"`, `"2015-01-01" "2015-1-2" "2015-01-01t12:00:00Z"
"2015-01-01 12:00:00"`, `"0o10" "0O10" "0x1f" "0b101"`, and `"Null" "NULL"
"TRUE" "FALSE"` — each quoted in the plaintext, so both implementations agree
it is a string, and each measured `sops -e` → `sops -d` exit 0 with the string
intact.

### Why one row of k135's five behaves differently

The ticket's fifth row, `"0755"`, is written here and not refused. Probed over
68 spellings: `$YAML::XS::QuoteNumericStrings` quotes a string that looks like a

docs/adr/0039-a-string-leaf-this-emitter-cannot-quote-stays-refused-and-says-so.md  view on Meta::CPAN


ADR 0038 measured 50 scalars in three slot configurations and found one class
where this library is simply wrong: **22 spellings that sops writes, sops reads
back at exit 0, and `File::SOPS->encrypt_file` refuses to produce.** Each is a
leaf that is a **string** on both sides — quoted in the plaintext, so both
implementations agree about its type — and each is refused by ADR 0013's
foreign-resolution guard, because `YAML::XS` writes the string as a **bare**
token and Go's yaml.v3 resolves that token into a number, a null, a boolean or
a time.

The 22 are `".inf" ".Inf" ".INF" "+.inf" "-.inf" ".nan" ".NaN"`, `"1_000" "0_7"
"685_230.15"`, `"2015-01-01" "2015-1-2" "2015-01-01t12:00:00Z"
"2015-01-01 12:00:00"`, `"0o10" "0O10" "0x1f" "0b101"`, and `"Null" "NULL"
"TRUE" "FALSE"`.

**A 23rd row was found here**, in the same class and by the same mechanism:
`"0xffffffffffffffff"`. sops writes it double-quoted and reads it back at exit
0; the guard refuses it because `_go_scalar_bytes` cannot model a `uint64` and
refuses what it cannot decide (ADR 0013). Its neighbour `"9223372036854775808"`
is written here, because `looks_like_number` is true for it and `YAML::XS`
quotes it for us. The row is recorded on k135 rather than changing

docs/adr/0039-a-string-leaf-this-emitter-cannot-quote-stays-refused-and-says-so.md  view on Meta::CPAN

is missing is the ability to *write* one.

### 2. There is no per-scalar quoting in this emitter, by any route

Three routes were probed, because a fix that does not need text surgery would
end the question:

**A global option that quotes wider.** `$YAML::XS::QuoteNumericStrings` set to
0, 1, 2 and 3 over 19 spellings: it is a **boolean** — 1, 2 and 3 are
byte-identical — and what it quotes is exactly what Perl's `looks_like_number`
accepts (`0755`, `007`, `1e3`, and also `Inf`, `Infinity`, `NaN`, `nan`), plus
lower-case `true`, `false`, `null`, `~` and the empty string. `.inf`, `TRUE`,
`Null`, `1_000`, `0x1f` and every date stay bare at every setting. There is no
other knob in the module: `Boolean`, `LoadBlessed`, `LoadCode`, `UseCode`,
`DumpCode`, `Indent`, `ForbidDuplicateKeys` and `QuoteNumericStrings` are the
whole surface.

**A carrier, the ADR 0037 route.** This is the route the handover named as the
most promising, and it is the one this decision spent the most on. It is dead,
and it is dead in the worse direction. Six SV shapes × 9 spellings through
`Dump`:

docs/adr/0039-a-string-leaf-this-emitter-cannot-quote-stays-refused-and-says-so.md  view on Meta::CPAN

and exactly as ADR 0019 refused to do for arbitrary leaves.

### 3. The obvious fix is wrong, and the measurement says by how much

"Quote every `str` leaf the guard refuses" cannot tell two different documents
apart. Measured, one document per row, `File::SOPS::Format::YAML->parse` of a
**bare** and a **quoted** source, compared by `detect_type` and `value_to_bytes`:

| family | rows | bare source parses as | quoted source parses as | distinguishable? |
|---|---|---|---|---|
| `.inf .Inf .INF +.inf -.inf .nan .NaN` | **7** | `float` `+Inf` / `-Inf` / `NaN` | `str`, the token | **yes** |
| `1_000 0_7 685_230.15` | 3 | `str`, the token | `str`, the token | no |
| `2015-01-01 2015-1-2 2015-01-01t12:00:00Z 2015-01-01 12:00:00` | **4** | `str`, the token | `str`, the token | no |
| `0o10 0O10 0x1f 0b101` | 4 | `str`, the token | `str`, the token | no |
| `Null NULL TRUE FALSE` | 4 | `str`, the token | `str`, the token | no |

**15 of the 22 arrive as the identical Perl string from a bare source and from a
quoted one**, and the two sources are two different documents to sops. Measured,
44 `sops -e` runs, the same 22 spellings bare and quoted, leaf under
`v_unencrypted`, all 44 at exit 0:

docs/adr/0040-an-encrypted-slot-carries-a-non-finite-float-because-sops-writes-one.md  view on Meta::CPAN

  it deliberately leaves alone.
- **Supersedes part 3 of ADR 0031** — "`encrypt_value` keeps refusing the
  encrypted slot" — and the premise that part rested on. Nothing else in
  ADR 0031 moves: its gate, its twelve-row table, its verdict and its
  unencrypted-slot decision are untouched, and this ADR keeps them for the slot
  they were written for.
- Depends on ADR 0031 (the gate, and the decision this replaces), ADR 0037
  (which turned this round trip's silent corruption into a refusal and named
  this ticket as the rung above it), ADR 0034 (whose repair on **every** parse
  supplies the leaf that closes k114), ADR 0026 (which produces that leaf),
  ADR 0006 (`+Inf` / `-Inf` / `NaN` as a non-finite float's digest text),
  ADR 0012 (a scalar whose two halves disagree is refused, not guessed) and
  ADR 0002 (the type comes from the SV; nothing here reads a leaf's text to
  decide what it is)

## Context

ADR 0031 refused a non-finite float in an **encrypted** slot, explicitly and
with a reason:

> The token is not on the wire there at all — the slot carries `type:float` and

docs/adr/0040-an-encrypted-slot-carries-a-non-finite-float-because-sops-writes-one.md  view on Meta::CPAN

Because it is a different decision, and it moves ADR 0037's counter-check.

The unconditional variant was built and measured: drop the non-finite refusal
for any leaf with no string half of its own, and the encrypted slot opens
without any slot argument at all — `Encrypted.pm` alone, no `SOPS.pm`, a
one-condition diff. Measured at HEAD, i.e. with ADR 0037's emit repair in place,
it also opens the **unencrypted** YAML cell:

| unencrypted slot, bare NV | before | unconditional variant |
|---|---|---|
| YAML `9**9**9` / `-9**9**9` / `NaN` | croak | **written** `.inf` / `-.inf` / `.nan`, `sops -d` exit 0 |
| JSON, the same three | croak, the guard | croak, the emit walk |

That is a **correct** widening — ADR 0037 gave the emitter a token for exactly
this leaf, and the digest still covers `+Inf` — and it is not this ticket. It
makes writable something a caller can construct and that was refused, which is
the property ADR 0037 stated and pinned in `t/52` section 9; it flips eight
further subtests in four more files; and ADR 0031's measurement of that cell
(`Inf` → `sops -d` exit 51) was taken before the repair existed and no longer
reproduces, which deserves to be said in its own ADR rather than in a paragraph
of this one. k141.

docs/adr/0040-an-encrypted-slot-carries-a-non-finite-float-because-sops-writes-one.md  view on Meta::CPAN

passing `encrypted` as a coderef so the sweep only computes the answer for a
leaf that needs one costs 43.7 – 45.1 ms / 101 – 113 ms, because a closure per
call is dearer than the predicate. The straight boolean is what ships.

## Consequences

### Wire bytes that move

One document class, and only where it could not be written at all before: a
non-finite float in an **encrypted** slot now reaches the wire as `type:float`
with the plaintext `+Inf` / `-Inf` / `NaN`, in YAML and in JSON. That is what
`sops -e` writes for the same value in the same slot, in both formats.

No unencrypted slot's bytes change. No document this library could write before
is written differently.

### What changes for existing callers

| input | before | after |
|---|---|---|
| `rotate` of a sops-written YAML document with an encrypted `.inf` / `-.inf` / `.nan` | croak | **written**, `sops -d` exit 0, the leaf still `type:float` |

docs/adr/0053-a-plaintext-emit-refuses-the-same-non-finite-contradiction-the-mac-covered-paths-refuse.md  view on Meta::CPAN

The numeric half is what `value_to_bytes` derives the digest from, and the
public string half is what the emitters write. When the two disagree, the
document and the digest state different things, and `sops -d` refuses the
file at exit 51.

The MAC-covered paths caught every one of these already:

- `_compute_mac` calls `assert_representable` per leaf with `encrypted => 1`
  (or `=> 0` for an unencrypted slot); the predicate gates on
  `!_carries_go_non_finite_token` and refuses a contradiction with the
  k59 message, naming the form (`+Inf` / `-Inf` / `NaN`) and pointing
  at type:str.
- `_canonical_floats`'s `mac_covered` croak refuses the JSON case where the
  handler has no spelling for a non-finite value at all, even when the leaf
  carries one of the twelve go-yaml tokens.

The plaintext emit path was the asymmetric third. `decrypt_file`, `edit`,
`_serialize_plaintext` and a direct `emit()` call on a tree the caller built
all go through `_canonical_floats` without `reject_scalar` (no MAC to check
against) and without the metadata `sops:` key (so `_document_carries_mac`
returns false). For a non-finite leaf with a public PV, the walk's existing

docs/adr/0053-a-plaintext-emit-refuses-the-same-non-finite-contradiction-the-mac-covered-paths-refuse.md  view on Meta::CPAN

### The bug, reproduced before anything was changed

| tree under `v` | perl `Format::YAML->emit` wrote | what `sops -d` made of it |
|---|---|---|
| `dualvar(+Inf, 'banana')` | `v: banana` | string `"banana"` |
| `dualvar(+Inf, '.INf')` | `v: .INf` | string `".INf"` |
| `dualvar(+Inf, '.infinity')` | `v: .infinity` | string `".infinity"` |
| `dualvar(+Inf, 'Inf')` | `v: Inf` | string `"Inf"` |
| `dualvar(+Inf, '-.inf')` | `v: -.inf` | string `"-.inf"` |
| `dualvar(-Inf, '.inf')` | `v: .inf` | string `".inf"` |
| `dualvar(NaN, '.inf')` | `v: .inf` | string `".inf"` |

Same shape in JSON — Cpanel quotes the public PV when it differs from
`%.15g` of the number, so `dualvar(+Inf, 'banana')` reaches the file as
`{"v":"banana"}` — and the result is identical on the next parse: a
string. ADR 0038's discriminator again: what one writer put on disk, the
other would read as something else.

### What still has to work after the fix

The whole reason ADR 0037 narrowed its repair to the bare-NV row was that
the caller chose the string half deliberately, and overwriting it on the
strength of the number beside it would be the guess ADR 0012 refuses to
make for an integer whose halves disagree. The valid rows must keep
working:

| tree under `v` | perl `Format::YAML->emit` writes | what sops reads it as |
|---|---|---|
| `dualvar(+Inf, '.inf')` | `v: .inf` | `+Inf` (k113 / ADR 0031's row) |
| `dualvar(-Inf, '-.inf')` | `v: -.inf` | `-Inf` |
| `dualvar(NaN, '.nan')` | `v: .nan` | `NaN` |
| bare `+Inf` (no PV) | `v: .inf` | `+Inf` (k134 / ADR 0037's repair) |
| bare `-Inf` (no PV) | `v: -.inf` | `-Inf` |
| bare `NaN` (no PV) | `v: .nan` | `NaN` |

JSON has no spelling at all for a non-finite value in an unencrypted slot
(`sops -d --output-type json` is exit 51 on every one of these), so the
JSON carrier croaks — measured, that is the existing k134 behaviour
and is unchanged by this decision.

## Decision

**The plaintext emit path consults `assert_representable`'s `encrypted => 0`
branch when a non-finite leaf carries a public PV, and croaks with the karr

docs/adr/0053-a-plaintext-emit-refuses-the-same-non-finite-contradiction-the-mac-covered-paths-refuse.md  view on Meta::CPAN


The `mac_covered` croak below the new call still refuses the JSON case
where the handler has no spelling for a non-finite value at all, even when
the leaf carries one of the twelve go-yaml tokens. The new consult runs
*before* it; for a contradiction, the k59 message is the one that
fires, and the JSON case is unreachable for those leaves. For a valid
token PV the new consult passes, and the JSON MAC-covered case croaks with
its existing message as before.

The `assert_representable` body itself is unchanged. The k59 message
text, the form-naming (`+Inf` / `-Inf` / `NaN`), and the `type:str`
suggestion are all untouched.

### 4. `_compute_mac` keeps its own consult with its own `encrypted` value

The encrypt side already calls `assert_representable` per leaf with the
slot-appropriate `encrypted` value (k122 / ADR 0040). The new walk
consult is *redundant* with `_compute_mac` for the MAC-covered paths, and
that is on purpose: the predicate is cheap, and the redundancy is the only
thing that makes the plaintext path symmetric without duplicating the
gate.

docs/adr/0053-a-plaintext-emit-refuses-the-same-non-finite-contradiction-the-mac-covered-paths-refuse.md  view on Meta::CPAN

  Refusing it would refuse to *write* a document this module *reads*
  correctly, which is the same defect k122 / ADR 0040 closed for
  the encrypted slot.

## Notes

Measured against sops 3.13.3 (`/tmp/sops`) with `Crypt::Age` on this
machine, on 2026-08-22: the seven contradicting rows through perl's
`Format::YAML->emit` and `Format::JSON->emit`; the six valid rows
(`.inf`, `.Inf`, `.INF`, `+.inf`, `-.inf`, `.nan`) on each format; the
three bare NVs (`+Inf`, `-Inf`, `NaN`) on each format; and the seven
contradicting rows through `sops -d` on the YAML perl wrote and on the
JSON perl wrote. All fixtures are invented values; the age keypair was
generated for the run.

`t/68-non-finite-dualvar-emit.t` is the new pin: every refusing row is
the k59 message, every refusing row in JSON is the same, the key
path is in the message for top-level, nested, array-element, and
deeply-nested leaves, and the regression rows (bare NV, valid token PV,
finite float) are kept in the same file. The interop sections of
`t/04-interop.t`, `t/52-non-finite-float-survives-the-encrypted-round-trip.t`,

docs/adr/0062-a-bare-non-finite-float-in-an-unencrypted-slot-is-written-by-the-carrier-not-refused-here.md  view on Meta::CPAN

- Does **not** touch `Encrypted::encrypt_value`. An encrypted slot is
  reached by `encrypt_value`, not by `assert_representable` on the read or
  write path, and k122 / ADR 0040 is still the decision that owns
  that slot. The narrowing is `assert_representable`'s `encrypted => 0`
  branch only.
- **Moves no wire bytes for any leaf that already passed.** What changes
  is which leaves pass. A bare NV in an unencrypted YAML slot, which
  `k59 / ADR 0031` refused at exit 1, reaches the file as `.inf`
  / `-.inf` / `.nan` — the byte `sops -d` itself writes for the same
  document — and `sops -d` reads it back at exit 0 as `+Inf` / `-Inf` /
  `NaN`.

## Context

A non-finite float this library encrypts has two paths to the wire:

- an **encrypted** slot, reached by `Encrypted::encrypt_value` (k122
  / ADR 0040 narrows that path to "carries one of go-yaml's twelve tokens
  as its public PV" in YAML and refuses it in JSON)
- an **unencrypted** slot, reached by `_compute_mac` on the encrypt path
  and by `_canonical_floats` on the plaintext emit path (k140 /

docs/adr/0062-a-bare-non-finite-float-in-an-unencrypted-slot-is-written-by-the-carrier-not-refused-here.md  view on Meta::CPAN

float that does not already carry its token PV. ADR 0031 carved out the
"carries a token PV" half; what it left in place was the refusal of every
remaining non-finite leaf at this layer, which is the bare NV.

The bare NV's path to the wire is now different in the two formats, and
that difference is what the ticket names.

### The premise the original guard was written under, and where it stopped holding

The k59 / ADR 0031 guard refused every bare NV because `value_to_bytes`
writes `+Inf` / `-Inf` / `NaN` — Go's `strconv.FormatFloat` text, the
text the digest covers — while the YAML emitter writes a bare `Inf` /
`-Inf` / `NaN` (which go-yaml reads as a string) and the JSON emitter
writes `null`. The premise was that no document could carry a bare NV,
so the only safe answer was to refuse.

ADR 0037 changed both halves. `_canonical_floats` stopped short-
circuiting a bare NV: the leaf now reaches `_non_finite_token_leaf`,
which hands it to the format handler's carrier and verifies the answer.
The YAML carrier answers `dualvar($double, '.inf')`, which the YAML
emitter writes as `.inf` — the exact text go-yaml resolves back to
`+Inf`, byte-identical to what `sops -d` itself writes. The JSON
carrier croaks, with a different message (the existing k134

docs/adr/0062-a-bare-non-finite-float-in-an-unencrypted-slot-is-written-by-the-carrier-not-refused-here.md  view on Meta::CPAN

answers, and the answers live in the carriers.

Re-measured here against sops 3.13.3 at `/tmp/sops`, with
`assert_representable`'s non-finite gate bypassed in a scratch copy of
`lib/`, **unencrypted** slot, one document per row:

| input | YAML | JSON |
|---|---|---|
| bare `9**9**9` | **WRITTEN** as `.inf`, `sops -d` exit 0 | **CROAK** (the JSON carrier) |
| bare `-9**9**9` | **WRITTEN** as `-.inf`, `sops -d` exit 0 | **CROAK** |
| bare `NaN` | **WRITTEN** as `.nan`, `sops -d` exit 0 | **CROAK** |

So the refusal in `assert_representable` for a leaf with **no** public
PV is now:

- **redundant in YAML**: the leaf is written, by the carrier, with the
  right token, and `sops -d` reads it back as the same float;
- **duplicated in JSON**: the same call still refuses, and the JSON
  carrier would also have refused — the croak would just be a different
  message, and the key path the carrier's croak names is the one the
  caller actually needs.

docs/adr/0062-a-bare-non-finite-float-in-an-unencrypted-slot-is-written-by-the-carrier-not-refused-here.md  view on Meta::CPAN

unchanged. A contradicting dualvar (any format, any slot) still croaks
here. A valid dualvar (`dualvar($double, $token)` for any of the
twelve tokens) still passes the gate, in either branch.

## Consequences

### What changes for existing callers

| input | before | after |
|---|---|---|
| `rotate` of a sops-written YAML document whose unencrypted slot holds a bare `+Inf` / `-Inf` / `NaN` | croak, k59 message | **written**, `sops -d` exit 0, wire byte-identical to `sops -d` for the same document |
| `encrypt` / `encrypt_file` of a hand-built tree with `v => 9**9**9` (or any of the three spellings) in an unencrypted YAML slot | croak, k59 message | **written**, the carrier's `dualvar($double, $token)`, `.inf` / `-.inf` / `.nan` on disk |
| `decrypt_file` of a sops-written YAML document whose unencrypted slot holds a bare `+Inf` / `-Inf` / `NaN` | croak | written, `.inf` / `-.inf` / `.nan` — what ADR 0037 already wrote in the encrypted-leaf's reverse case |
| `encrypt` / `encrypt_file` of the same bare NV in an **unencrypted JSON** slot | croak, k59 message | **croak**, the JSON carrier's `_non_finite_token_leaf` message — names the key path; the call never reaches the file |
| `rotate` / `decrypt_file` of a JSON document with a bare NV in an unencrypted slot | croak, k59 message | croak, JSON carrier's message; same `sops -d` exit 4 reference answer |
| `dualvar(+Inf, '.inf')` (or any of the twelve tokens) in either format, either slot | YAML written, JSON croak (ADR 0031) | **unchanged** |
| `dualvar(+Inf, 'banana')`, `dualvar(+Inf, '.INf')`, `dualvar(+Inf, '-.inf')` in either format, either slot | croak, k59 message | **unchanged** — still refused, same gate, same twelve-row counter-check |
| a bare NV in an **encrypted** slot, either format | croak, `Encrypted::encrypt_value` (k122 / ADR 0040) | **unchanged** |
| `encrypt` of a finite float (any signed zero, any normal, any subnormal) | written, `type:float`, digest covers the value | **unchanged** |
| `decrypt` / `extract` of any of the above | the float, exactly as ADR 0037 reads it | **unchanged** — the read path is not on this layer |

### Test sections that flip from RED to GREEN

docs/adr/0062-a-bare-non-finite-float-in-an-unencrypted-slot-is-written-by-the-carrier-not-refused-here.md  view on Meta::CPAN

now writes, or split a JSON refusal between k59 and the carrier's
own croak. Each was RED against the unpatched tree and GREEN against
the tree with this change, with the message text updated where the
croak moved from `assert_representable` to the carrier:

| file | section | what it pins |
|---|---|---|
| `t/28-non-finite-float-refusal.t` | section 1 | the **write-side split**: bare NV writes in YAML, croaks with the JSON carrier's message in JSON, contradicting dualvars still refused in both |
| `t/39-yaml-overflow-literal-becomes-a-string.t` | section 11 | a YAML leaf whose overflow resolves to `Inf` is the string sops reads, in both the direct API and the parse-and-write path; the bare-NV narrowing applies to a real `9**9**9` and not to ...
| `t/42-yaml-plain-infinity-is-a-float.t` | section 11 | a plain `.inf` resolves to a `+Inf` carrying `.inf` as its PV; the parse produces the leaf this ADR no longer refuses at write time |
| `t/46-non-finite-token-is-written.t` | sections 4-5 | `assert_representable` answers YES for a bare NV in either slot and NO for a contradicting dualvar; the message names the form (`+Inf` / `-Inf` / `NaN`) and points at the carrier (YAML) or the J...
| `t/52-non-finite-float-survives-the-encrypted-round-trip.t` | section 9 | ADR 0037's twelve-row encrypt-path counter-check: all twelve rows in both formats still refuse or write exactly as before; the bare-NV narrowing does not touch the table |
| `t/54-an-encrypted-non-finite-float-is-written.t` | sections 1, 4, 5 | the encrypt-side `assert_representable` consult now answers YES for a bare NV in all three slots (default, `encrypted => 0`, `encrypted => 1`) and NO for every contradicting dua...

### Wire bytes that move

- **Bare NV in an unencrypted YAML slot.** What used to be no bytes
  (the refusal croaked before the file was touched) is now
  `.inf` / `-.inf` / `.nan` — the byte `sops -d` itself writes for
  the same document.
- **Nothing else.** The encrypted slot is unchanged (k122 owns it).

docs/adr/0070-a-scoped-per-scalar-quote-is-feasible-for-the-non-ambiguous-divergent-string-leaves.md  view on Meta::CPAN

This is the finding that scopes the whole ticket, and it corrects ADR 0039.
k127 is now **done**, but the landed `_go_repair_int_leaf` repairs a leaf
only when it is `SVf_IOK` **and** its PV matches `/\A[+-]?0\d+\z/` — a
leading-zero *integer*. None of the 22/23 divergent spellings are leading-zero
integers. So the ambiguity ADR 0039 measured is exactly as wide today as it was
then. Measured, each spelling parsed from a **bare** and a **quoted** source
through `Format::YAML->parse`, compared by `detect_type` + `value_to_bytes`:

| family | rows | bare parses as | quoted parses as | distinguishable? |
|---|---|---|---|---|
| `.inf .Inf .INF +.inf -.inf .nan .NaN` | **7** | `float` `+Inf`/`-Inf`/`NaN` | `str`, the token | **yes** |
| `1_000 0_7 685_230.15` | 3 | `str`, the token | `str`, the token | no |
| `2015-01-01 2015-1-2 2015-01-01t12:00:00Z 2015-01-01 12:00:00` | 4 | `str`, the token | `str`, the token | no |
| `0o10 0O10 0x1f 0b101` | 4 | `str`, the token | `str`, the token | no |
| `Null NULL TRUE FALSE` | 4 | `str`, the token | `str`, the token | no |
| `0xffffffffffffffff` | 1 | `str`, the token | `str`, the token | no |

The seven that parse unambiguously do so because of ADR 0026/0034, not k127:
a bare `.inf` is resolved to a float at parse, so a leaf that is *still the
string* `.inf` can only have come from a quoted scalar or a caller's own Perl
string. Quoting it is therefore safe — it states the type the leaf already has.

docs/adr/0070-a-scoped-per-scalar-quote-is-feasible-for-the-non-ambiguous-divergent-string-leaves.md  view on Meta::CPAN

it — as sentinel substitution with fail-closed verification, applied only to the
leaves whose safety is measured, on the MAC-covered YAML write path.**

The scope is what §2 and §3 establish is safe **today**, and no wider:

- **The `type` divergence class** — a `str` leaf whose emitted token go-yaml
  resolves to a boolean (`True`, `False`). Quoting it turns today's `carp`
  (ADR 0019) into a written, self-consistent document. This is k99's
  headline.
- **The seven parse-unambiguous non-finite `str` leaves** —
  `.inf .Inf .INF +.inf -.inf .nan .NaN`. Quoting turns today's refusal
  (ADR 0013) into a written document. This is 7 of the 22 rows of ADR 0038/0039.

**Everything else stays exactly as it is.** The sixteen ambiguous rows
(`1_000 0_7 685_230.15`, the four dates, `0o10 0O10 0x1f 0b101`,
`Null NULL TRUE FALSE`, `0xffffffffffffffff`) stay **refused**, with the message
ADR 0039 already corrected, until the full k127 disambiguates their source
at parse. An integer/float `mac` divergence (`0755`, `010`) stays refused
(ADR 0013 — quoting would retype it, and the maintainer decided against that).
The plaintext emitters (`decrypt_file`, `edit`) install no guard and are not in
scope here; a related plaintext-path fidelity gap is filed separately (see

docs/adr/0071-the-plaintext-emitter-quotes-the-same-safe-set-so-it-is-a-faithful-inverse.md  view on Meta::CPAN

  plaintext path **out** and named this gap for a follow-up. This is that
  follow-up, and it reuses ADR 0070's mechanism unchanged
- Depends on ADR 0026/0034 (a plain non-finite scalar is a float, a quoted one a
  string — the distinction this relies on), ADR 0013/0018 (the plaintext
  emitters install no foreign-resolution guard, deliberately)

## Context

ADR 0070 taught the emitter to double-quote a safe set of divergent leaves — the
`True`/`False` type divergence and the seven parse-unambiguous non-finite str
spellings (`.inf .Inf .INF +.inf -.inf .nan .NaN`) — but only on the
**MAC-covered** write path, where a bare leaf makes a document fail its own MAC.
It scoped the plaintext emitters (`decrypt_file`, `edit`) out, because there is
no MAC there to protect.

k186 measured the cost of that scope-out. sops writes such a string
double-quoted; the plaintext emitter wrote it **bare**:

```
sops -d        x_unencrypted: ".inf"   (str, quoted)
decrypt_file   x_unencrypted: .inf     (bare)

lib/File/SOPS.pm  view on Meta::CPAN

A caller's own bare C<9**9**9> states nothing, and it is refused in an
B<unencrypted> slot only. In an B<encrypted> one it is now written, as
C<type:float> and the plaintext C<+Inf>, which is what C<sops -e> stores for
the same value in both formats. See
L<File::SOPS::Encrypted/assert_representable>, k122 and
L<docs/adr/0040|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0040-an-encrypted-slot-carries-a-non-finite-float-because-sops-writes-one.md>.

B<In YAML that literal is not refused any more, because it is not a number
there.> Since 0.003 L<File::SOPS::Format::YAML/parse> hands back the string
go-yaml reads -- C<1e400>, a 401-digit integer and the bare spellings C<Inf>,
C<NaN> and their relatives -- so the guard never sees a float, and the leaf is
written as C<type:str>, which is what C<sops -e> writes for the identical
plaintext (exit 0, measured against sops 3.13.3, encrypted and unencrypted slot
alike). Until 0.003 the same document could be neither written here -- all 20
measured hit the guard -- nor read, 17 of those 20 failing with C<MAC
verification failed>.

The B<read> paths follow from that and differ by format. In YAML L</decrypt>
and L</extract> hand the leaf back as a plain string carrying the literal's own
text, and the document verifies; L</A YAML literal that overflows a double
comes back as a string> under L</decrypt> has what that changed for a caller.

lib/File/SOPS.pm  view on Meta::CPAN

untrusted documents can lower to refuse deep documents earlier. Raising it
above 10000 produces documents sops will refuse to read.

See k117.

=head3 A plain YAML infinity is the float go-yaml reads

B<New in 0.003, and a change for existing callers of every method that reads a
YAML file.> A leaf a YAML document wrote as a B<plain> scalar whose token
go-yaml resolves to a non-finite float -- C<.inf>, C<.Inf>, C<.INF>, the same
three with a leading C<+> or C<->, C<.nan>, C<.NaN>, C<.NAN> -- is that float
here too, carrying the document's own token as its text. A B<quoted> C<".inf">
is the string it has always been; the difference is decided by asking
L<YAML::PP> how the document wrote the scalar, never by matching the leaf's
text. See L<File::SOPS::Format::YAML/A plain infinity comes back as the float
go-yaml reads>.

B<This applies to a plaintext file as well as to an encrypted one>, which is
what changed last: until then the repair ran only for a document that carried a
C<sops:> section, so this library's own L</decrypt_file> wrote
C<v_unencrypted: .inf> and its own L</encrypt_file> refused to read that file
back, and L</edit> could not save a document it had just opened. sops makes one
parse and this now makes one too.

What it means per slot, measured against sops 3.13.3 for all twelve spellings:

=over 4

=item * In an B<unencrypted> slot the leaf is written as the token the document
had, and the MAC digest covers C<+Inf> / C<-Inf> / C<NaN>. C<sops -d> reads it,
and for the three spellings C<sops -e> itself writes the wire bytes are
identical to sops's.

=item * In an B<encrypted> slot the leaf is B<refused>, naming the key path:
the wire form there is C<type:float> with the plaintext C<+Inf>, and
L<File::SOPS::Encrypted/encrypt_value> cannot see which format it is writing
for -- YAML would carry it, JSON cannot (C<sops -e> exit 4,
C<Error marshaling to json>). Before this such a leaf was written as a
C<type:str> holding C<.inf>, where C<sops -e> on the same plaintext writes a
C<type:float>: a working file that had silently stopped being a number. This is

lib/File/SOPS.pm  view on Meta::CPAN

into a C<File::SOPS::Comment> before there is anything to warn about, and
L<YAML::XS> discards one before this library sees the tree -- so a YAML document
never gets here, though C<sops> itself warns for YAML as well. See
L<docs/adr/0067|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0067-a-plaintext-comment-in-an-encrypted-slot-is-warned-about-not-silenced.md>.

=head3 A YAML literal that overflows a double comes back as a string

B<New in 0.003, and a change for existing callers.> From an B<unencrypted>
YAML slot, a literal libyaml resolves to a non-finite double -- C<1e400>, a
401-digit integer, and the bare spellings C<Inf>, C<inf>, C<INF>, C<Infinity>,
C<NaN>, C<nan>, C<NAN>, C<-Inf> and C<+Inf> -- comes back as a plain B<string>
holding the literal's own text. It used to carry C<Inf> or C<NaN> as its
numeric half as well, because L<YAML::XS> returns those literals with both
halves set.

B<This is a correction, and it does not extend to the encrypted slot.>
go-yaml -- the parser sops reads a document with -- resolves none of those
spellings to a number either: C<strconv.ParseFloat> answers C<ErrRange>, so
sops keeps a string, writes C<type:str> and digests the literal's own text. The
old return value also belonged to a document this library mostly could not read
at all: of 20 such documents C<sops -e> wrote and C<sops -d> read, 17 failed
here with C<MAC verification failed> and 3 verified by coincidence. An
B<encrypted> C<type:float> whose plaintext is C<+Inf>, C<-Inf> or C<NaN> is
B<unchanged> and still decrypts to a real Perl non-finite float, bit for bit --
measured on a document sops wrote, C<000000000000f07f>, C<000000000000f0ff> and
C<000000000000f8ff> -- because such a leaf is still an C<ENC[...]> string when
the document is parsed and cannot reach the retyping walk at all.

Arithmetic is not what changes. Perl numifies every one of those spellings to
the same double and does not warn, so C<0 + $value> answers exactly as before.
What moves is the scalar's B<type>, and with it what re-encrypting the returned
tree writes: C<type:str>, which is what sops writes for the same leaf, where
the numeric half used to hit the non-finite refusal in

lib/File/SOPS.pm  view on Meta::CPAN

changes the bytes the emitters write. Not the value: putting one into an
B<unencrypted> slot stores the canonical decimal as a number, in JSON as in
YAML (k78,
L<docs/adr/0011|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0011-a-float-leaf-that-carries-its-own-string-form-is-repaired.md>).
What changes is the spelling at the extremes -- C<1e300> written as 301
positional digits rather than C<1e+300> -- and an encrypted slot is unaffected
either way.

B<Since 0.003 a non-finite YAML literal comes back from an unencrypted slot as
a string, and is not wrapped either.> C<1e400>, a 401-digit integer and the
bare spellings C<Inf>, C<inf>, C<INF>, C<Infinity>, C<NaN>, C<nan>, C<NAN>,
C<-Inf> and C<+Inf> are the string go-yaml reads there, and a string is not a
float. This is a B<correction> -- such a leaf used to carry C<Inf> or C<NaN> as
its numeric half, on the few of those documents that could be read here at all
-- and it stops at the unencrypted slot: an B<encrypted> C<type:float> whose
plaintext is C<+Inf>, C<-Inf> or C<NaN> still comes back as the real Perl
non-finite float it always did. That one is the single float this method does
B<not> wrap, because C<+Inf> and C<NaN> are wire spellings rather than a
number's decimal, so C<"$value"> is Perl's own C<Inf> / C<NaN> and not a
canonical form. See L</A YAML literal that overflows a double comes back as a
string> under L</decrypt> and
L<File::SOPS::Encrypted/canonical_float_dualvar>.

B<Dies if the path does not exist>, at any depth, naming the component that was
not found. Before 0.003 a missing B<top-level> key returned C<undef> while a
missing nested one died, so the same mistake was silent or loud depending on
where it was made -- and C<undef> was indistinguishable from a key whose value
really is null. sops reports C<component ['nope'] not found> at every level.

lib/File/SOPS.pm  view on Meta::CPAN

say it: C<.inf> written plain is a float to go-yaml and to L</decrypt_file>'s
output alike, so a document sops wrote with a bare C<.inf> in an unencrypted
slot survives an edit and comes back with the wire byte-identical. Before
0.003 it did not -- editing any other key in such a file died with the leaf
refused, B<and the edit was destroyed with it>, because the temporary file is
already gone by then. See L</A plain YAML infinity is the float go-yaml reads>
and k123.

It is B<not> enough for a non-finite float in an B<encrypted> slot, and that
one is still wrong: such a leaf decrypts to a real Perl infinity, whose only
plaintext spelling from this emitter is a bare C<Inf> / C<-Inf> / C<NaN> --
tokens go-yaml reads as B<strings>. The editor is shown C<Inf>, the string
C<Inf> comes back, and the leaf is re-encrypted as a C<type:str>. C<sops edit>
keeps it a C<type:float>, measured. The file is written and nothing is said, so
this is the one place C<edit> can still lose a value quietly. Open as k134.

A C<data_key =E<gt> $bytes> argument would close the gap -- pass the
existing data key through and this method stops re-keying -- but it puts
raw key material on the public API, which is a real decision (and
probably an ADR) rather than a refactor. It will be worth doing once a
backend other than age exists (k39): today the refusal only fires

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN


# Canonical texts no emitter has a wire form for that it derives from the
# NUMBER alone: Go's strconv.FormatFloat produces them, and Perl's encoders
# produce something else (`null`, `Inf`) for the same double. Everything below
# that treats a non-finite float differently keys on this one regex, and it
# matches the output of value_to_bytes, never a rendering derived beside it.
#
# -0 used to be on this list and is not any more: k62 measured a YAML
# spelling that works, and the format that needed one supplies it in its own
# carrier. See docs/adr/0006.
my $NO_AGREED_FORM = qr/\A(?:NaN|[+-]Inf)\z/;

# The text value_to_bytes covers for a non-finite float, and undef for every
# other float. THE one statement of the rule: _float_bytes calls this and
# returns its answer, so what the digest covers and what the guards below ask
# about cannot become two comparisons against 9**9**9 that drift apart.
#
# It answers in three comparisons rather than through _float_bytes's whole
# shortest-round-trip loop, and that is measured rather than assumed: with the
# loop in the way, encrypt_value on a float leaf cost 130ms -> 272ms per 5000
# calls, a tax on every encrypted float for a guard about three values.
#
# The scalar is read numerically, which is what the digest does to it anyway.
# Nothing here reads or writes its string half.
my $POSITIVE_INFINITY = 9**9**9;

sub _non_finite_bytes {
    my ($n) = @_;

    return 'NaN' if $n != $n;                       # only NaN is unequal to itself
    return $n > 0 ? '+Inf' : '-Inf'
        if $n == $POSITIVE_INFINITY || $n == -$POSITIVE_INFINITY;
    return undef;
}

# The bytes go-yaml derives from a plain scalar it resolves to a non-finite
# float, for the twelve tokens that are the only spellings it does that for --
# and undef for everything else, `.INf`, `+.nan` and `.infinity` included.
#
# A SECOND STATEMENT of twelve rows of Go's resolveMap, whose single home is

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

# own foreign-resolution guard, which answers from `_go_scalar_bytes` -- the one
# model of resolve.go -- and has the last word on every document that carries a
# MAC. Both drift directions therefore fail CLOSED: a row here that
# %GO_CONSTANT lacks is refused by that guard on bytes, and a row %GO_CONSTANT
# gains that is missing here is refused by this gate. Neither can put a file on
# disk. See docs/adr/0031.
sub _go_non_finite_token_bytes {
    my ($token) = @_;
    return '+Inf' if $token =~ /\A\+?\.(?:inf|Inf|INF)\z/;
    return '-Inf' if $token =~ /\A-\.(?:inf|Inf|INF)\z/;
    return 'NaN'  if $token =~ /\A\.(?:nan|NaN|NAN)\z/;
    return undef;
}

# Does this scalar carry, as its OWN public string half, a token a foreign
# reader resolves back to exactly the double it holds?
#
# Both halves have to agree. dualvar(+Inf, '-.inf') is a contradiction -- the
# document would say one infinity and the digest cover the other -- and it is
# refused, the same answer docs/adr/0012 gives an integer whose halves disagree,
# and measured the same way (sops -d exit 51 for every mismatched pairing).

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

        return 1 if blessed($value);
        croak "cannot encrypt an unblessed " . ref($value)
            . " reference; the SOPS digest covers the reference's heap "
            . "address (e.g. SCALAR(0x...)), which differs per run, and "
            . "storing that as an encrypted value is almost never what the "
            . "caller means. Pass a string (the value the ref was holding, "
            . "or its stringification), or a blessed object whose "
            . "stringification is the value you mean.";
    }

    # k59: a non-finite float (NaN, +Inf, -Inf) has no agreed form on the
    # wire OF ITS OWN. value_to_bytes writes +Inf / -Inf / NaN -- the same text
    # Go's strconv.FormatFloat produces -- but the emitters write something
    # else for the same double: Cpanel::JSON::XS writes `null`, and YAML::XS
    # writes a bare `Inf` / `-Inf` / `NaN`, which go-yaml resolves as a STRING.
    # Measured against sops 3.13.3, unencrypted YAML leaf: `Inf` is `sops -d`
    # exit 51, and `-Inf` / `NaN` are exit 0 with the leaf silently retyped
    # from a float to a string -- which is worse, not better. Refused here, the
    # same shape as the ref and int64 checks.
    #
    # NARROWED for k113 / docs/adr/0031: that premise is about a scalar
    # whose only form is its number. One that also carries a plain YAML token
    # go-yaml resolves back to exactly that double -- the shape docs/adr/0026's
    # parse produces for a document sops wrote -- does have a wire form, and
    # refusing it left this library reading a document it could not write back
    # (rotate croaked on a file `sops -d` reads at exit 0). Measured, all twelve
    # tokens, unencrypted YAML slot: `sops -e` -> File::SOPS->rotate ->
    # `sops -d` exit 0, the wire byte-identical.
    #
    # This is a GATE, not the verdict. Whether the document being written can
    # really carry the token is a question about one emitter and one foreign
    # reader, and it is answered where the format is known: by docs/adr/0013's
    # foreign-resolution guard in Format::YAML, which compares the token that
    # emitter actually writes against Go's own resolution -- the single copy of
    # that model. canonical_float_tree hands the leaf over, and refuses it in a
    # MAC-covered document whose handler installs no such guard.
    #
    # Reading is unaffected -- a type:float plaintext of +Inf or NaN is accepted
    # by _deserialize_value today (k59's request, and Go writes it) and
    # stays accepted: assert_representable is encrypt-side only.
    #
    # NARROWED AGAIN for k122 / docs/adr/0040, and this time by SLOT. All
    # of the above is about a leaf the DOCUMENT carries as a token, which is
    # the unencrypted slot and nothing else. An encrypted slot carries
    # type:float and the plaintext value_to_bytes writes, in both formats, and
    # measured against sops 3.13.3 that is exactly what `sops -e` puts there --
    # `--output-type json` included, exit 0. So the emitters' inability to
    # spell the number says nothing about that slot, and the leaf is written.

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

# the bytes value_to_bytes covers for it. The INVERSE of
# _go_non_finite_token_bytes, narrowed to three of its twelve rows: sops
# normalises `.Inf`, `+.INF` and the rest away, so these are the only ones a
# document sops wrote can hold, and the only ones worth manufacturing.
#
# Not a third statement of Go's resolveMap. Every token this table produces is
# handed straight back to _go_non_finite_token_bytes by the check below, so a
# row here that gate does not accept REFUSES the document rather than writing
# it -- the same fail-closed pairing docs/adr/0031 set up between that gate and
# %GO_CONSTANT, one layer in.
my %GO_NON_FINITE_TOKEN = ('+Inf' => '.inf', '-Inf' => '-.inf', 'NaN' => '.nan');

# A non-finite float whose only form is its NUMBER, in the shape the emitter
# writing this document can put on the wire -- or a croak, where it has none.
#
# k134: an encrypted type:float decrypts to a bare Perl infinity, and
# YAML::XS writes one as `Inf` / `-Inf` / `NaN`, which go-yaml resolves as a
# STRING. So the plaintext decrypt_file and edit produce says a string where
# the document held a number, the editor hands that string back, and the leaf
# is re-encrypted as type:str -- silently, `sops -d` exit 0. Measured against
# sops 3.13.3, encrypted slot, three spellings: `sops -d` writes `.inf`,
# `-.inf` and `.nan`, and `sops edit` keeps the leaf a type:float. In JSON the
# same leaf reached the file as `null`, and edit replaced the whole ENC[...]
# with a bare unencrypted null -- where `sops -d --output-type json` and
# `sops edit` both refuse the document, exit 4.
#
# ASKED OF THE EMITTER, through the carrier -- the one hook whose job is

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

    # of the file. No text is derived for them on the way past -- value_to_bytes
    # encodes, and a handler with a cheap gate of its own should not pay a
    # conversion for every leaf it waves through.
    return _written_leaf($node, undef, $reject_scalar, $path) unless $kind eq 'float';

    # THE one conversion. This is the same method, on the same scalar, that the
    # MAC digest goes through -- not a second rendering that happens to agree
    # today. Do not inline a copy of it here.
    my $text = __PACKAGE__->value_to_bytes($node);

    # NaN and the infinities. The leaf is never REWRITTEN here -- neither the
    # round-trip test nor the carrier can help it, and k113 measured what
    # happens if they are asked: YAML::XS writes the token and libyaml reads it
    # back as a STRING, so $roundtrips answers no for a leaf that is perfectly
    # writable, and the carrier then replaces the document's own `.inf` with a
    # bare `+Inf` -- `sops -d` exit 0 and the leaf silently retyped to a string,
    # in both formats. A local reparse cannot answer a question about a foreign
    # resolver (docs/adr/0013). What changes is only who gets to CHECK it.
    #
    # A leaf whose string half is a token go-yaml resolves back to this same
    # double goes to the handler's foreign-resolution guard, which is the single

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

# numifies $g IN PLACE: the digits then left the loop carrying the double as
# well, so value_to_bytes returned a scalar detect_type called a float -- and
# for a negative zero an INT, since the text `-0` numifies to an IV. Text in,
# a number back out, from the one method whose whole job is to say what the
# wire carries. k72 and k73 are the same mechanism on the input side;
# this is k80 on the output side. Stringifying first numifies a COPY and
# leaves the digits a string, which is what they are.
sub _float_bytes {
    my ($n) = @_;

    # NaN and the infinities, from the one sub that decides what they are --
    # the same answer assert_representable and the emit walk ask for.
    my $non_finite = _non_finite_bytes($n);
    return $non_finite if defined $non_finite;

    my $g;
    for my $precision (1 .. 17) {                   # 17 always round-trips a double
        $g = sprintf('%.*g', $precision, $n);
        last if 0 + "$g" == $n;
    }

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

            unless _decimal_fits_int64($data);
        return 0 + $data;
    }
    # Go reads this back with strconv.ParseFloat, which fails on anything that
    # is not a number. Perl's numeric conversion turns it into 0 and says
    # nothing.
    if ($type eq 'float') {
        croak "type:float plaintext is not a number"
            unless $data =~ /\A[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)
                             (?:[eE][+-]?[0-9]+)?\z/x
                || $data =~ /\A[+-]?(?:Inf(?:inity)?|NaN)\z/i;

        # NOT `$data + 0.0`. That addition hands back a scalar carrying the
        # PUBLIC SVf_IOK flag whenever the result is integral -- grok_number
        # settles a text like `2` as an integer and pp_add calls SvIV_please --
        # so detect_type called the value an int and the next write relabelled
        # a leaf the document itself had marked type:float. Measured on a
        # document sops wrote: three of five type:float leaves came back
        # type:int after our rotate, exit 0 both times, silently (k73).
        #
        # pack 'd' lays the scalar's numeric value out as a native double and

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

Passing C<type> explicitly overrides the B<label> only, never the bytes: those
always come from what the value is. C<encrypt_value(value =E<gt> '007', type
=E<gt> 'int')> writes the label C<int> and the plaintext C<007>, because a
Perl string is written verbatim. That is how you reproduce a document some
other producer wrote; it is not how you write C<007> as an integer, which no
SOPS implementation does (see L</value_to_bytes>).

Dies if the value is one no SOPS document can carry -- today, an integer wider
than Go's C<int64>. See L</assert_representable>.

A B<non-finite float> (C<NaN>, C<+Inf>, C<-Inf>) B<is written>, in both
formats, as C<type:float> and the plaintext L</value_to_bytes> derives from the
number. That is what C<sops -e> stores for a plain C<.inf>, C<-.inf> or C<.nan>
-- measured against sops 3.13.3, six documents, C<--output-type yaml> and
C<--output-type json> alike, exit 0 with C<type:float> on the wire in both.
Every release before this one refused it here. See L</assert_representable>,
k122 and
L<docs/adr/0040|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0040-an-encrypted-slot-carries-a-non-finite-float-because-sops-writes-one.md>.

This method passes C<encrypted =E<gt> 1> to L</assert_representable>, which it
may because it B<is> the encrypted slot. The one non-finite shape still refused

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

and the caller had no reason to notice; that is the defect k67 exists to
close. A blessed object B<passes>: ADR 0008 measured that an encrypted
L<Math::BigFloat>, an object overloading C<"">, and a L<Regexp> all
round-trip correctly today -- they have a stringification the caller chose,
which is exactly what an encrypted slot carries. The exception is the same
class B<detect_type> uses for the digest, which is C<blessed($v)> and so
covers any subclass: the encrypted-slot rule and the unencrypted-slot guard
asked the same question in different ways and the encrypted slot is the
looser one.

=item B<A non-finite float:> C<NaN>, C<+Inf>, C<-Inf> -- B<unless it carries
go-yaml's own token for that double>. L</value_to_bytes> writes them as
C<NaN> / C<+Inf> / C<-Inf> -- the same text Go's C<strconv.FormatFloat>
produces -- but no emitter derives that text from the B<number>: Cpanel's
JSON encoder writes C<null> (the document is silently rounded), JSON::XS
writes bare C<inf> (invalid JSON, sops refuses with C<invalid character i>),
and YAML::XS writes a bare C<Inf> / C<-Inf> / C<NaN>, which Go's yaml.v3
resolves as a B<string>. Measured against sops 3.13.3 in an unencrypted YAML
slot, C<Inf> is C<sops -d> exit 51 and C<-Inf> / C<NaN> are exit 0 with the
leaf silently retyped from a float to a string -- which is worse, not
better. The pre-fix code wrote the file anyway, and the caller had no reason
to notice; that is the defect k59 exists to close.

B<Narrowed since 0.003> (k113, C<docs/adr/0031>): a scalar that also
carries, as its own string half, one of the twelve plain tokens go-yaml
resolves to exactly that double -- C<.inf>, C<+.Inf>, C<-.INF>, C<.nan> and
their case variants -- B<is> written, in an unencrypted YAML slot. That is
the shape L<File::SOPS::Format::YAML/parse> produces for a document sops
wrote (C<docs/adr/0026>), and refusing it left this library reading a

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

to sops, and a C<dualvar(+Inf, 'banana')> would put a document on disk that
fails its own MAC. This check is a B<gate>: whether the document being
written can really carry the token is answered where the format is known, by
the foreign-resolution guard C<docs/adr/0013> installs in the YAML handler.
A JSON document has no such spelling in an unencrypted slot (measured,
C<sops -d> exit 51) and is refused there.

B<Everything in this item is about the UNENCRYPTED slot>, which is the only
one whose leaf reaches the document as a token. With C<encrypted =E<gt> 1>
the value is written instead: the wire carries C<type:float> and the
plaintext C<+Inf> / C<-Inf> / C<NaN>, in both formats, which is what
C<sops -e> writes for the same value (k122, C<docs/adr/0040>). The one
exception is a scalar that B<states> a string half its number contradicts --
C<dualvar(+Inf, 'banana')>, or the JSON literal of 400 zeros whose text is
its digits -- because the encrypted slot is derived from the number and that
text would be dropped without a trace.

Store the value as a B<string> instead where none of that applies -- that is
C<type:str>, written verbatim, and the same number (or its deliberate
stringification) is round-tripped exactly through both implementations.
Reading is unaffected: a C<type:float> plaintext of C<+Inf> or C<NaN> is
accepted by L</decrypt_value> today, and sops itself writes such a value, so
the read path has to keep accepting it.

Since 0.003 a B<parsed document> can reach this guard on its own, where the
route in used to be Perl code or a YAML C<.inf>: a bare JSON integer literal
that overflows a double -- C<1> followed by 400 zeros -- is a C<float>
(L</detect_type>) whose value is C<+Inf>, and it used to be read as a string
and written back as one. The croak is the closer answer, because sops
refuses that document itself and one step earlier, at unmarshal time
(measured, sops 3.13.3, exit 2, C<strconv.ParseFloat: value out of range>).

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

The canonical text is B<not> recomputed by the caller and must not be: a second
conversion is how the ciphertext and the digest came to disagree in the first
place, and it is invisible from inside Perl because both sides are then
consistently wrong.

Call this at B<emit time, on a copy, after the digest has been taken>. The
walk that computes the MAC must never see a carrier: the L<Math::BigFloat> one
is a blessed reference, which L</detect_type> calls C<str>, so the digest would
cover its stringification instead of the number.

C<NaN>, C<+Inf> and C<-Inf> never go through C<roundtrips>. That callback
reparses with this side's own parser, which reads C<.inf> back as a string, so
it answers no for a leaf that is perfectly writable, and the carrier would then
be handed C<+Inf> as the text and write a bare C<+Inf> -- a document C<sops -d>
reads at exit 0 with the leaf silently retyped to a string.

What the walk does with one depends on whether anything can vouch for it. A
non-finite leaf whose B<string half> is a plain token go-yaml resolves back to
that same double -- C<.inf>, C<-.inf>, C<.nan> and their case variants, the
shape a sops-written YAML document parses to (C<docs/adr/0026>) -- is passed to
C<reject_scalar>, whose model of the foreign resolver is the one that decides.

lib/File/SOPS/Encrypted.pm  view on Meta::CPAN

L<File::SOPS::Format::YAML/emit>.

=head2 canonical_float_dualvar

    my $value = File::SOPS::Encrypted->canonical_float_dualvar($value);

Class method. Returns C<$value> with its stringification replaced by the
canonical decimal from L</value_to_bytes> -- numerically the same double, as a
string the text the document actually contains. Anything that is not a plain
float scalar comes back untouched: a reference, C<undef>, a string, an int, a
boolean, and a non-finite float, whose C<NaN> / C<+Inf> / C<-Inf> are wire
spellings rather than a number's decimal.

This exists because a decrypted float is a bare NV with no string form of its
own, so Perl renders it at 15 significant digits: an encrypted
C<0.30000000000000004> printed as C<0.3>, where C<sops -d --extract> prints all
17. See k61 and
L<docs/adr/0010|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0010-extract-returns-a-float-that-prints-all-its-digits.md>.

B<Only for a value on its way out to a caller.> The result is a
L<Scalar::Util/dualvar>, and a dualvar inside a tree changes the bytes the

lib/File/SOPS/Format/JSON.pm  view on Meta::CPAN

a value needing 16 or 17 the document stated one number and the digest another,
and the file failed its own verification; because this backend keeps no copy of
the text it parsed, that applied to floats read out of a sops-written document
as much as to computed ones, so C<rotate> could destroy a value the reference
implementation had written correctly. This method now reparses its own output
and substitutes the canonical decimal from
L<File::SOPS::Encrypted/value_to_bytes> only where the value does not survive,
carried as a L<Math::BigFloat> under C<allow_bignum> -- the only wrapper
measured to reach JSON as a bare number instead of a quoted string. A float that
already emitted faithfully keeps exactly the bytes it had, C<-0.0> included.
C<NaN> and C<Inf> are unchanged. See
L<docs/adr/0006|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0006-floats-are-emitted-in-a-form-that-parses-back-to-the-same-double.md>.

B<A float leaf carrying its own string form is written as a number.>
L<Cpanel::JSON::XS> writes a scalar with a public string half as a quoted JSON
string whenever that half differs from its own rendering of the number, so such
a leaf reached the document as a B<string> where the caller passed a number. It
failed nothing: the digest covers the canonical decimal either way, the file
verifies, and C<sops -d> exits 0 and reads a string back -- the value's type
changed and nothing said so. The round-trip check above could not see it,
because the reparsed string re-derives the very text the digest covers. It now

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN

# too -- which never had this guard, and carried k108's defect unnoticed
# the whole time (measured against sops 3.13.3: `sops -e --output-type json`
# writes type:comment leaves into JSON).
#
# Mapping-position comments are unchanged and remain the open half of k76:
# YAML::XS drops them on the way in and no emitter here can write one.

###############################################################################
# A literal libyaml numifies past the end of a double (k102, docs/adr/0023)
#
# `1e400`, a 401-digit integer, `Inf`, `NaN`: libyaml resolves each of them to a
# number, and the number it lands on is +Inf, -Inf or NaN. go-yaml resolves none
# of them -- strconv.ParseFloat answers ErrRange and yaml.v3 keeps a STRING --
# so sops writes `type:str` and digests the token's own bytes. Ours said `float`
# and digested `+Inf`, which is a document sops wrote that we cannot read and a
# value we cannot write.
#
# The repair is at PARSE time and nowhere else, because what is wrong is our
# parse result and not any guard downstream. _go_scalar_bytes already models the
# Go side correctly for all 29 spellings measured; detect_type already reads the
# SV and nothing else (ADR 0002); the non-finite guard from k59 is right
# about every value it was written for and is untouched here. What this does is
# hand the rest of the distribution the leaf go-yaml sees.
#
# The predicate is the SV, not the text (ADR 0002): a leaf whose PUBLIC SVf_NOK
# and SVf_POK are both set and whose NV is NaN or +-Inf. It cannot collide with
# the tokens Go DOES resolve to a non-finite float -- `.inf .Inf .INF +.inf
# +.Inf +.INF -.inf -.Inf -.INF .nan .NaN .NAN`, the twelve in %GO_CONSTANT --
# because YAML::XS hands every one of those back POK-ONLY. Measured against
# sops 3.13.3: those twelve are `type:float` to sops and fire nothing here; the
# 29 spellings that do fire are `type:str` to sops, every one. The two sets are
# disjoint, and that disjointness is what keeps this from retyping a leaf Go
# reads as a float.
#
# JSON is deliberately NOT walked. sops refuses such a JSON document at
# unmarshal time (`strconv.ParseFloat: value out of range`, exit 2), so the
# croak Format::JSON's leaf earns there is the reference behaviour -- see
# ADR 0020, which predicted this lever and expected it to answer for both

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN

# So a repair keyed on the leaf's TEXT fixes the first row and silently breaks
# the second, which works today. The question is not what the value is; it is
# whether the document wrote the scalar PLAIN, and that is a fact about the
# bytes.
#
# YAML::PP -- already this distribution's second parser (ADR 0001) -- answers
# it. Its Core schema resolves a scalar to a non-finite number IFF the scalar
# was written plain and its token is one of the twelve in %GO_CONSTANT.
# Measured: 12 of 12 plain tokens yes; 0 of 24 quoted; 0 of 12 near misses
# (`.INf` `.iNF` `.Nan` `.NAn` `+.nan` `-.nan` `-.NAN` `.infinity` `.Infinity`
# `Inf` `inf` `NaN`), every one of which is a type:str to sops and reads
# correctly here today. On the WIRE -- which is what this path sees -- sops has
# already normalised `!!float .inf` and `&a .inf` to a bare `.inf` and
# `!!str .inf` and `'.inf'` to a quoted `".inf"`, so only those two spellings
# arrive, and the oracle separates them in all four cases.
#
# This is NOT the "ask YAML::PP instead of modelling Go" that ADR 0013 and
# ADR 0023 rejected. There the question was what a value IS, and YAML::PP
# answers it the way libyaml does -- `0755` is 755 to both and 493 to Go, so it
# agrees with the side that is already wrong. Here it is asked whether a scalar
# was written plain, which is syntax rather than resolution; the VALUE still

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN

#
# ADR 0031 removed the premise: an unencrypted YAML slot holding one of these
# tokens IS written now, byte-identical to what sops writes. So the gate was
# refusing three documents this library can produce, and the two parses
# disagreed about identical bytes -- measured, `decrypt_file` wrote
# `v_unencrypted: .inf` and `encrypt_file` refused to read its own output back.
# sops resolves a plain scalar the same way on every parse; so does this now.
#
# WHAT IS WRITTEN BACK is a dualvar, not a bare infinity, and that is measured
# rather than tidy: YAML::XS writes a bare non-finite NV as `Inf` / `-Inf` /
# `NaN`, tokens go-yaml resolves as STRINGS, and writes dualvar(+Inf, '.inf')
# as `.inf`, the token sops itself writes. So decrypt_file reproduces sops's
# own plaintext byte for byte instead of degrading the value on the first
# round trip. Same shape as ADR 0011's carrier: a float leaf whose string half
# is the text the document contains.
#
# Since k113 (docs/adr/0031) such a document is written back as well: the
# non-finite guard lets a leaf carrying one of these tokens through to
# ADR 0013's foreign-resolution guard, which measures the token the emitter
# really writes. An ENCRYPTED slot is still refused there (k122).
my $PLAIN_STYLE_LOADER = YAML::PP->new(schema => [qw( Core )]);

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN

# The safely-quotable non-finite spellings (docs/adr/0070), scoped to EXACTLY
# the seven ADR 0038/0039 measured. A str leaf whose value is one of these came
# unambiguously from a QUOTED source or a caller's own Perl string, because
# _restore_plain_infinities (docs/adr/0026, 0034) already resolved a bare one to
# a float at parse -- so writing it double-quoted states the type it already
# has, and sops writes and reads the same bytes (measured, sops -d exit 0). The
# other five non-finite tokens in %GO_CONSTANT (`+.Inf +.INF -.Inf -.INF .NAN`)
# are deliberately NOT here: the corpus did not measure them, and "no wider than
# the nine rows" keeps them refused as they are today.
my %QUOTABLE_NON_FINITE =
    map { $_ => 1 } ( '.inf', '.Inf', '.INF', '+.inf', '-.inf', '.nan', '.NaN' );

sub emit {
    my ($class, $data, %args) = @_;
    croak "data required" unless defined $data;

    # A multi-document stream is an ArrayRef of document trees (docs/adr/0033,
    # k31). A bare HashRef is one document and stays byte-identical.
    my @docs = ref $data eq 'ARRAY' ? @$data : ($data);
    croak "data required" unless @docs;

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN

# null contributes nothing -- measured: a sops-written `x_unencrypted: null`
# verifies against this module's own digest, which covers the empty string.
my %GO_CONSTANT = (
    'true'  => 'True',  'True'  => 'True',  'TRUE'  => 'True',
    'false' => 'False', 'False' => 'False', 'FALSE' => 'False',
    ''      => '',      '~'     => '',
    'null'  => '',      'Null'  => '',      'NULL'  => '',
    '.inf'  => '+Inf',  '.Inf'  => '+Inf',  '.INF'  => '+Inf',
    '+.inf' => '+Inf',  '+.Inf' => '+Inf',  '+.INF' => '+Inf',
    '-.inf' => '-Inf',  '-.Inf' => '-Inf',  '-.INF' => '-Inf',
    '.nan'  => 'NaN',   '.NaN'  => 'NaN',   '.NAN'  => 'NaN',
);

# The DOUBLE go-yaml resolves one of those tokens to, or undef for a token it
# does not resolve to a number at all. Derived from %GO_CONSTANT's own byte
# string rather than from a second list of spellings: there is one token list
# in this module, and a copy of it is how a repair and the guard it depends on
# drift apart (ADR 0002's defect class, and k89's shape one level down).
#
# It lives HERE rather than beside its caller because it reads %GO_CONSTANT,
# and a `my` hash is not in scope above its own declaration. See
# _restore_plain_infinities, k105 and docs/adr/0026.
# The four bytes a repairable token cannot be written without. Built from the
# same %GO_CONSTANT keys, so widening that table widens this with it.
my $GO_NON_FINITE_TEXT = do {
    my @token = grep { $GO_CONSTANT{$_} =~ /\A(?:[-+]Inf|NaN)\z/ } keys %GO_CONSTANT;
    my %tail  = map  { (substr($_, -4) => 1) } @token;
    my $alt   = join '|', map { quotemeta } sort keys %tail;
    qr/(?:$alt)/;
};

sub _go_non_finite_in_text {
    return $_[0] =~ $GO_NON_FINITE_TEXT ? 1 : 0;
}

sub _go_non_finite_double {
    my ($token) = @_;

    my $bytes = $GO_CONSTANT{$token};
    return undef unless defined $bytes;

    return  $bytes eq '+Inf' ?  $POSITIVE_INFINITY
          : $bytes eq '-Inf' ? -$POSITIVE_INFINITY
          : $bytes eq 'NaN'  ?  $POSITIVE_INFINITY - $POSITIVE_INFINITY
          :                     undef;
}

# strconv.ParseInt/ParseUint with base 0, as a digit string. The magnitude is
# accumulated in Perl's own integer space, guarded by a STRING comparison
# against the base's uint64 maximum -- dividing to test for overflow is exactly
# where a double stops being exact, and a wrong answer here is a document
# refused or written for the wrong reason.
my %GO_BASE_MAX = (
    2  => '1111111111111111111111111111111111111111111111111111111111111111',

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN


Dies too if the document has a top-level C<sops> entry that is B<not> a
mapping -- C<sops: mine>, a list, or an explicit C<null>. Until 0.003 that
entry was deleted from the tree and reported as no metadata at all, so
L<File::SOPS/encrypt_file> wrote the document back without it. See
L<File::SOPS::Metadata/from_hash>, which is where the refusal lives.

=head3 A literal that overflows a double comes back as a string

C<1e400>, a 401-digit integer, and the bare spellings C<Inf>, C<inf>, C<INF>,
C<Infinity>, C<NaN>, C<nan>, C<NAN>, C<-Inf> and C<+Inf> are all resolved to a
B<number> by libyaml, and the number each of them lands on is C<+Inf>, C<-Inf>
or C<NaN>. go-yaml -- the parser sops reads a document with -- resolves none of
them: C<strconv.ParseFloat> answers C<ErrRange> and it keeps a B<string>. So
sops writes C<type:str> for such a leaf and digests the literal's own text.

Since 0.003 this method hands back the string go-yaml sees, so that
L<File::SOPS::Encrypted/detect_type> and the MAC agree with sops. Before it,
such a document could be neither read (17 of 20 measured documents that sops
writes failed MAC verification here) nor written (all 20 hit the non-finite
refusal in L<File::SOPS::Encrypted/assert_representable>).

Three things this is B<not>. It does not touch the twelve spellings go-yaml
really does resolve to a non-finite float -- C<.inf .Inf .INF +.inf +.Inf
+.INF -.inf -.Inf -.INF .nan .NaN .NAN> -- because L<YAML::XS> returns every
one of those as a plain string with no numeric half at all; those have a
repair of their own since 0.003, and a different one, described in
L</A plain infinity comes back as the float go-yaml reads>. It does not loosen
L<File::SOPS::Encrypted/assert_representable>: a caller who passes
L<File::SOPS/encrypt> a real C<9**9**9> still gets the refusal, because what is
repaired here is a parse result and not a rule about values. And it does not
apply to L<File::SOPS::Format::JSON>, where sops refuses the equivalent
document itself, at unmarshal time.

The cost is that the leaf is written back B<quoted> -- C<v: '1e400'> where sops

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN

=head3 A plain infinity comes back as the float go-yaml reads

The mirror image of the section above, and it needs a different authority.
L<YAML::XS> leaves C<.inf> a B<string>; go-yaml resolves it to the float
C<+Inf>, and sops digests C<+Inf>. So a document sops writes and C<sops -d>
verifies used to fail MAC verification here, with an error that named nothing.

Since 0.003 a leaf the document wrote as a B<plain> scalar, and whose token is
one of the twelve above, comes back as a L<Scalar::Util/dualvar>: the float
go-yaml resolved, carrying the document's own token as its text. So
L<File::SOPS::Encrypted/value_to_bytes> derives C<+Inf> / C<-Inf> / C<NaN> --
the bytes sops put in the MAC -- while every emitter writes the file back
exactly as it read it, and L<File::SOPS/decrypt_file> reproduces sops's own
plaintext byte for byte.

B<The word "plain" is the whole of it>, and it is why this repair is not the
one above. Measured against sops 3.13.3, in one document:

    list_unencrypted:
        - .inf          # go-yaml: a float,  digested +Inf
        - ".inf"        # go-yaml: a string, digested .inf

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN


B<This runs on every document, plaintext included>, and the plaintext half is
newer than the rest. Until 0.003 it was gated on the C<sops:> section, on the
argument that a plaintext has no MAC for anyone to disagree with; that gate is
gone, because the document such a plaintext turns into I<can> now be written
(see below), so the gate was refusing a document this module produces. sops
resolves a plain scalar the same way on every parse it makes, and so does this.

B<Such a document is written back> since 0.003: an B<unencrypted> YAML slot
holding one of the twelve tokens reaches the file as that token, with the
digest covering C<+Inf> / C<-Inf> / C<NaN>, which is what sops writes and what
sops digests for the same document. An B<encrypted> slot is still refused --
the wire form there is C<type:float> with the plaintext C<+Inf>, which
L<File::SOPS::Encrypted/encrypt_value> refuses because it cannot see which
format is being written (k122).

See
L<docs/adr/0026|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0026-a-plain-yaml-infinity-is-the-float-go-yaml-reads.md>,
L<docs/adr/0031|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0031-a-non-finite-float-that-carries-go-yamls-own-token-is-written.md>
and
L<docs/adr/0034|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0034-a-plain-scalar-is-resolved-the-same-way-on-every-parse.md>.

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN

it writes it double-quoted and reads it back -- measured against sops 3.13.3, 22
such spellings, C<sops -d> exit 0 for every one, and this module reads all 22 of
those documents correctly, in both slots, with the MAC verified. For fifteen of
them it cannot B<write> the leaf: a bare C<2015-01-01> and a quoted
C<"2015-01-01"> arrive as the same Perl string, while sops writes
C<2015-01-01T00:00:00Z> for the first and C<"2015-01-01"> for the second, so
quoting a leaf whose source may have been bare would turn a loud refusal into a
silent value divergence. Those fifteen stay refused, and the message names the
two remedies measured to work for them -- encrypt the leaf, or write the
document as JSON. The other seven -- the non-finite str spellings C<.inf>,
C<.Inf>, C<.INF>, C<+.inf>, C<-.inf>, C<.nan> and C<.NaN> -- parse
B<unambiguously>: a bare one is resolved to a float at parse (C<docs/adr/0026>),
so a leaf still holding the string can only have come from a quoted source or a
caller's own Perl string, and double-quoting it states the type it already has.
Since C<docs/adr/0070> this emitter writes those seven double-quoted through a
fail-closed sentinel substitution -- the same nine-leaf safe set as C<True> and
C<False> below -- byte-identical to what sops writes. See
L<docs/adr/0039|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0039-a-string-leaf-this-emitter-cannot-quote-stays-refused-and-says-so.md>,
k135,
L<docs/adr/0070|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0070-a-scoped-per-scalar-quote-is-feasible-for-the-non-ambiguous-divergent-string-leaves.md>
and k99.

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN

these files, and the MAC covers values rather than serialized text -- and it is
kept rather than stripped, since the MAC's encrypt side rides on this emitter
(C<docs/adr/0001>). See L<File::SOPS/Every YAML file starts with C<--->, where
sops writes none> and k83.

Called on its own -- which is what the plaintext emitters do -- it writes most
YAML spellings unchanged, C<0755> and C<2015-01-01> included, and a bare
C<type:float> C<.inf> stays bare. What it does B<not> pass through untouched is
the safe set L</serialize> force-quotes: a C<True> or C<False> string and the
seven parse-unambiguous non-finite C<str> spellings (C<.inf>, C<.Inf>, C<.INF>,
C<+.inf>, C<-.inf>, C<.nan>, C<.NaN>) are double-quoted here too. That is what
sops itself writes for those leaves, so C<decrypt_file> and C<edit> are faithful
inverses of it: a decrypt then re-encrypt round trip no longer flips such a leaf
from string to float or bool (a bare C<.inf> would resolve to C<+Inf> at the
next parse). It reuses ADR 0070's fail-closed sentinel mechanism unchanged. See
L<docs/adr/0071|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0071-the-plaintext-emitter-quotes-the-same-safe-set-so-it-is-a-faithful-inverse.md>
and k186.

The refuse-or-warn guard L</serialize> installs against the rest of the divergent
class is deliberately still not here: a plaintext document carries no MAC for a
reader to disagree with, and refusing them would refuse to write out documents

lib/File/SOPS/Format/YAML.pm  view on Meta::CPAN

B<Floats are written in a form that parses back to the same double.> L<YAML::XS>
renders a float by Perl stringification, roughly 15 significant digits, while
the MAC digest covers the shortest decimal that round-trips -- up to 17. For a
value needing 16 or 17 the document stated one number and the digest another,
and the file failed its own verification. This method now reparses its own
output and substitutes the canonical decimal from
L<File::SOPS::Encrypted/value_to_bytes> only where the value does not survive,
so a float that already emitted faithfully keeps exactly the bytes it had. In
practice that is most of them: YAML::XS retains the text of every float it
parsed, so only bare NVs -- computed by the caller, or parsed out of JSON --
are ever rewritten. C<NaN> and C<Inf> are unchanged -- they have no YAML form
Go reads back, and L<File::SOPS::Encrypted/assert_representable> refuses them
on the encrypt path. A negative zero B<is> rewritten, and it is the one value
whose written decimal is not L<File::SOPS::Encrypted/value_to_bytes>'s output
verbatim: that is C<-0>, which YAML resolves as an B<integer> and every reader
digests as C<0>, so this emitter writes C<-0.0> instead -- the spelling
measured to read back as the same double in sops 3.13.3 and here. See
L<docs/adr/0006|https://github.com/Getty/p5-file-sops/blob/main/docs/adr/0006-floats-are-emitted-in-a-form-that-parses-back-to-the-same-double.md>.

B<An integer leaf whose string form contradicts its number is refused.>
L<YAML::XS> writes the string half bare -- C<five> for a

t/24-float-precision.t  view on Meta::CPAN

        [ '0',        '0' ], [ '0.0',     '0' ], [ '+0',      '0' ],
        [ '+0.0',     '0' ],
        [ '-1',      '-1' ], [ '1',       '1' ], [ '-0.5', '-0.5' ],
        [ '0.5',    '0.5' ], [ '1.5',   '1.5' ], [ '-1.5', '-1.5' ],
        [ '3.14',  '3.14' ], [ '-3.14','-3.14'], [ '0.1',   '0.1' ],
        [ '-0.1',  '-0.1' ],
        [ '0.30000000000000004', '0.30000000000000004' ],
        [ '1e20',   '100000000000000000000' ],
        [ '-1e20', '-100000000000000000000' ],
        [ '1e-20',  '0.00000000000000000001' ],
        [ 'NaN',     'NaN' ], [ 'Inf',  '+Inf' ], [ '-Inf', '-Inf' ],
    );

    for my $row (@ladder) {
        my ($plaintext, $expected) = @$row;
        my $enc = File::SOPS::Encrypted->encrypt_value(
            value => $plaintext, type => 'float', key => $key, aad => '',
        );
        is($enc->decrypt_bytes(key => $key, aad => ''), $plaintext,
            "[$plaintext] the fixture really carries that plaintext");
        my $value = $enc->decrypt_value(key => $key, aad => '');

t/24-float-precision.t  view on Meta::CPAN

        # would never have produced from this plaintext.
        [ '9007199254740993',    '9007199254740992'    ],
        [ '9223372036854775807', '9223372036854776000' ],
        # Controls: rows that were already float and must not move.
        [ '2.0',  '2' ], [ '0.0',   '0' ], [ '1.5', '1.5' ],
        [ '-1.5', '-1.5' ], [ '0.1', '0.1' ],
        [ '0.30000000000000004', '0.30000000000000004' ],
        [ '1e20', '100000000000000000000' ],
        [ '1e-20', '0.00000000000000000001' ],
        [ '-0',   '-0' ], [ '-1e-400', '-0' ],
        [ 'NaN', 'NaN' ], [ 'Inf', '+Inf' ], [ '-Inf', '-Inf' ],
    );

    for my $row (@ladder) {
        my ($plaintext, $expected) = @$row;
        my $enc = File::SOPS::Encrypted->encrypt_value(
            value => $plaintext, type => 'float', key => $key, aad => '',
        );
        my $value = $enc->decrypt_value(key => $key, aad => '');
        is(File::SOPS::Encrypted->detect_type($value), 'float',
            "[$plaintext] comes back as a float, so the next write keeps type:float");

t/24-float-precision.t  view on Meta::CPAN

    # decrypt() is the same boundary from the other side. read_file in a
    # scalar, because in list context it returns LINES and would shift every
    # named argument after it.
    my $document = read_binary($enc_file);
    my $data = File::SOPS->decrypt(encrypted => $document,
        identities => [$secret], format => 'json');
    ok(!isdual($data->{db}{ratio}), 'decrypt returns plain scalars too');
};

subtest 'a non-finite float is returned unwrapped (ADR 0010)' => sub {
    # +Inf / NaN are value_to_bytes wire spellings, not a number decimal, and
    # no emitter has an agreed form for them. A caller printing one gets Perl's
    # own text, as before.
    my $key = "\x03" x 32;
    for my $plaintext (qw( NaN Inf -Inf )) {
        my $enc = File::SOPS::Encrypted->encrypt_value(
            value => $plaintext, type => 'float', key => $key, aad => '',
        );
        my $value = $enc->decrypt_value(key => $key, aad => '');
        my $wrapped = File::SOPS::Encrypted->canonical_float_dualvar($value);
        ok(!isdual($wrapped), "[$plaintext] comes back unwrapped");
    }

    # And everything that is not a float scalar at all.
    for my $case ([ 'a string', 'hello' ], [ 'an int', 42 ],

t/28-non-finite-float-refusal.t  view on Meta::CPAN

use strict;
use warnings;
use Test::More;
use File::Temp qw(tempdir);
use File::Slurper qw(write_binary);

use File::SOPS;
use Crypt::Age;

# ----------------------------------------------------------------------------
# k59: a non-finite float (NaN, +Inf, -Inf) has no agreed form on the
# wire. value_to_bytes writes +Inf / -Inf / NaN -- the same text Go's
# strconv.FormatFloat produces -- but no emitter can carry it. Cpanel writes
# null (silently rounded), JSON::XS writes bare inf (invalid JSON, sops exit
# 1), YAML::XS writes bare Inf / NaN (self-MAC OK, sops -d exit 51). All
# three produce a file nothing can read back.
#
# The pre-fix code wrote the file anyway. assert_representable now refuses
# them at encrypt time, with the same shape as the int64 and ref guards:
# the exception names the form, says to store as a string, never names the
# value. Reading is unaffected: a type:float plaintext of +Inf or NaN is
# accepted by _deserialize_value today (and sops writes it), and stays
# accepted.
#
# k141 / docs/adr/0062 NARROWED the unencrypted-slot refusal by PUBLIC PV:
# a leaf WITHOUT one (a bare NV, like `9**9**9`) is no longer refused here.
# docs/adr/0037's _non_finite_token_leaf manufactures the carrying dualvar for
# it in YAML (the carrier consults go-yaml's own twelve tokens and the YAML
# emitter writes the token the digest covers), so the leaf now reaches the
# document as `.inf` / `-.inf` / `.nan`. JSON has no such carrier, and the
# refusal there moves to the emit walk's mac_covered croak -- where the

t/28-non-finite-float-refusal.t  view on Meta::CPAN


my ($public, $secret) = Crypt::Age->generate_keypair();
my $tempdir = tempdir(CLEANUP => 1);
write_binary("$tempdir/key.txt", $secret);
$ENV{SOPS_AGE_KEY_FILE} = "$tempdir/key.txt";

my $inf = 9**9**9;
my %cases = (
    '+Inf' => $inf,
    '-Inf' => -$inf,
    'NaN'  => $inf - $inf,
);

###############################################################################
# 1. WRITE-SIDE SPLIT. A bare NV (no public PV) used to be refused by
#    assert_representable's unencrypted-slot guard in both formats (k59).
#    k141 / docs/adr/0062 removed that refusal: the YAML carrier
#    (docs/adr/0037) manufactures the carrying dualvar `.inf` / `-.inf` /
#    `.nan`, and the leaf now reaches the document as that token. JSON has no
#    such carrier, and the refusal moves to the emit walk's mac_covered croak.
#
#    Same value, same slot, two different answers -- the YAML carrier is the
#    ONLY difference, which is why this section splits by format rather than
#    asserting the same answer twice.
###############################################################################

# What the YAML carrier spells for each form. Verified against sops 3.13.3:
# `sops -e` normalises to the same three spellings.
my %CARRIER_TOKEN = ('+Inf' => '.inf', '-Inf' => '-.inf', 'NaN' => '.nan');

for my $name (sort keys %cases) {
    my $value = $cases{$name};
    my $token = $CARRIER_TOKEN{$name};

    subtest "[yaml] encrypt() writes a bare non-finite float ($name) as the carrier's token" => sub {
        my $encrypted = File::SOPS->encrypt(
            data       => { x_unencrypted => $value, secret => 'shh' },
            recipients => [$public],
            format     => 'yaml',

t/28-non-finite-float-refusal.t  view on Meta::CPAN

        ok(defined $encrypted, "-0.0 passes assert_representable in $format")
            if !$@;
    }
};

###############################################################################
# 4. THE READ PATH: a sops-written document carrying an unencrypted float
#    readable as +Inf (which sops writes as `Inf`) -- wait, JSON sops
#    writes `null` for that, so an unencrypted +Inf does not survive a
#    sops round trip. The legitimate read path is the ENCRYPTED type:float
#    plaintext +Inf or NaN, which sops writes when its input is the string
#    "Inf" or "NaN" with the value type manually labelled. The smaller
#    read-direction claim we can actually pin is that _deserialize_value
#    accepts the plaintext, which is what encrypt_value's encrypt side
#    would also produce if the caller forced type => 'float' on a string
#    'Inf'. assert_representable does NOT run on the encrypt path when
#    type is forced (the force skips the auto-detect that calls
#    _sv_kind and then refuses); verify this end-to-end.
###############################################################################

subtest "encrypt_value with type=>'float' on a caller-forced 'Inf' string still works" => sub {
    # Caller says: this is a type:float, plaintext 'Inf'. The plaintext is

t/31-negative-zero-integer-cache.t  view on Meta::CPAN

subtest 'the Go model still answers what ADR 0013 measured' => sub {
    my %expected = (
        '0755'                => '493',
        '010'                 => '8',
        '007'                 => '7',
        '1e3'                 => '1000',
        '0755e0'              => '755',
        '1_000'               => '1000',
        '.inf'                => '+Inf',
        '-.inf'               => '-Inf',
        '.nan'                => 'NaN',
        'TRUE'                => 'True',
        '2015-01-01'          => '2015-01-01T00:00:00Z',
        '2015-01-01T12:00:00Z' => '2015-01-01T12:00:00Z',
        '-0.5e0'              => '-0.5',
        '-1.0e0'              => '-1',
        '0.0e0'               => '0',
        '-0'                  => '0',
        'localhost'           => 'localhost',
        '123abc'              => '123abc',
    );

t/39-yaml-overflow-literal-becomes-a-string.t  view on Meta::CPAN

    '1e400', '-1e400', '1.5e400', '1e309', '1e310', '1e4000',
    '1' . ('0' x 400), '-1' . ('0' x 400), '+1' . ('0' x 400),
    '17976931348623158079372897140530341507993413271003782693617377898044'
  . '49682927647509466490179775872070963302864166928879109465555478519404'
  . '02630657488671505820681908902000708383676273854845817711531764475730'
  . '27006985557136695962284291481986083493647529271907416844436551070434'
  . '2711559699508093042880177904174497792',
);

# The second class, same mechanism: libyaml numifies each of these too.
my @SPELLINGS = qw( Inf inf INF NaN nan NAN -Inf +Inf Infinity -nan );

# The twelve go-yaml really does resolve to a non-finite float. In THIS file's
# plaintext parse -- yaml_leaf() below hands Format::YAML->parse a document
# with no sops: section -- these must NOT move: they stay POK-only here, and
# they are type:float to sops but str to us. ADR 0026 (k105, resolved)
# is why that is no longer the whole story: the same twelve DO move -- they
# come back a float whose digest is +Inf / -Inf / NaN -- once the document
# carries a sops: section, which this file's helper never gives it. See
# t/42-yaml-plain-infinity-is-a-float.t sections 1 and 7 for that other half.
my @GO_RESOLVES = qw(
    .inf .Inf .INF +.inf +.Inf +.INF -.inf -.Inf -.INF .nan .NaN .NAN
);

###############################################################################
# 1. THE MOVED ROWS. A literal libyaml pushed past the end of a double is the
#    string go-yaml kept, and its digest input is the literal's own text.
###############################################################################

subtest 'an overflowing literal parses to the string sops digests' => sub {
    for my $source (@OVERFLOW) {
        my $short = length($source) > 20 ? substr($source, 0, 17) . '...' : $source;
        my $leaf  = yaml_leaf($source);

        is(ref($leaf), '', "[$short] a plain scalar");
        is(leaf_type($leaf), 'str', "[$short] typed str, not float");
        is(leaf_bytes($leaf), $source,
            "[$short] and its digest input is the literal, not +Inf");
    }
};

subtest 'a bare Inf / NaN spelling is the same leaf' => sub {
    for my $source (@SPELLINGS) {
        my $leaf = yaml_leaf($source);
        is(leaf_type($leaf), 'str', "[$source] typed str");
        is(leaf_bytes($leaf), $source, "[$source] digested verbatim");
    }
};

###############################################################################
# 2. THE DISJOINTNESS, WHICH IS WHAT MAKES ADR 0023'S WALK SAFE. Its predicate
#    reads SVf_NOK, and every token Go resolves to a non-finite float arrives

t/39-yaml-overflow-literal-becomes-a-string.t  view on Meta::CPAN

    for my $source ('5e-324', '1e308', '1.7976931348623157e308',
        '17976931348623158079372897140530341507993413271003782693617377898044'
      . '49682927647509466490179775872070963302864166928879109465555478519404'
      . '02630657488671505820681908902000708383676273854845817711531764475730'
      . '27006985557136695962284291481986083493647529271907416844436551070434'
      . '2711559699508093042880177904174497791') {
        my $short = length($source) > 24 ? substr($source, 0, 21) . '...' : $source;
        my $leaf  = yaml_leaf($source);
        is(leaf_type($leaf), 'float', "[$short] a finite double, still a float");
        my $bytes = leaf_bytes($leaf);
        unlike($bytes, qr/\A[-+]?(?:Inf|NaN)\z/, "[$short] and not a non-finite one");
        like($bytes, qr/\A[0-9.]+\z/, "[$short] digested positionally as its double");
        isnt($bytes, $source, "[$short] canonicalised, not written as its source text");
    }
};

subtest 'a quoted literal was already a string and stays one' => sub {
    my $leaf = yaml_leaf(q{"1e400"});
    is(leaf_type($leaf), 'str', 'a quoted 1e400 is a str');
    is(leaf_bytes($leaf), '1e400', 'digested as its text');
};

t/39-yaml-overflow-literal-becomes-a-string.t  view on Meta::CPAN

#    what this section is really pinning is that the two answers are about
#    the SLOT and not about this walk.
###############################################################################

subtest 'a real non-finite float is written in YAML, as both slots it can reach'
    => sub {
    my $inf = 9**9**9;
    my @values = (
        [ '+Inf', $inf,        '.inf'  ],
        [ '-Inf', -$inf,       '-.inf' ],
        [ 'NaN',  $inf - $inf, '.nan'  ],
    );

    for my $case (@values) {
        my ($name, $value, $token) = @$case;

        # Unencrypted slot, YAML: the carrier writes the token. This USED to
        # refuse with the k59 message; k141 / docs/adr/0062 removed
        # the refusal because the YAML carrier spells the same token the
        # digest covers.
        my $unencrypted = File::SOPS->encrypt(

t/39-yaml-overflow-literal-becomes-a-string.t  view on Meta::CPAN

        my $got = eval { File::SOPS->decrypt(
            encrypted => read_binary("$tempdir/inf.yaml"),
            identities => [$secret]) };
        ok(defined $got, 'and this module reads it') or diag($@);

        my $inf = 9**9**9;
        is(unpack('H*', pack('d', $got->{pos})), unpack('H*', pack('d', $inf)),
            'the positive infinity comes back as the same double');
        is(unpack('H*', pack('d', $got->{neg})), unpack('H*', pack('d', -$inf)),
            'and the negative one');
        ok($got->{nn} != $got->{nn}, 'and the NaN is still a NaN');
    };
}

done_testing();

t/42-yaml-plain-infinity-is-a-float.t  view on Meta::CPAN


my $sops_bin = find_sops_bin();
diag("Using sops binary: $sops_bin") if $sops_bin;

# The twelve tokens go-yaml resolves to a non-finite float, and the bytes sops
# digests for each. Read out of twelve real `mac:` fields, not modelled.
my %GO_RESOLVES = (
    '.inf'  => '+Inf',  '.Inf'  => '+Inf',  '.INF'  => '+Inf',
    '+.inf' => '+Inf',  '+.Inf' => '+Inf',  '+.INF' => '+Inf',
    '-.inf' => '-Inf',  '-.Inf' => '-Inf',  '-.INF' => '-Inf',
    '.nan'  => 'NaN',   '.NaN'  => 'NaN',   '.NAN'  => 'NaN',
);

# Spellings one keystroke away from the twelve. Every one of them is a
# `type:str` to sops, digested verbatim, and read correctly here today --
# measured, twelve documents, twelve `sops -d` exit 0. They are what a repair
# drawn one row too wide would break.
my @NEAR_MISSES = qw(
    .INf .iNF .Nan .NAn +.nan -.nan -.NAN .infinity .Infinity Inf inf NaN
);

# A leaf out of a document shaped like an ENCRYPTED one: it has a sops section,
# so a foreign reader has already digested its unencrypted slots.
sub wire_leaf {
    my ($source) = @_;
    my ($data) = File::SOPS::Format::YAML->parse(
        "v: $source\nsops:\n    version: 3.7.3\n");
    return $data->{v};
}

t/42-yaml-plain-infinity-is-a-float.t  view on Meta::CPAN

            "[$token] and its text is still the document's own token");
    }
};

subtest 'the numeric half is the double go-yaml resolved' => sub {
    my $inf = 9**9**9;
    is(unpack('H*', pack('d', wire_leaf('.inf'))), unpack('H*', pack('d', $inf)),
        'a positive infinity, bit for bit');
    is(unpack('H*', pack('d', wire_leaf('-.INF'))), unpack('H*', pack('d', -$inf)),
        'a negative one');
    my $nan = wire_leaf('.NaN');
    ok($nan != $nan, 'and a NaN that is a NaN');
};

###############################################################################
# 2. WHAT MUST NOT MOVE. A quoted token is a STRING to sops, digested verbatim,
#    and YAML::XS hands back the same POK-only scalar for both spellings -- so
#    a repair keyed on the leaf's TEXT passes section 1 and breaks every row
#    here. This is the reason the walk asks YAML::PP about the document.
###############################################################################

subtest 'a quoted token stays the string both implementations read' => sub {

t/42-yaml-plain-infinity-is-a-float.t  view on Meta::CPAN

    }
};

###############################################################################
# 4. ADR 0023 STILL OWNS ITS OWN LEAVES. Its walk turns a literal libyaml
#    numified past the end of a double back into a string; this one turns a
#    string into a float. They run over the same tree and must not fight.
###############################################################################

subtest 'an overflowing literal is still the string ADR 0023 made it' => sub {
    for my $source ('1e400', '1e309', 'Inf', 'NaN', '-Inf') {
        my $leaf = wire_leaf($source);
        is(leaf_type($leaf), 'str', "[$source] still a str");
        is(leaf_bytes($leaf), $source, "[$source] still digested as the literal");
    }
};

subtest 'a finite number is still the number it was' => sub {
    my @rows = (
        [ '0',    'int',   '0'    ],
        [ '007',  'int',   '7'    ],

t/42-yaml-plain-infinity-is-a-float.t  view on Meta::CPAN

#    file is where the scalar comes from.
###############################################################################

subtest 'a caller-supplied non-finite float whose PV contradicts its number is refused' => sub {
    my $inf = 9**9**9;
    my @rows = (
        [ '+Inf with "banana"' => dualvar($inf,  'banana')  ],
        [ '+Inf with ".INf"'   => dualvar($inf,  '.INf')    ],
        [ '+Inf with "-.inf"'  => dualvar($inf,  '-.inf')   ],
        [ '-Inf with ".inf"'   => dualvar(-$inf, '.inf')    ],
        [ 'NaN with ".inf"'    => dualvar($inf - $inf, '.inf') ],
    );

    for my $row (@rows) {
        my ($name, $leaf) = @$row;
        my $ok = eval {
            File::SOPS::Encrypted->assert_representable($leaf); 1
        };
        ok(!$ok, "[$name] assert_representable refuses it");
        like($@, qr/non-finite float/, "[$name] and says why") if !$ok;
    }

t/42-yaml-plain-infinity-is-a-float.t  view on Meta::CPAN

        unless $sops_bin;

    my $tempdir = tempdir(CLEANUP => 1);
    my ($public, $secret) = Crypt::Age->generate_keypair();
    my $keyfile = "$tempdir/age.key";
    write_binary($keyfile, "$secret\n");
    local $ENV{SOPS_AGE_KEY_FILE} = $keyfile;

    # The three spellings a sops-written document can actually hold: measured,
    # `sops -e` normalises .Inf .INF +.inf +.Inf +.INF to `.inf`, -.Inf -.INF to
    # `-.inf`, and .NaN .NAN to `.nan`, exactly as it resolves `0755` to 493.
    my %WRITTEN = ('.inf' => '+Inf', '-.inf' => '-Inf', '.nan' => 'NaN');

    subtest 'sops -e writes only three of the twelve spellings' => sub {
        for my $token (sort keys %GO_RESOLVES) {
            write_binary("$tempdir/p.yaml", "keep: x\nv_unencrypted: $token\n");
            my $out = `$sops_bin -e --age $public --input-type yaml --output-type yaml $tempdir/p.yaml 2>&1`;
            is($? >> 8, 0, "[$token] sops -e accepts it") or diag($out);
            my ($wire) = $out =~ /^v_unencrypted: (.*)$/m;
            $wire = '' unless defined $wire;
            my $expected = $GO_RESOLVES{$token} eq '+Inf' ? '.inf'
                         : $GO_RESOLVES{$token} eq '-Inf' ? '-.inf'

t/46-non-finite-token-is-written.t  view on Meta::CPAN

use File::SOPS::Format::JSON;
use Crypt::Age;
use lib 't/lib';
use SopsBin qw(find_sops_bin);

# ----------------------------------------------------------------------------
# k113 / docs/adr/0031: a non-finite float that carries go-yaml's own
# token is written, where every non-finite float used to be refused.
#
# k59's guard refuses a non-finite float on the encrypt path because no
# emitter derives `+Inf` / `-Inf` / `NaN` -- the text the MAC digest covers --
# from the NUMBER. That is true of a bare NV. It stopped being true when
# ADR 0026 taught the YAML parse to hand back dualvar($double, $token) for a
# document sops wrote: measured against sops 3.13.3, the twelve tokens in an
# unencrypted YAML slot are `sops -d` exit 0, and the round trip
#
#     sops -e  ->  File::SOPS->rotate  ->  sops -d
#
# closes at exit 0 with the wire byte-identical. Before this change rotate
# croaked in the middle: the library could READ a document it could not WRITE.
#

t/46-non-finite-token-is-written.t  view on Meta::CPAN

my $INF = 9**9**9;
my $NAN = $INF - $INF;

# The twelve tokens go-yaml resolves to a non-finite float, and the double each
# one resolves to. Same table t/42 carries, for the same reason: it was read
# out of twelve real `mac:` fields rather than modelled.
my %GO_RESOLVES = (
    '.inf'  => '+Inf',  '.Inf'  => '+Inf',  '.INF'  => '+Inf',
    '+.inf' => '+Inf',  '+.Inf' => '+Inf',  '+.INF' => '+Inf',
    '-.inf' => '-Inf',  '-.Inf' => '-Inf',  '-.INF' => '-Inf',
    '.nan'  => 'NaN',   '.NaN'  => 'NaN',   '.NAN'  => 'NaN',
);

sub double_for {
    my ($bytes) = @_;
    return $bytes eq '+Inf' ? $INF : $bytes eq '-Inf' ? -$INF : $NAN;
}

# The leaf ADR 0026's parse produces for a plain token in a sops-written
# document: the double go-yaml resolved, carrying the document's own spelling.
sub token_leaf {

t/46-non-finite-token-is-written.t  view on Meta::CPAN

# 2. THE CONTRADICTION. Both halves have to agree -- the same answer ADR 0012
#    gives an integer whose halves disagree, and for the same reason: which
#    half is meant cannot be read off the scalar. Measured, every one of these
#    in an unencrypted YAML slot is `sops -d` exit 51.
###############################################################################

subtest 'a float whose token says a different double is refused' => sub {
    my @contradiction = (
        [ 'dualvar(+Inf, -.inf)' => dualvar($INF,  '-.inf') ],
        [ 'dualvar(-Inf, .inf)'  => dualvar(-$INF, '.inf')  ],
        [ 'dualvar(NaN, .inf)'   => dualvar($NAN,  '.inf')  ],
        [ 'dualvar(+Inf, .nan)'  => dualvar($INF,  '.nan')  ],
    );
    for my $case (@contradiction) {
        my ($name, $leaf) = @$case;
        my $err = refuses($leaf);
        ok(defined $err, "$name is refused");
        like($err, qr/non-finite float/, "$name says why");
    }
};

subtest 'a spelling go-yaml does not resolve is refused' => sub {
    # Every one of these is a `type:str` to sops, digested verbatim. As the
    # STRING HALF of a float they are a document that fails its own MAC, and
    # `banana` is the one that decides how tight this gate has to be: ADR 0013's
    # guard never looks at a token starting with `b`, so nothing downstream
    # would catch it.
    for my $token (qw( .INf .iNF .Nan +.nan -.nan .infinity Inf NaN banana ), '') {
        my $err = refuses(dualvar($INF, $token));
        ok(defined $err, "[$token] refused");
    }
};

###############################################################################
# 3. THE BARE VALUE, SPLIT. A bare non-finite float used to be refused here
#    in both formats -- that is what k59 was written for, measured, `Inf`
#    in an unencrypted YAML slot is sops -d exit 51, and `-Inf` / `NaN` are
#    exit 0 with the leaf silently retyped from a float to a string, which
#    is worse. k141 / docs/adr/0062 removed the assert_representable
#    refusal for the BARE case in the unencrypted slot: docs/adr/0037's
#    YAML carrier manufactures the carrying dualvar, and the leaf now
#    reaches the document as `.inf` / `-.inf` / `.nan`. JSON has no such
#    carrier, and the refusal there moves to the emit walk's mac_covered
#    croak -- which is what section 5 keeps and this section 3 splits.
#
#    What stays refused at this layer is a bare NV whose public PV has been
#    forced -- `"$printed"` sets the private POK, but the public one is what
#    the gate reads, so a caller who logged the value has not promised
#    anything about the wire.
###############################################################################

subtest 'a bare non-finite float is still refused, in the format where it must be'
    => sub {
    for my $case ([ '+Inf' => $INF ], [ '-Inf' => -$INF ], [ 'NaN' => $NAN ]) {
        my ($name, $value) = @$case;
        my $err = refuses($value);
        ok(!defined $err, "bare $name is no longer refused by assert_representable")
            or diag($err);
    }

    # A float that was merely PRINTED is still bare: Perl sets the private
    # SVf_POK for that and the gate reads the public one, so a caller who
    # logged the value has not promised anything about the wire.
    my $printed = $INF;

t/46-non-finite-token-is-written.t  view on Meta::CPAN

                diag($@); next };
            like($document, qr/type:float/,
                "[$format/$token] as type:float");
        }
    }
};

subtest 'encrypt_value writes it directly, and the token is not on the wire'
    => sub {
    my $key = "\0" x 32;
    my %expected = ('.inf' => '+Inf', '-.inf' => '-Inf', '.nan' => 'NaN');

    for my $token ('.inf', '-.inf', '.nan') {
        my $enc = eval {
            File::SOPS::Encrypted->encrypt_value(
                value => token_leaf($token), key => $key, aad => 'v:');
        };
        ok($enc, "[$token] encrypt_value writes it") or do { diag($@); next };
        is($enc->type, 'float', "[$token] as type:float");
        is($enc->decrypt_bytes(key => $key, aad => 'v:'), $expected{$token},
            "[$token] with the plaintext derived from the NUMBER");

t/46-non-finite-token-is-written.t  view on Meta::CPAN

        unless $sops_bin;

    my $tempdir = tempdir(CLEANUP => 1);
    my ($public, $secret) = Crypt::Age->generate_keypair();
    my $keyfile = "$tempdir/age.key";
    write_binary($keyfile, "$secret\n");
    local $ENV{SOPS_AGE_KEY_FILE} = $keyfile;

    # The three spellings a sops-written document can hold: `sops -e`
    # normalises the other nine away, exactly as it resolves `0755` to 493.
    my %WRITTEN = ('.inf' => '+Inf', '-.inf' => '-Inf', '.nan' => 'NaN');

    subtest 'sops -e, File::SOPS->rotate, sops -d' => sub {
        for my $token (sort keys %WRITTEN) {
            write_binary("$tempdir/p.yaml", "keep: x\nv_unencrypted: $token\n");
            my $enc = `$sops_bin -e --age $public --input-type yaml --output-type yaml $tempdir/p.yaml 2>&1`;
            is($? >> 8, 0, "[$token] sops -e") or diag($enc);
            write_binary("$tempdir/e.yaml", $enc);

            my $ok = eval {
                File::SOPS->rotate(file => "$tempdir/e.yaml",

t/49-plain-infinity-survives-the-plaintext-round-trip.t  view on Meta::CPAN

my $tempdir = tempdir(CLEANUP => 1);
my ($public, $secret) = Crypt::Age->generate_keypair();

# The twelve tokens go-yaml resolves to a non-finite float, and the bytes sops
# digests for each. Same table t/42 and t/46 carry, read out of twelve real
# `mac:` fields rather than modelled.
my %GO_RESOLVES = (
    '.inf'  => '+Inf',  '.Inf'  => '+Inf',  '.INF'  => '+Inf',
    '+.inf' => '+Inf',  '+.Inf' => '+Inf',  '+.INF' => '+Inf',
    '-.inf' => '-Inf',  '-.Inf' => '-Inf',  '-.INF' => '-Inf',
    '.nan'  => 'NaN',   '.NaN'  => 'NaN',   '.NAN'  => 'NaN',
);

# The three a sops-written document can actually hold: `sops -e` normalises the
# other nine away, the same way it resolves `0755` to 493.
my %SOPS_WRITES = ('.inf' => '+Inf', '-.inf' => '-Inf', '.nan' => 'NaN');

my $serial = 0;
sub scratch {
    my $sub = "$tempdir/case-" . ++$serial;
    mkdir $sub or die "mkdir $sub: $!";
    return $sub;
}

# A non-interactive $EDITOR: a perl script that applies ONE substitution to the
# file it is handed and dies if the pattern is not there, so a test whose

t/49-plain-infinity-survives-the-plaintext-round-trip.t  view on Meta::CPAN

    my $list = $data->{list_unencrypted};
    is(type_of($list->[0]), 'float', 'the plain one is the float');
    is(bytes_of($list->[0]), '+Inf', 'digested +Inf');
    is(type_of($list->[1]), 'str',  'the quoted one beside it is a string');
    is(bytes_of($list->[1]), '.inf', 'digested as its own text');
    is(bytes_of($list->[2]), 'one',  'and the neighbour is untouched');
};

subtest 'a spelling one keystroke off the twelve is untouched' => sub {
    for my $near (qw( .INf .iNF .Nan .NAn +.nan -.nan -.NAN .infinity
                      .Infinity Inf inf NaN )) {
        my $leaf = leaf_of("v_unencrypted: $near\n");
        is(type_of($leaf), 'str', "[$near] still a string");
        is(bytes_of($leaf), $near, "[$near] digested verbatim");
    }
};

subtest 'a leaf that merely contains the bytes is untouched' => sub {
    for my $value (qw( config.info .infrastructure sub.nan x.inf )) {
        my $leaf = leaf_of("v_unencrypted: $value\n");
        is(type_of($leaf), 'str', "[$value] still a string");
        is(bytes_of($leaf), $value, "[$value] digested verbatim");
    }
};

subtest 'ADR 0023 still owns its own leaves in a plaintext' => sub {
    for my $source (qw( 1e400 1e309 Inf NaN -Inf )) {
        my $leaf = leaf_of("v_unencrypted: $source\n");
        is(type_of($leaf), 'str', "[$source] still a string");
        is(bytes_of($leaf), $source, "[$source] still digested as the literal");
    }
};

subtest 'a finite number in a plaintext is the number it was' => sub {
    my @rows = (
        [ '0',    'int',   '0'    ],
        [ '007',  'int',   '7'    ],

t/49-plain-infinity-survives-the-plaintext-round-trip.t  view on Meta::CPAN

                "[$token] with the value intact");
        }
    };

    # go-yaml's own EMITTER normalises a non-finite float to one of three
    # spellings, which is why a sops-written document only ever holds those
    # three -- so `sops -d` prints `.inf` for a document whose wire says
    # `+.INF`. Our wire keeps the document's spelling (ADR 0026's dualvar
    # carries the token it read); sops's re-emission of it does not, and both
    # halves are asserted separately rather than confused for one another.
    my %NORMALISED = ('+Inf' => '.inf', '-Inf' => '-.inf', 'NaN' => '.nan');

    subtest 'all twelve spellings encrypt from a plaintext and sops reads them' => sub {
        for my $token (sort keys %GO_RESOLVES) {
            my $dir = scratch();
            write_binary("$dir/p.yaml", "keep: x\nv_unencrypted: $token\n");

            my $ok = eval {
                File::SOPS->encrypt_file(input      => "$dir/p.yaml",
                                         output     => "$dir/e.yaml",
                                         recipients => [$public]);

t/52-non-finite-float-survives-the-encrypted-round-trip.t  view on Meta::CPAN

#   sops -e             -> type:float, plaintext +Inf
#   sops -d             -> secret: .inf
#   File::SOPS->decrypt_file -> secret: Inf        <- a STRING to go-yaml
#   File::SOPS->edit of an UNRELATED key
#                       -> returns 1, no warning, wire becomes type:str
#   sops edit, same document, same editor
#                       -> exit 0, wire unchanged, still type:float
#
# The loss is at the EMIT: an encrypted type:float decrypts to a bare Perl
# infinity, whose only form is its number, and YAML::XS writes such a scalar as
# `Inf` / `-Inf` / `NaN` -- tokens go-yaml resolves as strings, and correctly
# so, which is why ADR 0026's repair cannot reach them and must not learn to.
#
# JSON was not the same defect but a worse one: the leaf reached the plaintext
# as `null`, and `edit` replaced the whole ENC[...] with a bare, UNENCRYPTED
# null -- where sops refuses the same document outright (`sops -d
# --output-type json` and `sops edit` are both exit 4).
#
# The fix asks the handler's own `carrier` for the token and verifies the
# answer with ADR 0031's gate. What this file also PINS is the half that must
# NOT move: a non-finite float that carries a string half of its own keeps it,

t/52-non-finite-float-survives-the-encrypted-round-trip.t  view on Meta::CPAN

my $NAN = $INF - $INF;

# The three non-finite doubles, the bytes value_to_bytes covers for each, and
# the one spelling per value `sops -e` itself writes. Read out of three real
# `sops -d` outputs rather than modelled; the other nine of ADR 0026's twelve
# tokens are spellings sops normalises away and cannot appear in a document it
# wrote.
my @NON_FINITE = (
    { name => '+Inf', double => $INF,  bytes => '+Inf', token => '.inf'  },
    { name => '-Inf', double => -$INF, bytes => '-Inf', token => '-.inf' },
    { name => 'NaN',  double => $NAN,  bytes => 'NaN',  token => '.nan'  },
);

my $serial = 0;
sub scratch {
    my $sub = "$tempdir/case-" . ++$serial;
    mkdir $sub or die "mkdir $sub: $!";
    return $sub;
}

# A non-interactive $EDITOR: applies ONE substitution and dies if the pattern is

t/52-non-finite-float-survives-the-encrypted-round-trip.t  view on Meta::CPAN

#    named in it.
###############################################################################

subtest 'a contradicting string half is now refused on the plaintext path' => sub {
    for my $case (
        [ 'banana'        => $INF,  'banana'    ],
        [ '.INf'          => $INF,  '.INf'      ],
        [ '.infinity'     => $INF,  '.infinity' ],
        [ '-.inf on +Inf' => $INF,  '-.inf'     ],
        [ '.inf on -Inf'  => -$INF, '.inf'      ],
        [ '.inf on NaN'   => $NAN,  '.inf'      ],
    ) {
        my ($name, $double, $pv) = @$case;
        my $err = error_from(sub {
            File::SOPS::Format::YAML->emit({ v => dualvar($double, $pv) });
        });
        ok($err, "[$name] YAML refuses it");
        like($err, qr/non-finite float/,
            "[$name] with the k59 message");

        my $jerr = error_from(sub {

t/52-non-finite-float-survives-the-encrypted-round-trip.t  view on Meta::CPAN

#    emit walk's mac_covered croak). The contradiction rows are unchanged:
#    a leaf with a string half still has to agree with its number.
###############################################################################

subtest 'the encrypt path answers exactly as it did' => sub {
    # [name, value, yaml_ok, expected_token] -- yaml_ok is the only column
    # that moved: a bare NV is now written in YAML (carrier manufactures
    # the token) and still refused in JSON.
    my @rows = (
        [ 'bare +Inf'              => $INF,                   1, '.inf'  ],
        [ 'bare NaN'               => $NAN,                   1, '.nan'  ],
        [ 'dualvar(+Inf, banana)'  => dualvar($INF, 'banana'), 0, undef   ],
        [ 'dualvar(+Inf, .INf)'    => dualvar($INF, '.INf'),  0, undef   ],
        [ 'dualvar(+Inf, -.inf)'   => dualvar($INF, '-.inf'), 0, undef   ],
        [ 'dualvar(-Inf, .inf)'    => dualvar(-$INF, '.inf'), 0, undef   ],
        [ 'dualvar(+Inf, .inf)'    => dualvar($INF, '.inf'),  1, '.inf'  ],
    );

    for my $row (@rows) {
        my ($name, $value, $yaml_ok, $token) = @$row;

t/53-a-string-leaf-sops-quotes-is-refused-and-says-why.t  view on Meta::CPAN


my $serial = 0;
sub scratch_file {
    my ($ext) = @_;
    return "$tempdir/f" . ++$serial . ".$ext";
}

# The 22 spellings measured in docs/adr/0038: a string on both sides, written
# double-quoted by sops, read back by sops at exit 0, refused here.
my @STRING_ROWS = (
    '.inf', '.Inf', '.INF', '+.inf', '-.inf', '.nan', '.NaN',
    '1_000', '0_7', '685_230.15',
    '2015-01-01', '2015-1-2', '2015-01-01t12:00:00Z', '2015-01-01 12:00:00',
    '0o10', '0O10', '0x1f', '0b101',
    'Null', 'NULL', 'TRUE', 'FALSE',
);

# docs/adr/0070: the seven parse-unambiguous non-finite spellings (the first
# seven of @STRING_ROWS) moved OUT of the refused set -- the emitter now
# quotes them, because a str leaf spelled this way can only have come from a
# quoted source or a caller's own Perl string (docs/adr/0026, 0034). The other
# fifteen -- a bare and a quoted source arrive as the same Perl string -- stay
# refused exactly as ADR 0039 measured them.
my @NOW_QUOTED = ('.inf', '.Inf', '.INF', '+.inf', '-.inf', '.nan', '.NaN');
my %now_quoted = map { $_ => 1 } @NOW_QUOTED;
my @STILL_REFUSED_ROWS = grep { !$now_quoted{$_} } @STRING_ROWS;

# A leaf exactly as a YAML parse hands it over -- for `0755` that is an INT
# carrying its source spelling, which is the leaf the unchanged half of the
# message is for.
sub yaml_leaf {
    my ($source) = @_;
    local $YAML::XS::Boolean = 'JSON::PP';
    return Load("v: $source\n")->{v};

t/53-a-string-leaf-sops-quotes-is-refused-and-says-why.t  view on Meta::CPAN

    }

    my @same = sort grep { !$distinguishable{$_} } keys %distinguishable;
    my @differ = sort grep { $distinguishable{$_} } keys %distinguishable;

    is(scalar @same, 15,
        '15 of the 22 arrive identically from a bare and a quoted source');
    is(scalar @differ, 7,
        'and 7 do not -- docs/adr/0026 and docs/adr/0034 resolve those at parse');
    is_deeply(\@differ,
        [ sort ('.inf', '.Inf', '.INF', '+.inf', '-.inf', '.nan', '.NaN') ],
        'the seven are the non-finite tokens, and nothing else');

    # the four the date trap is named for
    ok(!$distinguishable{$_}, "[$_] a date is not distinguishable")
        for ('2015-01-01', '2015-1-2', '2015-01-01t12:00:00Z',
             '2015-01-01 12:00:00');

    # and what sops writes for a BARE source, which is what quoting would
    # silently overwrite
    my %bare_output = (

t/54-an-encrypted-non-finite-float-is-written.t  view on Meta::CPAN

my ($public, $secret) = Crypt::Age->generate_keypair();

my $INF = 9**9**9;
my $NAN = $INF - $INF;

# The three non-finite doubles, the bytes value_to_bytes covers for each, and
# the one spelling per value `sops -e` itself writes.
my @NON_FINITE = (
    { name => '+Inf', double => $INF,  bytes => '+Inf', token => '.inf'  },
    { name => '-Inf', double => -$INF, bytes => '-Inf', token => '-.inf' },
    { name => 'NaN',  double => $NAN,  bytes => 'NaN',  token => '.nan'  },
);

# ADR 0026's twelve, which is k114's corpus.
my @TOKENS = qw( .inf .Inf .INF +.inf +.Inf +.INF -.inf -.Inf -.INF
                 .nan .NaN .NAN );

my $serial = 0;
sub scratch {
    my $sub = "$tempdir/case-" . ++$serial;
    mkdir $sub or die "mkdir $sub: $!";
    return $sub;
}

sub error_from {
    my ($code) = @_;

t/54-an-encrypted-non-finite-float-is-written.t  view on Meta::CPAN

#    the wrong way: seven leaves x two formats, and the bare-NV row is the
#    only cell that now writes in YAML.
###############################################################################

subtest 'the unencrypted slot answers exactly as it did, except for the bare NV' => sub {
    # [name, value, yaml_ok, expected_token] -- the third column moved for
    # the bare-NV rows: a bare NV is now written in YAML (the carrier's
    # token) and still refused in JSON. The contradicting rows are unchanged.
    my @rows = (
        [ 'bare +Inf'              => $INF,                   1, '.inf'  ],
        [ 'bare NaN'               => $NAN,                   1, '.nan'  ],
        [ 'dualvar(+Inf, banana)'  => dualvar($INF, 'banana'), 0, undef   ],
        [ 'dualvar(+Inf, .INf)'    => dualvar($INF, '.INf'),  0, undef   ],
        [ 'dualvar(+Inf, -.inf)'   => dualvar($INF, '-.inf'), 0, undef   ],
        [ 'dualvar(-Inf, .inf)'    => dualvar(-$INF, '.inf'), 0, undef   ],
        [ 'dualvar(+Inf, .inf)'    => dualvar($INF, '.inf'),  1, '.inf'  ],
    );

    for my $row (@rows) {
        my ($name, $value, $yaml_ok, $token) = @$row;



( run in 3.828 seconds using v1.01-cache-2.11-cpan-60884a8df76 )