permittable 0.13.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +43 -0
- data/README.md +34 -11
- data/lib/permittable/audit.rb +64 -7
- data/lib/permittable/authored_values.rb +23 -11
- data/lib/permittable/column_guard.rb +133 -12
- data/lib/permittable/contract.rb +4 -1
- data/lib/permittable/error_envelope.rb +21 -4
- data/lib/permittable/json_schema.rb +9 -3
- data/lib/permittable/open_api.rb +213 -11
- data/lib/permittable/rspec.rb +193 -12
- data/lib/permittable/tasks/audit.rake +3 -2
- data/lib/permittable/version.rb +1 -1
- data/lib/permittable.rb +349 -24
- metadata +2 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 7e1419e11eb73f0b94274aa8f6a868e81913f64a754bfecde44885e83a825942
|
|
4
|
+
data.tar.gz: 74a084502a3328e692fd522c719d16e8242fb2a12a9602e3da76c3e6076be426
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: de34efb031486908abdf6b26293108f83505dac300ce9a1977b88439c5677d058950a567bd79ead0aefe6f03605d7d312eede2215844393855beb098c99d2819
|
|
7
|
+
data.tar.gz: 95420ccea0d5842aaea3877ed3343ab444c7bc9a505efdad76b1b0b23fae1ab7bb636ba367cb9e4ad69151ae35e9a2491c05d6746d6cd31b87bb41cb5744c1be
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
<!-- CHANGELOG.md -->
|
|
2
2
|
|
|
3
|
+
## 0.15.0 (2026-11-12)
|
|
4
|
+
<!-- title: zone names and hours that Date._parse drops honoured or refused, an export that matches what the server stores, an audit that stops reporting rules that cannot run, matchers that redact what they print, and a column guard that knows aliases and store accessors -->
|
|
5
|
+
|
|
6
|
+
Five changes to what a string, an export, an audit, a matcher or a model is held to, and one to what a model may declare. A `:date` or `:datetime` string that carries a zone name, an hour or an offset that `Date._parse` reads only in some positions is read as the instant it names, or refused, where the part was dropped (#174). The export refuses a non-finite `BigDecimal` and a sub-nanosecond `Time` in an authored `:json` value, publishes a `:date` member as `YYYY-MM-DD` (#175), and lists Rails' form keys in a rootless `unknown: :error` JSON body (#178). `permittable:audit` reports a bare `ActionController::Metal` rule that cannot run as uncovered, and lists the controllers a route names that nothing has loaded (#176). The matchers read a Symbol value as the String a request carries and redact sensitive values from failure messages (#177). A model's `alias_attribute` and `store_accessor` fields are checked against the column that backs them, where 0.14.0 refused them at class load (#178).
|
|
7
|
+
|
|
8
|
+
Minor rather than patch: each entry can make a request, a boot, a spec, an audit or an export that passes today fail, or read differently. Before upgrading, read the entries that match what you use. A request can now be refused: an ISO date followed by `T` and no hour (`"2026-09-05T10"`, `"2026-09-05T1030"`, `"2026-09-05T10Z"`), any unknown word after a complete date (`"2026-09-05 foo"`), an initial-led zone name Ruby does not know (`"W. Europe"`), an hour or offset the parser misplaces (`"2026-09-05 10 EST"`, `"2026-09-05 10 -05:00"`), an offset after the year in a form other than git's or `ctime`'s, and a zone name with an offset after the year (`"Sat Sep 5 10:00:00 2026 UTC+0000"`), all as `invalid_type`, and a `:date` string with a zone name that does not name midnight UTC (`"2026-09-05 EST"`) (#174). A boot can now fail: an authored `default:` or `example:` on a `:json` field that holds a non-finite `BigDecimal` or a `Time` or `DateTime` finer than a nanosecond, at any depth (#175), and an `in:`, `default:` or `example:` written as a time-carrying `:date` string that is not exactly midnight UTC (#174). Nothing that loaded on 0.14.0 newly fails because of #178: on 0.14.0 an alias or store accessor field was refused at class load as a missing column, so its checks reject nothing that loaded. An action can now receive something different: a `:datetime` such as `"2026-09-05 EST"` is `05:00Z` where it was `00:00Z`, and `"Sat Sep 5 10:00:00 2026 EST"` or `"... -0500"` is `15:00Z` where it was `10:00Z` (#174), and `nil` for an omitted nullable `:json` field with `default: ""` (#175). An export now reads differently: a `:date` `in:` member written as a String prints as `YYYY-MM-DD` (#175), and a rootless `unknown: :error` JSON body lists `authenticity_token`, `_method`, `utf8`, `commit` and `button` as free optional properties (#178). An audit can now fail: a gate on uncovered actions fails for a bare Metal controller rule that cannot run, which was covered, and for a routed controller that the audit now loads, whose file now runs and whose load error now raises (#176). And a spec can fail where it passed: a controller matcher given a Symbol value that asserted a rejection now sees an acceptance, a `:json` field's Symbol values come back as Strings in a matcher's returned hash (#177), and a `returning` message that showed a sensitive value now shows the placeholder (#177).
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **`permittable:audit` lists the controllers a route names that nothing has loaded.** The audit collected controllers from `ActionController::Metal.descendants`, which holds only loaded classes, so `Rails::HealthController` behind `GET /up` had no row. `Audit.rails_controllers(routes)` now adds every controller a route names, constantized; a missing constant, or one that is not an `ActionController::Metal` class, is skipped. A controller from a gem is still ignored by default, and its row shows the ignore reason. Running the audit loads those controllers, so a controller with an import-time side effect runs it, and an error raised inside a controller's file is now raised, not rescued as a `NameError`. (#176)
|
|
12
|
+
- **The matchers print a hash with its sensitive values redacted, and say where it differs.** A `returning` mismatch printed the whole returned hash with `inspect`, and a `returning` expectation as written, so a CI log carried `sensitive:` values and the values in `config.filter_parameters`. Both now print the registry's placeholder, by the names from `sensitive:` (matched by substring, like Rails) and, under a booted Rails app, `config.filter_parameters`; under a `root:` contract a scoped filter such as `"payment.number"` applies, and an `ActionController::Parameters` is unwrapped first. When redaction hides a `returning` mismatch the message adds `differs at: <path>`, naming only paths. Matching still compares the real values, and a pass or fail is unchanged. (#177)
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
- **A `:date` or `:datetime` string reads or refuses the zone, offset or hour `Date._parse` drops.** `Date._parse` reports a zone only beside a time of day, so a zone name after a bare date, an hour after an ISO `T` and an offset after the year (git and `ctime` format) were dropped or misplaced, and the value came from the date alone. A zone name Ruby knows is applied (`"2026-09-05 EST"` is `05:00Z` as a `:datetime`, not `00:00Z`; `"Sat Sep 5 10:00:00 2026 EST"` and `"... -0500"` are `15:00Z`, not `10:00Z`; `"20260905 10 EST"` is `15:00Z`), and an offset after the year of git's and `ctime`'s format is read the same way. These are refused as `invalid_type`: an ISO `T` with no hour, any unknown word after a complete date, an initial-led zone name Ruby does not know (`"W. Europe"`, `"S. Africa Standard Time"`), an hour or offset the parser misplaces, and an offset after the year in any other form. Dotted eras (`A.D.`, `B.C.`) are skipped like `AD` and `BC`, and a single letter is never a zone. A `:date` string that carries a time or zone is still accepted only at exactly midnight UTC, so a `:date` zone name that moves the instant, `EST` included, is now refused, and the same rule fails an `in:`, `default:` or `example:` member at class load. The value is a plain `Date` built from its year, month and day. Date-only strings, `Date`, `Time`, `DateTime`, `TimeWithZone` and a zone name that names midnight UTC are unchanged. Still read as before: `"2026-09-05 10 A.D."`, `"2026-09-05 10 A."` and `"2026-09-05 GMT+5"` drop the hour or offset. (#174)
|
|
16
|
+
- **An authored `:json` value that the export cannot carry fails at class load, and a `:date` member is published as a date.** The check from #163 covered only `Float`. A `default:` or `example:` for a `:json` field that holds a non-finite `BigDecimal` (`NaN`, `Infinity`, `-Infinity`) or a `Time` or `DateTime` finer than a nanosecond, at any depth, raises `ArgumentError` naming the field and the path (`a.b[1].c`), with the hint to round a `Time` with `.round(9)`; 0.14.0 loaded the class and exported the `BigDecimal` as a String and the `Time` as a different instant. A `:date` `in:` member written as a String is exported as `YYYY-MM-DD`, so `in: ["Sep 5, 2026", Date.new(2026, 9, 6)]` is `["2026-09-05", "2026-09-06"]`, where the first value failed the field's own `format: date`; a member past year 9999 is published in a spelling the server reads back as the same `Date`. A `:datetime` String member is still published as written. The runtime cast of a request is unchanged. (#175)
|
|
17
|
+
- **A blank default on a nullable `:json` field reads as `nil`.** `optional :prefs, :json, nullable: true, default: ""` failed at class load with "must be a Hash", while a request that sends `""` for the field reads as `nil`. It now loads with `nil` as its default, and `with_default("")` reads as `nil` in the matcher. A non-nullable `:json` field given `""` still raises. (#175)
|
|
18
|
+
- **A Symbol value in a controller matcher payload is read as the String a request carries.** The matcher stringified Symbol keys but passed a Symbol value through, so `accept_params(status: :active)` against `in: %w[active]` failed with `invalid_type` for a request the app accepts. A `:json` field's Symbol values come back as Strings in the returned hash. A standalone `Contract` still gets the payload as given, and a Symbol there is still `invalid_type`. A bare `ActionDispatch` module, one defined without `ActionDispatch::Request`, no longer makes a matcher raise for a missing normalizer. (#177)
|
|
19
|
+
- **A bare `ActionController::Metal` rule that cannot run is audited as uncovered.** `Audit.entries` marked an action covered whenever a rule was declared. An action whose `before_action` the gem never registered, because `AbstractController::Callbacks` was missing when `permit_params` ran, and whose effective mode (the rule's own `mode:` or `Permittable.mode`) is `enforce` or `monitor`, is now uncovered, with the note "contract cannot run: controller lacks AbstractController::Callbacks (no before_action)". Including the module after `permit_params` does not make it covered. The class-load check in `permit_params` is unchanged and still reads only the rule's own `mode:`, so such a controller still loads, and the README says so. (#176)
|
|
20
|
+
- **The exported JSON body of a rootless `unknown: :error` contract lists Rails' form keys.** The runtime exempts `authenticity_token`, `_method`, `utf8`, `commit` and `button` at the top of a rootless contract, but the body schema set `additionalProperties: false` without them, so a body the server accepts failed validation against the export. They are now free, optional properties, and a name the contract declares keeps its own schema. A `root:` rule, a multipart body, `JsonSchema.rule` and `Contract#json_schema` are unchanged. A renamed CSRF token and `format` are not listed, as for #165. (#178)
|
|
21
|
+
- **`alias_attribute` and `store_accessor` fields are checked against the column behind them.** The column guard looked a field up by its own name, so an alias or a store key failed at class load as a missing column although assignment accepts it. An alias resolves to its target through any chain, so an alias of an enum, or an enum declared on the alias name, goes through the enum contract, and under `Permittable.check_column_types` its type is compared with the target's. A `store_accessor` is accepted when its store column exists and has no type to compare; it is accepted only under the name its writer takes (`settings_theme` with `prefix: true`, not the bare key), and a subclass finds an accessor a parent declared. An error for a missing alias target or store column now names the target or the store, with its migration. (#178)
|
|
22
|
+
|
|
23
|
+
## 0.14.0 (2026-11-09)
|
|
24
|
+
<!-- title: a :file field type with a multipart export, date strings read as the instant they name, Metal controllers that enforce whatever the include order, and matchers that see what a request sees -->
|
|
25
|
+
|
|
26
|
+
Two additions and six changes. A new `:file` field type, and `of: :file`, accept an uploaded file, and the OpenAPI export describes an operation with a file field as `multipart/form-data` (#165). A `:date` or `:datetime` string that carries a time or an offset is read as the instant it names, or refused, where it was read as another day or another hour (#153, #166). A bare `ActionController::Metal` controller enforces its rules whichever order its modules are included, and raises at class load where the gem cannot register a hook (#155). The matchers run a controller payload through Rails' deep munge (#154). The OpenAPI export drops a name the route fills from `defaults:` from the request body (#156), and a blank default on a nullable field reads as `nil` (#160).
|
|
27
|
+
|
|
28
|
+
Minor rather than patch: each entry can make a request, a boot or a spec that passes today fail, or change what an action or an export receives. Before upgrading, read the entries that match what you use. A request can now be refused: a `:date` string with a time of day other than midnight UTC, or with an offset that moves it off its day (#153), a `:date` or `:datetime` string such as `"2026-09-05 -0500"`, `"Sat, 05 Sep 2026 -0500"`, `"2026/09/05 -05:00"` or `"2026-09-05T+05:00"` that Ruby read as a time or dropped (#166), and a `:date` `"1500-02-29"` once it carries a time. A boot can now fail: a bare `ActionController::Metal` controller with an `enforce: true` or `mode: :monitor` rule and no `AbstractController::Callbacks`, or an `enforce: true` rule and no `ActionController::Rescue`, or with Rescue included before Callbacks (#155), and a `:date` `in:` member written as a time-carrying string that is not midnight UTC (#153). An action can now receive something different: `nil` for an omitted nullable field with `default: ""` (#160), a `:datetime` such as `" +05:00"` read as the instant it names (#166), and an `ActionDispatch::Http::UploadedFile` where a `:file` field used to be refused (#165). An export now reads differently: a field the route fills from `defaults:` is no longer in the request body (#156), a nullable field's `default` prints as `null` (#160), and an operation with a `:file` field has only a `multipart/form-data` body (#165). And a spec can fail where it passed: a `reject_params(... nil ...)` that asserted a null array element on a Rails controller was a false green, because a real request never carries that null (#154).
|
|
29
|
+
|
|
30
|
+
### Added
|
|
31
|
+
- **A `:file` field type, and `of: :file`, for uploads.** No field type accepted an upload: a multipart POST whose file was declared `:string`, `:json` or `of: :string` got a 422 `invalid_type`, and an undeclared upload was dropped under `unknown: :ignore`, so `Model.create!(permitted_params)` lost the attachment. A `:file` field takes the two upload objects strong parameters permit, `ActionDispatch::Http::UploadedFile` and `Rack::Test::UploadedFile`, passes them through uncast, and refuses everything else, a String included, as `invalid_type`. `of: :file` works the same way, with the blank-element drop of #111, and an empty file input still sends `""`, which is absent. `validate:` can check the upload (`->(f) { f.size <= 5.megabytes }`). `ColumnGuard` treats `:file` like `virtual: true`, since an attachment is not a column, and the matchers accept `Rack::Test::UploadedFile` payloads. An ActiveStorage direct upload (`direct_upload: true`) submits the blob's signed id, a String, in place of the file, so a `:file` field refuses it; declare that field `:string` and attach the signed id. (#165)
|
|
32
|
+
- **An operation with a `:file` field is exported as `multipart/form-data`.** A `:file` leaf is `{"type":"string","contentMediaType":"application/octet-stream"}`, the OpenAPI 3.1 spelling, with no `minLength` because a 0-byte upload is accepted. An operation whose rule has a `:file` field anywhere gets only a `multipart/form-data` body, with Rails' bracket names as properties (`avatar[image]`), an array of hashes described in the indexed `fields_for` form with anchored ECMA-262 `patternProperties`, and container constraints in a body-level `x-permittable-form-groups` map keyed by bracket name. Under `unknown: :error` the body gets `additionalProperties: false` at every depth, and still allows a nullable container's null part, a `:json` field's nested keys, parts outside a `root:` and, for a rootless rule, Rails' form keys (`Permittable::FORM_KEYS`); a renamed CSRF token and an image submit's `x` and `y` cannot be known statically, and the README says so. Every other operation exports byte-identically, and a JSON value for a file passes the exported schema while the server refuses it, which joins the README's list of divergences. (#165)
|
|
33
|
+
- **`OpenAPI.rails_routes` descriptors gain an optional `defaults:` key.** It is an array of name strings, present only when the route has `defaults:` other than `controller`, `action` and `format`. A mount's defaults are merged into each engine route the mount reaches. A caller that passes its own descriptors to the export can supply it; a descriptor without the key behaves as before. (#156)
|
|
34
|
+
|
|
35
|
+
### Changed
|
|
36
|
+
- **A `:date` string with a time of day or a zone is accepted only at midnight UTC.** A `:date` kept the calendar day of a string and ignored the rest, so `"2026-02-28T25:00:00Z"` was valid and `"2026-02-28T23:30:00-05:00"`, which is 2026-03-01 in UTC, was read as 2026-02-28. Such a string is now read the way `:datetime` reads it (a Gregorian parse, a zoneless string as UTC, an impossible time or an offset Ruby cannot honour refused) and accepted only if the result is exactly midnight UTC; the value is a plain `Date` built from its year, month and day. `"2026-09-05T24:00:00Z"` now reads as 2026-09-06, the instant it names. `"1500-02-29"`, a Julian-only leap day, is still accepted as a plain date, but is refused once it carries a time, because a time-carrying string is read proleptic Gregorian. A `:date` `in:` member written as a time-carrying string fails at class load by the same rule. Date-only strings, `Date`, `Time`, `DateTime` and `TimeWithZone` objects, and `:datetime` are unchanged. (#153)
|
|
37
|
+
- **An ISO date followed by an offset or `Z` and no time is midnight at that offset; other bare offsets and `T` are refused.** With no time of day, `Date._parse` read a signed offset as the time and dropped its sign, so `:datetime` read both `"2026-09-05 +05:00"` and `"2026-09-05 -05:00"` as 05:00 UTC, and a `-0500` or `+5` was dropped and read as midnight UTC. A whole string that is an ISO date and a numeric offset or `Z` (`"2026-09-05+00:00"`, `"20260905Z"`) is now midnight at that offset, and the offset must be one Ruby honours (`+24:00`, `-99:00` and `+05:99` are refused). Any other date followed by a bare signed offset (`"Sep 5 2026 -05:00"`) is `invalid_type`, and so is an ISO date followed by `T` with no time, which is never read as a military zone. A `:date` applies the same rules with #153's midnight-UTC acceptance on top, so `"2026-09-05 -05:00"` and `"2026-09-05 +05:00"` are `invalid_type` for a `:date` and the instants they name for a `:datetime`. A zone name with no time (`"2026-09-05 EST"`) keeps its earlier reading. A plain ISO `:date` string skips the new checks and costs what it did; a `:date` string that carries a time costs more, because it is now read the way a `:datetime` is. (#166)
|
|
38
|
+
- **The matchers run a controller payload through Rails' deep munge.** With `perform_deep_munge = true`, Rails removes `nil` from every array before a controller reads `params`, so a real request never shows a null element. The matchers passed the payload unchanged, so `reject_params(tags: ["a", nil]).with_violation("tags[1]", :invalid_type)` passed for a request the app serves with a 200, `accept_params(tags: ["a", nil])` failed, and a null slipped past `length:` uncounted. For a controller subject, the payload now goes through `ActionDispatch::Request::Utils.normalize_encode_params` on a copy, with Symbol keys stringified and an `ActionController::Parameters` unwrapped with `to_unsafe_h`. An app that turned deep munge off still sees the null. A spec that asserted the null element on a Rails controller now fails, and it was a false green. A standalone `Contract` is unchanged: a null element is still `invalid_type`. This also resolves `ActionDispatch::Http::Utils` on Rails main. (#154)
|
|
39
|
+
- **A bare `ActionController::Metal` controller enforces its rules whichever order its modules are included, or raises at class load.** The `rescue_from` and `before_action` hooks were registered once, at include time, and only if the host already answered both. A Metal controller that included Permittable before `AbstractController::Callbacks` and `ActionController::Rescue` got neither: an `enforce: true` POST without a required field got 202 and ran the action, monitor mode emitted no `invalid_parameters.permittable` event, a lazy rule raised an unrescued `InvalidParameters`, and `permittable:audit` still reported the rules as covered. The hooks are now registered at the include and again at each `permit_params`, and the gem never registers one twice, so a documented `skip_before_action :enforce_params_contract` holds. Where the gem cannot register the hook, `permit_params` raises `ArgumentError` naming the missing module: an `enforce: true` or `mode: :monitor` rule with no `before_action` (`AbstractController::Callbacks`), an `enforce: true` rule with no `rescue_from` (`ActionController::Rescue`), or Rescue included before Callbacks, which would let a `before_action` rejection escape as a 500. `ActionController::Base`, `ActionController::API` and non-controller hosts are untouched. A Metal controller with no `render` now answers a rejection instead of raising `NoMethodError: render` in the gem's handler: the error envelope writes `status`, `content_type` and `response_body` itself, byte-identical to `render json:` for the envelope and problem+json, and a `render_error` keeps its precedence. (#155)
|
|
40
|
+
- **A name the route fills from `defaults:` leaves the OpenAPI request body.** Rails merges a route's `defaults:` into `request.path_parameters`, which win over the body and are exempt from `unknown: :error`, but the export documented the name as a required body field: `post "w/special", defaults: { kind: "x" }` published `kind` with its enum while the server answered 200 with `kind` `"x"` whatever the body said. A rootless field whose name the route fills from `defaults:` is now removed from the body, its `required` entry included, for any kind of field; under `unknown: :error` it stays as a free property that is never required. No path parameter is added, because the URL does not carry the value. Two routes that share a path and verb keep only the intersection of their defaults, so a name a plain route still needs stays in the body. A `root:` contract, `defaults: { format: :json }` and array, nested and `:json` kinds that a path template names are unchanged. (#156)
|
|
41
|
+
- **A blank default on a nullable field reads as `nil`.** On a `nullable:` scalar, `default: ""`, or a default that normalizes to `""` such as `" "` with `normalize: :strip`, was stored as the blank string, while a request that sends `""` reads as `nil`. An omitted `optional :note, :string, nullable: true, default: ""` now gets `nil`, the exported schema prints `"default": null`, and `example: ""` publishes `[null]` as the array path already did. An `in:`, `format:` or `:integer` field with a nullable `default: ""` used to fail at class load and now loads with `nil` as its default. `with_default("")` on a nullable field reads as `nil` in the matcher. A field with `transform:` still stores its default as authored, a non-nullable `default: ""` is unchanged, and a nullable `required: true` field with `default: ""` is still refused. (#160)
|
|
42
|
+
|
|
43
|
+
### Development
|
|
44
|
+
- **Bump railties, activerecord, actionpack and activesupport 8.1.4 to 8.1.4.1, sqlite3 to 2.10.2 and rubocop to 1.92.2.** Development dependencies only; the gem's runtime requirements are unchanged. (#168, #169, #170, #171, #172)
|
|
45
|
+
|
|
3
46
|
## 0.13.1 (2026-11-04)
|
|
4
47
|
<!-- title: contracts that cannot be exported are refused at class load, a Metal catch-all and a date-parts example export correctly, and a pre-1582 date reads as the day it names -->
|
|
5
48
|
|
data/README.md
CHANGED
|
@@ -538,6 +538,8 @@ Validation is **lazy by default**: it runs on the first `permitted_params` call,
|
|
|
538
538
|
|
|
539
539
|
In [monitor mode](#monitor-mode-roll-out-without-rejecting) the same flow runs, but a violation is reported instead of raised and the request proceeds with the raw params passed through.
|
|
540
540
|
|
|
541
|
+
A bare `ActionController::Metal` controller has no callbacks and no `rescue_from` until it includes them. `include AbstractController::Callbacks` and then `include ActionController::Rescue` (the order `ActionController::Base` uses, so a rejection also covers the `before_action`), before or after `include Permittable`. The rendering modules (`AbstractController::Rendering`, `ActionController::Rendering`, `ActionController::Renderers::All`) are optional: without `ActionController::Rendering` the gem writes the error response itself, with the same status, content type and JSON body. An `enforce: true` rule, or a rule declaring `mode: :monitor`, raises `ArgumentError` at class load when `AbstractController::Callbacks` is missing. The class-load check reads only the rule's own `mode:`, not the app-wide `Permittable.mode`, which an initializer usually sets after the controller loads. A rule with no `mode:` under an app-wide `Permittable.mode = :monitor` therefore loads, but its `before_action` is not there to run it: `permittable:audit` reports those actions as `no contract` (`contract cannot run`) instead of as monitored. An `enforce: true` rule that is not in monitor mode still raises at class load when `ActionController::Rescue` is missing or was included before `AbstractController::Callbacks`. Both modules have to be in by the time of `permit_params`. A check registered at that first `permit_params` runs after any callback declared between the include and it (see [Per-request locales](#custom-error-messages-message)), and with `include Permittable` first, a `skip_before_action :enforce_params_contract` goes after the first `permit_params`, since the callback does not exist before it. On a bare `ActionController::Metal` controller that includes `ActionController::Rescue` after `include Permittable`, the gem registers its handler at the first `permit_params` instead, so there it is a catch-all declared after that `permit_params` that answers first, and a re-declaration goes after it.
|
|
542
|
+
|
|
541
543
|
### Declaring a contract
|
|
542
544
|
|
|
543
545
|
```ruby
|
|
@@ -596,6 +598,21 @@ end
|
|
|
596
598
|
optional :metadata, :json, max_depth: 3, length: 0..32
|
|
597
599
|
```
|
|
598
600
|
|
|
601
|
+
An upload is a `:file` field. It takes the objects Rails' strong parameters permit as scalars (`ActionDispatch::Http::UploadedFile`, `Rack::Test::UploadedFile`), passes the object through uncast, and refuses anything else, a String included, as `invalid_type`. Size and content-type checks belong in `validate:`:
|
|
602
|
+
|
|
603
|
+
```ruby
|
|
604
|
+
optional :avatar, :file, validate: ->(file) { file.size <= 2.megabytes && file.content_type.start_with?("image/") }
|
|
605
|
+
array :attachments, of: :file, length: 0..5
|
|
606
|
+
```
|
|
607
|
+
|
|
608
|
+
`:file` takes `required:`, `nullable:`, `validate:`, `transform:`, `desc:`, `sensitive:`, `virtual:` and `message:`. `in:`, `length:`, `format:`, `normalize:`, `default:` and `example:` are refused at class load. A form's empty file input sends `""`, which is absent as everywhere else. The [drift guard](#the-schema-drift-guard) does not look for a column behind a `:file` field (an attachment is not a column), and the OpenAPI export documents an operation with a file as `multipart/form-data`, its properties named the way Rails reads the parts (`user[avatar]`, `docs[]`, `user[address][scan]`). An array of hashes is sent with an index (`items[0][photo]`, `items[0][name]`, `items[1][photo]`, …), as Rails' `fields_for` renders it, and the document describes those leaves with anchored `patternProperties`. What a flat body cannot carry, a container's own `required`, `minItems`/`maxItems`, `nullable`, `description` and custom-validation marker, is kept in the body's `x-permittable-form-groups`, keyed by the container's bracket name (`user[items]`), with `[]` standing for the index of a container inside an element (`user[items][][info]`). Send a nullable container's null as an empty part named by that bracket name, without `[]` (`user[docs]=""`; `user[docs][]=""` is an empty array). Under `unknown: :error` the multipart body sets `additionalProperties: false`, which refuses an undeclared part at any depth (`user[address][bogus]`, `user[items][0][bogus]`), and it lists the parts the server still takes: a nullable container's null as `{"const": ""}`, a `:json` field's keys (`user[extra][any]`) and, for a `root:` rule, any part outside the root, or for a rootless one, the form keys the runtime exempts (`authenticity_token`, `_method`, `utf8`, `commit`, `button`). A renamed CSRF token (`request_forgery_protection_token`) and an image submit's `x`/`y` cannot be known when the document is built, so they are not listed. The children of an optional hash are required only when the hash is sent (the group entry says the hash is optional), and `patternProperties` cannot mark a leaf of an array element required.
|
|
609
|
+
|
|
610
|
+
An ActiveStorage direct upload (`form.file_field :avatar, direct_upload: true`) sends the file from the browser straight to the storage service, and the form then submits only the blob's signed id, a String, which a `:file` field refuses as `invalid_type`. Declare such a field `:string` and attach the signed id (`record.avatar.attach(signed_id)`):
|
|
611
|
+
|
|
612
|
+
```ruby
|
|
613
|
+
optional :avatar, :string # direct upload: a signed blob id
|
|
614
|
+
```
|
|
615
|
+
|
|
599
616
|
Arrays are **optional unless `required: true`**, and `length:` on an array constrains the element **count**.
|
|
600
617
|
|
|
601
618
|
An array of hashes also accepts the shape Rails' `fields_for` sends for nested attributes: `user[addresses_attributes][0][city]` reaches the params as a Hash keyed `"0"`, `"1"`, … and is read as the records it encodes, in the order sent, exactly as strong params and `accepts_nested_attributes_for` read it. Only that shape qualifies: every key an integer and every value a hash.
|
|
@@ -678,11 +695,12 @@ Coercion is **deliberately strict**, and deliberately *not* `ActiveModel::Type`.
|
|
|
678
695
|
| `:float` | a real `Numeric`; a canonical numeric string (`"1.5"`, `".5"`, `"-2e3"`) | `"abc"`, `"1_8.5"`, `" 1.5 "`, and any number outside a Float's range, as a `Numeric` or a string alike (`BigDecimal("1e-400")`, `"1e400"`), a `Complex` (even `Complex(1, 0)`), a `Numeric` that cannot be converted |
|
|
679
696
|
| `:decimal` | a real `Numeric`, or a canonical numeric string → `BigDecimal`; a `Rational` whose decimal expansion is exact (`Rational(1, 2)`, `3r`) | Unparseable strings, `"1_000"`, `" 1.5 "`, a `Complex`, a `Rational` no decimal holds exactly (`Rational(1, 3)`), a `Numeric` that cannot be converted |
|
|
680
697
|
| `:boolean` | `true`/`false`, `"true"`/`"false"`, `"1"`/`"0"`, `1`/`0` | `"yes"`, `"on"`, `2` |
|
|
681
|
-
| `:date` | `Date`; a `Time`, `DateTime` or `ActiveSupport::TimeWithZone` that is exactly midnight UTC, as that `Date`; a string naming a **complete** date, in any format `Date.parse` understands (`"2026-09-05"`, `"2026/09/05"`, `"Sep 5, 2026"`) | Unparseable strings, **incomplete** ones (`"09/2026"`, `"5th"`, `"Sept"`), and any other instant — one with a time of day, or a midnight in another zone |
|
|
682
|
-
| `:datetime` | `Time`, `DateTime`, `ActiveSupport::TimeWithZone`, `Date`; a string naming a complete date, with or without a time | Unparseable strings,
|
|
698
|
+
| `:date` | `Date`; a `Time`, `DateTime` or `ActiveSupport::TimeWithZone` that is exactly midnight UTC, as that `Date`; a string naming a **complete** date, in any format `Date.parse` understands (`"2026-09-05"`, `"2026/09/05"`, `"Sep 5, 2026"`); a string with a time or zone only if it is exactly midnight UTC (`"2026-09-05T00:00:00Z"`) | Unparseable strings, **incomplete** ones (`"09/2026"`, `"5th"`, `"Sept"`), and any other instant, as an object or a string — one with a time of day, or a midnight in another zone |
|
|
699
|
+
| `:datetime` | `Time`, `DateTime`, `ActiveSupport::TimeWithZone`, `Date`; a string naming a complete date, with or without a time (an ISO date with an offset or `Z` and no time, `"2026-09-05-05:00"`, is midnight at that offset) | Unparseable strings, any string without a complete date (`"10:30"`), any other date followed by a bare offset and no time of day (`"Sep 5 2026 -05:00"`), an offset or an hour the parser would drop (`"12:00 2026-09-05 -05:00"`, `"2026-09-05 10 -05:00"`, `"2026-09-05T10"`), any word after a date that is not a zone Ruby knows, a day name or an era (`"2026-09-05 XYZ"`, `"2026-09-05 noon"`), and an ISO date followed by `T` and no time (`"2026-09-05T"`) |
|
|
683
700
|
| `:json` | Any `Hash` — passed through uncast, see [free-form hashes](#free-form-hashes-json) | Arrays, scalars |
|
|
701
|
+
| `:file` | An upload object (`ActionDispatch::Http::UploadedFile`, `Rack::Test::UploadedFile`), passed through uncast | A `String` (including a form's file field sent as text), numbers, hashes, arrays |
|
|
684
702
|
|
|
685
|
-
**Dates are parsed, never guessed.** `Date.parse` fills in what a string omits *from today* — `"09/2026"` becomes the 1st, `"5th"` becomes this month of this year — so the same request would mean different things on different days. A `:date` or `:datetime` string must therefore name all three of year, month and day; which **format** it names them in is `Date.parse`'s business, so every complete format it understands still works. A `:datetime` may omit the *time* part, which reads as midnight UTC.
|
|
703
|
+
**Dates are parsed, never guessed.** `Date.parse` fills in what a string omits *from today* — `"09/2026"` becomes the 1st, `"5th"` becomes this month of this year — so the same request would mean different things on different days. A `:date` or `:datetime` string must therefore name all three of year, month and day; which **format** it names them in is `Date.parse`'s business, so every complete format it understands still works. A `:datetime` may omit the *time* part, which reads as midnight UTC. An ISO date with an offset or `Z` and no time is midnight at that offset (`"2026-09-05 -05:00"` is `2026-09-05T05:00:00Z`; a `:date` takes it only where that is midnight UTC, as in `"2026-09-05+00:00"`); any other date followed by a bare offset and no time of day is refused, since Ruby's parser reads the offset as a time of day or drops it, and so is an ISO date followed by `T` and no time. A zone *name* after a date is honoured where Ruby knows it, with or without a time (`"2026-09-05 EST"` is `2026-09-05T05:00:00Z`, so a `:date` refuses it, and `"Sat Sep 5 10:00:00 2026 EST"` is `15:00:00Z`), and refused where it does not. So is **any other word** after a complete date that is not a day name or an era (`"2026-09-05 XYZ"`, `"2026-09-05 noon"`, `"2026-09-05 foo"`): all it can be is a zone, and a zone Ruby cannot honour is never guessed at. An offset after the year of git's and ctime's format is read (`"Sat Sep 5 10:00:00 2026 -0500"` is `15:00:00Z`). An hour or offset the parser would drop or misread (`"2026-09-05T10"`, `"2026-09-05 10 -05:00"`, `"12:00 2026-09-05 -05:00"`) is refused rather than read as some other instant.
|
|
686
704
|
|
|
687
705
|
**Strings in other encodings are inspected, never converted.** A String whose bytes are not valid in its **own** encoding (`"caf\xC3"` in UTF-8, a lone UTF-16 surrogate) is `invalid_type` for every scalar type, before `normalize:` or `format:` sees it. Any other String keeps its encoding: a `:string` value is handed back exactly as it arrived, so a controller using Rails' `skip_parameter_encoding` or `param_encoding` gets its binary or Shift_JIS text unchanged. The number, boolean and date types parse a UTF-8 **copy** of the text, so UTF-16 `"12"` casts to `12` for an `:integer`; when the text has no UTF-8 reading (a byte Windows-1252 leaves undefined) that is `invalid_type`. `normalize:` and `format:` work on the String in its own encoding. Where a normalizer cannot handle that encoding (`:squish` on UTF-16), the value is left as it is; where a `format:` pattern cannot be applied to it (a non-ASCII pattern against UTF-16 or binary bytes), that is a `format` violation. `in:` compares Strings as Ruby does, encoding included. A `:json` field's contents are not examined.
|
|
688
706
|
|
|
@@ -726,7 +744,7 @@ In [exported OpenAPI](#exporting-openapi-docs-that-cannot-drift) the field is `{
|
|
|
726
744
|
|
|
727
745
|
### Absence, defaults, and partial updates
|
|
728
746
|
|
|
729
|
-
`nil` and `""` are **both treated as absent** — the query-parameter convention, where an untouched form field arrives as an empty string. Boolean `false` is present. `normalize:` runs *before* this rule, so a field declared `normalize: :squish` treats `" "` as absent too: whitespace cannot satisfy a `required` field by becoming `""`. The same goes for a `""` **element** of a scalar `array ..., of:`: it is dropped before casting and before `length:` counts, because `collection_check_boxes` and `select multiple: true` always send a hidden `""` so that unchecking everything still sends the key. A `null` element, which no form sends, is still `invalid_type`.
|
|
747
|
+
`nil` and `""` are **both treated as absent** — the query-parameter convention, where an untouched form field arrives as an empty string. Boolean `false` is present. `normalize:` runs *before* this rule, so a field declared `normalize: :squish` treats `" "` as absent too: whitespace cannot satisfy a `required` field by becoming `""`. The same goes for a `""` **element** of a scalar `array ..., of:`: it is dropped before casting and before `length:` counts, because `collection_check_boxes` and `select multiple: true` always send a hidden `""` so that unchecking everything still sends the key. A `null` element, which no form sends, never reaches a Rails controller's contract under the default `perform_deep_munge` (Rails drops it from every array first); on a standalone `Contract`, or with deep munge off, it is still `invalid_type`.
|
|
730
748
|
|
|
731
749
|
That single rule produces the behaviour you want from a `PATCH`:
|
|
732
750
|
|
|
@@ -765,7 +783,7 @@ Three more readings worth knowing:
|
|
|
765
783
|
|
|
766
784
|
- **`required` + `nullable`** is coherent, and means what it says in SQL: the client *must* state the field, and `null` is a legal statement. A missing key still violates.
|
|
767
785
|
- **`default: nil`** — legal only on a nullable field — gives the `PUT` reading, where absence *also* means clear.
|
|
768
|
-
- **On arrays and nested blocks**, `nullable:` applies to the array or object itself, never to its contents. `{ "tags": null }` yields `nil` (distinct from `[]`, which still gets length-checked); a null *element* inside `tags` is still `invalid_type
|
|
786
|
+
- **On arrays and nested blocks**, `nullable:` applies to the array or object itself, never to its contents. `{ "tags": null }` yields `nil` (distinct from `[]`, which still gets length-checked); a null *element* inside `tags` is still `invalid_type` wherever Rails has not already dropped it (a standalone `Contract`, or `perform_deep_munge` off).
|
|
769
787
|
|
|
770
788
|
Exported [OpenAPI](#exporting-openapi-docs-that-cannot-drift) tells the truth about all of this: a nullable field's `type` gains `"null"`, and a nullable `in:` set lists `null` in its `enum`.
|
|
771
789
|
|
|
@@ -910,7 +928,7 @@ The setting is app-wide, not per-contract, because the error format of an API is
|
|
|
910
928
|
|
|
911
929
|
Under `:log` that bound is the whole record: nothing else names an undeclared key, so beyond the tenth only the count survives. Where you need every name — auditing what a client really sends during a rollout — use `unknown: :error` in monitor mode, which records all of them in `details` and in the instrumentation payload without rejecting the request.
|
|
912
930
|
|
|
913
|
-
Rails merges its own keys into `params`: `controller`, `action`, and `format` from the router, plus `authenticity_token` (or whatever `config.action_controller.request_forgery_protection_token` renames it to), `_method`, `utf8`, and the submit button's name from an ordinary form POST: `commit` from `f.submit` / `submit_tag`, `button` from `f.button` / `button_tag` (sent as `button=` when the `<button>` has no value). All eight are exempt at the top level. So is the click point of an image submit: `image_submit_tag("save.png")` renders an `<input type="image">` with no name, and a browser submitting through it posts where it was clicked as `x=12&y=7` (or `save.x=12&save.y=7` when the tag is named `"save"`, which Rack keeps as those literal keys). `x` and `y` are ordinary names a contract may really be sent, so they are exempt only as a pair, both present and both plain digits (never negative or fractional); a lone `x`, or a pair that is not digits, is flagged as usual, and a contract that *declares* `x` or `y` has it validated as usual and sees the other flagged unless it declares that too. A bracketed image-submit name is not covered (`name: "user[save]"` is parsed by Rack as `{"user"=>{"save"=>{".x"=>..}}}`, nested rather than top level), just as only the top-level `commit` and `button` are. So are the route's **path parameters** (`PATCH /users/1` merges `id`, which the exported OpenAPI documents as a path parameter rather than a body field); a contract that *declares* `id` has it validated as usual, since the URL really carried it, and the export then documents that field as the path parameter's schema (`required :id, :integer, in: 1..1000` becomes `{"type":"integer","minimum":1,"maximum":1000}`) and leaves it out of the request body, `required` list included, so a body without `id` is valid. Only a rootless contract does this, and only for a name the route templates; a `root:` contract's `id` is a body field and stays one, and so does an `array`, nested or `:json` field, since no URL segment can be one. Under `unknown: :error` the body schema forbids undeclared keys, but every name the route templates stays in it as a property that takes any value and is never required, declared or not: `PATCH /users/1` with `{"id":1,"name":"x"}` is accepted, because the path parameter is exempt and the URL's `id` overwrites the body's. **ParamsWrapper's copy of a JSON body** under the controller's wrapper key (`user` for `UsersController`) goes further: when Rails made that copy, a rootless contract does not see the key at all, because the client never sent it. So an undeclared wrapper key is not flagged, and a scalar or array field that happens to share the wrapper's name (`optional :feedback, :string` on `FeedbackController`) is simply absent, rather than failing as `invalid_type` against Rails' copy of the whole body. The one exception is a rootless contract that declares the wrapper key as a hash container — a nested block (`required :user do ... end`) or `:json`. That contract is reading the copy on purpose, like a `root:` spelled as a field, so the copy is kept and validated as that field. A client that sends `user` itself is checked like any other key: validated if declared, flagged if not. That holds whether the wrapper name is configured as a String or as a Symbol (`wrap_parameters :user`). Either way `unknown: :error` flags what the *client* got wrong rather than what the framework added. Inside a `root:` or a nested hash there is no such exemption, because nothing legitimately injects keys there — and a standalone `Contract` exempts nothing at all, having neither a router, a form, nor a request.
|
|
931
|
+
Rails merges its own keys into `params`: `controller`, `action`, and `format` from the router, plus `authenticity_token` (or whatever `config.action_controller.request_forgery_protection_token` renames it to), `_method`, `utf8`, and the submit button's name from an ordinary form POST: `commit` from `f.submit` / `submit_tag`, `button` from `f.button` / `button_tag` (sent as `button=` when the `<button>` has no value). All eight are exempt at the top level. So is the click point of an image submit: `image_submit_tag("save.png")` renders an `<input type="image">` with no name, and a browser submitting through it posts where it was clicked as `x=12&y=7` (or `save.x=12&save.y=7` when the tag is named `"save"`, which Rack keeps as those literal keys). `x` and `y` are ordinary names a contract may really be sent, so they are exempt only as a pair, both present and both plain digits (never negative or fractional); a lone `x`, or a pair that is not digits, is flagged as usual, and a contract that *declares* `x` or `y` has it validated as usual and sees the other flagged unless it declares that too. A bracketed image-submit name is not covered (`name: "user[save]"` is parsed by Rack as `{"user"=>{"save"=>{".x"=>..}}}`, nested rather than top level), just as only the top-level `commit` and `button` are. So are the route's **path parameters** (`PATCH /users/1` merges `id`, which the exported OpenAPI documents as a path parameter rather than a body field); a contract that *declares* `id` has it validated as usual, since the URL really carried it, and the export then documents that field as the path parameter's schema (`required :id, :integer, in: 1..1000` becomes `{"type":"integer","minimum":1,"maximum":1000}`) and leaves it out of the request body, `required` list included, so a body without `id` is valid. Only a rootless contract does this, and only for a name the route templates; a `root:` contract's `id` is a body field and stays one, and so does an `array`, nested or `:json` field, since no URL segment can be one. Under `unknown: :error` the body schema forbids undeclared keys, but the form keys above (`authenticity_token`, `_method`, `utf8`, `commit`, `button`) stay in a rootless contract's JSON body as free, optional properties, as in its multipart body, because the runtime accepts them (a `root:` contract's body is unchanged: they sit outside the root; a name the contract declares keeps its own schema; `Contract#json_schema` describes the contract alone and lists none), and every name the route templates stays in it as a property that takes any value and is never required, declared or not: `PATCH /users/1` with `{"id":1,"name":"x"}` is accepted, because the path parameter is exempt and the URL's `id` overwrites the body's. A name the route fills from `defaults:` (`post "w", to: "widgets#create", defaults: { kind: "x" }`, on the route, its `scope` or the `mount` it is reached through) is no body field either, since the router overwrites the body's value: the export leaves it out of the body, `required` list included, and under `unknown: :error` keeps it as that same free property, but declares no path parameter for it, because no URL carries it. `rails_routes` names such keys in each descriptor's `defaults:`, apart from `controller`, `action` and `format`. **ParamsWrapper's copy of a JSON body** under the controller's wrapper key (`user` for `UsersController`) goes further: when Rails made that copy, a rootless contract does not see the key at all, because the client never sent it. So an undeclared wrapper key is not flagged, and a scalar or array field that happens to share the wrapper's name (`optional :feedback, :string` on `FeedbackController`) is simply absent, rather than failing as `invalid_type` against Rails' copy of the whole body. The one exception is a rootless contract that declares the wrapper key as a hash container — a nested block (`required :user do ... end`) or `:json`. That contract is reading the copy on purpose, like a `root:` spelled as a field, so the copy is kept and validated as that field. A client that sends `user` itself is checked like any other key: validated if declared, flagged if not. That holds whether the wrapper name is configured as a String or as a Symbol (`wrap_parameters :user`). Either way `unknown: :error` flags what the *client* got wrong rather than what the framework added. Inside a `root:` or a nested hash there is no such exemption, because nothing legitimately injects keys there — and a standalone `Contract` exempts nothing at all, having neither a router, a form, nor a request.
|
|
914
932
|
|
|
915
933
|
All of this changes what is *checked* only. Monitor mode still hands back the form keys, the path parameters and the wrapper's copy in its raw pass-through, where behaving exactly like the pre-contract app is the whole promise and a legacy action may read `params[:id]` or `_method` itself; only the router's three are dropped there.
|
|
916
934
|
|
|
@@ -1023,6 +1041,8 @@ The error carries a ready-to-paste migration command, typed from your own field
|
|
|
1023
1041
|
|
|
1024
1042
|
A field naming a column the model lists in `ignored_columns` raises too, but says so (remove it from `ignored_columns`, or declare it `virtual: true`) rather than suggesting a migration.
|
|
1025
1043
|
|
|
1044
|
+
An attribute assignment accepts without a column of its own is checked against the column behind it. A field named for an `alias_attribute` (`alias_attribute :title, :name`) is checked as its target `name`, type included. A field named for a `store_accessor` (`store_accessor :settings, :theme`) passes when the store's column (`settings`) exists, since the value lives inside that column; it has no type of its own to compare, and a missing store column is reported by the store's name rather than as a missing `theme` column. The name is the one assignment takes, so with `prefix: true` it is `settings_theme` and the bare `theme` is still reported missing. An accessor a parent model declared counts too. Rails does not record which prefix built which accessor, so two stores that share a key under different prefixes are ambiguous: the guard picks the store by the longest matching key, and may then check the other store's column. An alias whose target column is missing is reported as `'title' is an alias of 'name'`, with the migration for `name`. Only a name no column, alias or store accessor backs still needs `virtual: true`.
|
|
1045
|
+
|
|
1026
1046
|
#### Checking types too (opt-in)
|
|
1027
1047
|
|
|
1028
1048
|
A dropped column fails the deploy; a **retyped** one doesn't, unless you ask:
|
|
@@ -1249,7 +1269,7 @@ No Rails required for the core: `Permittable::Generator.draft(model: User)`, `.f
|
|
|
1249
1269
|
|
|
1250
1270
|
A controller declaring `permit_params :create` looks adopted. If it also answers `PATCH`, that action is validating **nothing** — and until now nothing in the gem said so. [`permittable:generate`](#generating-draft-contracts-permittablegenerate) only notices controllers with no contract at all, and the [OpenAPI export](#exporting-openapi-docs-that-cannot-drift) documents what exists rather than what is missing.
|
|
1251
1271
|
|
|
1252
|
-
The audit crosses the contract registry with the **route set**, so a half-covered controller is as visible as an uncovered one. It reads every controller a route can reach: `ActionController::Base` and `::API` subclasses, and bare `ActionController::Metal` ones such as a lean webhook endpoint. The export and the generator read the same list.
|
|
1272
|
+
The audit crosses the contract registry with the **route set**, so a half-covered controller is as visible as an uncovered one. It reads every controller a route can reach: `ActionController::Base` and `::API` subclasses, and bare `ActionController::Metal` ones such as a lean webhook endpoint. It also loads any autoloaded controller a route names (`Rails::HealthController` behind `/up`, which nothing has loaded yet), since the route's own controller is part of the app; a route whose controller constant does not exist is skipped, not raised on. A controller from a gem is still [ignored by default](#ignoring-controllers-and-actions). The export and the generator read the same list of loaded controllers; the audit also loads any autoloaded controller a route names.
|
|
1253
1273
|
|
|
1254
1274
|
```sh
|
|
1255
1275
|
bin/rails permittable:audit # the table plus a summary
|
|
@@ -1410,7 +1430,7 @@ Both work on a controller class, a controller instance, or a [standalone `Contra
|
|
|
1410
1430
|
|
|
1411
1431
|
The negated forms follow the same rules as `not_to permit_param`: `not_to accept_params(...)` passes only when the contract rejects the payload, and `not_to reject_params(...)` only when it accepts it. Neither takes a qualifier — `not_to accept_params(...).returning(x)` would pass both on a rejection and on an acceptance returning anything else, so it raises and names the positive form — and both fail, rather than passing, when no rule covers the action or the subject declares no contracts.
|
|
1412
1432
|
|
|
1413
|
-
The matchers run **without a request**, so they know the controller's settings but not its route. The CSRF parameter name set at class level with `request_forgery_protection_token` is exempt from `unknown: :error` as it is at runtime, but a per-instance override is not seen, and neither are a route's **path parameters**: a payload `id` on a member action under `unknown: :error` is reported `unknown`, although a real `PATCH /users/1` carries it in the URL and is accepted. Leave path parameters out of the payload you pass to `accept_params` / `reject_params`.
|
|
1433
|
+
The matchers run **without a request**, so they know the controller's settings but not its route. The CSRF parameter name set at class level with `request_forgery_protection_token` is exempt from `unknown: :error` as it is at runtime, but a per-instance override is not seen, and neither are a route's **path parameters**: a payload `id` on a member action under `unknown: :error` is reported `unknown`, although a real `PATCH /users/1` carries it in the URL and is accepted. Leave path parameters out of the payload you pass to `accept_params` / `reject_params`. On a controller the payload goes through the same normalization a request gets, so a `nil` array element is dropped as Rails drops it (unless the app turned `perform_deep_munge` off), and a Symbol value (`status: :active`) reads as the String a request carries; a standalone `Contract` gets the payload as given, so a Symbol value there is still `invalid_type`. A failure message that echoes params (the returned hash, a `returning` expectation) redacts them like a request log: the names of `sensitive:` fields, plus the app's `config.filter_parameters` when a Rails application is booted. Matching is by substring, like Rails, so `sensitive: true` on `pin` also redacts `shipping`; when a `returning` mismatch is hidden by that, the message adds `differs at: pin, shipping`, names only. Under a `root:` contract the hash is filtered as the request logs it, under its root, so a scoped filter such as `"payment.number"` applies; the note stops at a redacted key and never names anything below it.
|
|
1414
1434
|
|
|
1415
1435
|
### Standalone contracts (no controller)
|
|
1416
1436
|
|
|
@@ -1501,7 +1521,7 @@ Where they legitimately differ, the spec names the reason and asserts the **dire
|
|
|
1501
1521
|
- **`null` as absence.** The runtime reads `{"age": null}` as `{}` ([absence](#absence-defaults-and-partial-updates)); JSON Schema cannot express that, so `type: integer` rejects a null the server would accept and ignore. A [`nullable:`](#explicit-nulls-nullable) field is not this case — there the null is a value, the exported `type` widens to say so, and the two agree.
|
|
1502
1522
|
- **Padding that normalizes away.** `normalize:` runs before the checks, so under `normalize: :squish` and `length: 3..10` the server accepts `" abcdefghij "` — ten characters once squished — while the docs reject its fourteen.
|
|
1503
1523
|
|
|
1504
|
-
|
|
1524
|
+
Seven cases go the other way, and are worth knowing before you hand the document to a client. Each rule stays visible on its own field, and the spec asserts that as well as the direction:
|
|
1505
1525
|
|
|
1506
1526
|
- **Bounds JSON Schema has no keyword for.** A `:json` field's `max_depth:` is enforced by the server but cannot be written as a JSON Schema keyword, so the published document is **looser** there and an over-nested payload still earns a 422. The bound is not dropped — it is exported as `x-permittable-max-depth` — so a generator or linter that wants it can read it.
|
|
1507
1527
|
- **`normalize:` runs before the checks.** The server validates the *normalized* string, and JSON Schema has no keyword for "transform, then check". With `required :name, :string, length: 3..10, normalize: :squish`, `" "` passes the docs' `minLength: 3` and then squishes to `""` — absent, so `missing` — and `" a "` passes them and squishes to `"a"`, which is too short. The step is exported as `x-permittable-normalize` — the preset's name (`"squish"`, `"email"`, …), which a client can apply before validating, or `true` for a custom proc.
|
|
@@ -1510,7 +1530,9 @@ Six cases go the other way, and are worth knowing before you hand the document t
|
|
|
1510
1530
|
- **A Range of non-numbers.** `in: "a".."m"` has no `minimum`/`maximum` equivalent (those constrain numbers only) and rides along as `x-permittable-range` instead. A value outside it still passes the docs.
|
|
1511
1531
|
- **Strings whose validity is a `format`.** `:decimal`, `:date` and `:datetime` are sent as strings, and what makes such a string valid is its `format` (`"decimal"`, `"date"`, `"date-time"`) — which draft 2020-12 treats as an annotation unless a validator opts into asserting it. So `"abc"` or `"NaN"` for a `:decimal` and `"2026-02-30"` for a `:date` pass most validators and fail the server's cast with `invalid_type`.
|
|
1512
1532
|
|
|
1513
|
-
A `
|
|
1533
|
+
A `:file` field is looser in a way no JSON body can show: the JSON export accepts any string for it (`{"user":{"avatar":"abc"}}`), while the server takes only an upload object and refuses every JSON value. The schema describes the multipart part, and the field keeps `contentMediaType` to say so. It is a seventh case, asserted in the spec as `:file_upload`.
|
|
1534
|
+
|
|
1535
|
+
A `format:` regexp that does not translate to ECMA-262 is looser in the same way — it publishes as `x-permittable-pattern` rather than a `pattern` that would enforce something else, so a value it refuses still passes the docs — but it is not one of the seven above: `spec/schema_conformance_spec.rb` does not yet assert a case for it, since the Ruby → ECMA-262 translation it would depend on is being reworked separately. A `finalize` block is looser too, and has no field to sit on: its `violate!` cross-field checks (`ends_on` before `starts_on`) run only once every field has passed, so a payload each field's schema accepts can still earn a 422. The rule's own object carries `x-permittable-finalize: true` to say the schema alone is not the whole verdict, and so does the operation, so the marker is still there when an operation has no request body to hold the schema. Everything else the exporter cannot translate stays visible as an `x-permittable-*` extension rather than being guessed at.
|
|
1514
1536
|
|
|
1515
1537
|
|
|
1516
1538
|
<details>
|
|
@@ -1523,8 +1545,9 @@ A `format:` regexp that does not translate to ECMA-262 is looser in the same way
|
|
|
1523
1545
|
| `required` / `optional` | the object's `required:` array; required strings, and the string encoding of a required `:decimal`/`:date`/`:datetime`, also get `minLength: 1` (`""` is absent; a `nullable:` `:decimal`/`:date`/`:datetime` reads it as a null, so it gets none) |
|
|
1524
1546
|
| `:string` `:integer` `:float` `:boolean` | `string` / `integer` / `number` / `boolean` |
|
|
1525
1547
|
| `:date` / `:datetime` | `string` + `format: date` / `date-time` |
|
|
1548
|
+
| `:file` | `string` + `contentMediaType: application/octet-stream` (the 3.1 spelling; `format: binary` is 3.0's). An operation whose contract has a `:file` field gets a `multipart/form-data` request body instead of `application/json` |
|
|
1526
1549
|
| `:decimal` | `type: ["string", "number"]` + `format: decimal` (string is the precision-safe encoding) |
|
|
1527
|
-
| `in:` list / numeric Range | `enum` of the cast members (a `:
|
|
1550
|
+
| `in:` list / numeric Range | `enum` of the cast members (a `:datetime` member written as a String is published as written; a `:date` member, however written, as `YYYY-MM-DD`) / `minimum` + `maximum` (exclusive ends honoured). An `in:` object that only answers `include?` is flagged `x-permittable-custom-validation` |
|
|
1528
1551
|
| `length:` | `minLength`/`maxLength` on strings, `minItems`/`maxItems` on arrays |
|
|
1529
1552
|
| `format:` | `pattern`, valid under the `u` flag Ajv compiles with: `\A`/`\z` become `^`/`$`, `\s` and `.` are spelled out as the classes they are in Ruby (ECMA-262's `\s` also matches NBSP and U+2028; its `.` also stops at `\r`), and redundant escapes like `\-` and `\#` are written bare |
|
|
1530
1553
|
| `default:` / `desc:` / `example:` | `default` / `description` / `examples` |
|
data/lib/permittable/audit.rb
CHANGED
|
@@ -48,11 +48,13 @@ module Permittable
|
|
|
48
48
|
# never included the concern, which is exactly the case worth finding).
|
|
49
49
|
#
|
|
50
50
|
# `missing_action` marks a route to an action the controller does not
|
|
51
|
-
# define — see Audit.missing_action?. `
|
|
51
|
+
# define — see Audit.missing_action?. `inert` marks one whose rule exists
|
|
52
|
+
# but cannot run, so `rule` is nil and the action is uncovered — see
|
|
53
|
+
# Audit.inert?. `route` identifies the route the
|
|
52
54
|
# path came from (nil for a hand-built descriptor, which is then its own
|
|
53
55
|
# route); see `summary`. `ignored` is why the entry is left out of the
|
|
54
56
|
# counts — a key of IGNORE_REASONS — or nil when it is audited.
|
|
55
|
-
Entry = Struct.new(:controller, :action, :verb, :path, :rule, :missing_action, :route, :ignored,
|
|
57
|
+
Entry = Struct.new(:controller, :action, :verb, :path, :rule, :missing_action, :route, :ignored, :inert,
|
|
56
58
|
keyword_init: true) do
|
|
57
59
|
def covered?
|
|
58
60
|
!rule.nil?
|
|
@@ -66,6 +68,10 @@ module Permittable
|
|
|
66
68
|
!ignored.nil?
|
|
67
69
|
end
|
|
68
70
|
|
|
71
|
+
def inert?
|
|
72
|
+
inert == true
|
|
73
|
+
end
|
|
74
|
+
|
|
69
75
|
# The mode this action would actually run in, rule-level declaration
|
|
70
76
|
# first and the app-wide default behind it.
|
|
71
77
|
def mode
|
|
@@ -111,12 +117,33 @@ module Permittable
|
|
|
111
117
|
outside = :outside_root if outside_root?(controller, root)
|
|
112
118
|
routes.select { |route| route[:controller].to_s == key }.map do |route|
|
|
113
119
|
action = route[:action].to_s
|
|
120
|
+
rule = rule_for(controller, action)
|
|
121
|
+
inert = inert?(controller, rule)
|
|
114
122
|
Entry.new(controller: key, action: action, verb: route[:verb], path: route[:path],
|
|
115
|
-
rule:
|
|
116
|
-
|
|
123
|
+
rule: (rule unless inert), missing_action: missing[action], route: route[:route],
|
|
124
|
+
ignored: configured_ignore(key, action, ignore) || outside, inert: inert)
|
|
117
125
|
end
|
|
118
126
|
end
|
|
119
127
|
|
|
128
|
+
# Whether `rule` is declared on `controller` but can never run there: the
|
|
129
|
+
# gem never registered its before_action on it — a bare ActionController::
|
|
130
|
+
# Metal controller without AbstractController::Callbacks at its
|
|
131
|
+
# `permit_params`, which asks the flag the gem sets when it registers the
|
|
132
|
+
# callback (a callbacks module included afterwards does not undo that) —
|
|
133
|
+
# while the rule validates from that callback: an `enforce: true` rule, or
|
|
134
|
+
# one in monitor mode by its own mode: or the app-wide Permittable.mode.
|
|
135
|
+
# permit_params raises for this at class load, but reads only the rule's own
|
|
136
|
+
# mode, since the app-wide one is often set after the class loads; the
|
|
137
|
+
# effective mode is judged here. Such an action is audited as uncovered
|
|
138
|
+
# rather than as the monitored one it claims to be.
|
|
139
|
+
def inert?(controller, rule)
|
|
140
|
+
return false unless rule && defined?(::ActionController::Metal) && controller.is_a?(Class) &&
|
|
141
|
+
controller < ::ActionController::Metal
|
|
142
|
+
|
|
143
|
+
(rule[:enforce] || (rule[:mode] || Permittable.mode) == :monitor) &&
|
|
144
|
+
!(controller.respond_to?(:permittable_callback_registered) && controller.permittable_callback_registered)
|
|
145
|
+
end
|
|
146
|
+
|
|
120
147
|
# Why `controller` — or one of its actions — is left out of the audit and
|
|
121
148
|
# of permittable:generate: :configured (Permittable.audit_ignore names the
|
|
122
149
|
# controller, or "controller#action"), :outside_root, or nil. The
|
|
@@ -151,11 +178,32 @@ module Permittable
|
|
|
151
178
|
# themselves are Metal descendants too; they are the framework's abstract
|
|
152
179
|
# bases, which no route names, and the old lists never held them.
|
|
153
180
|
# Anonymous classes cannot be routed to, so only named ones are kept.
|
|
154
|
-
|
|
181
|
+
#
|
|
182
|
+
# `descendants` only holds classes that have been loaded, and a framework
|
|
183
|
+
# controller is autoloaded: Rails::HealthController behind `/up` is a
|
|
184
|
+
# registered constant until something touches it, so it had no row. Pass
|
|
185
|
+
# the route descriptors and every controller a route names is loaded and
|
|
186
|
+
# added — it is the route's own controller. A constant that does not exist,
|
|
187
|
+
# or is not a controller class, is left out rather than raised on.
|
|
188
|
+
def rails_controllers(routes = [])
|
|
155
189
|
return [] unless defined?(::ActionController::Metal)
|
|
156
190
|
|
|
157
191
|
frameworks = %w[ActionController::Base ActionController::API]
|
|
158
|
-
::ActionController::Metal.descendants
|
|
192
|
+
loaded = ::ActionController::Metal.descendants + routed_controllers(routes)
|
|
193
|
+
loaded.uniq.select { |controller| controller.name && !frameworks.include?(controller.name) }
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
# The controller classes the routes' `controller:` keys name, constantized
|
|
197
|
+
# (loading an autoloaded one). `safe_constantize` answers nil for a missing
|
|
198
|
+
# constant and raises on anything else — an error inside the controller's
|
|
199
|
+
# own file is the app's to see, so nothing more is rescued here. A key that
|
|
200
|
+
# names no constant, or one that is not an ActionController::Metal class,
|
|
201
|
+
# yields nothing.
|
|
202
|
+
def routed_controllers(routes)
|
|
203
|
+
routes.map { |route| route[:controller].to_s }.reject(&:empty?).uniq.filter_map do |key|
|
|
204
|
+
found = ActiveSupport::Inflector.safe_constantize("#{ActiveSupport::Inflector.camelize(key)}Controller")
|
|
205
|
+
found if found.is_a?(Class) && found < ::ActionController::Metal
|
|
206
|
+
end
|
|
159
207
|
end
|
|
160
208
|
|
|
161
209
|
# The root a controller's source must be inside to be audited:
|
|
@@ -434,7 +482,16 @@ module Permittable
|
|
|
434
482
|
end
|
|
435
483
|
|
|
436
484
|
def uncovered_note(entry)
|
|
437
|
-
not_found_note(entry) || ("ACCEPTS A BODY" if entry.body?)
|
|
485
|
+
not_found_note(entry) || inert_note(entry) || ("ACCEPTS A BODY" if entry.body?)
|
|
486
|
+
end
|
|
487
|
+
|
|
488
|
+
# Says why a declared contract is not counted, and keeps the body warning
|
|
489
|
+
# a gate reader needs.
|
|
490
|
+
def inert_note(entry)
|
|
491
|
+
return unless entry.inert?
|
|
492
|
+
|
|
493
|
+
["contract cannot run: controller lacks AbstractController::Callbacks (no before_action)",
|
|
494
|
+
("ACCEPTS A BODY" if entry.body?)].compact.join(" — ")
|
|
438
495
|
end
|
|
439
496
|
|
|
440
497
|
# The one wording for a route Rails would 404, covered or not.
|
|
@@ -143,29 +143,41 @@ module Permittable
|
|
|
143
143
|
end
|
|
144
144
|
|
|
145
145
|
# An authored hash is exported as a schema `default`/`example`, and JSON
|
|
146
|
-
# has no NaN or Infinity: JSON.generate raises on
|
|
147
|
-
# is written, long after the class loaded
|
|
148
|
-
#
|
|
149
|
-
#
|
|
146
|
+
# has no NaN or Infinity: JSON.generate raises on a Float's when the
|
|
147
|
+
# document is written, long after the class loaded, and a BigDecimal's was
|
|
148
|
+
# exported as the String "NaN". Nor does the export keep a Time finer than
|
|
149
|
+
# a nanosecond: it prints nine digits, a different instant (a :datetime
|
|
150
|
+
# field's own default is refused for the same reason). A request cannot
|
|
151
|
+
# carry any of these (JSON has none; a form sends Strings), so only the
|
|
152
|
+
# authored value is held to it, here, and not permittable_check_json for
|
|
153
|
+
# every request.
|
|
150
154
|
def permittable_check_json(field, value)
|
|
151
155
|
status, read = super
|
|
152
156
|
return [status, read] unless status == :ok
|
|
153
157
|
|
|
154
|
-
|
|
155
|
-
return [:error,
|
|
158
|
+
problem = unexportable_json(value, "")
|
|
159
|
+
return [:error, problem] if problem
|
|
156
160
|
|
|
157
161
|
[status, read]
|
|
158
162
|
end
|
|
159
163
|
|
|
160
|
-
#
|
|
161
|
-
|
|
164
|
+
# Why the first value that would not survive the export is refused, and
|
|
165
|
+
# where it sits (`a.b[1].c`), or nil.
|
|
166
|
+
def unexportable_json(value, path)
|
|
162
167
|
case value
|
|
163
|
-
when Float then path unless value.finite?
|
|
164
|
-
when
|
|
165
|
-
when
|
|
168
|
+
when Float, BigDecimal then "holds NaN or Infinity at #{path}, which JSON cannot carry" unless value.finite?
|
|
169
|
+
when Time, DateTime then unexportable_time(value, path)
|
|
170
|
+
when Hash then value.each_pair.lazy.filter_map { |k, v| unexportable_json(v, path.empty? ? k.to_s : "#{path}.#{k}") }.first
|
|
171
|
+
when Array then value.each_with_index.lazy.filter_map { |v, i| unexportable_json(v, "#{path}[#{i}]") }.first
|
|
166
172
|
end
|
|
167
173
|
end
|
|
168
174
|
|
|
175
|
+
def unexportable_time(time, path)
|
|
176
|
+
return if Coercion.whole_nanoseconds?(time)
|
|
177
|
+
|
|
178
|
+
"holds a Time at #{path} finer than a nanosecond, so the export publishes a different instant; round it, e.g. with .round(9)"
|
|
179
|
+
end
|
|
180
|
+
|
|
169
181
|
def permittable_violation(_field, param, code)
|
|
170
182
|
{ param: param, code: code.to_s }
|
|
171
183
|
end
|