From 2710ded1250dd125a7a36df97d9bf5009f2db291 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 18 Nov 2026 10:08:55 +0200 Subject: [PATCH 001/121] refactor!: rewrite the client for 2.0 2.0 replaces the internals of the gem and most of its surface. What 1.x did through method_missing and a mutable client is explicit, immutable and checked here. The calls that changed are listed in the changelog and in the README's migration guide. The client. Client.new takes keyword arguments and validates them into a Config before any request is made, and an unknown option raises. A client is immutable: with and on_behalf_of return a new one, so a single instance is safe to share between threads. Credentials are redacted wherever a config, a transport or an error can be printed, and more than one authentication scheme is refused. The transport. Requests carry timeouts by default. A read is retried with backoff on connection failures, timeouts and the transient statuses, and a write is never repeated. No Faraday exception or object escapes: every failure is a ZammadAPI::Error with a class per status, and a response is a ZammadAPI::Response. get, post, put and delete reach any endpoint the gem does not model. A query is written the way Rails reads it back, so a search condition with nested groups reaches Zammad as it was given, and one a query string cannot carry is refused before it is sent. Collections. ListBase, ListAll and ListSearch give way to Collection, a lazy Enumerable that walks every page instead of stopping at the first hundred records, with order, page, in_batches, find_each, count and pluck. A page size is clamped to what the endpoint serves. Records. Dispatcher gives way to ResourceProxy, reached through plural readers such as client.tickets; the singular ones remain as deprecated aliases. A resource declares what its endpoint does, and a class of the caller's own works through client.resource. Records track their changes and send only those, answer false from save on a validation failure, support pattern matching, and reach the records they point at through record.related. The toolchain moves with the code that needs it: Ruby 3.4 for the `it` block parameter, faraday-retry, the RuboCop configuration without its todo file, and a Rakefile that separates the unit specs from the ones that need a live Zammad. Those live specs move from spec/zammad_api to spec/integration and are rewritten for the new API, and as they create and delete records they run only against the Zammad that TEST_URL names: there is no default. The specs under spec/unit are new and need no Zammad. The version is 2.0.0.alpha1. The Rakefile's steep and rbs_published tasks have nothing to check until the signatures arrive, two commits on. --- .gitignore | 4 +- .overcommit.yml | 50 +- .rspec | 1 + .rubocop.yml | 156 +- .rubocop_todo.yml | 35 - .ruby-version | 1 + .yardopts | 9 + Gemfile | 30 +- Gemfile.lock | 96 +- Rakefile | 66 +- bin/console | 8 + bin/setup | 6 + examples/example_http_token.rb | 59 - lib/zammad_api.rb | 20 +- lib/zammad_api/associations.rb | 143 ++ lib/zammad_api/attribute_access.rb | 311 ++++ lib/zammad_api/client.rb | 527 +++++- lib/zammad_api/collection.rb | 813 +++++++++ lib/zammad_api/config.rb | 508 ++++++ lib/zammad_api/deep_copy.rb | 83 + lib/zammad_api/dispatcher.rb | 12 - lib/zammad_api/duplicate_keys.rb | 49 + lib/zammad_api/errors.rb | 195 +- lib/zammad_api/json_helper.rb | 11 - lib/zammad_api/list_all.rb | 11 - lib/zammad_api/list_base.rb | 84 - lib/zammad_api/list_search.rb | 11 - lib/zammad_api/log.rb | 18 - lib/zammad_api/query_encoder.rb | 162 ++ lib/zammad_api/resource_proxy.rb | 611 +++++++ lib/zammad_api/resources.rb | 26 +- lib/zammad_api/resources/base.rb | 1003 +++++++++- lib/zammad_api/resources/group.rb | 14 +- lib/zammad_api/resources/organization.rb | 14 +- lib/zammad_api/resources/ticket.rb | 116 +- lib/zammad_api/resources/ticket_article.rb | 53 +- .../resources/ticket_article_attachment.rb | 58 +- lib/zammad_api/resources/ticket_priority.rb | 12 +- lib/zammad_api/resources/ticket_state.rb | 12 +- lib/zammad_api/resources/user.rb | 29 +- lib/zammad_api/response.rb | 170 ++ lib/zammad_api/transport.rb | 1153 +++++++++++- lib/zammad_api/version.rb | 4 +- script/live_target.rb | 37 + spec/integration/authentication_spec.rb | 29 + .../resources => integration}/group_spec.rb | 30 +- .../organization_spec.rb | 46 +- .../ticket_priority_spec.rb | 32 +- .../resources => integration}/ticket_spec.rb | 41 +- .../ticket_state_spec.rb | 34 +- .../resources => integration}/user_spec.rb | 50 +- spec/spec_helper.rb | 106 +- spec/support/bare_socket_adapter.rb | 46 + spec/support/client_helper.rb | 29 + spec/support/integration_helper.rb | 147 ++ .../zammad_api/associations/proxy_spec.rb | 433 +++++ spec/unit/zammad_api/attribute_access_spec.rb | 394 ++++ spec/unit/zammad_api/client_spec.rb | 1141 ++++++++++++ spec/unit/zammad_api/collection_spec.rb | 1306 +++++++++++++ spec/unit/zammad_api/config_spec.rb | 683 +++++++ spec/unit/zammad_api/query_encoder_spec.rb | 180 ++ spec/unit/zammad_api/resource_proxy_spec.rb | 1069 +++++++++++ spec/unit/zammad_api/resources/base_spec.rb | 1513 +++++++++++++++ .../ticket_article_attachment_spec.rb | 152 ++ spec/unit/zammad_api/resources/ticket_spec.rb | 216 +++ spec/unit/zammad_api/response_error_spec.rb | 197 ++ spec/unit/zammad_api/response_spec.rb | 158 ++ spec/unit/zammad_api/transport_spec.rb | 1614 +++++++++++++++++ spec/zammad_api/client_spec.rb | 110 -- spec/zammad_api/errors_spec.rb | 164 -- spec/zammad_api/json_helper_spec.rb | 21 - spec/zammad_api/resources/list_base_spec.rb | 7 - spec/zammad_api/transport_spec.rb | 80 - spec/zammad_api_spec.rb | 36 - zammad_api.gemspec | 71 +- 75 files changed, 15729 insertions(+), 1197 deletions(-) delete mode 100644 .rubocop_todo.yml create mode 100644 .ruby-version create mode 100644 .yardopts create mode 100755 bin/console create mode 100755 bin/setup delete mode 100755 examples/example_http_token.rb create mode 100644 lib/zammad_api/associations.rb create mode 100644 lib/zammad_api/attribute_access.rb create mode 100644 lib/zammad_api/collection.rb create mode 100644 lib/zammad_api/config.rb create mode 100644 lib/zammad_api/deep_copy.rb delete mode 100644 lib/zammad_api/dispatcher.rb create mode 100644 lib/zammad_api/duplicate_keys.rb delete mode 100644 lib/zammad_api/json_helper.rb delete mode 100644 lib/zammad_api/list_all.rb delete mode 100644 lib/zammad_api/list_base.rb delete mode 100644 lib/zammad_api/list_search.rb delete mode 100644 lib/zammad_api/log.rb create mode 100644 lib/zammad_api/query_encoder.rb create mode 100644 lib/zammad_api/resource_proxy.rb create mode 100644 lib/zammad_api/response.rb create mode 100644 script/live_target.rb create mode 100644 spec/integration/authentication_spec.rb rename spec/{zammad_api/resources => integration}/group_spec.rb (83%) rename spec/{zammad_api/resources => integration}/organization_spec.rb (80%) rename spec/{zammad_api/resources => integration}/ticket_priority_spec.rb (75%) rename spec/{zammad_api/resources => integration}/ticket_spec.rb (84%) rename spec/{zammad_api/resources => integration}/ticket_state_spec.rb (84%) rename spec/{zammad_api/resources => integration}/user_spec.rb (86%) create mode 100644 spec/support/bare_socket_adapter.rb create mode 100644 spec/support/client_helper.rb create mode 100644 spec/support/integration_helper.rb create mode 100644 spec/unit/zammad_api/associations/proxy_spec.rb create mode 100644 spec/unit/zammad_api/attribute_access_spec.rb create mode 100644 spec/unit/zammad_api/client_spec.rb create mode 100644 spec/unit/zammad_api/collection_spec.rb create mode 100644 spec/unit/zammad_api/config_spec.rb create mode 100644 spec/unit/zammad_api/query_encoder_spec.rb create mode 100644 spec/unit/zammad_api/resource_proxy_spec.rb create mode 100644 spec/unit/zammad_api/resources/base_spec.rb create mode 100644 spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb create mode 100644 spec/unit/zammad_api/resources/ticket_spec.rb create mode 100644 spec/unit/zammad_api/response_error_spec.rb create mode 100644 spec/unit/zammad_api/response_spec.rb create mode 100644 spec/unit/zammad_api/transport_spec.rb delete mode 100644 spec/zammad_api/client_spec.rb delete mode 100644 spec/zammad_api/errors_spec.rb delete mode 100644 spec/zammad_api/json_helper_spec.rb delete mode 100644 spec/zammad_api/resources/list_base_spec.rb delete mode 100644 spec/zammad_api/transport_spec.rb delete mode 100644 spec/zammad_api_spec.rb diff --git a/.gitignore b/.gitignore index 002a2a1..bb396ef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ /.bundle/ -/.ruby-version -/.yardoc +/.steep/ +/.yardoc/ /_yardoc/ /coverage/ /doc/ diff --git a/.overcommit.yml b/.overcommit.yml index 8553cbe..740cb16 100644 --- a/.overcommit.yml +++ b/.overcommit.yml @@ -1,33 +1,23 @@ -# Use this file to configure the Overcommit hooks you wish to use. This will -# extend the default configuration defined in: -# https://github.com/sds/overcommit/blob/master/config/default.yml +# See https://github.com/sds/overcommit#configuration # -# At the topmost level of this YAML file is a key representing type of hook -# being run (e.g. pre-commit, commit-msg, etc.). Within each type you can -# customize each hook, such as whether to only run it on certain files (via -# `include`), whether to only display output if it fails (via `quiet`), etc. -# -# For a complete list of hooks, see: -# https://github.com/sds/overcommit/tree/master/lib/overcommit/hook -# -# For a complete list of options that you can use to customize hooks, see: -# https://github.com/sds/overcommit#configuration -# -# Uncomment the following lines to make the configuration take effect. +# Install with: bundle exec overcommit --install PreCommit: - RuboCop: - enabled: true - on_warn: fail # Treat all warnings as failures -# -# TrailingWhitespace: -# enabled: true -# exclude: -# - '**/db/structure.sql' # Ignore trailing whitespace in generated files -# -#PostCheckout: -# ALL: # Special hook name that customizes all hooks of this type -# quiet: true # Change all post-checkout hooks to only display output on failure -# -# IndexTags: -# enabled: true # Generate a tags file with `ctags` each time HEAD changes + RuboCop: + enabled: true + on_warn: fail # Treat all warnings as failures + command: ['bundle', 'exec', 'rubocop'] + + TrailingWhitespace: + enabled: true + + YamlSyntax: + enabled: true + + BundleCheck: + enabled: true + + RSpec: + enabled: true + description: 'Run the unit specs' + command: ['bundle', 'exec', 'rspec', 'spec/unit'] diff --git a/.rspec b/.rspec index 8c18f1a..7a2cc1a 100644 --- a/.rspec +++ b/.rspec @@ -1,2 +1,3 @@ +--require spec_helper --format documentation --color diff --git a/.rubocop.yml b/.rubocop.yml index 0ae18f9..f6254f4 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,117 +1,99 @@ -# Default enabled cops -# https://github.com/bbatsov/rubocop/blob/master/config/enabled.yml - plugins: - rubocop-performance - rubocop-rake - rubocop-rspec -inherit_from: - - .rubocop_todo.yml - AllCops: NewCops: enable Exclude: - - 'bin/rails' - - 'bin/rake' - - 'bin/spring' - - 'db/schema.rb' - - 'examples/**/*' - # Match the Ruby version specified in the gemspec. - TargetRubyVersion: 3.0 + - 'pkg/**/*' + - 'vendor/**/*' + # Keep in sync with required_ruby_version in the gemspec and the CI matrix. + TargetRubyVersion: 3.4 -# Zammad StyleGuide - -Style/FrozenStringLiteralComment: - Enabled: false +# --- Zammad style guide ----------------------------------------------------- Style/NegatedIf: - Description: >- - Favor unless over if for negative conditions - (or control flow or). - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#unless-for-negatives' + Description: 'Zammad prefers an explicit `if !x` over `unless x`.' Enabled: false Style/IfUnlessModifier: - Description: >- - Favor modifier if/unless usage when you have a - single-line body. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier' + Description: 'Zammad allows multi-line bodies for a single condition.' Enabled: false Style/TrailingCommaInArrayLiteral: - Description: 'Checks for trailing comma in array literals.' - StyleGuide: '#no-trailing-array-commas' Enabled: false Style/TrailingCommaInHashLiteral: - Description: 'Checks for trailing comma in hash literals.' Enabled: false Style/TrailingCommaInArguments: - Description: 'Checks for trailing comma in argument lists.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas' Enabled: false Layout/LeadingCommentSpace: - Description: 'Comments should start with a space.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#hash-space' Enabled: false Layout/HashAlignment: - Description: >- - Align the elements of a hash literal if they span more than - one line. Enabled: true EnforcedHashRocketStyle: table EnforcedColonStyle: table EnforcedLastArgumentHashStyle: always_inspect Style/ClassAndModuleChildren: - Description: 'Checks style of children classes and modules.' Enabled: false +Naming/PredicatePrefix: + # `has_many` is the established name for the declaration, and neither it nor + # the reader behind it is a predicate. + AllowedMethods: + - has_many + - has_many_target + Naming/MethodParameterName: - Description: >- - Checks for method parameter names that contain capital letters, - end in numbers, or do not meet a minimal length. - Enabled: true - AllowedNames: [id] + # `of` is ActiveRecord's name for a batch size, see Collection#in_batches. + AllowedNames: [id, to, of] Layout/MultilineMethodCallIndentation: - Description: >- - Checks the indentation of the method name part in method calls - that span more than one line. EnforcedStyle: indented Style/RescueStandardError: EnforcedStyle: implicit +Style/ArgumentsForwarding: + # Named parameters keep public signatures self-documenting for YARD/RBS. + UseAnonymousForwarding: false + +Naming/BlockForwarding: + EnforcedStyle: explicit + +Naming/PredicateMethod: + # Established names from the resource API. `save` reports whether the record + # was stored; the rest return true on success. + AllowedMethods: + - save + - save! + - update + - update! + - destroy + Style/Documentation: + Description: 'Public API documentation is enforced by review, not by this cop.' Enabled: false Style/PerlBackrefs: - Description: 'Avoid Perl-style regex back references.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-perl-regexp-last-matchers' Enabled: false Style/BlockComments: - # Keep block comments (=begin ... =end) to allow for easy copy-pasting of examples. - Description: 'Do not use block comments.' + Description: 'Block comments make examples easy to copy and paste.' Enabled: false Layout/LineLength: - Description: 'Limit lines to 80 characters.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#80-character-limits' Enabled: false Metrics/ClassLength: - Description: 'Avoid classes longer than 100 lines of code.' Enabled: false Metrics/MethodLength: - Description: 'Avoid methods longer than 10 lines of code.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#short-methods' Enabled: false Metrics/AbcSize: @@ -123,21 +105,61 @@ Metrics/CyclomaticComplexity: Metrics/PerceivedComplexity: Max: 12 +Metrics/ParameterLists: + # Config mirrors every supported option as a keyword argument. + Max: 16 + MaxOptionalParameters: 15 + +# Broken: "String".downcase == "strinG".downcase is not the same as +# "String".casecmp("strinG"), only as "String".casecmp("strinG") == 0. +Performance/Casecmp: + Enabled: false + +# --- Specs ------------------------------------------------------------------ + RSpec/ExampleLength: - inherit_mode: - merge: - - Exclude - CountAsOne: - - 'array' - - 'hash' - - 'heredoc' - Max: 25 + CountAsOne: ['array', 'hash', 'heredoc'] + Max: 12 + # Integration specs are end-to-end scenarios against a live Zammad. + Exclude: + - 'spec/integration/**/*' + +RSpec/MultipleExpectations: + Description: 'A few request assertions per example are clearer than splitting them.' + Max: 3 + Exclude: + - 'spec/integration/**/*' + +RSpec/DescribeMethod: + Exclude: + - 'spec/integration/**/*' RSpec/NestedGroups: - Max: 6 + Max: 4 -# Broken!!!! Generates broken code since "String".downcase == "strinG".downcase is not equals "String".casecmp("strinG") but "String".casecmp("strinG") == 0 !!! -Performance/Casecmp: - Description: 'Use `casecmp` rather than `downcase ==`.' - Reference: 'https://github.com/JuanitoFatas/fast-ruby#stringcasecmp-vs-stringdowncase---code' - Enabled: false +RSpec/SpecFilePathFormat: + # Integration specs are grouped by the Zammad object they exercise, not by + # the class under test. + Exclude: + - 'spec/integration/**/*' + +RSpec/DescribeClass: + Exclude: + - 'spec/integration/**/*' + +RSpec/BeforeAfterAll: + Exclude: + - 'spec/integration/**/*' + +RSpec/LeakyLocalVariable: + # The integration specs deliberately share a record across ordered examples: + # each one asserts on what the previous step left behind. The coupling is + # pinned by `config.order = :defined` and every example that reads the record + # goes through `established!`, so a partial run says what is missing rather + # than failing on nil. + Exclude: + - 'spec/integration/**/*' + +RSpec/NoExpectationExample: + Exclude: + - 'spec/integration/**/*' diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml deleted file mode 100644 index 20ec1c6..0000000 --- a/.rubocop_todo.yml +++ /dev/null @@ -1,35 +0,0 @@ -Naming/PredicateMethod: - Enabled: false - -Style/MissingRespondToMissing: - Enabled: false - -Style/StringConcatenation: - Enabled: false - -Naming/AccessorMethodName: - Enabled: false - -RSpec/MultipleExpectations: - Enabled: false - -RSpec/ExampleLength: - Enabled: false - -RSpec/SpecFilePathFormat: - Enabled: false - -RSpec/NoExpectationExample: - Enabled: false - -RSpec/DescribeMethod: - Enabled: false - -RSpec/ContextWording: - Enabled: false - -RSpec/BeforeAfterAll: - Enabled: false - -RSpec/LeakyLocalVariable: - Enabled: false diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..7919852 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +4.0.9 diff --git a/.yardopts b/.yardopts new file mode 100644 index 0000000..04abe42 --- /dev/null +++ b/.yardopts @@ -0,0 +1,9 @@ +--markup markdown +--readme README.md +--output-dir doc +--no-private +--protected +lib/**/*.rb +- +CHANGELOG.md +LICENSE.md diff --git a/Gemfile b/Gemfile index 2d9e06b..2d37c5e 100644 --- a/Gemfile +++ b/Gemfile @@ -1,17 +1,25 @@ +# frozen_string_literal: true + source 'https://rubygems.org' -# runtime dependencies are defined in zammad_api.gemspec +# Runtime dependencies are defined in zammad_api.gemspec. gemspec -# development dependencies group :development, :test do - gem 'bundler', '>= 2.2.10' - gem 'overcommit' - gem 'rake' - gem 'rspec' - gem 'rubocop' - gem 'rubocop-performance' - gem 'rubocop-rake' - gem 'rubocop-rspec' - gem 'webmock' + gem 'overcommit', require: false + gem 'rake', require: false + gem 'rspec', '~> 3.13' + gem 'rubocop', require: false + gem 'rubocop-performance', require: false + gem 'rubocop-rake', require: false + gem 'rubocop-rspec', require: false + gem 'simplecov', '~> 1.3', require: false + gem 'webmock', '~> 3.26' + gem 'yard', require: false +end + +group :development do + # Static type checking against the signatures in sig/. + gem 'rbs', require: false + gem 'steep', require: false end diff --git a/Gemfile.lock b/Gemfile.lock index 2b5b4f8..901d23a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,8 +1,9 @@ PATH remote: . specs: - zammad_api (1.3.1) - faraday (~> 2) + zammad_api (2.0.0.alpha1) + faraday (~> 2.9) + faraday-retry (~> 2.2) GEM remote: https://rubygems.org/ @@ -13,9 +14,11 @@ GEM bigdecimal (4.1.3) childprocess (5.1.0) logger (~> 1.5) + concurrent-ruby (1.3.8) crack (1.0.1) bigdecimal rexml + csv (3.3.7) diff-lcs (1.6.2) faraday (2.15.1) faraday-net_http (>= 2.0, < 3.6) @@ -23,11 +26,29 @@ GEM logger faraday-net_http (3.5.0) net-http (~> 0.5) + faraday-retry (2.4.0) + faraday (~> 2.0) + ffi (1.17.4) + ffi (1.17.4-aarch64-linux-gnu) + ffi (1.17.4-aarch64-linux-musl) + ffi (1.17.4-arm-linux-gnu) + ffi (1.17.4-arm-linux-musl) + ffi (1.17.4-arm64-darwin) + ffi (1.17.4-x86-linux-gnu) + ffi (1.17.4-x86-linux-musl) + ffi (1.17.4-x86_64-darwin) + ffi (1.17.4-x86_64-linux-gnu) + ffi (1.17.4-x86_64-linux-musl) + fileutils (1.8.1) hashdiff (1.3.0) iniparse (1.5.0) json (3.1.0) language_server-protocol (3.17.0.6) lint_roller (1.1.0) + listen (3.10.1) + logger + rb-fsevent (~> 0.10, >= 0.10.3) + rb-inotify (~> 0.9, >= 0.9.10) logger (1.7.0) net-http (0.10.0) net-protocol (>= 0.3.0) @@ -38,30 +59,45 @@ GEM childprocess (>= 5.0.0, < 6) iniparse (~> 1.4) rexml (>= 3.4.2) - parallel (1.28.0) + parallel (2.3.0) parser (3.3.14.0) ast (~> 2.4.1) racc prism (2.1.0) - public_suffix (6.0.2) + prism (2.1.0-aarch64-linux-gnu) + prism (2.1.0-aarch64-linux-musl) + prism (2.1.0-arm-linux-gnu) + prism (2.1.0-arm-linux-musl) + prism (2.1.0-arm64-darwin) + prism (2.1.0-x86_64-darwin) + prism (2.1.0-x86_64-linux-gnu) + prism (2.1.0-x86_64-linux-musl) + public_suffix (7.0.5) racc (1.8.1) rainbow (3.1.1) rake (13.4.2) + rb-fsevent (0.11.2) + rb-inotify (0.11.1) + ffi (~> 1.0) + rbs (4.2.0) + logger + prism (>= 1.6.0) + tsort regexp_parser (2.13.4) rexml (3.4.4) rspec (3.13.2) rspec-core (~> 3.13.0) rspec-expectations (~> 3.13.0) rspec-mocks (~> 3.13.0) - rspec-core (3.13.6) + rspec-core (3.13.7) rspec-support (~> 3.13.0) - rspec-expectations (3.13.5) + rspec-expectations (3.13.6) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) - rspec-mocks (3.13.8) + rspec-mocks (3.13.9) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) - rspec-support (3.13.7) + rspec-support (3.13.8) rubocop (1.92.3) json (>= 2.3) language_server-protocol (~> 3.17.0.2) @@ -90,7 +126,29 @@ GEM regexp_parser (>= 2.0) rubocop (~> 1.86, >= 1.86.2) ruby-progressbar (1.13.0) + securerandom (0.4.1) + simplecov (1.3.2) + steep (2.1.0) + concurrent-ruby (>= 1.1.10) + csv (>= 3.0.9) + fileutils (>= 1.1.0) + json (>= 2.1.0) + language_server-protocol (>= 3.17.0.4, < 4.0) + listen (~> 3.0) + logger (>= 1.3.0) + parser (>= 3.2) + prism (>= 0.25.0) + rainbow (>= 2.2.2, < 4.0) + rbs (~> 4.2) + securerandom (>= 0.1) + strscan (>= 1.0.0) + terminal-table (>= 2, < 5) + uri (>= 0.12.0) + strscan (3.1.8) + terminal-table (4.0.0) + unicode-display_width (>= 1.1.1, < 4) timeout (0.6.1) + tsort (0.2.0) unicode-display_width (3.3.0) unicode-emoji (~> 4.3) unicode-emoji (4.3.0) @@ -99,21 +157,35 @@ GEM addressable (>= 2.8.0) crack (>= 0.3.2) hashdiff (>= 0.4.0, < 2.0.0) + yard (0.9.45) PLATFORMS + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + arm64-darwin ruby + x86-linux-gnu + x86-linux-musl + x86_64-darwin + x86_64-linux-gnu + x86_64-linux-musl DEPENDENCIES - bundler (>= 2.2.10) overcommit rake - rspec + rbs + rspec (~> 3.13) rubocop rubocop-performance rubocop-rake rubocop-rspec - webmock + simplecov (~> 1.3) + steep + webmock (~> 3.26) + yard zammad_api! BUNDLED WITH - 2.6.9 + 4.0.20 diff --git a/Rakefile b/Rakefile index 4c774a2..756f246 100644 --- a/Rakefile +++ b/Rakefile @@ -1,6 +1,68 @@ +# frozen_string_literal: true + require 'bundler/gem_tasks' +require 'fileutils' require 'rspec/core/rake_task' +require 'rubocop/rake_task' +require_relative 'script/live_target' + +namespace :spec do + desc 'Run the unit specs (no Zammad instance required)' + RSpec::Core::RakeTask.new(:unit) do |task| + task.pattern = 'spec/unit/**/*_spec.rb' + end + + desc 'Run the integration specs against the Zammad that TEST_URL names' + RSpec::Core::RakeTask.new(integration: :live_target) do |task| + task.pattern = 'spec/integration/**/*_spec.rb' + end +end + +desc 'Run all specs' +task spec: [:live_target, 'spec:unit', 'spec:integration'] + +# The integration specs and check_connection create and delete records, so +# neither has a default for where. Asked here as well as in each of them, so +# that a task which was asked to run against a live Zammad says why it did +# not rather than passing over specs that were left out. +desc 'Check that TEST_URL names the Zammad to run the live checks against' +task :live_target do + abort LiveTarget.unset_message('This task') if LiveTarget.url.nil? +end + +desc 'Drive the Zammad that TEST_URL names end to end with this gem' +task check_connection: :live_target do + sh 'ruby script/check_connection.rb' +end + +RuboCop::RakeTask.new + +desc 'Type-check lib/ against the signatures in sig/' +task :steep do + sh 'bundle exec steep check' +end + +# sig/vendor stands in for dependencies that ship no signatures and is kept +# out of the gem, so the published set has to hold up without it. Naming a +# Faraday type in a published signature made `rbs validate` fail for every +# consumer, and nothing in this repo noticed, because sig/vendor is always +# on the load path here. +desc 'Check that the signatures the gem ships validate without sig/vendor' +task :rbs_published do + require 'tmpdir' -RSpec::Core::RakeTask.new(:spec) + Dir.mktmpdir do |dir| + published = Dir['sig/**/*.rbs'].grep_v(%r{\Asig/vendor/}) + published.each do |file| + target = File.join(dir, file) + FileUtils.mkdir_p(File.dirname(target)) + FileUtils.cp(file, target) + end + # `logger` is the only library the published signatures name, and it is a + # standard one RBS ships declarations for, so a consumer already has it. + sh "bundle exec rbs -r logger -I #{File.join(dir, 'sig')} validate" + end +end -task default: :spec +desc 'Run everything that does not need a Zammad instance' +task default: ['spec:unit', :rubocop, :steep, :rbs_published] diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..dcbd7d1 --- /dev/null +++ b/bin/console @@ -0,0 +1,8 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require 'bundler/setup' +require 'zammad_api' +require 'irb' + +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..bc8f0ad --- /dev/null +++ b/bin/setup @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +bundle install +bundle exec overcommit --install diff --git a/examples/example_http_token.rb b/examples/example_http_token.rb deleted file mode 100755 index 5cf5803..0000000 --- a/examples/example_http_token.rb +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env ruby - -$LOAD_PATH << './lib' -require 'rubygems' -require 'zammad_api' - -client = ZammadAPI::Client.new( - url: 'https://you.zammad.com/', - http_token: 'XXXX', -) - -# create ticket -ticket = client.ticket.new( - title: 'some new title', - state: 'new', - priority: '2 normal', - owner: '-', - customer: 'nicole.braun@zammad.org', - group: 'Users', - article: { - sender: 'Customer', - type: 'note', - subject: 'some subject', - content_type: 'text/plain', - body: "some body\nnext line", - } -) -ticket.save - -p '--------------------------------------------------------' -p "Ticket has been created: #{ticket.number} - #{ticket.title} at #{ticket.created_at}" -p " Attributes: #{ticket.attributes.inspect}" - -# get ticket -p '--------------------------------------------------------' -ticket = client.ticket.find(ticket.id) -p "Ticket found on server: #{ticket.number} - #{ticket.title} at #{ticket.created_at}" -p " Attributes: #{ticket.attributes.inspect}" - -# get articles of ticket -p '--------------------------------------------------------' -articles = ticket.articles -p "Total #{articles.length} articles" - -# create article -p '--------------------------------------------------------' -article = ticket.article( - type: 'note', - subject: 'some subject 2', - body: 'some body 2', -) -p "Article has been created: #{article.subject} at #{article.created_at}" -p " Attributes: #{article.attributes.inspect}" - -# get articles of ticket -p '--------------------------------------------------------' -articles = ticket.articles -p "Total #{articles.length} articles now" -p '--------------------------------------------------------' diff --git a/lib/zammad_api.rb b/lib/zammad_api.rb index 608477d..4e1a126 100644 --- a/lib/zammad_api.rb +++ b/lib/zammad_api.rb @@ -1,6 +1,20 @@ -require 'zammad_api/version' -require 'zammad_api/errors' -require 'zammad_api/client' +# frozen_string_literal: true +require_relative 'zammad_api/version' +require_relative 'zammad_api/errors' +require_relative 'zammad_api/deep_copy' +require_relative 'zammad_api/config' +require_relative 'zammad_api/response' +require_relative 'zammad_api/transport' +require_relative 'zammad_api/attribute_access' +require_relative 'zammad_api/associations' +require_relative 'zammad_api/collection' +require_relative 'zammad_api/resources' +require_relative 'zammad_api/resource_proxy' +require_relative 'zammad_api/client' + +# Ruby client for the Zammad API v1.0. +# +# @see Client module ZammadAPI end diff --git a/lib/zammad_api/associations.rb b/lib/zammad_api/associations.rb new file mode 100644 index 0000000..31fa295 --- /dev/null +++ b/lib/zammad_api/associations.rb @@ -0,0 +1,143 @@ +# frozen_string_literal: true + +require_relative 'errors' +require_relative 'transport' + +module ZammadAPI + # Readers for the records a record points at. + module Associations + # Fetches the records an association points at. + # + # Reached through +record.related+, never built directly. The readers live + # here rather than on the record itself because Zammad already expands an + # association into a name: +ticket.customer+ is the customer's login and + # +ticket.state+ is +"open"+, both free of charge. An association reader + # returns the whole record and costs a request, so it is worth telling the + # two apart at the call site. + # + # @example + # ticket = client.tickets.find(1) + # + # ticket.customer # => "customer@example.com", already loaded + # ticket.related.customer # => the User record, one request + # ticket.related.customer.email # => "customer@example.com" + # + # ticket.related.articles # => [TicketArticle, ...] + class Proxy + # @api private + # @param record [Resources::Base] + def initialize(record) + @record = record + @cache = {} + end + + def inspect + "#<#{Proxy.name} #{@record.class.name} id=#{@record.id.inspect} #{@record.class.associations.keys.join(', ')}>" + end + + private + + # Memoized: the record an id points at does not change under the caller, + # and an unmemoized reader would turn a loop over tickets into a request + # per ticket per mention. The record empties the memo through + # {#forget_targets} when what it was resolved from may no longer hold. + # + # What is resolved goes into the memo this call began with, not the one + # that is current once the request is back. They differ where the + # record was written to while the request was out - by a logger or a + # middleware of the caller's that reaches the record, or by another + # thread - and {#forget_targets} has swapped the memo for an empty one. + # Written to the current memo, the user fetched for `customer_id` 7 + # became the memoized answer for a record that by then says 9, and + # stayed it until the next write. + def belongs_to_target(name, class_name, foreign_key) + refuse_destroyed!(name) + memo = @cache + return memo[name] if memo.key?(name) + + id = @record[foreign_key] + # {Resources::Base.fetch_one} rather than a ResourceProxy built for the + # one call: {Client#setup} builds and freezes one proxy per resource so + # that callers get one proxy per resource, and a reader here that built + # a fresh one per association turned a walk over ten thousand tickets + # reading two associations each into twenty thousand objects that exist + # for a single method call. It is the read {ResourceProxy#find} makes + # too, so there is one of it rather than one here and one there. + memo[name] = id.nil? ? nil : resolve(class_name).fetch_one(@record.transport, id) + end + + # Deliberately not memoized: a list can grow while the record is held, + # and +ticket.related.articles+ after +ticket.add_article(...)+ has to show + # the article that was just added. + # + # The path proc is handed the escaped id rather than the record, so that + # a declaration cannot paste a raw id into a path. One that did resolved + # `related.articles` on a record carrying `id: "1/../../users"` onto the + # users endpoint, the same way an unescaped {Resources::Base#member_path} + # used to - and a proc is exactly where that is easy to forget. + def has_many_target(name, class_name, path) + refuse_destroyed!(name) + raise Error, "#{@record.class.name} has no id, so it has no #{name} to read; save it first" if @record.id.nil? + + target_class = resolve(class_name) + operation = "get #{name}" + + response = @record.transport.get( + path.call(Transport.escape_path_segment(@record.id)), + operation: operation, + resource_class: target_class, + query: { expand: true } + ) + records = response.decoded(:array, operation: operation, resource_class: target_class) + records.map { target_class.from_response(@record.transport, it) } + end + + # Drops every resolved target, so that the next read fetches it again. + # + # Called by the record, which keeps one proxy for as long as it lives + # and empties it on a save, a reload, a destroy and a write to a foreign + # key. It used to drop the proxy and build another on the next call to + # {Resources::Base#related}, which reached only the callers that asked + # again: `related = ticket.related`, the natural thing to write before + # reading two associations, kept the proxy that had been dropped, and + # after `ticket.customer_id = 9` or a reload `related.customer` went on + # answering with the user it had resolved before. A memo can only be + # emptied where it is held, so it is emptied here. + # + # Replaced rather than cleared, so that a lookup still on the wire has + # nowhere to put what it resolved from the value before: see + # {#belongs_to_target}. + def forget_targets + @cache = {} + end + + # Refuses to read through a record that was destroyed. + # + # {Resources::Base#related} asks the same question, but a proxy handed + # out before the destroy is already past that door: it answered from + # its memo, and `articles` requested the articles of a ticket that is + # gone. + def refuse_destroyed!(name) + return if !@record.destroyed? + + raise Error, "#{@record.class.name} #{@record.id} was destroyed, there is nothing to read #{name} from" + end + + # The target is named rather than referenced so that resources may point + # at each other without a load order between their files. The name comes + # from a declaration in code - this gem's, or a resource class a caller + # wrote - and never from data. + # + # A resource of this gem is named on its own, +'User'+, and wins: an + # application is likely to have a +User+ of its own at the top level, + # and that is not what a ticket's customer is. Any other name is read + # from the top level, so that a resource a caller declares can point at + # another of theirs: +belongs_to :role, class_name: 'Acme::Role'+. + def resolve(class_name) + return Resources.const_get(class_name, false) if Resources.const_defined?(class_name, false) + + Object.const_get(class_name) + end + end + end +end diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb new file mode 100644 index 0000000..22e82d7 --- /dev/null +++ b/lib/zammad_api/attribute_access.rb @@ -0,0 +1,311 @@ +# frozen_string_literal: true + +require 'json' + +require_relative 'deep_copy' + +module ZammadAPI + # Read access to a Zammad record's attributes. + # + # Zammad objects can carry administrator-defined custom attributes, so the + # set of readable attributes is not known ahead of time and is resolved + # through +method_missing+. A reader for an attribute the record does not + # carry raises +NoMethodError+; {#[]}, {#fetch} with a default, and {#key?} + # are the readers for an attribute that may be absent. + # + # This also carries the object protocols a record is expected to answer: + # {#==} and {#hash} identify a record by its id and the Zammad it came + # from, {#deconstruct_keys} makes + # one matchable with +case/in+, and {#to_json} serializes its attributes. + module AttributeAccess + # Suffixes that mark a method call as a predicate or bang method rather + # than an attribute, so that typos like +save!+ still raise NoMethodError. + NON_ATTRIBUTE_SUFFIXES = %w[! ?].freeze + + # What a writer for an attribute is named: a plain identifier and an `=`. + # + # Ending in `=` is not enough, because Ruby's operators do too. `record[:x] + # = 1` reaches `method_missing` as `:[]=` and used to stage an attribute + # literally called `[]` whose value was the index - the write was lost, no + # error was raised, and the next `save` sent `{"[]": "x"}` to Zammad. + # `record <= 5` did the same for an attribute called `<`. + ATTRIBUTE_WRITER = /\A[a-zA-Z_]\w*=\z/ + private_constant :ATTRIBUTE_WRITER + + # All known attributes, deeply frozen. + # + # Writing through this hash would change what the record reports without + # staging a change, so the next +save+ would not send it. {#to_h} returns a + # copy that is safe to modify; an attribute writer is the way to stage one. + # + # @return [Hash{Symbol => Object}] + attr_reader :attributes + + # @param key [Symbol, String] + # @return [Object, nil] + def [](key) = attributes[key.to_sym] + + # Stages an attribute by name, the writer matching {#[]}. + # + # Defined rather than left to `method_missing`, which saw `:[]=` as a + # writer for an attribute called `[]` and staged the index as its value. + # A read-only record refuses this the way it refuses any other write, and + # {#respond_to?} says so before it is called. + # + # @param key [Symbol, String] + # @param value [Object] + # @return [Object] the staged value + # @raise [Error] when the attribute cannot be staged, such as +id+, or + # when the record was destroyed + # @raise [NoMethodError] when the record is read-only + def []=(key, value) + write_attribute(key.to_sym, value) + end + + # @param key [Symbol, String] + # @param default [Object] returned instead of raising + # @yieldparam key [Symbol] called instead of raising + # @return [Object] + # @raise [ArgumentError] when more than one fallback was given + # @raise [KeyError] when the attribute is absent and no fallback was given + def fetch(key, *default) + # Hash#fetch refuses a third argument, and so does this: collecting the + # fallback with a splat and reading `default.first` accepted + # `fetch(:a, :b, :c)` - a multi-key read that this has never been - and + # answered it with `:b`. A method whose whole point is that a missing + # attribute is an error has no business swallowing a mistyped call. + raise ArgumentError, "wrong number of arguments (given #{default.size + 1}, expected 1..2)" if default.size > 1 + + # Hash#fetch warns for this and then ignores the default, so this does + # too rather than silently picking one of the two fallbacks a caller + # cannot have meant to pass together. + # + # `uplevel` so that this reads like the warning it mirrors: Hash#fetch + # names the line that made the call, and a bare Kernel#warn named + # nothing at all - neither the call site nor the library it came from, + # which in an application with several such calls is everything the + # reader needs. Kernel#warn writes the `warning: ` prefix itself when + # given `uplevel`, so the message must not carry its own. + # + # Nothing here has to consult $VERBOSE. Kernel#warn is already silent + # when warnings are off, so `ruby -W0` and `$VERBOSE = nil` quiet this + # the same way they quiet Hash#fetch's own warning. + warn('block supersedes default value argument', uplevel: 1) if block_given? && !default.empty? + + symbol = key.to_sym + # An explicit &block argument cannot be resolved against Hash#fetch's + # overloads by the type checker, so the block is forwarded with yield. + # rubocop:disable-next Style/ExplicitBlockArgument + return attributes.fetch(symbol) { |missing| yield(missing) } if block_given? + return attributes.fetch(symbol, default.first) if !default.empty? + + attributes.fetch(symbol) + end + + # @return [Boolean] + def key?(key) = attributes.key?(key.to_sym) + + # @return [Hash{Symbol => Object}] a deep copy of all attributes, safe to + # modify + def to_h = deep_dup(attributes) + + # @return [Integer, nil] + def id = attributes[:id] + + # Enables Ruby pattern matching against a record's attributes. + # + # @example + # case client.tickets.find(1) + # in {state: 'closed'} + # nil + # in {state: String => state, priority: '3 high'} + # escalate(state) + # end + # + # @param keys [Array, nil] the keys the pattern asks for + # @return [Hash{Symbol => Object}] + def deconstruct_keys(keys) = keys.nil? ? attributes : attributes.slice(*keys) + + # Whether +other+ is the same Zammad record: the same class, carrying the + # same id, read from the same Zammad. + # + # The last of those is the URL the client was configured with. An id is + # only unique within one installation, and a script that reads two of + # them - a migration, a sync - holds ticket 1 of each: compared by class + # and id alone they were one record, so `uniq` dropped one of the two and + # a Hash keyed by record handed back the other instance's value. Two + # clients for one URL, or one client and its {Client#on_behalf_of} scope, + # still read the same record. + # + # A record with no id is equal only to itself, because two unsaved records + # are two records waiting to be created however alike their attributes + # are. That also means the first save of a record changes its {#hash}, so + # one used as a Hash key before being saved has to be rehashed after. + # + # @example + # client.tickets.find(1) == client.tickets.find(1) # => true + # [client.tickets.find(1), client.tickets.find(1)].uniq.size # => 1 + # + # @param other [Object] + # @return [Boolean] + def ==(other) + return true if equal?(other) + return false if !other.instance_of?(self.class) + + # The steep:ignore is for `installation`, which is protected: RBS has + # no word for that, so the signature declares it private. + !id.nil? && other.id == id && other.installation == installation # steep:ignore NoMethod + end + alias eql? == + + # Consistent with {#==}, so that records can be deduplicated with +uniq+, + # collected in a +Set+ and used as Hash keys. + # + # The class is part of the digest because an id is only unique within one + # kind of record: ticket 1 and user 1 are different records. The + # installation is part of it for the same reason one level up. + # + # @return [Integer] + def hash + id.nil? ? super : [self.class, installation, id].hash + end + + # The attributes, for a JSON encoder. + # + # Named the way ActiveSupport and its encoders expect, so that a record + # nested inside a structure being serialized renders as its attributes. + # + # @return [Hash{Symbol => Object}] + def as_json(*) = to_h + + # Without this, a record would serialize as its +to_s+, because that is + # what +Object#to_json+ falls back to. + # + # @example + # client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}" + # + # @param state [JSON::State, nil] passed by +JSON.generate+ when a record + # is nested in a structure it is serializing + # @return [String] the attributes as a JSON object + def to_json(state = nil) = to_h.to_json(state) + + def method_missing(name, *args) + identifier = name.to_s + return super if NON_ATTRIBUTE_SUFFIXES.any? { identifier.end_with?(it) } + return write_attribute(identifier.delete_suffix('=').to_sym, args.first) if ATTRIBUTE_WRITER.match?(identifier) + return attributes[name] if attributes.key?(name) + + # An attribute the record does not carry used to read as nil, which made + # `ticket.titel` a silent nil that flowed on into whatever was written + # with it - and left this module the one place in the gem that answers a + # question it cannot answer instead of saying so. It also put + # `respond_to?` and the call itself at odds: `respond_to?(:titel)` was + # false and `method(:titel)` raised NameError while `ticket.titel` + # worked, so generic code that asks before it calls - a serializer, a + # delegator, `try` - was told the reader did not exist. + # + # Built rather than left to `super`, so that the message can name what + # to reach for instead, while `name` and `receiver` stay what a bare + # NoMethodError would have carried. + # + # The steep:ignore is for `name`: NameError.new takes a Symbol there and + # NoMethodError#name answers with one, while the core signature + # describes the parameter as a String. + raise NoMethodError.new(unknown_attribute_message(name), name, args, receiver: self) # steep:ignore ArgumentTypeMismatch + end + + # `[]=` is a defined method, so `respond_to_missing?` never sees it and a + # read-only record answered true for the one writer it has while answering + # false for every named one - then raised NoMethodError when it was called. + # That is the invariant the writer branch below is conditional for: generic + # code asks before it writes, and a record that claims a writer it would + # refuse leads it straight into the exception it was checking to avoid. + # + # Compared as a String, because `respond_to?` takes either spelling and + # Ruby does not normalise the argument before it reaches here. Compared to + # the Symbol alone, `respond_to?('[]=')` fell through to the definition + # and answered true on a record that refuses every write - the same wrong + # answer this method exists to prevent, reached by the other spelling. + # rubocop:disable-next Style/OptionalBooleanParameter -- Ruby's own signature + def respond_to?(name, include_private = false) + return writable_attributes? if name.to_s == '[]=' + + super + end + + def respond_to_missing?(name, include_private = false) + identifier = name.to_s + return false if NON_ATTRIBUTE_SUFFIXES.any? { identifier.end_with?(it) } + # Not an unconditional true: a read-only record that claimed a writer and + # then raised NoMethodError when one was called would defeat the point of + # asking, and lead generic code - serializers, form binders, + # assign_attributes loops - straight into the exception it was checking + # to avoid. + return writable_attributes? && attribute_writable?(identifier.delete_suffix('=').to_sym) if ATTRIBUTE_WRITER.match?(identifier) + + attributes.key?(name) || super + end + + protected + + # Which Zammad this record was read from, for {#==} and {#hash}. + # + # Overridden by the records that hold a transport, with the URL it is + # configured for. That is the URL as it was written, not the host it + # resolves to, so two spellings of one instance count as two: nothing + # here can know better, and telling one installation apart from itself + # only costs a duplicate, where taking two for one loses a record. + # + # Protected, because it is asked of the other record and of nobody else. + # + # @return [String, nil] nil for a record that has no transport + def installation = nil + + private + + # Why an attribute is missing is worth saying, because the two reasons + # lead somewhere quite different: a name that is simply wrong, and a + # record Zammad served less of than it holds. The second is the same fact + # {Resources::Base#no_id_message} and {Resources::Base#write_attribute} + # are written around - Zammad reduces the object it serializes for a + # client whose user may not see the whole record - and it is not + # something the spelling of the call can show. + def unknown_attribute_message(name) + # Sorted by the name rather than by the key, because a key that could + # not become a Symbol is left as it arrived - {DeepCopy.symbolize} says + # so - and `[:name, 1].sort` raises, which would replace this message + # with an ArgumentError from inside the method that explains it. + carried = attributes.keys.sort_by(&:to_s).join(', ') + + "undefined attribute #{name} for #{self.class.name}. This record carries " \ + "#{attributes.empty? ? 'no attributes at all' : carried}. " \ + "Check the spelling, or read it with [#{name.inspect}] or fetch(#{name.inspect}, nil) where it may be absent. " \ + 'Zammad also serves a reduced object where the authenticated user may not see the whole record, so an ' \ + 'attribute the record has in Zammad can still be missing here - check what this client may read.' + end + + # Whether this record stages attribute writes, so that {#respond_to?} and + # calling a writer agree. + def writable_attributes? = false + + # Whether one particular attribute may be written. Overridden by records + # that refuse one: a record that claimed `id=` and then raised when it was + # called would defeat the point of asking, which is the whole reason the + # writer branch above is not an unconditional true. + def attribute_writable?(_key) = true + + # Overridden by writable records; read-only ones fall back to NoMethodError. + def write_attribute(key, _value) + raise NoMethodError, "#{self.class.name} attributes are read-only (tried to set #{key})" + end + + # Recursively converts string keys to symbols, including inside arrays, so + # that user supplied attributes behave the same as decoded responses, and + # freezes the result. See {DeepCopy} for why the walk lives there. + def frozen_attributes(value) = DeepCopy.frozen_copy(value, symbolize_keys: true) + + # The inverse of {#frozen_attributes}, for handing out a copy that callers + # may treat as their own. + def deep_dup(value) = DeepCopy.writable_copy(value) + end +end diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index b1d6c85..c3059c6 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -1,65 +1,512 @@ -require 'forwardable' +# frozen_string_literal: true -require 'zammad_api/log' -require 'zammad_api/transport' -require 'zammad_api/dispatcher' -require 'zammad_api/resources' +require_relative 'config' +require_relative 'errors' +require_relative 'resource_proxy' +require_relative 'resources' +require_relative 'transport' module ZammadAPI + # The entry point of this gem. + # + # @example Token authentication + # client = ZammadAPI::Client.new( + # url: 'https://zammad.example.com/', + # http_token: 'your-access-token' + # ) + # client.tickets.find(1).title + # + # @example Basic authentication with a custom timeout and logger + # client = ZammadAPI::Client.new( + # url: 'https://zammad.example.com/', + # user: 'user@example.com', + # password: 'secret', + # timeout: 10, + # logger: Logger.new($stdout) + # ) class Client - extend Forwardable + # Maps the reader methods of this client to their resource classes. + # + # Plural, because what a reader hands back stands for every record of + # its kind: a {ResourceProxy} is +Enumerable+ over all of them, so + # +client.tickets.each+ and +client.tickets.first(5)+ say what they do, + # where the singular the readers had in 1.x read as if it acted on one + # ticket. That name dates from when a proxy was only a dispatcher for + # +find+ and +create+. + RESOURCES = { + groups: Resources::Group, + organizations: Resources::Organization, + tickets: Resources::Ticket, + ticket_articles: Resources::TicketArticle, + ticket_priorities: Resources::TicketPriority, + ticket_states: Resources::TicketState, + users: Resources::User + }.freeze - def_delegators :@transport, :on_behalf_of, :on_behalf_of= + # The names the readers had in 1.x, mapped to the ones they have now. + # Each still works, as a deprecated alias - see {#resource}. + DEPRECATED_RESOURCES = { + group: :groups, + organization: :organizations, + ticket: :tickets, + ticket_article: :ticket_articles, + ticket_priority: :ticket_priorities, + ticket_state: :ticket_states, + user: :users + }.freeze - def initialize(config) - @config = config - @logger = ZammadAPI::Log.new(@config) - @transport = ZammadAPI::Transport.new(@config, @logger) - check_config + # Methods Ruby calls implicitly for type coercion. They must keep raising + # NoMethodError so that this object behaves normally in core operations. + CONVERSION_METHODS = %i[to_ary to_a to_hash to_str to_io to_proc coerce].freeze + + # @return [Config] the validated configuration, with credentials redacted + # from its +inspect+ output + attr_reader :config + + # @!method groups + # @return [ResourceProxy] proxy for {Resources::Group} + # @!method organizations + # @return [ResourceProxy] proxy for {Resources::Organization} + # @!method tickets + # @return [ResourceProxy] proxy for {Resources::Ticket} + # @!method ticket_articles + # @return [ResourceProxy] proxy for {Resources::TicketArticle} + # @!method ticket_priorities + # @return [ResourceProxy] proxy for {Resources::TicketPriority} + # @!method ticket_states + # @return [ResourceProxy] proxy for {Resources::TicketState} + # @!method users + # @return [ResourceProxy] proxy for {Resources::User} + RESOURCES.each do |name, resource_class| + define_method(name) { @resources.fetch(resource_class) } end - def perform_on_behalf_of(identifier) - self.on_behalf_of = identifier - yield.tap do |_| - self.on_behalf_of = nil + # @!method group + # @deprecated Use {#groups}. + # @return [ResourceProxy] + # @!method organization + # @deprecated Use {#organizations}. + # @return [ResourceProxy] + # @!method ticket + # @deprecated Use {#tickets}. + # @return [ResourceProxy] + # @!method ticket_article + # @deprecated Use {#ticket_articles}. + # @return [ResourceProxy] + # @!method ticket_priority + # @deprecated Use {#ticket_priorities}. + # @return [ResourceProxy] + # @!method ticket_state + # @deprecated Use {#ticket_states}. + # @return [ResourceProxy] + # @!method user + # @deprecated Use {#users}. + # @return [ResourceProxy] + DEPRECATED_RESOURCES.each do |old_name, name| + define_method(old_name) do + Client.warn_deprecated_resource(old_name, name) + @resources.fetch(RESOURCES.fetch(name)) end end - def method_missing(method, *_args) - method = modulize(method.to_s) - class_name = "ZammadAPI::Resources::#{method}" - begin - class_object = Kernel.const_get(class_name) - rescue - raise ResourceNotFoundError, "Resource for #{method} does not exist" + # Says that a reader was called by the name it had in 1.x. + # + # In Ruby's own +deprecated+ category, so it is silent unless the + # application asks for deprecation warnings - +ruby -W:deprecated+, or + # +Warning[:deprecated] = true+, which is what a test suite turns on - + # and a script that has not been migrated yet does not print a line per + # request in production. +uplevel+ names the line that made the call, + # past the two frames of this class in between. + # + # @api private + # @param old_name [Symbol] + # @param name [Symbol] + # @return [void] + def self.warn_deprecated_resource(old_name, name) + warn("ZammadAPI::Client##{old_name} is deprecated and will be removed in 3.0: use ##{name} instead", uplevel: 2, category: :deprecated) + end + + # Environment variables {.from_env} reads, mapped to the options they set. + ENV_OPTIONS = { + 'ZAMMAD_URL' => :url, + 'ZAMMAD_TOKEN' => :http_token, + 'ZAMMAD_HTTP_TOKEN' => :http_token, + 'ZAMMAD_OAUTH2_TOKEN' => :oauth2_token, + 'ZAMMAD_USER' => :user, + 'ZAMMAD_PASSWORD' => :password + }.freeze + + # Builds a client from the environment. + # + # Reads {ENV_OPTIONS}, so a script needs no configuration of its own. + # Anything passed in wins over the environment, and every other option + # keeps its default. That includes the way to authenticate: passing + # +user:+ and +password:+, or a token, replaces whichever credentials the + # environment holds rather than sitting beside them. An empty variable + # counts as unset, and +ZAMMAD_HTTP_TOKEN+ wins over +ZAMMAD_TOKEN+ if + # both are set. An environment that sets more than one way to + # authenticate - a token and a user with a password - is refused like + # any other configuration that does, unless an argument names the one to + # use. + # + # @example + # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=secret ruby report.rb + # + # client = ZammadAPI::Client.from_env + # client = ZammadAPI::Client.from_env(timeout: 300) # for one bulk job + # + # @param overrides [Hash] any option accepted by {Config} + # @return [Client] + # @raise [ConfigurationError] when neither the environment nor +overrides+ + # supply a URL and credentials + def self.from_env(**overrides) + from_environment = ENV_OPTIONS.filter_map do |name, option| + value = ENV.fetch(name, nil) + [option, value] if !value.to_s.empty? end - ZammadAPI::Dispatcher.new(@transport, class_object) + options = Config.merge_options(from_environment.to_h, overrides) + + raise ConfigurationError, "missing url: set ZAMMAD_URL or pass url: to #{name}.from_env" if options[:url].to_s.empty? + + new(**options) end - private + # Builds a client from a {Config} that is already validated and a + # transport that is already built. + # + # The public constructor turns options into a Config and a Config into a + # Transport, and building a Transport means building a Faraday stack: + # authentication, JSON, the retry middleware, adapter resolution. Anything + # holding a transport of its own - {Test} - threw all of that away one + # line later, and paid for it again for every stand-in a suite builds. + # This is the way in for those, and the reason there is no public + # `with_transport` to swap one in after the fact. + # + # @api private + # @param config [Config] an already validated configuration + # @param transport [Transport] anything with a {Transport} interface + # @return [Client] + def self.build(config, transport) + allocate.send(:setup, config, transport) + end + + # @param options [Hash] see {Config} for every supported option + # @option options [String] :url base URL of the Zammad instance + # @option options [String] :http_token access token + # @option options [String] :oauth2_token OAuth2 token + # @option options [String] :user login for basic authentication + # @option options [String] :password password for basic authentication + # @raise [ConfigurationError] when the options are incomplete or invalid, + # or name more than one way to authenticate + def initialize(**options) + config = Config.new(**options) + setup(config, Transport.new(config)) + end - def check_config - raise ConfigurationError, 'missing url in config' if !@config[:url] - raise ConfigurationError, 'config url needs to start with http:// or https://' if !%r{^(http|https)://}.match?(@config[:url]) + # The proxy for a resource, by name or by class. + # + # A name from 1.x - +:ticket+ for +:tickets+ - is still answered, with + # a deprecation warning. + # + # A class is the way to the parts of the API this gem does not model. + # {Resources::Base} is built to be subclassed - a path, and whatever the + # endpoint needs said about it - and a proxy for such a class gives its + # records everything the modelled ones have: pagination, +find_by+, + # change tracking, +save+. 1.x reached any subclass through +const_get+ + # on a name a caller supplied, and 2.0 closed that, which left raw + # requests as the only way to the rest of the API; this is the same + # reach, with the class handed over rather than looked up. + # + # @example A resource this gem does not model + # class Role < ZammadAPI::Resources::Base + # path 'api/v1/roles' + # end + # + # client.resource(Role).each { |role| puts role.name } + # client.resource(Role).find(2).update(note: 'Reviewed') + # + # @param name [Symbol, String, Class] a key of {RESOURCES}, or a subclass + # of {Resources::Base} + # @return [ResourceProxy] + # @raise [UnknownResourceError] when no resource has that name + # @raise [ArgumentError] for a class that is not a resource + # @raise [Error] for a resource class that declares no path + def resource(name) + return proxy_for(name) if name.is_a?(Class) - # check for token auth - return if @config[:http_token] && !@config[:http_token].empty? - return if @config[:oauth2_token] && !@config[:oauth2_token].empty? + key = name.to_sym - if !@config[:user] || @config[:user].empty? - raise ConfigurationError, 'missing user in config' + if !RESOURCES.key?(key) + current = DEPRECATED_RESOURCES.fetch(key) { raise UnknownResourceError, unknown_resource_message(name) } + Client.warn_deprecated_resource(key, current) + key = current end - return if @config[:password] && !@config[:password].empty? + @resources.fetch(RESOURCES.fetch(key)) + end + + # @return [Array] every resource name this client supports + def resource_names = RESOURCES.keys + + # The user these requests authenticate as, or the one {#on_behalf_of} + # scoped them to. + # + # @example Checking which account a token belongs to + # client.me.email # => "agent@example.com" + # + # @return [Resources::User] + # @raise [AuthenticationError] when the credentials are not valid + def me + response = @transport.get( + # Derived from the resource that declares the endpoint, not spelled + # out again: `member_path` exists for the same reason, and a path kept + # in two places is one that moves in one of them. Spelled out here, + # `client.users` would follow the users endpoint wherever it went and + # `client.me` would keep requesting the old one. + "#{Resources::User.resource_path}/me", + operation: 'find current user', + resource_class: Resources::User, + query: { expand: true } + ) + Resources::User.from_response( + @transport, + response.decoded(:object, operation: 'find current user', resource_class: Resources::User) + ) + end + + # The version of the Zammad instance, not of this gem — that is + # {ZammadAPI::VERSION}. + # + # Zammad serves it to administrators only: its VersionControllerPolicy + # permits +admin+ and nothing else. An agent's or a customer's + # credentials are answered with a 403, so to check that a client can + # reach Zammad at all, ask {#me}, which every account may. + # + # @example + # client.version # => "6.4.0" + # + # @return [String, nil] nil when the instance reported no version + # @raise [AuthorizationError] when the account is not an administrator + def version + response = @transport.get('api/v1/version', operation: 'get the Zammad version') + version = response.decoded(:object, operation: 'get the Zammad version')[:version] + version&.to_s + end + + # @!group Raw requests + + # Performs a +GET+ against any endpoint of the Zammad API. + # + # The resource classes cover a part of the API; these four methods reach + # the rest of it without giving up authentication, retries, credential + # redaction, JSON decoding or the error classes. + # + # +headers:+ is here because an escape hatch that cannot set one does not + # reach an endpoint that needs one. What it will not set is the two + # headers this client owns - see the +headers+ parameter below. + # + # @example An endpoint this gem does not model + # client.get('api/v1/roles').body + # # => [{id: 1, name: "Admin", ...}, ...] + # + # @example Reading a response header + # client.get('api/v1/tickets').headers['content-type'] + # + # @example An endpoint that needs a header of its own + # client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) + # + # @param path [String] path relative to {Config#url}; a leading slash is + # ignored, so paths can be pasted from the Zammad documentation. An + # absolute URL is refused, so the client's credentials only ever go to + # the instance it was configured for. It is written the way a URL is: + # a space or a character outside ASCII has to be percent-encoded. + # @param query [Hash, nil] query string parameters + # @param headers [Hash, nil] request headers. Names are case-insensitive, + # and +Authorization+ and +From+ are refused: the first is what the + # client's credentials are for, the second is what {#on_behalf_of} sets. + # @return [Response] + # @raise [ResponseError] for any non-2xx response + # @raise [TransportError] when the request could not be completed + # @raise [ArgumentError] for a header this client sets itself, a value + # that is not text, a path that is an absolute URL, or one that cannot + # be read as a URL + def get(path, query: nil, headers: nil) = raw(:get, path, query: query, headers: headers) + + # Performs a +POST+ against any endpoint of the Zammad API. + # + # @example + # client.post('api/v1/tags/add', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) + # + # @param path [String] path relative to {Config#url} + # @param query [Hash, nil] query string parameters + # @param body [Hash, Array, nil] request payload, encoded as JSON + # @param headers [Hash, nil] request headers + # @return [Response] + # @raise [ResponseError] for any non-2xx response + # @see #get + def post(path, query: nil, body: nil, headers: nil) = raw(:post, path, query: query, body: body, headers: headers) + + # Performs a +PUT+ against any endpoint of the Zammad API. + # + # @param path [String] path relative to {Config#url} + # @param query [Hash, nil] query string parameters + # @param body [Hash, Array, nil] request payload, encoded as JSON + # @param headers [Hash, nil] request headers + # @return [Response] + # @raise [ResponseError] for any non-2xx response + # @see #get + def put(path, query: nil, body: nil, headers: nil) = raw(:put, path, query: query, body: body, headers: headers) + + # Performs a +DELETE+ against any endpoint of the Zammad API. + # + # @param path [String] path relative to {Config#url} + # @param query [Hash, nil] query string parameters + # @param headers [Hash, nil] request headers + # @return [Response] + # @raise [ResponseError] for any non-2xx response + # @see #get + def delete(path, query: nil, headers: nil) = raw(:delete, path, query: query, headers: headers) + + # @!endgroup - raise ConfigurationError, 'missing password in config' + # Returns a new client with some configuration options changed. + # + # The options are re-validated, and any {#on_behalf_of} scope is carried + # over. The original client keeps its own connection and settings. + # + # Naming credentials replaces the ones this client has, whichever kind + # they were: +with(oauth2_token: 'x')+ on a client built with an access + # token authenticates with the OAuth2 token alone. + # + # The transport derives from the current one rather than being built from + # scratch, so a client wired to a stand-in stays wired to it. + # + # @example A longer timeout for one bulk job + # bulk = client.with(timeout: 300, retries: 5) + # bulk.tickets.all.each { |ticket| archive(ticket) } + # + # @param options [Hash] any option accepted by {Config} + # @return [Client] + # @raise [ConfigurationError] when the resulting options are invalid + def with(**options) + derived_config = config.with(**options) + dup.send(:setup, derived_config, @transport.with_config(derived_config)) end - def modulize(string) - string.gsub(/__(.?)/) { "::#{$1.upcase}" } - .gsub(%r{/(.?)}) { "::#{$1.upcase}" } - .gsub(/(?:_+|-+)([a-z])/) { $1.upcase } - .gsub(/(\A|\s)([a-z])/) { $1 + $2.upcase } + # Performs requests on behalf of another user. + # + # Returns a new client rather than mutating this one, so the original + # client is unaffected and both can be used concurrently. + # + # @example Scoped client + # support = client.on_behalf_of('agent@example.com') + # support.tickets.create(title: 'Help', group: 'Users', customer_id: 1) + # + # @example Block form + # client.on_behalf_of('agent@example.com') do |scoped| + # scoped.tickets.find(1) + # end + # + # An identifier that names nobody is refused. Zammad skips a +From+ + # header with nothing in it, and a nil sent none at all, so + # +client.on_behalf_of(current_user&.login)+ with nobody signed in + # handed back a client that looked scoped and was not: every request + # ran with the rights of the account the client authenticates as, and + # a list read through it held everything that account can see. No + # request failed, so nothing said the scope was missing. + # + # @param identifier [String, Integer] login, email address or user id + # @yieldparam scoped [Client] + # @return [Client] when no block is given, otherwise the block's value + # @raise [ArgumentError] for an identifier that is nil, empty or blank + def on_behalf_of(identifier) + # Nil is what a transport takes for no scope, so it is refused here. + # The rest is refused by the rule every transport is meant to apply, + # applied here as well: Client.build takes anything with a transport's + # interface, and one that stored what it was given would send an empty + # From header for `on_behalf_of('')`. + raise ArgumentError, Transport.blank_on_behalf_of_message(identifier) if identifier.nil? + + scoped = dup.send(:setup, config, @transport.with_on_behalf_of(Transport.stringify_on_behalf_of(identifier))) + return scoped if !block_given? + + yield scoped + end + + # The scope is shown where there is one, so that a client acting for + # another user does not print as the one it was derived from. + def inspect + scope = @transport.on_behalf_of + + "#<#{self.class.name} url=#{config.redacted_url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{scope.inspect}" if scope}>" + end + + def method_missing(name, *args) + return super if CONVERSION_METHODS.include?(name) || name.to_s.end_with?('=', '!', '?') + + raise UnknownResourceError, unknown_resource_message(name) + end + + def respond_to_missing?(_name, _include_private = false) = false + + private + + def raw(method, path, query: nil, body: nil, headers: nil) + relative = Transport.relative_path(path) + + @transport.request( + method, + relative, + # Named by the path as it may be printed. The operation is in the + # message of every error the request raises, and a query string + # written into the path may carry a token. + operation: "#{method.to_s.upcase} #{Transport.redact_path(relative)}", + query: query, + body: body, + headers: headers + ) + end + + def unknown_resource_message(name) = "Unknown resource #{name}, available resources are: #{RESOURCES.keys.join(', ')}" + + # One of the proxies built with this client for a class it models, and a + # new one for any other resource class. A new one each time, rather than + # a memo: the client is frozen in everything but name once it is built - + # see {#setup} - and a proxy holds nothing but the transport and the + # class. + def proxy_for(resource_class) + raise ArgumentError, "resource takes the name of a resource or a subclass of #{Resources::Base.name}, and #{resource_class.inspect} is neither" if !(resource_class <= Resources::Base) + + @resources.fetch(resource_class) do + # Asked for now, so that a class without a path is reported by the + # call that named it rather than by its first request. + resource_class.resource_path + ResourceProxy.new(@transport, resource_class) + end + end + + # Everything a client is, in the one place all four ways of making one go + # through: {.new}, {.build}, {#with} and {#on_behalf_of}. Held apart, + # `build` restated `initialize`'s list of instance variables by hand, and + # the fourth one added to `initialize` would have left every client built + # for a test unset where it mattered. + # + # The proxies are built here rather than memoized on first use, because a + # client is documented - and used, in examples/concurrent_sync.rb - as + # immutable once built and safe to share between threads without locking. + # A memo populated by the first `client.tickets` in each worker is a write + # to shared state, and while CRuby's GVL makes it harmless, a contract + # that only holds on one implementation is not the contract that was + # written down. Building all seven up front costs an allocation each and + # keeps the object finished the moment it is handed back. + # + # @return [self] + def setup(config, transport) + @config = config + @transport = transport + @resources = RESOURCES.values.to_h { [it, ResourceProxy.new(transport, it)] }.freeze + + self end end end diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb new file mode 100644 index 0000000..262b531 --- /dev/null +++ b/lib/zammad_api/collection.rb @@ -0,0 +1,813 @@ +# frozen_string_literal: true + +require_relative 'errors' + +module ZammadAPI + # A lazily fetched, automatically paginated list of records. + # + # Nothing is requested until the collection is iterated. {#order} and + # {#page} return new collections, so a collection can be built up in + # steps and shared without being disturbed. + # + # {#each} walks every page until the server runs out of records, so it is + # safe to iterate a collection larger than one page. {#first} reads one page + # sized for what it was asked for, and +lazy+, +detect+ and the rest of + # +Enumerable+ stop the walk as soon as they have enough, so neither has to + # download everything. + # + # @example Iterate every ticket + # client.tickets.all.each { |ticket| puts ticket.title } + # + # @example Narrow to matches, then stop after the first five + # client.tickets.search('state.name:open').first(5) + # + # @example Sorted by the server + # client.groups.order(:name).each { |group| puts group.name } + # + # @example Work in batches, e.g. for an import + # client.tickets.all.in_batches(of: 50) { |tickets| import(tickets) } + # + # @example One explicit page + # client.tickets.all.page(2, per_page: 50).to_a + class Collection + include Enumerable + + # The two directions a sort can run in, as Zammad spells them. + SORT_DIRECTIONS = %w[asc desc].freeze + private_constant :SORT_DIRECTIONS + + # What an attribute to sort by is named. Zammad takes several of them as + # one comma-separated parameter, so a name carrying a comma or a space + # would be read as something other than the one attribute it was. + SORT_ATTRIBUTE = /\A\w+\z/ + private_constant :SORT_ATTRIBUTE + + # @api private + # @param per_page [Integer, nil] records fetched per request, or nil for + # as many as the endpoint serves + # @param search [Boolean] whether this is a search endpoint, which + # differs from an index in two ways a collection has to know about: it + # reports the size of the whole result, alone for +only_total_count+ + # and beside a page for +with_total_count+, and it can serve a page + # short of its size, or with nothing on it, before the last one + # @param sortable [Boolean] whether this endpoint reads +sort_by+ and + # +order_by+ + # @param unsortable_hint [String] what to do instead where it does not + # @param widens [Boolean] whether a walk may ask for a larger page than + # +per_page+ once one has come back with nothing on it, which a read + # sized by {#first} may and a batch size a caller chose may not: see + # {#widened} + def initialize(transport:, resource_class:, path:, operation:, max_per_page:, sortable:, unsortable_hint:, query: {}, per_page: nil, page: nil, search: false, widens: false) + @transport = transport + @resource_class = resource_class + @path = path + @operation = operation + @query = query + @max_per_page = max_per_page + @sortable = sortable + @unsortable_hint = unsortable_hint + # As many as the endpoint serves, unless a call asks for another size. + # + # A fixed default of 100 was the earlier answer, and it cost a request + # for every 100 records where the endpoint would have served 1000: a + # walk of the user index spent ten times the round trips it needed, and + # each of those is a TLS handshake of its own under Faraday's default + # adapter. The endpoint's own cap is the one number that is right for + # every resource without a caller looking each of them up - it is + # already what {#clamp_per_page} measures against. + # + # What that costs is a larger page held at once - a thousand expanded + # users rather than a hundred. {#first} is what made that affordable: + # the cheap-looking call that only wants a record or two now sizes its + # own page instead of taking them off the front of this one. + @per_page = clamp_per_page(per_page || max_per_page) + @page = page + @search = search + @widens = widens + end + + # Yields every record, fetching further pages as needed. + # + # @yieldparam record [Resources::Base] + # @return [Enumerator] when no block is given + def each(&block) + return to_enum(:each) if !block + + in_batches { |records| records.each(&block) } + self + end + + # Yields every record, like {#each}, with the page size set inline. + # + # @param batch_size [Integer, nil] records fetched per request + # @yieldparam record [Resources::Base] + # @return [Enumerator] when no block is given + def find_each(batch_size: nil, &block) + return to_enum(:find_each, batch_size: batch_size) if !block + return with(per_page: page_size!(batch_size, 'batch_size')).find_each(&block) if batch_size + + each(&block) + end + + # Yields one array of records per page. + # + # A batch is one response: what a request returned is what the block gets, + # so +of+ is what sizes it. For groups of a size the API knows nothing + # about, slice the records instead: +find_each.each_slice(12)+. + # + # @param of [Integer, nil] records fetched per request + # @yieldparam records [Array] + # @return [Enumerator] when no block is given + def in_batches(of: nil, &block) + return to_enum(:in_batches, of: of) if !block + return with(per_page: page_size!(of, 'of')).in_batches(&block) if of + + walk(&block) + self + end + + # Returns a new collection limited to a single page. + # + # +per_page+ decides how big that page is, and so which records it holds: + # +page(2, per_page: 50)+ is records 51 to 100. A size larger than the endpoint + # serves is refused rather than reduced, because reducing it moves the + # page: +page(3, per_page: 500)+ against an endpoint capping at 100 was sent as + # +page=3&per_page=100+ and answered with records 201 to 300 instead of + # 1001 to 1500. A job that checkpoints a page number then re-read what it + # had already handled and never reached the rest. + # + # @example + # client.tickets.all.page(2, per_page: 50).to_a + # + # @param number [Integer] one-based page number + # @param per_page [Integer, nil] records on the page, as many as the endpoint + # serves by default + # @return [Collection] + # @raise [ArgumentError] for a page size the endpoint does not serve + def page(number, per_page: nil) + raise ArgumentError, 'page needs to be a positive integer' if !number.is_a?(Integer) || !number.positive? + return with(page: number) if per_page.nil? + + size = positive_integer!(per_page, 'per_page') + raise ArgumentError, "#{@path} serves at most #{@max_per_page} records per page, so page(#{number}, per_page: #{size}) would be sent as page #{number} of #{@max_per_page} and hold different records. Ask for page(#{number}, per_page: #{@max_per_page}) or fewer, or walk the records with find_each." if size > @max_per_page + + with(page: number, per_page: size) + end + + # Returns a new collection sorted by the server. + # + # Attributes named on their own sort ascending, and a keyword says which + # way one runs, the way ActiveRecord reads the same call. A second + # +order+ sorts within the first, so +order(:active).order(name: :desc)+ + # is +order(:active, name: :desc)+. + # + # This is the one thing an index endpoint does besides paging, which is + # why it has a name of its own. It used to be reached as + # +where(sort_by: 'name', order_by: 'desc')+, on a method that refused + # nearly everything else it was given: an index endpoint does not filter + # by attribute value, so +where(state: 'open')+ could only raise, and on + # tickets and users +where+ accepted nothing at all. Narrowing by a value + # is what {ResourceProxy#search} and {ResourceProxy#find_by} are for. + # + # Not every endpoint sorts. +/api/v1/tickets+ and +/api/v1/users+ are + # always served in id order, and drop +sort_by+ along with everything + # else they do not read, so this refuses them rather than handing back + # records it would be calling sorted. A search does sort, for every + # resource that can be searched. + # + # @example + # client.groups.order(:name).first(5) + # client.organizations.order(name: :desc) + # client.tickets.search('state.name:open').order(:priority_id, created_at: :desc) + # + # @param attributes [Array] attributes to sort by, + # ascending + # @param directions [Hash{Symbol => Symbol, String}] attributes to sort by, + # each with +:asc+ or +:desc+ + # @return [Collection] + # @raise [ArgumentError] for an endpoint that does not sort, no + # attribute at all, an attribute named twice, or a direction that is + # neither +:asc+ nor +:desc+ + def order(*attributes, **directions) + raise ArgumentError, "#{@path} is always served in the same order and ignores sort_by, so order would hand back the records as they were. #{@unsortable_hint}" if !@sortable + + requested = sort_columns(attributes, directions) + raise ArgumentError, 'order needs at least one attribute to sort by: order(:name), or order(name: :desc)' if requested.empty? + + sorted = sorted_by + repeated = requested.keys & sorted.keys + raise ArgumentError, "order was given #{repeated.join(', ')}, which this collection is already sorted by" if !repeated.empty? + + columns = sorted.merge(requested) + with(query: @query.merge(sort_by: columns.keys.join(','), order_by: columns.values.join(','))) + end + + # Reads one or more attributes from every record. + # + # Zammad has no way to ask an index endpoint for a subset of the fields, so + # this shapes the result rather than shrinking the request. + # + # @example + # client.users.all.pluck(:email) # => ["a@example.com", ...] + # client.tickets.all.pluck(:id, :title) # => [[1, "Help"], ...] + # + # @param keys [Array] attribute names + # @return [Array] one value per record for a single key, one array of + # values per record for several + # @raise [ArgumentError] when no attribute name was given + def pluck(*keys) + raise ArgumentError, 'pluck needs at least one attribute name' if keys.empty? + return map { it[keys.first] } if keys.one? + + map { |record| keys.map { record[it] } } + end + + # The first record, or the first +count+ of them. + # + # Sized to what was asked for, which +Enumerable#first+ cannot be: it + # takes its records off the front of a page this collection sized for + # walking, so +all.first+ downloaded a page of a thousand users to hand + # back one of them. + # + # The request is sized, not the collection. Limiting it to one page of + # +count+ records would have been the shorter way to write this and + # answers wrongly where the endpoint serves a smaller page than the + # +max_per_page+ this resource declares: +first(500)+ against a server + # capping at 100 came back with 100 records and nothing to say that the + # other 400 were there to be read. Sizing the request instead leaves the + # walk able to fetch a second page, and +Enumerable#first+ stops it as + # soon as it has what it asked for - so the ordinary case is still the one + # request it looks like. + # + # A collection {#page} already limited is left as it is. Its page size + # says which records it holds, so re-sizing it would move them - the same + # reason {#page_size!} refuses to. + # + # The size is where the read starts, and not what it is held to. A + # search can serve a page with nothing on it and hits still behind it, + # and a read that stayed this small then paid a request for every one + # of them: see {#widened}. + # + # A read that sizes its own request leaves out a record it has already + # handed over. The larger pages it asks for past an empty one are where + # an endpoint that pages smaller than it is asked hands a hit back twice, + # and a caller acting on the records - `first(5).each { notify(it) }` - + # would act on that one twice. It holds no more ids than records wanted, + # and asks for nothing more to do it: the read goes on to the next + # record, as it does past a stale hit. + # + # @param count [Integer, nil] how many records to read + # @return [Resources::Base, Array, nil] one record, or an + # array of them when +count+ was given + def first(count = nil) + wanted = count || 1 + # Through an enumerator rather than `super`, so that the sized + # collection does the reading and this method is not asked to be both + # the caller and the callee of Enumerable#first. + records = own_request_for_first?(wanted) ? with(per_page: wanted, widens: true).to_enum(:each_distinct) : each + count.nil? ? records.first : records.first(count) + end + + # The first +count+ records, read the way {#first} reads them. + # + # +take(n)+ and +first(n)+ ask one question, and +Enumerable+ answers both + # by taking records off the front of a page this collection sized for + # walking. With {#first} sizing its own request and this one left alone, + # what the same read cost depended on which of the two words was typed. + # + # @param count [Integer] how many records to read + # @return [Array] + def take(count) + # Enumerable#take always answers with an Array, and {#first} only does + # when it is given a count - a nil is "just the one" there. Refused with + # the error Enumerable#take raises for it, rather than quietly answering + # a different question with a different type. + raise TypeError, 'no implicit conversion from nil to integer' if count.nil? + + first(count) + end + + # +Enumerable#find+, which takes a block. + # + # Defined only to refuse the other reading of it. {ResourceProxy#find} + # takes an id - +client.tickets.find(1)+ is the lookup by id - and the same + # word on a collection is +Enumerable#find+, whose argument is an ifnone + # callable rather than an id. So +client.tickets.all.find(1)+ made no + # request, raised nothing, and answered with an Enumerator: a silent + # no-op, on the one spelling a caller is most likely to reach for. + # + # A collection cannot do the lookup either, even where it would be + # unambiguous - a search has already narrowed what it holds, so an id + # found through one collection would mean something different from an id + # found through another. + # + # @yieldparam record [Resources::Base] + # @return [Resources::Base, nil] + # @raise [ArgumentError] when given an id where a block belongs + def find(*args, &block) + raise ArgumentError, find_by_id_message(args.first) if block.nil? && !args.empty? + + super + end + + # Number of records in this collection. + # + # One request on a search, which Zammad can count without serving the + # records: +only_total_count+ is the first thing + # ApplicationController#model_search_render looks at, and it answers with + # the figure alone. + # + # Every other endpoint has to be walked. An index endpoint drops + # +only_total_count+ along with every other parameter it does not know - + # model_index_render reads +sort_by+, +order_by+ and the paging and + # nothing else - and there is no header to read a total from either, so + # there is nothing cheaper to ask. Probing anyway cost a wasted request + # before the walk that had to happen regardless. + # + # @return [Integer] + def count(*args, &block) + # A block or an argument is Enumerable counting matches, not this asking + # how large the result is. A collection limited to one page has to read + # that page, because the total describes the whole query. + return super if !args.empty? || block || @page || !@search + + total_count || super + end + + # Number of records in this collection. + # + # An alias of {#count}, and so the same cost: one request on a search + # endpoint, a walk of every page on any other. + # + # @return [Integer] + # @see #count + alias size count + + # @return [Integer] + # @see #count + alias length count + + # Whether this collection has no records. + # + # Costs the one request {#first} costs: a page of a single record, except + # on a collection limited to one page, where the page size decides which + # records that page holds and so cannot be narrowed. A search whose + # first hits have lost their records costs the few more it takes to read + # past them. + # + # @example + # client.tickets.search('state.name:merged').empty? + # + # @return [Boolean] + def empty? = first.nil? + + def inspect + "#<#{self.class.name} #{@resource_class.name} path=#{@path.inspect} per_page=#{@per_page}#{" page=#{@page}" if @page}>" + end + + private + + # Yields each record whose id has not been yielded already. A record + # without an id is yielded, there being nothing to tell it by. + def each_distinct + seen = {} + each do |record| + id = record.id + next if !id.nil? && seen.key?(id) + + seen[id] = true if !id.nil? + yield record + end + end + + # Whether a read of this many records is worth sizing the request for. + # + # Not where this collection is already limited to a page, whose size says + # which records it holds, and not where the count is larger than the + # endpoint serves - {#clamp_per_page} would reduce it to the same size the + # collection already has. A zero or negative count is left to + # Enumerable#first, which has its own answers for both. + def own_request_for_first?(count) + return false if @page + + count.is_a?(Integer) && count.positive? && count <= @max_per_page + end + + def find_by_id_message(id) + "find on a #{self.class.name} is Enumerable#find, which takes a block: #{id.inspect} would be read as its " \ + 'ifnone argument and answered with an Enumerator, without a request. ' \ + "Look a record up by id on the resource itself - #{resource_reader}.find(#{id.inspect}) - " \ + 'or pick one out of the records this collection holds with detect { ... }.' + end + + # How a caller reaches this resource from a client: + # ZammadAPI::Resources::TicketArticle is client.ticket_articles, and a + # resource class the caller declared is client.resource(TheirClass). Looked + # up at the moment it is needed, in an error message, so that this file + # does not have to load the client that loads it. + def resource_reader + name = Client::RESOURCES.key(@resource_class) + name ? "client.#{name}" : "client.resource(#{@resource_class.name})" + end + + # The attributes an +order+ call names, each with its direction, in the + # order they were written. + # + # @return [Hash{String => String}] + def sort_columns(attributes, directions) + # `order(:name, :desc)` is the spelling several other clients use, and + # read literally it sorts by an attribute called desc - which Zammad + # answers with a server error about an invalid column. + misplaced = attributes.find { SORT_DIRECTIONS.include?(it.to_s.downcase) } + raise ArgumentError, "order reads #{misplaced.inspect} as an attribute to sort by. A direction goes with its attribute: order(name: #{misplaced.to_s.downcase.to_sym.inspect})" if misplaced + + columns = {} #: Hash[String, String] + (attributes.map { [it, 'asc'] } + directions.to_a).each do |attribute, direction| + name = sort_attribute!(attribute) + raise ArgumentError, "order was given #{name} twice" if columns.key?(name) + + columns[name] = sort_direction!(name, direction) + end + columns + end + + def sort_attribute!(attribute) + name = attribute.to_s + raise ArgumentError, "order needs the name of an attribute to sort by, got #{attribute.inspect}" if (!attribute.is_a?(Symbol) && !attribute.is_a?(String)) || !SORT_ATTRIBUTE.match?(name) + + name + end + + def sort_direction!(name, direction) + normalized = direction.to_s.downcase + raise ArgumentError, "order sorts #{name} either :asc or :desc, got #{direction.inspect}" if !SORT_DIRECTIONS.include?(normalized) + + normalized + end + + # What this collection is already sorted by, read back out of the query + # it will send. + # + # @return [Hash{String => String}] + def sorted_by + @query.fetch(:sort_by, '').to_s.split(',').zip(@query.fetch(:order_by, '').to_s.split(',')).to_h + end + + def positive_integer!(value, name) + raise ArgumentError, "#{name} needs a positive integer" if !value.is_a?(Integer) || !value.positive? + + value + end + + # Re-sizing the page of a collection that {#page} already limited would + # change which records it holds: `page(3, per_page: 50)` names records 101 to + # 150, and re-sizing to 10 behind the caller's back served records 21 to + # 30 instead - a different answer to the same question, with nothing said + # about it. The two ways of naming a page cannot both be honoured, so this + # says so rather than picking one. + def page_size!(value, name) + size = positive_integer!(value, name) + raise ArgumentError, "#{name} cannot be combined with page: page(#{@page}, per_page: #{@per_page}) already named which records this collection holds. Size that page with page(#{@page}, per_page: #{size}), or slice the records with each_slice(#{size})." if @page + + size + end + + def walk + page = @page || 1 + previous = nil + page_size = 0 + # `while`, and not `loop`. Kernel#loop rescues StopIteration, which is + # there for an enumerator driven by hand inside it, and the block this + # yields to is the caller's: one that calls `next` on an enumerator of + # its own - `map { [it.id, labels.next] }` with fewer labels than + # records - raised it from in here, and the walk took it for its own + # end. The records and the pages after that were dropped and `map` + # answered with what it had, where the same block over an Array raises. + # Every way out of this loop is a `break` below. + per_page = @per_page + while page + records, digest, total = fetch(page, per_page) + + # Counted before the block has the page, not after. The Array handed + # over is the block's to do with as it likes, and a consumer that + # works a batch off with `shift` hands it back empty: read afterwards, + # that was an empty page, and an import stopped after its first batch + # with every later page still on the server. + received = records.size + + # Before the records are handed over, not after. Yielding first meant + # an endpoint that ignores `page` had its repeated page imported, + # queued or written by the block, and only then did the guard that + # exists to prevent that get to look at it. + # + # A digest rather than the pages themselves, because holding the + # previous page across the next fetch doubled a walk's peak memory for + # a guard that only ever asks whether two pages are equal. What it is + # a digest of is in #page_digest: the ids, where every record has one. + # + # Where it is the payload, it is the decoded one, not the bytes it + # arrived as. Hashing raw_body is cheaper and looks equivalent - + # identical bytes do mean identical records - but the implication that + # matters here runs the other way: an endpoint that ignores `page` and + # re-serializes the same records with a different key order produces + # different bytes every time, so the guard never fires, and because + # every page is full the short-page break does not fire either. A + # missed repeat is not a missed error, it is a walk that never ends. + # `Hash#hash` ignores key order and whitespace, which is exactly the + # insensitivity this needs - and taking it from the decoded payload + # rather than from the built records costs nothing extra, because that + # payload is what the records were built from one line earlier. + # + # An empty page is not held against the one before it. Two in a row + # are what a search serves for two pages of hits whose records are + # gone, with more beyond them - see #hits_past? - and there is nothing + # on either for the block to be handed twice. + raise PaginationError.build(operation: @operation, page: page, resource_class: @resource_class) if received.positive? && digest == previous + + yield records if received.positive? + + # A collection limited to a single page never advances. + break if @page + + # The hits the pages read so far have covered, reckoned in the size + # asked for. Every page this walk asks for starts where the one + # before it ended, whatever size either was, so the last page's + # number and size say it all. + covered = page * per_page + # An empty page ends the walk, unless it is a search saying that it + # has hits beyond this one. + break if received.zero? && !hits_past?(covered, total) + + # Every stop condition here is derived from the records the endpoint + # actually served, and the one figure read beside them - a search's + # total, in #hits_past? - can only keep a walk going. There was a + # stop condition that was not: an index endpoint was believed to + # report the size of the whole result in a header, which would have + # ended a short walk one request earlier. Zammad sends no such header + # from any endpoint, so it never once fired. What it did leave behind + # was a stop condition that could end a walk early on a figure the + # records did not corroborate, which is the one way a walk can be + # wrong rather than merely slow. + # + # How big a page this endpoint actually serves, learned from the first + # one rather than assumed. The requested size is clamped to a per- + # resource page limit, and where that guess was higher than the + # server's real cap - a lowered setting, a custom deployment, an + # endpoint whose cap was never this generous - every page came back + # short and the walk stopped on page one with a truncated result and + # nothing to show for it. + # + # Asked of an index endpoint only. Its page is one SQL query with an + # offset and a limit, so a page short of the size it has been serving + # is the last one. A search page is put together in two steps: + # ApplicationController#model_search_render has the search - through + # Elasticsearch, or through SQL - name the ids for the page, and then + # loads the records with `where(id: ids)`. An id whose record is gone + # by the second step is left out and nothing fills its place: a ticket + # deleted in between, or one Elasticsearch still lists because its + # index has drifted from the database. So a search can serve 199 of + # 200 on page two with page three still to come, and stopping there + # truncated the result with nothing to say so. Only an empty page + # ends a search walk, which costs one more request where the last + # page of hits is part-filled - and not every empty page does, for + # the same reason: see #hits_past?. + page_size = received if page_size.zero? + break if !@search && received < page_size + + previous = digest + page, per_page = page_after(page, per_page, received, total) + end + end + + # The page that follows one a walk has read, and its size: the next of + # the same size, except past an empty page in a read sized by {#first}, + # which asks for more at a time from there. Only a search gets this far + # with nothing received. + # + # @return [Array(Integer, Integer)] the page to ask for and its size + def page_after(page, per_page, received, total) + received.zero? && @widens ? widened(page * per_page, total) : [page + 1, per_page] + end + + # The page to ask for after an empty one, in a read that may widen: the + # largest the endpoint serves that starts exactly where the pages read so + # far ended. + # + # {#first} and {#empty?} size their request to the records they want, + # and a search is read on past a page with nothing on it while the total + # says there are hits behind it. Kept at that size, the two together + # cost a request for every stale hit: on an instance whose Elasticsearch + # index has drifted from its database - one restored without a reindex - + # `search(term).empty?` behind five thousand of them made five thousand + # requests, one after the other, before it answered. + # + # The size that was asked for stopped being the right one at the first + # empty page: it was chosen to fetch no more than was wanted, and what it + # fetched was nothing. But a larger page cannot simply be asked for from + # there. A page is a position - page 3 of 50 is hits 101 to 150 - so one + # of another size starts somewhere else, and a read that moved to it + # would pass over hits or be handed records a second time. + # + # So the next page is one whose size divides what has been covered, + # which makes its start fall exactly on the end of the last: with 8 hits + # covered, page 2 of 8 is hits 9 to 16. The size doubles that way from a + # page of one, and from the endpoint's own limit on it is the largest + # divisor that fits. Five thousand stale hits are read past in + # thirty-four requests. + # + # No page reaches past the total the search last reported, though the + # endpoint would serve one: with 256 hits covered of 300, the next page + # is 32 hits rather than 128. Zammad hands the offset and the size to + # Elasticsearch as they are, and an index whose result window was + # lowered below them - the per-model settings allow it - refuses the + # request, which Zammad answers as no hits and a total of nought. Asked + # for hits 257 to 384 against a window of 300, a read with a live hit + # at 280 answered nil where a page of one would have found it. The + # window cannot be seen from here, so a total beyond it still leaves the + # read to end there; the default window is a million hits. + # + # It takes the endpoint to serve the size it is asked for, up to + # +max_per_page+, which is what #hits_past? takes as well. One that + # serves less pages by its own size, so page 3 of 192 served as 100 is + # hits 201 to 300: hits are passed over, and the pages read cover less + # than the walk takes them to. A hit served twice is left out by + # {#first}. A page of one, which every endpoint serves, could not go + # wrong that way. Zammad serves a search the 200 this asks for at most, + # so it takes an instance whose cap was lowered, and the README says so + # beside the walk's own limits. + # + # Not for a size a caller chose. `in_batches(of: 10)` says how many + # records a batch may hold, and a page of 160 is not one of those. + # + # @param covered [Integer] the hits the pages read so far have covered + # @param total [Integer, nil] the hits the search last reported + # @return [Array(Integer, Integer)] the page to ask for and its size + def widened(covered, total) + limit = total ? (total - covered).clamp(1, @max_per_page) : @max_per_page + pages = covered.fdiv(limit).ceil + pages += 1 until (covered % pages).zero? + + [pages + 1, covered / pages] + end + + def with(page: @page, per_page: @per_page, query: @query, widens: false) + self.class.new( + transport: @transport, + resource_class: @resource_class, + path: @path, + operation: @operation, + max_per_page: @max_per_page, + sortable: @sortable, + unsortable_hint: @unsortable_hint, + query: query, + per_page: per_page, + page: page, + search: @search, + widens: widens + ) + end + + # Whether a search reports hits beyond the page just read, which is what + # tells a page with nothing on it from the end of the result. + # + # A search page can come back empty with hits still to come, for the + # reason it can come back short: every id the search named for it has + # lost its record. On a page of 200 that takes 200 stale hits in a row. + # On the page of one that {#first} and {#empty?} ask for it takes one, + # and a search sorts by `updated_at`, newest first - so the hit likeliest + # to be stale, a record deleted a moment ago that Elasticsearch has yet + # to drop, is the first one served. `search(term).first` answered nil and + # `empty?` true for a search with live hits right behind it, and `each` + # ended on such a page with the rest unread. + # + # So a search that is walked asks for the size of the whole result beside + # every page - see #page_query - and an empty page ends the walk only + # once the pages read have covered it. + # + # The figure is not used the other way round, to end a walk on a page + # that still held records and save the request after it. Elasticsearch + # stops counting at ten thousand hits and reports that as the total, so + # a walk ended on the figure would stop there with the rest unread - + # which is the stop condition the note in #walk is about. Past that + # figure an empty page ends the walk, as it does where there is no figure + # at all: a Zammad before 6.5.1 answers `with_total_count` under `expand` + # with the bare array. That is the gap this leaves. + # + # Reckoned in the page sizes that were asked for. An endpoint that pages + # smaller has covered fewer hits than this takes it to have, and the + # walk then ends on an empty page it might have read past - no earlier + # than it ended before the figure was read at all. + # + # What reading on costs is bounded by the same figure: a request per + # page of the hits the endpoint reports, and none beyond them. How large + # those pages are is what #widened is about. + # + # @param covered [Integer] the hits the pages read so far have covered + def hits_past?(covered, total) = !total.nil? && covered < total + + # Fetches one page: the records, the digest the repeated-page guard + # compares, and the size of the whole result where the endpoint reported + # it beside them. + # + # @return [Array(Array, Integer, Integer)] the records, + # the digest and the total + # @return [Array(Array, Integer, nil)] where no total + # was reported + def fetch(page, per_page) + response = @transport.get( + @path, + operation: @operation, + resource_class: @resource_class, + query: page_query(page, per_page) + ) + decoded, total = response.decoded_list(operation: @operation, resource_class: @resource_class) + # The digest for the repeated-page guard is taken here, from the decoded + # payload, which is the one structure that has everything the guard needs + # and is already in hand. See the guard in `walk` for why it is this and + # not the records or the raw body. + [decoded.map { @resource_class.from_response(@transport, it) }, page_digest(decoded), total] + end + + # The parameters of a request for one page. + # + # `with_total_count` goes out where the answer is read, which is a search + # being walked: see #hits_past?. An index drops the parameter along with + # everything else it does not know, and a collection limited to one page + # has no walk to end, so both are sent what they always were. + # + # It costs Zammad nothing it was not doing. model_search_render asks the + # search for the total on every request and leaves it out of the answer + # unless the parameter is there. + def page_query(page, per_page) + query = @query.merge(page: page, per_page: per_page) + + @search && @page.nil? ? query.merge(with_total_count: true) : query + end + + # What the repeated-page guard compares two pages by: which records they + # hold, where every record says which it is. + # + # The whole payload was the first answer, and it misses the repeat that + # matters most. A job that writes to the records it is handed changes + # what they serialize as - `updated_at`, if nothing else - so an endpoint + # that ignores `page` served the same records with a different payload + # every time. No two pages compared equal, every page was full, and the + # job went round the same records, writing to each of them again, for as + # long as it was left running. + # + # The ids as a set rather than as a list, because a write can reorder + # them too: a search sorts by `updated_at` unless told otherwise. + # + # The payload is still what is compared where a record carries no id. + # Compared by id, a page of those is a list of nils equal to every other + # such page, and a perfectly good paginator was reported as stuck. + # + # @return [Integer] + def page_digest(decoded) + ids = decoded.map { it[:id] } + + ids.include?(nil) ? decoded.hash : ids.to_set.hash + end + + # Asked only of a search endpoint, which is the only kind that answers + # +only_total_count+. Every one of them routes through + # model_search_render, which reads it before it reads anything else, so a + # shape other than the +{total_count: n}+ object means something has + # answered that is not the endpoint this was addressed to - a proxy error + # page, a login form - and the walk is the honest fallback. + # + # A negative figure is refused rather than trusted: it cannot describe a + # result, and a count is the one answer nothing downstream can sanity + # check - `Array.new(collection.count)` and `count.zero?` both take it at + # its word. + # + # @return [Integer, nil] nil when the endpoint did not report a total + def total_count + response = @transport.get( + @path, + operation: @operation, + resource_class: @resource_class, + query: @query.merge(only_total_count: true) + ) + return nil if !response.body.is_a?(Hash) + + total = response.body[:total_count] + total if total.is_a?(Integer) && !total.negative? + end + + # Reduced rather than refused, unlike the size {#page} takes. The + # asymmetry is deliberate: a batch size says how much to fetch at a time, + # so a smaller one costs more requests and still walks to the same last + # record, while {#page}'s size also decides which records the page holds, + # and reducing that answers a different question than the one asked. + # + # It is also what lets one batch size be written against resources that + # cap differently - the index endpoints allow 1000, tickets 100, a search + # 200 - without the caller looking each of them up. + def clamp_per_page(size) + raise ArgumentError, 'per_page needs to be a positive integer' if !size.is_a?(Integer) || !size.positive? + + [size, @max_per_page].min + end + end +end diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb new file mode 100644 index 0000000..67d253d --- /dev/null +++ b/lib/zammad_api/config.rb @@ -0,0 +1,508 @@ +# frozen_string_literal: true + +require 'logger' +require 'uri' + +require_relative 'errors' +require_relative 'version' + +module ZammadAPI + # Immutable, validated client configuration. + # + # Credentials are never included in {#inspect} output, so configuration + # objects are safe to log or attach to exception reports. + # + # @example + # ZammadAPI::Config.new(url: 'https://zammad.example.com/', http_token: 'secret') + # + # @!attribute [r] url + # @return [String] base URL, always with a trailing slash + # @!attribute [r] user + # @return [String, nil] login for basic authentication + # @!attribute [r] password + # @return [String, nil] password for basic authentication + # @!attribute [r] http_token + # @return [String, nil] Zammad access token + # @!attribute [r] oauth2_token + # @return [String, nil] OAuth2 bearer token + # @!attribute [r] user_agent + # @return [String] value of the +User-Agent+ request header + # @!attribute [r] timeout + # @return [Numeric] seconds to wait for a response + # @!attribute [r] open_timeout + # @return [Numeric] seconds to wait for the connection + # @!attribute [r] retries + # @return [Integer] retry attempts for a request that only reads + # @!attribute [r] retry_interval + # @return [Numeric] seconds before the first retry, doubling after that. + # A +Retry-After+ header takes its place, and no wait is longer than + # {#timeout}. + # @!attribute [r] ssl_verify + # @return [Boolean] whether TLS certificates are verified + # @!attribute [r] proxy + # @return [String, nil] proxy URL + # @!attribute [r] adapter + # @return [Symbol, nil] name of the Faraday adapter, +nil+ for Faraday's + # default + # @!attribute [r] middleware + # @return [Proc, nil] called with the Faraday connection while it is + # being built + # @!attribute [r] logger + # @return [Logger] where debug output goes + Config = Data.define( + :url, + :user, + :password, + :http_token, + :oauth2_token, + :user_agent, + :timeout, + :open_timeout, + :retries, + :retry_interval, + :ssl_verify, + :proxy, + :adapter, + :middleware, + :logger + ) + + class Config + # Seconds to wait for a response before raising {TimeoutError}. + DEFAULT_TIMEOUT = 60 + + # Seconds to wait for the connection to be established. + DEFAULT_OPEN_TIMEOUT = 10 + + # How often a request that only reads is retried on a transient failure. + DEFAULT_RETRIES = 2 + + # Seconds to wait before the first retry; doubles on each attempt. + DEFAULT_RETRY_INTERVAL = 0.5 + + # Attributes whose values must never be rendered. + REDACTED_ATTRIBUTES = %i[password http_token oauth2_token].freeze + + # Placeholder rendered in place of a credential. + REDACTION = '[REDACTED]' + + # Identifies this gem in the +User-Agent+ header. + DEFAULT_USER_AGENT = "zammad_api-ruby/#{ZammadAPI::VERSION}".freeze + + SCHEME_PATTERN = %r{\Ahttps?://}i + + # An absolute http(s) URL, authority included. The host is part of the + # pattern because a bare scheme - +https://+ - passed a scheme-only check + # and was accepted here, then failed deep inside the adapter on the first + # request instead of at construction, which is the opposite of the + # up-front validation the rest of this class exists for. + URL_PATTERN = %r{\Ahttps?://[^/?\#]+}i + + # Where a URL stops being the part a trailing slash belongs on. + URL_SUFFIX_PATTERN = /[?\#]/ + + # The scheme of a URL, where it has one. A proxy is configured without + # one as often as with - +u:p@proxy:8080+ is the shape an +http_proxy+ + # style setting is copied out of - so the redaction below cannot assume + # it. + URL_SCHEME_PATTERN = %r{\A[a-z][a-z0-9+.-]*://}i + + # What RFC 3986 calls the authority of a URL: everything up to the first + # +/+, +?+ or +#+ after the scheme. + URL_AUTHORITY_PATTERN = %r{\A[^/?\#]*} + + # The options each authentication scheme is made of. + CREDENTIAL_OPTIONS = { + http_token: %i[http_token], + oauth2_token: %i[oauth2_token], + basic: %i[user password] + }.freeze + + # Lays +overrides+ over +options+, dropping the credentials they replace. + # + # A configuration authenticates one way, so an override that names + # another has to take the old one's place, not sit beside it. A plain + # merge left both, and the old scheme in charge: with +ZAMMAD_TOKEN+ set, + # +Client.from_env(user: 'u', password: 'p')+ still sent the + # environment's token, and +client.with(oauth2_token: 'x')+ on a token + # client went on acting as the account the token belonged to. Neither + # raised, and both read as if they had switched identity. Two schemes + # side by side are refused outright now, which is what makes dropping + # the old one here necessary rather than merely right. + # + # An override that names a scheme therefore takes the place of every + # other scheme. The options of its own scheme are kept, so overriding + # +password:+ alone still pairs it with the +user+ already there. + # + # @api private + # @param options [Hash{Symbol => Object}] the options being overridden + # @param overrides [Hash{Symbol => Object}] + # @return [Hash{Symbol => Object}] + def self.merge_options(options, overrides) + named = CREDENTIAL_OPTIONS.select { |_, keys| keys.any? { !overrides[it].to_s.empty? } } + replaced = named.empty? ? [] : CREDENTIAL_OPTIONS.except(*named.keys).values.flatten + + options.except(*replaced).merge(overrides) + end + + def initialize( + url:, + user: nil, + password: nil, + http_token: nil, + oauth2_token: nil, + user_agent: DEFAULT_USER_AGENT, + timeout: DEFAULT_TIMEOUT, + open_timeout: DEFAULT_OPEN_TIMEOUT, + retries: DEFAULT_RETRIES, + retry_interval: DEFAULT_RETRY_INTERVAL, + ssl_verify: true, + proxy: nil, + adapter: nil, + middleware: nil, + logger: nil + ) + # RBS cannot describe the initializer that Data.define generates, so + # these keyword arguments are invisible to the type checker. + # steep:ignore:start + super( + url: immutable(normalize_url(url)), + user: immutable(presence(user)), + password: immutable(presence(password)), + http_token: immutable(presence(http_token)), + oauth2_token: immutable(presence(oauth2_token)), + user_agent: immutable(presence(user_agent) || DEFAULT_USER_AGENT), + timeout: timeout, + open_timeout: open_timeout, + retries: retries, + retry_interval: retry_interval, + ssl_verify: ssl_verify, + proxy: immutable(normalize_proxy(proxy)), + adapter: normalize_adapter(adapter), + middleware: middleware, + logger: logger || Logger.new(IO::NULL) + ) + # steep:ignore:end + validate_credentials! + validate_numbers! + validate_user_agent! + validate_header_options! + validate_ssl_verify! + validate_middleware! + validate_logger! + end + + # The instance URL, with any inline credentials blanked. + # + # A URL that carries credentials is refused when the configuration is + # built - see {#normalize_url} - but only where it can be read as a URL + # at all. One that cannot, such as a password with an unencoded +#+ in + # it, is still held here until building the connection rejects it, and + # this is what that error and {#inspect} print in the meantime. The host + # has to stay readable for the URL to be worth printing, so the + # credentials are replaced rather than the whole value. + # + # @return [String] + def redacted_url = redacted(url) + + # Blanks the credentials in any URL this configuration holds. + # + # Public because {Transport} has to scrub the values it configured out of + # an error message raised from deep inside Faraday or URI, which quotes + # the proxy URL it rejected - credentials and all. + # + # @api private + # @param value [String] a URL that may carry inline credentials + # @return [String] the same URL with the credentials blanked + def redacted(value) = redact_userinfo(value) + + # The one way this configuration authenticates. There is never more than + # one to choose between: see {#validate_credentials!}. + # + # @return [Symbol] +:http_token+, +:oauth2_token+ or +:basic+ + def authentication_scheme + return :http_token if http_token + return :oauth2_token if oauth2_token + + :basic + end + + # Returns a copy with some options changed, re-validated. + # + # Through {.merge_options} rather than Data's own merge, so that naming + # one authentication scheme replaces the one this configuration had. + # + # @param options [Hash] any option this class accepts + # @return [Config] + # @raise [ConfigurationError] when the resulting options are invalid + def with(**options) = self.class.new(**self.class.merge_options(to_h, options)) + + # @return [String] configuration description with credentials redacted + def inspect + rendered = to_h.map { |key, value| "#{key}=#{render(key, value)}" } + "#" + end + alias to_s inspect + + # What +pp+ prints, which is what IRB and the Rails console show for a + # value typed at the prompt. + # + # +pp+ does not go through {#inspect} for a Data object: it has a printer + # of its own that renders the members directly. So +client.config+ in a + # console, or +pp config+ in a script, printed the token, the password + # and the credentials of a proxy in full - from the class documented as + # safe to log, and through the one route most likely to be looked at. + # + # @api private + # @param printer [PP] + # @return [void] + def pretty_print(printer) = printer.text(inspect) + + private + + # Blanks the +user:password@+ part of a URL, keeping the host visible. + # + # Everything up to the last +@+ goes, rather than up to the first: a + # password may carry an unencoded one, and +pa@ss+ used to leave +@ss+ in + # the rendered URL. + # + # Which +@+ is the last one depends on whether a password can be there at + # all. Without a colon in the authority there is none, so the search + # stays inside the authority and an +@+ in a path, a query string or a + # fragment is left alone: +https://host?a=b@c+ used to render as + # +https://[REDACTED]@c+, a host that does not exist, in every + # ConnectionError message. + # + # With a colon, the search runs to the end of the value. A password is + # not obliged to be URL-safe, and one carrying +/+, +?+ or +#+ ends the + # authority early as far as the syntax goes: +http://user:p#ss@proxy+ has + # the authority +user:p+, which holds no +@+, so a search bounded by it + # found nothing to blank and printed the password - in {#inspect}, and in + # the ConfigurationError that quotes a proxy URL the HTTP stack rejected. + # The cost is a URL with a port and an +@+ further on, such as + # +https://host:8443/a@b+, which renders with its host blanked. A colon + # cannot tell a port from a password, and of the two mistakes that is the + # one that leaks nothing. + # + # @param value [String] a URL that may carry inline credentials + # @return [String] the same URL with the credentials blanked + def redact_userinfo(value) + scheme = value[URL_SCHEME_PATTERN].to_s + rest = value.delete_prefix(scheme) + authority = rest[URL_AUTHORITY_PATTERN].to_s + boundary = authority.include?(':') ? rest.rindex('@') : authority.rindex('@') + return value if boundary.nil? + + "#{scheme}#{REDACTION}#{rest[boundary..]}" + end + + def render(key, value) + return REDACTION if REDACTED_ATTRIBUTES.include?(key) && value + # Loggers and procs have verbose default inspect output that would drown + # out the rest of the configuration. + return "#<#{value.class}>" if key == :logger + return "#<#{value.class}>" if key == :middleware && value + return redacted_url.inspect if key == :url + return redact_userinfo(value).inspect if key == :proxy && value + + value.inspect + end + + # The type check comes before the pattern, because every check after it + # is a String method. A URI is the plausible mistake here - it is what + # `URI(...)` hands back and it prints as the URL - and it used to reach + # `end_with?` and die there as a NoMethodError, past the ConfigurationError + # a caller had wrapped the constructor in. + def normalize_url(value) + raise ConfigurationError, 'missing url in config' if presence(value).nil? + raise ConfigurationError, "config url needs to be a string, got #{value.class}" if !value.is_a?(String) + raise ConfigurationError, 'config url needs to start with http:// or https://' if !SCHEME_PATTERN.match?(value) + raise ConfigurationError, "config url needs a host after the scheme, got #{value.inspect}" if !URL_PATTERN.match?(value) + raise ConfigurationError, inline_credentials_message(value) if inline_credentials?(value) + + # A trailing slash keeps Zammad installations served from a sub-path + # (e.g. https://example.com/zammad/) working, because request paths are + # appended relative to this prefix. + # + # Onto the path, not onto the end of the string. Appended blindly it + # landed behind a query string or fragment, so a url of + # `https://host/zammad?a=1` became `https://host/zammad?a=1/` - the base + # every request is resolved against, and the value {#redacted_url} + # prints in every ConnectionError and TimeoutError message. + path, separator, rest = value.partition(URL_SUFFIX_PATTERN) + path.end_with?('/') ? value : "#{path}/#{separator}#{rest}" + end + + # Whether the URL carries a +user:password@+ of its own. + # + # Asked of URI, because that is the parser Faraday reads the URL with: + # whatever it finds there, Faraday turns into a Basic +Authorization+ + # header on the connection, and its authorization middleware then leaves + # a header that is already set alone. So a URL with credentials silently + # replaced the scheme this class validated - an access token configured + # beside it was never sent, while {Client#inspect} went on reporting + # +auth=http_token+. + # + # A URL that URI cannot read is left for the connection to reject, which + # it does before any request is made. + def inline_credentials?(value) + !URI.parse(value).userinfo.nil? + rescue URI::InvalidURIError + false + end + + def inline_credentials_message(value) + "config url carries credentials of its own (#{redact_userinfo(value)}), which would be sent as basic authentication " \ + 'in place of the ones this configuration names. Leave them out of the url and pass user: and password:, ' \ + 'or http_token: or oauth2_token:, instead.' + end + + # One way to authenticate, and only one. + # + # Several used to be accepted together, and {#authentication_scheme} + # picked the first of them in a fixed order without a word. That is what + # let an override leave the old credential in charge - a token beside a + # user and password it was meant to replace - and it is the same mistake + # wherever it comes from: a client that holds two identities sends one of + # them, and which one is not something the call site shows. Refused here, + # a configuration says how it authenticates by construction, and the + # merges that build one - {.merge_options} - have to drop what an + # override replaces rather than keep it beside the new value. + # + # Half of a scheme counts as naming it, so a token beside a +user+ that + # has no password is refused as two schemes rather than passed as one. + def validate_credentials! + given = CREDENTIAL_OPTIONS.select { |_, options| options.any? { !public_send(it).nil? } }.keys + raise ConfigurationError, multiple_credentials_message(given) if given.size > 1 + return if http_token || oauth2_token + + raise ConfigurationError, 'missing user in config' if user.nil? + raise ConfigurationError, 'missing password in config' if password.nil? + end + + def multiple_credentials_message(schemes) + named = schemes.map { CREDENTIAL_OPTIONS.fetch(it).join(' and ') }.join(', ') + + "config names more than one way to authenticate (#{named}), and a request can carry only one. " \ + 'Pass http_token:, or oauth2_token:, or user: and password:, and leave the others out.' + end + + # Numeric is not the whole test. Complex is one and answers neither + # `positive?` nor `>`, so `timeout: Complex(1, 2)` left a NoMethodError + # where every other rejected option raises ConfigurationError - the same + # escape normalize_adapter, normalize_proxy and validate_logger! were each + # written to close. + def positive_number?(value) = value.is_a?(Numeric) && value.respond_to?(:positive?) && value.positive? + + def validate_numbers! + { timeout: timeout, open_timeout: open_timeout, retry_interval: retry_interval }.each do |name, value| + raise ConfigurationError, "config #{name} needs to be a positive number" if !positive_number?(value) + end + + raise ConfigurationError, 'config retries needs to be a non-negative integer' if !retries.is_a?(Integer) || retries.negative? + end + + # Not just a default: `user_agent: nil` reached Faraday as a nil header, + # and Faraday filled in its own, so the gem stopped identifying itself in + # the instance log an operator greps to find its requests - silently, and + # on every request. + def validate_user_agent! + return if user_agent.is_a?(String) + + raise ConfigurationError, 'config user_agent needs to be a string' + end + + # The options that are sent as a header: the two tokens in + # +Authorization+, and the user agent. + HEADER_OPTIONS = %i[http_token oauth2_token user_agent].freeze + private_constant :HEADER_OPTIONS + + # A line break inside one of these was taken here and refused by + # Net::HTTP at the first request, with the value in the message: see + # {Transport.line_break?}. Refused here instead, without the value. A + # user and password are not checked: basic authentication sends them + # Base64-encoded, which carries a line break like anything else. + def validate_header_options! + HEADER_OPTIONS.each do |name| + value = public_send(name) + next if !value.is_a?(String) || !Transport.line_break?(value) + + raise ConfigurationError, "config #{name} holds a line break, which a header cannot carry: #{Transport::LINE_BREAK_ADVICE}" + end + end + + # A proxy is the second string here that may carry credentials, and the + # only other one rendered rather than replaced wholesale. Unchecked, a + # URI - what `URI(...)` hands back, and what prints as the URL - was + # accepted here and reached String#sub inside {#inspect}, so the object + # this class documents as safe to log raised NoMethodError at exactly the + # moment something tried to log it. The same mistake {#normalize_url} + # already refuses for the instance URL. + def normalize_proxy(value) + return nil if presence(value).nil? + raise ConfigurationError, "config proxy needs to be a string, got #{value.class}" if !value.is_a?(String) + + value + end + + # `adapter&.to_sym` accepted anything that answered to_sym and died with + # a bare NoMethodError on anything that did not - `adapter: 1` and + # `adapter: true` both escaped the ConfigurationError that building a + # client is documented to need, from inside the constructor, before any + # of the validators below ran. + def normalize_adapter(value) + return nil if presence(value).nil? + raise ConfigurationError, "config adapter needs to be a symbol or a string, got #{value.class}" if !value.is_a?(Symbol) && !value.is_a?(String) + + value.to_sym + end + + # The one option that fails open. Every other value here is checked up + # front, while ssl_verify was passed to Faraday as it arrived: read from + # an environment variable, `ssl_verify: 'false'` is the string "false", + # which is truthy, so the setting a caller believed they had turned off + # was silently still on. That direction is the safe one, which is why it + # went unnoticed - `ssl_verify: 'no'` disables nothing either way, but a + # caller who cannot tell which of their settings took effect has no way + # to find out. + def validate_ssl_verify! + return if [true, false].include?(ssl_verify) + + raise ConfigurationError, "config ssl_verify needs to be true or false, got #{ssl_verify.inspect}" + end + + def validate_middleware! + return if middleware.nil? || middleware.respond_to?(:call) + + raise ConfigurationError, 'config middleware needs to respond to call' + end + + # In 1.x this option was a flag, so `logger: true` is a plausible thing to + # carry over. Without this it would be accepted here and raise NoMethodError + # at the first request instead. + def validate_logger! + return if logger.respond_to?(:debug) + + raise ConfigurationError, 'config logger needs to respond to debug' + end + + def presence(value) + return nil if value.nil? + return nil if value.respond_to?(:empty?) && value.empty? + + value + end + + # Ruby leaves the members of a Data object mutable, so a caller-supplied + # String would otherwise stay writable through the config - and shared + # with the caller's own variable. Freezing a copy keeps a Config, and any + # Transport built from one, genuinely immutable. + # + # This deliberately copies rather than using String#-@: interning would + # keep a credential in the global fstring table for the life of the + # process, well past the config that held it. + def immutable(value) + value.is_a?(String) ? value.dup.freeze : value + end + end +end diff --git a/lib/zammad_api/deep_copy.rb b/lib/zammad_api/deep_copy.rb new file mode 100644 index 0000000..cc7e8db --- /dev/null +++ b/lib/zammad_api/deep_copy.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +module ZammadAPI + # Recursive copies of the plain JSON structures this gem passes around. + # + # Three places need the same walk - a record freezing the attributes it was + # built with, a record handing a copy of them back, and the test kit + # recording the payload a request carried - and each used to carry its own. + # A rule written three times is one that gets fixed in one of them: the + # test kit's copy already differed by not symbolizing keys, and nothing + # said whether that was the point or an oversight. + # + # Only Hash, Array and String are walked, because that is the whole of what + # +JSON.parse+ builds and what a caller may hand in as attributes. Numbers, + # booleans and nil are immutable already and are passed through untouched. + # + # One walk, deliberately. A record built from a response copies every String + # of a body +JSON.parse+ has just built and nothing else holds, so a variant + # that froze such a body in place would save that copy on the paging hot + # path - which is a real cost, and still not a reason for a second walk: + # three of them is what this module replaced, and the one that differed did + # so without anything to say whether the difference was the point. If the + # copy is worth removing, it is an argument to this walk and it applies to + # the one place that can prove nothing else references the value. + # + # @api private + module DeepCopy + module_function + + # A frozen deep copy. + # + # Named for what it returns rather than `freeze`/`dup`, which would shadow + # the Object methods of those names inside this module and read as them at + # every call site. + # + # Freezing is what makes a record's attribute hash safe to hand out: one + # that gave away a writable hash would report changes it never staged and + # so never sent. Strings are copied before being frozen, so freezing a + # value the caller passed in does not reach back into their own variable. + # + # Keys are left alone. Ruby copies and freezes an unfrozen String key on + # insertion, so a Hash built here never holds the caller's own String, and + # symbolizing produces an immutable key anyway - which leaves only an + # Array or a custom object as a key that this walk would change. `JSON` + # cannot build one, so it could only come from a caller's own attribute + # hash, and paying a call per key on the record-building path for it is + # the cost this module's own note above weighs and declines. + # + # @param value [Object] + # @param symbolize_keys [Boolean] whether Hash keys become Symbols, so + # that caller-supplied attributes behave the same as decoded responses + # @return [Object] a frozen copy + def frozen_copy(value, symbolize_keys: false) + case value + when Hash then value.to_h { |key, nested| [symbolize_keys ? symbolize(key) : key, frozen_copy(nested, symbolize_keys: symbolize_keys)] }.freeze + when Array then value.map { frozen_copy(it, symbolize_keys: symbolize_keys) }.freeze + when String then value.dup.freeze + else value + end + end + + # A writable deep copy, for handing out something callers may treat as + # their own. The inverse of {frozen_copy}. + # + # @param value [Object] + # @return [Object] an unfrozen copy + def writable_copy(value) + case value + when Hash then value.to_h { |key, nested| [key, writable_copy(nested)] } + when Array then value.map { writable_copy(it) } + when String then value.dup + else value + end + end + + # A key that cannot become a Symbol is left as it is rather than refused: + # it came from a caller's attribute hash, and a record is not the place + # to decide that Zammad will not accept it. + # + # @api private + def symbolize(key) = key.respond_to?(:to_sym) ? key.to_sym : key + end +end diff --git a/lib/zammad_api/dispatcher.rb b/lib/zammad_api/dispatcher.rb deleted file mode 100644 index 07b311b..0000000 --- a/lib/zammad_api/dispatcher.rb +++ /dev/null @@ -1,12 +0,0 @@ -module ZammadAPI - class Dispatcher - def initialize(transport, resource) - @transport = transport - @resource = resource - end - - def method_missing(method, *args) - @resource.send(method, @transport, args[0]) - end - end -end diff --git a/lib/zammad_api/duplicate_keys.rb b/lib/zammad_api/duplicate_keys.rb new file mode 100644 index 0000000..24e6aad --- /dev/null +++ b/lib/zammad_api/duplicate_keys.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +module ZammadAPI + # One rule for two keys that name the same parameter. + # + # Both places that normalise caller-supplied parameter names had to refuse a + # collision, because normalising is what creates one: {ResourceProxy#search} + # maps every keyword to a Symbol and {Transport.stringify_query} maps every key to a + # String, so `sort_by` and `'sort_by'` become one key and the value that + # arrived first is dropped without a word. Written twice, the two refusals + # had already drifted into two different sentences for the same mistake. + # + # @api private + module DuplicateKeys + module_function + + # Maps every key through the block, refusing two that land on one name. + # + # The key each name was first seen as is kept, so the message can print + # both spellings: naming only the second left the reader to guess the + # first, which in a parameter hash assembled across several merges is the + # whole of the debugging. + # + # @param hash [Hash] + # @param prefix [String, nil] the parameter path this Hash sits at, for a + # nested structure + # @param noun [String] what the caller calls one of these, for the message + # @yieldparam key [Object] a key to normalise + # @return [Hash] the hash with normalised keys and untouched values + # @raise [ArgumentError] for two keys that name the same thing + def normalize(hash, prefix: nil, noun: 'parameter') + seen = {} + + hash.each_with_object({}) do |(key, value), result| + name = yield(key) + raise ArgumentError, message(noun, prefix ? "#{prefix}[#{name}]" : name, seen[name], key) if seen.key?(name) + + seen[name] = key + result[name] = value + end + end + + # @api private + def message(noun, path, first, second) + "#{noun} #{path} was given twice, as #{first.inspect} and as #{second.inspect}: " \ + 'pass it once, so that which value reaches the endpoint does not depend on Hash order' + end + end +end diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index 4e07e1d..c5bd351 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -1,62 +1,201 @@ -require 'json' +# frozen_string_literal: true module ZammadAPI - class Error < RuntimeError; end + # Base class for every error raised by this gem. + # + # Rescuing +ZammadAPI::Error+ catches all of them. + class Error < StandardError + # Formats the " ()" fragment shared by error + # messages, so every error reads the same way. + # + # @api private + # @param operation [String] + # @param resource_class [Class, nil] + # @return [String] + def self.subject_for(operation, resource_class) + resource_class ? "#{operation} (#{resource_class.name})" : operation + end + end + # Raised when {Config} cannot be built from the supplied options. class ConfigurationError < Error; end - class ResourceNotFoundError < Error; end + # Raised when a resource name is requested that this client does not know + # about, e.g. +client.unicorn+. + class UnknownResourceError < Error; end + + # Base class for failures that prevented a request from completing. + class TransportError < Error; end + + # Raised when the connection to the Zammad instance could not be + # established (DNS, refused connection, TLS failure, ...). + class ConnectionError < TransportError; end + + # Raised when a request exceeded {Config#open_timeout} or {Config#timeout}. + class TimeoutError < TransportError; end + # Raised when a response did not have the shape the caller expected. + class ParseError < Error + # @param operation [String] + # @param expected [Symbol, String] +:object+, +:array+, or a longer + # description of the shape that was wanted + # @param actual [Class, String] the class that was decoded instead, or a + # description of it + # @param resource_class [Class, nil] + # @return [ParseError] + def self.build(operation:, expected:, actual:, resource_class: nil) + new("Can't #{subject_for(operation, resource_class)}: expected a JSON #{expected}, got #{actual}") + end + end + + # Raised when the server answers a page request with the page before it, + # which means it is ignoring +page+ and a collection walk would never end. + class PaginationError < Error + # @param operation [String] + # @param page [Integer] the page that repeated its predecessor + # @param resource_class [Class, nil] + # @return [PaginationError] + def self.build(operation:, page:, resource_class: nil) + new("Can't #{subject_for(operation, resource_class)}: page #{page} repeated page #{page - 1}, so the endpoint is ignoring the page parameter") + end + end + + # Base class for errors carrying an HTTP response. + # + # Use {.build} rather than +new+ to get the most specific subclass for a + # given status code. class ResponseError < Error - attr_reader :response, :operation, :resource_class + # @return [Response, nil] the decoded HTTP response + attr_reader :response + + # @return [String] human readable description of what was attempted + attr_reader :operation + + # @return [Class, nil] the resource class involved, when applicable + attr_reader :resource_class - def initialize(operation:, response:, resource_class: nil) + # Returns the most specific error class for +response+ and instantiates it. + # + # @param response [Response, nil] + # @param operation [String] + # @param resource_class [Class, nil] + # @return [ResponseError] + def self.build(response, operation:, resource_class: nil) + error_class_for(response).new( + response: response, + operation: operation, + resource_class: resource_class + ) + end + + # @api private + def self.error_class_for(response) + return self if response.nil? + + STATUS_ERRORS.fetch(response.status) do + response.status >= 500 ? ServerError : ClientError + end + end + private_class_method :error_class_for + + # @param operation [String] what was attempted + # @param response [Response, nil] + # @param resource_class [Class, nil] + # @param detail [String, nil] replaces the part of the message that would + # otherwise describe the response, for a failure that has none + def initialize(operation:, response: nil, resource_class: nil, detail: nil) @operation = operation @response = response @resource_class = resource_class - super(default_message) + @detail = detail + super(build_message) end + # The status this error carries, or - for one this gem raised without a + # request, such as {ResourceProxy#find_by!} finding nothing - the status + # its class is the name for. A NotFoundError used to answer nil there, + # so `rescue NotFoundError => e; retry if e.status == 404` quietly stopped + # retrying for the one NotFoundError that came from this gem rather than + # from Zammad, while every other one carried 404. + # + # @return [Integer, nil] HTTP status code def status - response&.status + response&.status || STATUS_ERRORS.key(self.class) end + # @return [Hash, String, nil] parsed JSON body, or the raw body for + # non-JSON responses def body response&.body end - def self.from(response, **kwargs) - klass = if response.nil? - self - elsif response.status >= 500 - ServerError - else - ClientError - end - klass.new(response: response, **kwargs) + # @return [Hash] response headers, empty when there is no response + def headers + response&.headers || {} + end + + # @return [String, nil] the error message reported by Zammad, if any + def server_message + return nil if !body.is_a?(Hash) + + # Symbol keys only: both decode paths - Transport#decode_body and the + # test kit - parse with symbolize_names, so a string-keyed body cannot + # reach here and the fallbacks that read one were never run. + value = body[:error_human] || body[:error] + value.to_s.empty? ? nil : value.to_s end private - def default_message - subject = resource_class ? "#{operation} (#{resource_class.name})" : operation - "Can't #{subject}: #{detail}" + def build_message + "Can't #{Error.subject_for(operation, resource_class)}: #{detail}" end def detail - body_error || "HTTP #{status}" + @detail || server_message || (status ? "HTTP #{status}" : 'no response') end + end + + # Any 4xx response that has no more specific subclass. + class ClientError < ResponseError; end + + # Any 5xx response. + class ServerError < ResponseError; end + + # 401 - credentials missing, wrong, or expired. + class AuthenticationError < ClientError; end + + # 403 - authenticated, but not permitted to perform the operation. + class AuthorizationError < ClientError; end + + # 404 - the requested record does not exist. + class NotFoundError < ClientError; end - def body_error - return nil if body.to_s.strip.empty? + # 422 - Zammad rejected the submitted attributes. + class ValidationError < ClientError; end - parsed = JSON.parse(body) - parsed.is_a?(Hash) ? parsed['error'] : nil - rescue JSON::ParserError - nil + # 429 - too many requests. + class RateLimitError < ClientError + # @return [Integer, nil] value of the +Retry-After+ response header + def retry_after + # Downcased, because every {Response} is built with its header keys + # downcased - {Transport#decode} and {Test#stub} both do it - so there + # is no capitalised spelling left to fall back to. + value = headers['retry-after'] + return nil if value.nil? + + Integer(value, exception: false) end end - class ClientError < ResponseError; end - class ServerError < ResponseError; end + class ResponseError + STATUS_ERRORS = { + 401 => AuthenticationError, + 403 => AuthorizationError, + 404 => NotFoundError, + 422 => ValidationError, + 429 => RateLimitError + }.freeze + private_constant :STATUS_ERRORS + end end diff --git a/lib/zammad_api/json_helper.rb b/lib/zammad_api/json_helper.rb deleted file mode 100644 index fd8ca4c..0000000 --- a/lib/zammad_api/json_helper.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'json' - -module ZammadAPI - module JsonHelper - def safe_json_parse(string) - JSON.parse(string) - rescue JSON::ParserError - {} - end - end -end diff --git a/lib/zammad_api/list_all.rb b/lib/zammad_api/list_all.rb deleted file mode 100644 index 393c56a..0000000 --- a/lib/zammad_api/list_all.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'zammad_api/list_base' - -module ZammadAPI - class ListAll < ListBase - private - - def perform_request(parameter) - request('all', @url, parameter) - end - end -end diff --git a/lib/zammad_api/list_base.rb b/lib/zammad_api/list_base.rb deleted file mode 100644 index c8b692c..0000000 --- a/lib/zammad_api/list_base.rb +++ /dev/null @@ -1,84 +0,0 @@ -require 'zammad_api/json_helper' - -module ZammadAPI - class ListBase - include Enumerable - include ZammadAPI::JsonHelper - - def initialize(resource, transport, parameter = {}) - @resource = resource - @url = @resource.get_url - @transport = transport - @parameter = { - page: 1, - per_page: 10, - expand: 'true', - }.merge(parameter) - end - - def [](position) - local_parameter = @parameter.merge( - page: position + 1, - per_page: 1 - ) - perform_request(local_parameter)[0] - end - - def page(page, per_page, &block) - @parameter[:page] = page - @parameter[:per_page] = per_page - fetch_and_yield_each(&block) - end - - def page_next(&block) - @parameter[:page] += 1 - fetch_and_yield_each(&block) - end - - def page_prev(&block) - @parameter[:page] -= 1 - fetch_and_yield_each(&block) - end - - def each(&block) - fetch_and_yield_each(&block) - end - - private - - def fetch_and_yield_each(&block) - result = perform_request(@parameter) - result.each(&block) - end - - def request(request, url, parameter) - # convert parameters into a GET query - url += '?' + parameter.map { |key, value| - if !value.is_a? String - value = value.to_s - end - - "#{key}=#{CGI.escape value}" - }.join('&') - - response = @transport.get(url: url) - if response.status != 200 - raise ResponseError.from(response, operation: "get .#{request} of object", resource_class: @resource.class) - end - - data = safe_json_parse(response.body) - - list = [] - data.each do |local_data| - item = @resource.new(@transport, local_data) - item.new_instance = false - list.push item - end - list - end - - def perform_request(_parameter) - raise Error, "no perform_request implementation for #{self.class.name} found" - end - end -end diff --git a/lib/zammad_api/list_search.rb b/lib/zammad_api/list_search.rb deleted file mode 100644 index fac7f2b..0000000 --- a/lib/zammad_api/list_search.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'zammad_api/list_base' - -module ZammadAPI - class ListSearch < ListBase - private - - def perform_request(parameter) - request('search', "#{@url}/search", parameter) - end - end -end diff --git a/lib/zammad_api/log.rb b/lib/zammad_api/log.rb deleted file mode 100644 index b67ad26..0000000 --- a/lib/zammad_api/log.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ZammadAPI - class Log - def initialize(config) - return if !config[:logger] - - require 'logger' - @logger = Logger.new($stderr) - #@logger.level = Logger::WARN - @logger.level = Logger::DEBUG - end - - def method_missing(method, *args) - return if !@logger - - @logger.send(method, args) - end - end -end diff --git a/lib/zammad_api/query_encoder.rb b/lib/zammad_api/query_encoder.rb new file mode 100644 index 0000000..fc90b6a --- /dev/null +++ b/lib/zammad_api/query_encoder.rb @@ -0,0 +1,162 @@ +# frozen_string_literal: true + +require 'faraday' + +module ZammadAPI + # Writes a query the way Rails reads it back into the structure it was. + # + # Faraday's own encoder did this, and does it for everything but a list of + # Hashes that do not all carry the same keys. A query string has no mark for + # where one element of a list ends: a list of Hashes goes out as + # `list[][key]=value` pairs, and Rack - and the parser Rails 8.1 has of its + # own, which follows it - starts a new element only when a pair names a key + # the element it is filling already has. Faraday writes the keys of every + # Hash in alphabetical order, so the first pair of an element named + # whichever of its keys sorts first, whether or not the element before had + # it. + # + # Zammad's expert conditions are such a list. A group of conditions nests + # them, and a group and a condition share `operator` and nothing else: + # + # conditions: [ + # {name: 'ticket.state_id', operator: 'is', value: [2]}, + # {operator: 'AND', conditions: [a, b]} + # ] + # + # The second element went out `conditions` first, which the first element + # does not have, so Rails read that into the first element and began the + # second at `operator`: one condition holding the whole group, followed by + # a group holding nothing. Zammad was handed a selector nobody wrote. It + # answered this one with a 500, and the same two elements the other way + # round with every ticket there is, as if no condition had been given. + # + # So an element that follows another Hash is written with a value the two + # both have a place for first - see {.lead_path} - and the rest in the + # order they always were. Where there is no such value no order works, and + # {Transport.stringify_query} refuses the query before it gets here. + # + # The escaping is still Faraday's: this hands it the pairs in order, which + # its encoder keeps for a list where it sorts a Hash. + # + # @api private + module QueryEncoder + module_function + + # @param params [Hash, nil] a query as {Transport.stringify_query} leaves + # it + # @return [String, nil] the query string, nil for no query + def encode(params) + return nil if params.nil? + + Faraday::NestedParamsEncoder.encode(hash_pairs(nil, params.to_hash, nil)) + end + + # Reading a query string back is not this module's business, and Faraday + # asks whatever encodes for it: a query written into the instance URL is + # decoded on the way in. + # + # @param query [String, nil] + # @return [Hash, nil] + def decode(query) = Faraday::NestedParamsEncoder.decode(query) + + # The value to write first for a Hash that follows another in a list, so + # that Rails begins a new element with it: one the element before has a + # place for as well, named by the keys that lead to it. + # + # A plain value, reached through Hashes alone. The pair that writes it + # names every key on the way down, and Rails begins a new element where + # the element it is filling has all of them already. A value inside a + # list never begins one, whatever the element before holds. + # + # @param element [Hash] + # @param previous [Object] the element before it + # @return [Array, nil] the keys leading to the value, outermost first. + # nil where no value will do, and where none is needed: the element is + # the first, or follows something that is not a Hash, and begins a new + # one whatever is written first + def lead_path(element, previous) + return nil if !previous.is_a?(Hash) + + sorted_keys(element).each do |key| + # Taken in the element before only where something was written for + # it there. A Hash with no value in it is not written, so the key is + # missing from what Rails read, and a pair naming it is read into + # that element rather than beginning the next. + next if !previous.key?(key) || !written?(previous[key]) + + value = element[key] + next if value.is_a?(Array) + return [key] if !value.is_a?(Hash) + + inner = lead_path(value, previous[key]) + return [key, *inner] if inner + end + + nil + end + + # Why Rails could not read an element of a list back as it was written, + # where it could not. + # + # +:merged+ is a Hash it would read into the Hash before it, there being + # no value to begin a new element with. +:empty+ is a Hash nothing is + # written for, which leaves the list one element short. +:list+ is a + # list directly inside a list: both are written `[]`, and each value of + # the inner one is read as a list of its own. + # + # @param element [Object] + # @param previous [Object] the element before it, nil for the first + # @return [Symbol, nil] nil for an element that is read back as it was + def misread(element, previous) + return :list if element.is_a?(Array) + return nil if !element.is_a?(Hash) + return :empty if !written?(element) + + :merged if previous.is_a?(Hash) && lead_path(element, previous).nil? + end + + # Whether anything is written for a value. Nothing is for a Hash with + # nothing in it, or with nothing but such Hashes in it, so as an element + # of a list it is not there for Rails to read. + # + # @return [Boolean] + def written?(value) = !value.is_a?(Hash) || value.each_value.any? { written?(it) } + + # @param lead [Array, nil] the keys leading to the value to write first + # @return [Array] one pair per value, in the order + # they are written + def hash_pairs(prefix, hash, lead) + keys = sorted_keys(hash) + keys = [lead.first, *(keys - [lead.first])] if lead + + keys.flat_map do |key| + # The rest of the way to the value, for the key that leads to it. + inner = lead && key == lead.first && lead.size > 1 ? lead.drop(1) : nil + + value_pairs(prefix ? "#{prefix}[#{key}]" : key.to_s, hash[key], inner) + end + end + + def value_pairs(path, value, lead = nil) + case value + when Hash then hash_pairs(path, value, lead) + when Array then array_pairs("#{path}[]", value) + else [[path, value]] + end + end + + def array_pairs(path, array) + # A list with nothing in it is written as its name alone, which is what + # Faraday wrote for one. + return [[path, nil]] if array.empty? + + array.each_with_index.flat_map do |element, index| + next value_pairs(path, element) if !element.is_a?(Hash) + + hash_pairs(path, element, index.zero? ? nil : lead_path(element, array[index - 1])) + end + end + + def sorted_keys(hash) = hash.keys.sort_by(&:to_s) + end +end diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb new file mode 100644 index 0000000..a830b1c --- /dev/null +++ b/lib/zammad_api/resource_proxy.rb @@ -0,0 +1,611 @@ +# frozen_string_literal: true + +require 'forwardable' + +require_relative 'collection' +require_relative 'deep_copy' +require_relative 'duplicate_keys' +require_relative 'errors' +require_relative 'transport' + +module ZammadAPI + # Entry point for working with one kind of Zammad record. + # + # Obtained from {Client}, e.g. +client.tickets+, and exposes the operations + # that are not tied to an individual record. + # + # @example + # client.groups.find(1) + # client.groups.create(name: 'Support') + # client.groups.all.each { |group| puts group.name } + # client.groups.order(:name).first(5) + # client.groups.search('support').first + # + # A proxy is +Enumerable+ over {#all}, so the collection surface is reachable + # without naming it: + # + # @example + # client.groups.each { |group| puts group.name } + # client.groups.first(5) + # client.groups.map(&:name) + # client.groups.find_each(batch_size: 500) { |group| archive(group) } + # + # {#find} takes an id and is not +Enumerable#find+; +detect+ is still the + # block form. + class ResourceProxy + include Enumerable + extend Forwardable + + # Largest page size Zammad's search endpoints serve, from + # ApplicationController#model_search_render. + SEARCH_MAX_PER_PAGE = 200 + + # What every one of Zammad's search endpoints narrows by besides the term: + # the two parameters that CanSearch, the part all of them share, reads out + # of the call ApplicationController#model_search_render makes into + # Model.search. Unlike an index endpoint a search does narrow, but through + # these parameters and the term - never through an attribute name of its + # own. + # + # That call hands over +role_ids+, +group_ids+ and +permissions+ as well, + # and they used to be in this list for it. Only the user search reads + # them, so a resource says which of them its search takes: see + # {Resources::Base.search_filters}. + SEARCH_FILTER_KEYS = %i[condition ids].freeze + + # Why a search term with nothing in it is refused, and what to write + # for the answer Zammad would have given it: see {#search}. + BLANK_TERM_MESSAGE = 'search needs a non-empty query string: Zammad reads a blank one as no term at all and answers with ' \ + "every record. Search for '*' to ask for every record." + + # Said at the end of the error for sorting an index endpoint that is + # always served in id order, on a resource that can be searched. + SEARCHABLE_UNSORTABLE_HINT = 'A search does sort: search(term).order(...). Or sort what this collection yields, with sort_by { ... }.' + + # The same, for a resource Zammad routes no search endpoint for. + UNSORTABLE_HINT = 'Sort what this collection yields instead, with sort_by { ... }.' + + # @return [Class] the resource class this proxy operates on + attr_reader :resource_class + + # @api private + def initialize(transport, resource_class) + @transport = transport + @resource_class = resource_class + end + + # Builds an unsaved record. + # + # @param attributes [Hash] + # @return [Resources::Base] + def new(attributes = {}) + resource_class.new(@transport, attributes) + end + + # Builds and immediately saves a record. + # + # This raises when Zammad rejects the attributes, rather than handing back + # a record that looks created but is not. Use +new+ and + # {Resources::Base#save} to branch on a validation failure instead. + # + # @param attributes [Hash] + # @return [Resources::Base] + # @raise [ResponseError] when Zammad rejected the request + def create(attributes = {}) + record = new(attributes) + record.save! + record + end + + # Fetches a single record by id. + # + # @param id [Integer, String] + # @return [Resources::Base] + # @raise [NotFoundError] when no such record exists + def find(id) = resource_class.fetch_one(@transport, id) + + # Fetches the first record carrying all of these attribute values, from + # the candidates Zammad hands over: nil if none of them does. + # + # It answers for every resource and every kind of value. Where it walks + # the index, the candidates are every record this client can read, and nil + # means there is no such record. Where it searches, they are the hits, and + # nil means no hit carried the values - which is the same thing only for a + # value the search looks at. See "What the search can surface" below for + # which those are. Zammad cannot be asked the question directly - + # its index endpoints do not filter: ApplicationController#model_index_render + # sorts and pages and drops every other parameter, so a query parameter on + # the index, which is how this was first written, asked for + # +email=someone@example.com+ and got back the whole user index, of which + # it returned the first record. So the candidates are fetched and checked + # here, and there are two ways to fetch them: + # + # - A search, where the resource has a search endpoint and one of the + # values is a string to search on. That is the cheap way: Zammad narrows + # the candidates, and only the hits are read. + # - A walk of the index, everywhere else: +ticket_states+, + # +ticket_priorities+ and +ticket_articles+, which Zammad routes no + # search endpoint for, and a lookup such as +find_by(active: true)+ or + # +find_by(organization_id: 5)+ that has no string in it. That costs a + # request per page of records until one matches, and the whole index for + # a miss - nothing for a list of ticket states, and worth knowing before + # it is run against every ticket on an instance. + # + # Both used to be refused instead: a resource without a search endpoint + # raised, and so did a lookup without a string value. The caller was left + # to write +all.detect { ... }+, which is the walk this now makes, so the + # refusals kept nothing from happening and made +find_by+ a method that + # worked on four resources out of seven. + # + # Values are compared exactly, and against the record as Zammad stores it: + # +find_by(email: 'Someone@Example.com')+ does not match a login Zammad + # downcased. A record that does not carry an attribute does not match it, + # whatever the value - not even +nil+, which would otherwise match every + # record a misspelled name was asked of. + # + # The search term is one string value. Zammad searches by word, so a value + # of another type would go out as the word it prints as: +find_by(active: + # true)+ searched for "true" and matched records carrying that word, which + # is essentially none of them. Such a value is compared here instead. + # + # One value, never all of them joined. An instance searching without + # Elasticsearch matches the term literally, through a SQL LIKE over the + # string columns, so a joined term asks every column to contain the whole + # of it: +find_by(firstname: 'Jane', lastname: 'Doe')+ went out as "Jane + # Doe" and no column of Jane Doe's holds that, so a user that exists came + # back as nil and the +find_by(...) || create(...)+ this documents made a + # duplicate on every run. Single-attribute lookups were unaffected, which + # is why it stood. The longest value goes out, as the most selective of + # them, and every other value is compared here - which is where the + # non-string ones are compared anyway, so +find_by(email: ..., active: + # true)+ searches the email and then checks both. + # + # Values go out as they are. Quoting one that carries search syntax, so + # that it is looked for rather than obeyed, sounds like an improvement and + # is not: an instance searching without Elasticsearch matches the term + # literally, through a SQL LIKE over the string columns, so the quotes + # become characters the value has to contain. That made + # +find_by(name: 'support-eu')+ - a hyphen is syntax - find nothing on + # every such instance, which is how this was found. + # + # So a value carrying syntax is searched as syntax, and what that surfaces + # depends on the backend. On Elasticsearch +find_by(note: 'a AND b')+ goes + # out as a boolean query, and a value Elasticsearch cannot parse at all - + # an unbalanced +(+ or +"+ - takes SearchIndexBackend#search_by_index down + # the branch that logs the error and returns no hits, so it arrives here + # as a miss rather than as a failure. + # + # What the search can surface is Zammad's business. A value the instance + # has not indexed, or cannot index, is a record this does not find, so + # +find_by(...) || create(...)+ can still create a duplicate - exactly as + # writing the search out by hand would. + # + # Which values those are depends on the backend. Elasticsearch looks for + # the term in everything a record is indexed with. Without it the term is + # matched by the SQL LIKE mentioned above, and that reads a fixed set of + # columns: CanSearch takes the string columns of the model's own table, + # which covers users, organizations and groups, and Ticket::Search + # replaces that with the ticket's title and number and the from, to, + # subject and body of its articles. A name +expand+ adds for an + # association is not a column at all. So on such an instance + # +tickets.find_by(state: 'open')+, a ticket looked up by a custom + # attribute, and +users.find_by(organization: 'Acme')+ are searches for a + # word in fields that do not hold the value. They find the record only + # where the word happens to appear in one of those fields too, and + # otherwise answer nil for a record that exists. + # + # There is no walk of the index after a search that found nothing, which + # would close that gap. A miss is the ordinary case for what this is most + # used for - +find_by(email: ...) || create(...)+ on an address that is + # new - and the walk would turn each of them into a read of every user on + # the instance, a thousand to the request, to confirm what the search had + # already said correctly. Nothing here can tell that miss from one caused + # by a field the search does not read, because nothing in a response says + # which backend answered. The caller does know which lookup they are + # writing: +detect { ... }+ on the resource is the walk, over every + # record this client may read. Compared with +[]+ there, as it is below, + # because a reader raises for an attribute the record in hand does not + # carry and would end the walk on it. + # + # Every page of hits is read until one matches. Only the first + # {SEARCH_MAX_PER_PAGE} used to be, to keep a miss at one request, on the + # premise that hits come back by relevance and an exact match is at the + # top of them or nowhere. They do not: Zammad's search endpoints sort by + # +updated_at+, newest first, unless told otherwise, on the SQL path and + # the Elasticsearch one alike. So where more than a page of records + # matched the term - +find_by(name: 'Support')+ among a few hundred + # organizations with "Support" in their name - the one called exactly + # that could sit on any page, +find_by+ answered +nil+ for a record that + # exists, and +find_by(...) || create(...)+ created its duplicate. + # + # So a match costs as many requests as it takes to reach it, and a miss + # costs one per page of hits. The longest value is searched to keep + # those few. + # + # @example + # client.users.find_by(email: 'someone@example.com')&.id + # client.ticket_states.find_by(name: 'open') + # client.users.find_by(organization_id: 5, active: true) + # + # @param params [Hash] attribute names and the values to match exactly + # @return [Resources::Base, nil] nil when nothing matched + # @raise [ArgumentError] when no attribute was given + def find_by(**params) + raise ArgumentError, 'find_by needs at least one attribute to match' if params.empty? + + term = resource_class.searchable? ? search_term_for(params) : nil + candidates = term ? search(term) : all + + candidates.detect { |record| params.all? { |key, value| record.key?(key) && record[key] == value } } + end + + # Fetches the first record carrying all of these attribute values, raising + # when nothing matched. + # + # @param params [Hash] attribute names and the values to match exactly + # @return [Resources::Base] + # @raise [NotFoundError] when nothing matched + # @see #find_by + def find_by!(**params) + find_by(**params) || raise( + NotFoundError.new( + operation: "find object by #{params.keys.join(' and ')}", + resource_class: resource_class, + detail: 'no record matched' + ) + ) + end + + # Whether a record with this id exists. + # + # This costs one request, and reads the record to find out, because Zammad + # has no cheaper answer for a single id. + # + # @param id [Integer, String] + # @return [Boolean] + def exists?(id) + find(id) + true + rescue NotFoundError + false + end + + # Deletes a record by id, without fetching it first. + # + # @param id [Integer, String] + # @return [true] + # @raise [ResponseError] when Zammad rejected the request + def destroy(id) + @transport.delete(member_path(id), operation: 'destroy object', resource_class: resource_class) + true + end + + # Every record of this kind, as a lazily paginated collection. + # + # @return [Collection] + def all + collection(path, 'get .all of object') + end + + # @!group Collection shorthands + + # Everything below forwards to {#all}, the {Collection} that decides for + # itself what a missing block means and what a page size is measured + # against. + # + # Named once rather than written out one +def+ at a time. Each was a body + # that did nothing but pass its arguments on, and three carried a + # +steep:ignore+ because forwarding into {Collection}'s with-block and + # without-block overloads cannot be resolved - forwarded by name there is + # no call site left to resolve. What callers are checked against is + # sig/zammad_api/resource_proxy.rbs, where each of these is declared with + # the types {Collection} gives it. + + # @!method order(*attributes, **directions) + # Every record of this kind, sorted by the server. Shorthand for + # +all.order(...)+. + # @example + # client.groups.order(:name) + # client.organizations.order(name: :desc) + # @param attributes [Array] attributes to sort by, + # ascending + # @param directions [Hash{Symbol => Symbol, String}] attributes to sort + # by, each with +:asc+ or +:desc+ + # @return [Collection] + # @raise [ArgumentError] for a resource whose index endpoint does not + # sort + # @see Collection#order + + # @!method each(&block) + # Yields every record of this kind, fetching pages as needed. + # + # This is what makes a proxy +Enumerable+, so +first+, +map+, +lazy+ + # and the rest work straight off +client.groups+. + # @yieldparam record [Resources::Base] + # @return [Enumerator] when no block is given + # @see Collection#each + + # @!method find_each(batch_size: nil, &block) + # @param batch_size [Integer, nil] records fetched per request + # @yieldparam record [Resources::Base] + # @return [Enumerator] when no block is given + # @see Collection#find_each + + # @!method in_batches(of: nil, &block) + # @param of [Integer, nil] records fetched per request + # @yieldparam records [Array] + # @return [Enumerator] when no block is given + # @see Collection#in_batches + + # @!method page(number, per_page: nil) + # @param number [Integer] one-based page number + # @param per_page [Integer, nil] records on the page, as many as the + # endpoint serves by default + # @return [Collection] + # @see Collection#page + + # @!method pluck(*keys) + # @param keys [Array] attribute names + # @return [Array] + # @see Collection#pluck + + # @!method count(*args, &block) + # Overrides +Enumerable#count+ so that a collection counts the way it + # knows how. + # @return [Integer] + # @see Collection#count + + # @!method size + # @return [Integer] + # @see Collection#size + + # @!method length + # @return [Integer] + # @see Collection#size + + # @!method empty? + # @return [Boolean] + # @see Collection#empty? + + # @!method first(count = nil) + # Overrides +Enumerable#first+ so that it reads one sized page rather + # than taking records off the front of one sized for walking. + # @param count [Integer, nil] how many records to read + # @return [Resources::Base, Array, nil] + # @see Collection#first + + # @!method take(count) + # @param count [Integer] how many records to read + # @return [Array] + # @see Collection#take + + def_delegators :all, :order, :each, :find_each, :in_batches, :page, :pluck, :count, :size, :length, :empty?, :first, :take + + # @!endgroup + + # Records matching a Zammad search term, as a lazily paginated collection. + # + # The keywords are the other things a search endpoint narrows by. They + # are named here, on the call that searches, because they mean nothing + # anywhere else: they used to be passed to +where+ on the collection this + # returns, the one place that method accepted more than a sort. + # + # Anything else is refused rather than sent. Zammad drops a parameter it + # does not know, so +search('smith', active: true)+ would come back + # unnarrowed and nothing would say so. An attribute value belongs in the + # term, and a sort in {Collection#order}. + # + # That goes for a keyword another resource's search reads, too. + # +role_ids:+, +group_ids:+ and +permissions:+ narrow a user search and no + # other, and +client.tickets.search('printer', group_ids: [2])+ was sent + # as written and answered with tickets from every group the client can + # read. Tickets are narrowed by group through a +condition+ on + # +ticket.group_id+. + # + # +group_ids:+ comes in two forms, and they do not ask for the same + # thing. User::Search walks it as pairs of a group and an access, and + # HasGroups.group_access reads an access that is missing as +full+. So a + # list of ids, which names none, is the agents with full access to those + # groups, and +group_ids: [2]+ leaves out an agent who may only read + # group 2. A Hash names the access for each group, and +full+ always + # counts as having it: +group_ids: {2 => ['read']}+ is every agent with + # read or full access to group 2. + # + # A keyword with nothing in it is refused as well: an empty list, an + # empty Hash, a blank String. Zammad reads each of those as the keyword + # not having been given, the way it reads one it does not know. CanSearch + # narrows by +ids+ only where +params[:ids].present?+, so + # +search('smith', ids: allowed_ids)+ with no id allowed came back with + # every user matching the term, where the caller had asked for none of + # them. +role_ids+, +group_ids+ and +permissions+ are skipped the same + # way where the search runs through Elasticsearch, and an empty + # +condition+ does not reach the request at all. + # + # +permissions:+ is not an access check, and is sent as it is given all + # the same, because what it does is Zammad's to decide. User::Search + # resolves it to the roles granting one of the permissions and adds them + # to +role_ids+, so the two together widen each other. On the + # Elasticsearch path the role clause is then written only where there is + # a role to put in it: a permission no active role grants - a misspelt + # one, or one nobody has been given - resolves to none, the clause is + # left out, and the search answers with every user matching the term. + # The SQL path joins the roles against the empty list and answers with + # nobody. Nothing in a response says which path answered, and a user + # record carries role ids rather than permissions, so there is nothing + # here to check the hits against. +role_ids:+ with at least one id + # narrows on both paths. + # + # +role_ids:+ is no access check either. Both paths ask who holds the + # role - the SQL one joins the roles a user has, the Elasticsearch one + # matches the role ids a user is indexed with - and neither asks whether + # the role is active, which is what Zammad asks before it grants + # anything through one: Role.with_permissions leaves a disabled role + # out. Neither asks whether the user is active. So a user matches a role + # that grants nothing any more, and the hits are who to look at, not who + # may. + # + # @example + # client.users.search('smith') + # client.users.search('smith', role_ids: [2]) + # client.users.search('smith', group_ids: [2]) # full access to group 2 + # client.users.search('smith', group_ids: {2 => ['read']}) # read or full access to it + # client.tickets.search('printer', condition: {'ticket.state_id' => {operator: 'is', value: [1, 2]}}) + # client.tickets.search('state.name:open').order(created_at: :desc) + # + # A term with nothing in it is refused: Zammad reads it as no term, and + # answers with every record the filters and the account allow, which is + # what a search for a blank +params[:q]+ ought not to come back with. + # Nothing is what Rails calls blank, Unicode spaces included. `'*'` + # asks for that answer in so many words, which is how Zammad's own + # interface lists every user or organization, and is sent. + # + # @param term [String] the Zammad search term, `'*'` for every record + # @param filters [Hash] +condition:+ and +ids:+ on every search, and on + # users +role_ids:+, +permissions:+ and +group_ids:+ - the last as a + # list of group ids, for agents with full access to them, or as a Hash + # of group id to +read+, +create+, +change+, +overview+ or +full+, one + # or several + # @return [Collection] + # @raise [ArgumentError] when +term+ is not a non-empty string, or for a + # keyword the search endpoint does not read, a nil value, a keyword + # with nothing in it, two spellings of one key, or a list a query + # string cannot carry: see {Transport.stringify_query_list} + # @raise [Error] when Zammad routes no search endpoint for this resource + def search(term, **filters) + searchable! + raise ArgumentError, BLANK_TERM_MESSAGE if !term.is_a?(String) || Transport::BLANK.match?(Transport.wire_text(term, 'the search term')) + + collection( + "#{path}/search", + 'get .search of object', + # A copy of the term and the filters, taken here. The collection is + # lazy, so it reads them when it is enumerated, and it was reading the + # caller's own objects: `search('printer', ids: ids)` followed by + # `ids << 7`, or a term built up in a buffer that is then reused, + # searched for something other than what this call was given - after + # it had been checked, and with the collection already handed on. + query: DeepCopy.frozen_copy({ query: term }.merge(search_filters(filters))), + max_per_page: SEARCH_MAX_PER_PAGE, + sortable: true, + search: true + ) + end + + def inspect = "#<#{self.class.name} #{resource_class.name}>" + + private + + def collection(path, operation, query: {}, max_per_page: resource_class.page_limit, sortable: resource_class.sortable?, search: false) + Collection.new( + transport: @transport, + resource_class: resource_class, + path: path, + operation: operation, + max_per_page: max_per_page, + sortable: sortable, + unsortable_hint: resource_class.searchable? ? SEARCHABLE_UNSORTABLE_HINT : UNSORTABLE_HINT, + search: search, + query: { expand: true }.merge(query) + ) + end + + # The keywords of a search, checked at the call that wrote them. + # + # Through {Transport.stringify_query} for the refusals it makes at any + # depth - a nil value, two spellings of one key inside a +condition+, + # and a list of conditions a query string cannot keep apart - because + # left to the request they would be reported when the collection is + # first enumerated, some lines away from the search that wrote them. + # What it returns is what each keyword is asked about below, and not what + # is sent: the collection sends the values as they were given - a copy of + # them, see {#search} - and the transport stringifies them then, the + # same way. + # + # @return [Hash{Symbol => Object}] + # @raise [ArgumentError] + def search_filters(filters) + normalized = DuplicateKeys.normalize(filters) { it.to_s.to_sym } + unknown = normalized.keys - search_filter_keys + raise ArgumentError, unknown_search_filter_message(unknown) if !unknown.empty? + + sent = Transport.stringify_query(normalized) + empty = normalized.select { |name, _| empty_search_filter?(sent.fetch(name.to_s)) } + raise ArgumentError, empty_search_filter_message(empty) if !empty.empty? + + normalized + end + + # Whether Zammad would read a keyword's value as the keyword not having + # been given: what Rails calls blank, asked of the value as it goes on + # the wire. Asked of that and not of the value as given, because a + # Symbol or anything else with an empty +to_s+ is sent as an empty + # String, and a Hash that holds nothing but empty Hashes is not written + # at all - `condition: {'ticket.state_id' => {}}` left the request + # without a +condition+. + # + # Asked of the keyword's own value and not of what is nested in it - a + # +condition+ naming an attribute with an empty +value+ is a selector, + # and what that selects is Zammad's to say. An empty list is written, + # so a Hash holding one is not empty here. + # + # Blank as Rails reads it, Unicode spaces included: see + # {Transport::BLANK}. + # + # @param value [String, Array, Hash] as {Transport.stringify_query} + # leaves it + def empty_search_filter?(value) + case value + when String then Transport::BLANK.match?(value) + when Array then value.empty? + else !QueryEncoder.written?(value) + end + end + + def empty_search_filter_message(empty) + given = empty.map { |name, value| "#{name}: #{value.inspect}" }.join(', ') + + "search was given #{given} on #{path}, and Zammad reads a keyword with nothing in it as one that was not given: " \ + 'the search would come back with everything matching the term, not narrowed to nothing. ' \ + 'Leave the keyword out to search without it, and skip the search where there is nothing it may find.' + end + + # What the search endpoint of this resource narrows by besides the term. + # + # @return [Array] + def search_filter_keys = SEARCH_FILTER_KEYS + resource_class.search_filter_names + + def unknown_search_filter_message(unknown) + "search does not take #{unknown.join(', ')} on #{path}: this search endpoint narrows by the term, and by #{search_filter_keys.join(', ')}, " \ + 'and drops anything else, which would hand back an unnarrowed search. ' \ + "Put an attribute value in the term - search('state.name:open') - or in a condition - " \ + "search(term, condition: {'ticket.group_id' => {operator: 'is', value: [2]}}) - " \ + 'sort with search(term).order(...), and page with page, in_batches or find_each.' + end + + # Zammad routes a search endpoint per model, not for every model: users, + # organizations, tickets and groups have one, ticket states, ticket + # priorities and ticket articles do not. Asking one of the latter for + # `.../search` is a 404, which would arrive as a NotFoundError about a + # record from a call that asked for a list. + def searchable! + return if resource_class.searchable? + + raise Error, "Zammad routes no search endpoint for #{resource_class.name}, so it cannot be searched by term: #{path}/search answers 404, which would arrive here as a NotFoundError about a record. Look one record up by attribute value with find_by, which walks the records where it cannot search, or pick several out with select { ... }." + end + + # The one value {#find_by} searches on: the longest, as the most selective + # of them, which matters because a miss reads every page of hits. + # + # One value rather than all of them joined, and unquoted - both spellings + # find nothing on an instance without Elasticsearch, for the same reason. + # See {#find_by}. + # + # @return [String, nil] nil when no value can be searched on, in which + # case the index is walked instead + def search_term_for(params) = params.values.grep(String).reject { it.strip.empty? }.max_by(&:length) + + def path = resource_class.resource_path + + def member_path(id) = resource_class.member_path(id) + end +end diff --git a/lib/zammad_api/resources.rb b/lib/zammad_api/resources.rb index 8106a4d..f388c7d 100644 --- a/lib/zammad_api/resources.rb +++ b/lib/zammad_api/resources.rb @@ -1,17 +1,17 @@ -require 'zammad_api/list_base' -require 'zammad_api/list_all' -require 'zammad_api/list_search' -require 'zammad_api/resources/base' -require 'zammad_api/resources/user' -require 'zammad_api/resources/group' -require 'zammad_api/resources/organization' -require 'zammad_api/resources/ticket' -require 'zammad_api/resources/ticket_article' -require 'zammad_api/resources/ticket_article_attachment' -require 'zammad_api/resources/ticket_state' -require 'zammad_api/resources/ticket_priority' +# frozen_string_literal: true + +require_relative 'resources/base' +require_relative 'resources/group' +require_relative 'resources/organization' +require_relative 'resources/ticket' +require_relative 'resources/ticket_article' +require_relative 'resources/ticket_article_attachment' +require_relative 'resources/ticket_priority' +require_relative 'resources/ticket_state' +require_relative 'resources/user' module ZammadAPI - class Resource # rubocop:disable Lint/EmptyClass + # Namespace for the Zammad record classes. + module Resources end end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 2652c4d..b82317e 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -1,140 +1,975 @@ -require 'cgi' -require 'zammad_api/json_helper' -require 'zammad_api/transport' +# frozen_string_literal: true + +require_relative '../associations' +require_relative '../attribute_access' +require_relative '../deep_copy' +require_relative '../errors' +require_relative '../transport' module ZammadAPI module Resources + # Shared behaviour for every Zammad record. + # + # Attributes are read and written through +method_missing+, because Zammad + # records can carry administrator-defined custom attributes: + # + # group = client.groups.find(1) + # group.name # read + # group.name = 'Support' # stage a change + # group.changed? # => true + # group.save # persist class Base - include ZammadAPI::JsonHelper - extend ZammadAPI::JsonHelper + include AttributeAccess - attr_accessor :new_instance, :url, :attributes - attr_reader :changes + # Largest page size Zammad's generic index endpoints serve, from + # ApplicationController#model_index_render via CanPaginate. Resources + # whose endpoint caps lower declare +max_per_page+. + DEFAULT_MAX_PER_PAGE = 1000 - def initialize(transport, attributes = {}) - @new_instance = true - @transport = transport - @changes = {} - @url = self.class.get_url + # Guards the class-level memos on the singleton below. One lock for every + # resource, because it is held only while a memo is first built. + MEMO_LOCK = Mutex.new + private_constant :MEMO_LOCK + + # Staged changes as +attribute => [old_value, new_value]+. + # + # A copy, and frozen: writing to the change set a record hands out would + # decide what the next +save+ sends. + # + # @return [Hash{Symbol => Array(Object, Object)}] + def changes = @changes.dup.freeze - if attributes.nil? - attributes = {} + # The validation failure from the most recent {#save}, so that a +false+ + # return value can be acted on. Cleared when the next save is attempted, + # so it never describes anything but the most recent one. + # + # @return [ValidationError, nil] + attr_reader :error + + # @api private + attr_reader :transport + + class << self + # Declares the API path of this resource, relative to the instance URL. + # + # @param value [String] + # @return [void] + def path(value) + @path = value + end + + # Declares that Zammad routes a +/search+ endpoint for this resource. + # + # Declared rather than assumed, and false unless a resource says + # otherwise: an unrouted `.../search` answers 404, which arrives as a + # NotFoundError from inside {ResourceProxy#find_by} - a method + # documented to return nil when nothing matched. A resource that + # forgets to declare this is refused at the call site instead, which + # is a question about the resource rather than a wrong answer about a + # record. + # + # @param value [Boolean] + # @return [void] + def searchable(value) + @searchable = value + end + + # Declares what this resource's search endpoint narrows by, besides + # the term and the two filters every search reads. + # + # Every search endpoint goes through + # ApplicationController#model_search_render, which hands the same + # parameters to the search of whichever model it was asked for. What + # that search does with them is the model's own business. +condition+ + # and +ids+ are read by the part all of them share, CanSearch, and + # need no declaring. +role_ids+, +group_ids+ and +permissions+ are + # read by User::Search and by no other: a ticket search handed + # +group_ids+ takes it, drops it and answers unnarrowed, on the SQL + # path and the Elasticsearch one alike. + # + # Declared rather than accepted everywhere, so that + # {ResourceProxy#search} can refuse a keyword this resource's search + # would drop - the same refusal it makes for a keyword no search + # reads at all. + # + # @param names [Array] + # @return [void] + def search_filters(*names) + @search_filters = names.map(&:to_sym).freeze + end + + # Declares the largest page size this resource's index endpoint + # serves. + # + # @param value [Integer] + # @return [void] + def max_per_page(value) + @max_per_page = value end - @attributes = attributes - symbolize_keys_deep!(@attributes) - end - def method_missing(method, *args) - return @attributes[method] if !method.to_s.end_with?('=') + # Declares whether this resource's index endpoint sorts. + # + # ApplicationController#model_index_render builds its query as + # `reorder(order_sql).offset(...).limit(...)`: it reads +sort_by+ and + # +order_by+, pages, and drops every other parameter. That is the + # default, so a resource says nothing. One whose controller hardcodes + # the order declares +sortable false+, and {Collection#order} then + # refuses it rather than handing back records it would be calling + # sorted. + # + # There is no attribute filtering on an index endpoint at all; that + # is what /search is for. + # + # @param value [Boolean] + # @return [void] + def sortable(value) + @sortable = value + end + + # @return [String] the API path of this resource + def resource_path + declaration(:path) || raise(Error, "#{name} does not declare an API path") + end + + # @return [Boolean] whether Zammad routes a +/search+ endpoint here + def searchable? = declaration(:searchable) { false } + + # @return [Array] what this resource's search endpoint narrows + # by besides the term, +condition+ and +ids+ + def search_filter_names + declaration(:search_filters) do + [] #: Array[Symbol] + end + end + + # @return [Integer] the largest page size this endpoint serves + def page_limit = declaration(:max_per_page) { DEFAULT_MAX_PER_PAGE } + + # @return [Boolean] whether this resource's index endpoint reads + # +sort_by+ and +order_by+ + def sortable? = declaration(:sortable) { true } + + # The API path of one record of this kind. + # + # The id is escaped rather than interpolated, so that one taken from a + # request parameter cannot walk out of its segment into another + # endpoint. Held here because {ResourceProxy} builds this path too, + # from an id a caller handed it, and an escaping rule kept in two + # places is one that gets changed in one of them. + # + # @api private + # @param id [Integer, String] + # @return [String] + # @raise [ArgumentError] when the id cannot go into a path segment + def member_path(id) = "#{resource_path}/#{Transport.escape_path_segment(id)}" + + # Reads one record by id. + # + # On the resource rather than on {ResourceProxy}, because both callers + # of it need a proxy for nothing else: {ResourceProxy#find} has one, + # and {Associations::Proxy} was building a throwaway per association + # read until it grew a second copy of this instead. The resource + # already knows its member path and how to build itself from a body, + # which is the whole of the read. + # + # @api private + # @param transport [Transport] + # @param id [Integer, String] + # @return [Base] + def fetch_one(transport, id) + operation = 'find object' + response = transport.get( + member_path(id), + operation: operation, + resource_class: self, + query: { expand: true } + ) + from_response(transport, response.decoded(:object, operation: operation, resource_class: self)) + end - method = method.to_s[0, method.length - 1].to_sym - @changes[method] = [@attributes[method], args[0]] - @attributes[method] = args[0] - nil + # Builds a record that is already stored in Zammad. + # + # Straight to the state, past the constructor's refusal of attributes + # a caller may not stage. Zammad serves +id+ in every body it answers + # with, and +id+ is the one attribute that refusal exists for. + # + # @api private + # @param transport [Transport] + # @param attributes [Hash] + # @return [Base] + def from_response(transport, attributes) + record = allocate + record.send(:setup, transport, attributes) + record.send(:mark_persisted!) + record + end + + # Every association declared on this resource, including inherited + # ones. + # + # @return [Hash{Symbol => Hash}] + def associations + ancestors + .select { it.respond_to?(:declared_associations, true) } + .reverse + .inject({}) { |result, ancestor| result.merge(ancestor.send(:declared_associations)) } + end + + # The attributes a +belongs_to+ reader resolves through, so that + # writing one can drop the record it had already resolved to. + # + # Both of the class-level memos here are built under one lock, because + # a plain `@x ||=` is a write to shared state that two threads can + # reach at once: on JRuby or TruffleRuby each could see the ivar unset + # and build a different anonymous proxy class for the same resource, + # and whichever write lost would still be held by the records already + # built from it. + # + # Populating them eagerly was the earlier answer, first on first use, + # then in `Client#setup`, then at require time. Each move shrank the + # window without closing it: `Client.new` is itself something two + # threads can call, and a resource a caller subclasses themselves - + # `class MyTicket < Ticket; end`, which this gem supports - is never in + # any list built ahead of time. + # + # The unlocked read first, so the settled case stays a plain ivar read: + # this is asked on every attribute write, and a lock on that path would + # cost far more than the one build it guards. + # + # @api private + # @return [Array] + def belongs_to_foreign_keys + @belongs_to_foreign_keys || MEMO_LOCK.synchronize { @belongs_to_foreign_keys ||= associations.filter_map { |_, spec| spec[:foreign_key] if spec[:type] == :belongs_to } } + end + + # The class carrying this resource's association readers, reached + # through {Base#related}. + # + # @api private + # @return [Class] + def related_class + return @related_class if @related_class + + # A resource's proxy inherits its parent's readers, so Base's + # created_by and updated_by reach every resource. The parent is + # resolved before the lock is taken, because resolving it may build + # the parent's own proxy through this same method and a Mutex is not + # reentrant. + parent = superclass.respond_to?(:related_class) ? superclass.related_class : Associations::Proxy # steep:ignore NoMethod + MEMO_LOCK.synchronize { @related_class ||= Class.new(parent) } + end + + private + + # Reads a declaration from this class, or failing that from the + # resource it inherits from. + # + # A plain class-level ivar is not inherited, so `class MyTicket < + # Ticket; end` used to inherit all nine of Ticket's associations, its + # page limit and its searchability, and lose only its API path - + # `MyTicket.resource_path` raised "does not declare an API path" from + # a class that plainly did. {.associations} and {.related_class} both + # walk the ancestry deliberately; these read through the same way. + # + # `instance_variable_defined?` rather than a truth test, so that a + # resource may declare a value that is false or nil and have it + # override an inherited one. + def declaration(name, &default) + variable = :"@#{name}" + return instance_variable_get(variable) if instance_variable_defined?(variable) + return superclass.send(:declaration, name, &default) if superclass.respond_to?(:declaration, true) + + default&.call + end + + def declared_associations = @declared_associations ||= {} + + # Declares that this resource points at a single other record, through + # a foreign key on itself. + # + # The reader lands on {Base#related}, not on the record, because Zammad + # already expands the association into a name under the plain + # attribute: +ticket.customer+ is a login, +ticket.related.customer+ is + # the User record. + # + # @param name [Symbol] name of the reader on {Base#related} + # @param class_name [String] the target resource, named rather than + # referenced so that two resources may point at each other. A + # resource of this gem by its own name, +'User'+; one a caller + # declared by its full name, +'Acme::Role'+ + # @param foreign_key [Symbol] attribute holding the target's id + # @return [void] + def belongs_to(name, class_name:, foreign_key: :"#{name}_id") + declared_associations[name] = { type: :belongs_to, class_name: class_name, foreign_key: foreign_key } + # The block runs against a Proxy instance, which the type checker + # cannot see through define_method. + related_class.define_method(name) { belongs_to_target(name, class_name, foreign_key) } # steep:ignore NoMethod + end + + # Declares that this resource points at a list of other records, + # served by an endpoint of its own. + # + # The path has to name an endpoint that serves the whole list in one + # response, which is what the association endpoints Zammad routes do: + # TicketArticlesController#index_by_ticket renders every article of + # the ticket and reads no paging parameter. The reader spends one + # request and hands back an Array rather than a walking {Collection}. + # + # Nothing here can tell a whole list from the first page of one, so + # declaring this for an endpoint that pages would return that page + # and no more. This comment used to promise a refusal instead. The + # check behind that promise read a total from a response header + # Zammad has never sent, so it never ran, and it was removed for that + # reason. For an endpoint that pages, declare a resource and walk it + # as a {Collection}. + # + # @param name [Symbol] name of the reader on {Base#related} + # @param class_name [String] the target resource + # @param path [Proc] called with the record id, already escaped for + # a path segment, and returns the API path + # @return [void] + def has_many(name, class_name:, path:) + declared_associations[name] = { type: :has_many, class_name: class_name, path: path } + related_class.define_method(name) { has_many_target(name, class_name, path) } # steep:ignore NoMethod + end end - def new_record? - @new_instance + # Zammad stamps every object with the user that created and last + # touched it. + belongs_to :created_by, class_name: 'User' + belongs_to :updated_by, class_name: 'User' + + # @param transport [Transport] + # @param attributes [Hash, nil] + # @raise [Error] when an attribute cannot be staged, such as +id+ + def initialize(transport, attributes = {}) + given = attributes || {} + # The same refusal the writers make, at the one door that did not make + # it. `group.id = 99` is refused with a sentence about what an id is + # for, and `client.groups.new(id: 99)` was accepted in silence - and + # then `save` POSTed `{"id": 99, ...}`, because a new record is sent in + # full. So the one spelling that reached the wire was the one nothing + # checked, and Zammad's answer to it was the first news of the + # mistake. {.from_response} is the way in for a body Zammad served, + # which carries an id precisely because it is a record that has one. + given.each { |key, value| refuse_unwritable!(DeepCopy.symbolize(key), value) } + setup(transport, given) end - def changed? - !@changes.to_h.empty? + # Gives a +dup+ or +clone+ the state of its own that a write changes. + # + # The attributes need nothing done: they are frozen and replaced on + # write, so a copy sharing them never sees the original's next write. + # The change set is written in place, and the copy shared it: after + # +copy = record.dup; copy.name = 'X'+ the original reported + # +changed?+ and a change to +name+ while still reading +name+ as it + # was, and its next +save+ sent the copy's value - a change it had + # never shown. + # + # The association proxy goes too. It reads through the record it was + # built for, so a copy holding the original's would resolve its + # associations from the original's foreign keys. + # + # @api private + # @param source [Base] + # @return [void] + def initialize_copy(source) + super + @changes = @changes.dup + @related = nil end - def destroy - response = @transport.delete(url: "#{@url}/#{@attributes[:id]}") - return true if response.status == 200 + # @return [Boolean] whether this record has not been stored yet + def new_record? = @new_record + + # Whether this record exists in Zammad. + # + # False both before the first save and after {#destroy}, so this is not + # the inverse of {#new_record?}. + # + # @return [Boolean] + def persisted? = !@new_record && !@destroyed + + # Whether {#destroy} removed this record from Zammad. + # + # The attributes stay readable, so a destroyed record can still be logged + # or reported on; it just no longer stands for anything on the server. + # + # @return [Boolean] + def destroyed? = @destroyed - raise ResponseError.from(response, operation: 'destroy object', resource_class: self.class) + # @return [Boolean] whether there are unsaved changes + def changed? = !@changes.empty? + + # The records this one points at, each fetched on demand. + # + # Zammad expands an association into a name under the plain attribute, + # so +ticket.customer+ is already the customer's login. These readers + # return the whole record instead, which costs a request. + # + # @example + # ticket.customer # => "customer@example.com", already loaded + # ticket.related.customer.email # => the same, from the User record + # ticket.related.articles # => [TicketArticle, ...] + # + # @return [Associations::Proxy] + # @raise [Error] when the record was destroyed + # @see .associations + def related + # Asked here rather than left to the request. `destroy` drops the memo, + # and that was taken to be the whole of it - but this reader rebuilds + # on the next call, so a destroyed record went on handing out a working + # proxy and `related.articles` fetched the articles of a ticket that is + # gone. Clearing a memo is not refusing a reader, and only the refusal + # is worth asserting: the spec that covered this compared proxy + # identity, so it passed throughout. + raise_if_destroyed!('read related records from') + # One proxy for as long as the record lives. What a save, a reload or + # a write to a foreign key invalidates is what the proxy has resolved, + # and {#forget_related_targets} empties that where it is held. + @related ||= self.class.related_class.new(self) + end + + # Stages several attributes as changes, without saving. + # + # @example + # group.assign_attributes(name: 'Support 2', note: 'Renamed') + # group.changed? # => true + # + # @param attributes [Hash] attribute names and their new values + # @return [self] + # @raise [Error] when an attribute cannot be staged, such as +id+, or + # when the record was destroyed. Nothing is staged in either case, so + # the record is left as it was. + def assign_attributes(attributes) + # rubocop:disable Style/CombinableLoops -- combining them is the bug + # Two passes on purpose: every key is checked before any of them is + # written. Combined, `assign_attributes(name: 'X', id: 9, note: 'Y')` + # staged the name, raised on the id and never reached the note, leaving + # the record dirty with half a change set - the state `update` takes + # its own guard one line early to avoid. + # + # `write_attribute` checks again for each key, because it is also the + # direct writer's own guard and cannot assume a caller came through + # here. That is a second Symbol comparison per attribute, which is not + # worth a bypass to avoid. + attributes.each { |key, value| refuse_unwritable!(key.to_sym, value) } + attributes.each { |key, value| write_attribute(key.to_sym, value) } + # rubocop:enable Style/CombinableLoops + self end + # Creates or updates the record, reporting a validation failure as + # +false+ rather than by raising. + # + # Only a rejection of the submitted attributes is caught, and it is left + # in {#error}. A missing record, an expired token or an unreachable + # instance still raises, because retrying or branching on those is not + # the caller's business here. + # + # @example + # if group.save + # puts group.id + # else + # warn group.error.server_message + # end + # + # @return [Boolean] whether the record was stored + # @raise [ResponseError] for any failure other than a validation error + # @see #save! def save - attributes = saved_attributes - symbolize_keys_deep!(attributes) - attributes.delete(:article) - @attributes = attributes - @new_instance = false - @changes = {} + save! + rescue ValidationError => e + @error = e + false + end + + # Creates or updates the record, raising on any failure. + # + # New records are sent in full; existing records send only the attributes + # that changed. + # + # @return [true] + # @raise [ResponseError] when Zammad rejected the request + # @see #save + def save! + raise_if_destroyed!('save') + + # Before the request, not after it. Only the success path and the + # rescue in `save` used to clear this, so a save that raised anything + # else left the previous attempt's ValidationError in place and a + # caller reading #error to report the failure read the wrong cause. + @error = nil + + # What the request carries, held from before it goes out. The + # attributes are frozen and replaced on write, so this is the Hash the + # request is built from and stays that whatever is written meanwhile: + # see #acknowledge_changes!. + # + # Built from, and not only held beside. The body of an update used to + # be read out of the change set a few lines after this was taken, and + # those are two reads of a record another thread may write to in + # between: title "B" held here, "C" staged before the body was built, + # and the PUT carried "C" while an answer nothing could read settled + # the record on "B" - with nothing staged, so writing "B" again to + # put it right compared equal and sent nothing. One Hash is read once + # now, and both the body and what is settled come out of it. + sent = @attributes + + if new_record? + response = create_record(sent) + else + # An existing record is addressed by its id, so establish there is + # one before anything here can report success. Only a record left + # behind by a 2xx that did not decode reaches this without one, and + # for that record the short circuit below is a lie: nothing is + # staged, so `save` answered true without sending a request. + require_id! + + # An unchanged record has nothing to send. The empty PUT this used + # to issue was not just a wasted round trip: Zammad applies it, + # bumping updated_at and updated_by, so re-saving a record that + # nobody touched rewrote its audit trail and moved the timestamp + # that other callers use to tell whether it changed under them. + unsaved = unsaved_attributes(sent) + return true if unsaved.empty? + + response = update_record(unsaved) + end + + replace_attributes!(response, operation: 'save object', sent: sent) true end - def self.get_url - @url + # Stages several attributes and saves in one call. + # + # @example + # ticket.update(state: 'closed', priority: '1 low') + # + # @param attributes [Hash] attribute names and their new values + # @return [Boolean] whether the record was stored + # @raise [Error] when the record was destroyed, or when an attribute + # cannot be staged, such as +id+ + # @raise [ResponseError] for any failure other than a validation error + # @see #save + def update(attributes) + # Before the attributes are staged, not after. `save!` asks the same + # question one line later, but by then `assign_attributes` has already + # written into @changes, so `update` on a destroyed record raised and + # left it dirty with a change set that can never be sent - exactly the + # state `destroy` clears the staged changes to prevent. + raise_if_destroyed!('save') + assign_attributes(attributes) + save end - def self.url(value) - @url = value + # Stages several attributes and saves in one call, raising on any + # failure. + # + # @param attributes [Hash] attribute names and their new values + # @return [true] + # @raise [Error] when the record was destroyed, or when an attribute + # cannot be staged, such as +id+ + # @raise [ResponseError] when Zammad rejected the request + # @see #save! + def update!(attributes) + raise_if_destroyed!('save') + assign_attributes(attributes) + save! end - def self.all(transport, _) - ZammadAPI::ListAll.new(self, transport, per_page: 100) + # Re-reads the record from Zammad, discarding unsaved changes. + # + # @return [self] + # @raise [Error] when the record was destroyed + # @raise [ResponseError] when Zammad rejected the request + # @raise [ParseError] when the response is not a JSON object + def reload + raise_if_destroyed!('reload') + raise_if_new!('reload') + + response = transport.get( + member_path, + operation: 'reload object', + resource_class: self.class, + query: { expand: true } + ) + replace_attributes!(response, operation: 'reload object') + self end - def self.search(transport, parameter) - ZammadAPI::ListSearch.new(self, transport, parameter) + # Deletes the record. + # + # The record is marked {#destroyed?} rather than left looking live, so + # that a later {#save}, {#reload} or second {#destroy} fails here with + # the reason rather than one call later as a 404 from Zammad. The + # attributes stay readable, but the state that only meant something + # while the record existed does not: staged changes, the last validation + # failure, and the association readers all go, and a write to an + # attribute is refused from then on. + # + # Readable as the record last was in Zammad, which is not what dropping + # the staged changes alone left behind: `reset_pending_state!` empties + # `@changes` and leaves the writes those changes described standing in + # `@attributes`, so `group.name = 'B'; group.destroy` answered + # `changed?` with false, `changes` with `{}` and `name` with "B" - a + # value Zammad never saw, with nothing left to tell it apart from one it + # served. `@baseline` is what the record arrived with, and every other + # path through this state moves the two together. + # + # @return [true] + # @raise [Error] when the record was already destroyed + # @raise [ResponseError] when Zammad rejected the request + def destroy + raise_if_destroyed!('destroy') + raise_if_new!('destroy') + + transport.delete(member_path, operation: 'destroy object', resource_class: self.class) + @destroyed = true + @attributes = @baseline + reset_pending_state! + true end - def self.find(transport, id) - response = transport.get(url: "#{@url}/#{id}?expand=true") - if response.status != 200 - raise ResponseError.from(response, operation: 'find object', resource_class: self) - end + def inspect = "#<#{self.class.name} id=#{id.inspect} new_record=#{new_record?}#{' destroyed=true' if destroyed?} attributes=#{attributes.inspect}>" - data = safe_json_parse(response.body) - item = new(transport, data) - item.new_instance = false - item + protected + + # @see AttributeAccess#installation + def installation = transport.config.url + + private + + # Everything a record is, in the one place both ways of building one go + # through. Held apart, {.from_response} would restate this list by hand + # and the next field added to the constructor would be left unset on + # every record built from a response - the argument {Client#setup} is + # written around, one class over. + # + # @return [void] + def setup(transport, attributes) + @transport = transport + @attributes = frozen_attributes(attributes) + # What #changes measures against: the attributes this record arrived + # with, kept apart from the ones it currently holds. The two share the + # one frozen Hash until the first write copies it. + @baseline = @attributes + @changes = {} + @new_record = true + @destroyed = false + @error = nil + @related = nil + # Whether what this record holds came back from a save rather than + # from a read. Only {#no_id_message} asks, and only for a record left + # without an id, where the two lead somewhere quite different. + @saved = false end - def self.create(transport, data) - item = new(transport, data) - item.save - item + def mark_persisted! + @new_record = false end - def self.destroy(transport, id) - item = find(transport, id) - item.destroy - true + # Refuses an operation on a record Zammad never had. + # + # `destroyed?` was the only thing these asked, so a record built with an + # id it was simply handed - `client.groups.new(id: 99)`, which the + # attribute writers refuse but the constructor still allows - reported + # `new_record?` true and `persisted?` false and then issued a real DELETE + # against group 99. The id addresses a record this one does not stand + # for, and nothing about it came from Zammad. + def raise_if_new!(operation) + raise Error, "#{self.class.name} has not been saved, so there is nothing to #{operation}" if new_record? end - private + # Refuses an operation on a record Zammad no longer holds. + # + # `destroyed?` is sticky, and all three state-changing paths ask here. + # Only `save!` used to: `reload` re-read a record that no longer exists + # and cleared the flag on the way back, so a destroyed record came back + # reporting itself as persisted and its next `save` issued a PUT against + # the deleted path, while a second `destroy` surfaced Zammad's 404 + # instead of the local reason. A record that is gone is gone, and every + # path that acts on the server says so here rather than one request + # later. + def raise_if_destroyed!(action) + raise Error, "#{self.class.name} #{id} was destroyed, there is nothing to #{action}" if destroyed? + end + + def writable_attributes? = true - def saved_attributes - return save_new if @new_instance + # Asked by {#write_attribute} and by {AttributeAccess#respond_to_missing?}, + # so that a record never claims a writer it would then refuse. That is + # the invariant the writer branch of `respond_to_missing?` exists for. + def attribute_writable?(key) = key != :id - save_existing + # Everything a freshly loaded record has to forget, in the one place that + # every load path goes through. Held apart, `save!` and `reload` drifted + # the moment a sixth field was added to only one of them, and nothing + # would have caught a reloaded record still holding an association proxy + # from before the reload. + # The flag goes down before the body is decoded, because what makes a + # record persisted is that Zammad answered 2xx, not that the answer + # parsed. Decoded first, a create whose 201 carried something other than + # a JSON object - an HTML error page from an intervening proxy - raised + # ParseError with @new_record still true, so the ticket existed in + # Zammad while the record here still looked unsaved and a retried `save` + # POSTed a second one. + # + # What that leaves behind is a record which is persisted and carries no + # id, and the rest of this class has to treat it as the unusable thing + # it is: a record built by `new` has nothing staged, so without a word + # from {#require_id!} the retried `save` would have taken the "nothing + # to send" short circuit and reported true, having made no request at + # all, for a record that may or may not be in Zammad. + # + # +sent+ is what a save was sent with, and is what tells one from a + # read. + def replace_attributes!(response, operation:, sent: nil) + # First, while #new_record? still says whether this was a create. + acknowledge_changes!(sent) if sent + @new_record = false + @saved = !sent.nil? + @attributes = frozen_attributes(response.decoded(:object, operation: operation, resource_class: self.class)) + @baseline = @attributes + reset_pending_state! end - def save_new - response = @transport.post(url: "#{@url}?expand=true", params: @attributes) - return safe_json_parse(response.body) if response.status == 201 + # The same argument, for what was staged: a 2xx is Zammad saying it + # applied the changes, whether or not the rest of the answer parsed. + # + # They used to stay staged until the body had decoded. An update + # answered with a 2xx nothing could read - the same proxy page - raised + # ParseError with the whole change set still in place, so the next + # `save` sent all of it again along with whatever had been staged + # since. For most attributes that is the same value twice. For a + # ticket's `article` it is a second article, and a second e-mail to + # the customer: the one write {Transport::RETRIABLE_METHODS} leaves + # PUT out to keep from being repeated, repeated by the caller's next + # unrelated save instead. + # + # So the baseline moves up to what was sent, before the body is read. + # If that then raises, the record holds the values it sent and nothing + # staged: it is not what Zammad would serve - `updated_at` is behind, + # and anything Zammad derived is missing - and {#reload} is what + # brings that in. A save Zammad rejected never gets here, so what it + # was sent stays staged to be corrected and sent again. + # + # What was sent, and not what the record holds by the time the answer + # is in. The two differ where the record was written to while the + # request was out - by a logger or a middleware of the caller's that + # reaches the record, or by another thread - and the baseline used to + # be taken from the record as it then stood: a PUT that carried title + # "B", with "C" staged before the answer came, left the record reading + # "C" with nothing staged, so the next `save` reported true without a + # request for a value Zammad was never sent. A write made meanwhile is + # dropped instead, which is what a response that can be read does to + # it: the attributes it carries replace the record's, whatever was + # written to them since the request left. + # + # And of what was sent, only the attributes Zammad has served this + # record with. A key written since that it never sent back is not known + # to be an attribute at all. A ticket's `article` is the case that + # matters: a command that travels in the body of the same PUT and makes + # an article, and no part of what a ticket is served as. Settled into + # the baseline with the rest, it was remembered as the ticket's own + # state, so the same article assigned again - a second reply with the + # text of the first - compared equal to it, staged nothing, and `save` + # reported true without a request. A response that can be read leaves + # no such key behind, and neither does this. + # + # A record being created has nothing it was served with to measure + # against, and keeps all it sent. It has no id to be saved again by, + # so there is no second request for a key to be missing from. + # + # What the association proxy has resolved goes with the attributes it + # was resolved from. This puts the record back on what it sent, which + # is a write to every attribute at once, and it was the one write to a + # foreign key that left the proxy alone: `customer_id` sent as 9, + # written to 10 while the request was out and `related.customer` read + # then, and the record was back on 9 with user 10 still memoized as + # its customer. {#reset_pending_state!} empties the proxy too, but + # only once the body has decoded, and a body that does not is what + # this method is here for. + def acknowledge_changes!(sent) + settled = new_record? ? sent : sent.slice(*@baseline.keys).freeze + @attributes = settled + @baseline = settled + @changes = {} + forget_related_targets + end + + # The part of that which is not about arriving with new attributes, but + # about the record's state on the server having changed underneath what + # is held here. `destroy` is the third path through this, and was the + # one left out: a destroyed record went on reporting `changed?` and a + # change set that can never be sent, and went on handing out a `related` + # proxy that would happily request a record that no longer exists. + def reset_pending_state! + @changes = {} + @error = nil + forget_related_targets + end - save_error(response) + # Empties the association proxy, rather than dropping it. + # + # Dropping it was the earlier answer: `@related = nil`, and the next + # call to {#related} built a fresh one. That reached every caller who + # asked again and none who had kept what they were handed, so after + # `related = ticket.related` a reload, a save or `ticket.customer_id = 9` + # left `related.customer` answering with the record it had resolved + # before - the stale read these calls exist to prevent, one variable + # away from where it was fixed. + def forget_related_targets + @related&.send(:forget_targets) end - def save_existing - attributes_to_post = {} - @changes.each do |name, values| - attributes_to_post[name] = values[1] + # The baseline is the value this record was loaded with, not the value + # the previous assignment happened to leave behind. Writing twice must + # still report the original, and writing a value back to the original + # is not a change at all - but only where the record was loaded + # carrying that attribute in the first place. + # + # That last part is why the baseline is held rather than read back out + # of @attributes: an attribute the record does not carry - Zammad + # reduces the object it serializes for a permission-scoped client - + # compared nil against nil on the way in, staged nothing, and was still + # merged into @attributes below. The write was dropped without a word, + # no request was ever sent for it, and the record went on reporting a + # key Zammad had never sent it, so #changes and #attributes disagreed. + # + # A destroyed record takes no writes. `update` has refused one all + # along, so as not to leave a change set that can never be sent, but + # the writers themselves did not ask: `group.destroy; group.name = 'Z'` + # left `changed?` true and `name` reading "Z" on a record `destroy` + # promises to leave as it last was in Zammad, and the `save` after it + # was the first thing to object. Asked here, it holds for a named + # writer, `[]=` and `assign_attributes` alike, since all three write + # through this method. + def write_attribute(key, value) + raise_if_destroyed!('change') + refuse_unwritable!(key, value) + + staged = frozen_attributes(value) + + if @baseline.key?(key) && @baseline[key] == staged + @changes.delete(key) + else + @changes[key] = [@baseline[key], staged].freeze end - response = @transport.put(url: "#{@url}/#{@attributes[:id]}?expand=true", params: attributes_to_post) - return safe_json_parse(response.body) if response.status == 200 - save_error(response) + # Copy on write, because @attributes is frozen for the benefit of + # every reader that hands it out. + @attributes = @attributes.merge(key => staged).freeze + # A resolved association is only correct for the id it was resolved + # from. `replace_attributes!` forgets them on save and reload, but + # the write that actually changes a foreign key did not, so + # `ticket.customer_id = 9` left `ticket.related.customer` answering + # with user 3 and no request to show for it. Every target goes: + # evicting one reader means reaching into the cache by name for a + # saving that is one request at most. + forget_related_targets if self.class.belongs_to_foreign_keys.include?(key) + staged + end + + # The attributes of +held+ that differ from what this record arrived + # with, which is what an update sends. + # + # The same question {#write_attribute} asks before it stages a change, + # asked of one Hash of attributes rather than of the change set: see + # {#save!} for why the body of a request is not read from there. + # + # @param held [Hash{Symbol => Object}] attributes of this record + # @return [Hash{Symbol => Object}] + def unsaved_attributes(held) + baseline = @baseline + + held.reject { |key, value| baseline.key?(key) && baseline[key] == value } end - def save_error(response) - raise ResponseError.from(response, operation: 'save object', resource_class: self.class) + def create_record(body) + transport.post( + self.class.resource_path, + operation: 'save object', + resource_class: self.class, + query: { expand: true }, + body: body + ) end - def symbolize_keys_deep!(hash) - hash.keys.each do |key| - key_symbol = key.respond_to?(:to_sym) ? key.to_sym : key - hash[key_symbol] = hash.delete key # Preserve order even when key == key_symbol + def update_record(body) + transport.put( + member_path, + operation: 'save object', + resource_class: self.class, + query: { expand: true }, + body: body + ) + end + + # The id is what addresses the record, so it is not an attribute a caller + # stages. Written, it took effect immediately for every path that builds + # a URL from `@attributes` and not at all for the record those paths then + # reported on: `group.id = 99; group.destroy` sent DELETE to group 99 and + # left the record saying group 1 was the one destroyed. Zammad would not + # have applied it either - an id is not something its endpoints let you + # set - so there is no call here that a refusal takes away. + def refuse_unwritable!(key, value) + return if attribute_writable?(key) - symbolize_keys_deep! hash[key_symbol] if hash[key_symbol].is_a? Hash + message = "#{self.class.name}##{key} cannot be staged as an attribute" + # `attribute_writable?` is a hook a resource may override, so the + # reason belongs to the key that was refused rather than to the raise. + if key == :id + message += ', because it is what addresses this record; look up the record you meant ' \ + "with find(#{value.inspect})" end + raise Error, message + end + + def member_path = self.class.member_path(require_id!) + + # This record's id, for the paths and bodies that cannot be built + # without one. + # + # @return [Integer] the id + # @raise [Error] when the record has none + def require_id! + # Read once into a local, so that the guard below narrows what is + # handed on - `id` is an attribute reader, and the type checker cannot + # tell that two calls to one answer the same thing. + record_id = id + raise Error, no_id_message if record_id.nil? + + record_id + end + + # A record has no id in three quite different situations, and one message + # for more than one of them sends people looking in the wrong place. + # + # Before the first save there is simply nothing to address yet. + # + # After one there is - Zammad answered 2xx, so the record is in Zammad - + # but the response carried no id to address it by, which is what + # {#replace_attributes!} leaves behind when a 2xx body does not decode + # as the object it claims to be. + # + # And a record can arrive without one from a plain read: Zammad reduces + # the object it serializes for a permission-scoped client, which is the + # same thing {#write_attribute} is written around. Such a record is + # persisted, so it used to be told it "was saved" - pointing the caller + # at a save that never happened, when what they need to look at is which + # user the client authenticates as. + def no_id_message + return "#{self.class.name} has no id, save it first" if new_record? + + if @saved + return "#{self.class.name} was saved, but the response carried no id to address it by, " \ + 'so this record cannot act on the server. Look it up again to get one that can.' + end + + "#{self.class.name} was loaded without an id, so this record cannot act on the server. " \ + 'Zammad serves a reduced object where the authenticated user may not see the whole record, ' \ + 'so check what this client may read, then look it up again to get one that can.' end end end diff --git a/lib/zammad_api/resources/group.rb b/lib/zammad_api/resources/group.rb index 3a6a768..7e3cd64 100644 --- a/lib/zammad_api/resources/group.rb +++ b/lib/zammad_api/resources/group.rb @@ -1,3 +1,13 @@ -class ZammadAPI::Resources::Group < ZammadAPI::Resources::Base - url '/api/v1/groups' +# frozen_string_literal: true + +require_relative 'base' + +module ZammadAPI + module Resources + class Group < Base + path 'api/v1/groups' + + searchable true + end + end end diff --git a/lib/zammad_api/resources/organization.rb b/lib/zammad_api/resources/organization.rb index 671939f..2ffd0a3 100644 --- a/lib/zammad_api/resources/organization.rb +++ b/lib/zammad_api/resources/organization.rb @@ -1,3 +1,13 @@ -class ZammadAPI::Resources::Organization < ZammadAPI::Resources::Base - url '/api/v1/organizations' +# frozen_string_literal: true + +require_relative 'base' + +module ZammadAPI + module Resources + class Organization < Base + path 'api/v1/organizations' + + searchable true + end + end end diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index 448209b..3f3810a 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -1,25 +1,103 @@ -class ZammadAPI::Resources::Ticket < ZammadAPI::Resources::Base - url '/api/v1/tickets' +# frozen_string_literal: true - def articles - response = @transport.get(url: "/api/v1/ticket_articles/by_ticket/#{id}?expand=true") - if response.status != 200 - raise ZammadAPI::ResponseError.from(response, operation: 'get articles', resource_class: self.class) - end +require_relative 'base' +require_relative 'ticket_article' - data = safe_json_parse(response.body) +module ZammadAPI + module Resources + class Ticket < Base + path 'api/v1/tickets' - data.collect do |raw| - item = ZammadAPI::Resources::TicketArticle.new(@transport, raw) - item.new_instance = false - item - end - end + # TicketsController#index hardcodes `reorder(id: :asc)`, so it reads nothing + # but the paging - not even sort_by. + sortable false + + # /api/v1/tickets caps the page size at 100, unlike the generic index + # endpoints, see TicketsController#index. + max_per_page 100 + + searchable true + + belongs_to :customer, class_name: 'User' + belongs_to :owner, class_name: 'User' + belongs_to :organization, class_name: 'Organization' + belongs_to :group, class_name: 'Group' + belongs_to :state, class_name: 'TicketState' + belongs_to :priority, class_name: 'TicketPriority' - def article(data) - data[:ticket_id] = @attributes[:id] - item = ZammadAPI::Resources::TicketArticle.new(@transport, data) - item.save - item + has_many :articles, class_name: 'TicketArticle', path: ->(id) { "api/v1/ticket_articles/by_ticket/#{id}" } + + # Every article of this ticket, refetched on each call. + # + # The same list as +ticket.related.articles+; this is the older name and + # stays because it reads better than reaching through +related+ for the + # one association a ticket is usually asked for. + # + # @return [Array] + # @raise [ResponseError] when Zammad rejected the request + def articles = related.articles + + # Adds an article to this ticket. + # + # Named for what it does. It was +article+, a noun that sends a POST, + # next to +articles+, a noun that only reads - so the one letter + # between them was the difference between reading a ticket's history + # and writing to it. + # + # @example + # ticket.add_article(subject: 'Update', body: 'Reset link sent.', type: 'note') + # + # @param attributes [Hash] article attributes, e.g. +body:+, +type:+ + # @return [TicketArticle] the created article + # @raise [Error] when the ticket has no id yet, or was destroyed + # @raise [ResponseError] when Zammad rejected the request + def add_article(attributes = {}) + # A destroyed ticket takes no articles, and says so here rather than + # one request later. `require_id!` passes on its own, because destroy + # leaves the id readable, so without this the POST went out naming a + # ticket that is gone and Zammad's 422 about ticket_id was the first + # news of it - the fourth state-changing path, after the three that + # already ask. + raise_if_destroyed!('add an article to') + + # An article belongs to a ticket by id, so ask for one here rather + # than merging nil. Unchecked, this POSTed `ticket_id: null` and left + # the caller reading Zammad's 422 to work out that the ticket they + # were adding to had never been saved - the one path in the gem that + # needed a stored id and went to the server to find out it had none. + # + # Both spellings of the key are taken out before this ticket's id + # goes in. `merge(ticket_id: ...)` replaces a Symbol key and leaves a + # String one standing beside it, and the article symbolizes its keys + # in the order they come: given `ticket_id` under both spellings, the + # String one came last and won, so `add_article` on ticket 7 POSTed + # an article naming whichever ticket the caller's Hash did. + own = attributes.reject { |key, _| key.to_s == 'ticket_id' } + record = TicketArticle.new(transport, own.merge(ticket_id: require_id!)) + record.save! + record + end + + # Adds an article to this ticket, under the name the method had in 1.x. + # + # Warns in Ruby's +deprecated+ category, the way the singular readers + # on {Client} do: silent unless the application asks for deprecation + # warnings. + # + # The attributes are required, as they were in 1.x. With a default, + # a bare +ticket.article+ - which reads like the attribute a ticket is + # created with, `ticket.article = {body: 'reply'}` - sent a POST + # naming nothing but the ticket, which Zammad refused for want of a + # body. 1.x raised ArgumentError for it without a request, and so does + # this. + # + # @deprecated Use {#add_article}. + # @param attributes [Hash] article attributes + # @return [TicketArticle] the created article + def article(attributes) + warn("#{Ticket.name}#article is deprecated and will be removed in 3.0: use #add_article instead", uplevel: 1, category: :deprecated) + add_article(attributes) + end + end end end diff --git a/lib/zammad_api/resources/ticket_article.rb b/lib/zammad_api/resources/ticket_article.rb index 890918b..88a0434 100644 --- a/lib/zammad_api/resources/ticket_article.rb +++ b/lib/zammad_api/resources/ticket_article.rb @@ -1,11 +1,48 @@ -class ZammadAPI::Resources::TicketArticle < ZammadAPI::Resources::Base - url '/api/v1/ticket_articles' - - def attachments - @attributes[:attachments].collect do |raw| - raw[:ticket_id] = @attributes[:ticket_id] - raw[:article_id] = @attributes[:id] - ZammadAPI::Resources::TicketArticleAttachment.new(@transport, raw) +# frozen_string_literal: true + +require_relative '../errors' +require_relative 'base' +require_relative 'ticket_article_attachment' + +module ZammadAPI + module Resources + class TicketArticle < Base + path 'api/v1/ticket_articles' + + # Named the way a has_many reader names its own read - `get articles` - + # so the refusal below reads like every other one this gem raises. + ATTACHMENTS_OPERATION = 'get attachments' + private_constant :ATTACHMENTS_OPERATION + + belongs_to :ticket, class_name: 'Ticket' + + # @return [Array] the article's attachments + # @raise [ParseError] when the article does not carry attachment + # metadata in the shape Zammad serves + def attachments + list = attributes[:attachments] || [] + # The same check {Response#decoded} makes on a list of records, for + # the same reason: this metadata comes off a response body, and an + # element that is not an object reached `raw.merge` and died there as + # `undefined method 'merge' for an instance of String` - a bare + # NoMethodError from inside the gem, past the `rescue ZammadAPI::Error` + # every caller is told to write, for a body that was simply not what + # it claimed to be. + raise ParseError.build(operation: ATTACHMENTS_OPERATION, expected: 'array of objects', actual: list.class, resource_class: self.class) if !list.is_a?(Array) + + list.map { attachment(it) } + end + + private + + def attachment(raw) + raise ParseError.build(operation: ATTACHMENTS_OPERATION, expected: 'array of objects', actual: "an array holding #{raw.class}", resource_class: self.class) if !raw.is_a?(Hash) + + TicketArticleAttachment.new( + transport, + raw.merge(ticket_id: attributes[:ticket_id], article_id: id) + ) + end end end end diff --git a/lib/zammad_api/resources/ticket_article_attachment.rb b/lib/zammad_api/resources/ticket_article_attachment.rb index c3e06d9..c3035b0 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -1,18 +1,50 @@ -class ZammadAPI::Resources::TicketArticleAttachment < ZammadAPI::Resources::Base - def initialize(transport, attributes = {}) # rubocop:disable Lint/MissingSuper - @transport = transport - @attributes = attributes - symbolize_keys_deep!(@attributes) - end +# frozen_string_literal: true - def method_missing(method, *_args) - @attributes[method.to_sym] - end +require_relative '../attribute_access' +require_relative '../errors' +require_relative '../transport' + +module ZammadAPI + module Resources + # An attachment of a ticket article. + # + # Attachments are read-only metadata until {#download} is called, which + # returns the file contents. + class TicketArticleAttachment + include AttributeAccess + + # @api private + # @param transport [Transport] + # @param attributes [Hash] + def initialize(transport, attributes = {}) + @transport = transport + @attributes = frozen_attributes(attributes || {}) + end + + # Downloads the attachment. + # + # @return [String] the file contents, in +ASCII-8BIT+ encoding + # @raise [ResponseError] when Zammad rejected the request + def download + segments = %i[ticket_id article_id id].map { Transport.escape_path_segment(fetch(it)) } + response = @transport.get( + "api/v1/ticket_attachment/#{segments.join('/')}", + operation: 'download attachment', + resource_class: self.class + ) + # Attachments are arbitrary binary data; the transport's charset + # guess must not corrupt them. + response.raw_body.dup.force_encoding(Encoding::BINARY) + end + + def inspect + "#<#{self.class.name} id=#{id.inspect} filename=#{self[:filename].inspect} size=#{self[:size].inspect}>" + end - def download - response = @transport.get(url: "/api/v1/ticket_attachment/#{ticket_id}/#{article_id}/#{id}") - return response.body if response.status == 200 + protected - raise ZammadAPI::ResponseError.from(response, operation: 'get articles', resource_class: self.class) + # @see AttributeAccess#installation + def installation = @transport.config.url + end end end diff --git a/lib/zammad_api/resources/ticket_priority.rb b/lib/zammad_api/resources/ticket_priority.rb index c46534a..a02df3c 100644 --- a/lib/zammad_api/resources/ticket_priority.rb +++ b/lib/zammad_api/resources/ticket_priority.rb @@ -1,3 +1,11 @@ -class ZammadAPI::Resources::TicketPriority < ZammadAPI::Resources::Base - url '/api/v1/ticket_priorities' +# frozen_string_literal: true + +require_relative 'base' + +module ZammadAPI + module Resources + class TicketPriority < Base + path 'api/v1/ticket_priorities' + end + end end diff --git a/lib/zammad_api/resources/ticket_state.rb b/lib/zammad_api/resources/ticket_state.rb index d05b75f..091aa4d 100644 --- a/lib/zammad_api/resources/ticket_state.rb +++ b/lib/zammad_api/resources/ticket_state.rb @@ -1,3 +1,11 @@ -class ZammadAPI::Resources::TicketState < ZammadAPI::Resources::Base - url '/api/v1/ticket_states' +# frozen_string_literal: true + +require_relative 'base' + +module ZammadAPI + module Resources + class TicketState < Base + path 'api/v1/ticket_states' + end + end end diff --git a/lib/zammad_api/resources/user.rb b/lib/zammad_api/resources/user.rb index c5c667a..a879277 100644 --- a/lib/zammad_api/resources/user.rb +++ b/lib/zammad_api/resources/user.rb @@ -1,3 +1,28 @@ -class ZammadAPI::Resources::User < ZammadAPI::Resources::Base - url '/api/v1/users' +# frozen_string_literal: true + +require_relative 'base' + +module ZammadAPI + module Resources + class User < Base + path 'api/v1/users' + + # UsersController#index hardcodes `reorder(id: :asc)`, so it reads nothing + # but the paging - not even sort_by. + sortable false + + searchable true + + # User::Search is the one search that reads these: it joins the roles + # for +role_ids+, resolves +permissions+ to the roles that carry them, + # and +group_ids+ to the agents with access to those groups - full + # access where it is a list of ids, the access named for each group + # where it is a Hash. See {ResourceProxy#search}, also for what + # +permissions+ does not narrow where Zammad searches through + # Elasticsearch. + search_filters :role_ids, :group_ids, :permissions + + belongs_to :organization, class_name: 'Organization' + end + end end diff --git a/lib/zammad_api/response.rb b/lib/zammad_api/response.rb new file mode 100644 index 0000000..a444c20 --- /dev/null +++ b/lib/zammad_api/response.rb @@ -0,0 +1,170 @@ +# frozen_string_literal: true + +require 'json' + +require_relative 'errors' + +module ZammadAPI + # A decoded HTTP response. + # + # This deliberately does not expose Faraday objects, so that the HTTP client + # stays an implementation detail of {Transport}. + # + # @!attribute [r] status + # @return [Integer] HTTP status code + # @!attribute [r] headers + # @return [Hash{String => String}] response headers, keys downcased + # @!attribute [r] body + # @return [Hash, Array, String] JSON responses are decoded with symbol + # keys; every other content type is left as the raw body + # @!attribute [r] raw_body + # @return [String] the undecoded response body + # @!attribute [r] json + # @return [Boolean] whether {#body} was decoded from JSON + Response = Data.define(:status, :headers, :body, :raw_body, :json) + + class Response + SUCCESS_STATUSES = (200..299) + + # There is no reader here for the size of the whole result, and the + # absence is deliberate. This class carried a `reported_total` that read + # an `x-total-count` response header, and two stop conditions were built + # on it: {Collection#each} ended a walk one request early on it, and a + # has_many reader refused a list it judged truncated by it. + # + # Zammad has never sent that header, from any endpoint. Its only custom + # response header is `X-Failure`, and the totals it does report are + # fields in a JSON body: `only_total_count` and `with_total_count` on a + # search, `full` on the endpoints that render through + # model_index_render. So the reader answered nil every time, both guards + # were dead, and the one of them that could have acted - ending a walk on + # a figure the records did not corroborate - was the one that could have + # been wrong. {Collection#total_count} asks a search endpoint for its + # figure the way Zammad actually offers it, and {#decoded_list} reads + # the one a search reports beside a page. + + # @return [Boolean] whether the status code is in the 2xx range + def success? = SUCCESS_STATUSES.cover?(status) + + # Recorded at decode time, where the answer is known, rather than derived + # from `body` and `raw_body` being the same object. That identity held only + # while every producer was careful to hand the same String to both, and any + # edit that duped, re-encoded or normalised the raw body would have flipped + # this to true with nothing asserting otherwise. + # + # @return [Boolean] whether {#body} was decoded from JSON + def json? = json + + # Decodes a body the way this gem decodes every body, and says whether it + # did. + # + # Only JSON responses are decoded. Anything else - a proxy error page, a + # file download - is handed back untouched so that callers and error + # messages can still work with it. + # + # Here rather than on {Transport}, because {Test} has to answer the same + # way and was deciding from the Ruby type of the stub's body instead: a + # stub could declare `content-type: text/html` and still hand back a + # decoded Hash with `json?` true, where Zammad would have given the raw + # string and a ParseError. A stand-in whose decoding disagrees with the + # wire is the thing that kit exists to rule out. + # + # Public for that reason and no other, the way {Transport.stringify_query} + # is: both transports call it from outside this class. It is not part of + # what this gem promises a caller. + # + # @api private + # @param content_type [String, nil] + # @param raw_body [String] + # @return [Array(Hash | Array | String, bool)] the body and whether it was + # decoded from JSON + def self.decode_body(content_type, raw_body) + return [raw_body, false] if !content_type.to_s.include?('json') + return [raw_body, false] if raw_body.empty? + + [JSON.parse(raw_body, symbolize_names: true), true] + rescue JSON::ParserError + [raw_body, false] + end + + # Returns the decoded body once it matches the expected shape. + # + # Zammad answers with an object for a single record and an array for a + # list; anything else (a proxy error page, an unexpanded search result) + # is a {ParseError} rather than a confusing failure further downstream. + # + # @param shape [Symbol] +:object+ or +:array+ + # @param operation [String] description used in the error message + # @param resource_class [Class, nil] used in the error message + # @return [Hash, Array] + # @raise [ParseError] when the body has a different shape + def decoded(shape, operation:, resource_class: nil) + case [shape, body] + in [:object, Hash => object] then object + in [:array, Array => array] then array_of_objects!(array, operation: operation, resource_class: resource_class) + else + raise ParseError.build( + operation: operation, + expected: shape, + actual: body.class, + resource_class: resource_class + ) + end + end + + # Returns the records of a list, and the size of the whole result where + # the endpoint reports it beside them. + # + # A list is an array. A search asked for +with_total_count+ answers with + # an object instead, +{records: [...], total_count: n}+, where its Zammad + # reads that parameter under +expand+ - 6.5.1 and later - and with the + # array it always did where it does not. Both are a list, and + # {Collection} reads either. + # + # A total that cannot be one - a negative figure, a string - is reported + # as none rather than refused. The records beside it are still the page, + # and a walk without a total is a walk as it was before there was one. + # + # @param operation [String] description used in the error message + # @param resource_class [Class, nil] used in the error message + # @return [Array(Array, Integer)] the records and the total + # @return [Array(Array, nil)] where the endpoint reported no total + # @raise [ParseError] when the body is neither shape + def decoded_list(operation:, resource_class: nil) + case body + in { records: Array => records, total_count: total } + [array_of_objects!(records, operation: operation, resource_class: resource_class), total.is_a?(Integer) && !total.negative? ? total : nil] + else + [decoded(:array, operation: operation, resource_class: resource_class), nil] + end + end + + private + + # Only the top-level shape used to be checked, which is not what the + # promise above says. A search answering `[1, 2, 3]` - what an unexpanded + # one looks like - passed as an array, and every element went to + # `from_response`, which stored the Integer as a record's attributes. The + # first `record.id` then died with `TypeError: no implicit conversion of + # Symbol into Integer` from deep inside the gem: precisely the confusing + # failure further downstream. + # + # Asked for by position, because the element itself cannot say whether + # one was found. `find` answers nil for no offender and for an offender + # that is nil, so a list holding a JSON null - `[null]`, or one null + # among the records - passed as a list of objects, and the same failure + # came back one type over: NoMethodError for `nil[:id]`, from the walk + # that reads the ids of a page. + def array_of_objects!(array, operation:, resource_class:) + position = array.index { !it.is_a?(Hash) } + return array if position.nil? + + raise ParseError.build( + operation: operation, + expected: 'array of objects', + actual: "an array holding #{array.fetch(position).class}", + resource_class: resource_class + ) + end + end +end diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 5ade333..6c2ded2 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1,63 +1,1140 @@ +# frozen_string_literal: true + require 'faraday' +require 'faraday/retry' +require 'json' require 'openssl' +require 'socket' +require 'timeout' + +require_relative 'duplicate_keys' +require_relative 'errors' +require_relative 'query_encoder' +require_relative 'response' module ZammadAPI + # Performs the HTTP requests against a Zammad instance. + # + # Instances are immutable once built: {#with_on_behalf_of} returns a copy + # rather than mutating shared state, which makes a single transport safe to + # use from several threads. + # + # @api private class Transport - attr_accessor :url, :user, :password, :on_behalf_of + # The verb shorthands, defined once for the two transports that answer + # them. + # + # {Test::Transport} stands in for this class precisely so that the code + # under test cannot tell them apart, and it carried its own copy of this + # loop - so a fifth verb added here would have left the stand-in unable to + # answer one the real transport had. The same argument as + # {Transport.relative_path} and {Resources::Base.member_path}: a rule kept + # in two places is one that gets changed in one of them. + # + # @api private + module Verbs + # @!method get(path, operation:, query: nil, headers: nil, resource_class: nil) + # @!method post(path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) + # @!method put(path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) + # @!method delete(path, operation:, query: nil, headers: nil, resource_class: nil) + # @return [Response] + %i[get post put delete].each do |verb| + define_method(verb) do |path, **options| + request(verb, path, **options) # steep:ignore NoMethod + end + end + end + + include Verbs + + # HTTP methods that are safe to repeat against Zammad: the ones that only + # read. + # + # PUT and DELETE are idempotent in HTTP and used to be here for that + # reason, but neither is safe to repeat against Zammad. A ticket update + # carrying an `article` creates that article on every delivery, so an + # update answered with a 504 and then a 200 added the article twice and + # sent its e-mail twice, while `update` reported success once. And a + # DELETE whose first answer was lost was repeated into a 404, so + # `destroy` raised NotFoundError for a record it had just deleted. A + # write that fails is reported instead, the way a POST always was, and + # the caller - who knows what the request carried - decides. + RETRIABLE_METHODS = %i[get head options].freeze + + # Transient statuses worth retrying. + RETRIABLE_STATUSES = [429, 500, 502, 503, 504].freeze + + # Socket failures that mean the request ran out of time. Most adapters + # wrap these into a Faraday error, but not all do, and this gem lets a + # caller choose the adapter. + # + # `timeout` and `socket` are required above for this list and the next + # one. Both constants used to resolve only because `require 'faraday'` + # reaches net/http, which loads them - so the day Faraday stops eagerly + # loading its default adapter, or a caller picks a slimmer one, this class + # body raises NameError and `require 'zammad_api'` fails before a single + # request. The Steepfile has declared both libraries all along. + TIMEOUT_ERRORS = [Errno::ETIMEDOUT, Timeout::Error].freeze + + # Socket failures that mean the instance could not be reached. Listed + # rather than caught as SystemCallError, so that an unrelated Errno - a + # logger writing to a full disk, say - is not relabelled as a network + # problem. + CONNECTION_ERRORS = [ + Errno::ECONNREFUSED, + Errno::ECONNRESET, + Errno::EHOSTUNREACH, + Errno::ENETUNREACH, + Errno::EPIPE, + SocketError + ].freeze + + # TLS failures, for the same reason the socket errors above are listed: + # most adapters wrap one into a Faraday::SSLError, but this gem lets a + # caller choose the adapter and not every adapter does. Unlisted, a + # certificate mismatch through such an adapter left `request` raw, past + # the `rescue ZammadAPI::TransportError` a caller had written - the one + # thing the rescue clauses there exist to prevent. + # + # Not in {RETRIABLE_EXCEPTIONS}: a rejected certificate is a fact about + # the instance, not a transient failure, and retrying it only delays the + # error by the backoff. + SSL_ERRORS = [OpenSSL::SSL::SSLError].freeze + + # Failures worth retrying. Faraday::RetriableResponse is how the retry + # middleware signals a retriable status internally and must stay in this + # list, otherwise it escapes as an unhandled Faraday error. + # + # Composed from the two lists above rather than repeating them. Listed + # by hand, CONNECTION_ERRORS was left out: a transient ECONNRESET through + # an adapter that wraps it was retried as a Faraday::ConnectionFailed, + # while the same failure through an adapter that does not raised on the + # first attempt - so how often a request was retried depended on which + # adapter a caller picked, and `request` already documents these as + # failures this class expects to see. The retry middleware still only + # retries RETRIABLE_METHODS, so a write is not repeated. + RETRIABLE_EXCEPTIONS = [ + Faraday::RetriableResponse, + Faraday::ConnectionFailed, + Faraday::TimeoutError, + *TIMEOUT_ERRORS, + *CONNECTION_ERRORS + ].freeze + + # Substrings that mark a key of what a request carries - its payload, its + # query, its headers - as holding a credential. + # Matching on a substring rather than the whole key covers the variants + # Zammad and OAuth actually send - password_confirm, access_token, + # refresh_token, client_secret - which an exact-match list silently let + # through to the log. + # + # The same argument reaches further than the first version of this list + # took it. `password` alone wrote `passwd` and `pwd` out in full, and + # `private_key` covered exactly one of the key spellings, so `api_key` + # and a bare `key` went to the log intact. `key` is matched as a word + # rather than as a substring, so `ssh_key` and `key` are covered while + # `keyboard` and `monkey_id` are not; `apikey` is spelled out because + # nothing separates the word there. + # + # `cookie` and `authorization` are here for the headers. A raw request + # takes headers of its own, and the log prints them: `Cookie` carries a + # session and matched nothing above, so `client.get(path, headers: + # {'Cookie' => ...})` wrote it out in full at debug level, and + # `Proxy-Authorization` went the same way. `Authorization` itself never + # gets this far - {RESERVED_HEADERS} refuses it - but every header named + # after it carries what it carries. + SENSITIVE_KEY_PATTERN = /password|passwd|pwd|token|secret|credential|cookie|authorization|api_?key|(? 2}` used to collapse + # into one parameter and send whichever Hash insertion order put last, + # dropping the other value without a word - the same silent-wrong-result + # shape as the dropped nil above, and the reason {ResourceProxy#search} + # normalises its keywords before they ever reach here. + # + # @api private + # @param query [Hash] + # @return [Hash{String => String, Array, Hash}] + # @raise [ArgumentError] for a nil value, for two keys that name the + # same parameter, or for a list a query string cannot carry, any of + # them at any depth + def self.stringify_query(query) = stringify_query_hash(query, nil) + + # Stringifies one level of a query, at whatever depth it sits. + # + # The duplicate check lives here rather than at the top level alone, + # because `condition` - which the search endpoints read, and which + # {ResourceProxy#search} takes as a keyword - is a Hash, and two + # spellings inside it collapsed exactly + # the way two spellings at the top level did. The nil check below has been + # at every depth all along; this is the same kind of rule. + # + # The key each name was first seen as is kept, so the message can print + # both spellings. Naming only the second left the reader to guess the + # first, which in a query assembled across several merges is the whole of + # the debugging. + # + # @api private + # @param hash [Hash] + # @param prefix [String, nil] the parameter path this Hash sits at + # @return [Hash{String => String, Array, Hash}] + # + # A key with an empty name is refused, for the reason a list Rails + # cannot read back is: a query string has no way to write one. Inside a + # structure it is written `[]`, which Rails reads as a list - `{list: + # [{'' => '1'}]}` arrives as `[['1']]` - and at the top level as + # `=value`, which Rails drops. + def self.stringify_query_hash(hash, prefix) + DuplicateKeys + .normalize(hash, prefix: prefix, &:to_s) + .to_h do |name, value| + raise ArgumentError, empty_query_name_message(prefix) if name.empty? + + [name, stringify_query_value(prefix ? "#{prefix}[#{name}]" : name, value)] + end + end + + # @api private + # @return [String] + def self.empty_query_name_message(prefix) + found = if prefix + "query parameter #{prefix} holds a key with an empty name, and a query string writes that as #{prefix}[], which Rails reads as a list" + else + 'a query parameter has an empty name, and a query string writes that as nothing but its value, which Rails drops' + end + + "#{found}. Name the key, or put a structure a query string cannot carry in the JSON body of a raw request, such as client.post." + end + + # Stringifies the scalars and leaves the structure to {QueryEncoder}. + # + # A nested value used to be rendered with to_s, so the `condition` that + # Zammad's search endpoints read - and that {ResourceProxy#search} takes + # as a keyword - went on the wire as a Ruby inspect string. Zammad could not parse that, dropped the parameter, and + # answered with an unnarrowed search that nothing marked as unnarrowed. + # A Hash is written as `condition[ticket.state_id][operator]=is`, which + # is the shape Rails reads back. + # + # @api private + # @param key [String] the parameter path, for the error message + # @param value [Object] + # @return [String, Array, Hash] + # @raise [ArgumentError] for a nil value, or a list a query string cannot + # carry + def self.stringify_query_value(key, value) + case value + when nil then raise ArgumentError, "query parameter #{key} is nil, and Zammad has no way to read that: pass a value, or leave the parameter out" + when Hash then stringify_query_hash(value, key) + when Array then stringify_query_list(key, value) + else wire_text(value, "query parameter #{key}") + end + end + + # Stringifies a list, and refuses one Rails could not read back as the + # list it was. + # + # A query string does not mark where an element of a list ends, so one + # Hash after another is a new element only once it is written with a + # value the one before has a place for too - see {QueryEncoder} - and two + # with none are read as one: `[{a: 1}, {b: 2}]` arrives as + # `[{a: 1, b: 2}]`. A Hash with nothing in it is not written at all, and + # the list arrives one element short. A list directly inside a list is + # written `[]` like the one around it, and `[[1, 2], [3]]` arrives as + # three lists of one. + # + # Refused, because the other answer is a request that carries something + # the caller did not write, to an endpoint that then narrows by it. + # + # @api private + # @param key [String] the parameter path, for the error message + # @param list [Array] + # @return [Array] + # @raise [ArgumentError] + def self.stringify_query_list(key, list) + elements = list.each_with_index.map { |inner, index| stringify_query_value("#{key}[#{index}]", inner) } + + elements.each_with_index do |element, index| + reason = QueryEncoder.misread(element, index.zero? ? nil : elements[index - 1]) + raise ArgumentError, misread_element_message("#{key}[#{index}]", reason) if reason + end + + elements + end + + # What a query string does to each kind of element {QueryEncoder.misread} + # names. + MISREAD_ELEMENTS = { + merged: 'has no plain value under a key the element before it has as well, and that is all a query string has to say ' \ + 'where one element of a list ends and the next begins: Rails would read the two as one. Every condition and ' \ + 'every group of conditions in a Zammad selector carries `operator`, which is such a key', + empty: 'is a Hash with no value in it, and a query string writes nothing for one: Rails would read the list one ' \ + 'element short', + list: 'is a list directly inside a list, and a query string writes both as `[]`: Rails would read each value of ' \ + 'the inner list as a list of its own' + }.freeze + private_constant :MISREAD_ELEMENTS + + # @api private + # @return [String] + def self.misread_element_message(path, reason) + "query parameter #{path} #{MISREAD_ELEMENTS.fetch(reason)}. To send a structure a query string cannot carry, " \ + 'put it in the JSON body of a raw request, such as client.post, which carries it as it is.' + end + + # Header names this class sets from the configuration, and will not take + # from a caller. + # + # +Authorization+ is built from the credentials {Config} validated, and + # +From+ is what {Client#on_behalf_of} means. Faraday's authorization + # middleware leaves a header that is already set alone, so a raw request + # carrying one of these would have replaced the client's own - quietly, + # and while {Client#inspect} went on reporting the authentication scheme + # it was built with. Naming the option that does mean it is the useful + # answer; overwriting in silence is not. + RESERVED_HEADERS = { + 'authorization' => 'authentication is configured on the client: pass http_token:, oauth2_token:, or user: and password:, or build a second client with Client#with', + 'from' => 'the From header is what on_behalf_of sets: use client.on_behalf_of(...) to perform requests for another user' + }.freeze + + # The headers a request carries beyond the ones this class sets. + # + # Names are downcased, which is what makes two spellings of one header + # comparable at all: HTTP treats them as the same header, so + # +{'Accept' => 'a', 'accept' => 'b'}+ would otherwise send whichever Hash + # order put last and drop the other without a word - the silent drop + # {DuplicateKeys} exists to refuse. + # + # Values are stringified for the reason {#with_on_behalf_of} stringifies + # the +From+ scope: a header is text on the wire, and a value of another + # type reaches Net::HTTP intact and dies there with + # `undefined method 'strip' for an instance of Integer`. + # + # Public for the same reason as {.stringify_query}: {Test} records what a + # request would have carried, and a stand-in whose recorded values + # disagree with the wire makes green tests mean less than they appear to. + # + # @api private + # @param headers [Hash] + # @return [Hash{String => String}] + # @raise [ArgumentError] for a nil value, a value that is not text, two + # spellings of one header, or a header this class sets itself + def self.stringify_headers(headers) + DuplicateKeys + .normalize(headers, noun: 'header') { it.to_s.downcase } + .to_h { |name, value| [name, stringify_header_value(name, value)] } + end + + # @api private + # @return [String] + def self.stringify_header_value(name, value) + reserved = RESERVED_HEADERS[name] + raise ArgumentError, "header #{name} is set by this client, not by a request: #{reserved}" if reserved + raise ArgumentError, "header #{name} is nil, and a header is always text: pass a value, or leave the header out" if value.nil? + raise ArgumentError, "header #{name} was given as #{value.inspect}, and a header is always text: pass a String" if !value.is_a?(String) && !value.is_a?(Symbol) && !value.is_a?(Numeric) + + text = wire_text(value, "header #{name}") + raise ArgumentError, "header #{name} holds a line break, which a header cannot carry: #{LINE_BREAK_ADVICE}" if line_break?(text) + + text + end + + # What to do about a line break in a header value, said wherever one is + # refused. + LINE_BREAK_ADVICE = 'the value is not quoted here, as it may be a credential. Read it without the line break - ' \ + 'a value read from a file usually ends in one, which is taken, but one inside it is not.' + + # Whether a header value holds a line break no header can carry. + # + # Net::HTTP strips the whitespace around a header value and refuses one + # with a line break left in it, with an ArgumentError that quotes the + # value: `http_token: "abc\ndef"` was taken when the client was built + # and raised at its first request, neither as a {ZammadAPI::Error} nor + # where the token was configured, with the token in the message. The + # +From+ scope and a raw request's headers went the same way. A line + # break at either end is stripped there, so a token read from a file + # with its newline still on works, and is still taken. + # + # @api private + # @param text [String] + # @return [Boolean] + def self.line_break?(text) + text = text.encode(Encoding::UTF_8) if !text.encoding.ascii_compatible? + /[\r\n]/.match?(text.strip) + rescue EncodingError + false + end + + # The +From+ scope as a transport holds it: text, and a copy of its own. + # + # Text, because a user id is a documented way to name the user and + # arrives as an Integer, which reached Net::HTTP intact and died there + # with `undefined method 'strip' for an instance of Integer`. + # + # A copy, because `String#to_s` hands back the receiver. The scoped + # client held the caller's own String, so a login buffer that was reused + # after `client.on_behalf_of(login)` changed who every later request from + # that client was performed for - the one thing a scope exists to pin. + # Copied rather than interned, for the reason {Config} copies what it is + # given: nothing a caller passed in should outlive what holds it. + # + # Public for the same reason as {.stringify_query}: {Test} carries the + # scope the way this class does, so that what it records is what the + # header would have carried. + # + # An identifier that names nobody is refused here, the one place every + # way to a +From+ header goes through, rather than only by + # {Client#on_behalf_of}. Zammad skips a header with nothing in it, so a + # transport scoped to one sent every request as the account it + # authenticates as. Nothing in it is what Rails calls blank, which + # counts Unicode spaces as well as ASCII ones: Zammad asks + # `request_header_from.blank?`. + # + # @api private + # @param identifier [String, Integer, nil] login, email or user id + # @return [String, nil] frozen, or nil for no scope + # @raise [ArgumentError] for an identifier with nothing in it + def self.stringify_on_behalf_of(identifier) + return nil if identifier.nil? + + text = wire_text(identifier, 'on_behalf_of') + raise ArgumentError, blank_on_behalf_of_message(identifier) if BLANK.match?(text) + raise ArgumentError, "on_behalf_of holds a line break, which the From header cannot carry: #{LINE_BREAK_ADVICE}" if line_break?(text) + + text.dup.freeze + end + + # What Rails calls blank, for a String: nothing but whitespace, Unicode + # spaces included. +strip+ removes the ASCII ones only, so a no-break + # space passed a check built on it and was then read as nothing. + # + # Asked of a String {.wire_text} has had: the pattern is US-ASCII, and + # matching it against text in an encoding ASCII is no part of raises + # Encoding::CompatibilityError. + BLANK = /\A[[:space:]]*\z/ + + # A value as text a request can carry: in UTF-8 where it was given in an + # encoding ASCII is no part of, such as UTF-16. + # + # Such a String cannot be joined to the ASCII around it. Faraday's + # escaping of a query value and Net::HTTP's writing of a header both + # raised Encoding::CompatibilityError for one, as did {BLANK} asked of a + # +From+ scope or a search keyword: neither a {ZammadAPI::Error} nor the + # ArgumentError a malformed value is refused with, and for a non-blank + # value, one that had nothing wrong with it but its encoding. Converted, + # it is the same text, in the encoding Zammad reads. + # + # An encoding ASCII is a part of is left as it was, binary included: its + # bytes are what went on the wire, and still are. + # + # @api private + # @param value [Object] + # @param name [String] what the value is, for the error message + # @return [String] + # @raise [ArgumentError] for text that cannot be converted to UTF-8 + def self.wire_text(value, name) + text = value.to_s + return text if text.encoding.ascii_compatible? + + begin + text.encode(Encoding::UTF_8) + rescue EncodingError + raise ArgumentError, "#{name} was given as #{text.encoding} text that cannot be converted to UTF-8, which is what " \ + 'a request carries: it holds a byte sequence that is not valid in its own encoding.' + end + end + + # @api private + # @return [String] + def self.blank_on_behalf_of_message(identifier) + "on_behalf_of needs the login, email address or id of a user, and was given #{identifier.inspect}. " \ + 'Zammad reads a From header with nothing in it as no header at all, so every request would be performed ' \ + 'as the account this client authenticates as, with nothing to say the scope was missing.' + end + + # Percent-encodes one segment of a request path. + # + # Record ids are pasted into the path, and an id taken straight from a + # request parameter used to be pasted in whole: `find("1/../../api/v1/ + # users/1")` resolved to the users endpoint, so the parameter, not the + # call, chose which records the verb applied to. Encoding everything + # outside the unreserved set keeps a separator inside the segment it was + # written in, and a caller that really means a sub-path can spell it out + # with the raw request methods. + # + # A dot segment is refused rather than encoded. `.` and `..` are unreserved + # all the way through, so the encoding below returns them exactly as they + # arrived and `find('..')` still resolved one path level up - onto the + # index endpoint, and through a has_many path onto every article on the + # instance offered as one ticket's. Percent-encoding the dots would hold + # them inside the segment here, but a proxy that normalises a path before + # routing it would undo that, and no Zammad record is named for one. + # + # Public for the same reason as {.stringify_query}: {Test} builds the + # paths it records with it. + # + # @api private + # @param value [Object] + # @return [String] + # @raise [ArgumentError] when there is nothing to send, or when the id + # navigates instead of naming a record + def self.escape_path_segment(value) + segment = value.to_s + raise ArgumentError, 'a record id is required, and this one is empty' if segment.empty? + raise ArgumentError, "#{segment.inspect} points at another endpoint rather than naming a record" if DOT_SEGMENTS.include?(segment) + + segment.gsub(UNRESERVED_IN_PATH) { |character| character.bytes.map { format('%%%02X', it) }.join } + end + + # Strips the leading slashes from a path so that it resolves against the + # instance URL rather than against the host. + # + # {Config#url} always ends in a slash and every request path is appended + # relative to it, so a leading slash would drop the sub-path of a Zammad + # served from one - `https://host/zammad/` + `/api/v1/tickets` resolves to + # `https://host/api/v1/tickets`. + # + # A path that names a host of its own is refused. Faraday lets an absolute + # URL replace the instance URL and still attaches this client's headers, + # so `client.get('https://other.example/collect')` - a link lifted from a + # response body, say - sent the access token and the on_behalf_of scope + # to that host. Record ids are held inside their segment by + # {.escape_path_segment}; this is the same escape, one level up. The + # message does not quote the path, which may carry a secret of its own. + # + # Public for the same reason as {.stringify_query} and + # {.escape_path_segment}: {Client} and {Test} both apply this rule, the + # latter to decide which stub a request matches, and a path rule kept in + # three places is one that gets changed in one of them - at which point + # the stand-in quietly stops matching what the client sends. + # + # A path that cannot be read as a URL is refused here as well, which is + # where it stops being Faraday's to refuse. Faraday reads the path with + # URI when the request is built, and URI raises an error of its own for + # one it cannot read: `client.get('api/v1/tägs')` and + # `client.get(' api/v1/x')` left as URI::InvalidURIError, which is + # neither a {ZammadAPI::Error} nor the ArgumentError a raw request + # documents for a path, so no rescue a caller was told to write caught + # it. And it was raised after the request had been logged, leaving a line + # for a request that never left - what {#perform} stringifies the query + # and the headers first to prevent. + # + # @api private + # @param path [Object] + # @return [String] + # @raise [ArgumentError] for an absolute URL, or a path that cannot be + # read as a URL + def self.relative_path(path) + relative = path.to_s.sub(%r{\A/+}, '') + if ABSOLUTE_URL.match?(relative) + raise ArgumentError, 'a request path is relative to the instance URL, and this one is an absolute URL: sending it would hand ' \ + "this client's credentials to another host. Pass the path alone, such as 'api/v1/tickets'." + end + + refuse_unreadable_path!(relative) + relative + end + + # Reads a path the two ways Faraday will: the whole of it as a URL, and + # a query string written into it as parameters. + # + # The second can fail where the first does not. `?a=1&a[b]=2` names one + # parameter as a value and as a structure, and decoding it raised + # TypeError from inside the connection. + # + # Neither message quotes the path, for the reason the one above does + # not, and neither passes on the error underneath, which does quote it: + # not its message, and not the error itself as the cause, which Ruby + # attaches to an error raised in a rescue and prints with it, so an + # exception tracker recorded the path, credentials and all. + # + # @api private + # @param relative [String] + # @return [void] + # @raise [ArgumentError] + def self.refuse_unreadable_path!(relative) + begin + URI.parse(relative) + rescue URI::InvalidURIError + raise ArgumentError, unreadable_path_message(relative), cause: nil + end - def initialize(config, logger) - @logger = logger - @logger.debug "Transport to #{config[:url]} with #{config[:user]}:#{config[:password]}" - @conn = Faraday.new(url: config[:url]) do |faraday| - #faraday.request :url_encoded # form-encode POST params - #faraday.response :logger # log requests to STDOUT - faraday.adapter Faraday.default_adapter # make requests with Net::HTTP + begin + QueryEncoder.decode(relative.partition('#').first.partition('?').last) + rescue TypeError, Faraday::Error + raise ArgumentError, 'the query string written into this request path cannot be read as parameters: it names one of them ' \ + 'both as a value and as a structure, or nests them deeper than a query string is read. ' \ + 'Pass the parameters as query: instead, which takes them as a Hash.', cause: nil end - @conn.headers[:user_agent] = 'Zammad API Ruby' - if config[:http_token] && !config[:http_token].empty? - @conn.request :authorization, 'Token', config[:http_token] - elsif config[:oauth2_token] && !config[:oauth2_token].empty? - @conn.request :authorization, 'Bearer', config[:oauth2_token] - else - @conn.request :authorization, :basic, config[:user], config[:password] + end + + # @api private + # @return [String] + def self.unreadable_path_message(relative) + found = relative.ascii_only? ? 'a space, or another character a URL does not allow, or a % that begins no escape' : 'a character outside ASCII' + + "a request path is written the way a URL is, and this one cannot be read as one: it holds #{found}. " \ + 'Percent-encode what a URL cannot hold as it is - a space is %20, and ä is %C3%A4 - ' \ + 'or pass a parameter as query:, which encodes its value.' + end + + # A request path as it may be printed: with the credentials of a query + # string written into it blanked. + # + # A raw request may carry its query in the path - + # `client.get('api/v1/users/password_reset_verify?token=...')` is how the + # Zammad documentation spells that endpoint - and the path is printed in + # three places: the two log lines for a request, the message of a + # timeout, and the operation a raw request is named by in every error it + # raises. The `query:` Hash is redacted by key before it is logged, and + # the same parameter written into the path went out in full in all + # three. + # + # Redacted by name, as the Hash is, and written back as it was given + # otherwise. A name that cannot be decoded cannot be read, so its value + # is blanked rather than assumed to be harmless. + # + # Public for {Client}, which names a raw request by its path. + # + # @api private + # @param path [Object] + # @return [String] + def self.redact_path(path) + base, mark, query = path.to_s.partition('?') + return base if mark.empty? + + "#{base}?#{query.split('&', -1).map { redact_query_pair(it) }.join('&')}" + end + + # @api private + # @return [String] + def self.redact_query_pair(pair) + name, mark, = pair.partition('=') + return pair if mark.empty? + + decoded = begin + URI.decode_www_form_component(name) + rescue ArgumentError + nil end + + decoded && !SENSITIVE_KEY_PATTERN.match?(decoded) ? pair : "#{name}=#{REDACTED}" + end + + # The bytes a request body goes out as. + # + # Encoded here rather than left to Faraday's JSON middleware, because a + # body that cannot be encoded raised JSON::GeneratorError from inside the + # stack and nothing mapped it: `client.post(path, body: {data: + # File.binread('a.png')})` with the bytes not Base64-encoded, or any body + # holding a Float::NAN, went past the +rescue ZammadAPI::Error+ every + # caller is told to write, and a record whose +save+ carried the same + # value took the same way out. It is also encoded before the request is + # logged, for the reason the query and the headers are stringified + # first: a refused body leaves no line claiming a request that was never + # made. + # + # A String is passed through, as the middleware passes it: it is the + # caller saying the body is already encoded. + # + # Public for the same reason as {.stringify_query}: {Test} refuses what + # the wire would refuse. + # + # @api private + # @param body [Object] + # @param operation [String] description used in the error message + # @param resource_class [Class, nil] used in the error message + # @return [String, nil] nil for a request without a body + # @raise [Error] when the body cannot be encoded as JSON + def self.encode_body(body, operation:, resource_class: nil) + return body if body.nil? || body.is_a?(String) + + JSON.generate(body) + rescue JSON::JSONError => e + raise Error, "Can't #{Error.subject_for(operation, resource_class)}: the request body cannot be encoded as JSON (#{e.message}). " \ + 'Every value has to be a JSON type, and text has to be valid UTF-8: Base64-encode binary data such as an ' \ + 'attachment, and leave out a Float that is NaN or infinite.' + end + + # @param config [Config] + def initialize(config) + @config = config + @on_behalf_of = nil + @connection = build_connection + end + + # Returns a copy of this transport that sends the +From+ header. + # + # The scope is stringified here rather than at the point the header is + # set, so that {Test} records the value the wire would carry: an Integer + # used to die inside Net::HTTP while the test kit accepted it happily. + # See {.stringify_on_behalf_of} for what is held. + # + # @param identifier [String, Integer, nil] login, email or user id + # @return [Transport] + def with_on_behalf_of(identifier) + copy = dup + copy.instance_variable_set(:@on_behalf_of, Transport.stringify_on_behalf_of(identifier)) + copy end - %w[get post put delete].each do |method| - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{method}(params) # def get(params) - run_request(:#{method}, params) # run_request(:get, params) - end # end - RUBY + # Returns a transport of this kind configured with +config+, keeping any + # {#with_on_behalf_of} scope. + # + # {Client#with} goes through here rather than building a Transport itself, + # so that a client whose transport was replaced - the test kit's stand-in, + # say - derives another of the same kind instead of silently reverting to + # a real HTTP one. + # + # @param config [Config] + # @return [Transport] + def with_config(config) = self.class.new(config).with_on_behalf_of(on_behalf_of) + + # Says where this transport points and how it authenticates, and nothing + # else. + # + # Left to Ruby, this printed the instance variables, and one of them is + # the Faraday connection: its proxy options carry the proxy password and + # its middleware stack carries the arguments it was built with, the + # access token among them. Every record holds its transport, so that was + # one +inspect+ away from any of them. Defining this covers +pp+ as well, + # which uses an +inspect+ a class defines for itself. + # + # @return [String] + def inspect + "#<#{self.class.name} url=#{config.redacted_url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{on_behalf_of.inspect}" if on_behalf_of}>" + end + + # Performs a request and raises on anything but a 2xx response. + # + # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ + # @param path [String] path relative to {Config#url} + # @param operation [String] description used in error messages + # @param query [Hash, nil] query string parameters + # @param body [Hash, nil] request payload, encoded as JSON + # @param headers [Hash, nil] request headers, beyond the ones this class + # sets from the configuration + # @param resource_class [Class, nil] used in error messages + # @return [Response] + # @raise [ResponseError] for non-2xx responses + # @raise [TimeoutError] when the request timed out + # @raise [ConnectionError] when the instance was unreachable + # + # @raise [Error] when the body cannot be encoded as JSON + # + # Every failure leaves here as a {ZammadAPI::Error}. The bare socket + # errors are caught alongside the Faraday ones because they are already + # in {RETRIABLE_EXCEPTIONS}, which is this class saying it expects to see + # them: an adapter that does not wrap them used to let them out raw once + # the retries were spent, past every rescue a caller had written. + def request(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) + # Here as well as in {Client}, because this is the one door every + # request goes through, whichever caller built the path. + path = Transport.relative_path(path) + payload = Transport.encode_body(body, operation: operation, resource_class: resource_class) + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + response = decode(perform(method, path, query, body, payload, headers)) + log_response(method, path, response, started) + + return response if response.success? + + raise ResponseError.build(response, operation: operation, resource_class: resource_class) + rescue Faraday::TimeoutError, *TIMEOUT_ERRORS => e + raise TimeoutError, "Can't #{operation}: request to #{Transport.redact_path(path)} timed out (#{e.message})" + rescue Faraday::SSLError, *SSL_ERRORS => e + raise ConnectionError, "Can't #{operation}: TLS handshake with #{config.redacted_url} failed (#{e.message})" + rescue Faraday::ConnectionFailed, *CONNECTION_ERRORS => e + # Before it is called unreachable, because one kind of connection + # failure is a timeout. See #timed_out?. + raise TimeoutError, "Can't #{operation}: connecting to #{config.redacted_url} timed out (#{e.message})" if timed_out?(e) + + raise ConnectionError, "Can't #{operation}: #{config.redacted_url} is unreachable (#{e.message})" end private - def run_request(verb, param) - @logger.debug "#{verb.to_s.upcase}: #{@url}#{param[:url]}" + # Whether a connection failure is a timeout underneath. + # + # An exceeded +open_timeout+ is raised by Net::HTTP as Net::OpenTimeout, + # and the default adapter wraps that into Faraday::ConnectionFailed along + # with every other failure to connect. So it was reported as "is + # unreachable (execution expired)", a ConnectionError, and skipped the + # +rescue ZammadAPI::TimeoutError+ that is documented to catch an + # exceeded +open_timeout+. + # + # Both places an adapter can leave the original are looked at: Faraday's + # own +wrapped_exception+, and the +cause+ Ruby records for an error + # raised while another was being handled. + def timed_out?(error) + wrapped = error.respond_to?(:wrapped_exception) ? error.wrapped_exception : nil + + [wrapped, error.cause].any? { |inner| TIMEOUT_ERRORS.any? { inner.is_a?(it) } } + end - with_params = !param[:params].nil? - if with_params - @logger.debug "Params: #{param[:params].inspect}" + # +body+ is what the caller handed over, which is what the log redacts + # and prints; +payload+ is the same thing encoded, which is what is sent. + def perform(method, path, query, body, payload, headers) + # Built before the request is logged, so a rejected query or header does + # not leave a line claiming a request that was never made. + params = query && Transport.stringify_query(query) + fields = headers && Transport.stringify_headers(headers) + log_request(method, path, query, body, fields) + + @connection.public_send(method, path) do |request| + request.params.update(params) if params + # One at a time rather than in bulk, so that every name goes through + # Faraday's own case-insensitive writer and replaces the header it + # names rather than sitting beside it under another spelling. + fields&.each { |name, value| request.headers[name] = value } + request.body = payload if payload + request.headers['From'] = on_behalf_of if on_behalf_of end + end - response = @conn.public_send(verb) do |req| - req.url param[:url] + def build_connection + connection = Faraday.new( + url: config.url, + proxy: config.proxy, + ssl: { verify: config.ssl_verify }, + # The encoder is this gem's own: see {QueryEncoder} for the one + # structure Faraday's writes so that Rails reads another. + request: { timeout: config.timeout, open_timeout: config.open_timeout, params_encoder: QueryEncoder }, + headers: { 'User-Agent' => config.user_agent, 'Accept' => 'application/json' } + ) do |faraday| + apply_authentication(faraday) + faraday.request :json + faraday.request :retry, retry_options + # Last in the stack, so a caller's middleware sees the request as this + # gem finished building it and the response before anything else does. + config.middleware&.call(faraday) + faraday.adapter(config.adapter || Faraday.default_adapter) + end - if with_params - req.headers['Content-Type'] = 'application/json' - req.body = param[:params].to_json - end + refuse_unusable_middleware!(connection) + connection + rescue ZammadAPI::Error + raise + rescue => e + # An unregistered adapter, a proxy that is not a URL, or a middleware + # that rejects its options is a configuration mistake, and neither + # Faraday nor URI is part of this gem's surface. + # + # Caught as StandardError rather than as Faraday::Error, because the + # failures that do not come from Faraday are the ones a caller is least + # equipped to place: `proxy: 'http://user:pa ss@host'` escaped as + # URI::InvalidURIError and a `middleware` callable that raises escaped + # as whatever it raised, both straight past the + # `rescue ZammadAPI::ConfigurationError` that building a client is + # documented to need. The class is named in the message because + # "bad URI (is not URI?)" on its own says nothing about where to look. + raise ConfigurationError, "config could not be used to build a connection: #{e.class}: #{redact_config_values(e.message)}", cause: reportable_cause(e) + end - if !on_behalf_of.nil? - req.headers['From'] = on_behalf_of - end + # The error to keep as the cause of the ConfigurationError above, where + # it can be kept. + # + # Ruby attaches the error being rescued to the one raised in its place, + # and a report prints the whole chain: `full_message`, a logger's + # formatter, an error tracker. So the message above was scrubbed and the + # original went out right behind it, `caused by URI::InvalidURIError: bad + # URI (is not URI?): "http://user:pa ss@host:3128"`, password and all. + # + # Dropped only where that is what would happen. The whole report is + # asked, causes of its own included, because the whole report is what + # gets printed, and it is asked the question the message was: whether it + # quotes a configured value that redaction changes. Every other failure + # keeps its cause. A `middleware:` callable that raises is a bug in the + # caller's own code, and the backtrace into it is the one thing the + # message cannot carry. + # + # An error that cannot render its report is dropped as well. Rendering is + # the error's own code - `detailed_message` is there to be overridden, + # and one written without the `highlight:` keyword raises ArgumentError + # from inside `full_message` - and this runs in the rescue above, so what + # it raised left in place of the ConfigurationError, past the rescue + # building a client is documented to need. A report that cannot be read + # cannot be shown to quote nothing, which is the one condition a cause is + # kept on. + def reportable_cause(error) + report = error.full_message(highlight: false) + + redact_config_values(report) == report ? error : nil + rescue + nil + end - yield(req) if block_given? + # The underlying error quotes the value it rejected, and for a proxy that + # value carries its credentials: `proxy: 'http://user:pa ss@host:3128'` + # came back as URI::InvalidURIError with the whole URL, password included, + # in its message - and that message goes into the ConfigurationError + # above, which lands in every log and exception report. The one case + # {Config#inspect} and {Config#redacted} exist to prevent, reached by + # another route. + # + # The configured values are swapped for their redacted forms rather than + # the message being dropped, because "bad URI (is not URI?)" without the + # URI says nothing about where to look. Substring replacement, because + # the message embeds the value verbatim, and the url as well as the proxy + # because {Config} can only refuse the credentials in a url it can read: + # one that is not a URL at all gets this far, and is quoted here. + def redact_config_values(message) + [config.proxy, config.url].compact.inject(message.to_s) do |text, value| + redacted = config.redacted(value) + + # The block form. A String replacement expands the backslash + # sequences it contains, and the replacement here is the configured + # value with its userinfo blanked - so a value carrying `\0` or `\&` + # put the whole matched text back, credentials included, into the + # message it had just been taken out of, and one carrying `\1` cut + # the replacement short instead. + # + # Every spelling of the value, because the error being quoted may + # have inspected it rather than interpolated it: URI::InvalidURIError + # does, and inspect escapes exactly the backslashes, quotes and + # control characters that make a URL invalid in the first place. The + # escaped text no longer equals the value as configured, so the swap + # matched nothing and left the password standing in full - the case + # this method exists for, reached through the quoting rather than + # the value. + quoted_spellings(value).inject(text) { |scrubbed, spelling| scrubbed.gsub(spelling) { redacted } } + end + end + + # The value as an error may have quoted it: as it is, as +inspect+ + # writes it, and as +dump+ does. + # + # The last two part ways at the first character outside ASCII, which + # +inspect+ leaves standing and +dump+ writes as an escape, and URI + # rejects a URL holding one with the +dump+ spelling: "URI must be ascii + # only" and the value with every such character as `\u00E4`. A password + # with an umlaut in it therefore matched neither of the two spellings + # that were looked for, and stayed in the message - and in the cause, + # which is kept wherever redaction finds nothing to change. + def quoted_spellings(value) = [value, value.inspect[1...-1], value.dump[1...-1]].compact.uniq + + def apply_authentication(faraday) + case config.authentication_scheme + when :http_token then faraday.request :authorization, 'Token', config.http_token + when :oauth2_token then faraday.request :authorization, 'Bearer', config.oauth2_token + else faraday.request :authorization, :basic, config.user, config.password end + end + + # +max_interval+ is what bounds a wait. The retry middleware sleeps for + # whatever a +Retry-After+ header says, and its own ceiling defaults to + # no ceiling at all: a maintenance page answering 503 with + # +Retry-After: 3600+ held the calling thread for an hour per retry, + # whatever +timeout+ and +retry_interval+ said, before raising the error + # it could have raised at once. + # + # +timeout+ is the bound, because it is already how long this client + # was told it may wait for an answer. A +Retry-After+ within it is + # honoured; a longer one is not waited out, and the response it came + # with is reported as the error it is, with the figure still readable + # from {RateLimitError#retry_after}. + def retry_options + { + max: config.retries, + interval: config.retry_interval, + max_interval: config.timeout, + interval_randomness: 0.5, + backoff_factor: 2, + retry_statuses: RETRIABLE_STATUSES, + methods: RETRIABLE_METHODS, + exceptions: RETRIABLE_EXCEPTIONS + } + end + + def decode(faraday_response) + headers = faraday_response.headers.to_h.transform_keys { it.to_s.downcase }.freeze + raw_body = raw_body!(faraday_response.body) + body, json = Response.decode_body(headers['content-type'], raw_body) + + Response.new( + status: faraday_response.status, + headers: headers, + body: body, + raw_body: raw_body, + json: json + ) + end + + # Middleware this gem cannot do its own work behind, each with what it + # takes away and how it is usually spelled. Matched by name so that naming + # one does not require it to be loaded, and looked for among the ancestors + # of what is in the stack: see {#refused_middleware}. + # + # The first reads the body before this gem can. The second raises for a + # 4xx or 5xx before this gem sees the response, and it sits below the + # retry middleware, which is where a caller's middleware goes: a GET + # answered 503 left as Faraday::ServerError without being retried, a 404 + # as Faraday::ResourceNotFound, so `exists?` raised for a record that is + # merely absent, and a 422 as an error `save` does not turn into false. + # None of them is a {ZammadAPI::Error}, which is what every failure is + # documented to leave as. + REFUSED_MIDDLEWARE = { + 'Faraday::Response::Json' => ['which decodes the response body before this gem can. This gem parses JSON itself, and hands ' \ + 'the undecoded bytes to attachment downloads, so it needs the body as it arrives', + 'c.response :json'].freeze, + 'Faraday::Response::RaiseError' => ['which raises a Faraday error for a 4xx or 5xx response before this gem sees it. This gem ' \ + 'raises its own error for each status, and retries a read that was answered 429 or 5xx, ' \ + 'and behind this middleware it does neither', + 'c.response :raise_error'].freeze + }.freeze + private_constant :REFUSED_MIDDLEWARE + + # Refuses a stack this gem cannot work behind, while the stack is still + # the only thing that has happened. + # + # `raw_body!` below catches a decoded body too, but only once a response + # is in hand - which is one request too late: `client.groups.create(...)` + # sent the POST, Zammad created the group, and only then did a + # ConfigurationError come back, so a caller retrying what looked like a + # configuration failure created a second one. The middleware is fully + # visible here, where the unregistered adapter and the unusable proxy are + # already refused before anything is sent. + def refuse_unusable_middleware!(connection) + connection.builder.handlers.each do |handler| + refused = refused_middleware(handler.klass) + raise ConfigurationError, refused_middleware_message(handler.klass, refused) if refused + end + end + + # Which refused middleware a class in the stack is, if it is one: itself, + # or the one it inherits from. + # + # Only the class's own name used to be asked, and a subclass has another. + # `class QuietRaiseError < Faraday::Response::RaiseError`, the usual way + # to adjust what that middleware raises, went through `c.use` unrefused, + # and its inherited handler then raised Faraday::ResourceNotFound for a + # 404 before this gem saw the response - everything the refusal is there + # to prevent, one `<` away from it. + # + # @return [String, nil] the name it is refused under + def refused_middleware(klass) = klass.ancestors.filter_map(&:name).find { REFUSED_MIDDLEWARE.key?(it) } + + # A subclass is named along with what it inherits from, because the + # reason describes the parent - and it is told to drop "it", because the + # line that added a subclass is not the one the parent is usually spelled + # with. + def refused_middleware_message(klass, refused) + reason, spelling = REFUSED_MIDDLEWARE.fetch(refused) + found, drop = klass.name == refused ? [refused, "`#{spelling}`"] : ["#{klass.name || 'an anonymous class'}, a subclass of #{refused}", 'it'] - @logger.debug "Response: #{response.body}" - response + "the configured middleware includes #{found}, #{reason}: drop #{drop} from the `middleware:` callable." end + + # The body as it came off the wire. + # + # `middleware:` is a documented seam and `c.response :json` is a + # reasonable thing to put through it, at which point Faraday hands over a + # Hash rather than the bytes. `to_s` turned that into a Ruby inspect + # string, which JSON.parse then refused, so every record built from the + # response died in {Response#decoded} with a ParseError naming Zammad for + # what the caller's own stack had done. + # + # A backstop rather than the first line of defence: the stack is checked + # when it is built, which catches `c.response :json` before a request goes + # out. This is what is left for a middleware that decodes without being one + # of the names that check knows. + # + # Said plainly instead. Re-encoding the parsed structure was the other + # way out, and it is worse than it looks: {Response#raw_body} is + # documented as the undecoded body and + # {Resources::TicketArticleAttachment#download} hands exactly those bytes + # back as the file, so a re-encoding silently returns something that is + # not what Zammad stored - and JSON.generate has its own failures, which + # would escape from here past the `rescue ZammadAPI::Error` every caller + # is told to write. Once the bytes are gone they cannot be recovered, so + # the honest answer is to name the cause while it is still visible. + def raw_body!(body) + return body.to_s if body.nil? || body.is_a?(String) + + raise ConfigurationError, + 'the configured middleware decoded the response body before this gem could ' \ + "(Faraday handed over #{body.class} rather than the raw body). This gem parses JSON itself, " \ + 'and hands the undecoded bytes to attachment downloads, so it needs the body as it arrived: ' \ + 'drop the parsing middleware - `c.response :json` is the usual one - from the `middleware:` callable.' + end + + def log_request(method, path, query, body, headers) + logger.debug do + "Zammad API request: #{method.to_s.upcase} #{Transport.redact_path(path)}#{" query=#{redact(query).inspect}" if query}#{" headers=#{redact(headers).inspect}" if headers}" + end + logger.debug { "Zammad API payload: #{loggable_body(body).inspect}" } if body + end + + def log_response(method, path, response, started) + duration = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round + logger.debug { "Zammad API response: #{method.to_s.upcase} #{Transport.redact_path(path)} -> #{response.status} in #{duration}ms" } + end + + # What the log prints for a request body. + # + # A body handed over as a String is the caller's own encoding, and + # {#redact} works by key: it had no keys to go by, so + # `client.post(path, body: '{"login":"a","password":"hunter2"}')` was + # written to the log as it stood. Where the String is JSON it is read + # for its keys and redacted like the structure it spells. Where it is + # not - a form body, a file - nothing in it can be told from a + # credential, and its size is logged in its place. + def loggable_body(body) + return redact(body) if !body.is_a?(String) + + decoded = JSON.parse(body) + decoded.is_a?(Hash) || decoded.is_a?(Array) ? redact(decoded) : unlogged_body(body) + rescue JSON::JSONError, EncodingError + unlogged_body(body) + end + + def unlogged_body(body) = "[#{body.bytesize} bytes that are not a JSON object or array, not logged]" + + def redact(value) + case value + when Hash then value.to_h { |key, nested| [key, SENSITIVE_KEY_PATTERN.match?(key.to_s) ? REDACTED : redact(nested)] } + when Array then value.map { redact(it) } + else value + end + end + + def logger = config.logger end end diff --git a/lib/zammad_api/version.rb b/lib/zammad_api/version.rb index 4915c54..f8df209 100644 --- a/lib/zammad_api/version.rb +++ b/lib/zammad_api/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ZammadAPI - VERSION = '1.4.0'.freeze + VERSION = '2.0.0.alpha1' end diff --git a/script/live_target.rb b/script/live_target.rb new file mode 100644 index 0000000..a237e76 --- /dev/null +++ b/script/live_target.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +# The Zammad the live checks run against: the integration specs, `rake spec`, +# `rake check_connection` and script/check_connection.rb. +# +# Each of them creates and deletes records, so none has a default for where, +# and each asks here whether one was named. They used to ask with a check of +# their own, three copies of one rule that only stayed in step by being +# changed together - and the day one of them read a TEST_URL as set that the +# others read as unset, rake would refuse a run that rspec then made, or the +# other way round. +# +# Plain Ruby with nothing required, so that the check script, which loads +# nothing of the spec suite on purpose, can load it too. +module LiveTarget + # What to write where TEST_URL is not set. A placeholder that cannot reach + # anything if it is pasted as it is: `.example` is reserved and never + # resolves. `http://localhost:3000/`, which this used to suggest, is where + # a Zammad under development listens. + EXAMPLE = 'TEST_URL=https://zammad.example/ TEST_USER=admin@example.com TEST_PASSWORD=test' + + module_function + + # @return [String, nil] TEST_URL, or nil where it is unset or blank - + # Unicode spaces included, as Rails reads blank + def url + value = ENV['TEST_URL'].to_s + value.match?(/\A[[:space:]]*\z/) ? nil : value.strip + end + + # @param what [String] what the refusing check would have done, and to what + # @return [String] + def unset_message(what) + "TEST_URL is not set. #{what} creates and deletes records in the Zammad it runs against, so name one, " \ + "and make it one you can lose: #{EXAMPLE}" + end +end diff --git a/spec/integration/authentication_spec.rb b/spec/integration/authentication_spec.rb new file mode 100644 index 0000000..79a8380 --- /dev/null +++ b/spec/integration/authentication_spec.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI, 'authentication' do + it 'has a version number' do + expect(ZammadAPI::VERSION).not_to be_nil + end + + context 'with invalid credentials' do + let(:client) { Helper.client(user: 'not_existing', password: 'not_existing') } + + it 'raises AuthenticationError with the failing operation' do + expect { client.users.find(1) }.to raise_error(ZammadAPI::AuthenticationError) do |error| + expect(error.status).to eq(401) + expect(error.operation).to eq('find object') + expect(error.resource_class).to eq(ZammadAPI::Resources::User) + end + end + + it 'raises a ClientError, so both can be rescued together' do + expect { client.users.find(1) }.to raise_error(ZammadAPI::ClientError) + end + + %i[organization group ticket_priority ticket_state].each do |resource| + it "raises for #{resource}" do + expect { client.public_send(resource).find(1) }.to raise_error(ZammadAPI::AuthenticationError) + end + end + end +end diff --git a/spec/zammad_api/resources/group_spec.rb b/spec/integration/group_spec.rb similarity index 83% rename from spec/zammad_api/resources/group_spec.rb rename to spec/integration/group_spec.rb index 6caf0d3..f3ab1b6 100644 --- a/spec/zammad_api/resources/group_spec.rb +++ b/spec/integration/group_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'group object basics' do +RSpec.describe ZammadAPI, 'group object basics' do client = Helper.client name = "some_group#{Helper.random}" group = nil it 'new with invalid attributes' do - group_invalid = client.group.new + group_invalid = client.groups.new expect(group_invalid.class).to eq(ZammadAPI::Resources::Group) expect(group_invalid.new_record?).to be(true) - expect { group_invalid.save }.to raise_error(ZammadAPI::ClientError) + expect { group_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - group = client.group.new( + group = client.groups.new( name: name, assignment_timeout: 100, follow_up_assignment: false, @@ -37,6 +37,7 @@ end it 'save' do + group = established!(group, 'new with valid attributes') result = group.save expect(result).to be(true) @@ -76,7 +77,8 @@ end it 'find' do - group_lookup = client.group.find(group.id) + group = established!(group, 'new with valid attributes') + group_lookup = client.groups.find(group.id) expect(group_lookup.class).to eq(ZammadAPI::Resources::Group) expect(group_lookup.id).to eq(group.id) @@ -89,7 +91,8 @@ end it 'all' do - groups = client.group.all + group = established!(group, 'new with valid attributes') + groups = client.groups.all group_exists = nil groups.each do |local_group| @@ -109,7 +112,7 @@ group_exists.active = true group_exists.save - group_lookup = client.group.find(group.id) + group_lookup = client.groups.find(group.id) expect(group_lookup.class).to eq(ZammadAPI::Resources::Group) expect(group_lookup.id).to eq(group.id) expect(group_lookup.name).to eq("#{name}-2") @@ -121,9 +124,9 @@ end it 'pagination with all' do - groups = client.group.all + groups = client.groups.all - expect(groups[0].class).to eq(ZammadAPI::Resources::Group) + expect(groups.first.class).to eq(ZammadAPI::Resources::Group) count = 0 groups.each do |local_group| @@ -133,13 +136,13 @@ expect(count).to eq(3) count = 0 - groups = client.group.all - groups.page(1, 3) do |local_group| + groups = client.groups.all + groups.page(1, per_page: 3).each do |local_group| expect(local_group.class).to eq(ZammadAPI::Resources::Group) count += 1 end expect(count).to eq(3) - groups.page(2, 3) do |local_group| + groups.page(2, per_page: 3).each do |local_group| expect(local_group.class).to eq(ZammadAPI::Resources::Group) count += 1 end @@ -147,6 +150,7 @@ end it 'destroy' do + group = established!(group, 'new with valid attributes') result = group.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/organization_spec.rb b/spec/integration/organization_spec.rb similarity index 80% rename from spec/zammad_api/resources/organization_spec.rb rename to spec/integration/organization_spec.rb index 7851181..2bfd08c 100644 --- a/spec/zammad_api/resources/organization_spec.rb +++ b/spec/integration/organization_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'organization object basics' do +RSpec.describe ZammadAPI, 'organization object basics' do client = Helper.client name = "some_organization#{Helper.random}" organization = nil it 'new with invalid attributes' do - organization_invalid = client.organization.new + organization_invalid = client.organizations.new expect(organization_invalid.class).to eq(ZammadAPI::Resources::Organization) expect(organization_invalid.new_record?).to be(true) - expect { organization_invalid.save }.to raise_error(ZammadAPI::ClientError) + expect { organization_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - organization = client.organization.new( + organization = client.organizations.new( name: name, shared: false, note: '', @@ -33,6 +33,7 @@ end it 'save' do + organization = established!(organization, 'new with valid attributes') result = organization.save expect(result).to be(true) @@ -72,7 +73,8 @@ end it 'find' do - organization_lookup = client.organization.find(organization.id) + organization = established!(organization, 'new with valid attributes') + organization_lookup = client.organizations.find(organization.id) expect(organization_lookup.class).to eq(ZammadAPI::Resources::Organization) expect(organization_lookup.id).to eq(organization.id) @@ -85,7 +87,8 @@ end it 'all' do - organizations = client.organization.all + organization = established!(organization, 'new with valid attributes') + organizations = client.organizations.all organization_exists = nil organizations.each do |local_organization| @@ -104,7 +107,7 @@ organization_exists.active = true organization_exists.save - organization_lookup = client.organization.find(organization.id) + organization_lookup = client.organizations.find(organization.id) expect(organization_lookup.class).to eq(ZammadAPI::Resources::Organization) expect(organization_lookup.id).to eq(organization.id) expect(organization_lookup.name).to eq("#{name}-2") @@ -115,9 +118,9 @@ end it 'pagination with all' do - organizations = client.organization.all + organizations = client.organizations.all - expect(organizations[0].class).to eq(ZammadAPI::Resources::Organization) + expect(organizations.first.class).to eq(ZammadAPI::Resources::Organization) count = 0 organizations.each do |local_organization| @@ -127,13 +130,13 @@ expect(count).to eq(2) count = 0 - organizations = client.organization.all - organizations.page(1, 3) do |local_organization| + organizations = client.organizations.all + organizations.page(1, per_page: 3).each do |local_organization| expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) count += 1 end expect(count).to eq(2) - organizations.page(2, 3) do |local_organization| + organizations.page(2, per_page: 3).each do |local_organization| expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) count += 1 end @@ -141,7 +144,8 @@ end it 'search' do - organizations = client.organization.search(query: name) + organization = established!(organization, 'new with valid attributes') + organizations = client.organizations.search(name) organization_exists = nil organizations.each do |local_organization| @@ -160,7 +164,7 @@ organization_exists.active = false organization_exists.save - organization_lookup = client.organization.find(organization.id) + organization_lookup = client.organizations.find(organization.id) expect(organization_lookup.class).to eq(ZammadAPI::Resources::Organization) expect(organization_lookup.id).to eq(organization.id) expect(organization_lookup.name).to eq("#{name}-2") @@ -171,9 +175,10 @@ end it 'pagination with search' do - organizations = client.organization.search(query: "#{name}-2") + organization = established!(organization, 'new with valid attributes') + organizations = client.organizations.search("#{name}-2") - expect(organizations[0].class).to eq(ZammadAPI::Resources::Organization) + expect(organizations.first.class).to eq(ZammadAPI::Resources::Organization) count = 0 organization_exists = nil @@ -194,13 +199,13 @@ expect(organization_exists.updated_by).to eq('admin@example.com') count = 0 - organizations = client.organization.search(query: 'zammad') - organizations.page(1, 3) do |local_organization| + organizations = client.organizations.search('zammad') + organizations.page(1, per_page: 3).each do |local_organization| expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) count += 1 end expect(count).to eq(1) - organizations.page(2, 3) do |local_organization| + organizations.page(2, per_page: 3).each do |local_organization| expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) count += 1 end @@ -208,6 +213,7 @@ end it 'destroy' do + organization = established!(organization, 'new with valid attributes') result = organization.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/ticket_priority_spec.rb b/spec/integration/ticket_priority_spec.rb similarity index 75% rename from spec/zammad_api/resources/ticket_priority_spec.rb rename to spec/integration/ticket_priority_spec.rb index 45f41a8..646eda2 100644 --- a/spec/zammad_api/resources/ticket_priority_spec.rb +++ b/spec/integration/ticket_priority_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'ticket priority object basics' do +RSpec.describe ZammadAPI, 'ticket priority object basics' do client = Helper.client name = "some_ticket_priority#{Helper.random}" ticket_priority = nil it 'new with invalid attributes' do - ticket_priority_invalid = client.ticket_priority.new + ticket_priority_invalid = client.ticket_priorities.new expect(ticket_priority_invalid.class).to eq(ZammadAPI::Resources::TicketPriority) expect(ticket_priority_invalid.new_record?).to be(true) - expect { ticket_priority_invalid.save }.to raise_error(ZammadAPI::ClientError) + expect { ticket_priority_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - ticket_priority = client.ticket_priority.new( + ticket_priority = client.ticket_priorities.new( name: name, note: '', active: true, @@ -31,6 +31,7 @@ end it 'save' do + ticket_priority = established!(ticket_priority, 'new with valid attributes') result = ticket_priority.save expect(result).to be(true) @@ -61,7 +62,8 @@ end it 'find' do - ticket_priority_lookup = client.ticket_priority.find(ticket_priority.id) + ticket_priority = established!(ticket_priority, 'new with valid attributes') + ticket_priority_lookup = client.ticket_priorities.find(ticket_priority.id) expect(ticket_priority_lookup.class).to eq(ZammadAPI::Resources::TicketPriority) expect(ticket_priority_lookup.id).to eq(ticket_priority.id) @@ -71,7 +73,8 @@ end it 'all' do - ticket_priorities = client.ticket_priority.all + ticket_priority = established!(ticket_priority, 'new with valid attributes') + ticket_priorities = client.ticket_priorities.all ticket_priority_exists = nil ticket_priorities.each do |local_ticket_priority| @@ -88,7 +91,7 @@ ticket_priority_exists.active = true ticket_priority_exists.save - ticket_priority_lookup = client.ticket_priority.find(ticket_priority.id) + ticket_priority_lookup = client.ticket_priorities.find(ticket_priority.id) expect(ticket_priority_lookup.class).to eq(ZammadAPI::Resources::TicketPriority) expect(ticket_priority_lookup.id).to eq(ticket_priority.id) expect(ticket_priority_lookup.name).to eq("#{name}-2") @@ -97,9 +100,9 @@ end it 'pagination with all' do - ticket_priorities = client.ticket_priority.all + ticket_priorities = client.ticket_priorities.all - expect(ticket_priorities[0].class).to eq(ZammadAPI::Resources::TicketPriority) + expect(ticket_priorities.first.class).to eq(ZammadAPI::Resources::TicketPriority) count = 0 ticket_priorities.each do |local_ticket_priority| @@ -109,18 +112,18 @@ expect(count).to eq(4) count = 0 - ticket_priorities = client.ticket_priority.all - ticket_priorities.page(1, 2) do |local_ticket_priority| + ticket_priorities = client.ticket_priorities.all + ticket_priorities.page(1, per_page: 2).each do |local_ticket_priority| expect(local_ticket_priority.class).to eq(ZammadAPI::Resources::TicketPriority) count += 1 end expect(count).to eq(2) - ticket_priorities.page(2, 2) do |local_ticket_priority| + ticket_priorities.page(2, per_page: 2).each do |local_ticket_priority| expect(local_ticket_priority.class).to eq(ZammadAPI::Resources::TicketPriority) count += 1 end expect(count).to eq(4) - ticket_priorities.page(3, 2) do |local_ticket_priority| + ticket_priorities.page(3, per_page: 2).each do |local_ticket_priority| expect(local_ticket_priority.class).to eq(ZammadAPI::Resources::TicketPriority) count += 1 end @@ -128,6 +131,7 @@ end it 'destroy' do + ticket_priority = established!(ticket_priority, 'new with valid attributes') result = ticket_priority.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/ticket_spec.rb b/spec/integration/ticket_spec.rb similarity index 84% rename from spec/zammad_api/resources/ticket_spec.rb rename to spec/integration/ticket_spec.rb index 1c95705..fb7a75d 100644 --- a/spec/zammad_api/resources/ticket_spec.rb +++ b/spec/integration/ticket_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'ticket object basics' do +RSpec.describe ZammadAPI, 'ticket object basics' do client = Helper.client title = "some ticket title ##{Helper.random}" ticket = nil it 'new with invalid attributes' do - ticket_invalid = client.ticket.new + ticket_invalid = client.tickets.new expect(ticket_invalid.class).to eq(ZammadAPI::Resources::Ticket) expect(ticket_invalid.new_record?).to be(true) - expect { ticket_invalid.save }.to raise_error(ZammadAPI::ClientError) + expect { ticket_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - ticket = client.ticket.new( + ticket = client.tickets.new( title: title, state: 'new', priority: '2 normal', @@ -42,6 +42,7 @@ end it 'save' do + ticket = established!(ticket, 'new with valid attributes') result = ticket.save expect(result).to be(true) @@ -80,11 +81,11 @@ articles = ticket.articles expect(articles.length).to eq(1) - expect(articles[0].class).to eq(ZammadAPI::Resources::TicketArticle) + expect(articles.first.class).to eq(ZammadAPI::Resources::TicketArticle) expect(articles[0].subject).to eq('some subject') expect(articles[0].body).to eq('some body') - ticket.article( + ticket.add_article( subject: 'some subject2', body: 'some body2', ) @@ -96,7 +97,7 @@ expect(articles[1].body).to eq('some body2') expect(articles[1].attachments.count).to eq(0) - ticket.article( + ticket.add_article( subject: 'some subject3', body: 'some body3', attachments: [ @@ -121,7 +122,8 @@ end it 'find' do - ticket_lookup = client.ticket.find(ticket.id) + ticket = established!(ticket, 'new with valid attributes') + ticket_lookup = client.tickets.find(ticket.id) expect(ticket_lookup.class).to eq(ZammadAPI::Resources::Ticket) expect(ticket_lookup.id).to eq(ticket.id) @@ -135,7 +137,8 @@ end it 'all' do - tickets = client.ticket.all + ticket = established!(ticket, 'new with valid attributes') + tickets = client.tickets.all ticket_exists = nil tickets.each do |local_ticket| @@ -156,7 +159,7 @@ ticket_exists.state = 'closed' ticket_exists.save - ticket_lookup = client.ticket.find(ticket.id) + ticket_lookup = client.tickets.find(ticket.id) expect(ticket_lookup.class).to eq(ZammadAPI::Resources::Ticket) expect(ticket_lookup.id).to eq(ticket.id) expect(ticket_lookup.title).to eq("#{title}-2") @@ -169,8 +172,9 @@ end it 'pagination with all' do + ticket = established!(ticket, 'new with valid attributes') (1..10).each do |local_count| - client.ticket.create( + client.tickets.create( title: "test count ticket #{local_count}", state: 'new', priority: '2 normal', @@ -187,8 +191,8 @@ ) end - tickets = client.ticket.all - expect(tickets[0].class).to eq(ZammadAPI::Resources::Ticket) + tickets = client.tickets.all + expect(tickets.first.class).to eq(ZammadAPI::Resources::Ticket) count = 0 tickets.each do |local_ticket| expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) @@ -197,18 +201,18 @@ expect(count).to eq(12) count = 0 - tickets = client.ticket.all - tickets.page(1, 5) do |local_ticket| + tickets = client.tickets.all + tickets.page(1, per_page: 5).each do |local_ticket| expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) count += 1 end expect(count).to eq(5) - tickets.page(2, 5) do |local_ticket| + tickets.page(2, per_page: 5).each do |local_ticket| expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) count += 1 end expect(count).to eq(10) - tickets.page(3, 5) do |local_ticket| + tickets.page(3, per_page: 5).each do |local_ticket| expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) count += 1 end @@ -216,6 +220,7 @@ end it 'destroy' do + ticket = established!(ticket, 'new with valid attributes') result = ticket.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/ticket_state_spec.rb b/spec/integration/ticket_state_spec.rb similarity index 84% rename from spec/zammad_api/resources/ticket_state_spec.rb rename to spec/integration/ticket_state_spec.rb index d672398..8b62bc4 100644 --- a/spec/zammad_api/resources/ticket_state_spec.rb +++ b/spec/integration/ticket_state_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'ticket state object basics' do +RSpec.describe ZammadAPI, 'ticket state object basics' do client = Helper.client name = "some_ticket_state#{Helper.random}" ticket_state = nil it 'new with invalid attributes' do - ticket_state_invalid = client.ticket_state.new + ticket_state_invalid = client.ticket_states.new expect(ticket_state_invalid.class).to eq(ZammadAPI::Resources::TicketState) expect(ticket_state_invalid.new_record?).to be(true) - expect { ticket_state_invalid.save }.to raise_error(ZammadAPI::ClientError) + expect { ticket_state_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - ticket_state = client.ticket_state.new( + ticket_state = client.ticket_states.new( name: name, state_type: 'new', next_state_id: nil, @@ -30,7 +30,7 @@ expect(ticket_state.id).to be_nil expect(ticket_state.name).to eq(name) expect(ticket_state.state_type).to eq('new') - expect(ticket_state.state_type_id).to be_nil + expect(ticket_state.key?(:state_type_id)).to be(false) expect(ticket_state.next_state_id).to be_nil expect(ticket_state.ignore_escalation).to be(false) expect(ticket_state.note).to eq('') @@ -38,6 +38,7 @@ end it 'save' do + ticket_state = established!(ticket_state, 'new with valid attributes') result = ticket_state.save expect(result).to be(true) @@ -91,7 +92,8 @@ end it 'find' do - ticket_state_lookup = client.ticket_state.find(ticket_state.id) + ticket_state = established!(ticket_state, 'new with valid attributes') + ticket_state_lookup = client.ticket_states.find(ticket_state.id) expect(ticket_state_lookup.class).to eq(ZammadAPI::Resources::TicketState) expect(ticket_state_lookup.id).to eq(ticket_state.id) @@ -108,7 +110,8 @@ end it 'all' do - ticket_states = client.ticket_state.all + ticket_state = established!(ticket_state, 'new with valid attributes') + ticket_states = client.ticket_states.all ticket_state_exists = nil ticket_states.each do |local_ticket_state| @@ -132,7 +135,7 @@ ticket_state_exists.active = true ticket_state_exists.save - ticket_state_lookup = client.ticket_state.find(ticket_state.id) + ticket_state_lookup = client.ticket_states.find(ticket_state.id) expect(ticket_state_lookup.class).to eq(ZammadAPI::Resources::TicketState) expect(ticket_state_lookup.id).to eq(ticket_state.id) expect(ticket_state_lookup.name).to eq("#{name}-2") @@ -147,9 +150,9 @@ end it 'pagination with all' do - ticket_states = client.ticket_state.all + ticket_states = client.ticket_states.all - expect(ticket_states[0].class).to eq(ZammadAPI::Resources::TicketState) + expect(ticket_states.first.class).to eq(ZammadAPI::Resources::TicketState) count = 0 ticket_states.each do |local_ticket_state| @@ -159,18 +162,18 @@ expect(count).to be >= 7 count = 0 - ticket_states = client.ticket_state.all - ticket_states.page(1, 3) do |local_ticket_state| + ticket_states = client.ticket_states.all + ticket_states.page(1, per_page: 3).each do |local_ticket_state| expect(local_ticket_state.class).to eq(ZammadAPI::Resources::TicketState) count += 1 end expect(count).to eq(3) - ticket_states.page(2, 3) do |local_ticket_state| + ticket_states.page(2, per_page: 3).each do |local_ticket_state| expect(local_ticket_state.class).to eq(ZammadAPI::Resources::TicketState) count += 1 end expect(count).to eq(6) - ticket_states.page(3, 3) do |local_ticket_state| + ticket_states.page(3, per_page: 3).each do |local_ticket_state| expect(local_ticket_state.class).to eq(ZammadAPI::Resources::TicketState) count += 1 end @@ -178,6 +181,7 @@ end it 'destroy' do + ticket_state = established!(ticket_state, 'new with valid attributes') result = ticket_state.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/user_spec.rb b/spec/integration/user_spec.rb similarity index 86% rename from spec/zammad_api/resources/user_spec.rb rename to spec/integration/user_spec.rb index a82b94b..41fd018 100644 --- a/spec/zammad_api/resources/user_spec.rb +++ b/spec/integration/user_spec.rb @@ -1,6 +1,6 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'user object basics' do +RSpec.describe ZammadAPI, 'user object basics' do client = Helper.client random = Helper.random @@ -10,16 +10,16 @@ user = nil it 'new with invalid attributes' do - user_invalid = client.user.new + user_invalid = client.users.new expect(user_invalid.class).to eq(ZammadAPI::Resources::User) expect(user_invalid.new_record?).to be(true) - expect { user_invalid.save }.to raise_error(ZammadAPI::ClientError) + expect { user_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - user = client.user.new( + user = client.users.new( firstname: firstname, lastname: lastname, email: email, @@ -44,6 +44,7 @@ end it 'save' do + user = established!(user, 'new with valid attributes') result = user.save expect(result).to be(true) @@ -88,7 +89,8 @@ end it 'find' do - user_lookup = client.user.find(user.id) + user = established!(user, 'new with valid attributes') + user_lookup = client.users.find(user.id) expect(user_lookup.class).to eq(ZammadAPI::Resources::User) expect(user_lookup.id).to eq(user.id) @@ -105,7 +107,8 @@ end it 'all' do - users = client.user.all + user = established!(user, 'new with valid attributes') + users = client.users.all user_exists = nil users.each do |local_user| @@ -128,7 +131,7 @@ expect(user_exists.updated_by).to eq('admin@example.com') user_exists.save - user_lookup = client.user.find(user.id) + user_lookup = client.users.find(user.id) expect(user_lookup.class).to eq(ZammadAPI::Resources::User) expect(user_lookup.id).to eq(user.id) expect(user_lookup.firstname).to eq("#{firstname}-2") @@ -146,7 +149,7 @@ it 'pagination with all' do (1..10).each do |local_count| - client.user.create( + client.users.create( firstname: "firstname#{local_count}", lastname: "lastname#{local_count}", email: "customer_email#{local_count}@example.com", @@ -157,9 +160,9 @@ ) end - users = client.user.all + users = client.users.all - expect(users[0].class).to eq(ZammadAPI::Resources::User) + expect(users.first.class).to eq(ZammadAPI::Resources::User) count = 0 users.each do |local_user| expect(local_user.class).to eq(ZammadAPI::Resources::User) @@ -168,19 +171,19 @@ expect(count).to eq(15) count = 0 - users = client.user.all - users.page(1, 4) do |local_user| + users = client.users.all + users.page(1, per_page: 4).each do |local_user| expect(local_user.class).to eq(ZammadAPI::Resources::User) count += 1 end expect(count).to eq(4) - users.page(2, 5) do |local_user| + users.page(2, per_page: 5).each do |local_user| expect(local_user.class).to eq(ZammadAPI::Resources::User) count += 1 end expect(count).to eq(9) count = 0 - users.page(1, 200) do |local_user| + users.page(1, per_page: 200).each do |local_user| expect(local_user.class).to eq(ZammadAPI::Resources::User) count += 1 end @@ -188,7 +191,8 @@ end it 'search' do - users = client.user.search(query: firstname) + user = established!(user, 'new with valid attributes') + users = client.users.search(firstname) user_exists = nil users.each do |local_user| @@ -210,7 +214,7 @@ user_exists.active = false user_exists.save - user_lookup = client.user.find(user.id) + user_lookup = client.users.find(user.id) expect(user_lookup.class).to eq(ZammadAPI::Resources::User) expect(user_lookup.id).to eq(user.id) expect(user_lookup.firstname).to eq("#{firstname}-2") @@ -224,9 +228,10 @@ end it 'pagination with search' do - users = client.user.search(query: firstname) + user = established!(user, 'new with valid attributes') + users = client.users.search(firstname) - expect(users[0].class).to eq(ZammadAPI::Resources::User) + expect(users.first.class).to eq(ZammadAPI::Resources::User) count = 0 user_exists = nil @@ -250,13 +255,13 @@ expect(user_exists.updated_by).to eq('admin@example.com') count = 0 - users = client.user.search(query: firstname) - users.page(1, 3) do |local_user| + users = client.users.search(firstname) + users.page(1, per_page: 3).each do |local_user| expect(local_user.class).to eq(ZammadAPI::Resources::User) count += 1 end expect(count).to eq(1) - users.page(2, 3) do |local_user| + users.page(2, per_page: 3).each do |local_user| expect(local_user.class).to eq(ZammadAPI::Resources::User) count += 1 end @@ -264,6 +269,7 @@ end it 'destroy' do + user = established!(user, 'new with valid attributes') # wait until zammad scheduler wrote some entries to activity stream # to have some references and not allow users to delete sleep 12 diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 6c318c4..bb3ab91 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,50 +1,86 @@ +# frozen_string_literal: true + +if ENV['COVERAGE'] + require 'simplecov' + SimpleCov.start do + enable_coverage :branch + skip '/spec/' + minimum_coverage line: 90, branch: 75 + end +end + $LOAD_PATH.unshift File.expand_path('../lib', __dir__) -# we don't require 'webmock/rspec' over here -# since we want to mock only certain requests -# but the API should be available in general -require 'webmock' +# Unit specs run entirely against stubs; integration specs opt back out below. +require 'webmock/rspec' +require 'zammad_api' + +Dir[File.expand_path('support/**/*.rb', __dir__)].each { require it } RSpec.configure do |config| - config.include WebMock::API - config.include WebMock::Matchers -end + config.include ClientHelper + config.include LifecycleState, :integration -require 'zammad_api' + config.expect_with(:rspec) { it.syntax = :expect } + config.mock_with(:rspec) { it.verify_partial_doubles = true } -class Helper - def self.config - { - url: ENV['TEST_URL'] || 'http://localhost:3000/', - user: ENV['TEST_USER'] || 'admin@example.com', - password: ENV['TEST_PASSWORD'] || 'test' - } - end + config.disable_monkey_patching! + config.warnings = false + config.filter_run_when_matching :focus + config.example_status_persistence_file_path = 'tmp/rspec_status.txt' + config.shared_context_metadata_behavior = :apply_to_host_groups - def self.client(params = {}) - ZammadAPI::Client.new( - url: params[:url] || config[:url], - user: params[:user] || config[:user], - password: params[:password] || config[:password], - ) + # Specs are grouped by what they need: unit specs run against WebMock stubs + # and never touch the network, integration specs need a live Zammad. + # + # The integration specs also walk a record through its lifecycle across + # ordered examples, so they are pinned to definition order. Without that a + # `--seed` or `--order random` run scrambled the lifecycle and failed on a + # record that had not been built yet. Unit specs stay order-independent. + config.define_derived_metadata(file_path: %r{/spec/unit/}) { it[:unit] = true } + config.define_derived_metadata(file_path: %r{/spec/integration/}) do |metadata| + metadata[:integration] = true + metadata[:order] = :defined end - # start auto wizard - def self.auto_wizard - conn = Faraday.new(url: config[:url]) do |faraday| - faraday.adapter Faraday.default_adapter # make requests with Net::HTTP - end - - url_auto_wizard = '/api/v1/getting_started/auto_wizard' - response = conn.get url_auto_wizard - data = JSON.parse(response.body) + # Integration specs write to the Zammad they are pointed at, so they run + # only where TEST_URL names one: see Helper.target. Left out rather than + # failed, so that a bare `rspec` is the unit specs and nothing else, and + # said once so that nobody takes it for a run of them. + # + # The notice goes out when the first of them is loaded rather than before + # the suite: RSpec runs no suite hook for a run that selected nothing, + # which is what `rspec spec/integration` is without a TEST_URL. + # + # A run that selected nothing but them fails, though: `rspec + # spec/integration` without a TEST_URL left every example out and passed + # with `0 examples, 0 failures`, so a CI job that lost its TEST_URL went + # green having run nothing. A bare `rspec` still runs the unit specs, so + # this fires only where everything selected was left out. + config.fail_if_no_examples = true - return true if data['auto_wizard_success'] + if Helper.target.nil? + config.filter_run_excluding :integration + config.when_first_matching_example_defined(:integration) do + warn 'Integration specs left out: they create and delete records, so they run only against the Zammad that ' \ + 'TEST_URL names. Set TEST_URL, TEST_USER and TEST_PASSWORD to run them.' + end + end - raise "Unable to start auto wizard: #{response.body}" + # The instance has to have an admin account before anything can + # authenticate. Doing this from a hook rather than from one spec file keeps + # the suite independent of file order. + config.before(:each, :integration) do + Helper.ensure_configured! end - def self.random - rand(99_999_999).to_s + # Integration specs need the real network, so WebMock steps aside for them. + config.around(:each, :integration) do |example| + WebMock.allow_net_connect! + WebMock.disable! + example.run + ensure + WebMock.enable! + WebMock.disable_net_connect! end end diff --git a/spec/support/bare_socket_adapter.rb b/spec/support/bare_socket_adapter.rb new file mode 100644 index 0000000..6e6f870 --- /dev/null +++ b/spec/support/bare_socket_adapter.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +require 'faraday' +require 'openssl' + +# A Faraday adapter that lets a socket error out raw. +# +# Most adapters wrap one into Faraday::ConnectionFailed, but this gem lets a +# caller choose the adapter, and an adapter that does not wrap is the only way +# to tell apart the two halves of the retry configuration: which failures are +# mapped to a ZammadAPI error, and which are retried before being mapped. +class BareSocketAdapter < Faraday::Adapter + class << self + # @return [Array] the verb of every request that reached here + attr_accessor :attempts + end + self.attempts = [] + + def call(env) + self.class.attempts << env.method + raise Errno::ECONNRESET + end +end + +Faraday::Adapter.register_middleware(bare_socket: BareSocketAdapter) + +# A Faraday adapter that lets a TLS failure out raw. +# +# The counterpart of BareSocketAdapter for OpenSSL::SSL::SSLError, which most +# adapters wrap into Faraday::SSLError. Unwrapped and unlisted, it escaped +# `request` entirely, past every `rescue ZammadAPI::Error` a caller had +# written. +class BareTlsAdapter < Faraday::Adapter + class << self + # @return [Array] the verb of every request that reached here + attr_accessor :attempts + end + self.attempts = [] + + def call(env) + self.class.attempts << env.method + raise OpenSSL::SSL::SSLError, 'certificate verify failed' + end +end + +Faraday::Adapter.register_middleware(bare_tls: BareTlsAdapter) diff --git a/spec/support/client_helper.rb b/spec/support/client_helper.rb new file mode 100644 index 0000000..51110dd --- /dev/null +++ b/spec/support/client_helper.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +# Helpers for unit specs, which talk to WebMock stubs instead of a Zammad. +module ClientHelper + BASE_URL = 'http://zammad.test/' + + # Retries are disabled by default so that specs exercising error paths do + # not wait for the backoff intervals. + def unit_config(**overrides) + { url: BASE_URL, http_token: 'test-token', retries: 0 }.merge(overrides) + end + + def unit_client(**overrides) + ZammadAPI::Client.new(**unit_config(**overrides)) + end + + def unit_transport(**overrides) + ZammadAPI::Transport.new(ZammadAPI::Config.new(**unit_config(**overrides))) + end + + # @return [Hash] arguments for WebMock's +to_return+ with a JSON body + def json_response(body, status: 200, headers: {}) + { + status: status, + body: JSON.generate(body), + headers: { 'Content-Type' => 'application/json' }.merge(headers) + } + end +end diff --git a/spec/support/integration_helper.rb b/spec/support/integration_helper.rb new file mode 100644 index 0000000..f753d39 --- /dev/null +++ b/spec/support/integration_helper.rb @@ -0,0 +1,147 @@ +# frozen_string_literal: true + +require 'securerandom' +require_relative '../../script/live_target' + +# Helpers for integration specs, which need a reachable Zammad instance. +class Helper + class SetupError < StandardError; end + + # The Zammad the integration specs run against, where one was named. + # + # There is no default. These specs run the auto wizard and then create, + # change and delete groups, organizations, users, tickets, states and + # priorities, and `http://localhost:3000/` used to stand in for a TEST_URL + # that was not set. That is where a Zammad under development listens, and + # a bare `rspec` runs these files along with the unit specs, so the + # commonest way to run the suite wrote test records into whatever was + # there. Where to write is for whoever runs them to say. + # + # Asked of {LiveTarget}, which rake and script/check_connection.rb ask + # as well, so that the three agree on whether a target was named. + # + # @return [String, nil] nil when TEST_URL is not set + def self.target = LiveTarget.url + + # Where no TEST_URL is set, a URL nothing answers at stands in for it. The + # spec files build their client while they are loaded, which is before + # RSpec has left their examples out, so this cannot raise; the examples + # never run, and {.ensure_configured!} refuses them if they are made to. + # `.invalid` is reserved for names that never resolve. + UNSET_URL = 'http://test-url-not-set.invalid/' + + def self.config + { + url: target || UNSET_URL, + user: ENV['TEST_USER'] || 'admin@example.com', + password: ENV['TEST_PASSWORD'] || 'test' + } + end + + def self.client(**overrides) + settings = config + ZammadAPI::Client.new( + url: overrides.fetch(:url, settings[:url]), + user: overrides.fetch(:user, settings[:user]), + password: overrides.fetch(:password, settings[:password]), + **overrides.except(:url, :user, :password) + ) + end + + # Makes sure the instance has an admin account, running Zammad's auto wizard + # once per suite. + # + # Memoized and idempotent, so it does not matter which spec file happens to + # run first, and re-running the suite against an already configured instance + # is not an error. + # The failure is memoized alongside the success, because `||=` memoizes + # neither. A TEST_URL with nothing behind it re-ran the whole probe - two + # requests, each with a ten second open timeout - once per example, so a + # Zammad that never came up took the suite a very long time to say so. + def self.ensure_configured! + raise SetupError, 'TEST_URL is not set, so there is no Zammad to run the integration specs against' if target.nil? + return true if @ensure_configured + raise @setup_failure if @setup_failure + + begin + auto_wizard? || verify_setup_done! + @ensure_configured = true + rescue SetupError => e + @setup_failure = e + raise + end + end + + # The body is asked about only where it is a JSON object. Valid JSON + # that is not one - `null`, a list, a number - raised NoMethodError on + # the lookup, which is neither the SetupError {.ensure_configured!} + # memoizes nor an answer, so every example ran the probe again. Anything + # but an object saying the wizard ran leaves {.verify_setup_done!} to + # decide. + # + # @return [Boolean] whether the auto wizard ran now + # @raise [SetupError] when the instance cannot be reached at all + def self.auto_wizard? + response = connection.get('api/v1/getting_started/auto_wizard') + body = parse(response.body) + body.is_a?(Hash) && body['auto_wizard_success'] == true + rescue Faraday::Error => e + # {.verify_setup_done!} wraps its failure into a SetupError naming the URL + # and the user; this probe runs one line earlier and did not, so the + # commonest failure of all - CI booting against a Zammad that never came + # up - reached every example as a bare Faraday exception from a helper + # that exists to explain exactly that. + raise SetupError, + "Zammad at #{config[:url]} could not be reached: the setup check failed to connect " \ + "(#{e.class}: #{e.message}). Set TEST_URL to a running instance." + end + + # A configured Zammad requires authentication even for + # /api/v1/getting_started, so the setup state cannot be read from there. + # Proving that the configured credentials work answers the only question + # that matters here. + def self.verify_setup_done! + ZammadAPI::Client.new(**config).groups.all.page(1, per_page: 1).to_a + true + rescue ZammadAPI::Error => e + raise SetupError, + "Zammad at #{config[:url]} is not usable: the auto wizard did not run and " \ + "authenticating as #{config[:user]} failed (#{e.class}: #{e.message})" + end + + # Finite timeouts matter here: a TEST_URL that accepts the connection but + # never answers would otherwise hang the integration job until the CI + # timeout rather than failing the setup check. + def self.connection + Faraday.new(url: config[:url], request: { open_timeout: 10, timeout: 30 }) + end + + def self.parse(body) + JSON.parse(body) + rescue JSON::ParserError + {} + end + + def self.random + SecureRandom.random_number(99_999_999).to_s + end + + private_class_method :verify_setup_done!, :connection, :parse +end + +# Each integration spec file walks one record through its lifecycle - new, +# save, find, destroy - and every step asserts on what the previous one left +# behind, so the record is shared across ordered examples. +# +# That coupling is fine as long as the whole file runs in definition order, +# and silent nonsense as soon as it does not: `--only-failures`, `-e 'save'` +# or a `--seed` reordering used to fail as `NoMethodError: undefined method +# 'save' for nil`, which says nothing about the actual cause. This says it. +module LifecycleState + def established!(record, example) + return record if record + + raise "this example continues the record built by '#{example}', which did not run in this process. " \ + 'These examples share one record and have to run as a whole file, in definition order.' + end +end diff --git a/spec/unit/zammad_api/associations/proxy_spec.rb b/spec/unit/zammad_api/associations/proxy_spec.rb new file mode 100644 index 0000000..a34ee78 --- /dev/null +++ b/spec/unit/zammad_api/associations/proxy_spec.rb @@ -0,0 +1,433 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Associations::Proxy do + subject(:ticket) { client.tickets.find(42) } + + let(:client) { unit_client } + let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/42" } + let(:users_url) { "#{ClientHelper::BASE_URL}api/v1/users" } + + let(:ticket_attributes) do + { + id: 42, + title: 'Help', + customer: 'customer@example.com', + customer_id: 7, + state: 'open', + state_id: 2, + group: 'Users', + group_id: 1 + } + end + + before do + stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response(ticket_attributes)) + end + + describe 'belongs_to' do + it 'fetches the whole record behind a foreign key' do + stub_request(:get, "#{users_url}/7").with(query: { 'expand' => 'true' }) + .to_return(json_response({ id: 7, email: 'customer@example.com', firstname: 'Nicole' })) + + expect(ticket.related.customer.firstname).to eq('Nicole') + end + + it 'returns the resource class of the target' do + stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) + + expect(ticket.related.customer).to be_a(ZammadAPI::Resources::User) + end + + it 'returns a persisted record' do + stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) + + expect(ticket.related.customer).to be_persisted + end + + it 'leaves the expanded attribute alone, so reading a name stays free' do + expect(ticket.customer).to eq('customer@example.com') + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).not_to have_been_made + end + + it 'does not shadow an expanded attribute that names a state' do + expect(ticket.state).to eq('open') + end + + it 'is nil when the foreign key is not set' do + stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 42 })) + + expect(ticket.related.customer).to be_nil + end + + it 'makes no request when the foreign key is not set' do + stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 42 })) + + ticket.related.customer + expect(a_request(:get, %r{api/v1/users}).with(query: hash_including({}))).not_to have_been_made + end + + it 'memoizes, so a loop does not refetch the same record' do + stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) + + held = ticket + 3.times { held.related.customer } + + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.once + end + + it 'uses the declared foreign key rather than the association name' do + stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/ticket_states/2") + .with(query: hash_including({})) + .to_return(json_response({ id: 2, name: 'open' })) + + ticket.related.state + expect(stub).to have_been_requested + end + + it 'reaches the group resource' do + stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/groups/1") + .with(query: hash_including({})) + .to_return(json_response({ id: 1, name: 'Users' })) + + expect(ticket.related.group.name).to eq('Users') + expect(stub).to have_been_requested + end + + it 'propagates a failure to load the target' do + stub_request(:get, "#{users_url}/7").with(query: hash_including({})) + .to_return(json_response({ error: 'not found' }, status: 404)) + + expect { ticket.related.customer }.to raise_error(ZammadAPI::NotFoundError) + end + end + + describe 'has_many' do + let(:articles_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_articles/by_ticket/42" } + + it 'fetches the list from the association endpoint' do + stub_request(:get, articles_url).with(query: { 'expand' => 'true' }) + .to_return(json_response([{ id: 1, body: 'first' }])) + + expect(ticket.related.articles.map(&:body)).to eq(['first']) + end + + it 'returns records of the target class' do + stub_request(:get, articles_url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + + expect(ticket.related.articles.first).to be_a(ZammadAPI::Resources::TicketArticle) + end + + it 'is not memoized, so an article added afterwards shows up' do + stub_request(:get, articles_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1 }]), json_response([{ id: 1 }, { id: 2 }])) + + held = ticket + expect(held.related.articles.size).to eq(1) + expect(held.related.articles.size).to eq(2) + end + + it 'names the association in a parse failure' do + stub_request(:get, articles_url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect { ticket.related.articles } + .to raise_error(ZammadAPI::ParseError, /Can't get articles \(ZammadAPI::Resources::TicketArticle\)/) + end + + # The one list in the gem read in a single request, because the endpoint + # it is declared against serves the whole thing: index_by_ticket iterates + # `ticket.articles` and renders them all, with no pagination to opt into. + # A guard used to sit here for a target that paged anyway, reading a total + # from a response header - a header Zammad sends from no endpoint, so it + # never once looked at a figure. + it 'reads the whole list in one request' do + stub_request(:get, articles_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1 }, { id: 2 }])) + + expect(ticket.related.articles.size).to eq(2) + end + + it 'says to save an unsaved record rather than requesting a path without an id' do + unsaved = ZammadAPI::Resources::Ticket.new(unit_transport, title: 'Help') + + expect { unsaved.related.articles } + .to raise_error(ZammadAPI::Error, /has no id, so it has no articles to read; save it first/) + end + + it 'escapes a traversal in the id instead of reaching another endpoint' do + escaped = "#{ClientHelper::BASE_URL}api/v1/ticket_articles/by_ticket/1%2F..%2F..%2Fusers" + stub = stub_request(:get, escaped).with(query: hash_including({})).to_return(json_response([])) + escaping = ZammadAPI::Resources::Ticket.from_response(unit_transport, id: '1/../../users') + + escaping.related.articles + + expect(stub).to have_been_requested + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/users").with(query: hash_including({}))) + .not_to have_been_made + end + end + + describe 'inheritance' do + it 'gives every resource the stamps Zammad puts on every object' do + expect(ZammadAPI::Resources::Group.associations.keys).to eq(%i[created_by updated_by]) + end + + it 'adds a resource its own associations on top' do + expect(ZammadAPI::Resources::User.associations.keys).to include(:created_by, :organization) + end + + it 'does not leak one resource\'s associations into another' do + expect(ZammadAPI::Resources::Group.associations).not_to have_key(:customer) + end + + it 'does not define another resource\'s reader on the proxy' do + group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) + expect(group.related).not_to respond_to(:customer) + end + + it 'raises NoMethodError for an association that was never declared' do + expect { ticket.related.unicorn }.to raise_error(NoMethodError) + end + end + + describe 'the memo' do + before do + stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) + end + + it 'is dropped by reload, because the foreign key may have moved' do + held = ticket + held.related.customer + held.reload + held.related.customer + + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice + end + + it 'is dropped by a save' do + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(json_response(ticket_attributes)) + + held = ticket + held.related.customer + held.update!(title: 'Renamed') + held.related.customer + + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice + end + + it 'is dropped when the foreign key it resolved from is written' do + stub_request(:get, "#{users_url}/9").with(query: hash_including({})) + .to_return(json_response({ id: 9, email: 'nine@example.com' })) + + held = ticket + expect(held.related.customer.id).to eq(7) + + held.customer_id = 9 + + expect(held.related.customer.id).to eq(9) + end + + it 'survives a write to an attribute no association resolves through' do + held = ticket + held.related.customer + held.title = 'Renamed' + held.related.customer + + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.once + end + + it 'is dropped by assign_attributes touching a foreign key' do + stub_request(:get, "#{users_url}/9").with(query: hash_including({})) + .to_return(json_response({ id: 9 })) + + held = ticket + held.related.customer + held.assign_attributes(title: 'Renamed', customer_id: 9) + + expect(held.related.customer.id).to eq(9) + end + end + + # `related = ticket.related` is the natural thing to write before reading + # two associations. The record used to drop its proxy and build another, so + # everything under 'the memo' above held for a caller who asked the record + # again and for nobody who had kept what they were handed. + describe 'a proxy the caller kept' do + let(:related) { ticket.related } + + before do + stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) + stub_request(:get, "#{users_url}/9").with(query: hash_including({})).to_return(json_response({ id: 9 })) + end + + it 'is the one the record goes on handing out' do + related.customer + ticket.customer_id = 9 + + expect(ticket.related).to be(related) + end + + it 'follows a foreign key that was written' do + expect(related.customer.id).to eq(7) + + ticket.customer_id = 9 + + expect(related.customer.id).to eq(9) + end + + it 'follows a foreign key that assign_attributes wrote' do + related.customer + ticket.assign_attributes(title: 'Renamed', customer_id: 9) + + expect(related.customer.id).to eq(9) + end + + it 'follows a foreign key that a reload moved' do + related.customer + stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response(ticket_attributes.merge(customer_id: 9))) + ticket.reload + + expect(related.customer.id).to eq(9) + end + + it 'fetches the target again after a reload that left the foreign key alone' do + related.customer + ticket.reload + related.customer + + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice + end + + it 'fetches the target again after a save' do + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(json_response(ticket_attributes)) + + related.customer + ticket.update!(title: 'Renamed') + related.customer + + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice + end + + it 'keeps its memo across a write no association resolves through' do + related.customer + ticket.title = 'Renamed' + related.customer + + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.once + end + + context 'when the record was destroyed' do + before do + stub_request(:delete, ticket_url).to_return(json_response({})) + related.customer + ticket.destroy + end + + it 'refuses a target it had already resolved' do + expect { related.customer } + .to raise_error(ZammadAPI::Error, 'ZammadAPI::Resources::Ticket 42 was destroyed, there is nothing to read customer from') + end + + it 'refuses a list, rather than requesting it for a record that is gone' do + expect { related.articles }.to raise_error(ZammadAPI::Error, /was destroyed/) + expect(a_request(:get, %r{ticket_articles/by_ticket})).not_to have_been_made + end + end + + # The write clears the memo, and the lookup that was already out then + # filled it again, with the record behind the value from before. A logger + # or a middleware of the caller's that reaches the record is enough, on + # one thread; so is a second thread. + context 'when the foreign key is written while a lookup is on the wire' do + before do + stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return do + ticket.customer_id = 9 + json_response({ id: 7 }) + end + end + + it 'answers that lookup with the record it asked for' do + expect(related.customer.id).to eq(7) + end + + it 'does not keep that answer for the record the key now names' do + related.customer + + expect(related.customer.id).to eq(9) + end + + it 'memoizes the lookup made after it' do + 3.times { related.customer } + + expect(a_request(:get, "#{users_url}/9").with(query: hash_including({}))).to have_been_made.once + end + end + + it 'leaves the proxy of a copy to the copy' do + related.customer + copy = ticket.dup + copy.customer_id = 9 + + expect(related.customer.id).to eq(7) + expect(copy.related.customer.id).to eq(9) + end + end + + describe '.belongs_to_foreign_keys' do + it 'lists the keys a resource resolves associations through' do + expect(ZammadAPI::Resources::Ticket.belongs_to_foreign_keys) + .to include(:customer_id, :owner_id, :group_id, :state_id, :priority_id, :organization_id) + end + + it 'includes the ones inherited from Base' do + expect(ZammadAPI::Resources::Group.belongs_to_foreign_keys).to eq(%i[created_by_id updated_by_id]) + end + end + + describe '#inspect' do + it 'names the record and what can be reached from it' do + expect(ticket.related.inspect) + .to eq( + '#' + ) + end + end + + # A resource a caller declares can point at another of theirs, which is in + # no namespace of this gem. + describe 'an association declared on a resource a caller wrote' do + before do + stub_const('Acme::Role', Class.new(ZammadAPI::Resources::Base) { path 'api/v1/roles' }) + stub_const('Acme::Membership', Class.new(ZammadAPI::Resources::Base) do + path 'api/v1/memberships' + belongs_to :role, class_name: 'Acme::Role' + belongs_to :user, class_name: 'User' + end) + end + + let(:membership) { Acme::Membership.from_response(unit_transport, id: 1, role_id: 2, user_id: 3) } + + it 'resolves a target named by its full name' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/roles/2").with(query: hash_including({})) + .to_return(json_response({ id: 2, name: 'Agent' })) + + expect(membership.related.role).to be_a(Acme::Role) + end + + it 'still resolves a resource of this gem by its own name' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/3").with(query: hash_including({})) + .to_return(json_response({ id: 3, login: 'agent' })) + + expect(membership.related.user).to be_a(ZammadAPI::Resources::User) + end + + # An application is likely to have a User of its own at the top level. + it 'prefers the resource of this gem over a top-level constant of the same name' do + stub_const('User', Class.new) + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/3").with(query: hash_including({})) + .to_return(json_response({ id: 3, login: 'agent' })) + + expect(membership.related.user).to be_a(ZammadAPI::Resources::User) + end + end +end diff --git a/spec/unit/zammad_api/attribute_access_spec.rb b/spec/unit/zammad_api/attribute_access_spec.rb new file mode 100644 index 0000000..a0397ed --- /dev/null +++ b/spec/unit/zammad_api/attribute_access_spec.rb @@ -0,0 +1,394 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::AttributeAccess do + subject(:record) { record_class.new(attributes) } + + let(:record_class) do + Class.new do + include ZammadAPI::AttributeAccess + + def initialize(attributes) + @attributes = frozen_attributes(attributes) + end + end + end + + let(:attributes) do + { + 'id' => 1, + 'name' => 'Support', + 'preferences' => { 'notes' => [{ 'body' => 'hello' }] } + } + end + + describe 'key normalization' do + it 'symbolizes top level keys' do + expect(record.attributes.keys).to eq(%i[id name preferences]) + end + + it 'symbolizes nested hash keys' do + expect(record.attributes[:preferences].keys).to eq([:notes]) + end + + it 'symbolizes hash keys inside arrays' do + expect(record.attributes[:preferences][:notes].first).to eq({ body: 'hello' }) + end + + it 'leaves keys alone that cannot become symbols' do + expect(record_class.new(1 => 'one').attributes).to eq(1 => 'one') + end + end + + describe 'reading' do + it 'reads through a reader method' do + expect(record.name).to eq('Support') + end + + it 'reads through #[]' do + expect(record[:name]).to eq('Support') + end + + it 'accepts a string key in #[]' do + expect(record['name']).to eq('Support') + end + + it 'exposes the id' do + expect(record.id).to eq(1) + end + + # A reader used to answer nil here, which made a typo a silent nil that + # flowed on into whatever was written with it - and put respond_to? and + # the call itself at odds, since respond_to?(:custom_field) was false + # throughout. + it 'raises for an attribute the record does not carry' do + expect { record.custom_field }.to raise_error(NoMethodError, /undefined attribute custom_field/) + end + + it 'names the readers that tolerate an absent attribute' do + expect { record.custom_field }.to raise_error(NoMethodError, /fetch\(:custom_field, nil\)/) + end + + it 'says the record may be one Zammad served less of' do + expect { record.custom_field }.to raise_error(NoMethodError, /reduced object/) + end + + it 'lists what the record does carry, so the spelling can be compared' do + expect { record.custom_field }.to raise_error(NoMethodError, /carries id, name, preferences/) + end + + # A key that could not become a Symbol is left as it arrived, so sorting + # the keys themselves would raise from inside the message. + it 'lists mixed keys without raising from the message itself' do + expect { record_class.new(1 => 'one', 'name' => 'X').custom_field } + .to raise_error(NoMethodError, /carries 1, name/) + end + + it 'says so plainly for a record that carries nothing' do + expect { record_class.new({}).custom_field } + .to raise_error(NoMethodError, /carries no attributes at all/) + end + + it 'carries the name and the receiver a bare NoMethodError would' do + expect { record.custom_field }.to raise_error(NoMethodError) do |error| + expect(error.name).to eq(:custom_field) + expect(error.receiver).to be(record) + end + end + + it 'still reads an attribute the record carries but Zammad left nil' do + expect(record_class.new('note' => nil).note).to be_nil + end + + it 'leaves [] and fetch answering for an absent attribute' do + expect(record[:custom_field]).to be_nil + expect(record.fetch(:custom_field, 'fallback')).to eq('fallback') + end + + it 'reports known attributes via #key?' do + expect(record.key?(:name)).to be(true) + end + + it 'returns a copy from #to_h' do + record.to_h[:name] = 'changed' + expect(record.name).to eq('Support') + end + end + + describe 'immutability' do + it 'freezes the attribute hash' do + expect { record.attributes[:name] = 'changed' }.to raise_error(FrozenError) + end + + it 'freezes a nested hash' do + expect { record.attributes[:preferences][:notes] = [] }.to raise_error(FrozenError) + end + + it 'freezes a nested array' do + expect { record.attributes[:preferences][:notes] << {} }.to raise_error(FrozenError) + end + + it 'freezes a hash inside an array' do + expect { record.attributes[:preferences][:notes].first[:body] = 'changed' }.to raise_error(FrozenError) + end + + it 'freezes a string value' do + expect { record.name << '!' }.to raise_error(FrozenError) + end + + it 'hands out a deep copy from #to_h' do + copy = record.to_h + copy[:preferences][:notes].first[:body] = 'changed' + + expect(record.attributes[:preferences][:notes].first[:body]).to eq('hello') + end + + it 'hands out mutable strings from #to_h' do + copy = record.to_h + copy[:name] << '!' + + expect(record.name).to eq('Support') + end + end + + describe '#fetch' do + it 'returns the value for a known attribute' do + expect(record.fetch(:name)).to eq('Support') + end + + it 'raises for an unknown attribute' do + expect { record.fetch(:nope) }.to raise_error(KeyError) + end + + it 'supports a default' do + expect(record.fetch(:nope, 'fallback')).to eq('fallback') + end + + # Hash#fetch refuses a third argument, and so does this: collected with a + # splat and read as `default.first`, `fetch(:a, :b, :c)` - a multi-key read + # this has never been - was answered with `:b`. + it 'refuses more than one fallback, the way Hash#fetch does' do + expect { record.fetch(:nope, 'one', 'two') } + .to raise_error(ArgumentError, 'wrong number of arguments (given 3, expected 1..2)') + end + + # Hash#fetch warns and then ignores the default. Silently picking one of + # two fallbacks a caller cannot have meant to pass together is the same + # swallowed mistyped call the arity check above refuses. + # rubocop:disable Lint/UselessDefaultValueArgument -- the call under test + it 'says so when a block supersedes the default, the way Hash#fetch does' do + expect { record.fetch(:nope, 'fallback') { 'block' } } + .to output(/block supersedes default value argument/).to_stderr + end + + it 'still answers from the block when both were given' do + expect { expect(record.fetch(:nope, 'fallback') { 'block' }).to eq('block') }.to output.to_stderr + end + + # Hash#fetch names the line that made the call. A bare Kernel#warn named + # nothing at all - neither the call site nor the library it came from, + # which in an application with several such calls is everything the reader + # needs. `uplevel` supplies both that location and the `warning: ` prefix. + it 'names the line that made the call, the way Hash#fetch does' do + expect { record.fetch(:nope, 'fallback') { 'block' } } + .to output(/attribute_access_spec\.rb:\d+: warning: block supersedes/).to_stderr + end + # rubocop:enable Lint/UselessDefaultValueArgument + end + + # `record[:x] = v` reached method_missing as `:[]=`, which the writer branch + # took for an attribute called `[]` - it staged the index as the value, lost + # the write, and sent `{"[]": "x"}` on the next save. Ruby's operators end in + # `=` too, so `record <= 5` did the same for an attribute called `<`. + describe '#[]=' do + it 'goes through the same refusal a named writer does on a read-only record' do + expect { record[:note] = 'x' }.to raise_error(NoMethodError, /attributes are read-only/) + end + + it 'names the attribute that was tried, not the operator' do + expect { record[:note] = 'x' }.to raise_error(NoMethodError, /tried to set note/) + end + + # `[]=` is a defined method, so respond_to_missing? never sees it: a + # read-only record claimed the one writer it has while denying every named + # one, then raised when it was called - the invariant the writer branch of + # respond_to_missing? is conditional for. + it 'is not claimed by a record that would refuse it' do + expect(record).not_to respond_to(:[]=) + end + + it 'agrees with the named writers on the same record' do + expect(record.respond_to?(:[]=)).to eq(record.respond_to?(:name=)) + end + + # `respond_to?` takes either spelling and Ruby does not normalise the + # argument, so a Symbol-only comparison let the String fall through to the + # definition and answer true on a record that refuses every write. + it 'answers the same for the String spelling' do + # rubocop:disable-next Performance/StringIdentifierArgument -- the String spelling is the point + expect(record.respond_to?('[]=')).to eq(record.respond_to?(:[]=)) + end + end + + describe 'a name that only looks like a writer' do + it 'does not invent an attribute from a comparison operator' do + # Sent rather than written as `record <= 5`, which RuboCop reads as a + # void literal and rewrites away, taking the spec with it. + expect { record.public_send(:<=, 5) }.to raise_error(NoMethodError) + + expect(record.attributes.keys).not_to include(:<) + end + + it 'is not claimed as a writer' do + expect(record).not_to respond_to(:<=) + end + end + + describe '#respond_to?' do + it 'is true for a known attribute' do + expect(record).to respond_to(:name) + end + + it 'is false for an unknown attribute' do + expect(record).not_to respond_to(:nope) + end + + it 'is false for a writer on a read-only record, which would raise' do + expect(record).not_to respond_to(:anything=) + end + + it 'is true for any writer on a record that stages changes' do + expect(ZammadAPI::Resources::Group.new(unit_transport)).to respond_to(:anything=) + end + + it 'is false for a predicate' do + expect(record).not_to respond_to(:name?) + end + end + + describe 'method names that are not attributes' do + it 'raises NoMethodError for a bang method, so typos surface' do + expect { record.save! }.to raise_error(NoMethodError) + end + + it 'raises NoMethodError for a predicate' do + expect { record.active? }.to raise_error(NoMethodError) + end + end + + describe 'pattern matching' do + it 'matches on attribute values' do + result = case record + in { name: 'Support' } then :matched + else :not_matched + end + expect(result).to eq(:matched) + end + + it 'binds matched values' do + case record + in { name: String => name } + expect(name).to eq('Support') + end + end + + it 'matches nested structures' do + case record + in { preferences: { notes: [{ body: String => body }, *] } } + expect(body).to eq('hello') + end + end + + it 'does not match an absent attribute' do + result = case record + in { nope: _ } then :matched + else :not_matched + end + expect(result).to eq(:not_matched) + end + + it 'returns every attribute for a nil key list' do + expect(record.deconstruct_keys(nil)).to eq(record.attributes) + end + + it 'returns only the requested keys' do + expect(record.deconstruct_keys([:name])).to eq(name: 'Support') + end + end + + describe 'equality' do + it 'is the same record as another of its class carrying the same id' do + expect(record).to eq(record_class.new('id' => 1, 'name' => 'Renamed since')) + end + + it 'is not the same record as one with a different id' do + expect(record).not_to eq(record_class.new('id' => 2, 'name' => 'Support')) + end + + it 'is not the same record as one of another class with the same id' do + expect(record).not_to eq(Class.new(record_class).new('id' => 1)) + end + + it 'is not equal to something that is not a record' do + expect(record).not_to eq('id' => 1) + end + + it 'answers #eql? too, so a record can be a Hash key' do + expect({ record => :found }[record_class.new('id' => 1)]).to eq(:found) + end + + it 'hashes equal records alike' do + expect(record.hash).to eq(record_class.new('id' => 1).hash) + end + + it 'deduplicates equal records' do + expect([record, record_class.new('id' => 1)].uniq.size).to eq(1) + end + + it 'collects equal records into one Set member' do + expect(Set[record, record_class.new('id' => 1)].size).to eq(1) + end + + context 'without an id' do + subject(:unsaved) { record_class.new('name' => 'Support') } + + it 'is still itself, so it can be found again as a Hash key' do + expect({ unsaved => :found }[unsaved]).to eq(:found) + end + + it 'is not equal to an identical record, which is still a second record' do + expect(unsaved).not_to eq(record_class.new('name' => 'Support')) + end + + it 'is kept apart from an identical record' do + expect([unsaved, record_class.new('name' => 'Support')].uniq.size).to eq(2) + end + end + end + + describe 'serialization' do + it 'renders the attributes as a JSON object' do + expect(JSON.parse(record.to_json)) + .to eq('id' => 1, 'name' => 'Support', 'preferences' => { 'notes' => [{ 'body' => 'hello' }] }) + end + + it 'renders as its attributes when nested in a structure being generated' do + expect(JSON.parse(JSON.generate(group: record))['group']).to include('name' => 'Support') + end + + it 'carries the generator state, so pretty printing reaches the attributes' do + expect(JSON.pretty_generate(record)).to include("\n") + end + + it 'exposes the attributes to an encoder through #as_json' do + expect(record.as_json).to eq(record.to_h) + end + + it 'hands #as_json a copy rather than the frozen attributes' do + expect(record.as_json).not_to be_frozen + end + end + + it 'rejects writes by default' do + expect { record.name = 'other' }.to raise_error(NoMethodError, /read-only/) + end +end diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb new file mode 100644 index 0000000..60b158c --- /dev/null +++ b/spec/unit/zammad_api/client_spec.rb @@ -0,0 +1,1141 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Client do + let(:url) { "#{ClientHelper::BASE_URL}api/v1/users/1" } + + describe '.new' do + it 'refuses more than one way to authenticate' do + expect { described_class.new(url: 'http://zammad.test/', http_token: 't', user: 'u', password: 'p') } + .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate/) + end + + it 'accepts keyword arguments' do + expect(described_class.new(url: 'http://zammad.test/', http_token: 'token')).to be_a(described_class) + end + + it 'surfaces configuration errors' do + expect { described_class.new(http_token: 'token') }.to raise_error(ArgumentError) + end + + it 'rejects a missing url' do + expect { described_class.new(url: nil, http_token: 'token') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') + end + + it 'rejects an unsupported scheme' do + expect { described_class.new(url: 'ftp://example.com', http_token: 'token') } + .to raise_error(ZammadAPI::ConfigurationError, /needs to start with http/) + end + + it 'rejects missing credentials' do + expect { described_class.new(url: 'http://zammad.test/') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + end + + it 'rejects an unknown option' do + expect { described_class.new(url: 'http://zammad.test/', http_token: 't', nonsense: 1) } + .to raise_error(ArgumentError) + end + + it 'exposes the configuration' do + expect(unit_client.config).to be_a(ZammadAPI::Config) + end + end + + describe '.from_env' do + it 'reads the url and access token' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' }) + + config = described_class.from_env.config + expect(config.url).to eq('http://zammad.test/') + expect(config.http_token).to eq('from-env') + end + + it 'reads basic auth credentials' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'p' }) + + expect(described_class.from_env.config.authentication_scheme).to eq(:basic) + end + + it 'reads an OAuth2 token' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_OAUTH2_TOKEN' => 'oauth' }) + + expect(described_class.from_env.config.oauth2_token).to eq('oauth') + end + + it 'prefers ZAMMAD_HTTP_TOKEN over ZAMMAD_TOKEN' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'short', 'ZAMMAD_HTTP_TOKEN' => 'explicit' }) + + expect(described_class.from_env.config.http_token).to eq('explicit') + end + + it 'lets an argument win over the environment' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' }) + + expect(described_class.from_env(http_token: 'passed in').config.http_token).to eq('passed in') + end + + # A credential is read in a fixed order, so a plain merge left the + # environment's token in charge of a client that was handed another way to + # authenticate - and nothing said so. + context 'when an argument names another way to authenticate' do + before do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' }) + end + + it 'uses a user and password passed in, not the token in the environment' do + expect(described_class.from_env(user: 'u', password: 'p').config.authentication_scheme).to eq(:basic) + end + + it 'drops the token the environment held' do + expect(described_class.from_env(user: 'u', password: 'p').config.http_token).to be_nil + end + + it 'uses an OAuth2 token passed in, not the token in the environment' do + expect(described_class.from_env(oauth2_token: 'x').config.authentication_scheme).to eq(:oauth2_token) + end + + it 'sends what was passed in' do + stub = stub_request(:get, 'http://zammad.test/api/v1/users/1') + .with(query: hash_including({}), basic_auth: %w[u p]) + .to_return(json_response({ id: 1 })) + + described_class.from_env(user: 'u', password: 'p', retries: 0).users.find(1) + expect(stub).to have_been_requested + end + end + + # Two ways to authenticate in the environment, and nothing passed in to + # say which is meant. + it 'refuses an environment that sets more than one way to authenticate' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 't', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'p' }) + + expect { described_class.from_env } + .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate \(http_token, user and password\)/) + end + + it 'lets an argument say which of them is meant' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 't', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'p' }) + + expect(described_class.from_env(http_token: 't').config.authentication_scheme).to eq(:http_token) + end + + it 'keeps the user from the environment when only the password is passed in' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'old' }) + + config = described_class.from_env(password: 'new').config + expect([config.user, config.password]).to eq(%w[u new]) + end + + it 'accepts options that have no environment variable' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 't' }) + + expect(described_class.from_env(timeout: 300).config.timeout).to eq(300) + end + + it 'treats an empty variable as unset' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => '', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'p' }) + + expect(described_class.from_env.config.authentication_scheme).to eq(:basic) + end + + it 'names the variable to set when the url is missing' do + stub_const('ENV', { 'ZAMMAD_TOKEN' => 't' }) + + expect { described_class.from_env } + .to raise_error(ZammadAPI::ConfigurationError, /set ZAMMAD_URL or pass url:/) + end + + it 'still validates the credentials' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/' }) + + expect { described_class.from_env }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + end + end + + describe '#me' do + it 'reads the current user' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/me") + .with(query: { 'expand' => 'true' }) + .to_return(json_response({ id: 3, email: 'agent@example.com' })) + + expect(unit_client.me.email).to eq('agent@example.com') + end + + it 'returns a persisted user record' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/me").with(query: hash_including({})) + .to_return(json_response({ id: 3 })) + + me = unit_client.me + expect(me).to be_a(ZammadAPI::Resources::User) + expect(me).to be_persisted + end + + it 'follows an on_behalf_of scope' do + stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/me") + .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }) + .to_return(json_response({ id: 3 })) + + unit_client.on_behalf_of('agent@example.com').me + expect(stub).to have_been_requested + end + + it 'raises AuthenticationError for invalid credentials' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/me").with(query: hash_including({})) + .to_return(json_response({ error: 'authentication failed' }, status: 401)) + + expect { unit_client.me }.to raise_error(ZammadAPI::AuthenticationError) + end + end + + describe '#version' do + it 'reports the version of the Zammad instance' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/version").to_return(json_response({ version: '6.4.0' })) + + expect(unit_client.version).to eq('6.4.0') + end + + it 'is nil when the instance reports no version' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/version").to_return(json_response({})) + + expect(unit_client.version).to be_nil + end + + it 'is not the version of this gem' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/version").to_return(json_response({ version: '6.4.0' })) + + expect(unit_client.version).not_to eq(ZammadAPI::VERSION) + end + end + + describe 'resource readers' do + ZammadAPI::Client::RESOURCES.each do |name, resource_class| + it "exposes ##{name}" do + expect(unit_client.public_send(name).resource_class).to eq(resource_class) + end + + it "responds to ##{name}" do + expect(unit_client).to respond_to(name) + end + end + + it 'returns a proxy' do + expect(unit_client.groups).to be_a(ZammadAPI::ResourceProxy) + end + + it 'lists the supported resource names' do + expect(unit_client.resource_names).to eq(ZammadAPI::Client::RESOURCES.keys) + end + end + + # A proxy is Enumerable over every record of its kind, so the readers are + # plural. The singular names are what they were called in 1.x, when a proxy + # was only a dispatcher for find and create. + describe 'the singular names the readers had in 1.x' do + around do |example| + enabled = Warning[:deprecated] + Warning[:deprecated] = true + example.run + ensure + Warning[:deprecated] = enabled + end + + ZammadAPI::Client::DEPRECATED_RESOURCES.each do |old_name, name| + it "still answers ##{old_name} with what ##{name} answers" do + client = unit_client + proxy = nil + + expect { proxy = client.public_send(old_name) }.to output.to_stderr + expect(proxy).to be(client.public_send(name)) + end + end + + it 'covers every reader' do + expect(ZammadAPI::Client::DEPRECATED_RESOURCES.values).to eq(ZammadAPI::Client::RESOURCES.keys) + end + + it 'warns, naming the replacement' do + expect { unit_client.ticket } + .to output(/ZammadAPI::Client#ticket is deprecated and will be removed in 3\.0: use #tickets instead/).to_stderr + end + + it 'names the line that made the call, not one inside the gem' do + expect { unit_client.ticket }.to output(/#{Regexp.escape(__FILE__)}:#{__LINE__}: warning: /).to_stderr + end + + it 'does not warn for the plural name' do + expect { unit_client.tickets }.not_to output.to_stderr + end + + # Ruby's own category for this, so an application decides whether to hear + # it: a script that has not been migrated does not print a line per call. + it 'says nothing unless deprecation warnings are on' do + Warning[:deprecated] = false + expect { unit_client.ticket }.not_to output.to_stderr + end + + it 'is not listed among the resource names' do + expect(unit_client.resource_names).not_to include(:ticket) + end + end + + describe '#resource' do + it 'accepts a symbol' do + expect(unit_client.resource(:groups).resource_class).to eq(ZammadAPI::Resources::Group) + end + + it 'accepts a string' do + expect(unit_client.resource('groups').resource_class).to eq(ZammadAPI::Resources::Group) + end + + it 'answers with the proxy the reader answers with' do + client = unit_client + expect(client.resource(:ticket_priorities)).to be(client.ticket_priorities) + end + + it 'raises for an unknown resource' do + expect { unit_client.resource(:unicorn) } + .to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource unicorn/) + end + + it 'lists the available resources in the error' do + expect { unit_client.resource(:unicorn) }.to raise_error(/available resources are: groups, organizations/) + end + + # The way to the parts of the API this gem does not model: 1.x reached any + # subclass of Base through const_get, 2.0 closed that, and raw requests + # were all that was left. + context 'with a resource class a caller declared' do + let(:client) { unit_client } + let(:roles_url) { "#{ClientHelper::BASE_URL}api/v1/roles" } + + before do + stub_const('Role', Class.new(ZammadAPI::Resources::Base) { path 'api/v1/roles' }) + end + + it 'answers with a proxy for that class' do + expect(client.resource(Role).resource_class).to be(Role) + end + + it 'reads records of that class from the path it declares' do + stub_request(:get, roles_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Admin' }]), json_response([])) + + expect(client.resource(Role).map { [it.class, it.name] }).to eq([[Role, 'Admin']]) + end + + it 'finds one by id' do + stub_request(:get, "#{roles_url}/2").with(query: hash_including({})).to_return(json_response({ id: 2, name: 'Agent' })) + + expect(client.resource(Role).find(2).name).to eq('Agent') + end + + it 'saves a change to one, sending only what changed' do + stub_request(:get, "#{roles_url}/2").with(query: hash_including({})).to_return(json_response({ id: 2, name: 'Agent', note: nil })) + update = stub_request(:put, "#{roles_url}/2").with(query: hash_including({}), body: { note: 'Reviewed' }) + .to_return(json_response({ id: 2, name: 'Agent', note: 'Reviewed' })) + + client.resource(Role).find(2).update(note: 'Reviewed') + expect(update).to have_been_requested + end + + it 'creates one' do + create = stub_request(:post, roles_url).with(query: hash_including({}), body: { name: 'Auditor' }) + .to_return(json_response({ id: 9, name: 'Auditor' }, status: 201)) + + expect(client.resource(Role).create(name: 'Auditor').id).to eq(9) + expect(create).to have_been_requested + end + + it 'sends the scope of the client it was asked of' do + stub = stub_request(:get, "#{roles_url}/2") + .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }) + .to_return(json_response({ id: 2 })) + + client.on_behalf_of('agent@example.com').resource(Role).find(2) + expect(stub).to have_been_requested + end + + it 'answers a class this gem models with the proxy its reader answers with' do + expect(client.resource(ZammadAPI::Resources::Ticket)).to be(client.tickets) + end + + it 'takes a subclass of a class this gem models' do + stub_const('MyTicket', Class.new(ZammadAPI::Resources::Ticket)) + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/1").with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect(client.resource(MyTicket).find(1)).to be_a(MyTicket) + end + + it 'leaves the client as it was built' do + expect { client.resource(Role) }.not_to(change { client.instance_variable_get(:@resources).size }) + end + + it 'refuses a class that is not a resource' do + expect { client.resource(String) } + .to raise_error(ArgumentError, /resource takes the name of a resource or a subclass of ZammadAPI::Resources::Base, and String is neither/) + end + + # Reported by the call that named the class, not by its first request. + it 'refuses a resource class that declares no path' do + stub_const('Pathless', Class.new(ZammadAPI::Resources::Base)) + + expect { client.resource(Pathless) }.to raise_error(ZammadAPI::Error, /Pathless does not declare an API path/) + end + + it 'names the class in the hint a collection gives for a lookup by id' do + expect { client.resource(Role).all.find(1) }.to raise_error(ArgumentError, /client\.resource\(Role\)\.find\(1\)/) + end + end + + context 'with a name from 1.x' do + around do |example| + enabled = Warning[:deprecated] + Warning[:deprecated] = true + example.run + ensure + Warning[:deprecated] = enabled + end + + it 'still answers, with the proxy the plural answers with' do + client = unit_client + proxy = nil + + expect { proxy = client.resource(:ticket) }.to output.to_stderr + expect(proxy).to be(client.tickets) + end + + it 'warns, naming the line that made the call' do + expect { unit_client.resource('ticket') } + .to output(/#{Regexp.escape(__FILE__)}:#{__LINE__ - 1}: warning: ZammadAPI::Client#ticket is deprecated/).to_stderr + end + end + end + + describe 'unknown methods' do + it 'raises UnknownResourceError for an unknown resource name' do + expect { unit_client.unicorn }.to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource unicorn/) + end + + it 'does not claim to respond to it' do + expect(unit_client).not_to respond_to(:unicorn) + end + + it 'still raises NoMethodError for a bang method' do + expect { unit_client.save! }.to raise_error(NoMethodError) + end + + it 'still raises NoMethodError for a predicate' do + expect { unit_client.valid? }.to raise_error(NoMethodError) + end + + it 'stays usable in array operations that rely on to_ary' do + client = unit_client + expect([client].flatten).to eq([client]) + end + + it 'leaves Ruby core methods alone, so only declared resources are dispatched' do + expect(unit_client.hash).to be_an(Integer) + end + + it 'defines resource readers on the client itself, so they win over inherited methods' do + expect(described_class.instance_method(:users).owner).to eq(described_class) + end + end + + describe 'raw requests' do + subject(:client) { unit_client } + + let(:roles_url) { "#{ClientHelper::BASE_URL}api/v1/roles" } + + describe '#get' do + it 'reaches an endpoint the gem does not model' do + stub_request(:get, roles_url).to_return(json_response([{ id: 1, name: 'Admin' }])) + + expect(client.get('api/v1/roles').body).to eq([{ id: 1, name: 'Admin' }]) + end + + it 'returns a Response, so the status and headers stay reachable' do + stub_request(:get, roles_url).to_return(json_response([], headers: { 'X-Total-Count' => '7' })) + + response = client.get('api/v1/roles') + expect(response).to be_a(ZammadAPI::Response) + expect(response.status).to eq(200) + expect(response.headers['x-total-count']).to eq('7') + end + + it 'ignores a leading slash, so paths can be pasted from the Zammad docs' do + stub = stub_request(:get, roles_url).to_return(json_response([])) + + client.get('/api/v1/roles') + expect(stub).to have_been_requested + end + + it 'keeps the sub-path of a Zammad served from one' do + stub = stub_request(:get, 'http://zammad.test/helpdesk/api/v1/roles').to_return(json_response([])) + + unit_client(url: 'http://zammad.test/helpdesk/').get('/api/v1/roles') + expect(stub).to have_been_requested + end + + # Faraday lets an absolute URL replace the instance URL and still sends + # the client's headers, so this handed the access token to another host. + it 'refuses an absolute URL rather than sending the credentials to another host' do + expect { client.get('https://other.example/collect') } + .to raise_error(ArgumentError, /a request path is relative to the instance URL/) + end + + it 'makes no request for an absolute URL' do + stub_request(:any, /other\.example/) + + expect { client.get('https://other.example/collect') }.to raise_error(ArgumentError) + expect(a_request(:any, /other\.example/)).not_to have_been_made + end + + it 'refuses an absolute URL whatever the case of its scheme' do + expect { client.get('HTTP://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) + end + + it 'refuses an absolute URL behind a leading slash' do + expect { client.get('/https://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) + end + + it 'refuses an absolute URL for every verb' do + %i[post put delete].each do |verb| + expect { client.public_send(verb, 'https://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) + end + end + + it 'does not quote the path it refuses, which may carry a secret' do + expect { client.get('https://other.example/collect?token=s3cret') } + .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('s3cret') } + end + + # Faraday reads the path with URI, and URI raises an error of its own + # for one it cannot read: neither a ZammadAPI::Error nor the + # ArgumentError a path is documented to raise, and raised after the + # request had been logged. + describe 'a path that cannot be read as a URL' do + it 'refuses one holding a character outside ASCII' do + expect { client.get('api/v1/tägs') } + .to raise_error(ArgumentError, /this one cannot be read as one: it holds a character outside ASCII/) + end + + it 'refuses one holding a space' do + expect { client.get(' api/v1/roles') }.to raise_error(ArgumentError, /it holds a space, or another character a URL does not allow/) + end + + it 'refuses one holding a % that begins no escape' do + expect { client.get('api/v1/roles%zz') }.to raise_error(ArgumentError, /cannot be read as one/) + end + + it 'refuses one whose query string holds what a URL cannot' do + expect { client.get('api/v1/roles?name=prüfung') }.to raise_error(ArgumentError, /a character outside ASCII/) + end + + it 'says how to write it' do + expect { client.get('api/v1/tägs') }.to raise_error(ArgumentError, /a space is %20, and ä is %C3%A4 - or pass a parameter as query:/) + end + + it 'refuses a query string that names a parameter as two kinds of thing' do + expect { client.get('api/v1/roles?a=1&a[b]=2') } + .to raise_error(ArgumentError, /the query string written into this request path cannot be read as parameters/) + end + + it 'does not quote the path, which may carry a secret' do + expect { client.get('api/v1/ro les?token=s3cret') } + .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('s3cret') } + end + + # Ruby attaches the error a rescue raised in to the one it raises, + # and prints it with it. URI's quotes the path. + it 'does not carry the error that quotes the path along as its cause' do + expect { client.get('api/v1/ro les?token=s3cret') }.to raise_error(ArgumentError) { |error| + expect(error.cause).to be_nil + expect(error.full_message(highlight: false)).not_to include('s3cret') + } + end + + it 'does not carry one along for a query string it cannot read either' do + expect { client.get('api/v1/roles?token=s3cret&token[b]=2') } + .to raise_error(ArgumentError) { |error| expect(error.cause).to be_nil } + end + + it 'refuses it for every verb' do + %i[post put delete].each do |verb| + expect { client.public_send(verb, 'api/v1/tägs') }.to raise_error(ArgumentError, /cannot be read as one/) + end + end + + it 'makes no request and leaves no log line for one' do + log = StringIO.new + logged = unit_client(logger: Logger.new(log, level: Logger::DEBUG)) + stub_request(:any, /zammad\.test/) + + expect { logged.get('api/v1/tägs') }.to raise_error(ArgumentError) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + expect(log.string).to be_empty + end + + it 'still sends the same path percent-encoded' do + stub = stub_request(:get, 'http://zammad.test/api/v1/t%C3%A4gs').to_return(json_response([])) + + client.get('api/v1/t%C3%A4gs') + expect(stub).to have_been_requested + end + + it 'still sends a query string written into the path' do + stub = stub_request(:get, roles_url).with(query: { 'name' => 'prüfung', 'page' => '2' }).to_return(json_response([])) + + client.get('api/v1/roles?name=pr%C3%BCfung&page=2') + expect(stub).to have_been_requested + end + end + + it 'keeps a protocol-relative path on the instance' do + stub = stub_request(:get, 'http://zammad.test/other.example/collect').to_return(json_response([])) + + client.get('//other.example/collect') + expect(stub).to have_been_requested + end + + it 'still sends a path that merely contains a colon' do + stub = stub_request(:get, 'http://zammad.test/api/v1/tags:search').to_return(json_response([])) + + client.get('api/v1/tags:search') + expect(stub).to have_been_requested + end + + it 'passes query parameters' do + stub = stub_request(:get, roles_url).with(query: { 'active' => 'true' }).to_return(json_response([])) + + client.get('api/v1/roles', query: { active: true }) + expect(stub).to have_been_requested + end + + it 'sends the configured authentication' do + stub = stub_request(:get, roles_url) + .with(headers: { 'Authorization' => 'Token test-token' }) + .to_return(json_response([])) + + client.get('api/v1/roles') + expect(stub).to have_been_requested + end + + it 'carries an on_behalf_of scope' do + stub = stub_request(:get, roles_url) + .with(headers: { 'From' => 'agent@example.com' }) + .to_return(json_response([])) + + client.on_behalf_of('agent@example.com').get('api/v1/roles') + expect(stub).to have_been_requested + end + + # An escape hatch that cannot set a header does not reach an endpoint + # that needs one. + it 'sends the headers it was given' do + stub = stub_request(:get, roles_url) + .with(headers: { 'Accept-Language' => 'de-de' }) + .to_return(json_response([])) + + client.get('api/v1/roles', headers: { 'Accept-Language' => 'de-de' }) + expect(stub).to have_been_requested + end + + it 'stringifies a header value the wire could not carry' do + stub = stub_request(:get, roles_url) + .with(headers: { 'X-Retry' => '3' }) + .to_return(json_response([])) + + client.get('api/v1/roles', headers: { 'X-Retry' => 3 }) + expect(stub).to have_been_requested + end + + # Faraday's authorization middleware leaves a header that is already set + # alone, so this would have replaced the client's own credentials - + # quietly, while #inspect went on reporting the scheme it was built with. + it 'refuses to replace the configured authentication' do + expect { client.get('api/v1/roles', headers: { 'Authorization' => 'Token other' }) } + .to raise_error(ArgumentError, /header authorization is set by this client/) + end + + it 'names the option that does mean it' do + expect { client.get('api/v1/roles', headers: { 'Authorization' => 'Token other' }) } + .to raise_error(ArgumentError, /pass http_token:, oauth2_token:, or user: and password:/) + end + + it 'refuses the From header that on_behalf_of owns' do + expect { client.get('api/v1/roles', headers: { from: 'agent@example.com' }) } + .to raise_error(ArgumentError, /use client\.on_behalf_of/) + end + + it 'refuses a nil header value rather than sending an empty one' do + expect { client.get('api/v1/roles', headers: { 'X-Trace' => nil }) } + .to raise_error(ArgumentError, /header x-trace is nil/) + end + + it 'refuses a header value that is not text' do + expect { client.get('api/v1/roles', headers: { 'X-Trace' => ['a'] }) } + .to raise_error(ArgumentError, /a header is always text/) + end + + # HTTP reads the two names as one header, so a merge would send whichever + # Hash order put last and drop the other without a word. + it 'refuses two spellings of one header' do + expect { client.get('api/v1/roles', headers: { 'Accept-Language' => 'de', 'accept-language' => 'en' }) } + .to raise_error(ArgumentError, /header accept-language was given twice/) + end + + it 'makes no request for a header it refuses' do + expect { client.get('api/v1/roles', headers: { 'X-Trace' => nil }) }.to raise_error(ArgumentError) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'raises the mapped error class' do + stub_request(:get, roles_url).to_return(json_response({ error: 'nope' }, status: 403)) + + expect { client.get('api/v1/roles') }.to raise_error(ZammadAPI::AuthorizationError, /nope/) + end + + it 'names the request in the error message' do + stub_request(:get, roles_url).to_return(json_response({}, status: 500)) + + expect { client.get('api/v1/roles') } + .to raise_error(ZammadAPI::ServerError, "Can't GET api/v1/roles: HTTP 500") + end + + # The path names the request in every error it raises, and a query + # written into it went along: a token in an exception report. + it 'names it without a credential in a query written into the path' do + stub_request(:get, roles_url).with(query: hash_including({})).to_return(json_response({}, status: 500)) + + expect { client.get('api/v1/roles?token=path-s3cret&page=2') } + .to raise_error(ZammadAPI::ServerError, "Can't GET api/v1/roles?token=[REDACTED]&page=2: HTTP 500") + end + + it 'hands back a non-JSON body untouched' do + stub_request(:get, roles_url).to_return(status: 200, body: 'plain', headers: { 'Content-Type' => 'text/plain' }) + + expect(client.get('api/v1/roles').body).to eq('plain') + end + end + + describe '#post' do + it 'sends a JSON body' do + stub = stub_request(:post, roles_url) + .with(body: JSON.generate({ name: 'Agent' }), headers: { 'Content-Type' => 'application/json' }) + .to_return(json_response({ id: 2 })) + + expect(client.post('api/v1/roles', body: { name: 'Agent' }).body).to eq({ id: 2 }) + expect(stub).to have_been_requested + end + + it 'is not retried, so a failed create cannot be duplicated' do + stub_request(:post, roles_url).to_return(json_response({}, status: 500)) + + expect { unit_client(retries: 3).post('api/v1/roles', body: {}) }.to raise_error(ZammadAPI::ServerError) + expect(a_request(:post, roles_url)).to have_been_made.once + end + + it 'redacts credentials from the log' do + stub_request(:post, roles_url).to_return(json_response({})) + + log = StringIO.new + logger = Logger.new(log, level: Logger::DEBUG) + unit_client(logger: logger).post('api/v1/roles', body: { password: 'hunter2' }) + + expect(log.string).to include('[REDACTED]') + expect(log.string).not_to include('hunter2') + end + + it 'redacts a credential-bearing header from the log too' do + stub_request(:post, roles_url).to_return(json_response({})) + + log = StringIO.new + logger = Logger.new(log, level: Logger::DEBUG) + unit_client(logger: logger).post('api/v1/roles', headers: { 'X-Api-Key' => 'hunter2' }) + + expect(log.string).to include('[REDACTED]') + expect(log.string).not_to include('hunter2') + end + + it 'sends the headers it was given' do + stub = stub_request(:post, roles_url).with(headers: { 'X-Trace' => 'abc' }).to_return(json_response({})) + + client.post('api/v1/roles', body: {}, headers: { 'X-Trace' => 'abc' }) + expect(stub).to have_been_requested + end + end + + describe '#put' do + it 'sends a JSON body' do + stub = stub_request(:put, "#{roles_url}/1").with(body: JSON.generate({ name: 'Agent' })).to_return(json_response({ id: 1 })) + + client.put('api/v1/roles/1', body: { name: 'Agent' }) + expect(stub).to have_been_requested + end + + it 'sends the headers it was given' do + stub = stub_request(:put, "#{roles_url}/1").with(headers: { 'X-Trace' => 'abc' }).to_return(json_response({})) + + client.put('api/v1/roles/1', body: {}, headers: { 'X-Trace' => 'abc' }) + expect(stub).to have_been_requested + end + end + + describe '#delete' do + it 'passes query parameters, which is how Zammad takes tag removals' do + stub = stub_request(:delete, "#{ClientHelper::BASE_URL}api/v1/tags/remove") + .with(query: { 'object' => 'Ticket', 'o_id' => '1', 'item' => 'urgent' }) + .to_return(json_response({ success: true })) + + client.delete('api/v1/tags/remove', query: { object: 'Ticket', o_id: 1, item: 'urgent' }) + expect(stub).to have_been_requested + end + + it 'sends the headers it was given' do + stub = stub_request(:delete, roles_url).with(headers: { 'X-Trace' => 'abc' }).to_return(json_response({})) + + client.delete('api/v1/roles', headers: { 'X-Trace' => 'abc' }) + expect(stub).to have_been_requested + end + end + + # The scope is set after the caller's headers, so a request cannot take the + # header out from under the client that was scoped. + it 'keeps the on_behalf_of scope alongside a caller header' do + stub = stub_request(:get, roles_url) + .with(headers: { 'From' => 'agent@example.com', 'X-Trace' => 'abc' }) + .to_return(json_response([])) + + client.on_behalf_of('agent@example.com').get('api/v1/roles', headers: { 'X-Trace' => 'abc' }) + expect(stub).to have_been_requested + end + + it 'does not shadow a resource reader' do + expect(client.resource_names).not_to include(:get, :post, :put, :delete) + end + end + + describe '#on_behalf_of' do + before do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + end + + it 'sends the From header' do + stub = stub_request(:get, url) + .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }) + .to_return(json_response({ id: 1 })) + + unit_client.on_behalf_of('agent@example.com').users.find(1) + expect(stub).to have_been_requested + end + + it 'returns a new client' do + client = unit_client + expect(client.on_behalf_of('someone')).not_to be(client) + end + + it 'leaves the original client unscoped' do + client = unit_client + client.on_behalf_of('someone') + client.users.find(1) + + expect(a_request(:get, url).with { |request| request.headers.key?('From') }).not_to have_been_made + end + + it 'keeps the scoped client usable for several requests' do + scoped = unit_client.on_behalf_of('agent@example.com') + scoped.users.find(1) + scoped.users.find(1) + + expect(a_request(:get, url).with(query: hash_including({}), headers: { 'From' => 'agent@example.com' })) + .to have_been_made.twice + end + + # Zammad skips a From header with nothing in it, and a nil sent none, so + # each of these handed back a client that ran every request as the + # account it authenticates as - with no error to say the scope was gone. + describe 'an identifier that names nobody' do + [nil, '', ' ', "\t\n", "\u00A0", "\u3000"].each do |blank| + it "refuses #{blank.inspect}" do + expect { unit_client.on_behalf_of(blank) } + .to raise_error(ArgumentError, /on_behalf_of needs the login, email address or id of a user, and was given #{Regexp.escape(blank.inspect)}/) + end + end + + # Client.build takes anything with a transport's interface. One whose + # with_on_behalf_of stores what it is given would otherwise send an + # empty From header. + it 'refuses one through a transport that does not check it' do + storing = Class.new do + attr_reader :on_behalf_of + + def initialize(on_behalf_of = nil) = @on_behalf_of = on_behalf_of + def with_on_behalf_of(identifier) = self.class.new(identifier) + end + client = described_class.build(unit_client.config, storing.new) + + expect { client.on_behalf_of("\u00A0") }.to raise_error(ArgumentError, /on_behalf_of needs the login/) + end + + it 'hands such a transport the scope as the text the header carries' do + storing = Class.new do + attr_reader :on_behalf_of + + def initialize(on_behalf_of = nil) = @on_behalf_of = on_behalf_of + def with_on_behalf_of(identifier) = self.class.new(identifier) + end + + expect(described_class.build(unit_client.config, storing.new).on_behalf_of(7).inspect).to include('on_behalf_of="7"') + end + + it 'says what the request would have run as' do + expect { unit_client.on_behalf_of(nil) }.to raise_error(ArgumentError, /performed as the account this client authenticates as/) + end + + it 'refuses it before the block is run' do + ran = false + expect { unit_client.on_behalf_of('') { ran = true } }.to raise_error(ArgumentError) + + expect(ran).to be(false) + end + + it 'still takes a user id' do + stub = stub_request(:get, url).with(query: hash_including({}), headers: { 'From' => '7' }).to_return(json_response({ id: 1 })) + unit_client.on_behalf_of(7).users.find(1) + + expect(stub).to have_been_requested + end + end + + describe 'block form' do + it 'yields a scoped client' do + unit_client.on_behalf_of('agent@example.com') { |scoped| scoped.users.find(1) } + + expect(a_request(:get, url).with(query: hash_including({}), headers: { 'From' => 'agent@example.com' })) + .to have_been_made + end + + it 'returns the block value' do + expect(unit_client.on_behalf_of('agent@example.com') { :done }).to eq(:done) + end + + it 'does not affect the outer client when the block raises' do + client = unit_client + + expect { client.on_behalf_of('agent@example.com') { raise 'boom' } }.to raise_error('boom') + + client.users.find(1) + expect(a_request(:get, url).with { |request| request.headers.key?('From') }).not_to have_been_made + end + end + end + + describe '#with' do + it 'returns a new client' do + client = unit_client + expect(client.with(timeout: 5)).not_to be(client) + end + + it 'applies the changed option' do + expect(unit_client.with(timeout: 5).config.timeout).to eq(5) + end + + it 'leaves the original client untouched' do + client = unit_client + client.with(timeout: 5) + expect(client.config.timeout).to eq(ZammadAPI::Config::DEFAULT_TIMEOUT) + end + + it 'keeps the options that were not changed' do + expect(unit_client.with(timeout: 5).config.http_token).to eq('test-token') + end + + it 're-validates the resulting configuration' do + expect { unit_client.with(timeout: -1) } + .to raise_error(ZammadAPI::ConfigurationError, /positive number/) + end + + # Merged beside the token it was meant to replace, the new credential was + # never sent: the derived client went on acting as the old account. + context 'when it names another way to authenticate' do + it 'switches to an OAuth2 token' do + expect(unit_client.with(oauth2_token: 'x').config.authentication_scheme).to eq(:oauth2_token) + end + + it 'switches to a user and password' do + expect(unit_client.with(user: 'u', password: 'p').config.authentication_scheme).to eq(:basic) + end + + it 'drops the credential it replaced' do + expect(unit_client.with(oauth2_token: 'x').config.http_token).to be_nil + end + + it 'sends the new credential' do + stub = stub_request(:get, url) + .with(query: hash_including({}), headers: { 'Authorization' => 'Bearer x' }) + .to_return(json_response({ id: 1 })) + + unit_client.with(oauth2_token: 'x').users.find(1) + expect(stub).to have_been_requested + end + + it 'leaves the original client on its own credential' do + client = unit_client + client.with(oauth2_token: 'x') + expect(client.config.authentication_scheme).to eq(:http_token) + end + + it 'switches back to an access token from basic authentication' do + basic = unit_client(http_token: nil, user: 'u', password: 'p') + expect(basic.with(http_token: 't').config.to_h.slice(:user, :password, :http_token)) + .to eq({ user: nil, password: nil, http_token: 't' }) + end + end + + it 'replaces a token of the same kind' do + expect(unit_client.with(http_token: 'other').config.http_token).to eq('other') + end + + it 'keeps the user when only the password changes' do + basic = unit_client(http_token: nil, user: 'u', password: 'old').with(password: 'new') + expect([basic.config.user, basic.config.password]).to eq(%w[u new]) + end + + it 'carries an on_behalf_of scope over to the derived client' do + stub = stub_request(:get, url) + .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }) + .to_return(json_response({ id: 1 })) + + unit_client.on_behalf_of('agent@example.com').with(timeout: 5).users.find(1) + expect(stub).to have_been_requested + end + + it 'still works for requests' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + expect(unit_client.with(timeout: 5).users.find(1).id).to eq(1) + end + end + + describe 'concurrent use' do + it 'does not leak an on_behalf_of scope between threads' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + + client = unit_client + logins = %w[a@example.com b@example.com c@example.com] + + threads = logins.map do |login| + Thread.new { 5.times { client.on_behalf_of(login).users.find(1) } } + end + threads << Thread.new { 5.times { client.users.find(1) } } + threads.each(&:join) + + logins.each do |login| + expect(a_request(:get, url).with(query: hash_including({}), headers: { 'From' => login })) + .to have_been_made.times(5) + end + end + + it 'leaves the shared client unscoped throughout' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + + client = unit_client + threads = %w[a@example.com b@example.com].map do |login| + Thread.new { 5.times { client.on_behalf_of(login).users.find(1) } } + end + threads.each(&:join) + + client.users.find(1) + + expect( + a_request(:get, url).with(query: hash_including({})) { |request| !request.headers.key?('From') } + ).to have_been_made + end + end + + describe '#inspect' do + it 'shows the url and auth scheme' do + expect(unit_client.inspect) + .to eq('#') + end + + it 'does not leak the token' do + expect(unit_client(http_token: 'super-secret').inspect).not_to include('super-secret') + end + + # A scoped client printed as the one it was derived from, so nothing in a + # log told the two apart. + it 'shows the user a scoped client acts for' do + expect(unit_client.on_behalf_of('agent@example.com').inspect) + .to eq('#') + end + + # They used to be sent in place of the configured token, while this went + # on reporting auth=http_token. + it 'cannot be built from a url that carries credentials, so it never reports a scheme it does not use' do + expect { unit_client(url: 'https://admin:url-s3cret@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials of its own/) + end + end + + # A proxy holds nothing but the client's transport and the resource class, + # and `client.tickets` is the idiom every call starts with - each one used to + # allocate a fresh one. + describe 'resource proxies' do + subject(:client) { unit_client } + + it 'hands out the same proxy for the same resource' do + first = client.tickets + + expect(client.tickets).to be(first) + end + + # Built up front rather than memoized on first use. A client is documented + # as immutable once built and safe to share between threads without + # locking, and a memo filled in by the first `client.tickets` in each worker + # is a write to shared state - harmless under CRuby's GVL, but not the + # contract that was written down. + it 'is not mutated by reading a proxy off it' do + before_read = client.instance_variable_get(:@resources) + client.tickets + + expect(client.instance_variable_get(:@resources)).to be(before_read) + end + + it 'holds a proxy for every resource before any is asked for' do + expect(client.instance_variable_get(:@resources).size).to eq(client.resource_names.size) + end + + it 'refuses to be written to after it is built' do + expect(client.instance_variable_get(:@resources)).to be_frozen + end + + it 'hands out a different proxy per resource' do + expect(client.tickets).not_to be(client.users) + end + + # The cache belongs to one transport, so a derived client must not be + # handed proxies still wired to the transport it was derived from. + it 'does not carry a proxy over to an on_behalf_of client' do + expect(client.on_behalf_of('agent@example.com').tickets).not_to be(client.tickets) + end + + it 'does not carry a proxy over to a client built with #with' do + expect(client.with(timeout: 5).tickets).not_to be(client.tickets) + end + + # The point of not sharing the cache: a proxy from the derived client has + # to send that client's From header, not the original's. + it 'gives a derived client a proxy that carries its own scope' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/1") + .with(query: hash_including({})).to_return(json_response({ id: 1 })) + + client.tickets + client.on_behalf_of('agent@example.com').tickets.find(1) + + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/1") + .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' })).to have_been_made + end + end +end diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb new file mode 100644 index 0000000..9124d10 --- /dev/null +++ b/spec/unit/zammad_api/collection_spec.rb @@ -0,0 +1,1306 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Collection do + subject(:collection) { client.groups.all } + + let(:client) { unit_client } + let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } + + # What a collection over this endpoint fetches per request when nothing asks + # for another size: as many as the endpoint serves. Read off the resource + # rather than written out, so that these stubs follow the declaration. + def default_per_page = ZammadAPI::Resources::Group.page_limit + + def stub_page(page, records, per_page: default_per_page) + stub_request(:get, url) + .with(query: { 'expand' => 'true', 'page' => page.to_s, 'per_page' => per_page.to_s }) + .to_return(json_response(records)) + end + + # The walk asks for another page only after a full one, so anything about + # walking needs a page of the size that was requested. + def full_page(first_id = 1) + Array.new(default_per_page) { { id: first_id + it } } + end + + # A short page cannot be told apart from one the server shrank, so the walk + # confirms the end with one more request. Stubbing that empty page is what a + # collection that fits in a single page looks like from out here. + def stub_last_page(page, records, per_page: default_per_page) + stub_page(page, records, per_page: per_page) + stub_page(page + 1, [], per_page: per_page) + end + + # Mirrors Zammad's CanPaginate::Pagination: the endpoint reduces per_page to + # its own maximum and pages by that reduced size. + def stub_capped_endpoint(url, total:, max:) + stub_request(:get, url).with(query: hash_including({})).to_return do |request| + params = URI.decode_www_form(URI(request.uri).query).to_h + limit = [Integer(params['per_page']), max].min + offset = (Integer(params['page']) - 1) * limit + json_response(Array(offset...[offset + limit, total].min).map { { id: it + 1 } }) + end + end + + it 'is an Enumerable' do + expect(described_class.ancestors).to include(Enumerable) + end + + describe '#each' do + it 'walks every page until the server runs out of records' do + stub_page(1, full_page) + stub_page(2, [{ id: default_per_page + 1 }]) + + expect(collection.map(&:id)).to eq((1..(default_per_page + 1)).to_a) + end + + it 'confirms the end of a short first page rather than assuming it' do + stub_last_page(1, [{ id: 1 }]) + + expect(collection.map(&:id)).to eq([1]) + expect(a_request(:get, url).with(query: hash_including('page' => '2'))).to have_been_made + end + + it 'stops on a page shorter than the one the endpoint has been serving' do + stub_page(1, full_page) + stub_page(2, [{ id: default_per_page + 1 }]) + + expect(collection.map(&:id)).to eq((1..(default_per_page + 1)).to_a) + expect(a_request(:get, url).with(query: hash_including('page' => '3'))).not_to have_been_made + end + + it 'walks an endpoint that serves a smaller page than it was asked for' do + stub_capped_endpoint(url, total: 120, max: 50) + + expect(collection.map(&:id)).to eq((1..120).to_a) + end + + it 'stops on an empty page' do + stub_page(1, full_page) + stub_page(2, []) + + expect(collection.map(&:id)).to eq((1..default_per_page).to_a) + end + + it 'yields persisted records' do + stub_page(1, [{ id: 1 }], per_page: 1) + + expect(collection.first).to be_persisted + end + + it 'yields records of the right class' do + stub_page(1, [{ id: 1 }], per_page: 1) + + expect(collection.first).to be_a(ZammadAPI::Resources::Group) + end + + it 'returns an Enumerator without a block' do + expect(collection.each).to be_a(Enumerator) + end + + it 'does not make a request until it is iterated' do + collection + expect(a_request(:get, url).with(query: hash_including({}))).not_to have_been_made + end + + it 'stops fetching early when the caller stops consuming' do + stub_page(1, [{ id: 1 }], per_page: 1) + + expect(collection.first).to be_a(ZammadAPI::Resources::Group) + expect(a_request(:get, url).with(query: hash_including('page' => '2'))).not_to have_been_made + end + + it 'works with lazy enumeration' do + stub_page(1, [{ id: 1 }, { id: 2 }]) + + expect(collection.lazy.map(&:id).first(2)).to eq([1, 2]) + end + + it 'raises ParseError when the endpoint does not return a list' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect { collection.to_a } + .to raise_error(ZammadAPI::ParseError, /expected a JSON array, got Hash/) + end + + it 'raises PaginationError when the endpoint ignores the page parameter' do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response(full_page)) + + expect { collection.to_a } + .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) + end + + it 'keeps walking records that carry no id' do + stub_page(1, Array.new(default_per_page) { { name: "a#{it}" } }) + stub_page(2, [{ name: 'b0' }]) + + expect(collection.map(&:name)).to eq(Array.new(default_per_page) { "a#{it}" } + ['b0']) + end + + it 'does not hand the repeated page to the block before raising' do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response(full_page)) + + batches = [] + + expect { collection.in_batches { batches << it } }.to raise_error(ZammadAPI::PaginationError) + expect(batches.size).to eq(1) + end + + it 'does not yield the repeated records to each either' do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response(full_page)) + + seen = 0 + + expect { collection.each { seen += 1 } }.to raise_error(ZammadAPI::PaginationError) + expect(seen).to eq(default_per_page) + end + + # The guard compares the decoded payload, not the bytes it arrived as. + # Hashing raw_body is cheaper and looks equivalent - identical bytes do + # mean identical records - but the implication that matters runs the other + # way: an endpoint that ignores `page` and re-serializes the same records + # with a different key order produces different bytes every time, so the + # guard never fires. Every page is full, so neither the short-page break + # nor the total break fires either, and the walk never ends. + it 'raises PaginationError when a repeated page is re-serialized differently' do + forwards = Array.new(default_per_page) { { id: it, name: "a#{it}" } } + backwards = forwards.map { { name: it[:name], id: it[:id] } } + # Every page differs from the one before it in bytes and from none of + # them in records, which a fixed sequence cannot express: WebMock repeats + # its last response, so two pages running would come back byte-identical + # and a byte digest would catch them one page later. + order = [forwards, backwards].cycle + stub_request(:get, url).with(query: hash_including({})).to_return { json_response(order.next) } + + # Bounded, because what this guards against is a walk that never ends + # rather than one that ends wrongly - unbounded, a regression here hangs + # the suite instead of failing it. + expect { Timeout.timeout(5) { collection.to_a } } + .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) + end + + # A job that writes to the records it is handed changes what they + # serialize as, so the page an endpoint repeats is never the same payload + # twice. Compared by payload the guard never fired: every page was full, + # and the job went round the same records for as long as it ran. + it 'raises PaginationError when a repeated page comes back with its records changed' do + round = 0 + stub_request(:get, url).with(query: hash_including({})).to_return do + round += 1 + json_response(Array.new(default_per_page) { { id: it + 1, updated_at: "2026-11-18T10:00:#{format('%02d', round)}Z" } }) + end + + batches = 0 + + expect { Timeout.timeout(5) { collection.in_batches { batches += 1 } } } + .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) + expect(batches).to eq(1) + end + + # A search sorts by updated_at, so the write that changes a record's + # payload moves it within the page as well. + it 'raises PaginationError when a repeated page comes back changed and in another order' do + round = 0 + stub_request(:get, url).with(query: hash_including({})).to_return do + round += 1 + page = Array.new(default_per_page) { { id: it + 1, note: "round #{round}" } } + json_response(round.odd? ? page : page.reverse) + end + + expect { Timeout.timeout(5) { collection.to_a } } + .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) + end + + it 'does not take two pages that share some of their records for a repeat' do + stub_page(1, full_page) + stub_page(2, full_page(2)) + stub_page(3, []) + + expect(collection.map(&:id)).to eq([*1..default_per_page, *2..(default_per_page + 1)]) + end + + it 'raises PaginationError when records without an id repeat' do + page = Array.new(default_per_page) { { name: "a#{it}" } } + stub_request(:get, url).with(query: hash_including({})).to_return(json_response(page)) + + expect { collection.to_a } + .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) + end + + # The walk ran inside Kernel#loop, which rescues StopIteration for an + # enumerator driven by hand inside it. The block here is the caller's, and + # one raised from it was taken for the end of the walk: the rest of the + # records were dropped and `map` answered with the ones before it. + context 'when the block raises StopIteration' do + let(:labels) { %w[x y].each } + + before { stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) } + + it 'raises it, as the same block over an Array does' do + expect { collection.map { |group| [group.id, labels.next] } }.to raise_error(StopIteration) + end + + it 'raises it from each, rather than ending the walk as if it were complete' do + seen = [] + expect { collection.each { |group| seen << [group.id, labels.next] } }.to raise_error(StopIteration) + + expect(seen).to eq([[1, 'x'], [2, 'y']]) + end + + it 'raises it from in_batches' do + expect { collection.in_batches { raise StopIteration } }.to raise_error(StopIteration) + end + end + + # What Enumerable does with a walk it has had enough of is not an error, + # and still ends it there. + it 'still ends a walk that a break leaves early' do + stub_page(1, full_page) + + expect(collection.each { |group| break group.id if group.id == 2 }).to eq(2) + expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once + end + end + + describe '#find_each' do + it 'yields every record' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + stub_page(2, [{ id: 3 }], per_page: 2) + + ids = [] + collection.find_each(batch_size: 2) { ids << it.id } + expect(ids).to eq([1, 2, 3]) + end + + it 'walks at the default page size without one' do + stub_last_page(1, [{ id: 1 }]) + + ids = [] + collection.find_each { ids << it.id } + expect(ids).to eq([1]) + end + + it 'takes the page size inline' do + stub_last_page(1, [{ id: 1 }], per_page: 50) + + expect(collection.find_each(batch_size: 50).map(&:id)).to eq([1]) + end + + it 'returns an Enumerator without a block' do + expect(collection.find_each).to be_a(Enumerator) + end + + it 'rejects a non-positive page size' do + expect { collection.find_each(batch_size: 0) { nil } } + .to raise_error(ArgumentError, 'batch_size needs a positive integer') + end + + # Re-sizing the page silently changed which records the collection held: + # page(3, per_page: 50) names records 101 to 150, and a batch_size of 10 turned + # that into records 21 to 30 with nothing said about it. + it 'refuses to re-size a collection already limited to a page' do + expect { collection.page(3, per_page: 50).find_each(batch_size: 10) { nil } } + .to raise_error(ArgumentError, /batch_size cannot be combined with page/) + end + + it 'says how to name the page it would have served' do + expect { collection.page(3, per_page: 50).find_each(batch_size: 10) { nil } } + .to raise_error(ArgumentError, /page\(3, per_page: 10\)/) + end + end + + describe '#in_batches' do + it 'yields one array per page' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + stub_page(2, [{ id: 3 }], per_page: 2) + + batches = [] + collection.in_batches(of: 2) { batches << it.map(&:id) } + expect(batches).to eq([[1, 2], [3]]) + end + + it 'yields a whole page at the default size without one' do + stub_last_page(1, [{ id: 1 }, { id: 2 }]) + + batches = [] + collection.in_batches { batches << it.map(&:id) } + expect(batches).to eq([[1, 2]]) + end + + # The batch is the block's own Array, and working it off with `shift` is + # an ordinary way to consume one. The walk used to read the size of that + # Array after the block returned, so a drained batch looked like an empty + # page and ended the walk. + it 'keeps walking when the block empties the batch it was handed' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + stub_page(2, [{ id: 3 }], per_page: 2) + + ids = [] + collection.in_batches(of: 2) { |batch| ids << batch.shift.id until batch.empty? } + expect(ids).to eq([1, 2, 3]) + end + + it 'does not take a batch the block shortened for a short page' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + stub_page(2, [{ id: 3 }, { id: 4 }], per_page: 2) + stub_page(3, [], per_page: 2) + + ids = [] + collection.in_batches(of: 2) do |batch| + ids.concat(batch.map(&:id)) + batch.pop if ids.size > 2 + end + expect(ids).to eq([1, 2, 3, 4]) + expect(a_request(:get, url).with(query: hash_including('page' => '3'))).to have_been_made + end + + it 'returns an Enumerator without a block' do + expect(collection.in_batches).to be_a(Enumerator) + end + + it 'refuses to re-size a collection already limited to a page' do + expect { collection.page(3, per_page: 50).in_batches(of: 10) { nil } } + .to raise_error(ArgumentError, /of cannot be combined with page/) + end + + it 'pulls one page per Enumerator#next' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + + expect(collection.in_batches(of: 2).next.map(&:id)).to eq([1, 2]) + expect(a_request(:get, url).with(query: hash_including('page' => '2'))).not_to have_been_made + end + + it 'rejects a non-positive page size' do + expect { collection.in_batches(of: 0) { nil } } + .to raise_error(ArgumentError, 'of needs a positive integer') + end + end + + describe '#page' do + it 'fetches only the requested page' do + stub_page(2, [{ id: 3 }, { id: 4 }]) + + expect(collection.page(2).map(&:id)).to eq([3, 4]) + expect(a_request(:get, url).with(query: hash_including('page' => '3'))).not_to have_been_made + end + + it 'sizes the page, and so decides which records it holds' do + stub_page(2, [{ id: 3 }], per_page: 3) + + expect(collection.page(2, per_page: 3).map(&:id)).to eq([3]) + end + + it 'keeps the size when the page moves' do + stub_page(3, [{ id: 5 }], per_page: 3) + + expect(collection.page(2, per_page: 3).page(3).map(&:id)).to eq([5]) + end + + it 'returns a new collection and leaves the original unpaged' do + stub_last_page(1, [{ id: 1 }]) + + expect(collection.page(2)).not_to be(collection) + expect(collection.map(&:id)).to eq([1]) + end + + it 'rejects page zero' do + expect { collection.page(0) }.to raise_error(ArgumentError, /positive integer/) + end + + it 'rejects a non-integer page' do + expect { collection.page('2') }.to raise_error(ArgumentError, /positive integer/) + end + + it 'rejects a non-positive page size' do + expect { collection.page(1, per_page: 0) }.to raise_error(ArgumentError, 'per_page needs a positive integer') + end + + it 'rejects a non-integer page size' do + expect { collection.page(1, per_page: '7') }.to raise_error(ArgumentError, 'per_page needs a positive integer') + end + end + + describe 'page size caps' do + it 'clamps a walk to what a generic index endpoint serves' do + stub_page(1, [], per_page: 1000) + + client.groups.all.find_each(batch_size: 5000).to_a + expect(a_request(:get, url).with(query: hash_including('per_page' => '1000'))).to have_been_made + end + + it 'refuses a page larger than a generic index endpoint serves' do + expect { client.groups.all.page(1, per_page: 5000) } + .to raise_error(ArgumentError, /serves at most 1000 records per page/) + end + + it 'refuses a page larger than the ticket index endpoint serves' do + expect { client.tickets.all.page(1, per_page: 5000) } + .to raise_error(ArgumentError, /serves at most 100 records per page/) + end + + it 'refuses a page larger than a search endpoint serves' do + expect { client.users.search('smith').page(1, per_page: 5000) } + .to raise_error(ArgumentError, /serves at most 200 records per page/) + end + + it 'names the page that would have been served instead' do + expect { client.tickets.all.page(3, per_page: 500) } + .to raise_error(ArgumentError, /page\(3, per_page: 500\) would be sent as page 3 of 100/) + end + + it 'names a page size the endpoint does serve' do + expect { client.tickets.all.page(3, per_page: 500) } + .to raise_error(ArgumentError, /Ask for page\(3, per_page: 100\) or fewer/) + end + + it 'accepts a page exactly the size the endpoint serves' do + expect(client.tickets.all.page(2, per_page: 100).inspect).to include('per_page=100') + end + + it 'walks the whole list when asked for more per page than the endpoint serves' do + stub_capped_endpoint("#{ClientHelper::BASE_URL}api/v1/tickets", total: 250, max: 100) + + expect(client.tickets.all.find_each(batch_size: 250).map(&:id)).to eq((1..250).to_a) + end + end + + it 'raises rather than building records out of a list of ids' do + stub_page(1, [1, 2, 3]) + + expect { collection.to_a } + .to raise_error(ZammadAPI::ParseError, /expected a JSON array of objects, got an array holding Integer/) + end + + # An index endpoint sorts and pages and does nothing else, so sorting has a + # name of its own. It was reached through `where`, which refused nearly + # everything else it was given. + describe '#order' do + def sorted_request(sort_by, order_by) + a_request(:get, url).with(query: hash_including('sort_by' => sort_by, 'order_by' => order_by)) + end + + before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) } + + it 'sorts ascending by an attribute named on its own' do + collection.order(:name).to_a + expect(sorted_request('name', 'asc')).to have_been_made + end + + it 'sorts the way a keyword says' do + collection.order(name: :desc).to_a + expect(sorted_request('name', 'desc')).to have_been_made + end + + # Zammad pairs the two lists by position and skips an attribute that has + # no direction, so each attribute is sent with one. + it 'sorts by several attributes, each with a direction' do + collection.order(:active, name: :desc).to_a + expect(sorted_request('active,name', 'asc,desc')).to have_been_made + end + + it 'takes an attribute and a direction as strings' do + collection.order('active', 'name' => 'DESC').to_a + expect(sorted_request('active,name', 'asc,desc')).to have_been_made + end + + it 'sorts within an earlier order when chained' do + collection.order(:active).order(name: :desc).to_a + expect(sorted_request('active,name', 'asc,desc')).to have_been_made + end + + it 'keeps the sort on every page it walks' do + stub_request(:get, url).with(query: hash_including('page' => '1')).to_return(json_response(full_page)) + + collection.order(:name).to_a + expect(sorted_request('name', 'asc').with(query: hash_including('page' => '2'))).to have_been_made + end + + it 'keeps the sort on an explicit page' do + collection.order(:name).page(2, per_page: 10).to_a + expect(sorted_request('name', 'asc').with(query: hash_including('page' => '2', 'per_page' => '10'))).to have_been_made + end + + it 'returns a new collection' do + expect(collection.order(:name)).not_to be(collection) + end + + it 'leaves the collection it was called on unsorted' do + collection.order(:name) + collection.to_a + + expect(a_request(:get, url).with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s })) + .to have_been_made + end + + it 'makes no request until the collection is read' do + collection.order(:name) + expect(a_request(:get, url).with(query: hash_including({}))).not_to have_been_made + end + + it 'raises without an attribute to sort by' do + expect { collection.order }.to raise_error(ArgumentError, /order needs at least one attribute to sort by/) + end + + it 'raises for an attribute named twice in one call' do + expect { collection.order(:name, name: :desc) }.to raise_error(ArgumentError, /order was given name twice/) + end + + it 'raises for an attribute the collection is already sorted by' do + expect { collection.order(:name).order(name: :desc) } + .to raise_error(ArgumentError, /order was given name, which this collection is already sorted by/) + end + + it 'raises for a direction that is neither asc nor desc' do + expect { collection.order(name: :down) } + .to raise_error(ArgumentError, /order sorts name either :asc or :desc, got :down/) + end + + # The spelling several other clients use. Read literally it sorts by an + # attribute called desc, which Zammad answers with a server error. + it 'raises for a direction written where an attribute belongs, and says how to write it' do + expect { collection.order(:name, :desc) } + .to raise_error(ArgumentError, /order reads :desc as an attribute to sort by.*order\(name: :desc\)/) + end + + # Several attributes go out as one comma-separated parameter. + it 'raises for a name that would be read as more than one attribute' do + expect { collection.order('name,id') } + .to raise_error(ArgumentError, /order needs the name of an attribute to sort by, got "name,id"/) + end + + it 'raises for something that is not a name at all' do + expect { collection.order(1) }.to raise_error(ArgumentError, /order needs the name of an attribute/) + end + + # TicketsController#index and UsersController#index hardcode the order and + # drop sort_by with everything else they do not read. + context 'with an index endpoint that is always served in id order' do + it 'refuses, rather than handing back records it would be calling sorted' do + expect { client.tickets.all.order(:title) } + .to raise_error(ArgumentError, %r{api/v1/tickets is always served in the same order and ignores sort_by}) + end + + it 'refuses for users too' do + expect { client.users.all.order(:login) }.to raise_error(ArgumentError, %r{api/v1/users is always served}) + end + + it 'points at a search, which does sort' do + expect { client.tickets.all.order(:title) }.to raise_error(ArgumentError, /search\(term\)\.order\(\.\.\.\)/) + end + + it 'makes no request' do + expect { client.tickets.all.order(:title) }.to raise_error(ArgumentError) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end + + context 'with a search' do + let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/search" } + + before { stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) } + + it 'sorts, though the index of the same resource does not' do + client.tickets.search('printer').order(created_at: :desc).to_a + + expect(a_request(:get, search_url).with(query: hash_including('query' => 'printer', 'sort_by' => 'created_at', 'order_by' => 'desc'))) + .to have_been_made + end + end + + # Pointing at a search would send the caller in a circle where the + # resource has none. + it 'points at sort_by alone for an unsortable resource Zammad does not search' do + unsortable = Class.new(ZammadAPI::Resources::Base) do + path 'api/v1/things' + sortable false + end + + expect { ZammadAPI::ResourceProxy.new(unit_transport, unsortable).order(:name) } + .to raise_error(ArgumentError, /ignores sort_by, so order would hand back the records as they were\. Sort what this collection yields instead/) + end + end + + describe '#pluck' do + it 'returns one value per record for a single attribute' do + stub_last_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + + expect(collection.pluck(:name)).to eq(%w[Users Support]) + end + + it 'returns one array per record for several attributes' do + stub_last_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + + expect(collection.pluck(:id, :name)).to eq([[1, 'Users'], [2, 'Support']]) + end + + it 'accepts string keys' do + stub_last_page(1, [{ id: 1, name: 'Users' }]) + + expect(collection.pluck('name')).to eq(['Users']) + end + + it 'yields nil for an attribute a record does not carry' do + stub_last_page(1, [{ id: 1 }]) + + expect(collection.pluck(:name)).to eq([nil]) + end + + it 'walks every page, like each' do + stub_page(1, full_page) + stub_page(2, [{ id: default_per_page + 1 }]) + + expect(collection.pluck(:id)).to eq((1..(default_per_page + 1)).to_a) + end + + it 'needs at least one attribute name' do + expect { collection.pluck }.to raise_error(ArgumentError, 'pluck needs at least one attribute name') + end + end + + describe '#count' do + let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/users/search" } + + it 'asks a search endpoint for the total in one request' do + stub_request(:get, search_url) + .with(query: { 'expand' => 'true', 'query' => 'smith', 'only_total_count' => 'true' }) + .to_return(json_response({ total_count: 4711 })) + + expect(client.users.search('smith').count).to eq(4711) + end + + # model_index_render reads sort_by, order_by and the paging and drops + # every other parameter, so only_total_count means nothing to it, and + # there is no header to read a total from either. Probing anyway spent a + # request before the walk that had to happen regardless. + it 'walks an index endpoint rather than probing it for a total it cannot give' do + stub_page(1, full_page) + stub_page(2, [{ id: default_per_page + 1 }]) + + expect(collection.count).to eq(default_per_page + 1) + expect(a_request(:get, url).with(query: hash_including('only_total_count' => 'true'))).not_to have_been_made + end + + # A count is the one answer nothing downstream can sanity check: + # `Array.new(collection.count)` and `count.zero?` both take it at its word. + it 'walks rather than reporting a total that cannot describe a result' do + stub_request(:get, search_url).with(query: hash_including('page' => '1')) + .to_return(json_response([{ id: 1 }])) + stub_request(:get, search_url).with(query: hash_including('page' => '2')) + .to_return(json_response([])) + stub_request(:get, search_url).with(query: hash_including('only_total_count' => 'true')) + .to_return(json_response({ total_count: -3 })) + + expect(client.users.search('smith').count).to eq(1) + end + + it 'walks the pages when a search endpoint answers with no total at all' do + stub_request(:get, search_url).with(query: hash_including('page' => '1')) + .to_return(json_response([{ id: 1 }])) + stub_request(:get, search_url).with(query: hash_including('page' => '2')) + .to_return(json_response([])) + stub_request(:get, search_url).with(query: hash_including('only_total_count' => 'true')) + .to_return(json_response({})) + + expect(client.users.search('smith').count).to eq(1) + end + + it 'walks the pages when the total it answers with is not a count' do + stub_request(:get, search_url).with(query: hash_including('page' => '1')) + .to_return(json_response([{ id: 1 }])) + stub_request(:get, search_url).with(query: hash_including('page' => '2')) + .to_return(json_response([])) + stub_request(:get, search_url).with(query: hash_including('only_total_count' => 'true')) + .to_return(json_response({ total_count: 'lots' })) + + expect(client.users.search('smith').count).to eq(1) + end + + # Not an endpoint Zammad has - all four search actions route through + # model_search_render, which reads only_total_count before it reads + # anything else - but something other than the endpoint can answer: a + # proxy error page, a login form, an HTML body with a 200 on it. + it 'walks the pages when something answers with records instead of a total' do + stub_request(:get, search_url).with(query: hash_including('page' => '1')) + .to_return(json_response([{ id: 1 }, { id: 2 }])) + stub_request(:get, search_url).with(query: hash_including('page' => '2')) + .to_return(json_response([])) + stub_request(:get, search_url).with(query: hash_including('only_total_count' => 'true')) + .to_return(json_response([{ id: 1 }, { id: 2 }])) + + expect(client.users.search('smith').count).to eq(2) + end + + it 'counts one page only when limited to a page' do + stub_page(3, [{ id: 5 }, { id: 6 }]) + + expect(collection.page(3).count).to eq(2) + end + + it 'counts matches when given a block' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + expect(collection.count { it.id > 1 }).to eq(2) + end + end + + describe '#size' do + it 'walks the pages, like #count' do + stub_last_page(1, [{ id: 1 }, { id: 2 }]) + + expect(collection.size).to eq(2) + end + + it 'asks a search endpoint for the total in one request' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/search") + .with(query: { 'expand' => 'true', 'query' => 'smith', 'only_total_count' => 'true' }) + .to_return(json_response({ total_count: 4711 })) + + expect(client.users.search('smith').size).to eq(4711) + end + + it 'is also spelled #length' do + stub_last_page(1, [{ id: 1 }]) + + expect(collection.length).to eq(1) + end + end + + describe '#empty?' do + it 'is false when the endpoint has a record' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + + expect(collection).not_to be_empty + end + + it 'is true when the endpoint has none' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) + + expect(collection).to be_empty + end + + it 'asks for a single record rather than a whole page' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + + collection.empty? + expect(a_request(:get, url).with(query: hash_including('per_page' => '1'))).to have_been_made + end + + it 'leaves the page size alone on a collection limited to one page' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 3 }])) + + collection.page(2, per_page: 5).empty? + expect(a_request(:get, url).with(query: hash_including('page' => '2', 'per_page' => '5'))).to have_been_made + end + end + + # `take(n)` and `first(n)` ask one question. Enumerable answers both by + # taking records off the front of a page sized for walking, so with #first + # sizing its own page and this one left alone, what the same read cost + # depended on which word was typed. + describe '#take' do + it 'reads a page sized for what was asked for' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + + expect(collection.take(2).map(&:id)).to eq([1, 2]) + end + + it 'costs what the same read through #first costs' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + + collection.take(2) + expect(a_request(:get, url).with(query: hash_including('per_page' => '2'))).to have_been_made.once + end + + it 'walks when more records are asked for than the endpoint serves' do + stub_page(1, full_page) + stub_page(2, [{ id: default_per_page + 1 }]) + + expect(collection.take(default_per_page + 1).size).to eq(default_per_page + 1) + end + + it 'leaves a zero count to Enumerable' do + expect(collection.take(0)).to eq([]) + end + + # Enumerable#take always answers with an Array, where `first` reads a nil + # as "just the one" and answers with a record. + it 'refuses a nil the way Enumerable#take does' do + expect { collection.take(nil) }.to raise_error(TypeError, /no implicit conversion/) + end + + it 'reads on where the endpoint serves a smaller page than it was asked for' do + stub_capped_endpoint(url, total: 5, max: 2) + + expect(collection.take(5).map(&:id)).to eq([1, 2, 3, 4, 5]) + end + end + + # `find` on the proxy is the lookup by id, and Enumerable#find reads its + # argument as an ifnone callable - so `all.find(1)` answered with an + # Enumerator, made no request and raised nothing. + describe '#find' do + it 'is Enumerable#find with a block' do + stub_last_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + + expect(collection.find { it.name == 'Support' }.id).to eq(2) + end + + it 'refuses an id where a block belongs' do + expect { collection.find(1) } + .to raise_error(ArgumentError, /find on a ZammadAPI::Collection is Enumerable#find, which takes a block/) + end + + it 'names the lookup that does take an id' do + expect { collection.find(1) }.to raise_error(ArgumentError, /client\.groups\.find\(1\)/) + end + + it 'names the resource the way a client does, for a multi-word one' do + expect { client.ticket_articles.all.find(7) } + .to raise_error(ArgumentError, /client\.ticket_articles\.find\(7\)/) + end + + it 'points at detect for the block form' do + expect { collection.find(1) }.to raise_error(ArgumentError, /detect \{ \.\.\. \}/) + end + + it 'makes no request for the id it refuses' do + expect { collection.find(1) }.to raise_error(ArgumentError) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'still returns an Enumerator without a block or an argument' do + expect(collection.find).to be_a(Enumerator) + end + end + + # Enumerable#first takes its records off the front of a page this collection + # sized for walking, so `all.first` downloaded a whole page to hand back one + # record. + describe '#first' do + it 'reads a page of one for a single record' do + stub_page(1, [{ id: 1 }], per_page: 1) + + expect(collection.first.id).to eq(1) + end + + it 'is nil when the endpoint has nothing' do + stub_page(1, [], per_page: 1) + + expect(collection.first).to be_nil + end + + it 'sizes the page to the number of records asked for' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + + expect(collection.first(2).map(&:id)).to eq([1, 2]) + end + + it 'walks instead when more records are asked for than the endpoint serves' do + stub_page(1, full_page) + stub_page(2, [{ id: default_per_page + 1 }]) + + expect(collection.first(default_per_page + 1).size).to eq(default_per_page + 1) + end + + # The page size of a collection limited to one says which records it + # holds, so re-sizing it would move them - the same reason batch_size + # cannot be combined with page. + it 'leaves a collection already limited to a page at its own size' do + stub_page(3, [{ id: 5 }, { id: 6 }], per_page: 2) + + expect(collection.page(3, per_page: 2).first.id).to eq(5) + end + + it 'leaves a zero count to Enumerable' do + expect(collection.first(0)).to eq([]) + end + + it 'makes no request for a zero count' do + expect(collection.first(0)).to eq([]) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + # Sizing the request rather than limiting the collection to one page: + # limited, this came back with whatever the first page held and nothing to + # say the rest were there to be read. + it 'reads on where the endpoint serves a smaller page than it was asked for' do + stub_capped_endpoint(url, total: 5, max: 2) + + expect(collection.first(5).map(&:id)).to eq([1, 2, 3, 4, 5]) + end + + it 'stops as soon as it has what it asked for' do + stub_capped_endpoint(url, total: 500, max: 2) + + expect(collection.first(3).map(&:id)).to eq([1, 2, 3]) + expect(a_request(:get, url).with(query: hash_including('page' => '3'))).not_to have_been_made + end + end + + describe '#inspect' do + it 'describes the collection without fetching it' do + expect(collection.inspect) + .to eq("#") + end + + it 'mentions the page when limited to one' do + expect(collection.page(4).inspect).to include('page=4') + end + end + + # A walk stops on what the endpoint served, and the size it serves is + # learned from the first page rather than taken from `max_per_page`. Where + # the server's cap is lower than the request - a cap the gem's declaration + # has gone stale on - every page is short of what was asked for, and reading + # the requested size would make each one look like the last. + # A search names the ids for a page and then loads the records by id, so an + # id whose record is gone by then leaves the page one short - on any page, + # not only the last. An index page is a single query and has no such gap. + describe 'a search, which can serve a page short before the last one' do + subject(:search) { client.users.search('smith') } + + let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/users/search" } + let(:page_size) { ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE } + + def stub_search_page(page, records) + stub_request(:get, search_url) + .with(query: hash_including('page' => page.to_s)) + .to_return(json_response(records)) + end + + def hits(range) = range.map { { id: it } } + + it 'walks on past a page that came back short' do + stub_search_page(1, hits(1..page_size)) + stub_search_page(2, hits((page_size + 1)...(page_size * 2))) + stub_search_page(3, hits([900, 901])) + stub_search_page(4, []) + + expect(search.map(&:id)).to eq([*1...(page_size * 2), 900, 901]) + end + + it 'walks on past a short first page too' do + stub_search_page(1, hits(1...page_size)) + stub_search_page(2, hits(page_size..(page_size * 2))) + stub_search_page(3, []) + + expect(search.map(&:id)).to eq((1..(page_size * 2)).to_a) + end + + # The bare array is what a Zammad before 6.5.1 answers with, and it says + # nothing about how many hits there are. An empty page is then all there + # is to end on, hits behind it or not: see the next group for an endpoint + # that does say. + it 'ends on the empty page where the endpoint reports no total' do + stub_search_page(1, hits(1..3)) + last = stub_search_page(2, []) + stub_search_page(3, hits([4])) + + expect(search.map(&:id)).to eq([1, 2, 3]) + expect(last).to have_been_requested.once + expect(a_request(:get, search_url).with(query: hash_including('page' => '3'))).not_to have_been_made + end + + it 'still raises PaginationError for a search that ignores the page parameter' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response(hits(1..3))) + + expect { search.to_a }.to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) + end + + it 'still reads only the one page a search was limited to' do + stub_search_page(2, hits(1..3)) + + expect(search.page(2).map(&:id)).to eq([1, 2, 3]) + expect(a_request(:get, search_url).with(query: hash_including('page' => '3'))).not_to have_been_made + end + end + + # A page of a search can hold nothing with hits still behind it, for the + # reason it can come back short: every id the search named for it has lost + # its record. It takes one stale hit on the page of one that `first` and + # `empty?` ask for, and a search serves the newest first. A Zammad from 6.5.1 + # on reports the size of the whole result beside the page where it is asked + # to, which is what tells such a page from the end. + describe 'a search that reports its total beside each page' do + subject(:search) { client.users.search('smith') } + + let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/users/search" } + + def stub_counted_page(page, ids, total:) + stub_request(:get, search_url) + .with(query: hash_including('page' => page.to_s)) + .to_return(json_response({ records: ids.map { { id: it } }, total_count: total })) + end + + def walked_ids(per_page:) = search.find_each(batch_size: per_page).map(&:id) + + it 'asks for the total with every page of a walk' do + stub_counted_page(1, [1], total: 2) + stub_counted_page(2, [2], total: 2) + stub_counted_page(3, [], total: 2) + walked_ids(per_page: 1) + + expect(a_request(:get, search_url).with(query: hash_including('with_total_count' => 'true'))).to have_been_made.times(3) + end + + it 'reads the records out of the object the total arrives in' do + stub_counted_page(1, [1, 2, 3], total: 3) + stub_counted_page(2, [], total: 3) + + expect(search.map(&:id)).to eq([1, 2, 3]) + end + + it 'reads on past an empty page the total says has hits behind it' do + stub_counted_page(1, [1], total: 3) + stub_counted_page(2, [], total: 3) + stub_counted_page(3, [3], total: 3) + stub_counted_page(4, [], total: 3) + + expect(walked_ids(per_page: 1)).to eq([1, 3]) + end + + # Two empty pages hold the same nothing, and the guard against a page + # that repeats used to read that as an endpoint ignoring `page`. + it 'reads on past two empty pages in a row' do + stub_counted_page(1, [1], total: 4) + stub_counted_page(2, [], total: 4) + stub_counted_page(3, [], total: 4) + stub_counted_page(4, [4], total: 4) + stub_counted_page(5, [], total: 4) + + expect(walked_ids(per_page: 1)).to eq([1, 4]) + end + + it 'ends on an empty page once the pages read cover the total' do + stub_counted_page(1, [1, 2], total: 4) + last = stub_counted_page(2, [], total: 4) + stub_counted_page(3, [5], total: 4) + + expect(walked_ids(per_page: 2)).to eq([1, 2]) + expect(last).to have_been_requested.once + expect(a_request(:get, search_url).with(query: hash_including('page' => '3'))).not_to have_been_made + end + + # Elasticsearch stops counting at ten thousand hits and reports that as + # the total. A walk ended on the figure would stop there. + it 'does not end on the total while a page still holds records' do + stub_counted_page(1, [1], total: 2) + stub_counted_page(2, [2], total: 2) + stub_counted_page(3, [3], total: 2) + stub_counted_page(4, [], total: 2) + + expect(walked_ids(per_page: 1)).to eq([1, 2, 3]) + end + + it 'makes no more requests than the total has pages' do + (1..5).each { stub_counted_page(it, [], total: 3) } + + expect(walked_ids(per_page: 1)).to eq([]) + expect(a_request(:get, search_url).with(query: hash_including({}))).to have_been_made.times(3) + end + + it 'finds the first live hit behind a stale one' do + stub_counted_page(1, [], total: 3) + stub_counted_page(2, [2], total: 3) + + expect(search.first.id).to eq(2) + end + + it 'is not empty where the first hit is stale and the next is live' do + stub_counted_page(1, [], total: 3) + stub_counted_page(2, [2], total: 3) + + expect(search.empty?).to be(false) + end + + it 'is empty, in one request, where the stale hit was the only one' do + stub_counted_page(1, [], total: 1) + + expect(search.empty?).to be(true) + expect(a_request(:get, search_url).with(query: hash_including({}))).to have_been_made.once + end + + # `first` and `empty?` ask for a page of the size they want, and a search + # is read on past an empty one. Held to that size, the two cost a request + # for every stale hit in a row: five thousand of them for `empty?` on an + # instance whose index has drifted from its database. + describe 'read by first, behind hits that have lost their records' do + # A search over `hits`, of which `stale` have lost their record, served + # the way Zammad serves one: the ids for the page first, and then the + # records that are still there. Answers with every page it was asked + # for, as page and size. + # + # `serves` is a page size the endpoint holds to whatever it is asked + # for, paging by it. `window` is an Elasticsearch result window: a page + # that reaches past it is refused, and Zammad answers that as no hits + # and a total of nought. + def stub_search_over(hits, stale: [], serves: nil, window: nil) + asked = [] + stub_request(:get, search_url).with(query: hash_including({})).to_return do |request| + params = URI.decode_www_form(URI(request.uri).query).to_h + page = Integer(params['page']) + size = Integer(params['per_page']) + asked << [page, size] + next json_response({ records: [], total_count: 0 }) if window && page * size > window + + size = [size, serves].min if serves + json_response({ records: (Array(hits)[(page - 1) * size, size].to_a - Array(stale)).map { { id: it } }, total_count: Array(hits).size }) + end + asked + end + + it 'asks for a larger page after each empty one, starting where the last ended' do + asked = stub_search_over(1..32, stale: 1..32) + + expect(search.empty?).to be(true) + expect(asked).to eq([[1, 1], [2, 1], [2, 2], [2, 4], [2, 8], [2, 16]]) + end + + # A page that reaches past the total is one an index whose result + # window was lowered may refuse. + it 'asks for no page that reaches past the total the search reported' do + asked = stub_search_over(1..20, stale: 1..20) + search.empty? + + expect(asked).to eq([[1, 1], [2, 1], [2, 2], [2, 4], [2, 8], [5, 4]]) + end + + # Hits 257 to 384 were asked for, past the window, which Zammad answers + # as nothing at all, and the read ended there with the live hit unread. + it 'finds a live hit inside a lowered result window behind stale ones' do + stub_search_over(1..300, stale: 1..279, window: 300) + + expect(search.first.id).to eq(280) + end + + # Larger pages served by a smaller size start at other positions than + # the ones asked for, behind hits already read: hit 100 came back twice. + it 'hands back no record twice where the endpoint pages smaller than it is asked' do + stub_search_over(1..1000, stale: (1..1000).to_a - [100, 160], serves: 50) + + expect(search.first(2).map(&:id)).to eq([100, 160]) + end + + it 'reads past five thousand stale hits in tens of requests, not thousands' do + asked = stub_search_over(1..5000, stale: 1..5000) + + expect(search.empty?).to be(true) + expect(asked.size).to eq(34) + end + + it 'never asks for a page larger than the endpoint serves' do + asked = stub_search_over(1..5000, stale: 1..5000) + search.first(3) + + expect(asked.map(&:last).max).to be <= ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE + end + + it 'covers every hit once, however the pages were sized' do + asked = stub_search_over(1..5000, stale: 1..5000) + search.first(7) + + covered = asked.flat_map { |page, size| Array.new(size) { ((page - 1) * size) + it + 1 } } + expect(covered.first(5000)).to eq((1..5000).to_a) + end + + it 'finds the first live hit behind a run of stale ones' do + stub_search_over(1..300, stale: 1..137) + + expect(search.first.id).to eq(138) + end + + # Whatever is stale, the answer is the live hits in the order they are + # served: none passed over where a page changed size, none handed over + # twice. + [ + { stale: [], wanted: 3 }, + { stale: [1], wanted: 3 }, + { stale: [2, 3, 4, 5, 6, 7], wanted: 3 }, + { stale: (1..40).to_a - [17], wanted: 2 }, + { stale: (2..90).to_a, wanted: 5 }, + { stale: (1..300).step(2), wanted: 9 }, + { stale: (4..250).to_a, wanted: 4 } + ].each do |example| + it "reads the first #{example[:wanted]} live hits in order with #{example[:stale].to_a.size} of 300 stale" do + stub_search_over(1..300, stale: example[:stale]) + + expect(search.first(example[:wanted]).map(&:id)).to eq(((1..300).to_a - example[:stale].to_a).first(example[:wanted])) + end + end + + it 'still costs one request where the first hit is live' do + asked = stub_search_over(1..300) + search.first + + expect(asked).to eq([[1, 1]]) + end + + # A batch size is the caller saying how many records a batch may hold. + it 'does not widen a batch size the caller chose' do + asked = stub_search_over(1..100, stale: 1..100) + search.in_batches(of: 10) { nil } + + expect(asked.map(&:last).uniq).to eq([10]) + end + end + + it 'still raises PaginationError for a search that repeats a page of records' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response({ records: [{ id: 1 }], total_count: 9 })) + + expect { search.to_a }.to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) + end + + it 'ends on the empty page where the total is not a count' do + stub_counted_page(1, [1], total: 'lots') + stub_counted_page(2, [], total: -4) + stub_counted_page(3, [3], total: 'lots') + + expect(walked_ids(per_page: 1)).to eq([1]) + end + + it 'raises ParseError for an object that is not a page of records' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response({ total_count: 3 })) + + expect { search.to_a }.to raise_error(ZammadAPI::ParseError, /expected a JSON array, got Hash/) + end + + # The walk reads the id of every record on a page, so a null that got + # past the shape check died there as NoMethodError rather than as the + # ParseError a response of the wrong shape is. + it 'raises ParseError for a null among the records' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response({ records: [nil, { id: 2 }], total_count: 2 })) + + expect { search.to_a }.to raise_error(ZammadAPI::ParseError, /an array holding NilClass/) + end + + # One page is one request whatever it holds, so there is no walk for a + # total to end, and the request is the one it always was. + it 'does not ask a search limited to one page for the total' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + search.page(2).to_a + + expect(a_request(:get, search_url).with(query: { 'expand' => 'true', 'query' => 'smith', 'page' => '2', 'per_page' => '200' })).to have_been_made.once + end + + # model_index_render drops the parameter with every other it does not + # know, so asking would be noise on every request of every walk. + it 'does not ask an index for the total' do + index_url = "#{ClientHelper::BASE_URL}api/v1/users" + stub_request(:get, index_url).with(query: hash_including({})).to_return(json_response([])) + client.users.all.to_a + + expect(a_request(:get, index_url).with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => '1000' })).to have_been_made.once + end + end + + describe 'an endpoint that pages smaller than it was asked for' do + it 'is walked to the end rather than truncated at the first short page' do + stub_capped_endpoint(url, total: 5, max: 2) + + expect(collection.map(&:id)).to eq([1, 2, 3, 4, 5]) + end + end +end diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb new file mode 100644 index 0000000..a45f743 --- /dev/null +++ b/spec/unit/zammad_api/config_spec.rb @@ -0,0 +1,683 @@ +# frozen_string_literal: true + +require 'pp' + +RSpec.describe ZammadAPI::Config do + def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) + described_class.new(url: url, http_token: http_token, **overrides) + end + + describe 'url handling' do + it 'appends a trailing slash so sub-path installations keep working' do + expect(build(url: 'https://example.com/zammad').url).to eq('https://example.com/zammad/') + end + + it 'leaves an existing trailing slash alone' do + expect(build(url: 'https://example.com/').url).to eq('https://example.com/') + end + + it 'rejects a missing url' do + expect { build(url: nil) } + .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') + end + + it 'rejects an empty url' do + expect { build(url: '') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') + end + + it 'rejects a non-http scheme' do + expect { build(url: 'ftp://example.com') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https://') + end + + # Appended blindly, the slash landed behind the query string and every + # request was resolved against a base ending in `?tenant=acme/`. + it 'puts the trailing slash on the path, not behind a query string' do + expect(build(url: 'https://example.com/zammad?tenant=acme').url) + .to eq('https://example.com/zammad/?tenant=acme') + end + + it 'puts the trailing slash on the path, not behind a fragment' do + expect(build(url: 'https://example.com/zammad#top').url) + .to eq('https://example.com/zammad/#top') + end + + # Accepted, this failed deep inside the adapter on the first request + # instead of here. + it 'rejects a scheme with no host after it' do + expect { build(url: 'https://') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url needs a host after the scheme, got "https://"') + end + + # URI(...) is what a caller reaches for, and it prints as the URL, so it + # reached String#end_with? and died there as a NoMethodError - past the + # ConfigurationError the constructor is documented to raise. + it 'rejects a url that is not a string' do + expect { build(url: URI('https://example.com/')) } + .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to be a string, got URI::HTTPS') + end + end + + describe 'credentials' do + it 'accepts an access token' do + expect(build(http_token: 'token').authentication_scheme).to eq(:http_token) + end + + it 'accepts an OAuth2 token' do + expect(build(http_token: nil, oauth2_token: 'token').authentication_scheme).to eq(:oauth2_token) + end + + it 'accepts user and password' do + expect(build(http_token: nil, user: 'u', password: 'p').authentication_scheme).to eq(:basic) + end + + # Several used to be accepted together, and the first in a fixed order + # was sent without a word about the others - which is what let an override + # leave the credential it was meant to replace in charge. + context 'with more than one way to authenticate' do + it 'refuses a token beside a user and password' do + expect { build(http_token: 'token', user: 'u', password: 'p') } + .to raise_error(ZammadAPI::ConfigurationError, /config names more than one way to authenticate \(http_token, user and password\)/) + end + + it 'refuses two kinds of token' do + expect { build(http_token: 'token', oauth2_token: 'other') } + .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate \(http_token, oauth2_token\)/) + end + + it 'refuses all three, naming each' do + expect { build(http_token: 'token', oauth2_token: 'other', user: 'u', password: 'p') } + .to raise_error(ZammadAPI::ConfigurationError, /\(http_token, oauth2_token, user and password\)/) + end + + it 'says what to pass instead' do + expect { build(http_token: 'token', oauth2_token: 'other') } + .to raise_error(ZammadAPI::ConfigurationError, /Pass http_token:, or oauth2_token:, or user: and password:, and leave the others out/) + end + + # Half a scheme is still a second one being named. + it 'refuses a token beside a user that has no password' do + expect { build(http_token: 'token', user: 'u') } + .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate/) + end + + it 'keeps the credentials out of the message' do + expect { build(http_token: 'tok-s3cret', user: 'u', password: 'pw-s3cret') } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('s3cret') } + end + + it 'does not count a blank credential as one' do + expect(build(http_token: 'token', oauth2_token: '', user: nil, password: '').authentication_scheme).to eq(:http_token) + end + end + + it 'rejects a missing user' do + expect { build(http_token: nil, password: 'p') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + end + + it 'rejects a missing password' do + expect { build(http_token: nil, user: 'u') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing password in config') + end + + it 'treats blank credentials as absent' do + expect { build(http_token: '', oauth2_token: '', user: '', password: '') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + end + end + + describe 'defaults' do + it 'sets a request timeout' do + expect(build.timeout).to eq(described_class::DEFAULT_TIMEOUT) + end + + it 'sets a connection timeout' do + expect(build.open_timeout).to eq(described_class::DEFAULT_OPEN_TIMEOUT) + end + + it 'retries transient failures' do + expect(build.retries).to eq(described_class::DEFAULT_RETRIES) + end + + it 'identifies itself with the gem version' do + expect(build.user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + end + + it 'verifies TLS certificates' do + expect(build.ssl_verify).to be(true) + end + + it 'discards log output when no logger is supplied' do + expect(build.logger).to be_a(Logger) + end + + it 'leaves the Faraday adapter to Faraday' do + expect(build.adapter).to be_nil + end + + it 'installs no extra middleware' do + expect(build.middleware).to be_nil + end + end + + describe 'the user agent' do + # Handed to Faraday as a nil header, Faraday filled in its own, so the gem + # stopped identifying itself in the instance log an operator greps to find + # its requests - on every request, with nothing said about it. + it 'falls back to the default when it is nil' do + expect(build(user_agent: nil).user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + end + + it 'falls back to the default when it is empty' do + expect(build(user_agent: '').user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + end + + it 'rejects one that is not a string' do + expect { build(user_agent: 42) } + .to raise_error(ZammadAPI::ConfigurationError, 'config user_agent needs to be a string') + end + end + + # Each is sent as a header. Net::HTTP refused a line break inside one at + # the first request, with an ArgumentError that quoted the value. + describe 'a line break in an option sent as a header' do + { + http_token: { http_token: "secret-abc\nsecret-def" }, + oauth2_token: { http_token: nil, oauth2_token: "secret-abc\r\nsecret-def" }, + user_agent: { user_agent: "my-app\nsecret-def" } + }.each do |name, options| + it "refuses one inside #{name}, without quoting it" do + expect { build(**options) }.to raise_error(ZammadAPI::ConfigurationError) { |error| + expect(error.message).to start_with("config #{name} holds a line break, which a header cannot carry") + expect(error.message).not_to include('secret-def') + } + end + end + + # Net::HTTP strips it, so a token read from a file with its newline on + # worked, and still does. + it 'takes a token that only ends in one' do + expect(build(http_token: "secret\n").http_token).to eq("secret\n") + end + + it 'does not check a password, which basic authentication encodes' do + expect(build(http_token: nil, user: 'agent', password: "pass\nword").password).to eq("pass\nword") + end + end + + describe 'the Faraday seam' do + it 'symbolizes an adapter given as a string' do + expect(build(adapter: 'test').adapter).to eq(:test) + end + + it 'keeps an adapter given as a symbol' do + expect(build(adapter: :test).adapter).to eq(:test) + end + + it 'keeps the middleware callable' do + hook = ->(builder) { builder } + expect(build(middleware: hook).middleware).to be(hook) + end + + it 'rejects middleware that cannot be called' do + expect { build(middleware: 'not callable') } + .to raise_error(ZammadAPI::ConfigurationError, 'config middleware needs to respond to call') + end + + it 'accepts any callable, not only a proc' do + callable = Class.new { def call(builder) = builder }.new + expect(build(middleware: callable).middleware).to be(callable) + end + end + + describe 'the logger' do + it 'keeps the logger it is given' do + logger = Logger.new(IO::NULL) + expect(build(logger: logger).logger).to be(logger) + end + + it 'accepts anything that logs at debug, not only a Logger' do + logger = Class.new { def debug(...) = nil }.new + expect(build(logger: logger).logger).to be(logger) + end + + # 1.x took `logger: true` as "log to $stderr". + it 'rejects a boolean, as 1.x accepted' do + expect { build(logger: true) } + .to raise_error(ZammadAPI::ConfigurationError, 'config logger needs to respond to debug') + end + end + + describe 'numeric validation' do + # Complex is a Numeric and answers neither `positive?` nor `>`, so this + # left a NoMethodError where every other rejected option raises the error + # building a client is documented to need. + it 'rejects a Numeric that cannot be compared, as a configuration error' do + expect { build(timeout: Complex(1, 2)) } + .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') + end + + it 'rejects a zero timeout' do + expect { build(timeout: 0) } + .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') + end + + it 'rejects a negative open_timeout' do + expect { build(open_timeout: -1) } + .to raise_error(ZammadAPI::ConfigurationError, 'config open_timeout needs to be a positive number') + end + + it 'rejects a non-numeric timeout' do + expect { build(timeout: 'soon') } + .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') + end + + it 'rejects negative retries' do + expect { build(retries: -1) } + .to raise_error(ZammadAPI::ConfigurationError, 'config retries needs to be a non-negative integer') + end + + it 'allows disabling retries' do + expect(build(retries: 0).retries).to eq(0) + end + end + + describe '#inspect' do + subject(:rendered) { build(http_token: nil, user: 'u', password: 'pw-s3cret').inspect } + + it 'redacts the password' do + expect(rendered).not_to include('pw-s3cret') + end + + it 'redacts the access token' do + expect(build(http_token: 'tok-s3cret').inspect).not_to include('tok-s3cret') + end + + it 'redacts the OAuth2 token' do + expect(build(http_token: nil, oauth2_token: 'oauth-s3cret').inspect).not_to include('oauth-s3cret') + end + + it 'marks redacted values' do + expect(rendered).to include('password=[REDACTED]') + end + + it 'keeps non-sensitive values readable' do + expect(rendered).to include('url="https://zammad.example.com/"') + end + + it 'does not dump the logger internals' do + expect(rendered).to include('logger=#') + end + + it 'does not dump the middleware internals' do + expect(build(middleware: ->(builder) { builder }).inspect).to include('middleware=#') + end + + it 'still shows that no middleware is configured' do + expect(rendered).to include('middleware=nil') + end + + it 'is used for to_s as well' do + config = build(http_token: nil, user: 'u', password: 'hunter2') + expect(config.to_s).to eq(config.inspect) + end + + context 'with an authenticated proxy' do + subject(:rendered) { build(proxy: 'http://puser:pproxy-s3cret@proxy.test:8080').inspect } + + it 'redacts the proxy credentials' do + expect(rendered).not_to include('pproxy-s3cret') + end + + it 'keeps the proxy host visible' do + expect(rendered).to include('proxy.test:8080') + end + + it 'marks the redacted userinfo' do + expect(rendered).to include('proxy="http://[REDACTED]@proxy.test:8080"') + end + end + + it 'redacts a proxy password carrying an unencoded @' do + rendered = build(proxy: 'http://puser:pa@ss-s3cret@proxy.test:8080').inspect + + expect(rendered).to include('proxy="http://[REDACTED]@proxy.test:8080"') + expect(rendered).not_to include('ss-s3cret') + end + + # A password is not obliged to be URL-safe, and each of these ends the + # authority early as far as the syntax goes: `user:p` is all that is left + # of it, with no @ in it, so a search bounded by the authority found no + # credential to blank and printed the password. + { + 'a #' => 'http://puser:pa#ss-s3cret@proxy.test:8080', + 'a /' => 'http://puser:pa/ss-s3cret@proxy.test:8080', + 'a ?' => 'http://puser:pa?ss-s3cret@proxy.test:8080' + }.each do |character, proxy| + it "redacts a proxy password carrying #{character}" do + rendered = build(proxy: proxy).inspect + + expect(rendered).to include('proxy="http://[REDACTED]@proxy.test:8080"') + expect(rendered).not_to match(/pa.ss|s3cret/) + end + end + + it 'redacts such a password on a proxy configured without a scheme' do + rendered = build(proxy: 'puser:pa#ss-s3cret@proxy.test:8080').inspect + + expect(rendered).to include('proxy="[REDACTED]@proxy.test:8080"') + expect(rendered).not_to include('s3cret') + end + + it 'leaves a proxy without credentials alone' do + expect(build(proxy: 'http://proxy.test:8080').inspect).to include('proxy="http://proxy.test:8080"') + end + + # The shape an http_proxy style setting is copied out of. Anchored on a + # `://` lookbehind, the redaction never fired and the password went into + # every log line and exception report this class promises to be safe in. + it 'redacts the credentials of a proxy configured without a scheme' do + rendered = build(proxy: 'puser:pproxy-s3cret@proxy.test:8080').inspect + + expect(rendered).to include('proxy="[REDACTED]@proxy.test:8080"') + expect(rendered).not_to include('pproxy-s3cret') + end + + it 'leaves a scheme-less proxy without credentials alone' do + expect(build(proxy: 'proxy.test:8080').inspect).to include('proxy="proxy.test:8080"') + end + + it 'leaves a url without credentials alone' do + expect(build(url: 'https://zammad.example.com/').inspect).to include('url="https://zammad.example.com/"') + end + end + + # pp has a printer of its own for a Data object, which renders the members + # without going through #inspect - and pp is what IRB and the Rails console + # print a value with. + describe 'pretty printing' do + it 'redacts the password' do + expect(build(http_token: nil, user: 'u', password: 'pw-s3cret').pretty_inspect).not_to include('pw-s3cret') + end + + it 'redacts the access token' do + expect(build(http_token: 'tok-s3cret').pretty_inspect).not_to include('tok-s3cret') + end + + it 'redacts the OAuth2 token' do + expect(build(http_token: nil, oauth2_token: 'oauth-s3cret').pretty_inspect).not_to include('oauth-s3cret') + end + + it 'redacts the proxy credentials' do + expect(build(proxy: 'http://puser:pproxy-s3cret@proxy.test:8080').pretty_inspect).not_to include('pproxy-s3cret') + end + + it 'prints what inspect prints' do + config = build(http_token: nil, user: 'u', password: 'hunter2') + expect(config.pretty_inspect).to eq("#{config.inspect}\n") + end + + it 'stays redacted nested inside another structure' do + expect({ config: build(http_token: 'tok-s3cret') }.pretty_inspect).not_to include('tok-s3cret') + end + end + + # Faraday turns the userinfo of a URL into a Basic Authorization header, and + # its authorization middleware leaves a header that is already set alone - + # so the credentials in the URL were sent in place of the configured ones. + describe 'credentials in the instance url' do + it 'refuses them' do + expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials of its own/) + end + + it 'says where they belong instead' do + expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError, /pass user: and password:/) + end + + it 'keeps the password out of the message' do + expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('url-s3cret') } + end + + it 'still names the instance in the message' do + expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError, %r{https://\[REDACTED\]@zammad\.example\.com/}) + end + + it 'refuses them beside basic authentication too, where they would win just the same' do + expect { build(url: 'https://old:creds@zammad.example.com/', http_token: nil, user: 'u', password: 'p') } + .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials of its own/) + end + + it 'refuses a user name without a password' do + expect { build(url: 'https://admin@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials of its own/) + end + + it 'accepts a url whose path merely contains an @' do + expect(build(url: 'https://zammad.example.com/tenant@acme/').url).to eq('https://zammad.example.com/tenant@acme/') + end + end + + describe '#redacted' do + it 'blanks inline credentials' do + expect(build.redacted('https://admin:s3cret@zammad.example.com/')) + .to eq('https://[REDACTED]@zammad.example.com/') + end + + # Anchoring on the first @ left the tail of the password in the rendered + # URL, which is interpolated into every ConnectionError message. + it 'blanks a password carrying an unencoded @' do + expect(build.redacted('https://admin:pa@ss-s3cret@zammad.example.com/')) + .to eq('https://[REDACTED]@zammad.example.com/') + end + + # The same three characters, in the instance url. URI cannot read these, + # so they are not refused the way a readable url with credentials is, and + # stay printable until the connection rejects them. + it 'blanks a password carrying a #, which ends the authority early' do + expect(build.redacted('https://admin:pa#ss-s3cret@zammad.example.com/')) + .to eq('https://[REDACTED]@zammad.example.com/') + end + + it 'blanks a password carrying a /' do + expect(build.redacted('https://admin:pa/ss-s3cret@zammad.example.com/')) + .to eq('https://[REDACTED]@zammad.example.com/') + end + + it 'blanks a password carrying a ?' do + expect(build.redacted('https://admin:pa?ss-s3cret@zammad.example.com/')) + .to eq('https://[REDACTED]@zammad.example.com/') + end + + it 'blanks a password carrying both an @ and a /' do + expect(build.redacted('https://admin:pa@ss/w0rd@zammad.example.com/')) + .to eq('https://[REDACTED]@zammad.example.com/') + end + + it 'leaves a host and port alone' do + expect(build.redacted('https://zammad.example.com:8443/helpdesk/')).to eq('https://zammad.example.com:8443/helpdesk/') + end + + it 'leaves an IPv6 host alone' do + expect(build.redacted('http://[::1]:3128')).to eq('http://[::1]:3128') + end + + # A colon cannot tell a port from a password, and `user:8443/s3cret@host` + # is a password with a slash in it just as much as it is a port and a + # path. Blanking too much shows a wrong host; blanking too little shows a + # password. + it 'blanks rather than guesses where a colon could be either a port or a password' do + expect(build.redacted('https://zammad.example.com:8443/tenant@acme/')).to eq('https://[REDACTED]@acme/') + end + end + + describe '#redacted_url' do + it 'blanks a password the url is too malformed to be refused for' do + expect(build(url: 'https://admin:pa#ss-s3cret@zammad.example.com/').redacted_url) + .to eq('https://[REDACTED]@zammad.example.com/') + end + + it 'leaves an @ in the path alone' do + expect(build(url: 'https://zammad.example.com/tenant@acme/').redacted_url) + .to eq('https://zammad.example.com/tenant@acme/') + end + + # Bounded only by the path, the match crossed into the query string and + # rendered a host that does not exist - into every ConnectionError message. + it 'leaves an @ in a query string alone' do + expect(build(url: 'https://zammad.example.com?tenant=a@acme').redacted_url) + .to eq('https://zammad.example.com/?tenant=a@acme') + end + + it 'leaves an @ in a fragment alone' do + expect(build(url: 'https://zammad.example.com#a@b').redacted_url) + .to eq('https://zammad.example.com/#a@b') + end + + it 'leaves a url without credentials alone' do + expect(build(url: 'https://zammad.example.com/').redacted_url).to eq('https://zammad.example.com/') + end + end + + describe '#with' do + it 'changes an option' do + expect(build.with(timeout: 5).timeout).to eq(5) + end + + it 'keeps the rest' do + expect(build(proxy: 'http://proxy.test:8080').with(timeout: 5).proxy).to eq('http://proxy.test:8080') + end + + it 're-validates' do + expect { build.with(retries: -1) }.to raise_error(ZammadAPI::ConfigurationError, /non-negative integer/) + end + + it 'replaces the authentication scheme rather than adding a second one' do + derived = build.with(user: 'u', password: 'p') + expect(derived.to_h.slice(:http_token, :user, :password)).to eq({ http_token: nil, user: 'u', password: 'p' }) + end + + it 'does not read an explicit nil as naming a scheme' do + expect(build.with(oauth2_token: nil).authentication_scheme).to eq(:http_token) + end + + # The refusal of two schemes is what makes this necessary: merged beside + # the token, the new credential would no longer be ignored but refused. + it 'can switch to any scheme from any other without naming two at once' do + switched = build.with(oauth2_token: 'o').with(user: 'u', password: 'p').with(http_token: 't') + expect(switched.to_h.slice(:http_token, :oauth2_token, :user, :password)) + .to eq({ http_token: 't', oauth2_token: nil, user: nil, password: nil }) + end + + it 'still refuses two schemes named in one call' do + expect { build.with(oauth2_token: 'o', user: 'u', password: 'p') } + .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate/) + end + end + + describe '.merge_options' do + it 'lays the overrides over the options' do + expect(described_class.merge_options({ url: 'a', timeout: 1 }, { timeout: 2 })).to eq({ url: 'a', timeout: 2 }) + end + + it 'drops the credentials an override replaces' do + expect(described_class.merge_options({ http_token: 't' }, { oauth2_token: 'o' })).to eq({ oauth2_token: 'o' }) + end + + it 'keeps the other half of a scheme the override names' do + expect(described_class.merge_options({ user: 'u', password: 'old' }, { password: 'new' })) + .to eq({ user: 'u', password: 'new' }) + end + + it 'leaves the credentials alone when the overrides name none' do + expect(described_class.merge_options({ http_token: 't' }, { timeout: 2 })).to eq({ http_token: 't', timeout: 2 }) + end + end + + describe 'immutability of string members' do + it 'freezes the url' do + expect(build.url).to be_frozen + end + + it 'does not share the url with the caller' do + supplied = +'https://zammad.example.com/' + config = described_class.new(url: supplied, http_token: 'tok') + supplied << 'mutated' + expect(config.url).to eq('https://zammad.example.com/') + end + + it 'freezes the credentials' do + config = build(user: 'u', password: +'pw', http_token: nil) + expect(config.password).to be_frozen + end + + it 'freezes the proxy' do + expect(build(proxy: +'http://proxy.test:8080').proxy).to be_frozen + end + + it 'freezes the user agent' do + expect(build(user_agent: +'custom/1.0').user_agent).to be_frozen + end + end + + it 'is immutable' do + expect(build).to be_frozen + end + + # Every other option is checked up front; these three were not, so a bad + # value escaped the ConfigurationError that building a client is documented + # to need - two as a bare NoMethodError, one by silently staying on. + describe 'option validation' do + it 'rejects a proxy that is not a string' do + expect { build(proxy: URI('http://user:secret@proxy:3128')) } + .to raise_error(ZammadAPI::ConfigurationError, 'config proxy needs to be a string, got URI::HTTP') + end + + # The whole point of refusing it: a URI reached String#sub inside #inspect + # and died there, so the object this class documents as safe to log raised + # at the moment something logged it. + it 'keeps a proxy-bearing config renderable' do + expect { build(proxy: 'http://user:secret@proxy:3128').inspect }.not_to raise_error + end + + it 'redacts the credentials in a proxy it renders' do + rendered = build(proxy: 'http://user:secret@proxy:3128').inspect + + expect(rendered).to include('proxy="http://[REDACTED]@proxy:3128"') + expect(rendered).not_to include('secret') + end + + it 'rejects an adapter that cannot be a symbol' do + expect { build(adapter: 1) } + .to raise_error(ZammadAPI::ConfigurationError, 'config adapter needs to be a symbol or a string, got Integer') + end + + # `adapter: true` is the 1.x-flavoured mistake: it answered to_sym on + # nothing and raised NoMethodError from inside the constructor. + it 'rejects a boolean adapter' do + expect { build(adapter: true) } + .to raise_error(ZammadAPI::ConfigurationError, /config adapter needs to be a symbol or a string/) + end + + it 'accepts an adapter named as a string' do + expect(build(adapter: 'net_http').adapter).to eq(:net_http) + end + + # Read from an environment variable this is the string "false", which is + # truthy, so verification stayed on while the caller believed they had + # turned it off. + it 'rejects an ssl_verify that is not a boolean' do + expect { build(ssl_verify: 'false') } + .to raise_error(ZammadAPI::ConfigurationError, 'config ssl_verify needs to be true or false, got "false"') + end + + it 'accepts ssl_verify: false' do + expect(build(ssl_verify: false).ssl_verify).to be(false) + end + end +end diff --git a/spec/unit/zammad_api/query_encoder_spec.rb b/spec/unit/zammad_api/query_encoder_spec.rb new file mode 100644 index 0000000..05e6369 --- /dev/null +++ b/spec/unit/zammad_api/query_encoder_spec.rb @@ -0,0 +1,180 @@ +# frozen_string_literal: true + +# What is asserted here is the order the pairs of a query are written in, +# because that order is all a query string has to say where one element of a +# list ends. Rack, and the parser Rails 8.1 has of its own, fill the element +# they are on until a pair names a place in it that is already taken, and +# begin a new one there. The orders below were read back with both, from the +# Zammad this gem is developed against, and came out as written. +RSpec.describe ZammadAPI::QueryEncoder do + def written(query) = URI.decode_www_form(described_class.encode(ZammadAPI::Transport.stringify_query(query))) + + def faraday(query) = Faraday::NestedParamsEncoder.encode(ZammadAPI::Transport.stringify_query(query)) + + let(:by_group) { { name: 'ticket.group_id', operator: 'is', value: [1] } } + let(:by_title) { { name: 'ticket.title', operator: 'contains', value: 'x' } } + + describe '.encode' do + # Everything but a list of Hashes that differ is written as it was. + { + 'plain values' => { query: 'smith', page: 2, expand: true }, + 'a list of plain values' => { ids: [3, 1, 2] }, + 'a Hash of lists' => { group_ids: { 3 => %w[read change], 4 => 'full' } }, + 'a condition keyed by name' => { condition: { 'ticket.state_id' => { operator: 'is', value: [1, 2] } } }, + 'a list of Hashes alike' => { condition: { operator: 'AND', conditions: [{ name: 'a', operator: 'is', value: [1] }, { name: 'b', operator: 'is', value: [2] }] } }, + 'a list with nothing in it' => { ids: [] }, + 'a value that needs escaping' => { query: 'a b&c=d[e]' }, + 'a list of Hashes of Hashes' => { list: [{ a: { x: 1 } }, { a: { x: 2 } }] }, + 'plain values among the Hashes' => { list: [1, { a: 1 }, 2, { b: 3 }] } + }.each do |name, query| + it "writes #{name} as Faraday does" do + expect(described_class.encode(ZammadAPI::Transport.stringify_query(query))).to eq(faraday(query)) + end + end + + # A condition and a group of conditions share `operator` and nothing + # else. Written `conditions` first, the group was read into the condition + # before it, and what was left of it began an element holding nothing but + # its operator. + it 'begins a group of conditions with the key it shares with the condition before it' do + condition = { operator: 'OR', conditions: [{ name: 'ticket.state_id', operator: 'is', value: [2] }, { operator: 'AND', conditions: [by_group, by_title] }] } + + expect(written(condition: condition)).to eq( + [ + ['condition[conditions][][name]', 'ticket.state_id'], + ['condition[conditions][][operator]', 'is'], + ['condition[conditions][][value][]', '2'], + ['condition[conditions][][operator]', 'AND'], + ['condition[conditions][][conditions][][name]', 'ticket.group_id'], + ['condition[conditions][][conditions][][operator]', 'is'], + ['condition[conditions][][conditions][][value][]', '1'], + ['condition[conditions][][conditions][][name]', 'ticket.title'], + ['condition[conditions][][conditions][][operator]', 'contains'], + ['condition[conditions][][conditions][][value]', 'x'], + ['condition[operator]', 'OR'] + ] + ) + end + + # The other way round: `name` sorts first, and the group before has none. + it 'begins a condition with the key it shares with the group before it' do + condition = { operator: 'OR', conditions: [{ operator: 'AND', conditions: [by_group] }, { name: 'ticket.state_id', operator: 'is', value: [2] }] } + + expect(written(condition: condition).last(4)).to eq( + [ + ['condition[conditions][][operator]', 'is'], + ['condition[conditions][][name]', 'ticket.state_id'], + ['condition[conditions][][value][]', '2'], + ['condition[operator]', 'OR'] + ] + ) + end + + it 'begins every group in a row of them with its operator' do + condition = { conditions: [{ operator: 'OR', conditions: [by_group] }, { operator: 'NOT', conditions: [by_title] }, { operator: 'AND', conditions: [by_group] }] } + + expect(written(condition: condition).map(&:first).each_cons(2).count { |before, pair| pair == 'condition[conditions][][operator]' && before != pair }) + .to eq(2) + end + + # The shared place may be further down, and every key on the way to it + # goes first. + it 'begins an element with a value it shares further down' do + list = [{ a: { x: 1, y: { z: 1 } }, b: [1] }, { a: { w: [2], y: { q: 3, z: 2 } }, c: 4 }] + + expect(written(list: list).drop(3)).to eq([['list[][a][y][z]', '2'], ['list[][a][y][q]', '3'], ['list[][a][w][]', '2'], ['list[][c]', '4']]) + end + + it 'writes nothing for no query' do + expect(described_class.encode(nil)).to be_nil + end + + it 'writes an empty string for a query with nothing in it' do + expect(described_class.encode({})).to eq('') + end + end + + describe '.decode' do + it 'reads a query string the way Faraday does' do + expect(described_class.decode('a[]=1&a[]=2&b[c]=3')).to eq('a' => %w[1 2], 'b' => { 'c' => '3' }) + end + end + + describe '.lead_path' do + it 'is the first key both have that holds a plain value' do + expect(described_class.lead_path({ 'conditions' => [], 'operator' => 'AND' }, { 'name' => 'a', 'operator' => 'is' })).to eq(['operator']) + end + + it 'is not needed after something that is not a Hash' do + expect(described_class.lead_path({ 'a' => '1' }, 'x')).to be_nil + end + + it 'does not go through a list' do + expect(described_class.lead_path({ 'a' => ['1'] }, { 'a' => ['2'] })).to be_nil + end + + it 'goes through a Hash to a place the element before has too' do + expect(described_class.lead_path({ 'a' => { 'x' => '1' } }, { 'a' => { 'x' => '2' } })).to eq(%w[a x]) + end + + it 'does not go through a Hash where the element before holds a plain value' do + expect(described_class.lead_path({ 'a' => { 'x' => '1' } }, { 'a' => '2' })).to be_nil + end + + it 'is nil where the two share no key' do + expect(described_class.lead_path({ 'a' => '1' }, { 'b' => '2' })).to be_nil + end + + # Nothing is written for an empty Hash, so Rails never saw the key in the + # element before, and a pair naming it is read into that element. + it 'does not take a key the element before holds an empty Hash under' do + expect(described_class.lead_path({ 'a' => '2', 'c' => '3' }, { 'a' => {}, 'b' => '1' })).to be_nil + end + + it 'does not take one further down either' do + expect(described_class.lead_path({ 'a' => { 'x' => '2' } }, { 'a' => { 'x' => {} } })).to be_nil + end + + it 'takes another key the two share instead' do + expect(described_class.lead_path({ 'a' => '2', 'b' => '3' }, { 'a' => {}, 'b' => '1' })).to eq(['b']) + end + end + + describe '.misread' do + it 'is nil for a plain value' do + expect(described_class.misread('x', { 'a' => '1' })).to be_nil + end + + it 'is nil for the first Hash of a list' do + expect(described_class.misread({ 'a' => ['1'] }, nil)).to be_nil + end + + it 'is nil for a Hash after a plain value' do + expect(described_class.misread({ 'a' => '1' }, 'x')).to be_nil + end + + it 'is nil for a Hash that shares a plain value with the one before' do + expect(described_class.misread({ 'operator' => 'AND', 'conditions' => [] }, { 'operator' => 'is', 'name' => 'a' })).to be_nil + end + + it 'names a Hash that would be read into the one before' do + expect(described_class.misread({ 'b' => '2' }, { 'a' => '1' })).to eq(:merged) + end + + it 'names a Hash nothing is written for' do + expect(described_class.misread({}, nil)).to eq(:empty) + end + + it 'names a Hash holding nothing but such Hashes' do + expect(described_class.misread({ 'a' => { 'b' => {} } }, nil)).to eq(:empty) + end + + it 'names a Hash whose only shared key holds an empty Hash in the element before' do + expect(described_class.misread({ 'a' => '2', 'c' => '3' }, { 'a' => {}, 'b' => '1' })).to eq(:merged) + end + + it 'names a list directly inside a list' do + expect(described_class.misread(%w[1 2], nil)).to eq(:list) + end + end +end diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb new file mode 100644 index 0000000..1390e47 --- /dev/null +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -0,0 +1,1069 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::ResourceProxy do + subject(:proxy) { client.groups } + + let(:client) { unit_client } + let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } + + it 'exposes the resource class' do + expect(proxy.resource_class).to eq(ZammadAPI::Resources::Group) + end + + describe '#new' do + it 'builds an unsaved record' do + expect(proxy.new(name: 'Support')).to be_new_record + end + + it 'does not talk to the server' do + proxy.new(name: 'Support') + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'accepts no attributes at all' do + expect(proxy.new.attributes).to eq({}) + end + end + + describe '#find' do + it 'requests the record with expanded attributes' do + stub = stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }).to_return(json_response({ id: 1, name: 'Users' })) + + proxy.find(1) + expect(stub).to have_been_requested + end + + it 'returns a persisted record' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) + + expect(proxy.find(1)).to be_persisted + end + + it 'maps the attributes' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) + + expect(proxy.find(1).name).to eq('Users') + end + + it 'raises NotFoundError for an unknown id' do + stub_request(:get, "#{url}/404").with(query: hash_including({})).to_return(json_response({ error: 'not found' }, status: 404)) + + expect { proxy.find(404) }.to raise_error(ZammadAPI::NotFoundError) + end + + it 'raises ParseError when the response is not an object' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + + expect { proxy.find(1) }.to raise_error(ZammadAPI::ParseError, /expected a JSON object, got Array/) + end + end + + describe 'ids in the request path' do + it 'escapes a traversal instead of reaching another endpoint' do + stub = stub_request(:get, "#{url}/1%2F..%2F..%2Fapi%2Fv1%2Fusers%2F1") + .with(query: { 'expand' => 'true' }) + .to_return(json_response({ error: 'not found' }, status: 404)) + + expect { proxy.find('1/../../api/v1/users/1') }.to raise_error(ZammadAPI::NotFoundError) + expect(stub).to have_been_requested + expect(a_request(:get, %r{/api/v1/users/1\z})).not_to have_been_made + end + + it 'escapes the id on destroy too' do + stub = stub_request(:delete, "#{url}/1%2F..%2F..%2Fapi%2Fv1%2Fusers%2F1").to_return(status: 200, body: '') + + proxy.destroy('1/../../api/v1/users/1') + expect(stub).to have_been_requested + end + + it 'escapes the id a record uses for its own writes' do + record = ZammadAPI::Resources::Group.from_response(client.instance_variable_get(:@transport), { id: '1/../../api/v1/users/1' }) + stub = stub_request(:delete, "#{url}/1%2F..%2F..%2Fapi%2Fv1%2Fusers%2F1").to_return(status: 200, body: '') + + record.destroy + expect(stub).to have_been_requested + end + + it 'rejects an empty id rather than requesting the index' do + expect { proxy.find('') }.to raise_error(ArgumentError, /record id is required/) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end + + describe '#create' do + it 'posts the attributes' do + stub = stub_request(:post, url) + .with(query: { 'expand' => 'true' }, body: '{"name":"Support"}') + .to_return(json_response({ id: 5, name: 'Support' }, status: 201)) + + proxy.create(name: 'Support') + expect(stub).to have_been_requested + end + + it 'returns the persisted record' do + stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 5, name: 'Support' }, status: 201)) + + expect(proxy.create(name: 'Support')).to be_persisted + end + + it 'raises ValidationError when Zammad rejects the attributes' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422)) + + expect { proxy.create({}) }.to raise_error(ZammadAPI::ValidationError, /Name is required/) + end + end + + describe '#find_by' do + let(:search_url) { "#{url}/search" } + + it 'searches instead of filtering an index that cannot filter' do + stub = stub_request(:get, search_url) + .with(query: hash_including('query' => 'Users')) + .to_return(json_response([{ id: 1, name: 'Users' }])) + + proxy.find_by(name: 'Users') + + expect(stub).to have_been_requested + expect(a_request(:get, url).with(query: hash_including({}))).not_to have_been_made + end + + it 'returns the matching record' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }])) + + expect(proxy.find_by(name: 'Users').id).to eq(1) + end + + # Zammad's search sorts by updated_at, newest first, not by relevance, so + # the exact match can sit on any page of hits. Reading only the first one + # answered nil for a record that exists, and find_by(...) || create(...) + # then created its duplicate. + context 'when more records match the term than one page holds' do + let(:page_size) { ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE } + let(:others) { Array.new(page_size) { { id: it + 1, name: 'Users Archive' } } } + + def stub_page(number, records) + stub_request(:get, search_url) + .with(query: hash_including('page' => number.to_s)) + .to_return(json_response(records)) + end + + it 'finds a match on a later page' do + stub_page(1, others) + stub_page(2, [{ id: 999, name: 'Users' }]) + + expect(proxy.find_by(name: 'Users').id).to eq(999) + end + + it 'answers nil only once every page has been read' do + stub_page(1, others) + stub_page(2, others.map { it.merge(id: it[:id] + page_size) }) + last = stub_page(3, []) + + expect(proxy.find_by(name: 'Users')).to be_nil + expect(last).to have_been_requested + end + + it 'reads no further than the page the match is on' do + stub_page(1, [*others.first(page_size - 1), { id: 999, name: 'Users' }]) + second = stub_page(2, []) + + proxy.find_by(name: 'Users') + expect(second).not_to have_been_requested + end + end + + it 'asks for hits at the size the search endpoint serves' do + stub = stub_request(:get, search_url) + .with(query: hash_including('page' => '1', 'per_page' => ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE.to_s)) + .to_return(json_response([{ id: 1, name: 'Users' }])) + + proxy.find_by(name: 'Users') + + expect(stub).to have_been_requested + end + + it 'returns a persisted record' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }])) + + expect(proxy.find_by(name: 'Users')).to be_persisted + end + + it 'skips a hit the search returned that does not actually match' do + stub_request(:get, search_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users Archive' }, { id: 2, name: 'Users' }])) + + expect(proxy.find_by(name: 'Users').id).to eq(2) + end + + it 'returns nil when the search matched nothing this record carries' do + stub_request(:get, search_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users Archive' }]), json_response([])) + + expect(proxy.find_by(name: 'Users')).to be_nil + end + + # Quoting a value that carries search syntax, to have it looked for rather + # than obeyed, cost more than it bought: an instance searching without + # Elasticsearch matches the term literally through a SQL LIKE, so the + # quotes became characters the value had to contain, and a hyphen is + # syntax - so `find_by(name: 'support-eu')` found nothing at all there. + it 'sends a value carrying search syntax as it is' do + stub = stub_request(:get, search_url) + .with(query: hash_including('query' => 'support-eu')) + .to_return(json_response([])) + + proxy.find_by(name: 'support-eu') + + expect(stub).to have_been_requested + end + + it 'sends a value that reads as a boolean query as it is' do + stub = stub_request(:get, search_url) + .with(query: hash_including('query' => 'a AND b')) + .to_return(json_response([])) + + proxy.find_by(name: 'a AND b') + + expect(stub).to have_been_requested + end + + # Whatever the term meant to the backend, the answer is decided here. + it 'still matches the record exactly' do + stub_request(:get, search_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'a AND b' }])) + + expect(proxy.find_by(name: 'a AND b').id).to eq(1) + end + + it 'returns nil when nothing matched' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) + + expect(proxy.find_by(name: 'Nope')).to be_nil + end + + it 'matches on every attribute given, not just one' do + stub_request(:get, search_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users', active: false }, { id: 2, name: 'Users', active: true }])) + + expect(proxy.find_by(name: 'Users', active: true).id).to eq(2) + end + + # What a caller is promised: a record carrying both values comes back. + # The spec here asserted the query string instead - that "Users Support" + # went out - which a stub answers whatever it is handed, so nothing could + # see that an instance without Elasticsearch matches that term through a + # SQL LIKE per column and so finds neither of them. + it 'finds a record by two string attributes' do + stub_request(:get, search_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users', note: 'Other' }, { id: 2, name: 'Users', note: 'Support' }])) + + expect(proxy.find_by(name: 'Users', note: 'Support').id).to eq(2) + end + + # The fence for the above: one value goes out, never the values joined. + # Joined, the term is one no single column holds. + it 'searches a single value rather than joining them' do + stub = stub_request(:get, search_url) + .with(query: hash_including('query' => 'Support')) + .to_return(json_response([])) + + proxy.find_by(name: 'Users', note: 'Support') + expect(stub).to have_been_requested + end + + it 'searches the longest value, as the most selective of them' do + stub = stub_request(:get, search_url) + .with(query: hash_including('query' => 'a-very-specific-note')) + .to_return(json_response([])) + + proxy.find_by(name: 'Users', note: 'a-very-specific-note') + expect(stub).to have_been_requested + end + + # A non-string went to the search engine as the word it prints as, so + # `find_by(name: 'Users', active: true)` searched for "Users true" and + # matched nothing. + it 'keeps a non-string value out of the search term, and still matches on it' do + stub = stub_request(:get, search_url) + .with(query: hash_including('query' => 'Users')) + .to_return(json_response([{ id: 1, name: 'Users', active: false }, { id: 2, name: 'Users', active: true }])) + + expect(proxy.find_by(name: 'Users', active: true).id).to eq(2) + expect(stub).to have_been_requested + end + + it 'stops at the first match rather than walking the rest of the search' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }])) + + proxy.find_by(name: 'Users') + expect(a_request(:get, search_url).with(query: hash_including({}))).to have_been_made.once + end + + it 'rejects a lookup with no attribute at all' do + expect { proxy.find_by }.to raise_error(ArgumentError, /at least one attribute/) + end + + # find_by used to raise here, which left it working on four resources out + # of seven, and the caller writing all.detect by hand - the walk this makes. + context 'with a resource Zammad routes no search endpoint for' do + let(:states_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_states" } + + before do + stub_request(:get, states_url).with(query: hash_including('page' => '1')) + .to_return(json_response([{ id: 1, name: 'new' }, { id: 2, name: 'open' }])) + stub_request(:get, states_url).with(query: hash_including('page' => '2')).to_return(json_response([])) + end + + it 'walks the records and answers with the one that matches' do + expect(client.ticket_states.find_by(name: 'open').id).to eq(2) + end + + it 'answers nil when none does' do + expect(client.ticket_states.find_by(name: 'closed')).to be_nil + end + + it 'never asks the search endpoint, which would answer 404' do + client.ticket_states.find_by(name: 'open') + expect(a_request(:get, "#{states_url}/search").with(query: hash_including({}))).not_to have_been_made + end + + it 'stops at the page the match is on' do + client.ticket_states.find_by(name: 'new') + expect(a_request(:get, states_url).with(query: hash_including('page' => '2'))).not_to have_been_made + end + + it 'matches on a value of any type' do + expect(client.ticket_states.find_by(id: 2).name).to eq('open') + end + end + + # A value that is not a string cannot be searched on - Zammad matches + # words, so it would go out as the word it prints as - and this used to + # raise for want of one. + context 'with no string value to search on' do + before do + stub_request(:get, url).with(query: hash_including('page' => '1')) + .to_return(json_response([{ id: 1, name: 'Users', active: false }, { id: 2, name: 'Support', active: true }])) + stub_request(:get, url).with(query: hash_including('page' => '2')).to_return(json_response([])) + end + + it 'walks the index and answers with the first record that matches' do + expect(proxy.find_by(active: true).id).to eq(2) + end + + it 'does not search for the word the value prints as' do + proxy.find_by(active: true) + expect(a_request(:get, search_url).with(query: hash_including({}))).not_to have_been_made + end + + it 'answers nil once the whole index has been read' do + expect(proxy.find_by(active: nil)).to be_nil + expect(a_request(:get, url).with(query: hash_including('page' => '2'))).to have_been_made + end + + it 'walks for a string value that is blank, which is nothing to search on either' do + expect(proxy.find_by(name: ' ', active: true)).to be_nil + expect(a_request(:get, search_url).with(query: hash_including({}))).not_to have_been_made + end + end + + # record[key] is nil for an attribute a record does not carry, so a nil + # value matched every record a misspelled name was asked of. + it 'does not match nil against an attribute the record does not carry' do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users' }]), json_response([])) + + expect(proxy.find_by(nmae: nil)).to be_nil + end + + it 'does match nil against an attribute the record carries as nil' do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users', note: nil }]), json_response([])) + + expect(proxy.find_by(note: nil).id).to eq(1) + end + end + + describe '#find_by!' do + let(:search_url) { "#{url}/search" } + + it 'returns the matching record' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }])) + + expect(proxy.find_by!(name: 'Users').id).to eq(1) + end + + it 'raises NotFoundError when nothing matched' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) + + expect { proxy.find_by!(name: 'Nope') }.to raise_error(ZammadAPI::NotFoundError) + end + + it 'raises when the search answered with a record that does not match' do + stub_request(:get, search_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users Archive' }]), json_response([])) + + expect { proxy.find_by!(name: 'Users') }.to raise_error(ZammadAPI::NotFoundError) + end + + it 'names the query and the resource in the message' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) + + expect { proxy.find_by!(name: 'Nope', active: true) } + .to raise_error("Can't find object by name and active (ZammadAPI::Resources::Group): no record matched") + end + + it 'does not put the values it searched for in the message' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) + + expect { proxy.find_by!(name: 'secret-group') } + .to raise_error(ZammadAPI::NotFoundError) { |error| expect(error.message).not_to include('secret-group') } + end + end + + describe '#exists?' do + it 'is true when the record is there' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect(proxy.exists?(1)).to be(true) + end + + it 'is false for a 404' do + stub_request(:get, "#{url}/404").with(query: hash_including({})) + .to_return(json_response({ error: 'not found' }, status: 404)) + + expect(proxy.exists?(404)).to be(false) + end + + it 'does not swallow an authorization failure' do + stub_request(:get, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ error: 'no' }, status: 403)) + + expect { proxy.exists?(1) }.to raise_error(ZammadAPI::AuthorizationError) + end + end + + describe '#destroy' do + it 'deletes the record without fetching it first' do + stub = stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + + expect(proxy.destroy(1)).to be(true) + expect(stub).to have_been_requested + expect(a_request(:get, "#{url}/1")).not_to have_been_made + end + + it 'raises NotFoundError for an unknown id' do + stub_request(:delete, "#{url}/404").to_return(json_response({ error: 'not found' }, status: 404)) + + expect { proxy.destroy(404) }.to raise_error(ZammadAPI::NotFoundError) + end + end + + # What a collection over this endpoint fetches per request when nothing asks + # for another size: as many as the endpoint serves. Read off the resource + # rather than written out, so that these stubs follow the declaration. + def default_per_page = ZammadAPI::Resources::Group.page_limit + + describe '#all' do + it 'returns a collection' do + expect(proxy.all).to be_a(ZammadAPI::Collection) + end + + it 'defaults to the collection page size' do + stub = stub_request(:get, url) + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s }) + .to_return(json_response([])) + + proxy.all.to_a + expect(stub).to have_been_requested + end + + it 'takes no arguments' do + expect { proxy.all(active: true) }.to raise_error(ArgumentError) + end + end + + describe '#order' do + it 'returns a sorted collection of every record' do + stub = stub_request(:get, url) + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s, 'sort_by' => 'name', 'order_by' => 'desc' }) + .to_return(json_response([])) + + proxy.order(name: :desc).to_a + expect(stub).to have_been_requested + end + + it 'is the order of the collection all hands back' do + expect(proxy.order(:name).inspect).to eq(proxy.all.order(:name).inspect) + end + + it 'refuses a resource whose index endpoint does not sort' do + expect { unit_client.tickets.order(:created_at) } + .to raise_error(ArgumentError, %r{api/v1/tickets is always served in the same order}) + end + + # where took a sort and refused nearly everything else, which is why it + # went: the name promised a filter an index endpoint does not have. + it 'has no where to reach for instead' do + expect(proxy).not_to respond_to(:where) + end + end + + describe 'enumerating a proxy directly' do + def stub_page(page, records, per_page: default_per_page) + stub_request(:get, url) + .with(query: { 'expand' => 'true', 'page' => page.to_s, 'per_page' => per_page.to_s }) + .to_return(json_response(records)) + end + + # The walk confirms a short page with one more request, so a collection + # that fits in a single page needs the empty page after it. + def stub_last_page(page, records, per_page: default_per_page) + stub_page(page, records, per_page: per_page) + stub_page(page + 1, [], per_page: per_page) + end + + it 'is Enumerable' do + expect(proxy).to be_a(Enumerable) + end + + it 'yields every record from #each' do + stub_last_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + + expect(proxy.map(&:name)).to eq(%w[Users Support]) + end + + it 'walks pages, like the collection does' do + stub_page(1, Array.new(default_per_page) { { id: it + 1 } }) + stub_page(2, [{ id: default_per_page + 1 }]) + + expect(proxy.map(&:id).size).to eq(default_per_page + 1) + end + + # Forwarded to the collection rather than left to Enumerable#first, which + # would take one record off the front of a page sized for walking. + it 'reads one sized page for #first, without walking everything' do + stub_page(1, [{ id: 1 }], per_page: 1) + + expect(proxy.first.id).to eq(1) + expect(a_request(:get, url).with(query: hash_including({ 'page' => '2' }))).not_to have_been_made + end + + it 'returns an Enumerator from #each without a block' do + expect(proxy.each).to be_a(Enumerator) + end + + it 'supports a lazy chain' do + stub_page(1, [{ id: 1, active: true }, { id: 2, active: false }]) + + expect(proxy.lazy.select(&:active).first(1).map(&:id)).to eq([1]) + end + + it 'forwards #page to the collection' do + stub = stub_request(:get, url) + .with(query: hash_including({ 'page' => '3' })) + .to_return(json_response([])) + + proxy.page(3).to_a + expect(stub).to have_been_requested + end + + it 'forwards the page size #page was given' do + stub = stub_page(1, [], per_page: 5) + + proxy.page(1, per_page: 5).to_a + expect(stub).to have_been_requested + end + + it 'forwards #find_each' do + stub_last_page(1, [{ id: 1 }], per_page: 5) + + ids = [] + proxy.find_each(batch_size: 5) { ids << it.id } + expect(ids).to eq([1]) + end + + it 'forwards #in_batches' do + stub_last_page(1, [{ id: 1 }], per_page: 5) + + sizes = [] + proxy.in_batches(of: 5) { sizes << it.size } + expect(sizes).to eq([1]) + end + + it 'forwards #pluck' do + stub_last_page(1, [{ id: 1, name: 'Users' }]) + + expect(proxy.pluck(:name)).to eq(['Users']) + end + + it 'forwards #size' do + stub_last_page(1, [{ id: 1 }]) + + expect(proxy.size).to eq(1) + end + + it 'forwards #length' do + stub_last_page(1, [{ id: 1 }]) + + expect(proxy.length).to eq(1) + end + + it 'forwards #take, so it costs what #first costs' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + + expect(proxy.take(2).map(&:id)).to eq([1, 2]) + end + + it 'forwards #first' do + stub_page(1, [{ id: 1, name: 'Users' }], per_page: 1) + + expect(proxy.first.name).to eq('Users') + end + + it 'forwards #empty?' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) + + expect(proxy).to be_empty + end + + it 'keeps #find as a lookup by id rather than Enumerable#find' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) + + expect(proxy.find(1).name).to eq('Users') + end + + it 'leaves the block form to #detect' do + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + + expect(proxy.detect { it.name == 'Support' }.id).to eq(2) + end + + it 'does not pretend to be an array, so it is not flattened away' do + expect([proxy].flatten).to eq([proxy]) + end + end + + describe '#search' do + it 'refuses a resource Zammad routes no search endpoint for' do + expect { client.ticket_states.search('open') } + .to raise_error(ZammadAPI::Error, /routes no search endpoint for ZammadAPI::Resources::TicketState/) + end + + it 'refuses a search of ticket articles, which Zammad indexes but does not route' do + expect { client.ticket_articles.search('hello') } + .to raise_error(ZammadAPI::Error, /routes no search endpoint/) + end + + it 'requests the search endpoint' do + stub = stub_request(:get, "#{url}/search") + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE.to_s, 'query' => 'support', 'with_total_count' => 'true' }) + .to_return(json_response([])) + + proxy.search('support').to_a + expect(stub).to have_been_requested + end + + # The other things a search endpoint narrows by, named on the call that + # searches rather than passed to where on what it returned. + context 'with keywords the search endpoint reads' do + let(:users_search) { "#{ClientHelper::BASE_URL}api/v1/users/search" } + + before { stub_request(:get, /search/).with(query: hash_including({})).to_return(json_response([])) } + + it 'sends ids' do + client.users.search('x', ids: [1, 2]).to_a + expect(a_request(:get, users_search).with(query: hash_including('query' => 'x', 'ids' => %w[1 2]))).to have_been_made + end + + it 'sends role_ids, group_ids and permissions' do + client.users.search('x', role_ids: [2], group_ids: [3], permissions: ['ticket.agent']).to_a + + expect(a_request(:get, users_search).with(query: hash_including('role_ids' => ['2'], 'group_ids' => ['3'], 'permissions' => ['ticket.agent']))) + .to have_been_made + end + + # A list of group ids names no access, which Zammad reads as full. The + # Hash is how any other access is asked for, and it has to arrive as the + # pairs User::Search walks: `group_ids[3][]=read`. + # + # Read off the URL Faraday built rather than asked of WebMock, which + # takes a Hash keyed by numbers for an Array and reports + # `group_ids[][0]=read` for a request that was never sent that way. + # + # Every pair naming a group, and not only the three that were written. + # Looked for as a substring, they were found in a query that named a + # fourth group beside them as well, and a group nobody asked for is a + # set of agents the search then keeps. + it 'sends group_ids as a map of group to access, the way Rails reads a nested parameter back' do + sent = nil + recorder = Class.new(Faraday::Middleware) do + define_method(:on_request) { |env| sent = URI.decode_www_form(env.url.query) } + end + + unit_client(middleware: ->(builder) { builder.use(recorder) }) + .users.search('x', group_ids: { 3 => %w[read change], 4 => 'full' }).to_a + + expect(sent.select { |name, _| name.start_with?('group_ids') }) + .to contain_exactly(['group_ids[3][]', 'read'], ['group_ids[3][]', 'change'], ['group_ids[4]', 'full']) + end + + it 'sends a condition the way Rails reads a nested parameter back' do + client.tickets.search('x', condition: { 'ticket.state_id' => { operator: 'is', value: [1] } }).to_a + + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/search") + .with(query: hash_including('condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => ['1'] } }))) + .to have_been_made + end + + it 'accepts a keyword spelled as a string' do + expect(client.users.search('x', 'ids' => [1])).to be_a(ZammadAPI::Collection) + end + + it 'keeps the term the search was given' do + client.users.search('smith', ids: [1]).to_a + expect(a_request(:get, users_search).with(query: hash_including('query' => 'smith'))).to have_been_made + end + + # A collection is lazy: nothing is sent until it is enumerated. It held + # the caller's own Array, Hash and String until then, so changing one of + # them afterwards changed a search that had already been written and + # checked. + context 'when what it was given changes before the collection is read' do + it 'sends the ids it was given' do + ids = [1] + search = client.users.search('x', ids: ids) + ids << 2 + search.to_a + + expect(a_request(:get, users_search).with(query: hash_including('ids' => ['1']))).to have_been_made + end + + it 'sends the term it was given' do + term = +'smith' + search = client.users.search(term) + term << ' jones' + search.to_a + + expect(a_request(:get, users_search).with(query: hash_including('query' => 'smith'))).to have_been_made + end + + it 'sends the condition it was given, at every depth' do + condition = { 'ticket.state_id' => { operator: 'is', value: [1] } } + search = client.tickets.search('x', condition: condition) + condition['ticket.state_id'][:value] << 2 + condition['ticket.owner_id'] = { operator: 'is', value: [3] } + search.to_a + + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/search") + .with(query: hash_including('condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => ['1'] } }))) + .to have_been_made + end + + it 'carries the copy through page and order' do + ids = [1] + search = client.users.search('x', ids: ids).order(:login).page(2) + ids << 2 + search.to_a + + expect(a_request(:get, users_search).with(query: hash_including('ids' => ['1'], 'page' => '2', 'sort_by' => 'login'))) + .to have_been_made + end + + it 'leaves what it was given writable' do + ids = [1] + client.users.search('x', ids: ids) + + expect(ids).not_to be_frozen + end + end + end + + # Zammad drops a parameter it does not know, so these would come back + # unnarrowed with nothing to say so. + context 'with a keyword the search endpoint would drop' do + it 'refuses an attribute name' do + expect { proxy.search('support', name: 'Users') } + .to raise_error(ArgumentError, %r{search does not take name on api/v1/groups: this search endpoint narrows by the term, and by condition, ids, and drops}) + end + + it 'says where an attribute value goes instead' do + expect { proxy.search('support', name: 'Users') } + .to raise_error(ArgumentError, /Put an attribute value in the term - search\('state\.name:open'\)/) + end + + it 'refuses a sort, and names order' do + expect { proxy.search('support', sort_by: 'name') } + .to raise_error(ArgumentError, /search does not take sort_by.*sort with search\(term\)\.order\(\.\.\.\)/) + end + + it 'refuses to replace the search term' do + expect { proxy.search('login failure', query: 'anything') }.to raise_error(ArgumentError, /search does not take query/) + end + + %i[page per_page expand only_total_count].each do |owned| + it "refuses #{owned}, which the collection controls itself" do + expect { proxy.search('support', owned => 1) }.to raise_error(ArgumentError, /search does not take #{owned}/) + end + end + + it 'makes no request' do + expect { proxy.search('support', name: 'Users') }.to raise_error(ArgumentError) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end + + # model_search_render hands role_ids, group_ids and permissions to the + # search of every model, and only User::Search reads them. A ticket + # search given group_ids was sent as written and answered with tickets + # from every group the client can read. + context 'with a keyword only the user search reads' do + it 'refuses group_ids on tickets' do + expect { client.tickets.search('printer', group_ids: [2]) } + .to raise_error(ArgumentError, %r{search does not take group_ids on api/v1/tickets: this search endpoint narrows by the term, and by condition, ids, and drops}) + end + + it 'says how tickets are narrowed by group instead' do + expect { client.tickets.search('printer', group_ids: [2]) } + .to raise_error(ArgumentError, /or in a condition - search\(term, condition: \{'ticket\.group_id' => \{operator: 'is', value: \[2\]\}\}\)/) + end + + it 'refuses role_ids and permissions on organizations' do + expect { client.organizations.search('acme', role_ids: [2], permissions: ['ticket.agent']) } + .to raise_error(ArgumentError, /search does not take role_ids, permissions on/) + end + + it 'refuses them on groups' do + expect { proxy.search('support', group_ids: [1]) }.to raise_error(ArgumentError, /search does not take group_ids on/) + end + + it 'makes no request' do + expect { client.tickets.search('printer', group_ids: [2]) }.to raise_error(ArgumentError) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'still takes all three on users, and names them among what that search narrows by' do + expect(client.users.search('smith', role_ids: [2], group_ids: [3], permissions: ['ticket.agent'])).to be_a(ZammadAPI::Collection) + expect { client.users.search('smith', active: true) } + .to raise_error(ArgumentError, /and by condition, ids, role_ids, group_ids, permissions, and drops/) + end + + it 'still takes condition and ids on every search' do + expect(client.tickets.search('printer', ids: [1], condition: { 'ticket.group_id' => { operator: 'is', value: [2] } })) + .to be_a(ZammadAPI::Collection) + end + end + + context 'with a resource a caller declared' do + let(:role_class) do + Class.new(ZammadAPI::Resources::Base) do + def self.name = 'Role' + + path 'api/v1/roles' + searchable true + end + end + + it 'takes condition and ids, which every search reads' do + expect(client.resource(role_class).search('agent', ids: [1])).to be_a(ZammadAPI::Collection) + end + + it 'refuses a keyword it did not declare' do + expect { client.resource(role_class).search('agent', permissions: ['admin']) } + .to raise_error(ArgumentError, %r{search does not take permissions on api/v1/roles}) + end + + it 'takes a keyword it declared' do + role_class.search_filters :permissions + + expect(client.resource(role_class).search('agent', permissions: ['admin'])).to be_a(ZammadAPI::Collection) + end + end + + # Every one of these is refused at the call that wrote it, rather than + # when the collection is first read some lines away. + context 'with a keyword it cannot send' do + it 'refuses a nil value, which no query string can spell' do + expect { client.users.search('x', ids: nil) }.to raise_error(ArgumentError, /query parameter ids is nil/) + end + + # Zammad narrows by a keyword only where it is `present?`, so each of + # these was sent and answered with everything matching the term - for + # `ids: allowed_ids` with nothing allowed, where none was asked for. + { + ids: [], + role_ids: [], + permissions: [], + group_ids: {}, + condition: {} + }.each do |name, value| + it "refuses #{name}: #{value.inspect}, which Zammad reads as no #{name} at all" do + expect { client.users.search('smith', name => value) } + .to raise_error(ArgumentError, %r{search was given #{name}: #{Regexp.escape(value.inspect)} on api/v1/users}) + end + end + + it 'refuses a keyword given as a blank String' do + expect { client.users.search('smith', ids: ' ') }.to raise_error(ArgumentError, /search was given ids: " "/) + end + + # `present?` is false for it, so Zammad skips the filter. + it 'refuses one that holds only a Unicode space' do + expect { client.users.search('smith', permissions: "\u3000") }.to raise_error(ArgumentError, /search was given permissions:/) + end + + it 'refuses one that is blank in UTF-16, the way it does one in UTF-8' do + expect { client.users.search('smith', permissions: "\u3000".encode('UTF-16LE')) }.to raise_error(ArgumentError, /search was given permissions:/) + end + + it 'takes one given in UTF-16 that is not blank' do + expect(client.users.search('smith', permissions: 'admin'.encode('UTF-16LE'))).to be_a(ZammadAPI::Collection) + end + + # Sent as `permissions=`, which is as blank as a String with nothing in + # it: the check is of what is sent, not of the class it was given as. + it 'refuses one given as a value whose text is empty' do + expect { client.users.search('smith', permissions: :'') }.to raise_error(ArgumentError, /search was given permissions: :""/) + end + + # Nothing is written for an empty Hash, so the request went out with no + # condition at all. + it 'refuses a condition that holds nothing but empty Hashes' do + expect { client.tickets.search('printer', condition: { 'ticket.state_id' => {} }) } + .to raise_error(ArgumentError, /search was given condition: \{"ticket.state_id" => \{\}\}/) + end + + it 'refuses group_ids naming a group with nothing under it' do + expect { client.users.search('smith', group_ids: { 2 => {} }) }.to raise_error(ArgumentError, /search was given group_ids:/) + end + + it 'says what the search would have come back with' do + expect { client.users.search('smith', ids: []) } + .to raise_error(ArgumentError, /everything matching the term, not narrowed to nothing/) + end + + it 'names every empty keyword at once' do + expect { client.users.search('smith', ids: [], role_ids: []) }.to raise_error(ArgumentError, /search was given ids: \[\], role_ids: \[\] on/) + end + + it 'makes no request for one' do + stub = stub_request(:get, /search/).with(query: hash_including({})) + + expect { client.users.search('smith', ids: []).to_a }.to raise_error(ArgumentError) + expect(stub).not_to have_been_requested + end + + # What is nested in a condition is a selector, and Zammad's to read. + it 'still takes a condition whose value is empty' do + expect(client.tickets.search('x', condition: { 'ticket.tags' => { operator: 'contains all', value: [] } })).to be_a(ZammadAPI::Collection) + end + + # An empty list is written, as `condition[ticket.tags][value][]`, so + # the condition reaches Zammad. + it 'still takes a condition that holds nothing but an empty list' do + expect(client.tickets.search('x', condition: { 'ticket.tags' => { value: [] } })).to be_a(ZammadAPI::Collection) + end + + it 'still takes a value that is not empty for being false or zero' do + expect(client.users.search('smith', ids: [0])).to be_a(ZammadAPI::Collection) + end + + it 'refuses two spellings of one keyword rather than dropping a value' do + expect { client.users.search('x', 'ids' => [1], :ids => [2]) } + .to raise_error(ArgumentError, /ids was given twice, as "ids" and as :ids/) + end + + it 'refuses two spellings of one key nested inside a condition' do + expect { client.tickets.search('x', condition: { 'state_id' => 1, :state_id => 2 }) } + .to raise_error(ArgumentError, /parameter condition\[state_id\] was given twice/) + end + + # A group of conditions and a condition share `operator`, which is what + # lets a query string keep them apart. Two elements that share nothing + # would reach Zammad as one, so the search says so here. + it 'refuses a list of conditions a query string cannot keep apart' do + expect { client.tickets.search('x', condition: { conditions: [{ name: 'ticket.state_id' }, { operator: 'AND' }] }) } + .to raise_error(ArgumentError, /query parameter condition\[conditions\]\[1\] has no plain value under a key the element before it has/) + end + + # Read off the URL Faraday built, in the order it was written: WebMock + # sorts a query before it compares one, and the order is the point. + # Rails begins the second element at its `operator`, so that has to + # come before the conditions it holds, or the group is read into the + # condition before it. + it 'takes a condition that holds a group of conditions, and sends the group as an element of its own' do + nested = { operator: 'OR', conditions: [{ name: 'ticket.state_id', operator: 'is', value: [2] }, { operator: 'AND', conditions: [{ name: 'ticket.group_id', operator: 'is', value: [1] }] }] } + sent = nil + recorder = Class.new(Faraday::Middleware) do + define_method(:on_request) { |env| sent = URI.decode_www_form(env.url.query).map(&:first) } + end + stub_request(:get, /search/).with(query: hash_including({})).to_return(json_response([])) + + search = unit_client(middleware: ->(builder) { builder.use(recorder) }).tickets.search('x', condition: nested) + expect(search).to be_a(ZammadAPI::Collection) + + search.to_a + expect(sent.grep(/\Acondition\[conditions\]/)).to eq( + [ + 'condition[conditions][][name]', 'condition[conditions][][operator]', 'condition[conditions][][value][]', + 'condition[conditions][][operator]', 'condition[conditions][][conditions][][name]', + 'condition[conditions][][conditions][][operator]', 'condition[conditions][][conditions][][value][]' + ] + ) + end + + it 'still accepts a condition whose keys only look alike' do + expect(client.tickets.search('x', condition: { 'ticket.state_id' => { operator: 'is' }, 'ticket.group_id' => { operator: 'is' } })) + .to be_a(ZammadAPI::Collection) + end + end + + it 'sorts through order on the collection it returns' do + stub = stub_request(:get, "#{url}/search") + .with(query: hash_including('query' => 'support', 'sort_by' => 'name', 'order_by' => 'asc')) + .to_return(json_response([])) + + proxy.search('support').order(:name).to_a + expect(stub).to have_been_requested + end + + it 'requires a term' do + expect { proxy.search }.to raise_error(ArgumentError) + end + + it 'rejects an empty term' do + expect { proxy.search(' ') }.to raise_error(ArgumentError, /non-empty query string/) + end + + # Zammad asks `blank?`, which counts Unicode spaces, and answers a blank + # term with every record. + ["\u00A0", "\u3000", "\u3000".encode('UTF-16LE')].each do |blank| + it "rejects #{blank.inspect}, which Zammad reads as no term" do + expect { proxy.search(blank) }.to raise_error(ArgumentError, /non-empty query string/) + end + end + + it "says that '*' asks for every record" do + expect { proxy.search('') }.to raise_error(ArgumentError, /Search for '\*' to ask for every record/) + end + + # How Zammad's own interface lists every user or organization. + it "sends '*', which asks for every record in so many words" do + stub = stub_request(:get, "#{url}/search").with(query: hash_including('query' => '*')).to_return(json_response([])) + + proxy.search('*').to_a + expect(stub).to have_been_requested + end + + it 'rejects a term that is not a string' do + expect { proxy.search(42) }.to raise_error(ArgumentError, /non-empty query string/) + end + end + + describe '#inspect' do + it 'names the resource' do + expect(proxy.inspect).to eq('#') + end + end +end diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb new file mode 100644 index 0000000..d3287b8 --- /dev/null +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -0,0 +1,1513 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Resources::Base do + let(:client) { unit_client } + let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } + + describe 'the path DSL' do + it 'exposes the declared path' do + expect(ZammadAPI::Resources::Group.resource_path).to eq('api/v1/groups') + end + + it 'raises for a resource that declares none' do + anonymous = Class.new(described_class) do + def self.name + 'Anonymous' + end + end + expect { anonymous.resource_path }.to raise_error(ZammadAPI::Error, /does not declare an API path/) + end + + it 'does not leak a path between sibling resources' do + expect(ZammadAPI::Resources::User.resource_path).to eq('api/v1/users') + end + end + + describe 'attributes' do + subject(:group) { client.groups.new(name: 'Support', 'note' => 'from a string key') } + + it 'reads an attribute' do + expect(group.name).to eq('Support') + end + + it 'symbolizes string keys supplied by the caller' do + expect(group.note).to eq('from a string key') + end + + it 'starts without changes' do + expect(group).not_to be_changed + end + + it 'records a change as old and new value' do + group.name = 'Other' + expect(group.changes).to eq(name: %w[Support Other]) + end + + it 'reports being changed' do + group.name = 'Other' + expect(group).to be_changed + end + + it 'reflects the change when read back' do + group.name = 'Other' + expect(group.name).to eq('Other') + end + + it 'records a change for a previously unset attribute' do + group.active = true + expect(group.changes).to eq(active: [nil, true]) + end + + it 'keeps the original value when an attribute is written twice' do + group.name = 'First' + group.name = 'Second' + expect(group.changes).to eq(name: %w[Support Second]) + end + + it 'drops the change when the value returns to the original' do + group.name = 'Other' + group.name = 'Support' + expect(group.changes).to be_empty + end + + it 'is not changed once the value returns to the original' do + group.name = 'Other' + group.name = 'Support' + expect(group).not_to be_changed + end + + it 'still reads the reassigned value after the change is dropped' do + group.name = 'Other' + group.name = 'Support' + expect(group.name).to eq('Support') + end + + it 'drops the change when an attribute the record carries is set back to its nil original' do + carrying_nil = client.groups.new(name: 'Support', note: nil) + carrying_nil.note = 'Renamed' + carrying_nil.note = nil + expect(carrying_nil.changes).to be_empty + end + + # An attribute the record does not carry is not an attribute whose value + # is nil: Zammad reduces the object it serializes for a permission-scoped + # client, so the key being absent says nothing about what is stored. Read + # as a nil original, writing nil to one compared equal, staged nothing and + # was still merged into the attributes - the write was dropped without a + # word and the record went on reporting a key Zammad never sent it. + it 'stages a write of an attribute the record does not carry' do + group.active = nil + expect(group.changes).to eq(active: [nil, nil]) + end + + it 'keeps that write staged when it is written twice' do + group.active = true + group.active = nil + expect(group.changes).to eq(active: [nil, nil]) + end + + it 'keeps the attributes it reports in step with the changes it staged' do + group.active = nil + expect(group.key?(:active)).to be(group.changes.key?(:active)) + end + end + + describe 'attribute state a record hands out' do + subject(:group) { client.groups.new(name: 'Support', preferences: { 'note' => 'keep' }) } + + it 'cannot be written through #attributes, which would not stage a change' do + expect { group.attributes[:name] = 'Sneaky' }.to raise_error(FrozenError) + end + + it 'cannot be written through a nested value' do + expect { group.attributes[:preferences][:note] = 'Sneaky' }.to raise_error(FrozenError) + end + + it 'cannot be written through #changes, which would decide what save sends' do + group.name = 'Renamed' + expect { group.changes[:name] = %w[a b] }.to raise_error(FrozenError) + end + + it 'still records a change through the writer' do + group.name = 'Renamed' + expect(group.changes).to eq(name: %w[Support Renamed]) + end + + it 'does not report a change that was never staged' do + group.to_h[:name] = 'Sneaky' + expect(group).not_to be_changed + end + + it 'keeps a value the caller mutates after assigning it' do + note = +'Mutable' + group.note = note + note << ' changed' + + expect(group.note).to eq('Mutable') + end + + it 'freezes attributes adopted from a response' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ id: 7, preferences: { note: 'from the server' } }, status: 201)) + + group.save! + expect { group.attributes[:preferences][:note] << '!' }.to raise_error(FrozenError) + end + end + + describe '#save' do + context 'with a new record' do + subject(:group) { client.groups.new(name: 'Support') } + + before do + stub_request(:post, url) + .with(query: { 'expand' => 'true' }, body: '{"name":"Support"}') + .to_return(json_response({ id: 7, name: 'Support', note: nil }, status: 201)) + end + + it 'returns true' do + expect(group.save).to be(true) + end + + it 'posts to the collection path' do + group.save + expect(a_request(:post, url).with(query: hash_including({}))).to have_been_made + end + + it 'adopts the attributes from the response' do + group.save + expect(group.id).to eq(7) + end + + it 'is no longer a new record' do + group.save + expect(group).to be_persisted + end + + it 'clears the staged changes' do + group.name = 'Support' + group.save + expect(group.changes).to be_empty + end + end + + context 'with an existing record' do + subject(:group) { client.groups.find(1) } + + before do + stub_request(:get, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ id: 1, name: 'Users', note: 'old', active: true })) + end + + it 'sends only the changed attributes' do + stub = stub_request(:put, "#{url}/1") + .with(query: { 'expand' => 'true' }, body: '{"note":"new"}') + .to_return(json_response({ id: 1, name: 'Users', note: 'new', active: true })) + + group.note = 'new' + group.save + expect(stub).to have_been_requested + end + + it 'returns true' do + stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ id: 1, note: 'new' })) + + group.note = 'new' + expect(group.save).to be(true) + end + + it 'sends nothing at all when nothing changed' do + stub = stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ id: 1 })) + + expect(group.save).to be(true) + expect(stub).not_to have_been_requested + end + + it 'saves again once something changes' do + stub_request(:put, "#{url}/1").with(query: hash_including({}), body: '{"note":"new"}') + .to_return(json_response({ id: 1, note: 'new' })) + + group.save + group.note = 'new' + + expect(group.save).to be(true) + expect(group.note).to eq('new') + end + end + + it 'raises ParseError when the response is not an object' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response([], status: 201)) + + expect { client.groups.new(name: 'x').save } + .to raise_error(ZammadAPI::ParseError, /expected a JSON object, got Array/) + end + + context 'when Zammad rejects the attributes' do + subject(:group) { client.groups.new } + + before do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422)) + end + + it 'returns false instead of raising' do + expect(group.save).to be(false) + end + + it 'leaves the validation error in #error' do + group.save + expect(group.error).to be_a(ZammadAPI::ValidationError) + end + + it 'carries the message Zammad reported' do + group.save + expect(group.error.server_message).to eq('Name is required') + end + + it 'leaves the record unsaved' do + group.save + expect(group).to be_new_record + end + + it 'keeps the staged changes, so the attributes can be corrected and resent' do + group.name = 'Support' + group.save + expect(group.changes).to eq({ name: [nil, 'Support'] }) + end + end + + context 'when the failure is not a validation error' do + it 'still raises for a 403' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'no' }, status: 403)) + + expect { client.groups.new(name: 'x').save }.to raise_error(ZammadAPI::AuthorizationError) + end + + it 'still raises for a 500' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({}, status: 500)) + + expect { client.groups.new(name: 'x').save }.to raise_error(ZammadAPI::ServerError) + end + end + + it 'clears a previous error once the record saves' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422), json_response({ id: 7, name: 'Support' })) + + group = client.groups.new + group.save + group.name = 'Support' + + expect(group.save).to be(true) + expect(group.error).to be_nil + end + + context 'when the save after a rejected one fails some other way' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } + + before do + stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return( + json_response({ error: 'Name is required' }, status: 422), + json_response({ error: 'not yours' }, status: 403) + ) + group.name = '' + group.save + group.name = 'Support' + end + + it 'records the first rejection' do + expect(group.error).to be_a(ZammadAPI::ValidationError) + end + + it 'clears it rather than reporting it as the second failure' do + expect { group.save }.to raise_error(ZammadAPI::AuthorizationError) + expect(group.error).to be_nil + end + end + end + + describe '#save!' do + subject(:group) { client.groups.new(name: 'Support') } + + it 'returns true' do + stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 7 }, status: 201)) + + expect(group.save!).to be(true) + end + + it 'raises ValidationError when Zammad rejects the record' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422)) + + expect { group.save! }.to raise_error(ZammadAPI::ValidationError, /Name is required/) + end + + it 'does not record the error, because it was raised' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422)) + + expect { group.save! }.to raise_error(ZammadAPI::ValidationError) + expect(group.error).to be_nil + end + end + + describe '#assign_attributes' do + subject(:group) { client.groups.new(name: 'Support') } + + it 'stages every attribute as a change' do + group.assign_attributes(name: 'Renamed', note: 'Why') + expect(group.changes).to eq(name: %w[Support Renamed], note: [nil, 'Why']) + end + + it 'accepts string keys' do + group.assign_attributes('name' => 'Renamed') + expect(group.name).to eq('Renamed') + end + + it 'does not save' do + group.assign_attributes(name: 'Renamed') + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'returns the record, so it can be chained' do + expect(group.assign_attributes(name: 'Renamed')).to be(group) + end + + it 'drops a change that restores the original value' do + group.assign_attributes(name: 'Renamed') + group.assign_attributes(name: 'Support') + expect(group).not_to be_changed + end + end + + describe '#update' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users', note: 'old') } + + it 'sends only the assigned attributes' do + stub = stub_request(:put, "#{url}/1") + .with(query: { 'expand' => 'true' }, body: '{"note":"new"}') + .to_return(json_response({ id: 1, name: 'Users', note: 'new' })) + + group.update(note: 'new') + expect(stub).to have_been_requested + end + + it 'returns true when the record was stored' do + stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, note: 'new' })) + + expect(group.update(note: 'new')).to be(true) + end + + it 'adopts the attributes from the response' do + stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ id: 1, name: 'Renamed by Zammad' })) + + group.update(note: 'new') + expect(group.name).to eq('Renamed by Zammad') + end + + it 'returns false and records the error when Zammad rejects the attributes' do + stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ error: 'Note is too long' }, status: 422)) + + expect(group.update(note: 'new')).to be(false) + expect(group.error.server_message).to eq('Note is too long') + end + + it 'keeps the staged changes after a rejection, so they can be corrected' do + stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ error: 'Note is too long' }, status: 422)) + + group.update(note: 'new') + expect(group.changes).to eq(note: %w[old new]) + end + + it 'creates a record that has not been saved yet' do + stub = stub_request(:post, url).with(query: hash_including({}), body: '{"name":"Support"}') + .to_return(json_response({ id: 7, name: 'Support' }, status: 201)) + + expect(client.groups.new.update(name: 'Support')).to be(true) + expect(stub).to have_been_requested + end + end + + describe '#update!' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, note: 'old') } + + it 'returns true' do + stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect(group.update!(note: 'new')).to be(true) + end + + it 'raises when Zammad rejects the attributes' do + stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ error: 'Note is too long' }, status: 422)) + + expect { group.update!(note: 'new') }.to raise_error(ZammadAPI::ValidationError, /Note is too long/) + end + end + + describe '#reload' do + subject(:group) { ZammadAPI::Resources::Group.from_response(transport, id: 1, name: 'Users') } + + let(:transport) { unit_transport } + + before do + stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }) + .to_return(json_response({ id: 1, name: 'Renamed' })) + end + + it 'refetches the attributes' do + expect(group.reload.name).to eq('Renamed') + end + + it 'discards unsaved changes' do + group.name = 'Local' + expect(group.reload.changes).to be_empty + end + + it 'returns itself' do + expect(group.reload).to be(group) + end + + it 'raises for a record that was never saved' do + expect { ZammadAPI::Resources::Group.new(transport).reload } + .to raise_error(ZammadAPI::Error, /has not been saved, so there is nothing to reload/) + end + + it 'raises ParseError when the response is not an object' do + stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }) + .to_return(json_response([])) + + expect { group.reload } + .to raise_error(ZammadAPI::ParseError, /expected a JSON object, got Array/) + end + + it 'raises ParseError when the response is not JSON' do + stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }) + .to_return(status: 200, body: 'Gateway Timeout', headers: { 'Content-Type' => 'text/html' }) + + expect { group.reload } + .to raise_error(ZammadAPI::ParseError, /expected a JSON object, got String/) + end + + it 'keeps the previous attributes when the response cannot be decoded' do + stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }) + .to_return(json_response([])) + + expect { group.reload }.to raise_error(ZammadAPI::ParseError) + expect(group.name).to eq('Users') + end + end + + describe '.member_path' do + it 'builds the path of one record' do + expect(ZammadAPI::Resources::Group.member_path(1)).to eq('api/v1/groups/1') + end + + # ResourceProxy#find, #destroy and every instance method that reaches an + # endpoint go through here, so the escaping rule is applied once. + it 'escapes an id that would otherwise leave its segment' do + expect(ZammadAPI::Resources::Group.member_path('1/../users')).to eq('api/v1/groups/1%2F..%2Fusers') + end + + it 'refuses an id that navigates' do + expect { ZammadAPI::Resources::Group.member_path('..') }.to raise_error(ArgumentError) + end + end + + describe '#destroy' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) } + + it 'deletes the record' do + stub = stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + expect(group.destroy).to be(true) + expect(stub).to have_been_requested + end + + it 'raises for a record that was never saved' do + expect { client.groups.new.destroy }.to raise_error(ZammadAPI::Error, /has not been saved, so there is nothing to destroy/) + end + + # `destroy` asked only whether the record was already destroyed, so one + # built with an id it was simply handed issued a real DELETE for a record + # it does not stand for. The constructor refuses that id now, so there is + # no such record left to destroy. + it 'sends nothing for a record built with an id it was never saved with' do + stub = stub_request(:delete, "#{url}/99") + + expect { client.groups.new(id: 99, name: 'X').destroy } + .to raise_error(ZammadAPI::Error, /is what addresses this record/) + expect(stub).not_to have_been_requested + end + + context 'when the record is gone' do + before do + stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + group.destroy + end + + it 'reports the record as destroyed' do + expect(group).to be_destroyed + end + + it 'no longer reports it as persisted' do + expect(group).not_to be_persisted + end + + it 'says so in inspect' do + expect(group.inspect).to include('destroyed=true') + end + + it 'refuses a save rather than letting it 404' do + expect { group.save }.to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to save/) + end + + # `reload` re-read a record that no longer exists and cleared the flag on + # the way back, so the record came back reporting itself as persisted and + # its next save issued a PUT against the deleted path. + it 'refuses a reload rather than resurrecting the record' do + expect { group.reload } + .to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to reload/) + end + + it 'stays destroyed after a refused reload' do + expect { group.reload }.to raise_error(ZammadAPI::Error) + + expect(group).to be_destroyed + expect(group).not_to be_persisted + end + + it 'refuses a second destroy rather than surfacing Zammad\'s 404' do + expect { group.destroy } + .to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to destroy/) + end + end + + context 'with state staged before it was destroyed' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } + + before do + stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + group.name = 'Support' + end + + it 'drops a change that can never be sent' do + group.destroy + + expect(group).not_to be_changed + expect(group.changes).to be_empty + end + + # Readable as Zammad last served them. The staged write above was never + # sent, and dropping the change set without it left the record reporting + # "Support" while `changed?` was false and `changes` was empty - so + # nothing was left to tell a local edit apart from a value the server + # gave, in the one state where it can never be saved. + it 'keeps the attributes readable, so a destroyed record can still be reported on' do + group.destroy + + expect(group.id).to eq(1) + expect(group.name).to eq('Users') + end + + it 'does not report a write Zammad never saw' do + group.destroy + + expect(group.attributes).to eq({ id: 1, name: 'Users' }) + expect(group.inspect).not_to include('Support') + end + + it 'refuses the association readers, which would request a record that is gone' do + group.destroy + + # The guarantee, not the mechanism that was expected to deliver it. + # This compared the proxy against the one from before the destroy, + # which clearing the memo satisfied - while `related` went on + # rebuilding a working proxy on the very next call. It passed for as + # long as the behaviour it is named for was broken. + expect { group.related }.to raise_error(ZammadAPI::Error, /was destroyed/) + end + + it 'drops the failure of a save that is over' do + stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422)) + group.save + + expect(group.error).to be_a(ZammadAPI::ValidationError) + group.destroy + expect(group.error).to be_nil + end + end + + # `update` stages before it saves, and `save!` is where the destroyed + # check used to live. That order left a destroyed record holding a change + # set that can never be sent - the state destroy clears the staged changes + # to prevent - so the refusal happens before anything is written. + context 'when an update is attempted after it was destroyed' do + before do + stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + group.destroy + end + + it 'refuses the update' do + expect { group.update(name: 'Renamed') }.to raise_error(ZammadAPI::Error, /was destroyed/) + end + + it 'refuses the raising update' do + expect { group.update!(name: 'Renamed') }.to raise_error(ZammadAPI::Error, /was destroyed/) + end + + it 'leaves nothing staged behind the refusal' do + begin + group.update(name: 'Renamed') + rescue ZammadAPI::Error + nil + end + + expect(group).not_to be_changed + expect(group.changes).to be_empty + end + + it 'leaves the attributes as they were' do + begin + group.update(name: 'Renamed') + rescue ZammadAPI::Error + nil + end + + expect(group.key?(:name)).to be(false) + end + end + + # `update` refused a destroyed record, and the writers it is built on did + # not: a write left the record changed and reading a value Zammad never + # saw, and the save after it was the first thing to object. + context 'when an attribute is written after it was destroyed' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'A') } + + before do + stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + group.destroy + end + + it 'refuses a named writer' do + expect { group.name = 'Z' }.to raise_error(ZammadAPI::Error, /Group 1 was destroyed, there is nothing to change/) + end + + it 'refuses []=' do + expect { group[:name] = 'Z' }.to raise_error(ZammadAPI::Error, /was destroyed/) + end + + it 'refuses assign_attributes' do + expect { group.assign_attributes(name: 'Z') }.to raise_error(ZammadAPI::Error, /was destroyed/) + end + + it 'refuses a writer for an attribute the record never carried' do + expect { group.note = 'Z' }.to raise_error(ZammadAPI::Error, /was destroyed/) + end + + it 'leaves nothing staged behind the refusal' do + expect { group.name = 'Z' }.to raise_error(ZammadAPI::Error) + expect(group).not_to be_changed + end + + it 'leaves the record reading as it last was in Zammad' do + expect { group.assign_attributes(note: 'n', name: 'Z') }.to raise_error(ZammadAPI::Error) + expect(group.to_h).to eq({ id: 1, name: 'A' }) + end + + it 'still refuses the id for the reason an id is refused' do + expect { group.assign_attributes(id: 9) }.to raise_error(ZammadAPI::Error, /cannot be staged/) + end + end + end + + # The attributes are frozen and replaced on write, so a copy never saw the + # original's next write. The change set is written in place, and was shared. + describe 'a copy made with dup or clone' do + let(:original) { client.groups.find(1) } + + before do + stub_request(:get, "#{url}/1").with(query: { expand: 'true' }).to_return(json_response({ id: 1, name: 'A', note: 'n' })) + end + + %i[dup clone].each do |copier| + context "with #{copier}" do + let(:copy) { original.public_send(copier) } + + it 'does not mark the original as changed when the copy is written' do + copy.name = 'X' + expect(original).not_to be_changed + end + + it 'does not stage the write on the original' do + copy.name = 'X' + expect(original.changes).to eq({}) + end + + it 'stages the write on the copy' do + copy.name = 'X' + expect(copy.changes).to eq({ name: %w[A X] }) + end + + it 'sends nothing when the original is saved after the copy was written' do + copy.name = 'X' + original.save + expect(a_request(:put, "#{url}/1")).not_to have_been_made + end + + it 'does not stage a write to the original on the copy' do + copy + original.name = 'Y' + expect(copy.changes).to eq({}) + end + + it 'carries over what was staged when it was made' do + original.name = 'Y' + expect(copy.changes).to eq({ name: %w[A Y] }) + end + + it 'keeps those two change sets apart afterwards' do + original.name = 'Y' + copy.note = 'other' + expect(original.changes.keys).to eq([:name]) + end + + it 'is still the same Zammad record' do + expect(copy).to eq(original) + end + + it 'gets association readers of its own, not the ones bound to the original' do + expect(copy.related).not_to be(original.related) + end + end + end + end + + describe 'equality' do + it 'treats two separately fetched records as the same record' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) + + first_fetch = client.groups.find(1) + second_fetch = client.groups.find(1) + + expect(first_fetch).not_to equal(second_fetch) + expect(first_fetch).to eq(second_fetch) + end + + it 'tells records of different resources with the same id apart' do + group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) + user = ZammadAPI::Resources::User.from_response(unit_transport, id: 1) + + expect(group).not_to eq(user) + end + + # An id is only unique within one installation. A script that reads two + # of them holds a group 1 from each, and they are two records. + context 'with records of two Zammad instances' do + let(:here) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) } + let(:there) { ZammadAPI::Resources::Group.from_response(unit_transport(url: 'http://other.test/'), id: 1) } + + it 'tells the same id apart' do + expect(here).not_to eq(there) + end + + it 'keeps both through uniq' do + expect([here, there].uniq.size).to eq(2) + end + + it 'keeps both as members of a Set' do + expect(Set[here, there].size).to eq(2) + end + + it 'does not answer for one with the value stored under the other' do + expect({ here => :handled }[there]).to be_nil + end + end + + context 'with a record read through two clients for one instance' do + let(:record) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) } + + it 'is the same record through a client with other options' do + other = ZammadAPI::Resources::Group.from_response(unit_transport(timeout: 5, http_token: 'another'), id: 1) + + expect(record).to eq(other) + expect(record.hash).to eq(other.hash) + end + + it 'is the same record through an on_behalf_of scope' do + scoped = ZammadAPI::Resources::Group.from_response(unit_transport.with_on_behalf_of('agent@example.com'), id: 1) + + expect([record, scoped].uniq.size).to eq(1) + end + + it 'is the same record whether or not the url was written with its trailing slash' do + other = ZammadAPI::Resources::Group.from_response(unit_transport(url: ClientHelper::BASE_URL.chomp('/')), id: 1) + + expect(record).to eq(other) + end + end + + it 'identifies a record by its id once its first save assigns one' do + stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 7, name: 'Support' })) + group = client.groups.new(name: 'Support') + + expect(group).not_to eq(ZammadAPI::Resources::Group.from_response(unit_transport, id: 7)) + group.save! + expect(group).to eq(ZammadAPI::Resources::Group.from_response(unit_transport, id: 7)) + end + end + + describe '#to_json' do + it 'renders the attributes rather than the object' do + group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') + + expect(group.to_json).to eq('{"id":1,"name":"Users"}') + end + end + + describe '#inspect' do + it 'shows the id, state and attributes' do + group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') + expect(group.inspect) + .to eq('#') + end + end + + describe '.from_response' do + it 'builds a persisted record' do + expect(ZammadAPI::Resources::Group.from_response(unit_transport, id: 1)).to be_persisted + end + end + + # A plain class-level ivar is not inherited, so a subclass used to inherit + # every association, the page limit and the searchability, and lose only the + # API path - raising "does not declare an API path" from a class that + # plainly did. + describe 'a resource subclassed by a caller' do + subject(:subclass) { Class.new(ZammadAPI::Resources::Ticket) { def self.name = 'MyTicket' } } + + it 'inherits the API path' do + expect(subclass.resource_path).to eq('api/v1/tickets') + end + + it 'inherits the member path built from it' do + expect(subclass.member_path(7)).to eq('api/v1/tickets/7') + end + + it 'inherits searchability' do + expect(subclass.searchable?).to be(true) + end + + it 'inherits the filters its parent\'s search reads' do + expect(Class.new(ZammadAPI::Resources::User).search_filter_names).to eq(%i[role_ids group_ids permissions]) + end + + it 'has no search filters of its own unless it or a parent declares some' do + expect(subclass.search_filter_names).to eq([]) + end + + it 'takes filter names as strings too' do + subclass.search_filters 'role_ids' + + expect(subclass.search_filter_names).to eq([:role_ids]) + end + + it 'inherits the page limit' do + expect(subclass.page_limit).to eq(100) + end + + it 'inherits whether the index endpoint sorts' do + expect(subclass.sortable?).to be(false) + end + + it 'inherits the associations, as it always did' do + expect(subclass.associations.keys).to eq(ZammadAPI::Resources::Ticket.associations.keys) + end + + it 'lets a subclass declare a path of its own' do + own = Class.new(ZammadAPI::Resources::Ticket) { path 'api/v1/my_tickets' } + + expect(own.resource_path).to eq('api/v1/my_tickets') + end + + # An override has to win even when it is the falsey value, which is why + # the lookup asks whether the ivar is defined rather than whether it is + # truthy. + it 'lets a subclass declare itself unsearchable' do + own = Class.new(ZammadAPI::Resources::Ticket) { searchable false } + + expect(own.searchable?).to be(false) + end + end + + # Declared as bare constants, a misspelled override was silently ignored and + # the resource kept Base's default: SEARCHEABLE = true left the resource + # unsearchable, and every find_by on it raised "Zammad routes no search + # endpoint" with no hint that the declaration was the problem. + describe 'the endpoint declarations' do + it 'refuses a misspelled declaration at load' do + expect { Class.new(described_class) { searcheable true } } + .to raise_error(NoMethodError, /searcheable/) + end + + it 'defaults to unsearchable, so an unrouted /search is refused at the call site' do + expect(Class.new(described_class).searchable?).to be(false) + end + + it 'defaults to the generic index page limit' do + expect(Class.new(described_class).page_limit).to eq(described_class::DEFAULT_MAX_PER_PAGE) + end + + it 'defaults to an index endpoint that sorts, as the generic ones do' do + expect(Class.new(described_class).sortable?).to be(true) + end + + it 'records a declared page limit' do + expect(Class.new(described_class) { max_per_page 25 }.page_limit).to eq(25) + end + + it 'records a declaration that the index endpoint does not sort' do + expect(Class.new(described_class) { sortable false }.sortable?).to be(false) + end + + it 'declares tickets and users unsortable, whose controllers hardcode the order' do + expect([ZammadAPI::Resources::Ticket, ZammadAPI::Resources::User].map(&:sortable?)).to eq([false, false]) + end + end + + # The id is what addresses the record. Staged, it took effect for every path + # that builds a path from the attributes and not at all for the record those + # paths then reported on: `group.id = 99; group.destroy` sent DELETE to group + # 99 and left the record saying group 1 was the one destroyed. + # The parent is resolved before MEMO_LOCK is taken, because resolving it may + # build the parent's own proxy through this same method and a Mutex is not + # reentrant. Folded back inside the lock this raises + # `ThreadError: deadlock; recursive locking`, and a caller subclassing a + # resource is the case that lock exists to cover in the first place. + describe 'the association proxy of a subclass whose parent has none yet' do + it 'builds without deadlocking on the memo lock' do + leaf = Class.new(Class.new(ZammadAPI::Resources::Group)) + + expect(leaf.related_class).to be_a(Class) + end + end + + # `record[:x] = v` reached method_missing as `:[]=`, which the writer branch + # took for an attribute called `[]`: it staged the index as the value, lost + # the write, and sent `{"[]": "x"}` on the next save. + describe '#[]=' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } + + it 'stages the attribute it names' do + group[:note] = 'x' + + expect(group.changes).to eq({ note: [nil, 'x'] }) + end + + it 'reads back through the matching reader' do + group[:note] = 'x' + + expect(group[:note]).to eq('x') + end + + it 'takes a string key the way the reader does' do + group['note'] = 'x' + + expect(group[:note]).to eq('x') + end + + it 'refuses what the named writer refuses' do + expect { group[:id] = 9 }.to raise_error(ZammadAPI::Error, /cannot be staged as an attribute/) + end + + it 'invents no attribute from the operator itself' do + group[:note] = 'x' + + expect(group.attributes.keys).not_to include(:[]) + end + + it 'is claimed by a record that stages writes' do + expect(group).to respond_to(:[]=) + end + + it 'is claimed under either spelling' do + # rubocop:disable-next Performance/StringIdentifierArgument -- the String spelling is the point + expect(group.respond_to?('[]=')).to be(true) + end + + # The production case for recognising a writer by name rather than by a + # trailing `=`: on a record that stages writes, an operator reached the + # writer branch and invented an attribute from its stem. + it 'invents no attribute from a comparison operator' do + expect { group.public_send(:<=, 5) }.to raise_error(NoMethodError) + + expect(group.attributes.keys).not_to include(:<) + end + + it 'stages nothing for a comparison operator' do + expect { group.public_send(:<=, 5) }.to raise_error(NoMethodError) + + expect(group).not_to be_changed + end + end + + describe 'writing the id' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } + + it 'is refused' do + expect { group.id = 99 }.to raise_error(ZammadAPI::Error, /is what addresses this record/) + end + + it 'points at the lookup that was meant' do + expect { group.id = 99 }.to raise_error(ZammadAPI::Error, /look up the record you meant with find\(99\)/) + end + + it 'is refused through assign_attributes too' do + expect { group.assign_attributes(id: 99) }.to raise_error(ZammadAPI::Error, /is what addresses this record/) + end + + # The message exists to name the id the caller passed, and the pre-check + # that runs for these two paths dropped it - so a serializer or a form + # binder, which reach the writer this way, were told to call find(nil). + it 'names the id that was passed through assign_attributes' do + expect { group.assign_attributes(id: 99) }.to raise_error(ZammadAPI::Error, /find\(99\)/) + end + + it 'names the id that was passed through update' do + expect { group.update(id: 99) }.to raise_error(ZammadAPI::Error, /find\(99\)/) + end + + it 'names the attribute it refused' do + expect { group.id = 99 }.to raise_error(ZammadAPI::Error, /Group#id cannot be staged/) + end + + # Checked before anything is written, not on the way past: refusing + # mid-loop staged the keys that came first and left the record dirty with + # half a change set, which is the state `update` takes its own guard one + # line early to avoid. + it 'stages nothing at all when one key in the hash is refused' do + expect { group.assign_attributes(name: 'X', id: 99, note: 'Y') }.to raise_error(ZammadAPI::Error) + + expect(group).not_to be_changed + expect(group.changes).to be_empty + end + + it 'leaves the attributes it had already reached alone' do + expect { group.assign_attributes(name: 'X', id: 99, note: 'Y') }.to raise_error(ZammadAPI::Error) + + expect(group.name).to eq('Users') + end + + it 'stages nothing through update either' do + expect { group.update(name: 'X', id: 99) }.to raise_error(ZammadAPI::Error) + + expect(group).not_to be_changed + end + + # A record that claimed a writer and then raised when it was called would + # defeat the point of asking, and lead a serializer or form binder straight + # into the exception it was checking to avoid. + it 'does not claim a writer it would refuse' do + expect(group).not_to respond_to(:id=) + end + + it 'still claims the writers it honours' do + expect(group).to respond_to(:name=) + end + + it 'leaves the record addressing what it did before' do + expect { group.id = 99 }.to raise_error(ZammadAPI::Error) + + expect(group.id).to eq(1) + expect(group).not_to be_changed + end + + # The constructor was the one door that did not make this refusal, and + # the only one whose value reached the wire: a new record is sent in full, + # so `new(id: 5).save` POSTed the id nothing had checked. + it 'is refused by the constructor too' do + expect { client.groups.new(id: 5) }.to raise_error(ZammadAPI::Error, /is what addresses this record/) + end + + it 'still lets a record Zammad served carry one' do + expect(ZammadAPI::Resources::Group.from_response(unit_transport, id: 5).id).to eq(5) + end + end + + # The third way a record ends up persisted without an id, and the one that + # has nothing to do with a save: Zammad serves a reduced object where the + # authenticated user may not see the whole record, which is the same thing + # #write_attribute is written around. Such a record used to be told it "was + # saved, but the response carried no id" - sending the caller to look at a + # save that never happened, when what they need is which user the client + # authenticates as. + describe 'a record Zammad served without an id' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, name: 'Users') } + + it 'refuses a reload it cannot address' do + expect { group.reload }.to raise_error(ZammadAPI::Error, /was loaded without an id/) + end + + it 'points at what this client may read' do + expect { group.destroy }.to raise_error(ZammadAPI::Error, /check what this client may read/) + end + + it 'does not claim a save that never happened' do + expect { group.reload }.to raise_error(ZammadAPI::Error) { |error| expect(error.message).not_to include('was saved') } + end + + it 'does not tell the caller to save a record Zammad already holds' do + expect { group.destroy }.to raise_error(ZammadAPI::Error) { |error| expect(error.message).not_to include('save it first') } + end + + it 'refuses a save it cannot address' do + group.name = 'Support' + + expect { group.save! }.to raise_error(ZammadAPI::Error, /was loaded without an id/) + end + + it 'still says the record was saved where a save is what left it this way' do + stub_request(:post, url).with(query: hash_including({})).to_return(status: 201, body: 'proxy') + new_group = client.groups.new(name: 'Support') + begin + new_group.save + rescue ZammadAPI::ParseError + nil + end + + expect { new_group.reload }.to raise_error(ZammadAPI::Error, /was saved, but the response carried no id/) + end + end + + # What makes a record persisted is that Zammad answered 2xx, not that the + # answer parsed. Decoded first, a create whose 201 carried an HTML error + # page from an intervening proxy raised ParseError with the record still + # looking new - so the ticket existed in Zammad and a retried save POSTed a + # second one. Marked persisted, the record has no id to be addressed by + # either, and nothing staged to send, so the retry has to say so rather than + # take the "nothing to send" short circuit and report success. + describe 'a create whose success body cannot be parsed' do + subject(:group) { client.groups.new(name: 'Support') } + + before { stub_request(:post, url).with(query: hash_including({})).to_return(status: 201, body: 'proxy') } + + it 'still reports the parse failure' do + expect { group.save }.to raise_error(ZammadAPI::ParseError) + end + + it 'does not leave the record looking unsaved' do + begin + group.save + rescue ZammadAPI::ParseError + nil + end + + expect(group.new_record?).to be(false) + end + + it 'does not create a second record when the save is retried' do + 2.times do + group.save + rescue ZammadAPI::Error + nil + end + + expect(a_request(:post, url).with(query: hash_including({}))).to have_been_made.once + end + + it 'refuses the retried save rather than reporting it stored' do + begin + group.save + rescue ZammadAPI::ParseError + nil + end + + expect { group.save }.to raise_error(ZammadAPI::Error, /carried no id/) + end + + it 'refuses to reload a record it cannot address' do + begin + group.save + rescue ZammadAPI::ParseError + nil + end + + expect { group.reload }.to raise_error(ZammadAPI::Error, /carried no id/) + end + + it 'does not tell the caller to save a record that was already saved' do + begin + group.save + rescue ZammadAPI::ParseError + nil + end + + expect { group.destroy }.to raise_error(ZammadAPI::Error, /was saved/) + end + + # An update keeps only what Zammad had served the record with. A record + # being created was served nothing, and what it sent is all there is to + # read from it. + it 'goes on reading everything it sent, written after it was built or not' do + group.note = 'Second line' + begin + group.save + rescue ZammadAPI::ParseError + nil + end + + expect(group.attributes).to eq(name: 'Support', note: 'Second line') + end + end + + # The same argument for what was staged. Zammad answered 2xx, so it applied + # the changes, and they used to stay staged because the body did not parse: + # the next save sent all of them again. For a ticket's `article` that is a + # second article and a second e-mail, from a save that was about the title. + describe 'an update whose success body cannot be parsed' do + subject(:ticket) { client.tickets.find(1) } + + let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/1" } + let(:article) { { body: 'Reset link sent.', type: 'email', to: 'customer@example.com' } } + + before do + stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, title: 'Help', note: nil })) + stub_request(:put, ticket_url).with(query: hash_including({})) + .to_return({ status: 200, body: 'proxy' }, json_response({ id: 1, title: 'Renamed' })) + + ticket.article = article + begin + ticket.save + rescue ZammadAPI::ParseError + nil + end + end + + it 'still reports the parse failure' do + other = client.tickets.find(1) + other.note = 'x' + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(status: 200, body: 'proxy') + + expect { other.save }.to raise_error(ZammadAPI::ParseError) + end + + it 'no longer holds the changes Zammad acknowledged as staged' do + expect(ticket.changed?).to be(false) + expect(ticket.changes).to eq({}) + end + + it 'does not send the acknowledged changes again with the next save' do + ticket.title = 'Renamed' + ticket.save + + expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { title: 'Renamed' })).to have_been_made.once + expect(a_request(:put, ticket_url).with(query: hash_including({}), body: hash_including('article' => anything))).to have_been_made.once + end + + it 'sends nothing for a save with nothing new staged' do + expect(ticket.save).to be(true) + expect(a_request(:put, ticket_url).with(query: hash_including({}))).to have_been_made.once + end + + it 'goes on reading the values it sent for the attributes Zammad serves' do + other = client.tickets.find(1) + other.title = 'Sent' + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(status: 200, body: 'proxy') + begin + other.save + rescue ZammadAPI::ParseError + nil + end + + expect(other.title).to eq('Sent') + expect(other.attributes).to eq(id: 1, title: 'Sent', note: nil) + end + + # `article` is not an attribute of a ticket. It is a command in the body + # of the PUT, and Zammad never serves it back. Settled into the baseline + # with the attributes, it was remembered as the ticket's own state, and + # the same article assigned again compared equal to it. + it 'does not keep a key Zammad never served the record with' do + expect(ticket.key?(:article)).to be(false) + expect(ticket.attributes).to eq(id: 1, title: 'Help', note: nil) + end + + it 'stages the same article when it is assigned again' do + ticket.article = article + + expect(ticket.changes).to eq(article: [nil, article]) + end + + it 'sends the same article again when it is assigned again, as a second reply' do + ticket.article = article + ticket.save + + expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { article: article })).to have_been_made.twice + end + + it 'stages a value written back to what it was before the save, which Zammad no longer holds' do + other = client.tickets.find(1) + other.title = 'Sent' + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(status: 200, body: 'proxy') + begin + other.save + rescue ZammadAPI::ParseError + nil + end + + other.title = 'Help' + + expect(other.changes).to eq(title: %w[Sent Help]) + end + + it 'is brought up to date by a reload' do + stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, title: 'Help', article_count: 2 })) + ticket.reload + + expect(ticket.key?(:article)).to be(false) + expect(ticket.article_count).to eq(2) + end + + it 'keeps a change Zammad rejected staged, to be corrected and sent again' do + other = client.tickets.find(1) + other.title = '' + stub_request(:put, ticket_url).with(query: hash_including({})) + .to_return(json_response({ error: 'Title is required' }, status: 422)) + + expect(other.save).to be(false) + expect(other.changes).to eq(title: ['Help', '']) + end + + # What Zammad acknowledged is what the request carried. The baseline used + # to be taken from the record once the answer was in, so a write that + # landed while the request was out - from a logger or a middleware of the + # caller's that reaches the record, or from another thread - was settled + # along with it, for a value that was never sent. + context 'when the record is written to while the request is out' do + subject(:other) { client.tickets.find(1) } + + before do + stub_request(:put, ticket_url).with(query: hash_including({})).to_return do + other.title = 'C' + { status: 200, body: 'proxy' } + end + + other.title = 'B' + begin + other.save + rescue ZammadAPI::ParseError + nil + end + end + + it 'sent the value that was staged when the request left' do + expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { title: 'B' })).to have_been_made.once + end + + it 'reads the value Zammad was sent, not the one written since' do + expect(other.title).to eq('B') + end + + it 'has nothing staged, as after a response it could read' do + expect(other.changes).to eq({}) + end + + it 'stages the later value when it is written again' do + other.title = 'C' + + expect(other.changes).to eq(title: %w[B C]) + end + end + + # The interval before that one: between the attributes being held and the + # request being built from them. Nothing of the caller's runs there on one + # thread, so the path being built stands in for a second thread writing to + # the record. The body used to be read from the change set at that point, + # so the PUT carried "C" and the record was settled on "B". + context 'when the record is written to before the request is built' do + subject(:other) { client.tickets.find(1) } + + before do + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(status: 200, body: 'proxy') + + other.title = 'B' + allow(ZammadAPI::Resources::Ticket).to receive(:member_path).and_wrap_original do |original, id| + other.title = 'C' + original.call(id) + end + begin + other.save + rescue ZammadAPI::ParseError + nil + end + end + + it 'sent the value that was held when the save began' do + expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { title: 'B' })).to have_been_made.once + end + + it 'reads the value it sent, with nothing staged' do + expect(other.title).to eq('B') + expect(other.changes).to eq({}) + end + end + + # Settling the record on what it sent is a write to its foreign keys like + # any other, and what the association proxy resolved from a value written + # meanwhile is not the answer for the one the record is put back on. + context 'when an association is resolved from a key written while the request is out' do + subject(:other) { client.tickets.find(1) } + + let(:related) { other.related } + + before do + stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, customer_id: 3 })) + [9, 10].each do |id| + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/#{id}").with(query: hash_including({})).to_return(json_response({ id: id })) + end + stub_request(:put, ticket_url).with(query: hash_including({})).to_return do + other.customer_id = 10 + related.customer + { status: 200, body: 'proxy' } + end + + other.customer_id = 9 + begin + other.save + rescue ZammadAPI::ParseError + nil + end + end + + it 'is back on the key it sent' do + expect(other.customer_id).to eq(9) + end + + it 'resolves the association from the key it sent, on a proxy held from before' do + expect(related.customer.id).to eq(9) + end + end + + # The same write under a response that can be read, which is what the + # above is held to: the attributes it carries replace the record's. + it 'drops a write made while the request was out where the response can be read, too' do + other = client.tickets.find(1) + stub_request(:put, ticket_url).with(query: hash_including({})).to_return do + other.title = 'C' + json_response({ id: 1, title: 'B' }) + end + other.update!(title: 'B') + + expect(other.title).to eq('B') + expect(other.changes).to eq({}) + end + end +end diff --git a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb new file mode 100644 index 0000000..5145926 --- /dev/null +++ b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb @@ -0,0 +1,152 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Resources::TicketArticleAttachment do + let(:transport) { unit_transport } + let(:download_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_attachment/42/9/3" } + + describe 'built from an article' do + subject(:attachment) { article.attachments.first } + + let(:article) do + ZammadAPI::Resources::TicketArticle.from_response( + transport, + id: 9, + ticket_id: 42, + attachments: [{ id: 3, filename: 'note.txt', size: '12' }] + ) + end + + it 'carries the attachment id' do + expect(attachment.id).to eq(3) + end + + it 'is the same attachment as another read of it' do + expect(attachment).to eq(article.attachments.first) + end + + it 'is not the attachment with that id on another Zammad instance' do + elsewhere = ZammadAPI::Resources::TicketArticle + .from_response(unit_transport(url: 'http://other.test/'), article.to_h) + .attachments.first + + expect(attachment).not_to eq(elsewhere) + expect([attachment, elsewhere].uniq.size).to eq(2) + end + + it 'carries the filename' do + expect(attachment.filename).to eq('note.txt') + end + + it 'is given the ticket id, which the attachment endpoint needs' do + expect(attachment.ticket_id).to eq(42) + end + + it 'is given the article id' do + expect(attachment.article_id).to eq(9) + end + + it 'returns an empty list when the article has no attachments' do + bare = ZammadAPI::Resources::TicketArticle.from_response(transport, id: 9) + expect(bare.attachments).to eq([]) + end + + # This metadata comes off a response body like any other, and an element + # that is not an object reached `raw.merge` and died there as a bare + # NoMethodError from inside the gem - past the `rescue ZammadAPI::Error` + # every caller is told to write. + it 'refuses metadata that is not a list' do + article = ZammadAPI::Resources::TicketArticle.from_response(transport, id: 9, attachments: 'none') + + expect { article.attachments } + .to raise_error(ZammadAPI::ParseError, /expected a JSON array of objects, got String/) + end + + it 'refuses a list holding something that is not an object' do + article = ZammadAPI::Resources::TicketArticle.from_response(transport, id: 9, attachments: [3]) + + expect { article.attachments } + .to raise_error(ZammadAPI::ParseError, /got an array holding Integer/) + end + + it 'names the article in the refusal' do + article = ZammadAPI::Resources::TicketArticle.from_response(transport, id: 9, attachments: 'none') + + expect { article.attachments } + .to raise_error(ZammadAPI::ParseError, /ZammadAPI::Resources::TicketArticle/) + end + end + + describe '#download' do + subject(:attachment) { described_class.new(transport, id: 3, ticket_id: 42, article_id: 9) } + + it 'requests the attachment endpoint' do + stub = stub_request(:get, download_url).to_return(status: 200, body: 'contents') + attachment.download + expect(stub).to have_been_requested + end + + it 'returns the file contents' do + stub_request(:get, download_url).to_return(status: 200, body: 'contents') + expect(attachment.download).to eq('contents') + end + + it 'returns binary data undisturbed' do + png = "\x89PNG\r\n\x1A\n\x00\xFF".b + stub_request(:get, download_url) + .to_return(status: 200, body: png, headers: { 'Content-Type' => 'image/png' }) + + expect(attachment.download).to eq(png) + end + + it 'uses binary encoding' do + stub_request(:get, download_url).to_return(status: 200, body: 'contents') + expect(attachment.download.encoding).to eq(Encoding::BINARY) + end + + it 'raises when the attachment is gone' do + stub_request(:get, download_url).to_return(json_response({ error: 'not found' }, status: 404)) + expect { attachment.download }.to raise_error(ZammadAPI::NotFoundError) + end + + it 'raises a helpful error when the metadata is incomplete' do + expect { described_class.new(transport, id: 3).download }.to raise_error(KeyError) + end + + it 'escapes a traversal in an id instead of reaching another endpoint' do + stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/ticket_attachment/1%2F..%2F..%2F..%2Fapi%2Fv1%2Fusers/9/3") + .to_return(status: 200, body: 'contents') + escaping = described_class.new(transport, id: 3, ticket_id: '1/../../../api/v1/users', article_id: 9) + + escaping.download + + expect(stub).to have_been_requested + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/9/3")).not_to have_been_made + end + + it 'escapes the article id and the attachment id too' do + stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/ticket_attachment/42/9%2F..%2Fx/3%2F..%2Fy") + .to_return(status: 200, body: 'contents') + + described_class.new(transport, id: '3/../y', ticket_id: 42, article_id: '9/../x').download + + expect(stub).to have_been_requested + end + end + + it 'is read-only' do + attachment = described_class.new(transport, id: 3) + expect { attachment.filename = 'other.txt' }.to raise_error(NoMethodError, /read-only/) + end + + it 'does not claim a writer it would refuse' do + expect(described_class.new(transport, id: 3)).not_to respond_to(:filename=) + end + + describe '#inspect' do + it 'summarizes the attachment' do + attachment = described_class.new(transport, id: 3, filename: 'note.txt', size: '12') + expect(attachment.inspect) + .to eq('#') + end + end +end diff --git a/spec/unit/zammad_api/resources/ticket_spec.rb b/spec/unit/zammad_api/resources/ticket_spec.rb new file mode 100644 index 0000000..ea42c82 --- /dev/null +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -0,0 +1,216 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Resources::Ticket do + subject(:ticket) { described_class.from_response(unit_transport, id: 42, title: 'Help') } + + let(:articles_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_articles/by_ticket/42" } + let(:article_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_articles" } + + describe '#articles' do + it 'requests the articles of this ticket' do + stub = stub_request(:get, articles_url).with(query: { 'expand' => 'true' }).to_return(json_response([])) + ticket.articles + expect(stub).to have_been_requested + end + + it 'returns article records' do + stub_request(:get, articles_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, body: 'first' }, { id: 2, body: 'second' }])) + + expect(ticket.articles.map(&:body)).to eq(%w[first second]) + end + + it 'returns persisted articles' do + stub_request(:get, articles_url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + + expect(ticket.articles.first).to be_persisted + end + + it 'raises ParseError when the response is not a list' do + stub_request(:get, articles_url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect { ticket.articles }.to raise_error(ZammadAPI::ParseError, /expected a JSON array, got Hash/) + end + end + + describe 'once destroyed' do + let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/42" } + + before do + stub_request(:delete, ticket_url).with(query: hash_including({})).to_return(json_response({})) + ticket.destroy + end + + # Each of these says what the caller gets, not which ivar was cleared. + # `destroy` dropped the `related` memo and was taken to have closed this, + # but the reader rebuilt one on the next call, so every path below went + # on reaching a ticket that is gone. + it 'refuses the articles reader rather than fetching a deleted ticket' do + expect { ticket.articles }.to raise_error(ZammadAPI::Error, /was destroyed/) + end + + it 'refuses the related proxy' do + expect { ticket.related }.to raise_error(ZammadAPI::Error, /was destroyed/) + end + + it 'refuses to add an article rather than POSTing a dead ticket_id' do + expect { ticket.add_article(body: 'hello') }.to raise_error(ZammadAPI::Error, /was destroyed/) + end + + it 'makes no request at all when an article is refused' do + stub = stub_request(:post, article_url).with(query: hash_including({})) + begin + ticket.add_article(body: 'hello') + rescue ZammadAPI::Error # rubocop:disable Lint/SuppressedException + end + + expect(stub).not_to have_been_requested + end + end + + describe '#add_article' do + it 'creates the article for this ticket' do + stub = stub_request(:post, article_url) + .with(query: { 'expand' => 'true' }, body: '{"body":"hello","ticket_id":42}') + .to_return(json_response({ id: 9, body: 'hello', ticket_id: 42 }, status: 201)) + + ticket.add_article(body: 'hello') + expect(stub).to have_been_requested + end + + it 'returns the created article' do + stub_request(:post, article_url).with(query: hash_including({})) + .to_return(json_response({ id: 9, body: 'hello' }, status: 201)) + + expect(ticket.add_article(body: 'hello')).to be_a(ZammadAPI::Resources::TicketArticle) + end + + it 'returns a persisted article' do + stub_request(:post, article_url).with(query: hash_including({})) + .to_return(json_response({ id: 9 }, status: 201)) + + expect(ticket.add_article(body: 'hello')).to be_persisted + end + + # The article goes to the ticket it was added to, whatever the attributes + # say. Given `ticket_id` under both spellings, the Symbol was replaced and + # the String, coming later in the Hash, replaced it again when the article + # symbolized its keys - so the POST named the caller's ticket. + context 'when the attributes name a ticket of their own' do + before do + stub_request(:post, article_url).with(query: hash_including({})) + .to_return(json_response({ id: 9, ticket_id: 42 }, status: 201)) + end + + def posted_ticket_ids + ids = [] + expect(a_request(:post, article_url).with(query: hash_including({})) { |request| ids << JSON.parse(request.body)['ticket_id'] }) + .to have_been_made.once + ids + end + + it 'uses its own id over a Symbol key' do + ticket.add_article(ticket_id: 9, body: 'hello') + expect(posted_ticket_ids).to eq([42]) + end + + it 'uses its own id over a String key' do + ticket.add_article('body' => 'hello', 'ticket_id' => 9) + expect(posted_ticket_ids).to eq([42]) + end + + it 'uses its own id over both spellings at once' do + ticket.add_article(:ticket_id => 1, 'ticket_id' => 9, :body => 'hello', :type => 'note') + expect(posted_ticket_ids).to eq([42]) + end + + it 'sends ticket_id once' do + ticket.add_article(:ticket_id => 1, 'ticket_id' => 9, :body => 'hello') + + expect(a_request(:post, article_url).with(query: hash_including({}), body: '{"body":"hello","ticket_id":42}')).to have_been_made + end + + it 'leaves the Hash it was given as it was' do + attributes = { :ticket_id => 1, 'ticket_id' => 9, :body => 'hello' } + ticket.add_article(attributes) + + expect(attributes).to eq(:ticket_id => 1, 'ticket_id' => 9, :body => 'hello') + end + end + + # An article belongs to a ticket by id. Unchecked, this POSTed + # `ticket_id: null` and left the caller reading Zammad's 422 to work out + # that the ticket had never been saved. + context 'when the ticket has not been saved' do + subject(:ticket) { described_class.new(unit_transport, title: 'Help') } + + it 'refuses locally' do + expect { ticket.add_article(body: 'hello') }.to raise_error(ZammadAPI::Error, /has no id, save it first/) + end + + it 'sends nothing' do + stub = stub_request(:post, article_url).with(query: hash_including({})) + + begin + ticket.add_article(body: 'hello') + rescue ZammadAPI::Error + nil + end + + expect(stub).not_to have_been_requested + end + end + end + + # The name the method had in 1.x: a noun that sends a POST, one letter away + # from the reader beside it. + describe '#article' do + around do |example| + enabled = Warning[:deprecated] + Warning[:deprecated] = true + example.run + ensure + Warning[:deprecated] = enabled + end + + before do + stub_request(:post, article_url).with(query: hash_including({})) + .to_return(json_response({ id: 9, body: 'hello', ticket_id: 42 }, status: 201)) + end + + it 'still adds the article' do + added = nil + + expect { added = ticket.article(body: 'hello') }.to output.to_stderr + expect(added.id).to eq(9) + end + + it 'warns, naming the replacement' do + expect { ticket.article(body: 'hello') } + .to output(/ZammadAPI::Resources::Ticket#article is deprecated and will be removed in 3\.0: use #add_article instead/).to_stderr + end + + it 'names the line that made the call' do + expect { ticket.article(body: 'hello') }.to output(/#{Regexp.escape(__FILE__)}:#{__LINE__}: warning: /).to_stderr + end + + it 'says nothing unless deprecation warnings are on' do + Warning[:deprecated] = false + expect { ticket.article(body: 'hello') }.not_to output.to_stderr + end + + it 'does not warn for add_article' do + expect { ticket.add_article(body: 'hello') }.not_to output.to_stderr + end + + # It reads like the attribute a ticket is created with, and with a + # default it sent a POST naming nothing but the ticket. 1.x required the + # attributes. + it 'requires the attributes, as 1.x did, and sends nothing without them' do + ticket.article = { body: 'reply' } + + expect { ticket.article }.to raise_error(ArgumentError, /wrong number of arguments/) + expect(a_request(:post, article_url).with(query: hash_including({}))).not_to have_been_made + end + end +end diff --git a/spec/unit/zammad_api/response_error_spec.rb b/spec/unit/zammad_api/response_error_spec.rb new file mode 100644 index 0000000..97ac85c --- /dev/null +++ b/spec/unit/zammad_api/response_error_spec.rb @@ -0,0 +1,197 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::ResponseError do + def response(status, body, headers = {}) + ZammadAPI::Response.new( + status: status, + headers: headers, + body: body, + raw_body: body.is_a?(String) ? body : JSON.generate(body), + json: !body.is_a?(String) + ) + end + + describe 'hierarchy' do + { + ZammadAPI::ConfigurationError => ZammadAPI::Error, + ZammadAPI::UnknownResourceError => ZammadAPI::Error, + ZammadAPI::ParseError => ZammadAPI::Error, + ZammadAPI::ConnectionError => ZammadAPI::TransportError, + ZammadAPI::TimeoutError => ZammadAPI::TransportError, + ZammadAPI::ClientError => described_class, + ZammadAPI::ServerError => described_class, + ZammadAPI::AuthenticationError => ZammadAPI::ClientError, + ZammadAPI::AuthorizationError => ZammadAPI::ClientError, + ZammadAPI::NotFoundError => ZammadAPI::ClientError, + ZammadAPI::ValidationError => ZammadAPI::ClientError, + ZammadAPI::RateLimitError => ZammadAPI::ClientError + }.each do |error_class, parent| + it "#{error_class} descends from #{parent}" do + expect(error_class.ancestors).to include(parent) + end + end + + it 'roots every error at ZammadAPI::Error' do + expect(ZammadAPI::TransportError.ancestors).to include(ZammadAPI::Error) + end + + it 'roots ZammadAPI::Error at StandardError' do + expect(ZammadAPI::Error.ancestors).to include(StandardError) + end + end + + describe '.build' do + { + 401 => ZammadAPI::AuthenticationError, + 403 => ZammadAPI::AuthorizationError, + 404 => ZammadAPI::NotFoundError, + 422 => ZammadAPI::ValidationError, + 429 => ZammadAPI::RateLimitError, + 400 => ZammadAPI::ClientError, + 408 => ZammadAPI::ClientError, + 418 => ZammadAPI::ClientError, + 500 => ZammadAPI::ServerError, + 502 => ZammadAPI::ServerError, + 503 => ZammadAPI::ServerError + }.each do |status, error_class| + it "maps #{status} to #{error_class}" do + result = described_class.build(response(status, {}), operation: 'find object') + expect(result).to be_an_instance_of(error_class) + end + end + + it 'falls back to the base class without a response' do + expect(described_class.build(nil, operation: 'find object')).to be_an_instance_of(described_class) + end + end + + describe '#message' do + it "uses the body's error key" do + error = described_class.build( + response(404, { error: 'User not found' }), + operation: 'find object', + resource_class: ZammadAPI::Resources::User + ) + expect(error.message).to eq("Can't find object (ZammadAPI::Resources::User): User not found") + end + + it 'prefers error_human, which Zammad intends for end users' do + error = described_class.build( + response(422, { error: 'Validation failed', error_human: 'Name is required' }), + operation: 'save object' + ) + expect(error.message).to eq("Can't save object: Name is required") + end + + it 'falls back to the status when the body is not JSON' do + error = described_class.build( + response(502, 'Bad Gateway'), + operation: 'find object', + resource_class: ZammadAPI::Resources::User + ) + expect(error.message).to eq("Can't find object (ZammadAPI::Resources::User): HTTP 502") + end + + it 'falls back to the status when the body has no error key' do + error = described_class.build(response(400, { foo: 'bar' }), operation: 'find object') + expect(error.message).to eq("Can't find object: HTTP 400") + end + + it 'falls back to the status when the error value is empty' do + error = described_class.build(response(500, { error: '' }), operation: 'find object') + expect(error.message).to eq("Can't find object: HTTP 500") + end + + it 'reports a missing response' do + expect(described_class.build(nil, operation: 'find object').message) + .to eq("Can't find object: no response") + end + + it 'omits the resource class when none was supplied' do + error = described_class.build(response(404, { error: 'nope' }), operation: 'find object') + expect(error.message).to eq("Can't find object: nope") + end + end + + describe 'accessors' do + subject(:error) do + described_class.build( + response(404, { error: 'nope' }, 'x-request-id' => 'abc'), + operation: 'find object', + resource_class: ZammadAPI::Resources::User + ) + end + + it 'exposes the status' do + expect(error.status).to eq(404) + end + + it 'exposes the decoded body' do + expect(error.body).to eq({ error: 'nope' }) + end + + it 'exposes the headers' do + expect(error.headers).to eq('x-request-id' => 'abc') + end + + it 'exposes the operation' do + expect(error.operation).to eq('find object') + end + + it 'exposes the resource class' do + expect(error.resource_class).to eq(ZammadAPI::Resources::User) + end + + it 'exposes the server message' do + expect(error.server_message).to eq('nope') + end + + it 'returns nil accessors without a response' do + bare = described_class.build(nil, operation: 'find object') + expect([bare.status, bare.body, bare.headers, bare.server_message]).to eq([nil, nil, {}, nil]) + end + + # A NotFoundError this gem raises itself - find_by! finding nothing - used + # to answer nil here, so `retry if e.status == 404` stopped retrying for + # the one NotFoundError that did not come from Zammad. + it 'reports the status its class is the name for, without a response' do + bare = ZammadAPI::NotFoundError.new(operation: 'find object by name', detail: 'no record matched') + expect(bare.status).to eq(404) + end + + it 'still has no body or headers to report without a response' do + bare = ZammadAPI::NotFoundError.new(operation: 'find object by name', detail: 'no record matched') + expect([bare.body, bare.headers]).to eq([nil, {}]) + end + + it 'leaves a generic ResponseError without a status' do + expect(described_class.new(operation: 'find object').status).to be_nil + end + end + + describe ZammadAPI::RateLimitError do + it 'exposes Retry-After as an integer' do + error = ZammadAPI::ResponseError.build( + ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => '30' }, body: {}, raw_body: '{}', json: true), + operation: 'find object' + ) + expect(error.retry_after).to eq(30) + end + + it 'returns nil when the header is absent' do + error = ZammadAPI::ResponseError.build( + ZammadAPI::Response.new(status: 429, headers: {}, body: {}, raw_body: '{}', json: true), + operation: 'find object' + ) + expect(error.retry_after).to be_nil + end + + it 'returns nil when the header is not a number' do + error = ZammadAPI::ResponseError.build( + ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => 'later' }, body: {}, raw_body: '{}', json: true), + operation: 'find object' + ) + expect(error.retry_after).to be_nil + end + end +end diff --git a/spec/unit/zammad_api/response_spec.rb b/spec/unit/zammad_api/response_spec.rb new file mode 100644 index 0000000..e7f7fd9 --- /dev/null +++ b/spec/unit/zammad_api/response_spec.rb @@ -0,0 +1,158 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Response do + def build(status: 200, body: { a: 1 }, raw_body: '{"a":1}', headers: {}, json: !body.is_a?(String)) + described_class.new(status: status, headers: headers, body: body, raw_body: raw_body, json: json) + end + + describe '#success?' do + [200, 201, 204, 299].each do |status| + it "is true for #{status}" do + expect(build(status: status)).to be_success + end + end + + [199, 300, 400, 500].each do |status| + it "is false for #{status}" do + expect(build(status: status)).not_to be_success + end + end + end + + describe '#json?' do + it 'is true when the body was decoded' do + expect(build).to be_json + end + + it 'is false when the body is the untouched raw body' do + raw = '' + expect(build(body: raw, raw_body: raw)).not_to be_json + end + + it 'reports what the decoder recorded, not whether the two bodies differ' do + expect(build(body: '"a string"', raw_body: '"a string"', json: true)).to be_json + end + end + + describe '#decoded' do + it 'returns an object body when one is expected' do + expect(build(body: { a: 1 }).decoded(:object, operation: 'find object')).to eq(a: 1) + end + + it 'returns an array body when one is expected' do + expect(build(body: [{ a: 1 }]).decoded(:array, operation: 'get list')).to eq([{ a: 1 }]) + end + + it 'raises when an object was expected but a list arrived' do + expect { build(body: []).decoded(:object, operation: 'find object') } + .to raise_error(ZammadAPI::ParseError, "Can't find object: expected a JSON object, got Array") + end + + it 'raises when a list was expected but an object arrived' do + expect { build(body: {}).decoded(:array, operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array, got Hash") + end + + it 'raises when the body was never JSON' do + expect { build(body: '', raw_body: '').decoded(:object, operation: 'find object') } + .to raise_error(ZammadAPI::ParseError, /got String/) + end + + it 'names the resource class in the message' do + expect { build(body: []).decoded(:object, operation: 'find object', resource_class: ZammadAPI::Resources::User) } + .to raise_error(/\(ZammadAPI::Resources::User\)/) + end + + it 'accepts an empty list' do + expect(build(body: []).decoded(:array, operation: 'get list')).to eq([]) + end + + # An unexpanded search answers with ids. Passing them on stored an Integer + # as a record's attributes, and the first reader died with a TypeError + # from deep inside the gem. + it 'raises for a list of scalars rather than building records from them' do + expect { build(body: [1, 2, 3]).decoded(:array, operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array of objects, got an array holding Integer") + end + + it 'raises for a list that is only partly objects' do + expect { build(body: [{ id: 1 }, 'nope']).decoded(:array, operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, /an array holding String/) + end + + # `find` cannot tell "no offender" from "the offender is nil", so a null + # passed as an object and the first read of it died with NoMethodError. + it 'raises for a list holding a null' do + expect { build(body: [nil]).decoded(:array, operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array of objects, got an array holding NilClass") + end + + it 'raises for a null among the objects of a list' do + expect { build(body: [{ id: 1 }, nil, { id: 3 }]).decoded(:array, operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, /an array holding NilClass/) + end + + it 'names the resource class when a list element has the wrong shape' do + expect { build(body: [1]).decoded(:array, operation: 'get list', resource_class: ZammadAPI::Resources::User) } + .to raise_error(/\(ZammadAPI::Resources::User\)/) + end + end + + # A list is an array, and a search asked for its total answers with an + # object holding the array and the figure. A walk reads either. + describe '#decoded_list' do + it 'returns an array body, and no total' do + expect(build(body: [{ a: 1 }]).decoded_list(operation: 'get list')).to eq([[{ a: 1 }], nil]) + end + + it 'returns the records and the total of a counted list' do + expect(build(body: { records: [{ a: 1 }], total_count: 7 }).decoded_list(operation: 'get list')).to eq([[{ a: 1 }], 7]) + end + + it 'accepts a counted list with no records' do + expect(build(body: { records: [], total_count: 0 }).decoded_list(operation: 'get list')).to eq([[], 0]) + end + + it 'reports a negative total as none, and keeps the records' do + expect(build(body: { records: [{ a: 1 }], total_count: -1 }).decoded_list(operation: 'get list')).to eq([[{ a: 1 }], nil]) + end + + it 'reports a total that is not a number as none' do + expect(build(body: { records: [], total_count: '7' }).decoded_list(operation: 'get list')).to eq([[], nil]) + end + + it 'raises for records that are not objects' do + expect { build(body: { records: [1, 2], total_count: 2 }).decoded_list(operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array of objects, got an array holding Integer") + end + + it 'raises for a null among the records of a counted list' do + expect { build(body: { records: [nil, { a: 1 }], total_count: 2 }).decoded_list(operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array of objects, got an array holding NilClass") + end + + it 'raises for an object that holds no records' do + expect { build(body: { total_count: 2 }).decoded_list(operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array, got Hash") + end + + it 'raises for records that are not a list' do + expect { build(body: { records: 'none', total_count: 0 }).decoded_list(operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, /expected a JSON array, got Hash/) + end + + it 'raises when the body was never JSON' do + expect { build(body: '', raw_body: '').decoded_list(operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, /got String/) + end + + it 'names the resource class in the message' do + expect { build(body: {}).decoded_list(operation: 'get list', resource_class: ZammadAPI::Resources::User) } + .to raise_error(/\(ZammadAPI::Resources::User\)/) + end + end + + it 'is immutable' do + expect(build).to be_frozen + end +end diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb new file mode 100644 index 0000000..142f00d --- /dev/null +++ b/spec/unit/zammad_api/transport_spec.rb @@ -0,0 +1,1614 @@ +# frozen_string_literal: true + +require 'pp' + +RSpec.describe ZammadAPI::Transport do + let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } + + describe 'authentication' do + it 'sends a Token header for an access token' do + stub = stub_request(:get, url).with(headers: { 'Authorization' => 'Token test-token' }).to_return(json_response([])) + unit_transport.get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + + it 'sends a Bearer header for an OAuth2 token' do + stub = stub_request(:get, url).with(headers: { 'Authorization' => 'Bearer oauth' }).to_return(json_response([])) + unit_transport(http_token: nil, oauth2_token: 'oauth').get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + + it 'sends basic auth for user and password' do + stub = stub_request(:get, url).with(basic_auth: %w[u p]).to_return(json_response([])) + unit_transport(http_token: nil, user: 'u', password: 'p').get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + end + + describe 'default headers' do + it 'identifies the client' do + stub = stub_request(:get, url) + .with(headers: { 'User-Agent' => "zammad_api-ruby/#{ZammadAPI::VERSION}" }) + .to_return(json_response([])) + unit_transport.get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + + it 'asks for JSON' do + stub = stub_request(:get, url).with(headers: { 'Accept' => 'application/json' }).to_return(json_response([])) + unit_transport.get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + + it 'allows overriding the user agent' do + stub = stub_request(:get, url).with(headers: { 'User-Agent' => 'my-app/1.0' }).to_return(json_response([])) + unit_transport(user_agent: 'my-app/1.0').get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + + # Net::HTTP refused it at the request, quoting the value. + it 'refuses a raw request header with a line break inside it, without quoting it' do + expect { described_class.stringify_headers('X-Api-Key' => "abc\r\nsecret") } + .to raise_error(ArgumentError, /\Aheader x-api-key holds a line break, which a header cannot carry/) { |error| + expect(error.message).not_to include('secret') + } + end + + it 'takes one that only ends in a line break, which Net::HTTP strips' do + expect(described_class.stringify_headers('X-Note' => "abc\n")).to eq('x-note' => "abc\n") + end + + it 'carries a header value given in UTF-16 as the same text in UTF-8' do + expect(described_class.stringify_headers('X-Note' => 'ä'.encode('UTF-16LE'))).to eq('x-note' => 'ä') + end + end + + describe 'base url handling' do + it 'keeps a sub-path prefix in front of the request path' do + stub = stub_request(:get, 'http://zammad.test/helpdesk/api/v1/groups').to_return(json_response([])) + unit_transport(url: 'http://zammad.test/helpdesk').get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + end + + describe 'query parameters' do + it 'encodes scalars as strings' do + stub = stub_request(:get, url).with(query: { 'page' => '1', 'expand' => 'true' }).to_return(json_response([])) + unit_transport.get('api/v1/groups', operation: 'test', query: { page: 1, expand: true }) + expect(stub).to have_been_requested + end + + it 'escapes values that need it' do + stub = stub_request(:get, "#{url}/search").with(query: { 'query' => 'a b&c' }).to_return(json_response([])) + unit_transport.get('api/v1/groups/search', operation: 'test', query: { query: 'a b&c' }) + expect(stub).to have_been_requested + end + + it 'encodes arrays' do + stub = stub_request(:get, url).with(query: { 'ids' => %w[1 2] }).to_return(json_response([])) + unit_transport.get('api/v1/groups', operation: 'test', query: { ids: [1, 2] }) + expect(stub).to have_been_requested + end + + # `condition` is what Zammad's search endpoints narrow by, and it is + # nested. Rendered with to_s it went out as a Ruby inspect string, which + # Zammad dropped, answering an unnarrowed search. + it 'encodes a nested hash the way Rails reads it back' do + stub = stub_request(:get, "#{url}/search") + .with(query: { 'condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => %w[1 2] } } }) + .to_return(json_response([])) + unit_transport.get( + 'api/v1/groups/search', + operation: 'test', + query: { condition: { 'ticket.state_id' => { operator: 'is', value: [1, 2] } } } + ) + expect(stub).to have_been_requested + end + + it 'stringifies the scalars inside a nested hash' do + expect(described_class.stringify_query(condition: { open: { active: true, limit: 5 } })) + .to eq({ 'condition' => { 'open' => { 'active' => 'true', 'limit' => '5' } } }) + end + + # Faraday's escaping raised Encoding::CompatibilityError for one. + it 'sends a value given in UTF-16 as the same text in UTF-8' do + stub = stub_request(:get, "#{url}/search").with(query: { 'query' => 'ä b' }).to_return(json_response([])) + unit_transport.get('api/v1/groups/search', operation: 'test', query: { query: 'ä b'.encode('UTF-16LE') }) + expect(stub).to have_been_requested + end + + it 'leaves a value in an encoding ASCII is a part of as it was' do + value = "caf\xC3\xA9".b + + expect(described_class.stringify_query(q: value)['q']).to be(value) + end + + it 'refuses a value that cannot be converted to UTF-8, without quoting it' do + broken = "\xD8\x00".dup.force_encoding('UTF-16BE') + + expect { described_class.stringify_query(token: broken) } + .to raise_error(ArgumentError, /\Aquery parameter token was given as UTF-16BE text that cannot be converted to UTF-8/) + end + + it 'raises on a nil value rather than dropping the parameter' do + expect { unit_transport.get('api/v1/groups', operation: 'test', query: { page: 1, note: nil }) } + .to raise_error(ArgumentError, /query parameter note is nil/) + end + + it 'names the path to a nil buried in a nested value' do + expect { described_class.stringify_query(condition: { state: { value: nil } }) } + .to raise_error(ArgumentError, /parameter condition\[state\]\[value\] is nil/) + end + + it 'refuses two spellings of one parameter rather than sending whichever came last' do + expect { described_class.stringify_query(state_id: 1, 'state_id' => 2) } + .to raise_error(ArgumentError, /parameter state_id was given twice/) + end + + it 'refuses the collision whichever order it arrives in' do + expect { described_class.stringify_query('state_id' => 2, state_id: 1) } + .to raise_error(ArgumentError, /parameter state_id was given twice/) + end + + it 'names both spellings, so the caller does not have to guess the other' do + expect { described_class.stringify_query(state_id: 1, 'state_id' => 2) } + .to raise_error(ArgumentError, /as :state_id and as "state_id"/) + end + + # `condition` is a Hash the search endpoints read, and two spellings inside + # it collapsed exactly the way two at the top level did. + it 'refuses a collision nested inside a structured parameter' do + expect { described_class.stringify_query(condition: { 'state_id' => 1, state_id: 2 }) } + .to raise_error(ArgumentError, /parameter condition\[state_id\] was given twice/) + end + + it 'still sends a structured parameter whose keys only look alike' do + expect(described_class.stringify_query(condition: { 'ticket.state_id' => { operator: 'is' } })) + .to eq({ 'condition' => { 'ticket.state_id' => { 'operator' => 'is' } } }) + end + + it 'still accepts two parameters that only look alike' do + expect(described_class.stringify_query(state_id: 1, state_ids: [2])) + .to eq({ 'state_id' => '1', 'state_ids' => ['2'] }) + end + + it 'names the index of a nil inside an array' do + expect { described_class.stringify_query(ids: [1, nil]) } + .to raise_error(ArgumentError, /query parameter ids\[1\] is nil/) + end + + it 'makes no request for a query it rejects' do + stub = stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) + + expect { unit_transport.get('api/v1/groups', operation: 'test', query: { note: nil }) } + .to raise_error(ArgumentError) + expect(stub).not_to have_been_requested + end + + # A query string does not mark where an element of a list ends. Rails + # begins a new one where a pair names a place the element it is filling + # has taken already, so a list is refused where it would not be read + # back as the list it was: the request would carry something the caller + # did not write, to an endpoint that narrows by it. + describe 'a list a query string cannot carry' do + it 'refuses a Hash that shares no key with the one before it, which Rails would read into it' do + expect { described_class.stringify_query(condition: { conditions: [{ a: 1 }, { b: 2 }] }) } + .to raise_error(ArgumentError, /query parameter condition\[conditions\]\[1\] has no plain value under a key the element before it has as well/) + end + + it 'refuses one that shares a key holding only a list' do + expect { described_class.stringify_query(list: [{ value: [1] }, { value: [2] }]) } + .to raise_error(ArgumentError, /Rails would read the two as one/) + end + + it 'refuses a Hash with nothing in it, which is not written at all' do + expect { described_class.stringify_query(list: [{ a: 1 }, {}]) } + .to raise_error(ArgumentError, /query parameter list\[1\] is a Hash with no value in it.*one element short/) + end + + it 'refuses a list directly inside a list' do + expect { described_class.stringify_query(list: [[1, 2], [3]]) } + .to raise_error(ArgumentError, /query parameter list\[0\] is a list directly inside a list/) + end + + it 'says where such a structure can be sent as it is' do + expect { described_class.stringify_query(list: [{ a: 1 }, { b: 2 }]) } + .to raise_error(ArgumentError, /put it in the JSON body of a raw request, such as client\.post/) + end + + it 'takes a group of conditions beside a condition, which share an operator' do + conditions = [{ name: 'ticket.state_id', operator: 'is', value: [2] }, { operator: 'AND', conditions: [{ name: 'a', operator: 'is', value: 1 }] }] + + expect(described_class.stringify_query(condition: { operator: 'OR', conditions: conditions }).dig('condition', 'conditions', 1, 'operator')).to eq('AND') + end + + it 'takes Hashes among plain values, each of which begins an element of its own' do + expect(described_class.stringify_query(list: [{ a: 1 }, 2, { b: 3 }])).to eq('list' => [{ 'a' => '1' }, '2', { 'b' => '3' }]) + end + + it 'makes no request for one' do + stub = stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) + + expect { unit_transport.get('api/v1/groups', operation: 'test', query: { list: [{ a: 1 }, { b: 2 }] }) }.to raise_error(ArgumentError) + expect(stub).not_to have_been_requested + end + end + + # A query string has no way to write a key with an empty name: `[]` + # inside a structure, which Rails reads as a list, and nothing but the + # value at the top level, which Rails drops. + describe 'a key with an empty name' do + it 'refuses one in a Hash inside a list, which Rails would read as a list' do + expect { described_class.stringify_query(list: [{ '' => '1' }]) } + .to raise_error(ArgumentError, /query parameter list\[0\] holds a key with an empty name.*list\[0\]\[\], which Rails reads as a list/) + end + + it 'refuses one in a Hash further down' do + expect { described_class.stringify_query(condition: { a: { '' => '1' } }) } + .to raise_error(ArgumentError, /query parameter condition\[a\] holds a key with an empty name/) + end + + it 'refuses one given as an empty Symbol' do + expect { described_class.stringify_query(condition: { '': '1' }) }.to raise_error(ArgumentError, /holds a key with an empty name/) + end + + it 'refuses one at the top level, which Rails drops' do + expect { described_class.stringify_query('' => '1') }.to raise_error(ArgumentError, /a query parameter has an empty name.*which Rails drops/) + end + + it 'still takes a Hash in a list with an ordinary key' do + expect(described_class.stringify_query(list: [{ 'a' => '1' }])).to eq('list' => [{ 'a' => '1' }]) + end + + it 'still takes a key that is a space' do + expect(described_class.stringify_query(condition: { ' ' => '1' })).to eq('condition' => { ' ' => '1' }) + end + end + + # Read off the URL Faraday built, in the order it was written: WebMock + # sorts a query before it compares one, and the order is the point. See + # the QueryEncoder specs for why this is the order Rails needs. + it 'writes the query with the encoder that keeps a list of Hashes apart' do + sent = nil + recorder = Class.new(Faraday::Middleware) do + define_method(:on_request) { |env| sent = URI.decode_www_form(env.url.query).map(&:first) } + end + stub_request(:get, "#{url}/search").with(query: hash_including({})).to_return(json_response([])) + + unit_transport(middleware: ->(builder) { builder.use(recorder) }).get( + 'api/v1/groups/search', + operation: 'test', + query: { condition: { conditions: [{ name: 'a', operator: 'is', value: 1 }, { operator: 'AND', conditions: [{ name: 'b', operator: 'is', value: 2 }] }] } } + ) + + expect(sent.drop(3).first(2)).to eq(['condition[conditions][][operator]', 'condition[conditions][][conditions][][name]']) + end + end + + # The path is printed in the log, in the message of a timeout and in the + # operation a raw request is named by, and a raw request may carry its + # query in it. + describe '.redact_path' do + it 'leaves a path without a query as it is' do + expect(described_class.redact_path('api/v1/tickets/1')).to eq('api/v1/tickets/1') + end + + it 'blanks the value of a parameter named like a credential' do + expect(described_class.redact_path('api/v1/x?token=s3cret')).to eq('api/v1/x?token=[REDACTED]') + end + + it 'keeps every other parameter as it was written' do + expect(described_class.redact_path('api/v1/x?page=2&password=s3cret&q=a%20b')).to eq('api/v1/x?page=2&password=[REDACTED]&q=a%20b') + end + + it 'reads a name that was percent-encoded' do + expect(described_class.redact_path('api/v1/x?user%5Bpassword%5D=s3cret')).to eq('api/v1/x?user%5Bpassword%5D=[REDACTED]') + end + + it 'blanks a value whose name cannot be read' do + expect(described_class.redact_path('api/v1/x?%zz=s3cret')).to eq('api/v1/x?%zz=[REDACTED]') + end + + it 'keeps a parameter with no value' do + expect(described_class.redact_path('api/v1/x?expand&token=s3cret')).to eq('api/v1/x?expand&token=[REDACTED]') + end + + it 'blanks a value that holds a = of its own' do + expect(described_class.redact_path('api/v1/x?token=a=b')).to eq('api/v1/x?token=[REDACTED]') + end + end + + describe '.escape_path_segment' do + it 'leaves an ordinary id alone' do + expect(described_class.escape_path_segment(42)).to eq('42') + end + + it 'encodes a separator, so an id cannot walk out of its segment' do + expect(described_class.escape_path_segment('1/../../api/v1/users/1')) + .to eq('1%2F..%2F..%2Fapi%2Fv1%2Fusers%2F1') + end + + it 'encodes a query and fragment marker' do + expect(described_class.escape_path_segment('1?a=b#c')).to eq('1%3Fa%3Db%23c') + end + + it 'encodes a multibyte character one byte at a time' do + expect(described_class.escape_path_segment('ä')).to eq('%C3%A4') + end + + it 'raises for an id with nothing to send' do + expect { described_class.escape_path_segment('') }.to raise_error(ArgumentError, /record id is required/) + end + + it 'raises for a parent dot segment, which the unreserved set would carry through' do + expect { described_class.escape_path_segment('..') }.to raise_error(ArgumentError, /points at another endpoint/) + end + + it 'raises for a current-directory dot segment' do + expect { described_class.escape_path_segment('.') }.to raise_error(ArgumentError, /points at another endpoint/) + end + + it 'leaves an id that merely starts with dots alone' do + expect(described_class.escape_path_segment('..1')).to eq('..1') + end + + it 'encodes an already-encoded dot segment rather than passing it on' do + expect(described_class.escape_path_segment('%2e%2e')).to eq('%252e%252e') + end + end + + describe 'request bodies' do + it 'sends JSON with the matching content type' do + stub = stub_request(:post, url) + .with(body: '{"name":"Support"}', headers: { 'Content-Type' => 'application/json' }) + .to_return(json_response({ id: 1 }, status: 201)) + unit_transport.post('api/v1/groups', operation: 'test', body: { name: 'Support' }) + expect(stub).to have_been_requested + end + + it 'sends a body that is already a string as it is' do + stub = stub_request(:post, url) + .with(body: '{"name":"Raw"}', headers: { 'Content-Type' => 'application/json' }) + .to_return(json_response({ id: 1 }, status: 201)) + unit_transport.post('api/v1/groups', operation: 'test', body: '{"name":"Raw"}') + expect(stub).to have_been_requested + end + + # Faraday's JSON middleware raised JSON::GeneratorError from inside the + # stack and nothing mapped it, so it went past the rescue of + # ZammadAPI::Error every caller is told to write. + context 'with a body that cannot be encoded as JSON' do + let(:binary) { { data: "\xFF\xD8\xFF".b } } + + it 'raises a ZammadAPI::Error for bytes that are not text' do + expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary) } + .to raise_error(ZammadAPI::Error, /Can't save object: the request body cannot be encoded as JSON/) + end + + it 'raises a ZammadAPI::Error for a Float that JSON has no spelling for' do + expect { unit_transport.put('api/v1/groups/1', operation: 'save object', body: { weight: Float::NAN }) } + .to raise_error(ZammadAPI::Error, /NaN not allowed in JSON/) + end + + it 'says what to do about binary data' do + expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary) } + .to raise_error(ZammadAPI::Error, /Base64-encode binary data/) + end + + it 'names the resource it was sending' do + expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary, resource_class: ZammadAPI::Resources::Group) } + .to raise_error(ZammadAPI::Error, /save object \(ZammadAPI::Resources::Group\)/) + end + + it 'makes no request' do + expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary) }.to raise_error(ZammadAPI::Error) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'leaves no log line claiming a request that was never made' do + log = StringIO.new + expect { unit_transport(logger: Logger.new(log)).post('api/v1/groups', operation: 'save object', body: binary) } + .to raise_error(ZammadAPI::Error) + expect(log.string).to be_empty + end + + it 'is raised by a record save carrying such a value' do + group = unit_client.groups.new(name: 'Support', weight: Float::INFINITY) + expect { group.save }.to raise_error(ZammadAPI::Error, /Infinity not allowed in JSON/) + end + end + end + + describe 'response decoding' do + it 'decodes JSON with symbol keys' do + stub_request(:get, url).to_return(json_response({ id: 1, nested: { a: 'b' } })) + response = unit_transport.get('api/v1/groups', operation: 'test') + expect(response.body).to eq({ id: 1, nested: { a: 'b' } }) + end + + it 'exposes the raw body as well' do + stub_request(:get, url).to_return(json_response({ id: 1 })) + response = unit_transport.get('api/v1/groups', operation: 'test') + expect(response.raw_body).to eq('{"id":1}') + end + + it 'leaves non-JSON bodies untouched' do + stub_request(:get, url).to_return(status: 200, body: 'plain text', headers: { 'Content-Type' => 'text/plain' }) + response = unit_transport.get('api/v1/groups', operation: 'test') + expect(response.body).to eq('plain text') + end + + it 'keeps a malformed JSON body as a string instead of raising' do + stub_request(:get, url).to_return(status: 200, body: 'not json', headers: { 'Content-Type' => 'application/json' }) + response = unit_transport.get('api/v1/groups', operation: 'test') + expect(response.body).to eq('not json') + end + + it 'handles an empty body' do + stub_request(:get, url).to_return(status: 200, body: '', headers: { 'Content-Type' => 'application/json' }) + response = unit_transport.get('api/v1/groups', operation: 'test') + expect(response.body).to eq('') + end + + it 'downcases header names' do + stub_request(:get, url).to_return(json_response([], headers: { 'X-Request-Id' => 'abc' })) + response = unit_transport.get('api/v1/groups', operation: 'test') + expect(response.headers['x-request-id']).to eq('abc') + end + end + + describe 'error responses' do + it 'raises NotFoundError for 404' do + stub_request(:get, url).to_return(json_response({ error: 'nope' }, status: 404)) + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::NotFoundError, "Can't find object: nope") + end + + it 'raises AuthenticationError for 401' do + stub_request(:get, url).to_return(json_response({ error: 'authentication failed' }, status: 401)) + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::AuthenticationError) + end + + it 'raises ServerError with the status when a proxy returns HTML' do + stub_request(:get, url).to_return(status: 502, body: 'Bad Gateway', headers: { 'Content-Type' => 'text/html' }) + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::ServerError, "Can't find object: HTTP 502") + end + + it 'includes the resource class in the message' do + stub_request(:get, url).to_return(json_response({ error: 'nope' }, status: 404)) + expect { unit_transport.get('api/v1/groups', operation: 'find object', resource_class: ZammadAPI::Resources::Group) } + .to raise_error(/\(ZammadAPI::Resources::Group\)/) + end + end + + describe 'network failures' do + it 'wraps a read timeout' do + stub_request(:get, url).to_raise(Net::ReadTimeout) + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError, %r{Can't find object: request to api/v1/groups timed out}) + end + + it 'keeps a credential in a query written into the path out of the message' do + stub_request(:get, url).with(query: hash_including({})).to_raise(Net::ReadTimeout) + expect { unit_transport.get('api/v1/groups?token=path-s3cret', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError, %r{request to api/v1/groups\?token=\[REDACTED\] timed out}) + end + + # Net::HTTP raises Net::OpenTimeout for it, and the default adapter wraps + # that into Faraday::ConnectionFailed with every other failure to connect, + # so it was reported as an unreachable host and skipped the rescue that is + # documented to catch it. + context 'when the connection is not established within open_timeout' do + before { stub_request(:get, url).to_raise(Net::OpenTimeout.new('execution expired')) } + + it 'raises TimeoutError, not ConnectionError' do + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError) + end + + it 'says it was the connection that timed out' do + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(%r{Can't find object: connecting to http://zammad\.test/ timed out \(execution expired\)}) + end + + it 'is still retried, as a read that never reached the server' do + expect { unit_transport(retries: 2, retry_interval: 0.01).get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError) + expect(a_request(:get, url)).to have_been_made.times(3) + end + end + + it 'reports the timeout WebMock simulates as one' do + stub_request(:get, url).to_timeout + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError) + end + + it 'reads a timeout out of a connection failure that only wraps one' do + stub_request(:get, url).to_raise(Faraday::ConnectionFailed.new(Errno::ETIMEDOUT.new)) + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError, /connecting to/) + end + + it 'wraps a refused connection' do + stub_request(:get, url).to_raise(Errno::ECONNREFUSED) + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::ConnectionError, /is unreachable/) + end + + it 'wraps a TLS failure' do + stub_request(:get, url).to_raise(OpenSSL::SSL::SSLError) + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::ConnectionError, /TLS handshake/) + end + + it 'names the instance it could not reach' do + stub_request(:get, url).to_raise(Faraday::ConnectionFailed.new('down')) + + expect { unit_transport.get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ConnectionError, %r{http://zammad\.test/ is unreachable}) + end + + context 'with an adapter that does not wrap socket errors' do + # The middleware seam raises from inside the stack, past the point where + # an adapter would normally translate the error into a Faraday one. + def raising(error) + unit_transport(middleware: lambda { |faraday| + faraday.use(Class.new(Faraday::Middleware) { define_method(:call) { |_env| raise error } }) + }) + end + + it 'wraps a bare Errno::ETIMEDOUT' do + expect { raising(Errno::ETIMEDOUT).get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError, /timed out/) + end + + it 'wraps a bare Timeout::Error' do + expect { raising(Timeout::Error).get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError) + end + + it 'wraps a bare Errno::ECONNREFUSED' do + expect { raising(Errno::ECONNREFUSED).get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::ConnectionError, /is unreachable/) + end + + it 'wraps a SocketError' do + expect { raising(SocketError).get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::ConnectionError) + end + + it 'leaves an unrelated Errno alone rather than calling it a network problem' do + expect { raising(Errno::ENOSPC).get('api/v1/groups', operation: 'find object') } + .to raise_error(Errno::ENOSPC) + end + end + + it 'raises a TransportError subclass so both can be rescued together' do + stub_request(:get, url).to_raise(Errno::ECONNREFUSED) + expect { unit_transport.get('api/v1/groups', operation: 'find object') } + .to raise_error(ZammadAPI::TransportError) + end + end + + describe 'retries' do + it 'retries an idempotent request after a server error' do + stub_request(:get, url).to_return({ status: 500 }, json_response([{ id: 1 }])) + response = unit_transport(retries: 2, retry_interval: 0.01).get('api/v1/groups', operation: 'test') + expect(response.status).to eq(200) + end + + it 'retries after a rate limit response' do + stub_request(:get, url).to_return({ status: 429 }, json_response([])) + response = unit_transport(retries: 1, retry_interval: 0.01).get('api/v1/groups', operation: 'test') + expect(response.status).to eq(200) + end + + # The retry middleware sleeps for whatever Retry-After says, and its own + # ceiling defaults to none: this held the calling thread for an hour per + # retry before raising the error it could have raised at once. + context 'when the server asks for a longer wait than the timeout' do + let(:transport) { unit_transport(retries: 2, retry_interval: 0.01, timeout: 2) } + + before do + stub_request(:get, url).to_return({ status: 429, headers: { 'Retry-After' => '3600' } }, json_response([])) + end + + it 'reports the response instead of waiting it out' do + expect { transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::RateLimitError) + end + + it 'does not retry' do + expect { transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::RateLimitError) + expect(a_request(:get, url)).to have_been_made.once + end + + it 'leaves the wait the server asked for readable from the error' do + expect { transport.get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::RateLimitError) { |error| expect(error.retry_after).to eq(3600) } + end + end + + it 'does not wait out a long Retry-After on a 503 either' do + stub_request(:get, url).to_return({ status: 503, headers: { 'Retry-After' => '3600' } }, json_response([])) + + expect { unit_transport(retries: 2, retry_interval: 0.01, timeout: 2).get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ServerError) + expect(a_request(:get, url)).to have_been_made.once + end + + it 'still waits as long as the server asks, where that is within the timeout' do + stub_request(:get, url).to_return({ status: 429, headers: { 'Retry-After' => '0.2' } }, json_response([])) + + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + response = unit_transport(retries: 1, retry_interval: 0.01).get('api/v1/groups', operation: 'test') + + expect(response.status).to eq(200) + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be >= 0.2 + end + + it 'gives up after the configured number of attempts' do + stub_request(:get, url).to_return(status: 500) + expect { unit_transport(retries: 1, retry_interval: 0.01).get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ServerError) + expect(a_request(:get, url)).to have_been_made.twice + end + + it 'does not retry POST, which could duplicate records' do + stub_request(:post, url).to_return(status: 500) + expect { unit_transport(retries: 2, retry_interval: 0.01).post('api/v1/groups', operation: 'test', body: { a: 1 }) } + .to raise_error(ZammadAPI::ServerError) + expect(a_request(:post, url)).to have_been_made.once + end + + # A ticket update carrying an article creates that article on every + # delivery, so repeating it sent the article - and its e-mail - twice. + it 'does not retry PUT, which Zammad does not always handle idempotently' do + stub_request(:put, "#{url}/1").to_return({ status: 504 }, json_response({ id: 1 })) + expect { unit_transport(retries: 2, retry_interval: 0.01).put('api/v1/groups/1', operation: 'test', body: { a: 1 }) } + .to raise_error(ZammadAPI::ServerError) + expect(a_request(:put, "#{url}/1")).to have_been_made.once + end + + it 'does not retry PUT after a timeout either' do + stub_request(:put, "#{url}/1").to_raise(Net::ReadTimeout).then.to_return(json_response({ id: 1 })) + expect { unit_transport(retries: 2, retry_interval: 0.01).put('api/v1/groups/1', operation: 'test', body: { a: 1 }) } + .to raise_error(ZammadAPI::TimeoutError) + expect(a_request(:put, "#{url}/1")).to have_been_made.once + end + + # Repeated after a lost answer, the second DELETE met a 404 and reported a + # record that had just been deleted as one that could not be found. + it 'does not retry DELETE, which would answer a lost success with a 404' do + stub_request(:delete, "#{url}/1").to_raise(Net::ReadTimeout).then.to_return(json_response({ error: 'gone' }, status: 404)) + expect { unit_transport(retries: 2, retry_interval: 0.01).delete('api/v1/groups/1', operation: 'test') } + .to raise_error(ZammadAPI::TimeoutError) + expect(a_request(:delete, "#{url}/1")).to have_been_made.once + end + + it 'does not retry a client error' do + stub_request(:get, url).to_return(json_response({ error: 'nope' }, status: 404)) + expect { unit_transport(retries: 2, retry_interval: 0.01).get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::NotFoundError) + expect(a_request(:get, url)).to have_been_made.once + end + end + + # Most adapters wrap a socket failure into Faraday::ConnectionFailed, which + # was retried; the same failure raw was not, so how often a request was + # retried depended on which adapter the caller picked - through an option + # this gem offers. + describe 'retries through an adapter that does not wrap socket errors' do + before { BareSocketAdapter.attempts = [] } + + def bare_socket_transport(**overrides) + unit_transport(adapter: :bare_socket, retry_interval: 0.01, **overrides) + end + + it 'retries an unwrapped socket error as often as a wrapped one' do + expect { bare_socket_transport(retries: 2).get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ConnectionError) + expect(BareSocketAdapter.attempts.size).to eq(3) + end + + it 'still maps it to ConnectionError once the retries are spent' do + expect { bare_socket_transport(retries: 1).get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ConnectionError, /is unreachable/) + end + + it 'does not repeat a POST, which could duplicate records' do + expect { bare_socket_transport(retries: 2).post('api/v1/groups', operation: 'test', body: { a: 1 }) } + .to raise_error(ZammadAPI::ConnectionError) + expect(BareSocketAdapter.attempts).to eq([:post]) + end + + it 'retries every socket failure it maps to ConnectionError' do + expect(described_class::RETRIABLE_EXCEPTIONS).to include(*described_class::CONNECTION_ERRORS) + end + + it 'retries every socket failure it maps to TimeoutError' do + expect(described_class::RETRIABLE_EXCEPTIONS).to include(*described_class::TIMEOUT_ERRORS) + end + end + + describe 'the Faraday seam' do + it 'calls the middleware with the connection being built' do + seen = nil + unit_transport(middleware: ->(connection) { seen = connection }) + + expect(seen).to be_a(Faraday::Connection) + end + + it 'lets the middleware see a request this gem built' do + stub_request(:get, url).to_return(json_response([])) + + seen = nil + transport = unit_transport(middleware: lambda { |builder| + builder.use(Class.new(Faraday::Middleware) do + define_method(:on_request) { |env| seen = env.request_headers['User-Agent'] } + end) + }) + transport.get('api/v1/groups', operation: 'test') + + expect(seen).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + end + + it 'lets the middleware see the response' do + stub_request(:get, url).to_return(json_response([{ id: 1 }])) + + seen = nil + transport = unit_transport(middleware: lambda { |builder| + builder.use(Class.new(Faraday::Middleware) do + define_method(:on_complete) { |env| seen = env.status } + end) + }) + transport.get('api/v1/groups', operation: 'test') + + expect(seen).to eq(200) + end + + # `c.response :json` is a reasonable thing to put through a documented + # seam, and Faraday then hands over a Hash rather than the bytes. `to_s` + # turned that into a Ruby inspect string, which JSON.parse refused, so + # every record built from the response died in Response#decoded with a + # ParseError naming Zammad for what the caller's own stack had done. + # + # Re-encoding the parsed structure was the other way out, and it is worse: + # `raw_body` is what an attachment download hands back as the file, so a + # re-encoding returns something Zammad never stored. The bytes are gone + # either way, so this names the cause while it is still visible. + context 'with middleware that decodes the body first' do + it 'refuses it when the stack is built, before anything is sent' do + expect { unit_transport(middleware: ->(builder) { builder.response(:json) }) } + .to raise_error(ZammadAPI::ConfigurationError, /decodes the response body before this gem can/) + end + + it 'names the middleware it found' do + expect { unit_transport(middleware: ->(builder) { builder.response(:json) }) } + .to raise_error(ZammadAPI::ConfigurationError, /Faraday::Response::Json/) + end + + it 'says which middleware to drop' do + expect { unit_transport(middleware: ->(builder) { builder.response(:json) }) } + .to raise_error(ZammadAPI::ConfigurationError, /c\.response :json/) + end + + it 'is catchable as the gem error every caller rescues' do + expect { unit_transport(middleware: ->(builder) { builder.response(:json) }) }.to raise_error(ZammadAPI::Error) + end + + # The check used to live in `decode`, which is one request too late: the + # POST went out, Zammad created the record, and only then did a + # "configuration" error come back - so a caller retrying it made a second. + it 'sends nothing before refusing' do + stub = stub_request(:post, url).with(query: hash_including({})) + + expect { unit_client(middleware: ->(builder) { builder.response(:json) }).groups.create(name: 'X') } + .to raise_error(ZammadAPI::ConfigurationError) + expect(stub).not_to have_been_requested + end + end + + # `c.response :raise_error` is in most Faraday stacks people have written + # before, so it is what a caller adds by habit. It sits below the retry + # middleware and raises for a 4xx or 5xx before this gem sees the + # response: a GET answered 503 left as Faraday::ServerError without being + # retried, and a 404 as Faraday::ResourceNotFound rather than the + # NotFoundError that `exists?` and every caller's rescue are written for. + context 'with middleware that raises for an error status first' do + let(:raising) { ->(builder) { builder.response(:raise_error) } } + + it 'refuses it when the stack is built' do + expect { unit_transport(middleware: raising) } + .to raise_error(ZammadAPI::ConfigurationError, /raises a Faraday error for a 4xx or 5xx response before this gem sees it/) + end + + it 'names the middleware it found' do + expect { unit_transport(middleware: raising) } + .to raise_error(ZammadAPI::ConfigurationError, /the configured middleware includes Faraday::Response::RaiseError/) + end + + it 'says which middleware to drop' do + expect { unit_transport(middleware: raising) }.to raise_error(ZammadAPI::ConfigurationError, /drop `c\.response :raise_error`/) + end + + it 'refuses it where it was added by class' do + expect { unit_transport(middleware: ->(builder) { builder.use(Faraday::Response::RaiseError) }) } + .to raise_error(ZammadAPI::ConfigurationError, /Faraday::Response::RaiseError/) + end + + # The stub is for the path `find(1)` asks, and answers with a group. One + # for the index, which this was, is not a request `find` makes, so the + # assertion below held whether or not the GET went out before the + # refusal. + it 'sends nothing before refusing' do + stub = stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) + + expect { unit_client(middleware: raising).groups.find(1) }.to raise_error(ZammadAPI::ConfigurationError) + expect(stub).not_to have_been_requested + end + end + + # A subclass has a name of its own, and only the name was asked. It is how + # a caller adjusts what `raise_error` raises, and what it inherits is the + # handler that raises before this gem sees the response. + context 'with a subclass of a middleware it refuses' do + let(:subclass) { stub_const('QuietRaiseError', Class.new(Faraday::Response::RaiseError)) } + + it 'refuses it for what it inherits' do + expect { unit_transport(middleware: ->(builder) { builder.use(subclass) }) } + .to raise_error(ZammadAPI::ConfigurationError, /raises a Faraday error for a 4xx or 5xx response before this gem sees it/) + end + + it 'names the subclass and the middleware it inherits from' do + expect { unit_transport(middleware: ->(builder) { builder.use(subclass) }) } + .to raise_error(ZammadAPI::ConfigurationError, /includes QuietRaiseError, a subclass of Faraday::Response::RaiseError, which raises/) + end + + # `c.response :raise_error` is not the line that added it. + it 'says to drop the subclass rather than the spelling its parent has' do + expect { unit_transport(middleware: ->(builder) { builder.use(subclass) }) } + .to raise_error(ZammadAPI::ConfigurationError, /it does neither: drop it from the `middleware:` callable\./) + end + + it 'refuses one that was never given a name' do + expect { unit_transport(middleware: ->(builder) { builder.use(Class.new(Faraday::Response::RaiseError)) }) } + .to raise_error(ZammadAPI::ConfigurationError, /includes an anonymous class, a subclass of Faraday::Response::RaiseError,/) + end + + it 'refuses a subclass of the decoding middleware too' do + expect { unit_transport(middleware: ->(builder) { builder.use(Class.new(Faraday::Response::Json)) }) } + .to raise_error(ZammadAPI::ConfigurationError, /decodes the response body before this gem can/) + end + + it 'sends nothing before refusing' do + stub = stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) + + expect { unit_client(middleware: ->(builder) { builder.use(subclass) }).groups.find(1) }.to raise_error(ZammadAPI::ConfigurationError) + expect(stub).not_to have_been_requested + end + end + + # The build-time check knows the two above by name; anything + # else that consumes the body is caught only once a response is in hand. + context 'with a decoder the build-time check does not know by name' do + subject(:transport) do + unit_transport(middleware: lambda { |builder| + builder.use(Class.new(Faraday::Middleware) do + def on_complete(env) = env.body = { id: 1 } + end) + }) + end + + before { stub_request(:get, url).to_return(json_response([{ id: 1 }])) } + + it 'builds, because nothing named is in the stack' do + expect { transport }.not_to raise_error + end + + it 'refuses the response rather than stringifying what it got' do + expect { transport.get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ConfigurationError, /decoded the response body before this gem could/) + end + + it 'names what it was handed instead of the body' do + expect { transport.get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ConfigurationError, /Faraday handed over Hash rather than the raw body/) + end + end + + it 'leaves a middleware that does not touch the body alone' do + stub_request(:get, url).to_return(json_response([{ id: 1, name: 'Users' }])) + + response = unit_transport(middleware: ->(builder) { builder.response(:logger, Logger.new(File::NULL)) }) + .get('api/v1/groups', operation: 'test') + + expect(response.body).to eq([{ id: 1, name: 'Users' }]) + end + + it 'uses the configured adapter' do + transport = unit_transport(adapter: :test) + expect(transport.instance_variable_get(:@connection).adapter.name).to include('Adapter::Test') + end + + it 'reports an unregistered adapter as a configuration error' do + expect { unit_transport(adapter: :nonsense) } + .to raise_error(ZammadAPI::ConfigurationError, /is not registered on Faraday::Adapter/) + end + + it 'does not leak a Faraday error out of the client constructor' do + expect { unit_client(adapter: :nonsense) }.to raise_error(ZammadAPI::ConfigurationError) + end + + # Only Faraday::Error used to be wrapped, so the failures that do not come + # from Faraday - the ones a caller is least equipped to place - escaped + # raw, past the `rescue ZammadAPI::ConfigurationError` the constructor is + # documented to need. + it 'reports a proxy that is not a url as a configuration error' do + expect { unit_transport(proxy: 'http://user:pa ss@host') } + .to raise_error(ZammadAPI::ConfigurationError, /URI::InvalidURIError/) + end + + it 'reports a middleware that raises as a configuration error' do + expect { unit_transport(middleware: ->(_) { raise NameError, 'boom' }) } + .to raise_error(ZammadAPI::ConfigurationError, /NameError: boom/) + end + + # The backtrace into the caller's own code is the one thing the message + # cannot carry, so the cause stays wherever it gives nothing away. + it 'keeps the error a middleware raised as the cause' do + failure = NameError.new('boom') + + expect { unit_transport(middleware: ->(_) { raise failure }) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be(failure) } + end + + # The middleware is on a line of its own on purpose. A NameError's report + # quotes the source line it was raised on, so with the proxy written on + # that line the report would carry the password after all - and the cause + # would be dropped, rightly. + it 'keeps it beside a proxy that carries credentials, where the report does not quote them' do + failure = NameError.new('boom') + raising = ->(_) { raise failure } + + expect { unit_transport(proxy: 'http://user:s3cret@proxyhost:3128', middleware: raising) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be(failure) } + end + + # Rendering a report is the error's own code, and this asks for it from + # inside the rescue that turns the error into a ConfigurationError. A + # `detailed_message` written without the `highlight:` keyword is all it + # takes: `full_message` passes it one and gets ArgumentError back. + context 'when the error a middleware raised cannot render its own report' do + let(:failure) do + Class.new(StandardError) do + def detailed_message = "unreadable: #{message}" + end.new('boom') + end + + it 'has a report that raises, which is what this is about' do + expect { failure.full_message(highlight: false) }.to raise_error(ArgumentError) + end + + it 'still reports a configuration error' do + expect { unit_transport(middleware: ->(_) { raise failure }) } + .to raise_error(ZammadAPI::ConfigurationError, /config could not be used to build a connection: .*: boom/) + end + + it 'drops the cause, which cannot be shown to quote nothing' do + expect { unit_transport(middleware: ->(_) { raise failure }) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_nil } + end + end + + it 'keeps the cause of an unregistered adapter' do + expect { unit_transport(adapter: :nonsense) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_a(Faraday::Error) } + end + + it 'does not relabel an error this gem raised itself' do + failure = ZammadAPI::NotFoundError.new(operation: 'test', resource_class: nil, detail: 'gone') + + expect { unit_transport(middleware: ->(_) { raise failure }) } + .to raise_error(ZammadAPI::NotFoundError) + end + end + + describe '#with_on_behalf_of' do + it 'sends the From header' do + stub = stub_request(:get, url).with(headers: { 'From' => 'agent@example.com' }).to_return(json_response([])) + unit_transport.with_on_behalf_of('agent@example.com').get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + + it 'sends an integer user id, which Net::HTTP will not stringify itself' do + stub = stub_request(:get, url).with(headers: { 'From' => '42' }).to_return(json_response([])) + unit_transport.with_on_behalf_of(42).get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + + it 'records the scope as the string the header carries' do + expect(unit_transport.with_on_behalf_of(42).on_behalf_of).to eq('42') + end + + it 'keeps an unscoped transport unscoped' do + expect(unit_transport.with_on_behalf_of(nil).on_behalf_of).to be_nil + end + + # Every way to a From header goes through here, not only + # Client#on_behalf_of, and a header with nothing in it is no scope. + ['', ' ', "\u00A0"].each do |blank| + it "refuses #{blank.inspect}, which Zammad reads as no From header" do + expect { unit_transport.with_on_behalf_of(blank) }.to raise_error(ArgumentError, /on_behalf_of needs the login/) + end + end + + # The blank check raised Encoding::CompatibilityError for text in an + # encoding ASCII is no part of, for an identifier that names someone too. + it 'refuses an identifier with a line break inside it' do + expect { unit_transport.with_on_behalf_of("agent\nadmin") }.to raise_error(ArgumentError, /on_behalf_of holds a line break/) + end + + it 'refuses a blank identifier given in UTF-16' do + expect { unit_transport.with_on_behalf_of(' '.encode('UTF-16LE')) }.to raise_error(ArgumentError, /on_behalf_of needs the login/) + end + + it 'holds an identifier given in UTF-16 as the same text in UTF-8' do + expect(unit_transport.with_on_behalf_of('bob'.encode('UTF-16LE')).on_behalf_of).to eq('bob').and(have_attributes(encoding: Encoding::UTF_8)) + end + + # `String#to_s` hands back the receiver, so the scoped transport held the + # caller's own String: a login buffer reused after the scope was taken + # changed who every later request was performed for. + context 'when the string it was given changes afterwards' do + let(:login) { +'agent@example.com' } + let(:scoped) { unit_transport.with_on_behalf_of(login) } + + before do + scoped + login.replace('admin@example.com') + end + + it 'goes on sending the scope it was given' do + stub = stub_request(:get, url).with(headers: { 'From' => 'agent@example.com' }).to_return(json_response([])) + scoped.get('api/v1/groups', operation: 'test') + + expect(stub).to have_been_requested + end + + it 'goes on reporting the scope it was given' do + expect(scoped.on_behalf_of).to eq('agent@example.com') + end + end + + it 'holds the scope frozen' do + expect(unit_transport.with_on_behalf_of(+'agent@example.com').on_behalf_of).to be_frozen + end + + it 'leaves the string it was given writable' do + login = +'agent@example.com' + unit_transport.with_on_behalf_of(login) + + expect(login).not_to be_frozen + end + + it 'returns a different transport' do + transport = unit_transport + expect(transport.with_on_behalf_of('someone')).not_to be(transport) + end + + it 'leaves the original transport unscoped' do + transport = unit_transport + transport.with_on_behalf_of('someone') + expect(transport.on_behalf_of).to be_nil + end + + it 'does not send a From header from the original transport' do + transport = unit_transport + transport.with_on_behalf_of('someone') + + stub_request(:get, url).to_return(json_response([])) + transport.get('api/v1/groups', operation: 'test') + + expect(a_request(:get, url).with { |request| request.headers.key?('From') }).not_to have_been_made + end + + it 'shares the underlying connection instead of rebuilding it' do + transport = unit_transport + scoped = transport.with_on_behalf_of('someone') + expect(scoped.instance_variable_get(:@connection)).to be(transport.instance_variable_get(:@connection)) + end + end + + # Left to Ruby, inspect printed the Faraday connection, whose proxy options + # carry the proxy password and whose middleware stack carries the token it + # was built with. + describe '#inspect' do + let(:transport) do + unit_transport(http_token: 'tok-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') + end + + it 'names the instance and the authentication scheme' do + expect(unit_transport.inspect).to eq('#') + end + + it 'names an on_behalf_of scope' do + expect(unit_transport.with_on_behalf_of('agent@example.com').inspect).to include('on_behalf_of="agent@example.com"') + end + + it 'does not print the access token' do + expect(transport.inspect).not_to include('tok-s3cret') + end + + it 'does not print the proxy password' do + expect(transport.inspect).not_to include('pproxy-s3cret') + end + + it 'does not print a basic authentication password' do + basic = unit_transport(http_token: nil, user: 'u', password: 'pw-s3cret') + expect(basic.inspect).not_to include('pw-s3cret') + end + + it 'keeps both out of what pp prints too' do + expect(transport.pretty_inspect).not_to match(/tok-s3cret|pproxy-s3cret/) + end + end + + describe '#with_config' do + it 'applies the new configuration' do + expect(unit_transport.with_config(ZammadAPI::Config.new(**unit_config(timeout: 7))).config.timeout).to eq(7) + end + + it 'carries the on_behalf_of scope over' do + derived = unit_transport.with_on_behalf_of('agent@example.com') + .with_config(ZammadAPI::Config.new(**unit_config(timeout: 7))) + + expect(derived.on_behalf_of).to eq('agent@example.com') + end + + it 'keeps a subclass on its own kind, rather than reverting to a real one' do + recording = Class.new(described_class) + stub_const('RecordingTransport', recording) + + derived = recording.new(ZammadAPI::Config.new(**unit_config)).with_config(ZammadAPI::Config.new(**unit_config(timeout: 7))) + + expect(derived).to be_a(recording) + end + + it 'returns a different transport' do + transport = unit_transport + expect(transport.with_config(transport.config)).not_to be(transport) + end + end + + describe 'logging' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + let(:logger) { Logger.new(log_device, level: Logger::DEBUG) } + + before do + stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) + unit_transport(logger: logger, user: 'u', password: 'pw-s3cret', http_token: nil) + .post('api/v1/groups', operation: 'test', body: { login: 'jane', password: 'pw-s3cret' }) + end + + it 'logs the request' do + expect(log).to include('Zammad API request: POST api/v1/groups') + end + + it 'logs the response status' do + expect(log).to include('Zammad API response: POST api/v1/groups -> 201') + end + + it 'never logs a password from the payload' do + expect(log).not_to include('pw-s3cret') + end + + it 'marks the redacted payload value' do + expect(log).to include('password: "[REDACTED]"') + end + + it 'keeps non-sensitive payload values' do + expect(log).to include('login: "jane"') + end + + it 'stays silent by default' do + stub_request(:get, url).to_return(json_response([])) + + expect { unit_transport.get('api/v1/groups', operation: 'test') } + .to output('').to_stdout.and output('').to_stderr + end + + context 'with credential-bearing payload keys' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + + before do + stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) + unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)).post( + 'api/v1/groups', + operation: 'test', + body: { + login: 'jane', + keyboard_layout: 'de', + password_confirm: 'confirm-s3cret', + passwd: 'passwd-s3cret', + access_token: 'access-s3cret', + refresh_token: 'refresh-s3cret', + client_secret: 'client-s3cret', + api_key: 'api-key-s3cret', + apikey: 'apikey-s3cret', + key: 'key-s3cret' + } + ) + end + + it 'redacts a password_confirm' do + expect(log).not_to include('confirm-s3cret') + end + + it 'redacts an access_token' do + expect(log).not_to include('access-s3cret') + end + + it 'redacts a refresh_token' do + expect(log).not_to include('refresh-s3cret') + end + + it 'redacts an api_key' do + expect(log).not_to include('api-key-s3cret') + end + + it 'redacts an apikey, which nothing separates the word in' do + expect(log).not_to include('apikey-s3cret') + end + + it 'redacts a bare key' do + expect(log).not_to include('key-s3cret') + end + + it 'redacts a passwd' do + expect(log).not_to include('passwd-s3cret') + end + + # Matched as a word, so that a key merely containing the letters stays + # readable in the log rather than being blanked for nothing. + it 'leaves a key whose name only contains one of the words alone' do + expect(log).to include('keyboard_layout: "de"') + end + + it 'redacts a client_secret' do + expect(log).not_to include('client-s3cret') + end + + it 'still keeps a non-sensitive value' do + expect(log).to include('login: "jane"') + end + end + + # A body handed over as a String is the caller's own encoding. Redaction + # goes by key and found none in a String, so the payload line printed it + # as it stood. + context 'with a body handed over as a String' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + let(:transport) { unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)) } + + before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } + + it 'redacts a credential in one that is JSON' do + transport.post('api/v1/groups', operation: 'test', body: '{"login":"jane","password":"string-s3cret"}') + + expect(log).not_to include('string-s3cret') + end + + it 'keeps what is not a credential readable, redacted by key like a Hash' do + transport.post('api/v1/groups', operation: 'test', body: '{"login":"jane","password":"string-s3cret"}') + + expect(log).to include('Zammad API payload: {"login" => "jane", "password" => "[REDACTED]"}') + end + + it 'redacts one nested in a JSON list' do + transport.post('api/v1/groups', operation: 'test', body: '[{"user":{"api_key":"string-s3cret"}}]') + + expect(log).not_to include('string-s3cret') + end + + it 'does not log one that is not JSON, and says how much was left out' do + transport.post('api/v1/groups', operation: 'test', body: 'login=jane&password=string-s3cret') + + expect(log).not_to include('string-s3cret') + expect(log).to include('Zammad API payload: "[33 bytes that are not a JSON object or array, not logged]"') + end + + it 'does not log a JSON value with no keys to go by' do + transport.post('api/v1/groups', operation: 'test', body: '"string-s3cret"') + + expect(log).not_to include('string-s3cret') + end + + it 'does not raise for bytes that are not text' do + expect { transport.post('api/v1/groups', operation: 'test', body: "\xFF\xFEstring-s3cret".b) }.not_to raise_error + expect(log).not_to include('string-s3cret') + end + + it 'still sends the body as it was given' do + transport.post('api/v1/groups', operation: 'test', body: '{"login":"jane","password":"string-s3cret"}') + + expect(a_request(:post, url).with(body: '{"login":"jane","password":"string-s3cret"}')).to have_been_made + end + end + + # A raw request may carry its query in the path. The `query:` Hash is + # redacted by key, and the same parameter written into the path was + # printed in full, in the request line and in the response line. + context 'with a query string written into the path' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + let(:verify) { 'api/v1/users/password_reset_verify?token=path-s3cret&locale=de' } + + before do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/password_reset_verify").with(query: hash_including({})).to_return(json_response({})) + unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)).get(verify, operation: 'test') + end + + it 'redacts a credential in it' do + expect(log).not_to include('path-s3cret') + end + + it 'marks it in the request line, and keeps the other parameters' do + expect(log).to include('Zammad API request: GET api/v1/users/password_reset_verify?token=[REDACTED]&locale=de') + end + + it 'marks it in the response line' do + expect(log).to include('Zammad API response: GET api/v1/users/password_reset_verify?token=[REDACTED]&locale=de -> 200') + end + + it 'still sends the query as it was given' do + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/password_reset_verify").with(query: { 'token' => 'path-s3cret', 'locale' => 'de' })) + .to have_been_made + end + end + + # A raw request takes headers of its own and the request line prints + # them. `Cookie` carries a session and matched none of the credential + # words, so it was written out in full. + context 'with credential-bearing headers' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + + before do + stub_request(:get, url).to_return(json_response([])) + unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)).get( + 'api/v1/groups', + operation: 'test', + headers: { + 'Cookie' => '_zammad_session=cookie-s3cret', + 'Proxy-Authorization' => 'Basic proxy-s3cret', + 'X-CSRF-Token' => 'csrf-s3cret', + 'X-Request-Id' => 'request-123' + } + ) + end + + it 'redacts a Cookie' do + expect(log).not_to include('cookie-s3cret') + end + + it 'marks the redacted header, under the name it is sent as' do + expect(log).to include('"cookie" => "[REDACTED]"') + end + + it 'redacts a Proxy-Authorization' do + expect(log).not_to include('proxy-s3cret') + end + + it 'redacts a token header' do + expect(log).not_to include('csrf-s3cret') + end + + it 'keeps a header that carries no credential' do + expect(log).to include('"x-request-id" => "request-123"') + end + + it 'still sends the headers as they were given' do + expect(a_request(:get, url).with(headers: { 'Cookie' => '_zammad_session=cookie-s3cret', 'Proxy-Authorization' => 'Basic proxy-s3cret' })) + .to have_been_made + end + end + end + + # `request` documents that every failure leaves it as a ZammadAPI::Error. + # Faraday::SSLError was handled and its unwrapped counterpart was not, so a + # certificate mismatch through an adapter that does not wrap - an adapter + # this gem lets a caller choose - went straight past the rescue. + describe 'a TLS failure through an adapter that does not wrap it' do + before { BareTlsAdapter.attempts = [] } + + def bare_tls_transport(**overrides) + unit_transport(adapter: :bare_tls, retry_interval: 0.01, **overrides) + end + + it 'maps it to ConnectionError rather than letting it out raw' do + expect { bare_tls_transport.get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ConnectionError, /TLS handshake with .* failed/) + end + + it 'is catchable as the gem error every caller rescues' do + expect { bare_tls_transport.get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::Error) + end + + # A rejected certificate is a fact about the instance, not a transient + # failure: retrying only delays the error by the backoff. + it 'does not retry it' do + expect { bare_tls_transport(retries: 2).get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ConnectionError) + expect(BareTlsAdapter.attempts.size).to eq(1) + end + + it 'keeps the unwrapped TLS error out of the retry list' do + expect(described_class::RETRIABLE_EXCEPTIONS).not_to include(*described_class::SSL_ERRORS) + end + end + + # The error Faraday or URI raises quotes the value it rejected, and for a + # proxy that value carries its credentials - into a message that lands in + # every log and exception report. + describe 'a connection that cannot be built from a credential-bearing proxy' do + let(:proxy) { 'http://user:pa ss@proxyhost:3128' } + + it 'reports it as a configuration error' do + expect { unit_transport(proxy: proxy) }.to raise_error(ZammadAPI::ConfigurationError) + end + + it 'keeps the proxy password out of the message' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('pa ss') } + end + + it 'still says which value was rejected' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) + end + + # The message is not what a log or an error tracker prints. They print + # the report, and Ruby had attached the error being rescued as the cause: + # the redacted message went out with the original, password and all, + # right behind it. + it 'keeps the proxy password out of the whole report, not just the message' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('pa ss') } + end + + it 'does not carry the error that quotes the password along as its cause' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_nil } + end + + it 'still names the class of the error it replaced' do + expect { unit_transport(proxy: proxy) }.to raise_error(ZammadAPI::ConfigurationError, /URI::InvalidURIError/) + end + + # The error being replaced may be clean itself and still have the + # password one level down, and a report prints every level. + context 'when the error quotes the proxy only further down its own chain' do + let(:proxy) { 'http://user:s3cret@proxyhost:3128' } + + let(:wrapping) do + lambda do |_| + raise URI::InvalidURIError, "bad URI: #{proxy}" + rescue URI::InvalidURIError + raise ArgumentError, 'the proxy could not be used' + end + end + + it 'has nothing to redact in the message' do + expect { unit_transport(proxy: proxy, middleware: wrapping) } + .to raise_error(ZammadAPI::ConfigurationError, /ArgumentError: the proxy could not be used/) + end + + it 'keeps the password out of the whole report all the same' do + expect { unit_transport(proxy: proxy, middleware: wrapping) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('s3cret') } + end + end + + # A # ends the authority early, so the redaction found no credential in + # what was left of it and the message quoted the password in full. + context 'when the password carries a character that ends the authority' do + let(:proxy) { 'http://user:pa#ss-s3cret@proxyhost:3128' } + + it 'keeps the password out of the message' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to match(/pa#ss|s3cret/) } + end + + it 'still says which value was rejected' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) + end + + it 'keeps the password out of the whole report' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to match(/pa#ss|s3cret/) } + end + end + + context 'when it is the instance url that carries such a password' do + it 'keeps the password out of the message' do + expect { unit_transport(url: 'https://admin:pa#ss-s3cret@zammad.test/') } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to match(/pa#ss|s3cret/) } + end + end + + # The error quotes what it rejected through `inspect`, which escapes the + # backslash - so the text in the message stopped matching the configured + # value and the substring swap redacted nothing at all. + context 'when the value carries a backslash, which inspect escapes' do + let(:proxy) { 'http://user:secret@proxyhost/a\0b' } + + it 'still keeps the password out of the message' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('secret') } + end + end + + # URI turns away a URL holding a character outside ASCII, and quotes it + # through `dump`, which writes that character as an escape where + # `inspect` leaves it standing. Neither spelling that was looked for + # matched, so the password stayed in the message and in the cause. + context 'when the password carries a character outside ASCII, which dump escapes' do + let(:proxy) { 'http://user:pässwörd@proxyhost:3128' } + + it 'keeps the password out of the message' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to match(/ssw|user:/) } + end + + it 'still says which value was rejected' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError, %r{URI must be ascii only "http://\[REDACTED\]@proxyhost:3128"}) + end + + it 'keeps the password out of the whole report' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to match(/ssw|user:/) } + end + + it 'does not carry the error that quotes the password along as its cause' do + expect { unit_transport(proxy: proxy) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_nil } + end + + it 'keeps it out of the message where the instance url carries it' do + expect { unit_transport(url: 'https://admin:pässwörd@zammad.test/') } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to match(/ssw|admin:/) } + end + end + + # `\0` in a gsub replacement String expands to the matched text, which is + # the unredacted value. + context 'when the value carries a sequence a gsub replacement would expand' do + let(:proxy) { 'http://user:secret@proxyhost/a\0b' } + + it 'does not put the credential back through the replacement' do + message = begin + unit_transport(proxy: proxy) + nil + rescue ZammadAPI::ConfigurationError => e + e.message + end + + expect(message.scan('user:secret')).to be_empty + end + end + end +end diff --git a/spec/zammad_api/client_spec.rb b/spec/zammad_api/client_spec.rb deleted file mode 100644 index 9f6b73f..0000000 --- a/spec/zammad_api/client_spec.rb +++ /dev/null @@ -1,110 +0,0 @@ -require 'spec_helper' -require 'logger' - -describe ZammadAPI::Client do - before(:all) do - WebMock.enable! - end - - after(:all) do - WebMock.disable! - end - - after do - WebMock.reset! - end - - let(:config) { Helper.config } - let(:instance) { described_class.new(config) } - - describe '.new' do - it 'raises ConfigurationError when url is missing' do - expect { described_class.new(config.merge(url: nil)) } - .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') - end - - it 'raises ConfigurationError when url scheme is unsupported' do - expect { described_class.new(config.merge(url: 'ftp://example.com')) } - .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https://') - end - - it 'raises ConfigurationError when user is missing' do - expect { described_class.new(config.merge(user: nil)) } - .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') - end - - it 'raises ConfigurationError when password is missing' do - expect { described_class.new(config.merge(password: nil)) } - .to raise_error(ZammadAPI::ConfigurationError, 'missing password in config') - end - - it 'does not require user/password when http_token is supplied' do - expect { described_class.new(url: config[:url], http_token: 'token') }.not_to raise_error - end - - it 'does not require user/password when oauth2_token is supplied' do - expect { described_class.new(url: config[:url], oauth2_token: 'token') }.not_to raise_error - end - end - - describe '#method_missing' do - it 'raises ResourceNotFoundError for unknown resources' do - expect { instance.does_not_exist }.to raise_error(ZammadAPI::ResourceNotFoundError, /Resource for DoesNotExist does not exist/) - end - - it 'attaches the underlying NameError as #cause' do - instance.does_not_exist - rescue ZammadAPI::ResourceNotFoundError => e - expect(e.cause).to be_a(NameError) - end - end - - describe '#perform_on_behalf_of' do - it 'performs a given block on behalft of a given user' do - on_behalf_of_identifier = 'some_login' - - stub_request(:get, /#{config[:url]}/) - .with(headers: { - 'From' => on_behalf_of_identifier - }) - .to_return(status: 200, body: '{}', headers: {}) - - instance.perform_on_behalf_of(on_behalf_of_identifier) do - instance.user.find(1) - end - end - - it "doesn't affect later requests outside of the block" do - # first perform request on behalf of a login - on_behalf_of_identifier = 'some_login' - - stub_request(:get, /#{config[:url]}/) - .with(headers: { - 'From' => on_behalf_of_identifier - }) - .to_return(status: 200, body: '{}', headers: {}) - - instance.perform_on_behalf_of(on_behalf_of_identifier) do - instance.user.find(1) - end - - # now without and check that - # the header isn't set anymore - stub = stub_request(:get, /#{config[:url]}/) - .to_return(status: 200, body: '{}', headers: {}) - - # this is kind of a hack/workaround to check if the - # header was not set/send since webmock doesn't support - # checks for not existing headers - request_pattern = stub.request_pattern - def request_pattern.matches?(request_signature) - return false if !super - return true if request_signature.headers.empty? - - !request_signature.headers.key?('From') - end - - instance.user.find(1) - end - end -end diff --git a/spec/zammad_api/errors_spec.rb b/spec/zammad_api/errors_spec.rb deleted file mode 100644 index b335088..0000000 --- a/spec/zammad_api/errors_spec.rb +++ /dev/null @@ -1,164 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI do - describe ZammadAPI::Error do - it 'descends from RuntimeError' do - expect(described_class.ancestors).to include(RuntimeError) - end - end - - describe ZammadAPI::ConfigurationError do - it 'descends from ZammadAPI::Error' do - expect(described_class.ancestors).to include(ZammadAPI::Error) - end - - it 'descends from RuntimeError' do - expect(described_class.ancestors).to include(RuntimeError) - end - end - - describe ZammadAPI::ResourceNotFoundError do - it 'descends from ZammadAPI::Error' do - expect(described_class.ancestors).to include(ZammadAPI::Error) - end - - it 'descends from RuntimeError' do - expect(described_class.ancestors).to include(RuntimeError) - end - end - - describe ZammadAPI::ResponseError do - let(:fake_response) { Struct.new(:status, :body) } - - describe '.from' do - it 'returns a ClientError for 4xx responses' do - response = fake_response.new(404, '{}') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ClientError) - end - - it 'returns a ClientError for 408 (Request Timeout)' do - response = fake_response.new(408, '{}') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ClientError) - end - - it 'returns a ClientError for 429 (Too Many Requests)' do - response = fake_response.new(429, '{}') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ClientError) - end - - it 'returns a ServerError for 5xx responses' do - response = fake_response.new(500, '{}') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ServerError) - end - - it 'returns a ServerError for 502 (Bad Gateway)' do - response = fake_response.new(502, 'Bad Gateway') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ServerError) - end - - it 'returns a base ResponseError when no response is supplied' do - result = described_class.from(nil, operation: 'find object') - expect(result.class).to eq(described_class) - end - end - - describe 'subclasses' do - it 'ClientError descends from ResponseError' do - expect(ZammadAPI::ClientError.ancestors).to include(described_class) - end - - it 'ServerError descends from ResponseError' do - expect(ZammadAPI::ServerError.ancestors).to include(described_class) - end - - it 'descends from ZammadAPI::Error' do - expect(described_class.ancestors).to include(ZammadAPI::Error) - end - - it 'descends from RuntimeError' do - expect(described_class.ancestors).to include(RuntimeError) - end - end - - describe '#message' do - it "uses the JSON body's 'error' key when present" do - response = fake_response.new(404, '{"error":"User not found"}') - error = described_class.from(response, operation: 'find object', resource_class: ZammadAPI::Resources::User) - expect(error.message).to eq("Can't find object (ZammadAPI::Resources::User): User not found") - end - - it 'preserves the original message format for the JSON-with-error case' do - response = fake_response.new(422, '{"error":"name can\'t be blank"}') - error = described_class.from(response, operation: 'save object', resource_class: ZammadAPI::Resources::Group) - expect(error.message).to eq("Can't save object (ZammadAPI::Resources::Group): name can't be blank") - end - - it 'falls back to HTTP status when the body is not JSON (issue #29 scenario)' do - response = fake_response.new(502, 'Bad Gateway') - error = described_class.from(response, operation: 'find object', resource_class: ZammadAPI::Resources::User) - expect(error.message).to eq("Can't find object (ZammadAPI::Resources::User): HTTP 502") - end - - it 'falls back to HTTP status when the body is empty' do - response = fake_response.new(500, '') - error = described_class.from(response, operation: 'destroy object', resource_class: ZammadAPI::Resources::User) - expect(error.message).to eq("Can't destroy object (ZammadAPI::Resources::User): HTTP 500") - end - - it "falls back to HTTP status when the JSON body has no 'error' key" do - response = fake_response.new(400, '{"foo":"bar"}') - error = described_class.from(response, operation: 'find object', resource_class: ZammadAPI::Resources::User) - expect(error.message).to eq("Can't find object (ZammadAPI::Resources::User): HTTP 400") - end - - it 'omits the resource_class segment when none is supplied' do - response = fake_response.new(404, '{"error":"nope"}') - error = described_class.from(response, operation: 'find object') - expect(error.message).to eq("Can't find object: nope") - end - - it 'does not attach the JSON parser error as cause (it is a symptom, not the cause)' do - response = fake_response.new(502, 'Bad Gateway') - error = described_class.from(response, operation: 'find object') - expect(error.cause).to be_nil - end - end - - describe 'accessors' do - let(:response) { fake_response.new(404, '{"error":"nope"}') } - let(:error) do - described_class.from(response, operation: 'find object', resource_class: ZammadAPI::Resources::User) - end - - it 'exposes the underlying response' do - expect(error.response).to be(response) - end - - it 'exposes the response status' do - expect(error.status).to eq(404) - end - - it 'exposes the response body' do - expect(error.body).to eq('{"error":"nope"}') - end - - it 'exposes the operation' do - expect(error.operation).to eq('find object') - end - - it 'exposes the resource_class' do - expect(error.resource_class).to eq(ZammadAPI::Resources::User) - end - - it 'returns nil for status when no response is supplied' do - error = described_class.from(nil, operation: 'find object') - expect(error.status).to be_nil - end - - it 'returns nil for body when no response is supplied' do - error = described_class.from(nil, operation: 'find object') - expect(error.body).to be_nil - end - end - end -end diff --git a/spec/zammad_api/json_helper_spec.rb b/spec/zammad_api/json_helper_spec.rb deleted file mode 100644 index 29eb956..0000000 --- a/spec/zammad_api/json_helper_spec.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI::JsonHelper do - subject(:helper) do - Class.new { include ZammadAPI::JsonHelper }.new - end - - describe '#safe_json_parse' do - it 'parses valid JSON' do - expect(helper.safe_json_parse('{"key":"value"}')).to eq('key' => 'value') - end - - it 'returns empty hash for invalid JSON' do - expect(helper.safe_json_parse('not json')).to eq({}) - end - - it 'returns empty hash for HTML responses' do - expect(helper.safe_json_parse('Bad Gateway')).to eq({}) - end - end -end diff --git a/spec/zammad_api/resources/list_base_spec.rb b/spec/zammad_api/resources/list_base_spec.rb deleted file mode 100644 index c7018e3..0000000 --- a/spec/zammad_api/resources/list_base_spec.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI::ListBase do - it 'is a Enumerable' do - expect(described_class.ancestors).to include(Enumerable) - end -end diff --git a/spec/zammad_api/transport_spec.rb b/spec/zammad_api/transport_spec.rb deleted file mode 100644 index 66032e5..0000000 --- a/spec/zammad_api/transport_spec.rb +++ /dev/null @@ -1,80 +0,0 @@ -require 'spec_helper' -require 'logger' - -describe ZammadAPI::Transport do - before(:all) do - WebMock.enable! - end - - after(:all) do - WebMock.disable! - end - - after do - WebMock.reset! - end - - let(:config) { Helper.config } - let(:logger) do - Logger.new($stderr).tap do |logger| - logger.level = Logger::ERROR - end - end - let(:instance) { described_class.new(config, logger) } - - context 'GET' do - it 'performs GET requests' do - stub_request(:get, "#{config[:url]}some/path") - .to_return(status: 200, body: '', headers: {}) - - instance.get(url: '/some/path') - end - end - - context 'on behalf of' do - it 'responds to #on_behalf_of' do - expect(instance).to respond_to(:on_behalf_of) - end - - it 'responds to #on_behalf_of=' do - expect(instance).to respond_to(:on_behalf_of=) - end - - it 'sets From header' do - on_behalf_of_identifier = 'some_login' - - instance.on_behalf_of = on_behalf_of_identifier - - stub_request(:get, "#{config[:url]}some/path") - .with(headers: { - 'From' => on_behalf_of_identifier - }) - .to_return(status: 200, body: '', headers: {}) - - instance.get(url: '/some/path') - end - - it 'unsets From header' do - on_behalf_of_identifier = 'some_login' - - instance.on_behalf_of = on_behalf_of_identifier - instance.on_behalf_of = nil - - stub = stub_request(:get, "#{config[:url]}some/path") - .to_return(status: 200, body: '', headers: {}) - - # this is kind of a hack/workaround to check if the - # header was not set/send since webmock doesn't support - # checks for not existing headers - request_pattern = stub.request_pattern - def request_pattern.matches?(request_signature) - return false if !super - return true if request_signature.headers.empty? - - !request_signature.headers.key?('From') - end - - instance.get(url: '/some/path') - end - end -end diff --git a/spec/zammad_api_spec.rb b/spec/zammad_api_spec.rb deleted file mode 100644 index 6616717..0000000 --- a/spec/zammad_api_spec.rb +++ /dev/null @@ -1,36 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI do - it 'has a version number' do - expect(ZammadAPI::VERSION).not_to be_nil - end - - context 'failing authentication' do - Helper.auto_wizard - client = Helper.client(user: 'not_existing', password: 'not_existing') - - it 'user' do - expect { client.user.find(1) }.to raise_error(ZammadAPI::ClientError) do |error| - expect(error.status).to eq(401) - expect(error.operation).to eq('find object') - expect(error.resource_class).to eq(ZammadAPI::Resources::User) - end - end - - it 'organization' do - expect { client.organization.find(1) }.to raise_error(ZammadAPI::ClientError) - end - - it 'group' do - expect { client.group.find(1) }.to raise_error(ZammadAPI::ClientError) - end - - it 'ticket_priority' do - expect { client.ticket_priority.find(1) }.to raise_error(ZammadAPI::ClientError) - end - - it 'ticket_state' do - expect { client.ticket_state.find(1) }.to raise_error(ZammadAPI::ClientError) - end - end -end diff --git a/zammad_api.gemspec b/zammad_api.gemspec index 7b09454..ee07fb0 100644 --- a/zammad_api.gemspec +++ b/zammad_api.gemspec @@ -1,28 +1,59 @@ -lib = File.expand_path('lib', __dir__) -$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'zammad_api/version' +# frozen_string_literal: true + +require_relative 'lib/zammad_api/version' Gem::Specification.new do |spec| - spec.name = 'zammad_api' - spec.version = ZammadAPI::VERSION.dup - spec.authors = ['Martin Edenhofer', 'Martin Gruner'] - spec.email = ['support@zammad.org'] + spec.name = 'zammad_api' + spec.version = ZammadAPI::VERSION + spec.authors = ['Martin Edenhofer', 'Martin Gruner', 'Mantas Masalskis'] + spec.email = ['support@zammad.org'] + + # Two versions meet in these lines, and only one of them is this gem's: 2.0 + # is the client, and v1.0 is the API that Zammad serves under /api/v1. + # + # A prerelease says so where the gem is listed, and stops saying so by itself + # once VERSION no longer carries a prerelease segment. + prerelease = Gem::Version.new(ZammadAPI::VERSION).prerelease? - spec.summary = 'Zammad API v1.0 client.' - spec.description = 'Ruby wrapper for the Zammad API v1.0.' - spec.homepage = 'https://github.com/zammad/zammad-api-client-ruby' - spec.licenses = ['AGPL-3.0-only', 'MIT'] - spec.required_ruby_version = '>= 3.0' # Same as TargetRubyVersion in .rubocop.yml. + spec.summary = "Version 2.0 of the Ruby client for the Zammad API#{' (prerelease)' if prerelease}." + spec.description = 'Version 2.0 of the Ruby client for the Zammad API v1.0, the one a Zammad serves under ' \ + '/api/v1. It is a breaking release: the README lists every call that changed since 1.x.' + spec.description += " This is a prerelease, #{ZammadAPI::VERSION}: install it with --pre." if prerelease + spec.homepage = 'https://github.com/zammad/zammad-api-client-ruby' + spec.licenses = ['AGPL-3.0-only', 'MIT'] - spec.metadata['allowed_push_host'] = 'https://rubygems.org' + # Keep in sync with TargetRubyVersion in .rubocop.yml and the CI matrix. + # + # 3.4 rather than 3.3, the one older line still maintained - for security + # fixes, until March 2027 - and for a single reason: the `it` block + # parameter, which lib/ uses throughout. Nothing else here needs 3.4. On + # Ruby 3.3.13, with every `it` rewritten to `_1`, the unit suite passed but + # for five examples that assert the format Hash#inspect has had since 3.4. + # So the floor is a choice of style over reach rather than a dependency, and + # lowering it is that rewrite, those five expectations and a CI entry. + spec.required_ruby_version = '>= 3.4' - spec.metadata['homepage_uri'] = spec.homepage - spec.metadata['source_code_uri'] = 'https://github.com/zammad/zammad-api-client-ruby' - spec.metadata['changelog_uri'] = 'https://github.com/zammad/zammad-api-client-ruby/blob/master/CHANGELOG.md' - spec.metadata['rubygems_mfa_required'] = 'true' + spec.metadata['allowed_push_host'] = 'https://rubygems.org' + spec.metadata['homepage_uri'] = spec.homepage + spec.metadata['source_code_uri'] = spec.homepage + spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md" + spec.metadata['bug_tracker_uri'] = "#{spec.homepage}/issues" + spec.metadata['documentation_uri'] = "https://rubydoc.info/gems/zammad_api/#{ZammadAPI::VERSION}" + spec.metadata['rubygems_mfa_required'] = 'true' - spec.files = Dir['{lib}/**/*'] - spec.require_paths = ['lib'] + # sig/vendor holds the declarations that exist only for this repository's own + # type checking - stand-ins for dependencies that ship none, and the internal + # ones in sig/vendor/internal.rbs - and must not be published. + spec.files = Dir['lib/**/*.rb', 'sig/**/*.rbs'].grep_v(%r{\Asig/vendor/}) + %w[ + CHANGELOG.md + LICENSE.AGPL.txt + LICENSE.MIT.txt + LICENSE.md + README.md + ] + spec.require_paths = ['lib'] + spec.extra_rdoc_files = ['README.md', 'CHANGELOG.md'] - spec.add_dependency 'faraday', '~> 2' + spec.add_dependency 'faraday', '~> 2.9' + spec.add_dependency 'faraday-retry', '~> 2.2' end From 2e8ee952ead9f3ad0b05d170fae3cdadc4f652bf Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 18 Nov 2026 10:09:23 +0200 Subject: [PATCH 002/121] feat: ship a test kit for code that calls this client Code that calls this gem had two ways to test itself. It could intercept HTTP at the socket, which ties a test to URLs and to Faraday, or stub the client's methods, which tests the stub. require 'zammad_api/test' gives a third: a stand-in Zammad behind a real client. ZammadAPI::Test.new answers from stubs instead of a network, and hands out a client through #client. Everything above the transport is the real thing - decoding, error mapping, records, change tracking, pagination - so a test goes down the path production does. A stub names a verb and a path and answers with a body and a status. Stubs for one request are consumed in order, and a later page of a list is answered the way an endpoint would answer it. Each request is recorded by value, with its query, body and headers, and #requests hands them back for assertions. A request nothing was stubbed for raises UnstubbedRequestError, and two stubs that describe one request equally well raise AmbiguousStubError. Both are StandardErrors outside ZammadAPI::Error, because they say the test is wrong, not that Zammad refused anything: inside the hierarchy, the `rescue ZammadAPI::Error` of the code under test would swallow a forgotten stub and report it as an API failure. --- lib/zammad_api/test.rb | 534 ++++++++++++++++++ spec/unit/zammad_api/test_spec.rb | 877 ++++++++++++++++++++++++++++++ 2 files changed, 1411 insertions(+) create mode 100644 lib/zammad_api/test.rb create mode 100644 spec/unit/zammad_api/test_spec.rb diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb new file mode 100644 index 0000000..40a17c5 --- /dev/null +++ b/lib/zammad_api/test.rb @@ -0,0 +1,534 @@ +# frozen_string_literal: true + +require 'json' + +require_relative '../zammad_api' + +module ZammadAPI + # A stand-in Zammad, for testing code that calls this client. + # + # Stub the endpoints the code under test will reach, hand it {#client}, then + # assert against {#requests}. No HTTP stack is involved, so nothing has to be + # intercepted at the socket level and the responses come back through the + # same decoding, error mapping and record building as real ones. + # + # @example + # require 'zammad_api/test' + # + # zammad = ZammadAPI::Test.new + # zammad.stub(:get, 'api/v1/tickets/1', body: {id: 1, title: 'Help', state: 'open'}) + # zammad.stub(:put, 'api/v1/tickets/1', body: {id: 1, state: 'closed'}) + # + # TicketCloser.new(zammad.client).close(1) + # + # zammad.requests.last.verb # => :put + # zammad.requests.last.body # => {state: "closed"} + # + # @example An error path + # zammad.stub(:get, 'api/v1/tickets/9', status: 404, body: {error: 'not found'}) + # # the code under test sees ZammadAPI::NotFoundError + class Test + # Raised when the code under test reaches an endpoint that was not stubbed. + # + # The message lists what is stubbed, because the usual cause is a path that + # differs from the expected one. + # + # Deliberately outside {ZammadAPI::Error}: this says the test is wrong, not + # that Zammad refused something, and code under test is written to handle + # the latter. Inside the hierarchy, the `rescue ZammadAPI::Error` that this + # gem's own examples recommend swallowed a forgotten stub and reported it + # as an API failure - so a test asserting the error path passed green over + # a request it had never declared. + class UnstubbedRequestError < StandardError; end + + # Raised when two stubs describe one request equally well. + # + # Two stubs that name different query parameters can both match a request + # carrying all of them, and there is no honest way to rank them: a search + # stubbed once for its records and once for its count is matched by both + # when `count` sends the search term and +only_total_count+ together. The + # stand-in used to pick one, hand back the wrong body, consume the stub on + # the way past, and then report the endpoint as unstubbed - three + # confusing symptoms for one fixable declaration. + # + # Outside {ZammadAPI::Error} for the same reason as + # {UnstubbedRequestError}: it says the test is wrong, not that Zammad + # refused anything. + class AmbiguousStubError < StandardError; end + + # One request the code under test made. + # + # The verb is +verb+ rather than +method+, because a member named +method+ + # would shadow +Object#method+ on every recorded request. + # + # @!attribute [r] verb + # @return [Symbol] +:get+, +:post+, +:put+ or +:delete+ + # @!attribute [r] path + # @return [String] path relative to the instance URL + # @!attribute [r] query + # @return [Hash{String => String, Array}] query parameters as the + # client sent them, stringified the way the real transport sends them + # @!attribute [r] body + # @return [Hash, nil] the request payload + # @!attribute [r] headers + # @return [Hash{String => String}] the headers the call asked for, + # downcased and stringified the way the real transport sends them. + # Empty for a request that named none; the headers the client sets + # from its own configuration are not in here, and the +From+ scope has + # a member of its own below. + # @!attribute [r] on_behalf_of + # @return [String, nil] the +From+ scope in effect, stringified the way + # the +From+ header carries it + Request = Data.define(:verb, :path, :query, :body, :headers, :on_behalf_of) + + # @return [Config] the configuration the stand-in client reports + attr_reader :config + + # @param options [Hash] any option accepted by {Config}; the defaults are + # enough for a client that never opens a connection + def initialize(**options) + # Through the merge a client's own overrides go through, so that + # `Test.new(user: 'u', password: 'p')` replaces the stand-in token + # rather than being refused for naming a second way to authenticate. + @config = Config.new(**Config.merge_options({ url: 'https://zammad.test/', http_token: 'test-token' }, options)) + @stubs = {} + # The stub each scope of each endpoint last answered a first page with, + # which is the one a later page of the same read belongs to. See #take. + @served = {} + @requests = [] + @monitor = Mutex.new + @transport = Transport.new(self) + # Built once, and built straight onto the stand-in. Going through + # `Client.new` re-validated the config assembled one line above and then + # assembled a whole Faraday stack - auth, JSON, retries, adapter - only + # to swap it straight back out, which is the cost the comment here used + # to claim it was avoiding. A suite writing + # `let(:zammad) { ZammadAPI::Test.new }` paid it once per example. + @client = Client.build(@config, @transport) + end + + # A client that talks to this stand-in instead of to a Zammad. + # + # The same client every time; it holds no per-request state, and + # {Client#on_behalf_of} and {Client#with} return copies of their own. + # + # @return [Client] + attr_reader :client + + # Declares the response for one endpoint. + # + # Stubbing the same method and path again queues a second response: the + # first request gets the first, and the last stub answers every request + # after it. A collection read is one step of such a sequence however many + # pages it asks for, so three list stubs answer three reads in turn. A + # +query+ matches when every parameter it names is present in + # the request with that value, so a stub does not have to repeat the + # +expand+, +page+ and +per_page+ parameters the client adds itself. + # + # A stub that names a +query+ is more specific than one that does not, and + # answers ahead of it however they were declared. Queueing applies within + # a scope: two stubs carrying the same +query+ describe a sequence, while + # a scoped stub and a catch-all are two separate answers, each of which + # keeps answering. + # + # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ + # @param path [String] path relative to the instance URL, leading slash + # optional + # @param status [Integer] HTTP status to answer with + # @param body [Hash, Array, String, nil] a Hash or Array is serialized to + # JSON bytes, anything else is served as it is. Whether those bytes are + # then decoded is decided by the content-type, the way a real response + # decides it - so a Hash served as +text/html+ comes back undecoded, and + # a JSON String served as +application/json+ comes back decoded. + # @param headers [Hash] response headers. Names and values are stringified + # and names downcased, the way a {Response} carries them. A Hash or Array + # body is given +content-type: application/json+ unless this says + # otherwise. + # @param query [Hash, nil] only answer requests carrying these parameters + # @return [self] + def stub(method, path, status: 200, body: nil, headers: {}, query: nil) + # Stringified here rather than on each request, so that a query the + # transport would refuse - a nil value - is reported against the line + # that wrote the stub instead of against whichever request reached it. + scope = query && ::ZammadAPI::Transport.stringify_query(query) + # A scope that names nothing matches every request, which is what a stub + # with no query at all is. Kept apart, the two were equally specific and + # `query: {}` collided with a catch-all as an ambiguous pair rather than + # joining it. + scope = nil if scope.nil? || scope.empty? + + # Refused here rather than stringified into something the wire could not + # carry, and for the same reason the query above is: the error names the + # line that wrote the stub. A nil `Content-Type` became `''`, which then + # beat the JSON default this method supplies and served a Hash body + # undecoded, so the test failed inside the code under test with nothing + # to say the stub was at fault. + headers.each do |name, value| + next if value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(Numeric) + + raise ArgumentError, "header #{name} was stubbed as #{value.inspect}, and a response header is always text: pass a String" + end + + @monitor.synchronize do + (@stubs[key(method, path)] ||= []) << { + status: status, + body: body, + headers: response_headers(headers, body), + query: scope + } + end + self + end + + # Every request the code under test made, oldest first. + # + # @return [Array] + def requests = @monitor.synchronize { @requests.dup.freeze } + + # Forgets the stubs and the recorded requests. + # + # @return [self] + def reset + @monitor.synchronize do + @stubs.clear + @served.clear + @requests.clear + end + self + end + + # @return [Array] one +"GET api/v1/groups"+ per stubbed endpoint + def stubbed = @monitor.synchronize { @stubs.keys.map { |method, path| "#{method.to_s.upcase} #{path}" } } + + # Reads both collections under the monitor, and reaches for @stubs rather + # than {#stubbed} because the monitor is a plain Mutex and would deadlock + # on the way back in. The counts used to be read outside it, so printing a + # stand-in from a failure message or a debugger raced the thread under + # test appending to @requests - which is the one thing the monitor is here + # to prevent. + def inspect = @monitor.synchronize { "#<#{self.class.name} stubbed=#{@stubs.size} requests=#{@requests.size}>" } + + # Answers a request from the stubs, recording it first. + # + # This is the {Transport} interface, called by the client rather than by a + # test. + # + # @api private + # @return [Response] + # @raise [ResponseError] for a stubbed non-2xx status + # @raise [UnstubbedRequestError] when no stub matches + def answer(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil, on_behalf_of: nil) + relative = ::ZammadAPI::Transport.relative_path(path) + # Through the real transport's own stringification, so that {Request#query} + # and {Request#headers} hold what a request would have carried rather + # than the raw Ruby values. A stand-in that records a different shape + # than the wire makes an assertion pass here and fail in production, or + # the other way round - and the header rules are where that matters + # most, because a reserved name or a non-text value is refused on the + # wire and would otherwise sail through here. + params = ::ZammadAPI::Transport.stringify_query(query || {}) + fields = ::ZammadAPI::Transport.stringify_headers(headers || {}) + # For the refusal alone: a body the wire could not carry is refused here + # too, before anything is recorded. What is recorded is the body as the + # test wrote it, which is what a test asserts against. + ::ZammadAPI::Transport.encode_body(body, operation: operation, resource_class: resource_class) + + stub = @monitor.synchronize do + @requests << Request.new(verb: method, path: relative, query: params, body: snapshot(body), headers: fields, on_behalf_of: on_behalf_of) + take(method, relative, params) + end + + raise UnstubbedRequestError, unstubbed_message(method, relative, params) if stub.nil? + + response = response_for(stub, params) + return response if response.success? + + raise ResponseError.build(response, operation: operation, resource_class: resource_class) + end + + private + + def key(method, path) = [method.to_sym, ::ZammadAPI::Transport.relative_path(path)] + + # The headers a stub answers with, downcased the way a {Response} carries + # them. + # + # A Hash or Array body is served as JSON, so it gets the content-type a + # real one would. {Transport#decode} always hands over a response whose + # headers name the type - it is what the decode branches on - while this + # set `json: true` directly and left the headers as written, so every + # stubbed response differed from the wire in a header a test can read. + # Code that branches on `response.headers['content-type']` passed against + # Zammad and failed against the stand-in, or the reverse, which is the + # divergence this kit exists to keep out. + # + # A caller's own content-type wins, so a test can still say the endpoint + # answered with something else. + def response_headers(headers, body) + # Values stringified as well as names. Only the name was normalised, so + # `headers: { 'X-Total-Count' => 7 }` reached the code under test as an + # Integer where the wire always carries "7": an assertion written the + # natural way passed against Zammad and failed here, or the reverse, and + # the one reader inside this gem had to tolerate both types to cope. + # Downcasing is what creates the collision, so it is refused here rather + # than merged: `{'Content-Type' => 'text/html', 'content-type' => + # 'application/json'}` kept whichever Hash order put last and dropped the + # other without a word - the same silent drop DuplicateKeys refuses for a + # query parameter, and here it decided whether the body was decoded. + normalized = DuplicateKeys + .normalize(headers, noun: 'header') { it.to_s.downcase } + .transform_values(&:to_s) + return normalized if !body.is_a?(Hash) && !body.is_a?(Array) + + { 'content-type' => 'application/json' }.merge(normalized) + end + + # A copy of the payload, frozen, for the record of what was sent. + # + # The caller's Hash used to be recorded by reference, so a test that built + # one payload, sent it, then changed it for a second call rewrote the + # first recorded request and asserted against a body that never went + # anywhere. `query` is already a fresh structure by the time it gets here, + # because the transport's stringification builds one; `body` is handed + # over untouched, and was the one shape left sharing state with the test. + def snapshot(value) = DeepCopy.frozen_copy(value) + + # Picks the stub that answers this request, and keeps the last one of its + # kind in place so that one stub can answer any number of requests while + # two describe a sequence. + # + # Sequencing runs within a query scope, not across the endpoint. Keying it + # on the last stub queued meant a query-scoped stub was consumed on its + # first use as soon as any other stub for the same verb and path existed + # behind it - the pair a `search(...).count` test needs - so the second + # count silently fell through to the records stub and walked the pages. + # + # A scope here is the exact set of parameters a stub names, not merely the + # fact that it names some. Grouped by whether a stub was scoped at all, + # two stubs carrying *different* scopes were read as a sequence and the + # first was consumed: stubbing a search once for its records and once for + # its count made `count` eat the records stub, hand back an Array where a + # count belonged, and then raise UnstubbedRequestError for a page that was + # stubbed all along. + # + # The most specific scope answers, counting the parameters it pins, so a + # stub written for one request still wins over a catch-all for the + # endpoint however they were declared. Scopes that tie are genuinely + # ambiguous and say so. + # + # A request for a later page does not move the sequence on. Every full + # read of a collection asks for the page after its last one, to learn + # that there is none, and that request used to take the next stub in the + # queue and serve it as the empty page {#paged_body} makes of it: with + # three list stubs A, B and C, three reads answered A, C and C, and B was + # never seen. The trailing request belongs to the read that made it, so it + # is answered by the stub that read's first page came from. + def take(method, path, params) + endpoint = key(method, path) + queued = @stubs[endpoint] + return nil if queued.nil? + + matching = queued.each_index.select { matches?(queued[it][:query], params) } + return nil if matching.empty? + + group = most_specific(queued, matching, method, path) + scope = queued[group.first][:query] + # The stub at the head of the queue is the fallback, for a later page + # that is the first thing asked: `page(3)` on a list nothing has read. + return @served[[endpoint, scope]] || queued[group.first] if later_page?(scope, params) + + @served[[endpoint, scope]] = group.one? ? queued[group.first] : queued.delete_at(group.first) + end + + # Whether a request asks for a page beyond the first of a list whose stub + # did not say what its pages hold. Such a stub is one page of records, so + # the request is the tail of a read rather than a read of its own. + def later_page?(scope, params) + return false if scope&.key?('page') + + ![nil, '1'].include?(params['page']) + end + + # The matching stubs that share the most specific scope, in the order they + # were declared. + # + # @raise [AmbiguousStubError] when two scopes are equally specific + def most_specific(queued, matching, method, path) + scopes = matching.group_by { queued[it][:query] } + depth = scopes.keys.to_h { [it, it.nil? ? 0 : it.size] } + best = depth.values.max + + winners = scopes.select { |scope, _| depth[scope] == best } + raise AmbiguousStubError, ambiguous_message(method, path, winners.keys) if winners.size > 1 + + winners.values.first + end + + def ambiguous_message(method, path, scopes) + rendered = scopes.map { "query: #{it.inspect}" }.join(' and ') + "#{method.to_s.upcase} #{path} is matched equally well by #{scopes.size} stubs (#{rendered}), " \ + 'and this stand-in will not guess which one you meant. Name the parameters that tell the requests apart ' \ + '- a count stub that also carries the search term is more specific than one that does not - or leave the ' \ + 'more general stub unscoped, which makes it a catch-all that answers only what the scoped ones do not.' + end + + # Both sides have been through the transport's own stringification, the + # stub's when it was declared. Comparing a raw value against a stringified + # one worked for a scalar - `1.to_s` is `"1"` either way - and could never + # match for an Array: `[1, 2].to_s` is `"[1, 2]"` while the recorded + # `["1", "2"].to_s` is `"[\"1\", \"2\"]"`. `ids`, `role_ids`, `group_ids` + # and `permissions` are all array-valued search parameters, so a stub + # scoped to any of them silently never answered and the request came back + # as unstubbed. + def matches?(expected, params) + return true if expected.nil? + + expected.all? { |name, value| params[name] == value } + end + + # The records a stub holds are one page of them, not the answer to every + # page. + # + # A collection walks until a page repeats, comes back short, or comes back + # empty. A stub that keeps serving the same records to every page trips + # the first of those, so the obvious way to stand in for a list endpoint - + # one `stub(:get, 'api/v1/groups', body: [...])` - made every full read of + # that collection raise PaginationError, and the only way to find that out + # was to hit it. Against a real Zammad the same code works, because page 2 + # comes back empty; the stand-in is what differed. + # + # So a stub that does not name a page answers one, and a request for any + # page after it gets an empty one. A stub that does name a page is left + # exactly as written - that is how a test says what the second page holds. + # + # A search stubbed with its total beside the records, the object Zammad + # answers `with_total_count` with, is a list as well: the page after it + # holds no records and reports the same total. Served again as written it + # was the repeated page above, for the one stub that says how many hits + # there are. + def paged_body(stub, params, body) + return body if !later_page?(stub[:query], params) + + case body + in Array then [] + in { records: Array, total_count: _ } then body.merge(records: []) + else body + end + end + + # Decoded by {Response.decode_body}, the rule {Transport#decode} reads, so + # that a stub answers the way the wire does. + # + # `json:` used to be set from the Ruby type of the stub's body, which made + # the content-type beside it decorative: a stub could say `text/html` and + # still hand back a decoded Hash with `json?` true, where Zammad gives the + # raw string and `decoded(:object)` raises ParseError. A test asserting + # that path passed here and failed in production, which is the divergence + # this kit exists to rule out. + # Paged after decoding, not before. Paging read the stub's body as written, + # which was the same thing only while a list could arrive as an Array - and + # once the content-type decided decoding, a list stubbed as a JSON string + # decoded to one and was never paged, so it answered every page with the + # same records and every full read of that collection raised + # PaginationError. Against Zammad the same code works, because page two + # comes back empty. + def response_for(stub, params) + raw = raw_body_for(stub[:body]) + body, json = Response.decode_body(stub[:headers]['content-type'], raw) + paged = paged_body(stub, params, body) + # Re-serialized only where paging replaced the body, so `raw_body` stays + # the bytes the stub was written with for every other response. + return build_response(stub, body, raw, json: json) if paged.equal?(body) + + build_response(stub, paged, JSON.generate(paged), json: json) + end + + # The bytes a stub's body would have arrived as. A Hash or Array is what a + # test writes when it means JSON, so that is what it is serialized to; + # anything else is already the body. + def raw_body_for(body) + case body + when Hash, Array then JSON.generate(body) + when nil then '' + else body.to_s + end + end + + # A copy, because the stub keeps serving after this response is built and + # Response is a value. Handing out the stub's own Hash made every response + # from one stub share it, so a test that wrote to `response.headers` - + # editing a content-type to check a decode path, say - rewrote the + # stand-in for every later request in the example. The real transport builds a fresh + # hash per response, and this exists to behave like it. + def build_response(stub, body, raw_body, json:) + Response.new(status: stub[:status], headers: stub[:headers].dup.freeze, body: body, raw_body: raw_body, json: json) + end + + # Where the endpoint is stubbed and only the query kept every stub from + # answering, the message says so, with the query the request carried + # and the scopes the stubs name. Listing the endpoint among what is + # stubbed, as it does for a wrong path, read as a contradiction: a read + # over stubs for pages 1 and 2 asks for page 3, and was told that + # `GET api/v1/users/search was not stubbed (stubbed: GET + # api/v1/users/search)`. + def unstubbed_message(method, path, params) + request = "#{method.to_s.upcase} #{path}" + scopes = @monitor.synchronize { @stubs[key(method, path)]&.map { it[:query] }&.uniq } + return unmatched_query_message(request, params, scopes) if scopes + + stubbed_endpoints = stubbed.empty? ? 'nothing is stubbed' : "stubbed: #{stubbed.join(', ')}" + "#{request} was not stubbed on this #{self.class.name} (#{stubbed_endpoints})" + end + + def unmatched_query_message(request, params, scopes) + message = "#{request} with query #{params.inspect} was not stubbed on this #{self.class.name}: " \ + "its stubs answer only #{scopes.map { "query: #{it.inspect}" }.join(', ')}." + return message if !params.key?('page') || !scopes.all? { it&.key?('page') } + + "#{message} A read asks for the page after the last one it was served, to learn that there are no more: " \ + 'stub that page as well, with body: [], or leave page out of the scope, and the stub serves its records as one ' \ + 'page and an empty page after it.' + end + + # Routes the client's requests to {Test#answer}, and carries the + # +on_behalf_of+ scope the way the real transport does. + # + # @api private + class Transport + include ::ZammadAPI::Transport::Verbs + + attr_reader :test, :on_behalf_of + + # The scope is stringified, copied and checked by the real transport's + # own rule, so that a recorded scope is what a request would have + # carried. Here rather than in {#with_on_behalf_of} alone, which left + # one built directly holding whatever it was given. + def initialize(test, on_behalf_of: nil) + @test = test + @on_behalf_of = ::ZammadAPI::Transport.stringify_on_behalf_of(on_behalf_of) + end + + def config = test.config + + def with_on_behalf_of(identifier) = self.class.new(test, on_behalf_of: identifier) + + # {Client#with} re-validates the options and hands them here. There is + # no connection to rebuild, and the derived client reports the derived + # config itself, so the stand-in keeps answering. + def with_config(_config) = self + + def request(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) + test.answer( + method, + path, + operation: operation, + query: query, + body: body, + headers: headers, + resource_class: resource_class, + on_behalf_of: on_behalf_of + ) + end + end + end +end diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb new file mode 100644 index 0000000..9d639e8 --- /dev/null +++ b/spec/unit/zammad_api/test_spec.rb @@ -0,0 +1,877 @@ +# frozen_string_literal: true + +require 'zammad_api/test' + +RSpec.describe ZammadAPI::Test do + subject(:zammad) { described_class.new } + + let(:client) { zammad.client } + + describe '#client' do + it 'is a real client' do + expect(client).to be_a(ZammadAPI::Client) + end + + it 'opens no connection at all' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + client.groups.find(1) + + expect(a_request(:any, //)).not_to have_been_made + end + + it 'reports the stand-in configuration' do + expect(client.config.url).to eq('https://zammad.test/') + end + + it 'reports the very configuration the stand-in was built with' do + expect(client.config).to be(zammad.config) + end + + # Going through Client.new assembled a Faraday stack - auth, JSON, + # retries, adapter - only for it to be swapped straight back out, once per + # stand-in. + it 'builds no HTTP stack on the way to the stand-in transport' do + allow(ZammadAPI::Transport).to receive(:new).and_call_original + + described_class.new + + expect(ZammadAPI::Transport).not_to have_received(:new) + end + + # The stand-in carries a token of its own, so credentials handed to it + # replace that one rather than being refused as a second scheme. + it 'accepts credentials of another kind in place of its own token' do + zammad = described_class.new(user: 'u', password: 'p') + expect(zammad.client.config.authentication_scheme).to eq(:basic) + end + + it 'accepts configuration overrides' do + expect(described_class.new(url: 'https://other.test/').client.config.url).to eq('https://other.test/') + end + + it 'is the same client every time, rather than a new HTTP stack per call' do + expect(zammad.client).to equal(zammad.client) + end + + describe 'a client derived with #with' do + it 'still answers from the stand-in instead of opening a connection' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Support' }) + + expect(zammad.client.with(timeout: 5).groups.find(1).name).to eq('Support') + expect(a_request(:any, //)).not_to have_been_made + end + + it 'reports the derived option' do + expect(zammad.client.with(timeout: 5).config.timeout).to eq(5) + end + + it 'keeps an on_behalf_of scope' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + zammad.client.on_behalf_of('agent@example.com').with(timeout: 5).groups.find(1) + + expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') + end + end + end + + describe '#stub' do + it 'answers a find with a record' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) + + expect(client.groups.find(1).name).to eq('Users') + end + + it 'builds records that behave like fetched ones' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) + + group = client.groups.find(1) + expect(group).to be_persisted + expect { group.attributes[:name] = 'x' }.to raise_error(FrozenError) + end + + it 'answers a collection with every page' do + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }], query: { page: 1 }) + zammad.stub(:get, 'api/v1/groups', body: [], query: { page: 2 }) + + expect(client.groups.pluck(:name)).to eq(%w[Users Support]) + end + + it 'ignores a leading slash on the stub' do + zammad.stub(:get, '/api/v1/groups/1', body: { id: 1 }) + + expect(client.groups.find(1).id).to eq(1) + end + + # The real transport refuses this, so a stand-in that answered it would + # let a test pass over a request production never sends. + it 'refuses an absolute URL the way the real transport does' do + expect { client.get('https://other.example/collect') } + .to raise_error(ArgumentError, /a request path is relative to the instance URL/) + end + + it 'refuses a path that cannot be read as a URL the way the real transport does' do + expect { client.get('api/v1/tägs') }.to raise_error(ArgumentError, /cannot be read as one: it holds a character outside ASCII/) + expect(zammad.requests).to be_empty + end + + it 'records nothing for a path it refuses' do + expect { client.get('https://other.example/collect') }.to raise_error(ArgumentError) + expect(zammad.requests).to be_empty + end + + # The same for a body the wire could not carry: a stand-in that took it + # would let a test pass over a save production raises on. + it 'refuses a body that cannot be encoded as JSON, the way the real transport does' do + zammad.stub(:post, 'api/v1/groups', body: { id: 1 }) + + expect { client.groups.create(name: 'Support', weight: Float::NAN) } + .to raise_error(ZammadAPI::Error, /the request body cannot be encoded as JSON/) + expect(zammad.requests).to be_empty + end + + # And for a query a query string could not carry as it was written. + it 'refuses a list of Hashes Rails would read as one, the way the real transport does' do + zammad.stub(:get, 'api/v1/roles', body: []) + + expect { client.get('api/v1/roles', query: { list: [{ a: 1 }, { b: 2 }] }) } + .to raise_error(ArgumentError, /Rails would read the two as one/) + expect(zammad.requests).to be_empty + end + + it 'raises the mapped error class for a non-2xx status' do + zammad.stub(:get, 'api/v1/groups/1', status: 404, body: { error: 'not found' }) + + expect { client.groups.find(1) }.to raise_error(ZammadAPI::NotFoundError, /not found/) + end + + it 'raises a validation error that save reports as false' do + zammad.stub(:post, 'api/v1/groups', status: 422, body: { error: 'Name is required' }) + + group = client.groups.new(name: '') + expect(group.save).to be(false) + expect(group.error.server_message).to eq('Name is required') + end + + it 'serves a non-JSON body untouched, e.g. an attachment' do + zammad.stub(:get, 'api/v1/ticket_attachment/1/2/3', body: 'binary-ish') + + attachment = ZammadAPI::Resources::TicketArticleAttachment + .new(zammad.client.tickets.new.transport, id: 3, ticket_id: 1, article_id: 2) + + expect(attachment.download).to eq('binary-ish') + end + + it 'returns itself, so stubs can be chained' do + expect(zammad.stub(:get, 'api/v1/groups', body: [])).to be(zammad) + end + + it 'accepts string keys in the body' do + zammad.stub(:get, 'api/v1/groups/1', body: { 'id' => 1, 'name' => 'Users' }) + + expect(client.groups.find(1).name).to eq('Users') + end + + it 'exposes response headers' do + zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => '7' }) + + expect(client.get('api/v1/groups').headers['x-total-count']).to eq('7') + end + + # The stand-in exists so that the code under test cannot tell it from the + # real transport, and it carried its own copy of the verb loop - so a fifth + # verb added to one would have left the other unable to answer it. + it 'answers every verb the real transport answers' do + expect(ZammadAPI::Test::Transport.new(zammad)) + .to respond_to(*ZammadAPI::Transport::Verbs.instance_methods) + end + + # Transport#decode always hands over a response whose headers name the + # type - it is what the decode branches on - while this set `json: true` + # directly and left the headers as written. Code that branches on + # `response.headers['content-type']` passed against Zammad and failed + # against the stand-in, or the reverse. + it 'serves a JSON body with the content-type a real response carries' do + zammad.stub(:get, 'api/v1/groups', body: []) + + expect(client.get('api/v1/groups').headers['content-type']).to eq('application/json') + end + + it 'serves an object body with the same content-type' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + + expect(client.get('api/v1/groups/1').headers['content-type']).to eq('application/json') + end + + it 'lets a test say the endpoint answered with something else' do + zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'Content-Type' => 'application/json; charset=utf-8' }) + + expect(client.get('api/v1/groups').headers['content-type']).to eq('application/json; charset=utf-8') + end + + # The header used to be decorative: `json:` came from the Ruby type of the + # stub's body, so a stub could say `text/html` and still hand back a + # decoded Hash, where Zammad gives the raw string and `decoded` raises. + context 'when a stub declares a type that is not JSON' do + before { zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }, headers: { 'Content-Type' => 'text/html' }) } + + it 'does not decode the body' do + expect(client.get('api/v1/groups/1')).not_to be_json + end + + it 'hands back the raw body Zammad would have sent' do + expect(client.get('api/v1/groups/1').body).to eq('{"id":1}') + end + + it 'fails the way a real one would when a record is read from it' do + expect { client.groups.find(1) }.to raise_error(ZammadAPI::ParseError) + end + end + + # A nil Content-Type stringified to '', which then beat the JSON default + # this kit supplies and served a Hash body undecoded - so the test failed + # inside the code under test with nothing to say the stub was at fault. + it 'refuses two spellings of one header rather than dropping a value' do + expect { zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'Content-Type' => 'text/html', 'content-type' => 'application/json' }) } + .to raise_error(ArgumentError, /header content-type was given twice/) + end + + it 'refuses a header value the wire could not carry' do + expect { zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'Content-Type' => nil }) } + .to raise_error(ArgumentError, /header Content-Type was stubbed as nil/) + end + + it 'names what a response header has to be' do + expect { zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => [7] }) } + .to raise_error(ArgumentError, /a response header is always text: pass a String/) + end + + # Only the name used to be normalised, so a count written as an Integer + # reached the code under test as one, where the wire always carries "7". + it 'carries a header value as the String the wire would have sent' do + zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => 7 }) + + expect(client.get('api/v1/groups').headers['x-total-count']).to eq('7') + end + + # Paging read the stub's body as written, which was the same thing only + # while a list could arrive as an Array. Once the content-type decided + # decoding, a list stubbed as a JSON string decoded to one and was never + # paged, so it answered every page with the same records and every full + # read raised PaginationError - where Zammad answers page two empty. + it 'pages a list stubbed as a JSON string the way it pages an Array' do + zammad.stub(:get, 'api/v1/groups', body: '[{"id":1,"name":"a"},{"id":2,"name":"b"}]', headers: { 'Content-Type' => 'application/json' }) + + expect(client.groups.all.map(&:name)).to eq(%w[a b]) + end + + it 'answers a later page of a string-bodied list as an endpoint out of records would' do + zammad.stub(:get, 'api/v1/groups', body: '[{"id":1}]', headers: { 'Content-Type' => 'application/json' }) + + expect(client.get('api/v1/groups', query: { page: 2 }).body).to eq([]) + end + + it 'keeps the raw body of a page it did not replace' do + zammad.stub(:get, 'api/v1/groups/1', body: '{"id":1}', headers: { 'Content-Type' => 'application/json' }) + + expect(client.get('api/v1/groups/1').raw_body).to eq('{"id":1}') + end + + it 'decodes a string body a stub declares as JSON' do + zammad.stub(:get, 'api/v1/groups/1', body: '{"id":1,"name":"Users"}', headers: { 'Content-Type' => 'application/json' }) + + expect(client.groups.find(1).name).to eq('Users') + end + + it 'claims no content-type for a body it does not serve as JSON' do + zammad.stub(:get, 'api/v1/groups/1/avatar', body: 'binary') + + expect(client.get('api/v1/groups/1/avatar').headers).not_to have_key('content-type') + end + + # The stub keeps serving after a response is built, and Response is a + # value. Handing out the stub's own Hash made every response from one stub + # share it, so writing to `response.headers` in one example rewrote the + # stand-in for every later request in it. + it 'gives each response its own headers rather than the stub\'s' do + zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => '7' }) + + first = client.get('api/v1/groups') + second = client.get('api/v1/groups') + + expect(first.headers).not_to be(second.headers) + end + + it 'hands out headers a caller cannot write through' do + zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => '7' }) + + expect { client.get('api/v1/groups').headers['x-total-count'] = '999' }.to raise_error(FrozenError) + end + + describe 'a sequence' do + it 'serves stubs in the order they were declared' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'First' }) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) + + expect(client.groups.find(1).name).to eq('First') + expect(client.groups.find(1).name).to eq('Second') + end + + it 'keeps answering with the last one' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'First' }) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) + + 3.times { client.groups.find(1) } + expect(client.groups.find(1).name).to eq('Second') + end + + it 'reuses a single stub for any number of requests' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) + + expect(Array.new(3) { client.groups.find(1).name }).to eq(%w[Users Users Users]) + end + end + + describe 'query matching' do + it 'matches a stub that names a subset of the parameters' do + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) + + expect(client.groups.order(:name).first.id).to eq(1) + end + + it 'does not answer a request without those parameters' do + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) + + expect { client.groups.all.to_a }.to raise_error(described_class::UnstubbedRequestError) + end + + it 'ignores the parameters the client adds itself' do + zammad.stub(:get, 'api/v1/groups', body: [], query: { sort_by: 'name' }) + + expect { client.groups.order(:name).to_a }.not_to raise_error + end + + it 'keeps answering when a catch-all for the same endpoint follows it' do + zammad.stub(:get, 'api/v1/groups/search', body: { total_count: 42 }, query: { only_total_count: true }) + zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1 }]) + + expect(Array.new(3) { client.groups.search('x').count }).to eq([42, 42, 42]) + end + + it 'leaves the catch-all answering the requests it does not match' do + zammad.stub(:get, 'api/v1/groups/search', body: { total_count: 42 }, query: { only_total_count: true }) + zammad.stub(:get, 'api/v1/groups/search', body: [], query: { page: 2 }) + zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1 }]) + + expect(client.groups.search('x').count).to eq(42) + expect(client.groups.search('x').map(&:id)).to eq([1]) + expect(client.groups.search('x').count).to eq(42) + end + + it 'matches an array-valued parameter' do + zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { ids: [1, 2], page: 1 }) + zammad.stub(:get, 'api/v1/users/search', body: [], query: { ids: [1, 2], page: 2 }) + + expect(client.users.search('x', ids: [1, 2]).map(&:id)).to eq([1]) + end + + it 'reports a nil query value against the stub that wrote it' do + expect { zammad.stub(:get, 'api/v1/users/search', body: [], query: { ids: nil }) } + .to raise_error(ArgumentError, /query parameter ids is nil/) + end + + it 'does not match an array whose values differ' do + zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { ids: [1, 2] }) + + expect { client.users.search('x', ids: [3]).to_a } + .to raise_error(described_class::UnstubbedRequestError) + end + + it 'answers ahead of a catch-all declared before it' do + zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1 }]) + zammad.stub(:get, 'api/v1/groups/search', body: { total_count: 42 }, query: { only_total_count: true }) + + expect(client.groups.search('x').count).to eq(42) + end + + it 'still sequences two stubs that share a scope' do + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }], query: { sort_by: 'name' }) + + expect(client.groups.all.order(:name).page(1, per_page: 1).map(&:id)).to eq([1]) + expect(client.groups.all.order(:name).page(1, per_page: 1).map(&:id)).to eq([2]) + expect(client.groups.all.order(:name).page(1, per_page: 1).map(&:id)).to eq([2]) + end + end + end + + describe 'an unstubbed request' do + it 'raises rather than returning something empty' do + expect { client.groups.find(1) }.to raise_error(described_class::UnstubbedRequestError) + end + + it 'names the request that was not stubbed' do + expect { client.groups.find(1) } + .to raise_error(%r{GET api/v1/groups/1 was not stubbed}) + end + + it 'says so when nothing at all is stubbed' do + expect { client.groups.find(1) }.to raise_error(/nothing is stubbed/) + end + + it 'lists what is stubbed, because a wrong path is the usual cause' do + zammad.stub(:get, 'api/v1/groups/2', body: { id: 2 }) + + expect { client.groups.find(1) }.to raise_error(%r{stubbed: GET api/v1/groups/2}) + end + + # Listing the endpoint among what is stubbed read as a contradiction. + context 'when the endpoint is stubbed for other queries' do + before do + zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { page: 1 }) + zammad.stub(:get, 'api/v1/users/search', body: [{ id: 2 }], query: { page: 2 }) + end + + it 'names the query the request carried and the scopes its stubs answer' do + expect { client.users.search('x').to_a }.to raise_error( + described_class::UnstubbedRequestError, + %r{GET api/v1/users/search with query \{.*"page" => "3".*\} was not stubbed .*: its stubs answer only query: \{"page" => "1"\}, query: \{"page" => "2"\}\.} + ) + end + + it 'says that a read asks for the page after its last one' do + expect { client.users.search('x').to_a } + .to raise_error(described_class::UnstubbedRequestError, /A read asks for the page after the last one it was served/) + end + + it 'says nothing about pages where the scopes do not name one' do + zammad.reset.stub(:get, 'api/v1/users/search', body: [], query: { ids: [1] }) + + expect { client.users.search('x', ids: [2]).to_a } + .to raise_error(described_class::UnstubbedRequestError) { |error| expect(error.message).not_to include('page after') } + end + end + + it 'is outside ZammadAPI::Error, so code under test cannot rescue it as an API failure' do + expect(described_class::UnstubbedRequestError.ancestors).not_to include(ZammadAPI::Error) + expect(described_class::UnstubbedRequestError.ancestors).to include(StandardError) + end + + it 'escapes a rescue of the gem\'s errors, the way the examples write one' do + zammad.stub(:get, 'api/v1/groups/2', body: { id: 2 }) + + caller_with_a_rescue = lambda do + client.groups.find(1) + rescue ZammadAPI::Error + :handled_as_an_api_failure + end + + expect { caller_with_a_rescue.call }.to raise_error(described_class::UnstubbedRequestError) + end + end + + describe '#requests' do + before do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) + zammad.stub(:put, 'api/v1/groups/1', body: { id: 1, name: 'Renamed' }) + end + + it 'records the verb and path' do + client.groups.find(1) + + expect(zammad.requests.last.verb).to eq(:get) + expect(zammad.requests.last.path).to eq('api/v1/groups/1') + end + + it 'records only what a save actually sends' do + client.groups.find(1).update!(name: 'Renamed') + + expect(zammad.requests.last.body).to eq({ name: 'Renamed' }) + end + + # Recorded by reference, a test that built one payload, sent it, then + # changed it for a second call rewrote the first recorded request and + # asserted against a body that never went anywhere. + it 'records the body as it was sent, not as the test left it afterwards' do + zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) + payload = { name: 'Support', note: { internal: 'yes' } } + client.post('api/v1/groups', body: payload) + + payload[:name] = 'Mutated' + payload[:note][:internal] = 'no' + + expect(zammad.requests.last.body).to eq({ name: 'Support', note: { internal: 'yes' } }) + end + + it 'hands out a recorded body that cannot be written through' do + zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) + client.post('api/v1/groups', body: { name: 'Support' }) + + expect(zammad.requests.last.body).to be_frozen + end + + it 'records the query parameters the client sent' do + client.groups.find(1) + + expect(zammad.requests.last.query).to eq({ 'expand' => 'true' }) + end + + it 'records them stringified, the way the transport sends them' do + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }]) + client.groups.all.page(2, per_page: 50).to_a + + expect(zammad.requests.last.query) + .to eq({ 'expand' => 'true', 'page' => '2', 'per_page' => '50' }) + end + + it 'rejects a nil query value the way the transport does' do + expect { client.get('api/v1/groups', query: { sort_by: nil }) } + .to raise_error(ArgumentError, /query parameter sort_by is nil/) + end + + it 'records requests oldest first' do + client.groups.find(1).update!(name: 'Renamed') + + expect(zammad.requests.map(&:verb)).to eq(%i[get put]) + end + + it 'records an on_behalf_of scope' do + client.on_behalf_of('agent@example.com').groups.find(1) + + expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') + end + + it 'records an integer user id the way the wire carries it' do + client.on_behalf_of(42).groups.find(1) + + expect(zammad.requests.last.on_behalf_of).to eq('42') + end + + it 'records the scope a client was given, not what its string became afterwards' do + login = +'agent@example.com' + scoped = client.on_behalf_of(login) + login.replace('admin@example.com') + scoped.groups.find(1) + + expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') + end + + it 'leaves on_behalf_of nil for an unscoped client' do + client.groups.find(1) + + expect(zammad.requests.last.on_behalf_of).to be_nil + end + + # The stand-in carries the scope by the real transport's rule, so it + # refuses one the wire would carry as no scope at all. + it 'refuses a blank scope reached through the transport, the way the real transport does' do + expect { client.instance_variable_get(:@transport).with_on_behalf_of(' ') } + .to raise_error(ArgumentError, /on_behalf_of needs the login/) + end + + it 'refuses one it is built with directly' do + expect { ZammadAPI::Test::Transport.new(zammad, on_behalf_of: ' ') }.to raise_error(ArgumentError, /on_behalf_of needs the login/) + end + + it 'holds one it is built with as the text the header carries' do + expect(ZammadAPI::Test::Transport.new(zammad, on_behalf_of: 7).on_behalf_of).to eq('7') + end + + # Through the real transport's own rules, so that a stand-in cannot accept + # a header the wire would refuse or record it in a shape the wire would + # not carry. + it 'records the headers a raw request asked for' do + zammad.stub(:get, 'api/v1/roles', body: []) + client.get('api/v1/roles', headers: { 'Accept-Language' => 'de-de' }) + + expect(zammad.requests.last.headers).to eq('accept-language' => 'de-de') + end + + it 'records a header value the way the wire would carry it' do + zammad.stub(:get, 'api/v1/roles', body: []) + client.get('api/v1/roles', headers: { 'X-Retry' => 3 }) + + expect(zammad.requests.last.headers).to eq('x-retry' => '3') + end + + it 'leaves the headers empty for a request that named none' do + client.groups.find(1) + + expect(zammad.requests.last.headers).to eq({}) + end + + it 'refuses a header the real transport would refuse' do + expect { client.get('api/v1/roles', headers: { 'Authorization' => 'Token other' }) } + .to raise_error(ArgumentError, /header authorization is set by this client/) + end + + it 'records a request that was not stubbed, so the failure can be inspected' do + expect { client.groups.find(2) }.to raise_error(described_class::UnstubbedRequestError) + expect(zammad.requests.map(&:path)).to eq(['api/v1/groups/2']) + end + + it 'hands out a frozen list' do + expect { zammad.requests << :nonsense }.to raise_error(FrozenError) + end + + it 'is recorded from several threads without losing any' do + threads = Array.new(4) { Thread.new { 5.times { client.groups.find(1) } } } + threads.each(&:join) + + expect(zammad.requests.size).to eq(20) + end + end + + describe '#reset' do + it 'forgets the stubs' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + zammad.reset + + expect { client.groups.find(1) }.to raise_error(described_class::UnstubbedRequestError) + end + + it 'forgets the recorded requests' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + client.groups.find(1) + + expect(zammad.reset.requests).to be_empty + end + end + + describe '#inspect' do + it 'reports the stubs and the requests' do + zammad.stub(:get, 'api/v1/groups', body: []) + client.groups.all.to_a + + expect(zammad.inspect).to eq('#') + end + + # The request count used to be read outside the monitor, so printing a + # stand-in from a failure message or a debugger raced a thread under test + # appending to it - which is the one thing the monitor is here to prevent. + it 'reads the recorded requests under the monitor' do + zammad.stub(:get, 'api/v1/groups', body: []) + writers = Array.new(4) { Thread.new { 25.times { client.groups.all.to_a } } } + readers = Array.new(4) { Thread.new { 25.times { zammad.inspect } } } + + expect { (writers + readers).each(&:join) }.not_to raise_error + expect(zammad.requests.size).to eq(100) + end + end + + # A collection walks until a page repeats, comes back short, or comes back + # empty. A stub that served the same records to every page tripped the + # first of those, so the obvious way to stand in for a list endpoint made + # every full read of it raise PaginationError - against a real Zammad the + # same code works, because page 2 comes back empty. + describe 'a list endpoint stubbed once' do + subject(:zammad) { described_class.new } + + let(:client) { zammad.client } + + before { zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }]) } + + it 'reads the whole collection without a second stub' do + expect(client.groups.all.map(&:id)).to eq([1, 2]) + end + + it 'counts it' do + expect(client.groups.all.count).to eq(2) + end + + it 'plucks from it' do + expect(client.groups.all.pluck(:name)).to eq(%w[a b]) + end + + it 'answers page 1 with the records it holds' do + expect(client.groups.all.page(1).map(&:id)).to eq([1, 2]) + end + + it 'answers a later page as an endpoint out of records would' do + expect(client.groups.all.page(2).map(&:id)).to eq([]) + end + + it 'stops walking rather than reporting the stand-in as a broken paginator' do + expect { client.groups.all.to_a }.not_to raise_error + end + end + + # The object a Zammad from 6.5.1 on answers a walked search with. It is a + # list too, so the page after it holds no records - and reports the same + # total, which is what a walk reads to tell that page from the end. + describe 'a search stubbed once with its total beside the records' do + subject(:zammad) { described_class.new } + + let(:client) { zammad.client } + + it 'reads the whole search without a second stub' do + zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }], total_count: 2 }) + + expect(client.users.search('smith').map(&:id)).to eq([1, 2]) + end + + it 'answers a later page with no records and the same total' do + zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }], total_count: 2 }) + + expect(client.get('api/v1/users/search', query: { query: 'smith', page: 2 }).body).to eq(records: [], total_count: 2) + end + + it 'answers page 1 as it was written' do + zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }], total_count: 2 }) + + expect(client.get('api/v1/users/search', query: { query: 'smith', page: 1 }).body).to eq(records: [{ id: 1 }, { id: 2 }], total_count: 2) + end + + # The stub holds two records and says there are five hundred hits, so the + # walk reads on, a page of two hundred at a time, until it has covered + # them: the page it was served, and two that hold nothing. + it 'is read on past, where the total says there are hits beyond the stub' do + zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }], total_count: 500 }) + + expect(client.users.search('smith').map(&:id)).to eq([1, 2]) + expect(zammad.requests.map { it.query['page'] }).to eq(%w[1 2 3]) + end + + it 'records the parameter a walked search asks for the total with' do + zammad.stub(:get, 'api/v1/users/search', body: []) + client.users.search('smith').to_a + + expect(zammad.requests.last.query).to include('with_total_count' => 'true') + end + + it 'leaves an object that is not a counted list as it was written' do + zammad.stub(:get, 'api/v1/settings', body: { records: 'none' }) + + expect(client.get('api/v1/settings', query: { page: 2 }).body).to eq(records: 'none') + end + end + + # Every full read asks for the page after its last one, and that request + # used to take the next stub in the queue and serve it as an empty page: + # three stubs answered three reads with the first, the third and the third. + describe 'a list endpoint stubbed as a sequence' do + subject(:zammad) { described_class.new } + + let(:client) { zammad.client } + + def names = client.groups.all.map(&:name) + + before do + %w[A B C].each { zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: it }]) } + end + + it 'answers each read with the next stub' do + expect(Array.new(3) { names }).to eq([['A'], ['B'], ['C']]) + end + + it 'keeps answering with the last one' do + 3.times { names } + expect(names).to eq(['C']) + end + + it 'spends one stub on a read, however many pages the read asks for' do + names + expect(zammad.requests.map { it.query['page'] }).to eq(%w[1 2]) + expect(names).to eq(['B']) + end + + it 'answers the trailing page from the stub the read began with, not the next one' do + zammad.reset + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'A' }]) + zammad.stub(:get, 'api/v1/groups', status: 500, body: { error: 'down' }) + + expect(names).to eq(['A']) + expect { names }.to raise_error(ZammadAPI::ServerError) + end + + it 'does not spend a stub on a later page asked for first' do + expect(client.groups.all.page(3).to_a).to eq([]) + expect(names).to eq(['A']) + end + + it 'spends one stub on a read sized for a single record' do + expect(Array.new(3) { client.groups.first.name }).to eq(%w[A B C]) + end + + it 'starts over after a reset' do + names + zammad.reset + zammad.stub(:get, 'api/v1/groups', body: [{ id: 2, name: 'D' }]) + + expect(Array.new(2) { names }).to eq([['D'], ['D']]) + end + + it 'sequences a scoped list the same way' do + zammad.reset + %w[A B].each { zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1, name: it }], query: { query: 'x' }) } + + expect(Array.new(2) { client.groups.search('x').map(&:name) }).to eq([['A'], ['B']]) + end + end + + describe 'a list endpoint whose pages are stubbed by hand' do + subject(:zammad) { described_class.new } + + let(:client) { zammad.client } + + # A stub that names a page is left exactly as written - that is how a test + # says what the second page holds. + it 'serves each page as declared' do + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { page: 1 }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }], query: { page: 2 }) + zammad.stub(:get, 'api/v1/groups', body: [], query: { page: 3 }) + + expect(client.groups.all.map(&:id)).to eq([1, 2]) + end + + it 'keeps a body that is not a list alone' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'a' }) + + expect(client.groups.find(1).name).to eq('a') + end + end + + # Two stubs naming different parameters both match a request carrying all of + # them. Grouped only by whether they were scoped at all, they were read as a + # sequence and the first was consumed: the count ate the records stub, + # handed back an Array where a count belonged, and then reported the + # endpoint as unstubbed. + describe 'two stubs that describe one request equally well' do + subject(:zammad) { described_class.new } + + let(:client) { zammad.client } + + before do + zammad.stub(:get, 'api/v1/tickets/search', body: [{ id: 1 }], query: { query: 'foo' }) + zammad.stub(:get, 'api/v1/tickets/search', body: { total_count: 2 }, query: { only_total_count: true }) + end + + it 'refuses to guess which one was meant' do + expect { client.tickets.search('foo').count }.to raise_error(described_class::AmbiguousStubError) + end + + it 'names both scopes, so the fix is visible from the message' do + expect { client.tickets.search('foo').count } + .to raise_error(described_class::AmbiguousStubError, /only_total_count.*|.*only_total_count/) + end + + it 'says the test is wrong rather than that Zammad refused something' do + expect(described_class::AmbiguousStubError.ancestors).not_to include(ZammadAPI::Error) + end + + it 'answers the request a more specific stub names' do + zammad.reset + zammad.stub(:get, 'api/v1/tickets/search', body: [{ id: 1 }], query: { query: 'foo' }) + zammad.stub(:get, 'api/v1/tickets/search', body: { total_count: 2 }, query: { query: 'foo', only_total_count: true }) + + expect(client.tickets.search('foo').count).to eq(2) + end + + it 'leaves the less specific stub answering the requests it alone matches' do + zammad.reset + zammad.stub(:get, 'api/v1/tickets/search', body: [{ id: 1 }], query: { query: 'foo' }) + zammad.stub(:get, 'api/v1/tickets/search', body: { total_count: 2 }, query: { query: 'foo', only_total_count: true }) + + expect(client.tickets.search('foo').map(&:id)).to eq([1]) + end + end +end From 30534e172e715d70d70ac99a300227d237b3922a Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 18 Nov 2026 10:09:40 +0200 Subject: [PATCH 003/121] feat: add RBS signatures and check them with Steep The gem ships signatures in sig/, so a typed project gets completion and checking for the client, the collections and the records without writing any of its own. ResourceProxy and Collection are generic over the resource they hold: client.tickets is a ResourceProxy[Resources::Ticket], and what it finds, yields and searches is a Ticket. Each resource declares the attributes Zammad serves for it, typed the way their JSON arrives. The declarations are signatures only. A record still answers through method_missing, so an attribute an administrator added works and is simply untyped. Three things keep the signatures honest. rake steep checks lib/ against them. rake rbs_published validates the published set without sig/vendor, which holds stand-ins for dependencies that ship no signatures and is kept out of the gem: a Faraday type named in a published signature would fail for every consumer and pass here. And spec/typed/usage.rb is a file written the way a caller writes one, checked as a second Steep target, where each line that must be a type error carries a steep:ignore that Steep reports once it silences nothing. With this commit the default rake task has everything it runs. --- Steepfile | 42 +++++ sig/vendor/faraday.rbs | 57 +++++++ sig/vendor/internal.rbs | 14 ++ sig/zammad_api.rbs | 3 + sig/zammad_api/associations.rbs | 37 +++++ sig/zammad_api/attribute_access.rbs | 39 +++++ sig/zammad_api/client.rbs | 66 ++++++++ sig/zammad_api/collection.rbs | 83 ++++++++++ sig/zammad_api/config.rbs | 92 +++++++++++ sig/zammad_api/deep_copy.rbs | 7 + sig/zammad_api/duplicate_keys.rbs | 9 ++ sig/zammad_api/errors.rbs | 74 +++++++++ sig/zammad_api/query_encoder.rbs | 13 ++ sig/zammad_api/resource_proxy.rbs | 60 +++++++ sig/zammad_api/resources/base.rbs | 101 ++++++++++++ sig/zammad_api/resources/resources.rbs | 210 +++++++++++++++++++++++++ sig/zammad_api/response.rbs | 26 +++ sig/zammad_api/test.rbs | 84 ++++++++++ sig/zammad_api/transport.rbs | 91 +++++++++++ spec/typed/sig/usage.rbs | 34 ++++ spec/typed/usage.rb | 78 +++++++++ 21 files changed, 1220 insertions(+) create mode 100644 Steepfile create mode 100644 sig/vendor/faraday.rbs create mode 100644 sig/vendor/internal.rbs create mode 100644 sig/zammad_api.rbs create mode 100644 sig/zammad_api/associations.rbs create mode 100644 sig/zammad_api/attribute_access.rbs create mode 100644 sig/zammad_api/client.rbs create mode 100644 sig/zammad_api/collection.rbs create mode 100644 sig/zammad_api/config.rbs create mode 100644 sig/zammad_api/deep_copy.rbs create mode 100644 sig/zammad_api/duplicate_keys.rbs create mode 100644 sig/zammad_api/errors.rbs create mode 100644 sig/zammad_api/query_encoder.rbs create mode 100644 sig/zammad_api/resource_proxy.rbs create mode 100644 sig/zammad_api/resources/base.rbs create mode 100644 sig/zammad_api/resources/resources.rbs create mode 100644 sig/zammad_api/response.rbs create mode 100644 sig/zammad_api/test.rbs create mode 100644 sig/zammad_api/transport.rbs create mode 100644 spec/typed/sig/usage.rbs create mode 100644 spec/typed/usage.rb diff --git a/Steepfile b/Steepfile new file mode 100644 index 0000000..d46d146 --- /dev/null +++ b/Steepfile @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +target :lib do + signature 'sig' + check 'lib' + + # socket is here for SocketError and openssl for OpenSSL::SSL::SSLError, + # both of which Transport maps to ConnectionError; forwardable is here for + # the collection shorthands ResourceProxy delegates to Collection; uri is + # here for the parse Config makes to find credentials in the instance url. + # None of the four is named in the signatures the gem publishes - see + # SSL_ERRORS in sig/zammad_api/transport.rbs and sig/vendor/internal.rbs - so + # this does not add anything a consumer has to load. + library 'json', 'logger', 'timeout', 'socket', 'openssl', 'forwardable', 'uri' + + configure_code_diagnostics do |hash| + # Default keyword-argument hashes such as `attributes = {}` cannot be + # annotated without hurting readability. + hash[Steep::Diagnostic::Ruby::UnannotatedEmptyCollection] = nil + end +end + +# A file written the way a typed project that uses this gem writes one, checked +# against the same signatures as lib/. It is never run - see spec/typed/usage.rb +# for what it pins. +# +# sig/vendor is in here, although a consumer does not have it, because Steep +# hands a signature file to every target of a project whatever the target's +# own pattern says. Listing only the published directories left this target +# with sig/vendor/internal.rbs all the same and without the library it names, +# so its signatures failed to load and Steep then skips the source files of +# such a target without a word: the check passed having checked nothing. That +# the published signatures stand on their own is what `rake rbs_published` +# establishes. +target :usage do + signature 'sig', 'spec/typed/sig' + check 'spec/typed' + + # logger is the one library the published signatures name; forwardable is + # here for sig/vendor/internal.rbs. + library 'logger', 'forwardable' +end diff --git a/sig/vendor/faraday.rbs b/sig/vendor/faraday.rbs new file mode 100644 index 0000000..728de63 --- /dev/null +++ b/sig/vendor/faraday.rbs @@ -0,0 +1,57 @@ +# Minimal declarations for the parts of Faraday this gem uses. +# Faraday does not ship RBS signatures of its own. + +module Faraday + class Error < StandardError + end + + class ConnectionFailed < Error + end + + class TimeoutError < Error + end + + class SSLError < Error + end + + class RetriableResponse < Error + end + + class Response + def status: () -> Integer + def body: () -> untyped + def headers: () -> untyped + end + + class Request + def url: (String) -> void + def params: () -> Hash[String, untyped] + def body=: (untyped) -> void + def headers: () -> Hash[String, untyped] + end + + # Faraday.new yields the connection itself, which delegates the stack + # building methods below to its RackBuilder. + class Connection + def get: (String) ?{ (Request) -> void } -> Response + def post: (String) ?{ (Request) -> void } -> Response + def put: (String) ?{ (Request) -> void } -> Response + def delete: (String) ?{ (Request) -> void } -> Response + def public_send: (Symbol, *untyped) ?{ (Request) -> void } -> Response + + def request: (Symbol, *untyped) -> void + def response: (Symbol, *untyped) -> void + def adapter: (untyped, *untyped) -> void + def use: (untyped, *untyped) -> void + end + + # The encoder a connection writes its query with by default. An Array of + # pairs is written in the order it is given, where a Hash is sorted. + class NestedParamsEncoder + def self.encode: (untyped params) -> String? + def self.decode: (String? query) -> untyped + end + + def self.new: (**untyped) ?{ (Connection) -> void } -> Connection + def self.default_adapter: () -> Symbol +end diff --git a/sig/vendor/internal.rbs b/sig/vendor/internal.rbs new file mode 100644 index 0000000..620fdc7 --- /dev/null +++ b/sig/vendor/internal.rbs @@ -0,0 +1,14 @@ +# Declarations that hold only while this repository is type-checked, and are +# deliberately not part of what the gem publishes. +# +# ResourceProxy forwards the collection shorthands with Forwardable, so the +# type checker has to know the class extends it before it can see +# `def_delegators` on the singleton. Consumers never need that: the published +# signatures declare each forwarded method concretely, which is what a caller +# is checked against, and naming Forwardable there would make `rbs validate` +# fail for anyone who has not loaded the stdlib declarations for it. +module ZammadAPI + class ResourceProxy[R < Resources::Base] + extend Forwardable + end +end diff --git a/sig/zammad_api.rbs b/sig/zammad_api.rbs new file mode 100644 index 0000000..3a9109a --- /dev/null +++ b/sig/zammad_api.rbs @@ -0,0 +1,3 @@ +module ZammadAPI + VERSION: String +end diff --git a/sig/zammad_api/associations.rbs b/sig/zammad_api/associations.rbs new file mode 100644 index 0000000..44d58c9 --- /dev/null +++ b/sig/zammad_api/associations.rbs @@ -0,0 +1,37 @@ +module ZammadAPI + module Associations + # The readers are defined by the belongs_to and has_many declarations in + # lib/zammad_api/resources, onto a per-resource subclass of this one that + # has no name to declare. They are listed here so that callers get types + # and completion; every name is declared once and means the same target + # wherever it is declared, so the type of a given reader is accurate. The + # class is wider than any one resource, so a reader the record does not + # declare type-checks here and raises NoMethodError at runtime. + class Proxy + @record: Resources::Base + @cache: Hash[Symbol, untyped] + + def initialize: (Resources::Base record) -> void + def inspect: () -> String + + def created_by: () -> Resources::User? + def updated_by: () -> Resources::User? + def customer: () -> Resources::User? + def owner: () -> Resources::User? + def organization: () -> Resources::Organization? + def group: () -> Resources::Group? + def state: () -> Resources::TicketState? + def priority: () -> Resources::TicketPriority? + def ticket: () -> Resources::Ticket? + def articles: () -> Array[Resources::TicketArticle] + + private + + def belongs_to_target: (Symbol name, String class_name, Symbol foreign_key) -> untyped + def has_many_target: (Symbol name, String class_name, ^(String) -> String path) -> Array[untyped] + def forget_targets: () -> void + def refuse_destroyed!: (Symbol name) -> void + def resolve: (String class_name) -> untyped + end + end +end diff --git a/sig/zammad_api/attribute_access.rbs b/sig/zammad_api/attribute_access.rbs new file mode 100644 index 0000000..0189c51 --- /dev/null +++ b/sig/zammad_api/attribute_access.rbs @@ -0,0 +1,39 @@ +module ZammadAPI + module AttributeAccess + NON_ATTRIBUTE_SUFFIXES: Array[String] + # private_constant in the source; RBS has no way to say so. + ATTRIBUTE_WRITER: Regexp + + @attributes: Hash[Symbol, untyped] + + attr_reader attributes: Hash[Symbol, untyped] + + def []: (Symbol | String key) -> untyped + def []=: (Symbol | String key, untyped value) -> untyped + def fetch: (Symbol | String key, *untyped default) ?{ (Symbol) -> untyped } -> untyped + def key?: (Symbol | String key) -> bool + def to_h: () -> Hash[Symbol, untyped] + def id: () -> Integer? + def deconstruct_keys: (Array[Symbol]?) -> Hash[Symbol, untyped] + def ==: (untyped other) -> bool + def eql?: (untyped other) -> bool + def hash: () -> Integer + def as_json: (*untyped) -> Hash[Symbol, untyped] + def to_json: (?untyped state) -> String + def method_missing: (Symbol, *untyped) -> untyped + def respond_to?: (untyped name, ?bool include_private) -> bool + def respond_to_missing?: (Symbol, ?bool) -> bool + + private + + # Protected in the source, which RBS has no way to say: it is asked of + # the other record in `==`, and of nobody else. + def installation: () -> String? + def unknown_attribute_message: (Symbol name) -> String + def writable_attributes?: () -> bool + def attribute_writable?: (Symbol key) -> bool + def write_attribute: (Symbol, untyped) -> untyped + def frozen_attributes: (untyped) -> untyped + def deep_dup: (untyped) -> untyped + end +end diff --git a/sig/zammad_api/client.rbs b/sig/zammad_api/client.rbs new file mode 100644 index 0000000..ce64ff2 --- /dev/null +++ b/sig/zammad_api/client.rbs @@ -0,0 +1,66 @@ +module ZammadAPI + class Client + RESOURCES: Hash[Symbol, untyped] + DEPRECATED_RESOURCES: Hash[Symbol, Symbol] + CONVERSION_METHODS: Array[Symbol] + ENV_OPTIONS: Hash[String, Symbol] + + attr_reader config: Config + + @transport: Transport + @resources: Hash[untyped, ResourceProxy[untyped]] + + def self.from_env: (**untyped overrides) -> Client + def self.warn_deprecated_resource: (Symbol old_name, Symbol name) -> void + def self.build: (Config config, untyped transport) -> Client + + def initialize: (**untyped options) -> void + + def groups: () -> ResourceProxy[Resources::Group] + def organizations: () -> ResourceProxy[Resources::Organization] + def tickets: () -> ResourceProxy[Resources::Ticket] + def ticket_articles: () -> ResourceProxy[Resources::TicketArticle] + def ticket_priorities: () -> ResourceProxy[Resources::TicketPriority] + def ticket_states: () -> ResourceProxy[Resources::TicketState] + def users: () -> ResourceProxy[Resources::User] + + # The names these readers had in 1.x. Each warns in Ruby's `deprecated` + # category and answers what its plural answers. + %a{deprecated: use groups} def group: () -> ResourceProxy[Resources::Group] + %a{deprecated: use organizations} def organization: () -> ResourceProxy[Resources::Organization] + %a{deprecated: use tickets} def ticket: () -> ResourceProxy[Resources::Ticket] + %a{deprecated: use ticket_articles} def ticket_article: () -> ResourceProxy[Resources::TicketArticle] + %a{deprecated: use ticket_priorities} def ticket_priority: () -> ResourceProxy[Resources::TicketPriority] + %a{deprecated: use ticket_states} def ticket_state: () -> ResourceProxy[Resources::TicketState] + %a{deprecated: use users} def user: () -> ResourceProxy[Resources::User] + + # A class cannot carry its own type into the answer - RBS has no way to + # say "a proxy for whichever class this is" - so a proxy for a resource of + # your own is untyped until you say what it is: + # + # roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role] + def resource: (Symbol | String | Class name) -> ResourceProxy[untyped] + def resource_names: () -> Array[Symbol] + def me: () -> Resources::User + def version: () -> String? + + def get: (String path, ?query: Hash[untyped, untyped]?, ?headers: Hash[untyped, untyped]?) -> Response + def post: (String path, ?query: Hash[untyped, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?) -> Response + def put: (String path, ?query: Hash[untyped, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?) -> Response + def delete: (String path, ?query: Hash[untyped, untyped]?, ?headers: Hash[untyped, untyped]?) -> Response + + def with: (**untyped options) -> Client + def on_behalf_of: (String | Integer identifier) -> Client + | [T] (String | Integer identifier) { (Client) -> T } -> T + def inspect: () -> String + def method_missing: (Symbol, *untyped) -> untyped + def respond_to_missing?: (Symbol, ?bool) -> bool + + private + + def raw: (Symbol method, String path, ?query: Hash[untyped, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?) -> Response + def unknown_resource_message: (Symbol | String) -> String + def proxy_for: (untyped resource_class) -> ResourceProxy[untyped] + def setup: (Config config, untyped transport) -> self + end +end diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs new file mode 100644 index 0000000..7909465 --- /dev/null +++ b/sig/zammad_api/collection.rbs @@ -0,0 +1,83 @@ +module ZammadAPI + # Generic over the resource it holds, so that what a walk yields is a + # Resources::Ticket rather than something untyped: `client.tickets.all` is a + # Collection[Resources::Ticket]. + class Collection[R < Resources::Base] + include Enumerable[R] + + # Both are private_constant in the source; RBS has no way to say so. + SORT_DIRECTIONS: Array[String] + SORT_ATTRIBUTE: Regexp + + @transport: Transport + @resource_class: untyped + @path: String + @operation: String + @query: Hash[Symbol, untyped] + @max_per_page: Integer + @sortable: bool + @unsortable_hint: String + @per_page: Integer + @page: Integer? + @search: bool + @widens: bool + + def initialize: ( + transport: Transport, + resource_class: untyped, + path: String, + operation: String, + max_per_page: Integer, + sortable: bool, + unsortable_hint: String, + ?query: Hash[Symbol, untyped], + ?per_page: Integer?, + ?page: Integer?, + ?search: bool, + ?widens: bool + ) -> void + + def each: () { (R) -> void } -> Collection[R] + | () -> Enumerator[R, Collection[R]] + def find_each: (?batch_size: Integer?) { (R) -> void } -> Collection[R] + | (?batch_size: Integer?) -> Enumerator[R, Collection[R]] + def in_batches: (?of: Integer?) { (Array[R]) -> void } -> Collection[R] + | (?of: Integer?) -> Enumerator[Array[R], Collection[R]] + def page: (Integer number, ?per_page: Integer?) -> Collection[R] + def first: () -> R? + | (Integer count) -> Array[R] + def take: (Integer count) -> Array[R] + def find: (?untyped ifnone) { (R) -> boolish } -> R? + | (*untyped) -> untyped + def order: (*(Symbol | String) attributes, **(Symbol | String) directions) -> Collection[R] + def pluck: (*(Symbol | String) keys) -> Array[untyped] + def count: (*untyped) ?{ (R) -> boolish } -> Integer + def size: (*untyped) ?{ (R) -> boolish } -> Integer + def length: (*untyped) ?{ (R) -> boolish } -> Integer + def empty?: () -> bool + def inspect: () -> String + + private + + def own_request_for_first?: (untyped count) -> bool + def find_by_id_message: (untyped) -> String + def resource_reader: () -> String + def sort_columns: (Array[untyped] attributes, Hash[untyped, untyped] directions) -> Hash[String, String] + def sort_attribute!: (untyped attribute) -> String + def sort_direction!: (String name, untyped direction) -> String + def sorted_by: () -> Hash[String, String] + def positive_integer!: (untyped, String) -> Integer + def page_size!: (untyped, String) -> Integer + def walk: () { (Array[R]) -> void } -> void + def page_after: (Integer page, Integer per_page, Integer received, Integer? total) -> [ Integer, Integer ] + def widened: (Integer covered, Integer? total) -> [ Integer, Integer ] + def each_distinct: () { (Resources::Base) -> void } -> void + def with: (?page: Integer?, ?per_page: Integer, ?query: Hash[Symbol, untyped], ?widens: bool) -> Collection[R] + def hits_past?: (Integer covered, Integer? total) -> bool + def fetch: (Integer, Integer) -> [ Array[R], Integer, Integer? ] + def page_query: (Integer page, Integer per_page) -> Hash[Symbol, untyped] + def page_digest: (Array[Hash[Symbol, untyped]] decoded) -> Integer + def total_count: () -> Integer? + def clamp_per_page: (untyped) -> Integer + end +end diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs new file mode 100644 index 0000000..1306364 --- /dev/null +++ b/sig/zammad_api/config.rbs @@ -0,0 +1,92 @@ +module ZammadAPI + # Built with Data.define; the generated readers are declared explicitly. + # + # `middleware` is a block handed a Faraday::Connection, but it is declared + # untyped here: these signatures ship with the gem, while the Faraday + # declarations they would need live in sig/vendor, which does not. Naming + # Faraday here made `rbs validate` fail for every consumer with + # `Could not find Faraday::Connection`. + class Config < ::Data + DEFAULT_TIMEOUT: Integer + DEFAULT_OPEN_TIMEOUT: Integer + DEFAULT_RETRIES: Integer + DEFAULT_RETRY_INTERVAL: Float + REDACTED_ATTRIBUTES: Array[Symbol] + REDACTION: String + DEFAULT_USER_AGENT: String + SCHEME_PATTERN: Regexp + URL_PATTERN: Regexp + URL_SUFFIX_PATTERN: Regexp + URL_SCHEME_PATTERN: Regexp + URL_AUTHORITY_PATTERN: Regexp + CREDENTIAL_OPTIONS: Hash[Symbol, Array[Symbol]] + + def self.new: (**untyped) -> instance + def self.merge_options: (Hash[Symbol, untyped] options, Hash[Symbol, untyped] overrides) -> Hash[Symbol, untyped] + + attr_reader url: String + attr_reader user: String? + attr_reader password: String? + attr_reader http_token: String? + attr_reader oauth2_token: String? + attr_reader user_agent: String + attr_reader timeout: Numeric + attr_reader open_timeout: Numeric + attr_reader retries: Integer + attr_reader retry_interval: Numeric + attr_reader ssl_verify: bool + attr_reader proxy: String? + attr_reader adapter: Symbol? + attr_reader middleware: untyped + attr_reader logger: Logger + + def initialize: ( + url: untyped, + ?user: String?, + ?password: String?, + ?http_token: String?, + ?oauth2_token: String?, + ?user_agent: String, + ?timeout: untyped, + ?open_timeout: untyped, + ?retries: untyped, + ?retry_interval: untyped, + ?ssl_verify: bool, + ?proxy: String?, + ?adapter: (Symbol | String)?, + ?middleware: untyped, + ?logger: Logger? + ) -> void + + def redacted_url: () -> String + def redacted: (String value) -> String + def authentication_scheme: () -> Symbol + def with: (**untyped) -> Config + def inspect: () -> String + def to_s: () -> String + def pretty_print: (untyped printer) -> void + def to_h: () -> Hash[Symbol, untyped] + + private + + def redact_userinfo: (String) -> String + def normalize_proxy: (untyped) -> String? + def normalize_adapter: (untyped) -> Symbol? + def render: (Symbol, untyped) -> String + def normalize_url: (untyped) -> String + def inline_credentials?: (String) -> bool + def inline_credentials_message: (String) -> String + def validate_credentials!: () -> void + def multiple_credentials_message: (Array[Symbol] schemes) -> String + def positive_number?: (untyped) -> bool + def validate_numbers!: () -> void + def validate_user_agent!: () -> void + HEADER_OPTIONS: Array[Symbol] + def validate_header_options!: () -> void + def validate_ssl_verify!: () -> void + def validate_middleware!: () -> void + def validate_logger!: () -> void + def presence: (untyped) -> untyped + def immutable: (untyped) -> untyped + end +end diff --git a/sig/zammad_api/deep_copy.rbs b/sig/zammad_api/deep_copy.rbs new file mode 100644 index 0000000..09526b8 --- /dev/null +++ b/sig/zammad_api/deep_copy.rbs @@ -0,0 +1,7 @@ +module ZammadAPI + module DeepCopy + def self?.frozen_copy: (untyped value, ?symbolize_keys: bool) -> untyped + def self?.writable_copy: (untyped value) -> untyped + def self?.symbolize: (untyped key) -> untyped + end +end diff --git a/sig/zammad_api/duplicate_keys.rbs b/sig/zammad_api/duplicate_keys.rbs new file mode 100644 index 0000000..3f26306 --- /dev/null +++ b/sig/zammad_api/duplicate_keys.rbs @@ -0,0 +1,9 @@ +module ZammadAPI + module DuplicateKeys + def self.normalize: (Hash[untyped, untyped] hash, ?prefix: String?, ?noun: String) { (untyped key) -> untyped } -> Hash[untyped, untyped] + def self.message: (String noun, untyped path, untyped first, untyped second) -> String + + def normalize: (Hash[untyped, untyped] hash, ?prefix: String?, ?noun: String) { (untyped key) -> untyped } -> Hash[untyped, untyped] + def message: (String noun, untyped path, untyped first, untyped second) -> String + end +end diff --git a/sig/zammad_api/errors.rbs b/sig/zammad_api/errors.rbs new file mode 100644 index 0000000..2b255eb --- /dev/null +++ b/sig/zammad_api/errors.rbs @@ -0,0 +1,74 @@ +module ZammadAPI + class Error < StandardError + def self.subject_for: (String operation, Class? resource_class) -> String + end + + class ConfigurationError < Error + end + + class UnknownResourceError < Error + end + + class TransportError < Error + end + + class ConnectionError < TransportError + end + + class TimeoutError < TransportError + end + + class ParseError < Error + def self.build: (operation: String, expected: (Symbol | String), actual: (Class | String), ?resource_class: Class?) -> ParseError + end + + class PaginationError < Error + def self.build: (operation: String, page: Integer, ?resource_class: Class?) -> PaginationError + end + + class ResponseError < Error + STATUS_ERRORS: Hash[Integer, singleton(ResponseError)] + + attr_reader response: Response? + attr_reader operation: String + attr_reader resource_class: Class? + + @detail: String? + + def self.build: (Response? response, operation: String, ?resource_class: Class?) -> ResponseError + def self.error_class_for: (Response?) -> singleton(ResponseError) + + def initialize: (operation: String, ?response: Response?, ?resource_class: Class?, ?detail: String?) -> void + def status: () -> Integer? + def body: () -> untyped + def headers: () -> Hash[String, String] + def server_message: () -> String? + + private + + def build_message: () -> String + def detail: () -> String + end + + class ClientError < ResponseError + end + + class ServerError < ResponseError + end + + class AuthenticationError < ClientError + end + + class AuthorizationError < ClientError + end + + class NotFoundError < ClientError + end + + class ValidationError < ClientError + end + + class RateLimitError < ClientError + def retry_after: () -> Integer? + end +end diff --git a/sig/zammad_api/query_encoder.rbs b/sig/zammad_api/query_encoder.rbs new file mode 100644 index 0000000..7404b7e --- /dev/null +++ b/sig/zammad_api/query_encoder.rbs @@ -0,0 +1,13 @@ +module ZammadAPI + module QueryEncoder + def self?.encode: (untyped params) -> String? + def self?.decode: (String? query) -> untyped + def self?.lead_path: (Hash[untyped, untyped] element, untyped previous) -> Array[untyped]? + def self?.misread: (untyped element, untyped previous) -> Symbol? + def self?.written?: (untyped value) -> bool + def self?.hash_pairs: (String? prefix, Hash[untyped, untyped] hash, Array[untyped]? lead) -> Array[[ String, untyped ]] + def self?.value_pairs: (String path, untyped value, ?Array[untyped]? lead) -> Array[[ String, untyped ]] + def self?.array_pairs: (String path, Array[untyped] array) -> Array[[ String, untyped ]] + def self?.sorted_keys: (Hash[untyped, untyped] hash) -> Array[untyped] + end +end diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs new file mode 100644 index 0000000..d166f80 --- /dev/null +++ b/sig/zammad_api/resource_proxy.rbs @@ -0,0 +1,60 @@ +module ZammadAPI + # Generic over the resource it is the entry point for: `client.tickets` is a + # ResourceProxy[Resources::Ticket], so `find` answers with a Ticket and a + # block over it is handed one. + class ResourceProxy[R < Resources::Base] + include Enumerable[R] + + SEARCH_MAX_PER_PAGE: Integer + SEARCH_FILTER_KEYS: Array[Symbol] + BLANK_TERM_MESSAGE: String + SEARCHABLE_UNSORTABLE_HINT: String + UNSORTABLE_HINT: String + + attr_reader resource_class: untyped + + @transport: Transport + + def initialize: (Transport, untyped resource_class) -> void + def new: (?Hash[untyped, untyped] attributes) -> R + def create: (?Hash[untyped, untyped] attributes) -> R + def find: (Integer | String id) -> R + def find_by: (**untyped) -> R? + def find_by!: (**untyped) -> R + def exists?: (Integer | String id) -> bool + def destroy: (Integer | String id) -> true + def all: () -> Collection[R] + def order: (*(Symbol | String) attributes, **(Symbol | String) directions) -> Collection[R] + + def each: () { (R) -> void } -> Collection[R] + | () -> Enumerator[R, Collection[R]] + def find_each: (?batch_size: Integer?) { (R) -> void } -> Collection[R] + | (?batch_size: Integer?) -> Enumerator[R, Collection[R]] + def in_batches: (?of: Integer?) { (Array[R]) -> void } -> Collection[R] + | (?of: Integer?) -> Enumerator[Array[R], Collection[R]] + def page: (Integer number, ?per_page: Integer?) -> Collection[R] + def pluck: (*(Symbol | String) keys) -> Array[untyped] + def count: (*untyped) ?{ (R) -> boolish } -> Integer + def size: () -> Integer + def length: () -> Integer + def empty?: () -> bool + def first: () -> R? + | (Integer count) -> Array[R] + def take: (Integer count) -> Array[R] + def search: (String term, ?condition: Hash[untyped, untyped], ?ids: Array[Integer | String], ?role_ids: Array[Integer | String], ?group_ids: Array[Integer | String] | Hash[Integer | String, String | Symbol | Array[String | Symbol]], ?permissions: Array[String]) -> Collection[R] + def inspect: () -> String + + private + + def collection: (String, String, ?query: Hash[Symbol, untyped], ?max_per_page: Integer, ?sortable: bool, ?search: bool) -> Collection[R] + def search_filters: (Hash[untyped, untyped] filters) -> Hash[Symbol, untyped] + def search_filter_keys: () -> Array[Symbol] + def unknown_search_filter_message: (Array[Symbol] unknown) -> String + def empty_search_filter?: (untyped value) -> bool + def empty_search_filter_message: (Hash[Symbol, untyped] empty) -> String + def searchable!: () -> void + def search_term_for: (Hash[Symbol, untyped]) -> String? + def path: () -> String + def member_path: (Integer | String id) -> String + end +end diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs new file mode 100644 index 0000000..1e7bf7b --- /dev/null +++ b/sig/zammad_api/resources/base.rbs @@ -0,0 +1,101 @@ +module ZammadAPI + module Resources + class Base + include AttributeAccess + + DEFAULT_MAX_PER_PAGE: Integer + MEMO_LOCK: Thread::Mutex + + attr_reader error: ValidationError? + attr_reader transport: Transport + + # What Zammad stamps every record with. These four are columns of every + # table, and the two names beside them are what `expand` adds: the login + # of each user. A record that was built with `new` and not saved yet + # carries none of them, and reading one then raises NoMethodError - the + # types here, and on every resource, describe a record Zammad served. + attr_reader created_by_id: Integer + attr_reader updated_by_id: Integer + attr_reader created_at: String + attr_reader updated_at: String + attr_reader created_by: String + attr_reader updated_by: String + + @new_record: bool + @destroyed: bool + @saved: bool + @error: ValidationError? + @changes: Hash[Symbol, Array[untyped]] + @related: Associations::Proxy? + @baseline: Hash[Symbol, untyped] + self.@related_class: untyped + self.@belongs_to_foreign_keys: Array[Symbol]? + self.@declared_associations: Hash[Symbol, Hash[Symbol, untyped]]? + self.@path: String? + self.@searchable: bool? + self.@max_per_page: Integer? + self.@search_filters: Array[Symbol]? + self.@sortable: bool? + + def self.path: (String) -> void + def self.searchable: (bool) -> void + def self.max_per_page: (Integer) -> void + def self.search_filters: (*Symbol | String names) -> void + def self.sortable: (bool) -> void + def self.resource_path: () -> String + def self.searchable?: () -> bool + def self.search_filter_names: () -> Array[Symbol] + def self.page_limit: () -> Integer + def self.sortable?: () -> bool + def self.member_path: ((Integer | String) id) -> String + def self.fetch_one: (Transport transport, (Integer | String) id) -> Base + def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> Base + def self.associations: () -> Hash[Symbol, Hash[Symbol, untyped]] + def self.belongs_to_foreign_keys: () -> Array[Symbol] + def self.related_class: () -> untyped + def self.declaration: [T] (Symbol name) { () -> T } -> T + | (Symbol name) -> untyped + def self.declared_associations: () -> Hash[Symbol, Hash[Symbol, untyped]] + def self.belongs_to: (Symbol name, class_name: String, ?foreign_key: Symbol) -> void + def self.has_many: (Symbol name, class_name: String, path: ^(String) -> String) -> void + + def initialize: (Transport, ?Hash[untyped, untyped]? attributes) -> void + def new_record?: () -> bool + def persisted?: () -> bool + def destroyed?: () -> bool + def changes: () -> Hash[Symbol, Array[untyped]] + def changed?: () -> bool + def related: () -> Associations::Proxy + def assign_attributes: (Hash[untyped, untyped] attributes) -> self + def save: () -> bool + def save!: () -> true + def update: (Hash[untyped, untyped] attributes) -> bool + def update!: (Hash[untyped, untyped] attributes) -> true + def reload: () -> self + def destroy: () -> true + def inspect: () -> String + + private + + def initialize_copy: (self source) -> void + def setup: (Transport, Hash[untyped, untyped] attributes) -> void + def mark_persisted!: () -> void + def raise_if_destroyed!: (String action) -> void + def raise_if_new!: (String operation) -> void + def writable_attributes?: () -> bool + def attribute_writable?: (Symbol key) -> bool + def refuse_unwritable!: (Symbol key, untyped value) -> void + def replace_attributes!: (Response, operation: String, ?sent: Hash[Symbol, untyped]?) -> void + def acknowledge_changes!: (Hash[Symbol, untyped] sent) -> void + def reset_pending_state!: () -> void + def forget_related_targets: () -> void + def write_attribute: (Symbol, untyped) -> untyped + def unsaved_attributes: (Hash[Symbol, untyped] held) -> Hash[Symbol, untyped] + def create_record: (Hash[Symbol, untyped] body) -> Response + def update_record: (Hash[Symbol, untyped] body) -> Response + def member_path: () -> String + def require_id!: () -> Integer + def no_id_message: () -> String + end + end +end diff --git a/sig/zammad_api/resources/resources.rbs b/sig/zammad_api/resources/resources.rbs new file mode 100644 index 0000000..c4e5b10 --- /dev/null +++ b/sig/zammad_api/resources/resources.rbs @@ -0,0 +1,210 @@ +module ZammadAPI + # The attributes declared on each resource are the ones every Zammad the + # gem supports serves for it: the columns of its table, as they have been + # since Zammad 5, typed the way their JSON arrives - a timestamp is a + # String, and `preferences` is a Hash with Symbol keys. + # + # They are declarations only. A record answers them through + # method_missing, from whatever the response carried, so nothing here makes + # an attribute exist: these say what a typed caller may rely on. + # + # What is left out, on purpose: + # + # - Attributes an administrator added. Reach one with `record[:name]`, or + # declare it in your own signatures by reopening the class: + # + # class ZammadAPI::Resources::Ticket + # attr_accessor escalation_reason: String? + # end + # + # - Columns that newer Zammad versions added, which an older instance does + # not serve. + # + # - The name `expand` adds for an association that may be empty, such as + # `organization` on a ticket or a user. Zammad leaves the key out rather + # than sending null, so the reader would raise rather than answer nil. + # `record[:organization]` is nil in that case, and `organization_id` is + # always there. + module Resources + class Group < Base + attr_accessor name: String + attr_accessor signature_id: Integer? + attr_accessor email_address_id: Integer? + attr_accessor assignment_timeout: Integer? + attr_accessor follow_up_possible: String + attr_accessor follow_up_assignment: bool + attr_accessor active: bool + attr_accessor note: String? + end + + class Organization < Base + attr_accessor name: String + attr_accessor shared: bool + attr_accessor domain: String? + attr_accessor domain_assignment: bool + attr_accessor active: bool + attr_accessor note: String? + end + + class TicketPriority < Base + attr_accessor name: String + attr_accessor default_create: bool + attr_accessor ui_icon: String? + attr_accessor ui_color: String? + attr_accessor active: bool + attr_accessor note: String? + end + + class TicketState < Base + attr_accessor name: String + attr_accessor state_type_id: Integer + attr_accessor next_state_id: Integer? + attr_accessor ignore_escalation: bool + attr_accessor default_create: bool + attr_accessor default_follow_up: bool + attr_accessor active: bool + attr_accessor note: String? + end + + class User < Base + # Narrowed from Base so Client#me returns the concrete user type. + def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> User + + attr_accessor login: String + attr_accessor firstname: String? + attr_accessor lastname: String? + attr_accessor email: String? + attr_accessor organization_id: Integer? + attr_accessor image: String? + attr_accessor image_source: String? + attr_accessor web: String? + attr_accessor phone: String? + attr_accessor fax: String? + attr_accessor mobile: String? + attr_accessor department: String? + attr_accessor street: String? + attr_accessor zip: String? + attr_accessor city: String? + attr_accessor country: String? + attr_accessor address: String? + attr_accessor vip: bool + attr_accessor verified: bool + attr_accessor active: bool + attr_accessor note: String? + attr_accessor out_of_office: bool + attr_accessor out_of_office_start_at: String? + attr_accessor out_of_office_end_at: String? + attr_accessor out_of_office_replacement_id: Integer? + attr_accessor preferences: Hash[Symbol, untyped]? + + # Set by Zammad as the user signs in, so there is nothing to write. + attr_reader last_login: String? + attr_reader login_failed: Integer + attr_reader source: String? + + # Zammad takes a password and never serves one. + attr_writer password: String + end + + class Ticket < Base + attr_accessor title: String + attr_accessor group_id: Integer + attr_accessor state_id: Integer + attr_accessor priority_id: Integer + attr_accessor owner_id: Integer + attr_accessor customer_id: Integer + attr_accessor organization_id: Integer? + attr_accessor note: String? + attr_accessor pending_time: String? + attr_accessor type: String? + attr_accessor preferences: Hash[Symbol, untyped]? + + # The name `expand` puts beside each of the ids above that cannot be + # empty. Writing one is how a ticket is moved by name: + # `ticket.update(state: 'closed', group: 'Support')`. + attr_accessor group: String + attr_accessor state: String + attr_accessor priority: String + attr_accessor owner: String + attr_accessor customer: String + + # Kept by Zammad as the ticket moves, so there is nothing to write. + attr_reader number: String + attr_reader article_count: Integer? + attr_reader create_article_type_id: Integer? + attr_reader create_article_sender_id: Integer? + attr_reader first_response_at: String? + attr_reader first_response_escalation_at: String? + attr_reader first_response_in_min: Integer? + attr_reader first_response_diff_in_min: Integer? + attr_reader close_at: String? + attr_reader close_escalation_at: String? + attr_reader close_in_min: Integer? + attr_reader close_diff_in_min: Integer? + attr_reader update_escalation_at: String? + attr_reader update_in_min: Integer? + attr_reader update_diff_in_min: Integer? + attr_reader escalation_at: String? + attr_reader last_contact_at: String? + attr_reader last_contact_agent_at: String? + attr_reader last_contact_customer_at: String? + attr_reader last_owner_update_at: String? + + def articles: () -> Array[TicketArticle] + def add_article: (?Hash[untyped, untyped] attributes) -> TicketArticle + %a{deprecated: use add_article} def article: (Hash[untyped, untyped] attributes) -> TicketArticle + end + + class TicketArticle < Base + # Narrowed from Base so callers get the concrete article type. + def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> TicketArticle + + # private_constant in the source; RBS has no way to say so. + ATTACHMENTS_OPERATION: String + + attr_accessor ticket_id: Integer + attr_accessor type_id: Integer + attr_accessor sender_id: Integer + attr_accessor from: String? + attr_accessor to: String? + attr_accessor cc: String? + attr_accessor subject: String? + attr_accessor reply_to: String? + attr_accessor in_reply_to: String? + attr_accessor content_type: String + attr_accessor body: String + attr_accessor internal: bool + attr_accessor preferences: Hash[Symbol, untyped]? + + # The name `expand` puts beside type_id and sender_id, which is also + # how an article is given either: `add_article(type: 'note')`. + attr_accessor type: String + attr_accessor sender: String + + attr_reader message_id: String? + attr_reader message_id_md5: String? + attr_reader origin_by_id: Integer? + + def attachments: () -> Array[TicketArticleAttachment] + + private + + def attachment: (untyped raw) -> TicketArticleAttachment + end + + class TicketArticleAttachment + include AttributeAccess + + @transport: Transport + + # What Zammad lists for each attachment of an article. + attr_reader filename: String + attr_reader size: String + attr_reader preferences: Hash[Symbol, untyped] + + def initialize: (Transport, ?Hash[untyped, untyped]? attributes) -> void + def download: () -> String + def inspect: () -> String + end + end +end diff --git a/sig/zammad_api/response.rbs b/sig/zammad_api/response.rbs new file mode 100644 index 0000000..ee9f3a4 --- /dev/null +++ b/sig/zammad_api/response.rbs @@ -0,0 +1,26 @@ +module ZammadAPI + # Built with Data.define; the generated readers are declared explicitly. + class Response < ::Data + attr_reader status: Integer + attr_reader headers: Hash[String, String] + attr_reader body: untyped + attr_reader raw_body: String + attr_reader json: bool + + def self.new: (status: Integer, headers: Hash[String, String], body: untyped, raw_body: String, json: bool) -> instance + SUCCESS_STATUSES: Range[Integer] + # private_constant in the source; RBS has no way to say so. + TOTAL_COUNT_HEADER: String + + def self.decode_body: (String?, String) -> [untyped, bool] + + def success?: () -> bool + def json?: () -> bool + def decoded: (Symbol shape, operation: String, ?resource_class: Class?) -> untyped + def decoded_list: (operation: String, ?resource_class: Class?) -> [ Array[Hash[Symbol, untyped]], Integer? ] + + private + + def array_of_objects!: (Array[untyped], operation: String, resource_class: Class?) -> Array[untyped] + end +end diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs new file mode 100644 index 0000000..e478b6c --- /dev/null +++ b/sig/zammad_api/test.rbs @@ -0,0 +1,84 @@ +module ZammadAPI + class Test + # Both are deliberately outside ZammadAPI::Error: they say the test is + # wrong, not that Zammad refused anything, and the signature said + # otherwise - so a `rescue ZammadAPI::Error` type-checked as catching a + # forgotten stub that it does not in fact catch. + class UnstubbedRequestError < ::StandardError + end + + class AmbiguousStubError < ::StandardError + end + + class Request < ::Data + attr_reader verb: Symbol + attr_reader path: String + attr_reader query: Hash[String, untyped] + attr_reader body: untyped + attr_reader headers: Hash[String, String] + attr_reader on_behalf_of: String? + + def self.new: (**untyped) -> instance + end + + attr_reader config: Config + attr_reader client: Client + + @stubs: Hash[[Symbol, String], Array[Hash[Symbol, untyped]]] + @requests: Array[Request] + @served: Hash[[[Symbol, String], Hash[String, untyped]?], Hash[Symbol, untyped]] + @monitor: Thread::Mutex + @transport: Test::Transport + @client: Client + + def initialize: (**untyped options) -> void + def stub: (Symbol method, String path, ?status: Integer, ?body: untyped, ?headers: Hash[untyped, untyped], ?query: Hash[untyped, untyped]?) -> self + def requests: () -> Array[Request] + def reset: () -> self + def stubbed: () -> Array[String] + def inspect: () -> String + + def answer: ( + Symbol method, + String path, + operation: String, + ?query: Hash[untyped, untyped]?, + ?body: untyped, + ?headers: Hash[untyped, untyped]?, + ?resource_class: Class?, + ?on_behalf_of: String? + ) -> Response + + private + + def key: (Symbol method, String path) -> [Symbol, String] + def raw_body_for: (untyped body) -> String + def response_headers: (Hash[untyped, untyped] headers, untyped body) -> Hash[String, String] + def snapshot: (untyped) -> untyped + def take: (Symbol method, String path, Hash[String, untyped] params) -> Hash[Symbol, untyped]? + def later_page?: (Hash[String, untyped]? scope, Hash[String, untyped] params) -> bool + def most_specific: (Array[Hash[Symbol, untyped]] queued, Array[Integer] matching, Symbol method, String path) -> Array[Integer] + def ambiguous_message: (Symbol method, String path, Array[Hash[String, untyped]?] scopes) -> String + def matches?: (Hash[untyped, untyped]? expected, Hash[String, untyped] params) -> bool + def paged_body: (Hash[Symbol, untyped] stub, Hash[String, untyped] params, untyped body) -> untyped + def response_for: (Hash[Symbol, untyped] stub, Hash[String, untyped] params) -> Response + def build_response: (Hash[Symbol, untyped] stub, untyped body, String raw_body, json: bool) -> Response + def unstubbed_message: (Symbol method, String path, Hash[String, untyped] params) -> String + def unmatched_query_message: (String request, Hash[String, untyped] params, Array[Hash[String, untyped]?] scopes) -> String + + class Transport + include ::ZammadAPI::Transport::Verbs + + attr_reader test: Test + attr_reader on_behalf_of: String? + + def initialize: (Test test, ?on_behalf_of: (String | Integer)?) -> void + def config: () -> Config + def with_on_behalf_of: ((String | Integer)? identifier) -> Test::Transport + def with_config: (Config) -> Test::Transport + + + def request: (Symbol method, String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response + end + end +end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs new file mode 100644 index 0000000..ceb3d6c --- /dev/null +++ b/sig/zammad_api/transport.rbs @@ -0,0 +1,91 @@ +module ZammadAPI + # The Faraday connection and responses are untyped here rather than named: + # these signatures ship with the gem and the Faraday declarations they would + # need live in sig/vendor, which does not. See sig/zammad_api/config.rbs. + class Transport + # Included by Transport and by Test::Transport, which stands in for it. + module Verbs + def get: (String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response + def post: (String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response + def put: (String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response + def delete: (String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response + end + + include Verbs + + RETRIABLE_METHODS: Array[Symbol] + RETRIABLE_STATUSES: Array[Integer] + RETRIABLE_EXCEPTIONS: Array[untyped] + TIMEOUT_ERRORS: Array[untyped] + CONNECTION_ERRORS: Array[untyped] + # Untyped for the same reason as the Faraday ones above: naming + # OpenSSL::SSL::SSLError here would make the published signatures need + # openssl declarations that a consumer has not loaded. + SSL_ERRORS: Array[untyped] + # private_constant in the source; RBS has no way to say so. + REFUSED_MIDDLEWARE: Hash[String, [String, String]] + MISREAD_ELEMENTS: Hash[Symbol, String] + SENSITIVE_KEY_PATTERN: Regexp + REDACTED: String + UNRESERVED_IN_PATH: Regexp + DOT_SEGMENTS: Array[String] + ABSOLUTE_URL: Regexp + RESERVED_HEADERS: Hash[String, String] + + attr_reader config: Config + attr_reader on_behalf_of: String? + + @connection: untyped + + def self.redact_path: (untyped path) -> String + def self.redact_query_pair: (String pair) -> String + def self.stringify_query: (Hash[untyped, untyped]) -> Hash[String, untyped] + def self.stringify_query_hash: (Hash[untyped, untyped], String?) -> Hash[String, untyped] + def self.stringify_query_value: (String, untyped) -> untyped + def self.stringify_query_list: (String, Array[untyped]) -> Array[untyped] + def self.misread_element_message: (String, Symbol) -> String + def self.empty_query_name_message: (String? prefix) -> String + def self.stringify_headers: (Hash[untyped, untyped]) -> Hash[String, String] + BLANK: Regexp + def self.wire_text: (untyped value, String name) -> String + LINE_BREAK_ADVICE: String + def self.line_break?: (String text) -> bool + def self.stringify_on_behalf_of: ((String | Integer)? identifier) -> String? + def self.blank_on_behalf_of_message: (untyped identifier) -> String + def self.stringify_header_value: (String, untyped) -> String + def self.escape_path_segment: (untyped) -> String + def self.relative_path: (untyped) -> String + def self.refuse_unreadable_path!: (String relative) -> void + def self.unreadable_path_message: (String relative) -> String + def self.encode_body: (untyped body, operation: String, ?resource_class: Class?) -> String? + + def initialize: (Config) -> void + def with_on_behalf_of: ((String | Integer)? identifier) -> Transport + def with_config: (Config) -> Transport + def inspect: () -> String + + def request: (Symbol method, String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response + + private + + def timed_out?: (untyped error) -> bool + def perform: (Symbol, String, Hash[Symbol, untyped]?, untyped, String?, Hash[untyped, untyped]?) -> untyped + def build_connection: () -> untyped + def refuse_unusable_middleware!: (untyped connection) -> void + def refused_middleware: (Class klass) -> String? + def refused_middleware_message: (Class klass, String refused) -> String + def apply_authentication: (untyped) -> void + def retry_options: () -> Hash[Symbol, untyped] + def decode: (untyped) -> Response + def raw_body!: (untyped) -> String + def log_request: (Symbol, String, Hash[Symbol, untyped]?, untyped, Hash[String, String]?) -> void + def log_response: (Symbol, String, Response, Float) -> void + def redact: (untyped) -> untyped + def loggable_body: (untyped body) -> untyped + def unlogged_body: (String body) -> String + def reportable_cause: (StandardError error) -> StandardError? + def redact_config_values: (untyped message) -> String + def quoted_spellings: (String value) -> Array[String] + def logger: () -> Logger + end +end diff --git a/spec/typed/sig/usage.rbs b/spec/typed/sig/usage.rbs new file mode 100644 index 0000000..bae828d --- /dev/null +++ b/spec/typed/sig/usage.rbs @@ -0,0 +1,34 @@ +# The signatures a typed project writes for its own code. Not published with +# the gem: see spec/typed/usage.rb. +module TypedUsage + class Role < ZammadAPI::Resources::Base + attr_accessor name: String + end + + def self.title: (ZammadAPI::Client) -> String + def self.misspelled_reader: (ZammadAPI::Client) -> untyped + def self.logins: (ZammadAPI::Client) -> Array[String] + def self.block_parameter: (ZammadAPI::Client) -> untyped + def self.first_group: (ZammadAPI::Client) -> ZammadAPI::Resources::Group? + def self.first_tickets: (ZammadAPI::Client) -> Array[ZammadAPI::Resources::Ticket] + def self.found: (ZammadAPI::Client) -> ZammadAPI::Resources::Organization? + def self.newest_open: (ZammadAPI::Client) -> String? + def self.readers_of_group: (ZammadAPI::Client) -> Array[String] + def self.owners_of_group: (ZammadAPI::Client) -> Array[String] + def self.batches: (ZammadAPI::Client) -> Array[Integer] + def self.customer_email: (ZammadAPI::Client) -> String? + def self.article_bodies: (ZammadAPI::Client) -> Array[String] + def self.written: (ZammadAPI::Client) -> bool + def self.custom_attribute: (ZammadAPI::Client) -> [untyped, String?] + def self.role_names: (ZammadAPI::Client) -> Array[String] + def self.unsaved: (ZammadAPI::Client) -> String +end + +# An attribute an administrator added, declared by the project that uses it. +module ZammadAPI + module Resources + class Ticket + attr_accessor escalation_reason: String? + end + end +end diff --git a/spec/typed/usage.rb b/spec/typed/usage.rb new file mode 100644 index 0000000..c90fd91 --- /dev/null +++ b/spec/typed/usage.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +# Never run. `rake steep` checks this file against the signatures the gem +# publishes, the way a typed project that uses the gem is checked, so that the +# types a caller gets are pinned by something other than the signatures saying +# so. +# +# A line that ends in `steep:ignore` is one that has to be a type error. Steep +# reports an ignore comment that silences nothing, so each of them fails the +# check on the day its line stops being an error. That is how "a record is +# typed" is asserted here: against an untyped record a misspelled reader is no +# error at all, and the comment beside it would be the redundant one. +module TypedUsage + # A resource of the caller's own, reached through Client#resource. + class Role < ZammadAPI::Resources::Base + path 'api/v1/roles' + end + + def self.title(client) = client.tickets.find(1).title + + def self.misspelled_reader(client) + client.tickets.find(1).titel # steep:ignore NoMethod + end + + def self.logins(client) = client.users.map(&:login) + + def self.block_parameter(client) + client.users.each do |user| + user.loginn.upcase # steep:ignore NoMethod + end + end + + def self.first_group(client) = client.groups.first + + def self.first_tickets(client) = client.tickets.first(5) + + def self.found(client) = client.organizations.find_by(name: 'Zammad') + + def self.newest_open(client) + client.tickets.search('state.name:open').order(created_at: :desc).first&.number + end + + def self.readers_of_group(client) = client.users.search('smith', group_ids: { 2 => ['read'] }).map(&:login) + + def self.owners_of_group(client) = client.users.search('smith', group_ids: [2]).map(&:login) + + def self.batches(client) + sizes = [] #: Array[Integer] + client.tickets.in_batches(of: 50) { |tickets| sizes << tickets.sum { it.article_count || 0 } } + sizes + end + + def self.customer_email(client) = client.tickets.find(1).related.customer&.email + + def self.article_bodies(client) = client.tickets.find(1).articles.map(&:body) + + def self.written(client) + ticket = client.tickets.find(1) + ticket.title = 'Printer on fire' + ticket.title = 1 # steep:ignore ArgumentTypeMismatch + ticket.number = '1' # steep:ignore NoMethod + ticket.save + end + + # An attribute an administrator added is read by name, or declared by the + # project that knows about it - see usage.rbs. + def self.custom_attribute(client) + ticket = client.tickets.find(1) + [ticket[:anything_at_all], ticket.escalation_reason] + end + + def self.role_names(client) + roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role] + roles.map(&:name) + end + + def self.unsaved(client) = client.ticket_states.new(name: 'waiting').name +end From 374420b5fb357780e428f7d99faf741f7eb9ba30 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 18 Nov 2026 10:10:02 +0200 Subject: [PATCH 004/121] ci: drive a live Zammad end to end and publish by tag CI runs RuboCop, Steep and the unit specs on every supported stable Ruby, from the gemspec's floor to the current release: on pull requests, on pushes, and weekly, to catch what a new Ruby or a new Zammad breaks. A further job boots a Zammad and drives it with the gem. It waits for the instance to answer instead of sleeping, then runs script/check_connection.rb before the integration specs. The script stands alone - it does not load the spec suite - and walks the gem's surface against the instance: records, collections, sorting, search, tickets with their articles and attachments, acting on behalf of a user, and the error classes. A broken link between the gem and Zammad fails there, with a transcript that reads from top to bottom. A release is published by pushing a v* tag, through RubyGems trusted publishing, so no API key is stored in the repository. Before it publishes, the workflow refuses a tag that disagrees with ZammadAPI::VERSION or has no heading in the changelog, and runs the checks again. Dependabot groups its updates, so a week's bumps arrive as one pull request for the actions and one each for the runtime and the development gems. --- .github/dependabot.yml | 11 ++ .github/workflows/ci.yml | 174 ++++++++++++++--- .github/workflows/release.yml | 45 +++++ script/check_connection.rb | 339 ++++++++++++++++++++++++++++++++++ 4 files changed, 547 insertions(+), 22 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100755 script/check_connection.rb diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 710ebe8..84471df 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,7 +5,18 @@ updates: directory: "/" schedule: interval: "weekly" + groups: + actions: + patterns: ["*"] - package-ecosystem: "bundler" directory: "/" schedule: interval: "weekly" + groups: + # Lint and type tooling churns often and never affects the shipped gem. + development: + dependency-type: "development" + patterns: ["*"] + runtime: + dependency-type: "production" + patterns: ["*"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 144eff7..152ea0a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,57 +1,187 @@ name: CI + on: push: branches: [master] pull_request: schedule: - # Run every on Friday to ensure everything works as expected. - - cron: '0 6 * * 5' + # Weekly, to catch breakage from new Ruby or Zammad releases. + - cron: '0 6 * * 5' + workflow_dispatch: + inputs: + zammad_ref: + description: 'Zammad git ref to run the integration specs against' + default: 'develop' + type: string + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + jobs: lint: + name: RuboCop runs-on: ubuntu-latest - container: - image: zammad/zammad-ci:latest steps: - uses: actions/checkout@v7 - - name: Run lint actions - shell: bash - run: | - source /etc/profile.d/rvm.sh # ensure RVM is loaded - bundle update --bundler - bundle install -j $(nproc) - bundle exec rubocop - test: + - uses: ruby/setup-ruby@v1 + with: + ruby-version: '4.0' + bundler-cache: true + - run: bundle exec rubocop --format github + + types: + name: Steep + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: '4.0' + bundler-cache: true + - run: bundle exec steep check + # sig/vendor is always on the load path here but never in the gem, so + # the published set is checked on its own as well. + - run: bundle exec rake rbs_published + + unit: + name: Unit specs (Ruby ${{ matrix.ruby }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # Stable releases only, from required_ruby_version up to the current + # stable line. There is no 3.5: that line was abandoned after + # 3.5.0-preview1 and became 4.0. + # + # 'head' is absent. It could not install while the lockfile said + # `BUNDLED WITH 2.6.9`: bundler self-downgraded from head's 4.1.0.dev + # and died with NameError on the removed Pathname::SEPARATOR_PAT, and + # without the lockfile a fresh resolution pulled steep -> listen -> + # rb-inotify -> ffi, whose native gems require Ruby < 4.1.dev. The + # lockfile now names Bundler 4.0.20, which does not use that constant, + # so the first of those may be gone; head has not been retried since. + ruby: ['3.4', '4.0'] + env: + # The unit specs do not need the type-checking toolchain, and skipping it + # keeps this job fast. The `types` job installs it separately. + BUNDLE_WITHOUT: development + steps: + - uses: actions/checkout@v7 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Run unit specs + run: bundle exec rake spec:unit + env: + COVERAGE: 'true' + + integration: + name: Integration specs (live Zammad) runs-on: ubuntu-latest + # Booting Zammad costs far more runner time than the unit suite, so there + # is no point paying for it when the unit specs are already failing. + needs: unit + # A full Zammad boot takes many minutes; without a cap a hung boot would + # occupy a runner until the six hour default expires. + timeout-minutes: 45 container: image: zammad/zammad-ci:latest services: postgresql: - image: postgres:17 + image: postgres:18 env: POSTGRES_USER: zammad POSTGRES_PASSWORD: zammad redis: image: redis:7 + env: + ZAMMAD_REF: ${{ inputs.zammad_ref || 'develop' }} + TEST_USER: admin@example.com + TEST_PASSWORD: test steps: - uses: actions/checkout@v7 - - name: Set up Zammad + + - name: Report the toolchain shell: bash run: | - git clone --depth 1 https://github.com/zammad/zammad.git + source /etc/profile.d/rvm.sh + # The gem requires Ruby >= 3.4; fail here with a clear message rather + # than inside a confusing bundler resolution error. + ruby -v + ruby -e 'abort "zammad-ci image ships Ruby #{RUBY_VERSION}, this gem needs >= 3.4" if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("3.4")' + + - name: Boot Zammad + shell: bash + run: | + # No `set -u`: /etc/profile.d/rvm.sh reads unset variables and aborts + # under nounset. + set -eo pipefail + git clone --depth 1 --branch "$ZAMMAD_REF" https://github.com/zammad/zammad.git cd zammad - source /etc/profile.d/rvm.sh # ensure RVM is loaded + source /etc/profile.d/rvm.sh bundle config set --local frozen 'true' bundle config set --local path 'vendor' - bundle install -j $(nproc) + bundle install -j "$(nproc)" bundle exec ruby .gitlab/configure_environment.rb + # Each workflow step runs in its own shell, so Zammad's generated + # environment has to be promoted to the job environment to survive. + sed -E 's/^export +//' .gitlab/environment.env \ + | grep -E '^[A-Za-z_][A-Za-z0-9_]*=' >> "$GITHUB_ENV" source .gitlab/environment.env RAILS_ENV=test bundle exec rake db:create cp contrib/auto_wizard_test.json auto_wizard.json bundle exec rake zammad:ci:test:start - - name: Run Ruby API integration tests + echo "TEST_URL=http://localhost:${RAILS_PORT:-3000}/" >> "$GITHUB_ENV" + + - name: Wait for Zammad to answer + shell: bash + run: | + probe="${TEST_URL%/}/api/v1/getting_started" + for attempt in $(seq 1 60); do + if curl -sSf --max-time 5 "$probe" >/dev/null 2>&1; then + echo "Zammad answered at $TEST_URL after ${attempt} attempt(s)" + exit 0 + fi + sleep 5 + done + echo "::error::Zammad never answered at $probe" + exit 1 + + - name: Install the gem's dependencies + shell: bash + run: | + source /etc/profile.d/rvm.sh + bundle install -j "$(nproc)" + + - name: Drive Zammad with this gem + shell: bash + run: | + source /etc/profile.d/rvm.sh + bundle exec ruby script/check_connection.rb + + - name: Run the integration specs + shell: bash + run: | + source /etc/profile.d/rvm.sh + bundle exec rake spec:integration + + - name: Collect Zammad logs on failure + if: failure() shell: bash run: | - source /etc/profile.d/rvm.sh # ensure RVM is loaded - bundle update --bundler - bundle install -j $(nproc) - bundle exec rspec + echo '--- zammad/log ---' + tail -n 200 zammad/log/*.log 2>/dev/null || echo 'no logs found' + + - name: Upload Zammad logs + if: failure() + uses: actions/upload-artifact@v7 + with: + name: zammad-logs + path: zammad/log/ + if-no-files-found: ignore + retention-days: 7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..63c96a2 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,45 @@ +name: Release + +# Publishes to RubyGems via trusted publishing (OIDC), so no API key is +# stored in this repository. Configure the trusted publisher once at +# https://rubygems.org/gems/zammad_api/trusted_publishers +on: + push: + tags: ['v*'] + +permissions: + contents: read + +jobs: + release: + name: Build and publish + runs-on: ubuntu-latest + environment: rubygems + permissions: + contents: write # create the GitHub release and push the tag commit + id-token: write # request the OIDC token for trusted publishing + steps: + - uses: actions/checkout@v7 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: '4.0' + bundler-cache: true + # The tag is what triggers this workflow, and nothing downstream reads + # it: the gem is built from the gemspec, so a tag that disagrees with + # ZammadAPI::VERSION publishes a gem under a version nobody tagged and + # leaves a GitHub release pointing at one that does not exist. + - name: Check the tag against the gem version and the changelog + run: | + tagged="${GITHUB_REF_NAME#v}" + declared="$(ruby -Ilib -rzammad_api/version -e 'print ZammadAPI::VERSION')" + if [ "$tagged" != "$declared" ]; then + echo "::error::tag ${GITHUB_REF_NAME} does not match ZammadAPI::VERSION ($declared)" + exit 1 + fi + if ! grep -q "^## \[${declared}\]" CHANGELOG.md; then + echo "::error::CHANGELOG.md has no '## [${declared}]' heading" + exit 1 + fi + - name: Verify the release candidate + run: bundle exec rake spec:unit rubocop steep rbs_published + - uses: rubygems/release-gem@v1 diff --git a/script/check_connection.rb b/script/check_connection.rb new file mode 100755 index 0000000..aef9884 --- /dev/null +++ b/script/check_connection.rb @@ -0,0 +1,339 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# End-to-end check that this gem can actually drive a live Zammad instance. +# +# Deliberately standalone: it does not load the spec suite, so it still +# reports usefully when the specs themselves are what is broken. CI runs it +# after booting Zammad and before the integration specs, so a broken +# gem-to-Zammad link fails fast with a readable transcript. +# +# TEST_URL=https://zammad.example/ \ +# TEST_USER=admin@example.com \ +# TEST_PASSWORD=test \ +# bundle exec ruby script/check_connection.rb + +$LOAD_PATH.unshift File.expand_path('../lib', __dir__) + +require 'zammad_api' +require 'faraday' +require 'json' +require 'securerandom' +require_relative 'live_target' + +# No default for the URL. This script creates and deletes records, and +# `http://localhost:3000/` is where a Zammad under development listens. +URL = LiveTarget.url || abort(LiveTarget.unset_message('This script')) + +LOGIN = ENV['TEST_USER'] || 'admin@example.com' +PASSWORD = ENV['TEST_PASSWORD'] || 'test' +SUFFIX = SecureRandom.hex(4) + +@failures = [] +@group = nil +@ticket = nil + +# Runs one named check, printing its result and recording any failure. +def check(name) + detail = yield + puts format(' ok %-42s %s', name: name, detail: detail) + true +rescue => e + @failures << name + puts format(' FAIL %-42s %s: %s', name: name, error: e.class, message: e.message) + false +end + +# A check whose failure makes every later check meaningless, so the run stops +# rather than burying the cause under cascading NoMethodErrors. +def check!(name, &block) + return if check(name, &block) + + puts "\nAborting: '#{name}' is a precondition for the remaining checks." + finish +end + +def section(title) + puts "\n#{title}" +end + +def parse_json(body) + JSON.parse(body) +rescue JSON::ParserError + {} +end + +def cleanup + return if @group.nil? && @ticket.nil? + + section 'Cleanup' + check('destroy the ticket') { CLIENT.tickets.destroy(@ticket.id) } if @ticket + check('destroy the group') { CLIENT.groups.destroy(@group.id) } if @group +end + +def finish + cleanup + puts + if @failures.empty? + puts 'All checks passed.' + exit 0 + end + + puts "#{@failures.size} check(s) failed:" + @failures.each { puts " - #{it}" } + exit 1 +end + +puts "Checking #{URL} with zammad_api #{ZammadAPI::VERSION} on Ruby #{RUBY_VERSION}" + +section 'Instance setup' + +# The auto wizard creates the admin account. An instance that is already +# configured reports failure here, which is fine as long as it is set up. +check!('auto wizard or already configured') do + wizard = parse_json(Faraday.new(url: URL).get('api/v1/getting_started/auto_wizard').body) + next 'auto wizard ran' if wizard['auto_wizard_success'] + + # A configured Zammad requires authentication even for + # /api/v1/getting_started, so the setup state cannot be read from there. + # An authenticated request answers the only question that matters. + ZammadAPI::Client.new(url: URL, user: LOGIN, password: PASSWORD, retries: 0) + .groups.all.page(1, per_page: 1).to_a + 'already set up' +end + +CLIENT = ZammadAPI::Client.new(url: URL, user: LOGIN, password: PASSWORD, timeout: 30) + +section 'Client' + +check('credentials are redacted') do + raise 'password leaked into inspect output' if CLIENT.config.inspect.include?(PASSWORD) + + 'password absent from inspect output' +end + +check('derived client re-validates options') do + CLIENT.with(timeout: 45) + CLIENT.with(timeout: -1) + raise 'expected ConfigurationError' +rescue ZammadAPI::ConfigurationError + 'invalid option rejected' +end + +section 'Records' + +check!('create a group') do + @group = CLIENT.groups.create(name: "smoke-#{SUFFIX}", note: 'created by check_connection.rb') + raise 'no id assigned' if @group.id.nil? + + "id=#{@group.id}" +end + +check('find it back') do + found = CLIENT.groups.find(@group.id) + raise "name mismatch: #{found.name}" if found.name != "smoke-#{SUFFIX}" + + found.name +end + +check('update only the changed attribute') do + @group.note = 'updated' + raise 'change not staged' if !@group.changed? + + @group.save + CLIENT.groups.find(@group.id).note +end + +check('reload discards local changes') do + @group.note = 'not saved' + @group.reload.note +end + +check('pattern match a record') do + case CLIENT.groups.find(@group.id) + in { name: String => name, active: true } then name + else raise 'record did not match the expected pattern' + end +end + +section 'Collections' + +check('iterate every group across pages') do + names = CLIENT.groups.all.map(&:name) + raise 'created group missing from .all' if !names.include?("smoke-#{SUFFIX}") + + "#{names.size} groups" +end + +check('fetch a single page') { "#{CLIENT.groups.all.page(1, per_page: 1).to_a.size} record" } + +check('lazy enumeration stops early') { CLIENT.groups.all.lazy.map(&:id).first(1).inspect } + +check('page by page') do + pages = 0 + CLIENT.groups.all.in_batches(of: 1) { pages += 1 } + "#{pages} page(s)" +end + +check('search') { "#{CLIENT.users.search(LOGIN).to_a.size} hits" } + +# These were never driven against a live Zammad, which is why nobody noticed +# that an attribute filter passed to an index endpoint never reached the query +# at all. +check('find_by returns a record that matches') do + found = CLIENT.groups.find_by(name: "smoke-#{SUFFIX}") + raise 'no record found' if found.nil? + raise "found the wrong record: #{found.name}" if found.name != "smoke-#{SUFFIX}" + + "id=#{found.id}" +end + +# Two string attributes, because one is the shape that works whatever the +# search term looks like. Joined into a single term - which is what this used +# to send - the query asks every string column to contain the whole of it, and +# on an instance searching through SQL LIKE rather than Elasticsearch no +# column does, so a record that exists comes back as nil. A stubbed unit spec +# cannot see that; it answers whatever term it is handed. +check('find_by matches on two string attributes') do + group = CLIENT.groups.find(@group.id) + found = CLIENT.groups.find_by(name: group.name, note: group.note) + raise 'no record found' if found.nil? + raise "found the wrong record: #{found.name}" if found.id != group.id + + "id=#{found.id}" +end + +check('find_by returns nil for no match') do + found = CLIENT.groups.find_by(name: "no-such-group-#{SUFFIX}") + raise "expected nil, got #{found.inspect}" if !found.nil? + + 'nil' +end + +check('find_by! raises for no match') do + CLIENT.groups.find_by!(name: "no-such-group-#{SUFFIX}") + raise 'expected NotFoundError' +rescue ZammadAPI::NotFoundError + 'raised' +end + +check('exists?') do + raise 'the created group is missing' if !CLIENT.groups.exists?(@group.id) + raise 'a made-up id exists' if CLIENT.groups.exists?(0) + + 'true and false' +end + +check('pluck') do + names = CLIENT.groups.all.pluck(:name) + raise 'created group missing' if !names.include?("smoke-#{SUFFIX}") + + "#{names.size} names" +end + +check('empty? on a search with no hits') do + raise 'expected empty' if !CLIENT.groups.search("no-such-group-#{SUFFIX}").empty? + + 'true' +end + +check('order sorts an index endpoint that sorts') do + "#{CLIENT.groups.order(name: :desc).page(1, per_page: 2).to_a.size} record(s)" +end + +check('order refuses an index served in a fixed order') do + CLIENT.tickets.order(:title).to_a + raise 'expected ArgumentError' +rescue ArgumentError => e + e.message.split('.').first +end + +check('order sorts a search') do + "#{CLIENT.groups.search("smoke-#{SUFFIX}").order(:name, id: :desc).to_a.size} hit(s)" +end + +check('search refuses a keyword the endpoint would drop') do + CLIENT.groups.search('smoke', name: "smoke-#{SUFFIX}").to_a + raise 'expected ArgumentError' +rescue ArgumentError => e + e.message.split(':').first +end + +section 'Tickets' + +check!('create a ticket with its first article') do + @ticket = CLIENT.tickets.create( + title: "smoke ticket #{SUFFIX}", + group: 'Users', + customer: LOGIN, + article: { subject: 'smoke', body: 'created by check_connection.rb', type: 'note' } + ) + "number=#{@ticket.number}" +end + +check('read its articles') { "#{@ticket.articles.size} article(s)" } + +check('add another article') do + CLIENT.tickets.find(@ticket.id).add_article(subject: 'second', body: 'another one', type: 'note').id +end + +check('article count grew') do + count = @ticket.articles.size + raise "expected 2 articles, got #{count}" if count != 2 + + count +end + +check('attachment metadata and download') do + CLIENT.tickets.find(@ticket.id).add_article( + subject: 'with attachment', + body: 'see attachment', + type: 'note', + attachments: [{ filename: 'smoke.txt', data: ['smoke test 123'].pack('m0'), 'mime-type': 'text/plain' }] + ) + attachment = @ticket.articles.last.attachments.first + raise 'no attachment returned' if attachment.nil? + + # Once: each call is a full attachment fetch, and this transcript is meant to + # be a fast read of a freshly booted Zammad. + contents = attachment.download + raise "unexpected content: #{contents.inspect}" if contents != 'smoke test 123' + + "#{attachment.filename} (#{contents.bytesize} bytes)" +end + +section 'On behalf of another user' + +check('sends the From header') do + CLIENT.on_behalf_of(LOGIN) { |scoped| scoped.tickets.find(@ticket.id).number } +end + +check('block form leaves the outer client unscoped') do + CLIENT.on_behalf_of(LOGIN) { |scoped| scoped.groups.find(@group.id) } + CLIENT.groups.find(@group.id).name +end + +section 'Errors' + +check('missing record raises NotFoundError') do + CLIENT.groups.find(0) + raise 'expected NotFoundError' +rescue ZammadAPI::NotFoundError => e + "status=#{e.status}" +end + +check('invalid attributes raise a ClientError') do + CLIENT.groups.create({}) + raise 'expected a ClientError' +rescue ZammadAPI::ClientError => e + "status=#{e.status}" +end + +check('bad credentials raise AuthenticationError') do + ZammadAPI::Client.new(url: URL, user: 'nobody', password: 'wrong', retries: 0).groups.find(1) + raise 'expected AuthenticationError' +rescue ZammadAPI::AuthenticationError => e + "status=#{e.status}" +end + +finish From 8f7562db41df08f9e0165b7de8a0150df0e2fb25 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 18 Nov 2026 10:10:13 +0200 Subject: [PATCH 005/121] docs: document 2.0 and the way up from 1.x The README is rewritten around the 2.0 API: creating a client, the resources, records, collections, errors, timeouts and retries, logging, the test kit and the type signatures. A coverage table sets what 1.x and 2.0 model against what Zammad's API serves, and the text around it says how to reach the rest: a resource class of the caller's own, or a raw request. "Migrating from 1.x" lists every call that changed. It starts with the changes that do not announce themselves, where 1.x code keeps running and does something different. The changelog entry for 2.0.0.alpha1 carries the same changes as a list. "Staying on 1.x" is for those who do not move yet: the 1.x code lives on the 1-stable branch, it installs with a version constraint below 2, and it stays in maintenance mode, with fixes and no new features. examples/ holds nine runnable scripts, each built on Client.from_env: a quickstart, the ways to read a collection, pagination driven by hand, a CSV export, triage with pattern matching, onboarding a customer on behalf of a user, attachment downloads, error handling, and a worker pool sharing one client. The single 1.x example went with the rewrite. --- CHANGELOG.md | 837 ++++++++++++++++ README.md | 1596 +++++++++++++++++++++++++----- examples/README.md | 38 + examples/concurrent_sync.rb | 57 ++ examples/download_attachments.rb | 45 + examples/error_handling.rb | 77 ++ examples/manual_batches.rb | 142 +++ examples/onboard_customer.rb | 85 ++ examples/pagination.rb | 71 ++ examples/quickstart.rb | 53 + examples/ticket_report.rb | 54 + examples/triage_tickets.rb | 58 ++ 12 files changed, 2863 insertions(+), 250 deletions(-) create mode 100644 examples/README.md create mode 100755 examples/concurrent_sync.rb create mode 100755 examples/download_attachments.rb create mode 100755 examples/error_handling.rb create mode 100755 examples/manual_batches.rb create mode 100755 examples/onboard_customer.rb create mode 100755 examples/pagination.rb create mode 100755 examples/quickstart.rb create mode 100755 examples/ticket_report.rb create mode 100755 examples/triage_tickets.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 422138f..c5d867e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,840 @@ +# Changelog + +## [2.0.0.alpha1] - 2026-11-17 + +The first prerelease of 2.0, a breaking release that modernises the whole gem. See +[Migrating from 1.x](README.md#migrating-from-1x) for the complete before/after guide. + +Everything below is what changed since 1.4.0. It is published as an alpha so that it can +still change: names, defaults and behaviour may differ in 2.0.0. A prerelease has to be +asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.alpha'`. + +### Breaking + +- Minimum Ruby version is now 3.4. 3.0 through 3.2 are end-of-life, and 3.3 is in security + maintenance until March 2027. The library needs nothing from 3.4 but the `it` block + parameter, so the floor is a choice rather than a dependency. +- `Client.new` takes keyword arguments, so a configuration Hash has to be splatted: + `Client.new(**config)`. A positional Hash raises `ArgumentError`. +- An unknown client option raises `ArgumentError: unknown keyword` instead of being + ignored, so an option that is misspelled or no longer supported is no longer silent. +- `logger:` takes a `Logger` rather than a boolean flag. `logger: true` used to turn on + debug output to `$stderr`; pass `Logger.new($stderr)` for the same thing. Any object + that responds to `debug` is accepted, and anything else raises `ConfigurationError`. +- `Collection#each` (`client.x.all`, `client.x.search`) now walks every page. Previously it + fetched a single page, so iterating stopped silently at 100 records for `all` and at + 10 for `search`. +- Collections are built up by chaining instead of by keyword arguments: + `all(per_page: 50)` is now `find_each(batch_size: 50)` or `page(1, per_page: 50)`, + `all(active: true)` is `search(...)` or `all.detect { ... }`, + `search(query: 'zammad')` is `search('zammad')`, + and `search(query: 'z', page: 2, per_page: 50)` is `search('z').page(2, per_page: 50)`. + `all` accepted those keywords and then discarded them, so its page size was always + 100 and its filters never reached the request; `search` did honour `page` and + `per_page`. All of them now raise `ArgumentError` rather than being accepted. +- `page(number, per_page)` with a block was replaced by `page(number, per_page: size)`, which + returns a new collection. `page_next` and `page_prev` were removed. +- `Collection#each_page` was renamed to `#in_batches`, which also takes the page size as + `in_batches(of: 500)`. +- `Collection#[]` was removed. It cost a request per index and ignored the page a + collection was limited to; use `first`, or `page(n, per_page: 1).first` for one record at an + offset. +- `Collection#per_page` and `#current_page` are no longer public. `inspect` reports both. +- There is no `per`. The page size belongs to the call that reads: `find_each(batch_size:)` + to walk, `in_batches(of:)` to batch, `page(number, per_page:)` for one page. Everything else + fetches as many records as the endpoint serves. +- A collection fetches the endpoint's own page size rather than a fixed 100 — 1000 on the + index endpoints, 100 on `/api/v1/tickets`, 200 on a search — so a walk spends roughly a + tenth of the round trips, each of which is a fresh TLS handshake under Faraday's default + adapter. `page(n)` without `per_page:` is a page of that size, so pin it with + `page(n, per_page: 100)` where a persisted page number has to keep meaning what it did. +- A `nil` query value raises `ArgumentError`. 1.x dropped the parameter, so a filter that + happened to be `nil` requested every record and the caller iterated all of them + believing they had been narrowed. +- `client.on_behalf_of = 'login'` and `client.perform_on_behalf_of` were replaced by + `client.on_behalf_of('login')`, which returns a new client and also accepts a block. +- `ZammadAPI::ResourceNotFoundError` is now `ZammadAPI::UnknownResourceError`, freeing the + 404 case to be `ZammadAPI::NotFoundError`. +- `record.save` reports a validation failure as `false` and leaves the error in + `record.error`, instead of raising. `record.save!` is the raising form. Every other + failure — an expired token, a missing record, an unreachable instance — still raises from + both, because no attribute the caller can fix would change the outcome. + `client..create` uses `save!`, so it keeps raising rather than returning a + record that looks created but is not. +- A resource's class-level memos — the association proxy class and the `belongs_to` + foreign keys — are built under a lock. They were plain `@x ||=`, so two threads building + clients or reading associations at once could each build a different anonymous proxy + class for one resource, and whichever write lost was still held by the records already + built from it. Harmless under CRuby's GVL, wrong on JRuby and TruffleRuby, which is not + the contract `README` writes down. +- `record[:x] = 1` stages the attribute it names. It reached the writer dispatch as `[]=` + and was taken for an attribute literally called `[]` whose value was the index, so the + write was lost without an error and the next `save` sent `{"[]": "x"}` to Zammad. Ruby's + operators end in `=` too, so `record <= 5` invented an attribute called `<` the same way; + a writer is now recognised only by a plain attribute name. +- `record.destroy` and `record.reload` refuse a record that was never saved, instead of + acting on an id it was merely built with. `client.groups.new(id: 99).destroy` reported + `new_record?` true and `persisted?` false and still sent `DELETE /api/v1/groups/99`. +- `record.id = ...` raises. The id is what addresses the record, so a staged one took + effect for every path that builds a URL from the attributes and not at all for the record + those paths then reported on: `group.id = 99; group.destroy` sent `DELETE` to group 99 + and left the record saying group 1 was the one destroyed. Zammad does not let an id be + set either, so no call that used to reach the server is lost. The constructor refuses it + too: `client.groups.new(id: 5)` raises, because a new record is sent in full, so the one + spelling that reached the wire was the one nothing checked. `Resource.from_response` is + how a body Zammad served becomes a record carrying its id. +- `record.destroy` marks the record `destroyed?`, and `persisted?` answers false for one. + 1.x left a destroyed record looking live, so a later `save` went out as a `PUT` to the + deleted id and came back a 404 one call after the mistake. +- `record.attributes` and `record.changes` are deeply frozen, and `record.to_h` returns a + deep copy rather than a shallow one. Writing through either reader used to change what a + record reported without staging anything, so the next `save` did not send it, and a + nested hash from `to_h` was shared with the record. +- The `record.attributes=` writer was removed. An unknown name is an ordinary attribute + now, so `record.attributes = {name: 'Support'}` stages a change called `attributes` + that `save` sends to Zammad. Use `assign_attributes` or `update`. +- `ZammadAPI::Error` descends from `StandardError` instead of `RuntimeError`. +- `ResponseError#response` returns a `ZammadAPI::Response`, not a Faraday object, and + `#body` is the decoded payload rather than a raw JSON string. +- No Faraday exception escapes any more: an unreachable host or a timeout raises + `ZammadAPI::ConnectionError` or `ZammadAPI::TimeoutError`, so a + `rescue Faraday::ConnectionFailed` stops matching. +- `ZammadAPI::ListBase`, `ListAll` and `ListSearch` were replaced by `ZammadAPI::Collection`. +- `ZammadAPI::Log` and `ZammadAPI::JsonHelper` were removed. Pass any `Logger` via `logger:`. +- `ZammadAPI::Dispatcher` was replaced by `ZammadAPI::ResourceProxy`. +- The resource readers on a client are plural: `client.tickets`, `client.users`, + `client.groups`, `client.organizations`, `client.ticket_articles`, + `client.ticket_priorities` and `client.ticket_states`. A resource is `Enumerable` over + every record of its kind, so `client.ticket.each` and `client.ticket.first(5)` read as if + they acted on one ticket; the singular dates from 1.x, when a resource was only a + dispatcher for `find` and `create`. The singular names still work, as deprecated aliases + that warn in Ruby's `deprecated` category — silent unless the application asks for + deprecation warnings, with `ruby -W:deprecated` or `Warning[:deprecated] = true` — and + will be removed in 3.0. `client.resource(:ticket)` is answered the same way, and + `client.resource_names` lists the plural names. +- The resource readers a client has are a fixed list. 1.x resolved `client.` to + `ZammadAPI::Resources::` through `const_get`, so a subclass of `Base` defined in + application code could be reached that way. `client.role` now raises + `UnknownResourceError`; hand the class over instead, with `client.resource(Role)`. +- The internal `new_instance` accessor was replaced by `new_record?` and `persisted?`, and + the instance-level `url` accessor by the class-level `resource_path`. Both old names now + raise `NoMethodError` as unknown attributes, naming the attributes the record does carry. +- A reader for an attribute the record does not carry raises `NoMethodError` instead of + answering `nil`. A typo read as `nil` and flowed on into whatever was written with it, + and `respond_to?` and `method` disagreed with the call throughout, so generic code that + asks before it calls was told the reader did not exist. `record[:x]`, + `record.fetch(:x, nil)` and `record.key?(:x)` are the readers for an attribute that may + legitimately be absent — which it may, because Zammad serves a reduced object where the + authenticated user may not see the whole record, and the message says so. +- `Collection#find` raises `ArgumentError` when given an id. `find` on a resource proxy is + the lookup by id; on a collection it is `Enumerable#find`, whose argument is an ifnone + callable — so `client.tickets.all.find(1)` answered with an `Enumerator`, made no request + and raised nothing. Use `client.tickets.find(1)`, or `detect { … }` for the block form. +- `TicketArticle#attachments` raises `ParseError` for attachment metadata that is not a + list of objects, where it used to die with a bare `NoMethodError` from inside the gem — + past the `rescue ZammadAPI::Error` every caller is told to write. +- `page(number, per_page: size)` raises `ArgumentError` when `size` is larger than the endpoint + serves, instead of quietly reducing it. A reduced page size moves the page: + `page(3, per_page: 500)` against `/api/v1/tickets` went out as `page=3&per_page=100` and + answered with records 201–300 rather than 1001–1500, so a job checkpointing a page + number re-read what it had already handled. `find_each(batch_size:)` and + `in_batches(of:)` are still reduced, because a batch size names how much to fetch per + request, not which records the call is about. +- `find_by` searches one string value — the longest. Zammad matches words, so + `find_by(active: true)` searched for `"true"` and found nothing. Every other value is + compared against the record, so `find_by(email: '…', active: true)` searches the email + and compares both, and a lookup with no string in it walks the index instead. The values are + never joined into a single term: an instance searching without Elasticsearch matches the + term literally, through a SQL `LIKE` over each string column, so + `find_by(firstname: 'Jane', lastname: 'Doe')` asked for one column containing + `"Jane Doe"` and reported a user that exists as `nil`. +- `search` raises `ZammadAPI::Error` on a resource Zammad routes no search endpoint for — + `ticket_states`, `ticket_priorities` and `ticket_articles`. Those endpoints answered 404, + which arrived as a `NotFoundError` about a record from a call that asked for a list, and + reached `find_by` the same way, so `find_by(…) || create(…)` raised instead of creating. + `find_by` walks those lists instead of searching them. +- Nothing reads an `x-total-count` response header any more, because Zammad has never sent + one — from any endpoint, in any version. `Response#reported_total` was built on it, and + two guards read that: `Collection#each` would have ended a walk one request early on the + reported figure, and a `has_many` reader would have refused a list it judged truncated. + Both were dead, and the one that could have acted was the one that could have been + wrong, since it ends a walk on a figure the records do not corroborate. Zammad reports a + total in the body instead, and only where asked: `only_total_count` — which is what + `Collection#count` uses on a search — or `with_total_count` on `/search`, and `full` on + the index endpoints that render through `model_index_render`. +- A record id of `.` or `..` raises `ArgumentError`. Both are made entirely of unreserved + characters, so escaping carried them through and `find('..')` resolved one path level + up — onto the index endpoint, or through a `has_many` path onto every article on the + instance offered as one ticket's. +- A configuration that names more than one way to authenticate raises `ConfigurationError`. + `http_token`, `oauth2_token` and `user` with `password` used to be accepted together, and + the first of them in that order was sent without a word about the others — which is what + let `from_env(user:, password:)` and `with(oauth2_token:)` keep sending an old token. A + client authenticates one way by construction now. `from_env` and `with` drop the + credentials an override replaces, so switching schemes through either still works, and an + environment that itself sets two schemes is refused until an argument says which is meant. +- `ticket.article(…)` is `ticket.add_article(…)`. A noun that sends a `POST` sat one letter + away from `ticket.articles`, which only reads. `article` still works, as a deprecated + alias that warns in Ruby's `deprecated` category the way the singular resource readers do, + and will be removed in 3.0. It requires its attributes, as it did in 1.x, so a bare + `ticket.article` raises `ArgumentError` rather than sending an article with no body. + +### Added + +- `Collection#first` and `#take` size their own request: `all.first` is one request for one + record and `all.first(5)` one request for five, where `Enumerable` took them off the + front of a page sized for walking. The request is sized rather than the collection + limited to a page, so a read still walks on where a page comes back shorter than it was + asked for — `first(5)` answers with five records if five exist. A collection `page` + already limited keeps its own size, because that size says which records it holds. +- `client.get`, `#post`, `#put` and `#delete` take `headers:`, for an endpoint that needs + one. Names are case-insensitive and two spellings of one header are refused rather than + merged; `Authorization` and `From` are refused outright, being what the client's + credentials and `on_behalf_of` are for. +- `Test::Request#headers` records the headers a request asked for, stringified and + downcased through the real transport's own rules, so a stand-in cannot accept a header + the wire would refuse. +- `client.get`, `client.post`, `client.put` and `client.delete` reach any endpoint of the + Zammad API, including the many this gem does not model. They return a + `ZammadAPI::Response` and keep authentication, timeouts, retries, credential redaction, + JSON decoding and the error classes. Previously the only way past the seven resource + classes was to build a Faraday connection by hand. +- Request and connection timeouts (`timeout`, `open_timeout`), on by default at 60 and + 10 seconds. 1.x waited as long as the server took, so a call that used to hang now + raises `TimeoutError`. +- Automatic retry with exponential backoff for a `GET` on connection failures, timeouts + and transient statuses. A write is never retried. `POST` would create a second record, + and `PUT` and `DELETE` are not safe to repeat against Zammad either: a ticket update + carrying an `article` adds that article, and sends its e-mail, once per delivery, and a + `DELETE` repeated after a lost answer comes back as a 404 for a record that was just + deleted, so `destroy` raised `NotFoundError` and left the record looking live. +- A specific error class per status: `AuthenticationError` (401), `AuthorizationError` + (403), `NotFoundError` (404), `ValidationError` (422) and `RateLimitError` (429, with + `#retry_after`). Network failures raise `ConnectionError` or `TimeoutError` instead of + leaking Faraday exceptions. +- `Collection#order`, `#page`, `#in_batches`, `#find_each`, `#count` and lazy + enumeration, plus `client.x.order(...)` as a shorthand for `all.order(...)`. +- `order` sorts on the server: `order(:name)`, `order(name: :desc)`, + `order(:active, name: :desc)`, read the way ActiveRecord reads them, and a second + `order` sorts within the first. Sorting is the one thing an index endpoint does besides + paging. `/api/v1/tickets` and `/api/v1/users` do not even do that — their controllers + hardcode id order — so `order` on those raises `ArgumentError` rather than handing back + records it would be calling sorted; a search sorts for every resource that can be + searched. +- `search` takes what a search endpoint narrows by besides the term as keywords: + `condition:` and `ids:` on every search, and `role_ids:`, `group_ids:` and `permissions:` + on users, the one search that reads them. Any other keyword raises `ArgumentError`, + because Zammad drops a parameter it does not know rather than refusing it, and the search + would come back unnarrowed with nothing to say so. That includes a user keyword on + another resource: `tickets.search('printer', group_ids: [2])` was sent as written and + answered with tickets from every group, where a `condition` on `ticket.group_id` is what + narrows them. A keyword with nothing in it raises too, an empty list, an empty Hash, a + Hash of nothing but empty Hashes, or a value that is sent as a blank String: Zammad reads + it as not given, so `search('smith', ids: [])` came back with + every user matching the term rather than none. A resource of your own declares what its search reads with + `search_filters`. `group_ids:` is a list of group ids, for the agents with `full` access + to them, or a Hash of group id to access, `group_ids: {2 => ['read']}`, for any other: + Zammad reads a group named without an access as `full`. `permissions:` is not an access + check: where Zammad searches through Elasticsearch, a permission no active role grants + leaves the search unnarrowed. `role_ids:` narrows on both paths and is not one either: it + matches a user holding a role that has been disabled. The README says what to check. +- There is no `where`. During the development of 2.0 there was one, which took `sort_by` + and `order_by` on a generic index, nothing at all on tickets and users, and the search + parameters on a search, and raised for everything else — an attribute filter above all, + since Zammad's index endpoints do not filter. The most familiar verb on a collection + refused nearly everything it was given, so the two things it did do have names of their + own: `order`, and the keywords of `search`. +- A resource proxy is `Enumerable` over `all`, so `client.tickets.each`, + `client.tickets.first(5)`, `client.tickets.map`, `#find_each`, `#in_batches`, `#page`, + `#pluck` and `#count` all work without naming `all`. `client.x.find(id)` keeps + its own meaning rather than becoming `Enumerable#find`; `detect` is the block form. +- `Collection#count` costs a single request on a search endpoint, which Zammad can count + without returning the records. +- `Collection#pluck(*attributes)`, for reading one or more attributes from every record. +- `client..find_by(**params)` and `#find_by!`, which look a record up by + attribute value, and `client..exists?(id)`. `find_by` answers on every + resource and for any kind of value: the first record that carries the values, `nil` if + it finds none. It fetches candidates and checks them itself, because Zammad's index + endpoints cannot filter — through a search where the resource has a search endpoint and + one of the values is a string, and by walking the index everywhere else, which is what + `ticket_states`, `ticket_priorities` and `ticket_articles` and a lookup such as + `find_by(active: true)` get. A walk costs a request per page until a record matches. It + returns a record that genuinely carries the attributes asked for, or nil; a record that + does not carry an attribute does not match it, not even for `nil`. What the search can + surface is Zammad's business, so `find_by(...) || create(...)` can still create a + duplicate — as writing the search out by hand would. Without Elasticsearch a search + reads only the string columns of a user, organization or group, and of a ticket only the + title, the number and its articles, so a lookup by anything else answers `nil` there; + the README lists what that covers and why `find_by` does not walk the index after a + miss. Every page of hits is read until + one matches, so a miss costs a request per page of hits: Zammad's search sorts by + `updated_at`, newest first, rather than by relevance, so the exact match can be on any + page. +- `ResponseError` accepts a `detail:` describing a failure that has no HTTP response of its + own, so `find_by!` reads as `no record matched` rather than `no response`. Such an error + still reports the status its class is the name for, so a `NotFoundError` raised without a + request answers `404` like every other one. +- The page size is clamped to what an endpoint serves (100 for `/api/v1/tickets`, 200 for + a search, 1000 for the other index endpoints). Asking for more used to end iteration + after the first page, because Zammad capped the response and the short page read as the + end of the list. A walk also learns the size the endpoint actually serves from its first + page, so an instance that pages smaller than those figures is still walked to the end + rather than truncated. +- `find_each(batch_size:)` and `in_batches(of:)` raise when the collection is already + limited to a page. `page(3, per_page: 50)` and a batch size are two ways of naming the same + thing, and re-sizing the page behind the caller would hand back different records. +- `ZammadAPI::PaginationError`, raised when an endpoint answers a page with the page + before it, instead of paging forever. +- `Base#reload`, `#persisted?`, `#[]`, `#fetch`, `#to_h` and a readable `#inspect`. +- `record.update(attributes)`, `record.update!(attributes)` and + `record.assign_attributes(attributes)`. Applying a hash of changes previously meant one + writer call per attribute before `save`. +- `ssl_verify`, `proxy`, `user_agent`, `retries` and `retry_interval` client options. + The default `User-Agent` is now `zammad_api-ruby/` rather than + `Zammad API Ruby`. +- `adapter` and `middleware` client options, the seam into the Faraday stack. Swapping in a + persistent-connection adapter or adding instrumentation previously meant that the HTTP + stack was closed to callers. A Faraday error while building the connection surfaces as + `ConfigurationError`, so Faraday stays an implementation detail. +- RBS signatures in `sig/`, verified by Steep in CI. +- `require 'zammad_api/test'` ships a stand-in Zammad for testing code that calls this + client: `ZammadAPI::Test#stub` declares responses, `#client` hands back a real client + wired to them, and `#requests` records what was sent. Responses travel the same decoding, + error mapping and record building as real ones, so a stubbed 404 raises `NotFoundError`. + An unstubbed request raises rather than answering with something empty. Consumers + previously had to intercept HTTP to test against this client at all. +- `respond_to?` now answers correctly for attribute readers and resource methods. +- Records implement `deconstruct_keys`, so they can be used with `case/in` pattern + matching, including against nested attributes. `Config` and `Response` are `Data` + objects and match as well. +- `Client#with(**options)` derives a new client with changed options. The options are + re-validated and any `on_behalf_of` scope is carried over. +- `Client.from_env` builds a client from `ZAMMAD_URL`, `ZAMMAD_TOKEN`, + `ZAMMAD_HTTP_TOKEN`, `ZAMMAD_OAUTH2_TOKEN`, `ZAMMAD_USER` and `ZAMMAD_PASSWORD`, with + passed-in options winning. Every example script used to repeat the same `ENV.fetch` pair. +- `Client#me`, the user the credentials authenticate as, and `Client#version`, the version + of the Zammad instance. +- `Response#decoded(:object | :array)` validates the shape of a response body in one + place, so an unexpected payload raises `ParseError` with a consistent message instead of + failing further downstream. +- `record.related` reaches the records a record points at: `ticket.related.customer`, + `ticket.related.group`, `ticket.related.articles`, `user.related.organization`, and + `created_by` / `updated_by` on everything. Following a foreign key used to mean + `client.users.find(ticket.customer_id)` by hand. The readers sit under `related` rather + than on the record because Zammad expands an association into a name under the plain + attribute, and `ticket.customer` has to keep returning that name rather than turning + into a request. `Resource.associations` lists what a resource declares. +- Records compare as the Zammad records they came from: two records of the same kind with + the same id are equal, and `#hash` agrees, so `uniq`, `Set`, `include?` and records as + Hash keys all work. They previously compared by object identity, so the same ticket + fetched twice was two unequal records. A record with no id stays equal only to itself, + which means its first save changes its hash and a record used as a Hash key before that + save has to be rehashed after it. +- `record.to_json` and `record.as_json` render a record's attributes. `to_json` previously + fell through to `Object#to_json`, which serialized a record as the string + `"#"`. +- `Collection#empty?`, and `#size` / `#length` as names for `#count`. `Enumerable` supplies + none of the three, so `client.tickets.all.empty?` used to raise `NoMethodError`. `empty?` + costs one request and asks for a single record rather than a whole page, except on a + collection limited to one page, where the page size decides which records that page holds. + A resource proxy forwards all three. +- `client.resource(SomeClass)` takes a subclass of `ZammadAPI::Resources::Base` and answers + with a proxy for it, so an endpoint this gem does not model gets records, pagination, + `find_by`, change tracking and `save` from a class that declares its `path`: `class Role < + ZammadAPI::Resources::Base; path 'api/v1/roles'; end`, then `client.resource(Role).each { + … }`. `Base` already supported being subclassed, and `searchable`, `max_per_page`, + `sortable`, `belongs_to` and `has_many` are there to say what else is true of the + endpoint; what was missing since `const_get` went was a public way to a proxy for one, + which left raw requests as the only way to the rest of the API. An association on such a + class can point at another by its full name, `class_name: 'Acme::Role'`. +- Typed records. `ResourceProxy` and `Collection` are generic over the resource they hold, + so `client.tickets` is a `ResourceProxy[Resources::Ticket]` and `find`, `first`, + `find_by`, the block of `each` and a search all answer with a `Ticket` where the + signatures said `untyped`. Each resource declares the attributes every supported Zammad + serves for it — the columns of its table, typed the way their JSON arrives — so + `ticket.title` is a `String` and `ticket.titel` is a type error. Attributes an + administrator added are read with `record[:name]` or declared by reopening the class in a + project's own signatures; the README's Type signatures section says what else is left + undeclared and why. `spec/typed/usage.rb` is checked by `rake steep` the way a caller's + code is, and pins these types from the outside. + +### Fixed + +- Credentials are no longer written to the debug log. The old transport logged + `user:password` on every client build; payload keys such as `password` and `token` are + now redacted, and `Config#inspect` redacts credentials. A `ConfigurationError` raised + while building the connection redacts the configured url and proxy out of the underlying + message too, including where that message quoted the value through `inspect` rather than + interpolating it — which is what `URI::InvalidURIError` does, for exactly the characters + that make a URL invalid — or through `dump`, which is how it quotes a URL holding a + character outside ASCII: a proxy password with an umlaut in it stayed in the message, and + in the error kept as its cause. +- The debug log redacts a body handed over as a String and a query string written into the + path. Redaction went by key, on a Hash or a list, so + `client.post(path, body: '{"password":"..."}')` was logged as it stood, and + `client.get('api/v1/users/password_reset_verify?token=...')` printed the token in the + request line and the response line. A String body is read for its keys where it is JSON + and replaced by its size where it is not. The path is redacted by parameter name, also + in the message of a timeout and in the operation a raw request is named by in every + error it raises. +- `on_behalf_of` no longer leaks: the old `perform_on_behalf_of` used `tap` without an + `ensure`, so an exception inside the block left the `From` header set on every later + request. +- `on_behalf_of` refuses an identifier that is `nil`, empty or blank with `ArgumentError`. + Zammad reads a `From` header with nothing in it as no header at all, and a `nil` sent + none, so `client.on_behalf_of(user&.login)` with no user handed back a client that + performed every request as the account it authenticates as, and read everything that + account can see, with no error. `Client#inspect` shows the scope of a client that has + one, where it printed as the client it was derived from. +- Zammad installations served from a sub-path (`https://example.com/zammad/`) now work. + Request paths are relative, so the prefix is no longer stripped. +- Query parameters are encoded by the HTTP layer, including arrays and characters that + need escaping. +- Nested attributes inside arrays are symbolized consistently. +- A malformed or non-JSON response body no longer degrades into an empty hash that + callers then iterate as key/value pairs. +- Unknown resource names no longer resolve to unrelated Ruby classes. +- Record ids are escaped everywhere they reach a path, including the attachment download + endpoint and `has_many` association paths, so an id carrying a traversal cannot redirect + a request onto another endpoint. +- A credential carrying an unencoded `@` is redacted whole. Redaction stopped at the first + `@`, so the tail of such a password survived into `Config#inspect` and into every + `ConnectionError` message. +- `Transport#with_config` keeps the transport's own class, so a stand-in written as a + `Transport` subclass survives `client.with(...)` instead of reverting to a real HTTP one. +- `save` on a persisted record with nothing staged sends no request. The empty `PUT` it + used to issue was applied by Zammad, bumping `updated_at` and `updated_by`. +- A nested query parameter is sent as a structure rather than as its Ruby `inspect`. + `condition`, which the search endpoints narrow by and which `search` takes, went out as + `condition=%7B%22ticket.state_id%22…`; Zammad could not parse it, dropped it, and + answered with an unnarrowed search. A `nil` is now refused at any depth, and the message + names the path to it. +- A `condition` that nests groups of conditions reaches Zammad as it was written. A list of + Hashes goes out as `list[][key]=value` pairs, and Rails begins a new element only at a + key the element before it has too. Faraday writes the keys of each Hash in alphabetical + order, so a group, `{operator: 'AND', conditions: [...]}`, after a condition went out + `conditions` first and was read into the condition before it, leaving a second element + that held only an operator. Zammad was handed a selector nobody wrote: it answered that + one with a 500, and the same two elements the other way round with every ticket. The + client writes the query itself now, and begins such an element with a key the two share. + A list no order can carry raises `ArgumentError`: one whose elements share no such key, + a list directly inside a list, and an empty Hash inside a list. Every other query is + written as it was. +- Bare socket failures are retried. `Errno::ECONNRESET` and the rest were mapped to + `ConnectionError` but were missing from the retriable list, so a transient failure + through an adapter that wraps it (net_http) was retried while the same failure through + an adapter that does not raised on the first attempt. +- A list body that is not made of objects raises `ParseError` instead of failing later. An + unexpanded search answering `[1, 2, 3]` stored an Integer as a record's attributes, and + the first reader died with `TypeError: no implicit conversion of Symbol into Integer`. + A `null` among the records is refused as well. It passed the check, which could not tell + a `nil` it had found from having found nothing, and a walk then raised `NoMethodError` + reading the ids of the page. +- `destroy` clears the staged changes and the last validation error, and refuses the + association readers. A destroyed record went on reporting `changed?` and a change set + that can never be sent, and `record.related` went on requesting a record that no longer + exists — dropping the memo was not enough on its own, because the reader rebuilt one on + the next call. `record.related`, `ticket.articles` and `ticket.add_article(…)` all raise + `ZammadAPI::Error` for a destroyed record now, rather than reaching the server for it. +- `Config#redacted_url` no longer mangles a URL whose query string contains an `@`. + `https://host?a=b@c` was rendered as `https://[REDACTED]@c`, a host that does not exist, + in every `ConnectionError` and `TimeoutError` message. +- The RBS signatures the gem ships validate on their own. They named Faraday types that + are declared only in `sig/vendor`, which is deliberately not published, so `rbs validate` + failed for every consumer with `Could not find Faraday::Connection`. +- `ZammadAPI::Test.new` no longer builds a Faraday stack it immediately discards, which a + suite using `let(:zammad) { ZammadAPI::Test.new }` paid for once per example. +- The trailing slash a base URL is normalised with lands on the path rather than at the end + of the string. `https://host/zammad?tenant=acme` became `https://host/zammad?tenant=acme/`, + which every request was then resolved against and every `ConnectionError` printed. +- `Config` refuses a URL with a scheme and no host, and one that is not a String. Both used + to be accepted: `'https://'` failed deep inside the adapter on the first request, and a + `URI` — what `URI(...)` hands back, and it prints as the URL — died as a `NoMethodError` + past the `ConfigurationError` the constructor is documented to raise. +- `user_agent: nil` falls back to the gem's own value instead of reaching Faraday as a nil + header, which Faraday filled in with its own — so the gem silently stopped identifying + itself in the instance log an operator greps to find its requests. A `user_agent` that is + not a String raises `ConfigurationError`. +- A line break inside `http_token`, `oauth2_token` or `user_agent` raises + `ConfigurationError` when the client is built, and one inside an `on_behalf_of` + identifier or a raw request's header raises `ArgumentError`. Each was taken and then + refused by Net::HTTP at the first request, with an `ArgumentError` that quoted the value, + the access token included. Neither message quotes it now. A line break at the end, as a + token read from a file has, is stripped by Net::HTTP and still taken. +- Proxy credentials are redacted whether or not the proxy URL carries a scheme. + `proxy: 'user:secret@proxy:8080'` — the shape an `http_proxy` setting is copied out of — + rendered in `Config#inspect` in full. +- A `proxy` that is not a URL, and a `middleware` callable that raises, are reported as + `ConfigurationError`. Only `Faraday::Error` was wrapped, so these escaped as + `URI::InvalidURIError` and as whatever the callable raised, past the + `rescue ZammadAPI::ConfigurationError` around building a client. +- The debug log redacts `api_key`, `apikey`, `passwd`, `pwd` and a bare `key` as well. The + pattern matched `private_key` but not the other key spellings, and `password` but not its + short forms, so those payload values were written out in full. +- `destroyed?` is sticky. `reload` re-read a record that no longer exists and cleared the + flag on the way back, so a destroyed record came back reporting itself as `persisted?` + and its next `save` issued a `PUT` against the deleted path; a second `destroy` surfaced + Zammad's 404 rather than saying the record was already gone. `save`, `reload` and + `destroy` now all refuse a destroyed record with the same local error. +- `record.fetch` refuses more than one fallback, the way `Hash#fetch` does. `fetch(:a, :b, + :c)` — a multi-key read this has never been — was answered with `:b`. +- A collection smaller than one page costs one request rather than two. The walk confirms + the end of a short page with another request, which could only ever come back empty; it + now stops on the total the endpoint reports alongside the page, and only falls back to + confirming when the endpoint reports none. The total has to be corroborated by the page + it arrived with — the page came back short of the size requested, and exactly as many + records were seen as the total names. It is the one stop condition not derived from the + records the endpoint served, and a total that under-reports (a count taken before + permission scoping, a stale cache, a proxy rewriting the header) ended the walk early: + 100 of 150 records came back, nothing was raised, and nothing told that result apart + from a complete one. +- The test kit records a request body by value. Held by reference, a test that built one + payload, sent it, then changed it for a second call rewrote the first recorded request + and asserted against a body that never went anywhere. `Test#inspect` also reads the + recorded requests under the monitor that guards them. +- A record is persisted because Zammad answered 2xx, not because the answer parsed. The + create response was decoded before the flag went down, so a 201 carrying something other + than a JSON object — an HTML error page from an intervening proxy — raised `ParseError` + with the record still looking new. The ticket existed in Zammad while the record here did + not, and a retried `save` POSTed a second one. What that leaves behind is a record that + is persisted and has no id, and `save`, `reload` and `destroy` all refuse it by name + rather than pretending: a record built by `new` has nothing staged, so the retried `save` + took the "nothing changed, nothing to send" short circuit and returned `true` without + making a single request, for a record that may or may not be in Zammad. +- A `ConfigurationError` raised while building the connection no longer quotes the proxy + credentials. `proxy: 'http://user:pa ss@host:3128'` came back as + `URI::InvalidURIError` with the whole URL, password included, in a message that lands in + every log and exception report — the case `Config#inspect` exists to prevent, reached by + another route. +- `Config` refuses a `proxy` that is not a String, an `adapter` that cannot be a Symbol, + and an `ssl_verify` that is not a boolean. A `URI` proxy was accepted and then died as a + `NoMethodError` inside `inspect`, so the object documented as safe to log raised at the + moment something logged it; `adapter: 1` and `adapter: true` escaped the constructor as + `NoMethodError`; and `ssl_verify: 'false'` — a plausible environment read — is the + truthy string `"false"`, so verification stayed on while the caller believed otherwise. +- An `OpenSSL::SSL::SSLError` that an adapter did not wrap is mapped to `ConnectionError` + like its Faraday counterpart. Unlisted, a certificate mismatch through such an adapter — + and this gem lets a caller choose one — escaped `request` raw, past every + `rescue ZammadAPI::Error`. It is not retried: a rejected certificate is a fact about the + instance, not a transient failure. +- A resource subclassed by a caller keeps its parent's API path. Class-level state is not + inherited, so `class MyTicket < Ticket; end` inherited all nine of Ticket's associations, + its page limit and its searchability, and lost only the path — `MyTicket.resource_path` + raised "does not declare an API path" from a class that plainly did. +- The test kit answers a later page of a singly-stubbed list endpoint the way an endpoint + out of records would. A stub that kept serving the same records to every page tripped the + repeated-page guard, so the obvious `stub(:get, 'api/v1/groups', body: [...])` made every + full read of that collection raise `PaginationError`. Against a real Zammad the same code + works, because page 2 comes back empty; the stand-in was what differed. A stub that names + a `page` is still served exactly as written. +- The test kit sequences stubs within an identical query scope rather than across every + scoped stub for an endpoint. Two stubs naming different parameters both match a request + carrying all of them, and they were read as a sequence: stubbing a search once for its + records and once for its count made `count` consume the records stub, hand back an Array + where a count belonged, and then report the endpoint as unstubbed. The most specific + scope now answers, and two that are equally specific raise + `ZammadAPI::Test::AmbiguousStubError` rather than one of them being picked. +- `Collection#count` reads the total from the header when a search endpoint ignores + `only_total_count`. The probe came back as the usual page of records and was thrown away, + so the answer cost 1 + N requests instead of N. +- `update` and `update!` refuse a destroyed record before staging anything. They assigned + first and saved second, and `save!` is where the destroyed check lives, so `update` on a + destroyed record raised and left it `changed?` with a change set that can never be + sent — the state `destroy` clears the staged changes to prevent. +- Writing an attribute the record does not carry is a change, and is sent. Zammad reduces + the object it serializes for a permission-scoped client, so a key being absent says + nothing about what is stored; read as a `nil` original, `group.note = nil` compared equal + to nil, staged nothing and was still merged into the attributes. The write was dropped + without a word, `save` returned `true` having sent no request, and the record went on + reporting a key Zammad never sent it, so `changes` and `attributes` disagreed. +- `ticket.add_article(...)` refuses a ticket that has not been saved instead of POSTing + `ticket_id: null` and leaving the caller to read Zammad's 422 for the reason. Every other + path in the gem that needs a stored id says so locally. +- The documentation no longer promises that a `has_many` reader refuses a partial list + with `ZammadAPI::PaginationError`. The check behind that promise read a total from an + `x-total-count` response header, which Zammad has never sent, so it never ran and was + removed — see the entry on that header under Breaking — while this entry, the README and + the comment on `has_many` went on describing it. A `has_many` list is read in a single + request because the association endpoints Zammad routes serve the whole thing: + `ticket_articles/by_ticket` renders every article of the ticket and reads no paging + parameter. Nothing in a response tells a whole list from the first page of one, so + there is no honest check to put in its place. +- The documented page sizes are sizes the endpoints actually serve. Every `find_each` and + `in_batches` example used `of: 500` against `client.tickets`, which caps at 100, so each + headline example did something other than what it showed. The clamp itself stands — a + batch size says how much to fetch at a time, not which records you get, which is why + `page` refuses an oversize size and a walk reduces it. +- A destroyed record reports the attributes Zammad last served, not a write that never + left the process. `destroy` dropped the staged change set and left the writes it + described standing, so `group.name = 'B'; group.destroy` answered `changed?` with false, + `changes` with `{}` and `name` with `"B"` — with nothing left to tell a local edit apart + from a value the server gave, in the one state where it can never be saved. +- A record Zammad served without an id is no longer told it "was saved". Zammad serves a + reduced object where the authenticated user may not see the whole record, so a plain read + can hand back a persisted record with no id; the message sent the caller to look at a + save that never happened instead of at what the client may read. +- `require 'zammad_api'` no longer depends on Faraday loading `net/http` for it. + `Timeout::Error` and `SocketError` are named in `Transport`'s class body and resolved + only because the default adapter pulled `timeout` and `socket` in transitively — so a + Faraday that stopped doing that, or a slimmer adapter, turned the require into a + `NameError` before a single request. +- `middleware:` that decodes the response body — `c.response :json` is the usual one — is + refused when the client is built, before anything is sent, with a `ConfigurationError` + naming it. Faraday's parsed Hash used to become a Ruby inspect string that `JSON.parse` + refused, which killed every record built from it with a `ParseError` naming Zammad for + what the caller's stack had done. This gem parses JSON itself and hands the undecoded + bytes to attachment downloads, so once a middleware has consumed the body there is + nothing faithful left to hand back. +- Two spellings of one query parameter raise instead of silently sending whichever Hash + order put last — at any depth, and in `search` at the call that wrote it as well as on + the wire. The same goes for two spellings of one response header in `ZammadAPI::Test`. Keys are normalised + in both places, so `search('x', 'ids' => [1], ids: [2])` and + `{state_id: 1, 'state_id' => 2}` each collapsed into one parameter and dropped the other + value without a word — including inside `condition`, the structured parameter the search + endpoints read. +- A stubbed response from `ZammadAPI::Test` carries `content-type` the way a real one does, + and is decoded by that header rather than by the Ruby type of the stub's body. Code that + branches on `response.headers['content-type']` passed against Zammad and failed against + the stand-in, or the reverse; and a stub declaring a non-JSON type still handed back a + decoded Hash, where Zammad gives the raw string and reading a record from it raises + `ParseError`. +- `record.fetch(:missing, default) { ... }` warns the way `Hash#fetch` warns, naming the + line that made the call. A bare `Kernel#warn` reports no source location, so the warning + identified neither the call site nor the library it came from. +- A raw request refuses an absolute URL with `ArgumentError`. Faraday lets one replace the + instance URL and still attaches the client's headers, so + `client.get('https://other.example/collect')` — a link taken from a response body, say — + sent the access token and the `on_behalf_of` scope to that host. The path is documented as + relative to the instance URL, and record ids were already held inside their segment; this + is the same escape one level up. The test kit refuses it too. +- A raw request refuses a path that cannot be read as a URL with `ArgumentError`. + `client.get('api/v1/tägs')` and `client.get(' api/v1/x')` raised `URI::InvalidURIError` + from inside the connection, which is neither a `ZammadAPI::Error` nor the `ArgumentError` + a path is documented to raise, after the debug log had already written a line for a + request that never left. A query string in the path that names one parameter as a value + and as a structure raised `TypeError` the same way. Both are refused before anything is + logged, with a message that does not quote the path. +- An instance `url` that carries credentials raises `ConfigurationError`. Faraday turns the + userinfo of a URL into a Basic `Authorization` header, and its authorization middleware + leaves a header that is already set alone, so with `url: 'https://old:pass@host/'` and + `http_token: 'new'` every request went out as the old account while `client.inspect` + reported `auth=http_token` — the token was never sent. Credentials belong in `user:` and + `password:`, or in one of the token options. +- `Client.from_env(**overrides)` and `Client#with` replace the credentials they override. A + credential is one of several options read in a fixed order, so a plain merge left the old + one in charge: with `ZAMMAD_TOKEN` set, `from_env(user: 'u', password: 'p')` still sent + the environment's token, and `client.with(oauth2_token: 'x')` on a token client went on + acting as the account the token belonged to, with no error. Naming one way to authenticate + now drops the others; overriding `password:` alone still keeps the `user` it pairs with. + `Config#with` does the same. +- `pp config` redacts credentials, and a transport no longer prints its connection. `Config` + is a `Data`, and `pp` — what IRB and the Rails console print a value with — has a printer + of its own for those that renders the members without going through `inspect`, so + `client.config` typed at a prompt showed the token, the password and a proxy's credentials + in full. `Transport` had no `inspect` at all, so Ruby's default printed the Faraday + connection it holds, proxy password and access token included, and every record holds its + transport. +- A proxy or instance URL whose password carries an unencoded `/`, `?` or `#` is redacted. + Each of those ends the authority early as far as URL syntax goes, so `proxy: + 'http://user:p#ss@proxy:3128'` left `user:p` as the authority, the redaction found no `@` + in it, and the password was printed by `Config#inspect` and quoted in the + `ConfigurationError` raised when the connection could not be built. Where a colon makes a + password possible, everything up to the last `@` of the whole value is blanked now. The + price is a URL with a port and an `@` further on, such as `https://host:8443/a@b`, which + renders with its host blanked: a colon cannot tell a port from a password, and that is the + mistake that leaks nothing. +- A wait before a retry is never longer than `timeout`. The retry middleware sleeps for + whatever a `Retry-After` header says and has no ceiling of its own by default, so a + maintenance page answering 503 or a rate limiter answering 429 with `Retry-After: 3600` + held the calling thread for an hour per retry — two by default — before raising the error, + whatever `timeout` and `retry_interval` said. A `Retry-After` within `timeout` is still + honoured; a longer one is not waited out, and the request fails at once with the error for + its status, `RateLimitError#retry_after` still carrying the figure. +- The test kit serves a sequence of list stubs one per read. Every full read of a collection + asks for the page after its last one, and that request took the next stub in the queue and + served it as an empty page: three stubs for `GET api/v1/groups` answered three reads with + the first, the third and the third, and the second was never seen. A request for a later + page is now answered by the stub its read began with and does not move the sequence on. +- An exceeded `open_timeout` raises `TimeoutError`. Net::HTTP reports it as + `Net::OpenTimeout`, which Faraday's default adapter wraps into `Faraday::ConnectionFailed` + with every other failure to connect, so it surfaced as `ConnectionError: … is unreachable + (execution expired)` and skipped the `rescue ZammadAPI::TimeoutError` documented to catch + it. +- A `dup` or `clone` of a record has a change set of its own. The attributes are frozen and + replaced on write, but the change set is written in place and the copy shared it: after + `copy = record.dup; copy.name = 'X'` the original reported `changed?` and a change to + `name` while still reading `name` as it was, and its next `save` sent the copy's value. + The copy also gets association readers of its own, rather than ones that read through the + original. +- An attribute write on a destroyed record raises. `update` and `update!` already refused + one, so as not to leave a change set that can never be sent, but the writers they are + built on did not ask: `group.destroy; group.name = 'Z'` left `changed?` true and `name` + reading `"Z"` on a record `destroy` promises to leave as it last was in Zammad, and the + `save` after it was the first thing to object. A named writer, `[]=` and + `assign_attributes` all refuse now, and stage nothing. +- A request body that cannot be encoded as JSON raises `ZammadAPI::Error`. Faraday's JSON + middleware raised `JSON::GeneratorError` from inside the stack and nothing mapped it, so + `client.post(path, body: {data: File.binread('a.png')})` with the bytes not + Base64-encoded, or any body holding `Float::NAN`, went past the `rescue ZammadAPI::Error` + callers are told to write — and so did a record `save` carrying such a value. The body is + encoded before the request is logged now, so a refused one leaves no line claiming a + request that was never made, and the test kit refuses it the same way. +- A walk no longer ends when the block empties the batch it was handed. The size of a page + was read after the block returned, so an `in_batches` consumer that worked its batch off + with `shift` looked like an empty page and the walk stopped after the first one, and a + batch the block shortened looked like the last. The records are counted before they are + handed over. +- A search is walked to its end where one of its pages comes back short. A walk stopped at + the first page shorter than the one before it, which is right for an index and not for a + search: Zammad has the search name the ids for a page and then loads the records by id, + so one deleted in between, or one Elasticsearch still lists after it was removed, is left + out and nothing fills its place. `search(...).each` then ended on that page with the + rest of the hits unread, and `find_by` answered `nil` for a record on a later one. Only + an empty page ends a search walk now, at the cost of one more request where the last page + of hits is part-filled. +- A search is read on past a page with nothing on it where Zammad says there are hits + behind it. A page comes back empty for the reason it comes back short, every id on it + having lost its record, and on the page of one that `first` and `empty?` ask for a single + stale hit does it: `search(term).first` answered `nil` and `empty?` answered `true` with + live hits behind a record deleted a moment before, and `each` ended on such a page. A + search that is walked sends `with_total_count` and ends on an empty page only once the + pages read cover the total reported beside it. The total never ends a walk on a page that + held records, because Elasticsearch stops counting at ten thousand hits. An empty page + still ends the walk where there is no total to go by: on a Zammad before 6.5.1, which + answers with the records alone, and past the ten thousandth hit on Elasticsearch. It can + also end the walk short of the total on an instance that serves a search in smaller pages + than were asked for, because the pages read are reckoned at the size asked for. The test + kit pages a search stubbed as `{records: [...], total_count: n}` the way it pages an + Array. +- `first`, `take` and `empty?` read on past stale search hits in pages that grow. They size + their request to the records they want, and held to that size, reading on past an empty + page cost a request for every stale hit in a row: 5000 requests for `empty?` behind 5000 + of them, on an instance whose Elasticsearch index has drifted from its database. Past an + empty page they now ask for the largest page that starts where the last one ended, + doubling up to the 200 a search serves, and the same read takes 34. No hit is passed over + or read twice. A batch size given to `in_batches` or `find_each` is left as it is. +- A `StopIteration` raised by the block a collection yields to is raised, not taken for the + end of the walk. The walk ran inside `Kernel#loop`, which rescues it, so a block calling + `next` on an enumerator of its own that ran out, as in `map { [it.id, labels.next] }`, + dropped the records and pages after that one and `map` answered with what it had. The + same block over an Array raises. +- A repeated page is recognised by the records on it rather than by their payload. A job + that writes to the records it is handed changes what they serialize as, so an endpoint + that ignores `page` served the same records with a different payload each time: the + guard never fired, and the job went round the same records, writing to them again, for + as long as it ran. Two consecutive pages holding the same ids, in any order, raise + `PaginationError` before the second is handed over. Records without an id are still + compared by payload. +- A search sends the term and the filters it was given. The collection `search` returns is + lazy and held the caller's own String, Array and Hash until it was enumerated, so + `search('printer', ids: ids)` followed by `ids << 7` searched for something the call was + never given, after the filters had been checked. `search` keeps a copy of its own, which + `page` and `order` carry on. +- A `related` kept in a variable follows its record. A save, a reload and a write to a + foreign key dropped the record's association proxy and built another on the next call, so + only a caller who asked the record again saw the change: after `related = ticket.related` + and `ticket.customer_id = 9`, `related.customer` went on answering with the user it had + resolved before, and the same after a reload. A record keeps one proxy now and empties + it. A kept one also refuses a destroyed record, as `related` does, where it used to + answer from its memo and request the articles of a ticket that is gone. A lookup that is + still on the wire when the foreign key is written, by a logger or a middleware that + reaches the record or by another thread, no longer leaves the record it fetched behind as + the answer for the new key. The proxy is emptied as well where a save answered with a 2xx + nothing could read puts the record back on what it sent: a key written while that request + was out, and an association read from it, left the record on the key it sent with the + other key's record still the answer. +- Records of two Zammad instances are no longer equal for sharing a class and an id. An id + is only unique within one installation, so a script reading two of them, such as a + migration or a sync, held ticket 1 of each as one record: `uniq` dropped one of the two, + and a Hash keyed by record answered for one instance with the other's value. `==`, + `eql?` and `hash` take in the `url` the record's client was configured with. Two clients + for one URL, and a client and its `on_behalf_of` scope, still hold the same record. +- An update Zammad acknowledged is not sent again. The staged changes were dropped only + once the response had decoded, so an update answered with a 2xx nothing could read, such + as a proxy's HTML page, raised `ParseError` with the whole change set still staged, and + the next `save` sent all of it again along with whatever had been staged since. For a + ticket's `article` that is a second article and a second e-mail. A 2xx now settles what + was sent before the body is read: the record holds the values it sent with nothing + staged, and `reload` brings in the rest. A save Zammad rejected keeps its changes staged, + as before. What is settled is what the request carried: a write that reaches the record + while the request is out, from a logger or a middleware that touches it or from another + thread, is dropped, as it is by a response that can be read, rather than settled as if + it had been sent. The body of the request is built from the same attributes it is then + settled on, read once, so a write from another thread cannot land between the two and be + sent without being settled. A key Zammad never served the record with is not kept either, which a + ticket's `article` is: kept, the same article assigned again compared equal to the first + and `save` reported `true` without sending the second reply. +- `ticket.add_article` adds to that ticket whatever its attributes say. A `ticket_id:` + among them was replaced by the ticket's own, but only under the Symbol spelling: given + `'ticket_id'` as well, the String key came later in the Hash and won when the article + symbolized its keys, so the article was posted to the ticket the caller's Hash named. + Both spellings are taken out before the ticket's id goes in. +- `on_behalf_of` keeps the user it was given. The scoped client held the caller's own + String, so a login buffer reused after `client.on_behalf_of(login)` changed who every + later request from that client was performed for. The scope is copied and frozen, in the + test kit's transport as well. +- A proxy password no longer reaches an exception report through `cause`. The + `ConfigurationError` for a connection that cannot be built had its message redacted, but + Ruby attached the error it replaced as the cause, and a report prints the whole chain: + `full_message`, a log formatter and an error tracker all showed `URI::InvalidURIError` + quoting the proxy URL in full. The cause is dropped where its report would print a + configured value that redaction changes, and kept everywhere else, so a `middleware:` + callable that raises still shows the backtrace into the caller's code. An error that + cannot render its report at all, such as one whose `detailed_message` takes no + `highlight:` keyword, is dropped as a cause too, rather than leaving in place of the + `ConfigurationError`. +- `middleware:` that adds `c.response :raise_error` is refused with a `ConfigurationError` + when the client is built, as `c.response :json` already is. It sits below the retry + middleware and raises for a 4xx or 5xx before this gem sees the response, so a `GET` + answered 503 was not retried and left as `Faraday::ServerError`, a 404 left as + `Faraday::ResourceNotFound`, which `exists?` does not rescue, and a 422 as an error + `save` does not turn into `false`. None of them is a `ZammadAPI::Error`. A subclass of + either middleware is refused as well: the stack was asked for the two by name, and + `class QuietRaiseError < Faraday::Response::RaiseError` has another. +- A `Cookie` header is redacted in the debug log, and so is `Proxy-Authorization`. A raw + request takes headers of its own and the request line prints them, and neither name + matched the words that mark a credential, so `client.get(path, headers: {'Cookie' => + ...})` wrote the session out in full. + +### Changed + +- `Response#headers` is frozen, and each response carries its own. Writing through it + changed nothing on the wire and, in `ZammadAPI::Test`, rewrote the stub for every later + request in the example. + +- `client..destroy(id)` deletes directly instead of fetching the record first. +- Resource dispatch is explicit rather than `method_missing` plus `const_get`. +- A resource declares what its endpoint does — `searchable true`, `max_per_page 100`, + `sortable false` — the way it already declared `path`, rather than by setting + `SEARCHABLE`, `MAX_PER_PAGE` and `INDEX_QUERY_KEYS`. A misspelled constant was silently + ignored and the resource kept Base's default, so `SEARCHEABLE = true` left the resource + unsearchable and every `find_by` on it raised "Zammad routes no search endpoint" with no + hint that the declaration was the problem; a misspelled declaration is a `NoMethodError` + at load. +- `client.` returns the same proxy each time rather than allocating one per call. + The proxies are built with the client and frozen, so a client stays immutable once built + and safe to share between threads without locking, as documented. Clients from `#with` + and `#on_behalf_of` get proxies of their own, so none is shared with the transport it was + derived from. +- The recursive copy behind frozen attributes, `to_h` and the test kit's recorded bodies + lives in one place (`ZammadAPI::DeepCopy`) instead of being written once per caller. +- Unit specs (`rake spec:unit`) run without a Zammad instance; the specs that need a live + server live in `spec/integration`. +- CI runs RuboCop, Steep and the unit specs on every supported stable Ruby, and publishes + releases through RubyGems trusted publishing. +- The integration job now waits for Zammad to answer before running specs, promotes + Zammad's generated CI environment into the job so it survives across steps, pins the + Zammad ref (overridable via `workflow_dispatch`), carries a timeout, and uploads Zammad's + logs on failure. It also runs `script/check_connection.rb` as a preflight, so a broken + gem-to-Zammad link fails in seconds with a readable transcript instead of 53 spec errors. +- The integration suite no longer depends on spec file order to run Zammad's auto wizard, + and tolerates an instance that is already set up. Its lifecycle examples are pinned to + definition order and say what is missing when only part of a file is run. +- `Test::UnstubbedRequestError` is a `StandardError` rather than a `ZammadAPI::Error`, so + a forgotten stub is not caught by the `rescue ZammadAPI::Error` in the code under test. +- The test kit matches array-valued query stubs, such as `query: {ids: [1, 2]}`, which + could never match before. + ## [1.4.0] - 2026-08-25 - Follow up - c3af2a9 - Fixes #29 - [JSON::ParserError on gateway timeout when proxy responds with HTML](https://github.com/zammad/zammad-api-client-ruby/issues/29) - Dependencies updated diff --git a/README.md b/README.md index 211469b..734313c 100644 --- a/README.md +++ b/README.md @@ -1,390 +1,1486 @@ -# Zammad API Client (Ruby) [![Gem Version](https://badge.fury.io/rb/zammad_api.svg)](https://badge.fury.io/rb/zammad_api) - -## API version support -This client supports Zammad API version 1.0. +# Zammad API Client (Ruby) + +[![Gem Version](https://badge.fury.io/rb/zammad_api.svg)](https://badge.fury.io/rb/zammad_api) +[![CI](https://github.com/zammad/zammad-api-client-ruby/actions/workflows/ci.yml/badge.svg)](https://github.com/zammad/zammad-api-client-ruby/actions/workflows/ci.yml) + +--- + +> [!IMPORTANT] +> ## 📣 2.0 is taking shape — tell us what you think +> +> **Version 2.0 is a breaking release, and it is not finished yet: this is `2.0.0.alpha1`, +> its first prerelease.** This is the moment when your feedback can still change it: names, +> defaults, what is missing, what reads wrong, and anything that makes upgrading from 1.x +> harder than it should be. +> +> **[→ Open an issue and tell us](https://github.com/zammad/zammad-api-client-ruby/issues/new)** +> +> Especially useful to hear: +> +> - Which 1.x calls in **your** code the [migration table](#migrating-from-1x) does not cover. +> - Endpoints you reach with [raw requests](#raw-requests) that should be modelled resources. +> - Anything the [test kit](#testing-code-that-uses-this-client) cannot stand in for. +> - Naming that made you look twice, and defaults you had to override every time. +> +> Rough notes are welcome — a half-formed "this felt off" is worth more to us now than a +> polished report after the release. + +--- + +Ruby client for the Zammad API v1.0. + +- Requires **Ruby 3.4** or later. +- Ships **RBS signatures** in `sig/`, so typed projects get completion and checking out of the box. +- Requests carry **timeouts** and **retry with backoff** for transient failures by default. +- Collections are **lazily paginated** `Enumerable`s, with a familiar + `order` / `page` / `in_batches` / `find_each` surface. +- Records support **pattern matching**, and clients are **immutable** and safe to share + between threads. +- **Your own resources** — `client.resource(Role)` gives a class you declare everything a + modelled one has — and **raw requests** reach the rest of the API, without giving up + authentication, retries or the error classes. +- A **test kit** (`zammad_api/test`) stands in for a Zammad, so your own tests need no + HTTP interception. + +> **Upgrading from 1.x?** See [Migrating from 1.x](#migrating-from-1x), which lists every +> call that changed. +> +> **Staying on 1.x?** See [Staying on 1.x](#staying-on-1x) for where its code lives and how +> to install it. ## Installation -Add this line to your application's Gemfile: +2.0 is a prerelease for now, `2.0.0.alpha1`, and a prerelease has to be asked for: ```ruby -gem 'zammad_api' +gem 'zammad_api', '~> 2.0.0.alpha' ``` -And then execute: +Or: - $ bundle +```sh +gem install zammad_api --pre +``` -Or install it yourself as: +`'~> 2.0'` does not match an alpha, and `gem install zammad_api` without `--pre` installs +1.x. - $ gem install zammad_api +### Staying on 1.x -## Available objects +1.x stays available for a project that is not ready for 2.0, or that runs on a Ruby older +than 3.4: 1.x needs Ruby 3.0 or later. -* user -* organization -* group -* ticket -* ticket_article -* ticket_state -* ticket_priority +Its code lives on the +[`1-stable`](https://github.com/zammad/zammad-api-client-ruby/tree/1-stable) branch, and +the [README there](https://github.com/zammad/zammad-api-client-ruby/blob/1-stable/README.md) +documents the 1.x API. To install it, keep the version below 2: -## Usage +```ruby +gem 'zammad_api', '~> 1.4' +``` -### Create instance +Or: -#### Username/email and password +```sh +gem install zammad_api -v '~> 1.4' +``` + +1.x is in maintenance mode, and will stay there for the foreseeable future: it still gets +fixes, while new features go into 2.0 only. Report a 1.x problem in the same +[issue tracker](https://github.com/zammad/zammad-api-client-ruby/issues), naming the +version, and open a pull request for it against `1-stable`. + +## Creating a client + +### Access token ```ruby client = ZammadAPI::Client.new( - url: 'http://localhost:3000/', - user: 'user', - password: 'some_pass' + url: 'https://zammad.example.com/', + http_token: 'your-access-token' ) ``` -#### Access token +### OAuth2 ```ruby client = ZammadAPI::Client.new( - url: 'http://localhost:3000/', - http_token: '12345678901234567890', + url: 'https://zammad.example.com/', + oauth2_token: 'your-oauth2-token' ) ``` -#### OAuth2 +### Username and password ```ruby client = ZammadAPI::Client.new( - url: 'http://localhost:3000/', - oauth2_token: '12345678901234567890', + url: 'https://zammad.example.com/', + user: 'user@example.com', + password: 'some_pass' ) ``` -## Resource management +A client authenticates one way. Passing more than one of these — a token beside a user and +password, say — raises `ZammadAPI::ConfigurationError` rather than quietly sending one of +them. + +### From the environment + +`from_env` reads `ZAMMAD_URL` and `ZAMMAD_TOKEN` (or `ZAMMAD_USER` and +`ZAMMAD_PASSWORD`, or `ZAMMAD_OAUTH2_TOKEN`), so a script needs no configuration of its +own. Anything passed in wins over the environment, credentials included — passing +`user:` and `password:` replaces a token the environment holds rather than sitting beside +it. An environment that itself sets more than one way to authenticate is refused, until an +argument says which is meant: + +```ruby +client = ZammadAPI::Client.from_env +client = ZammadAPI::Client.from_env(timeout: 300) +``` + +### Options + +| Option | Default | Description | +| ---------------- | ------------------ | ------------------------------------------------------------------ | +| `url` | *required* | Base URL. A sub-path such as `https://example.com/zammad/` works; credentials in it are refused. | +| `http_token` | `nil` | Zammad access token. | +| `oauth2_token` | `nil` | OAuth2 bearer token. | +| `user` | `nil` | Login for basic authentication. | +| `password` | `nil` | Password for basic authentication. | +| `timeout` | `60` | Seconds to wait for a response. | +| `open_timeout` | `10` | Seconds to wait for the connection. | +| `retries` | `2` | Retry attempts for a `GET` that failed transiently. `0` disables retrying. | +| `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt. No wait is longer than `timeout`. | +| `ssl_verify` | `true` | Set to `false` only against a server with a self-signed certificate. | +| `proxy` | `nil` | Proxy URL. | +| `user_agent` | `zammad_api-ruby/` | Value of the `User-Agent` header. | +| `logger` | discards output | Any `Logger`; the client logs requests and responses at `debug`. | +| `adapter` | Faraday's default | Name of the Faraday adapter to use. | +| `middleware` | `nil` | Callable that receives the Faraday connection while it is built. | + +Credentials are never written to the log, and `client.config` redacts them however it is +printed — `inspect`, `to_s` or `pp`, which is what a console shows — so a configuration +object is safe to include in an error report. + +Credentials belong in the options above, not in the URL. `https://user:secret@host/` raises +`ZammadAPI::ConfigurationError`, because the HTTP stack would send those as basic +authentication in place of the token configured beside them. + +### Checking the connection + +```ruby +client.me.email # => "agent@example.com", the account the credentials belong to +client.version # => "6.4.0", the Zammad instance's version, for an administrator +``` + +`client.me` answers for any account, so it is the check that the client can reach Zammad +and authenticate. `client.version` is the version of the Zammad instance, and Zammad serves +it to administrators only: with an agent's or a customer's credentials it raises +`ZammadAPI::AuthorizationError`. `ZammadAPI::VERSION` is the version of this gem. + +### Adapter and middleware + +The HTTP stack is Faraday's, and these two options are the seam into it — for a +persistent-connection adapter, instrumentation, or a cache: + +```ruby +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'token', + adapter: :net_http_persistent, + middleware: ->(connection) { connection.use(MyInstrumentation) } +) +``` + +The callable runs last, after this gem's own middleware and before the adapter, so it sees +requests as the client finished building them and responses before anything else does. +Faraday stays an implementation detail either way: an unregistered adapter raises +`ZammadAPI::ConfigurationError`, not a Faraday error. + +Faraday's default adapter, `net_http`, opens and closes a connection around every +request, so a walk of N pages is N TCP connections and N TLS handshakes. That is the +default because it needs no extra gem; for anything that pages, downloads attachments in a +loop, or runs a worker pool, add `faraday-net_http_persistent` to your Gemfile and pass +`adapter: :net_http_persistent` as above. Nothing else changes — the option is the whole of +it. + +Two things the seam will not take, and it says so with a `ZammadAPI::ConfigurationError` +when the client is built. One is middleware that decodes the response body, +`connection.response :json`: this gem parses JSON itself, and hands the undecoded bytes +back as the file from `attachment.download`, so a stack that has already consumed the body +leaves nothing faithful to return. The other is `connection.response :raise_error`, which +raises a Faraday error for a 4xx or 5xx before this gem sees the response: nothing would be +retried, and a missing record would arrive as `Faraday::ResourceNotFound` rather than the +`ZammadAPI::NotFoundError` your code rescues. A subclass of either is refused for what it +inherits. + +## Available resources + +`groups`, `organizations`, `tickets`, `ticket_articles`, `ticket_priorities`, +`ticket_states`, `users` + +`client.resource_names` returns the current list. + +The names are plural because what each one hands back stands for every record of its kind: +`client.tickets.each` walks them all, and `client.tickets.find(1)` picks one out. The +singular names from 1.x — `client.ticket` and the rest — still work as deprecated aliases; +see [Migrating from 1.x](#the-client). + +Anything not in that list is reachable by [declaring a resource](#resources-this-gem-does-not-model) +for it, or with [raw requests](#raw-requests). + +### Coverage + +What each major version of this gem models, set against what Zammad's API serves. A check +is a class or a method of the gem's own; an empty box is something 2.0 does not model yet. + +| | 1.x | 2.0 | +| ------------------------------------------------ | :-: | :-: | +| **Records** | | | +| Tickets | ✅ | ✅ | +| Ticket articles | ✅ | ✅ | +| Article attachments | ✅ | ✅ | +| Ticket states | ✅ | ✅ | +| Ticket priorities | ✅ | ✅ | +| Users | ✅ | ✅ | +| Organizations | ✅ | ✅ | +| Groups | ✅ | ✅ | +| Text modules | | ⬜ | +| **Ticket features** | | | +| Tags | | ⬜ | +| Links | | ⬜ | +| Mentions | | ⬜ | +| Time accounting | | ⬜ | +| Checklists | | ⬜ | +| Shared drafts | | ⬜ | +| Merge | | ⬜ | +| History | | ⬜ | +| **Knowledge base** | | | +| Knowledge bases | | ⬜ | +| Categories | | ⬜ | +| Answers, and publishing them | | ⬜ | +| Answer attachments | | ⬜ | +| Search | | ⬜ | +| **Across resources** | | | +| Global search | | ⬜ | +| CSV imports (users, organizations, text modules) | | ⬜ | + +An empty box in the 2.0 column is not out of reach: [declare a resource](#resources-this-gem-does-not-model) +for an endpoint that serves records, or use [raw requests](#raw-requests) for one that does +not. The empty boxes are also where this gem grows next — +[open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) for the one +you need, so we know what to model first. + +### Resources this gem does not model + +A resource is a class with a path. Declare one for an endpoint that serves records the way +the modelled ones do — an index, and a member under its id — and `client.resource` hands +you the same thing `client.tickets` is: + +```ruby +class Role < ZammadAPI::Resources::Base + path 'api/v1/roles' +end + +roles = client.resource(Role) + +roles.each { |role| puts role.name } # paginated, like any other +roles.find(2).update(note: 'Reviewed') # change tracking and save +roles.create(name: 'Auditor') +roles.find_by(name: 'Agent') +``` + +Say what else is true of the endpoint, where it differs from the defaults: -Individual resources can be created, modified, saved, and destroyed. +| Declaration | Default | Says | +| ------------------ | ------- | -------------------------------------------------------------------- | +| `path '…'` | *required* | The index endpoint, relative to the instance URL. | +| `searchable true` | `false` | Zammad routes `/search`, so `search` works and `find_by` uses it. | +| `search_filters :role_ids` | none | What that search narrows by besides the term, `condition:` and `ids:`. `search` refuses any other keyword. | +| `max_per_page 100` | `1000` | The largest page the index endpoint serves. | +| `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. | +| `belongs_to :role, class_name: 'Role'` | — | A foreign key, read as a record through `record.related.role`. | +| `has_many :members, class_name: 'User', path: ->(id) { "…/#{id}" }` | — | A list served whole by an endpoint of its own. | -### Create object +`class_name` is a resource of this gem by its own name, `'User'`, or a class of yours by its +full name, `'Acme::Role'`. A subclass of a modelled resource works too, and inherits what +its parent declares: `class MyTicket < ZammadAPI::Resources::Ticket`. + +Use raw requests for an endpoint that is not shaped like that — an action, a report, a +setting. + +## Raw requests + +`get`, `post`, `put` and `delete` reach any endpoint of the Zammad API, without giving up +authentication, timeouts, retries, credential redaction, JSON decoding or the error +classes. Use them for the endpoints that are not a list of records, and for a one-off call +to one that is. + +```ruby +client.get('api/v1/roles').body +# => [{id: 1, name: "Admin", ...}, ...] + +client.post('api/v1/tags/add', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) +client.put('api/v1/roles/2', body: {note: 'Updated'}) +client.delete('api/v1/tags/remove', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) +``` + +All four take `headers:`, for an endpoint that needs one: + +```ruby +client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) +``` + +Names are case-insensitive, and two spellings of one header are refused rather than merged. +`Authorization` and `From` are refused outright: the first is what the client's credentials +are for, the second is what `on_behalf_of` sets, and replacing either from a single request +would leave the client reporting something it no longer does. + +Each returns a `ZammadAPI::Response`, so the status and headers stay reachable: -With new and save: ```ruby -group = client.group.new( - name: 'Support', - note: 'Some note', -); +response = client.get('api/v1/tickets') +response.status # => 200 +response.headers['content-type'] +response.body # decoded JSON, or the raw body for anything else +response.raw_body # the bytes as they arrived +response.json? # => whether the body was decoded +``` + +Zammad reports the size of a result in the body rather than in a header, and only +where you ask for it: `only_total_count=true` or `with_total_count=true` on a `/search` +endpoint, and `full=true` on the index endpoints that render through +`model_index_render`. `count` on a search collection uses the first of those. + +Paths are relative to the instance URL, and a leading slash is ignored, so they can be +pasted straight from the Zammad documentation. An absolute URL raises `ArgumentError`: the +client's credentials only ever go to the instance it was configured for, so a link taken +from a response body has to be reduced to its path first. A path is written the way a URL +is, so a space or a character outside ASCII has to be percent-encoded, `t%C3%A4gs` for +`tägs`; one that cannot be read as a URL raises `ArgumentError` too, before anything is +sent or logged. A non-2xx response raises the same error class it would raise for a +modelled resource, and only a `GET` is retried. + +## Working with records + +### Create + +```ruby +group = client.groups.new(name: 'Support', note: 'Some note') group.save -group.id # id of record -group.name # 'Support' +group.id # => 42 +group.name # => "Support" ``` -With create: +Or in one call: + ```ruby -group = client.group.create( - name: 'Support', - note: 'Some note', -); +group = client.groups.create(name: 'Support', note: 'Some note') +``` + +### Fetch -group.id # id of record -group.name # 'Support' +```ruby +group = client.groups.find(42) +group.name # => "Support" +group[:name] # same, and nil rather than an error when it is absent +group.fetch(:name) # raises KeyError if the attribute is absent +group.key?(:name) # => true +group.to_h # every attribute, as a Hash you may modify ``` -### Fetch object +Or by attribute value: ```ruby -group = client.group.find(123) -puts group.inspect +client.users.find_by(email: 'someone@example.com') # => the record, or nil +client.users.find_by!(email: 'nobody@example.com') # raises NotFoundError +client.groups.exists?(42) # => true ``` -### Update object + +`find_by` answers with the first record that carries those values, and `nil` if it finds +none, on every resource and for any kind of value. Zammad cannot be asked that directly, +because its index endpoints cannot filter — see [Narrowing](#narrowing) — so `find_by` +fetches candidates and checks them itself. A record it returns genuinely carries the +attributes you asked for, compared exactly and against the value as Zammad stores it, so +`find_by(email: 'Someone@Example.com')` does not match a login Zammad downcased. What a +`nil` means depends on how the candidates were fetched: after a walk, that no record this +client can read carries the values; after a search, that no hit does, and a search reads +less than the whole record, as described below. + +There are two ways it fetches the candidates, and they cost differently: ```ruby -group = client.group.find(123) +client.users.find_by(email: 'someone@example.com', active: true) # searches the email, matches both +client.users.find_by(firstname: 'Jane', lastname: 'Doe') # searches "Jane", matches both +client.ticket_states.find_by(name: 'open') # no search endpoint: walks the list +client.users.find_by(organization_id: 5) # no string to search on: walks the index +``` + +A search is the cheap way, and is used wherever the resource has a search endpoint and one +of the values is a string. The term is one string value, because Zammad matches words: a +value of another type would go out as the word it prints as, so `active: true` would look +for records containing `"true"`. Every other value is matched against the hits. + +Everywhere else `find_by` walks the index, a page at a time, until a record matches. That +is one request for a list of ticket states. Against every user or ticket on an instance it +is a request per page until the match, and the whole index for a miss — the same walk +`all.detect { ... }` makes, so give `find_by` a string to search on where there is one. + +The values are never joined into one term. An instance searching without Elasticsearch +matches the term literally, through a SQL `LIKE` over each string column, so `"Jane Doe"` +would ask for a single column containing the whole of it and match nobody. + +`find_by` reads the hits a page at a time until one matches, so a match usually costs one +request and a miss costs one per page of hits. It cannot stop at the first page: Zammad's +search sorts by `updated_at`, newest first, rather than by relevance, so where a few +hundred records contain the term the one that carries it exactly can be on any page. + +What the search can surface is Zammad's business: a value the instance has not indexed, or +cannot index, is a record `find_by` will not find. `find_by(...) || create(...)` can +therefore still create a duplicate — as writing the search out by hand would. + +Which values those are depends on the instance. With Elasticsearch the term is looked for +in everything a record is indexed with. Without it, Zammad reads a fixed set of columns: + +| Resource | What a search without Elasticsearch reads | +| ----------------------------------- | -------------------------------------------------------------- | +| `users`, `organizations`, `groups` | The string columns of the record's own table. | +| `tickets` | The title and number, and the from, to, subject and body of the ticket's articles. | + +Neither reads a name `expand` adds for an association, which is not a column, and a ticket +search reads no other attribute of the ticket. So on such an instance these look for the +word in fields that do not hold the value. They find the record only where the word +happens to appear in one of those fields as well, and otherwise answer `nil` for a record +that exists: + +```ruby +client.tickets.find_by(state: 'open') # the state is not among what a ticket search reads +client.tickets.find_by(external_ref: 'SO-1001') # nor is a custom attribute of a ticket +client.users.find_by(organization: 'Acme') # a name expand adds, not a column +``` + +`find_by` does not walk the index after a search that found nothing. A miss is the ordinary +case for `find_by(email: ...) || create(...)` on an address that is new, and that walk would +read every user on the instance to confirm it, a thousand to the request. Nothing in a +response says which backend answered, so `find_by` cannot tell that miss from one caused by +a field the search does not read. You can, and the walk is one word away: + +```ruby +client.tickets.detect { it[:state] == 'open' } # walks the index: every ticket this client may read +client.tickets.search('printer', condition: {'ticket.state_id' => {operator: 'is', value: [2]}}) +``` + +The walk compares `it[:state]`, as `find_by` does, and not `it.state`. Every record the +client may read goes through the block, and a reader raises for an attribute the record in +hand does not carry, which would end the walk on that record rather than pass it over. A +user without an organization carries no `organization`, and Zammad serves a reduced record +where the client may not see the whole of one. What the walk cannot find is a record the +client may not read, or a value on a record it only sees reduced. + +Zammad records can carry administrator-defined custom attributes, so readers are resolved +against the attributes the record arrived with rather than declared ahead of time. A reader +for an attribute the record does not carry raises `NoMethodError`, naming what it does +carry — a typo is not worth a silent `nil` that flows on into whatever you write with it: + +```ruby +group.titel # NoMethodError: undefined attribute titel for ... +group[:titel] # => nil +group.fetch(:titel, nil) # => nil +group.key?(:titel) # => false +``` + +That matters beyond typos: Zammad serves a reduced object where the authenticated user may +not see the whole record, so an attribute that exists in Zammad can be missing here. The +message says so. Use `[]`, `fetch` with a default, or `key?` wherever an attribute may +legitimately be absent. + +`attributes` and `changes` are deeply frozen, because a record that let you write into +them would report a change it had never staged and would not send: + +```ruby +group.attributes[:name] = 'Support 2' # FrozenError +group.name = 'Support 2' # the way to stage a change +group.to_h # a deep copy, yours to modify +``` + +### Pattern matching + +Records implement `deconstruct_keys`, so they work with `case/in`: + +```ruby +case client.tickets.find(1) +in {state: 'closed'} + nil +in {state: String => state, priority: '3 high'} + escalate(state) +in {group: {name: 'Support'}} + notify_support +end +``` + +`Config` and `Response` are `Data` objects, so their members match too: + +```ruby +case client.config +in {http_token: String} + :token_auth +in {user: String, password: String} + warn 'prefer an access token over basic auth' +end +``` + +### Update + +```ruby +group = client.groups.find(42) group.name = 'Support 2' -group.save + +group.changed? # => true +group.changes # => {name: ["Support", "Support 2"]} + +group.save # sends only the changed attributes ``` -### Destroy object +A `save` on a persisted record with nothing staged sends no request at all and returns +`true`. Zammad applies an empty update, bumping `updated_at` and `updated_by`, so a no-op +save would otherwise rewrite the record's audit trail. + +Writing back the value a record was loaded with is not a change, so it stages nothing. +Writing an attribute the record does not carry always is one, even when the value is `nil`: +Zammad reduces the object it serializes for a permission-scoped client, so a key being +absent says nothing about what is stored, and `group.note = nil` is a request to store +`nil` rather than a write to drop. + +Or in one call: ```ruby -group = client.group.find(123) -group.destroy +group.update(name: 'Support 2', note: 'Renamed') # assigns, then saves +group.assign_attributes(name: 'Support 3') # assigns without saving ``` -## Collection management +### Saving and validation failures + +`save` returns whether the record was stored, and leaves a rejection in `error`: -A list of individual resources. +```ruby +group = client.groups.new(name: '') -### All +if group.save + puts group.id +else + warn group.error.server_message # => "Name is required" +end +``` + +Only a rejection of the attributes (HTTP 422) is reported that way. An expired token, a +missing record or an unreachable instance still raises, because those are not something +the calling code can correct by fixing an attribute. + +`save!` and `update!` raise on every failure, including validation, which is what you want +in a script: ```ruby -groups = client.group.all +group.save! # raises ZammadAPI::ValidationError +group.update!(name: '') # the same, in one call +``` + +`client.groups.create(...)` uses `save!`, so it raises rather than handing back a record +that looks created but is not. Use `new` plus `save` when you need to branch instead. -group1 = groups[0] -group1.note = 'Some note' -group1.save +### Associations -groups.each {|group| - p "group: #{group.name}" -} +Zammad expands an association into a name under the plain attribute, so those reads are +already loaded and free: + +```ruby +ticket = client.tickets.find(1) + +ticket.customer # => "customer@example.com" +ticket.state # => "open" +ticket.group # => "Users" +ticket.customer_id # => 7 ``` -### Search +`related` reaches the whole record behind one of those, which costs a request: + ```ruby -groups = client.group.search(query: 'some name') +ticket.related.customer.firstname # => "Nicole" +ticket.related.group.note +ticket.related.articles # => [TicketArticle, ...] +ticket.related.created_by.email + +client.users.find(7).related.organization +``` + +A `has_many` reader such as `articles` is the one list here that is read in a single +request and comes back as an Array rather than a paginating collection, because the +association endpoints Zammad routes serve the whole list: `ticket_articles/by_ticket` +renders every article of the ticket and takes no paging parameter. -group1 = groups[0] -group1.note = 'Some note' -group1.save +A ticket's articles are also reachable without `related`, and `add_article` writes one: -groups.each {|group| - p "group: #{group.name}" -} +```ruby +ticket.articles # the same list +ticket.add_article(body: 'Reset link sent.', type: 'note') # => the created TicketArticle ``` -### All with pagination (beta) +The readers live under `related` rather than on the record so that `ticket.customer` keeps +returning the name it always did — an attribute read that silently became an HTTP request +would be a poor trade. `belongs_to` targets are memoized, and `reload`, a save or a write +to the foreign key drops the memo; `has_many` lists are fetched each call, so an article +added in between shows up. A record hands out the same `related` every time, so one kept in +a variable follows the record too: after `related = ticket.related` and +`ticket.customer_id = 9`, `related.customer` is user 9. +`Ticket.associations` lists what a resource declares. + +### Comparing and serializing + +A record is the Zammad record it came from, not the object that happens to hold it, so two +records of the same kind carrying the same id, read from the same Zammad, are equal. That +makes `uniq`, `Set`, `include?` and records-as-Hash-keys behave: ```ruby -groups = client.group.all +client.tickets.find(1) == client.tickets.find(1) # => true + +[client.tickets.find(1), client.tickets.find(1)].uniq.size # => 1 +Set[client.tickets.find(1), client.tickets.find(1)].size # => 1 +seen = { client.tickets.find(1) => :handled } +seen[client.tickets.find(1)] # => :handled +``` -groups.page(1,3) {|group| - p "group: #{group.name}" +A record with no id is equal only to itself, because two unsaved records are two records +waiting to be created however alike their attributes are. One consequence: a record's first +save assigns its id and so changes its hash, and a record used as a Hash key before that +save has to be rehashed after it. - group.note = 'Some new note, inclued in page 1 with 3 per page' - group.save -} +Which Zammad a record came from is the `url` its client was configured with. A script that +reads two instances, such as a migration or a sync, therefore keeps ticket 1 of each apart, +while two clients for one URL, or a client and its `on_behalf_of` scope, hold the same +record. -groups.page(2,3) {|group| - p "group: #{group.name}" +`to_json` renders the attributes, so a record can be cached, queued or logged as it stands, +and nests inside a structure being generated: - group.note = 'Some new note, inclued in page 2 with 3 per page' - group.save -} +```ruby +client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}" +JSON.generate(group: client.groups.find(1)) ``` -### Search with pagination (beta) +`as_json` returns the same attributes as a Hash, for ActiveSupport and any encoder that +follows its convention. + +### Reload and destroy + ```ruby -groups = client.group.search(query: 'some name') +group.reload # re-reads from Zammad, discarding unsaved changes +group.destroy # => true -groups.page(1,3) {|group| - p "group: #{group.name}" +group.destroyed? # => true +group.persisted? # => false, so this is not the inverse of new_record? +group.save # raises: the record is gone, and a PUT would only 404 +group.update(...) # raises too, and stages nothing, so the record stays unchanged +group.name = 'X' # raises as well: a destroyed record reads as it last was in Zammad - group.note = 'Some new note, inclued in page 1 with 3 per page' - group.save -} +client.groups.destroy(42) # delete by id, without fetching first +``` -groups.page(2,3) {|group| - p "group: #{group.name}" +## Collections - group.note = 'Some new note, inclued in page 2 with 3 per page' - group.save -} +`all`, `order` and `search` return a lazily paginated `ZammadAPI::Collection`. No request +is made until you iterate, and pages are fetched as needed. + +A resource proxy is itself `Enumerable` over `all`, so `.all` is optional: + +```ruby +client.tickets.each { |ticket| puts ticket.title } +client.tickets.first(5) +client.tickets.pluck(:title) +client.tickets.find_each(batch_size: 50) { |ticket| archive(ticket) } ``` -## Perform actions on behalf of another user +`find` keeps its own meaning there — `client.tickets.find(1)` is a lookup by id, not +`Enumerable#find`. Use `detect` for the block form. + +```ruby +# Walks every page automatically. +client.tickets.all.each do |ticket| + puts ticket.title +end -As described in the [Zammad API documentation](https://docs.zammad.org/en/latest/api/intro.html#actions-on-behalf-of-other-users) it is possible to perfom actions on behalf other users. To use this feature you can set the attribute of the client accordingly: +# Stops after the first page, because Enumerable stops consuming. +first_five = client.tickets.all.first(5) -> **Note:** This feature requires Zammad 5.0 or later, since the client sends the standard HTTP `From` header instead of the deprecated `X-On-Behalf-Of` header (see [zammad/zammad#3113](https://github.com/zammad/zammad/issues/3113)). +# Lazy chains work as expected. +client.tickets.all.lazy.select { |t| t.state == 'open' }.first(10) + +# One array of records per request, e.g. for a bulk import. +client.tickets.all.in_batches(of: 50) do |tickets| + import(tickets) +end + +# Record by record, with the page size set inline. +client.tickets.all.find_each(batch_size: 50) do |ticket| + archive(ticket) +end +``` + +### Sorting + +`order` sorts on the server: + +```ruby +client.groups.order(:name) # ascending +client.organizations.order(name: :desc) +client.groups.order(:active, name: :desc) # by active, then by name descending +client.tickets.search('state.name:open').order(created_at: :desc) +``` + +An attribute on its own sorts ascending and a keyword says which way one runs, as in +ActiveRecord. A second `order` sorts within the first, so +`order(:active).order(name: :desc)` is the third line above. + +Not every endpoint sorts. `/api/v1/tickets` and `/api/v1/users` are always served in id +order — their controllers hardcode it and drop `sort_by` along with everything else they +do not read — so `order` on those raises `ArgumentError` rather than handing back records +it would be calling sorted. A search sorts for every resource that can be searched: ```ruby -client.on_behalf_of = 'some_login' +client.tickets.order(:title) +# ArgumentError: api/v1/tickets is always served in the same order and ignores sort_by, +# so order would hand back the records as they were. A search does sort: ... + +client.tickets.search('state.name:open').order(:title) ``` -All following actions with the client will be performed on behalf of the user with the `login` "some_login". +### Narrowing + +**Zammad's index endpoints do not filter.** `ApplicationController#model_index_render` +sorts and pages and drops every other parameter. Filtering by an attribute value exists +only on the `/search` endpoints, which is why a collection has no `where`: there is nothing +an index endpoint would do with what it was given. -To reset this back to regular requests just set `nil`: +Narrow by a value with [`find_by`](#fetch) for one record, or `search` for many: ```ruby -client.on_behalf_of = nil +client.users.find_by(email: 'someone@example.com') +client.tickets.search('state.name:open').first(10) ``` -It's possible to perform only a block of actions on behalf of another user via: +`search` also takes the other things a search endpoint narrows by, as keywords: +`condition:` and `ids:` on every search, and `role_ids:`, `group_ids:` and `permissions:` +on users, the one search that reads them: ```ruby -client.perform_on_behalf_of('some_login') do - # ticket is created on behalf of the user with - # the login "some_login" - client.ticket.create( - ... - ) +client.users.search('smith', role_ids: [2]) +client.users.search('smith', group_ids: [1], permissions: ['ticket.agent']) +client.users.search('smith', group_ids: {1 => ['read']}) +client.tickets.search('printer', condition: {'ticket.state_id' => {operator: 'is', value: [1, 2]}}) +client.tickets.search('printer', condition: {'ticket.group_id' => {operator: 'is', value: [2]}}) +``` + +A `condition` may nest groups of conditions, the form Zammad calls expert mode: + +```ruby +client.tickets.search('printer', condition: { + operator: 'OR', + conditions: [ + {name: 'ticket.state_id', operator: 'is', value: [2]}, + {operator: 'AND', conditions: [ + {name: 'ticket.group_id', operator: 'is', value: [1]}, + {name: 'ticket.priority_id', operator: 'is', value: [3]} + ]} + ] +}) +``` + +A query string does not mark where one element of a list ends, and Rails begins a new one +only at a key the element before it has too. The elements above all carry `operator`, and +the client writes that first, so they arrive as written. A list whose elements share no +such key, a list directly inside a list, an empty Hash inside a list and a key with an empty +name cannot be carried at all and raise `ArgumentError`; the JSON body of `client.post` takes +any structure. + +`group_ids:` narrows to the agents with access to a group, and its two forms ask for +different access. A list of ids names no access, and Zammad reads that as `full`: +`group_ids: [1]` leaves out an agent who may only read group 1. A Hash names the access +for each group — `read`, `create`, `change`, `overview` or `full`, one or several — and +an agent with `full` access always counts: `group_ids: {1 => ['read']}` is every agent +with `read` or `full` access to group 1. Access granted through a role counts like access +granted to the user, and an agent matching any one of the groups is kept. + +`permissions:` is not an access check. Zammad resolves it to the roles that grant one of +the permissions and adds those to `role_ids:`, so the two together keep a user with any +of the roles, not one with both. And where the instance searches through Elasticsearch, a +permission that no active role grants resolves to no role at all, and Zammad then leaves +the filter out: `permissions: ['ticket.agnet']`, or a permission nobody has been given, +comes back with every user matching the term. Without Elasticsearch the same search is +empty, and nothing in the response says which of the two answered. `role_ids:` narrows +on both. + +`role_ids:` is not an access check either. It asks who holds a role, and Zammad does not +ask whether the role still grants anything: a user matches a role that has been disabled, +and a user who has been deactivated matches as well, though neither can do what the role +allowed. So the hits are candidates. Where the result decides what someone may do, check +each one: the user's `active`, and the `active` and the permissions of the roles in +their `role_ids`, which `client.resource` reaches at `api/v1/roles`. + +Any other keyword raises `ArgumentError`. Zammad drops a parameter it does not know, so +`search('smith', active: true)` would come back unnarrowed with nothing to say so; an +attribute value goes in the term, a sort in `order`, and paging in `page`, `in_batches` or +`find_each`. A user keyword on another resource raises for the same reason: Zammad takes +`group_ids` on a ticket search and drops it, so tickets are narrowed by group with the +condition above. A `nil` value raises too: there is no query string that means "this field +is null". So does a keyword with nothing in it, such as `ids: []`, `condition: {}`, or a +condition that holds nothing but empty Hashes, which a query string does not write. Zammad +reads that as the keyword not having been given, so `search('smith', ids: allowed_ids)` +with no id allowed would come back with every user matching the term rather than none. + +Zammad routes a search endpoint per model, not for every model. `users`, `organizations`, +`tickets` and `groups` have one; `ticket_states`, `ticket_priorities` and `ticket_articles` +do not, and `search` on those raises `ZammadAPI::Error` rather than reaching a 404 that +would read as a missing record. `find_by` works on them all the same, by walking the list: + +```ruby +client.ticket_states.find_by(name: 'open') +client.ticket_priorities.select { it.active } +``` + +### Search + +```ruby +client.organizations.search('zammad').each do |organization| + puts organization.name end +``` + +A term with nothing in it, Unicode spaces included, raises `ArgumentError`: Zammad reads it +as no term at all and answers with every record, which a search for an empty form field +should not come back with. `search('*')` asks for every record in so many words, and is +sent; it is how Zammad's own interface lists users, and the keywords above still narrow it. -# further actions are performed regularly. +### Explicit pages + +```ruby +tickets = client.tickets.all + +tickets.page(2) # page 2 at the size the endpoint serves +tickets.page(2, per_page: 10) # records 11 to 20 ``` -## Examples +Collections are immutable: `order` and `page` return a new collection and leave the +original untouched. -Create a ticket: -```ruby -ticket = client.ticket.create( - title: 'a new ticket #1', - state: 'new', - group: 'Users', - priority: '2 normal', - customer: 'some_customer@example.com', - article: { - content_type: 'text/plain', # or text/html, if not given test/plain is used - body: 'some body', - # attachments can be optional, data needs to be base64 encoded - attachments: [ - 'filename' => 'some_file.txt', - 'data' => 'dGVzdCAxMjM=', - 'mime-type' => 'text/plain', - ], - }, -) +### Page size + +A request fetches as many records as the endpoint will serve — 100 for `/api/v1/tickets`, +200 for a search, 1000 for the other index endpoints — so a walk spends as few round trips +as it can. Three calls take another size, each for its own kind of work: -ticket.id # id of record -ticket.number # uniq number of ticket -ticket.title # 'a new ticket #1' -ticket.group # 'Support' -ticket.created_at # '2022-01-01T12:42:01Z' -# ... +```ruby +client.tickets.all.find_each(batch_size: 50) { |ticket| archive(ticket) } # walking +client.tickets.all.in_batches(of: 50) { |tickets| import(tickets) } # batching +client.tickets.all.page(2, per_page: 100) # one page ``` -List all new or open tickets: +`find_each` without a block is an Enumerator, so it is also how you read at a chosen page +size: `client.tickets.all.find_each(batch_size: 50).first(7)`. + +`page` and a batch size are two ways of naming the same thing, so combining them raises: +`page(3, per_page: 50)` already says which records the collection holds, and re-sizing it would +quietly hand back different ones. Size the page itself, or slice with `each_slice`. + +That cap is also the ceiling. `find_each` and `in_batches` are reduced to it: a +batch size is how much to fetch at a time, so a smaller one costs more requests and still +yields every record. `page` raises instead, because a page size also says *which* records +you get — `page(3, per_page: 500)` reduced to 100 hands back records 201 to 300 rather than 1001 +to 1500. So `in_batches(of: 500)` over tickets yields batches of 100, while +`page(3, per_page: 500)` over tickets is refused. +A walk learns the size the endpoint actually serves from the first page rather than trusting +that cap, so an instance that pages smaller than expected is walked to the end rather than +truncated at the first short page. +That keeps a walk complete: a page size the server silently shrank would otherwise end the +iteration at the first page. + +A search is walked until a page comes back empty, whatever the size of the pages before it. +Zammad has the search name the ids for a page and then loads those records, so a record +deleted in between, or one Elasticsearch still lists after it was removed, leaves the page +short with more hits behind it. A short page therefore ends the walk of an index and not of +a search, which costs a search one more request where its last page of hits is part-filled. + +A page can come back with nothing on it for the same reason, and on the page of one that +`first` and `empty?` ask for, one stale hit is enough — at the top of the result, since a +search serves the newest first. So a search that is walked asks Zammad for the size of the +whole result beside each page, with `with_total_count`, and an empty page ends the walk +only once the pages read have covered that many hits. The total is never what ends a walk +on a page that still held records. + +Three limits remain, and at each an empty page ends the walk whatever is behind it. A +Zammad before 6.5.1 does not report the total beside expanded records. Elasticsearch stops +counting at ten thousand hits, so past that many a page of stale hits reads as the end. And +the pages read are reckoned at the size that was asked for, 200 hits unless a batch size +says otherwise: an instance that serves a search in smaller pages than that has covered +fewer hits than the walk takes it to have. Asked for 200 and served 50, an empty first page +beside a total of 150 reads as the end, with the hits from the 51st on unread. On such an +instance `first`, `take` and `empty?` can also miss hits behind stale ones, since the +larger pages they ask for past an empty one (see below) are served from other positions +than the ones asked for. A hit served twice that way is handed back once. Zammad itself +serves a search 200 at a time. + +`first` and `take` size their own request rather than taking records off the front of one +sized for walking, so the cheap-looking call is cheap: + ```ruby -tickets = client.ticket.search(query: 'state.name:new OR state.name:open') +client.tickets.all.first # one request, for one record +client.tickets.all.first(5) # one request, for five +client.tickets.all.take(5) # the same, and the same cost +``` + +They size the request, not the collection, so they still read on where a page comes back +shorter than it was asked for — `first(5)` answers with five records if five exist, however +the endpoint chooses to page them. A collection `page` already limited keeps its own size, +since that size says which records it holds. + +On a search, the size is where the read starts and not what it is held to. Past a page with +nothing on it and hits still behind it, `first`, `take` and `empty?` ask for more at a +time, each page starting where the last one ended, up to the 200 a search serves and never +past the total it reported. Held to a page of one they paid a request for every stale hit +in a row, which is thousands of them where an Elasticsearch index has drifted from the +database. Held to the total, they stay inside an index whose result window was lowered +below the hits there are, which refuses a page reaching past it and is answered as no hits +at all. A batch size you chose, with `in_batches(of:)` or `find_each(batch_size:)`, is +never changed. + +### Reading single attributes + +```ruby +client.users.all.pluck(:email) # => ["a@example.com", ...] +client.tickets.all.pluck(:id, :title) # => [[1, "Help"], ...] +``` + +Zammad cannot be asked for a subset of the fields, so this shapes the result rather than +shrinking the request. + +### Counting + +`count` is one request on a search, which Zammad can answer without serving the records. +Every other endpoint has to be walked, because an index endpoint offers nothing cheaper: +`model_index_render` reads `sort_by`, `order_by` and the paging and drops every other +parameter, so it has no answer for `only_total_count` and no total to report. + +```ruby +client.tickets.search('state.name:open').count # one request +client.tickets.all.count # one request per page +``` + +`size` and `length` are `count`, and cost the same. `empty?` and `first` ask for a single +record rather than a page: + +```ruby +client.tickets.search('state.name:merged').empty? # one request, for one record +client.groups.all.size # => 12, having walked +``` + +A block or an argument is `Enumerable#count` counting matches, and walks either way: + +```ruby +client.tickets.all.count { it.state == 'open' } # walks every page +``` + +Nothing is cached, so every traversal of a collection fetches again. + +### `find` is a lookup, not a filter + +`find` on a resource takes an id. On a collection it is `Enumerable#find`, which takes a +block — and its argument is an ifnone callable, not an id, so passing one is refused rather +than answered with an Enumerator and no request: + +```ruby +client.tickets.find(1) # the lookup by id +client.tickets.all.detect { ... } # the block form +client.tickets.all.find { ... } # the same +client.tickets.all.find(1) # ArgumentError, naming both of the above +``` + +## Deriving clients + +A client is immutable. `with` returns a new one with some options changed, re-validating +them and carrying over any `on_behalf_of` scope: + +```ruby +bulk = client.with(timeout: 300, retries: 5) +bulk.tickets.all.each { |ticket| archive(ticket) } +``` + +Naming credentials replaces the ones the client has, whichever kind they were, so +`client.with(oauth2_token: '…')` on a client built with an access token authenticates with +the OAuth2 token alone. + +Because nothing is mutated after construction, one client — and any client derived from it — +is safe to use from several threads at once. -ticket[0].id # id of record -ticket[0].number # uniq number of ticket -ticket[0].title # 'title of ticket' -ticket[0].group # 'Support' -ticket[0].created_at # '2022-01-01T12:42:01Z' +## Acting on behalf of another user -tickets.each {|ticket| - p "ticket: #{ticket.number} - #{ticket.title}" -} +As described in the [Zammad API documentation](https://docs.zammad.org/en/latest/api/intro.html#actions-on-behalf-of-other-users), +actions can be performed on behalf of another user. `on_behalf_of` returns a **new** +client, so the original is unaffected and both are safe to use concurrently. + +```ruby +support = client.on_behalf_of('agent@example.com') +support.tickets.create(title: 'Help', group: 'Users', customer_id: 1) ``` -Get all articles of a ticket: +Or scoped to a block: + ```ruby -ticket = client.ticket.find(123) -articles = ticket.articles +client.on_behalf_of('agent@example.com') do |scoped| + scoped.tickets.find(1) +end +``` -articles[0].id # id of record -articles[0].from # creator of article -articles[0].to # recipients of article -articles[0].subject # article subject -articles[0].body # text of message -articles[0].content_type # text/plain or text/html of .body -articles[0].type # 'note' -articles[0].sender # 'Customer' -articles[0].created_at # '2022-01-01T12:42:01Z' +The identifier can be a login, an email address or a user id. This sends the standard +HTTP `From` header and requires Zammad 5.0 or later. + +An identifier that is `nil`, empty or blank raises `ArgumentError`. Zammad reads a `From` +header with nothing in it as no header at all, so `client.on_behalf_of(user&.login)` with +no user would otherwise perform every request as the account the client authenticates +as, and read everything that account can see. + +## Error handling + +Every error descends from `ZammadAPI::Error`. + +```text +ZammadAPI::Error +├── ZammadAPI::ConfigurationError invalid client options +├── ZammadAPI::UnknownResourceError no such resource, e.g. client.unicorn +├── ZammadAPI::ParseError unexpected response shape +├── ZammadAPI::PaginationError endpoint ignored the page parameter +├── ZammadAPI::TransportError +│ ├── ZammadAPI::ConnectionError unreachable host or TLS failure +│ └── ZammadAPI::TimeoutError exceeded timeout or open_timeout +└── ZammadAPI::ResponseError carries the HTTP response + ├── ZammadAPI::ClientError 4xx + │ ├── ZammadAPI::AuthenticationError 401 + │ ├── ZammadAPI::AuthorizationError 403 + │ ├── ZammadAPI::NotFoundError 404 + │ ├── ZammadAPI::ValidationError 422 + │ └── ZammadAPI::RateLimitError 429 + └── ZammadAPI::ServerError 5xx +``` -p "ticket: #{ticket.number} - #{ticket.title}" -articles.each {|article| - p "article: #{article.from} - #{article.subject}" -} +```ruby +begin + client.tickets.find(1) +rescue ZammadAPI::NotFoundError + nil +rescue ZammadAPI::RateLimitError => e + # The client already waited and retried, so this limit outlasted that. + reschedule(in: e.retry_after || 60) +rescue ZammadAPI::ResponseError => e + warn "#{e.status}: #{e.server_message}" + warn e.body.inspect +end ``` -Create an article for a ticket: +`ResponseError` exposes `status`, `body`, `headers`, `server_message`, `operation` and +`resource_class`. A proxy that returns an HTML error page instead of JSON produces a +`ServerError` describing the status, not a JSON parse failure. + +### Timeouts and retries + +A `GET` is retried on connection failures, timeouts and the transient statuses 429, 500, +502, 503 and 504, with exponential backoff. + +A `Retry-After` header on one of those responses is honoured: the client waits as long as +the server asked before the next attempt, up to `timeout` seconds. A longer one is not +waited out. The request fails at once with the error for its status, and +`RateLimitError#retry_after` carries the figure, so a job can reschedule itself rather +than hold a thread for however long a maintenance page suggests. + +A write is never retried. `POST` would create a second record, and `PUT` and `DELETE` are +not safe to repeat against Zammad either, whatever HTTP says about them: a ticket update +carrying an `article` adds that article — and sends its e-mail — once per delivery, and a +`DELETE` repeated after a lost answer comes back as a 404 for a record that was just +deleted. So a write that fails raises, and the code that knows what the request carried +decides whether to send it again: + ```ruby -ticket = client.ticket.find(123) +begin + ticket.update!(state: 'closed') +rescue ZammadAPI::TransportError, ZammadAPI::ServerError + ticket.reload # did it arrive? + retry if ticket.state != 'closed' +end +``` -article = ticket.article( - type: 'note', - subject: 'some subject 2', - body: 'some body 2', - # attachments can be optional, data needs to be base64 encoded - attachments: [ - 'filename' => 'some_file.txt', - 'data' => 'dGVzdCAxMjM=', - 'mime-type' => 'text/plain', - ], +```ruby +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'token', + timeout: 10, + retries: 5 ) +``` -article.id # id of record -article.from # creator of article -article.to # recipients of article -article.subject # article subject -article.body # text of message -article.content_type # text/plain or text/html of .body -article.type # 'note' -article.sender # 'Customer' -article.created_at # '2022-01-01T12:42:01Z' -article.attachments.each { |attachment| - attachment.filename # 'some_file.txt' - attachment.size # 1234 - attachment.preferences # { :"Mime-Type"=>"image/jpeg" } - attachment.download # content of attachment / extra REST call will be executed -} - -p "article: #{article.from} - #{article.subject}" -``` - -Create an article with html and inline images for a ticket: -```ruby -ticket = client.ticket.find(123) - -article = ticket.article( - type: 'note', - subject: 'some subject 2', - body: 'some body with an image Red dot', - content_type: 'text/html', # optional, default is text/plain +## Logging + +```ruby +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'token', + logger: Logger.new($stdout) ) +``` + +Requests, response statuses and durations are logged at `debug` level. Payload keys, query +parameters and headers that look like credentials (`password`, `token`, `secret`, `cookie`, +...) are redacted. That holds for a query string written into the path of a raw request, +in the log and in the message of an error the request raises, and for a body handed over +as a String where it is JSON. A String body that is not JSON is not logged, only its size. + +## Testing code that uses this client + +`zammad_api/test` ships a stand-in Zammad, so your own tests need no HTTP interception: + +```ruby +require 'zammad_api/test' -article.id # id of record -article.from # creator of article -article.to # recipients of article -article.subject # article subject -article.body # text of message -article.content_type # text/plain or text/html of .body -article.type # 'note' -article.sender # 'Customer' -article.created_at # '2022-01-01T12:42:01Z' -article.attachments.each { |attachment| - attachment.filename # '122.146472496@www.znuny.com' - attachment.size # 1167 - attachment.preferences # { :'Mime-Type'=>'image/jpeg', :'Content-ID'=>'122.146472496@www.znuny.com', :'Content-Disposition'=>'inline'} } - attachment.download # content of attachment / extra REST call will be executed -} +RSpec.describe TicketCloser do + let(:zammad) { ZammadAPI::Test.new } -p "article: #{article.from} - #{article.subject}" + it 'closes the ticket' do + zammad.stub(:get, 'api/v1/tickets/1', body: {id: 1, title: 'Help', state: 'open'}) + zammad.stub(:put, 'api/v1/tickets/1', body: {id: 1, state: 'closed'}) + + described_class.new(zammad.client).close(1) + + expect(zammad.requests.last.verb).to eq(:put) + expect(zammad.requests.last.body).to eq({state: 'closed'}) + end +end ``` -## Testing +`zammad.client` is a real `ZammadAPI::Client`, so responses come back through the same +decoding, error mapping and record building as real ones — a stub with `status: 404` +raises `NotFoundError`, and one with `status: 422` makes `save` return `false`. + +| Method | What it does | +| ------ | ------------ | +| `stub(verb, path, status:, body:, headers:, query:)` | Declares a response. Stubbing the same endpoint twice with the same scope describes a sequence; the last stub answers every later request. `query:` matches a subset, so it need not repeat `expand`, `page` or `per_page`. | +| `client` | A client wired to this stand-in. | +| `requests` | Every request made, oldest first, as `verb` / `path` / `query` / `body` / `headers` / `on_behalf_of`. | +| `reset` | Forgets the stubs and the recorded requests. | + +A `Hash` or `Array` body is served as JSON and gets `content-type: application/json` +unless `headers:` says otherwise — and it is that header, not the Ruby type, that decides +whether the body comes back decoded, exactly as it does on the wire. So a `Hash` stubbed +as `text/html` comes back as the raw string and reading a record from it raises +`ParseError`, which is what Zammad would do. Header names and values are stringified and +names downcased, the way a real `Response` carries them; a value that is not text, or two +spellings of one header name, are refused where the stub is written rather than turned +into something the wire could not send. + +`query` and `headers` are recorded through the real transport's own stringification, so +they hold what a request would have carried rather than the raw Ruby values — and a header +the wire would refuse is refused here too. `headers` names only what the call asked for; +the ones the client sets from its configuration are not in it, and an `on_behalf_of` scope +has a field of its own. + +A request that was not stubbed raises `ZammadAPI::Test::UnstubbedRequestError`, listing +what is stubbed, rather than answering with something empty. It is deliberately not a +`ZammadAPI::Error`: a forgotten stub means the test is wrong, not that Zammad refused +something, so a `rescue ZammadAPI::Error` in the code under test lets it through instead of +reporting it as an API failure. + +### Stubbing a list endpoint + +One stub is enough for a collection that fits in a page. The records it holds are one page +of them, so a request for any later page is answered the way an endpoint out of records +would answer it: -### Setup an (empty Zammad) test env +```ruby +zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}, {id: 2, name: 'Sales'}]) +client.groups.all.map(&:name) # => ["Users", "Sales"] ``` -git clone git@github.com:zammad/zammad.git -cd zammad -export RAILS_ENV="test" -export APP_RESTART_CMD="bundle exec rake zammad:ci:app:restart" -script/bootstrap.sh && echo '' > log/test.log -cp contrib/auto_wizard_test.json auto_wizard.json -bundle exec rake zammad:ci:test:start + +Stub the endpoint again to describe a list that changes between reads. A read is one step +of the sequence however many pages it asks for, so each read gets the next stub and the +last one answers every read after it: + +```ruby +zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}]) +zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}, {id: 2, name: 'Sales'}]) + +client.groups.all.count # => 1 +client.groups.all.count # => 2 ``` -### Execute client tests +Name a `page` to say what each one holds, and the stub is served exactly as written: -Run tests via `rake spec`. (Remember to export the vars above if you are running this in another shell.) +```ruby +zammad.stub(:get, 'api/v1/groups', body: first_hundred, query: {page: 1}) +zammad.stub(:get, 'api/v1/groups', body: [{id: 101}], query: {page: 2}) +``` -## Publishing +A search that is walked asks for its total with `with_total_count`, and an Array answers +it the way a Zammad before 6.5.1 does, with the records alone. To stand in for one that +reports the total, stub the object it answers with. It is paged like an Array: a later +page holds no records and the same total. -1. Update version in [version.rb](lib/zammad_api/version.rb). -2. Add release to [CHANGELOG.md](CHANGELOG.md) -3. Commit. -4. Test build. +```ruby +zammad.stub(:get, 'api/v1/users/search', body: {records: [{id: 1}, {id: 2}], total_count: 2}) ``` -> rake build -zammad_api 1.0.7 built to pkg/zammad_api-1.0.7.gem. + +### Scopes that overlap + +A stub naming `query:` answers ahead of one that does not, so a scoped stub and a catch-all +are two separate answers rather than a sequence: + +```ruby +zammad.stub(:get, 'api/v1/tickets/search', body: {total_count: 42}, query: {only_total_count: true}) +zammad.stub(:get, 'api/v1/tickets/search', body: [{id: 1}]) + +client.tickets.search('urgent').count # => 42, however often it is asked ``` -5. Release + +Two stubs whose scopes match a request equally well raise +`ZammadAPI::Test::AmbiguousStubError` rather than one of them being picked: `count` sends +the search term and `only_total_count` together, so a records stub scoped to +`{query: 'urgent'}` matches it just as well as the count stub does. Name what tells the +requests apart — here, the search term on the count stub too — or leave the more general +one unscoped as above. + +## Type signatures + +RBS signatures ship in `sig/` and are checked in CI with [Steep](https://github.com/soutaro/steep). +Add the gem to your own RBS collection to type-check calls into this client. + +Records are typed, not only the client. `client.tickets` is a +`ResourceProxy[Resources::Ticket]`, so `find`, `first`, `find_by`, the block of `each` and +a search all hand you a `Ticket`, and each resource declares the attributes every +supported Zammad serves for it: + +```ruby +ticket = client.tickets.find(1) + +ticket.title # String +ticket.organization_id # Integer? +ticket.related.customer&.email # String? +ticket.titel # a type error, where it used to be untyped +``` + +Three things are deliberately not declared, and each has a way through: + +- **Attributes an administrator added.** Read one with `ticket[:escalation_reason]`, or + declare it in your own signatures by reopening the class: + + ```rbs + class ZammadAPI::Resources::Ticket + attr_accessor escalation_reason: String? + end + ``` + +- **Columns only newer Zammad versions have**, which an older instance does not serve. + `record[:name]` reads those too. +- **The name `expand` adds for an association that may be empty**, such as `organization` + on a ticket or a user. Zammad leaves the key out rather than sending `null`, so a reader + would raise rather than answer `nil`; `ticket[:organization]` is `nil` in that case, and + `ticket.organization_id` is always there. + +A proxy for [a resource of your own](#resources-this-gem-does-not-model) is untyped until +you say what it holds, because a signature cannot carry a class into its own return type: + +```ruby +roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role] ``` -> rake release -zammad_api 1.0.7 built to pkg/zammad_api-1.0.7.gem. -Tag v1.0.7 has already been created. -Pushing gem to https://rubygems.org... -You have enabled multi-factor authentication. Please enter OTP code. -Code: ...... -Successfully registered gem: zammad_api (1.0.7) -Pushed zammad_api 1.0.7 to https://rubygems.org +The types describe a record Zammad served. One built with `new` carries only what it was +given until it is saved, and reading anything else from it raises `NoMethodError`, whatever +the signature says the type would be. + +## Examples + +Runnable scripts covering pagination, pattern matching, acting on behalf of a user, +attachments, error handling and threaded use live in [`examples/`](examples/README.md). + +## Development + +```sh +bin/setup # or: bundle install +bundle exec rake # unit specs, RuboCop and Steep ``` -## Contributing +| Task | What it does | +| ------------------------ | ----------------------------------------------------- | +| `rake spec:unit` | Unit specs; stubbed, no Zammad needed | +| `rake spec:integration` | Integration specs against a live Zammad | +| `rake check_connection` | Drives a live Zammad end to end and prints a transcript | +| `rake rubocop` | Style checks | +| `rake steep` | Type-check `lib/` against `sig/`, and `spec/typed/` the way a caller is checked | + +Set `COVERAGE=true` to produce a coverage report in `coverage/`. + +### Testing against a live Zammad + +The integration specs and `check_connection` need a reachable Zammad instance and **will +create and delete records**, so they run only where `TEST_URL` names one, and there is no +default: point it at something disposable. Without it, `rspec` runs the unit specs and +says the integration specs were left out, `rspec spec/integration` fails for having +nothing to run, and `rake spec:integration`, `rake spec` and `rake check_connection` stop +before running anything. + +```sh +export TEST_URL=https://zammad.example/ # a disposable Zammad, never one you keep data in +export TEST_USER=admin@example.com +export TEST_PASSWORD=test + +bundle exec rake check_connection # one linear pass, readable transcript +bundle exec rake spec:integration # the full spec suite +``` -Bug reports and pull requests are welcome on [GitHub](https://github.com/zammad/zammad-api-client-ruby). This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. +`check_connection` walks the documented workflows in order — create, find, update, reload, +pattern match, paginate, search, ticket with articles, attachment download, acting on +behalf of a user, and each error class — printing `ok` or `FAIL` per step and cleaning up +after itself. It stops early if a precondition fails, so a broken instance produces one +clear line rather than a cascade. + +CI runs both against a Zammad booted from source: the `integration` job clones Zammad, +starts it, waits for it to answer, runs `check_connection` as a fast preflight, then runs +the integration specs. Trigger it by hand from the Actions tab (`workflow_dispatch`) to +test against a specific Zammad ref. + +## Migrating from 1.x + +Version 2.0 fixes long-standing behaviour that could not change without breaking +compatibility. Most calling code needs no edits, and almost everything that does raises +at the call site. Start with the handful of changes that do not. + +If this is not the time to move, [1.x stays available](#staying-on-1x). + +### Changes that do not announce themselves + +- **`record.attributes = {...}`** was a writer in 1.x. It is now an ordinary attribute + assignment, so it stages a change named `attributes` and `save` sends it to Zammad: + + ```ruby + group.attributes = {name: 'Support'} + group.changes # => {attributes: [nil, {name: "Support"}]} + ``` + + Use `assign_attributes(name: 'Support')`, or `update` to assign and save. + +- **`record.save`** returns `false` when Zammad rejects the attributes, where 1.x raised. + Code that relied on the exception carries on after a rejected save: + + ```ruby + ticket.state = 'closed' + ticket.save # false on a 422 in 2.0; nothing raises, and the ticket is still open + ``` + + Check what `save` returns and read `record.error`, or call `save!`, which raises + `ZammadAPI::ValidationError` as `save` used to. `update` and `update!` are the same pair. + +- **`collection.each`** walks every page, where 1.x read one and stopped: + `client.ticket.all.each { ... }`, as 1.x spelled it, touched the first 100 tickets. It + still runs in 2.0, through the deprecated singular reader (`client.tickets` is the new + name), and now touches every ticket the client can read, at a request per page. A loop written to handle the first + page, or one that writes to each record it is handed, does that to all of them now. + Limit it explicitly with `first(n)` or `page(1, per_page: n)`. + +- **`rescue Faraday::ConnectionFailed`** (and any other Faraday exception) no longer + matches. Transport failures are wrapped, so rescue `ZammadAPI::ConnectionError`, + `ZammadAPI::TimeoutError`, or `ZammadAPI::TransportError` for both. + +### The client + +| 1.x | 2.0 | Why | +| -------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------- | +| `Client.new(config_hash)` | `Client.new(**config_hash)` | Options are keyword arguments now, so a Hash has to be splatted | +| an unknown option was ignored | raises `ArgumentError: unknown keyword` | A typo'd option used to be dropped without a word | +| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object, so you choose the device and level. Anything that answers `debug` is accepted; `true` raises `ConfigurationError` | +| `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is `Enumerable` over every record now, so `client.ticket.each` read as if it acted on one ticket. The singular names still work and warn in Ruby's `deprecated` category; run with `RUBYOPT=-W:deprecated` to find them. They go in 3.0 | +| `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads | +| `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised | +| `ZammadAPI::Resources::Role < Base` reached by `client.role` | `client.resource(Role)`, for a `Role < ZammadAPI::Resources::Base` of your own | The named readers are a fixed list, and a class is handed over rather than looked up by name. [Raw requests](#raw-requests) reach whatever is not a resource | + +### Collections + +| 1.x | 2.0 | Why | +| ---------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------- | +| `collection.each` stopped after one page | `each` walks every page | Iterating truncated silently at the page size: 100 for `all`, 10 for `search` | +| `collection.page(1, 3) { \|r\| ... }` | `collection.page(1, per_page: 3).each { ... }` | `page` now returns a collection instead of mutating and yielding | +| `collection.page_next` / `page_prev` | `collection.page(n)` or `in_batches` | Removed; they mutated shared state | +| `collection.each_page { ... }` | `collection.in_batches { ... }` | Ruby already has a name for this | +| `collection[3]` | `collection.page(4, per_page: 1).first` | An index that costs a request, and that ignored `page`, was a trap | +| `collection.find(1)` | `client.x.find(1)`, or `collection.detect { ... }` | On a collection `find` is `Enumerable#find`, whose argument is an ifnone callable — so an id answered with an Enumerator and made no request. It raises now | +| `client.x.all(per_page: 50)` | `client.x.all.page(1, per_page: 50)`, `find_each(batch_size: 50)` | `all` accepted the argument and discarded it; page size belongs to the call that reads | +| `client.x.all(active: true)` | `client.x.search(...)`, or `client.x.all.detect { ... }` | The filter never reached the request in 1.x, and could not have: Zammad's index endpoints do not filter, so 2.0 has no call that pretends to. `find_by(active: true)` answers with the first such record, by walking the index where it has no string to search on | +| `client.x.search(query: 'zammad')` | `client.x.search('zammad')` | The search term is the argument, not a keyword | +| `client.x.search(query: 'z', page: 2, per_page: 50)` | `client.x.search('z').page(2, per_page: 50)` | Search did honour those two; paging is the collection's job now | + +### Records + +| 1.x | 2.0 | Why | +| ----------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------- | +| `record.save` raised on a rejection | `save` → `false` with `record.error`; `save!` raises | Branching on a rejected attribute needed a begin/rescue | +| `record.attributes[:x] = 1` | `record.x = 1`, or `record.to_h` for a copy | Writing through the reader staged no change, so `save` never sent it | +| `record.attributes = {...}` | `record.assign_attributes(...)` / `record.update(...)` | The writer is gone, and the name now stages an attribute of its own | +| `record.id = 5` | `client.x.find(5)` | The id addresses the record, so a staged one deleted or updated a different record than it reported | +| `record.new_instance` | `record.new_record?` / `record.persisted?` | Internal flag is no longer public; the old name raises `NoMethodError`, naming the attributes the record does carry | +| `resource.url` (instance) | `Resource.resource_path` (class) | Clashed with an attribute named `url` | +| `record.unknown_attribute` → `nil` | raises `NoMethodError`; use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` | A typo read as `nil` and flowed on into whatever was written with it. Zammad also serves a reduced object where the user may not see the whole record, and that is worth being told about | +| `client.x.new(id: 5)` | `client.x.find(5)` | The constructor was the one door that did not refuse a staged id — and the only one whose value reached Zammad, since a new record is sent in full | +| `client.users.find(ticket.customer_id)` | `ticket.related.customer` | Following a foreign key needed the client threaded through | +| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | A noun that sends a `POST`, one letter away from `ticket.articles`, which only reads. `article` still works and warns in Ruby's `deprecated` category; it goes in 3.0 | + +### Errors + +| 1.x | 2.0 | Why | +| ------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------- | +| `ZammadAPI::Error < RuntimeError` | `ZammadAPI::Error < StandardError` | `RuntimeError` is for `raise "string"` | +| `ZammadAPI::ResourceNotFoundError` | `ZammadAPI::UnknownResourceError` | Renamed so it is not confused with a 404, now `NotFoundError` | +| `ClientError` for every 4xx | `AuthenticationError`, `NotFoundError`, `ValidationError`, … | All still `ClientError`, so existing rescues keep working | +| a Faraday exception for a dead host | `ZammadAPI::ConnectionError` / `TimeoutError` | Every failure this gem can raise descends from `ZammadAPI::Error` | +| `error.response` was a Faraday object | `ZammadAPI::Response` with `status`/`body`/`headers` | Faraday is no longer part of the public surface | +| `error.body` was a raw JSON string | decoded Hash, or the raw body for non-JSON | Saves every caller from parsing it again | + +### Removed constants, and the Ruby version + +| 1.x | 2.0 | Why | +| ------------------------------------------------ | -------------------------- | ------------------------------------------------------------ | +| `ZammadAPI::ListBase` / `ListAll` / `ListSearch` | `ZammadAPI::Collection` | One class instead of three | +| `ZammadAPI::Dispatcher` | `ZammadAPI::ResourceProxy` | Renamed; `client.` hands you one | +| `ZammadAPI::Log`, `ZammadAPI::JsonHelper` | removed | Pass any `Logger` as `logger:`; decoding moved into the transport | +| Ruby >= 3.0 | Ruby >= 3.4 | 3.0 through 3.3 are end-of-life or nearly so | + +### Defaults 1.x did not have + +A collection fetches as many records per request as the endpoint serves — 1000 on the index +endpoints, 100 on tickets, 200 on a search — rather than a fixed 100, so a walk spends +roughly a tenth of the round trips. `page(n)` without `per_page:` is a page of that size, so pin +it with `page(n, per_page: 100)` if a persisted page number has to keep meaning what it did. + +A request now times out after 60 seconds (10 to connect) where 1.x waited as long as the +server took, so a call that used to hang raises `ZammadAPI::TimeoutError`. A `GET` is +retried twice with exponential backoff on connection failures, timeouts and the transient +statuses, which means a genuinely broken endpoint takes a little longer to report itself; +a `POST`, `PUT` or `DELETE` is never retried. Both are options — see +[Timeouts and retries](#timeouts-and-retries). The `User-Agent` is now +`zammad_api-ruby/` rather than `Zammad API Ruby`. + +### What did not change + +`find`, `all`, `create` and `new` on a resource, `record.destroy`, attribute readers and +writers, `ticket.articles` and `attachment.download`. The resources themselves are reached +by their plural names now — `client.tickets` — and adding an article is +`ticket.add_article`; the old names still answer, with a deprecation warning. + +`record.save`, `record.changes` and `record.attributes` still exist and still mean what +they meant; the tables above only change how they behave at the edges. + +## License + +Dual licensed under the [AGPL-3.0-only](LICENSE.AGPL.txt) or [MIT](LICENSE.MIT.txt) +licenses. See [LICENSE.md](LICENSE.md). diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..4e7052b --- /dev/null +++ b/examples/README.md @@ -0,0 +1,38 @@ +# Examples + +Runnable scripts showing how the 2.0 API works in a real project. Each one is +self-contained and builds its client with `ZammadAPI::Client.from_env`, which +reads the credentials from the environment: + +```sh +export ZAMMAD_URL=https://zammad.example.com/ +export ZAMMAD_TOKEN=your-access-token + +ruby examples/quickstart.rb +``` + +`ZAMMAD_USER` and `ZAMMAD_PASSWORD` work instead of a token, as does +`ZAMMAD_OAUTH2_TOKEN`. + +> These scripts **create, modify and delete records**. Point them at a +> disposable instance. + +None of them set a timeout or a retry policy: requests time out after 60s and +a read that fails transiently is retried with backoff out of the box, so the +examples show what is left for your own code to do. A write is never repeated; +`error_handling.rb` shows what that leaves to you. + +| Script | What it does | API features it shows | +| ------ | ------------ | --------------------- | +| [`quickstart.rb`](quickstart.rb) | Creates a ticket, reads it back, adds an article, updates it | The basics end to end | +| [`pagination.rb`](pagination.rb) | Reads a collection every available way | `each`, `find_each`, `in_batches`, `page(n, per_page: m)`, `search`, `order`, `count`, `empty?`, `lazy`, `first(n)`, `detect`, collection immutability | +| [`manual_batches.rb`](manual_batches.rb) | Drives pagination by hand: pull-based, numbered, resumable | `in_batches` as an Enumerator (`next`, `with_index`), an explicit `page(n, per_page: m)` loop with a persisted cursor | +| [`ticket_report.rb`](ticket_report.rb) | Exports every ticket to CSV | Automatic pagination, `in_batches` batching, `fetch` for required attributes | +| [`triage_tickets.rb`](triage_tickets.rb) | Flags urgent tickets, nudges stale ones | `search`, `case/in` pattern matching on records, staged `changes` so only diffs are sent, `add_article` | +| [`onboard_customer.rb`](onboard_customer.rb) | Creates an organization, a user, and a welcome ticket raised as that user | `find_by`, `create`, `on_behalf_of` as a scoped client and as a block | +| [`download_attachments.rb`](download_attachments.rb) | Saves a ticket's attachments to disk | `articles`, attachment metadata, binary-safe `download` | +| [`error_handling.rb`](error_handling.rb) | Handles the failures that are yours to handle | The error hierarchy, `save` → `false` with `record.error`, rescuing by category, `client.with` for different retry settings | +| [`concurrent_sync.rb`](concurrent_sync.rb) | Syncs tickets with a worker pool sharing one client | Immutable clients are thread-safe; also sketches the Rails initializer pattern | + +The examples are linted along with the rest of the repository (`rake rubocop`), +so they cannot silently rot. diff --git a/examples/concurrent_sync.rb b/examples/concurrent_sync.rb new file mode 100755 index 0000000..b4ac7f5 --- /dev/null +++ b/examples/concurrent_sync.rb @@ -0,0 +1,57 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Syncs tickets from a worker pool that shares a single client. +# +# A client is immutable once built, so one instance is safe to share between +# threads: no locking, no client per thread, and `on_behalf_of` scoping in one +# thread cannot leak into another. It is the same reason one client works as a +# Rails initializer constant used from every background worker: +# +# # config/initializers/zammad.rb +# ZAMMAD = ZammadAPI::Client.new( +# url: Rails.application.credentials.zammad_url, +# http_token: Rails.application.credentials.zammad_token, +# logger: Rails.logger +# ) +# +# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ +# ruby examples/concurrent_sync.rb + +require 'zammad_api' + +WORKERS = 4 + +client = ZammadAPI::Client.from_env + +# Collect the work first; `first` stops paginating once it has enough. +queue = Queue.new +client.tickets.all.first(40).each { queue << it.id } +queue.close # so a worker draining an empty queue stops instead of blocking + +results = Queue.new + +workers = Array.new(WORKERS) do + Thread.new do + # Every worker shares this one client. Nothing about it is mutated by + # making a request, so there is nothing to synchronise. + while (id = queue.pop) + results << begin + client.tickets.find(id) + :ok + rescue ZammadAPI::Error => e + # Transient failures were already retried, so anything arriving here + # is worth reporting rather than trying again. + warn "ticket #{id}: #{e.class}" + :failed + end + end + end +end + +workers.each(&:join) + +tally = Hash.new(0) +tally[results.pop] += 1 until results.empty? + +puts "synced #{tally[:ok]}, failed #{tally[:failed]}" diff --git a/examples/download_attachments.rb b/examples/download_attachments.rb new file mode 100755 index 0000000..067fa89 --- /dev/null +++ b/examples/download_attachments.rb @@ -0,0 +1,45 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Saves every attachment of a ticket to a directory. +# +# Shows walking articles, attachment metadata, and binary-safe downloads. +# +# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ +# ruby examples/download_attachments.rb 12345 ./downloads + +require 'zammad_api' +require 'fileutils' + +client = ZammadAPI::Client.from_env + +ticket_id = Integer(ARGV.fetch(0) { abort "usage: #{$PROGRAM_NAME} TICKET_ID [DIRECTORY]" }) +directory = ARGV.fetch(1, "ticket-#{ticket_id}") + +ticket = client.tickets.find(ticket_id) +FileUtils.mkdir_p(directory) + +# The filename comes from the server, so `File.basename` strips any directory +# part that would otherwise let `../` escape the download directory. The ids +# keep two same-named attachments from overwriting each other. +def safe_filename(article_id, attachment) + name = File.basename(attachment.filename.to_s) + name = 'attachment' if name.empty? || name.start_with?('.') + "#{article_id}-#{attachment.id}-#{name}" +end + +saved = 0 + +ticket.articles.each do |article| + article.attachments.each do |attachment| + # `download` returns the bytes as ASCII-8BIT, so images and archives + # survive intact. + contents = attachment.download + File.binwrite(File.join(directory, safe_filename(article.id, attachment)), contents) + saved += 1 + + puts format('%-40s %8d bytes', file: attachment.filename, size: contents.bytesize) + end +end + +puts saved.zero? ? "Ticket ##{ticket.number} has no attachments." : "Saved #{saved} file(s) to #{directory}/" diff --git a/examples/error_handling.rb b/examples/error_handling.rb new file mode 100755 index 0000000..9200c7f --- /dev/null +++ b/examples/error_handling.rb @@ -0,0 +1,77 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# What to rescue, and what the client has already handled for you. +# +# Timeouts, connection failures and the transient statuses (429, 500, 502, +# 503, 504) are retried with backoff on a GET before any error reaches your +# code. A write is never repeated, because only you know whether sending it +# twice is safe. So what is left to handle is what only you can decide about: +# a missing record, a rejected attribute, bad credentials, a write that may or +# may not have arrived. +# +# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ +# ruby examples/error_handling.rb + +require 'zammad_api' + +# Options are validated up front, before any request is made. +begin + ZammadAPI::Client.new(url: 'not-a-url', http_token: 'x') +rescue ZammadAPI::ConfigurationError => e + puts "rejected early: #{e.message}" +end + +client = ZammadAPI::Client.from_env + +# A missing record is a decision to make, not a failure to retry. +ticket = begin + client.tickets.find(0) +rescue ZammadAPI::NotFoundError + nil +end + +puts "missing ticket: #{ticket.inspect}" + +# A rejected attribute (422) makes `save` return false and leaves the reason +# on the record, so branching needs no begin/rescue. +group = client.groups.new(name: '') + +if group.save + puts "created group: #{group.id}" +else + puts "rejected save: #{group.error.status} #{group.error.server_message}" + puts " body #{group.error.body.inspect}" + puts " operation #{group.error.operation} on #{group.error.resource_class}" +end + +# `create` and `save!` raise instead, which is what a script wants. +begin + client.groups.create(name: '') +rescue ZammadAPI::ValidationError => e + puts "raised instead: #{e.class}" +end + +# Rescue by category where the exact class does not matter. +begin + client.tickets.find(0) +rescue ZammadAPI::ClientError => e # any 4xx + puts "client error: #{e.status}" +rescue ZammadAPI::ServerError => e # any 5xx, including an HTML proxy page + puts "server error: #{e.status}" +rescue ZammadAPI::TransportError => e # never reached the server, retries spent + puts "transport error: #{e.message}" +end + +# Or catch everything this gem raises in one place. +begin + client.tickets.find(0) +rescue ZammadAPI::Error => e + puts "any gem error: #{e.class}" +end + +# Where the defaults do not suit the job, change them once on a derived +# client instead of writing a retry loop around every call. +patient = client.with(retries: 5, retry_interval: 1) + +puts "derived client: #{patient.config.retries} retries, original still #{client.config.retries}" diff --git a/examples/manual_batches.rb b/examples/manual_batches.rb new file mode 100755 index 0000000..d9d72f6 --- /dev/null +++ b/examples/manual_batches.rb @@ -0,0 +1,142 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Driving pagination yourself, for when the loop is not yours to own: a job +# that has to checkpoint and resume, or a producer feeding a queue. +# +# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ +# ruby examples/manual_batches.rb + +require 'zammad_api' +require 'digest' +require 'fileutils' +require 'tmpdir' + +PER_PAGE = 50 + +client = ZammadAPI::Client.from_env +tickets = client.tickets.all + +# Where the loop in part 3 keeps its checkpoint. A page number says which +# tickets come next only together with the instance it was counted on, the +# user whose tickets they are - the index serves what that user may read - +# the list it pages and the size of the pages, so the file is named for all +# of them. Under one name for every run, a job stopped at page 4 of one +# Zammad had the next run against another start at page 4 there, with the +# first three pages never read - and remove the first job's checkpoint when +# it finished. The user costs a request to look up. +JOB = Digest::SHA256.hexdigest("#{client.config.url} #{client.me.id} api/v1/tickets #{PER_PAGE}")[0, 16] +CURSOR = File.join(Dir.tmpdir, "zammad_batch_cursor_#{JOB}") +NEXT_CURSOR = "#{CURSOR}.next".freeze + +# 1. Pull a page when you are ready for it ----------------------------------- +# +# `in_batches` without a block is an Enumerator: nothing is fetched until +# `next`, and each `next` costs exactly one request. + +puts '1. pulling two pages, leaving the rest unfetched' + +pages = tickets.in_batches(of: PER_PAGE) + +2.times do + puts " pulled #{pages.next.size} tickets" +rescue StopIteration + break +end + +# 2. Numbered batches -------------------------------------------------------- +# +# `with_index` is Ruby's own, and works for the same reason: an Enumerator. + +puts '2. every batch, numbered' + +tickets.in_batches(of: PER_PAGE).with_index do |batch, index| + puts " batch #{index}: #{batch.size} tickets" +end + +# 3. A resumable page loop --------------------------------------------------- +# +# Own the page number when the job has to survive being interrupted. The +# loop ends on a page with nothing on it, and not on a page short of +# PER_PAGE: that is the size asked for, and what counts is the size served. +# An instance that serves 25 where 50 were asked for hands back a "short" +# page every time, and a loop that stops on one has stopped after the first +# with the checkpoint cleared. `find_each` and `in_batches` learn the size +# from the first page; here one more request at the end does the same job. +# +# A page number is a position, not a record, so it only resumes where it left +# off while nothing before it goes away. Delete one ticket from a page already +# handled and every later ticket moves up a place: the next page then starts +# one ticket further on, and the ticket that moved into the handled page is +# never seen. New tickets are no trouble here, because this index is served in +# id order and they arrive at the end. +# +# So this loop is for a set that only grows. Where tickets can be deleted +# between two runs of the job, checkpoint the id of the last ticket handled +# instead, and skip up to it on the way back in: +# +# tickets.find_each.lazy.drop_while { it.id <= last_id }.each { ... } +# +# That reads the earlier pages again, so a ticket deleted while the job was +# down no longer moves the place it picks up from. +# +# It does nothing about a ticket deleted while a walk is under way, and +# neither does anything else here. `find_each` pages by position too: delete +# ticket 1 once page 1 has been read, and page 2 starts one ticket further +# on, with the ticket that moved up into page 1 never handed over. No way of +# reading an index that is paged by position rules that out, and walking +# again does not either: a second walk that tickets are deleted under can +# pass over the same ticket and turn up nothing new. What settles it is a +# walk nothing was deleted during, which the job has to be able to vouch +# for - by holding deletions off while it runs, say - and which turns up +# no ticket it has not handled. + +puts '3. resumable page loop' + +page = 1 + +if File.exist?(CURSOR) + # A checkpoint holds a page number or it holds nothing this loop can use. + # Said here, rather than left to `Integer` or to `page` to raise about. + page = Integer(File.read(CURSOR), exception: false) + abort " #{CURSOR} does not hold a page number. Remove it to start from page 1." if page.nil? || !page.positive? +end + +puts " starting at page #{page}" + +loop do + batch = tickets.page(page, per_page: PER_PAGE).to_a + break if batch.empty? + + puts " page #{page}: #{batch.size} tickets" + + # Checkpoint once the batch is safely handled, so an interrupted run + # repeats a batch rather than skipping one - on a set nothing is deleted + # from, see above. + # + # Written beside the checkpoint and renamed over it, which replaces it in + # one step. `File.write` on the checkpoint itself empties the file before + # it fills it, and a run stopped in between leaves a checkpoint with + # nothing in it, where the page before was still worth having. + File.write(NEXT_CURSOR, page + 1) + File.rename(NEXT_CURSOR, CURSOR) + + page += 1 +end + +FileUtils.rm_f([CURSOR, NEXT_CURSOR]) + +puts <<~NOTE + + Which to reach for: + + each / find_each the loop is yours and runs to completion + in_batches you want one whole response at a time + in_batches.next you want to pull batches as a consumer is ready + in_batches.with_index you want the batches numbered as they arrive + page(n, per_page: m) the page number must be persisted, retried or skipped, + and nothing is deleted from the set meanwhile + + Pacing is not on this list: the client already backs off and retries a 429, + so a manual sleep loop only duplicates it. +NOTE diff --git a/examples/onboard_customer.rb b/examples/onboard_customer.rb new file mode 100755 index 0000000..bcd9892 --- /dev/null +++ b/examples/onboard_customer.rb @@ -0,0 +1,85 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Onboards a new customer: organization, user, and a welcome ticket raised as +# that user. +# +# Shows `find_by` for a lookup by attribute, `create`, and `on_behalf_of` both +# as a scoped client and as a block. +# +# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ +# ruby examples/onboard_customer.rb "Acme Inc" jane@acme.test Jane Doe + +require 'zammad_api' + +client = ZammadAPI::Client.from_env + +company, email, firstname, lastname = ARGV +abort "usage: #{$PROGRAM_NAME} COMPANY EMAIL FIRSTNAME LASTNAME" if [company, email, firstname, lastname].any?(&:nil?) + +# Zammad stores an address trimmed and in lower case, and `find_by` matches a +# value exactly. Looked up as typed, Jane@Acme.Test misses the jane@acme.test +# Zammad holds: the check below then sees no user, and the script makes the +# organization before Zammad refuses the address as taken. +email = email.strip.downcase + +# `find_by` searches and then checks the hits itself, because Zammad's index +# endpoints cannot filter. It returns a record that genuinely carries the +# attribute, or nil - never an unrelated one. +# +# What the search surfaces is Zammad's business, so a value it has not indexed +# is a record this will not find, and the `||= create` below would then make a +# second organization. Searching by hand has the same gap. +organization = client.organizations.find_by(name: company) +user = client.users.find_by(email: email) + +# An address Zammad already knows is only this customer's if it sits in this +# organization. Reused regardless, a jane@acme.test who belongs to Contoso +# got Acme's welcome ticket and a report that all was well, with nothing +# having put that user in Acme. Moving a user is not this script's call +# either, so it stops, before anything is created. `[]` rather than a reader, +# because a user with no organization may not carry the attribute at all. +if user && (organization.nil? || user[:organization_id] != organization.id) + # Named where the response carries the name, by id where it carries only + # that, and "no organization" only for a user that has neither. + current = user[:organization] || (user[:organization_id] ? "organization id=#{user[:organization_id]}" : 'no organization') + + abort "#{email} is already a user (id=#{user.id}) of #{current}, not of #{company}. " \ + 'Nothing was created or changed. Move the user in Zammad first, if that is what is meant.' +end + +organization ||= client.organizations.create(name: company) + +puts "organization: #{organization.name} (id=#{organization.id})" + +user ||= client.users.create( + firstname: firstname, + lastname: lastname, + email: email, + organization_id: organization.id, + roles: ['Customer'] +) + +puts "user: #{user.firstname} #{user.lastname} <#{user.email}> (id=#{user.id})" + +# `on_behalf_of` returns a new client rather than mutating this one, so the +# admin client stays unscoped and both remain safe to use. +as_customer = client.on_behalf_of(user.email) + +ticket = as_customer.tickets.create( + title: "Welcome, #{firstname}!", + group: 'Users', + customer: user.email, + article: { + subject: 'Getting started', + body: "Hi #{firstname},\n\nyour account is ready.", + type: 'note' + } +) + +puts "ticket: ##{ticket.number} raised as #{user.email}" + +# The block form scopes a single operation. +own_tickets = client.on_behalf_of(user.email) { |scoped| scoped.tickets.all.count } + +puts "the customer can see #{own_tickets} ticket(s) of their own" diff --git a/examples/pagination.rb b/examples/pagination.rb new file mode 100755 index 0000000..a3332d1 --- /dev/null +++ b/examples/pagination.rb @@ -0,0 +1,71 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Every way to read a collection, and what each one costs. +# +# Collections are lazy: nothing is fetched until you iterate, and only the +# pages you actually consume are fetched. A request carries as many records as +# the endpoint serves - 100 for tickets, 200 for a search, 1000 for the other +# index endpoints - unless a call asks for another size. +# +# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ +# ruby examples/pagination.rb + +require 'zammad_api' + +client = ZammadAPI::Client.from_env +tickets = client.tickets.all # no request yet + +# Walk every record. Pages are fetched as the iteration reaches them, so only +# one page is ever held in memory. +seen = 0 +tickets.each { seen += 1 } +puts "each #{seen} tickets, one request per page" + +# The same walk with the page size chosen for the job at hand. +ids = [] +tickets.find_each(batch_size: 50) { ids << it.id } +puts "find_each #{ids.size} tickets, 50 per request" + +# One whole page per block call, for work that batches: an import, a bulk +# insert, a push onto a queue. +sizes = [] +tickets.in_batches(of: 50) { sizes << it.size } +puts "in_batches pages of #{sizes.inspect}" + +# Stop early and the remaining pages are never fetched. +puts "first(3) #{tickets.first(3).map(&:id).inspect}, one request, for three records" +puts "lazy.select #{tickets.lazy.select { it.state == 'open' }.first(2).map(&:id).inspect}" +puts "detect ##{tickets.detect { it.state == 'open' }&.number}, stops at the match" + +# One specific page, when you are driving the paging yourself. +puts "page(2, per_page: 10) #{tickets.page(2, per_page: 10).map(&:id).inspect}" + +# Narrowing by a value is `search`: Zammad's index endpoints sort and page and +# drop every other parameter, so there is no filter to pass them. Searches +# compose with all of the above. +puts "search #{client.tickets.search('state.name:open').first(5).size} open tickets" + +# `order` sorts on the server. A search sorts for every resource; of the index +# endpoints, the ticket and user ones are always served in id order. +newest = client.tickets.search('state.name:open').order(created_at: :desc).first +puts "search.order ##{newest&.number}, the most recently created open ticket" +puts "order #{client.groups.order(:name).first(3).map(&:name).inspect}" + +# Counting a search is one request, because Zammad can answer `only_total_count` +# without serving the records. An index endpoint has no answer for it and no +# total to report, so counting one means walking it. +puts "search.count #{client.tickets.search('state.name:open').count}, one request" +puts "empty? #{client.tickets.search('state.name:merged').empty?}, asks for a single record" + +# `search` and `page` return a new collection, so scoping one never disturbs +# the original. +puts "immutable #{tickets.page(2).equal?(tickets)}" + +puts <<~NOTE + + Upgrading from 1.x: `each` used to fetch a single page, so iterating a + collection silently stopped at 100 records. It now walks every page. Ask + for one page explicitly with `page(1, per_page: 100)` where that is what you + wanted. +NOTE diff --git a/examples/quickstart.rb b/examples/quickstart.rb new file mode 100755 index 0000000..f7c55c3 --- /dev/null +++ b/examples/quickstart.rb @@ -0,0 +1,53 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# The basics, end to end: create a ticket, read it back, add an article and +# update it. +# +# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ +# ruby examples/quickstart.rb + +require 'zammad_api' + +client = ZammadAPI::Client.from_env + +# `me` answers for any account. `client.version` would name the Zammad +# version as well, but Zammad serves it to administrators only, and an +# agent's token is answered with ZammadAPI::AuthorizationError. +puts "connected to #{client.config.redacted_url} as #{client.me.email}" + +# Create a ticket together with its first article. +ticket = client.tickets.create( + title: 'Cannot log in', + group: 'Users', + customer: 'nicole.braun@zammad.org', + article: { + subject: 'Cannot log in', + body: "Hi,\n\nmy password stopped working.", + type: 'note' + } +) + +puts "created ##{ticket.number} - #{ticket.title}" + +# Read it back. Associations come expanded, so these are plain attribute +# reads rather than further requests. +ticket = client.tickets.find(ticket.id) +puts "state #{ticket.state}, priority #{ticket.priority}, group #{ticket.group}" + +# Add another article. +ticket.add_article(subject: 'Update', body: 'Reset link sent.', type: 'note') +puts "#{ticket.articles.size} article(s)" + +# Assignments are staged, and `save` sends only what changed. It answers +# false, with the reason in `error`, where Zammad rejects the change as +# invalid (a 422). Any other failure raises: a 403 as +# ZammadAPI::AuthorizationError, for one. +ticket.priority = '3 high' +puts "sending #{ticket.changes.inspect}" +abort "Zammad rejected the change: #{ticket.error.message}" if !ticket.save + +# Collections paginate themselves, and `first` stops as soon as it has enough. +client.tickets.search('state.name:open').first(5).each do |open_ticket| + puts "open: ##{open_ticket.number} #{open_ticket.title}" +end diff --git a/examples/ticket_report.rb b/examples/ticket_report.rb new file mode 100755 index 0000000..c6c3340 --- /dev/null +++ b/examples/ticket_report.rb @@ -0,0 +1,54 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Exports every ticket to CSV. +# +# Shows automatic pagination with `in_batches`, and `fetch` for an attribute +# that has to be there. The defaults carry a long export on their own: a +# request times out after 60s, and transient failures are retried with +# backoff before any error reaches this script. +# +# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ +# ruby examples/ticket_report.rb tickets.csv + +require 'zammad_api' +require 'csv' + +client = ZammadAPI::Client.from_env +destination = ARGV.fetch(0, 'tickets.csv') +exported = 0 + +# A spreadsheet reads a cell starting with =, +, -, @, tab or CR as a formula, +# and a ticket title is whatever the customer typed. An apostrophe keeps every +# exported cell text. +def csv_safe(value) + text = value.to_s + text.match?(/\A[=+\-@\t\r]/) ? "'#{text}" : text +end + +CSV.open(destination, 'w') do |csv| + csv << %w[id number title state priority group customer created_at] + + # Nothing is loaded until the block runs, and each call is one page. + client.tickets.all.in_batches(of: 100) do |tickets| + tickets.each do |ticket| + row = [ + ticket.fetch(:id), # raises KeyError if it is missing + ticket.number, + ticket.title, + ticket.state, # present because associations come expanded + ticket.priority, + ticket.group, + ticket.customer, + ticket.created_at + ] + + csv << row.map { csv_safe(it) } + end + + exported += tickets.size + warn "exported #{exported} tickets..." + end +end + +puts "Wrote #{exported} tickets to #{destination}" diff --git a/examples/triage_tickets.rb b/examples/triage_tickets.rb new file mode 100755 index 0000000..8402360 --- /dev/null +++ b/examples/triage_tickets.rb @@ -0,0 +1,58 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Triages open tickets: flags the urgent ones, nudges the stale ones. +# +# Shows `search`, pattern matching against records, staged changes so only +# what was modified is sent, and adding an article. +# +# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ +# ruby examples/triage_tickets.rb + +require 'zammad_api' +require 'time' + +STALE_AFTER = 7 * 24 * 60 * 60 # a week, in seconds + +client = ZammadAPI::Client.from_env +flagged = 0 +nudged = 0 + +# Oldest first: a search is served newest-updated first, so without the +# order the 200 read would be the freshest, and on an instance with more +# open tickets than that the stale ones would never be looked at. `first` +# stops paginating as soon as it has what it asked for. +client.tickets.search('state.name:open').order(updated_at: :asc).first(200).each do |ticket| + # Records implement `deconstruct_keys`, so case/in works on them. + case ticket + in { priority: '3 high', owner_id: 1 } # 1 is Zammad's "-", i.e. unassigned + puts "unassigned and high priority: ##{ticket.number} #{ticket.title}" + flagged += 1 + + in { updated_at: String => updated } if Time.now - Time.parse(updated) > STALE_AFTER + puts "stale: ##{ticket.number} #{ticket.title}" + + ticket.priority = '3 high' + # Sends the one changed attribute, nothing else. A change Zammad rejects + # as invalid (a 422) comes back as false rather than raising, so it is + # checked: an unchecked save carries on as if the priority had been + # raised. Any other failure, such as a 403, raises. + if !ticket.save + warn " could not raise the priority of ##{ticket.number}: #{ticket.error.message}" + next + end + + ticket.add_article( + subject: 'Automated follow-up', + body: "No activity for over #{STALE_AFTER / 86_400} days; priority raised.", + type: 'note', + internal: true + ) + nudged += 1 + + else + next + end +end + +puts "\n#{flagged} ticket(s) flagged, #{nudged} nudged." From be4d46404e2407f5df015b2b94283204cbc38d9e Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 00:18:20 +0200 Subject: [PATCH 006/121] fix: refuse a record where a record id belongs `Transport.escape_path_segment` turned whatever it was given into a path segment with `to_s`, which answers for every object. A record passed where its id belongs went into the path as it inspects: `client.tickets.exists?(ticket)` asked for `tickets/%23%3CZammadAPI%3A%3AResources%3A%3ATicket...%3E`, was told 404 about a path that names nothing, and answered false for a ticket that exists. `destroy(ticket)` raised NotFoundError for a record that was right there. An id is an Integer, a String or a Symbol, and anything else is refused with an ArgumentError before a request is made. The message names the class and does not quote the value, which for a record is every attribute it carries. nil is still told that an id is required. --- CHANGELOG.md | 6 ++++ lib/zammad_api/transport.rb | 31 +++++++++++++++++++-- sig/zammad_api/transport.rbs | 2 ++ spec/unit/zammad_api/resource_proxy_spec.rb | 20 +++++++++++++ spec/unit/zammad_api/transport_spec.rb | 29 +++++++++++++++++++ 5 files changed, 85 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5d867e..24dcb4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -795,6 +795,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a request takes headers of its own and the request line prints them, and neither name matched the words that mark a credential, so `client.get(path, headers: {'Cookie' => ...})` wrote the session out in full. +- A record passed where its id belongs is refused with an `ArgumentError`. Whatever was + given went into the request path through `to_s`, which answers for every object, so + `client.tickets.exists?(ticket)` asked for a path spelling out the record's `inspect`, was + told 404 about it and answered `false` for a ticket that exists, and `destroy(ticket)` + raised `NotFoundError` for one that was right there. An id is an `Integer`, a `String` or + a `Symbol`; the message names the class of anything else and does not quote it. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 6c2ded2..6d4075d 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -156,6 +156,12 @@ module Verbs # untouched. DOT_SEGMENTS = ['.', '..'].freeze + # What a record id is written as: the Integer Zammad serves, or text - a + # String out of a request parameter, a Symbol for a named member such as + # `users/me`. Everything else has a `to_s` as well, and none of those + # names a record. + RECORD_ID_TYPES = [Integer, String, Symbol].freeze + # A request path that carries a scheme and an authority, and so names a # host of its own. Any scheme and either case, which is wider than the # two lowercase prefixes Faraday itself treats as absolute: what is @@ -508,15 +514,27 @@ def self.blank_on_behalf_of_message(identifier) # them inside the segment here, but a proxy that normalises a path before # routing it would undo that, and no Zammad record is named for one. # + # Anything that is not an id is refused rather than printed. `to_s` + # answers for every object, so a record where its id belongs was pasted + # in as it inspects: `exists?(ticket)` asked for + # `tickets/%23%3CZammadAPI%3A%3AResources%3A%3ATicket...%3E`, was told + # 404 about a path that names nothing, and answered false for a ticket + # that exists, while `destroy(ticket)` raised NotFoundError for one that + # was right there. The message names the class and does not quote the + # value, which for a record is every attribute it carries. + # # Public for the same reason as {.stringify_query}: {Test} builds the # paths it records with it. # # @api private - # @param value [Object] + # @param value [Integer, String, Symbol, nil] # @return [String] - # @raise [ArgumentError] when there is nothing to send, or when the id - # navigates instead of naming a record + # @raise [ArgumentError] when there is nothing to send, when the value + # is not an id at all, or when the id navigates instead of naming a + # record def self.escape_path_segment(value) + raise ArgumentError, not_a_record_id_message(value) if !value.nil? && RECORD_ID_TYPES.none? { value.is_a?(it) } + segment = value.to_s raise ArgumentError, 'a record id is required, and this one is empty' if segment.empty? raise ArgumentError, "#{segment.inspect} points at another endpoint rather than naming a record" if DOT_SEGMENTS.include?(segment) @@ -524,6 +542,13 @@ def self.escape_path_segment(value) segment.gsub(UNRESERVED_IN_PATH) { |character| character.bytes.map { format('%%%02X', it) }.join } end + # @api private + # @return [String] + def self.not_a_record_id_message(value) + "a record id is an Integer or a String, and this one is #{value.class}: it would go into the request path as " \ + 'that object prints, which names no record. To address a record you hold, pass its id.' + end + # Strips the leading slashes from a path so that it resolves against the # instance URL rather than against the host. # diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index ceb3d6c..3d8aaf1 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -29,6 +29,7 @@ module ZammadAPI REDACTED: String UNRESERVED_IN_PATH: Regexp DOT_SEGMENTS: Array[String] + RECORD_ID_TYPES: Array[Class] ABSOLUTE_URL: Regexp RESERVED_HEADERS: Hash[String, String] @@ -54,6 +55,7 @@ module ZammadAPI def self.blank_on_behalf_of_message: (untyped identifier) -> String def self.stringify_header_value: (String, untyped) -> String def self.escape_path_segment: (untyped) -> String + def self.not_a_record_id_message: (untyped value) -> String def self.relative_path: (untyped) -> String def self.refuse_unreadable_path!: (String relative) -> void def self.unreadable_path_message: (String relative) -> String diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 1390e47..b824bce 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -88,6 +88,26 @@ expect { proxy.find('') }.to raise_error(ArgumentError, /record id is required/) expect(a_request(:any, /zammad\.test/)).not_to have_been_made end + + # A record where its id belongs went into the path as it inspects, and + # the 404 for that path was read as an answer about the record. + context 'with a record where its id belongs' do + let(:record) { ZammadAPI::Resources::Group.from_response(client.instance_variable_get(:@transport), { id: 1, name: 'Users' }) } + + it 'refuses exists? rather than answering false for a record that exists' do + expect { proxy.exists?(record) }.to raise_error(ArgumentError, /pass its id/) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'refuses find' do + expect { proxy.find(record) }.to raise_error(ArgumentError, /pass its id/) + end + + it 'refuses destroy rather than raising NotFoundError for a record that is there' do + expect { proxy.destroy(record) }.to raise_error(ArgumentError, /pass its id/) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end end describe '#create' do diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 142f00d..caabea5 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -355,6 +355,35 @@ it 'encodes an already-encoded dot segment rather than passing it on' do expect(described_class.escape_path_segment('%2e%2e')).to eq('%252e%252e') end + + it 'takes a Symbol, for a member that is named rather than numbered' do + expect(described_class.escape_path_segment(:me)).to eq('me') + end + + # `to_s` answers for every object, so a record where its id belongs was + # pasted into the path as it inspects and answered with a 404. + it 'raises for a record where its id belongs' do + record = ZammadAPI::Resources::Group.from_response(unit_transport, { id: 1, name: 'Users' }) + + expect { described_class.escape_path_segment(record) } + .to raise_error(ArgumentError, /record id is an Integer or a String, and this one is ZammadAPI::Resources::Group/) + end + + it 'does not quote what it refuses, which for a record is its attributes' do + record = ZammadAPI::Resources::Group.from_response(unit_transport, { id: 1, name: 'Users' }) + + expect { described_class.escape_path_segment(record) }.to raise_error(ArgumentError) { |error| expect(error.message).not_to include('Users') } + end + + [[1], { id: 1 }, 1.0, true, Object.new].each do |value| + it "raises for #{value.class}, which only prints as something" do + expect { described_class.escape_path_segment(value) }.to raise_error(ArgumentError, /this one is #{value.class}/) + end + end + + it 'still says that an id is missing for nil' do + expect { described_class.escape_path_segment(nil) }.to raise_error(ArgumentError, /record id is required/) + end end describe 'request bodies' do From d8f5d0f464856b186ffd24af511a94f135a38893 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 00:20:21 +0200 Subject: [PATCH 007/121] fix: refuse one attribute given under two spellings A record symbolizes the keys of the attributes it is given, and two keys that land on one name were merged in silence: `client.groups.new('name' => 'Support', name: 'Sales')` built a record holding `name: 'Sales'` alone, so an attribute Hash put together from form parameters and defaults lost a value to Hash order. `assign_attributes` wrote such an attribute twice and kept the last. `Ticket#add_article` took both spellings of `ticket_id` out by hand for this, and nothing else did. `DeepCopy.frozen_copy` refuses the pair with the ArgumentError `DuplicateKeys` raises for a query parameter and a header, at any depth. It compares the sizes of the Hash and its copy, so a Hash built from a response pays no call per key. `assign_attributes` copies its values before it writes the first of them, so a pair inside a later value leaves nothing staged. --- CHANGELOG.md | 7 ++++ lib/zammad_api/deep_copy.rb | 32 +++++++++++++++- lib/zammad_api/resources/base.rb | 21 ++++++++++- lib/zammad_api/resources/ticket.rb | 5 ++- sig/zammad_api/deep_copy.rbs | 1 + spec/unit/zammad_api/attribute_access_spec.rb | 24 ++++++++++++ spec/unit/zammad_api/resources/base_spec.rb | 37 +++++++++++++++++++ 7 files changed, 123 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24dcb4a..16fdd5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -801,6 +801,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a told 404 about it and answered `false` for a ticket that exists, and `destroy(ticket)` raised `NotFoundError` for one that was right there. An id is an `Integer`, a `String` or a `Symbol`; the message names the class of anything else and does not quote it. +- One attribute given under two spellings raises `ArgumentError` instead of keeping + whichever Hash order put last. A record symbolizes the keys of the attributes it is given, + so `client.groups.new('name' => 'Support', name: 'Sales')` built a record holding + `name: 'Sales'` alone, and an attribute Hash put together from form parameters and + defaults lost a value without a word. `create`, `assign_attributes`, `update` and a + writer handed a Hash refuse the pair the same way, at any depth, and nothing is staged + when they do. It is the refusal a query parameter and a header already had. ### Changed diff --git a/lib/zammad_api/deep_copy.rb b/lib/zammad_api/deep_copy.rb index cc7e8db..b038c40 100644 --- a/lib/zammad_api/deep_copy.rb +++ b/lib/zammad_api/deep_copy.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require_relative 'duplicate_keys' + module ZammadAPI # Recursive copies of the plain JSON structures this gem passes around. # @@ -50,15 +52,43 @@ module DeepCopy # @param symbolize_keys [Boolean] whether Hash keys become Symbols, so # that caller-supplied attributes behave the same as decoded responses # @return [Object] a frozen copy + # @raise [ArgumentError] when symbolizing lands two keys of one Hash on + # one name def frozen_copy(value, symbolize_keys: false) case value - when Hash then value.to_h { |key, nested| [symbolize_keys ? symbolize(key) : key, frozen_copy(nested, symbolize_keys: symbolize_keys)] }.freeze + when Hash then frozen_hash(value, symbolize_keys) when Array then value.map { frozen_copy(it, symbolize_keys: symbolize_keys) }.freeze when String then value.dup.freeze else value end end + # The Hash branch of {frozen_copy}. + # + # Two keys that symbolize to one name are refused rather than merged. + # Symbolizing is what creates the collision, the way stringifying does + # for a query - see {DuplicateKeys} - and here it went unrefused: + # `client.groups.new('name' => 'Support', name: 'Sales')` built a record + # holding `name: 'Sales'` alone, and an attribute Hash put together from + # form parameters and defaults lost a value to Hash order without a word. + # {Resources::Ticket#add_article} had to take both spellings of + # `ticket_id` out by hand for it. + # + # Asked of the sizes, so that a Hash with no collision in it - every one + # built from a response - pays one comparison and no call per key. The + # walk that names the two spellings is made only once there is a pair to + # name. + # + # @api private + # @return [Hash] a frozen copy + # @raise [ArgumentError] + def frozen_hash(hash, symbolize_keys) + copy = hash.to_h { |key, nested| [symbolize_keys ? symbolize(key) : key, frozen_copy(nested, symbolize_keys: symbolize_keys)] } + DuplicateKeys.normalize(hash, noun: 'attribute') { symbolize(it) } if symbolize_keys && copy.size != hash.size + + copy.freeze + end + # A writable deep copy, for handing out something callers may treat as # their own. The inverse of {frozen_copy}. # diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index b82317e..4e929a0 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -3,6 +3,7 @@ require_relative '../associations' require_relative '../attribute_access' require_relative '../deep_copy' +require_relative '../duplicate_keys' require_relative '../errors' require_relative '../transport' @@ -342,6 +343,8 @@ def has_many(name, class_name:, path:) # @param transport [Transport] # @param attributes [Hash, nil] # @raise [Error] when an attribute cannot be staged, such as +id+ + # @raise [ArgumentError] when an attribute is named twice, as a String + # and as a Symbol, at any depth def initialize(transport, attributes = {}) given = attributes || {} # The same refusal the writers make, at the one door that did not make @@ -441,7 +444,21 @@ def related # @raise [Error] when an attribute cannot be staged, such as +id+, or # when the record was destroyed. Nothing is staged in either case, so # the record is left as it was. + # @raise [ArgumentError] when an attribute is named twice, as a String + # and as a Symbol. Nothing is staged then either. def assign_attributes(attributes) + # Two spellings of one attribute are refused before anything is + # written, for the reason the constructor refuses them - see + # {DeepCopy.frozen_hash}. Each key is written by its Symbol, so + # `assign_attributes('name' => 'A', name: 'B')` wrote the attribute + # twice and kept whichever Hash order put last. + # + # The values are copied here as well, which is where a pair inside + # one of them is refused. Left to the writes below, a value that + # names a nested key twice raised from the middle of them, with the + # attributes before it already staged. + staged = frozen_attributes(DuplicateKeys.normalize(attributes, noun: 'attribute', &:to_sym)) + # rubocop:disable Style/CombinableLoops -- combining them is the bug # Two passes on purpose: every key is checked before any of them is # written. Combined, `assign_attributes(name: 'X', id: 9, note: 'Y')` @@ -453,8 +470,8 @@ def assign_attributes(attributes) # direct writer's own guard and cannot assume a caller came through # here. That is a second Symbol comparison per attribute, which is not # worth a bypass to avoid. - attributes.each { |key, value| refuse_unwritable!(key.to_sym, value) } - attributes.each { |key, value| write_attribute(key.to_sym, value) } + staged.each { |key, value| refuse_unwritable!(key, value) } + staged.each { |key, value| write_attribute(key, value) } # rubocop:enable Style/CombinableLoops self end diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index 3f3810a..7f1c1f5 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -71,7 +71,10 @@ def add_article(attributes = {}) # String one standing beside it, and the article symbolizes its keys # in the order they come: given `ticket_id` under both spellings, the # String one came last and won, so `add_article` on ticket 7 POSTed - # an article naming whichever ticket the caller's Hash did. + # an article naming whichever ticket the caller's Hash did. An + # article refuses two spellings of one attribute now, and a String + # `ticket_id` left beside this ticket's would be refused as a pair + # the caller never wrote. own = attributes.reject { |key, _| key.to_s == 'ticket_id' } record = TicketArticle.new(transport, own.merge(ticket_id: require_id!)) record.save! diff --git a/sig/zammad_api/deep_copy.rbs b/sig/zammad_api/deep_copy.rbs index 09526b8..b5c7325 100644 --- a/sig/zammad_api/deep_copy.rbs +++ b/sig/zammad_api/deep_copy.rbs @@ -1,6 +1,7 @@ module ZammadAPI module DeepCopy def self?.frozen_copy: (untyped value, ?symbolize_keys: bool) -> untyped + def self?.frozen_hash: (Hash[untyped, untyped] hash, bool symbolize_keys) -> Hash[untyped, untyped] def self?.writable_copy: (untyped value) -> untyped def self?.symbolize: (untyped key) -> untyped end diff --git a/spec/unit/zammad_api/attribute_access_spec.rb b/spec/unit/zammad_api/attribute_access_spec.rb index a0397ed..28f2aea 100644 --- a/spec/unit/zammad_api/attribute_access_spec.rb +++ b/spec/unit/zammad_api/attribute_access_spec.rb @@ -37,6 +37,30 @@ def initialize(attributes) it 'leaves keys alone that cannot become symbols' do expect(record_class.new(1 => 'one').attributes).to eq(1 => 'one') end + + # Symbolizing is what makes two keys one, and the value that came first + # was dropped without a word. + context 'with one attribute under two spellings' do + it 'refuses the pair rather than keeping whichever came last' do + expect { record_class.new('name' => 'Support', name: 'Sales') } + .to raise_error(ArgumentError, /attribute name was given twice, as "name" and as :name/) + end + + it 'refuses a pair inside a nested Hash' do + expect { record_class.new(preferences: { 'locale' => 'de', locale: 'en' }) } + .to raise_error(ArgumentError, /attribute locale was given twice/) + end + + it 'refuses a pair inside a Hash in an Array' do + expect { record_class.new(notes: [{ 'body' => 'a', body: 'b' }]) } + .to raise_error(ArgumentError, /attribute body was given twice/) + end + + it 'takes the same name at two depths, which is two attributes' do + expect(record_class.new('name' => 'Support', preferences: { name: 'Sales' }).attributes) + .to eq(name: 'Support', preferences: { name: 'Sales' }) + end + end end describe 'reading' do diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index d3287b8..bbc729f 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -34,6 +34,23 @@ def self.name expect(group.note).to eq('from a string key') end + # A record built from a Hash put together across several merges held + # whichever spelling Hash order put last, and sent that. + it 'refuses one attribute under two spellings rather than keeping the last' do + expect { client.groups.new('name' => 'Support', name: 'Sales') } + .to raise_error(ArgumentError, /attribute name was given twice, as "name" and as :name/) + end + + it 'refuses two spellings on create before anything is sent' do + expect { client.groups.create('name' => 'Support', name: 'Sales') }.to raise_error(ArgumentError, /given twice/) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'refuses two spellings inside a value a writer is given' do + expect { group.preferences = { 'locale' => 'de', locale: 'en' } }.to raise_error(ArgumentError, /attribute locale was given twice/) + expect(group).not_to be_changed + end + it 'starts without changes' do expect(group).not_to be_changed end @@ -383,6 +400,26 @@ def self.name group.assign_attributes(name: 'Support') expect(group).not_to be_changed end + + # Each key is written by its Symbol, so the attribute was written twice + # and whichever spelling came last in the Hash was the one staged. + context 'with one attribute under two spellings' do + it 'refuses the pair' do + expect { group.assign_attributes('name' => 'A', name: 'B') } + .to raise_error(ArgumentError, /attribute name was given twice, as "name" and as :name/) + end + + it 'stages nothing' do + expect { group.assign_attributes(:note => 'Why', 'name' => 'A', :name => 'B') }.to raise_error(ArgumentError) + expect(group).not_to be_changed + end + + it 'stages nothing where the pair is inside a later value' do + expect { group.assign_attributes(note: 'Why', preferences: { 'locale' => 'de', locale: 'en' }) } + .to raise_error(ArgumentError, /attribute locale was given twice/) + expect(group).not_to be_changed + end + end end describe '#update' do From 6aa7163a9c28920ffda2b9b19cce8eeecad0d1a5 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 00:21:38 +0200 Subject: [PATCH 008/121] fix: keep credentials out of a record's inspect `Resources::Base#inspect` printed every attribute as it stood, and a record can hold a credential: `client.users.new(login: 'x', password: 'hunter2')` is how a user is given a password. `inspect` is what IRB and `pp` show, what an RSpec failure diffs and what an exception report prints for a record it interpolates, so the password went wherever any of those did. `Config#inspect` and the debug log both blank such a value already. `inspect` blanks the value under a key `SENSITIVE_KEY_PATTERN` matches, at any depth. The log's `redact` moves from a private method of a transport to `Transport.redact` so that both print by one rule. `attributes`, `to_h` and `to_json` hand over the values as before. --- CHANGELOG.md | 5 +++ lib/zammad_api/resources/base.rb | 18 ++++++++++- lib/zammad_api/transport.rb | 33 ++++++++++++------- sig/zammad_api/transport.rbs | 2 +- spec/unit/zammad_api/resources/base_spec.rb | 36 +++++++++++++++++++++ spec/unit/zammad_api/transport_spec.rb | 30 +++++++++++++++++ 6 files changed, 111 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16fdd5f..d717d2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -808,6 +808,11 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a defaults lost a value without a word. `create`, `assign_attributes`, `update` and a writer handed a Hash refuse the pair the same way, at any depth, and nothing is staged when they do. It is the refusal a query parameter and a header already had. +- A record's `inspect` blanks the value of an attribute that names a credential, by the + rule the debug log redacts a request with. The attributes were printed as they stood, so + `client.users.new(login: 'x', password: 'hunter2')` showed the password in IRB and under + `pp`, in an RSpec failure and in any exception report that interpolates the record. + `attributes`, `to_h` and `to_json` still hand the value over. ### Changed diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 4e929a0..c4fc271 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -648,7 +648,23 @@ def destroy true end - def inspect = "#<#{self.class.name} id=#{id.inspect} new_record=#{new_record?}#{' destroyed=true' if destroyed?} attributes=#{attributes.inspect}>" + # Says which record this is and what it holds, with the value of an + # attribute that names a credential blanked. + # + # The attributes were printed as they stood, and a record can hold a + # credential: `client.users.new(login: 'x', password: 'hunter2')` is + # how a user is given one. Its `inspect` is what IRB and `pp` show, + # what an RSpec failure diffs and what an exception report prints for + # a record it interpolates, so the password staged for one request + # was written wherever any of those went. The log has blanked the same + # key in the same request all along, by {Transport.redact}, which is + # the rule applied here. + # + # Only what is printed. {#attributes}, {#to_h} and {#to_json} hand over + # the values, because sending them is what a record is for. + # + # @return [String] + def inspect = "#<#{self.class.name} id=#{id.inspect} new_record=#{new_record?}#{' destroyed=true' if destroyed?} attributes=#{Transport.redact(attributes).inspect}>" protected diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 6d4075d..b93ee26 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -684,6 +684,25 @@ def self.redact_query_pair(pair) decoded && !SENSITIVE_KEY_PATTERN.match?(decoded) ? pair : "#{name}=#{REDACTED}" end + # A structure as it may be printed: with the value under every key that + # names a credential blanked, at any depth. See {SENSITIVE_KEY_PATTERN} + # for which keys those are. + # + # Public for {Resources::Base#inspect}. This was the log's own rule, and + # a record printed the same attributes with nothing applied to them. + # + # @api private + # @param value [Object] + # @return [Object] a copy where anything was blanked, or holds a Hash or + # an Array + def self.redact(value) + case value + when Hash then value.to_h { |key, nested| [key, SENSITIVE_KEY_PATTERN.match?(key.to_s) ? REDACTED : redact(nested)] } + when Array then value.map { redact(it) } + else value + end + end + # The bytes a request body goes out as. # # Encoded here rather than left to Faraday's JSON middleware, because a @@ -1122,7 +1141,7 @@ def raw_body!(body) def log_request(method, path, query, body, headers) logger.debug do - "Zammad API request: #{method.to_s.upcase} #{Transport.redact_path(path)}#{" query=#{redact(query).inspect}" if query}#{" headers=#{redact(headers).inspect}" if headers}" + "Zammad API request: #{method.to_s.upcase} #{Transport.redact_path(path)}#{" query=#{Transport.redact(query).inspect}" if query}#{" headers=#{Transport.redact(headers).inspect}" if headers}" end logger.debug { "Zammad API payload: #{loggable_body(body).inspect}" } if body end @@ -1142,24 +1161,16 @@ def log_response(method, path, response, started) # not - a form body, a file - nothing in it can be told from a # credential, and its size is logged in its place. def loggable_body(body) - return redact(body) if !body.is_a?(String) + return Transport.redact(body) if !body.is_a?(String) decoded = JSON.parse(body) - decoded.is_a?(Hash) || decoded.is_a?(Array) ? redact(decoded) : unlogged_body(body) + decoded.is_a?(Hash) || decoded.is_a?(Array) ? Transport.redact(decoded) : unlogged_body(body) rescue JSON::JSONError, EncodingError unlogged_body(body) end def unlogged_body(body) = "[#{body.bytesize} bytes that are not a JSON object or array, not logged]" - def redact(value) - case value - when Hash then value.to_h { |key, nested| [key, SENSITIVE_KEY_PATTERN.match?(key.to_s) ? REDACTED : redact(nested)] } - when Array then value.map { redact(it) } - else value - end - end - def logger = config.logger end end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 3d8aaf1..5bef0a1 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -40,6 +40,7 @@ module ZammadAPI def self.redact_path: (untyped path) -> String def self.redact_query_pair: (String pair) -> String + def self.redact: (untyped value) -> untyped def self.stringify_query: (Hash[untyped, untyped]) -> Hash[String, untyped] def self.stringify_query_hash: (Hash[untyped, untyped], String?) -> Hash[String, untyped] def self.stringify_query_value: (String, untyped) -> untyped @@ -82,7 +83,6 @@ module ZammadAPI def raw_body!: (untyped) -> String def log_request: (Symbol, String, Hash[Symbol, untyped]?, untyped, Hash[String, String]?) -> void def log_response: (Symbol, String, Response, Float) -> void - def redact: (untyped) -> untyped def loggable_body: (untyped body) -> untyped def unlogged_body: (String body) -> String def reportable_cause: (StandardError error) -> StandardError? diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index bbc729f..5ebd858 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -916,6 +916,42 @@ def self.name expect(group.inspect) .to eq('#') end + + # A record is printed by IRB, by pp, in an RSpec failure and in an + # exception report, and a user is given a password by staging one. + context 'with an attribute that names a credential' do + let(:user) { client.users.new(login: 'x', password: 'hunter2', preferences: { tokens: [{ access_token: 's3cret' }], locale: 'de' }) } + + it 'blanks a staged password' do + expect(user.inspect).to include('password: "[REDACTED]"').and include('login: "x"') + end + + it 'does not print the password anywhere' do + expect(user.inspect).not_to include('hunter2') + end + + it 'blanks a credential nested in another attribute' do + expect(user.inspect).not_to include('s3cret') + end + + it 'leaves what sits beside a nested credential readable' do + expect(user.inspect).to include('locale: "de"') + end + + it 'is what pp prints as well' do + expect(PP.pp(user, +'')).not_to include('hunter2') + end + + it 'blanks one that was written after the record was built' do + user.password = 'correct horse' + expect(user.inspect).not_to include('correct horse') + end + + it 'still hands the value over to what sends it' do + expect(user.attributes[:password]).to eq('hunter2') + expect(user.to_h[:password]).to eq('hunter2') + end + end end describe '.from_response' do diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index caabea5..312d11e 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -318,6 +318,36 @@ end end + describe '.redact' do + it 'blanks the value under a key that names a credential' do + expect(described_class.redact({ login: 'x', password: 'hunter2' })).to eq({ login: 'x', password: '[REDACTED]' }) + end + + it 'reads a String key the way it reads a Symbol' do + expect(described_class.redact({ 'api_key' => 'k' })).to eq({ 'api_key' => '[REDACTED]' }) + end + + it 'blanks one at any depth, through Hashes and Arrays' do + expect(described_class.redact({ users: [{ preferences: { access_token: 't', locale: 'de' } }] })) + .to eq({ users: [{ preferences: { access_token: '[REDACTED]', locale: 'de' } }] }) + end + + it 'blanks the whole of a structure held under such a key' do + expect(described_class.redact({ tokens: [{ name: 'a' }] })).to eq({ tokens: '[REDACTED]' }) + end + + it 'leaves what it was given as it was' do + attributes = { password: 'hunter2' } + described_class.redact(attributes) + + expect(attributes).to eq({ password: 'hunter2' }) + end + + it 'hands back anything that is not a structure' do + expect(described_class.redact('password')).to eq('password') + end + end + describe '.escape_path_segment' do it 'leaves an ordinary id alone' do expect(described_class.escape_path_segment(42)).to eq('42') From f324a4d911d117d9bdbfe27fdfded67151cb54c5 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 00:25:28 +0200 Subject: [PATCH 009/121] fix: have the test kit retry a read as the client does The real transport sends a GET again that was answered 429 or 5xx. `ZammadAPI::Test` raised for the first such answer. Stubbed 503 and then 200, `client.groups.find(1)` returns the group against Zammad and raised ServerError against the stand-in, and a single stubbed 503 was recorded as one request where the wire carries three. A test of code that leans on the retry passed or failed the other way round from production. `Test#answer` attempts a request up to `retries` more times. Each attempt is recorded and takes a stub of its own, and there is no wait between them. Whether a response is retried is asked of `Transport.retried?`, which reads the options the retry middleware is built with and has the middleware itself say whether it would wait, so a write is not repeated and a Retry-After longer than the timeout ends the attempts, as on the wire. `retry_options` becomes a class method for it. `ZammadAPI::Test.new(retries: 0)` raises for the first failure. --- CHANGELOG.md | 9 ++ README.md | 17 +++ lib/zammad_api/test.rb | 59 ++++++++-- lib/zammad_api/transport.rb | 87 ++++++++++----- sig/vendor/faraday.rbs | 16 +++ sig/zammad_api/test.rbs | 1 + sig/zammad_api/transport.rbs | 3 +- spec/unit/zammad_api/test_spec.rb | 149 +++++++++++++++++++++++++ spec/unit/zammad_api/transport_spec.rb | 56 ++++++++++ 9 files changed, 362 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d717d2f..d91a2f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -813,6 +813,15 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `client.users.new(login: 'x', password: 'hunter2')` showed the password in IRB and under `pp`, in an RSpec failure and in any exception report that interpolates the record. `attributes`, `to_h` and `to_json` still hand the value over. +- The test kit sends a read again that the client would retry. It raised for the first + stubbed 429 or 5xx, where the real transport asks again: stubbed 503 and then 200, + `client.groups.find(1)` returns the group against Zammad and raised `ServerError` against + the stand-in, and a single stubbed 503 was recorded as one request where the wire carries + three. A `GET` is now attempted up to `retries` more times, each attempt recorded and + answered by the next stub, with no wait in between. Whether a response is retried is the + transport's own rule, so a write is not repeated and a `Retry-After` longer than + `timeout` ends the attempts. `ZammadAPI::Test.new(retries: 0)` raises for the first + failure, as before. ### Changed diff --git a/README.md b/README.md index 734313c..10296b9 100644 --- a/README.md +++ b/README.md @@ -1187,6 +1187,23 @@ the wire would refuse is refused here too. `headers` names only what the call as the ones the client sets from its configuration are not in it, and an `on_behalf_of` scope has a field of its own. +A read that is answered 429 or 5xx is sent again, as it is on the wire: a `GET`, up to +`retries` times, and never a write. Each attempt is in `requests` and takes the next stub +of a sequence, so a read that fails once and then succeeds is two stubs: + +```ruby +zammad.stub(:get, 'api/v1/tickets/1', status: 503) +zammad.stub(:get, 'api/v1/tickets/1', body: {id: 1, title: 'Help'}) + +zammad.client.tickets.find(1).title # => "Help" +zammad.requests.size # => 2 +``` + +A single failing stub answers every attempt, so the error is raised once the retries are +spent, with three requests recorded under the default of two retries. There is no wait +between attempts. A `Retry-After` longer than `timeout` ends them at once, as it does +against Zammad. `ZammadAPI::Test.new(retries: 0)` raises for the first failure. + A request that was not stubbed raises `ZammadAPI::Test::UnstubbedRequestError`, listing what is stubbed, rather than answering with something empty. It is deliberately not a `ZammadAPI::Error`: a forgotten stub means the test is wrong, not that Zammad refused diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index 40a17c5..92ef189 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -27,6 +27,11 @@ module ZammadAPI # @example An error path # zammad.stub(:get, 'api/v1/tickets/9', status: 404, body: {error: 'not found'}) # # the code under test sees ZammadAPI::NotFoundError + # + # @example A read the client retries + # zammad.stub(:get, 'api/v1/tickets/1', status: 503) + # zammad.stub(:get, 'api/v1/tickets/1', body: {id: 1, title: 'Help'}) + # # the code under test sees the ticket, and zammad.requests holds both attempts class Test # Raised when the code under test reaches an endpoint that was not stubbed. # @@ -131,6 +136,10 @@ def initialize(**options) # a scoped stub and a catch-all are two separate answers, each of which # keeps answering. # + # A +GET+ answered with a status the client retries - 429, 500, 502, 503 + # or 504 - is asked again, as it is on the wire, and each attempt takes + # the next stub of the sequence: see {#answer}. + # # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ # @param path [String] path relative to the instance URL, leading slash # optional @@ -213,9 +222,28 @@ def inspect = @monitor.synchronize { "#<#{self.class.name} stubbed=#{@stubs.size # This is the {Transport} interface, called by the client rather than by a # test. # + # A request the real transport would send again is sent again here: a + # +GET+ answered 429 or 5xx, as many times as {Config#retries} allows. + # The first such answer used to be raised. Stubbed 503 and then 200, + # `client.groups.find(1)` returns the group on the wire and raised + # ServerError here, and a single stubbed 503 was recorded as one request + # where the wire carries three - so a test of code that leans on the + # retry passed or failed the other way round from production. + # + # Each attempt is recorded and takes a stub of its own, which is what + # makes "fails once, then answers" two stubs in a row. There is no wait + # between them: the backoff is the one part of a retry a test has no use + # for. Whether a response is retried at all is {Transport.retried?}, the + # real transport's own rule, so a +Retry-After+ longer than the timeout + # ends the attempts here as it does there. + # + # The count is this stand-in's, read from the options it was built + # with: `ZammadAPI::Test.new(retries: 0)` raises for the first failure. + # # @api private # @return [Response] - # @raise [ResponseError] for a stubbed non-2xx status + # @raise [ResponseError] for a stubbed non-2xx status, once the retries + # it is due are spent # @raise [UnstubbedRequestError] when no stub matches def answer(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil, on_behalf_of: nil) relative = ::ZammadAPI::Transport.relative_path(path) @@ -232,15 +260,14 @@ def answer(method, path, operation:, query: nil, body: nil, headers: nil, resour # too, before anything is recorded. What is recorded is the body as the # test wrote it, which is what a test asserts against. ::ZammadAPI::Transport.encode_body(body, operation: operation, resource_class: resource_class) + request = Request.new(verb: method, path: relative, query: params, body: snapshot(body), headers: fields, on_behalf_of: on_behalf_of) - stub = @monitor.synchronize do - @requests << Request.new(verb: method, path: relative, query: params, body: snapshot(body), headers: fields, on_behalf_of: on_behalf_of) - take(method, relative, params) - end + response = attempt(request) + config.retries.times do + break if !::ZammadAPI::Transport.retried?(config, method, response) - raise UnstubbedRequestError, unstubbed_message(method, relative, params) if stub.nil? - - response = response_for(stub, params) + response = attempt(request) + end return response if response.success? raise ResponseError.build(response, operation: operation, resource_class: resource_class) @@ -248,6 +275,22 @@ def answer(method, path, operation:, query: nil, body: nil, headers: nil, resour private + # One delivery of a request: recorded, and answered by the stub whose + # turn it is. + # + # @return [Response] + # @raise [UnstubbedRequestError] when no stub matches + def attempt(request) + stub = @monitor.synchronize do + @requests << request + take(request.verb, request.path, request.query) + end + + raise UnstubbedRequestError, unstubbed_message(request.verb, request.path, request.query) if stub.nil? + + response_for(stub, request.query) + end + def key(method, path) = [method.to_sym, ::ZammadAPI::Transport.relative_path(path)] # The headers a stub answers with, downcased the way a {Response} carries diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index b93ee26..6a32554 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -738,6 +738,66 @@ def self.encode_body(body, operation:, resource_class: nil) 'attachment, and leave out a Float that is NaN or infinite.' end + # What the retry middleware is built with. + # + # +max_interval+ is what bounds a wait. The retry middleware sleeps for + # whatever a +Retry-After+ header says, and its own ceiling defaults to + # no ceiling at all: a maintenance page answering 503 with + # +Retry-After: 3600+ held the calling thread for an hour per retry, + # whatever +timeout+ and +retry_interval+ said, before raising the error + # it could have raised at once. + # + # +timeout+ is the bound, because it is already how long this client + # was told it may wait for an answer. A +Retry-After+ within it is + # honoured; a longer one is not waited out, and the response it came + # with is reported as the error it is, with the figure still readable + # from {RateLimitError#retry_after}. + # + # Public for {.retried?}, which {Test} asks. + # + # @api private + # @param config [Config] + # @return [Hash{Symbol => Object}] + def self.retry_options(config) + { + max: config.retries, + interval: config.retry_interval, + max_interval: config.timeout, + interval_randomness: 0.5, + backoff_factor: 2, + retry_statuses: RETRIABLE_STATUSES, + methods: RETRIABLE_METHODS, + exceptions: RETRIABLE_EXCEPTIONS + } + end + + # Whether a request answered with +response+ is one the retry middleware + # sends again, while it has attempts left. + # + # Public for {Test}, for the reason {.stringify_query} is: a stand-in + # that raised for the first 503 a +GET+ was answered with, where the + # wire asks again, made a test of code that leans on the retry pass or + # fail the other way round from production. + # + # The wait is asked of the middleware itself, built from the options + # above, and not worked out a second time here. It answers nil where a + # +Retry-After+ - or a +RateLimit-Reset+, or either as a date - asks + # for longer than it may wait, which is the one response with a + # retriable status that it does not send again. A copy of that reading + # is the kind that gets changed in one place. + # + # @api private + # @param config [Config] + # @param method [Symbol] + # @param response [Response] + # @return [Boolean] + def self.retried?(config, method, response) + options = retry_options(config) + return false if !options[:methods].include?(method) || !options[:retry_statuses].include?(response.status) + + !Faraday::Retry::Middleware.new(nil, options).calculate_sleep_amount(1, { response_headers: Faraday::Utils::Headers.new(response.headers) }).nil? + end + # @param config [Config] def initialize(config) @config = config @@ -885,7 +945,7 @@ def build_connection ) do |faraday| apply_authentication(faraday) faraday.request :json - faraday.request :retry, retry_options + faraday.request :retry, Transport.retry_options(config) # Last in the stack, so a caller's middleware sees the request as this # gem finished building it and the response before anything else does. config.middleware&.call(faraday) @@ -1002,31 +1062,6 @@ def apply_authentication(faraday) end end - # +max_interval+ is what bounds a wait. The retry middleware sleeps for - # whatever a +Retry-After+ header says, and its own ceiling defaults to - # no ceiling at all: a maintenance page answering 503 with - # +Retry-After: 3600+ held the calling thread for an hour per retry, - # whatever +timeout+ and +retry_interval+ said, before raising the error - # it could have raised at once. - # - # +timeout+ is the bound, because it is already how long this client - # was told it may wait for an answer. A +Retry-After+ within it is - # honoured; a longer one is not waited out, and the response it came - # with is reported as the error it is, with the figure still readable - # from {RateLimitError#retry_after}. - def retry_options - { - max: config.retries, - interval: config.retry_interval, - max_interval: config.timeout, - interval_randomness: 0.5, - backoff_factor: 2, - retry_statuses: RETRIABLE_STATUSES, - methods: RETRIABLE_METHODS, - exceptions: RETRIABLE_EXCEPTIONS - } - end - def decode(faraday_response) headers = faraday_response.headers.to_h.transform_keys { it.to_s.downcase }.freeze raw_body = raw_body!(faraday_response.body) diff --git a/sig/vendor/faraday.rbs b/sig/vendor/faraday.rbs index 728de63..a811cfb 100644 --- a/sig/vendor/faraday.rbs +++ b/sig/vendor/faraday.rbs @@ -52,6 +52,22 @@ module Faraday def self.decode: (String? query) -> untyped end + # The retry middleware, asked what it would do with a response. See + # ZammadAPI::Transport.retried?. + module Retry + class Middleware + def initialize: (untyped app, ?untyped options) -> void + def calculate_sleep_amount: (Integer retries, untyped env) -> Float? + end + end + + module Utils + # Response headers, read whatever the case of the name. + class Headers + def initialize: (?Hash[untyped, untyped] hash) -> void + end + end + def self.new: (**untyped) ?{ (Connection) -> void } -> Connection def self.default_adapter: () -> Symbol end diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs index e478b6c..9215855 100644 --- a/sig/zammad_api/test.rbs +++ b/sig/zammad_api/test.rbs @@ -51,6 +51,7 @@ module ZammadAPI private + def attempt: (Request request) -> Response def key: (Symbol method, String path) -> [Symbol, String] def raw_body_for: (untyped body) -> String def response_headers: (Hash[untyped, untyped] headers, untyped body) -> Hash[String, String] diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 5bef0a1..0da883f 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -61,6 +61,8 @@ module ZammadAPI def self.refuse_unreadable_path!: (String relative) -> void def self.unreadable_path_message: (String relative) -> String def self.encode_body: (untyped body, operation: String, ?resource_class: Class?) -> String? + def self.retry_options: (Config config) -> Hash[Symbol, untyped] + def self.retried?: (Config config, Symbol method, Response response) -> bool def initialize: (Config) -> void def with_on_behalf_of: ((String | Integer)? identifier) -> Transport @@ -78,7 +80,6 @@ module ZammadAPI def refused_middleware: (Class klass) -> String? def refused_middleware_message: (Class klass, String refused) -> String def apply_authentication: (untyped) -> void - def retry_options: () -> Hash[Symbol, untyped] def decode: (untyped) -> Response def raw_body!: (untyped) -> String def log_request: (Symbol, String, Hash[Symbol, untyped]?, untyped, Hash[String, String]?) -> void diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 9d639e8..1a63c3b 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -663,6 +663,155 @@ # first of those, so the obvious way to stand in for a list endpoint made # every full read of it raise PaginationError - against a real Zammad the # same code works, because page 2 comes back empty. + # The real transport sends a GET again that was answered 429 or 5xx. The + # stand-in raised for the first such answer, so a test of code that leans + # on the retry passed or failed the other way round from production. + describe 'a read the client retries' do + def find = client.groups.find(1) + + context 'when it fails once and is then answered' do + before do + zammad.stub(:get, 'api/v1/groups/1', status: 503, body: { error: 'down' }) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) + end + + it 'answers with the record, as the wire does' do + expect(find.name).to eq('Users') + end + + it 'records both attempts' do + find + expect(zammad.requests.map(&:path)).to eq(%w[api/v1/groups/1 api/v1/groups/1]) + end + + it 'records the second attempt as the request the first was' do + find + expect(zammad.requests.last).to eq(zammad.requests.first) + end + end + + [429, 500, 502, 503, 504].each do |status| + it "asks again past a #{status}" do + zammad.stub(:get, 'api/v1/groups/1', status: status) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + + expect(find.id).to eq(1) + end + end + + context 'when it keeps failing' do + before { zammad.stub(:get, 'api/v1/groups/1', status: 503, body: { error: 'down' }) } + + it 'raises the error for the status once the retries are spent' do + expect { find }.to raise_error(ZammadAPI::ServerError, /down/) + end + + it 'records as many requests as the wire would carry' do + expect { find }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(1 + zammad.config.retries) + end + end + + it 'follows the number of retries it was built with' do + zammad = described_class.new(retries: 4) + zammad.stub(:get, 'api/v1/groups/1', status: 500) + + expect { zammad.client.groups.find(1) }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(5) + end + + it 'raises for the first failure where it was built without retries' do + zammad = described_class.new(retries: 0) + zammad.stub(:get, 'api/v1/groups/1', status: 503) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + + expect { zammad.client.groups.find(1) }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(1) + end + + it 'does not ask again past a status the client does not retry' do + zammad.stub(:get, 'api/v1/groups/1', status: 404) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + + expect { find }.to raise_error(ZammadAPI::NotFoundError) + expect(zammad.requests.size).to eq(1) + end + + # A write is never repeated on the wire, so it is not repeated here. + it 'does not repeat a POST' do + zammad.stub(:post, 'api/v1/groups', status: 503) + zammad.stub(:post, 'api/v1/groups', status: 201, body: { id: 1 }) + + expect { client.groups.create(name: 'Users') }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(1) + end + + it 'does not repeat a PUT' do + zammad.stub(:put, 'api/v1/groups/1', status: 504) + + expect { client.put('api/v1/groups/1', body: { name: 'Users' }) }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(1) + end + + it 'does not repeat a DELETE' do + zammad.stub(:delete, 'api/v1/groups/1', status: 500) + + expect { client.groups.destroy(1) }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(1) + end + + # The wire does not wait out a Retry-After longer than the timeout: it + # reports the response at once. + context 'when the answer asks for a longer wait than the timeout' do + before do + zammad.stub(:get, 'api/v1/groups/1', status: 429, headers: { 'Retry-After' => '3600' }) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + end + + it 'does not ask again' do + expect { find }.to raise_error(ZammadAPI::RateLimitError) + expect(zammad.requests.size).to eq(1) + end + + it 'leaves the wait readable from the error' do + expect { find }.to raise_error(ZammadAPI::RateLimitError) { |error| expect(error.retry_after).to eq(3600) } + end + end + + context 'when the answer asks for a wait within the timeout' do + before do + zammad.stub(:get, 'api/v1/groups/1', status: 429, headers: { 'Retry-After' => '30' }) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + end + + it 'asks again' do + expect(find.id).to eq(1) + end + + it 'does not wait first' do + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + find + + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 5 + end + end + + it 'asks again for a page of a list, and reads the list from the stub after' do + zammad.stub(:get, 'api/v1/groups', status: 502) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'A' }]) + + expect(client.groups.map(&:name)).to eq(['A']) + end + + it 'carries the scope of a client acting for another user on every attempt' do + zammad.stub(:get, 'api/v1/groups/1', status: 503) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + client.on_behalf_of('agent@example.com').groups.find(1) + + expect(zammad.requests.map(&:on_behalf_of)).to eq(%w[agent@example.com agent@example.com]) + end + end + describe 'a list endpoint stubbed once' do subject(:zammad) { described_class.new } diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 312d11e..8a66a29 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -318,6 +318,62 @@ end end + # The question the test kit asks, so that it sends again what the wire + # sends again. + describe '.retried?' do + let(:config) { ZammadAPI::Config.new(**unit_config(retries: 2, timeout: 60)) } + + def response(status, headers = {}) + ZammadAPI::Response.new(status: status, headers: headers, body: nil, raw_body: '', json: false) + end + + described_class::RETRIABLE_STATUSES.each do |status| + it "is true for a GET answered #{status}" do + expect(described_class.retried?(config, :get, response(status))).to be(true) + end + end + + [200, 404, 422].each do |status| + it "is false for a GET answered #{status}" do + expect(described_class.retried?(config, :get, response(status))).to be(false) + end + end + + %i[post put delete].each do |verb| + it "is false for a #{verb.to_s.upcase}, which is never sent twice" do + expect(described_class.retried?(config, verb, response(503))).to be(false) + end + end + + it 'is false where Retry-After asks for longer than the timeout' do + expect(described_class.retried?(config, :get, response(429, 'retry-after' => '61'))).to be(false) + end + + it 'is true where Retry-After asks for no longer than the timeout' do + expect(described_class.retried?(config, :get, response(429, 'retry-after' => '60'))).to be(true) + end + + it 'reads a Retry-After that is a date' do + expect(described_class.retried?(config, :get, response(503, 'retry-after' => (Time.now + 3600).utc.strftime('%a, %d %b %Y %H:%M:%S GMT')))).to be(false) + end + + it 'reads a RateLimit-Reset the same way' do + expect(described_class.retried?(config, :get, response(429, 'ratelimit-reset' => '3600'))).to be(false) + end + + # What makes this the transport's own answer and not a second reading of + # the same rules: a stack that was answered this way made one request. + it 'agrees with what a request does' do + stub_request(:get, url).to_return({ status: 429, headers: { 'Retry-After' => '3600' } }, json_response([])) + transport = unit_transport(retries: 2, retry_interval: 0.01, timeout: 2) + + expect { transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::RateLimitError) do |error| + expect(described_class.retried?(transport.config, :get, error.response)).to be(false) + end + expect(a_request(:get, url)).to have_been_made.once + end + end + describe '.redact' do it 'blanks the value under a key that names a credential' do expect(described_class.redact({ login: 'x', password: 'hunter2' })).to eq({ login: 'x', password: '[REDACTED]' }) From 8d5bedcdb50c63f8696f3d118591d17f8ea5b3fa Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 00:29:48 +0200 Subject: [PATCH 010/121] fix: read an index that does not page in one request A walk learns the page size from the first page and asks for the next while pages come back that full. An index that serves every record in one response and reads no `page`, as `api/v1/object_manager_attributes` does, answers that with the same list, and the guard against an endpoint that ignores `page` raised PaginationError for it. A resource declared for such an endpoint could not be read: `to_a` raised with every record in hand, and a `find_by` that missed raised instead of answering nil, which broke `find_by(...) || create(...)`. The two responses look the same from an endpoint that serves only the first of many pages, so this is declared and not inferred. A resource says `paginated false`, and its index is read in one request that names no page. `in_batches(of:)` slices that response and `page` refuses such a collection. A search still pages, and whether the index sorts is still what `sortable` says. PaginationError says what to declare where an index repeated its first page. --- CHANGELOG.md | 11 ++ README.md | 23 +++ lib/zammad_api/collection.rb | 64 +++++++- lib/zammad_api/errors.rb | 17 ++- lib/zammad_api/resource_proxy.rb | 5 +- lib/zammad_api/resources/base.rb | 44 ++++++ sig/zammad_api/collection.rbs | 5 +- sig/zammad_api/errors.rbs | 4 +- sig/zammad_api/resource_proxy.rbs | 2 +- sig/zammad_api/resources/base.rbs | 3 + spec/unit/zammad_api/collection_spec.rb | 155 ++++++++++++++++++++ spec/unit/zammad_api/resource_proxy_spec.rb | 56 +++++++ spec/unit/zammad_api/resources/base_spec.rb | 27 ++++ spec/unit/zammad_api/test_spec.rb | 22 +++ 14 files changed, 425 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d91a2f9..7a4bf58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -822,6 +822,17 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a transport's own rule, so a write is not repeated and a `Retry-After` longer than `timeout` ends the attempts. `ZammadAPI::Test.new(retries: 0)` raises for the first failure, as before. +- A resource can declare that its index endpoint does not page, with `paginated false`, + and is then read in one request. A walk asks for the page after a full one, and an + endpoint that serves every record in one response and reads no `page` — + `api/v1/object_manager_attributes` is one — answers that with the same list. The guard + against an endpoint that ignores `page` raised `PaginationError` for it, so a resource + declared for such an endpoint could not be read at all: `to_a` raised with every record + in hand, and a `find_by` that missed raised instead of answering `nil`, which broke + `find_by(...) || create(...)`. Nothing in the responses tells such an endpoint from one + that serves only its first page, so it is declared rather than inferred, and the error + for an index that repeats its first page now says what to declare. `page` refuses a + resource declared this way. Whether its index sorts is still what `sortable` says. ### Changed diff --git a/README.md b/README.md index 10296b9..8335cbe 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,7 @@ Say what else is true of the endpoint, where it differs from the defaults: | `search_filters :role_ids` | none | What that search narrows by besides the term, `condition:` and `ids:`. `search` refuses any other keyword. | | `max_per_page 100` | `1000` | The largest page the index endpoint serves. | | `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. | +| `paginated false` | `true` | The index endpoint serves every record in one response and reads no `page`. It is read in one request, and `page` refuses it. | | `belongs_to :role, class_name: 'Role'` | — | A foreign key, read as a record through `record.related.role`. | | `has_many :members, class_name: 'User', path: ->(id) { "…/#{id}" }` | — | A list served whole by an endpoint of its own. | @@ -306,6 +307,28 @@ Say what else is true of the endpoint, where it differs from the defaults: full name, `'Acme::Role'`. A subclass of a modelled resource works too, and inherits what its parent declares: `class MyTicket < ZammadAPI::Resources::Ticket`. +Most of Zammad's index endpoints page, and a collection walks them a page at a time. One +that does not — `api/v1/object_manager_attributes` serves every attribute in one response, +whatever it is asked — answers the request for a second page with the first again, which +a walk reports as `ZammadAPI::PaginationError` rather than read as the end. Declare such a +resource `paginated false`: + +```ruby +class ObjectAttribute < ZammadAPI::Resources::Base + path 'api/v1/object_manager_attributes' + paginated false + sortable false +end + +client.resource(ObjectAttribute).find_by(name: 'priority_id') # one request +``` + +Declare it only where the endpoint does serve every record. One that ignores `page` and +caps what it serves would be read as far as its cap, with nothing to say that there is +more. Whether the endpoint sorts is a declaration of its own: this one reads no parameter +at all, so it says `sortable false` as well. A search always pages, whatever the index +beside it does. + Use raw requests for an endpoint that is not shaped like that — an action, a report, a setting. diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb index 262b531..caff818 100644 --- a/lib/zammad_api/collection.rb +++ b/lib/zammad_api/collection.rb @@ -15,6 +15,10 @@ module ZammadAPI # +Enumerable+ stop the walk as soon as they have enough, so neither has to # download everything. # + # An index that serves every record in one response and reads no +page+ is + # read in one request instead, where its resource says so: see + # {Resources::Base.paginated}. + # # @example Iterate every ticket # client.tickets.all.each { |ticket| puts ticket.title } # @@ -57,7 +61,10 @@ class Collection # +per_page+ once one has come back with nothing on it, which a read # sized by {#first} may and a batch size a caller chose may not: see # {#widened} - def initialize(transport:, resource_class:, path:, operation:, max_per_page:, sortable:, unsortable_hint:, query: {}, per_page: nil, page: nil, search: false, widens: false) + # @param paginated [Boolean] whether this endpoint reads +page+ and + # +per_page+. One that does not serves every record in one response, + # and is read in one request: see {#read_whole} + def initialize(transport:, resource_class:, path:, operation:, max_per_page:, sortable:, unsortable_hint:, query: {}, per_page: nil, page: nil, search: false, widens: false, paginated: true) @transport = transport @resource_class = resource_class @path = path @@ -84,6 +91,7 @@ def initialize(transport:, resource_class:, path:, operation:, max_per_page:, so @page = page @search = search @widens = widens + @paginated = paginated end # Yields every record, fetching further pages as needed. @@ -115,6 +123,9 @@ def find_each(batch_size: nil, &block) # so +of+ is what sizes it. For groups of a size the API knows nothing # about, slice the records instead: +find_each.each_slice(12)+. # + # An index that is not paginated has one response for every record, so + # there a batch is a slice of it, of the same size at most. + # # @param of [Integer, nil] records fetched per request # @yieldparam records [Array] # @return [Enumerator] when no block is given @@ -122,7 +133,7 @@ def in_batches(of: nil, &block) return to_enum(:in_batches, of: of) if !block return with(per_page: page_size!(of, 'of')).in_batches(&block) if of - walk(&block) + @paginated ? walk(&block) : read_whole(&block) self end @@ -143,9 +154,11 @@ def in_batches(of: nil, &block) # @param per_page [Integer, nil] records on the page, as many as the endpoint # serves by default # @return [Collection] - # @raise [ArgumentError] for a page size the endpoint does not serve + # @raise [ArgumentError] for a page size the endpoint does not serve, or + # an endpoint that does not page at all def page(number, per_page: nil) raise ArgumentError, 'page needs to be a positive integer' if !number.is_a?(Integer) || !number.positive? + raise ArgumentError, "#{@path} serves every record in one response and reads no page parameter, so page(#{number}) would hold all of them, whatever the number. Read them with each, or in groups with each_slice." if !@paginated return with(page: number) if per_page.nil? size = positive_integer!(per_page, 'per_page') @@ -362,7 +375,7 @@ def count(*args, &block) def empty? = first.nil? def inspect - "#<#{self.class.name} #{@resource_class.name} path=#{@path.inspect} per_page=#{@per_page}#{" page=#{@page}" if @page}>" + "#<#{self.class.name} #{@resource_class.name} path=#{@path.inspect} per_page=#{@per_page}#{" page=#{@page}" if @page}#{' paginated=false' if !@paginated}>" end private @@ -387,8 +400,11 @@ def each_distinct # endpoint serves - {#clamp_per_page} would reduce it to the same size the # collection already has. A zero or negative count is left to # Enumerable#first, which has its own answers for both. + # + # And not where the endpoint does not page: it serves every record + # whatever it is asked for, so there is no request to size. def own_request_for_first?(count) - return false if @page + return false if @page || !@paginated count.is_a?(Integer) && count.positive? && count <= @max_per_page end @@ -472,6 +488,34 @@ def page_size!(value, name) size end + # The one read of an index that does not page: every record it serves, + # from one request that names no page. + # + # Walked like the others, such an index never got past its first page. + # A walk learns the page size from the first page and asks for the next + # while pages come back that full, so a whole list was always followed + # by a request for page two - and an endpoint that reads no +page+ + # answers that with the same list. The repeated-page guard is there for + # exactly that answer, so `to_a` raised PaginationError with every + # record in hand, and a `find_by` that found nothing on the first page + # raised it instead of answering nil. + # + # Nothing in the two responses tells such an endpoint from one that + # ignores +page+ and serves the first hundred of a thousand records. + # Reading that one in a single request would return a truncated list and + # call it whole, which is what the guard exists to refuse. So this is + # not inferred from a page that repeats: the resource says it, with + # {Resources::Base.paginated}, and the guard stays as it is for every + # resource that does not. + # + # The batches are slices of the one response, so that `in_batches(of: + # 50)` hands a block fifty records at most here as everywhere else. + def read_whole(&block) + records, = fetch(1, @per_page) + + records.each_slice(@per_page, &block) + end + def walk page = @page || 1 previous = nil @@ -522,7 +566,7 @@ def walk # are what a search serves for two pages of hits whose records are # gone, with more beyond them - see #hits_past? - and there is nothing # on either for the block to be handed twice. - raise PaginationError.build(operation: @operation, page: page, resource_class: @resource_class) if received.positive? && digest == previous + raise PaginationError.build(operation: @operation, page: page, resource_class: @resource_class, index: !@search) if received.positive? && digest == previous yield records if received.positive? @@ -663,7 +707,8 @@ def with(page: @page, per_page: @per_page, query: @query, widens: false) per_page: per_page, page: page, search: @search, - widens: widens + widens: widens, + paginated: @paginated ) end @@ -738,7 +783,12 @@ def fetch(page, per_page) # It costs Zammad nothing it was not doing. model_search_render asks the # search for the total on every request and leaves it out of the answer # unless the parameter is there. + # + # An endpoint that does not page is sent neither parameter. It would + # drop both, and a request that names a page reads as one of several. def page_query(page, per_page) + return @query if !@paginated + query = @query.merge(page: page, per_page: per_page) @search && @page.nil? ? query.merge(with_total_count: true) : query diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index c5bd351..6ea7ce0 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -51,12 +51,25 @@ def self.build(operation:, expected:, actual:, resource_class: nil) # Raised when the server answers a page request with the page before it, # which means it is ignoring +page+ and a collection walk would never end. class PaginationError < Error + # What to do about an index that repeats its first page, which is what + # one that serves every record in a single response does. Said as a + # condition, because the same two pages come from an endpoint that + # serves only the first of many and ignores +page+, and that one is not + # to be read as whole. + UNPAGINATED_ADVICE = 'If this endpoint serves every record in one response, declare `paginated false` on the resource, ' \ + 'and it is read in one request.' + # @param operation [String] # @param page [Integer] the page that repeated its predecessor # @param resource_class [Class, nil] + # @param index [Boolean] whether an index endpoint was being walked, + # which is the kind a resource may declare as not paginated. A search + # always pages. # @return [PaginationError] - def self.build(operation:, page:, resource_class: nil) - new("Can't #{subject_for(operation, resource_class)}: page #{page} repeated page #{page - 1}, so the endpoint is ignoring the page parameter") + def self.build(operation:, page:, resource_class: nil, index: false) + message = "Can't #{subject_for(operation, resource_class)}: page #{page} repeated page #{page - 1}, so the endpoint is ignoring the page parameter" + + new(index && page == 2 ? "#{message}. #{UNPAGINATED_ADVICE}" : message) end end diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index a830b1c..141e73d 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -487,6 +487,8 @@ def search(term, **filters) query: DeepCopy.frozen_copy({ query: term }.merge(search_filters(filters))), max_per_page: SEARCH_MAX_PER_PAGE, sortable: true, + # Every search endpoint pages, whatever the index beside it does. + paginated: true, search: true ) end @@ -495,7 +497,7 @@ def inspect = "#<#{self.class.name} #{resource_class.name}>" private - def collection(path, operation, query: {}, max_per_page: resource_class.page_limit, sortable: resource_class.sortable?, search: false) + def collection(path, operation, query: {}, max_per_page: resource_class.page_limit, sortable: resource_class.sortable?, paginated: resource_class.paginated?, search: false) Collection.new( transport: @transport, resource_class: resource_class, @@ -505,6 +507,7 @@ def collection(path, operation, query: {}, max_per_page: resource_class.page_lim sortable: sortable, unsortable_hint: resource_class.searchable? ? SEARCHABLE_UNSORTABLE_HINT : UNSORTABLE_HINT, search: search, + paginated: paginated, query: { expand: true }.merge(query) ) end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index c4fc271..a06f5be 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -127,6 +127,46 @@ def sortable(value) @sortable = value end + # Declares whether this resource's index endpoint pages. + # + # ApplicationController#model_index_render reads +page+ and + # +per_page+, and every resource this gem models is served by it. + # That is the default, so a resource says nothing. Not every index + # is: ObjectManagerAttributesController#index renders + # `ObjectManager::Attribute.list_full`, every attribute in one + # response, and reads no parameter at all. + # + # Such an index could not be read. A {Collection} asks for the page + # after a full one, was answered with the same list again, and + # raised {PaginationError} for it - correctly, as far as it could + # tell, because an endpoint that ignores +page+ and serves only the + # first of many pages looks the same. A resource that declares + # +paginated false+ says which of the two it is: its index is read + # in one request, and {Collection#page} refuses it. + # + # Declare it only for an endpoint that does serve every record. One + # that caps what it serves and ignores +page+ would be read as far + # as its cap and no further, with nothing to say so. + # + # A search is not affected. Every search endpoint pages. + # + # Whether the index sorts is not affected either: that is + # {.sortable}, a declaration of its own. An endpoint that reads no + # parameter at all, as the one below, says both. + # + # @example + # class ObjectAttribute < ZammadAPI::Resources::Base + # path 'api/v1/object_manager_attributes' + # paginated false + # sortable false + # end + # + # @param value [Boolean] + # @return [void] + def paginated(value) + @paginated = value + end + # @return [String] the API path of this resource def resource_path declaration(:path) || raise(Error, "#{name} does not declare an API path") @@ -150,6 +190,10 @@ def page_limit = declaration(:max_per_page) { DEFAULT_MAX_PER_PAGE } # +sort_by+ and +order_by+ def sortable? = declaration(:sortable) { true } + # @return [Boolean] whether this resource's index endpoint reads + # +page+ and +per_page+ + def paginated? = declaration(:paginated) { true } + # The API path of one record of this kind. # # The id is escaped rather than interpolated, so that one taken from a diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs index 7909465..7830bbe 100644 --- a/sig/zammad_api/collection.rbs +++ b/sig/zammad_api/collection.rbs @@ -21,6 +21,7 @@ module ZammadAPI @page: Integer? @search: bool @widens: bool + @paginated: bool def initialize: ( transport: Transport, @@ -34,7 +35,8 @@ module ZammadAPI ?per_page: Integer?, ?page: Integer?, ?search: bool, - ?widens: bool + ?widens: bool, + ?paginated: bool ) -> void def each: () { (R) -> void } -> Collection[R] @@ -69,6 +71,7 @@ module ZammadAPI def positive_integer!: (untyped, String) -> Integer def page_size!: (untyped, String) -> Integer def walk: () { (Array[R]) -> void } -> void + def read_whole: () { (Array[R]) -> void } -> void def page_after: (Integer page, Integer per_page, Integer received, Integer? total) -> [ Integer, Integer ] def widened: (Integer covered, Integer? total) -> [ Integer, Integer ] def each_distinct: () { (Resources::Base) -> void } -> void diff --git a/sig/zammad_api/errors.rbs b/sig/zammad_api/errors.rbs index 2b255eb..9760b35 100644 --- a/sig/zammad_api/errors.rbs +++ b/sig/zammad_api/errors.rbs @@ -23,7 +23,9 @@ module ZammadAPI end class PaginationError < Error - def self.build: (operation: String, page: Integer, ?resource_class: Class?) -> PaginationError + UNPAGINATED_ADVICE: String + + def self.build: (operation: String, page: Integer, ?resource_class: Class?, ?index: bool) -> PaginationError end class ResponseError < Error diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs index d166f80..208dd3c 100644 --- a/sig/zammad_api/resource_proxy.rbs +++ b/sig/zammad_api/resource_proxy.rbs @@ -46,7 +46,7 @@ module ZammadAPI private - def collection: (String, String, ?query: Hash[Symbol, untyped], ?max_per_page: Integer, ?sortable: bool, ?search: bool) -> Collection[R] + def collection: (String, String, ?query: Hash[Symbol, untyped], ?max_per_page: Integer, ?sortable: bool, ?paginated: bool, ?search: bool) -> Collection[R] def search_filters: (Hash[untyped, untyped] filters) -> Hash[Symbol, untyped] def search_filter_keys: () -> Array[Symbol] def unknown_search_filter_message: (Array[Symbol] unknown) -> String diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 1e7bf7b..877689a 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -36,17 +36,20 @@ module ZammadAPI self.@max_per_page: Integer? self.@search_filters: Array[Symbol]? self.@sortable: bool? + self.@paginated: bool? def self.path: (String) -> void def self.searchable: (bool) -> void def self.max_per_page: (Integer) -> void def self.search_filters: (*Symbol | String names) -> void def self.sortable: (bool) -> void + def self.paginated: (bool) -> void def self.resource_path: () -> String def self.searchable?: () -> bool def self.search_filter_names: () -> Array[Symbol] def self.page_limit: () -> Integer def self.sortable?: () -> bool + def self.paginated?: () -> bool def self.member_path: ((Integer | String) id) -> String def self.fetch_one: (Transport transport, (Integer | String) id) -> Base def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> Base diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb index 9124d10..f491e21 100644 --- a/spec/unit/zammad_api/collection_spec.rb +++ b/spec/unit/zammad_api/collection_spec.rb @@ -951,6 +951,154 @@ def sorted_request(sort_by, order_by) end end + # ObjectManagerAttributesController#index renders every attribute in one + # response and reads no parameter. Walked like a paged index, it was asked + # for page two, answered with the same list, and the guard against an + # endpoint that ignores `page` raised with every record already in hand. + describe 'an index that serves every record in one response' do + subject(:collection) { client.resource(resource).all } + + let(:resource) do + Class.new(ZammadAPI::Resources::Base) do + def self.name = 'ObjectAttribute' + + path 'api/v1/object_manager_attributes' + paginated false + end + end + let(:url) { "#{ClientHelper::BASE_URL}api/v1/object_manager_attributes" } + let(:records) { [{ id: 1, name: 'c' }, { id: 2, name: 'a' }, { id: 3, name: 'b' }] } + + # The same list whatever it is asked, which is what such an endpoint does. + before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response(records)) } + + it 'reads every record' do + expect(collection.map(&:id)).to eq([1, 2, 3]) + end + + it 'spends one request on it' do + collection.to_a + expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once + end + + it 'names no page in that request' do + collection.to_a + expect(a_request(:get, url).with(query: { 'expand' => 'true' })).to have_been_made.once + end + + context 'without the declaration' do + let(:resource) do + Class.new(ZammadAPI::Resources::Base) do + def self.name = 'ObjectAttribute' + + path 'api/v1/object_manager_attributes' + end + end + + it 'raises PaginationError, as for any endpoint that repeats a page' do + expect { collection.to_a }.to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1/) + end + + it 'says what to declare where the endpoint does serve every record' do + expect { collection.to_a }.to raise_error(ZammadAPI::PaginationError, /declare `paginated false` on the resource/) + end + end + + it 'hands the list over as one batch' do + expect(collection.in_batches.map { |batch| batch.map(&:id) }).to eq([[1, 2, 3]]) + end + + it 'slices the list where a batch size is asked for' do + expect(collection.in_batches(of: 2).map { |batch| batch.map(&:id) }).to eq([[1, 2], [3]]) + end + + it 'still spends one request where a batch size is asked for' do + collection.find_each(batch_size: 1).to_a + expect(a_request(:get, url).with(query: { 'expand' => 'true' })).to have_been_made.once + end + + it 'yields no batch for a list with nothing on it' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) + + expect(collection.in_batches.to_a).to eq([]) + end + + it 'reads the first record off the one response' do + expect(collection.first.id).to eq(1) + expect(a_request(:get, url).with(query: { 'expand' => 'true' })).to have_been_made.once + end + + it 'reads the first few' do + expect(collection.first(2).map(&:id)).to eq([1, 2]) + end + + it 'counts the records' do + expect(collection.count).to eq(3) + end + + it 'says whether there are any' do + expect(collection).not_to be_empty + end + + it 'finds a record by what it carries' do + expect(collection.detect { it.name == 'b' }.id).to eq(3) + end + + # Every number would name the same records. + it 'refuses a page' do + expect { collection.page(2) }.to raise_error(ArgumentError, /serves every record in one response and reads no page parameter/) + end + + it 'still refuses a page that is not a number first' do + expect { collection.page(0) }.to raise_error(ArgumentError, /positive integer/) + end + + # Whether an index sorts is a declaration of its own, and sorts unless + # the resource says otherwise, as it does for an index that pages. + it 'sends a sort, and still no page' do + collection.order(:name).to_a + + expect(a_request(:get, url).with(query: { 'expand' => 'true', 'sort_by' => 'name', 'order_by' => 'asc' })).to have_been_made.once + end + + context 'when the resource says the endpoint does not sort either' do + let(:resource) do + Class.new(ZammadAPI::Resources::Base) do + def self.name = 'ObjectAttribute' + + path 'api/v1/object_manager_attributes' + paginated false + sortable false + end + end + + it 'refuses a sort, which such an endpoint drops' do + expect { collection.order(:name) }.to raise_error(ArgumentError, /ignores sort_by/) + end + end + + it 'says so in inspect' do + expect(collection.inspect).to end_with('paginated=false>') + end + end + + describe ZammadAPI::PaginationError do + def message(**) = described_class.build(operation: 'get .all of object', **).message + + it 'says what to declare for an index that repeats its first page' do + expect(message(page: 2, index: true)).to include('declare `paginated false` on the resource') + end + + # An endpoint that served two different pages reads `page`. + it 'does not say so for a page further on' do + expect(message(page: 3, index: true)).not_to include('paginated false') + end + + it 'does not say so for a search, which always pages' do + expect(message(page: 2)).not_to include('paginated false') + end + end + # A walk stops on what the endpoint served, and the size it serves is # learned from the first page rather than taken from `max_per_page`. Where # the server's cap is lower than the request - a cap the gem's declaration @@ -1010,6 +1158,13 @@ def hits(range) = range.map { { id: it } } expect { search.to_a }.to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) end + # `paginated false` is a declaration about an index. Every search pages. + it 'does not suggest declaring the resource as not paginated' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response(hits(1..3))) + + expect { search.to_a }.to raise_error(ZammadAPI::PaginationError) { |error| expect(error.message).not_to include('paginated false') } + end + it 'still reads only the one page a search was limited to' do stub_search_page(2, hits(1..3)) diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index b824bce..c3300ec 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -442,6 +442,62 @@ def stub_page(number, records) end end + # An index that serves its whole list and reads no page was walked into the + # guard against an endpoint that ignores `page`, so a lookup that missed on + # the first page raised instead of answering nil. + describe 'a resource whose index does not page' do + subject(:proxy) { client.resource(resource) } + + let(:resource) do + Class.new(ZammadAPI::Resources::Base) do + def self.name = 'ObjectAttribute' + + path 'api/v1/object_manager_attributes' + paginated false + end + end + let(:url) { "#{ClientHelper::BASE_URL}api/v1/object_manager_attributes" } + + before do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'a' }, { id: 2, name: 'b' }])) + end + + it 'finds a record by an attribute' do + expect(proxy.find_by(name: 'b').id).to eq(2) + end + + it 'answers nil for a lookup that matches nothing' do + expect(proxy.find_by(name: 'missing')).to be_nil + end + + it 'spends one request on a miss' do + proxy.find_by(name: 'missing') + expect(a_request(:get, url).with(query: { 'expand' => 'true' })).to have_been_made.once + end + + it 'lets a miss go on to create the record' do + created = stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 3, name: 'missing' }, status: 201)) + + expect((proxy.find_by(name: 'missing') || proxy.create(name: 'missing')).id).to eq(3) + expect(created).to have_been_requested + end + + it 'reads every record straight off the proxy' do + expect(proxy.map(&:name)).to eq(%w[a b]) + end + + # The declaration is about the index. A search endpoint always pages. + it 'still pages a search' do + resource.searchable true + search = stub_request(:get, "#{url}/search") + .with(query: hash_including('page' => '1', 'per_page' => described_class::SEARCH_MAX_PER_PAGE.to_s)) + .to_return(json_response({ records: [], total_count: 0 })) + + proxy.search('a').to_a + expect(search).to have_been_requested + end + end + describe '#exists?' do it 'is true when the record is there' do stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1 })) diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index 5ebd858..2de2afe 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -1001,6 +1001,12 @@ def self.name expect(subclass.sortable?).to be(false) end + it 'inherits whether the index endpoint pages' do + unpaged = Class.new(described_class) { paginated false } + + expect(Class.new(unpaged).paginated?).to be(false) + end + it 'inherits the associations, as it always did' do expect(subclass.associations.keys).to eq(ZammadAPI::Resources::Ticket.associations.keys) end @@ -1043,6 +1049,27 @@ def self.name expect(Class.new(described_class).sortable?).to be(true) end + it 'defaults to an index endpoint that pages, as the generic ones do' do + expect(Class.new(described_class).paginated?).to be(true) + end + + it 'records a declaration that the index endpoint does not page' do + expect(Class.new(described_class) { paginated false }.paginated?).to be(false) + end + + # Two declarations, and neither reads the other. + it 'leaves whether the index endpoint sorts to its own declaration' do + expect(Class.new(described_class) { paginated false }.sortable?).to be(true) + end + + it 'leaves whether the index endpoint pages to its own declaration' do + expect(Class.new(described_class) { sortable false }.paginated?).to be(true) + end + + it 'pages every resource this gem models' do + expect(ZammadAPI::Client::RESOURCES.values).to all(be_paginated) + end + it 'records a declared page limit' do expect(Class.new(described_class) { max_per_page 25 }.page_limit).to eq(25) end diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 1a63c3b..9f020c3 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -812,6 +812,28 @@ def find = client.groups.find(1) end end + describe 'a list endpoint whose resource says it does not page' do + let(:resource) do + Class.new(ZammadAPI::Resources::Base) do + def self.name = 'ObjectAttribute' + + path 'api/v1/object_manager_attributes' + paginated false + end + end + + before { zammad.stub(:get, 'api/v1/object_manager_attributes', body: [{ id: 1, name: 'a' }]) } + + it 'is read from the one stub' do + expect(client.resource(resource).map(&:name)).to eq(['a']) + end + + it 'is recorded as the one request it is, naming no page' do + client.resource(resource).to_a + expect(zammad.requests.map(&:query)).to eq([{ 'expand' => 'true' }]) + end + end + describe 'a list endpoint stubbed once' do subject(:zammad) { described_class.new } From 3ef61755d6cab6b233c0a0140813693f8e994b15 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 00:38:23 +0200 Subject: [PATCH 011/121] refactor!: remove the names 1.x had for readers and add_article 2.0 kept the singular resource readers and `Ticket#article` as aliases that warned in Ruby's `deprecated` category and were to go in 3.0. 2.0 is a breaking release already, so they go now and it ships without names it would only take away again. `client.ticket` and the other six singular readers raise UnknownResourceError, which lists the plural names, and so does `client.resource(:ticket)`. `DEPRECATED_RESOURCES` and `Client.warn_deprecated_resource` are gone with them. `Ticket#article` is gone, which leaves `article` an attribute reader like any other: `ticket.article(body: '...')` raises NoMethodError on a ticket that has no article staged, and sends nothing. The README and the changelog say the old names raise. The migration guide said most calling code needs no edits, and says now that it needs the one rename. --- CHANGELOG.md | 15 ++-- README.md | 28 +++---- lib/zammad_api/client.rb | 70 +----------------- lib/zammad_api/resources/ticket.rb | 21 ------ sig/zammad_api/client.rbs | 12 --- sig/zammad_api/resources/resources.rbs | 1 - spec/unit/zammad_api/client_spec.rb | 73 +++---------------- spec/unit/zammad_api/resources/ticket_spec.rb | 55 ++++---------- 8 files changed, 49 insertions(+), 226 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a4bf58..6bc8db6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -107,11 +107,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `client.ticket_priorities` and `client.ticket_states`. A resource is `Enumerable` over every record of its kind, so `client.ticket.each` and `client.ticket.first(5)` read as if they acted on one ticket; the singular dates from 1.x, when a resource was only a - dispatcher for `find` and `create`. The singular names still work, as deprecated aliases - that warn in Ruby's `deprecated` category — silent unless the application asks for - deprecation warnings, with `ruby -W:deprecated` or `Warning[:deprecated] = true` — and - will be removed in 3.0. `client.resource(:ticket)` is answered the same way, and - `client.resource_names` lists the plural names. + dispatcher for `find` and `create`. The singular names are gone: `client.ticket` raises + `UnknownResourceError`, which lists the plural names, and so does + `client.resource(:ticket)`. `client.resource_names` lists the plural names. - The resource readers a client has are a fixed list. 1.x resolved `client.` to `ZammadAPI::Resources::` through `const_get`, so a subclass of `Base` defined in application code could be reached that way. `client.role` now raises @@ -174,10 +172,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a credentials an override replaces, so switching schemes through either still works, and an environment that itself sets two schemes is refused until an argument says which is meant. - `ticket.article(…)` is `ticket.add_article(…)`. A noun that sends a `POST` sat one letter - away from `ticket.articles`, which only reads. `article` still works, as a deprecated - alias that warns in Ruby's `deprecated` category the way the singular resource readers do, - and will be removed in 3.0. It requires its attributes, as it did in 1.x, so a bare - `ticket.article` raises `ArgumentError` rather than sending an article with no body. + away from `ticket.articles`, which only reads. The old method is gone, which leaves + `article` an attribute reader like any other: it raises `NoMethodError` on a ticket that + has no article staged, and sends nothing. ### Added diff --git a/README.md b/README.md index 8335cbe..0f84e37 100644 --- a/README.md +++ b/README.md @@ -223,8 +223,8 @@ inherits. The names are plural because what each one hands back stands for every record of its kind: `client.tickets.each` walks them all, and `client.tickets.find(1)` picks one out. The -singular names from 1.x — `client.ticket` and the rest — still work as deprecated aliases; -see [Migrating from 1.x](#the-client). +singular names from 1.x — `client.ticket` and the rest — are gone and raise +`UnknownResourceError`; see [Migrating from 1.x](#the-client). Anything not in that list is reachable by [declaring a resource](#resources-this-gem-does-not-model) for it, or with [raw requests](#raw-requests). @@ -1394,8 +1394,9 @@ test against a specific Zammad ref. ## Migrating from 1.x Version 2.0 fixes long-standing behaviour that could not change without breaking -compatibility. Most calling code needs no edits, and almost everything that does raises -at the call site. Start with the handful of changes that do not. +compatibility. Most calling code needs one rename and no more — the resource readers are +plural, so `client.ticket` is `client.tickets` — and almost everything else that needs an +edit raises at the call site. Start with the handful of changes that do not. If this is not the time to move, [1.x stays available](#staying-on-1x). @@ -1423,11 +1424,12 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). `ZammadAPI::ValidationError` as `save` used to. `update` and `update!` are the same pair. - **`collection.each`** walks every page, where 1.x read one and stopped: - `client.ticket.all.each { ... }`, as 1.x spelled it, touched the first 100 tickets. It - still runs in 2.0, through the deprecated singular reader (`client.tickets` is the new - name), and now touches every ticket the client can read, at a request per page. A loop written to handle the first - page, or one that writes to each record it is handed, does that to all of them now. - Limit it explicitly with `first(n)` or `page(1, per_page: n)`. + `client.ticket.all.each { ... }`, as 1.x spelled it, touched the first 100 tickets. That + line raises in 2.0, because the reader is `client.tickets` now, and renaming it is all it + takes to run again — after which it touches every ticket the client can read, at a request + per page. A loop written to handle the first page, or one that writes to each record it is + handed, does that to all of them now. Limit it explicitly with `first(n)` or + `page(1, per_page: n)`. - **`rescue Faraday::ConnectionFailed`** (and any other Faraday exception) no longer matches. Transport failures are wrapped, so rescue `ZammadAPI::ConnectionError`, @@ -1440,7 +1442,7 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | `Client.new(config_hash)` | `Client.new(**config_hash)` | Options are keyword arguments now, so a Hash has to be splatted | | an unknown option was ignored | raises `ArgumentError: unknown keyword` | A typo'd option used to be dropped without a word | | `logger: true` | `logger: Logger.new($stderr)` | The flag became an object, so you choose the device and level. Anything that answers `debug` is accepted; `true` raises `ConfigurationError` | -| `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is `Enumerable` over every record now, so `client.ticket.each` read as if it acted on one ticket. The singular names still work and warn in Ruby's `deprecated` category; run with `RUBYOPT=-W:deprecated` to find them. They go in 3.0 | +| `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is `Enumerable` over every record now, so `client.ticket.each` read as if it acted on one ticket. The singular names raise `UnknownResourceError`, which lists the plural ones, and so does `client.resource(:ticket)` | | `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads | | `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised | | `ZammadAPI::Resources::Role < Base` reached by `client.role` | `client.resource(Role)`, for a `Role < ZammadAPI::Resources::Base` of your own | The named readers are a fixed list, and a class is handed over rather than looked up by name. [Raw requests](#raw-requests) reach whatever is not a resource | @@ -1473,7 +1475,7 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | `record.unknown_attribute` → `nil` | raises `NoMethodError`; use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` | A typo read as `nil` and flowed on into whatever was written with it. Zammad also serves a reduced object where the user may not see the whole record, and that is worth being told about | | `client.x.new(id: 5)` | `client.x.find(5)` | The constructor was the one door that did not refuse a staged id — and the only one whose value reached Zammad, since a new record is sent in full | | `client.users.find(ticket.customer_id)` | `ticket.related.customer` | Following a foreign key needed the client threaded through | -| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | A noun that sends a `POST`, one letter away from `ticket.articles`, which only reads. `article` still works and warns in Ruby's `deprecated` category; it goes in 3.0 | +| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | A noun that sends a `POST`, one letter away from `ticket.articles`, which only reads. The method is gone: `article` is an attribute reader like any other, and raises `NoMethodError` on a ticket that has no article staged | ### Errors @@ -1514,8 +1516,8 @@ a `POST`, `PUT` or `DELETE` is never retried. Both are options — see `find`, `all`, `create` and `new` on a resource, `record.destroy`, attribute readers and writers, `ticket.articles` and `attachment.download`. The resources themselves are reached -by their plural names now — `client.tickets` — and adding an article is -`ticket.add_article`; the old names still answer, with a deprecation warning. +by their plural names — `client.tickets` — and adding an article is `ticket.add_article`; +those two are renames, and the old names raise. `record.save`, `record.changes` and `record.attributes` still exist and still mean what they meant; the tables above only change how they behave at the edges. diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index c3059c6..2f80e11 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -43,18 +43,6 @@ class Client users: Resources::User }.freeze - # The names the readers had in 1.x, mapped to the ones they have now. - # Each still works, as a deprecated alias - see {#resource}. - DEPRECATED_RESOURCES = { - group: :groups, - organization: :organizations, - ticket: :tickets, - ticket_article: :ticket_articles, - ticket_priority: :ticket_priorities, - ticket_state: :ticket_states, - user: :users - }.freeze - # Methods Ruby calls implicitly for type coercion. They must keep raising # NoMethodError so that this object behaves normally in core operations. CONVERSION_METHODS = %i[to_ary to_a to_hash to_str to_io to_proc coerce].freeze @@ -81,51 +69,6 @@ class Client define_method(name) { @resources.fetch(resource_class) } end - # @!method group - # @deprecated Use {#groups}. - # @return [ResourceProxy] - # @!method organization - # @deprecated Use {#organizations}. - # @return [ResourceProxy] - # @!method ticket - # @deprecated Use {#tickets}. - # @return [ResourceProxy] - # @!method ticket_article - # @deprecated Use {#ticket_articles}. - # @return [ResourceProxy] - # @!method ticket_priority - # @deprecated Use {#ticket_priorities}. - # @return [ResourceProxy] - # @!method ticket_state - # @deprecated Use {#ticket_states}. - # @return [ResourceProxy] - # @!method user - # @deprecated Use {#users}. - # @return [ResourceProxy] - DEPRECATED_RESOURCES.each do |old_name, name| - define_method(old_name) do - Client.warn_deprecated_resource(old_name, name) - @resources.fetch(RESOURCES.fetch(name)) - end - end - - # Says that a reader was called by the name it had in 1.x. - # - # In Ruby's own +deprecated+ category, so it is silent unless the - # application asks for deprecation warnings - +ruby -W:deprecated+, or - # +Warning[:deprecated] = true+, which is what a test suite turns on - - # and a script that has not been migrated yet does not print a line per - # request in production. +uplevel+ names the line that made the call, - # past the two frames of this class in between. - # - # @api private - # @param old_name [Symbol] - # @param name [Symbol] - # @return [void] - def self.warn_deprecated_resource(old_name, name) - warn("ZammadAPI::Client##{old_name} is deprecated and will be removed in 3.0: use ##{name} instead", uplevel: 2, category: :deprecated) - end - # Environment variables {.from_env} reads, mapped to the options they set. ENV_OPTIONS = { 'ZAMMAD_URL' => :url, @@ -205,9 +148,6 @@ def initialize(**options) # The proxy for a resource, by name or by class. # - # A name from 1.x - +:ticket+ for +:tickets+ - is still answered, with - # a deprecation warning. - # # A class is the way to the parts of the API this gem does not model. # {Resources::Base} is built to be subclassed - a path, and whatever the # endpoint needs said about it - and a proxy for such a class gives its @@ -234,15 +174,9 @@ def initialize(**options) def resource(name) return proxy_for(name) if name.is_a?(Class) - key = name.to_sym - - if !RESOURCES.key?(key) - current = DEPRECATED_RESOURCES.fetch(key) { raise UnknownResourceError, unknown_resource_message(name) } - Client.warn_deprecated_resource(key, current) - key = current - end + resource_class = RESOURCES.fetch(name.to_sym) { raise UnknownResourceError, unknown_resource_message(name) } - @resources.fetch(RESOURCES.fetch(key)) + @resources.fetch(resource_class) end # @return [Array] every resource name this client supports diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index 7f1c1f5..cf2385e 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -80,27 +80,6 @@ def add_article(attributes = {}) record.save! record end - - # Adds an article to this ticket, under the name the method had in 1.x. - # - # Warns in Ruby's +deprecated+ category, the way the singular readers - # on {Client} do: silent unless the application asks for deprecation - # warnings. - # - # The attributes are required, as they were in 1.x. With a default, - # a bare +ticket.article+ - which reads like the attribute a ticket is - # created with, `ticket.article = {body: 'reply'}` - sent a POST - # naming nothing but the ticket, which Zammad refused for want of a - # body. 1.x raised ArgumentError for it without a request, and so does - # this. - # - # @deprecated Use {#add_article}. - # @param attributes [Hash] article attributes - # @return [TicketArticle] the created article - def article(attributes) - warn("#{Ticket.name}#article is deprecated and will be removed in 3.0: use #add_article instead", uplevel: 1, category: :deprecated) - add_article(attributes) - end end end end diff --git a/sig/zammad_api/client.rbs b/sig/zammad_api/client.rbs index ce64ff2..0ac96c6 100644 --- a/sig/zammad_api/client.rbs +++ b/sig/zammad_api/client.rbs @@ -1,7 +1,6 @@ module ZammadAPI class Client RESOURCES: Hash[Symbol, untyped] - DEPRECATED_RESOURCES: Hash[Symbol, Symbol] CONVERSION_METHODS: Array[Symbol] ENV_OPTIONS: Hash[String, Symbol] @@ -11,7 +10,6 @@ module ZammadAPI @resources: Hash[untyped, ResourceProxy[untyped]] def self.from_env: (**untyped overrides) -> Client - def self.warn_deprecated_resource: (Symbol old_name, Symbol name) -> void def self.build: (Config config, untyped transport) -> Client def initialize: (**untyped options) -> void @@ -24,16 +22,6 @@ module ZammadAPI def ticket_states: () -> ResourceProxy[Resources::TicketState] def users: () -> ResourceProxy[Resources::User] - # The names these readers had in 1.x. Each warns in Ruby's `deprecated` - # category and answers what its plural answers. - %a{deprecated: use groups} def group: () -> ResourceProxy[Resources::Group] - %a{deprecated: use organizations} def organization: () -> ResourceProxy[Resources::Organization] - %a{deprecated: use tickets} def ticket: () -> ResourceProxy[Resources::Ticket] - %a{deprecated: use ticket_articles} def ticket_article: () -> ResourceProxy[Resources::TicketArticle] - %a{deprecated: use ticket_priorities} def ticket_priority: () -> ResourceProxy[Resources::TicketPriority] - %a{deprecated: use ticket_states} def ticket_state: () -> ResourceProxy[Resources::TicketState] - %a{deprecated: use users} def user: () -> ResourceProxy[Resources::User] - # A class cannot carry its own type into the answer - RBS has no way to # say "a proxy for whichever class this is" - so a proxy for a resource of # your own is untyped until you say what it is: diff --git a/sig/zammad_api/resources/resources.rbs b/sig/zammad_api/resources/resources.rbs index c4e5b10..8b96876 100644 --- a/sig/zammad_api/resources/resources.rbs +++ b/sig/zammad_api/resources/resources.rbs @@ -152,7 +152,6 @@ module ZammadAPI def articles: () -> Array[TicketArticle] def add_article: (?Hash[untyped, untyped] attributes) -> TicketArticle - %a{deprecated: use add_article} def article: (Hash[untyped, untyped] attributes) -> TicketArticle end class TicketArticle < Base diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index 60b158c..6c8c488 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -230,52 +230,17 @@ # A proxy is Enumerable over every record of its kind, so the readers are # plural. The singular names are what they were called in 1.x, when a proxy - # was only a dispatcher for find and create. + # was only a dispatcher for find and create, and they are gone. describe 'the singular names the readers had in 1.x' do - around do |example| - enabled = Warning[:deprecated] - Warning[:deprecated] = true - example.run - ensure - Warning[:deprecated] = enabled - end - - ZammadAPI::Client::DEPRECATED_RESOURCES.each do |old_name, name| - it "still answers ##{old_name} with what ##{name} answers" do - client = unit_client - proxy = nil - - expect { proxy = client.public_send(old_name) }.to output.to_stderr - expect(proxy).to be(client.public_send(name)) + %i[group organization ticket ticket_article ticket_priority ticket_state user].each do |old_name| + it "does not answer ##{old_name}" do + expect { unit_client.public_send(old_name) } + .to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource #{old_name}, available resources are: groups, /) end end - it 'covers every reader' do - expect(ZammadAPI::Client::DEPRECATED_RESOURCES.values).to eq(ZammadAPI::Client::RESOURCES.keys) - end - - it 'warns, naming the replacement' do - expect { unit_client.ticket } - .to output(/ZammadAPI::Client#ticket is deprecated and will be removed in 3\.0: use #tickets instead/).to_stderr - end - - it 'names the line that made the call, not one inside the gem' do - expect { unit_client.ticket }.to output(/#{Regexp.escape(__FILE__)}:#{__LINE__}: warning: /).to_stderr - end - - it 'does not warn for the plural name' do - expect { unit_client.tickets }.not_to output.to_stderr - end - - # Ruby's own category for this, so an application decides whether to hear - # it: a script that has not been migrated does not print a line per call. - it 'says nothing unless deprecation warnings are on' do - Warning[:deprecated] = false - expect { unit_client.ticket }.not_to output.to_stderr - end - - it 'is not listed among the resource names' do - expect(unit_client.resource_names).not_to include(:ticket) + it 'does not claim to respond to one' do + expect(unit_client).not_to respond_to(:ticket) end end @@ -388,27 +353,9 @@ end end - context 'with a name from 1.x' do - around do |example| - enabled = Warning[:deprecated] - Warning[:deprecated] = true - example.run - ensure - Warning[:deprecated] = enabled - end - - it 'still answers, with the proxy the plural answers with' do - client = unit_client - proxy = nil - - expect { proxy = client.resource(:ticket) }.to output.to_stderr - expect(proxy).to be(client.tickets) - end - - it 'warns, naming the line that made the call' do - expect { unit_client.resource('ticket') } - .to output(/#{Regexp.escape(__FILE__)}:#{__LINE__ - 1}: warning: ZammadAPI::Client#ticket is deprecated/).to_stderr - end + it 'raises for a singular name from 1.x' do + expect { unit_client.resource(:ticket) } + .to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource ticket, available resources are: groups, /) end end diff --git a/spec/unit/zammad_api/resources/ticket_spec.rb b/spec/unit/zammad_api/resources/ticket_spec.rb index ea42c82..8c743f7 100644 --- a/spec/unit/zammad_api/resources/ticket_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -162,55 +162,32 @@ def posted_ticket_ids end end - # The name the method had in 1.x: a noun that sends a POST, one letter away - # from the reader beside it. + # The name add_article had in 1.x: a noun that sends a POST, one letter away + # from the reader beside it. It is gone, which leaves `article` what it is + # everywhere else on a record - an attribute. describe '#article' do - around do |example| - enabled = Warning[:deprecated] - Warning[:deprecated] = true - example.run - ensure - Warning[:deprecated] = enabled + it 'is not a method of a ticket' do + expect(described_class.method_defined?(:article)).to be(false) end - before do - stub_request(:post, article_url).with(query: hash_including({})) - .to_return(json_response({ id: 9, body: 'hello', ticket_id: 42 }, status: 201)) - end - - it 'still adds the article' do - added = nil - - expect { added = ticket.article(body: 'hello') }.to output.to_stderr - expect(added.id).to eq(9) - end - - it 'warns, naming the replacement' do - expect { ticket.article(body: 'hello') } - .to output(/ZammadAPI::Resources::Ticket#article is deprecated and will be removed in 3\.0: use #add_article instead/).to_stderr + it 'raises NoMethodError for the call 1.x made' do + expect { ticket.article(body: 'hello') }.to raise_error(NoMethodError) end - it 'names the line that made the call' do - expect { ticket.article(body: 'hello') }.to output(/#{Regexp.escape(__FILE__)}:#{__LINE__}: warning: /).to_stderr - end - - it 'says nothing unless deprecation warnings are on' do - Warning[:deprecated] = false - expect { ticket.article(body: 'hello') }.not_to output.to_stderr - end + it 'sends nothing for the call 1.x made' do + begin + ticket.article(body: 'hello') + rescue NoMethodError + nil + end - it 'does not warn for add_article' do - expect { ticket.add_article(body: 'hello') }.not_to output.to_stderr + expect(a_request(:post, article_url).with(query: hash_including({}))).not_to have_been_made end - # It reads like the attribute a ticket is created with, and with a - # default it sent a POST naming nothing but the ticket. 1.x required the - # attributes. - it 'requires the attributes, as 1.x did, and sends nothing without them' do + it 'reads the article staged for the next save' do ticket.article = { body: 'reply' } - expect { ticket.article }.to raise_error(ArgumentError, /wrong number of arguments/) - expect(a_request(:post, article_url).with(query: hash_including({}))).not_to have_been_made + expect(ticket.article).to eq(body: 'reply') end end end From 123bcf609f935a41d5102593582a12af325a9248 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 11:20:26 +0200 Subject: [PATCH 012/121] fix: redact a URL that has no host where the host belongs 9d299be searches a URL to its last @ where the authority holds a colon, and inside the authority otherwise. The authority ends at the first slash, so a value with a slash too many, or with the slashes and no scheme, has an empty one, with no colon and no @ in it, and nothing was blanked. `proxy: '//user:secret@proxy:8080'` was printed by `Config#inspect` with its password. Faraday reads no host out of that value, so the proxy did not work either, and the configuration is what gets printed to find out why. `url: 'https:///admin:secret@host/'` was quoted in full by the ConfigurationError that refuses a url without a host, which did not go through the redaction at all. An empty authority is now searched like one with a colon: there is no host in it to blank by mistake. The error quotes the url redacted. --- CHANGELOG.md | 6 ++++ lib/zammad_api/config.rb | 14 +++++++-- spec/unit/zammad_api/config_spec.rb | 46 +++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bc8db6..55b398e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -830,6 +830,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a that serves only its first page, so it is declared rather than inferred, and the error for an index that repeats its first page now says what to declare. `page` refuses a resource declared this way. Whether its index sorts is still what `sortable` says. +- A proxy or instance URL with no host where the host belongs is redacted. A slash too + many, or the slashes without the scheme, end the authority before it has begun, so + `proxy: '//user:secret@proxy:8080'` was printed by `Config#inspect` with its password, and + `url: 'https:///admin:secret@host/'` was quoted in full by the `ConfigurationError` that + refuses a url without a host. With no host there to blank by mistake, everything up to + the last `@` is blanked, and that error quotes the url redacted. ### Changed diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 67d253d..bfba645 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -284,13 +284,21 @@ def pretty_print(printer) = printer.text(inspect) # cannot tell a port from a password, and of the two mistakes that is the # one that leaks nothing. # + # An empty authority is searched the same way, for the same reason and + # at no cost: there is no host in it to blank by mistake. It is what a + # slash too many leaves, or the slashes without the scheme - the + # authority ends at the first slash, so +//user:secret@proxy:8080+ and + # +https:///user:secret@host/+ have none, with no colon and no +@+ in it, + # and were printed as they stood: the proxy by {#inspect}, and the url + # by the ConfigurationError that refuses a url without a host. + # # @param value [String] a URL that may carry inline credentials # @return [String] the same URL with the credentials blanked def redact_userinfo(value) scheme = value[URL_SCHEME_PATTERN].to_s rest = value.delete_prefix(scheme) authority = rest[URL_AUTHORITY_PATTERN].to_s - boundary = authority.include?(':') ? rest.rindex('@') : authority.rindex('@') + boundary = authority.empty? || authority.include?(':') ? rest.rindex('@') : authority.rindex('@') return value if boundary.nil? "#{scheme}#{REDACTION}#{rest[boundary..]}" @@ -317,7 +325,9 @@ def normalize_url(value) raise ConfigurationError, 'missing url in config' if presence(value).nil? raise ConfigurationError, "config url needs to be a string, got #{value.class}" if !value.is_a?(String) raise ConfigurationError, 'config url needs to start with http:// or https://' if !SCHEME_PATTERN.match?(value) - raise ConfigurationError, "config url needs a host after the scheme, got #{value.inspect}" if !URL_PATTERN.match?(value) + # Quoted through the redaction: what follows the scheme here is not a + # host, and may be the credentials of a url with a slash too many. + raise ConfigurationError, "config url needs a host after the scheme, got #{redact_userinfo(value).inspect}" if !URL_PATTERN.match?(value) raise ConfigurationError, inline_credentials_message(value) if inline_credentials?(value) # A trailing slash keeps Zammad installations served from a sub-path diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index a45f743..cb0b846 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -50,6 +50,20 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) .to raise_error(ZammadAPI::ConfigurationError, 'config url needs a host after the scheme, got "https://"') end + # The value was quoted as it stood, and what stands where the host + # belongs may be credentials: a slash too many, and the userinfo is the + # start of a path as far as the syntax goes. + it 'does not quote the credentials of a url with a slash too many' do + expect { build(url: 'https:///admin:url-s3cret@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url needs a host after the scheme, got "https://[REDACTED]@zammad.example.com/"') + end + + it 'does not quote them where a ? or a # stands in for the host' do + %w[https://?admin:url-s3cret@zammad.example.com/ https://#admin:url-s3cret@zammad.example.com/].each do |url| + expect { build(url: url) }.to raise_error(ZammadAPI::ConfigurationError) { expect(it.message).not_to include('s3cret') } + end + end + # URI(...) is what a caller reaches for, and it prints as the URL, so it # reached String#end_with? and died there as a NoMethodError - past the # ConfigurationError the constructor is documented to raise. @@ -389,6 +403,28 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect(build(proxy: 'proxy.test:8080').inspect).to include('proxy="proxy.test:8080"') end + # A proxy written with the slashes and without the scheme, or with a + # slash too many. The authority was looked for where the scheme ended, + # and found to end at once, at the slash it began with: an empty + # authority holds no colon and no @, so nothing was blanked. + { + 'two slashes and no scheme' => ['//puser:pproxy-s3cret@proxy.test:8080', '[REDACTED]@proxy.test:8080'], + 'one slash' => ['/puser:pproxy-s3cret@proxy.test:8080', '[REDACTED]@proxy.test:8080'], + 'a scheme and three' => ['http:///puser:pproxy-s3cret@proxy.test:8080', 'http://[REDACTED]@proxy.test:8080'], + 'two and a # in a password' => ['//puser:pa#ss-s3cret@proxy.test:8080', '[REDACTED]@proxy.test:8080'] + }.each do |opening, (proxy, redacted)| + it "redacts the credentials of a proxy that opens with #{opening}" do + rendered = build(proxy: proxy).inspect + + expect(rendered).to include("proxy=#{redacted.inspect}") + expect(rendered).not_to include('s3cret') + end + end + + it 'leaves a proxy that opens with two slashes and has no credentials alone' do + expect(build(proxy: '//proxy.test:8080').inspect).to include('proxy="//proxy.test:8080"') + end + it 'leaves a url without credentials alone' do expect(build(url: 'https://zammad.example.com/').inspect).to include('url="https://zammad.example.com/"') end @@ -514,6 +550,16 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) it 'blanks rather than guesses where a colon could be either a port or a password' do expect(build.redacted('https://zammad.example.com:8443/tenant@acme/')).to eq('https://[REDACTED]@acme/') end + + # No host stands in an empty authority, so there is none to blank by + # mistake, and what follows it is searched to its last @. + it 'blanks what stands behind an empty authority' do + expect(build.redacted('https:///admin:s3cret@zammad.example.com/')).to eq('https://[REDACTED]@zammad.example.com/') + end + + it 'leaves a value with an empty authority and no @ alone' do + expect(build.redacted('https:///helpdesk/')).to eq('https:///helpdesk/') + end end describe '#redacted_url' do From 4b32dff0173fde815bc3623f853228092ef6c264 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 11:23:05 +0200 Subject: [PATCH 013/121] fix: log a request body as it is sent The payload line printed the body the caller handed over, redacted by key through its Hashes and Arrays. dc06edc gave a String the same treatment by parsing it. Anything else in a body was still printed by `inspect`. An object that writes its own JSON goes out as keys and values like any Hash. `client.post(path, body: credentials)` with a value object that has a `to_json`, or the same object under a key of a Hash or as an attribute of a record, sent `{"login":..,"password":..}` and was logged with the password. An object without a `to_json` is sent as its `to_s`, which for most objects names the class alone, and the log showed everything `inspect` lists and the request never carried. The log now reads the encoded payload, for every body and not only for a String: parsed, and redacted by key where it is a JSON object or array, replaced by its size where it is not. So the line shows String keys where it showed the Hash as given, and a body that is one value is no longer printed. Parsed inside the logger's block, so only where the line is written. --- CHANGELOG.md | 9 ++++ README.md | 6 ++- lib/zammad_api/transport.rb | 55 ++++++++++++-------- sig/zammad_api/transport.rbs | 6 +-- spec/unit/zammad_api/transport_spec.rb | 69 ++++++++++++++++++++++++-- 5 files changed, 116 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 55b398e..6522fe8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -836,6 +836,15 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `url: 'https:///admin:secret@host/'` was quoted in full by the `ConfigurationError` that refuses a url without a host. With no host there to blank by mistake, everything up to the last `@` is blanked, and that error quotes the url redacted. +- The debug log prints a request body as it is sent, and no longer by `inspect`. It + redacted by key through the Hashes and lists of the body it was handed and printed + anything else in it as it stood, so an object that writes its own JSON — a value object + with a `to_json`, as the body or under a key of it — was logged with the password the + request carries as a key. An object that does not is sent as its `to_s`, and the log + showed what `inspect` lists and the request never carried. The payload is now read back + from the JSON it was encoded to and redacted by key, however it was handed over, so the + line shows String keys: `{"login" => "jane", "password" => "[REDACTED]"}`. A body that is + one value is not logged, only its size. ### Changed diff --git a/README.md b/README.md index 0f84e37..6278a27 100644 --- a/README.md +++ b/README.md @@ -1159,8 +1159,10 @@ client = ZammadAPI::Client.new( Requests, response statuses and durations are logged at `debug` level. Payload keys, query parameters and headers that look like credentials (`password`, `token`, `secret`, `cookie`, ...) are redacted. That holds for a query string written into the path of a raw request, -in the log and in the message of an error the request raises, and for a body handed over -as a String where it is JSON. A String body that is not JSON is not logged, only its size. +in the log and in the message of an error the request raises. A request body is logged as +it is sent: read back from the JSON it was encoded to and redacted by key, whether it was +handed over as a Hash, as a JSON String or as an object that writes its own JSON. A body +that is not a JSON object or array is not logged, only its size. ## Testing code that uses this client diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 6a32554..d88ccbb 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -875,7 +875,7 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou path = Transport.relative_path(path) payload = Transport.encode_body(body, operation: operation, resource_class: resource_class) started = Process.clock_gettime(Process::CLOCK_MONOTONIC) - response = decode(perform(method, path, query, body, payload, headers)) + response = decode(perform(method, path, query, payload, headers)) log_response(method, path, response, started) return response if response.success? @@ -913,14 +913,14 @@ def timed_out?(error) [wrapped, error.cause].any? { |inner| TIMEOUT_ERRORS.any? { inner.is_a?(it) } } end - # +body+ is what the caller handed over, which is what the log redacts - # and prints; +payload+ is the same thing encoded, which is what is sent. - def perform(method, path, query, body, payload, headers) + # +payload+ is the body as it is sent, and it is what the log reads as + # well: see {#loggable_body}. + def perform(method, path, query, payload, headers) # Built before the request is logged, so a rejected query or header does # not leave a line claiming a request that was never made. params = query && Transport.stringify_query(query) fields = headers && Transport.stringify_headers(headers) - log_request(method, path, query, body, fields) + log_request(method, path, query, payload, fields) @connection.public_send(method, path) do |request| request.params.update(params) if params @@ -1174,11 +1174,11 @@ def raw_body!(body) 'drop the parsing middleware - `c.response :json` is the usual one - from the `middleware:` callable.' end - def log_request(method, path, query, body, headers) + def log_request(method, path, query, payload, headers) logger.debug do "Zammad API request: #{method.to_s.upcase} #{Transport.redact_path(path)}#{" query=#{Transport.redact(query).inspect}" if query}#{" headers=#{Transport.redact(headers).inspect}" if headers}" end - logger.debug { "Zammad API payload: #{loggable_body(body).inspect}" } if body + logger.debug { "Zammad API payload: #{loggable_body(payload).inspect}" } if payload end def log_response(method, path, response, started) @@ -1186,22 +1186,37 @@ def log_response(method, path, response, started) logger.debug { "Zammad API response: #{method.to_s.upcase} #{Transport.redact_path(path)} -> #{response.status} in #{duration}ms" } end - # What the log prints for a request body. + # What the log prints for a request body: the body as it is sent, read + # back for its keys and redacted by them. # - # A body handed over as a String is the caller's own encoding, and - # {#redact} works by key: it had no keys to go by, so + # Read from the encoded payload and not from what the caller handed + # over, because {.redact} works by key and only a Hash has keys. What + # was handed over was printed by +inspect+ wherever it was anything + # else, and there are two ways for that to be a credential. + # + # One is a String, which is the caller's own encoding: # `client.post(path, body: '{"login":"a","password":"hunter2"}')` was - # written to the log as it stood. Where the String is JSON it is read - # for its keys and redacted like the structure it spells. Where it is - # not - a form body, a file - nothing in it can be told from a - # credential, and its size is logged in its place. - def loggable_body(body) - return Transport.redact(body) if !body.is_a?(String) - - decoded = JSON.parse(body) - decoded.is_a?(Hash) || decoded.is_a?(Array) ? Transport.redact(decoded) : unlogged_body(body) + # written to the log as it stood. + # + # The other is an object inside the body. One that writes its own JSON + # goes out as keys and values like any Hash - a value object with a + # +to_json+, as the whole body or under a key of it - and +inspect+ + # printed every one of them. One that does not is sent as its +to_s+, + # which for most objects names the class and no more, while +inspect+ + # lists what the object holds: the log then showed a value the request + # never carried. + # + # So the payload is parsed, and the log holds what the wire holds. Where + # it is a JSON object or array it is redacted like the structure it + # spells. Where it is not - a form body, a file, a single value - + # nothing in it can be told from a credential, and its size is logged + # in its place. Parsed only where the line is written: this runs inside + # the logger's block. + def loggable_body(payload) + decoded = JSON.parse(payload) + decoded.is_a?(Hash) || decoded.is_a?(Array) ? Transport.redact(decoded) : unlogged_body(payload) rescue JSON::JSONError, EncodingError - unlogged_body(body) + unlogged_body(payload) end def unlogged_body(body) = "[#{body.bytesize} bytes that are not a JSON object or array, not logged]" diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 0da883f..94ea3da 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -74,7 +74,7 @@ module ZammadAPI private def timed_out?: (untyped error) -> bool - def perform: (Symbol, String, Hash[Symbol, untyped]?, untyped, String?, Hash[untyped, untyped]?) -> untyped + def perform: (Symbol, String, Hash[Symbol, untyped]?, String?, Hash[untyped, untyped]?) -> untyped def build_connection: () -> untyped def refuse_unusable_middleware!: (untyped connection) -> void def refused_middleware: (Class klass) -> String? @@ -82,9 +82,9 @@ module ZammadAPI def apply_authentication: (untyped) -> void def decode: (untyped) -> Response def raw_body!: (untyped) -> String - def log_request: (Symbol, String, Hash[Symbol, untyped]?, untyped, Hash[String, String]?) -> void + def log_request: (Symbol, String, Hash[Symbol, untyped]?, String?, Hash[String, String]?) -> void def log_response: (Symbol, String, Response, Float) -> void - def loggable_body: (untyped body) -> untyped + def loggable_body: (String payload) -> untyped def unlogged_body: (String body) -> String def reportable_cause: (StandardError error) -> StandardError? def redact_config_values: (untyped message) -> String diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 8a66a29..e2e3bc4 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1323,11 +1323,11 @@ def detailed_message = "unreadable: #{message}" end it 'marks the redacted payload value' do - expect(log).to include('password: "[REDACTED]"') + expect(log).to include('"password" => "[REDACTED]"') end it 'keeps non-sensitive payload values' do - expect(log).to include('login: "jane"') + expect(log).to include('"login" => "jane"') end it 'stays silent by default' do @@ -1393,7 +1393,7 @@ def detailed_message = "unreadable: #{message}" # Matched as a word, so that a key merely containing the letters stays # readable in the log rather than being blanked for nothing. it 'leaves a key whose name only contains one of the words alone' do - expect(log).to include('keyboard_layout: "de"') + expect(log).to include('"keyboard_layout" => "de"') end it 'redacts a client_secret' do @@ -1401,7 +1401,7 @@ def detailed_message = "unreadable: #{message}" end it 'still keeps a non-sensitive value' do - expect(log).to include('login: "jane"') + expect(log).to include('"login" => "jane"') end end @@ -1459,6 +1459,67 @@ def detailed_message = "unreadable: #{message}" end end + # The payload line printed the body the caller handed over, redacted by + # key through its Hashes and Arrays, and anything else in it by + # `inspect`. An object that writes its own JSON goes out as keys and + # values like any Hash, and was printed with every one of them. + context 'with a body holding an object that is neither a Hash nor an Array' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + let(:transport) { unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)) } + let(:credentials) { Data.define(:login, :password) { def to_json(*) = to_h.to_json(*) }.new(login: 'jane', password: 'object-s3cret') } + + before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } + + it 'redacts a credential in one that writes its own JSON' do + transport.post('api/v1/groups', operation: 'test', body: credentials) + + expect(log).not_to include('object-s3cret') + end + + it 'prints it as it is sent, redacted by key' do + transport.post('api/v1/groups', operation: 'test', body: credentials) + + expect(log).to include('Zammad API payload: {"login" => "jane", "password" => "[REDACTED]"}') + end + + it 'redacts a credential in one that a Hash holds' do + transport.post('api/v1/groups', operation: 'test', body: { note: 'x', user: credentials }) + + expect(log).to include('Zammad API payload: {"note" => "x", "user" => {"login" => "jane", "password" => "[REDACTED]"}}') + end + + it 'redacts a credential in one that an Array holds' do + transport.post('api/v1/groups', operation: 'test', body: [credentials]) + + expect(log).not_to include('object-s3cret') + end + + # JSON has no spelling for such an object, and the generator sends its + # `to_s`, which names the class and no more. `inspect` lists what it + # holds, so the log showed a value the request never carried. + it 'does not print what an object holds and the request does not carry' do + holder = Class.new { def initialize = @password = 'object-s3cret' }.new + transport.post('api/v1/groups', operation: 'test', body: { user: holder }) + + expect(log).not_to include('object-s3cret') + end + + it 'does not log a body that is one value with no keys to go by' do + transport.post('api/v1/groups', operation: 'test', body: :'object-s3cret') + + expect(log).not_to include('object-s3cret') + expect(log).to include('Zammad API payload: "[15 bytes that are not a JSON object or array, not logged]"') + end + + it 'still sends the body as it was given' do + transport.post('api/v1/groups', operation: 'test', body: { user: credentials }) + + expect(a_request(:post, url).with(body: '{"user":{"login":"jane","password":"object-s3cret"}}')).to have_been_made + end + end + # A raw request may carry its query in the path. The `query:` Hash is # redacted by key, and the same parameter written into the path was # printed in full, in the request line and in the response line. From b5329badfac5975b47558c0d05baf33f2c727022 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 11:24:55 +0200 Subject: [PATCH 014/121] fix: redact a path query that is separated by semicolons dc06edc redacts a query string written into the path of a raw request by parameter name, and splits it at `&`. Rack 2 ends a parameter at a `;` as well, and Zammad ran on Rack 2 up to 7.0. So `client.get('api/v1/x?page=2;token=...')` carries a token on those versions, and here it was the tail of a value named `page`: printed in both log lines for the request, in the message of a timeout and in the operation every error of the request names. A stretch between two `&` is now followed past each `;`, and a parameter named like a credential there is blanked as far as the next one. A credential the stretch opens with is still blanked to the next `&`, because Rack 3, and Zammad since 7.1, reads a `;` as part of the value: `?token=a;b` leaves no `b` standing under either reading. --- CHANGELOG.md | 7 +++++ lib/zammad_api/transport.rb | 39 ++++++++++++++++++++++++-- sig/zammad_api/transport.rbs | 2 ++ spec/unit/zammad_api/transport_spec.rb | 36 ++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6522fe8..da9e097 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -845,6 +845,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a from the JSON it was encoded to and redacted by key, however it was handed over, so the line shows String keys: `{"login" => "jane", "password" => "[REDACTED]"}`. A body that is one value is not logged, only its size. +- A query string written into the path of a raw request is redacted where its parameters + are separated by `;`. Zammad up to 7.0 runs on Rack 2, which ends a parameter at a `;` as + it does at an `&`, so `client.get('api/v1/x?page=2;token=...')` carries a token there. The + path was split at `&` alone, which made that the tail of a value named `page`, and it was + printed in the log and in the message of an error the request raised. A credential that + opens such a stretch is still blanked to the next `&`, since Rack 3, and Zammad since 7.1, + reads a `;` as part of the value. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index d88ccbb..0be91f4 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -669,11 +669,40 @@ def self.redact_path(path) "#{base}?#{query.split('&', -1).map { redact_query_pair(it) }.join('&')}" end + # One stretch of a query string between two +&+, as it may be printed. + # + # Usually that is one parameter. Rack 2 ends a parameter at a +;+ as + # well, though, and Zammad ran on it up to 7.0: there + # `?page=2;token=...` carries a token, and read as one parameter it was + # the tail of a value named +page+ and printed. Rack 3, and Zammad + # since 7.1, reads the +;+ as part of the value. + # + # Both readings are covered, since nothing here knows which server is + # asked. A credential the stretch opens with is blanked to its end, the + # +;+ and what follows included, which is the whole of its value as + # Rack 3 reads it. Any other is followed past each +;+, and a parameter + # named like a credential there is blanked as far as the next one, + # which is where Rack 2 ends it. + # # @api private # @return [String] def self.redact_query_pair(pair) - name, mark, = pair.partition('=') - return pair if mark.empty? + return blank_query_value(pair) if credential_parameter?(pair) + + first, separator, later = pair.partition(';') + return pair if separator.empty? + + "#{first};#{later.split(';', -1).map { credential_parameter?(it) ? blank_query_value(it) : it }.join(';')}" + end + + # Whether +name=value+ is named like a credential. A name that cannot + # be decoded cannot be read, and counts as one. + # + # @api private + # @return [Boolean] + def self.credential_parameter?(parameter) + name, mark, = parameter.partition('=') + return false if mark.empty? decoded = begin URI.decode_www_form_component(name) @@ -681,9 +710,13 @@ def self.redact_query_pair(pair) nil end - decoded && !SENSITIVE_KEY_PATTERN.match?(decoded) ? pair : "#{name}=#{REDACTED}" + decoded.nil? || SENSITIVE_KEY_PATTERN.match?(decoded) end + # @api private + # @return [String] + def self.blank_query_value(parameter) = "#{parameter.partition('=').first}=#{REDACTED}" + # A structure as it may be printed: with the value under every key that # names a credential blanked, at any depth. See {SENSITIVE_KEY_PATTERN} # for which keys those are. diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 94ea3da..af0d043 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -40,6 +40,8 @@ module ZammadAPI def self.redact_path: (untyped path) -> String def self.redact_query_pair: (String pair) -> String + def self.credential_parameter?: (String parameter) -> bool + def self.blank_query_value: (String parameter) -> String def self.redact: (untyped value) -> untyped def self.stringify_query: (Hash[untyped, untyped]) -> Hash[String, untyped] def self.stringify_query_hash: (Hash[untyped, untyped], String?) -> Hash[String, untyped] diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index e2e3bc4..ed06fc7 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -316,6 +316,42 @@ it 'blanks a value that holds a = of its own' do expect(described_class.redact_path('api/v1/x?token=a=b')).to eq('api/v1/x?token=[REDACTED]') end + + # Rack 2 ends a parameter at a `;` as it does at an `&`, and Zammad ran + # on it up to 7.0. There `?page=2;token=s3cret` carries a token, and + # split at `&` alone it was the tail of a value named `page`. + context 'with parameters separated by a semicolon' do + it 'blanks the value of one named like a credential' do + expect(described_class.redact_path('api/v1/x?page=2;token=s3cret')).to eq('api/v1/x?page=2;token=[REDACTED]') + end + + it 'keeps the parameters around it as they were written' do + expect(described_class.redact_path('api/v1/x?page=2;token=s3cret;q=a%20b&locale=de')).to eq('api/v1/x?page=2;token=[REDACTED];q=a%20b&locale=de') + end + + it 'reads the name behind a parameter with no value' do + expect(described_class.redact_path('api/v1/x?expand;page=2;password=s3cret')).to eq('api/v1/x?expand;page=2;password=[REDACTED]') + end + + it 'reads a name behind the space Rack skips after a separator' do + expect(described_class.redact_path('api/v1/x?page=2; token=s3cret')).to eq('api/v1/x?page=2; token=[REDACTED]') + end + + it 'blanks a value whose name cannot be read' do + expect(described_class.redact_path('api/v1/x?page=2;%zz=s3cret')).to eq('api/v1/x?page=2;%zz=[REDACTED]') + end + + # Rack 3 reads a `;` as part of the value, and so does every Zammad + # since 7.1. A credential is blanked to the next `&`, so that neither + # reading leaves the rest of it standing. + it 'blanks a credential that holds one to the end of its value' do + expect(described_class.redact_path('api/v1/x?token=s3;cret&page=2')).to eq('api/v1/x?token=[REDACTED]&page=2') + end + + it 'leaves a query without a credential as it was written' do + expect(described_class.redact_path('api/v1/x?page=2;q=a;b&c;')).to eq('api/v1/x?page=2;q=a;b&c;') + end + end end # The question the test kit asks, so that it sends again what the wire From 9c62a305d5b4e1317ceab3ce2467799d59d1323c Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 12:10:13 +0200 Subject: [PATCH 015/121] fix: refuse what is not a Hash in assign_attributes `assign_attributes` handed its argument straight to `DuplicateKeys.normalize` with `&:to_sym`. Nil raised NoMethodError naming `each_with_object`, from inside the gem, and so did `update(params[:ticket])` with the key missing. A Hash with a key that has no `to_sym` raised one too, where the constructor takes that Hash and keeps the key. An Array of pairs was read as a Hash. It raises ArgumentError for anything that is not a Hash, naming the class it was given and not the value. Keys become Symbols through `DeepCopy.symbolize`, the constructor's rule. `update` and `update!` stage through here, so they refuse the same and send nothing. Nil is refused rather than read as nothing to assign, which is what the constructor makes of it: `update(nil)` would stage nothing, send nothing and answer true. --- CHANGELOG.md | 7 ++++ lib/zammad_api/resources/base.rb | 25 ++++++++++-- spec/unit/zammad_api/resources/base_spec.rb | 42 +++++++++++++++++++++ 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da9e097..9bf5f91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -852,6 +852,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a printed in the log and in the message of an error the request raised. A credential that opens such a stretch is still blanked to the next `&`, since Rack 3, and Zammad since 7.1, reads a `;` as part of the value. +- `assign_attributes`, `update` and `update!` raise `ArgumentError` for something that is + not a Hash, and take a key that cannot become a Symbol. `ticket.update(nil)` — which is + `update(params[:ticket])` with the key missing — raised `NoMethodError: undefined method + 'each_with_object' for nil` from inside the gem, and `assign_attributes(1 => 'x')` raised + one about `to_sym` for a Hash the constructor takes. The message names the class that was + given and does not quote the value. Nil is refused rather than read as nothing to assign: + an `update` that staged nothing would answer `true`. ### Changed diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index a06f5be..bb9fc22 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -488,20 +488,35 @@ def related # @raise [Error] when an attribute cannot be staged, such as +id+, or # when the record was destroyed. Nothing is staged in either case, so # the record is left as it was. - # @raise [ArgumentError] when an attribute is named twice, as a String - # and as a Symbol. Nothing is staged then either. + # @raise [ArgumentError] when given something that is not a Hash, nil + # included, or when an attribute is named twice, as a String and as + # a Symbol. Nothing is staged then either. def assign_attributes(attributes) + # Asked before anything else, because everything below is a method + # of Hash. Nil raised NoMethodError naming `each_with_object`, from + # inside the gem, and so did `update(params[:group])` with the key + # missing; an Array of pairs was read as a Hash, by the accident of + # how it is iterated. Refused rather than read as nothing to assign, + # which is what the constructor makes of nil: a record built from + # nothing says so by being empty, and an `update` that staged + # nothing answers true as if it had stored something. + raise ArgumentError, "attributes need to be a Hash of names and values, got #{attributes.class}" if !attributes.is_a?(Hash) + # Two spellings of one attribute are refused before anything is # written, for the reason the constructor refuses them - see # {DeepCopy.frozen_hash}. Each key is written by its Symbol, so # `assign_attributes('name' => 'A', name: 'B')` wrote the attribute # twice and kept whichever Hash order put last. # + # A key becomes a Symbol by the constructor's rule, which keeps one + # that cannot: through `to_sym`, `assign_attributes(1 => 'x')` raised + # NoMethodError for a Hash `new` takes. + # # The values are copied here as well, which is where a pair inside # one of them is refused. Left to the writes below, a value that # names a nested key twice raised from the middle of them, with the # attributes before it already staged. - staged = frozen_attributes(DuplicateKeys.normalize(attributes, noun: 'attribute', &:to_sym)) + staged = frozen_attributes(DuplicateKeys.normalize(attributes, noun: 'attribute') { DeepCopy.symbolize(it) }) # rubocop:disable Style/CombinableLoops -- combining them is the bug # Two passes on purpose: every key is checked before any of them is @@ -611,6 +626,8 @@ def save! # @return [Boolean] whether the record was stored # @raise [Error] when the record was destroyed, or when an attribute # cannot be staged, such as +id+ + # @raise [ArgumentError] when given something that is not a Hash, nil + # included, or an attribute named twice: see {#assign_attributes} # @raise [ResponseError] for any failure other than a validation error # @see #save def update(attributes) @@ -631,6 +648,8 @@ def update(attributes) # @return [true] # @raise [Error] when the record was destroyed, or when an attribute # cannot be staged, such as +id+ + # @raise [ArgumentError] when given something that is not a Hash, nil + # included, or an attribute named twice: see {#assign_attributes} # @raise [ResponseError] when Zammad rejected the request # @see #save! def update!(attributes) diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index 2de2afe..4387447 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -420,6 +420,36 @@ def self.name expect(group).not_to be_changed end end + + # The constructor makes a Symbol of a key where it can and keeps one it + # cannot. Here every key went through `to_sym`, so the Hash the + # constructor takes raised NoMethodError from inside the gem. + it 'keeps a key that cannot become a Symbol, as the constructor does' do + group.assign_attributes(1 => 'x') + + expect(group.attributes).to eq(client.groups.new(:name => 'Support', 1 => 'x').attributes) + end + + # Handed straight to a method of Hash, so what was not one raised + # NoMethodError naming that method, and an Array was read as pairs. + context 'with something that is not a Hash' do + it 'refuses nil, and names the class it was given' do + expect { group.assign_attributes(nil) }.to raise_error(ArgumentError, 'attributes need to be a Hash of names and values, got NilClass') + end + + it 'refuses a String' do + expect { group.assign_attributes('name') }.to raise_error(ArgumentError, /got String/) + end + + it 'refuses an Array of pairs rather than reading it as a Hash' do + expect { group.assign_attributes([[:name, 'Renamed']]) }.to raise_error(ArgumentError, /got Array/) + expect(group).not_to be_changed + end + + it 'does not quote what it was given, which may hold a credential' do + expect { group.assign_attributes('password=hunter2') }.to raise_error(ArgumentError) { expect(it.message).not_to include('hunter2') } + end + end end describe '#update' do @@ -471,11 +501,23 @@ def self.name expect(client.groups.new.update(name: 'Support')).to be(true) expect(stub).to have_been_requested end + + # `update(params[:group])` with the key missing. It raised NoMethodError + # for nil, from inside the gem. + it 'refuses nil, and sends nothing' do + expect { group.update(nil) }.to raise_error(ArgumentError, /attributes need to be a Hash of names and values, got NilClass/) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end end describe '#update!' do subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, note: 'old') } + it 'refuses nil, and sends nothing' do + expect { group.update!(nil) }.to raise_error(ArgumentError, /got NilClass/) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + it 'returns true' do stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1 })) From 8d476fd423e23ffcc603e022d567302d354a45ac Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 12:24:40 +0200 Subject: [PATCH 016/121] fix: read strong parameters as the Hash they convert to `ActionController::Parameters` is not a Hash, and the walk that copies, freezes and symbolizes a record's attributes passes anything that is not one through. So `client.users.new(permitted)` held the caller's own object: `inspect` (884660f) and the debug log redact by key through a Hash and printed the password, `save` sent the object's `to_s` as one JSON string where 1.x sent `params.to_json`, and a later write to the parameters changed the record. `update` and `assign_attributes` raised NoMethodError for them, and a `condition:` given to `search` that way went out as its `to_s`. What answers `to_hash` is now read as that Hash at every door a structure comes in through: - `DeepCopy.frozen_copy`, for an attribute set and for a value in it at any depth, and so for a writer and a search filter - `Base#attribute_hash`, for the argument of `new`, `create`, `update`, `assign_attributes` and `add_article` - `Transport.stringify_query`, for a query and a value inside it - `Transport.encode_body`, for the body of a raw request, which the test kit records through the same walk Parameters that were not permitted raise their own error from `to_hash`. Anything else given as attributes raises ArgumentError naming its class, after 2285f61: a String and an Integer raised NoMethodError in the constructor, and an Array of pairs was stored. `new(nil)` still builds a record with no attributes. A `query:` that is no Hash is refused the same way. The request line of the debug log prints the query as it is sent, since the one handed over may hold what `inspect` prints in full. The cases of the walk are reordered by how often each turns up in a record, so that asking the new question costs the path that builds records from a page nothing a benchmark shows. --- CHANGELOG.md | 17 ++++ README.md | 11 +++ lib/zammad_api/deep_copy.rb | 43 +++++++++- lib/zammad_api/resources/base.rb | 41 ++++++++-- lib/zammad_api/resources/ticket.rb | 8 +- lib/zammad_api/transport.rb | 41 ++++++++-- sig/zammad_api/deep_copy.rbs | 1 + sig/zammad_api/resource_proxy.rbs | 4 +- sig/zammad_api/resources/base.rbs | 9 ++- sig/zammad_api/resources/resources.rbs | 2 +- sig/zammad_api/transport.rbs | 4 +- spec/support/strong_parameters.rb | 28 +++++++ spec/unit/zammad_api/resource_proxy_spec.rb | 16 ++++ spec/unit/zammad_api/resources/base_spec.rb | 80 +++++++++++++++++++ spec/unit/zammad_api/resources/ticket_spec.rb | 16 ++++ spec/unit/zammad_api/test_spec.rb | 16 ++++ spec/unit/zammad_api/transport_spec.rb | 79 ++++++++++++++++++ 17 files changed, 390 insertions(+), 26 deletions(-) create mode 100644 spec/support/strong_parameters.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bf5f91..2f5e940 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -859,6 +859,23 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a one about `to_sym` for a Hash the constructor takes. The message names the class that was given and does not quote the value. Nil is refused rather than read as nothing to assign: an `update` that staged nothing would answer `true`. +- Strong parameters are read as the Hash they convert to. `ActionController::Parameters` is + not a Hash, so `client.users.new(params.require(:user).permit(:login, :password))` built + a record holding the caller's own object: `inspect` and the debug log printed the + password, `save` sent the parameters as one JSON string holding their `to_s`, where 1.x + sent `params.to_json`, and a later change to the parameters changed the record. `update` + and `assign_attributes` raised `NoMethodError` for them, and a `condition:` given to + `search` that way was written as its `to_s`, which Zammad drops. Whatever answers + `to_hash` is now converted wherever a structure is handed over: as the attributes of + `new`, `create`, `update`, `assign_attributes` and `add_article`, as the value of an + attribute at any depth, in a search filter, and in the `query:` and `body:` of a raw + request. Parameters that were not permitted raise their own + `ActionController::UnfilteredParameters`. Anything else given as a set of attributes — + a String, an Array of pairs, a Struct — raises `ArgumentError` naming its class, where it + raised `NoMethodError` or was stored as it was; `new(nil)` is still a record with no + attributes. A `query:` that is not a Hash raises `ArgumentError` the same way. +- The debug log prints the query of a request as it is sent, like its headers and its + body, so the line shows String keys and values: `query={"page" => "1"}`. ### Changed diff --git a/README.md b/README.md index 6278a27..77c9e99 100644 --- a/README.md +++ b/README.md @@ -402,6 +402,17 @@ Or in one call: group = client.groups.create(name: 'Support', note: 'Some note') ``` +Attributes are a Hash, or anything that converts to one with `to_hash`. In a Rails +controller that is the permitted parameters, which `new`, `create`, `update`, +`assign_attributes` and `add_article` take as they are: + +```ruby +client.users.create(params.require(:user).permit(:login, :email, :password)) +``` + +Parameters that were not permitted raise `ActionController::UnfilteredParameters`, and +anything else that is not a Hash raises `ArgumentError`. + ### Fetch ```ruby diff --git a/lib/zammad_api/deep_copy.rb b/lib/zammad_api/deep_copy.rb index b038c40..59e7f81 100644 --- a/lib/zammad_api/deep_copy.rb +++ b/lib/zammad_api/deep_copy.rb @@ -16,6 +16,9 @@ module ZammadAPI # +JSON.parse+ builds and what a caller may hand in as attributes. Numbers, # booleans and nil are immutable already and are passed through untouched. # + # A caller may also hand in what is not a Hash and converts to one, and + # that is read as the Hash it converts to: see {frozen_object}. + # # One walk, deliberately. A record built from a response copies every String # of a body +JSON.parse+ has just built and nothing else holds, so a variant # that froze such a body in place would save that copy on the paging hot @@ -55,14 +58,50 @@ module DeepCopy # @raise [ArgumentError] when symbolizing lands two keys of one Hash on # one name def frozen_copy(value, symbolize_keys: false) + # Ordered by how often each kind turns up in a record Zammad serves, + # where nil, a String and an Integer are nine values in ten. Every + # value that has nothing to copy is answered before {frozen_object} is + # asked, and in this order asking it costs the record-building path + # nothing that a benchmark of a page of tickets shows: copying one + # hundred of them took the same time with the question as without. case value + when nil then nil + when String then value.dup.freeze + when Integer, true, false, Float, Symbol then value when Hash then frozen_hash(value, symbolize_keys) when Array then value.map { frozen_copy(it, symbolize_keys: symbolize_keys) }.freeze - when String then value.dup.freeze - else value + else frozen_object(value, symbolize_keys) end end + # What is none of the above: copied as the Hash it converts to, where it + # converts to one, and handed back as it is otherwise. + # + # `ActionController::Parameters` is the reason. It is not a Hash, so the + # walk passed it through, and it is what a Rails controller holds: + # `client.users.new(params.require(:user).permit(:login, :password))` + # built a record whose attributes were the caller's own object, unfrozen + # and with String keys. Its `inspect` and the debug log redact by key + # through a Hash and printed the password, and the body of its `save` + # was that object's `to_s` as one JSON string, where 1.x sent + # `params.to_json`. Nested under an attribute it did the same one level + # down. + # + # +to_hash+ is what is asked, which is how Ruby itself asks whether + # something may stand in for a Hash - a Struct and a Data have +to_h+ + # and do not claim that. Strong parameters answer it with plain Hashes + # all the way down, and refuse where they were not permitted, with + # `ActionController::UnfilteredParameters`: that error is left to say + # so. + # + # @api private + # @return [Object] a frozen copy, or +value+ + def frozen_object(value, symbolize_keys) + converted = Hash.try_convert(value) + + converted ? frozen_hash(converted, symbolize_keys) : value + end + # The Hash branch of {frozen_copy}. # # Two keys that symbolize to one name are refused rather than merged. diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index bb9fc22..279ee3a 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -385,12 +385,16 @@ def has_many(name, class_name:, path:) belongs_to :updated_by, class_name: 'User' # @param transport [Transport] - # @param attributes [Hash, nil] + # @param attributes [Hash, nil] or what converts to a Hash, such as + # permitted `ActionController::Parameters` # @raise [Error] when an attribute cannot be staged, such as +id+ - # @raise [ArgumentError] when an attribute is named twice, as a String - # and as a Symbol, at any depth + # @raise [ArgumentError] when given something that is neither, or when + # an attribute is named twice, as a String and as a Symbol, at any + # depth def initialize(transport, attributes = {}) - given = attributes || {} + # Nil alone is no attributes. Anything else is read as a Hash or + # refused: see {#attribute_hash}. + given = nil.equal?(attributes) ? {} : attribute_hash(attributes) # The same refusal the writers make, at the one door that did not make # it. `group.id = 99` is refused with a sentence about what an id is # for, and `client.groups.new(id: 99)` was accepted in silence - and @@ -483,12 +487,14 @@ def related # group.assign_attributes(name: 'Support 2', note: 'Renamed') # group.changed? # => true # - # @param attributes [Hash] attribute names and their new values + # @param attributes [Hash] attribute names and their new values, or + # what converts to a Hash, such as permitted + # `ActionController::Parameters` # @return [self] # @raise [Error] when an attribute cannot be staged, such as +id+, or # when the record was destroyed. Nothing is staged in either case, so # the record is left as it was. - # @raise [ArgumentError] when given something that is not a Hash, nil + # @raise [ArgumentError] when given something that is neither, nil # included, or when an attribute is named twice, as a String and as # a Symbol. Nothing is staged then either. def assign_attributes(attributes) @@ -500,7 +506,7 @@ def assign_attributes(attributes) # which is what the constructor makes of nil: a record built from # nothing says so by being empty, and an `update` that staged # nothing answers true as if it had stored something. - raise ArgumentError, "attributes need to be a Hash of names and values, got #{attributes.class}" if !attributes.is_a?(Hash) + attributes = attribute_hash(attributes) # Two spellings of one attribute are refused before anything is # written, for the reason the constructor refuses them - see @@ -765,6 +771,27 @@ def mark_persisted! @new_record = false end + # A set of attributes a caller handed over, as the Hash it is read as. + # + # A Hash, or what converts to one. `ActionController::Parameters` is + # not a Hash, and it is what `client.users.new(params.require(:user) + # .permit(:login, :password))` hands over: the constructor took it as + # it was - see {DeepCopy.frozen_object} for what became of the record - + # and {#assign_attributes} raised NoMethodError for it. Converted here, + # at the door, so that everything behind it is handed a Hash. + # + # Anything else is refused, and named by its class alone: what was + # given may hold a credential. It used to raise NoMethodError from + # whichever method of Hash was called on it first, or be taken, as an + # Array of pairs was. + # + # @param given [Object] + # @return [Hash] + # @raise [ArgumentError] + def attribute_hash(given) + Hash.try_convert(given) || raise(ArgumentError, "attributes need to be a Hash of names and values, got #{given.class}") + end + # Refuses an operation on a record Zammad never had. # # `destroyed?` was the only thing these asked, so a record built with an diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index cf2385e..c5e5991 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -75,7 +75,13 @@ def add_article(attributes = {}) # article refuses two spellings of one attribute now, and a String # `ticket_id` left beside this ticket's would be refused as a pair # the caller never wrote. - own = attributes.reject { |key, _| key.to_s == 'ticket_id' } + # + # Read as a Hash first, by the rule the article's own constructor + # has - see {Base#attribute_hash} - so that what is taken apart here + # is one: the strong parameters of a controller, converted, and + # anything that is no set of attributes refused before `reject` is + # called on it. + own = attribute_hash(attributes).reject { |key, _| key.to_s == 'ticket_id' } record = TicketArticle.new(transport, own.merge(ticket_id: require_id!)) record.save! record diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 0be91f4..20f52e2 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -197,13 +197,26 @@ module Verbs # shape as the dropped nil above, and the reason {ResourceProxy#search} # normalises its keywords before they ever reach here. # + # What is not a Hash and converts to one is read as that Hash, at the + # top and at any depth, as a record reads its attributes: see + # {DeepCopy.frozen_object}. `ActionController::Parameters` is the case. + # A +condition+ handed to {ResourceProxy#search} as one went on the wire + # as its +to_s+, which is the unnarrowed search described below, and a + # whole +query:+ given as one raised NoMethodError from inside the gem. + # So did anything else that is no Hash, and that is refused here by + # name. + # # @api private # @param query [Hash] # @return [Hash{String => String, Array, Hash}] - # @raise [ArgumentError] for a nil value, for two keys that name the - # same parameter, or for a list a query string cannot carry, any of - # them at any depth - def self.stringify_query(query) = stringify_query_hash(query, nil) + # @raise [ArgumentError] for a query that is not a Hash, for a nil + # value, for two keys that name the same parameter, or for a list a + # query string cannot carry, the last three at any depth + def self.stringify_query(query) + hash = Hash.try_convert(query) || raise(ArgumentError, "query needs to be a Hash of parameter names and values, got #{query.class}") + + stringify_query_hash(hash, nil) + end # Stringifies one level of a query, at whatever depth it sits. # @@ -271,7 +284,10 @@ def self.stringify_query_value(key, value) when nil then raise ArgumentError, "query parameter #{key} is nil, and Zammad has no way to read that: pass a value, or leave the parameter out" when Hash then stringify_query_hash(value, key) when Array then stringify_query_list(key, value) - else wire_text(value, "query parameter #{key}") + else + converted = Hash.try_convert(value) + + converted ? stringify_query_hash(converted, key) : wire_text(value, "query parameter #{key}") end end @@ -764,7 +780,13 @@ def self.redact(value) def self.encode_body(body, operation:, resource_class: nil) return body if body.nil? || body.is_a?(String) - JSON.generate(body) + # Through the walk a record's attributes go through, for what it + # reads as a Hash: see {DeepCopy.frozen_object}. The generator has no + # spelling for `ActionController::Parameters` and writes its `to_s` + # as one String, so `client.post(path, body: permitted)` sent that in + # place of an object, password included, and a body holding one sent + # it under the key. + JSON.generate(DeepCopy.frozen_copy(body)) rescue JSON::JSONError => e raise Error, "Can't #{Error.subject_for(operation, resource_class)}: the request body cannot be encoded as JSON (#{e.message}). " \ 'Every value has to be a JSON type, and text has to be valid UTF-8: Base64-encode binary data such as an ' \ @@ -953,7 +975,12 @@ def perform(method, path, query, payload, headers) # not leave a line claiming a request that was never made. params = query && Transport.stringify_query(query) fields = headers && Transport.stringify_headers(headers) - log_request(method, path, query, payload, fields) + # The query as it is sent, like the headers and the body. The one the + # caller handed over was logged, redacted by key through its Hashes, + # and what it held that converts to a Hash and is sent as one - see + # {.stringify_query} - was printed by `inspect`, under whatever key + # it sat. + log_request(method, path, params, payload, fields) @connection.public_send(method, path) do |request| request.params.update(params) if params diff --git a/sig/zammad_api/deep_copy.rbs b/sig/zammad_api/deep_copy.rbs index b5c7325..d9a37ab 100644 --- a/sig/zammad_api/deep_copy.rbs +++ b/sig/zammad_api/deep_copy.rbs @@ -2,6 +2,7 @@ module ZammadAPI module DeepCopy def self?.frozen_copy: (untyped value, ?symbolize_keys: bool) -> untyped def self?.frozen_hash: (Hash[untyped, untyped] hash, bool symbolize_keys) -> Hash[untyped, untyped] + def self?.frozen_object: (untyped value, bool symbolize_keys) -> untyped def self?.writable_copy: (untyped value) -> untyped def self?.symbolize: (untyped key) -> untyped end diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs index 208dd3c..a557bd9 100644 --- a/sig/zammad_api/resource_proxy.rbs +++ b/sig/zammad_api/resource_proxy.rbs @@ -16,8 +16,8 @@ module ZammadAPI @transport: Transport def initialize: (Transport, untyped resource_class) -> void - def new: (?Hash[untyped, untyped] attributes) -> R - def create: (?Hash[untyped, untyped] attributes) -> R + def new: (?hash[untyped, untyped] attributes) -> R + def create: (?hash[untyped, untyped] attributes) -> R def find: (Integer | String id) -> R def find_by: (**untyped) -> R? def find_by!: (**untyped) -> R diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 877689a..79a274f 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -62,18 +62,18 @@ module ZammadAPI def self.belongs_to: (Symbol name, class_name: String, ?foreign_key: Symbol) -> void def self.has_many: (Symbol name, class_name: String, path: ^(String) -> String) -> void - def initialize: (Transport, ?Hash[untyped, untyped]? attributes) -> void + def initialize: (Transport, ?hash[untyped, untyped]? attributes) -> void def new_record?: () -> bool def persisted?: () -> bool def destroyed?: () -> bool def changes: () -> Hash[Symbol, Array[untyped]] def changed?: () -> bool def related: () -> Associations::Proxy - def assign_attributes: (Hash[untyped, untyped] attributes) -> self + def assign_attributes: (hash[untyped, untyped] attributes) -> self def save: () -> bool def save!: () -> true - def update: (Hash[untyped, untyped] attributes) -> bool - def update!: (Hash[untyped, untyped] attributes) -> true + def update: (hash[untyped, untyped] attributes) -> bool + def update!: (hash[untyped, untyped] attributes) -> true def reload: () -> self def destroy: () -> true def inspect: () -> String @@ -83,6 +83,7 @@ module ZammadAPI def initialize_copy: (self source) -> void def setup: (Transport, Hash[untyped, untyped] attributes) -> void def mark_persisted!: () -> void + def attribute_hash: (untyped given) -> Hash[untyped, untyped] def raise_if_destroyed!: (String action) -> void def raise_if_new!: (String operation) -> void def writable_attributes?: () -> bool diff --git a/sig/zammad_api/resources/resources.rbs b/sig/zammad_api/resources/resources.rbs index 8b96876..fabf036 100644 --- a/sig/zammad_api/resources/resources.rbs +++ b/sig/zammad_api/resources/resources.rbs @@ -151,7 +151,7 @@ module ZammadAPI attr_reader last_owner_update_at: String? def articles: () -> Array[TicketArticle] - def add_article: (?Hash[untyped, untyped] attributes) -> TicketArticle + def add_article: (?hash[untyped, untyped] attributes) -> TicketArticle end class TicketArticle < Base diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index af0d043..a34b5d9 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -43,7 +43,7 @@ module ZammadAPI def self.credential_parameter?: (String parameter) -> bool def self.blank_query_value: (String parameter) -> String def self.redact: (untyped value) -> untyped - def self.stringify_query: (Hash[untyped, untyped]) -> Hash[String, untyped] + def self.stringify_query: (untyped) -> Hash[String, untyped] def self.stringify_query_hash: (Hash[untyped, untyped], String?) -> Hash[String, untyped] def self.stringify_query_value: (String, untyped) -> untyped def self.stringify_query_list: (String, Array[untyped]) -> Array[untyped] @@ -84,7 +84,7 @@ module ZammadAPI def apply_authentication: (untyped) -> void def decode: (untyped) -> Response def raw_body!: (untyped) -> String - def log_request: (Symbol, String, Hash[Symbol, untyped]?, String?, Hash[String, String]?) -> void + def log_request: (Symbol, String, Hash[String, untyped]?, String?, Hash[String, String]?) -> void def log_response: (Symbol, String, Response, Float) -> void def loggable_body: (String payload) -> untyped def unlogged_body: (String body) -> String diff --git a/spec/support/strong_parameters.rb b/spec/support/strong_parameters.rb new file mode 100644 index 0000000..2df64e5 --- /dev/null +++ b/spec/support/strong_parameters.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +# What `ActionController::Parameters` is to this gem, without Rails: not a +# Hash, converting to one with String keys where it was permitted and +# refusing where it was not, and printing everything it holds. +# +# The real one answers `to_hash` with plain Hashes all the way down, so this +# one converts what it holds of its own kind. +class StrongParameters + class Unfiltered < ArgumentError; end + + # @param values [Hash] the parameters, which may also be written as + # keywords: `StrongParameters.new(name: 'Support')` + def initialize(values = {}, permitted: true, **keywords) + @values = values.merge(keywords) + @permitted = permitted + end + + def to_hash + raise Unfiltered, 'unable to convert unpermitted parameters to hash' if !@permitted + + @values.to_h { |key, value| [key.to_s, value.is_a?(self.class) ? value.to_hash : value] } + end + + def to_s = @values.to_s + + def inspect = "#<#{self.class.name} #{@values.inspect} permitted: #{@permitted}>" +end diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index c3300ec..0440b3f 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -793,6 +793,22 @@ def stub_last_page(page, records, per_page: default_per_page) .to have_been_made end + # `condition: params.require(:condition).permit!`. It is not a Hash, + # so it was written as its `to_s`, which Zammad cannot read and drops: + # the search came back unnarrowed. + it 'sends a condition given as strong parameters the same way' do + condition = StrongParameters.new('ticket.state_id' => StrongParameters.new(operator: 'is', value: [1])) + client.tickets.search('x', condition: condition).to_a + + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/search") + .with(query: hash_including('condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => ['1'] } }))) + .to have_been_made + end + + it 'refuses a condition given as strong parameters with nothing in them, as it does an empty Hash' do + expect { client.tickets.search('x', condition: StrongParameters.new({})) }.to raise_error(ArgumentError, /search was given condition/) + end + it 'accepts a keyword spelled as a string' do expect(client.users.search('x', 'ids' => [1])).to be_a(ZammadAPI::Collection) end diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index 4387447..c2dd158 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -55,6 +55,71 @@ def self.name expect(group).not_to be_changed end + # What a Rails controller holds. It is not a Hash, so it was stored as + # it was handed over: the record held the caller's own object, printed + # its password, and saved it as one JSON string. + context 'when given strong parameters, which convert to a Hash and are not one' do + subject(:user) { client.users.new(permitted) } + + let(:permitted) { StrongParameters.new(login: 'jane', password: 'hunter2', preferences: StrongParameters.new(locale: 'de')) } + + it 'holds them as attributes of its own' do + expect(user.attributes).to eq(login: 'jane', password: 'hunter2', preferences: { locale: 'de' }) + end + + it 'holds a frozen copy, as it does of a Hash' do + expect(user.instance_variable_get(:@attributes)).to be_frozen.and be_a(Hash) + end + + it 'keeps the password out of inspect' do + expect(user.inspect).to include('password: "[REDACTED]"') + expect(user.inspect).not_to include('hunter2') + end + + it 'saves them as a JSON object' do + stub = stub_request(:post, "#{ClientHelper::BASE_URL}api/v1/users") + .with(query: hash_including({}), body: '{"login":"jane","password":"hunter2","preferences":{"locale":"de"}}') + .to_return(json_response({ id: 7, login: 'jane' }, status: 201)) + + client.users.create(permitted) + expect(stub).to have_been_requested + end + + it 'reads them as a Hash where they are the value of an attribute' do + expect(client.users.new(login: 'jane', preferences: StrongParameters.new(locale: 'de')).preferences).to eq(locale: 'de') + end + + it 'reads them as a Hash where a writer is given them' do + user.preferences = StrongParameters.new(locale: 'en') + + expect(user.preferences).to eq(locale: 'en') + end + + it 'leaves the refusal of parameters that were not permitted to say so' do + expect { client.users.new(StrongParameters.new({ login: 'jane' }, permitted: false)) }.to raise_error(StrongParameters::Unfiltered) + end + end + + # Each of these reached a method of Hash and raised NoMethodError for + # it, and an Array of pairs was stored as the attributes. + context 'when given what is no set of attributes' do + it 'refuses a String, naming its class' do + expect { client.groups.new('name') }.to raise_error(ArgumentError, 'attributes need to be a Hash of names and values, got String') + end + + it 'refuses an Array of pairs' do + expect { client.groups.new([[:name, 'Support']]) }.to raise_error(ArgumentError, /got Array/) + end + + it 'refuses a Struct, which has a to_h and does not claim to be a Hash' do + expect { client.groups.new(Struct.new(:name).new('Support')) }.to raise_error(ArgumentError, /attributes need to be a Hash/) + end + + it 'still takes nil for no attributes' do + expect(client.groups.new(nil).attributes).to eq({}) + end + end + it 'records a change as old and new value' do group.name = 'Other' expect(group.changes).to eq(name: %w[Support Other]) @@ -450,6 +515,21 @@ def self.name expect { group.assign_attributes('password=hunter2') }.to raise_error(ArgumentError) { expect(it.message).not_to include('hunter2') } end end + + # `record.update(params.require(:group).permit(:name))`. It raised + # NoMethodError naming `each_with_object`. + context 'with strong parameters' do + it 'stages what they convert to' do + group.assign_attributes(StrongParameters.new(name: 'Renamed', note: 'Why')) + + expect(group.changes).to eq(name: %w[Support Renamed], note: [nil, 'Why']) + end + + it 'stages nothing where they were not permitted' do + expect { group.assign_attributes(StrongParameters.new({ name: 'Renamed' }, permitted: false)) }.to raise_error(StrongParameters::Unfiltered) + expect(group).not_to be_changed + end + end end describe '#update' do diff --git a/spec/unit/zammad_api/resources/ticket_spec.rb b/spec/unit/zammad_api/resources/ticket_spec.rb index 8c743f7..465ad21 100644 --- a/spec/unit/zammad_api/resources/ticket_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -92,6 +92,22 @@ expect(ticket.add_article(body: 'hello')).to be_persisted end + # `ticket.add_article(params.require(:article).permit(:body))`, which is + # taken apart here before the article is built from it. + it 'reads strong parameters as the Hash they convert to' do + stub = stub_request(:post, article_url) + .with(query: { 'expand' => 'true' }, body: '{"body":"hello","ticket_id":42}') + .to_return(json_response({ id: 9, body: 'hello', ticket_id: 42 }, status: 201)) + + ticket.add_article(StrongParameters.new(body: 'hello')) + expect(stub).to have_been_requested + end + + it 'refuses what is no set of attributes, and sends nothing' do + expect { ticket.add_article('hello') }.to raise_error(ArgumentError, 'attributes need to be a Hash of names and values, got String') + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + # The article goes to the ticket it was added to, whatever the attributes # say. Given `ticket_id` under both spellings, the Symbol was replaced and # the String, coming later in the Hash, replaced it again when the article diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 9f020c3..a3abf84 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -509,6 +509,22 @@ expect(zammad.requests.last.body).to be_frozen end + # The wire carries strong parameters as the Hash they convert to, so + # that is what the record of a request holds, and not the object. + it 'records strong parameters as the Hash they are sent as' do + zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) + client.post('api/v1/groups', body: { group: StrongParameters.new(name: 'Support') }) + + expect(zammad.requests.last.body).to eq({ group: { 'name' => 'Support' } }) + end + + it 'records a record built from them as the attributes it sends' do + zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) + client.groups.create(StrongParameters.new(name: 'Support')) + + expect(zammad.requests.last.body).to eq({ name: 'Support' }) + end + it 'records the query parameters the client sent' do client.groups.find(1) diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index ed06fc7..de1404e 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -110,6 +110,35 @@ .to eq({ 'condition' => { 'open' => { 'active' => 'true', 'limit' => '5' } } }) end + # `ActionController::Parameters` is not a Hash. Nested, it was written + # as its `to_s`; as the whole query it raised NoMethodError. + context 'with what converts to a Hash and is not one' do + it 'reads it as that Hash where it is a value' do + expect(described_class.stringify_query(condition: StrongParameters.new(open: StrongParameters.new(limit: 5)))) + .to eq({ 'condition' => { 'open' => { 'limit' => '5' } } }) + end + + it 'reads it as that Hash where it is the query' do + expect(described_class.stringify_query(StrongParameters.new(page: 2))).to eq({ 'page' => '2' }) + end + + it 'refuses two spellings of one key in it, as in a Hash' do + expect { described_class.stringify_query(condition: StrongParameters.new(a: 1), 'condition' => 2) }.to raise_error(ArgumentError, /given twice/) + end + + it 'sends it the way Rails reads a nested parameter back' do + stub = stub_request(:get, "#{url}/search").with(query: { 'condition' => { 'state' => { 'operator' => 'is' } } }).to_return(json_response([])) + unit_transport.get('api/v1/groups/search', operation: 'test', query: { condition: StrongParameters.new(state: { operator: 'is' }) }) + + expect(stub).to have_been_requested + end + end + + it 'refuses a query that is no Hash, naming its class' do + expect { described_class.stringify_query('page=2') } + .to raise_error(ArgumentError, 'query needs to be a Hash of parameter names and values, got String') + end + # Faraday's escaping raised Encoding::CompatibilityError for one. it 'sends a value given in UTF-16 as the same text in UTF-8' do stub = stub_request(:get, "#{url}/search").with(query: { 'query' => 'ä b' }).to_return(json_response([])) @@ -525,6 +554,31 @@ def response(status, headers = {}) expect(stub).to have_been_requested end + # The generator has no spelling for `ActionController::Parameters` and + # writes its `to_s`, so the body was one JSON string holding a Ruby + # inspect of the parameters. + context 'with a body that converts to a Hash and is not one' do + before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } + + it 'sends it as the JSON object it converts to' do + unit_transport.post('api/v1/groups', operation: 'test', body: StrongParameters.new(name: 'Support', preferences: StrongParameters.new(locale: 'de'))) + + expect(a_request(:post, url).with(body: '{"name":"Support","preferences":{"locale":"de"}}')).to have_been_made + end + + it 'sends one that a Hash or an Array holds the same way' do + unit_transport.post('api/v1/groups', operation: 'test', body: { groups: [StrongParameters.new(name: 'Support')] }) + + expect(a_request(:post, url).with(body: '{"groups":[{"name":"Support"}]}')).to have_been_made + end + + it 'sends nothing where it refuses to convert' do + expect { unit_transport.post('api/v1/groups', operation: 'test', body: StrongParameters.new({ name: 'Support' }, permitted: false)) } + .to raise_error(StrongParameters::Unfiltered) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end + # Faraday's JSON middleware raised JSON::GeneratorError from inside the # stack and nothing mapped it, so it went past the rescue of # ZammadAPI::Error every caller is told to write. @@ -1556,6 +1610,31 @@ def detailed_message = "unreadable: #{message}" end end + # The request line printed the `query:` the caller handed over, redacted + # by key through its Hashes. What it held that converts to a Hash, and + # is sent as one, was printed by `inspect` under the key it sat at. + context 'with a query that carries a credential' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + let(:transport) { unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)) } + + before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) } + + it 'redacts it by key, in the query as it is sent' do + transport.get('api/v1/groups', operation: 'test', query: { page: 1, token: 'query-s3cret' }) + + expect(log).to include('Zammad API request: GET api/v1/groups query={"page" => "1", "token" => "[REDACTED]"}') + end + + it 'redacts it in strong parameters the query holds' do + transport.get('api/v1/groups', operation: 'test', query: { filter: StrongParameters.new(page: 1, token: 'query-s3cret') }) + + expect(log).to include('query={"filter" => {"page" => "1", "token" => "[REDACTED]"}}') + expect(log).not_to include('query-s3cret') + end + end + # A raw request may carry its query in the path. The `query:` Hash is # redacted by key, and the same parameter written into the path was # printed in full, in the request line and in the response line. From 01147ad40b9c188b504afe0cabbbc04f7a7bc57c Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 12:26:26 +0200 Subject: [PATCH 017/121] fix: refuse arguments given to an attribute reader An attribute is read through `method_missing`, which never looked at its arguments: `ticket.state('closed')` answered "open" and changed nothing, and `ticket.title(1, 2, 3)` answered with the title. b6a68f7 removed `Ticket#article` and has the call that added an article in 1.x raise NoMethodError. That holds for a ticket with no article staged. On one that has - `ticket.article = {...}`, or a ticket built with `article:` whose save was rejected - `article` is an attribute the record carries, and `ticket.article(body: 'reply')` answered with the staged article, sent nothing and raised nothing. A reader given arguments raises ArgumentError, opening with Ruby's own words for it: "wrong number of arguments (given 1, expected 0)". It says the name is an attribute, and on a record that takes writes, where a value for it is written. A ticket adds, for `article`, that `add_article` is the call. A block is still ignored, as any method ignores one. --- CHANGELOG.md | 11 +++++-- README.md | 2 +- lib/zammad_api/attribute_access.rb | 33 ++++++++++++++++++- lib/zammad_api/resources/ticket.rb | 15 +++++++++ sig/zammad_api/attribute_access.rbs | 1 + spec/unit/zammad_api/attribute_access_spec.rb | 32 ++++++++++++++++++ spec/unit/zammad_api/resources/ticket_spec.rb | 26 +++++++++++++++ 7 files changed, 116 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f5e940..7469840 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -173,8 +173,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a environment that itself sets two schemes is refused until an argument says which is meant. - `ticket.article(…)` is `ticket.add_article(…)`. A noun that sends a `POST` sat one letter away from `ticket.articles`, which only reads. The old method is gone, which leaves - `article` an attribute reader like any other: it raises `NoMethodError` on a ticket that - has no article staged, and sends nothing. + `article` an attribute reader like any other: called the old way it raises `NoMethodError` + on a ticket that has no article staged and `ArgumentError`, naming `add_article`, on one + that has, and sends nothing either way. ### Added @@ -876,6 +877,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a attributes. A `query:` that is not a Hash raises `ArgumentError` the same way. - The debug log prints the query of a request as it is sent, like its headers and its body, so the line shows String keys and values: `query={"page" => "1"}`. +- An attribute reader called with arguments raises `ArgumentError`, as a reader written out + does. The arguments were never looked at, so `ticket.state('closed')` answered `"open"` + and changed nothing. On a ticket with an article staged, the call that added an article + in 1.x, `ticket.article(body: '…')`, answered with the staged article, sent nothing and + raised nothing; it now raises and names `add_article`. The message says where a value + for the attribute is written, on a record that takes writes. ### Changed diff --git a/README.md b/README.md index 77c9e99..5d9636b 100644 --- a/README.md +++ b/README.md @@ -1488,7 +1488,7 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | `record.unknown_attribute` → `nil` | raises `NoMethodError`; use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` | A typo read as `nil` and flowed on into whatever was written with it. Zammad also serves a reduced object where the user may not see the whole record, and that is worth being told about | | `client.x.new(id: 5)` | `client.x.find(5)` | The constructor was the one door that did not refuse a staged id — and the only one whose value reached Zammad, since a new record is sent in full | | `client.users.find(ticket.customer_id)` | `ticket.related.customer` | Following a foreign key needed the client threaded through | -| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | A noun that sends a `POST`, one letter away from `ticket.articles`, which only reads. The method is gone: `article` is an attribute reader like any other, and raises `NoMethodError` on a ticket that has no article staged | +| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | A noun that sends a `POST`, one letter away from `ticket.articles`, which only reads. The method is gone: `article` is an attribute reader like any other, and the old call raises `NoMethodError` on a ticket that has no article staged and `ArgumentError`, naming `add_article`, on one that has | ### Errors diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb index 22e82d7..80ea902 100644 --- a/lib/zammad_api/attribute_access.rb +++ b/lib/zammad_api/attribute_access.rb @@ -193,7 +193,20 @@ def method_missing(name, *args) identifier = name.to_s return super if NON_ATTRIBUTE_SUFFIXES.any? { identifier.end_with?(it) } return write_attribute(identifier.delete_suffix('=').to_sym, args.first) if ATTRIBUTE_WRITER.match?(identifier) - return attributes[name] if attributes.key?(name) + + if attributes.key?(name) + # A reader takes no arguments, and says so as one written out + # would. They were never looked at: `ticket.state('closed')` + # answered "open" and changed nothing, and the call 1.x added an + # article with, `ticket.article(body: '...')`, answered with the + # article already staged on a ticket that had one, sent nothing + # and raised nothing. Keywords arrive here as one Hash, so they + # count as one. A block is not asked about, as it is not for any + # method that does not use one. + raise ArgumentError, reader_arguments_message(name, args.size) if !args.empty? + + return attributes[name] + end # An attribute the record does not carry used to read as nil, which made # `ticket.titel` a silent nil that flowed on into whatever was written @@ -284,6 +297,24 @@ def unknown_attribute_message(name) 'attribute the record has in Zammad can still be missing here - check what this client may read.' end + # What a reader called with arguments raises with. + # + # It opens the way Ruby's own message for the mistake does, so that it + # reads as that mistake, and then says what Ruby cannot: that the name + # is an attribute, and where a value for it goes on a record that takes + # one. A record may add what it knows about a name: see + # {Resources::Ticket#reader_arguments_message}. + # + # @param name [Symbol] + # @param given [Integer] how many arguments the reader was called with + # @return [String] + def reader_arguments_message(name, given) + message = "wrong number of arguments (given #{given}, expected 0): #{name} reads the attribute of that name and takes no arguments." + return message if !writable_attributes? || !attribute_writable?(name) + + "#{message} To change it, write it with #{name} = ... or update(#{name}: ...)." + end + # Whether this record stages attribute writes, so that {#respond_to?} and # calling a writer agree. def writable_attributes? = false diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index c5e5991..168c5de 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -86,6 +86,21 @@ def add_article(attributes = {}) record.save! record end + + private + + # `ticket.article(body: '...')` is the call that added an article in + # 1.x. On a ticket with an article staged - one built with `article:` + # whose save was rejected, say - +article+ is an attribute it carries, + # and the call reaches the reader with an argument. Whoever wrote it + # meant {#add_article}, so the refusal names it. + # + # @see AttributeAccess#reader_arguments_message + def reader_arguments_message(name, given) + return super if name != :article + + "#{super} To add an article to this ticket, which is what article(...) did in 1.x, call add_article(...)." + end end end end diff --git a/sig/zammad_api/attribute_access.rbs b/sig/zammad_api/attribute_access.rbs index 0189c51..8432e07 100644 --- a/sig/zammad_api/attribute_access.rbs +++ b/sig/zammad_api/attribute_access.rbs @@ -30,6 +30,7 @@ module ZammadAPI # the other record in `==`, and of nobody else. def installation: () -> String? def unknown_attribute_message: (Symbol name) -> String + def reader_arguments_message: (Symbol name, Integer given) -> String def writable_attributes?: () -> bool def attribute_writable?: (Symbol key) -> bool def write_attribute: (Symbol, untyped) -> untyped diff --git a/spec/unit/zammad_api/attribute_access_spec.rb b/spec/unit/zammad_api/attribute_access_spec.rb index 28f2aea..5761921 100644 --- a/spec/unit/zammad_api/attribute_access_spec.rb +++ b/spec/unit/zammad_api/attribute_access_spec.rb @@ -80,6 +80,38 @@ def initialize(attributes) expect(record.id).to eq(1) end + # The arguments were never looked at, so `record.name('Other')` answered + # with the name and changed nothing, where a reader written out raises. + context 'when a reader is given arguments' do + it 'raises ArgumentError, as a reader written out would' do + expect { record.name('Other') }.to raise_error(ArgumentError, /\Awrong number of arguments \(given 1, expected 0\)/) + end + + it 'counts them' do + expect { record.name(1, 2, 3) }.to raise_error(ArgumentError, /given 3, expected 0/) + end + + it 'counts keywords as the one Hash they arrive as' do + expect { record.name(to: 'Other') }.to raise_error(ArgumentError, /given 1, expected 0/) + end + + it 'says what the reader reads' do + expect { record.name('Other') }.to raise_error(ArgumentError, /name reads the attribute of that name and takes no arguments/) + end + + it 'does not point a record that takes no writes at a writer' do + expect { record.name('Other') }.to raise_error(ArgumentError) { expect(it.message).not_to include('name =') } + end + + it 'still reads with a block, which any method takes' do + expect(record.name { 'ignored' }).to eq('Support') + end + + it 'still raises NoMethodError for an attribute the record does not carry' do + expect { record.custom_field('x') }.to raise_error(NoMethodError, /undefined attribute custom_field/) + end + end + # A reader used to answer nil here, which made a typo a silent nil that # flowed on into whatever was written with it - and put respond_to? and # the call itself at odds, since respond_to?(:custom_field) was false diff --git a/spec/unit/zammad_api/resources/ticket_spec.rb b/spec/unit/zammad_api/resources/ticket_spec.rb index 465ad21..a51b4bc 100644 --- a/spec/unit/zammad_api/resources/ticket_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -205,5 +205,31 @@ def posted_ticket_ids expect(ticket.article).to eq(body: 'reply') end + + # With an article staged the reader is there, and it never looked at + # its arguments: the call 1.x made answered with the staged article, + # sent nothing and raised nothing. + context 'when an article is staged and the call 1.x made is made' do + before { ticket.article = { body: 'draft' } } + + it 'raises ArgumentError rather than answering with the staged article' do + expect { ticket.article(body: 'reply') }.to raise_error(ArgumentError, /wrong number of arguments \(given 1, expected 0\)/) + end + + it 'names add_article' do + expect { ticket.article(body: 'reply') }.to raise_error(ArgumentError, /add_article\(\.\.\.\)/) + end + + it 'sends nothing' do + expect { ticket.article(body: 'reply') }.to raise_error(ArgumentError) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end + + it 'tells a reader given a value where the value is written' do + ticket.assign_attributes(state: 'open') + + expect { ticket.state('closed') }.to raise_error(ArgumentError, /write it with state = \.\.\. or update\(state: \.\.\.\)/) + end end end From ee735d6eace0d59871e2a3f02c82ac22b1b33e3a Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 12:28:11 +0200 Subject: [PATCH 018/121] fix: answer any? and none? with the request empty? makes `empty?` sizes its request to one record through `first`. `any?` and `none?` were Enumerable's, which starts the walk at the page size for walking and stops at the first record. So `client.tickets.all.any?` and `client.tickets.none?` asked for a page of 100 expanded tickets, and `client.tickets.search('x').any?` for 200 hits, to answer the question `empty?` answers with `per_page=1`. A collection defines both. Without a block or a pattern they answer from `empty?`, which is the same answer, a record being neither nil nor false. With either they are left to Enumerable and walk. A resource proxy forwards them to `all`, as it forwards `empty?`. --- CHANGELOG.md | 6 ++ README.md | 5 +- lib/zammad_api/collection.rb | 36 +++++++++++ lib/zammad_api/resource_proxy.rb | 13 +++- sig/zammad_api/collection.rbs | 4 ++ sig/zammad_api/resource_proxy.rbs | 4 ++ spec/unit/zammad_api/collection_spec.rb | 72 +++++++++++++++++++++ spec/unit/zammad_api/resource_proxy_spec.rb | 16 +++++ 8 files changed, 153 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7469840..e6378e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -883,6 +883,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a in 1.x, `ticket.article(body: '…')`, answered with the staged article, sent nothing and raised nothing; it now raises and names `add_article`. The message says where a value for the attribute is written, on a record that takes writes. +- `any?` and `none?` without a block ask for one record, as `empty?` does. They were + `Enumerable`'s, which starts a walk at the page size for walking and stops at the first + record: `client.tickets.all.any?` fetched a hundred expanded tickets, and + `client.tickets.search('x').any?` two hundred hits, to answer what `empty?` answers with a + page of one. A resource proxy forwards both. With a block or a pattern they walk, as + before. ### Changed diff --git a/README.md b/README.md index 5d9636b..362711f 100644 --- a/README.md +++ b/README.md @@ -1007,11 +1007,12 @@ client.tickets.search('state.name:open').count # one request client.tickets.all.count # one request per page ``` -`size` and `length` are `count`, and cost the same. `empty?` and `first` ask for a single -record rather than a page: +`size` and `length` are `count`, and cost the same. `empty?`, `any?`, `none?` and `first` +ask for a single record rather than a page: ```ruby client.tickets.search('state.name:merged').empty? # one request, for one record +client.tickets.search('state.name:new').any? # the same client.groups.all.size # => 12, having walked ``` diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb index caff818..329d72d 100644 --- a/lib/zammad_api/collection.rb +++ b/lib/zammad_api/collection.rb @@ -374,6 +374,42 @@ def count(*args, &block) # @return [Boolean] def empty? = first.nil? + # Whether this collection has a record. + # + # Without a block or a pattern it is {#empty?} asked the other way + # round, and costs what that costs. It was +Enumerable#any?+, which + # starts a walk at the page size for walking and stops at the first + # record, so +client.tickets.all.any?+ fetched a hundred expanded + # tickets, and two hundred hits on a search, to learn what one record + # says - the argument made above {#take}, that what a read costs should + # not depend on which word it was written with. A record is never nil + # or false, so the answer is the same. + # + # A block or a pattern asks about the records themselves, which is a + # walk, and is left to +Enumerable+. + # + # @example + # notify(agent) if client.tickets.search("owner.login:#{login} AND state.name:open").any? + # + # @yieldparam record [Resources::Base] + # @return [Boolean] + def any?(*pattern, &block) + return super if block || !pattern.empty? + + !empty? + end + + # Whether this collection has no record: {#empty?}, unless a block or a + # pattern is given. See {#any?}. + # + # @yieldparam record [Resources::Base] + # @return [Boolean] + def none?(*pattern, &block) + return super if block || !pattern.empty? + + empty? + end + def inspect "#<#{self.class.name} #{@resource_class.name} path=#{@path.inspect} per_page=#{@per_page}#{" page=#{@page}" if @page}#{' paginated=false' if !@paginated}>" end diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index 141e73d..2f461dc 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -367,6 +367,17 @@ def all # @return [Boolean] # @see Collection#empty? + # @!method any?(*pattern, &block) + # Overrides +Enumerable#any?+ so that, without a block or a pattern, it + # asks for one record rather than a page. + # @return [Boolean] + # @see Collection#any? + + # @!method none?(*pattern, &block) + # Overrides +Enumerable#none?+ the same way. + # @return [Boolean] + # @see Collection#none? + # @!method first(count = nil) # Overrides +Enumerable#first+ so that it reads one sized page rather # than taking records off the front of one sized for walking. @@ -379,7 +390,7 @@ def all # @return [Array] # @see Collection#take - def_delegators :all, :order, :each, :find_each, :in_batches, :page, :pluck, :count, :size, :length, :empty?, :first, :take + def_delegators :all, :order, :each, :find_each, :in_batches, :page, :pluck, :count, :size, :length, :empty?, :any?, :none?, :first, :take # @!endgroup diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs index 7830bbe..1eee7ea 100644 --- a/sig/zammad_api/collection.rbs +++ b/sig/zammad_api/collection.rbs @@ -57,6 +57,10 @@ module ZammadAPI def size: (*untyped) ?{ (R) -> boolish } -> Integer def length: (*untyped) ?{ (R) -> boolish } -> Integer def empty?: () -> bool + def any?: () -> bool + | ... + def none?: () -> bool + | ... def inspect: () -> String private diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs index a557bd9..a3502b2 100644 --- a/sig/zammad_api/resource_proxy.rbs +++ b/sig/zammad_api/resource_proxy.rbs @@ -38,6 +38,10 @@ module ZammadAPI def size: () -> Integer def length: () -> Integer def empty?: () -> bool + def any?: () -> bool + | ... + def none?: () -> bool + | ... def first: () -> R? | (Integer count) -> Array[R] def take: (Integer count) -> Array[R] diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb index f491e21..de0ffd2 100644 --- a/spec/unit/zammad_api/collection_spec.rb +++ b/spec/unit/zammad_api/collection_spec.rb @@ -796,6 +796,78 @@ def sorted_request(sort_by, order_by) end end + # The question #empty? asks, in the words more often typed. They were + # Enumerable's, which starts a walk at the page size for walking and stops + # at the first record: up to a full page of expanded records fetched to + # learn whether there is one. + describe '#any? and #none?' do + context 'with a record at the endpoint' do + before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) } + + it 'answers any? with true' do + expect(collection.any?).to be(true) + end + + it 'answers none? with false' do + expect(collection.none?).to be(false) + end + + it 'asks for a single record to answer any?' do + collection.any? + + expect(a_request(:get, url).with(query: hash_including('per_page' => '1'))).to have_been_made.once + expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once + end + + it 'asks for a single record to answer none?' do + collection.none? + + expect(a_request(:get, url).with(query: hash_including('per_page' => '1'))).to have_been_made.once + expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once + end + + it 'leaves the page size alone on a collection limited to one page' do + collection.page(2, per_page: 5).any? + + expect(a_request(:get, url).with(query: hash_including('page' => '2', 'per_page' => '5'))).to have_been_made + end + end + + context 'with no record at the endpoint' do + before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) } + + it 'answers any? with false' do + expect(collection.any?).to be(false) + end + + it 'answers none? with true' do + expect(collection.none?).to be(true) + end + end + + # A block or a pattern asks about the records, and that is a walk. + context 'with a block or a pattern' do + before do + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + stub_page(2, []) + end + + it 'leaves any? with a block to Enumerable' do + expect(collection.any? { it.name == 'Support' }).to be(true) + expect(collection.any? { it.name == 'Sales' }).to be(false) + end + + it 'leaves none? with a block to Enumerable' do + expect(collection.none? { it.name == 'Sales' }).to be(true) + end + + it 'leaves a pattern to Enumerable' do + expect(collection.any?(ZammadAPI::Resources::Group)).to be(true) + expect(collection.none?(ZammadAPI::Resources::Group)).to be(false) + end + end + end + # `take(n)` and `first(n)` ask one question. Enumerable answers both by # taking records off the front of a page sized for walking, so with #first # sizing its own page and this one left alone, what the same read cost diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 0440b3f..26f8dc5 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -704,6 +704,22 @@ def stub_last_page(page, records, per_page: default_per_page) expect(proxy).to be_empty end + # A proxy is Enumerable, so it had Enumerable's own, which read a page + # sized for walking to answer what one record answers. + it 'forwards #any? and #none?, which ask for a single record' do + stub_page(1, [{ id: 1, name: 'Users' }], per_page: 1) + + expect(proxy.any?).to be(true) + expect(proxy.none?).to be(false) + expect(a_request(:get, url).with(query: hash_including('per_page' => '1'))).to have_been_made.twice + end + + it 'forwards the block of #any? as well' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }]), json_response([])) + + expect(proxy.any? { it.name == 'Users' }).to be(true) + end + it 'keeps #find as a lookup by id rather than Enumerable#find' do stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) From 3bfe28e8f5995af2463049bea9cde62528d9638d Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 12:30:01 +0200 Subject: [PATCH 019/121] fix: keep an adapter the middleware callable sets `build_connection` set the adapter after the `middleware:` callable had run, and Faraday's `adapter` replaces the one that is there. So `middleware: ->(f) { f.adapter :test, stubs }` built a connection on Net::HTTP and raised nothing: a test that put the test adapter in that way believed itself stubbed and sent real requests with the real token. The callable is also the only place an adapter can be given arguments, `f.adapter :net_http_persistent, pool_size: 5`, because `adapter:` takes a name. An adapter the callable set is kept. Faraday puts its default in before the block runs and builds a new handler for each `adapter` call, so the handler is compared by identity before and after the callable, which also sees the default named again with a block. Where the callable set none, the `adapter:` option or the default goes in as before. An adapter named in the callable and in `adapter:` as well raises ConfigurationError when the connection is built. One of the two would be dropped, and nothing in either spelling says which. --- CHANGELOG.md | 7 ++++ README.md | 14 ++++++++ lib/zammad_api/config.rb | 6 ++-- lib/zammad_api/transport.rb | 35 +++++++++++++++++-- sig/zammad_api/transport.rbs | 1 + spec/unit/zammad_api/transport_spec.rb | 47 ++++++++++++++++++++++++++ 6 files changed, 106 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6378e6..37e09fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -889,6 +889,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `client.tickets.search('x').any?` two hundred hits, to answer what `empty?` answers with a page of one. A resource proxy forwards both. With a block or a pattern they walk, as before. +- An adapter set inside the `middleware:` callable is kept. The adapter was set after the + callable ran, which replaces the one that is there, so + `middleware: ->(f) { f.adapter :test, stubs }` left the connection on Net::HTTP without a + word: a test that believed itself stubbed sent real requests with the real token. The + callable is also the only place an adapter can be given arguments, such as + `f.adapter :net_http_persistent, pool_size: 5`. Naming an adapter there and in `adapter:` + as well raises `ConfigurationError`. ### Changed diff --git a/README.md b/README.md index 362711f..90d1869 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,20 @@ requests as the client finished building them and responses before anything else Faraday stays an implementation detail either way: an unregistered adapter raises `ZammadAPI::ConfigurationError`, not a Faraday error. +`adapter:` takes a name. An adapter that needs arguments is set inside the callable +instead, and is the one the client then uses: + +```ruby +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'token', + middleware: ->(connection) { connection.adapter :net_http_persistent, pool_size: 5 } +) +``` + +Naming an adapter both ways raises `ZammadAPI::ConfigurationError`, since one of the two +would be dropped. + Faraday's default adapter, `net_http`, opens and closes a connection around every request, so a walk of N pages is N TCP connections and N TLS handshakes. That is the default because it needs no extra gem; for anything that pages, downloads attachments in a diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index bfba645..22e0c4c 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -43,10 +43,12 @@ module ZammadAPI # @return [String, nil] proxy URL # @!attribute [r] adapter # @return [Symbol, nil] name of the Faraday adapter, +nil+ for Faraday's - # default + # default or for one the +middleware+ callable sets # @!attribute [r] middleware # @return [Proc, nil] called with the Faraday connection while it is - # being built + # being built. An adapter it sets is the one used, which is how an + # adapter is given arguments; one named in +adapter+ as well is + # refused when the connection is built # @!attribute [r] logger # @return [Logger] where debug output goes Config = Data.define( diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 20f52e2..edfff4b 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1008,8 +1008,7 @@ def build_connection faraday.request :retry, Transport.retry_options(config) # Last in the stack, so a caller's middleware sees the request as this # gem finished building it and the response before anything else does. - config.middleware&.call(faraday) - faraday.adapter(config.adapter || Faraday.default_adapter) + apply_middleware_and_adapter(faraday) end refuse_unusable_middleware!(connection) @@ -1032,6 +1031,38 @@ def build_connection raise ConfigurationError, "config could not be used to build a connection: #{e.class}: #{redact_config_values(e.message)}", cause: reportable_cause(e) end + # Runs the caller's `middleware:` callable, and then settles the adapter. + # + # The adapter used to be set after the callable, unconditionally, and + # setting one replaces the one that is there. So an adapter the callable + # chose was dropped without a word: `middleware: ->(f) { f.adapter + # :test, stubs }` left the connection on Net::HTTP, and a test that + # believed itself stubbed sent real requests with the real token. The + # callable is also the one place an adapter can be given arguments - + # `f.adapter :net_http_persistent, pool_size: 5` - since `adapter:` + # takes a name. + # + # An adapter the callable set is kept. Whether it set one is asked of + # the handler's identity: Faraday puts its default in before the block + # runs and builds a new handler for every `adapter` call, so one that + # names the default again, to hand it a block, is seen as well. + # + # Named in both places, it is refused. One of the two would be dropped, + # and which one is not something either spelling says. + def apply_middleware_and_adapter(faraday) + preset = faraday.builder.adapter + config.middleware&.call(faraday) + chosen = faraday.builder.adapter + + return faraday.adapter(config.adapter || Faraday.default_adapter) if chosen.equal?(preset) + return if config.adapter.nil? + + raise ConfigurationError, + "config adapter is #{config.adapter.inspect}, and the `middleware:` callable set an adapter as well (#{chosen.name}): " \ + 'a connection has one adapter. Drop the `adapter:` option to use the one the callable sets, with the arguments ' \ + 'it gives it, or drop the call from the callable.' + end + # The error to keep as the cause of the ConfigurationError above, where # it can be kept. # diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index a34b5d9..8fdb039 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -78,6 +78,7 @@ module ZammadAPI def timed_out?: (untyped error) -> bool def perform: (Symbol, String, Hash[Symbol, untyped]?, String?, Hash[untyped, untyped]?) -> untyped def build_connection: () -> untyped + def apply_middleware_and_adapter: (untyped faraday) -> void def refuse_unusable_middleware!: (untyped connection) -> void def refused_middleware: (Class klass) -> String? def refused_middleware_message: (Class klass, String refused) -> String diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index de1404e..dd0704e 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1138,6 +1138,53 @@ def on_complete(env) = env.body = { id: 1 } expect(transport.instance_variable_get(:@connection).adapter.name).to include('Adapter::Test') end + # The adapter was set after the callable ran, and setting one replaces + # the one that is there. A test that put the test adapter in through + # the callable was on Net::HTTP, with nothing to say so. + context 'with an adapter chosen inside the middleware callable' do + let(:stubs) { Faraday::Adapter::Test::Stubs.new { it.get('/api/v1/groups') { [200, { 'Content-Type' => 'application/json' }, '[{"id":7}]'] } } } + + it 'keeps it' do + transport = unit_transport(middleware: ->(faraday) { faraday.adapter :test, stubs }) + + expect(transport.instance_variable_get(:@connection).adapter.name).to include('Adapter::Test') + end + + it 'sends requests through it, with the arguments it was given' do + transport = unit_transport(middleware: ->(faraday) { faraday.adapter :test, stubs }) + + expect(transport.get('api/v1/groups', operation: 'test').body).to eq([{ id: 7 }]) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'keeps it where it is the default adapter, named again to give it a block' do + configured = nil + transport = unit_transport(middleware: ->(faraday) { faraday.adapter(Faraday.default_adapter) { configured = true } }) + stub_request(:get, url).to_return(json_response([])) + transport.get('api/v1/groups', operation: 'test') + + expect(configured).to be(true) + end + + it 'still puts the default adapter in where the callable chose none' do + transport = unit_transport(middleware: ->(faraday) { faraday.use(Class.new(Faraday::Middleware)) }) + + expect(transport.instance_variable_get(:@connection).adapter.name).to eq(Faraday::Adapter.lookup_middleware(Faraday.default_adapter).name) + end + + # Two answers to one question, and whichever was kept the other was + # dropped without a word. + it 'refuses one named in the adapter option as well' do + expect { unit_transport(adapter: :net_http, middleware: ->(faraday) { faraday.adapter :test, stubs }) } + .to raise_error(ZammadAPI::ConfigurationError, /config adapter is :net_http, and the `middleware:` callable set an adapter as well \(Faraday::Adapter::Test\)/) + end + + it 'refuses the pair even where both name the same adapter' do + expect { unit_transport(adapter: :test, middleware: ->(faraday) { faraday.adapter :test, stubs }) } + .to raise_error(ZammadAPI::ConfigurationError, /set an adapter as well/) + end + end + it 'reports an unregistered adapter as a configuration error' do expect { unit_transport(adapter: :nonsense) } .to raise_error(ZammadAPI::ConfigurationError, /is not registered on Faraday::Adapter/) From 7ae5ba51a844a49a4aea3ba6a47099df45a31d95 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 13:45:44 +0200 Subject: [PATCH 020/121] test: read resources by their plural names in the live specs b6a68f7 removed the singular resource readers, and the integration spec for invalid credentials still called four of them through `public_send`. `client.organization` raises UnknownResourceError now, so "raises for organization", "group", "ticket_priority" and "ticket_state" failed where they expect AuthenticationError, and the live job of the CI run for b6a68f7 ended red with 4 of 53 failing. The unit specs do not load this file, which is why `rake` passed. --- spec/integration/authentication_spec.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/integration/authentication_spec.rb b/spec/integration/authentication_spec.rb index 79a8380..7b0da48 100644 --- a/spec/integration/authentication_spec.rb +++ b/spec/integration/authentication_spec.rb @@ -20,7 +20,7 @@ expect { client.users.find(1) }.to raise_error(ZammadAPI::ClientError) end - %i[organization group ticket_priority ticket_state].each do |resource| + %i[organizations groups ticket_priorities ticket_states].each do |resource| it "raises for #{resource}" do expect { client.public_send(resource).find(1) }.to raise_error(ZammadAPI::AuthenticationError) end From 5187ada4f232d9c5910097f0417fdf7fe343e04e Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 18:08:04 +0200 Subject: [PATCH 021/121] fix: find a line break beside bytes invalid in the encoding `Transport.line_break?` stripped the value before it looked, and `strip` raises Encoding::CompatibilityError for text that holds a byte sequence its encoding does not allow. The `rescue EncodingError` written for the UTF-16 conversion above it answered false for that too. So `http_token: "abc\xFF\ndef"` built a client, and a raw request took the same in `headers:`. Net::HTTP raised its own error at the request, past `rescue ZammadAPI::Error`, and an adapter that checks no header itself sent what followed the break as a header of its own: Faraday's test adapter received it. The bytes are read now. A line break is the same byte in every encoding ASCII is a part of, and binary text has no sequence that is not allowed. One at the end is still taken, as Net::HTTP strips it. The conversion is `wire_text`'s, which the two callers in Transport had been through already. Config goes through it as well, so `http_token`, `oauth2_token` or `user_agent` given as UTF-16 text that cannot be converted raises ConfigurationError where it was passed as holding no line break. The EncodingError underneath quotes the bytes it stopped at and is not kept as the cause. --- CHANGELOG.md | 7 ++++++ lib/zammad_api/config.rb | 13 ++++++++++- lib/zammad_api/transport.rb | 17 +++++++++------ sig/zammad_api/config.rbs | 1 + spec/unit/zammad_api/config_spec.rb | 30 ++++++++++++++++++++++++++ spec/unit/zammad_api/transport_spec.rb | 9 ++++++++ 6 files changed, 70 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37e09fb..f79634f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -896,6 +896,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a callable is also the only place an adapter can be given arguments, such as `f.adapter :net_http_persistent, pool_size: 5`. Naming an adapter there and in `adapter:` as well raises `ConfigurationError`. +- A line break in a header value is refused beside bytes that are invalid in the value's + encoding too. The check stripped the value first, which raises for such text, and read + the error as no line break: `http_token: "abc\xFF\ndef"` built a client, a raw request + took the same in `headers:`, and an adapter that checks no header itself sent what + followed the break as a header of its own. The bytes are read now. `http_token`, + `oauth2_token` or `user_agent` given as UTF-16 text that cannot be converted raises + `ConfigurationError`; it was passed as holding no line break. ### Changed diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 22e0c4c..1567f2f 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -437,12 +437,23 @@ def validate_user_agent! def validate_header_options! HEADER_OPTIONS.each do |name| value = public_send(name) - next if !value.is_a?(String) || !Transport.line_break?(value) + next if !value.is_a?(String) || !Transport.line_break?(header_text(name, value)) raise ConfigurationError, "config #{name} holds a line break, which a header cannot carry: #{Transport::LINE_BREAK_ADVICE}" end end + # The option as text whose bytes are the ones a header carries: see + # {Transport.wire_text}. Text that cannot be converted cannot be shown + # to hold no line break, and was passed as holding none. Refused + # without the error underneath as its cause, which quotes the bytes it + # stopped at. + def header_text(name, value) + Transport.wire_text(value, "config #{name}") + rescue ArgumentError => e + raise ConfigurationError, e.message, cause: nil + end + # A proxy is the second string here that may carry credentials, and the # only other one rendered rather than replaced wholesale. Unchecked, a # URI - what `URI(...)` hands back, and what prints as the URL - was diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index edfff4b..73c8f57 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -415,15 +415,20 @@ def self.stringify_header_value(name, value) # break at either end is stripped there, so a token read from a file # with its newline still on works, and is still taken. # + # Asked of the bytes. +strip+ raises for text that holds a byte sequence + # its encoding does not allow, and that error was read here as "no line + # break": `http_token: "abc\xFF\ndef"` was taken, and an adapter that + # does not check a header itself sent what follows the break as a header + # of its own. A line break is the same byte in every encoding ASCII is a + # part of, and binary text has no sequence that is not allowed. + # + # Asked of a String {.wire_text} has had, as {BLANK} is: the bytes of + # UTF-16 are not the bytes a request carries. + # # @api private # @param text [String] # @return [Boolean] - def self.line_break?(text) - text = text.encode(Encoding::UTF_8) if !text.encoding.ascii_compatible? - /[\r\n]/.match?(text.strip) - rescue EncodingError - false - end + def self.line_break?(text) = /[\r\n]/.match?(text.b.strip) # The +From+ scope as a transport holds it: text, and a copy of its own. # diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index 1306364..1f2c234 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -83,6 +83,7 @@ module ZammadAPI def validate_user_agent!: () -> void HEADER_OPTIONS: Array[Symbol] def validate_header_options!: () -> void + def header_text: (Symbol name, String value) -> String def validate_ssl_verify!: () -> void def validate_middleware!: () -> void def validate_logger!: () -> void diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index cb0b846..128cf64 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -210,12 +210,42 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) end end + # `strip` raises for text holding a byte sequence that is invalid in its + # encoding, and the error was read as "no line break": the token was + # taken, and an adapter that checks nothing sent the second line. + it 'refuses one beside a byte sequence that is invalid in the encoding' do + expect { build(http_token: "secret-abc\xFF\nX-Injected: secret-def") }.to raise_error(ZammadAPI::ConfigurationError) { |error| + expect(error.message).to start_with('config http_token holds a line break, which a header cannot carry') + expect(error.message).not_to include('secret-def') + } + end + + it 'refuses one in a token given as binary text' do + expect { build(http_token: "secret-abc\xFF\nsecret-def".b) } + .to raise_error(ZammadAPI::ConfigurationError, /\Aconfig http_token holds a line break/) + end + + # It cannot be shown to hold no line break, and was passed as holding + # none. + it 'refuses UTF-16 text that cannot be converted, without quoting it or the error underneath' do + broken = "secret-abc\nsecret-def".encode('UTF-16LE').b[0..-2].force_encoding('UTF-16LE') + + expect { build(user_agent: broken) }.to raise_error(ZammadAPI::ConfigurationError) { |error| + expect(error.message).to start_with('config user_agent was given as UTF-16LE text that cannot be converted to UTF-8') + expect(error.cause).to be_nil + } + end + # Net::HTTP strips it, so a token read from a file with its newline on # worked, and still does. it 'takes a token that only ends in one' do expect(build(http_token: "secret\n").http_token).to eq("secret\n") end + it 'takes a token that only ends in one after bytes that are invalid in the encoding' do + expect(build(http_token: "secret\xFF\n").http_token).to eq("secret\xFF\n") + end + it 'does not check a password, which basic authentication encodes' do expect(build(http_token: nil, user: 'agent', password: "pass\nword").password).to eq("pass\nword") end diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index dd0704e..40a6c45 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -54,6 +54,15 @@ } end + # The check stripped the value first, which raises for such text, and + # read the error as "no line break". + it 'refuses a line break beside a byte sequence that is invalid in the encoding' do + expect { described_class.stringify_headers('Accept-Language' => "de\xFF\nX-Injected: secret") } + .to raise_error(ArgumentError, /\Aheader accept-language holds a line break, which a header cannot carry/) { |error| + expect(error.message).not_to include('secret') + } + end + it 'takes one that only ends in a line break, which Net::HTTP strips' do expect(described_class.stringify_headers('X-Note' => "abc\n")).to eq('x-note' => "abc\n") end From 6c46f3d71d3fc26316ff1906f5b6d63388fb58d8 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 18:09:05 +0200 Subject: [PATCH 022/121] fix: redact the credentials Zammad filters from its own log `SENSITIVE_KEY_PATTERN` had no word for `bind_pw`, the password an LDAP source binds with, or for `passphrase`, a PGP key's. With a logger set, `client.post('api/v1/ldap_sources', body: {preferences: {bind_user: ..., bind_pw: ...}})` logged the password, a PGP key import logged the passphrase beside a redacted `key`, and a record of an LDAP source printed the password from `inspect`. Its `key` rule asks for a separator in front of the word and missed `privateKey`. Zammad filters all of these from its own log, in config/initializers/filter_parameter_logging.rb. The pattern takes `bind_pw`, `passphrase`, `otp` and `salt` from that list. `otp` and `salt` are matched as words, as `key` is, so `footprint` and `basalt` stay readable, and `totp` and `hotp` count as `otp`. A capital K after a lower-case letter or a digit begins `key` as well, which covers `privateKey` and `sshKeys` and leaves `hotKeyboard` alone. The same pattern reads the names of a query string written into a request path, so those are covered with it. --- CHANGELOG.md | 6 ++++++ lib/zammad_api/transport.rb | 21 +++++++++++++++++- spec/unit/zammad_api/transport_spec.rb | 30 ++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f79634f..177ebd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -903,6 +903,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a followed the break as a header of its own. The bytes are read now. `http_token`, `oauth2_token` or `user_agent` given as UTF-16 text that cannot be converted raises `ConfigurationError`; it was passed as holding no line break. +- The debug log and a record's `inspect` redact `bind_pw`, `passphrase`, `otp` and `salt`, + and a `key` spelled in camelCase such as `privateKey`. Zammad filters all of them from + its own log, and none matched here: creating an LDAP source logged the bind password + inside its `preferences`, importing a PGP key logged its passphrase beside the redacted + key, and a record of an LDAP source printed the password. `otp` and `salt` are matched + as words, as `key` is, with `totp` and `hotp` counted in. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 73c8f57..478934c 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -143,7 +143,26 @@ module Verbs # `Proxy-Authorization` went the same way. `Authorization` itself never # gets this far - {RESERVED_HEADERS} refuses it - but every header named # after it carries what it carries. - SENSITIVE_KEY_PATTERN = /password|passwd|pwd|token|secret|credential|cookie|authorization|api_?key|(? 's3cret' })).to eq({ name => '[REDACTED]' }) + end + end + + # Matched as words, so that a key merely containing the letters stays + # readable. + %w[footprint basalt hotKeyboard Keyboard monkey_id bind_user].each do |name| + it "leaves #{name} alone" do + expect(described_class.redact({ name => 'shown' })).to eq({ name => 'shown' }) + end + end + + it 'redacts a bind password inside the preferences of an LDAP source' do + expect(described_class.redact({ name: 'x', preferences: { bind_user: 'cn=admin', bind_pw: 'hunter2' } })) + .to eq({ name: 'x', preferences: { bind_user: 'cn=admin', bind_pw: '[REDACTED]' } }) + end + + it 'redacts them where they are written into a request path' do + expect(described_class.redact_path('api/v1/x?passphrase=opensesame&privateKey=abc&page=2')) + .to eq('api/v1/x?passphrase=[REDACTED]&privateKey=[REDACTED]&page=2') + end + end + # A body handed over as a String is the caller's own encoding. Redaction # goes by key and found none in a String, so the payload line printed it # as it stood. From 035f454c7777d2ece420e3c48d03a0a88b3b358a Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 18:10:31 +0200 Subject: [PATCH 023/121] fix: carry a derived config in the test kit's transport `Test::Transport#with_config` returned self, and `Test#answer` read the retry count from the stand-in's own configuration. A client derived with `Client#with` from the test kit's client reported the derived option in `client.config` and nothing else followed it: zammad.stub(:get, 'api/v1/groups/1', status: 503) zammad.client.with(retries: 0).groups.find(1) recorded three requests where a derived client sends one on the wire. `with(timeout:)` did not change which Retry-After ends the attempts, and a record found through `with(url:)` named the stand-in's URL as its installation, so it compared equal to the same id found through the client it was derived from. The transport holds a configuration of its own, the stand-in's unless `with_config` handed it another, and keeps it under an on_behalf_of scope. It passes it to `answer`, which reads the retry count and the timeout from it. The same stand-in still answers every client, and records their requests in one list. --- CHANGELOG.md | 6 ++++ README.md | 3 +- lib/zammad_api/test.rb | 40 +++++++++++++++++--------- sig/zammad_api/test.rbs | 7 +++-- spec/unit/zammad_api/test_spec.rb | 48 +++++++++++++++++++++++++++++++ 5 files changed, 87 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 177ebd4..a4ecefd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -909,6 +909,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a inside its `preferences`, importing a PGP key logged its passphrase beside the redacted key, and a record of an LDAP source printed the password. `otp` and `salt` are matched as words, as `key` is, with `totp` and `hotp` counted in. +- A client derived with `Client#with` from the test kit's client behaves as it is + configured. The stand-in's transport kept its own configuration, so + `zammad.client.with(retries: 0)` was asked three times for a stubbed 503 where a derived + client is asked once on the wire, `with(timeout:)` did not change which `Retry-After` + ends the attempts, and a record found through `with(url:)` compared equal to the same id + found through the client it was derived from. Only `client.config` showed the option. ### Changed diff --git a/README.md b/README.md index 90d1869..cfd416a 100644 --- a/README.md +++ b/README.md @@ -1253,7 +1253,8 @@ zammad.requests.size # => 2 A single failing stub answers every attempt, so the error is raised once the retries are spent, with three requests recorded under the default of two retries. There is no wait between attempts. A `Retry-After` longer than `timeout` ends them at once, as it does -against Zammad. `ZammadAPI::Test.new(retries: 0)` raises for the first failure. +against Zammad. `ZammadAPI::Test.new(retries: 0)` raises for the first failure, and so +does a client derived with `zammad.client.with(retries: 0)`. A request that was not stubbed raises `ZammadAPI::Test::UnstubbedRequestError`, listing what is stubbed, rather than answering with something empty. It is deliberately not a diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index 92ef189..80715b4 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -237,15 +237,22 @@ def inspect = @monitor.synchronize { "#<#{self.class.name} stubbed=#{@stubs.size # real transport's own rule, so a +Retry-After+ longer than the timeout # ends the attempts here as it does there. # - # The count is this stand-in's, read from the options it was built - # with: `ZammadAPI::Test.new(retries: 0)` raises for the first failure. + # The count is the client's that sent the request, which is this + # stand-in's own unless the client was derived with {Client#with}: + # `ZammadAPI::Test.new(retries: 0)` raises for the first failure, and + # so does `zammad.client.with(retries: 0)`. It used to be read from the + # stand-in whichever client asked, so the derived one was asked three + # times here where the wire is asked once. The +timeout+ a + # +Retry-After+ is held against is read the same way. # # @api private + # @param config [Config] the configuration of the client that sent the + # request # @return [Response] # @raise [ResponseError] for a stubbed non-2xx status, once the retries # it is due are spent # @raise [UnstubbedRequestError] when no stub matches - def answer(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil, on_behalf_of: nil) + def answer(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil, on_behalf_of: nil, config: self.config) relative = ::ZammadAPI::Transport.relative_path(path) # Through the real transport's own stringification, so that {Request#query} # and {Request#headers} hold what a request would have carried rather @@ -534,31 +541,37 @@ def unmatched_query_message(request, params, scopes) end # Routes the client's requests to {Test#answer}, and carries the - # +on_behalf_of+ scope the way the real transport does. + # +on_behalf_of+ scope and the configuration the way the real transport + # does. # # @api private class Transport include ::ZammadAPI::Transport::Verbs - attr_reader :test, :on_behalf_of + attr_reader :test, :config, :on_behalf_of # The scope is stringified, copied and checked by the real transport's # own rule, so that a recorded scope is what a request would have # carried. Here rather than in {#with_on_behalf_of} alone, which left # one built directly holding whatever it was given. - def initialize(test, on_behalf_of: nil) + def initialize(test, on_behalf_of: nil, config: test.config) @test = test + @config = config @on_behalf_of = ::ZammadAPI::Transport.stringify_on_behalf_of(on_behalf_of) end - def config = test.config - - def with_on_behalf_of(identifier) = self.class.new(test, on_behalf_of: identifier) + def with_on_behalf_of(identifier) = self.class.new(test, on_behalf_of: identifier, config: config) # {Client#with} re-validates the options and hands them here. There is - # no connection to rebuild, and the derived client reports the derived - # config itself, so the stand-in keeps answering. - def with_config(_config) = self + # no connection to rebuild, and the same stand-in keeps answering, but + # the configuration is the transport's to carry as well as the + # client's. This returned self, and everything read from the transport + # stayed the stand-in's own: `client.with(retries: 0)` was asked as + # often as the stand-in retries, and a record found through + # `client.with(url:)` named the stand-in's URL as its installation, so + # it compared equal to the same id found through the client it was + # derived from. + def with_config(config) = self.class.new(test, on_behalf_of: on_behalf_of, config: config) def request(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) test.answer( @@ -569,7 +582,8 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou body: body, headers: headers, resource_class: resource_class, - on_behalf_of: on_behalf_of + on_behalf_of: on_behalf_of, + config: config ) end end diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs index 9215855..2925e20 100644 --- a/sig/zammad_api/test.rbs +++ b/sig/zammad_api/test.rbs @@ -46,7 +46,8 @@ module ZammadAPI ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?, - ?on_behalf_of: String? + ?on_behalf_of: String?, + ?config: Config ) -> Response private @@ -71,10 +72,10 @@ module ZammadAPI include ::ZammadAPI::Transport::Verbs attr_reader test: Test + attr_reader config: Config attr_reader on_behalf_of: String? - def initialize: (Test test, ?on_behalf_of: (String | Integer)?) -> void - def config: () -> Config + def initialize: (Test test, ?on_behalf_of: (String | Integer)?, ?config: Config) -> void def with_on_behalf_of: ((String | Integer)? identifier) -> Test::Transport def with_config: (Config) -> Test::Transport diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index a3abf84..e856847 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -71,6 +71,54 @@ expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') end + + # The stand-in's transport answered `with_config` with itself, so what + # is read from the transport stayed the stand-in's own: the derived + # client reported the option and went on as if it had not been given. + it 'retries as often as the derived client is told to' do + zammad.stub(:get, 'api/v1/groups/1', status: 503) + + expect { zammad.client.with(retries: 0).groups.find(1) }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(1) + end + + it 'leaves the retries of the client it was derived from as they were' do + zammad.stub(:get, 'api/v1/groups/1', status: 503) + zammad.client.with(retries: 0) + + expect { zammad.client.groups.find(1) }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(1 + zammad.config.retries) + end + + it 'holds a Retry-After against the derived timeout' do + zammad.stub(:get, 'api/v1/groups/1', status: 429, headers: { 'Retry-After' => '30' }) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + + expect { zammad.client.with(timeout: 5).groups.find(1) }.to raise_error(ZammadAPI::RateLimitError) + expect(zammad.requests.size).to eq(1) + end + + it 'keeps the derived options under an on_behalf_of scope taken afterwards' do + zammad.stub(:get, 'api/v1/groups/1', status: 503) + + expect { zammad.client.with(retries: 0).on_behalf_of('agent@example.com').groups.find(1) }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(1) + end + + # A record names its installation by the URL of its transport. + it 'tells a record found through another URL from one of its own' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + + expect(zammad.client.with(url: 'https://other.test/').groups.find(1)).not_to eq(zammad.client.groups.find(1)) + end + + it 'still takes two records found through the same derived client as one' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + derived = zammad.client.with(timeout: 5) + found = derived.groups.find(1) + + expect(derived.groups.find(1)).to eq(found) + end end end From 054dbe3fe919688e6c99162dccc7c2375b6d516b Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 18:13:16 +0200 Subject: [PATCH 024/121] fix: refuse a request path that opens with a scheme `Transport.relative_path` refused a path as an absolute URL only where `://` followed the scheme, so `client.get('http:/collect')` passed as relative. What happens to it then depends on the Faraday installed. 2.9.0 and 2.9.1, which `~> 2.9` allows, escape the colon of an opaque URL only and otherwise join the path to the instance URL as URI does: URI('https://zammad.example.com/') + 'http:/collect' # => #, host nil The request leaves for that URL in plain HTTP with the Authorization header and any From scope attached. 2.9.2 puts `./` in front of such a path and keeps it on the instance. Both were read from the gem sources; the request itself was not run under 2.9.0. `ABSOLUTE_URL` matches the scheme alone now. A colon in the first segment is the one thing RFC 3986 does not let a relative path have, so no path relative to the instance matches, and one with a colon further in, or a URL in its query string, is taken as before. The test kit applies the same rule through `relative_path`. --- CHANGELOG.md | 6 ++++++ README.md | 11 ++++++----- lib/zammad_api/transport.rb | 30 ++++++++++++++++++++++------- spec/unit/zammad_api/client_spec.rb | 25 ++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a4ecefd..7054df0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -915,6 +915,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a client is asked once on the wire, `with(timeout:)` did not change which `Retry-After` ends the attempts, and a record found through `with(url:)` compared equal to the same id found through the client it was derived from. Only `client.config` showed the option. +- A raw request refuses any path that opens with a scheme, not only one followed by `://`. + `client.get('http:/collect')` passed as a relative path, and Faraday 2.9.0 and 2.9.1, + which the gemspec allows, resolve it as URI does: to an absolute URL with no host, where + the request then goes over plain HTTP with the client's `Authorization` header and any + `on_behalf_of` scope. Faraday from 2.9.2 on keeps such a path on the instance; the + refusal no longer depends on which is installed. ### Changed diff --git a/README.md b/README.md index cfd416a..85cfa60 100644 --- a/README.md +++ b/README.md @@ -392,11 +392,12 @@ endpoint, and `full=true` on the index endpoints that render through Paths are relative to the instance URL, and a leading slash is ignored, so they can be pasted straight from the Zammad documentation. An absolute URL raises `ArgumentError`: the client's credentials only ever go to the instance it was configured for, so a link taken -from a response body has to be reduced to its path first. A path is written the way a URL -is, so a space or a character outside ASCII has to be percent-encoded, `t%C3%A4gs` for -`tägs`; one that cannot be read as a URL raises `ArgumentError` too, before anything is -sent or logged. A non-2xx response raises the same error class it would raise for a -modelled resource, and only a `GET` is retried. +from a response body has to be reduced to its path first. Any path that opens with a +scheme counts as one, `http:/collect` as much as `https://other.example/collect`. A path +is written the way a URL is, so a space or a character outside ASCII has to be +percent-encoded, `t%C3%A4gs` for `tägs`; one that cannot be read as a URL raises +`ArgumentError` too, before anything is sent or logged. A non-2xx response raises the same +error class it would raise for a modelled resource, and only a `GET` is retried. ## Working with records diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 478934c..67e03f5 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -181,11 +181,24 @@ module Verbs # names a record. RECORD_ID_TYPES = [Integer, String, Symbol].freeze - # A request path that carries a scheme and an authority, and so names a - # host of its own. Any scheme and either case, which is wider than the - # two lowercase prefixes Faraday itself treats as absolute: what is - # refused here should not depend on how one Faraday version reads a URL. - ABSOLUTE_URL = %r{\A[a-z][a-z0-9+.-]*://}i + # A request path that opens with a scheme, which is what makes a URL an + # absolute one, whatever follows. Any scheme and either case, which is + # wider than the two lowercase prefixes Faraday itself treats as + # absolute: what is refused here should not depend on how one Faraday + # version reads a URL. + # + # It did. This asked for `://` after the scheme, so `http:/collect` + # passed as a relative path, and Faraday 2.9.0 and 2.9.1, which the + # gemspec allows, join a path to the instance URL the way URI does: the + # result is `http:/collect`, an absolute URL with no host, and the + # request leaves for it over plain HTTP with this client's headers + # attached. Faraday keeps such a path relative from 2.9.2 on, with a + # `./` in front of it. + # + # A path relative to the instance never matches. A colon in the first + # segment is the one thing RFC 3986 does not let a relative path have, + # for this reason, and every path Zammad serves opens with `api/`. + ABSOLUTE_URL = /\A[a-z][a-z0-9+.-]*:/i # @return [Config] attr_reader :config @@ -604,6 +617,8 @@ def self.not_a_record_id_message(value) # to that host. Record ids are held inside their segment by # {.escape_path_segment}; this is the same escape, one level up. The # message does not quote the path, which may carry a secret of its own. + # What counts as absolute is {ABSOLUTE_URL}: a path that opens with a + # scheme, with or without a host after it. # # Public for the same reason as {.stringify_query} and # {.escape_path_segment}: {Client} and {Test} both apply this rule, the @@ -630,8 +645,9 @@ def self.not_a_record_id_message(value) def self.relative_path(path) relative = path.to_s.sub(%r{\A/+}, '') if ABSOLUTE_URL.match?(relative) - raise ArgumentError, 'a request path is relative to the instance URL, and this one is an absolute URL: sending it would hand ' \ - "this client's credentials to another host. Pass the path alone, such as 'api/v1/tickets'." + raise ArgumentError, 'a request path is relative to the instance URL, and this one opens with a scheme, which makes it an ' \ + "absolute URL: sending it would hand this client's credentials to another host. Pass the path alone, " \ + "such as 'api/v1/tickets'." end refuse_unreadable_path!(relative) diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index 6c8c488..64f2cd9 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -447,6 +447,31 @@ expect { client.get('/https://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) end + # The guard asked for `://` after the scheme. Faraday 2.9.0 and 2.9.1 + # join such a path to the instance URL as URI does, which makes it an + # absolute URL with no host, and send the client's headers there. + ['http:/collect', 'HTTP:/collect', 'http:collect', '/http:/collect', 'file:/etc/hosts', 'api:v1/tickets'].each do |path| + it "refuses #{path}, which opens with a scheme and no host" do + expect { client.get(path) }.to raise_error(ArgumentError, /opens with a scheme, which makes it an absolute URL/) + end + end + + it 'reads such a path as URI does, which is what an older Faraday resolves it with' do + expect(URI('https://zammad.test/').merge('http:/collect').host).to be_nil + end + + it 'takes a colon after the first segment, which leaves the path relative' do + stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/tags:x").to_return(json_response({})) + client.get('api/v1/tags:x') + expect(stub).to have_been_requested + end + + it 'takes a URL written into the query string' do + stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/roles").with(query: { 'next' => 'http://other.example/x' }).to_return(json_response({})) + client.get('api/v1/roles?next=http://other.example/x') + expect(stub).to have_been_requested + end + it 'refuses an absolute URL for every verb' do %i[post put delete].each do |verb| expect { client.public_send(verb, 'https://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) From 9b7dcf2e78757ca4f9cfebc3f06a0b0a9bbfc73d Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 18:16:10 +0200 Subject: [PATCH 025/121] fix: refuse a query value or a scope that is no value `Transport.stringify_query_value` wrote whatever was neither a Hash nor an Array as its `to_s`, and every object has one: client.users.search('smith', ids: Set[1, 2]) # ids=Set[1, 2] client.users.search('smith', ids: (1..3)) # ids=1..3 Neither names a user, Zammad narrows by the text all the same, and nothing marks the answer as the wrong one. A record under a key went as it prints. `stringify_on_behalf_of` did the same with the From scope: `client.on_behalf_of(user)`, with the record where its id or login belongs, built a client whose From header read `#`. A query value is text, a Symbol, a number or a boolean, alone or in a list or a structure, and anything else raises ArgumentError at whatever depth it sits, with the parameter path. What converts to a Hash is still read as one. A scope is text or an Integer, the types a record id is written as. Both messages name the class and do not quote the value, as the one for a record given as an id does not. A Time is refused with the rest. Its `to_s` is not the ISO 8601 text Zammad's conditions read, and the message says to pass that. --- CHANGELOG.md | 7 +++ README.md | 15 ++++-- lib/zammad_api/client.rb | 3 +- lib/zammad_api/transport.rb | 67 ++++++++++++++++++++++---- sig/zammad_api/transport.rbs | 3 ++ spec/unit/zammad_api/client_spec.rb | 17 +++++++ spec/unit/zammad_api/transport_spec.rb | 48 ++++++++++++++++++ 7 files changed, 145 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7054df0..2341fcd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -921,6 +921,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a the request then goes over plain HTTP with the client's `Authorization` header and any `on_behalf_of` scope. Faraday from 2.9.2 on keeps such a path on the instance; the refusal no longer depends on which is installed. +- A query value that is not text, a number, a boolean, a list or a structure raises + `ArgumentError`, at any depth. It was sent as its `to_s`: + `client.users.search('smith', ids: Set[1, 2])` asked for `ids=Set[1, 2]`, which names + neither user, `ids: (1..3)` for `ids=1..3`, and a record under a key went as it prints, + and Zammad narrowed by that text. `client.on_behalf_of(user)`, with the record where its + id or login belongs, built a client whose `From` header carried the record the same way, + and raises too. Both messages name the class and do not quote the value. ### Changed diff --git a/README.md b/README.md index 85cfa60..f20d5a5 100644 --- a/README.md +++ b/README.md @@ -880,10 +880,14 @@ attribute value goes in the term, a sort in `order`, and paging in `page`, `in_b `find_each`. A user keyword on another resource raises for the same reason: Zammad takes `group_ids` on a ticket search and drops it, so tickets are narrowed by group with the condition above. A `nil` value raises too: there is no query string that means "this field -is null". So does a keyword with nothing in it, such as `ids: []`, `condition: {}`, or a -condition that holds nothing but empty Hashes, which a query string does not write. Zammad -reads that as the keyword not having been given, so `search('smith', ids: allowed_ids)` -with no id allowed would come back with every user matching the term rather than none. +is null". A value that is not text, a number, `true` or `false` raises as well, alone or +inside a list or a condition: `ids: Set[1, 2]` would be sent as that text, which names no +user, so pass a `Set` or a `Range` as its `to_a`, a time as the text Zammad reads, and a +record as its id. So does a keyword with nothing in it, such as `ids: []`, +`condition: {}`, or a condition that holds nothing but empty Hashes, which a query string +does not write. Zammad reads that as the keyword not having been given, so +`search('smith', ids: allowed_ids)` with no id allowed would come back with every user +matching the term rather than none. Zammad routes a search endpoint per model, not for every model. `users`, `organizations`, `tickets` and `groups` have one; `ticket_states`, `ticket_priorities` and `ticket_articles` @@ -1096,6 +1100,9 @@ header with nothing in it as no header at all, so `client.on_behalf_of(user&.log no user would otherwise perform every request as the account the client authenticates as, and read everything that account can see. +So does one that is neither text nor an Integer. Pass `user.id` or `user.login`, not the +record: `client.on_behalf_of(user)` would send the record as it prints, which names nobody. + ## Error handling Every error descends from `ZammadAPI::Error`. diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index 2f80e11..3bc28c0 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -352,7 +352,8 @@ def with(**options) # @param identifier [String, Integer] login, email address or user id # @yieldparam scoped [Client] # @return [Client] when no block is given, otherwise the block's value - # @raise [ArgumentError] for an identifier that is nil, empty or blank + # @raise [ArgumentError] for an identifier that is nil, empty or blank, + # or neither text nor an Integer, such as the record of the user def on_behalf_of(identifier) # Nil is what a transport takes for no scope, so it is refused here. # The rest is refused by the rule every transport is meant to apply, diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 67e03f5..7906d4e 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -181,6 +181,12 @@ module Verbs # names a record. RECORD_ID_TYPES = [Integer, String, Symbol].freeze + # What a query value is written as, where it is not a list or a + # structure: text, a number or a boolean. Each has one spelling a query + # string can carry and Zammad reads back. No other object does, and + # `to_s` answers for all of them. + QUERY_VALUE_TYPES = [String, Symbol, Numeric, TrueClass, FalseClass].freeze + # A request path that opens with a scheme, which is what makes a URL an # absolute one, whatever follows. Any scheme and either case, which is # wider than the two lowercase prefixes Faraday itself treats as @@ -242,8 +248,9 @@ module Verbs # @param query [Hash] # @return [Hash{String => String, Array, Hash}] # @raise [ArgumentError] for a query that is not a Hash, for a nil - # value, for two keys that name the same parameter, or for a list a - # query string cannot carry, the last three at any depth + # value, for a value that is neither text, a number, a boolean, a + # list nor a structure, for two keys that name the same parameter, or + # for a list a query string cannot carry, the last four at any depth def self.stringify_query(query) hash = Hash.try_convert(query) || raise(ArgumentError, "query needs to be a Hash of parameter names and values, got #{query.class}") @@ -305,24 +312,46 @@ def self.empty_query_name_message(prefix) # A Hash is written as `condition[ticket.state_id][operator]=is`, which # is the shape Rails reads back. # + # The same happened one kind of value further out. Whatever was neither + # a Hash nor an Array was still rendered with to_s: `ids: Set[1, 2]` + # went on the wire as `ids=Set[1, 2]` and `ids: (1..3)` as `ids=1..3`, + # text that names no record and that Zammad narrows by all the same, + # and a record under a key went as `#`. + # Refused, as a record where an id belongs is by + # {.escape_path_segment}, and for its reason: the answer to such a + # request is the wrong one, and nothing marks it. See + # {QUERY_VALUE_TYPES} for what is written. + # # @api private # @param key [String] the parameter path, for the error message # @param value [Object] # @return [String, Array, Hash] - # @raise [ArgumentError] for a nil value, or a list a query string cannot - # carry + # @raise [ArgumentError] for a nil value, a value a query string has no + # spelling for, or a list it cannot carry def self.stringify_query_value(key, value) case value - when nil then raise ArgumentError, "query parameter #{key} is nil, and Zammad has no way to read that: pass a value, or leave the parameter out" - when Hash then stringify_query_hash(value, key) - when Array then stringify_query_list(key, value) + when nil then raise ArgumentError, "query parameter #{key} is nil, and Zammad has no way to read that: pass a value, or leave the parameter out" + when Hash then stringify_query_hash(value, key) + when Array then stringify_query_list(key, value) + when *QUERY_VALUE_TYPES then wire_text(value, "query parameter #{key}") else - converted = Hash.try_convert(value) + converted = Hash.try_convert(value) || raise(ArgumentError, not_a_query_value_message(key, value)) - converted ? stringify_query_hash(converted, key) : wire_text(value, "query parameter #{key}") + stringify_query_hash(converted, key) end end + # Names the class and does not quote the value, which for a record is + # every attribute it carries. + # + # @api private + # @return [String] + def self.not_a_query_value_message(key, value) + "query parameter #{key} was given as #{value.class}, and a query string carries text, numbers and booleans, alone " \ + 'or in an Array or a Hash: it would be sent as that object prints, and Zammad would narrow by that text. ' \ + 'Pass a Set or a Range as its to_a, a time as text Zammad reads, such as its iso8601, and a record as its id.' + end + # Stringifies a list, and refuses one Rails could not read back as the # list it was. # @@ -487,12 +516,20 @@ def self.line_break?(text) = /[\r\n]/.match?(text.b.strip) # counts Unicode spaces as well as ASCII ones: Zammad asks # `request_header_from.blank?`. # + # So is one that is neither text nor an Integer. Every object has a + # `to_s`, and `client.on_behalf_of(user)`, with the record where its + # login belongs, built a client whose From header read + # `#`. The types are the ones a + # record id is written as: see {RECORD_ID_TYPES}. + # # @api private # @param identifier [String, Integer, nil] login, email or user id # @return [String, nil] frozen, or nil for no scope - # @raise [ArgumentError] for an identifier with nothing in it + # @raise [ArgumentError] for an identifier that is neither text nor an + # Integer, or has nothing in it def self.stringify_on_behalf_of(identifier) return nil if identifier.nil? + raise ArgumentError, not_an_identifier_message(identifier) if RECORD_ID_TYPES.none? { identifier.is_a?(it) } text = wire_text(identifier, 'on_behalf_of') raise ArgumentError, blank_on_behalf_of_message(identifier) if BLANK.match?(text) @@ -541,6 +578,16 @@ def self.wire_text(value, name) end end + # Names the class and does not quote the identifier, which for a record + # is every attribute it carries. + # + # @api private + # @return [String] + def self.not_an_identifier_message(identifier) + "on_behalf_of needs the login, email address or id of a user, as a String or an Integer, and was given #{identifier.class}: " \ + 'the From header would carry that object as it prints, which names no user. To act for a user you hold a record of, pass its id.' + end + # @api private # @return [String] def self.blank_on_behalf_of_message(identifier) diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 8fdb039..3b5ad80 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -30,6 +30,7 @@ module ZammadAPI UNRESERVED_IN_PATH: Regexp DOT_SEGMENTS: Array[String] RECORD_ID_TYPES: Array[Class] + QUERY_VALUE_TYPES: Array[Class] ABSOLUTE_URL: Regexp RESERVED_HEADERS: Hash[String, String] @@ -46,6 +47,7 @@ module ZammadAPI def self.stringify_query: (untyped) -> Hash[String, untyped] def self.stringify_query_hash: (Hash[untyped, untyped], String?) -> Hash[String, untyped] def self.stringify_query_value: (String, untyped) -> untyped + def self.not_a_query_value_message: (String key, untyped value) -> String def self.stringify_query_list: (String, Array[untyped]) -> Array[untyped] def self.misread_element_message: (String, Symbol) -> String def self.empty_query_name_message: (String? prefix) -> String @@ -55,6 +57,7 @@ module ZammadAPI LINE_BREAK_ADVICE: String def self.line_break?: (String text) -> bool def self.stringify_on_behalf_of: ((String | Integer)? identifier) -> String? + def self.not_an_identifier_message: (untyped identifier) -> String def self.blank_on_behalf_of_message: (untyped identifier) -> String def self.stringify_header_value: (String, untyped) -> String def self.escape_path_segment: (untyped) -> String diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index 64f2cd9..6b7366d 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -825,6 +825,23 @@ .to have_been_made.twice end + # `client.on_behalf_of(user)` built a client whose From header carried + # the record as it prints. + describe 'the record of a user where its login belongs' do + let(:user) { unit_client.users.find(1) } + + it 'is refused by its class, without printing it' do + expect { unit_client.on_behalf_of(user) } + .to raise_error(ArgumentError, /and was given ZammadAPI::Resources::User: .* pass its id\.\z/) { |error| + expect(error.message).not_to include('#<') + } + end + + it 'is what its id is taken from' do + expect(unit_client.on_behalf_of(user.id).inspect).to include('on_behalf_of="1"') + end + end + # Zammad skips a From header with nothing in it, and a nil sent none, so # each of these handed back a client that ran every request as the # account it authenticates as - with no error to say the scope was gone. diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 7cc4f70..14b43f0 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -119,6 +119,38 @@ .to eq({ 'condition' => { 'open' => { 'active' => 'true', 'limit' => '5' } } }) end + # Whatever was neither a Hash nor an Array went on the wire as its + # `to_s`, which names nothing, and Zammad narrowed by it all the same. + context 'with a value a query string has no spelling for' do + { 'a Set' => Set[1, 2], 'a Range' => (1..3), 'a Time' => Time.at(0), 'any other object' => Object.new }.each do |kind, value| + it "refuses #{kind} by its class, without quoting it" do + expect { described_class.stringify_query(ids: value) } + .to raise_error(ArgumentError, /\Aquery parameter ids was given as #{value.class}, and a query string carries text, numbers and booleans/) { |error| + expect(error.message).not_to include(value.to_s) + } + end + end + + it 'refuses one inside a list, naming where' do + expect { described_class.stringify_query(ids: [1, Set[2]]) }.to raise_error(ArgumentError, /\Aquery parameter ids\[1\] was given as Set/) + end + + it 'refuses one inside a structure, naming where' do + expect { described_class.stringify_query(condition: { 'ticket.id' => { operator: 'is', value: (1..3) } }) } + .to raise_error(ArgumentError, /\Aquery parameter condition\[ticket\.id\]\[value\] was given as Range/) + end + + it 'sends nothing for a request that carries one' do + expect { unit_transport.get('api/v1/groups', operation: 'test', query: { ids: Set[1, 2] }) }.to raise_error(ArgumentError) + expect(a_request(:any, //)).not_to have_been_made + end + + it 'still writes text, a Symbol, a number and a boolean' do + expect(described_class.stringify_query(a: 'x', b: :y, c: 1, d: 1.5, e: true, f: false)) + .to eq({ 'a' => 'x', 'b' => 'y', 'c' => '1', 'd' => '1.5', 'e' => 'true', 'f' => 'false' }) + end + end + # `ActionController::Parameters` is not a Hash. Nested, it was written # as its `to_s`; as the whole query it raised NoMethodError. context 'with what converts to a Hash and is not one' do @@ -1306,6 +1338,22 @@ def detailed_message = "unreadable: #{message}" end end + # Every object has a `to_s`, and the From header carried it. + { 'an Array' => ['agent'], 'a Float' => 1.5, 'true' => true, 'any other object' => Object.new }.each do |kind, value| + it "refuses #{kind}, which names no user, by its class" do + expect { unit_transport.with_on_behalf_of(value) } + .to raise_error(ArgumentError, /\Aon_behalf_of needs the login, email address or id of a user, as a String or an Integer, and was given #{value.class}:/) + end + end + + it 'takes a user id given as an Integer' do + expect(unit_transport.with_on_behalf_of(7).on_behalf_of).to eq('7') + end + + it 'takes a login given as a Symbol' do + expect(unit_transport.with_on_behalf_of(:agent).on_behalf_of).to eq('agent') + end + # The blank check raised Encoding::CompatibilityError for text in an # encoding ASCII is no part of, for an identifier that names someone too. it 'refuses an identifier with a line break inside it' do From 49b547bda16a865d9ad63aafd869226717fb2e92 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 19 Nov 2026 18:17:12 +0200 Subject: [PATCH 026/121] fix: drop a constant the library no longer has from the sigs sig/zammad_api/response.rbs still declared `ZammadAPI::Response::TOTAL_COUNT_HEADER`. lib/zammad_api/response.rb defines no such constant: the `x-total-count` reader it belonged to is gone, since Zammad sends no such header. So Steep accepted `response.headers[ZammadAPI::Response::TOTAL_COUNT_HEADER]` in a consumer's code, and the line raised NameError when it ran. The other constants the response, transport and config signatures declare were checked against the loaded classes, and all exist. --- CHANGELOG.md | 3 +++ sig/zammad_api/response.rbs | 2 -- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2341fcd..a60646f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -928,6 +928,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a and Zammad narrowed by that text. `client.on_behalf_of(user)`, with the record where its id or login belongs, built a client whose `From` header carried the record the same way, and raises too. Both messages name the class and do not quote the value. +- The signatures no longer declare `ZammadAPI::Response::TOTAL_COUNT_HEADER`, a constant + the library does not have. Steep accepted code that named it, which then raised + `NameError` when it ran. ### Changed diff --git a/sig/zammad_api/response.rbs b/sig/zammad_api/response.rbs index ee9f3a4..e77f4b2 100644 --- a/sig/zammad_api/response.rbs +++ b/sig/zammad_api/response.rbs @@ -9,8 +9,6 @@ module ZammadAPI def self.new: (status: Integer, headers: Hash[String, String], body: untyped, raw_body: String, json: bool) -> instance SUCCESS_STATUSES: Range[Integer] - # private_constant in the source; RBS has no way to say so. - TOTAL_COUNT_HEADER: String def self.decode_body: (String?, String) -> [untyped, bool] From 3f18eed33fff886dae87e5c5049896c0c02fdfc0 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 12:41:58 +0200 Subject: [PATCH 027/121] fix: refuse a body value that JSON has no type for `Transport.encode_body` handed the body to `JSON.generate`, which writes an object JSON has no type for as its `to_s`: client.users.create(login: 'x', role_ids: Set[1, 2]) # {"login":"x","role_ids":"Set[1, 2]"} A Struct went as `#`. Nothing raised, and Zammad received a String where the list belongs. With ActiveSupport loaded it is the same, as `JSON.generate` does not ask `as_json`: 1.x sent the body with `to_json`, which there wrote the Set as a list and `2.days` as 172800, and 2.0 sent `"Set[1, 2]"` and `"172800"`. The body is walked before it is encoded. What converts to a Hash is that Hash, as before. An object with a `to_json` of its own is left to the generator, which is how a record of this gem and a value object written to be sent go out. An object with an `as_json` is what that returns, walked in turn, so a body in a Rails app is what 1.x sent. Anything else raises ZammadAPI::Error through the message every body that cannot be encoded has, with the key and the class and without the value. A Time and a Date are left to print as they did. Their text is what Zammad reads a time or a date attribute from, so refusing them would have broken requests that were right. The query rule refuses a Time because a condition does not read that text. The test kit refuses the same bodies, through `encode_body`. --- CHANGELOG.md | 8 ++ README.md | 8 ++ Steepfile | 11 +- lib/zammad_api/transport.rb | 114 +++++++++++++++++-- sig/zammad_api/transport.rbs | 6 + spec/unit/zammad_api/test_spec.rb | 8 ++ spec/unit/zammad_api/transport_spec.rb | 145 ++++++++++++++++++++++++- 7 files changed, 279 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a60646f..790be5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -931,6 +931,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - The signatures no longer declare `ZammadAPI::Response::TOTAL_COUNT_HEADER`, a constant the library does not have. Steep accepted code that named it, which then raised `NameError` when it ran. +- A request body value JSON has no type for is no longer sent as its `to_s`. + `client.users.create(login: 'x', role_ids: Set[1, 2])` sent `"role_ids":"Set[1, 2]"`, a + String where the list belongs, and a Struct went as `#`. Where ActiveSupport + is loaded such an object is sent as its `as_json`, which is what 1.x sent there: the Set + as a list, `2.days` as `172800` and not as `"172800"`, a model as its attributes. + Elsewhere it raises `ZammadAPI::Error`, naming the key and the class and not the value. An + object with a `to_json` of its own still writes itself, and a `Time` or a `Date` is still + sent as its text, which Zammad reads. ### Changed diff --git a/README.md b/README.md index f20d5a5..9fe3b71 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,14 @@ Names are case-insensitive, and two spellings of one header are refused rather t are for, the second is what `on_behalf_of` sets, and replacing either from a single request would leave the client reporting something it no longer does. +A `body:` is sent as JSON, and so are the attributes a record is saved with. A value JSON +has no type for raises `ZammadAPI::Error` rather than going out as it prints, which is all +the encoder does with one: pass a `Set` or a `Range` as its `to_a`. An object that defines +`to_json` writes itself, a `Time` or a `Date` is sent as its text, which Zammad reads, and +what converts to a Hash, such as permitted `ActionController::Parameters`, is sent as that +Hash. Where ActiveSupport is loaded, any other object is sent as its `as_json`, as its +`to_json` there would write it. + Each returns a `ZammadAPI::Response`, so the status and headers stay reachable: ```ruby diff --git a/Steepfile b/Steepfile index d46d146..be45c0f 100644 --- a/Steepfile +++ b/Steepfile @@ -7,11 +7,12 @@ target :lib do # socket is here for SocketError and openssl for OpenSSL::SSL::SSLError, # both of which Transport maps to ConnectionError; forwardable is here for # the collection shorthands ResourceProxy delegates to Collection; uri is - # here for the parse Config makes to find credentials in the instance url. - # None of the four is named in the signatures the gem publishes - see - # SSL_ERRORS in sig/zammad_api/transport.rbs and sig/vendor/internal.rbs - so - # this does not add anything a consumer has to load. - library 'json', 'logger', 'timeout', 'socket', 'openssl', 'forwardable', 'uri' + # here for the parse Config makes to find credentials in the instance url; + # date is here for the Date a request body carries as text. None of the + # five is named in the signatures the gem publishes - see SSL_ERRORS in + # sig/zammad_api/transport.rbs and sig/vendor/internal.rbs - so this does + # not add anything a consumer has to load. + library 'json', 'logger', 'timeout', 'socket', 'openssl', 'forwardable', 'uri', 'date' configure_code_diagnostics do |hash| # Default keyword-argument hashes such as `attributes = {}` cannot be diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 7906d4e..b042442 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require 'date' require 'faraday' require 'faraday/retry' require 'json' @@ -187,6 +188,16 @@ module Verbs # `to_s` answers for all of them. QUERY_VALUE_TYPES = [String, Symbol, Numeric, TrueClass, FalseClass].freeze + # What a request body is made of, where it is not a list or a structure: + # the values JSON has a type for, and a Symbol, which the generator + # writes as text. + JSON_VALUE_TYPES = [NilClass, String, Symbol, Integer, Float, TrueClass, FalseClass].freeze + + # Objects that are no JSON type and go into a body as they print all the + # same, because what they print is the value: Zammad reads a time or a + # date attribute from that text. `date` is required above for this list. + TEXT_VALUE_TYPES = [Time, Date].freeze + # A request path that opens with a scheme, which is what makes a URL an # absolute one, whatever follows. Any scheme and either case, which is # wider than the two lowercase prefixes Faraday itself treats as @@ -867,19 +878,102 @@ def self.redact(value) def self.encode_body(body, operation:, resource_class: nil) return body if body.nil? || body.is_a?(String) - # Through the walk a record's attributes go through, for what it - # reads as a Hash: see {DeepCopy.frozen_object}. The generator has no - # spelling for `ActionController::Parameters` and writes its `to_s` - # as one String, so `client.post(path, body: permitted)` sent that in - # place of an object, password included, and a body holding one sent - # it under the key. - JSON.generate(DeepCopy.frozen_copy(body)) + JSON.generate(json_value(body, nil)) rescue JSON::JSONError => e raise Error, "Can't #{Error.subject_for(operation, resource_class)}: the request body cannot be encoded as JSON (#{e.message}). " \ 'Every value has to be a JSON type, and text has to be valid UTF-8: Base64-encode binary data such as an ' \ 'attachment, and leave out a Float that is NaN or infinite.' end + # A body as the generator may be handed it: every value in it one JSON + # has a type for, or an object that says what it is written as. + # + # The generator writes whatever is neither as the object's `to_s`, and + # every object has one. `client.users.create(login: 'x', role_ids: + # Set[1, 2])` sent `"role_ids":"Set[1, 2]"`, a String where the list + # belongs, and a Struct went as `#`. Nothing raised, and + # what Zammad made of the text was the answer. It is what + # {.stringify_query_value} refuses in a query, one request part over. + # + # @api private + # @param value [Object] + # @param key [Object, nil] the key the value sits under, for the error + # message + # @return [Object] + # @raise [JSON::GeneratorError] for a value JSON has no type for, which + # {.encode_body} words like any other body that cannot be encoded + def self.json_value(value, key) + case value + when *JSON_VALUE_TYPES then value + when Hash then value.to_h { |name, nested| [name, json_value(nested, name)] } + when Array then value.map { json_value(it, key) } + else json_object(value, key) + end + end + + # What is none of the above, as what the object itself says it is, in + # the order the object is asked. + # + # What converts to a Hash is that Hash, as it is for a record's + # attributes: see {DeepCopy.frozen_object}. The generator has no + # spelling for `ActionController::Parameters` either, so `client.post(path, + # body: permitted)` sent its `to_s` in place of an object, password + # included, and a body holding one sent it under the key. + # + # An object with a `to_json` of its own is left to the generator, which + # calls it: a record of this gem, or a value object written to be sent. + # + # An object with an `as_json` is what that returns, and what it holds is + # walked in turn. ActiveSupport gives every object one and builds its + # `to_json` on it, which is what 1.x sent a body with. `JSON.generate` + # does not ask it, so in a Rails app `role_ids: Set[1, 2]` was the list + # under 1.x and the String above here, `ttl: 2.days` was `"172800"`, and + # a model went as `#`. + # + # A Time and a Date are left to print: see {TEXT_VALUE_TYPES}. + # + # @api private + # @return [Object] + # @raise [JSON::GeneratorError] + def self.json_object(value, key) + converted = Hash.try_convert(value) + return json_value(converted, key) if converted + return value if writes_own_json?(value) + + described = value.respond_to?(:as_json) ? value.as_json : value + case described + when *JSON_VALUE_TYPES, Hash, Array then json_value(described, key) + when *TEXT_VALUE_TYPES then described + else raise JSON::GeneratorError, not_a_json_value_message(value, key) + end + end + + # Whether an object has a `to_json` of its own, and not the one the + # generator gives every object - or ActiveSupport, around that one - + # which writes the object's `to_s`. + # + # Asked of where the method is defined, which is the same place for + # every object that has only the generic one, whichever of the two + # libraries put it there. And asked through Kernel, because a Struct or + # a Data may have a member called `method`. + # + # @api private + # @return [Boolean] + def self.writes_own_json?(value) + Kernel.instance_method(:method).bind_call(value, :to_json).owner != Object.instance_method(:to_json).owner + end + + # Names the class and the key, and does not quote the value, as + # {.not_a_query_value_message} does not. + # + # @api private + # @return [String] + def self.not_a_json_value_message(value, key) + "#{key.nil? ? 'it' : "its key #{key}"} was given as #{value.class}, which is no JSON type and would be sent as that " \ + 'object prints: pass a Set or a Range as its to_a, a number as an Integer or a Float, and any other object as ' \ + 'a Hash of what it holds' + end + # What the retry middleware is built with. # # +max_interval+ is what bounds a wait. The retry middleware sleeps for @@ -1379,10 +1473,8 @@ def log_response(method, path, response, started) # The other is an object inside the body. One that writes its own JSON # goes out as keys and values like any Hash - a value object with a # +to_json+, as the whole body or under a key of it - and +inspect+ - # printed every one of them. One that does not is sent as its +to_s+, - # which for most objects names the class and no more, while +inspect+ - # lists what the object holds: the log then showed a value the request - # never carried. + # printed every one of them. So does one that is sent as its +as_json+: + # see {.json_object}. # # So the payload is parsed, and the log holds what the wire holds. Where # it is a JSON object or array it is redacted like the structure it diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 3b5ad80..cc6aa13 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -31,6 +31,8 @@ module ZammadAPI DOT_SEGMENTS: Array[String] RECORD_ID_TYPES: Array[Class] QUERY_VALUE_TYPES: Array[Class] + JSON_VALUE_TYPES: Array[Class] + TEXT_VALUE_TYPES: Array[Class] ABSOLUTE_URL: Regexp RESERVED_HEADERS: Hash[String, String] @@ -66,6 +68,10 @@ module ZammadAPI def self.refuse_unreadable_path!: (String relative) -> void def self.unreadable_path_message: (String relative) -> String def self.encode_body: (untyped body, operation: String, ?resource_class: Class?) -> String? + def self.json_value: (untyped value, untyped key) -> untyped + def self.json_object: (untyped value, untyped key) -> untyped + def self.writes_own_json?: (untyped value) -> bool + def self.not_a_json_value_message: (untyped value, untyped key) -> String def self.retry_options: (Config config) -> Hash[Symbol, untyped] def self.retried?: (Config config, Symbol method, Response response) -> bool diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index e856847..07a188d 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -177,6 +177,14 @@ expect(zammad.requests).to be_empty end + it 'refuses a body holding a value JSON has no type for, the way the real transport does' do + zammad.stub(:post, 'api/v1/users', body: { id: 1 }) + + expect { client.users.create(login: 'jane', role_ids: Set[1, 2]) } + .to raise_error(ZammadAPI::Error, /its key role_ids was given as Set, which is no JSON type/) + expect(zammad.requests).to be_empty + end + # And for a query a query string could not carry as it was written. it 'refuses a list of Hashes Rails would read as one, the way the real transport does' do zammad.stub(:get, 'api/v1/roles', body: []) diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 14b43f0..9bc37c0 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -620,6 +620,131 @@ def response(status, headers = {}) end end + # The generator writes an object JSON has no type for as its `to_s`, so + # `role_ids: Set[1, 2]` went out as the String "Set[1, 2]" where the + # list belongs, and nothing raised. + context 'with a value JSON has no type for' do + let(:url) { "#{ClientHelper::BASE_URL}api/v1/users" } + + before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } + + { 'a Set' => Set[1, 2], 'a Range' => (1..3), 'a Struct' => Struct.new(:id).new(1), 'a Rational' => Rational(1, 2), 'any other object' => Object.new }.each do |kind, value| + it "raises a ZammadAPI::Error for #{kind}, which only prints as something" do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: { role_ids: value }) } + .to raise_error(ZammadAPI::Error, /request body cannot be encoded as JSON \(its key role_ids was given as #{Regexp.escape(value.class.to_s)}, which is no JSON type/) + end + end + + it 'raises for one further in' do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: { users: [{ role_ids: Set[1] }] }) } + .to raise_error(ZammadAPI::Error, /its key role_ids was given as Set/) + end + + it 'raises for one that is the whole body' do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: Set[1]) } + .to raise_error(ZammadAPI::Error, /\(it was given as Set/) + end + + it 'says what to pass in its place' do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: { role_ids: Set[1, 2] }) } + .to raise_error(ZammadAPI::Error, /pass a Set or a Range as its to_a/) + end + + it 'does not quote what it refuses' do + holder = Class.new { def initialize = @password = 'object-s3cret' }.new + + expect { unit_transport.post('api/v1/users', operation: 'save object', body: { user: holder }) } + .to raise_error(ZammadAPI::Error) { |error| expect(error.message).not_to include('object-s3cret') } + end + + it 'makes no request' do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: { role_ids: Set[1, 2] }) }.to raise_error(ZammadAPI::Error) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'is raised by a record save carrying such a value' do + user = unit_client.users.new(login: 'jane', role_ids: Set[1, 2]) + expect { user.save }.to raise_error(ZammadAPI::Error, /its key role_ids was given as Set/) + end + + it 'sends a Symbol as text, as the generator writes it' do + unit_transport.post('api/v1/users', operation: 'test', body: { state: :open, 1 => nil }) + + expect(a_request(:post, url).with(body: '{"state":"open","1":null}')).to have_been_made + end + + # Zammad reads a time or a date attribute from the text either prints. + it 'sends a Time and a Date as they print' do + unit_transport.post('api/v1/users', operation: 'test', body: { pending_time: Time.utc(2026, 1, 2, 3, 4, 5), due: Date.new(2026, 1, 2) }) + + expect(a_request(:post, url).with(body: '{"pending_time":"2026-01-02 03:04:05 UTC","due":"2026-01-02"}')).to have_been_made + end + + # A member called `method` is in the way of asking the object where + # its `to_json` comes from, and is not asked. + it 'leaves an object with a to_json of its own to write itself' do + # rubocop:disable-next Lint/DataDefineOverride -- the member in the way is the point + point = Data.define(:method, :id) { def to_json(*) = to_h.to_json(*) }.new('get', 1) + unit_transport.post('api/v1/users', operation: 'test', body: { point: point, points: [point] }) + + expect(a_request(:post, url).with(body: '{"point":{"method":"get","id":1},"points":[{"method":"get","id":1}]}')).to have_been_made + end + + it 'sends a record of this gem as its attributes' do + group = ZammadAPI::Resources::Group.from_response(unit_transport, { id: 1, name: 'Users' }) + unit_transport.post('api/v1/users', operation: 'test', body: { group: group }) + + expect(a_request(:post, url).with(body: '{"group":{"id":1,"name":"Users"}}')).to have_been_made + end + end + + # ActiveSupport gives every object an `as_json` and builds `to_json` on + # it, which is what 1.x sent a body with. `JSON.generate` does not ask + # it, so in a Rails app a Set was the list under 1.x and its `to_s` + # here, and `2.days` was "172800". Stood in for by objects that define + # the method, as ActiveSupport is not loaded here. + context 'with an object that says what it is as JSON' do + let(:as_json_class) { Struct.new(:described) { def as_json(*) = described } } + + before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } + + it 'sends what its as_json returns' do + unit_transport.post('api/v1/groups', operation: 'test', body: { ids: as_json_class.new([1, 2]), ttl: as_json_class.new(172_800) }) + + expect(a_request(:post, url).with(body: '{"ids":[1,2],"ttl":172800}')).to have_been_made + end + + it 'sends one that is the whole body the same way' do + unit_transport.post('api/v1/groups', operation: 'test', body: as_json_class.new({ 'name' => 'Support' })) + + expect(a_request(:post, url).with(body: '{"name":"Support"}')).to have_been_made + end + + it 'asks what its as_json returns in turn' do + unit_transport.post('api/v1/groups', operation: 'test', body: { group: as_json_class.new({ 'ids' => as_json_class.new([1]) }) }) + + expect(a_request(:post, url).with(body: '{"group":{"ids":[1]}}')).to have_been_made + end + + it 'raises where its as_json is no JSON type either' do + number = as_json_class.new(Rational(1, 2)) + + expect { unit_transport.post('api/v1/groups', operation: 'save object', body: { weight: number }) } + .to raise_error(ZammadAPI::Error, /its key weight was given as #{Regexp.escape(number.class.to_s)}, which is no JSON type/) + end + + it 'prefers the to_json an object has of its own' do + both = Class.new do + def as_json(*) = { 'from' => 'as_json' } + def to_json(*) = '{"from":"to_json"}' + end + + unit_transport.post('api/v1/groups', operation: 'test', body: { value: both.new }) + + expect(a_request(:post, url).with(body: '{"value":{"from":"to_json"}}')).to have_been_made + end + end + # Faraday's JSON middleware raised JSON::GeneratorError from inside the # stack and nothing mapped it, so it went past the rescue of # ZammadAPI::Error every caller is told to write. @@ -1720,13 +1845,23 @@ def detailed_message = "unreadable: #{message}" expect(log).not_to include('object-s3cret') end - # JSON has no spelling for such an object, and the generator sends its - # `to_s`, which names the class and no more. `inspect` lists what it - # holds, so the log showed a value the request never carried. - it 'does not print what an object holds and the request does not carry' do + # An object that is sent as its `as_json` goes out as keys and values + # too, and `inspect` printed the object in their place. + it 'redacts a credential in one that is sent as its as_json' do + described = Struct.new(:password) { def as_json(*) = to_h.transform_keys(&:to_s) }.new('object-s3cret') + transport.post('api/v1/groups', operation: 'test', body: { user: described }) + + expect(log).to include('Zammad API payload: {"user" => {"password" => "[REDACTED]"}}') + end + + # JSON has no type for such an object, and it is refused before the + # request is logged. It was sent as its `to_s`, which names the class + # and no more, while the log printed its `inspect`, which lists what + # it holds. + it 'does not print what an object holds and no request carries' do holder = Class.new { def initialize = @password = 'object-s3cret' }.new - transport.post('api/v1/groups', operation: 'test', body: { user: holder }) + expect { transport.post('api/v1/groups', operation: 'test', body: { user: holder }) }.to raise_error(ZammadAPI::Error) expect(log).not_to include('object-s3cret') end From 846d106c4ad75115e8f0584227aa666e3f6915f3 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 12:45:03 +0200 Subject: [PATCH 028/121] fix: keep credentials out of to_json under ActiveSupport `Config` redacts `inspect`, `to_s` and `pp`. ActiveSupport serializes an object another way, as what it holds: a Data as its members, any other object as its instance variables, and builds `to_json` on that. So in a Rails app client.config.to_json wrote the token, the password and the proxy credentials in full, and `client.to_json` wrote them through its configuration and transport and then requested every page of all seven index endpoints, as each resource proxy is Enumerable and is serialized as its elements. A log line or an error report that serialized something holding the client did the same. The README calls the configuration safe to include in an error report. Config, Client and Transport define `as_json` and `to_json`. A configuration is every option with what `inspect` blanks blanked, the logger and the middleware by their class. `inspect` and `as_json` read which options those are from one place. A client and a transport are what their `inspect` says: the URL, the authentication scheme and any on_behalf_of scope. The client builds that from its own configuration and does not ask its transport, which may be the test kit's. Without ActiveSupport `JSON.generate` wrote a configuration as its `to_s`, one redacted String. It writes the object now. --- CHANGELOG.md | 7 ++++ README.md | 6 ++- lib/zammad_api/client.rb | 17 +++++++++ lib/zammad_api/config.rb | 52 ++++++++++++++++++++++---- lib/zammad_api/transport.rb | 26 +++++++++++++ sig/zammad_api/client.rbs | 2 + sig/zammad_api/config.rbs | 4 ++ sig/zammad_api/transport.rbs | 3 ++ spec/unit/zammad_api/client_spec.rb | 42 +++++++++++++++++++++ spec/unit/zammad_api/config_spec.rb | 50 +++++++++++++++++++++++++ spec/unit/zammad_api/transport_spec.rb | 25 +++++++++++++ 11 files changed, 225 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 790be5d..aa43891 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -939,6 +939,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a Elsewhere it raises `ZammadAPI::Error`, naming the key and the class and not the value. An object with a `to_json` of its own still writes itself, and a `Time` or a `Date` is still sent as its text, which Zammad reads. +- `to_json` and `as_json` of a configuration, a client and a transport hold no credential. + With ActiveSupport loaded, which serializes an object as what it holds, `config.to_json` + wrote the token, the password and the proxy credentials in full, and `client.to_json` + did the same and then requested every page of every resource, a proxy being Enumerable. + So did a log line or an error report that serialized something holding either. A + configuration is now written with what `inspect` blanks blanked, and a client as its URL, + the way it authenticates and any `on_behalf_of` scope. ### Changed diff --git a/README.md b/README.md index 9fe3b71..acf2e6d 100644 --- a/README.md +++ b/README.md @@ -159,8 +159,10 @@ client = ZammadAPI::Client.from_env(timeout: 300) | `middleware` | `nil` | Callable that receives the Faraday connection while it is built. | Credentials are never written to the log, and `client.config` redacts them however it is -printed — `inspect`, `to_s` or `pp`, which is what a console shows — so a configuration -object is safe to include in an error report. +printed — `inspect`, `to_s` or `pp`, which is what a console shows — and however it is +serialized, with `to_json` or with the `as_json` ActiveSupport asks, so a configuration +object is safe to include in an error report. A client serializes as its URL and the way it +authenticates, and no more. Credentials belong in the options above, not in the URL. `https://user:secret@host/` raises `ZammadAPI::ConfigurationError`, because the HTTP stack would send those as basic diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index 3bc28c0..13aa466 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -376,6 +376,23 @@ def inspect "#<#{self.class.name} url=#{config.redacted_url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{scope.inspect}" if scope}>" end + # The client for a JSON encoder: what {#inspect} says, and nothing else. + # + # ActiveSupport gives every object an +as_json+ that is its instance + # variables, and builds +to_json+ on it. For a client those are the + # configuration, the transport and the resource proxies, so in a Rails + # app +client.to_json+ - or a log line or an error report serializing + # something that holds the client - wrote the credentials through the + # first two, and then read every record of every resource through the + # third: a proxy is Enumerable, which is serialized as its elements. + # + # @return [Hash{Symbol => Object}] + def as_json(*) = Transport.description(config, @transport.on_behalf_of) + + # @param state [JSON::State, nil] passed by +JSON.generate+ + # @return [String] {#as_json} as a JSON object + def to_json(state = nil) = as_json.to_json(state) + def method_missing(name, *args) return super if CONVERSION_METHODS.include?(name) || name.to_s.end_with?('=', '!', '?') diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 1567f2f..c694d83 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -260,6 +260,28 @@ def inspect # @return [void] def pretty_print(printer) = printer.text(inspect) + # The configuration for a JSON encoder: every option, with what + # {#inspect} blanks blanked. + # + # ActiveSupport gives a Data an +as_json+ that is its members as they + # are, and builds +to_json+ on it. So in a Rails app +config.to_json+ + # wrote the token, the password and the credentials of a proxy in full, + # and so did a log line or an error report that serialized something + # holding the configuration - the third way out of the class documented + # as safe to log, after {#inspect} and +pp+, and the one a structured + # logger takes. + # + # @return [Hash{Symbol => Object}] + def as_json(*) = to_h.to_h { |key, value| [key, placeholder(key, value) || printable(key, value)] } + + # Without this, +JSON.generate+ would write the configuration as one + # String, its {#to_s}, and ActiveSupport would not come by {#as_json} + # where +to_json+ is what is called. + # + # @param state [JSON::State, nil] passed by +JSON.generate+ + # @return [String] {#as_json} as a JSON object + def to_json(state = nil) = as_json.to_json(state) + private # Blanks the +user:password@+ part of a URL, keeping the host visible. @@ -306,16 +328,32 @@ def redact_userinfo(value) "#{scheme}#{REDACTION}#{rest[boundary..]}" end - def render(key, value) + # One option as {#inspect} prints it. What stands in for a value is + # printed bare, and a value as it inspects. + def render(key, value) = placeholder(key, value) || printable(key, value).inspect + + # What is shown in place of an option that is not shown itself, where it + # is one of those. One rule for {#inspect} and {#as_json}: a second + # copy of which options are credentials is the copy that misses the + # next one. + # + # @return [String, nil] + def placeholder(key, value) return REDACTION if REDACTED_ATTRIBUTES.include?(key) && value + # Loggers and procs have verbose default inspect output that would drown - # out the rest of the configuration. - return "#<#{value.class}>" if key == :logger - return "#<#{value.class}>" if key == :middleware && value - return redacted_url.inspect if key == :url - return redact_userinfo(value).inspect if key == :proxy && value + # out the rest of the configuration, and an encoder walks into whatever + # they hold. + "#<#{value.class}>" if key == :logger || (key == :middleware && value) + end + + # An option that is shown, as it may be: a URL without the credentials + # it carries. + def printable(key, value) + return redacted_url if key == :url + return redact_userinfo(value) if key == :proxy && value - value.inspect + value end # The type check comes before the pattern, because every check after it diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index b042442..deccb21 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1034,6 +1034,18 @@ def self.retried?(config, method, response) !Faraday::Retry::Middleware.new(nil, options).calculate_sleep_amount(1, { response_headers: Faraday::Utils::Headers.new(response.headers) }).nil? end + # What {#inspect} says of a transport or of a client, for a JSON + # encoder. Public for {Client#as_json}, whose transport may be another + # kind than this one. + # + # @api private + # @param config [Config] + # @param on_behalf_of [String, nil] + # @return [Hash{Symbol => Object}] + def self.description(config, on_behalf_of) + { url: config.redacted_url, auth: config.authentication_scheme, on_behalf_of: on_behalf_of }.compact + end + # @param config [Config] def initialize(config) @config = config @@ -1083,6 +1095,20 @@ def inspect "#<#{self.class.name} url=#{config.redacted_url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{on_behalf_of.inspect}" if on_behalf_of}>" end + # The transport for a JSON encoder: what {#inspect} says, and nothing + # else. + # + # ActiveSupport serializes an object as its instance variables, and + # here one of them is the Faraday connection, for which {#inspect} has + # said why it is not printed. Every record holds its transport. + # + # @return [Hash{Symbol => Object}] + def as_json(*) = Transport.description(config, on_behalf_of) + + # @param state [JSON::State, nil] passed by +JSON.generate+ + # @return [String] {#as_json} as a JSON object + def to_json(state = nil) = as_json.to_json(state) + # Performs a request and raises on anything but a 2xx response. # # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ diff --git a/sig/zammad_api/client.rbs b/sig/zammad_api/client.rbs index 0ac96c6..b340a72 100644 --- a/sig/zammad_api/client.rbs +++ b/sig/zammad_api/client.rbs @@ -41,6 +41,8 @@ module ZammadAPI def on_behalf_of: (String | Integer identifier) -> Client | [T] (String | Integer identifier) { (Client) -> T } -> T def inspect: () -> String + def as_json: (*untyped) -> Hash[Symbol, untyped] + def to_json: (?untyped state) -> String def method_missing: (Symbol, *untyped) -> untyped def respond_to_missing?: (Symbol, ?bool) -> bool diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index 1f2c234..ad6c79a 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -65,6 +65,8 @@ module ZammadAPI def inspect: () -> String def to_s: () -> String def pretty_print: (untyped printer) -> void + def as_json: (*untyped) -> Hash[Symbol, untyped] + def to_json: (?untyped state) -> String def to_h: () -> Hash[Symbol, untyped] private @@ -73,6 +75,8 @@ module ZammadAPI def normalize_proxy: (untyped) -> String? def normalize_adapter: (untyped) -> Symbol? def render: (Symbol, untyped) -> String + def placeholder: (Symbol, untyped) -> String? + def printable: (Symbol, untyped) -> untyped def normalize_url: (untyped) -> String def inline_credentials?: (String) -> bool def inline_credentials_message: (String) -> String diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index cc6aa13..0faa8ff 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -74,11 +74,14 @@ module ZammadAPI def self.not_a_json_value_message: (untyped value, untyped key) -> String def self.retry_options: (Config config) -> Hash[Symbol, untyped] def self.retried?: (Config config, Symbol method, Response response) -> bool + def self.description: (Config config, String? on_behalf_of) -> Hash[Symbol, untyped] def initialize: (Config) -> void def with_on_behalf_of: ((String | Integer)? identifier) -> Transport def with_config: (Config) -> Transport def inspect: () -> String + def as_json: (*untyped) -> Hash[Symbol, untyped] + def to_json: (?untyped state) -> String def request: (Symbol method, String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index 6b7366d..9603233 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -1068,6 +1068,48 @@ def with_on_behalf_of(identifier) = self.class.new(identifier) end end + # ActiveSupport serializes an object as its instance variables. For a + # client that was the configuration and the transport, credentials + # included, and then every record of every resource: a proxy is + # Enumerable, which is serialized as its elements. It is not loaded here: + # what is asked is what it asks, and that the answer is this class's own. + describe 'serializing as JSON' do + it 'answers as_json itself, where ActiveSupport would answer for any object' do + expect(described_class.instance_method(:as_json).owner).to be(described_class) + end + + it 'is the url and the auth scheme' do + expect(unit_client.as_json).to eq({ url: 'http://zammad.test/', auth: :http_token }) + end + + it 'names the user a scoped client acts for' do + expect(unit_client.on_behalf_of('agent@example.com').as_json).to include(on_behalf_of: 'agent@example.com') + end + + it 'writes that as a JSON object' do + expect(unit_client.to_json).to eq('{"url":"http://zammad.test/","auth":"http_token"}') + end + + it 'does not leak the token' do + expect(unit_client(http_token: 'super-secret').to_json).not_to include('super-secret') + end + + it 'stays that nested inside another structure' do + expect(JSON.generate(event: 'sync', client: unit_client(http_token: 'super-secret'))) + .to eq('{"event":"sync","client":{"url":"http://zammad.test/","auth":"http_token"}}') + end + + it 'makes no request' do + unit_client.to_json + + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'does not ask the transport, which may be the test kit\'s' do + expect(ZammadAPI::Test.new.client.as_json).to eq({ url: 'https://zammad.test/', auth: :http_token }) + end + end + # A proxy holds nothing but the client's transport and the resource class, # and `client.tickets` is the idiom every call starts with - each one used to # allocate a fresh one. diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 128cf64..69d3cd6 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -490,6 +490,56 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) end end + # ActiveSupport gives a Data an as_json that is its members as they are, + # and builds to_json on it, so in a Rails app `config.to_json` wrote the + # credentials in full. It is not loaded here: what is asked is what it + # asks, and that the answer is this class's own. + describe 'serializing as JSON' do + it 'answers as_json itself, where ActiveSupport would answer for a Data' do + expect(described_class.instance_method(:as_json).owner).to be(described_class) + end + + it 'redacts the password' do + expect(build(http_token: nil, user: 'u', password: 'pw-s3cret').as_json).to include(user: 'u', password: '[REDACTED]') + end + + it 'redacts the access token' do + expect(build(http_token: 'tok-s3cret').as_json).to include(http_token: '[REDACTED]', password: nil) + end + + it 'redacts the OAuth2 token' do + expect(build(http_token: nil, oauth2_token: 'oauth-s3cret').as_json).to include(oauth2_token: '[REDACTED]') + end + + it 'redacts the proxy credentials' do + expect(build(proxy: 'http://puser:pproxy-s3cret@proxy.test:8080').as_json).to include(proxy: 'http://[REDACTED]@proxy.test:8080') + end + + it 'names the logger and the middleware, and does not hand them to the encoder' do + expect(build(middleware: ->(faraday) { faraday }).as_json).to include(logger: '#', middleware: '#') + end + + it 'keeps every other option as it is' do + expect(build(timeout: 7, adapter: :net_http).as_json).to include(url: 'https://zammad.example.com/', timeout: 7, adapter: :net_http, ssl_verify: true) + end + + it 'writes that as a JSON object' do + written = JSON.parse(build(http_token: 'tok-s3cret', timeout: 7).to_json) + + expect(written).to include('url' => 'https://zammad.example.com/', 'http_token' => '[REDACTED]', 'timeout' => 7, 'logger' => '#') + end + + it 'holds no credential in what it writes' do + config = build(http_token: nil, user: 'u', password: 'pw-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') + + expect(config.to_json).not_to match(/pw-s3cret|pproxy-s3cret/) + end + + it 'stays redacted nested inside another structure' do + expect(JSON.generate(config: build(http_token: 'tok-s3cret'))).not_to include('tok-s3cret') + end + end + # Faraday turns the userinfo of a URL into a Basic Authorization header, and # its authorization middleware leaves a header that is already set alone - # so the credentials in the URL were sent in place of the configured ones. diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 9bc37c0..d2b2b04 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1590,6 +1590,31 @@ def detailed_message = "unreadable: #{message}" end end + # ActiveSupport serializes an object as its instance variables, and one of + # a transport's is the Faraday connection. It is not loaded here: what is + # asked is what it asks, and that the answer is this class's own. + describe 'serializing as JSON' do + let(:transport) do + unit_transport(http_token: 'tok-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') + end + + it 'answers as_json itself, where ActiveSupport would answer for any object' do + expect(described_class.instance_method(:as_json).owner).to be(described_class) + end + + it 'is the instance and the authentication scheme' do + expect(transport.as_json).to eq({ url: 'http://zammad.test/', auth: :http_token }) + end + + it 'names an on_behalf_of scope' do + expect(transport.with_on_behalf_of('agent@example.com').as_json).to include(on_behalf_of: 'agent@example.com') + end + + it 'writes that as a JSON object, with neither the token nor the proxy password' do + expect(JSON.generate(transport: transport)).to eq('{"transport":{"url":"http://zammad.test/","auth":"http_token"}}') + end + end + describe '#with_config' do it 'applies the new configuration' do expect(unit_transport.with_config(ZammadAPI::Config.new(**unit_config(timeout: 7))).config.timeout).to eq(7) From d1fa2148cb9485673edbc7fe30cf373927531efa Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 12:47:44 +0200 Subject: [PATCH 029/121] fix: refuse a raw request header name that is not one `Transport.stringify_headers` downcased a header's name and checked only its value. The name went to the adapter as it was, and the Net::HTTP that ships with Ruby 3.4 and 4.0 writes it to the socket as given: name = "X-A: 1\r\nFrom: admin@example.com\r\nX-B" client.get(path, headers: {name => 'v'}) sent the lines `X-A: 1`, `from: admin@example.com` and `x-B: v`, read off a local socket with net-http 0.9.1. From is one of the two headers a raw request is refused by name, and Authorization went the same way. `'From '` passed that refusal too and was sent as `From : v`, and an empty name as `: v`, with 0.10.0 as well. net-http refuses a control character or a colon from 0.10.0 on, with an ArgumentError of its own that quotes the name, raised after the request was logged. A name is an RFC 9110 token, and one that is empty or holds another character raises ArgumentError where the headers are stringified, which is before the request is logged. It is read from the bytes, so a name with a byte sequence invalid in its encoding is refused by the same message, where `downcase` raised its own. The message quotes the name as far as it is one. What follows a line break in it would have been header lines, and may be a credential. The test kit refuses the same names, through `stringify_headers`. --- CHANGELOG.md | 8 ++++ README.md | 4 +- lib/zammad_api/client.rb | 6 +-- lib/zammad_api/transport.rb | 53 ++++++++++++++++++++++++-- sig/zammad_api/transport.rbs | 3 ++ spec/unit/zammad_api/test_spec.rb | 8 ++++ spec/unit/zammad_api/transport_spec.rb | 52 +++++++++++++++++++++++++ 7 files changed, 127 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa43891..da90349 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -946,6 +946,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a So did a log line or an error report that serialized something holding either. A configuration is now written with what `inspect` blanks blanked, and a client as its URL, the way it authenticates and any `on_behalf_of` scope. +- A raw request refuses a header name that is not one. Only the value was checked, and the + `Net::HTTP` that ships with Ruby 3.4 and 4.0 writes a name as it is given: + `headers: {"X-A: 1\r\nFrom: admin@example.com\r\nX-B" => 'v'}` sent a `From` header of + its own, the one refused by name, and an `Authorization` went the same way. `'From '` + passed that refusal as well, and an empty name was sent as `: v`. A name that is empty or + holds anything but letters, digits and the signs RFC 9110 allows raises `ArgumentError` + before the request is sent or logged, and the test kit refuses it too. net-http from + 0.10.0 on refuses a line break or a colon itself, with an error that quotes the name. ### Changed diff --git a/README.md b/README.md index acf2e6d..4535a71 100644 --- a/README.md +++ b/README.md @@ -373,7 +373,9 @@ client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) Names are case-insensitive, and two spellings of one header are refused rather than merged. `Authorization` and `From` are refused outright: the first is what the client's credentials are for, the second is what `on_behalf_of` sets, and replacing either from a single request -would leave the client reporting something it no longer does. +would leave the client reporting something it no longer does. A name is letters, digits and +signs such as `-` and `_`; one that is empty, or holds a space, a colon or a line break, +raises `ArgumentError` before anything is sent or logged. A `body:` is sent as JSON, and so are the attributes a record is saved with. A value JSON has no type for raises `ZammadAPI::Error` rather than going out as it prints, which is all diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index 13aa466..d88fd26 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -261,9 +261,9 @@ def version # @return [Response] # @raise [ResponseError] for any non-2xx response # @raise [TransportError] when the request could not be completed - # @raise [ArgumentError] for a header this client sets itself, a value - # that is not text, a path that is an absolute URL, or one that cannot - # be read as a URL + # @raise [ArgumentError] for a header this client sets itself, a header + # name that is not one, a value that is not text, a path that is an + # absolute URL, or one that cannot be read as a URL def get(path, query: nil, headers: nil) = raw(:get, path, query: query, headers: headers) # Performs a +POST+ against any endpoint of the Zammad API. diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index deccb21..7729cc1 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -429,6 +429,11 @@ def self.misread_element_message(path, reason) 'from' => 'the From header is what on_behalf_of sets: use client.on_behalf_of(...) to perform requests for another user' }.freeze + # The part of a header name that is one, from its start: what RFC 9110 + # calls a token, which is letters, digits and these signs. Read from + # the bytes, as a name is ASCII in every encoding a request can carry. + HEADER_NAME = /\A[!\#$%&'*+\-.^_`|~0-9A-Za-z]*/ + # The headers a request carries beyond the ones this class sets. # # Names are downcased, which is what makes two spellings of one header @@ -437,6 +442,8 @@ def self.misread_element_message(path, reason) # order put last and drop the other without a word - the silent drop # {DuplicateKeys} exists to refuse. # + # A name that is not one is refused: see {.header_name}. + # # Values are stringified for the reason {#with_on_behalf_of} stringifies # the +From+ scope: a header is text on the wire, and a value of another # type reaches Net::HTTP intact and dies there with @@ -449,14 +456,54 @@ def self.misread_element_message(path, reason) # @api private # @param headers [Hash] # @return [Hash{String => String}] - # @raise [ArgumentError] for a nil value, a value that is not text, two - # spellings of one header, or a header this class sets itself + # @raise [ArgumentError] for a name that is not a header name, a nil + # value, a value that is not text, two spellings of one header, or a + # header this class sets itself def self.stringify_headers(headers) DuplicateKeys - .normalize(headers, noun: 'header') { it.to_s.downcase } + .normalize(headers, noun: 'header') { header_name(it) } .to_h { |name, value| [name, stringify_header_value(name, value)] } end + # A header name as it is compared and sent: downcased, and refused + # where it is not a name. + # + # Only the value was checked. A name went to the adapter as it was, and + # the Net::HTTP that ships with Ruby 3.4 and 4.0 writes it to the socket + # as it is: `headers: {"X-A: 1\r\nFrom: admin@example.com\r\nX-B" => + # 'v'}` sent a From header of its own, which is the one {RESERVED_HEADERS} + # refuses by name, and an Authorization went the same way. `'From '` + # passed that lookup too, and was sent as `From : v`, and a name with + # nothing in it as `: v`. net-http refuses a control character or a + # colon from 0.10.0 on, with an ArgumentError of its own that quotes the + # name, raised after the request was logged, and takes the other two. + # + # @api private + # @param name [Object] + # @return [String] + # @raise [ArgumentError] + def self.header_name(name) + text = name.to_s + bytes = text.b + start = bytes[HEADER_NAME].to_s + raise ArgumentError, not_a_header_name_message(start) if start.empty? || start.bytesize != bytes.bytesize + + text.downcase + end + + # Quotes the name as far as it is one, and no further. + # + # @api private + # @param start [String] the part of the name that is a name + # @return [String] + def self.not_a_header_name_message(start) + found = start.empty? ? 'a header name is empty or begins' : "the header name that begins #{start.inspect} goes on" + + "#{found} with a character no header name carries: a name is letters, digits and signs such as - and _, " \ + 'without a space, a colon or a line break. The rest of it is not quoted here: what follows a line break in a ' \ + 'name would be sent as header lines of their own, and may be a credential.' + end + # @api private # @return [String] def self.stringify_header_value(name, value) diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 0faa8ff..396309a 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -35,6 +35,7 @@ module ZammadAPI TEXT_VALUE_TYPES: Array[Class] ABSOLUTE_URL: Regexp RESERVED_HEADERS: Hash[String, String] + HEADER_NAME: Regexp attr_reader config: Config attr_reader on_behalf_of: String? @@ -61,6 +62,8 @@ module ZammadAPI def self.stringify_on_behalf_of: ((String | Integer)? identifier) -> String? def self.not_an_identifier_message: (untyped identifier) -> String def self.blank_on_behalf_of_message: (untyped identifier) -> String + def self.header_name: (untyped name) -> String + def self.not_a_header_name_message: (String start) -> String def self.stringify_header_value: (String, untyped) -> String def self.escape_path_segment: (untyped) -> String def self.not_a_record_id_message: (untyped value) -> String diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 07a188d..a2ea4d9 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -177,6 +177,14 @@ expect(zammad.requests).to be_empty end + it 'refuses a header name that is not one, the way the real transport does' do + zammad.stub(:get, 'api/v1/roles', body: []) + + expect { client.get('api/v1/roles', headers: { "X-A\r\nFrom: admin@example.com" => 'v' }) } + .to raise_error(ArgumentError, /goes on with a character no header name carries/) + expect(zammad.requests).to be_empty + end + it 'refuses a body holding a value JSON has no type for, the way the real transport does' do zammad.stub(:post, 'api/v1/users', body: { id: 1 }) diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index d2b2b04..3bbcf2b 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -72,6 +72,58 @@ end end + # Only the value of a raw request's header was checked. The Net::HTTP that + # ships with Ruby 3.4 and 4.0 writes a name to the socket as it is, so one + # holding a line break sent header lines of its own, a From or an + # Authorization among them. + describe 'header names' do + it 'downcases a name, and takes it as text or as a Symbol' do + expect(described_class.stringify_headers('Accept-Language' => 'de', :'X-Trace' => 'abc')).to eq('accept-language' => 'de', 'x-trace' => 'abc') + end + + it 'takes every sign a name may hold' do + expect(described_class.stringify_headers("X!#$%&'*+-.^_`|~9" => 'v')).to eq("x!#$%&'*+-.^_`|~9" => 'v') + end + + it 'refuses a name with a line break in it, and header lines of its own after that' do + expect { described_class.stringify_headers("X-A: 1\r\nFrom: admin@example.com\r\nX-B" => 'v') } + .to raise_error(ArgumentError, /\Athe header name that begins "X-A" goes on with a character no header name carries/) + end + + it 'does not quote what follows, which may be a credential' do + expect { described_class.stringify_headers("X-A: 1\r\nAuthorization: Token name-s3cret\r\nX-B" => 'v') } + .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('name-s3cret') } + end + + # Each passed the lookup that refuses a From header by name. + ['From ', ' From', "From\t", 'From:', "From\n"].each do |name| + it "refuses #{name.inspect}, which is no spelling of a header" do + expect { described_class.stringify_headers(name => 'agent@example.com') }.to raise_error(ArgumentError, /no header name carries/) + end + end + + ['', nil, 'X Trace', 'Träce', 'X-Trace'.encode('UTF-16LE')].each do |name| + it "refuses #{name.inspect}" do + expect { described_class.stringify_headers(name => 'abc') }.to raise_error(ArgumentError, /no header name carries/) + end + end + + # `downcase` raises for such text, with a message of its own. + it 'refuses a name with a byte sequence that is invalid in its encoding' do + expect { described_class.stringify_headers("X-\xFFTrace" => 'abc') } + .to raise_error(ArgumentError, /\Athe header name that begins "X-" goes on with a character no header name carries/) + end + + it 'makes no request for one, and logs none' do + log = StringIO.new + + expect { unit_transport(logger: Logger.new(log)).get('api/v1/groups', operation: 'test', headers: { "X-A\r\nFrom: x" => 'v' }) } + .to raise_error(ArgumentError) + expect(log.string).to be_empty + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end + describe 'base url handling' do it 'keeps a sub-path prefix in front of the request path' do stub = stub_request(:get, 'http://zammad.test/helpdesk/api/v1/groups').to_return(json_response([])) From a3c28a736acb7c8b047a808d8418f38a234a8d10 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 12:49:42 +0200 Subject: [PATCH 030/121] fix: serve a stub declared after an earlier one answered `Test#take` keeps a lone stub in the queue when it answers, so that one stub answers any number of requests. Once a second stub for the same endpoint and scope was queued behind it, the first was still at the head, and was taken as the first of a sequence of two: path = 'api/v1/tickets/1' zammad.stub(:get, path, body: {id: 1, state: 'open'}) client.tickets.find(1).state # => "open" zammad.stub(:get, path, body: {id: 1, state: 'closed'}) client.tickets.find(1).state # => "open" client.tickets.find(1).state # => "closed" A test that changes what an endpoint answers between two steps read the old answer once more. A stubbed 503 that the client had retried and raised for went on answering one more request after the 200 was stubbed. Where the stub at the head of its scope is the one that scope last answered with, and another waits behind it, it is dropped before one is taken. It can only still be there because it was the last when it answered. Stubs declared up front are sequenced as before, a request for a later page is still answered by the stub its read began with, and a stub of another scope is left alone. --- CHANGELOG.md | 5 +++ README.md | 3 ++ lib/zammad_api/test.rb | 34 +++++++++++++----- spec/unit/zammad_api/test_spec.rb | 60 +++++++++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da90349..df08c6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -954,6 +954,11 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a holds anything but letters, digits and the signs RFC 9110 allows raises `ArgumentError` before the request is sent or logged, and the test kit refuses it too. net-http from 0.10.0 on refuses a line break or a colon itself, with an error that quotes the name. +- `ZammadAPI::Test` answers with a stub declared after an earlier one for the same endpoint + has answered. The earlier one was served once more: stubbed open, read, stubbed closed + and read again, a ticket was open twice and closed only at the third read. A lone stub + stays in place to go on answering, and was taken for the first of the sequence the second + one began. ### Changed diff --git a/README.md b/README.md index 4535a71..2b021e7 100644 --- a/README.md +++ b/README.md @@ -1306,6 +1306,9 @@ client.groups.all.count # => 1 client.groups.all.count # => 2 ``` +The second stub may also be declared once the first has answered, between two steps of a +test. It answers from the next request on. + Name a `page` to say what each one holds, and the stub is served exactly as written: ```ruby diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index 80715b4..0fd469e 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -124,11 +124,13 @@ def initialize(**options) # # Stubbing the same method and path again queues a second response: the # first request gets the first, and the last stub answers every request - # after it. A collection read is one step of such a sequence however many - # pages it asks for, so three list stubs answer three reads in turn. A - # +query+ matches when every parameter it names is present in - # the request with that value, so a stub does not have to repeat the - # +expand+, +page+ and +per_page+ parameters the client adds itself. + # after it. One declared after an earlier one has answered takes over + # from the next request on. A collection read is one step of such a + # sequence however many pages it asks for, so three list stubs answer + # three reads in turn. A +query+ matches when every parameter it names + # is present in the request with that value, so a stub does not have to + # repeat the +expand+, +page+ and +per_page+ parameters the client adds + # itself. # # A stub that names a +query+ is more specific than one that does not, and # answers ahead of it however they were declared. Queueing applies within @@ -373,6 +375,15 @@ def snapshot(value) = DeepCopy.frozen_copy(value) # three list stubs A, B and C, three reads answered A, C and C, and B was # never seen. The trailing request belongs to the read that made it, so it # is answered by the stub that read's first page came from. + # + # A stub that answered while it was the last of its kind has had its + # turn, and gives way to one declared after it. It is kept in place so + # that it can go on answering, and so it was still at the head once a + # second one was queued behind it, and was taken for the first of a + # sequence that had not begun: stubbed open, read, stubbed closed and + # read again, a ticket was open twice and closed at the third read. A + # test that changes what an endpoint answers as it goes is the same + # sequence as one that declares it up front. def take(method, path, params) endpoint = key(method, path) queued = @stubs[endpoint] @@ -381,11 +392,18 @@ def take(method, path, params) matching = queued.each_index.select { matches?(queued[it][:query], params) } return nil if matching.empty? - group = most_specific(queued, matching, method, path) - scope = queued[group.first][:query] + group = most_specific(queued, matching, method, path) + scope = queued[group.first][:query] + served = @served[[endpoint, scope]] # The stub at the head of the queue is the fallback, for a later page # that is the first thing asked: `page(3)` on a list nothing has read. - return @served[[endpoint, scope]] || queued[group.first] if later_page?(scope, params) + return served || queued[group.first] if later_page?(scope, params) + + if group.size > 1 && queued[group.first].equal?(served) + queued.delete_at(group.first) + # Every other stub of the group sat behind the one that went. + group = group.drop(1).map(&:pred) + end @served[[endpoint, scope]] = group.one? ? queued[group.first] : queued.delete_at(group.first) end diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index a2ea4d9..9ba0524 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -393,6 +393,57 @@ expect(Array.new(3) { client.groups.find(1).name }).to eq(%w[Users Users Users]) end + + # A lone stub stays in place to go on answering, so it was still at + # the head when a second one was queued, and answered once more. + context 'when a stub is declared after an earlier one has answered' do + before do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'First' }) + client.groups.find(1) + end + + it 'answers the next request with the later one' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) + + expect(Array.new(2) { client.groups.find(1).name }).to eq(%w[Second Second]) + end + + it 'does so however often the earlier one answered' do + 2.times { client.groups.find(1) } + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) + + expect(client.groups.find(1).name).to eq('Second') + end + + it 'serves several declared after it in turn' do + %w[Second Third].each { zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: it }) } + + expect(Array.new(3) { client.groups.find(1).name }).to eq(%w[Second Third Third]) + end + + it 'does so again for one declared after the last of a sequence has answered' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) + client.groups.find(1) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Third' }) + + expect(client.groups.find(1).name).to eq('Third') + end + + it 'leaves a stub of another scope where it is' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Scoped' }, query: { full: true }) + + expect(client.groups.find(1).name).to eq('First') + expect(client.get('api/v1/groups/1', query: { full: true }).body).to eq({ id: 1, name: 'Scoped' }) + end + + it 'answers a failure the client retried with the stub declared after it' do + zammad.stub(:get, 'api/v1/groups/2', status: 503) + expect { client.groups.find(2) }.to raise_error(ZammadAPI::ServerError) + zammad.stub(:get, 'api/v1/groups/2', body: { id: 2, name: 'Back' }) + + expect(client.groups.find(2).name).to eq('Back') + end + end end describe 'query matching' do @@ -1057,6 +1108,15 @@ def names = client.groups.all.map(&:name) expect(Array.new(2) { client.groups.search('x').map(&:name) }).to eq([['A'], ['B']]) end + + # The read before it asked for a page after its last, and that request + # belongs to the stub the read began with. + it 'answers a read with a stub declared after the last one has answered a whole read' do + 3.times { names } + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'D' }]) + + expect(Array.new(2) { names }).to eq([['D'], ['D']]) + end end describe 'a list endpoint whose pages are stubbed by hand' do From 4e79f0b4fbe74ac52eec5a65f2a2e10778d33c81 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 12:53:32 +0200 Subject: [PATCH 031/121] fix: raise for a response body cut short of its length A body framed by Content-Length ends where the count is reached or where the connection does, and Net::HTTP takes the second for the first: `ignore_eof` is on by default. `Transport#decode` took what had arrived, so a server that announced 1000 bytes, sent 10 and closed the connection was answered with attachment.download # => the 10 bytes and examples/download_attachments.rb wrote them to disk as the file. A raw request for anything that is not JSON returned the same. A chunked body cut short raised already, and a JSON body that no longer parses is refused where it is decoded. `Transport#request` compares the bytes of a 2xx response with its Content-Length and raises ConnectionError where the body is shorter, with the number missing. It asks only where the bytes in hand are the ones that were counted: one Content-Length, no Content-Encoding, which an adapter may have decoded while leaving both headers as they arrived, no Transfer-Encoding, and not a 204. A body longer than announced is left alone, and a response that is not a 2xx still raises the error its status names. The check is made on the response the retry middleware handed over, so a GET that ends this way is not sent again. --- CHANGELOG.md | 7 ++ README.md | 2 +- lib/zammad_api/errors.rb | 3 +- .../resources/ticket_article_attachment.rb | 2 + lib/zammad_api/transport.rb | 57 +++++++++++- sig/zammad_api/transport.rbs | 3 + .../ticket_article_attachment_spec.rb | 10 ++ spec/unit/zammad_api/transport_spec.rb | 92 +++++++++++++++++++ 8 files changed, 172 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df08c6e..102f5d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -959,6 +959,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a and read again, a ticket was open twice and closed only at the third read. A lone stub stays in place to go on answering, and was taken for the first of the sequence the second one began. +- A response the connection was closed under raises `ZammadAPI::ConnectionError` where its + body is shorter than its `Content-Length`. `Net::HTTP` hands over what had arrived + without a word, so `attachment.download` returned the first bytes of a file as the file, + and a raw request for anything that is not JSON did the same. Checked for a 2xx response + that names one `Content-Length` and neither a `Content-Encoding` nor a + `Transfer-Encoding`; a chunked body cut short raised already. The request is not sent + again. ### Changed diff --git a/README.md b/README.md index 2b021e7..d70d87a 100644 --- a/README.md +++ b/README.md @@ -1126,7 +1126,7 @@ ZammadAPI::Error ├── ZammadAPI::ParseError unexpected response shape ├── ZammadAPI::PaginationError endpoint ignored the page parameter ├── ZammadAPI::TransportError -│ ├── ZammadAPI::ConnectionError unreachable host or TLS failure +│ ├── ZammadAPI::ConnectionError unreachable host, TLS failure or a response cut short │ └── ZammadAPI::TimeoutError exceeded timeout or open_timeout └── ZammadAPI::ResponseError carries the HTTP response ├── ZammadAPI::ClientError 4xx diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index 6ea7ce0..cf69ac1 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -28,7 +28,8 @@ class UnknownResourceError < Error; end class TransportError < Error; end # Raised when the connection to the Zammad instance could not be - # established (DNS, refused connection, TLS failure, ...). + # established (DNS, refused connection, TLS failure, ...), or was closed + # before the body of a response had arrived. class ConnectionError < TransportError; end # Raised when a request exceeded {Config#open_timeout} or {Config#timeout}. diff --git a/lib/zammad_api/resources/ticket_article_attachment.rb b/lib/zammad_api/resources/ticket_article_attachment.rb index c3035b0..fe2ff9a 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -25,6 +25,8 @@ def initialize(transport, attributes = {}) # # @return [String] the file contents, in +ASCII-8BIT+ encoding # @raise [ResponseError] when Zammad rejected the request + # @raise [ConnectionError] when the connection was closed before the + # whole file had arrived. The part that did arrive is not returned. def download segments = %i[ticket_id article_id id].map { Transport.escape_path_segment(fetch(it)) } response = @transport.get( diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 7729cc1..29da904 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1169,7 +1169,8 @@ def to_json(state = nil) = as_json.to_json(state) # @return [Response] # @raise [ResponseError] for non-2xx responses # @raise [TimeoutError] when the request timed out - # @raise [ConnectionError] when the instance was unreachable + # @raise [ConnectionError] when the instance was unreachable, or the + # connection was closed before the body of a 2xx response had arrived # # @raise [Error] when the body cannot be encoded as JSON # @@ -1187,7 +1188,7 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou response = decode(perform(method, path, query, payload, headers)) log_response(method, path, response, started) - return response if response.success? + return whole(response, operation) if response.success? raise ResponseError.build(response, operation: operation, resource_class: resource_class) rescue Faraday::TimeoutError, *TIMEOUT_ERRORS => e @@ -1204,6 +1205,58 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou private + # A Content-Length that can be compared: one figure, and nothing else. + # Two that were sent arrive joined by a comma, and say nothing certain. + CONTENT_LENGTH = /\A\d+\z/ + private_constant :CONTENT_LENGTH + + # A 2xx response, once its body is known to have arrived: see + # {#missing_bytes}. + # + # @return [Response] + # @raise [ConnectionError] + def whole(response, operation) + missing = missing_bytes(response) + return response if missing.nil? + + raise ConnectionError, "Can't #{operation}: the response from #{config.redacted_url} ended #{missing} bytes short of the " \ + "#{response.headers['content-length']} its Content-Length announces, so the connection was closed " \ + 'before the body had arrived' + end + + # How many bytes of its body a response stopped short by, where it did. + # + # A body framed by Content-Length ends where the count is reached, or + # where the connection does. Net::HTTP takes the second for the first + # without a word - its +ignore_eof+ is on by default - so a download + # the connection dropped under came back as the file: + # {Resources::TicketArticleAttachment#download} returned the first ten + # bytes of a thousand, and whatever wrote them to disk wrote a file that + # opens as a broken one. A chunked body cut short did raise, and a JSON + # one that no longer parses is refused where it is decoded, so this was + # the one response that came back wrong and looked right. + # + # Asked only where the bytes in hand are the bytes that were counted. A + # body under a Content-Encoding may have been decoded on the way here, + # by an adapter that leaves both headers as they arrived - Net::HTTP + # drops the one and corrects the other - and one under a + # Transfer-Encoding is not framed by the count at all. A 204 has no + # body whatever a header beside it says. + # + # Only a body that is short. One that is longer was not cut off. + # + # @return [Integer, nil] nil for a response that is whole, or that + # cannot be told + def missing_bytes(response) + headers = response.headers + announced = headers['content-length'] + return nil if announced.nil? || !CONTENT_LENGTH.match?(announced) + return nil if response.status == 204 || headers.key?('content-encoding') || headers.key?('transfer-encoding') + + missing = announced.to_i - response.raw_body.bytesize + missing.positive? ? missing : nil + end + # Whether a connection failure is a timeout underneath. # # An exceeded +open_timeout+ is raised by Net::HTTP as Net::OpenTimeout, diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 396309a..53262a0 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -24,6 +24,7 @@ module ZammadAPI SSL_ERRORS: Array[untyped] # private_constant in the source; RBS has no way to say so. REFUSED_MIDDLEWARE: Hash[String, [String, String]] + CONTENT_LENGTH: Regexp MISREAD_ELEMENTS: Hash[Symbol, String] SENSITIVE_KEY_PATTERN: Regexp REDACTED: String @@ -90,6 +91,8 @@ module ZammadAPI private + def whole: (Response response, String operation) -> Response + def missing_bytes: (Response response) -> Integer? def timed_out?: (untyped error) -> bool def perform: (Symbol, String, Hash[Symbol, untyped]?, String?, Hash[untyped, untyped]?) -> untyped def build_connection: () -> untyped diff --git a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb index 5145926..4cf335e 100644 --- a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb @@ -103,6 +103,16 @@ expect(attachment.download.encoding).to eq(Encoding::BINARY) end + # Net::HTTP hands over what had arrived when the connection dropped, + # and that was returned as the file. + it 'raises for a file the connection was closed under, and does not return the part that arrived' do + stub_request(:get, download_url) + .to_return(status: 200, body: "\x89PNG\r\n".b, headers: { 'Content-Type' => 'image/png', 'Content-Length' => '1000' }) + + expect { attachment.download } + .to raise_error(ZammadAPI::ConnectionError, /\ACan't download attachment: the response from .+ ended 994 bytes short of the 1000/) + end + it 'raises when the attachment is gone' do stub_request(:get, download_url).to_return(json_response({ error: 'not found' }, status: 404)) expect { attachment.download }.to raise_error(ZammadAPI::NotFoundError) diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 3bbcf2b..fc22942 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -919,6 +919,98 @@ def to_json(*) = '{"from":"to_json"}' .to raise_error(ZammadAPI::TimeoutError, %r{request to api/v1/groups\?token=\[REDACTED\] timed out}) end + # Net::HTTP reads a body framed by Content-Length until the count is + # reached or the connection ends, and takes the second for the first. + # The bytes that had arrived came back as the response. + context 'when the connection closes before the body has arrived' do + def cut_off(headers = {}, status: 200, body: '0123456789') + stub_request(:get, url).to_return(status: status, body: body, headers: { 'Content-Length' => '1000' }.merge(headers)) + end + + it 'raises a ConnectionError for a body shorter than its Content-Length' do + cut_off({ 'Content-Type' => 'image/png' }) + + expect { unit_transport.get('api/v1/groups', operation: 'download attachment') } + .to raise_error(ZammadAPI::ConnectionError, %r{\ACan't download attachment: the response from http://zammad\.test/ ended 990 bytes short of the 1000}) + end + + it 'raises for a JSON body that is short, and still parses' do + cut_off({ 'Content-Type' => 'application/json' }, body: '[]') + + expect { unit_transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::ConnectionError, /998 bytes short/) + end + + it 'raises for a body of which nothing arrived' do + cut_off(body: '') + + expect { unit_transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::ConnectionError, /1000 bytes short/) + end + + it 'counts the bytes, not the characters' do + stub_request(:get, url).to_return(status: 200, body: 'ää', headers: { 'Content-Length' => '4', 'Content-Type' => 'text/plain; charset=utf-8' }) + + expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body.bytesize).to eq(4) + end + + it 'returns a body as long as its Content-Length' do + stub_request(:get, url).to_return(status: 200, body: '0123456789', headers: { 'Content-Length' => '10' }) + + expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') + end + + it 'returns a body that names no Content-Length' do + stub_request(:get, url).to_return(status: 200, body: '0123456789') + + expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') + end + + # The bytes in hand may be the decoded ones, beside a count of the + # encoded ones, and a chunked body is not framed by the count. + it 'does not judge a body under a Content-Encoding or a Transfer-Encoding' do + [{ 'Content-Encoding' => 'br' }, { 'Transfer-Encoding' => 'chunked' }].each do |header| + cut_off(header) + + expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') + end + end + + it 'does not judge a Content-Length that is not one figure' do + ['1000, 1000', 'many', ''].each do |announced| + cut_off({ 'Content-Length' => announced }) + + expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') + end + end + + it 'does not judge a 204, which has no body whatever is announced beside it' do + stub_request(:delete, url).to_return(status: 204, body: '', headers: { 'Content-Length' => '5' }) + + expect(unit_transport.delete('api/v1/groups', operation: 'test').status).to eq(204) + end + + it 'leaves a body that is longer than announced alone' do + stub_request(:get, url).to_return(status: 200, body: '0123456789', headers: { 'Content-Length' => '4' }) + + expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') + end + + # The status is what such a response says, and the body is read for + # the message only. + it 'still raises the error its status names for one that is not a 2xx' do + cut_off({ 'Content-Type' => 'application/json' }, status: 404, body: '{"error":') + + expect { unit_transport.get('api/v1/groups', operation: 'find object') }.to raise_error(ZammadAPI::NotFoundError) + end + + it 'logs the response it then refuses' do + log = StringIO.new + cut_off + + expect { unit_transport(logger: Logger.new(log)).get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::ConnectionError) + expect(log.string).to include('Zammad API response: GET api/v1/groups -> 200') + end + end + # Net::HTTP raises Net::OpenTimeout for it, and the default adapter wraps # that into Faraday::ConnectionFailed with every other failure to connect, # so it was reported as an unreachable host and skipped the rescue that is From 310daa81211fa4d8064b508bae79ae0b5ac8f53a Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 12:55:19 +0200 Subject: [PATCH 032/121] fix: refuse a query value that is no Integer or Float `QUERY_VALUE_TYPES` named Numeric, and `stringify_query_value` wrote every number as it prints. Only an Integer and a Float print as the number: client.users.search('smith', ids: [BigDecimal('5')]) # ids[]=0.5e1 which is how an id read from a decimal column went out, and user 5 was not among the hits. A Rational went as `1/2` and a Complex as `1+2i`. The list's own comment promised one spelling Zammad reads back for each type on it. The list names Integer and Float. Any other number is refused with the message every value a query string has no spelling for gets, which now says to pass it as one of the two. A Float that is NaN or infinite is of a type on the list and prints as that word, so it is refused too, by a message of its own. A BigDecimal is not written with `to_s('F')` here. Which of an id and an amount it stands for is the caller's to say, and a body refuses it the same way. --- CHANGELOG.md | 6 ++++ README.md | 10 +++--- lib/zammad_api/transport.rb | 42 +++++++++++++++++++++----- sig/zammad_api/transport.rbs | 1 + spec/unit/zammad_api/transport_spec.rb | 23 +++++++++++++- 5 files changed, 69 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 102f5d1..f6249dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -966,6 +966,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a that names one `Content-Length` and neither a `Content-Encoding` nor a `Transfer-Encoding`; a chunked body cut short raised already. The request is not sent again. +- A query value that is a number and neither an `Integer` nor a `Float` raises + `ArgumentError`, as any other value a query string has no spelling for does. Every + `Numeric` was taken as it prints: `client.users.search('smith', ids: [BigDecimal('5')])`, + with the id read from a decimal column, asked for `ids[]=0.5e1`, and user 5 was not among + the hits. A `Rational` went as `1/2` and a `Complex` as `1+2i`. A `Float` that is `NaN` or + infinite raises as well, where it was sent as that word. ### Changed diff --git a/README.md b/README.md index d70d87a..1b9eaa5 100644 --- a/README.md +++ b/README.md @@ -892,10 +892,12 @@ attribute value goes in the term, a sort in `order`, and paging in `page`, `in_b `find_each`. A user keyword on another resource raises for the same reason: Zammad takes `group_ids` on a ticket search and drops it, so tickets are narrowed by group with the condition above. A `nil` value raises too: there is no query string that means "this field -is null". A value that is not text, a number, `true` or `false` raises as well, alone or -inside a list or a condition: `ids: Set[1, 2]` would be sent as that text, which names no -user, so pass a `Set` or a `Range` as its `to_a`, a time as the text Zammad reads, and a -record as its id. So does a keyword with nothing in it, such as `ids: []`, +is null". A value that is not text, an `Integer`, a `Float`, `true` or `false` raises as +well, alone or inside a list or a condition: `ids: Set[1, 2]` would be sent as that text, +which names no user, so pass a `Set` or a `Range` as its `to_a`, a time as the text Zammad +reads, and a record as its id. A number of another kind counts: `BigDecimal('5')` prints as +`0.5e1`, so pass it as an `Integer` or a `Float`, and a `Float` that is `NaN` or infinite +raises too. So does a keyword with nothing in it, such as `ids: []`, `condition: {}`, or a condition that holds nothing but empty Hashes, which a query string does not write. Zammad reads that as the keyword not having been given, so `search('smith', ids: allowed_ids)` with no id allowed would come back with every user diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 29da904..28b6fc5 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -183,10 +183,16 @@ module Verbs RECORD_ID_TYPES = [Integer, String, Symbol].freeze # What a query value is written as, where it is not a list or a - # structure: text, a number or a boolean. Each has one spelling a query - # string can carry and Zammad reads back. No other object does, and - # `to_s` answers for all of them. - QUERY_VALUE_TYPES = [String, Symbol, Numeric, TrueClass, FalseClass].freeze + # structure: text, an Integer, a Float or a boolean. Each has one + # spelling a query string can carry and Zammad reads back. No other + # object does, and `to_s` answers for all of them. + # + # Not every Numeric, which is what this list named. A number of another + # kind prints as something else: `BigDecimal('5')`, an id read from a + # decimal column, as `0.5e1`, a Rational as `1/2` and a Complex as + # `1+2i`, and Zammad narrowed by that text. A Float that is not finite + # has no spelling either: see {.stringify_query_scalar}. + QUERY_VALUE_TYPES = [String, Symbol, Integer, Float, TrueClass, FalseClass].freeze # What a request body is made of, where it is not a list or a structure: # the values JSON has a type for, and a Symbol, which the generator @@ -344,7 +350,7 @@ def self.stringify_query_value(key, value) when nil then raise ArgumentError, "query parameter #{key} is nil, and Zammad has no way to read that: pass a value, or leave the parameter out" when Hash then stringify_query_hash(value, key) when Array then stringify_query_list(key, value) - when *QUERY_VALUE_TYPES then wire_text(value, "query parameter #{key}") + when *QUERY_VALUE_TYPES then stringify_query_scalar(key, value) else converted = Hash.try_convert(value) || raise(ArgumentError, not_a_query_value_message(key, value)) @@ -352,15 +358,35 @@ def self.stringify_query_value(key, value) end end + # One of {QUERY_VALUE_TYPES} as text. + # + # A Float that is not a number, or not a finite one, is refused. It is + # of a type the list names and prints as `NaN` or `Infinity`, which is + # the text Zammad then narrowed by - the result of a division nothing + # checked, sent as a filter. + # + # @api private + # @return [String] + # @raise [ArgumentError] + def self.stringify_query_scalar(key, value) + if value.is_a?(Float) && !value.finite? + raise ArgumentError, "query parameter #{key} is #{value}, and a query string has no spelling for a Float that is not finite: " \ + 'it would be sent as that text, and Zammad would narrow by it. Pass a number, or leave the parameter out.' + end + + wire_text(value, "query parameter #{key}") + end + # Names the class and does not quote the value, which for a record is # every attribute it carries. # # @api private # @return [String] def self.not_a_query_value_message(key, value) - "query parameter #{key} was given as #{value.class}, and a query string carries text, numbers and booleans, alone " \ - 'or in an Array or a Hash: it would be sent as that object prints, and Zammad would narrow by that text. ' \ - 'Pass a Set or a Range as its to_a, a time as text Zammad reads, such as its iso8601, and a record as its id.' + "query parameter #{key} was given as #{value.class}, and a query string carries text, Integers, Floats and " \ + 'booleans, alone or in an Array or a Hash: it would be sent as that object prints, and Zammad would narrow by that ' \ + 'text. Pass a Set or a Range as its to_a, a number of another kind as an Integer or a Float, a time as text ' \ + 'Zammad reads, such as its iso8601, and a record as its id.' end # Stringifies a list, and refuses one Rails could not read back as the diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 53262a0..eb667a7 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -51,6 +51,7 @@ module ZammadAPI def self.stringify_query: (untyped) -> Hash[String, untyped] def self.stringify_query_hash: (Hash[untyped, untyped], String?) -> Hash[String, untyped] def self.stringify_query_value: (String, untyped) -> untyped + def self.stringify_query_scalar: (String key, untyped value) -> String def self.not_a_query_value_message: (String key, untyped value) -> String def self.stringify_query_list: (String, Array[untyped]) -> Array[untyped] def self.misread_element_message: (String, Symbol) -> String diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index fc22942..c36347c 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require 'bigdecimal' require 'pp' RSpec.describe ZammadAPI::Transport do @@ -177,7 +178,7 @@ { 'a Set' => Set[1, 2], 'a Range' => (1..3), 'a Time' => Time.at(0), 'any other object' => Object.new }.each do |kind, value| it "refuses #{kind} by its class, without quoting it" do expect { described_class.stringify_query(ids: value) } - .to raise_error(ArgumentError, /\Aquery parameter ids was given as #{value.class}, and a query string carries text, numbers and booleans/) { |error| + .to raise_error(ArgumentError, /\Aquery parameter ids was given as #{value.class}, and a query string carries text, Integers, Floats and booleans/) { |error| expect(error.message).not_to include(value.to_s) } end @@ -201,6 +202,26 @@ expect(described_class.stringify_query(a: 'x', b: :y, c: 1, d: 1.5, e: true, f: false)) .to eq({ 'a' => 'x', 'b' => 'y', 'c' => '1', 'd' => '1.5', 'e' => 'true', 'f' => 'false' }) end + + # Every Numeric was taken for a number a query string spells, and + # these print as `0.5e1`, `1/2` and `1+2i`. + { 'a BigDecimal' => BigDecimal('5'), 'a Rational' => Rational(1, 2), 'a Complex' => Complex(1, 2) }.each do |kind, value| + it "refuses #{kind}, which is a number and prints as something else" do + expect { described_class.stringify_query(ids: [value]) } + .to raise_error(ArgumentError, /\Aquery parameter ids\[0\] was given as #{value.class}, .+ a number of another kind as an Integer or a Float/) + end + end + + [Float::NAN, Float::INFINITY, -Float::INFINITY].each do |value| + it "refuses #{value}, which is a Float and no number a query string spells" do + expect { described_class.stringify_query(condition: { weight: value }) } + .to raise_error(ArgumentError, /\Aquery parameter condition\[weight\] is #{value}, and a query string has no spelling for a Float that is not finite/) + end + end + + it 'still writes a Float of any size' do + expect(described_class.stringify_query(a: 0.0, b: -2.5, c: 1e20)).to eq({ 'a' => '0.0', 'b' => '-2.5', 'c' => '1.0e+20' }) + end end # `ActionController::Parameters` is not a Hash. Nested, it was written From 95acc4a377cd849e0d3a2bd12d960d8f1c9dd358 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 14:58:36 +0200 Subject: [PATCH 033/121] fix: leave deep_dup and presence to ActiveSupport --- CHANGELOG.md | 5 +++++ lib/zammad_api/attribute_access.rb | 12 ++++++----- lib/zammad_api/config.rb | 21 +++++++++++-------- sig/zammad_api/attribute_access.rbs | 1 - sig/zammad_api/config.rbs | 2 +- spec/unit/zammad_api/attribute_access_spec.rb | 15 +++++++++++++ spec/unit/zammad_api/config_spec.rb | 14 +++++++++++++ 7 files changed, 54 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f6249dc..e559454 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -972,6 +972,11 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a with the id read from a decimal column, asked for `ids[]=0.5e1`, and user 5 was not among the hits. A `Rational` went as `1/2` and a `Complex` as `1+2i`. A `Float` that is `NaN` or infinite raises as well, where it was sent as that word. +- `deep_dup` of anything that holds a record or an attachment works with ActiveSupport + loaded. A private helper of that name answered in place of the public one ActiveSupport + gives every object, so `{ticket: ticket}.deep_dup` raised + `NoMethodError: undefined attribute deep_dup`, and so did a list of records. + `config.presence` raised the same way, for a private helper called `presence`. ### Changed diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb index 80ea902..8a5ef4b 100644 --- a/lib/zammad_api/attribute_access.rb +++ b/lib/zammad_api/attribute_access.rb @@ -107,7 +107,7 @@ def key?(key) = attributes.key?(key.to_sym) # @return [Hash{Symbol => Object}] a deep copy of all attributes, safe to # modify - def to_h = deep_dup(attributes) + def to_h = DeepCopy.writable_copy(attributes) # @return [Integer, nil] def id = attributes[:id] @@ -333,10 +333,12 @@ def write_attribute(key, _value) # Recursively converts string keys to symbols, including inside arrays, so # that user supplied attributes behave the same as decoded responses, and # freezes the result. See {DeepCopy} for why the walk lives there. + # + # Its inverse, {DeepCopy.writable_copy}, is called where it is needed and + # has no helper here. It had one, named `deep_dup`, and a private method + # of that name answers in place of the public one ActiveSupport gives + # every object and calls on whatever a Hash or an Array holds: so + # `{ticket: ticket}.deep_dup` raised NoMethodError in a Rails app. def frozen_attributes(value) = DeepCopy.frozen_copy(value, symbolize_keys: true) - - # The inverse of {#frozen_attributes}, for handing out a copy that callers - # may treat as their own. - def deep_dup(value) = DeepCopy.writable_copy(value) end end diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index c694d83..12350eb 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -169,11 +169,11 @@ def initialize( # steep:ignore:start super( url: immutable(normalize_url(url)), - user: immutable(presence(user)), - password: immutable(presence(password)), - http_token: immutable(presence(http_token)), - oauth2_token: immutable(presence(oauth2_token)), - user_agent: immutable(presence(user_agent) || DEFAULT_USER_AGENT), + user: immutable(non_empty(user)), + password: immutable(non_empty(password)), + http_token: immutable(non_empty(http_token)), + oauth2_token: immutable(non_empty(oauth2_token)), + user_agent: immutable(non_empty(user_agent) || DEFAULT_USER_AGENT), timeout: timeout, open_timeout: open_timeout, retries: retries, @@ -362,7 +362,7 @@ def printable(key, value) # `end_with?` and die there as a NoMethodError, past the ConfigurationError # a caller had wrapped the constructor in. def normalize_url(value) - raise ConfigurationError, 'missing url in config' if presence(value).nil? + raise ConfigurationError, 'missing url in config' if non_empty(value).nil? raise ConfigurationError, "config url needs to be a string, got #{value.class}" if !value.is_a?(String) raise ConfigurationError, 'config url needs to start with http:// or https://' if !SCHEME_PATTERN.match?(value) # Quoted through the redaction: what follows the scheme here is not a @@ -500,7 +500,7 @@ def header_text(name, value) # moment something tried to log it. The same mistake {#normalize_url} # already refuses for the instance URL. def normalize_proxy(value) - return nil if presence(value).nil? + return nil if non_empty(value).nil? raise ConfigurationError, "config proxy needs to be a string, got #{value.class}" if !value.is_a?(String) value @@ -512,7 +512,7 @@ def normalize_proxy(value) # client is documented to need, from inside the constructor, before any # of the validators below ran. def normalize_adapter(value) - return nil if presence(value).nil? + return nil if non_empty(value).nil? raise ConfigurationError, "config adapter needs to be a symbol or a string, got #{value.class}" if !value.is_a?(Symbol) && !value.is_a?(String) value.to_sym @@ -547,7 +547,10 @@ def validate_logger! raise ConfigurationError, 'config logger needs to respond to debug' end - def presence(value) + # Not called `presence`: that is the name of a public method ActiveSupport + # gives every object, and a private one here answered in its place, so + # `config.presence` raised NoMethodError in a Rails app. + def non_empty(value) return nil if value.nil? return nil if value.respond_to?(:empty?) && value.empty? diff --git a/sig/zammad_api/attribute_access.rbs b/sig/zammad_api/attribute_access.rbs index 8432e07..b0b376b 100644 --- a/sig/zammad_api/attribute_access.rbs +++ b/sig/zammad_api/attribute_access.rbs @@ -35,6 +35,5 @@ module ZammadAPI def attribute_writable?: (Symbol key) -> bool def write_attribute: (Symbol, untyped) -> untyped def frozen_attributes: (untyped) -> untyped - def deep_dup: (untyped) -> untyped end end diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index ad6c79a..58883ca 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -91,7 +91,7 @@ module ZammadAPI def validate_ssl_verify!: () -> void def validate_middleware!: () -> void def validate_logger!: () -> void - def presence: (untyped) -> untyped + def non_empty: (untyped) -> untyped def immutable: (untyped) -> untyped end end diff --git a/spec/unit/zammad_api/attribute_access_spec.rb b/spec/unit/zammad_api/attribute_access_spec.rb index 5761921..1594add 100644 --- a/spec/unit/zammad_api/attribute_access_spec.rb +++ b/spec/unit/zammad_api/attribute_access_spec.rb @@ -444,6 +444,21 @@ def initialize(attributes) end end + # ActiveSupport gives every object a public `deep_dup`, and calls it on + # whatever a Hash or an Array holds. A private helper of that name here + # answered in its place, so `{ticket: ticket}.deep_dup` raised + # NoMethodError. It is not loaded here: what is asked is that the name is + # left to it. + describe 'the names ActiveSupport gives every object' do + it 'defines no deep_dup of its own' do + expect(described_class.private_method_defined?(:deep_dup)).to be(false) + end + + it 'still hands out a deep copy from #to_h' do + expect(record.to_h).to eq(record.attributes).and(satisfy { !it[:preferences][:notes].frozen? }) + end + end + it 'rejects writes by default' do expect { record.name = 'other' }.to raise_error(NoMethodError, /read-only/) end diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 69d3cd6..91da778 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -540,6 +540,20 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) end end + # ActiveSupport gives every object a public `presence`. A private helper of + # that name here answered in its place, so `config.presence` raised + # NoMethodError. It is not loaded here: what is asked is that the name is + # left to it. + describe 'the names ActiveSupport gives every object' do + it 'defines no presence of its own' do + expect(described_class.private_method_defined?(:presence)).to be(false) + end + + it 'still reads an empty option as one that was not given' do + expect(build(http_token: nil, user: 'u', password: 'p', oauth2_token: '', proxy: '')).to have_attributes(oauth2_token: nil, proxy: nil) + end + end + # Faraday turns the userinfo of a URL into a Basic Authorization header, and # its authorization middleware leaves a header that is already set alone - # so the credentials in the URL were sent in place of the configured ones. From 635e89fd23eda16e9260ebffbffdaca9d052d858 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 14:59:43 +0200 Subject: [PATCH 034/121] fix: refuse a logger whose debug requires an argument --- CHANGELOG.md | 7 ++++++- README.md | 7 ++++++- lib/zammad_api/config.rb | 24 +++++++++++++++++++--- sig/zammad_api/config.rbs | 1 + spec/unit/zammad_api/config_spec.rb | 31 +++++++++++++++++++++++++++++ 5 files changed, 65 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e559454..e51277d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a ignored, so an option that is misspelled or no longer supported is no longer silent. - `logger:` takes a `Logger` rather than a boolean flag. `logger: true` used to turn on debug output to `$stderr`; pass `Logger.new($stderr)` for the same thing. Any object - that responds to `debug` is accepted, and anything else raises `ConfigurationError`. + whose `debug` can be called with a block and no argument, as `Logger#debug` is, is + accepted, and anything else raises `ConfigurationError`. - `Collection#each` (`client.x.all`, `client.x.search`) now walks every page. Previously it fetched a single page, so iterating stopped silently at 100 records for `all` and at 10 for `search`. @@ -977,6 +978,10 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a gives every object, so `{ticket: ticket}.deep_dup` raised `NoMethodError: undefined attribute deep_dup`, and so did a list of records. `config.presence` raised the same way, for a private helper called `presence`. +- A logger whose `debug` requires an argument raises `ConfigurationError` when the client + is built. It was accepted, as anything that answers `debug` was, and each line is handed + over as a block: `def debug(message)` raised a bare `ArgumentError` at the first request + and at every one after it. ### Changed diff --git a/README.md b/README.md index 1b9eaa5..7bd665d 100644 --- a/README.md +++ b/README.md @@ -1204,6 +1204,11 @@ client = ZammadAPI::Client.new( ) ``` +Any object will do in place of a `Logger`, as long as its `debug` can be called with a block +and no argument: each line is handed over as a block, so that it is only built where it is +written. One whose `debug` requires an argument raises `ConfigurationError` when the client +is built. + Requests, response statuses and durations are logged at `debug` level. Payload keys, query parameters and headers that look like credentials (`password`, `token`, `secret`, `cookie`, ...) are redacted. That holds for a query string written into the path of a raw request, @@ -1495,7 +1500,7 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | -------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------- | | `Client.new(config_hash)` | `Client.new(**config_hash)` | Options are keyword arguments now, so a Hash has to be splatted | | an unknown option was ignored | raises `ArgumentError: unknown keyword` | A typo'd option used to be dropped without a word | -| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object, so you choose the device and level. Anything that answers `debug` is accepted; `true` raises `ConfigurationError` | +| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object, so you choose the device and level. Anything whose `debug` takes a block, as `Logger#debug` does, is accepted; `true` raises `ConfigurationError` | | `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is `Enumerable` over every record now, so `client.ticket.each` read as if it acted on one ticket. The singular names raise `UnknownResourceError`, which lists the plural ones, and so does `client.resource(:ticket)` | | `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads | | `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised | diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 12350eb..4a74da1 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -50,7 +50,9 @@ module ZammadAPI # adapter is given arguments; one named in +adapter+ as well is # refused when the connection is built # @!attribute [r] logger - # @return [Logger] where debug output goes + # @return [Logger] where debug output goes. Any object will do whose + # +debug+ can be called with a block and no argument, which is how + # each line is handed over Config = Data.define( :url, :user, @@ -541,10 +543,26 @@ def validate_middleware! # In 1.x this option was a flag, so `logger: true` is a plausible thing to # carry over. Without this it would be accepted here and raise NoMethodError # at the first request instead. + # + # Answering `debug` is not the whole of it. The transport calls it the + # way a Logger is called for a line that costs something to build, with + # a block and no argument, so a logger written as `def debug(message)` + # was accepted here and raised a bare ArgumentError at every request. def validate_logger! - return if logger.respond_to?(:debug) + raise ConfigurationError, 'config logger needs to respond to debug' if !logger.respond_to?(:debug) + return if !debug_needs_argument? + + raise ConfigurationError, 'config logger needs a debug that can be called with a block and no argument, as Logger#debug is: ' \ + 'this one requires an argument' + end - raise ConfigurationError, 'config logger needs to respond to debug' + # A logger that answers `respond_to?` for a method it does not have - + # one that forwards through `method_missing` and says so nowhere else - + # cannot be asked, and is taken at its word. + def debug_needs_argument? + logger.method(:debug).parameters.any? { |kind, _| %i[req keyreq].include?(kind) } + rescue NameError + false end # Not called `presence`: that is the name of a public method ActiveSupport diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index 58883ca..bbc5476 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -91,6 +91,7 @@ module ZammadAPI def validate_ssl_verify!: () -> void def validate_middleware!: () -> void def validate_logger!: () -> void + def debug_needs_argument?: () -> bool def non_empty: (untyped) -> untyped def immutable: (untyped) -> untyped end diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 91da778..166aaf5 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -292,6 +292,37 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect { build(logger: true) } .to raise_error(ZammadAPI::ConfigurationError, 'config logger needs to respond to debug') end + + # Each line is handed over as a block, so this was accepted and raised + # a bare ArgumentError at every request. + it 'rejects a debug that requires an argument' do + logger = Class.new { def debug(message) = message }.new + + expect { build(logger: logger) } + .to raise_error(ZammadAPI::ConfigurationError, /\Aconfig logger needs a debug that can be called with a block and no argument/) + end + + it 'rejects a debug that requires a keyword' do + logger = Class.new { def debug(message = nil, level:) = [message, level] }.new + + expect { build(logger: logger) }.to raise_error(ZammadAPI::ConfigurationError, /requires an argument/) + end + + it 'accepts a debug that takes its message as an option, as Logger#debug does' do + logger = Class.new { def debug(message = nil) = message || yield }.new + + expect(build(logger: logger).logger).to be(logger) + end + + # Such a logger cannot be asked what its debug takes. + it 'accepts a logger that forwards debug without having the method' do + logger = Class.new do + def respond_to?(name, *) = name == :debug || super + def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Style/MissingRespondToMissing + end.new + + expect(build(logger: logger).logger).to be(logger) + end end describe 'numeric validation' do From 441cffe8cd3aca6eb48a8cb706e1aacbfcd5dc23 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 15:01:59 +0200 Subject: [PATCH 035/121] fix: download an attachment uncompressed to check its length --- CHANGELOG.md | 7 ++++ .../resources/ticket_article_attachment.rb | 39 ++++++++++++++++--- lib/zammad_api/transport.rb | 11 ++++-- sig/zammad_api/resources/resources.rbs | 6 +++ .../ticket_article_attachment_spec.rb | 32 +++++++++++++++ 5 files changed, 85 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e51277d..18b9fdd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -982,6 +982,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a is built. It was accepted, as anything that answers `debug` was, and each line is handed over as a block: `def debug(message)` raised a bare `ArgumentError` at the first request and at every one after it. +- `attachment.download` asks for the file with `Accept-Encoding: identity`, so that one the + connection was closed under raises `ZammadAPI::ConnectionError` behind a proxy that + compresses as well. `Net::HTTP` asks for gzip by itself and inflates what arrives, without + a word for a stream that stops halfway, and the length of a body under a + `Content-Encoding` is not checked: a text attachment of 180 kB came back as its first + 16 kB. A server that compresses the file all the same is asked a second time without the + header, and what it sends is decoded and not checked, as before. ### Changed diff --git a/lib/zammad_api/resources/ticket_article_attachment.rb b/lib/zammad_api/resources/ticket_article_attachment.rb index fe2ff9a..f28b736 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -21,19 +21,33 @@ def initialize(transport, attributes = {}) @attributes = frozen_attributes(attributes || {}) end + # Asks for the file as it is stored. A response says how long it is in + # the bytes that were sent, and the transport can hold that against + # the bytes in hand only where nothing decoded them on the way: see + # {Transport#missing_bytes}. Left to itself Net::HTTP asks for gzip + # and inflates what arrives, without a word for a stream that stops + # halfway, so a text attachment behind a proxy that compresses came + # back as its first part when the connection was closed under it. + UNENCODED = { 'Accept-Encoding' => 'identity' }.freeze + private_constant :UNENCODED + # Downloads the attachment. # + # The file is asked for with +Accept-Encoding: identity+, so that one + # the connection was closed under is told from a whole one. + # # @return [String] the file contents, in +ASCII-8BIT+ encoding # @raise [ResponseError] when Zammad rejected the request # @raise [ConnectionError] when the connection was closed before the # whole file had arrived. The part that did arrive is not returned. def download - segments = %i[ticket_id article_id id].map { Transport.escape_path_segment(fetch(it)) } - response = @transport.get( - "api/v1/ticket_attachment/#{segments.join('/')}", - operation: 'download attachment', - resource_class: self.class - ) + response = request_file(UNENCODED) + # A server that encodes the body all the same has sent what only + # the adapter reads, and an adapter handed the header leaves that + # to its caller: the bytes would be the compressed ones. Asked + # again the way every other request is, the file is decoded as it + # was before, and its length goes unchecked as it did before. + response = request_file(nil) if response.headers.key?('content-encoding') # Attachments are arbitrary binary data; the transport's charset # guess must not corrupt them. response.raw_body.dup.force_encoding(Encoding::BINARY) @@ -47,6 +61,19 @@ def inspect # @see AttributeAccess#installation def installation = @transport.config.url + + private + + def request_file(headers) + segments = %i[ticket_id article_id id].map { Transport.escape_path_segment(fetch(it)) } + + @transport.get( + "api/v1/ticket_attachment/#{segments.join('/')}", + operation: 'download attachment', + headers: headers, + resource_class: self.class + ) + end end end end diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 28b6fc5..d5d25a5 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1264,10 +1264,13 @@ def whole(response, operation) # # Asked only where the bytes in hand are the bytes that were counted. A # body under a Content-Encoding may have been decoded on the way here, - # by an adapter that leaves both headers as they arrived - Net::HTTP - # drops the one and corrects the other - and one under a - # Transfer-Encoding is not framed by the count at all. A 204 has no - # body whatever a header beside it says. + # by an adapter that leaves both headers as they arrived. The default + # one does: Net::HTTP drops the one and corrects the other while it + # reads the body, and Faraday has taken its copy of the headers by + # then. So a compressed body cut short is not caught here, and + # {Resources::TicketArticleAttachment#download} asks for its file + # uncompressed. A body under a Transfer-Encoding is not framed by the + # count at all, and a 204 has no body whatever a header beside it says. # # Only a body that is short. One that is longer was not cut off. # diff --git a/sig/zammad_api/resources/resources.rbs b/sig/zammad_api/resources/resources.rbs index fabf036..77c9dfb 100644 --- a/sig/zammad_api/resources/resources.rbs +++ b/sig/zammad_api/resources/resources.rbs @@ -204,6 +204,12 @@ module ZammadAPI def initialize: (Transport, ?Hash[untyped, untyped]? attributes) -> void def download: () -> String def inspect: () -> String + + private + + UNENCODED: Hash[String, String] + + def request_file: (Hash[String, String]? headers) -> Response end end end diff --git a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb index 4cf335e..21d112a 100644 --- a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb @@ -113,6 +113,38 @@ .to raise_error(ZammadAPI::ConnectionError, /\ACan't download attachment: the response from .+ ended 994 bytes short of the 1000/) end + # Net::HTTP asks for gzip by itself and inflates what arrives, without a + # word for a stream that stops halfway, and the length of a body that + # was decoded on the way cannot be checked. + it 'asks for the file as it is stored, so that its length can be checked' do + stub = stub_request(:get, download_url).with(headers: { 'Accept-Encoding' => 'identity' }).to_return(status: 200, body: 'contents') + attachment.download + + expect(stub).to have_been_requested + end + + # An adapter handed the header leaves the decoding to its caller, so + # these would have been the compressed bytes. + context 'when the server encodes the file all the same' do + let(:unencoded) { { headers: { 'Accept-Encoding' => 'identity' } } } + + before do + stub_request(:get, download_url).to_return(status: 200, body: 'contents') + stub_request(:get, download_url).with(unencoded).to_return(status: 200, body: "\x1F\x8B\b".b, headers: { 'Content-Encoding' => 'gzip' }) + end + + it 'returns the file from a second request, sent the way every other request is' do + expect(attachment.download).to eq('contents') + end + + it 'asks twice, and once of the two as the file is stored' do + attachment.download + + expect(a_request(:get, download_url)).to have_been_made.twice + expect(a_request(:get, download_url).with(unencoded)).to have_been_made.once + end + end + it 'raises when the attachment is gone' do stub_request(:get, download_url).to_return(json_response({ error: 'not found' }, status: 404)) expect { attachment.download }.to raise_error(ZammadAPI::NotFoundError) From d5375fd96d94ed3bf62f97c4c7d48f3f07e9db84 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 15:02:32 +0200 Subject: [PATCH 036/121] fix: raise ConfigurationError for a url that was left out --- CHANGELOG.md | 3 +++ lib/zammad_api/config.rb | 7 ++++++- spec/unit/zammad_api/client_spec.rb | 5 ++++- spec/unit/zammad_api/config_spec.rb | 5 +++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18b9fdd..5e85343 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -989,6 +989,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `Content-Encoding` is not checked: a text attachment of 180 kB came back as its first 16 kB. A server that compresses the file all the same is asked a second time without the header, and what it sends is decoded and not checked, as before. +- `Client.new` without a `url:` raises `ZammadAPI::ConfigurationError`, as it does for one + that is `nil` or empty and as 1.x did. It raised `ArgumentError: missing keyword: :url`, + past a `rescue ZammadAPI::ConfigurationError` written for an incomplete configuration. ### Changed diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 4a74da1..fc33388 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -149,8 +149,13 @@ def self.merge_options(options, overrides) options.except(*replaced).merge(overrides) end + # `url:` has a default so that leaving it out is answered by + # {#normalize_url}, with the ConfigurationError that building a client is + # documented to raise and that 1.x raised. As a required keyword it was + # Ruby that answered, with `ArgumentError: missing keyword: :url`, past + # the rescue a caller had written for an incomplete configuration. def initialize( - url:, + url: nil, user: nil, password: nil, http_token: nil, diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index 9603233..bbaec0a 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -13,8 +13,11 @@ expect(described_class.new(url: 'http://zammad.test/', http_token: 'token')).to be_a(described_class) end + # A required keyword, this was Ruby's `ArgumentError: missing keyword`, + # past the rescue written for an incomplete configuration. it 'surfaces configuration errors' do - expect { described_class.new(http_token: 'token') }.to raise_error(ArgumentError) + expect { described_class.new(http_token: 'token') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') end it 'rejects a missing url' do diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 166aaf5..7f4788f 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -26,6 +26,11 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') end + it 'rejects a url that was left out' do + expect { described_class.new(http_token: 'token') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') + end + it 'rejects a non-http scheme' do expect { build(url: 'ftp://example.com') } .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https://') From 25022e7da9562514cf9e231a9e386c84278a7ffd Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 15:03:11 +0200 Subject: [PATCH 037/121] test: load the test kit in the client spec that uses it --- spec/unit/zammad_api/client_spec.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index bbaec0a..12d3b71 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require 'zammad_api/test' + RSpec.describe ZammadAPI::Client do let(:url) { "#{ClientHelper::BASE_URL}api/v1/users/1" } From b81744ca8e56100b5f150b12164442d0e853173a Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 15:03:48 +0200 Subject: [PATCH 038/121] fix: read Retry-After in base ten --- CHANGELOG.md | 3 +++ lib/zammad_api/errors.rb | 8 +++++- spec/unit/zammad_api/response_error_spec.rb | 28 +++++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e85343..0d8f5eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -992,6 +992,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `Client.new` without a `url:` raises `ZammadAPI::ConfigurationError`, as it does for one that is `nil` or empty and as 1.x did. It raised `ArgumentError: missing keyword: :url`, past a `rescue ZammadAPI::ConfigurationError` written for an incomplete configuration. +- `RateLimitError#retry_after` reads the header in base ten. A zero in front made the figure + octal: `Retry-After: 010` was 8, and `08` was `nil`, so the `e.retry_after || 60` the + README shows waited a minute. `0x10`, which was 16, is `nil` now. ### Changed diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index cf69ac1..90ae237 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -198,7 +198,13 @@ def retry_after value = headers['retry-after'] return nil if value.nil? - Integer(value, exception: false) + # In base ten, said outright. Left to itself Integer reads a prefix as + # a radix, so `010` was 8 and `08`, which is no octal number, was nil - + # where the retry middleware waited ten seconds and eight - and `0x10` + # was 16, which is no figure this header carries. A base is only taken + # with text, hence the `to_s`: a Response built by hand may hold the + # figure as an Integer. + Integer(value.to_s, 10, exception: false) end end diff --git a/spec/unit/zammad_api/response_error_spec.rb b/spec/unit/zammad_api/response_error_spec.rb index 97ac85c..ad9eee5 100644 --- a/spec/unit/zammad_api/response_error_spec.rb +++ b/spec/unit/zammad_api/response_error_spec.rb @@ -193,5 +193,33 @@ def response(status, body, headers = {}) ) expect(error.retry_after).to be_nil end + + # Integer reads a prefix as a radix unless it is told the base, so a + # zero in front made the figure octal: `010` was 8, and `08` was nil. + it 'reads a figure with a zero in front in base ten' do + figures = %w[010 08 0030].map do |value| + response = ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => value }, body: {}, raw_body: '{}', json: true) + + ZammadAPI::ResponseError.build(response, operation: 'find object').retry_after + end + + expect(figures).to eq([10, 8, 30]) + end + + it 'returns nil for a figure in another base' do + error = ZammadAPI::ResponseError.build( + ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => '0x10' }, body: {}, raw_body: '{}', json: true), + operation: 'find object' + ) + expect(error.retry_after).to be_nil + end + + it 'reads a figure held as an Integer' do + error = ZammadAPI::ResponseError.build( + ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => 30 }, body: {}, raw_body: '{}', json: true), + operation: 'find object' + ) + expect(error.retry_after).to eq(30) + end end end From 4c273fc2df50bfed302bb66b4045f93e80886cce Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 15:04:41 +0200 Subject: [PATCH 039/121] fix: declare the dependency on logger --- CHANGELOG.md | 4 ++++ Gemfile.lock | 1 + zammad_api.gemspec | 4 ++++ 3 files changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d8f5eb..3c31981 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -995,6 +995,10 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `RateLimitError#retry_after` reads the header in base ten. A zero in front made the figure octal: `Retry-After: 010` was 8, and `08` was `nil`, so the `e.retry_after || 60` the README shows waited a minute. `0x10`, which was 16, is `nil` now. +- The gem names `logger` among its dependencies. It requires it, and from Ruby 4.0 on + `logger` is a bundled gem, which Bundler makes loadable only where the bundle names it. + Faraday does from 2.10.0 on, so `require 'zammad_api'` worked by way of it, and raised + `LoadError` in a bundle resolved to Faraday 2.9, which the gem allows. ### Changed diff --git a/Gemfile.lock b/Gemfile.lock index 901d23a..a534278 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -4,6 +4,7 @@ PATH zammad_api (2.0.0.alpha1) faraday (~> 2.9) faraday-retry (~> 2.2) + logger (~> 1.5) GEM remote: https://rubygems.org/ diff --git a/zammad_api.gemspec b/zammad_api.gemspec index ee07fb0..0938378 100644 --- a/zammad_api.gemspec +++ b/zammad_api.gemspec @@ -56,4 +56,8 @@ Gem::Specification.new do |spec| spec.add_dependency 'faraday', '~> 2.9' spec.add_dependency 'faraday-retry', '~> 2.2' + # Required by lib/zammad_api/config.rb. From Ruby 4.0 on it is a bundled + # gem, which Bundler makes loadable only where the bundle names it, and + # Faraday names it from 2.10.0 on: a bundle resolved to 2.9 had none. + spec.add_dependency 'logger', '~> 1.5' end From 5626d5cb25c98702a7ad328c3cb9fcd2768d9a73 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 15:05:05 +0200 Subject: [PATCH 040/121] docs: drop the 1.x collection methods that never existed --- CHANGELOG.md | 3 --- README.md | 1 - 2 files changed, 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c31981..935cf38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,12 +35,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `per_page`. All of them now raise `ArgumentError` rather than being accepted. - `page(number, per_page)` with a block was replaced by `page(number, per_page: size)`, which returns a new collection. `page_next` and `page_prev` were removed. -- `Collection#each_page` was renamed to `#in_batches`, which also takes the page size as - `in_batches(of: 500)`. - `Collection#[]` was removed. It cost a request per index and ignored the page a collection was limited to; use `first`, or `page(n, per_page: 1).first` for one record at an offset. -- `Collection#per_page` and `#current_page` are no longer public. `inspect` reports both. - There is no `per`. The page size belongs to the call that reads: `find_each(batch_size:)` to walk, `in_batches(of:)` to batch, `page(number, per_page:)` for one page. Everything else fetches as many records as the endpoint serves. diff --git a/README.md b/README.md index 7bd665d..f8d4b44 100644 --- a/README.md +++ b/README.md @@ -1513,7 +1513,6 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | `collection.each` stopped after one page | `each` walks every page | Iterating truncated silently at the page size: 100 for `all`, 10 for `search` | | `collection.page(1, 3) { \|r\| ... }` | `collection.page(1, per_page: 3).each { ... }` | `page` now returns a collection instead of mutating and yielding | | `collection.page_next` / `page_prev` | `collection.page(n)` or `in_batches` | Removed; they mutated shared state | -| `collection.each_page { ... }` | `collection.in_batches { ... }` | Ruby already has a name for this | | `collection[3]` | `collection.page(4, per_page: 1).first` | An index that costs a request, and that ignored `page`, was a trap | | `collection.find(1)` | `client.x.find(1)`, or `collection.detect { ... }` | On a collection `find` is `Enumerable#find`, whose argument is an ifnone callable — so an id answered with an Enumerator and made no request. It raises now | | `client.x.all(per_page: 50)` | `client.x.all.page(1, per_page: 50)`, `find_each(batch_size: 50)` | `all` accepted the argument and discarded it; page size belongs to the call that reads | From bf3146b7280da72fd995b77e65535197dc9dc8fb Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 15:05:10 +0200 Subject: [PATCH 041/121] docs: match an expanded group by its name in the README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f8d4b44..565fceb 100644 --- a/README.md +++ b/README.md @@ -575,7 +575,7 @@ in {state: 'closed'} nil in {state: String => state, priority: '3 high'} escalate(state) -in {group: {name: 'Support'}} +in {group: 'Support'} notify_support end ``` From 6f0673990ae33f78de78e0a113342b458d889a4a Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 16:38:08 +0200 Subject: [PATCH 042/121] fix: read a Content-Length a middleware left as an Integer --- CHANGELOG.md | 5 +++++ lib/zammad_api/transport.rb | 6 ++++- spec/unit/zammad_api/transport_spec.rb | 31 ++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 935cf38..8d7ffe0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -996,6 +996,11 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `logger` is a bundled gem, which Bundler makes loadable only where the bundle names it. Faraday does from 2.10.0 on, so `require 'zammad_api'` worked by way of it, and raised `LoadError` in a bundle resolved to Faraday 2.9, which the gem allows. +- A response whose `Content-Length` a middleware left as an Integer is read. `faraday-gzip` + writes the length of what it inflated that way, and the check for a body cut short asked a + regexp of it: every successful request behind `c.request :gzip` raised a bare `TypeError`, + past a `rescue ZammadAPI::Error`. `Response#headers` has every value as a String now, as + it is documented to. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index d5d25a5..70151fb 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1489,8 +1489,12 @@ def apply_authentication(faraday) end end + # The header values as text, as well as the names. Faraday keeps a value + # as whatever wrote it: faraday-gzip sets Content-Length to the Integer + # length of what it inflated, and {#missing_bytes} asked a regexp of that, + # so every 2xx behind such a middleware raised a bare TypeError. def decode(faraday_response) - headers = faraday_response.headers.to_h.transform_keys { it.to_s.downcase }.freeze + headers = faraday_response.headers.to_h.to_h { |name, value| [name.to_s.downcase, value.to_s] }.freeze raw_body = raw_body!(faraday_response.body) body, json = Response.decode_body(headers['content-type'], raw_body) diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index c36347c..e2ba4ac 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1003,6 +1003,37 @@ def cut_off(headers = {}, status: 200, body: '0123456789') end end + # faraday-gzip writes the length of what it inflated as an Integer, and + # a regexp asked of one raised TypeError for every 2xx. + context 'with a Content-Length that a middleware left as an Integer' do + def counting(length) + lambda { |builder| + builder.use(Class.new(Faraday::Middleware) do + define_method(:on_complete) { |env| env.response_headers['Content-Length'] = length } + end) + } + end + + before { stub_request(:get, url).to_return(status: 200, body: '0123456789') } + + it 'returns a body as long as it' do + response = unit_transport(middleware: counting(10)).get('api/v1/groups', operation: 'test') + + expect(response.raw_body).to eq('0123456789') + end + + it 'serves the header as text' do + response = unit_transport(middleware: counting(10)).get('api/v1/groups', operation: 'test') + + expect(response.headers['content-length']).to eq('10') + end + + it 'still raises for a body that is shorter' do + expect { unit_transport(middleware: counting(1000)).get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::ConnectionError, /990 bytes short of the 1000/) + end + end + it 'does not judge a 204, which has no body whatever is announced beside it' do stub_request(:delete, url).to_return(status: 204, body: '', headers: { 'Content-Length' => '5' }) From fcf8b9631e9658d7c6308fb3b29ba5b449586630 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 16:41:38 +0200 Subject: [PATCH 043/121] fix: settle a record whose 2xx answer was cut short --- CHANGELOG.md | 8 ++ README.md | 10 +- examples/error_handling.rb | 2 +- lib/zammad_api/errors.rb | 23 +++- lib/zammad_api/resources/base.rb | 66 +++++++-- .../resources/ticket_article_attachment.rb | 2 +- lib/zammad_api/transport.rb | 20 ++- sig/zammad_api/errors.rbs | 6 + sig/zammad_api/resources/base.rbs | 3 + spec/unit/zammad_api/resources/base_spec.rb | 126 ++++++++++++++++++ spec/unit/zammad_api/transport_spec.rb | 12 ++ 11 files changed, 259 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d7ffe0..7bf0dc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1001,6 +1001,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a regexp of it: every successful request behind `c.request :gzip` raised a bare `TypeError`, past a `rescue ZammadAPI::Error`. `Response#headers` has every value as a String now, as it is documented to. +- A `save` or `destroy` that Zammad answered 2xx leaves the record saved or destroyed where + the answer was cut short of its `Content-Length`, as it does where the answer does not + parse. The error was raised before the record heard of the response: a create answered + 201 left the record looking new, so a second `save` POSTed a second record, an update + kept its changes staged, so the next `save` sent a ticket's `article` and its e-mail + again, and a second `destroy` came back as a 404. The error is + `ZammadAPI::IncompleteResponseError` now, a `ConnectionError` that carries the `response` + as far as it arrived, so a raw `client.post` can tell from the status that it was applied. ### Changed diff --git a/README.md b/README.md index 565fceb..ac7d8d4 100644 --- a/README.md +++ b/README.md @@ -1128,7 +1128,8 @@ ZammadAPI::Error ├── ZammadAPI::ParseError unexpected response shape ├── ZammadAPI::PaginationError endpoint ignored the page parameter ├── ZammadAPI::TransportError -│ ├── ZammadAPI::ConnectionError unreachable host, TLS failure or a response cut short +│ ├── ZammadAPI::ConnectionError unreachable host or TLS failure +│ │ └── ZammadAPI::IncompleteResponseError answered 2xx, body cut short │ └── ZammadAPI::TimeoutError exceeded timeout or open_timeout └── ZammadAPI::ResponseError carries the HTTP response ├── ZammadAPI::ClientError 4xx @@ -1158,6 +1159,13 @@ end `resource_class`. A proxy that returns an HTML error page instead of JSON produces a `ServerError` describing the status, not a JSON parse failure. +A `TransportError` is a request with no whole answer, which is not the same as one Zammad +never saw: a write that timed out may have been applied. `IncompleteResponseError` is the +one case where that is known. Zammad answered 2xx, the connection closed before the body +had arrived, and `e.response` holds the status and what did arrive. A record whose `save` +or `destroy` raises it is left saved or destroyed, so the call is not to be repeated; +`reload` brings in what the lost answer would have. + ### Timeouts and retries A `GET` is retried on connection failures, timeouts and the transient statuses 429, 500, diff --git a/examples/error_handling.rb b/examples/error_handling.rb index 9200c7f..fcb23cb 100755 --- a/examples/error_handling.rb +++ b/examples/error_handling.rb @@ -59,7 +59,7 @@ puts "client error: #{e.status}" rescue ZammadAPI::ServerError => e # any 5xx, including an HTML proxy page puts "server error: #{e.status}" -rescue ZammadAPI::TransportError => e # never reached the server, retries spent +rescue ZammadAPI::TransportError => e # no whole answer arrived, retries spent puts "transport error: #{e.message}" end diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index 90ae237..382b8a2 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -29,9 +29,30 @@ class TransportError < Error; end # Raised when the connection to the Zammad instance could not be # established (DNS, refused connection, TLS failure, ...), or was closed - # before the body of a response had arrived. + # before the body of a response had arrived: see {IncompleteResponseError} + # for the second. class ConnectionError < TransportError; end + # Raised when Zammad answered 2xx and the connection was closed before the + # body it announced had arrived. + # + # A {ConnectionError}, and caught as one. It has a class of its own for the + # one thing that sets it apart from the others: the request was received and + # answered. A write that raises this was applied, so it is not to be sent + # again, and a record that was being saved or destroyed is left as saved or + # destroyed. + class IncompleteResponseError < ConnectionError + # @return [Response, nil] the response as far as it arrived + attr_reader :response + + # @param message [String, nil] + # @param response [Response, nil] + def initialize(message = nil, response: nil) + super(message) + @response = response + end + end + # Raised when a request exceeded {Config#open_timeout} or {Config#timeout}. class TimeoutError < TransportError; end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 279ee3a..b4b0f72 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -573,6 +573,10 @@ def save # # @return [true] # @raise [ResponseError] when Zammad rejected the request + # @raise [IncompleteResponseError] when Zammad stored the record and the + # connection was closed before its answer had arrived. The record is + # persisted and holds what it sent; {#reload} brings in the rest, and + # a record that was being created has no id to be reloaded by. # @see #save def save! raise_if_destroyed!('save') @@ -599,7 +603,7 @@ def save! sent = @attributes if new_record? - response = create_record(sent) + response = applied(sent) { create_record(sent) } else # An existing record is addressed by its id, so establish there is # one before anything here can report success. Only a record left @@ -616,7 +620,7 @@ def save! unsaved = unsaved_attributes(sent) return true if unsaved.empty? - response = update_record(unsaved) + response = applied(sent) { update_record(unsaved) } end replace_attributes!(response, operation: 'save object', sent: sent) @@ -703,17 +707,27 @@ def reload # served. `@baseline` is what the record arrived with, and every other # path through this state moves the two together. # + # Destroyed too where Zammad answered 2xx and the answer did not arrive + # whole, for the reason {#applied} gives: the record is gone, and one + # that still looked live sent a second DELETE, which came back as a 404. + # # @return [true] # @raise [Error] when the record was already destroyed # @raise [ResponseError] when Zammad rejected the request + # @raise [IncompleteResponseError] when Zammad destroyed the record and + # the connection was closed before its answer had arrived. The record + # is {#destroyed?} all the same. def destroy raise_if_destroyed!('destroy') raise_if_new!('destroy') - transport.delete(member_path, operation: 'destroy object', resource_class: self.class) - @destroyed = true - @attributes = @baseline - reset_pending_state! + begin + transport.delete(member_path, operation: 'destroy object', resource_class: self.class) + rescue IncompleteResponseError + mark_destroyed! + raise + end + mark_destroyed! true end @@ -771,6 +785,12 @@ def mark_persisted! @new_record = false end + def mark_destroyed! + @destroyed = true + @attributes = @baseline + reset_pending_state! + end + # A set of attributes a caller handed over, as the Hash it is read as. # # A Hash, or what converts to one. `ActionController::Parameters` is @@ -848,13 +868,41 @@ def attribute_writable?(key) = key != :id # +sent+ is what a save was sent with, and is what tells one from a # read. def replace_attributes!(response, operation:, sent: nil) + mark_answered!(sent) + @attributes = frozen_attributes(response.decoded(:object, operation: operation, resource_class: self.class)) + @baseline = @attributes + reset_pending_state! + end + + # What a 2xx settles before its body is read, and all it settles where + # the body cannot be: see {#replace_attributes!} and {#applied}. + def mark_answered!(sent) # First, while #new_record? still says whether this was a create. acknowledge_changes!(sent) if sent @new_record = false @saved = !sent.nil? - @attributes = frozen_attributes(response.decoded(:object, operation: operation, resource_class: self.class)) - @baseline = @attributes - reset_pending_state! + end + + # The request of a save, with the record settled where Zammad applied + # it and the answer did not arrive whole. + # + # A 2xx whose body stops short of its Content-Length is refused inside + # the transport, so it never came back to {#replace_attributes!}, which + # is where a 2xx that cannot be read settles the record. Raised past it, + # a create answered 201 left the record looking unsaved, and the retried + # `save` POSTed a second one; an update left its whole change set + # staged, so the next `save` sent a ticket's `article` again. The same + # response with a body that does not parse had done neither since + # {#acknowledge_changes!}. + # + # @yieldreturn [Response] + # @return [Response] + # @raise [IncompleteResponseError] once the record is settled + def applied(sent) + yield + rescue IncompleteResponseError + mark_answered!(sent) + raise end # The same argument, for what was staged: a 2xx is Zammad saying it diff --git a/lib/zammad_api/resources/ticket_article_attachment.rb b/lib/zammad_api/resources/ticket_article_attachment.rb index f28b736..0a9fd2e 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -38,7 +38,7 @@ def initialize(transport, attributes = {}) # # @return [String] the file contents, in +ASCII-8BIT+ encoding # @raise [ResponseError] when Zammad rejected the request - # @raise [ConnectionError] when the connection was closed before the + # @raise [IncompleteResponseError] when the connection was closed before the # whole file had arrived. The part that did arrive is not returned. def download response = request_file(UNENCODED) diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 70151fb..0047550 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1195,8 +1195,9 @@ def to_json(state = nil) = as_json.to_json(state) # @return [Response] # @raise [ResponseError] for non-2xx responses # @raise [TimeoutError] when the request timed out - # @raise [ConnectionError] when the instance was unreachable, or the - # connection was closed before the body of a 2xx response had arrived + # @raise [ConnectionError] when the instance was unreachable + # @raise [IncompleteResponseError] when the connection was closed before + # the body of a 2xx response had arrived # # @raise [Error] when the body cannot be encoded as JSON # @@ -1239,15 +1240,22 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou # A 2xx response, once its body is known to have arrived: see # {#missing_bytes}. # + # Raised with the response, as the one {ConnectionError} that has one: + # Zammad answered, so a write was applied, and {Resources::Base#save!} + # and {Resources::Base#destroy} have to hear that to settle the record. + # # @return [Response] - # @raise [ConnectionError] + # @raise [IncompleteResponseError] def whole(response, operation) missing = missing_bytes(response) return response if missing.nil? - raise ConnectionError, "Can't #{operation}: the response from #{config.redacted_url} ended #{missing} bytes short of the " \ - "#{response.headers['content-length']} its Content-Length announces, so the connection was closed " \ - 'before the body had arrived' + raise IncompleteResponseError.new( + "Can't #{operation}: the response from #{config.redacted_url} ended #{missing} bytes short of the " \ + "#{response.headers['content-length']} its Content-Length announces, so the connection was closed " \ + 'before the body had arrived', + response: response + ) end # How many bytes of its body a response stopped short by, where it did. diff --git a/sig/zammad_api/errors.rbs b/sig/zammad_api/errors.rbs index 9760b35..4093c84 100644 --- a/sig/zammad_api/errors.rbs +++ b/sig/zammad_api/errors.rbs @@ -15,6 +15,12 @@ module ZammadAPI class ConnectionError < TransportError end + class IncompleteResponseError < ConnectionError + attr_reader response: Response? + + def initialize: (?String? message, ?response: Response?) -> void + end + class TimeoutError < TransportError end diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 79a274f..0a595cc 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -83,6 +83,7 @@ module ZammadAPI def initialize_copy: (self source) -> void def setup: (Transport, Hash[untyped, untyped] attributes) -> void def mark_persisted!: () -> void + def mark_destroyed!: () -> void def attribute_hash: (untyped given) -> Hash[untyped, untyped] def raise_if_destroyed!: (String action) -> void def raise_if_new!: (String operation) -> void @@ -90,6 +91,8 @@ module ZammadAPI def attribute_writable?: (Symbol key) -> bool def refuse_unwritable!: (Symbol key, untyped value) -> void def replace_attributes!: (Response, operation: String, ?sent: Hash[Symbol, untyped]?) -> void + def mark_answered!: (Hash[Symbol, untyped]? sent) -> void + def applied: (Hash[Symbol, untyped] sent) { () -> Response } -> Response def acknowledge_changes!: (Hash[Symbol, untyped] sent) -> void def reset_pending_state!: () -> void def forget_related_targets: () -> void diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index c2dd158..60e174a 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -1732,4 +1732,130 @@ def self.name expect(other.changes).to eq({}) end end + + # The third answer a write can get that says Zammad applied it and tells + # nothing more: a 2xx whose body stops short of its Content-Length. The + # transport refuses it before the record sees a response, so the record + # was not settled the way it is for a body that does not parse. + describe 'a write whose success body was cut short' do + def cut_short(status) + { status: status, body: '{"id":1,"na', headers: { 'Content-Type' => 'application/json', 'Content-Length' => '30' } } + end + + def swallow + yield + rescue ZammadAPI::IncompleteResponseError + nil + end + + context 'when it was a create' do + subject(:group) { client.groups.new(name: 'Support') } + + before { stub_request(:post, url).with(query: hash_including({})).to_return(cut_short(201)) } + + it 'still reports the response as cut short, with the status Zammad answered' do + expect { group.save }.to raise_error(ZammadAPI::IncompleteResponseError, /19 bytes short of the 30/) { |error| + expect(error.response.status).to eq(201) + } + end + + it 'is caught as the ConnectionError it was before' do + expect { group.save }.to raise_error(ZammadAPI::ConnectionError) + end + + it 'does not leave the record looking unsaved' do + swallow { group.save } + + expect(group.new_record?).to be(false) + end + + it 'does not create a second record when the save is retried' do + 2.times do + group.save + rescue ZammadAPI::Error + nil + end + + expect(a_request(:post, url).with(query: hash_including({}))).to have_been_made.once + end + + it 'refuses the retried save rather than reporting it stored' do + swallow { group.save } + + expect { group.save }.to raise_error(ZammadAPI::Error, /was saved, but the response carried no id/) + end + end + + context 'when it was an update' do + subject(:ticket) { client.tickets.find(1) } + + let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/1" } + + before do + stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, title: 'Help', note: nil })) + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(cut_short(200), json_response({ id: 1, title: 'Renamed' })) + + ticket.article = { body: 'Reset link sent.', type: 'email', to: 'customer@example.com' } + swallow { ticket.save } + end + + it 'no longer holds the changes Zammad acknowledged as staged' do + expect(ticket.changed?).to be(false) + expect(ticket.changes).to eq({}) + end + + it 'does not send the article again with the next save' do + ticket.title = 'Renamed' + ticket.save + + expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { title: 'Renamed' })).to have_been_made.once + expect(a_request(:put, ticket_url).with(query: hash_including({}), body: hash_including('article' => anything))).to have_been_made.once + end + + it 'keeps the id it is addressed by' do + expect(ticket.attributes).to eq(id: 1, title: 'Help', note: nil) + end + end + + context 'when it was a destroy' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Support') } + + before { stub_request(:delete, "#{url}/1").to_return(cut_short(200)) } + + it 'still reports the response as cut short' do + expect { group.destroy }.to raise_error(ZammadAPI::IncompleteResponseError) + end + + it 'leaves the record destroyed' do + swallow { group.destroy } + + expect(group).to be_destroyed + end + + it 'refuses a second destroy rather than surfacing Zammad\'s 404' do + swallow { group.destroy } + + expect { group.destroy }.to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to destroy/) + expect(a_request(:delete, "#{url}/1")).to have_been_made.once + end + + it 'drops what was staged, as a destroy that was answered whole does' do + group.name = 'Renamed' + swallow { group.destroy } + + expect(group.name).to eq('Support') + expect(group.changed?).to be(false) + end + end + + # A read was not applied to anything, and settles nothing. + it 'leaves a record alone whose reload was cut short' do + group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Support') + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(cut_short(200)) + group.name = 'Renamed' + swallow { group.reload } + + expect(group.changes).to eq(name: %w[Support Renamed]) + end + end end diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index e2ba4ac..e566bb9 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -955,6 +955,18 @@ def cut_off(headers = {}, status: 200, body: '0123456789') .to raise_error(ZammadAPI::ConnectionError, %r{\ACan't download attachment: the response from http://zammad\.test/ ended 990 bytes short of the 1000}) end + # The one ConnectionError raised for a request that was answered, and + # the status is what tells a caller its write was applied. + it 'raises it as an IncompleteResponseError that carries the response' do + cut_off({ 'Content-Type' => 'image/png' }) + + expect { unit_transport.get('api/v1/groups', operation: 'download attachment') } + .to raise_error(ZammadAPI::IncompleteResponseError) { |error| + expect(error.response.status).to eq(200) + expect(error.response.raw_body).to eq('0123456789') + } + end + it 'raises for a JSON body that is short, and still parses' do cut_off({ 'Content-Type' => 'application/json' }, body: '[]') From e571d27aa4fc285c555a63016a859909e903d418 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 16:44:04 +0200 Subject: [PATCH 044/121] fix: strip a line break from the end of a header value --- CHANGELOG.md | 6 +++ lib/zammad_api/transport.rb | 35 +++++++++++-- sig/zammad_api/transport.rbs | 1 + spec/unit/zammad_api/test_spec.rb | 6 +++ spec/unit/zammad_api/transport_spec.rb | 71 +++++++++++++++++++++++++- 5 files changed, 112 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bf0dc7..0d35d68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1009,6 +1009,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a again, and a second `destroy` came back as a 404. The error is `ZammadAPI::IncompleteResponseError` now, a `ConnectionError` that carries the `response` as far as it arrived, so a raw `client.post` can tell from the status that it was applied. +- A token, a user agent, an `on_behalf_of` scope or a raw request header that ends in a line + break is handed to the adapter without it. One read from a file usually ends in one, and + it is taken because `Net::HTTP` strips the value. That was left to `Net::HTTP`: an + adapter set with `adapter:` was handed `"Token abc\n"`, and one that writes a header as it + stands ends the line, or the headers, where the value does. `ZammadAPI::Test` recorded the + scope with the break on it too. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 0047550..0e88d89 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -541,7 +541,7 @@ def self.stringify_header_value(name, value) text = wire_text(value, "header #{name}") raise ArgumentError, "header #{name} holds a line break, which a header cannot carry: #{LINE_BREAK_ADVICE}" if line_break?(text) - text + stripped(text) end # What to do about a line break in a header value, said wherever one is @@ -575,6 +575,29 @@ def self.stringify_header_value(name, value) # @return [Boolean] def self.line_break?(text) = /[\r\n]/.match?(text.b.strip) + # A header value without what Net::HTTP strips from around it. + # + # {.line_break?} takes a value that only ends in a line break, because + # Net::HTTP strips one before it writes the header. That is the default + # adapter and not the only one, and the value was handed on with the + # break still on it: to an adapter that writes a header as it stands, + # the break ends the line, and `\r\n\r\n` ends the headers. Stripped + # here, every adapter is handed the value Net::HTTP sent. + # + # Of the bytes, as {.line_break?} asks of them and for its reason. Text + # in an encoding ASCII is no part of is left as it is: its bytes are not + # the ones a request carries, see {.wire_text}. + # + # @api private + # @param text [String] + # @return [String] the text itself where there is nothing to strip + def self.stripped(text) + return text if !text.encoding.ascii_compatible? + + bare = text.b.strip + bare.bytesize == text.bytesize ? text : bare.force_encoding(text.encoding) + end + # The +From+ scope as a transport holds it: text, and a copy of its own. # # Text, because a user id is a documented way to name the user and @@ -615,7 +638,7 @@ def self.stringify_on_behalf_of(identifier) return nil if identifier.nil? raise ArgumentError, not_an_identifier_message(identifier) if RECORD_ID_TYPES.none? { identifier.is_a?(it) } - text = wire_text(identifier, 'on_behalf_of') + text = stripped(wire_text(identifier, 'on_behalf_of')) raise ArgumentError, blank_on_behalf_of_message(identifier) if BLANK.match?(text) raise ArgumentError, "on_behalf_of holds a line break, which the From header cannot carry: #{LINE_BREAK_ADVICE}" if line_break?(text) @@ -1345,7 +1368,7 @@ def build_connection # The encoder is this gem's own: see {QueryEncoder} for the one # structure Faraday's writes so that Rails reads another. request: { timeout: config.timeout, open_timeout: config.open_timeout, params_encoder: QueryEncoder }, - headers: { 'User-Agent' => config.user_agent, 'Accept' => 'application/json' } + headers: { 'User-Agent' => Transport.stripped(config.user_agent), 'Accept' => 'application/json' } ) do |faraday| apply_authentication(faraday) faraday.request :json @@ -1489,10 +1512,12 @@ def redact_config_values(message) # which is kept wherever redaction finds nothing to change. def quoted_spellings(value) = [value, value.inspect[1...-1], value.dump[1...-1]].compact.uniq + # A token as every adapter is to be handed it: see {Transport.stripped}. + # A user and password are sent Base64-encoded, whatever is around them. def apply_authentication(faraday) case config.authentication_scheme - when :http_token then faraday.request :authorization, 'Token', config.http_token - when :oauth2_token then faraday.request :authorization, 'Bearer', config.oauth2_token + when :http_token then faraday.request :authorization, 'Token', Transport.stripped(config.http_token.to_s) + when :oauth2_token then faraday.request :authorization, 'Bearer', Transport.stripped(config.oauth2_token.to_s) else faraday.request :authorization, :basic, config.user, config.password end end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index eb667a7..bf55968 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -57,6 +57,7 @@ module ZammadAPI def self.misread_element_message: (String, Symbol) -> String def self.empty_query_name_message: (String? prefix) -> String def self.stringify_headers: (Hash[untyped, untyped]) -> Hash[String, String] + def self.stripped: (String text) -> String BLANK: Regexp def self.wire_text: (untyped value, String name) -> String LINE_BREAK_ADVICE: String diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 9ba0524..eeefdb5 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -677,6 +677,12 @@ expect(zammad.requests.last.on_behalf_of).to eq('42') end + it 'records a scope that ends in a line break the way the wire carries it' do + client.on_behalf_of("agent@example.com\n").groups.find(1) + + expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') + end + it 'records the scope a client was given, not what its string became afterwards' do login = +'agent@example.com' scoped = client.on_behalf_of(login) diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index e566bb9..15a35ce 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -64,8 +64,65 @@ } end - it 'takes one that only ends in a line break, which Net::HTTP strips' do - expect(described_class.stringify_headers('X-Note' => "abc\n")).to eq('x-note' => "abc\n") + # Net::HTTP strips it, and it was left to: an adapter that does not was + # handed the value with the break on it. + it 'takes one that only ends in a line break, and hands it on without' do + expect(described_class.stringify_headers('X-Note' => "abc\n")).to eq('x-note' => 'abc') + end + + it 'strips what Net::HTTP does from both ends, and nothing inside' do + expect(described_class.stringify_headers('X-Note' => " \tone two\r\n\r\n")).to eq('x-note' => 'one two') + end + + it 'strips a line break after bytes that are invalid in the encoding, and keeps the encoding' do + value = described_class.stringify_headers('X-Note' => "abc\xFF\n").fetch('x-note') + + expect(value).to eq("abc\xFF") + expect(value.encoding).to eq(Encoding::UTF_8) + end + + it 'hands a value with nothing around it on as the String it was given' do + value = 'abc' + + expect(described_class.stripped(value)).to be(value) + end + + # WebMock is asked by Net::HTTP, which has stripped the headers by then. + # A middleware sees them as the adapter is handed them. + context 'with a configured header value that ends in a line break' do + def handed_to_the_adapter(**options) + seen = nil + recorder = Class.new(Faraday::Middleware) do + define_method(:on_request) { |env| seen = env.request_headers.to_h } + end + stub_request(:get, url).to_return(json_response([])) + unit_transport(middleware: ->(builder) { builder.use(recorder) }, **options).get('api/v1/groups', operation: 'test') + seen + end + + it 'hands the adapter an access token without it' do + expect(handed_to_the_adapter(http_token: "abc\n")['Authorization']).to eq('Token abc') + end + + it 'hands the adapter an OAuth2 token without it' do + expect(handed_to_the_adapter(http_token: nil, oauth2_token: "abc\r\n")['Authorization']).to eq('Bearer abc') + end + + it 'hands the adapter a user agent without it' do + expect(handed_to_the_adapter(user_agent: "my-app/1.0\n")['User-Agent']).to eq('my-app/1.0') + end + + it 'hands the adapter a raw request header without it' do + seen = nil + recorder = Class.new(Faraday::Middleware) do + define_method(:on_request) { |env| seen = env.request_headers['x-trace'] } + end + stub_request(:get, url).to_return(json_response([])) + unit_transport(middleware: ->(builder) { builder.use(recorder) }) + .get('api/v1/groups', operation: 'test', headers: { 'X-Trace' => "t\r\n" }) + + expect(seen).to eq('t') + end end it 'carries a header value given in UTF-16 as the same text in UTF-8' do @@ -1693,6 +1750,16 @@ def detailed_message = "unreadable: #{message}" expect { unit_transport.with_on_behalf_of("agent\nadmin") }.to raise_error(ArgumentError, /on_behalf_of holds a line break/) end + # Net::HTTP strips it. The scope was held, and handed to any other + # adapter, with the break on it. + it 'holds an identifier that only ends in a line break without it' do + expect(unit_transport.with_on_behalf_of("agent\n").on_behalf_of).to eq('agent') + end + + it 'refuses an identifier that is nothing once it is stripped' do + expect { unit_transport.with_on_behalf_of("\0") }.to raise_error(ArgumentError, /on_behalf_of needs the login/) + end + it 'refuses a blank identifier given in UTF-16' do expect { unit_transport.with_on_behalf_of(' '.encode('UTF-16LE')) }.to raise_error(ArgumentError, /on_behalf_of needs the login/) end From 1d17b193f783e4cfdbb815f88a1fb21bbbf0067c Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 16:48:05 +0200 Subject: [PATCH 045/121] fix: read only: and except: in a record's as_json --- CHANGELOG.md | 6 +++ README.md | 8 ++- lib/zammad_api/attribute_access.rb | 46 +++++++++++++++-- sig/zammad_api/attribute_access.rbs | 2 +- spec/unit/zammad_api/attribute_access_spec.rb | 51 +++++++++++++++++++ 5 files changed, 107 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d35d68..1290662 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1015,6 +1015,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a adapter set with `adapter:` was handed `"Token abc\n"`, and one that writes a header as it stands ends the line, or the headers, where the value does. `ZammadAPI::Test` recorded the scope with the break on it too. +- `as_json` on a record reads `only:` and `except:`. It dropped its options, so + `user.as_json(except: [:password])` answered with the password, as did a record inside a + Hash or a collection that ActiveSupport serialized with the option, while + `user.to_json(except: [:password])` left it out. `to_json` is written from `as_json` now, + and both take a name as a Symbol or a String: `except: ['password']` filtered nothing in + either. ### Changed diff --git a/README.md b/README.md index ac7d8d4..5759dc5 100644 --- a/README.md +++ b/README.md @@ -729,7 +729,13 @@ JSON.generate(group: client.groups.find(1)) ``` `as_json` returns the same attributes as a Hash, for ActiveSupport and any encoder that -follows its convention. +follows its convention. Both take `only:` and `except:` with attribute names, as Symbols or +Strings: + +```ruby +user.as_json(except: [:password]) +user.to_json(only: %w[id login]) +``` ### Reload and destroy diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb index 8a5ef4b..f319a92 100644 --- a/lib/zammad_api/attribute_access.rb +++ b/lib/zammad_api/attribute_access.rb @@ -175,19 +175,57 @@ def hash # Named the way ActiveSupport and its encoders expect, so that a record # nested inside a structure being serialized renders as its attributes. # + # With the two options those encoders hand on, +only:+ and +except:+. + # They were dropped here: `user.as_json(except: [:password])` answered + # with the password, as did a record inside a Hash or a collection that + # was serialized with the option, while `user.to_json(except: + # [:password])` left it out under ActiveSupport, by way of the Hash it + # is written from. A name is taken as a Symbol or a String, the way + # ActiveModel takes one: the attributes are keyed by Symbols, and a name + # given as a String filtered nothing in {#to_json} either. + # + # @example + # user.as_json(except: [:password]) + # user.as_json(only: %w[id login]) + # + # @param options [Hash, nil] +only:+ or +except:+ with attribute names; + # +only:+ is the one read where both are given # @return [Hash{Symbol => Object}] - def as_json(*) = to_h + def as_json(options = nil) + attributes = to_h + return attributes if !options.is_a?(Hash) + + only = options[:only] + given = only || options[:except] + return attributes if !given + + names = Array(given) #: Array[untyped] + names = names.map { it.to_s.to_sym } + only ? attributes.slice(*names) : attributes.except(*names) + end # Without this, a record would serialize as its +to_s+, because that is # what +Object#to_json+ falls back to. # + # Written from {#as_json} where it is given options, so that the two + # leave out the same attributes whichever is asked. The two options are + # applied here and not handed on: they name attributes of the record, + # ActiveSupport would apply them again to every Hash an attribute holds, + # and the generator of the json gem refuses a keyword it does not know. + # # @example # client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}" # - # @param state [JSON::State, nil] passed by +JSON.generate+ when a record - # is nested in a structure it is serializing + # @param state [JSON::State, Hash, nil] passed by +JSON.generate+ when a + # record is nested in a structure it is serializing, or the options + # {#as_json} reads beside any the generator does # @return [String] the attributes as a JSON object - def to_json(state = nil) = to_h.to_json(state) + def to_json(state = nil) + return to_h.to_json(state) if !state.is_a?(Hash) + + generator_options = state.except(:only, :except) #: untyped + as_json(state).to_json(generator_options) + end def method_missing(name, *args) identifier = name.to_s diff --git a/sig/zammad_api/attribute_access.rbs b/sig/zammad_api/attribute_access.rbs index b0b376b..77d38b9 100644 --- a/sig/zammad_api/attribute_access.rbs +++ b/sig/zammad_api/attribute_access.rbs @@ -18,7 +18,7 @@ module ZammadAPI def ==: (untyped other) -> bool def eql?: (untyped other) -> bool def hash: () -> Integer - def as_json: (*untyped) -> Hash[Symbol, untyped] + def as_json: (?untyped options) -> Hash[Symbol, untyped] def to_json: (?untyped state) -> String def method_missing: (Symbol, *untyped) -> untyped def respond_to?: (untyped name, ?bool include_private) -> bool diff --git a/spec/unit/zammad_api/attribute_access_spec.rb b/spec/unit/zammad_api/attribute_access_spec.rb index 1594add..d5a24f6 100644 --- a/spec/unit/zammad_api/attribute_access_spec.rb +++ b/spec/unit/zammad_api/attribute_access_spec.rb @@ -442,6 +442,57 @@ def initialize(attributes) it 'hands #as_json a copy rather than the frozen attributes' do expect(record.as_json).not_to be_frozen end + + # ActiveSupport hands them to every object it serializes, a record + # inside a Hash or a collection included, and they were dropped: + # `user.as_json(except: [:password])` answered with the password. + context 'with the options an ActiveSupport encoder hands on' do + it 'leaves out what except: names' do + expect(record.as_json(except: [:preferences])).to eq(id: 1, name: 'Support') + end + + it 'keeps only what only: names' do + expect(record.as_json(only: [:id])).to eq(id: 1) + end + + it 'takes one name as well as a list' do + expect(record.as_json(except: :preferences)).to eq(id: 1, name: 'Support') + end + + # The attributes are keyed by Symbols, and a String matched none. + it 'takes a name given as a String' do + expect(record.as_json(except: ['preferences'])).to eq(id: 1, name: 'Support') + expect(record.as_json(only: %w[id name])).to eq(id: 1, name: 'Support') + end + + it 'reads only: where both are given, as ActiveSupport does' do + expect(record.as_json(only: [:id], except: [:id])).to eq(id: 1) + end + + it 'keeps nothing for an only: that names nothing' do + expect(record.as_json(only: [])).to eq({}) + end + + it 'returns every attribute for options that name neither, and for none' do + expect(record.as_json({})).to eq(record.to_h) + expect(record.as_json(nil)).to eq(record.to_h) + end + + it 'still hands over a copy' do + expect(record.as_json(only: [:preferences])[:preferences]).not_to be_frozen + end + + # The json gem raises for a keyword its generator does not know, so + # the two are applied and not handed on. + it 'leaves the same attributes out of #to_json' do + expect(JSON.parse(record.to_json(except: ['preferences']))).to eq('id' => 1, 'name' => 'Support') + expect(JSON.parse(record.to_json(only: [:id]))).to eq('id' => 1) + end + + it 'still hands #to_json the options that are the generator\'s' do + expect(record.to_json(only: [:id], space: ' ')).to eq('{"id": 1}') + end + end end # ActiveSupport gives every object a public `deep_dup`, and calls it on From e8452d35c8800f26511c3a8bc137cbe8a1eeb4b8 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 16:50:16 +0200 Subject: [PATCH 046/121] fix: blank a fragment where a request path is printed --- CHANGELOG.md | 5 +++ lib/zammad_api/transport.rb | 14 ++++++-- spec/unit/zammad_api/transport_spec.rb | 45 ++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1290662..786cc23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1021,6 +1021,11 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `user.to_json(except: [:password])` left it out. `to_json` is written from `as_json` now, and both take a name as a Symbol or a String: `except: ['password']` filtered nothing in either. +- A fragment written into the path of a raw request is blanked where the path is printed: + in the log, in the message of a timeout and in the `operation` of an error. + `client.get('api/v1/x#token=...')` printed the token in all three, since only what + follows a `?` was read for credentials, and a fragment after a query was printed as the + tail of its last value. It is no part of the request, which is sent without it as before. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 0e88d89..8454f92 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -867,16 +867,24 @@ def self.unreadable_path_message(relative) # otherwise. A name that cannot be decoded cannot be read, so its value # is blanked rather than assumed to be harmless. # + # A fragment is blanked whole. What follows a +#+ is no part of the + # request, and Faraday leaves it out of what it sends, but it was + # printed with the path: `api/v1/x#token=...` has no +?+ to be read as a + # query from, and came back as it stood, and after a query the fragment + # was printed as the tail of the last value. Blanked and not dropped, so + # that what is printed still says the path was written with one. + # # Public for {Client}, which names a raw request by its path. # # @api private # @param path [Object] # @return [String] def self.redact_path(path) - base, mark, query = path.to_s.partition('?') - return base if mark.empty? + sent, hash, = path.to_s.partition('#') + base, mark, query = sent.partition('?') + printed = mark.empty? ? base : "#{base}?#{query.split('&', -1).map { redact_query_pair(it) }.join('&')}" - "#{base}?#{query.split('&', -1).map { redact_query_pair(it) }.join('&')}" + hash.empty? ? printed : "#{printed}##{REDACTED}" end # One stretch of a query string between two +&+, as it may be printed. diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 15a35ce..3cb24fe 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -552,6 +552,51 @@ def handed_to_the_adapter(**options) expect(described_class.redact_path('api/v1/x?page=2;q=a;b&c;')).to eq('api/v1/x?page=2;q=a;b&c;') end end + + # No part of the request, and printed with the path all the same. With + # no `?` before it, it was not read as a query, whatever it was named. + context 'with a fragment' do + it 'blanks one written straight after the path' do + expect(described_class.redact_path('api/v1/x#token=s3cret')).to eq('api/v1/x#[REDACTED]') + end + + it 'blanks one that names nothing' do + expect(described_class.redact_path('api/v1/x#s3cret')).to eq('api/v1/x#[REDACTED]') + end + + it 'blanks one after a query, which is still redacted by name' do + expect(described_class.redact_path('api/v1/x?page=2&token=abc#access_token=s3cret')).to eq('api/v1/x?page=2&token=[REDACTED]#[REDACTED]') + end + + it 'does not print one as the tail of the value before it' do + expect(described_class.redact_path('api/v1/x?page=2#s3cret')).to eq('api/v1/x?page=2#[REDACTED]') + end + + it 'reads a ? after the # as part of it' do + expect(described_class.redact_path('api/v1/x#a?page=2')).to eq('api/v1/x#[REDACTED]') + end + + context 'when a raw request is written with one' do + let(:log) { StringIO.new } + + before { stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/x").to_return(json_response({}, status: 404)) } + + it 'keeps it out of the error the request raises' do + expect { unit_client.get('api/v1/x#token=s3cret') } + .to raise_error(ZammadAPI::NotFoundError) { |error| + expect(error.message).not_to include('s3cret') + expect(error.operation).to eq('GET api/v1/x#[REDACTED]') + } + end + + it 'keeps it out of the log' do + expect { unit_client(logger: Logger.new(log)).get('api/v1/x#token=s3cret') }.to raise_error(ZammadAPI::NotFoundError) + + expect(log.string).to include('Zammad API request: GET api/v1/x#[REDACTED]') + expect(log.string).not_to include('s3cret') + end + end + end end # The question the test kit asks, so that it sends again what the wire From 29eec345c9921f24e806250d2819c63a1bcecfb4 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 16:51:17 +0200 Subject: [PATCH 047/121] chore: name irb in the bundle for bin/console --- Gemfile | 3 +++ Gemfile.lock | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/Gemfile b/Gemfile index 2d37c5e..a8d8416 100644 --- a/Gemfile +++ b/Gemfile @@ -19,6 +19,9 @@ group :development, :test do end group :development do + # For bin/console. A bundled gem from Ruby 4.0 on, which Bundler makes + # loadable only where the bundle names it. + gem 'irb', require: false # Static type checking against the signatures in sig/. gem 'rbs', require: false gem 'steep', require: false diff --git a/Gemfile.lock b/Gemfile.lock index a534278..ba12f34 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -21,6 +21,7 @@ GEM rexml csv (3.3.7) diff-lcs (1.6.2) + erb (6.0.7) faraday (2.15.1) faraday-net_http (>= 2.0, < 3.6) json @@ -43,6 +44,12 @@ GEM fileutils (1.8.1) hashdiff (1.3.0) iniparse (1.5.0) + io-console (0.9.5) + irb (1.19.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) json (3.1.0) language_server-protocol (3.17.0.6) lint_roller (1.1.0) @@ -64,6 +71,9 @@ GEM parser (3.3.14.0) ast (~> 2.4.1) racc + pp (0.6.4) + prettyprint + prettyprint (0.2.1) prism (2.1.0) prism (2.1.0-aarch64-linux-gnu) prism (2.1.0-aarch64-linux-musl) @@ -84,7 +94,14 @@ GEM logger prism (>= 1.6.0) tsort + rdoc (8.1.0) + erb + prism (>= 1.6.0) + rbs (>= 4.0.0) + tsort regexp_parser (2.13.4) + reline (0.7.0) + io-console (~> 0.5) rexml (3.4.4) rspec (3.13.2) rspec-core (~> 3.13.0) @@ -174,6 +191,7 @@ PLATFORMS x86_64-linux-musl DEPENDENCIES + irb overcommit rake rbs From 2fca771da2e8a794ad85520cbcfd75f64456d675 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 16:52:33 +0200 Subject: [PATCH 048/121] docs: say a retry wait can exceed timeout by the jitter --- CHANGELOG.md | 3 ++- README.md | 2 +- lib/zammad_api/config.rb | 8 +++++--- lib/zammad_api/transport.rb | 8 ++++++++ 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 786cc23..5fe437c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -639,7 +639,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a price is a URL with a port and an `@` further on, such as `https://host:8443/a@b`, which renders with its host blanked: a colon cannot tell a port from a password, and that is the mistake that leaks nothing. -- A wait before a retry is never longer than `timeout`. The retry middleware sleeps for +- A wait before a retry is bounded by `timeout`, with only the jitter on top of it, at most + half a `retry_interval`. The retry middleware sleeps for whatever a `Retry-After` header says and has no ceiling of its own by default, so a maintenance page answering 503 or a rate limiter answering 429 with `Retry-After: 3600` held the calling thread for an hour per retry — two by default — before raising the error, diff --git a/README.md b/README.md index 5759dc5..17ce41e 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ client = ZammadAPI::Client.from_env(timeout: 300) | `timeout` | `60` | Seconds to wait for a response. | | `open_timeout` | `10` | Seconds to wait for the connection. | | `retries` | `2` | Retry attempts for a `GET` that failed transiently. `0` disables retrying. | -| `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt. No wait is longer than `timeout`. | +| `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt, up to `timeout`. Up to half of it is added to each wait as jitter. | | `ssl_verify` | `true` | Set to `false` only against a server with a self-signed certificate. | | `proxy` | `nil` | Proxy URL. | | `user_agent` | `zammad_api-ruby/` | Value of the `User-Agent` header. | diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index fc33388..0883aa4 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -34,9 +34,11 @@ module ZammadAPI # @!attribute [r] retries # @return [Integer] retry attempts for a request that only reads # @!attribute [r] retry_interval - # @return [Numeric] seconds before the first retry, doubling after that. - # A +Retry-After+ header takes its place, and no wait is longer than - # {#timeout}. + # @return [Numeric] seconds before the first retry, doubling after that + # up to {#timeout}. A +Retry-After+ header takes its place where it + # asks for longer, up to {#timeout} as well. Up to half of this is + # added to a wait that is not a +Retry-After+, as jitter, so one can be + # that much longer than {#timeout}. # @!attribute [r] ssl_verify # @return [Boolean] whether TLS certificates are verified # @!attribute [r] proxy diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 8454f92..99c985a 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1093,6 +1093,14 @@ def self.not_a_json_value_message(value, key) # with is reported as the error it is, with the figure still readable # from {RateLimitError#retry_after}. # + # It bounds the backoff and a +Retry-After+, and not the jitter: the + # middleware adds up to +interval_randomness+ of +interval+ once it has + # applied the ceiling. So a wait of its own is at most +timeout+ and + # half a +retry_interval+, which is a quarter of a second with the + # defaults and five on top of two for `timeout: 2, retry_interval: 10`. + # Lowering the ceiling by that much would refuse a +Retry-After+ that + # is within +timeout+, so the documentation says it instead. + # # Public for {.retried?}, which {Test} asks. # # @api private From 7aaa7bdc2bca5e2297f6b26fc7818df80768b61c Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 16:55:27 +0200 Subject: [PATCH 049/121] docs: run the examples through Bundler from a checkout --- examples/README.md | 7 ++++++- examples/concurrent_sync.rb | 2 +- examples/download_attachments.rb | 2 +- examples/error_handling.rb | 2 +- examples/manual_batches.rb | 2 +- examples/onboard_customer.rb | 2 +- examples/pagination.rb | 2 +- examples/quickstart.rb | 2 +- examples/ticket_report.rb | 2 +- examples/triage_tickets.rb | 2 +- 10 files changed, 15 insertions(+), 10 deletions(-) diff --git a/examples/README.md b/examples/README.md index 4e7052b..c46f245 100644 --- a/examples/README.md +++ b/examples/README.md @@ -8,9 +8,14 @@ reads the credentials from the environment: export ZAMMAD_URL=https://zammad.example.com/ export ZAMMAD_TOKEN=your-access-token -ruby examples/quickstart.rb +bundle exec ruby examples/quickstart.rb ``` +Run from a checkout of this repository, they go through Bundler, which is what puts +`lib/` on the load path: plain `ruby` would load an installed release of the gem, 1.x +included, or none. Copied into a project that has `zammad_api` 2.0 in its bundle, they +run there the same way. + `ZAMMAD_USER` and `ZAMMAD_PASSWORD` work instead of a token, as does `ZAMMAD_OAUTH2_TOKEN`. diff --git a/examples/concurrent_sync.rb b/examples/concurrent_sync.rb index b4ac7f5..45073f3 100755 --- a/examples/concurrent_sync.rb +++ b/examples/concurrent_sync.rb @@ -16,7 +16,7 @@ # ) # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# ruby examples/concurrent_sync.rb +# bundle exec ruby examples/concurrent_sync.rb require 'zammad_api' diff --git a/examples/download_attachments.rb b/examples/download_attachments.rb index 067fa89..1b441b8 100755 --- a/examples/download_attachments.rb +++ b/examples/download_attachments.rb @@ -6,7 +6,7 @@ # Shows walking articles, attachment metadata, and binary-safe downloads. # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# ruby examples/download_attachments.rb 12345 ./downloads +# bundle exec ruby examples/download_attachments.rb 12345 ./downloads require 'zammad_api' require 'fileutils' diff --git a/examples/error_handling.rb b/examples/error_handling.rb index fcb23cb..9af37ef 100755 --- a/examples/error_handling.rb +++ b/examples/error_handling.rb @@ -11,7 +11,7 @@ # may not have arrived. # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# ruby examples/error_handling.rb +# bundle exec ruby examples/error_handling.rb require 'zammad_api' diff --git a/examples/manual_batches.rb b/examples/manual_batches.rb index d9d72f6..2fab1c0 100755 --- a/examples/manual_batches.rb +++ b/examples/manual_batches.rb @@ -5,7 +5,7 @@ # that has to checkpoint and resume, or a producer feeding a queue. # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# ruby examples/manual_batches.rb +# bundle exec ruby examples/manual_batches.rb require 'zammad_api' require 'digest' diff --git a/examples/onboard_customer.rb b/examples/onboard_customer.rb index bcd9892..27c9099 100755 --- a/examples/onboard_customer.rb +++ b/examples/onboard_customer.rb @@ -8,7 +8,7 @@ # as a scoped client and as a block. # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# ruby examples/onboard_customer.rb "Acme Inc" jane@acme.test Jane Doe +# bundle exec ruby examples/onboard_customer.rb "Acme Inc" jane@acme.test Jane Doe require 'zammad_api' diff --git a/examples/pagination.rb b/examples/pagination.rb index a3332d1..2742866 100755 --- a/examples/pagination.rb +++ b/examples/pagination.rb @@ -9,7 +9,7 @@ # index endpoints - unless a call asks for another size. # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# ruby examples/pagination.rb +# bundle exec ruby examples/pagination.rb require 'zammad_api' diff --git a/examples/quickstart.rb b/examples/quickstart.rb index f7c55c3..357d41a 100755 --- a/examples/quickstart.rb +++ b/examples/quickstart.rb @@ -5,7 +5,7 @@ # update it. # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# ruby examples/quickstart.rb +# bundle exec ruby examples/quickstart.rb require 'zammad_api' diff --git a/examples/ticket_report.rb b/examples/ticket_report.rb index c6c3340..f661bfd 100755 --- a/examples/ticket_report.rb +++ b/examples/ticket_report.rb @@ -9,7 +9,7 @@ # backoff before any error reaches this script. # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# ruby examples/ticket_report.rb tickets.csv +# bundle exec ruby examples/ticket_report.rb tickets.csv require 'zammad_api' require 'csv' diff --git a/examples/triage_tickets.rb b/examples/triage_tickets.rb index 8402360..959865e 100755 --- a/examples/triage_tickets.rb +++ b/examples/triage_tickets.rb @@ -7,7 +7,7 @@ # what was modified is sent, and adding an article. # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# ruby examples/triage_tickets.rb +# bundle exec ruby examples/triage_tickets.rb require 'zammad_api' require 'time' From 7dd9e9313096c4aaa4b56ec10cb4e5cc65873f91 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 16:55:51 +0200 Subject: [PATCH 050/121] ci: call the zammad_ref input a branch or a tag --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 152ea0a..219bb00 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ on: workflow_dispatch: inputs: zammad_ref: - description: 'Zammad git ref to run the integration specs against' + description: 'Zammad branch or tag to run the integration specs against (not a commit SHA)' default: 'develop' type: string From b2cd6f8d0dfad1af1a9a9bc3dcf11f18a8def756 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 18:05:58 +0200 Subject: [PATCH 051/121] fix: quote no value where a body cannot be encoded --- CHANGELOG.md | 9 ++++ README.md | 4 +- lib/zammad_api/transport.rb | 60 +++++++++++++++++++--- sig/zammad_api/transport.rbs | 3 ++ spec/unit/zammad_api/transport_spec.rb | 69 ++++++++++++++++++++++++-- 5 files changed, 133 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fe437c..37a4d57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1027,6 +1027,15 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `client.get('api/v1/x#token=...')` printed the token in all three, since only what follows a `?` was read for credentials, and a fragment after a query was printed as the tail of its last value. It is no part of the request, which is sent without it as before. +- The error for a request body that cannot be encoded quotes nothing from the body. Its + message repeated the JSON generator's and kept the generator's error as its cause, and + the generator quotes what it could not write: `client.users.create(login: 'a', password: + "hunter2\xFF")` raised an error whose backtrace printed `Invalid object: "hunter2\xFF"`, + and under json 3 a body naming one key twice was quoted whole in the message. The error + has no cause now and says only what this gem refused itself, by key and class, a Float + that is NaN or infinite included. A body that names one key twice, as `login:` and as + `'login'`, raises `ArgumentError` with both spellings, as a query does; json 2 sent both + and left the choice to Zammad. ### Changed diff --git a/README.md b/README.md index 17ce41e..e6790c8 100644 --- a/README.md +++ b/README.md @@ -383,7 +383,9 @@ the encoder does with one: pass a `Set` or a `Range` as its `to_a`. An object th `to_json` writes itself, a `Time` or a `Date` is sent as its text, which Zammad reads, and what converts to a Hash, such as permitted `ActionController::Parameters`, is sent as that Hash. Where ActiveSupport is loaded, any other object is sent as its `as_json`, as its -`to_json` there would write it. +`to_json` there would write it. A Hash that names one key twice, as `login:` and as +`'login'`, raises `ArgumentError`, as it does in a query. Neither error quotes a value of +the body, so one with a password in it is safe to log. Each returns a `ZammadAPI::Response`, so the status and headers stay reachable: diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 99c985a..6ee11f2 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -199,6 +199,12 @@ module Verbs # writes as text. JSON_VALUE_TYPES = [NilClass, String, Symbol, Integer, Float, TrueClass, FalseClass].freeze + # A body value refused here, before the generator is handed it. Its + # message is this file's own: it names a key and a class and quotes no + # value, which is what tells {.encode_body} it may be printed. + class RefusedValue < StandardError; end + private_constant :RefusedValue + # Objects that are no JSON type and go into a body as they print all the # same, because what they print is the value: Zammad reads a time or a # date attribute from that text. `date` is required above for this list. @@ -970,6 +976,14 @@ def self.redact(value) # A String is passed through, as the middleware passes it: it is the # caller saying the body is already encoded. # + # The error says nothing the generator said, and has no cause. The + # generator quotes what it could not write: a value with invalid bytes + # as `Invalid object: "hunter2\xFF"` in the detailed message, which a + # backtrace prints for a cause too, and a Hash with one key twice whole, + # so a body with a password in it put the password into the log of + # whoever rescued the error. Only what {.json_value} refused itself is + # quoted, and that names a key and a class. + # # Public for the same reason as {.stringify_query}: {Test} refuses what # the wire would refuse. # @@ -979,14 +993,16 @@ def self.redact(value) # @param resource_class [Class, nil] used in the error message # @return [String, nil] nil for a request without a body # @raise [Error] when the body cannot be encoded as JSON + # @raise [ArgumentError] for a Hash in it that names one key twice def self.encode_body(body, operation:, resource_class: nil) return body if body.nil? || body.is_a?(String) JSON.generate(json_value(body, nil)) - rescue JSON::JSONError => e - raise Error, "Can't #{Error.subject_for(operation, resource_class)}: the request body cannot be encoded as JSON (#{e.message}). " \ + rescue RefusedValue, JSON::JSONError => e + detail = " (#{e.message})" if e.is_a?(RefusedValue) + raise Error, "Can't #{Error.subject_for(operation, resource_class)}: the request body cannot be encoded as JSON#{detail}. " \ 'Every value has to be a JSON type, and text has to be valid UTF-8: Base64-encode binary data such as an ' \ - 'attachment, and leave out a Float that is NaN or infinite.' + 'attachment, and leave out a Float that is NaN or infinite.', cause: nil end # A body as the generator may be handed it: every value in it one JSON @@ -999,22 +1015,47 @@ def self.encode_body(body, operation:, resource_class: nil) # what Zammad made of the text was the answer. It is what # {.stringify_query_value} refuses in a query, one request part over. # + # A Float that is not finite is refused here as well, by its key. The + # generator refuses it too, and names no key. + # # @api private # @param value [Object] # @param key [Object, nil] the key the value sits under, for the error # message # @return [Object] - # @raise [JSON::GeneratorError] for a value JSON has no type for, which + # @raise [RefusedValue] for a value JSON has no type for, which # {.encode_body} words like any other body that cannot be encoded + # @raise [ArgumentError] for a Hash that names one key twice def self.json_value(value, key) case value + when Float then value.finite? ? value : raise(RefusedValue, not_a_json_value_message(value, key)) when *JSON_VALUE_TYPES then value - when Hash then value.to_h { |name, nested| [name, json_value(nested, name)] } + when Hash then json_hash(value, key) when Array then value.map { json_value(it, key) } else json_object(value, key) end end + # A Hash with every key as the text the generator writes it as, which + # is its `to_s`, and two keys that are written alike refused. + # + # `{login: 'a', 'login' => 'b'}` is one key twice in JSON. json 3 raises + # for it and quotes the whole Hash, and json 2 wrote both and left the + # choice to the reader, which for Rails is the last. It is refused by + # name, as a query and a record's attributes refuse it: see + # {DuplicateKeys}. + # + # @api private + # @param hash [Hash] + # @param key [Object, nil] the key the Hash sits under + # @return [Hash{String => Object}] + # @raise [ArgumentError] + def self.json_hash(hash, key) + DuplicateKeys + .normalize(hash, prefix: key, noun: 'body key', &:to_s) + .to_h { |name, nested| [name, json_value(nested, name)] } + end + # What is none of the above, as what the object itself says it is, in # the order the object is asked. # @@ -1038,7 +1079,7 @@ def self.json_value(value, key) # # @api private # @return [Object] - # @raise [JSON::GeneratorError] + # @raise [RefusedValue] def self.json_object(value, key) converted = Hash.try_convert(value) return json_value(converted, key) if converted @@ -1048,7 +1089,7 @@ def self.json_object(value, key) case described when *JSON_VALUE_TYPES, Hash, Array then json_value(described, key) when *TEXT_VALUE_TYPES then described - else raise JSON::GeneratorError, not_a_json_value_message(value, key) + else raise RefusedValue, not_a_json_value_message(value, key) end end @@ -1073,7 +1114,10 @@ def self.writes_own_json?(value) # @api private # @return [String] def self.not_a_json_value_message(value, key) - "#{key.nil? ? 'it' : "its key #{key}"} was given as #{value.class}, which is no JSON type and would be sent as that " \ + subject = key.nil? ? 'it' : "its key #{key}" + return "#{subject} was given as #{value}, which JSON has no number for" if value.is_a?(Float) + + "#{subject} was given as #{value.class}, which is no JSON type and would be sent as that " \ 'object prints: pass a Set or a Range as its to_a, a number as an Integer or a Float, and any other object as ' \ 'a Hash of what it holds' end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index bf55968..39124cb 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -33,6 +33,8 @@ module ZammadAPI RECORD_ID_TYPES: Array[Class] QUERY_VALUE_TYPES: Array[Class] JSON_VALUE_TYPES: Array[Class] + class RefusedValue < StandardError + end TEXT_VALUE_TYPES: Array[Class] ABSOLUTE_URL: Regexp RESERVED_HEADERS: Hash[String, String] @@ -75,6 +77,7 @@ module ZammadAPI def self.unreadable_path_message: (String relative) -> String def self.encode_body: (untyped body, operation: String, ?resource_class: Class?) -> String? def self.json_value: (untyped value, untyped key) -> untyped + def self.json_hash: (Hash[untyped, untyped] hash, untyped key) -> Hash[String, untyped] def self.json_object: (untyped value, untyped key) -> untyped def self.writes_own_json?: (untyped value) -> bool def self.not_a_json_value_message: (untyped value, untyped key) -> String diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 3cb24fe..a75f2f9 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -931,9 +931,9 @@ def to_json(*) = '{"from":"to_json"}' .to raise_error(ZammadAPI::Error, /Can't save object: the request body cannot be encoded as JSON/) end - it 'raises a ZammadAPI::Error for a Float that JSON has no spelling for' do + it 'raises a ZammadAPI::Error for a Float that JSON has no spelling for, naming its key' do expect { unit_transport.put('api/v1/groups/1', operation: 'save object', body: { weight: Float::NAN }) } - .to raise_error(ZammadAPI::Error, /NaN not allowed in JSON/) + .to raise_error(ZammadAPI::Error, /cannot be encoded as JSON \(its key weight was given as NaN, which JSON has no number for\)/) end it 'says what to do about binary data' do @@ -960,7 +960,70 @@ def to_json(*) = '{"from":"to_json"}' it 'is raised by a record save carrying such a value' do group = unit_client.groups.new(name: 'Support', weight: Float::INFINITY) - expect { group.save }.to raise_error(ZammadAPI::Error, /Infinity not allowed in JSON/) + expect { group.save }.to raise_error(ZammadAPI::Error, /its key weight was given as Infinity/) + end + + # The generator quotes what it could not write, in its message or in + # the detailed message a backtrace prints for a cause, so the error + # for a body with a password in it carried the password. + context 'with a secret in the value that cannot be encoded' do + let(:secret) { { login: 'a', password: "hunter2\xFF" } } + + def refusal(body) + unit_transport.post('api/v1/users', operation: 'save object', body: body) + rescue ZammadAPI::Error, ArgumentError => e + e + end + + it 'says nothing of the value' do + expect(refusal(secret).full_message(highlight: false)).not_to include('hunter2') + end + + it 'carries no cause that would' do + expect(refusal(secret)).to be_a(ZammadAPI::Error).and have_attributes(cause: nil) + end + + it 'still says what a body has to be' do + expect(refusal(secret).message).to include('cannot be encoded as JSON. Every value has to be a JSON type') + end + end + end + + # One key twice in JSON. json 3 raises for it and quotes the whole Hash, + # password and all, and json 2 wrote both and left the choice to Rails. + context 'with a body that names one key twice' do + let(:body) { { login: 'a', password: 'hunter2', 'login' => 'b' } } + + it 'raises an ArgumentError naming both spellings' do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: body) } + .to raise_error(ArgumentError, /body key login was given twice, as :login and as "login"/) + end + + it 'says nothing of the values beside it' do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: body) } + .to(raise_error { expect(it.full_message(highlight: false)).not_to include('hunter2') }) + end + + it 'raises for one further in, with the key it sits under' do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: { users: [{ user: body }] }) } + .to raise_error(ArgumentError, /body key user\[login\] was given twice/) + end + + it 'raises for two keys that are only written alike' do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: { 1 => 'a', '1' => 'b' }) } + .to raise_error(ArgumentError, /body key 1 was given twice, as 1 and as "1"/) + end + + it 'makes no request' do + expect { unit_transport.post('api/v1/users', operation: 'save object', body: body) }.to raise_error(ArgumentError) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + it 'sends a body whose keys differ as it did' do + stub_request(:post, "#{ClientHelper::BASE_URL}api/v1/users").to_return(json_response({ id: 1 }, status: 201)) + unit_transport.post('api/v1/users', operation: 'save object', body: { login: 'a', 'email' => 'a@b.c', 7 => [{ x: nil }] }) + + expect(a_request(:post, "#{ClientHelper::BASE_URL}api/v1/users").with(body: '{"login":"a","email":"a@b.c","7":[{"x":null}]}')).to have_been_made end end end From 4dd7ad68e6e49efeb855ac7592e801a053ab41b1 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 18:10:57 +0200 Subject: [PATCH 052/121] fix: write no credential into a to_yaml --- CHANGELOG.md | 8 ++++++ README.md | 8 +++--- lib/zammad_api/config.rb | 20 ++++++++++++++ lib/zammad_api/test.rb | 8 ++++++ lib/zammad_api/transport.rb | 13 ++++++++++ sig/zammad_api/config.rbs | 1 + sig/zammad_api/test.rbs | 1 + sig/zammad_api/transport.rbs | 1 + spec/unit/zammad_api/config_spec.rb | 28 ++++++++++++++++++++ spec/unit/zammad_api/test_spec.rb | 24 +++++++++++++++++ spec/unit/zammad_api/transport_spec.rb | 36 ++++++++++++++++++++++++++ 11 files changed, 145 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37a4d57..9f33a69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1036,6 +1036,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a that is NaN or infinite included. A body that names one key twice, as `login:` and as `'login'`, raises `ArgumentError` with both spellings, as a query does; json 2 sent both and left the choice to Zammad. +- `to_yaml` of a configuration, a client, a collection and a record holds no credential. + Psych asks neither `inspect` nor `as_json`: it writes the members of a Data and the + instance variables of an object, and every record holds its transport, whose connection + holds the token and the proxy password. So `record.to_yaml`, which is what Rails' `debug` + view helper and a Delayed::Job handler write, printed both. A configuration is written as + the mapping its JSON holds, and a transport as its URL and the way it authenticates, the + test kit's included. `Marshal.dump` still holds the credentials: it is what a copy is + rebuilt from. ### Changed diff --git a/README.md b/README.md index e6790c8..60d4428 100644 --- a/README.md +++ b/README.md @@ -160,9 +160,11 @@ client = ZammadAPI::Client.from_env(timeout: 300) Credentials are never written to the log, and `client.config` redacts them however it is printed — `inspect`, `to_s` or `pp`, which is what a console shows — and however it is -serialized, with `to_json` or with the `as_json` ActiveSupport asks, so a configuration -object is safe to include in an error report. A client serializes as its URL and the way it -authenticates, and no more. +serialized as text, with `to_json`, with the `as_json` ActiveSupport asks or with `to_yaml`, +so a configuration object is safe to include in an error report. A client serializes as its +URL and the way it authenticates, and no more, and so does the transport a record's YAML +names. `Marshal.dump` is the exception: it writes what the object is rebuilt from, +credentials included. Credentials belong in the options above, not in the URL. `https://user:secret@host/` raises `ZammadAPI::ConfigurationError`, because the HTTP stack would send those as basic diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 0883aa4..55f01f9 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require 'json' require 'logger' require 'uri' @@ -291,6 +292,25 @@ def as_json(*) = to_h.to_h { |key, value| [key, placeholder(key, value) || print # @return [String] {#as_json} as a JSON object def to_json(state = nil) = as_json.to_json(state) + # What Psych writes for a configuration: {#as_json}, as a plain mapping + # of what its JSON reads back as. + # + # Psych asks none of the above. It writes the members of a Data as + # they are, so +config.to_yaml+ held the token, the password and the + # credentials of a proxy in full - the fourth way out of the class + # documented as safe to log, and the one Rails' +debug+ view helper and + # a Delayed::Job handler take. + # + # No tag is written, so the mapping loads as the Hash it is and not as + # a configuration with placeholders where its credentials were. And it + # goes through the JSON, so that nothing in it is an object Psych would + # write by its instance variables in turn. + # + # @api private + # @param coder [Psych::Coder] + # @return [void] + def encode_with(coder) = coder.represent_object(nil, JSON.parse(to_json)) + private # Blanks the +user:password@+ part of a URL, keeping the host visible. diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index 0fd469e..0392a35 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -580,6 +580,14 @@ def initialize(test, on_behalf_of: nil, config: test.config) def with_on_behalf_of(identifier) = self.class.new(test, on_behalf_of: identifier, config: config) + # What the real transport writes for Psych, so that a record's YAML + # is the same under the stand-in and does not carry every stub and + # every recorded request with it. + # + # @param coder [Psych::Coder] + # @return [void] + def encode_with(coder) = coder.represent_object(nil, JSON.parse(::ZammadAPI::Transport.description(config, on_behalf_of).to_json)) + # {Client#with} re-validates the options and hands them here. There is # no connection to rebuild, and the same stand-in keeps answering, but # the configuration is the transport's to carry as well as the diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 6ee11f2..2a70f08 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1265,6 +1265,19 @@ def as_json(*) = Transport.description(config, on_behalf_of) # @return [String] {#as_json} as a JSON object def to_json(state = nil) = as_json.to_json(state) + # What Psych writes for a transport: {#as_json}, as a plain mapping. + # + # Psych writes an object as its instance variables, as ActiveSupport + # does for JSON, and the connection among them holds the token in its + # middleware stack and the proxy password in its options. Every record + # holds its transport, so +record.to_yaml+ wrote both. + # + # @api private + # @param coder [Psych::Coder] + # @return [void] + # @see Config#encode_with + def encode_with(coder) = coder.represent_object(nil, JSON.parse(to_json)) + # Performs a request and raises on anything but a 2xx response. # # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index bbc5476..b1b1c0b 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -67,6 +67,7 @@ module ZammadAPI def pretty_print: (untyped printer) -> void def as_json: (*untyped) -> Hash[Symbol, untyped] def to_json: (?untyped state) -> String + def encode_with: (untyped coder) -> void def to_h: () -> Hash[Symbol, untyped] private diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs index 2925e20..4637253 100644 --- a/sig/zammad_api/test.rbs +++ b/sig/zammad_api/test.rbs @@ -78,6 +78,7 @@ module ZammadAPI def initialize: (Test test, ?on_behalf_of: (String | Integer)?, ?config: Config) -> void def with_on_behalf_of: ((String | Integer)? identifier) -> Test::Transport def with_config: (Config) -> Test::Transport + def encode_with: (untyped coder) -> void def request: (Symbol method, String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 39124cb..eb329eb 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -91,6 +91,7 @@ module ZammadAPI def inspect: () -> String def as_json: (*untyped) -> Hash[Symbol, untyped] def to_json: (?untyped state) -> String + def encode_with: (untyped coder) -> void def request: (Symbol method, String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 7f4788f..67c246a 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require 'pp' +require 'yaml' RSpec.describe ZammadAPI::Config do def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) @@ -576,6 +577,33 @@ def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Sty end end + # Psych writes the members of a Data as they are and asks neither inspect + # nor as_json, so `config.to_yaml` held every credential in full. It is + # what Rails' `debug` view helper and a Delayed::Job handler write. + describe 'serializing as YAML' do + let(:config) { build(http_token: nil, user: 'u', password: 'pw-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') } + + it 'holds no credential in what it writes' do + expect(config.to_yaml).not_to match(/pw-s3cret|pproxy-s3cret/) + end + + it 'writes neither token' do + expect(build(http_token: 'tok-s3cret').to_yaml + build(http_token: nil, oauth2_token: 'oauth-s3cret').to_yaml).not_to match(/tok-s3cret|oauth-s3cret/) + end + + it 'writes what its JSON holds, as a mapping any loader reads' do + expect(YAML.safe_load(config.to_yaml)).to eq(JSON.parse(config.to_json)) + end + + it 'keeps the options that are no secret readable' do + expect(YAML.safe_load(build(timeout: 7).to_yaml)).to include('url' => 'https://zammad.example.com/', 'timeout' => 7, 'http_token' => '[REDACTED]', 'logger' => '#') + end + + it 'stays redacted nested inside another structure' do + expect({ config: config, list: [config] }.to_yaml).not_to match(/pw-s3cret|pproxy-s3cret/) + end + end + # ActiveSupport gives every object a public `presence`. A private helper of # that name here answered in its place, so `config.presence` raised # NoMethodError. It is not loaded here: what is asked is that the name is diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index eeefdb5..b74b4aa 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require 'yaml' require 'zammad_api/test' RSpec.describe ZammadAPI::Test do @@ -795,6 +796,29 @@ end end + # A record holds its transport, and Psych writes an object as its instance + # variables. The real transport writes where it points and how it + # authenticates, and the stand-in's wrote the stand-in: every stub and + # every recorded request, under each record. + describe 'a record written as YAML' do + let(:zammad) { described_class.new(http_token: 'tok-s3cret') } + + it 'names the transport the way the real one does' do + expect(YAML.unsafe_load(client.groups.new(name: 'Support').to_yaml.sub(/\A--- .*$/, '---'))) + .to include('transport' => { 'url' => 'https://zammad.test/', 'auth' => 'http_token' }) + end + + it 'names an on_behalf_of scope' do + expect(client.on_behalf_of('agent@example.com').groups.new(name: 'Support').to_yaml).to include('on_behalf_of: agent@example.com') + end + + it 'holds neither the token nor what was stubbed' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'stubbed-name' }) + + expect(client.groups.new(name: 'Support').to_yaml).not_to match(/tok-s3cret|stubbed-name/) + end + end + # A collection walks until a page repeats, comes back short, or comes back # empty. A stub that served the same records to every page tripped the # first of those, so the obvious way to stand in for a list endpoint made diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index a75f2f9..fa15cad 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -2,6 +2,7 @@ require 'bigdecimal' require 'pp' +require 'yaml' RSpec.describe ZammadAPI::Transport do let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } @@ -1998,6 +1999,41 @@ def detailed_message = "unreadable: #{message}" end end + # Psych writes an object as its instance variables too, and asks neither + # inspect nor as_json. Every record holds its transport. + describe 'serializing as YAML' do + let(:transport) do + unit_transport(http_token: 'tok-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') + end + + it 'is the instance and the authentication scheme, with neither the token nor the proxy password' do + expect(YAML.safe_load(transport.to_yaml)).to eq({ 'url' => 'http://zammad.test/', 'auth' => 'http_token' }) + end + + it 'names an on_behalf_of scope' do + expect(YAML.safe_load(transport.with_on_behalf_of('agent@example.com').to_yaml)).to include('on_behalf_of' => 'agent@example.com') + end + + it 'writes no credential for a record, which holds it' do + written = ZammadAPI::Resources::Group.new(transport, { name: 'Users' }).to_yaml + + expect(written).to include('name: Users') + expect(written).not_to match(/tok-s3cret|pproxy-s3cret/) + end + + it 'writes none for a client or a collection either' do + client = unit_client(http_token: 'tok-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') + + expect(client.to_yaml + client.groups.to_yaml + client.groups.all.to_yaml).not_to match(/tok-s3cret|pproxy-s3cret/) + end + + it 'makes no request' do + unit_client.groups.all.to_yaml + + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end + describe '#with_config' do it 'applies the new configuration' do expect(unit_transport.with_config(ZammadAPI::Config.new(**unit_config(timeout: 7))).config.timeout).to eq(7) From 7b64645e988c7a4cd646ee160d9b254f356dba35 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 18:18:10 +0200 Subject: [PATCH 053/121] fix: sort by id last, so tied records keep their page --- CHANGELOG.md | 10 ++++ README.md | 8 +++ lib/zammad_api/collection.rb | 28 +++++++++- sig/zammad_api/collection.rbs | 1 + spec/unit/zammad_api/collection_spec.rb | 59 ++++++++++++++++++--- spec/unit/zammad_api/resource_proxy_spec.rb | 6 +-- spec/unit/zammad_api/test_spec.rb | 10 ++-- 7 files changed, 106 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f33a69..396b664 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1044,6 +1044,16 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a the mapping its JSON holds, and a transport as its URL and the way it authenticates, the test kit's included. `Marshal.dump` still holds the credentials: it is what a copy is rebuilt from. +- A walk sorted by an attribute that records share hands each record over once. `order` + sent the columns it was given, and Zammad sorts by those and by nothing after them, an + index and a search alike, so PostgreSQL was free to hand rows that tie back in another + order for each page. Against a Zammad that searches through SQL, + `client.tickets.search('*').order(:state_id)` over 214 tickets came back as 214 records + and 151 tickets at every page size tried, and no page repeated another, so nothing + raised. Every sorted request names `id` as its last column now, unless the order names it + already: `order(:state_id)` is sent as `sort_by=state_id,id`, and a stub of the test kit + that is scoped to `sort_by` has to spell it that way. A search that is given no order is + sent none, as before. ### Changed diff --git a/README.md b/README.md index 60d4428..86cfd04 100644 --- a/README.md +++ b/README.md @@ -811,6 +811,14 @@ An attribute on its own sorts ascending and a keyword says which way one runs, a ActiveRecord. A second `order` sorts within the first, so `order(:active).order(name: :desc)` is the third line above. +Every sorted request names `id` as its last column as well, unless the order names it +already: `order(:active)` is sent as `sort_by=active,id`, which is also what the test kit +records. Zammad sorts by the columns it is given and by nothing after them, so records that +tie changed places from one page to the next, and a walk handed one over twice and passed +another by. A search that is given no order is sent none and keeps Zammad's own, latest +`updated_at` first for most resources, which breaks no tie either: give a search an `order` +before walking records that a bulk update left with the same `updated_at`. + Not every endpoint sorts. `/api/v1/tickets` and `/api/v1/users` are always served in id order — their controllers hardcode it and drop `sort_by` along with everything else they do not read — so `order` on those raises `ArgumentError` rather than handing back records diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb index 329d72d..e724a8f 100644 --- a/lib/zammad_api/collection.rb +++ b/lib/zammad_api/collection.rb @@ -825,11 +825,37 @@ def fetch(page, per_page) def page_query(page, per_page) return @query if !@paginated - query = @query.merge(page: page, per_page: per_page) + query = tie_broken.merge(page: page, per_page: per_page) @search && @page.nil? ? query.merge(with_total_count: true) : query end + # The query with +id+ as the last column of the sort it names. + # + # Zammad orders by the columns it is given and by nothing after them, + # an index and a search alike, and PostgreSQL does not hand rows that + # tie back in the same order from one LIMIT and OFFSET to the next. So + # the pages of `order(:state_id)` did not add up to the records: a + # ticket could be on two of them and another on none. A search of 214 + # tickets walked ten at a time came back as 214 records and 151 + # tickets, and no page repeated another, so nothing raised. + # + # Only the request is given the column. What {#order} recorded is what + # the caller wrote, and `order(:name).order(:id)` is still theirs to + # write. A sort that names +id+ anywhere has no ties left to break. + # + # A collection that names no sort is sent none. An index is served by + # id then, and what a search sorts by where it is not told differs by + # resource, so naming a column here would replace that order. + # + # @return [Hash{Symbol => Object}] + def tie_broken + columns = sorted_by + return @query if columns.empty? || columns.key?('id') + + @query.merge(sort_by: [*columns.keys, 'id'].join(','), order_by: [*columns.values, 'asc'].join(',')) + end + # What the repeated-page guard compares two pages by: which records they # hold, where every record says which it is. # diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs index 1eee7ea..1371645 100644 --- a/sig/zammad_api/collection.rbs +++ b/sig/zammad_api/collection.rbs @@ -83,6 +83,7 @@ module ZammadAPI def hits_past?: (Integer covered, Integer? total) -> bool def fetch: (Integer, Integer) -> [ Array[R], Integer, Integer? ] def page_query: (Integer page, Integer per_page) -> Hash[Symbol, untyped] + def tie_broken: () -> Hash[Symbol, untyped] def page_digest: (Array[Hash[Symbol, untyped]] decoded) -> Integer def total_count: () -> Integer? def clamp_per_page: (untyped) -> Integer diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb index de0ffd2..4d954be 100644 --- a/spec/unit/zammad_api/collection_spec.rb +++ b/spec/unit/zammad_api/collection_spec.rb @@ -486,36 +486,73 @@ def sorted_request(sort_by, order_by) it 'sorts ascending by an attribute named on its own' do collection.order(:name).to_a - expect(sorted_request('name', 'asc')).to have_been_made + expect(sorted_request('name,id', 'asc,asc')).to have_been_made end it 'sorts the way a keyword says' do collection.order(name: :desc).to_a - expect(sorted_request('name', 'desc')).to have_been_made + expect(sorted_request('name,id', 'desc,asc')).to have_been_made end # Zammad pairs the two lists by position and skips an attribute that has # no direction, so each attribute is sent with one. it 'sorts by several attributes, each with a direction' do collection.order(:active, name: :desc).to_a - expect(sorted_request('active,name', 'asc,desc')).to have_been_made + expect(sorted_request('active,name,id', 'asc,desc,asc')).to have_been_made end it 'takes an attribute and a direction as strings' do collection.order('active', 'name' => 'DESC').to_a - expect(sorted_request('active,name', 'asc,desc')).to have_been_made + expect(sorted_request('active,name,id', 'asc,desc,asc')).to have_been_made end it 'sorts within an earlier order when chained' do collection.order(:active).order(name: :desc).to_a - expect(sorted_request('active,name', 'asc,desc')).to have_been_made + expect(sorted_request('active,name,id', 'asc,desc,asc')).to have_been_made end it 'keeps the sort on every page it walks' do stub_request(:get, url).with(query: hash_including('page' => '1')).to_return(json_response(full_page)) collection.order(:name).to_a - expect(sorted_request('name', 'asc').with(query: hash_including('page' => '2'))).to have_been_made + expect(a_request(:get, url).with(query: hash_including('sort_by' => 'name,id', 'order_by' => 'asc,asc', 'page' => '2'))).to have_been_made + end + + # Zammad orders by the columns it is given and by nothing after them, and + # PostgreSQL does not hand rows that tie back in the same order from one + # LIMIT and OFFSET to the next. Seen against a Zammad that searches + # through SQL: 214 tickets sorted by state_id and walked ten at a time + # came back as 214 records and 151 tickets. + context 'with records that tie on what they are sorted by' do + it 'sorts them by id last, so that they keep one order from page to page' do + collection.order(:active).to_a + expect(sorted_request('active,id', 'asc,asc')).to have_been_made + end + + it 'does so for a single page, whose number means nothing otherwise' do + collection.order(:active).page(3, per_page: 10).to_a + expect(a_request(:get, url).with(query: hash_including('sort_by' => 'active,id', 'order_by' => 'asc,asc', 'page' => '3'))).to have_been_made + end + + it 'adds nothing to a sort by id' do + collection.order(id: :desc).to_a + expect(sorted_request('id', 'desc')).to have_been_made + end + + it 'adds nothing where id is named among the attributes, wherever it stands' do + collection.order(:id, name: :desc).to_a + expect(sorted_request('id,name', 'asc,desc')).to have_been_made + end + + it 'leaves a further order by id to the caller' do + collection.order(:active).order(id: :desc).to_a + expect(sorted_request('active,id', 'asc,desc')).to have_been_made + end + + it 'sends no sort for a collection that asked for none' do + collection.to_a + expect(a_request(:get, url).with(query: hash_including({})) { !it.uri.query.match?(/sort_by|order_by/) }).to have_been_made + end end it 'keeps the sort on an explicit page' do @@ -605,9 +642,17 @@ def sorted_request(sort_by, order_by) it 'sorts, though the index of the same resource does not' do client.tickets.search('printer').order(created_at: :desc).to_a - expect(a_request(:get, search_url).with(query: hash_including('query' => 'printer', 'sort_by' => 'created_at', 'order_by' => 'desc'))) + expect(a_request(:get, search_url).with(query: hash_including('query' => 'printer', 'sort_by' => 'created_at,id', 'order_by' => 'desc,asc'))) .to have_been_made end + + # What a search sorts by where it is not told differs by resource, so a + # column named here would replace that order. + it 'sends no sort for a search that asked for none' do + client.tickets.search('printer').to_a + + expect(a_request(:get, search_url).with(query: hash_including({})) { !it.uri.query.match?(/sort_by|order_by/) }).to have_been_made + end end # Pointing at a search would send the caller in a circle where the diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 26f8dc5..4d1dc3f 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -563,7 +563,7 @@ def default_per_page = ZammadAPI::Resources::Group.page_limit describe '#order' do it 'returns a sorted collection of every record' do stub = stub_request(:get, url) - .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s, 'sort_by' => 'name', 'order_by' => 'desc' }) + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s, 'sort_by' => 'name,id', 'order_by' => 'desc,asc' }) .to_return(json_response([])) proxy.order(name: :desc).to_a @@ -875,7 +875,7 @@ def stub_last_page(page, records, per_page: default_per_page) ids << 2 search.to_a - expect(a_request(:get, users_search).with(query: hash_including('ids' => ['1'], 'page' => '2', 'sort_by' => 'login'))) + expect(a_request(:get, users_search).with(query: hash_including('ids' => ['1'], 'page' => '2', 'sort_by' => 'login,id'))) .to have_been_made end @@ -1129,7 +1129,7 @@ def self.name = 'Role' it 'sorts through order on the collection it returns' do stub = stub_request(:get, "#{url}/search") - .with(query: hash_including('query' => 'support', 'sort_by' => 'name', 'order_by' => 'asc')) + .with(query: hash_including('query' => 'support', 'sort_by' => 'name,id', 'order_by' => 'asc,asc')) .to_return(json_response([])) proxy.search('support').order(:name).to_a diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index b74b4aa..5f96700 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -449,19 +449,19 @@ describe 'query matching' do it 'matches a stub that names a subset of the parameters' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name,id' }) expect(client.groups.order(:name).first.id).to eq(1) end it 'does not answer a request without those parameters' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name,id' }) expect { client.groups.all.to_a }.to raise_error(described_class::UnstubbedRequestError) end it 'ignores the parameters the client adds itself' do - zammad.stub(:get, 'api/v1/groups', body: [], query: { sort_by: 'name' }) + zammad.stub(:get, 'api/v1/groups', body: [], query: { sort_by: 'name,id' }) expect { client.groups.order(:name).to_a }.not_to raise_error end @@ -510,8 +510,8 @@ end it 'still sequences two stubs that share a scope' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) - zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }], query: { sort_by: 'name' }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name,id' }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }], query: { sort_by: 'name,id' }) expect(client.groups.all.order(:name).page(1, per_page: 1).map(&:id)).to eq([1]) expect(client.groups.all.order(:name).page(1, per_page: 1).map(&:id)).to eq([2]) From a24cfb3aba1257ee165f54e43d34f4851c07eb8f Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 18:19:43 +0200 Subject: [PATCH 054/121] fix: refuse a url with no host before its port --- CHANGELOG.md | 6 ++++++ lib/zammad_api/config.rb | 20 +++++++++++++++++++- sig/zammad_api/config.rbs | 1 + spec/unit/zammad_api/config_spec.rb | 21 +++++++++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 396b664..5ecfcaa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1054,6 +1054,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a already: `order(:state_id)` is sent as `sort_by=state_id,id`, and a stub of the test kit that is scoped to `sort_by` has to spell it that way. A search that is given no order is sent none, as before. +- A url with nothing where the host belongs, such as `http://:3000/`, raises + `ZammadAPI::ConfigurationError`. It is what `"http://#{ENV['ZAMMAD_HOST']}:3000/"` comes to + with the variable unset, and it was accepted, as 1.x accepted it: the check asked only + that something follows the scheme. `Net::HTTP` connects to localhost for an empty host, + so the client sent every request, and the token with it, to whatever listened on that + port of the machine it ran on. ### Changed diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 55f01f9..2fbc7e6 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -396,7 +396,7 @@ def normalize_url(value) raise ConfigurationError, 'config url needs to start with http:// or https://' if !SCHEME_PATTERN.match?(value) # Quoted through the redaction: what follows the scheme here is not a # host, and may be the credentials of a url with a slash too many. - raise ConfigurationError, "config url needs a host after the scheme, got #{redact_userinfo(value).inspect}" if !URL_PATTERN.match?(value) + raise ConfigurationError, "config url needs a host after the scheme, got #{redact_userinfo(value).inspect}" if !URL_PATTERN.match?(value) || hostless?(value) raise ConfigurationError, inline_credentials_message(value) if inline_credentials?(value) # A trailing slash keeps Zammad installations served from a sub-path @@ -412,6 +412,24 @@ def normalize_url(value) path.end_with?('/') ? value : "#{path}/#{separator}#{rest}" end + # Whether what follows the scheme names no host, though something + # stands there: a port alone, as in +http://:3000/+. + # + # It is what `"http://#{ENV['ZAMMAD_HOST']}:3000/"` comes to where the + # variable is not set, and {URL_PATTERN} asks only for a character that + # ends no authority. Net::HTTP connects to localhost for an empty host, + # so the client was built and then sent every request, with the token + # in its header, to whatever listens on that port of the machine it + # runs on. + # + # Asked of URI for the reason {#inline_credentials?} is, and a URL that + # URI cannot read is left to the connection for the same one. + def hostless?(value) + URI.parse(value).host.to_s.empty? + rescue URI::InvalidURIError + false + end + # Whether the URL carries a +user:password@+ of its own. # # Asked of URI, because that is the parser Faraday reads the URL with: diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index b1b1c0b..c30b4ac 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -79,6 +79,7 @@ module ZammadAPI def placeholder: (Symbol, untyped) -> String? def printable: (Symbol, untyped) -> untyped def normalize_url: (untyped) -> String + def hostless?: (String) -> bool def inline_credentials?: (String) -> bool def inline_credentials_message: (String) -> String def validate_credentials!: () -> void diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 67c246a..61d2ccd 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -56,6 +56,27 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) .to raise_error(ZammadAPI::ConfigurationError, 'config url needs a host after the scheme, got "https://"') end + # What `"http://#{ENV['ZAMMAD_HOST']}:3000/"` comes to with the variable + # unset. Net::HTTP connects to localhost for an empty host, so every + # request went, token and all, to whatever listens on that port. + ['http://:3000/', 'http://:3000', 'https://:443/zammad/', 'http://:/'].each do |url| + it "rejects #{url}, which has a port where the host belongs" do + expect { build(url: url) } + .to raise_error(ZammadAPI::ConfigurationError, "config url needs a host after the scheme, got #{url.inspect}") + end + end + + it 'rejects a url with a user and no host, without quoting the user' do + expect { build(url: 'http://admin:url-s3cret@:3000/') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url needs a host after the scheme, got "http://[REDACTED]@:3000/"') + end + + ['http://localhost:3000/', 'http://[::1]:3000/', 'http://192.168.0.1:8080/api/', 'http://host:/'].each do |url| + it "accepts #{url}, which names one" do + expect(build(url: url).url).to eq(url) + end + end + # The value was quoted as it stood, and what stands where the host # belongs may be credentials: a slash too many, and the userinfo is the # start of a path as far as the syntax goes. From dc408fe75f2b7f24ab25261dd24ca59e4e617a6b Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 18:22:50 +0200 Subject: [PATCH 055/121] fix: refuse a timeout the HTTP stack cannot wait for --- CHANGELOG.md | 8 ++++++ README.md | 4 +-- lib/zammad_api/config.rb | 18 +++++++++++++ sig/zammad_api/config.rbs | 2 ++ spec/unit/zammad_api/config_spec.rb | 39 +++++++++++++++++++++++++++++ 5 files changed, 69 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ecfcaa..82dbe64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1060,6 +1060,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a that something follows the scheme. `Net::HTTP` connects to localhost for an empty host, so the client sent every request, and the token with it, to whatever listened on that port of the machine it ran on. +- A `timeout`, `open_timeout` or `retry_interval` the HTTP stack cannot wait for raises + `ZammadAPI::ConfigurationError`. Any positive number was accepted, so `timeout: + Float::INFINITY`, the natural way to ask for the 1.x behaviour of no timeout, built a + client whose every request raised a bare `RangeError` from inside `Net::HTTP`, as did a + figure past what a C long holds, and an infinite `retry_interval` raised it from the wait + before the first retry. The three take at most 100000000 seconds, a little over three + years, which is the longest wait every platform takes: macOS refused a longer one, and + that came back as a `ConnectionError` calling the instance unreachable. ### Changed diff --git a/README.md b/README.md index 86cfd04..b35ff97 100644 --- a/README.md +++ b/README.md @@ -147,8 +147,8 @@ client = ZammadAPI::Client.from_env(timeout: 300) | `oauth2_token` | `nil` | OAuth2 bearer token. | | `user` | `nil` | Login for basic authentication. | | `password` | `nil` | Password for basic authentication. | -| `timeout` | `60` | Seconds to wait for a response. | -| `open_timeout` | `10` | Seconds to wait for the connection. | +| `timeout` | `60` | Seconds to wait for a response, at most 100000000. No value means no timeout. | +| `open_timeout` | `10` | Seconds to wait for the connection, with the same limit. | | `retries` | `2` | Retry attempts for a `GET` that failed transiently. `0` disables retrying. | | `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt, up to `timeout`. Up to half of it is added to each wait as jitter. | | `ssl_verify` | `true` | Set to `false` only against a server with a self-signed certificate. | diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 2fbc7e6..0db6ff0 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -87,6 +87,12 @@ class Config # Seconds to wait before the first retry; doubles on each attempt. DEFAULT_RETRY_INTERVAL = 0.5 + # The longest wait a configuration takes, in seconds: a little over + # three years, and the longest one every platform takes. macOS refuses a + # wait on a socket that is one second longer, and what came of it was a + # ConnectionError calling the instance unreachable. + MAX_SECONDS = 100_000_000 + # Attributes whose values must never be rendered. REDACTED_ATTRIBUTES = %i[password http_token oauth2_token].freeze @@ -477,6 +483,11 @@ def validate_credentials! raise ConfigurationError, 'missing password in config' if password.nil? end + def too_long_message(name, value) + "config #{name} needs to be at most #{MAX_SECONDS} seconds, got #{value}. No value stands for no #{name == :retry_interval ? 'limit' : 'timeout'}: " \ + 'pass the longest wait that is acceptable.' + end + def multiple_credentials_message(schemes) named = schemes.map { CREDENTIAL_OPTIONS.fetch(it).join(' and ') }.join(', ') @@ -491,9 +502,16 @@ def multiple_credentials_message(schemes) # written to close. def positive_number?(value) = value.is_a?(Numeric) && value.respond_to?(:positive?) && value.positive? + # A number has to be one the HTTP stack can wait for as well, and that + # is not every positive one. `timeout: Float::INFINITY`, the natural way + # to ask for no timeout, which is what 1.x had, was accepted, and every + # request then raised a bare RangeError from inside Net::HTTP, as it did + # for a figure past what a C long holds. An infinite +retry_interval+ + # raised the same from the sleep before the first retry. def validate_numbers! { timeout: timeout, open_timeout: open_timeout, retry_interval: retry_interval }.each do |name, value| raise ConfigurationError, "config #{name} needs to be a positive number" if !positive_number?(value) + raise ConfigurationError, too_long_message(name, value) if value > MAX_SECONDS end raise ConfigurationError, 'config retries needs to be a non-negative integer' if !retries.is_a?(Integer) || retries.negative? diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index c30b4ac..2b04aad 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -11,6 +11,7 @@ module ZammadAPI DEFAULT_OPEN_TIMEOUT: Integer DEFAULT_RETRIES: Integer DEFAULT_RETRY_INTERVAL: Float + MAX_SECONDS: Integer REDACTED_ATTRIBUTES: Array[Symbol] REDACTION: String DEFAULT_USER_AGENT: String @@ -86,6 +87,7 @@ module ZammadAPI def multiple_credentials_message: (Array[Symbol] schemes) -> String def positive_number?: (untyped) -> bool def validate_numbers!: () -> void + def too_long_message: (Symbol name, untyped value) -> String def validate_user_agent!: () -> void HEADER_OPTIONS: Array[Symbol] def validate_header_options!: () -> void diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 61d2ccd..30a16fe 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -376,6 +376,45 @@ def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Sty .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') end + # The natural way to ask for no timeout, which is what 1.x had. Accepted, + # every request raised a bare RangeError from inside Net::HTTP. + it 'rejects an infinite timeout' do + expect { build(timeout: Float::INFINITY) } + .to raise_error(ZammadAPI::ConfigurationError, /\Aconfig timeout needs to be at most 100000000 seconds, got Infinity\. No value stands for no timeout/) + end + + it 'rejects an infinite open_timeout' do + expect { build(open_timeout: Float::INFINITY) } + .to raise_error(ZammadAPI::ConfigurationError, /config open_timeout needs to be at most 100000000 seconds, got Infinity/) + end + + # It raised the same from the sleep before the first retry. + it 'rejects an infinite retry_interval' do + expect { build(retry_interval: Float::INFINITY) } + .to raise_error(ZammadAPI::ConfigurationError, /config retry_interval needs to be at most 100000000 seconds, got Infinity\. No value stands for no limit/) + end + + it 'rejects a timeout too large for a C long' do + expect { build(timeout: 10**20) } + .to raise_error(ZammadAPI::ConfigurationError, /config timeout needs to be at most 100000000 seconds, got 100000000000000000000/) + end + + # macOS refuses a wait on a socket that is longer, and that came back as + # a ConnectionError calling the instance unreachable. + it 'rejects a timeout one second past the longest every platform takes' do + expect { build(timeout: 100_000_001) }.to raise_error(ZammadAPI::ConfigurationError, /at most 100000000 seconds/) + end + + it 'accepts the longest one' do + expect(build(timeout: 100_000_000, open_timeout: 100_000_000.0, retry_interval: Rational(100_000_000))) + .to have_attributes(timeout: 100_000_000, open_timeout: 100_000_000.0, retry_interval: Rational(100_000_000)) + end + + it 'still says a Float that is no number needs to be one' do + expect { build(timeout: Float::NAN) } + .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') + end + it 'rejects negative retries' do expect { build(retries: -1) } .to raise_error(ZammadAPI::ConfigurationError, 'config retries needs to be a non-negative integer') From 80734b7175c5e1e47f7be0bd706f901ed8bb5666 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 18:25:35 +0200 Subject: [PATCH 056/121] fix: refuse a Hash with no value in a query --- CHANGELOG.md | 6 +++ README.md | 2 +- lib/zammad_api/resource_proxy.rb | 15 ++++--- lib/zammad_api/transport.rb | 48 +++++++++++++++++++-- sig/zammad_api/transport.rbs | 2 + spec/unit/zammad_api/resource_proxy_spec.rb | 9 ++++ spec/unit/zammad_api/test_spec.rb | 5 +++ spec/unit/zammad_api/transport_spec.rb | 46 ++++++++++++++++++++ 8 files changed, 123 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82dbe64..f572785 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1068,6 +1068,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a before the first retry. The three take at most 100000000 seconds, a little over three years, which is the longest wait every platform takes: macOS refused a longer one, and that came back as a `ConnectionError` calling the instance unreachable. +- A Hash with no value in it raises `ArgumentError` wherever it stands in the `query:` of a + raw request. A query string writes nothing for one, so + `client.get(path, query: {filter: {}, a: 1})` asked for `?a=1`, and Zammad answered as if + the parameter had been left out. A `nil` and an empty Hash inside a list were refused for + that reason already, and a `search` refused an empty `condition`; a condition holding an + empty Hash beside one that is written lost it in the same way, and is refused now too. ### Changed diff --git a/README.md b/README.md index b35ff97..bbcf14e 100644 --- a/README.md +++ b/README.md @@ -876,7 +876,7 @@ client.tickets.search('printer', condition: { A query string does not mark where one element of a list ends, and Rails begins a new one only at a key the element before it has too. The elements above all carry `operator`, and the client writes that first, so they arrive as written. A list whose elements share no -such key, a list directly inside a list, an empty Hash inside a list and a key with an empty +such key, a list directly inside a list, a Hash with no value in it and a key with an empty name cannot be carried at all and raise `ArgumentError`; the JSON body of `client.post` takes any structure. diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index 2f461dc..e402236 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -525,11 +525,13 @@ def collection(path, operation, query: {}, max_per_page: resource_class.page_lim # The keywords of a search, checked at the call that wrote them. # - # Through {Transport.stringify_query} for the refusals it makes at any - # depth - a nil value, two spellings of one key inside a +condition+, - # and a list of conditions a query string cannot keep apart - because - # left to the request they would be reported when the collection is - # first enumerated, some lines away from the search that wrote them. + # Through what {Transport.stringify_query} is made of, for the refusals + # it makes at any depth - a nil value, two spellings of one key inside a + # +condition+, a list of conditions a query string cannot keep apart + # and, once the keywords themselves were asked, a Hash further in that + # holds no value - because left to the request they would be reported + # when the collection is first enumerated, some lines away from the + # search that wrote them. # What it returns is what each keyword is asked about below, and not what # is sent: the collection sends the values as they were given - a copy of # them, see {#search} - and the transport stringifies them then, the @@ -542,10 +544,11 @@ def search_filters(filters) unknown = normalized.keys - search_filter_keys raise ArgumentError, unknown_search_filter_message(unknown) if !unknown.empty? - sent = Transport.stringify_query(normalized) + sent = Transport.stringify_query_hash(normalized, nil) empty = normalized.select { |name, _| empty_search_filter?(sent.fetch(name.to_s)) } raise ArgumentError, empty_search_filter_message(empty) if !empty.empty? + Transport.refuse_unwritten!(sent, nil) normalized end diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 2a70f08..21d990d 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -272,12 +272,54 @@ class RefusedValue < StandardError; end # @return [Hash{String => String, Array, Hash}] # @raise [ArgumentError] for a query that is not a Hash, for a nil # value, for a value that is neither text, a number, a boolean, a - # list nor a structure, for two keys that name the same parameter, or - # for a list a query string cannot carry, the last four at any depth + # list nor a structure, for two keys that name the same parameter, + # for a list a query string cannot carry, or for a Hash with no value + # in it, the last five at any depth def self.stringify_query(query) hash = Hash.try_convert(query) || raise(ArgumentError, "query needs to be a Hash of parameter names and values, got #{query.class}") - stringify_query_hash(hash, nil) + refuse_unwritten!(stringify_query_hash(hash, nil), nil) + end + + # Refuses a Hash a query string says nothing of: one with no value in + # it, or with nothing but such Hashes. + # + # {QueryEncoder} writes a pair for each value and has none to write + # here, so the parameter was not in the request, and Zammad answered as + # if it had been left out: `client.get(path, query: {filter: {}, a: + # 1})` asked for `?a=1`, and a `condition` built from nothing searched + # unnarrowed. A nil is refused for the same reason, and so is an empty + # Hash inside a list. It is named by the outermost parameter nothing is + # written for. + # + # Apart from {.stringify_query_hash}, so that {ResourceProxy#search} + # can say it in its own words for a keyword of its own first. + # + # @api private + # @param query [Hash] as {.stringify_query_hash} leaves it + # @param prefix [String, nil] the parameter path the Hash sits at + # @return [Hash] the query + # @raise [ArgumentError] + def self.refuse_unwritten!(query, prefix) + query.each do |name, value| + path = prefix ? "#{prefix}[#{name}]" : name + + case value + when Hash + raise ArgumentError, unwritten_query_message(path) if !QueryEncoder.written?(value) + + refuse_unwritten!(value, path) + when Array + value.each_with_index { |element, index| refuse_unwritten!(element, "#{path}[#{index}]") if element.is_a?(Hash) } + end + end + end + + # @api private + # @return [String] + def self.unwritten_query_message(path) + "query parameter #{path} is a Hash with no value in it, and a query string writes nothing for one: Zammad would " \ + 'answer as if the parameter had been left out. Pass a value, or leave the parameter out' end # Stringifies one level of a query, at whatever depth it sits. diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index eb329eb..e017a0f 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -51,6 +51,8 @@ module ZammadAPI def self.blank_query_value: (String parameter) -> String def self.redact: (untyped value) -> untyped def self.stringify_query: (untyped) -> Hash[String, untyped] + def self.refuse_unwritten!: (Hash[String, untyped] query, String? prefix) -> Hash[String, untyped] + def self.unwritten_query_message: (String path) -> String def self.stringify_query_hash: (Hash[untyped, untyped], String?) -> Hash[String, untyped] def self.stringify_query_value: (String, untyped) -> untyped def self.stringify_query_scalar: (String key, untyped value) -> String diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 4d1dc3f..8f4eea5 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -1042,6 +1042,15 @@ def self.name = 'Role' .to raise_error(ArgumentError, /search was given condition: \{"ticket.state_id" => \{\}\}/) end + # The keyword itself is written, by its other condition, and the one + # that holds nothing was dropped from the request. + it 'refuses a condition that holds an empty Hash beside one that is written' do + condition = { 'ticket.state_id' => {}, 'ticket.title' => { operator: 'contains', value: 'printer' } } + + expect { client.tickets.search('printer', condition: condition) } + .to raise_error(ArgumentError, /query parameter condition\[ticket\.state_id\] is a Hash with no value in it/) + end + it 'refuses group_ids naming a group with nothing under it' do expect { client.users.search('smith', group_ids: { 2 => {} }) }.to raise_error(ArgumentError, /search was given group_ids:/) end diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 5f96700..2e9d5ed 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -660,6 +660,11 @@ .to raise_error(ArgumentError, /query parameter sort_by is nil/) end + it 'rejects a query value with nothing in it the way the transport does' do + expect { client.get('api/v1/groups', query: { filter: {} }) } + .to raise_error(ArgumentError, /query parameter filter is a Hash with no value in it/) + end + it 'records requests oldest first' do client.groups.find(1).update!(name: 'Renamed') diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index fa15cad..3b8a2c4 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -435,6 +435,52 @@ def handed_to_the_adapter(**options) end end + # The encoder writes a pair for each value and has none to write for a + # Hash without one, so the parameter was not in the request and Zammad + # answered as if it had been left out: `query: {filter: {}, a: 1}` asked + # for `?a=1`. + context 'with a Hash that holds no value' do + it 'refuses one under a parameter, by its name' do + expect { described_class.stringify_query(filter: {}, a: 1) } + .to raise_error(ArgumentError, /query parameter filter is a Hash with no value in it.*as if the parameter had been left out/) + end + + it 'refuses one that holds nothing but such Hashes, which is not written either' do + expect { described_class.stringify_query(filter: { a: { b: {} } }) } + .to raise_error(ArgumentError, /query parameter filter is a Hash with no value in it/) + end + + it 'refuses one further in, beside a value that is written' do + expect { described_class.stringify_query(filter: { a: { b: {} }, c: 1 }) } + .to raise_error(ArgumentError, /query parameter filter\[a\] is a Hash with no value in it/) + end + + it 'refuses one inside an element of a list' do + expect { described_class.stringify_query(list: [{ operator: 'is', value: {} }]) } + .to raise_error(ArgumentError, /query parameter list\[0\]\[value\] is a Hash with no value in it/) + end + + it 'refuses what converts to one' do + expect { described_class.stringify_query(filter: StrongParameters.new({})) } + .to raise_error(ArgumentError, /query parameter filter is a Hash with no value in it/) + end + + it 'takes a query with no parameter at all' do + expect(described_class.stringify_query({})).to eq({}) + end + + it 'takes an empty list and an empty String, which are written' do + expect(described_class.stringify_query(filter: { ids: [], name: '' })).to eq('filter' => { 'ids' => [], 'name' => '' }) + end + + it 'makes no request for one' do + stub = stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) + + expect { unit_transport.get('api/v1/groups', operation: 'test', query: { filter: {}, a: 1 }) }.to raise_error(ArgumentError) + expect(stub).not_to have_been_requested + end + end + # A query string has no way to write a key with an empty name: `[]` # inside a structure, which Rails reads as a list, and nothing but the # value at the top level, which Rails drops. From f93e2b2c11137d1467e9c26b8c13eda17ba6131f Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 18:27:59 +0200 Subject: [PATCH 057/121] fix: take a blank token for unset and refuse a non-String --- CHANGELOG.md | 6 ++++ lib/zammad_api/config.rb | 48 ++++++++++++++++++++++++++-- sig/zammad_api/config.rbs | 4 +++ spec/unit/zammad_api/config_spec.rb | 49 +++++++++++++++++++++++++++++ 4 files changed, 104 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f572785..c38a9a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1074,6 +1074,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a the parameter had been left out. A `nil` and an empty Hash inside a list were refused for that reason already, and a `search` refused an empty `condition`; a condition holding an empty Hash beside one that is written lost it in the same way, and is refused now too. +- An `http_token` or `oauth2_token` of nothing but whitespace is taken for unset, as an + empty one is, and one that is no String raises `ZammadAPI::ConfigurationError`. Reading an + empty token file gives `"\n"`, and with it the client was built, reported + `auth=http_token` and sent `Authorization: Token` with nothing after it. `http_token: + 12345`, `:abc` and `['a']` were sent as they print, and a Symbol was never asked for the + line break a String is refused for. ### Changed diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 0db6ff0..d9e42bc 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -131,6 +131,9 @@ class Config basic: %i[user password] }.freeze + # The credentials that are sent as they stand, in a header of their own. + TOKEN_OPTIONS = %i[http_token oauth2_token].freeze + # Lays +overrides+ over +options+, dropping the credentials they replace. # # A configuration authenticates one way, so an override that names @@ -152,12 +155,31 @@ class Config # @param overrides [Hash{Symbol => Object}] # @return [Hash{Symbol => Object}] def self.merge_options(options, overrides) - named = CREDENTIAL_OPTIONS.select { |_, keys| keys.any? { !overrides[it].to_s.empty? } } + named = CREDENTIAL_OPTIONS.select { |_, keys| keys.any? { names_credential?(it, overrides[it]) } } replaced = named.empty? ? [] : CREDENTIAL_OPTIONS.except(*named.keys).values.flatten options.except(*replaced).merge(overrides) end + # Whether an override holds a credential, and so names its scheme. Not + # where it is nil or empty, and not a token of nothing but whitespace, + # which {#normalize_token} takes for none as well. + # + # @api private + # @return [Boolean] + def self.names_credential?(name, value) + !value.to_s.empty? && !(TOKEN_OPTIONS.include?(name) && blank_token?(value)) + end + + # Whether a token is one a header would carry nothing of. + # + # Asked of the bytes with +strip+, which is how {Transport.stripped} + # takes the whitespace off the token it sends. + # + # @api private + # @return [Boolean] + def self.blank_token?(value) = value.is_a?(String) && value.b.strip.empty? + # `url:` has a default so that leaving it out is answered by # {#normalize_url}, with the ConfigurationError that building a client is # documented to raise and that 1.x raised. As a required keyword it was @@ -187,8 +209,8 @@ def initialize( url: immutable(normalize_url(url)), user: immutable(non_empty(user)), password: immutable(non_empty(password)), - http_token: immutable(non_empty(http_token)), - oauth2_token: immutable(non_empty(oauth2_token)), + http_token: immutable(normalize_token(:http_token, http_token)), + oauth2_token: immutable(normalize_token(:oauth2_token, oauth2_token)), user_agent: immutable(non_empty(user_agent) || DEFAULT_USER_AGENT), timeout: timeout, open_timeout: open_timeout, @@ -557,6 +579,26 @@ def header_text(name, value) raise ConfigurationError, e.message, cause: nil end + # A token as it is held: text, or nil where there is none to send. + # + # One of nothing but whitespace is none. It is what reading an empty + # token file gives, and the transport takes the whitespace off the value + # it sends, so the client was built, reported +auth=http_token+ and + # sent +Authorization: Token+ with nothing after it. Taken for unset, as + # an empty String is, it is answered here with what is missing. + # + # And one that is no String is refused. It was sent as it prints, an + # Array as +["a"]+, and it passed {#validate_header_options!}, which + # asks a String for its line breaks and had nothing to ask a Symbol + # holding one. The class is named and the value is not: it is a + # credential, or was meant to be. + def normalize_token(name, value) + return nil if non_empty(value).nil? + raise ConfigurationError, "config #{name} needs to be a string, got #{value.class}" if !value.is_a?(String) + + self.class.blank_token?(value) ? nil : value + end + # A proxy is the second string here that may carry credentials, and the # only other one rendered rather than replaced wholesale. Unchecked, a # URI - what `URI(...)` hands back, and what prints as the URL - was diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index 2b04aad..44ff778 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -23,7 +23,10 @@ module ZammadAPI CREDENTIAL_OPTIONS: Hash[Symbol, Array[Symbol]] def self.new: (**untyped) -> instance + TOKEN_OPTIONS: Array[Symbol] def self.merge_options: (Hash[Symbol, untyped] options, Hash[Symbol, untyped] overrides) -> Hash[Symbol, untyped] + def self.names_credential?: (Symbol name, untyped value) -> bool + def self.blank_token?: (untyped value) -> bool attr_reader url: String attr_reader user: String? @@ -74,6 +77,7 @@ module ZammadAPI private def redact_userinfo: (String) -> String + def normalize_token: (Symbol name, untyped value) -> String? def normalize_proxy: (untyped) -> String? def normalize_adapter: (untyped) -> Symbol? def render: (Symbol, untyped) -> String diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 30a16fe..7b09225 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -167,6 +167,55 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect { build(http_token: '', oauth2_token: '', user: '', password: '') } .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') end + + # What reading an empty token file gives. The transport takes the + # whitespace off the token it sends, so the client was built, reported + # auth=http_token and sent `Authorization: Token` with nothing after it. + context 'with a token of nothing but whitespace' do + [" \n", "\t", "\r\n", ' '].each do |blank| + it "treats #{blank.inspect} as absent, for either token" do + expect { build(http_token: blank) }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + expect { build(http_token: nil, oauth2_token: blank) }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + end + end + + it 'does not count it as a second way to authenticate' do + expect(build(http_token: "\n", user: 'u', password: 'p').authentication_scheme).to eq(:basic) + end + + it 'leaves the scheme it would have replaced in an override alone' do + expect(build(http_token: nil, user: 'u', password: 'p').with(http_token: " \n")).to have_attributes(http_token: nil, user: 'u', password: 'p') + end + + it 'still replaces the scheme for a token with something in it' do + expect(build(http_token: nil, user: 'u', password: 'p').with(http_token: " abc\n")).to have_attributes(http_token: " abc\n", user: nil, password: nil) + end + + it 'keeps a password of spaces, which basic authentication carries as it is' do + expect(build(http_token: nil, user: 'u', password: ' ').password).to eq(' ') + end + end + + # It was sent as it prints, and a Symbol holding a line break passed the + # check that asks a String for one. + context 'with a token that is no String' do + { 12_345 => 'Integer', :abc => 'Symbol', ['a'] => 'Array', true => 'TrueClass' }.each do |value, kind| + it "rejects #{kind == 'Integer' ? 'an' : 'a'} #{kind}" do + expect { build(http_token: value) } + .to raise_error(ZammadAPI::ConfigurationError, "config http_token needs to be a string, got #{kind}") + end + end + + it 'rejects one for oauth2_token' do + expect { build(http_token: nil, oauth2_token: 99) } + .to raise_error(ZammadAPI::ConfigurationError, 'config oauth2_token needs to be a string, got Integer') + end + + it 'rejects a Symbol that holds a line break, which was never asked for one' do + expect { build(http_token: :"abc\r\nX-Injected: 1") } + .to raise_error(ZammadAPI::ConfigurationError, 'config http_token needs to be a string, got Symbol') + end + end end describe 'defaults' do From b023a503164267ae34b98a0e004d1c595992dc90 Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 18:29:48 +0200 Subject: [PATCH 058/121] test: compare what the preflight reads back from Zammad --- script/check_connection.rb | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/script/check_connection.rb b/script/check_connection.rb index aef9884..6d96977 100755 --- a/script/check_connection.rb +++ b/script/check_connection.rb @@ -136,17 +136,29 @@ def finish found.name end +# Each of these reads back what Zammad holds and compares it. Printing it +# was not a check: with the body of the PUT lost on the way, this said +# `ok ... created by check_connection.rb` and went on. check('update only the changed attribute') do @group.note = 'updated' raise 'change not staged' if !@group.changed? + raise "staged more than the note: #{@group.changes.keys.inspect}" if @group.changes.keys != [:note] @group.save - CLIENT.groups.find(@group.id).note + found = CLIENT.groups.find(@group.id) + raise "note was not saved: #{found.note.inspect}" if found.note != 'updated' + raise "name changed with it: #{found.name.inspect}" if found.name != "smoke-#{SUFFIX}" + + found.note end check('reload discards local changes') do @group.note = 'not saved' - @group.reload.note + note = @group.reload.note + raise "the staged value is still there: #{note.inspect}" if note != 'updated' + raise 'the record still reports a change' if @group.changed? + + note end check('pattern match a record') do @@ -175,7 +187,14 @@ def finish "#{pages} page(s)" end -check('search') { "#{CLIENT.users.search(LOGIN).to_a.size} hits" } +# The account this runs as is the one record a search is sure to have, and +# a search that answers with nothing does not raise. +check('search') do + hits = CLIENT.users.search(LOGIN).to_a + raise "no hit is #{LOGIN}, among #{hits.size}" if hits.none? { [it.login, it.email].include?(LOGIN) } + + "#{hits.size} hit(s)" +end # These were never driven against a live Zammad, which is why nobody noticed # that an attribute filter passed to an index endpoint never reached the query @@ -304,8 +323,19 @@ def finish section 'On behalf of another user' +# Acting for the account the client is signed in as reads the same with the +# header or without it. Zammad answers 403 for a From that names nobody, so +# that is the answer which says the header arrived. check('sends the From header') do - CLIENT.on_behalf_of(LOGIN) { |scoped| scoped.tickets.find(@ticket.id).number } + number = CLIENT.on_behalf_of(LOGIN) { |scoped| scoped.tickets.find(@ticket.id).number } + raise "read ticket #{number}, not #{@ticket.number}" if number != @ticket.number + + begin + CLIENT.on_behalf_of("nobody-#{SUFFIX}@example.com") { |scoped| scoped.tickets.find(@ticket.id) } + rescue ZammadAPI::AuthorizationError => e + next "number=#{number}, and status=#{e.status} for a user that does not exist" + end + raise 'a From header naming no user was accepted, so none was sent' end check('block form leaves the outer client unscoped') do From 9628d3ad0fb2a5a881ae5191df8bc5ebaa1d248c Mon Sep 17 00:00:00 2001 From: Mantas Date: Fri, 20 Nov 2026 18:30:25 +0200 Subject: [PATCH 059/121] docs: say a create cut short has no id to reload by --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bbcf14e..bcf35bb 100644 --- a/README.md +++ b/README.md @@ -1181,8 +1181,10 @@ A `TransportError` is a request with no whole answer, which is not the same as o never saw: a write that timed out may have been applied. `IncompleteResponseError` is the one case where that is known. Zammad answered 2xx, the connection closed before the body had arrived, and `e.response` holds the status and what did arrive. A record whose `save` -or `destroy` raises it is left saved or destroyed, so the call is not to be repeated; -`reload` brings in what the lost answer would have. +or `destroy` raises it is left saved or destroyed, so the call is not to be repeated. After +an update, `reload` brings in what the lost answer would have. A record that was being +created is in Zammad as well, but its id was in that answer: it has none to reload by, and +`reload` raises `ZammadAPI::Error` saying so. Look it up again, with `find_by` for instance. ### Timeouts and retries From 3c19f49f42e23e69c736ec247b479a7994cccc17 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 12:19:54 +0200 Subject: [PATCH 060/121] fix: ask again before calling a repeated page ignored --- CHANGELOG.md | 10 +++ lib/zammad_api/collection.rb | 47 +++++++++++- lib/zammad_api/errors.rb | 3 +- sig/zammad_api/collection.rbs | 1 + spec/unit/zammad_api/collection_spec.rb | 99 +++++++++++++++++++++++++ 5 files changed, 158 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c38a9a4..9ea617e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1080,6 +1080,16 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `auth=http_token` and sent `Authorization: Token` with nothing after it. `http_token: 12345`, `:abc` and `['a']` were sent as they print, and a Symbol was never asked for the line break a String is refused for. +- A walk no longer raises `ZammadAPI::PaginationError` for a list that moved by exactly a + page between two requests. A page holding the records of the one before it was taken as + proof that the endpoint ignores `page`, and it is also what a list served newest first + answers with after that many records were created or updated at its front: + `client.tickets.search('state.name:open').in_batches(of: 2)` raised where two other open + tickets were updated between its first and second request, and on an index the message + advised `paginated false`, which would have read a list cut short. The walk asks for the + page before once more now. Where that holds the same records again it raises as before, + one request later. Where it holds others, the page that repeated is passed over, since + the block has had its records, and the walk goes on from the page after it. ### Changed diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb index e724a8f..5ba6ff2 100644 --- a/lib/zammad_api/collection.rb +++ b/lib/zammad_api/collection.rb @@ -602,7 +602,16 @@ def walk # are what a search serves for two pages of hits whose records are # gone, with more beyond them - see #hits_past? - and there is nothing # on either for the block to be handed twice. - raise PaginationError.build(operation: @operation, page: page, resource_class: @resource_class, index: !@search) if received.positive? && digest == previous + # + # A repeat alone does not say that `page` is ignored: see + # #refuse_ignored_page!. Where the list moved instead, this page is + # the one the block has had, so it is passed over and the walk goes + # on from the page after it. + if received.positive? && digest == previous + refuse_ignored_page!(page, per_page, digest) + page += 1 + next + end yield records if received.positive? @@ -659,6 +668,42 @@ def walk end end + # Raises where a page that came back holding the records of the one + # before it means that the endpoint ignores +page+, and returns where it + # means that the list moved under the walk. + # + # Such a page is what an endpoint serves that ignores +page+, and it is + # also what one serves that pages as it should, where the list grew at + # its front by exactly a page between the two requests: a search is + # served most recently updated first, so two tickets updated elsewhere + # while `in_batches(of: 2)` was between its first and second request put + # the first page's tickets on the second. That walk raised + # PaginationError, and on an index the message went on to advise + # `paginated false`, which reads the list in one request and would have + # cut it short. + # + # The page before tells the two apart. Asked for again, it holds what it + # held, where the endpoint answers every page alike, and other records, + # where the ones it held have moved on to the next page. The page after + # would tell them apart as well and is one the walk needs anyway, but it + # repeats too where the list moves by a page a second time, which a small + # batch on a busy instance makes likely enough. For the page before to + # hold the same records again, the list has to move back. + # + # A page that repeats always follows one of its own size: only a page + # with nothing on it is followed by one of another size, and a page with + # records on it never compares equal to that. + # + # @param page [Integer] the page that repeated the one before it + # @param digest [Integer] what both pages held + # @raise [PaginationError] + def refuse_ignored_page!(page, per_page, digest) + _, again, = fetch(page - 1, per_page) + return if again != digest + + raise PaginationError.build(operation: @operation, page: page, resource_class: @resource_class, index: !@search) + end + # The page that follows one a walk has read, and its size: the next of # the same size, except past an empty page in a read sized by {#first}, # which asks for more at a time from there. Only a search gets this far diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index 382b8a2..d7fb3db 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -71,7 +71,8 @@ def self.build(operation:, expected:, actual:, resource_class: nil) end # Raised when the server answers a page request with the page before it, - # which means it is ignoring +page+ and a collection walk would never end. + # and that page, asked for again, still holds the same records. It is + # ignoring +page+ then, and a collection walk would never end. class PaginationError < Error # What to do about an index that repeats its first page, which is what # one that serves every record in a single response does. Said as a diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs index 1371645..3477494 100644 --- a/sig/zammad_api/collection.rbs +++ b/sig/zammad_api/collection.rbs @@ -76,6 +76,7 @@ module ZammadAPI def page_size!: (untyped, String) -> Integer def walk: () { (Array[R]) -> void } -> void def read_whole: () { (Array[R]) -> void } -> void + def refuse_ignored_page!: (Integer page, Integer per_page, Integer digest) -> void def page_after: (Integer page, Integer per_page, Integer received, Integer? total) -> [ Integer, Integer ] def widened: (Integer covered, Integer? total) -> [ Integer, Integer ] def each_distinct: () { (Resources::Base) -> void } -> void diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb index 4d954be..77376bd 100644 --- a/spec/unit/zammad_api/collection_spec.rb +++ b/spec/unit/zammad_api/collection_spec.rb @@ -230,6 +230,87 @@ def stub_capped_endpoint(url, total:, max:) .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) end + # A page that repeats the one before it is what an endpoint serves that + # ignores `page`, and also what one serves that pages as it should, where + # the list grew at its front by exactly a page between the two requests. + # The page before, asked for again, tells the two apart. + describe 'a page that repeats the one before it' do + # A list served newest first, paged as Zammad pages it. + def stub_list(url, list) + asked = [] + stub_request(:get, url).with(query: hash_including({})).to_return do |request| + params = URI.decode_www_form(URI(request.uri).query).to_h + page = Integer(params['page']) + size = Integer(params['per_page']) + asked << page + json_response(list[(page - 1) * size, size].to_a.map { { id: it } }) + end + asked + end + + def walk(list, of:, grows_by:) + seen = [] + collection.in_batches(of: of) do |batch| + list.unshift(*grows_by) if seen.empty? + seen.concat(batch.map(&:id)) + end + seen + end + + it 'reads on where the list grew by a page between two requests' do + list = [5, 4, 3, 2, 1] + stub_list(url, list) + + expect(walk(list, of: 1, grows_by: [6])).to eq([5, 4, 3, 2, 1]) + end + + it 'hands the page that repeated over once' do + list = [6, 5, 4, 3, 2, 1] + stub_list(url, list) + + expect(walk(list, of: 2, grows_by: [8, 7])).to eq([6, 5, 4, 3, 2, 1]) + end + + it 'asks for the page before once more to tell, and goes on from the page after' do + list = [3, 2, 1] + asked = stub_list(url, list) + walk(list, of: 1, grows_by: [4]) + + expect(asked).to eq([1, 2, 1, 3, 4, 5]) + end + + it 'ends where the page after the repeated one is empty' do + list = [2, 1] + stub_list(url, list) + + expect(walk(list, of: 2, grows_by: [4, 3])).to eq([2, 1]) + end + + it 'asks an endpoint that ignores the page parameter once more before it raises' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response(full_page)) + + expect { collection.to_a }.to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1/) + expect(a_request(:get, url).with(query: hash_including('page' => '1'))).to have_been_made.twice + expect(a_request(:get, url).with(query: hash_including('page' => '2'))).to have_been_made.once + end + + # The list has to move back for the page before to hold what it held, + # so one that moves on by a page a second time, while the walk is + # asking, repeats a page twice over and is still read to its end. + it 'reads on where the list grew by a page twice running' do + list = [3, 2, 1] + grows = [[4], [5]] + stub_request(:get, url).with(query: hash_including({})).to_return do |request| + params = URI.decode_www_form(URI(request.uri).query).to_h + served = list[Integer(params['page']) - 1, 1].to_a + list.unshift(*grows.shift) + json_response(served.map { { id: it } }) + end + + expect(Timeout.timeout(5) { collection.in_batches(of: 1).to_a.flatten.map(&:id) }).to eq([3, 2, 1]) + end + end + # The walk ran inside Kernel#loop, which rescues StopIteration for an # enumerator driven by hand inside it. The block here is the caller's, and # one raised from it was taken for the end of the walk: the rest of the @@ -1525,6 +1606,24 @@ def stub_search_over(hits, stale: [], serves: nil, window: nil) expect { search.to_a }.to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) end + # A search is served most recently updated first, so hits that are + # updated or created while it is walked go to its front. + it 'reads on where the hits moved by a page between two requests' do + list = [5, 4, 3, 2, 1] + stub_request(:get, search_url).with(query: hash_including({})).to_return do |request| + params = URI.decode_www_form(URI(request.uri).query).to_h + size = Integer(params['per_page']) + json_response({ records: list[(Integer(params['page']) - 1) * size, size].to_a.map { { id: it } }, total_count: list.size }) + end + seen = [] + search.in_batches(of: 2) do |batch| + list.unshift(7, 6) if seen.empty? + seen.concat(batch.map(&:id)) + end + + expect(seen).to eq([5, 4, 3, 2, 1]) + end + it 'ends on the empty page where the total is not a count' do stub_counted_page(1, [1], total: 'lots') stub_counted_page(2, [], total: -4) From bef37a9813e6485745e68b0ae7e73ac8cd2ff7a6 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 12:25:38 +0200 Subject: [PATCH 061/121] fix: settle a save only on a 2xx that says it is JSON --- CHANGELOG.md | 29 ++-- README.md | 10 ++ lib/zammad_api/errors.rb | 3 +- lib/zammad_api/resources/base.rb | 52 +++++-- lib/zammad_api/response.rb | 22 ++- sig/zammad_api/resources/base.rbs | 1 + sig/zammad_api/response.rbs | 2 + spec/support/client_helper.rb | 8 ++ spec/unit/zammad_api/resources/base_spec.rb | 151 ++++++++++++++++++-- spec/unit/zammad_api/response_spec.rb | 23 +++ 10 files changed, 268 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ea617e..b553947 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -490,13 +490,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a recorded requests under the monitor that guards them. - A record is persisted because Zammad answered 2xx, not because the answer parsed. The create response was decoded before the flag went down, so a 201 carrying something other - than a JSON object — an HTML error page from an intervening proxy — raised `ParseError` - with the record still looking new. The ticket existed in Zammad while the record here did - not, and a retried `save` POSTed a second one. What that leaves behind is a record that - is persisted and has no id, and `save`, `reload` and `destroy` all refuse it by name - rather than pretending: a record built by `new` has nothing staged, so the retried `save` - took the "nothing changed, nothing to send" short circuit and returned `true` without - making a single request, for a record that may or may not be in Zammad. + than a JSON object — a body cut off or rewritten on its way through a proxy — raised + `ParseError` with the record still looking new. The ticket existed in Zammad while the + record here did not, and a retried `save` POSTed a second one. What that leaves behind is + a record that is persisted and has no id, and `save`, `reload` and `destroy` all refuse + it by name rather than pretending: a record built by `new` has nothing staged, so the + retried `save` took the "nothing changed, nothing to send" short circuit and returned + `true` without making a single request, for a record that may or may not be in Zammad. - A `ConfigurationError` raised while building the connection no longer quotes the proxy credentials. `proxy: 'http://user:pa ss@host:3128'` came back as `URI::InvalidURIError` with the whole URL, password included, in a message that lands in @@ -748,7 +748,7 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a for one URL, and a client and its `on_behalf_of` scope, still hold the same record. - An update Zammad acknowledged is not sent again. The staged changes were dropped only once the response had decoded, so an update answered with a 2xx nothing could read, such - as a proxy's HTML page, raised `ParseError` with the whole change set still staged, and + as a body a proxy cut off, raised `ParseError` with the whole change set still staged, and the next `save` sent all of it again along with whatever had been staged since. For a ticket's `article` that is a second article and a second e-mail. A 2xx now settles what was sent before the body is read: the record holds the values it sent with nothing @@ -1090,6 +1090,19 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a page before once more now. Where that holds the same records again it raises as before, one request later. Where it holds others, the page that repeated is passed over, since the block has had its records, and the walk goes on from the page after it. +- A save answered 2xx by something that is not Zammad is no longer recorded as applied. + Every 2xx settled the record before its body was read, and the 2xx that cannot be read is + most often the page of something in front of Zammad that never passed the request on: a + single sign-on login page, a captive portal, the default page of a load balancer. After + `ticket.update(state: 'closed')` raised `ParseError` for a `200 text/html`, the ticket + read as closed with nothing staged, and the retried `save` returned `true` without a + request while Zammad still had it open. A create was left persisted with no id, for a + record Zammad never made. Zammad answers a create and an update with JSON, so only a 2xx + that says it is JSON settles the record now, whether or not its body can then be read. + Any other leaves the changes staged and a new record new, and the `save` can be + repeated. That holds for a 2xx cut short of its Content-Length as well, and + `Response#json_content_type?` is what is asked. `destroy` is as it was: Zammad answers a + ticket's DELETE with no body at all, so nothing in that 2xx says whose it is. ### Changed diff --git a/README.md b/README.md index bcf35bb..ce5696f 100644 --- a/README.md +++ b/README.md @@ -1186,6 +1186,16 @@ an update, `reload` brings in what the lost answer would have. A record that was created is in Zammad as well, but its id was in that answer: it has none to reload by, and `reload` raises `ZammadAPI::Error` saying so. Look it up again, with `find_by` for instance. +A `save` that raises `ParseError` was answered 2xx without the record, and whose answer +that was decides what it leaves behind. One that says it is JSON is Zammad's, with a body +cut off or rewritten on the way: the save was applied, and the record is left as it is +after an `IncompleteResponseError`. One of any other content type, or of none, is the +answer of something in front of Zammad that did not pass the request on, such as a login +page served with status 200. The record is left as it was, its changes staged and a new +record still new, and the `save` can be repeated once the way is clear. An +`IncompleteResponseError` whose `e.response` is not JSON leaves a record being saved that +way as well. + ### Timeouts and retries A `GET` is retried on connection failures, timeouts and the transient statuses 429, 500, diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index d7fb3db..24efbb6 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -40,7 +40,8 @@ class ConnectionError < TransportError; end # one thing that sets it apart from the others: the request was received and # answered. A write that raises this was applied, so it is not to be sent # again, and a record that was being saved or destroyed is left as saved or - # destroyed. + # destroyed. A save is taken as applied only where the answer said it was + # JSON, as Zammad's does: see {Resources::Base#save!}. class IncompleteResponseError < ConnectionError # @return [Response, nil] the response as far as it arrived attr_reader :response diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index b4b0f72..88c2b74 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -577,6 +577,10 @@ def save # connection was closed before its answer had arrived. The record is # persisted and holds what it sent; {#reload} brings in the rest, and # a record that was being created has no id to be reloaded by. + # @raise [ParseError] when a 2xx did not carry the record. One that said + # it was JSON was Zammad's, and leaves the record as the error above + # does. Any other was the answer of something in front of Zammad, and + # leaves the record as it was, changes staged, to be saved again. # @see #save def save! raise_if_destroyed!('save') @@ -853,10 +857,10 @@ def attribute_writable?(key) = key != :id # The flag goes down before the body is decoded, because what makes a # record persisted is that Zammad answered 2xx, not that the answer # parsed. Decoded first, a create whose 201 carried something other than - # a JSON object - an HTML error page from an intervening proxy - raised - # ParseError with @new_record still true, so the ticket existed in - # Zammad while the record here still looked unsaved and a retried `save` - # POSTed a second one. + # a JSON object - a body cut off or rewritten on its way through a + # proxy - raised ParseError with @new_record still true, so the ticket + # existed in Zammad while the record here still looked unsaved and a + # retried `save` POSTed a second one. # # What that leaves behind is a record which is persisted and carries no # id, and the rest of this class has to treat it as the unusable thing @@ -865,10 +869,14 @@ def attribute_writable?(key) = key != :id # to send" short circuit and reported true, having made no request at # all, for a record that may or may not be in Zammad. # + # Only where the 2xx is Zammad's, which {#applied_by?} asks: one that + # is not settles nothing, and the ParseError its body raises below + # leaves the record as the save found it. + # # +sent+ is what a save was sent with, and is what tells one from a # read. def replace_attributes!(response, operation:, sent: nil) - mark_answered!(sent) + mark_answered!(sent) if sent.nil? || applied_by?(response) @attributes = frozen_attributes(response.decoded(:object, operation: operation, resource_class: self.class)) @baseline = @attributes reset_pending_state! @@ -900,16 +908,44 @@ def mark_answered!(sent) # @raise [IncompleteResponseError] once the record is settled def applied(sent) yield - rescue IncompleteResponseError - mark_answered!(sent) + rescue IncompleteResponseError => e + mark_answered!(sent) if applied_by?(e.response) raise end + # Whether a 2xx says that Zammad applied the save it answers. + # + # Every 2xx was taken to. But the 2xx whose body cannot be read is, more + # often than a record Zammad served mangled, the page of something in + # front of Zammad that never passed the request on: the login page of a + # single sign-on gateway, a captive portal, the default page of a load + # balancer. Settled on that, `ticket.update(state: 'closed')` raised + # ParseError and left the ticket reading closed with nothing staged, so + # the retried `save` answered true without a request while Zammad still + # had it open, and a create was left persisted with no id for a record + # Zammad never made. + # + # The content type tells the two apart. Zammad answers a create and an + # update with JSON, from every controller, so a 2xx that says it is + # JSON is its own, readable or not, and one that says anything else, or + # nothing, is not. A body that was decoded from JSON counts as said, + # for a transport of the caller's that hands over a {Response} without + # the header. + # + # Not asked of a destroy. Zammad answers a ticket's DELETE with no body + # at all, so there is nothing in that 2xx to say whose it is. + # + # @param response [Response, nil] nil where an error that says Zammad + # answered carries none, which leaves its word for it + def applied_by?(response) + response.nil? || response.json? || response.json_content_type? + end + # The same argument, for what was staged: a 2xx is Zammad saying it # applied the changes, whether or not the rest of the answer parsed. # # They used to stay staged until the body had decoded. An update - # answered with a 2xx nothing could read - the same proxy page - raised + # answered with a 2xx nothing could read - the same mangled body - raised # ParseError with the whole change set still in place, so the next # `save` sent all of it again along with whatever had been staged # since. For most attributes that is the same value twice. For a diff --git a/lib/zammad_api/response.rb b/lib/zammad_api/response.rb index a444c20..b7d2a2d 100644 --- a/lib/zammad_api/response.rb +++ b/lib/zammad_api/response.rb @@ -55,6 +55,26 @@ def success? = SUCCESS_STATUSES.cover?(status) # @return [Boolean] whether {#body} was decoded from JSON def json? = json + # Whether the response says that its body is JSON, which is not whether + # the body then decoded as that: an empty one and one that does not parse + # are left as they arrived, and {#json?} is false for both. + # + # What an answer says it is tells whose it is. Zammad answers a request + # to its API with JSON, so a 2xx of another type - a login page, the + # default page of a load balancer - is the answer of something in front + # of it: see {Resources::Base#save!}. + # + # @return [Boolean] + def json_content_type? = Response.json_type?(headers['content-type']) + + # The one reading of a content-type, for {.decode_body} and + # {#json_content_type?} alike. + # + # @api private + # @param content_type [String, nil] + # @return [Boolean] + def self.json_type?(content_type) = content_type.to_s.include?('json') + # Decodes a body the way this gem decodes every body, and says whether it # did. # @@ -79,7 +99,7 @@ def json? = json # @return [Array(Hash | Array | String, bool)] the body and whether it was # decoded from JSON def self.decode_body(content_type, raw_body) - return [raw_body, false] if !content_type.to_s.include?('json') + return [raw_body, false] if !json_type?(content_type) return [raw_body, false] if raw_body.empty? [JSON.parse(raw_body, symbolize_names: true), true] diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 0a595cc..576500b 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -93,6 +93,7 @@ module ZammadAPI def replace_attributes!: (Response, operation: String, ?sent: Hash[Symbol, untyped]?) -> void def mark_answered!: (Hash[Symbol, untyped]? sent) -> void def applied: (Hash[Symbol, untyped] sent) { () -> Response } -> Response + def applied_by?: (Response? response) -> bool def acknowledge_changes!: (Hash[Symbol, untyped] sent) -> void def reset_pending_state!: () -> void def forget_related_targets: () -> void diff --git a/sig/zammad_api/response.rbs b/sig/zammad_api/response.rbs index e77f4b2..439aca3 100644 --- a/sig/zammad_api/response.rbs +++ b/sig/zammad_api/response.rbs @@ -11,9 +11,11 @@ module ZammadAPI SUCCESS_STATUSES: Range[Integer] def self.decode_body: (String?, String) -> [untyped, bool] + def self.json_type?: (String?) -> bool def success?: () -> bool def json?: () -> bool + def json_content_type?: () -> bool def decoded: (Symbol shape, operation: String, ?resource_class: Class?) -> untyped def decoded_list: (operation: String, ?resource_class: Class?) -> [ Array[Hash[Symbol, untyped]], Integer? ] diff --git a/spec/support/client_helper.rb b/spec/support/client_helper.rb index 51110dd..1709c28 100644 --- a/spec/support/client_helper.rb +++ b/spec/support/client_helper.rb @@ -26,4 +26,12 @@ def json_response(body, status: 200, headers: {}) headers: { 'Content-Type' => 'application/json' }.merge(headers) } end + + # Zammad's own answer with a body that cannot be read: it says it is JSON, + # and what arrived of it is not. + # + # @return [Hash] arguments for WebMock's +to_return+ + def unreadable_json_response(status: 200) + { status: status, body: '{"id":1,"na', headers: { 'Content-Type' => 'application/json' } } + end end diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index 60e174a..c7b5400 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -1397,7 +1397,7 @@ def self.name end it 'still says the record was saved where a save is what left it this way' do - stub_request(:post, url).with(query: hash_including({})).to_return(status: 201, body: 'proxy') + stub_request(:post, url).with(query: hash_including({})).to_return(unreadable_json_response(status: 201)) new_group = client.groups.new(name: 'Support') begin new_group.save @@ -1410,16 +1410,17 @@ def self.name end # What makes a record persisted is that Zammad answered 2xx, not that the - # answer parsed. Decoded first, a create whose 201 carried an HTML error - # page from an intervening proxy raised ParseError with the record still - # looking new - so the ticket existed in Zammad and a retried save POSTed a - # second one. Marked persisted, the record has no id to be addressed by - # either, and nothing staged to send, so the retry has to say so rather than - # take the "nothing to send" short circuit and report success. + # answer parsed. Decoded first, a create whose 201 carried a body cut off + # or rewritten on its way through a proxy raised ParseError with the record + # still looking new - so the ticket existed in Zammad and a retried save + # POSTed a second one. Marked persisted, the record has no id to be + # addressed by either, and nothing staged to send, so the retry has to say + # so rather than take the "nothing to send" short circuit and report + # success. describe 'a create whose success body cannot be parsed' do subject(:group) { client.groups.new(name: 'Support') } - before { stub_request(:post, url).with(query: hash_including({})).to_return(status: 201, body: 'proxy') } + before { stub_request(:post, url).with(query: hash_including({})).to_return(unreadable_json_response(status: 201)) } it 'still reports the parse failure' do expect { group.save }.to raise_error(ZammadAPI::ParseError) @@ -1503,7 +1504,7 @@ def self.name before do stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, title: 'Help', note: nil })) stub_request(:put, ticket_url).with(query: hash_including({})) - .to_return({ status: 200, body: 'proxy' }, json_response({ id: 1, title: 'Renamed' })) + .to_return(unreadable_json_response, json_response({ id: 1, title: 'Renamed' })) ticket.article = article begin @@ -1516,7 +1517,7 @@ def self.name it 'still reports the parse failure' do other = client.tickets.find(1) other.note = 'x' - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(status: 200, body: 'proxy') + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(unreadable_json_response) expect { other.save }.to raise_error(ZammadAPI::ParseError) end @@ -1542,7 +1543,7 @@ def self.name it 'goes on reading the values it sent for the attributes Zammad serves' do other = client.tickets.find(1) other.title = 'Sent' - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(status: 200, body: 'proxy') + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(unreadable_json_response) begin other.save rescue ZammadAPI::ParseError @@ -1578,7 +1579,7 @@ def self.name it 'stages a value written back to what it was before the save, which Zammad no longer holds' do other = client.tickets.find(1) other.title = 'Sent' - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(status: 200, body: 'proxy') + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(unreadable_json_response) begin other.save rescue ZammadAPI::ParseError @@ -1619,7 +1620,7 @@ def self.name before do stub_request(:put, ticket_url).with(query: hash_including({})).to_return do other.title = 'C' - { status: 200, body: 'proxy' } + unreadable_json_response end other.title = 'B' @@ -1658,7 +1659,7 @@ def self.name subject(:other) { client.tickets.find(1) } before do - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(status: 200, body: 'proxy') + stub_request(:put, ticket_url).with(query: hash_including({})).to_return(unreadable_json_response) other.title = 'B' allow(ZammadAPI::Resources::Ticket).to receive(:member_path).and_wrap_original do |original, id| @@ -1698,7 +1699,7 @@ def self.name stub_request(:put, ticket_url).with(query: hash_including({})).to_return do other.customer_id = 10 related.customer - { status: 200, body: 'proxy' } + unreadable_json_response end other.customer_id = 9 @@ -1858,4 +1859,124 @@ def swallow expect(group.changes).to eq(name: %w[Support Renamed]) end end + + # A 2xx says that Zammad applied a save only where the 2xx is Zammad's. + # It answers a create and an update with JSON, so a 2xx that says it is + # anything else, or does not say, is the page of something in front of + # Zammad that never passed the request on: a login page, a captive portal, + # the default page of a load balancer. Settled on that, the record read as + # saved and the retried save sent nothing, with Zammad none the wiser. + describe 'a save answered 2xx by something that is not Zammad' do + def login_page(**headers) + { status: 200, body: 'Please sign in', headers: { 'Content-Type' => 'text/html' }.merge(headers) } + end + + def swallow + yield + rescue ZammadAPI::ParseError, ZammadAPI::IncompleteResponseError + nil + end + + context 'when it was a create' do + subject(:group) { client.groups.new(name: 'Support') } + + before do + stub_request(:post, url).with(query: hash_including({})) + .to_return(login_page, json_response({ id: 7, name: 'Support' }, status: 201)) + end + + it 'still reports the parse failure' do + expect { group.save }.to raise_error(ZammadAPI::ParseError, /expected a JSON object, got String/) + end + + it 'leaves the record new' do + swallow { group.save } + + expect(group.new_record?).to be(true) + expect(group.persisted?).to be(false) + end + + it 'sends the record with the next save, which is the first Zammad sees' do + swallow { group.save } + + expect(group.save).to be(true) + expect(group.id).to eq(7) + expect(a_request(:post, url).with(query: hash_including({}), body: { name: 'Support' })).to have_been_made.twice + end + end + + context 'when it was an update' do + subject(:ticket) { client.tickets.find(1) } + + let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/1" } + + before do + stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, title: 'Help', state: 'open' })) + stub_request(:put, ticket_url).with(query: hash_including({})) + .to_return(login_page, json_response({ id: 1, title: 'Help', state: 'closed' })) + + swallow { ticket.update(state: 'closed') } + end + + it 'keeps the changes staged' do + expect(ticket.changes).to eq(state: %w[open closed]) + end + + it 'sends them with the next save rather than reporting it stored' do + expect(ticket.save).to be(true) + expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { state: 'closed' })).to have_been_made.twice + expect(ticket.changed?).to be(false) + end + + it 'keeps a write made while the request was out, as after any save that failed' do + other = client.tickets.find(1) + stub_request(:put, ticket_url).with(query: hash_including({})).to_return do + other.title = 'Written meanwhile' + login_page + end + swallow { other.update(state: 'closed') } + + expect(other.changes).to eq(state: %w[open closed], title: ['Help', 'Written meanwhile']) + end + end + + it 'takes a 2xx that names no content type the same way' do + stub_request(:post, url).with(query: hash_including({})).to_return(status: 200, body: 'OK') + group = client.groups.new(name: 'Support') + swallow { group.save } + + expect(group.new_record?).to be(true) + end + + # The transport refuses this one before the record sees a response, and + # the record is asked the same question of the response the error holds. + it 'takes a page cut short of its Content-Length the same way' do + stub_request(:post, url).with(query: hash_including({})).to_return(login_page('Content-Length' => '300')) + group = client.groups.new(name: 'Support') + + expect { group.save }.to raise_error(ZammadAPI::IncompleteResponseError) + expect(group.new_record?).to be(true) + end + + # Zammad answers a ticket's DELETE with no body at all, so a 2xx to a + # destroy carries nothing that says whose it is. + it 'does not ask the same of a destroy' do + group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Support') + stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + + expect(group.destroy).to be(true) + expect(group).to be_destroyed + end + + # A transport of the caller's can hand over a Response without the + # header. One whose body was decoded from JSON has said as much. + it 'takes a response decoded from JSON for Zammad\'s, with or without the header' do + response = ZammadAPI::Response.new(status: 201, headers: {}, body: { id: 7, name: 'Support' }, raw_body: '', json: true) + transport = instance_double(ZammadAPI::Transport, post: response) + group = ZammadAPI::Resources::Group.new(transport, name: 'Support') + + expect(group.save).to be(true) + expect(group.persisted?).to be(true) + end + end end diff --git a/spec/unit/zammad_api/response_spec.rb b/spec/unit/zammad_api/response_spec.rb index e7f7fd9..95fc531 100644 --- a/spec/unit/zammad_api/response_spec.rb +++ b/spec/unit/zammad_api/response_spec.rb @@ -34,6 +34,29 @@ def build(status: 200, body: { a: 1 }, raw_body: '{"a":1}', headers: {}, json: ! end end + # What a response says it carries, which is not what it turned out to: a + # JSON body that did not parse still came from something that speaks JSON. + describe '#json_content_type?' do + it 'is true for a JSON content type' do + expect(build(headers: { 'content-type' => 'application/json; charset=utf-8' })).to be_json_content_type + end + + it 'is true where the body then did not decode' do + response = build(body: '{"id":', raw_body: '{"id":', headers: { 'content-type' => 'application/json' }) + + expect(response).to be_json_content_type + expect(response).not_to be_json + end + + it 'is false for another content type' do + expect(build(headers: { 'content-type' => 'text/html' })).not_to be_json_content_type + end + + it 'is false where the response names none' do + expect(build).not_to be_json_content_type + end + end + describe '#decoded' do it 'returns an object body when one is expected' do expect(build(body: { a: 1 }).decoded(:object, operation: 'find object')).to eq(a: 1) From 4a656301c4494c07fad772b24af1a938fc5f62fc Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 12:29:12 +0200 Subject: [PATCH 062/121] fix: take no Authorization from Faraday's shared options --- CHANGELOG.md | 9 ++++ README.md | 6 +++ lib/zammad_api/transport.rb | 33 +++++++++++- sig/zammad_api/transport.rbs | 1 + spec/unit/zammad_api/transport_spec.rb | 72 ++++++++++++++++++++++++++ 5 files changed, 120 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b553947..1d9ad21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1103,6 +1103,15 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a repeated. That holds for a 2xx cut short of its Content-Length as well, and `Response#json_content_type?` is what is asked. `destroy` is as it was: Zammad answers a ticket's DELETE with no body at all, so nothing in that 2xx says whose it is. +- An `Authorization` header in `Faraday.default_connection_options` no longer replaces the + client's authentication. Every connection `Faraday.new` builds starts from those options, + and the authorization middleware leaves a header it finds, so a process that set + `Authorization: Bearer ...` there for another API sent that token to Zammad and the + configured one never, from a client whose `inspect` said `auth=http_token`. A `From` set + there was sent with every request, which Zammad reads as the user to act for, and + parameters set there went into every query. The connection is built without those three, + as 1.x never was. Everything else in the options still applies, and what the + `middleware:` callable sets on the connection stands. ### Changed diff --git a/README.md b/README.md index ce5696f..41a67be 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,12 @@ retried, and a missing record would arrive as `Faraday::ResourceNotFound` rather `ZammadAPI::NotFoundError` your code rescues. A subclass of either is refused for what it inherits. +What a process sets in `Faraday.default_connection_options` for all of its Faraday +connections applies to this client's as well: other headers, TLS settings, a proxy. An +`Authorization` header, a `From` header and query parameters set there are left off. The +two headers are what `http_token:` and `on_behalf_of` say, and a request carries the query +it names. + ## Available resources `groups`, `organizations`, `tickets`, `ticket_articles`, `ticket_priorities`, diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 21d990d..0653c42 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1483,8 +1483,12 @@ def build_connection # The encoder is this gem's own: see {QueryEncoder} for the one # structure Faraday's writes so that Rails reads another. request: { timeout: config.timeout, open_timeout: config.open_timeout, params_encoder: QueryEncoder }, - headers: { 'User-Agent' => Transport.stripped(config.user_agent), 'Accept' => 'application/json' } + headers: { 'User-Agent' => Transport.stripped(config.user_agent), 'Accept' => 'application/json' }, + # Named, and as nil, so that it stands in for the parameters of + # `Faraday.default_connection_options`: see #drop_shared_headers. + params: nil ) do |faraday| + drop_shared_headers(faraday) apply_authentication(faraday) faraday.request :json faraday.request :retry, Transport.retry_options(config) @@ -1627,6 +1631,33 @@ def redact_config_values(message) # which is kept wherever redaction finds nothing to change. def quoted_spellings(value) = [value, value.inspect[1...-1], value.dump[1...-1]].compact.uniq + # Takes off the connection what `Faraday.default_connection_options` put + # on it that only this client's configuration is to say. + # + # `Faraday.new` starts every connection from those options, which a + # process sets once for all of its Faraday clients. An `Authorization` + # among their headers, there for another API, stood on this connection + # before the authorization middleware ran, and that middleware leaves a + # header it finds: the token of the other service was sent to Zammad and + # the configured one never, by a client whose `inspect` said + # `auth=http_token`. A `From` there was sent with every request, which + # Zammad reads as the user to act for, and their parameters went into + # the query of every request, beside the ones the request named and + # where no log line showed them. + # + # The two headers are the ones {RESERVED_HEADERS} refuses a raw request, + # for the same reason. The parameters are left out where the connection + # is built, with `params: nil`, and not cleared here: a query the + # configured url carries is on the connection as parameters by now, and + # is this client's own. + # + # Everything else those options hold is kept: other headers, TLS + # settings, a proxy. And this runs before the `middleware:` callable, so + # what that sets on the connection it was handed stands, as it did. + def drop_shared_headers(faraday) + RESERVED_HEADERS.each_key { faraday.headers.delete(it) } + end + # A token as every adapter is to be handed it: see {Transport.stripped}. # A user and password are sent Base64-encoded, whatever is around them. def apply_authentication(faraday) diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index e017a0f..81a8eca 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -108,6 +108,7 @@ module ZammadAPI def refuse_unusable_middleware!: (untyped connection) -> void def refused_middleware: (Class klass) -> String? def refused_middleware_message: (Class klass, String refused) -> String + def drop_shared_headers: (untyped) -> void def apply_authentication: (untyped) -> void def decode: (untyped) -> Response def raw_body!: (untyped) -> String diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 3b8a2c4..4f8e32e 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1854,6 +1854,78 @@ def detailed_message = "unreadable: #{message}" end end + # `Faraday.default_connection_options` is where a process says what every + # Faraday connection it makes starts from, and `Faraday.new` starts this + # one from it too. What only this client's configuration is to say was + # taken from there all the same: a default Authorization stood in for the + # configured token, because the authorization middleware leaves a header + # it finds. + describe 'options a process set for every Faraday connection' do + around do |example| + before = Faraday.default_connection_options + Faraday.default_connection_options = Faraday::ConnectionOptions.new( + headers: { 'Authorization' => 'Bearer other-service-token', 'From' => 'someone@else.example', 'X-Source' => 'app' }, + params: { api_key: 'other-service-key' } + ) + example.run + ensure + Faraday.default_connection_options = before + end + + before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) } + + def sent = a_request(:get, url).with(query: hash_including({})) + + it 'sends the configured token, not an Authorization set there' do + unit_transport.get('api/v1/groups', operation: 'test') + + expect(sent.with(headers: { 'Authorization' => 'Token test-token' })).to have_been_made.once + end + + it 'sends the configured user and password, not an Authorization set there' do + unit_transport(http_token: nil, user: 'u', password: 'p').get('api/v1/groups', operation: 'test') + + expect(a_request(:get, url).with(basic_auth: %w[u p])).to have_been_made.once + end + + it 'sends no From set there, which Zammad would read as the user to act for' do + unit_transport.get('api/v1/groups', operation: 'test') + + expect(sent.with { |request| !request.headers.key?('From') }).to have_been_made.once + end + + it 'sends the From of on_behalf_of, not one set there' do + unit_transport.with_on_behalf_of('agent@example.com').get('api/v1/groups', operation: 'test') + + expect(sent.with(headers: { 'From' => 'agent@example.com' })).to have_been_made.once + end + + it 'sends no parameter set there' do + unit_transport.get('api/v1/groups', operation: 'test', query: { page: 1 }) + + expect(a_request(:get, url).with(query: { 'page' => '1' })).to have_been_made.once + end + + it 'keeps a query the configured url carries, which is this client\'s own' do + stub_request(:get, 'http://zammad.test/helpdesk/api/v1/groups').with(query: hash_including({})).to_return(json_response([])) + unit_transport(url: 'http://zammad.test/helpdesk?tenant=a').get('api/v1/groups', operation: 'test') + + expect(a_request(:get, 'http://zammad.test/helpdesk/api/v1/groups').with(query: { 'tenant' => 'a' })).to have_been_made.once + end + + it 'keeps a header set there that this client does not configure' do + unit_transport.get('api/v1/groups', operation: 'test') + + expect(sent.with(headers: { 'X-Source' => 'app' })).to have_been_made.once + end + + it 'keeps what the middleware callable sets on the connection it is handed' do + unit_transport(middleware: ->(connection) { connection.params['tenant'] = 'a' }).get('api/v1/groups', operation: 'test') + + expect(a_request(:get, url).with(query: { 'tenant' => 'a' })).to have_been_made.once + end + end + describe '#with_on_behalf_of' do it 'sends the From header' do stub = stub_request(:get, url).with(headers: { 'From' => 'agent@example.com' }).to_return(json_response([])) From 76224bca4b4982d1727b988e0740c503436bd4e4 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 12:32:10 +0200 Subject: [PATCH 063/121] fix: redact a proxy the environment names from an error --- CHANGELOG.md | 8 +++ lib/zammad_api/transport.rb | 45 +++++++++++++++-- sig/zammad_api/transport.rbs | 2 + spec/unit/zammad_api/transport_spec.rb | 68 ++++++++++++++++++++++++++ 4 files changed, 119 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d9ad21..ab191c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1112,6 +1112,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a parameters set there went into every query. The connection is built without those three, as 1.x never was. Everything else in the options still applies, and what the `middleware:` callable sets on the connection stands. +- A `ConfigurationError` raised while building the connection no longer quotes the + credentials of a proxy the environment names. With no `proxy:` given, Faraday takes the + one in `http_proxy` or `https_proxy`, and the redaction of that error knew the configured + values only: `https_proxy='http://user:hunter 2@proxy.example:3128'` came back as + `URI::InvalidURIError: bad URI (is not URI?)` with the whole URL in the message and again + in the cause, as 1.x let it out unwrapped. Every variable of the environment whose name + ends in `_proxy` is scrubbed as the configured proxy is, and the cause is dropped where + it quotes one. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 0653c42..f71680e 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1596,9 +1596,15 @@ def reportable_cause(error) # the message embeds the value verbatim, and the url as well as the proxy # because {Config} can only refuse the credentials in a url it can read: # one that is not a URL at all gets this far, and is quoted here. + # + # And the proxies the environment names, which no option holds: see + # {#environment_proxies}. def redact_config_values(message) - [config.proxy, config.url].compact.inject(message.to_s) do |text, value| - redacted = config.redacted(value) + [config.proxy, config.url, *environment_proxies].compact.inject(message.to_s) do |text, value| + spellings = quoted_spellings(value) + # Of the value as it can be read. A configured one is its own first + # spelling, and redacting text with a broken byte in it raises. + redacted = config.redacted(spellings.first) # The block form. A String replacement expands the backslash # sequences it contains, and the replacement here is the configured @@ -1615,10 +1621,37 @@ def redact_config_values(message) # matched nothing and left the password standing in full - the case # this method exists for, reached through the quoting rather than # the value. - quoted_spellings(value).inject(text) { |scrubbed, spelling| scrubbed.gsub(spelling) { redacted } } + spellings.inject(text) { |scrubbed, spelling| scrubbed.gsub(spelling) { redacted } } end end + # A variable of the environment that names a proxy, in either case: + # `https_proxy`, `HTTP_PROXY`, and `no_proxy` among them, which is a + # list of hosts and comes through the redaction as it went in. + ENVIRONMENT_PROXY = /_proxy\z/i + private_constant :ENVIRONMENT_PROXY + + # The proxy URLs the environment names, to be scrubbed from an error as + # the configured one is. + # + # With no `proxy:` given, Faraday takes the one `http_proxy` or + # `https_proxy` names, and it is URI that reads it: one it cannot parse + # was quoted whole in the ConfigurationError above and kept as its + # cause. `https_proxy='http://user:hunter 2@proxy.example:3128'`, a + # password with a space left unencoded, printed that password wherever + # the error was logged. The redaction knew the values of the + # configuration only, and this one is in none of them. + # + # Every such variable rather than the two Faraday is known to read: + # which of them URI consults depends on the scheme and on whether the + # process is a CGI, and a value that holds no credentials is not + # changed by being looked for. + # + # @return [Array] + def environment_proxies + ENV.filter_map { |name, value| value if name.match?(ENVIRONMENT_PROXY) && !value.empty? } + end + # The value as an error may have quoted it: as it is, as +inspect+ # writes it, and as +dump+ does. # @@ -1629,7 +1662,11 @@ def redact_config_values(message) # with an umlaut in it therefore matched neither of the two spellings # that were looked for, and stayed in the message - and in the cause, # which is kept wherever redaction finds nothing to change. - def quoted_spellings(value) = [value, value.inspect[1...-1], value.dump[1...-1]].compact.uniq + # + # Only the spellings that can be looked for. A value with a byte that is + # not text in its encoding, which the environment can hold, raises from + # the search for it, and an error can only have quoted it escaped. + def quoted_spellings(value) = [value, value.inspect[1...-1], value.dump[1...-1]].compact.uniq.select(&:valid_encoding?) # Takes off the connection what `Faraday.default_connection_options` put # on it that only this client's configuration is to say. diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 81a8eca..48af0ef 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -25,6 +25,7 @@ module ZammadAPI # private_constant in the source; RBS has no way to say so. REFUSED_MIDDLEWARE: Hash[String, [String, String]] CONTENT_LENGTH: Regexp + ENVIRONMENT_PROXY: Regexp MISREAD_ELEMENTS: Hash[Symbol, String] SENSITIVE_KEY_PATTERN: Regexp REDACTED: String @@ -118,6 +119,7 @@ module ZammadAPI def unlogged_body: (String body) -> String def reportable_cause: (StandardError error) -> StandardError? def redact_config_values: (untyped message) -> String + def environment_proxies: () -> Array[String] def quoted_spellings: (String value) -> Array[String] def logger: () -> Logger end diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 4f8e32e..d73ccd6 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -2671,6 +2671,74 @@ def bare_tls_transport(**overrides) end end + # With no `proxy:` given, Faraday takes the one the environment names, + # and URI quotes one it cannot parse as it quotes a configured one. The + # redaction knew the values of the configuration, and this is in none. + context 'when the proxy is the one the environment names' do + let(:proxy) { 'http://user:hunter 2@proxyhost:3128' } + + around do |example| + before = ENV.fetch('http_proxy', nil) + ENV['http_proxy'] = proxy + example.run + ensure + ENV['http_proxy'] = before + end + + # An address, so that URI has no name to look up before it reads the + # proxy. + def build = unit_transport(url: 'http://192.0.2.1/') + + it 'reports it as a configuration error' do + expect { build }.to raise_error(ZammadAPI::ConfigurationError, /URI::InvalidURIError/) + end + + it 'keeps the proxy password out of the message' do + expect { build }.to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('hunter 2') } + end + + it 'still says which value was rejected' do + expect { build }.to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) + end + + it 'keeps the proxy password out of the whole report' do + expect { build } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('hunter 2') } + end + + it 'does not carry the error that quotes the password along as its cause' do + expect { build }.to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_nil } + end + + # The environment can hold what no option is accepted with, and text + # with a broken byte in it raises from being searched for. + context 'when its password holds a byte that is not text' do + let(:proxy) { "http://user:hunter\xFF2@proxyhost:3128" } + + it 'is still reported as a configuration error, without the password' do + expect { build }.to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) { |error| + expect(error.full_message(highlight: false)).not_to include('hunter') + } + end + end + + context 'when the environment names it in upper case' do + around do |example| + before = ENV.fetch('HTTPS_PROXY', nil) + ENV['http_proxy'] = nil + ENV['HTTPS_PROXY'] = proxy + example.run + ensure + ENV['HTTPS_PROXY'] = before + end + + it 'keeps the proxy password out of the whole report' do + expect { unit_transport(url: 'https://192.0.2.1/') } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('hunter 2') } + end + end + end + # The error quotes what it rejected through `inspect`, which escapes the # backslash - so the text in the message stopped matching the configured # value and the substring swap redacted nothing at all. From 1167fe3d23ffb66e825c2c8572ed2397428b2e3e Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 12:33:11 +0200 Subject: [PATCH 064/121] fix: answer exists? with false for a record with no id --- CHANGELOG.md | 5 +++++ lib/zammad_api/resource_proxy.rb | 10 ++++++++-- spec/unit/zammad_api/resource_proxy_spec.rb | 8 ++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab191c1..3f76298 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1120,6 +1120,11 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a in the cause, as 1.x let it out unwrapped. Every variable of the environment whose name ends in `_proxy` is scrubbed as the configured proxy is, and the cause is dropped where it quotes one. +- `exists?` is `false` where Zammad answers with an object that carries no id. Any 2xx + counted as the record, and Zammad answers `organizations/5` with `200` and `{}` for a + customer who belongs to no organization, whether or not there is an organization 5, so + `client.organizations.exists?(5)` was `true` for it. `find` hands over what was served, + as before: a record with no id. ### Changed diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index e402236..1edddf1 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -261,11 +261,17 @@ def find_by!(**params) # This costs one request, and reads the record to find out, because Zammad # has no cheaper answer for a single id. # + # A record is one that says which it is. Any 2xx used to count, and + # Zammad answers one with an empty object where it has nothing to show + # the client: `organizations/5` is `{}` for a customer who belongs to no + # organization, whether or not there is an organization 5. That came + # back as true. {#find} still hands over what was served, a record with + # no id. + # # @param id [Integer, String] # @return [Boolean] def exists?(id) - find(id) - true + !find(id).id.nil? rescue NotFoundError false end diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 8f4eea5..7d3021d 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -512,6 +512,14 @@ def self.name = 'ObjectAttribute' expect(proxy.exists?(404)).to be(false) end + # What Zammad answers a customer who belongs to no organization with, + # for any organization id: 200 and an object with nothing in it. + it 'is false where Zammad answers with an object that names no record' do + stub_request(:get, "#{url}/5").with(query: hash_including({})).to_return(json_response({})) + + expect(proxy.exists?(5)).to be(false) + end + it 'does not swallow an authorization failure' do stub_request(:get, "#{url}/1").with(query: hash_including({})) .to_return(json_response({ error: 'no' }, status: 403)) From a3e65ac7542ad7311a449d9e68cb07c6d7575925 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 12:33:34 +0200 Subject: [PATCH 065/121] docs: say the timeout cannot be turned off --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 41a67be..75aaa14 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ client = ZammadAPI::Client.from_env(timeout: 300) | `oauth2_token` | `nil` | OAuth2 bearer token. | | `user` | `nil` | Login for basic authentication. | | `password` | `nil` | Password for basic authentication. | -| `timeout` | `60` | Seconds to wait for a response, at most 100000000. No value means no timeout. | +| `timeout` | `60` | Seconds to wait for a response, at most 100000000. It cannot be turned off, and `nil` is refused: pass the longest wait that is acceptable. | | `open_timeout` | `10` | Seconds to wait for the connection, with the same limit. | | `retries` | `2` | Retry attempts for a `GET` that failed transiently. `0` disables retrying. | | `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt, up to `timeout`. Up to half of it is added to each wait as jitter. | From c5ac8845a815604ba736ce3d66a0fd7d5dea5db3 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 12:35:27 +0200 Subject: [PATCH 066/121] fix: follow a belongs_to declared after the first write --- CHANGELOG.md | 6 +++ lib/zammad_api/resources/base.rb | 23 ++++++++++- sig/zammad_api/resources/base.rbs | 1 + .../zammad_api/associations/proxy_spec.rb | 39 +++++++++++++++++++ 4 files changed, 68 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f76298..17788e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1125,6 +1125,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a customer who belongs to no organization, whether or not there is an organization 5, so `client.organizations.exists?(5)` was `true` for it. `find` hands over what was served, as before: a record with no id. +- A `belongs_to` declared after a record of the class was written to is followed. The + foreign keys of a resource are listed at the first write to an attribute and the list was + kept, so an association added later, on a class reopened for it, was not in it: a write + to its foreign key left what the association had resolved in place, and `related.role` + answered role 5 after `role_id = 6`. Declaring one drops the list, on the class and on + every class that inherits from it. ### Changed diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 88c2b74..6ba84f1 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -345,12 +345,33 @@ def declared_associations = @declared_associations ||= {} # @param foreign_key [Symbol] attribute holding the target's id # @return [void] def belongs_to(name, class_name:, foreign_key: :"#{name}_id") - declared_associations[name] = { type: :belongs_to, class_name: class_name, foreign_key: foreign_key } + # Under the lock the list of foreign keys is built under, so that + # one being built meanwhile is either built with this declaration + # in it or dropped here once it stands. + MEMO_LOCK.synchronize do + declared_associations[name] = { type: :belongs_to, class_name: class_name, foreign_key: foreign_key } + forget_foreign_keys + end # The block runs against a Proxy instance, which the type checker # cannot see through define_method. related_class.define_method(name) { belongs_to_target(name, class_name, foreign_key) } # steep:ignore NoMethod end + # Drops the list {.belongs_to_foreign_keys} keeps, here and on every + # class that inherits what this one declares. + # + # The list is built at the first write to an attribute of a record + # and was kept from then on. A `belongs_to` declared after that - on + # a class reopened to add one, or declared late in a file that had + # built a record further up - was never in it, so a write to its + # foreign key left the association alone: `related.role` went on + # answering role 5 after `role_id = 6`. A subclass keeps a list of + # its own that holds the keys of its ancestors, so its list goes too. + def forget_foreign_keys + @belongs_to_foreign_keys = nil + subclasses.each { it.send(:forget_foreign_keys) } + end + # Declares that this resource points at a list of other records, # served by an endpoint of its own. # diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 576500b..b423d10 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -60,6 +60,7 @@ module ZammadAPI | (Symbol name) -> untyped def self.declared_associations: () -> Hash[Symbol, Hash[Symbol, untyped]] def self.belongs_to: (Symbol name, class_name: String, ?foreign_key: Symbol) -> void + def self.forget_foreign_keys: () -> void def self.has_many: (Symbol name, class_name: String, path: ^(String) -> String) -> void def initialize: (Transport, ?hash[untyped, untyped]? attributes) -> void diff --git a/spec/unit/zammad_api/associations/proxy_spec.rb b/spec/unit/zammad_api/associations/proxy_spec.rb index a34ee78..8ff8285 100644 --- a/spec/unit/zammad_api/associations/proxy_spec.rb +++ b/spec/unit/zammad_api/associations/proxy_spec.rb @@ -381,6 +381,45 @@ it 'includes the ones inherited from Base' do expect(ZammadAPI::Resources::Group.belongs_to_foreign_keys).to eq(%i[created_by_id updated_by_id]) end + + # The list is built at the first write to an attribute and kept. An + # association declared after that was never in it, so a write to its + # foreign key left the record it had resolved in place. + context 'when an association is declared after the list was built' do + let(:resource) { Class.new(ZammadAPI::Resources::Base) { path 'api/v1/memberships' } } + + before { stub_const('Acme::Role', Class.new(ZammadAPI::Resources::Base) { path 'api/v1/roles' }) } + + def declare_role = resource.send(:belongs_to, :role, class_name: 'Acme::Role') + + it 'takes in its foreign key' do + resource.belongs_to_foreign_keys + declare_role + + expect(resource.belongs_to_foreign_keys).to eq(%i[created_by_id updated_by_id role_id]) + end + + it 'takes it in on a class that inherits the declaration' do + subclass = Class.new(resource) + subclass.belongs_to_foreign_keys + declare_role + + expect(subclass.belongs_to_foreign_keys).to include(:role_id) + end + + it 'drops what the association resolved when its foreign key is written' do + [5, 6].each do |id| + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/roles/#{id}").with(query: hash_including({})).to_return(json_response({ id: id })) + end + record = resource.from_response(unit_transport, id: 1, role_id: 5) + record.note = 'written before the declaration' + declare_role + record.related.role + record.role_id = 6 + + expect(record.related.role.id).to eq(6) + end + end end describe '#inspect' do From 19b32acc7e7ddec75412e083aabf9d05050f666c Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 12:35:56 +0200 Subject: [PATCH 067/121] docs: tell 1.x code of Symbol keys inside an Array --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index 75aaa14..02da041 100644 --- a/README.md +++ b/README.md @@ -1534,6 +1534,17 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). handed, does that to all of them now. Limit it explicitly with `first(n)` or `page(1, per_page: n)`. +- **A Hash inside an Array attribute** has Symbol keys, where 1.x left it the String keys + Zammad sent: only a Hash directly under another Hash was symbolized. Read by String key, + it answers `nil` and nothing raises: + + ```ruby + article.attributes[:attachments].first['filename'] # the name in 1.x, nil in 2.0 + article.attributes[:attachments].first[:filename] # the name in 2.0 + ``` + + Keys are Symbols at every depth now, so one spelling reads a value wherever it sits. + - **`rescue Faraday::ConnectionFailed`** (and any other Faraday exception) no longer matches. Transport failures are wrapped, so rescue `ZammadAPI::ConnectionError`, `ZammadAPI::TimeoutError`, or `ZammadAPI::TransportError` for both. From 3f02cface8ce63621b96706270a400068bd20251 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:39:29 +0200 Subject: [PATCH 068/121] fix: read the records once for each_slice and each_cons --- CHANGELOG.md | 11 ++ README.md | 5 + lib/zammad_api/collection.rb | 56 +++++++++ lib/zammad_api/resource_proxy.rb | 23 +++- sig/zammad_api/collection.rbs | 5 + sig/zammad_api/resource_proxy.rbs | 5 + spec/unit/zammad_api/collection_spec.rb | 131 ++++++++++++++++++++ spec/unit/zammad_api/resource_proxy_spec.rb | 27 ++++ 8 files changed, 262 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17788e3..6837767 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1131,6 +1131,17 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a to its foreign key left what the association had resolved in place, and `related.role` answered role 5 after `role_id = 6`. Declaring one drops the list, on the class and on every class that inherits from it. +- `each_slice` and `each_cons` read the records once. Ruby asks the receiver for its `size` + before either starts, and the `size` of a collection is its `count`: a walk of every page + on an index, a request for the total on a search, the page once more on a collection + limited to one. So `client.tickets.each_slice(100)` read every ticket twice, and + `page(1, per_page: 50).each_slice(10)`, the call the errors of `page` point to, fetched + its page twice. The groups were also cut to the count the first of the two reads came + back with, whatever the second then held. Both run over the Enumerator of `each` now, on + a collection and on `client.tickets` alike, and `lazy` is made from it as well, since a + lazy enumerator hands the same question on to its source. An Enumerator that Ruby makes + from the collection itself, as `each_with_index` without a block is, still counts when it + is sliced: slice first, with `each_slice(10).with_index`. ### Changed diff --git a/README.md b/README.md index 02da041..a157240 100644 --- a/README.md +++ b/README.md @@ -1079,6 +1079,11 @@ A block or an argument is `Enumerable#count` counting matches, and walks either client.tickets.all.count { it.state == 'open' } # walks every page ``` +Ruby asks for a `size` in places that do not look like a count. `each_slice`, `each_cons` +and `lazy` on a collection do not: they read the records once. An Enumerator that Ruby makes +from the collection does, so `each_with_index.each_slice(10)` counts before it slices, and +`each_slice(10).with_index` is the way to write it. + Nothing is cached, so every traversal of a collection fetches again. ### `find` is a lookup, not a filter diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb index 5ba6ff2..82aff8b 100644 --- a/lib/zammad_api/collection.rb +++ b/lib/zammad_api/collection.rb @@ -360,6 +360,62 @@ def count(*args, &block) # @see #count alias length count + # Yields the records in groups of +size+, the last group being what is + # left over. + # + # +Enumerable#each_slice+, run over the Enumerator of {#each} rather than + # over the collection. Ruby asks the receiver for its +size+ before it + # slices, to hold no more than there is to hold, and {#size} here is + # {#count}: a walk of every page on an index, a request for the total on + # a search, the page over again on a collection limited to one. So + # `page(1, per_page: 50).each_slice(10)` fetched its page twice and + # `client.tickets.each_slice(100)` read every ticket twice, and the + # groups were cut to the count the first of the two reads came back + # with, whatever the second then held. The Enumerator has no size to be + # asked for. + # + # An Enumerator that Ruby makes from the collection itself still has: + # `each_with_index` and `map` without a block report the size of what + # they were made from, so slicing one of those counts first. Slice + # first, and number the groups: `each_slice(10).with_index`. + # + # @example + # client.users.each_slice(25) { |users| mailer.deliver(users) } + # + # @param size [Integer] records in a group + # @yieldparam records [Array] + # @return [Enumerator] when no block is given + def each_slice(size, &block) + return each.each_slice(size) if !block + + each.each_slice(size, &block) + self + end + + # Yields every run of +size+ records that follow one another. + # + # Run over the Enumerator of {#each}, for the reason {#each_slice} is: + # +Enumerable#each_cons+ asks for the +size+ in the same way. + # + # @param size [Integer] records in a run + # @yieldparam records [Array] + # @return [Enumerator] when no block is given + def each_cons(size, &block) + return each.each_cons(size) if !block + + each.each_cons(size, &block) + self + end + + # A lazy enumerator over the records. + # + # Made from the Enumerator of {#each} as well. A lazy enumerator answers + # +size+ with what its source answers, so `lazy.each_slice(10).first(2)` + # counted the collection on its way to two groups. + # + # @return [Enumerator::Lazy] + def lazy = each.lazy + # Whether this collection has no records. # # Costs the one request {#first} costs: a page of a single record, except diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index 1edddf1..be61f95 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -396,7 +396,28 @@ def all # @return [Array] # @see Collection#take - def_delegators :all, :order, :each, :find_each, :in_batches, :page, :pluck, :count, :size, :length, :empty?, :any?, :none?, :first, :take + # @!method each_slice(size, &block) + # Overrides +Enumerable#each_slice+, which asks for the +size+ before it + # slices, and so read every record twice. + # @param size [Integer] records in a group + # @yieldparam records [Array] + # @return [Enumerator] when no block is given + # @see Collection#each_slice + + # @!method each_cons(size, &block) + # Overrides +Enumerable#each_cons+ the same way. + # @param size [Integer] records in a run + # @yieldparam records [Array] + # @return [Enumerator] when no block is given + # @see Collection#each_cons + + # @!method lazy + # Overrides +Enumerable#lazy+, whose enumerator hands the same question + # on to +size+. + # @return [Enumerator::Lazy] + # @see Collection#lazy + + def_delegators :all, :order, :each, :find_each, :in_batches, :page, :pluck, :count, :size, :length, :empty?, :any?, :none?, :first, :take, :each_slice, :each_cons, :lazy # @!endgroup diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs index 3477494..847b59a 100644 --- a/sig/zammad_api/collection.rbs +++ b/sig/zammad_api/collection.rbs @@ -56,6 +56,11 @@ module ZammadAPI def count: (*untyped) ?{ (R) -> boolish } -> Integer def size: (*untyped) ?{ (R) -> boolish } -> Integer def length: (*untyped) ?{ (R) -> boolish } -> Integer + def each_slice: (Integer size) { (Array[R]) -> void } -> Collection[R] + | (Integer size) -> Enumerator[Array[R], untyped] + def each_cons: (Integer size) { (Array[R]) -> void } -> Collection[R] + | (Integer size) -> Enumerator[Array[R], untyped] + def lazy: () -> Enumerator::Lazy[R, void] def empty?: () -> bool def any?: () -> bool | ... diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs index a3502b2..153f1c6 100644 --- a/sig/zammad_api/resource_proxy.rbs +++ b/sig/zammad_api/resource_proxy.rbs @@ -45,6 +45,11 @@ module ZammadAPI def first: () -> R? | (Integer count) -> Array[R] def take: (Integer count) -> Array[R] + def each_slice: (Integer size) { (Array[R]) -> void } -> Collection[R] + | (Integer size) -> Enumerator[Array[R], untyped] + def each_cons: (Integer size) { (Array[R]) -> void } -> Collection[R] + | (Integer size) -> Enumerator[Array[R], untyped] + def lazy: () -> Enumerator::Lazy[R, void] def search: (String term, ?condition: Hash[untyped, untyped], ?ids: Array[Integer | String], ?role_ids: Array[Integer | String], ?group_ids: Array[Integer | String] | Hash[Integer | String, String | Symbol | Array[String | Symbol]], ?permissions: Array[String]) -> Collection[R] def inspect: () -> String diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb index 77376bd..8e7d413 100644 --- a/spec/unit/zammad_api/collection_spec.rb +++ b/spec/unit/zammad_api/collection_spec.rb @@ -894,6 +894,137 @@ def sorted_request(sort_by, order_by) end end + # Enumerable#each_slice and #each_cons ask the receiver for its size before + # they start, and the size of a collection is a count of it. + describe '#each_slice' do + let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/users/search" } + + def requests_made = a_request(:get, url).with(query: hash_including({})) + + it 'yields the records in groups, the last one being what is left' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + groups = [] + collection.each_slice(2) { groups << it.map(&:id) } + expect(groups).to eq([[1, 2], [3]]) + end + + it 'walks the pages once' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + collection.each_slice(2) { nil } + expect(requests_made).to have_been_made.twice + end + + it 'fetches a page once' do + stub_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }], per_page: 3) + + collection.page(1, per_page: 3).each_slice(2) { nil } + expect(requests_made).to have_been_made.once + end + + it 'does not ask a search for its total' do + stub_request(:get, search_url).with(query: hash_including('page' => '1')).to_return(json_response([{ id: 1 }])) + stub_request(:get, search_url).with(query: hash_including('page' => '2')).to_return(json_response([])) + + client.users.search('smith').each_slice(2) { nil } + expect(a_request(:get, search_url).with(query: hash_including('only_total_count' => 'true'))).not_to have_been_made + end + + # The groups were cut to the count that came back first, so a list that + # grew between the two reads was handed over in groups of that many. + it 'groups the records it reads, whatever a read before it held' do + stub_request(:get, url).with(query: hash_including('page' => '1')) + .to_return(json_response([{ id: 1 }]), json_response([{ id: 1 }, { id: 2 }])) + stub_request(:get, url).with(query: hash_including('page' => '2')).to_return(json_response([])) + + groups = [] + collection.each_slice(5) { groups << it.map(&:id) } + expect(groups).to eq([[1]]) + end + + it 'returns the collection' do + stub_last_page(1, [{ id: 1 }]) + + expect(collection.each_slice(2) { nil }).to equal(collection) + end + + it 'returns an Enumerator without a block, and asks for nothing' do + expect(collection.each_slice(2)).to be_a(Enumerator) + expect(requests_made).not_to have_been_made + end + + it 'numbers the groups without counting the records' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + expect(collection.each_slice(2).with_index.map { |group, index| [index, group.size] }).to eq([[0, 2], [1, 1]]) + expect(requests_made).to have_been_made.twice + end + + it 'refuses a size that is not positive, with or without a block' do + expect { collection.each_slice(0) }.to raise_error(ArgumentError, 'invalid slice size') + expect { collection.each_slice(0) { nil } }.to raise_error(ArgumentError, 'invalid slice size') + end + end + + describe '#each_cons' do + def requests_made = a_request(:get, url).with(query: hash_including({})) + + it 'yields every run of records that follow one another' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + runs = [] + collection.each_cons(2) { runs << it.map(&:id) } + expect(runs).to eq([[1, 2], [2, 3]]) + end + + it 'walks the pages once' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + collection.each_cons(2) { nil } + expect(requests_made).to have_been_made.twice + end + + it 'returns the collection' do + stub_last_page(1, [{ id: 1 }]) + + expect(collection.each_cons(2) { nil }).to equal(collection) + end + + it 'returns an Enumerator without a block, and asks for nothing' do + expect(collection.each_cons(2)).to be_a(Enumerator) + expect(requests_made).not_to have_been_made + end + + it 'refuses a size that is not positive' do + expect { collection.each_cons(0) }.to raise_error(ArgumentError, 'invalid size') + end + end + + describe '#lazy' do + def requests_made = a_request(:get, url).with(query: hash_including({})) + + it 'stops the walk as soon as it has enough' do + stub_page(1, full_page) + + expect(collection.lazy.map(&:id).first(2)).to eq([1, 2]) + expect(requests_made).to have_been_made.once + end + + # A lazy enumerator answers size with its source's, which was the count. + it 'slices without counting the records first' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + expect(collection.lazy.each_slice(2).map { it.map(&:id) }.to_a).to eq([[1, 2], [3]]) + expect(requests_made).to have_been_made.twice + end + + it 'has no size to report' do + expect(collection.lazy.size).to be_nil + expect(requests_made).not_to have_been_made + end + end + describe '#empty?' do it 'is false when the endpoint has a record' do stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 7d3021d..9b61ad8 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -694,6 +694,33 @@ def stub_last_page(page, records, per_page: default_per_page) expect(proxy.length).to eq(1) end + # A proxy is Enumerable, and Enumerable's own two ask for the size before + # they start, which is a walk of its own. + it 'forwards #each_slice, which walks the pages once' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + groups = [] + proxy.each_slice(2) { groups << it.map(&:id) } + expect(groups).to eq([[1, 2], [3]]) + expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.twice + end + + it 'forwards #each_cons, which walks the pages once' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + runs = [] + proxy.each_cons(2) { runs << it.map(&:id) } + expect(runs).to eq([[1, 2], [2, 3]]) + expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.twice + end + + it 'forwards #lazy, which slices without counting first' do + stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + expect(proxy.lazy.each_slice(2).first(1).map { it.map(&:id) }).to eq([[1, 2]]) + expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once + end + it 'forwards #take, so it costs what #first costs' do stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) From 08f456616785d4d10db12ff351f149dfb998a7c4 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:44:28 +0200 Subject: [PATCH 069/121] fix: keep a staged password out of the FrozenError --- CHANGELOG.md | 11 ++++ README.md | 5 ++ lib/zammad_api/attribute_access.rb | 6 ++- lib/zammad_api/attributes.rb | 54 +++++++++++++++++++ lib/zammad_api/deep_copy.rb | 14 ++++- lib/zammad_api/resources/base.rb | 8 +-- sig/zammad_api/attributes.rbs | 9 ++++ spec/unit/zammad_api/attributes_spec.rb | 53 +++++++++++++++++++ spec/unit/zammad_api/resources/base_spec.rb | 57 +++++++++++++++++++++ 9 files changed, 211 insertions(+), 6 deletions(-) create mode 100644 lib/zammad_api/attributes.rb create mode 100644 sig/zammad_api/attributes.rbs create mode 100644 spec/unit/zammad_api/attributes_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 6837767..72f0d48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1142,6 +1142,17 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a lazy enumerator hands the same question on to its source. An Enumerator that Ruby makes from the collection itself, as `each_with_index` without a block is, still counts when it is sliced: slice first, with `each_slice(10).with_index`. +- A write to the Hash `attributes` or `changes` hands out no longer raises an error that + quotes a staged password. Both are frozen, and Ruby prints a frozen object in the error + for a write to it: `user.attributes[:vip] = true`, which is how 1.x staged a change, + raised `FrozenError: can't modify frozen Hash: {login: "jane", password: "hunter2"}`, and + the message of an error is what a log and an error tracker keep. `inspect` of the record + blanked the same attributes, and the Hash it handed out printed itself. Both are a + `ZammadAPI::Attributes` now, as is every Hash inside them: a Hash that prints with the + value under each key naming a credential blanked, through `inspect`, `to_s` and `pp`. It + reads, compares and serializes as the Hash it was, to JSON and to YAML alike, and `to_h` + is a plain Hash. A String cannot be told how to print, so a write into the password + itself, `user.attributes[:password] << 'x'`, still quotes it. ### Changed diff --git a/README.md b/README.md index a157240..6a17d1d 100644 --- a/README.md +++ b/README.md @@ -575,6 +575,11 @@ group.name = 'Support 2' # the way to stage a change group.to_h # a deep copy, yours to modify ``` +Ruby quotes a frozen Hash in that `FrozenError`, so both are a `ZammadAPI::Attributes`: a +Hash that prints with the value under a key such as `password` or `token` blanked, the way +`inspect` of the record prints them, and that is a Hash in every other way. Reading from it +hands over every value, and `to_h` is a plain Hash. + ### Pattern matching Records implement `deconstruct_keys`, so they work with `case/in`: diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb index f319a92..b8242b6 100644 --- a/lib/zammad_api/attribute_access.rb +++ b/lib/zammad_api/attribute_access.rb @@ -38,7 +38,11 @@ module AttributeAccess # staging a change, so the next +save+ would not send it. {#to_h} returns a # copy that is safe to modify; an attribute writer is the way to stage one. # - # @return [Hash{Symbol => Object}] + # An {Attributes}, here and for every Hash inside it: a Hash that prints + # with its credentials blanked, since the error Ruby raises for a write + # to a frozen Hash prints it. + # + # @return [Attributes{Symbol => Object}] attr_reader :attributes # @param key [Symbol, String] diff --git a/lib/zammad_api/attributes.rb b/lib/zammad_api/attributes.rb new file mode 100644 index 0000000..1ba5fdf --- /dev/null +++ b/lib/zammad_api/attributes.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +module ZammadAPI + # The Hash a record hands its attributes out in. + # + # A Hash in every way but how it is printed, which is with the value under + # every key that names a credential blanked, the way + # {Resources::Base#inspect} prints a record. + # + # It is frozen where it is handed out, and Ruby quotes a frozen object in + # the error for a write to it. `user.attributes[:vip] = true`, which is how + # 1.x staged a change, raised `FrozenError: can't modify frozen Hash: + # {login: "jane", password: "hunter2"}`, and the message of an error is + # what a log and an error tracker keep. The record printed its attributes + # blanked, and the Hash it handed out printed itself. + # + # Only the printing. Every value reads as it is, and +to_h+, +to_json+ and + # YAML write them out, because handing them over is what a record is for. + # A Hash made from this one, by +slice+, +select+ or +to_h+, is a plain + # Hash again. + # + # What it holds is not covered where that is not a Hash. A String cannot + # be told how to print, so `user.attributes[:password] << 'x'` still + # quotes the password it was asked to change, and an Array prints what is + # in it. + # + # @example + # user.attributes[:vip] = true + # # FrozenError: can't modify frozen ZammadAPI::Attributes: {login: "jane", password: "[REDACTED]"} + class Attributes < Hash + # @return [String] the Hash as Ruby prints one, credentials blanked + def inspect = Transport.redact(self).inspect + + # +Hash#to_s+ is +Hash#inspect+ under a second name, and stays the one + # Hash defines unless it is named again here. + alias to_s inspect + + # What +pp+ prints, which is not what {#inspect} answers for a Hash. + # + # @param printer [PP] + # @return [void] + def pretty_print(printer) = printer.pp(Transport.redact(self)) + + # Written to YAML as the plain mapping a Hash is. + # + # Psych tags a subclass of Hash with its class, and refuses to load a + # tag it was not told to expect, so `record.attributes.to_yaml` would + # have stopped loading with +YAML.load+. + # + # @param coder [Psych::Coder] + # @return [void] + def encode_with(coder) = coder.represent_map(nil, self) + end +end diff --git a/lib/zammad_api/deep_copy.rb b/lib/zammad_api/deep_copy.rb index 59e7f81..57c1cf8 100644 --- a/lib/zammad_api/deep_copy.rb +++ b/lib/zammad_api/deep_copy.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require_relative 'attributes' require_relative 'duplicate_keys' module ZammadAPI @@ -118,14 +119,23 @@ def frozen_object(value, symbolize_keys) # walk that names the two spellings is made only once there is a pair to # name. # + # A copy with Symbol keys is the attributes of a record, at whatever + # depth, and those are handed out: see {Attributes} for why such a Hash + # is one that prints its credentials blanked. Made from the copy rather + # than filled key by key, which costs a page of a thousand tickets a + # millisecond. The payload the test kit records is copied with its keys + # as they are and stays a plain Hash, since a failed expectation is read + # from how it prints. + # # @api private # @return [Hash] a frozen copy # @raise [ArgumentError] def frozen_hash(hash, symbolize_keys) copy = hash.to_h { |key, nested| [symbolize_keys ? symbolize(key) : key, frozen_copy(nested, symbolize_keys: symbolize_keys)] } - DuplicateKeys.normalize(hash, noun: 'attribute') { symbolize(it) } if symbolize_keys && copy.size != hash.size + return copy.freeze if !symbolize_keys - copy.freeze + DuplicateKeys.normalize(hash, noun: 'attribute') { symbolize(it) } if copy.size != hash.size + Attributes[copy].freeze end # A writable deep copy, for handing out something callers may treat as diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 6ba84f1..891c252 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -35,10 +35,11 @@ class Base # Staged changes as +attribute => [old_value, new_value]+. # # A copy, and frozen: writing to the change set a record hands out would - # decide what the next +save+ sends. + # decide what the next +save+ sends. An {Attributes}, so that the error + # for such a write does not quote a password that is staged. # # @return [Hash{Symbol => Array(Object, Object)}] - def changes = @changes.dup.freeze + def changes = Attributes[@changes].freeze # The validation failure from the most recent {#save}, so that a +false+ # return value can be acted on. Cleared when the next save is attempted, @@ -1019,7 +1020,8 @@ def applied_by?(response) # only once the body has decoded, and a body that does not is what # this method is here for. def acknowledge_changes!(sent) - settled = new_record? ? sent : sent.slice(*@baseline.keys).freeze + # `slice` answers with a plain Hash, whatever it was called on. + settled = new_record? ? sent : Attributes[sent.slice(*@baseline.keys)].freeze @attributes = settled @baseline = settled @changes = {} diff --git a/sig/zammad_api/attributes.rbs b/sig/zammad_api/attributes.rbs new file mode 100644 index 0000000..a9377e6 --- /dev/null +++ b/sig/zammad_api/attributes.rbs @@ -0,0 +1,9 @@ +module ZammadAPI + # A Hash in every way but how it is printed: see lib/zammad_api/attributes.rb. + class Attributes[unchecked out K, unchecked out V] < Hash[K, V] + def inspect: () -> String + def to_s: () -> String + def pretty_print: (untyped printer) -> void + def encode_with: (untyped coder) -> void + end +end diff --git a/spec/unit/zammad_api/attributes_spec.rb b/spec/unit/zammad_api/attributes_spec.rb new file mode 100644 index 0000000..2809fea --- /dev/null +++ b/spec/unit/zammad_api/attributes_spec.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +require 'pp' +require 'yaml' + +RSpec.describe ZammadAPI::Attributes do + subject(:attributes) { described_class[plain].freeze } + + let(:plain) { { login: 'jane', password: 'hunter2', preferences: { api_key: 'k', locale: 'de' } } } + + it 'is a Hash, and equal to one holding the same' do + expect(attributes).to be_a(Hash).and eq(plain) + end + + it 'reads every value as it is' do + expect(attributes[:password]).to eq('hunter2') + end + + it 'prints with the value under every key that names a credential blanked' do + expect(attributes.inspect).to eq('{login: "jane", password: "[REDACTED]", preferences: {api_key: "[REDACTED]", locale: "de"}}') + end + + it 'prints the same way where it is written into a String' do + expect("#{attributes}").to eq(attributes.inspect) # rubocop:disable Style/RedundantInterpolation + end + + # pp prints a Hash pair by pair and does not ask it for inspect. The width + # keeps it on one line. + it 'is printed the same way by pp' do + expect(PP.pp(attributes, +'', 200)).to eq("#{attributes.inspect}\n") + end + + # What Ruby raises for a write quotes the Hash, which is why this class is. + it 'is quoted with its credentials blanked by the error for a write to it' do + expect { attributes[:vip] = true } + .to raise_error(FrozenError, %(can't modify frozen ZammadAPI::Attributes: #{attributes.inspect})) + end + + it 'converts to a plain Hash, which prints what it holds' do + expect(attributes.to_h).to be_an_instance_of(Hash).and(satisfy { it.inspect.include?('hunter2') }) + end + + it 'writes its values to JSON' do + expect(JSON.generate(attributes)).to eq(JSON.generate(plain)) + end + + # Psych tags a subclass of Hash with its class and refuses to load a tag + # it was not told of, so the YAML of a record's attributes would not load. + it 'is written to YAML as the mapping a Hash is, and loads as one' do + expect(attributes.to_yaml).to eq(plain.to_yaml) + expect(YAML.load(attributes.to_yaml, permitted_classes: [Symbol])).to eq(plain) + end +end diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index c7b5400..a65b4f1 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -235,6 +235,63 @@ def self.name group.save! expect { group.attributes[:preferences][:note] << '!' }.to raise_error(FrozenError) end + + # Ruby quotes the frozen object in the error for a write to it, and the + # message of an error is what a log and an error tracker keep. + context 'with a credential among the attributes' do + subject(:user) { client.users.new(login: 'jane', password: 'hunter2', preferences: { bind_pw: 's3cret', locale: 'de' }) } + + def message_of + yield + nil + rescue FrozenError => e + e.message + end + + it 'does not quote a staged password in the error for a write to #attributes' do + expect(message_of { user.attributes[:vip] = true }) + .to eq(%(can't modify frozen ZammadAPI::Attributes: {login: "jane", password: "[REDACTED]", preferences: {bind_pw: "[REDACTED]", locale: "de"}})) + end + + it 'does not quote a credential in the error for a write to a nested Hash' do + expect(message_of { user.attributes[:preferences][:x] = 1 }) + .to eq(%(can't modify frozen ZammadAPI::Attributes: {bind_pw: "[REDACTED]", locale: "de"})) + end + + it 'does not quote either password in the error for a write to #changes' do + user.password = 'correct horse' + + expect(message_of { user.changes[:x] = 1 }) + .to eq(%(can't modify frozen ZammadAPI::Attributes: {password: "[REDACTED]"})) + end + + it 'does not quote one that was written after the record was built' do + user.password = 'correct horse' + + expect(message_of { user.attributes[:vip] = true }).to include('password: "[REDACTED]"') + end + + it 'still reads every value as it is' do + expect(user.attributes).to eq(login: 'jane', password: 'hunter2', preferences: { bind_pw: 's3cret', locale: 'de' }) + end + + it 'hands out plain Hashes from #to_h, which print what they hold' do + expect(user.to_h).to be_an_instance_of(Hash).and(satisfy { it[:preferences].instance_of?(Hash) }) + end + end + + # A save whose answer cannot be read puts the record on what it sent, + # cut to the attributes it arrived with, and `slice` hands back a plain + # Hash whatever it was called on. + it 'hands out an Attributes after a save whose answer could not be read' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) + stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return(unreadable_json_response) + found = client.groups.find(1) + found.name = 'Support' + + expect { found.save! }.to raise_error(ZammadAPI::ParseError) + expect(found.attributes).to be_a(ZammadAPI::Attributes).and be_frozen + end end describe '#save' do From 3bcdd682d4a8da41b1c5e6a95e0cf9bff4ed264d Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:46:59 +0200 Subject: [PATCH 070/121] fix: settle a destroy only on a 2xx that is Zammad's --- CHANGELOG.md | 13 +++- README.md | 5 ++ lib/zammad_api/resource_proxy.rb | 6 +- lib/zammad_api/resources/base.rb | 58 +++++++++++++-- sig/zammad_api/resources/base.rbs | 1 + spec/unit/zammad_api/resource_proxy_spec.rb | 15 ++++ spec/unit/zammad_api/resources/base_spec.rb | 78 +++++++++++++++++++-- 7 files changed, 160 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72f0d48..a97e989 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1101,8 +1101,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a that says it is JSON settles the record now, whether or not its body can then be read. Any other leaves the changes staged and a new record new, and the `save` can be repeated. That holds for a 2xx cut short of its Content-Length as well, and - `Response#json_content_type?` is what is asked. `destroy` is as it was: Zammad answers a - ticket's DELETE with no body at all, so nothing in that 2xx says whose it is. + `Response#json_content_type?` is what is asked. A `destroy` is asked another question, + since Zammad answers a ticket's DELETE with no body at all: see below. - An `Authorization` header in `Faraday.default_connection_options` no longer replaces the client's authentication. Every connection `Faraday.new` builds starts from those options, and the authorization middleware leaves a header it finds, so a process that set @@ -1153,6 +1153,15 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a reads, compares and serializes as the Hash it was, to JSON and to YAML alike, and `to_h` is a plain Hash. A String cannot be told how to print, so a write into the password itself, `user.attributes[:password] << 'x'`, still quotes it. +- `destroy` no longer reports a record destroyed where something that is not Zammad answered + the request. Every 2xx settled it, so a single sign-on gateway that answered the DELETE + with its login page and status 200 made `group.destroy` return `true` and left the record + `destroyed?`, refusing every call after it, with the group still in Zammad. + `client.groups.destroy(6)` returned `true` for the same page, as 1.x did. Zammad answers a + DELETE with no body, for a ticket, and with an empty JSON object for everything else, so + a 2xx whose body does not say it is JSON raises `ParseError` now, from both. The record + is left as it was, with what was staged, and the `destroy` can be repeated. A 2xx cut + short of its Content-Length leaves the record destroyed only where it said it was JSON. ### Changed diff --git a/README.md b/README.md index 6a17d1d..0c1d11a 100644 --- a/README.md +++ b/README.md @@ -1212,6 +1212,11 @@ record still new, and the `save` can be repeated once the way is clear. An `IncompleteResponseError` whose `e.response` is not JSON leaves a record being saved that way as well. +A `destroy` asks the same of its 2xx. Zammad answers a DELETE with no body or with JSON, so +a 2xx with a body of any other kind raises `ParseError`, from `record.destroy` and from +`client.groups.destroy(id)` alike. The record is not `destroyed?`, and the call can be +repeated. + ### Timeouts and retries A `GET` is retried on connection failures, timeouts and the transient statuses 429, 500, diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index be61f95..b57f6ec 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -281,8 +281,12 @@ def exists?(id) # @param id [Integer, String] # @return [true] # @raise [ResponseError] when Zammad rejected the request + # @raise [ParseError] when the request was answered 2xx with a body that + # is not JSON, by something that is not Zammad: see + # {Resources::Base.confirm_destroyed!} def destroy(id) - @transport.delete(member_path(id), operation: 'destroy object', resource_class: resource_class) + response = @transport.delete(member_path(id), operation: 'destroy object', resource_class: resource_class) + resource_class.confirm_destroyed!(response) true end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 891c252..807ef57 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -233,6 +233,41 @@ def fetch_one(transport, id) from_response(transport, response.decoded(:object, operation: operation, resource_class: self)) end + # Refuses a 2xx to a DELETE that is not an answer Zammad gives to one. + # + # Zammad answers a DELETE with no body at all, for a ticket, and + # with an empty JSON object for what it destroys through + # ApplicationController#model_destroy_render. So a 2xx with a body + # that does not say it is JSON is the page of something in front of + # Zammad that never passed the request on - the login page of a + # single sign-on gateway, the default page of a load balancer - and + # the record is still there. Every 2xx was taken for Zammad's: + # `group.destroy` answered true to such a page and left the record + # destroyed, so nothing more could be asked of it, with the group + # still in Zammad. + # + # A 2xx with no body cannot be told from Zammad's own, and is taken + # for it. + # + # Here for the two callers that send a DELETE, {#destroy} and + # {ResourceProxy#destroy}. + # + # @api private + # @param response [Response] + # @return [Response] + # @raise [ParseError] when the body is neither empty nor JSON + def confirm_destroyed!(response) + return response if response.raw_body.to_s.empty? || response.json? || response.json_content_type? + + content_type = response.headers['content-type'].to_s + raise ParseError.build( + operation: 'destroy object', + expected: 'body or none', + actual: content_type.empty? ? 'a body that names no content type' : content_type, + resource_class: self + ) + end + # Builds a record that is already stored in Zammad. # # Straight to the state, past the constructor's refusal of attributes @@ -737,22 +772,32 @@ def reload # whole, for the reason {#applied} gives: the record is gone, and one # that still looked live sent a second DELETE, which came back as a 404. # + # Only where the 2xx is Zammad's, as a save is settled only by one that + # is: see {.confirm_destroyed!} for what tells them apart after a + # DELETE. A 2xx that is not leaves the record as it was, and the + # +destroy+ can be repeated. + # # @return [true] # @raise [Error] when the record was already destroyed # @raise [ResponseError] when Zammad rejected the request + # @raise [ParseError] when the request was answered 2xx with a body + # that is not JSON, by something that is not Zammad. The record is + # not {#destroyed?}. # @raise [IncompleteResponseError] when Zammad destroyed the record and # the connection was closed before its answer had arrived. The record - # is {#destroyed?} all the same. + # is {#destroyed?} all the same, unless the answer did not say it was + # JSON. def destroy raise_if_destroyed!('destroy') raise_if_new!('destroy') begin - transport.delete(member_path, operation: 'destroy object', resource_class: self.class) - rescue IncompleteResponseError - mark_destroyed! + response = transport.delete(member_path, operation: 'destroy object', resource_class: self.class) + rescue IncompleteResponseError => e + mark_destroyed! if applied_by?(e.response) raise end + self.class.confirm_destroyed!(response) mark_destroyed! true end @@ -954,8 +999,9 @@ def applied(sent) # for a transport of the caller's that hands over a {Response} without # the header. # - # Not asked of a destroy. Zammad answers a ticket's DELETE with no body - # at all, so there is nothing in that 2xx to say whose it is. + # A destroy is asked this only of an answer that was cut short. Zammad + # answers a ticket's DELETE with no body at all, so a whole one is + # asked what {.confirm_destroyed!} asks instead. # # @param response [Response, nil] nil where an error that says Zammad # answered carries none, which leaves its word for it diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index b423d10..715dedd 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -52,6 +52,7 @@ module ZammadAPI def self.paginated?: () -> bool def self.member_path: ((Integer | String) id) -> String def self.fetch_one: (Transport transport, (Integer | String) id) -> Base + def self.confirm_destroyed!: (Response response) -> Response def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> Base def self.associations: () -> Hash[Symbol, Hash[Symbol, untyped]] def self.belongs_to_foreign_keys: () -> Array[Symbol] diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 9b61ad8..3dfe875 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -542,6 +542,21 @@ def self.name = 'ObjectAttribute' expect { proxy.destroy(404) }.to raise_error(ZammadAPI::NotFoundError) end + + it 'answers true for the empty object Zammad answers a DELETE with' do + stub_request(:delete, "#{url}/1").to_return(json_response({})) + + expect(proxy.destroy(1)).to be(true) + end + + # The page of something in front of Zammad that never passed the DELETE + # on. This answered true for it, with the record still in Zammad. + it 'raises ParseError for a 2xx whose body is not JSON' do + stub_request(:delete, "#{url}/1").to_return(status: 200, body: 'Please sign in', headers: { 'Content-Type' => 'text/html' }) + + expect { proxy.destroy(1) } + .to raise_error(ZammadAPI::ParseError, "Can't destroy object (ZammadAPI::Resources::Group): expected a JSON body or none, got text/html") + end end # What a collection over this endpoint fetches per request when nothing asks diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index a65b4f1..c59573e 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -2015,14 +2015,78 @@ def swallow expect(group.new_record?).to be(true) end - # Zammad answers a ticket's DELETE with no body at all, so a 2xx to a - # destroy carries nothing that says whose it is. - it 'does not ask the same of a destroy' do - group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Support') - stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + # Zammad answers a ticket's DELETE with no body at all, and with an empty + # JSON object for everything else it destroys. A 2xx whose body is + # neither is not its answer, and the record is still there. + context 'when it was a destroy' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Support') } - expect(group.destroy).to be(true) - expect(group).to be_destroyed + let(:member_url) { "#{url}/1" } + + it 'reports the page, naming what it was served as' do + stub_request(:delete, member_url).to_return(login_page) + + expect { group.destroy } + .to raise_error(ZammadAPI::ParseError, "Can't destroy object (ZammadAPI::Resources::Group): expected a JSON body or none, got text/html") + end + + it 'leaves the record as it was, with what was staged' do + stub_request(:delete, member_url).to_return(login_page) + group.name = 'Renamed' + swallow { group.destroy } + + expect(group).not_to be_destroyed + expect(group.changes).to eq(name: %w[Support Renamed]) + end + + it 'sends the DELETE again with the next destroy, which is the first Zammad sees' do + stub_request(:delete, member_url).to_return(login_page, json_response({})) + swallow { group.destroy } + + expect(group.destroy).to be(true) + expect(group).to be_destroyed + expect(a_request(:delete, member_url)).to have_been_made.twice + end + + it 'takes a body that names no content type the same way' do + stub_request(:delete, member_url).to_return(status: 200, body: 'OK') + + expect { group.destroy }.to raise_error(ZammadAPI::ParseError, /got a body that names no content type/) + expect(group).not_to be_destroyed + end + + it 'takes a page cut short of its Content-Length the same way' do + stub_request(:delete, member_url).to_return(login_page('Content-Length' => '300')) + + expect { group.destroy }.to raise_error(ZammadAPI::IncompleteResponseError) + expect(group).not_to be_destroyed + end + + it 'is destroyed by a 2xx with no body, as Zammad answers for a ticket' do + stub_request(:delete, member_url).to_return(status: 200, body: '', headers: { 'Content-Type' => 'text/html' }) + + expect(group.destroy).to be(true) + expect(group).to be_destroyed + end + + it 'is destroyed by a 204' do + stub_request(:delete, member_url).to_return(status: 204) + + expect(group.destroy).to be(true) + end + + it 'is destroyed by the empty object Zammad answers with for a group' do + stub_request(:delete, member_url).to_return(json_response({})) + + expect(group.destroy).to be(true) + expect(group).to be_destroyed + end + + it 'is destroyed by a body that says it is JSON and cannot be read as it' do + stub_request(:delete, member_url).to_return(unreadable_json_response) + + expect(group.destroy).to be(true) + end end # A transport of the caller's can hand over a Response without the From d573762a99923295bff50e5053b1726694fca627 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:47:50 +0200 Subject: [PATCH 071/121] docs: say that a record does not go through Marshal --- CHANGELOG.md | 5 +++-- README.md | 19 +++++++++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a97e989..6149879 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1042,8 +1042,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a holds the token and the proxy password. So `record.to_yaml`, which is what Rails' `debug` view helper and a Delayed::Job handler write, printed both. A configuration is written as the mapping its JSON holds, and a transport as its URL and the way it authenticates, the - test kit's included. `Marshal.dump` still holds the credentials: it is what a copy is - rebuilt from. + test kit's included. `Marshal.dump` still holds the credentials where it writes anything: + it is what a copy is rebuilt from, and it raises `TypeError` for a client or a record + once the client has made a request. - A walk sorted by an attribute that records share hands each record over once. `order` sent the columns it was given, and Zammad sorts by those and by nothing after them, an index and a search alike, so PostgreSQL was free to hand rows that tie back in another diff --git a/README.md b/README.md index 0c1d11a..bc22eb6 100644 --- a/README.md +++ b/README.md @@ -163,8 +163,12 @@ printed — `inspect`, `to_s` or `pp`, which is what a console shows — and how serialized as text, with `to_json`, with the `as_json` ActiveSupport asks or with `to_yaml`, so a configuration object is safe to include in an error report. A client serializes as its URL and the way it authenticates, and no more, and so does the transport a record's YAML -names. `Marshal.dump` is the exception: it writes what the object is rebuilt from, -credentials included. +names. `Marshal.dump` is the exception, where it works at all. It writes what the object is +rebuilt from, credentials included, and it writes a configuration whose logger is the +default one. A client and a record are dumped only until the client has made a request: +from then on the connection holds a lock, and `Marshal.dump` raises `TypeError`, as it does +from the start where the logger writes to a file or a stream. See +[Comparing and serializing](#comparing-and-serializing) for what to cache of a record. Credentials belong in the options above, not in the URL. `https://user:secret@host/` raises `ZammadAPI::ConfigurationError`, because the HTTP stack would send those as basic @@ -752,6 +756,17 @@ user.as_json(except: [:password]) user.to_json(only: %w[id login]) ``` +The record itself does not go through `Marshal`, so it does not go into a cache that +marshals what it is given, as `Rails.cache` does. A record holds the connection it was read +over, which cannot be dumped once it has carried a request, and `Marshal.dump(ticket)` +raises `TypeError`. Cache what the record holds, and read it again by its id where a record +is needed: + +```ruby +Rails.cache.write("ticket/#{ticket.id}", ticket.to_h) # a plain Hash of what it holds +client.tickets.find(ticket.id) # the record, read again +``` + ### Reload and destroy ```ruby From 6e92b5a9db4404a680b72282b9b6ebf44f383255 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:50:23 +0200 Subject: [PATCH 072/121] fix: spend one stub on the count of a stubbed search --- CHANGELOG.md | 7 +++ README.md | 3 ++ lib/zammad_api/test.rb | 48 +++++++++++++++++++- sig/zammad_api/test.rbs | 3 ++ spec/unit/zammad_api/test_spec.rb | 74 +++++++++++++++++++++++++++++++ 5 files changed, 133 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6149879..5c75968 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1163,6 +1163,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a a 2xx whose body does not say it is JSON raises `ParseError` now, from both. The record is left as it was, with what was staged, and the `destroy` can be repeated. A 2xx cut short of its Content-Length leaves the record destroyed only where it said it was JSON. +- In `ZammadAPI::Test`, `count`, `size` and `length` on a search spend one stub of a + sequence, as reading its records does. `count` asks for the total alone first and walks + the pages where it is answered with records, and the stand-in took the two for two reads: + over three stubs holding one, two and three records, `search('x').count` answered 2, 3 + and 3 where `search('x').to_a.size` answered 1, 2 and 3. A request carrying + `only_total_count` is answered by the stub whose turn it is and leaves the sequence where + it was, unless that stub holds a total, fails, or was scoped to the request. ### Changed diff --git a/README.md b/README.md index bc22eb6..dc3b12a 100644 --- a/README.md +++ b/README.md @@ -1387,6 +1387,9 @@ client.groups.all.count # => 1 client.groups.all.count # => 2 ``` +A `count` on a search is one step as well, although it asks twice: for the total alone, +which a stub holding records answers with the records, and then for the pages. + The second stub may also be declared once the first has answered, between two steps of a test. It answers from the next request on. diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index 0392a35..e1d4e5e 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -384,6 +384,15 @@ def snapshot(value) = DeepCopy.frozen_copy(value) # read again, a ticket was open twice and closed at the third read. A # test that changes what an endpoint answers as it goes is the same # sequence as one that declares it up front. + # + # A request for the count of a search does not move the sequence on + # either, where the stub whose turn it is holds records rather than a + # total. `count` asks with +only_total_count+ first, is answered with the + # records the way a Zammad before 6.5.0 answers it, and walks the pages + # instead, so the request and the walk are one read. Taken for two, they + # spent a stub each: three stubs of one, two and three records counted + # two, three and three, where `to_a.size` over the same stubs is one, two + # and three. See {#counted_alone?}. def take(method, path, params) endpoint = key(method, path) queued = @stubs[endpoint] @@ -399,13 +408,48 @@ def take(method, path, params) # that is the first thing asked: `page(3)` on a list nothing has read. return served || queued[group.first] if later_page?(scope, params) - if group.size > 1 && queued[group.first].equal?(served) + # A stub that answered while it was the last of its kind has had its + # turn, so the one behind it is due. + turn_over = group.size > 1 && queued[group.first].equal?(served) + due = queued[turn_over ? group[1] : group.first] + return due if count_request?(scope, params) && !counted_alone?(due) + + @served[[endpoint, scope]] = advance(queued, group, turn_over) + end + + # Moves a sequence on by one read, and hands over the stub that read is + # answered by. The last of its kind is kept in place, to go on answering. + def advance(queued, group, turn_over) + if turn_over queued.delete_at(group.first) # Every other stub of the group sat behind the one that went. group = group.drop(1).map(&:pred) end - @served[[endpoint, scope]] = group.one? ? queued[group.first] : queued.delete_at(group.first) + group.one? ? queued[group.first] : queued.delete_at(group.first) + end + + # Whether a request asks a search for its total alone, of a stub that + # was not written for that request in particular. One scoped to + # +only_total_count+ is the answer to this request and to no other, and + # is sequenced as any stub is. + def count_request?(scope, params) + params.key?('only_total_count') && !scope&.key?('only_total_count') + end + + # Whether a stub answers a request for the total with one, which makes + # that request the whole of a `count`. {Collection#total_count} reads a + # total off a 2xx whose body is an object holding a count, and walks the + # pages for anything else. + # + # A stub of another status is no part of a walk: the request it answers + # fails, or is sent again, and either way has had a stub of its own. + def counted_alone?(stub) + return true if !Response::SUCCESS_STATUSES.cover?(stub[:status]) + + body, = Response.decode_body(stub[:headers]['content-type'], raw_body_for(stub[:body])) + total = body.is_a?(Hash) ? body[:total_count] : nil + total.is_a?(Integer) && !total.negative? end # Whether a request asks for a page beyond the first of a list whose stub diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs index 4637253..66fef4c 100644 --- a/sig/zammad_api/test.rbs +++ b/sig/zammad_api/test.rbs @@ -59,6 +59,9 @@ module ZammadAPI def snapshot: (untyped) -> untyped def take: (Symbol method, String path, Hash[String, untyped] params) -> Hash[Symbol, untyped]? def later_page?: (Hash[String, untyped]? scope, Hash[String, untyped] params) -> bool + def advance: (Array[Hash[Symbol, untyped]] queued, Array[Integer] group, bool turn_over) -> Hash[Symbol, untyped] + def count_request?: (Hash[String, untyped]? scope, Hash[String, untyped] params) -> bool + def counted_alone?: (Hash[Symbol, untyped] stub) -> bool def most_specific: (Array[Hash[Symbol, untyped]] queued, Array[Integer] matching, Symbol method, String path) -> Array[Integer] def ambiguous_message: (Symbol method, String path, Array[Hash[String, untyped]?] scopes) -> String def matches?: (Hash[untyped, untyped]? expected, Hash[String, untyped] params) -> bool diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 2e9d5ed..9eaf3fb 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -1154,6 +1154,80 @@ def names = client.groups.all.map(&:name) end end + # `count` on a search asks for the total alone first, and walks the pages + # where it is answered with records instead. Each of the two took a stub: + # the first of a sequence was never counted, and the last was counted + # twice. + describe 'a search stubbed as a sequence, and counted' do + subject(:zammad) { described_class.new } + + let(:client) { zammad.client } + let(:path) { 'api/v1/users/search' } + + def counts(times) = Array.new(times) { client.users.search('x').count } + + def stub_lists + [1, 2, 3].each { |records| zammad.stub(:get, path, body: Array.new(records) { { id: it + 1 } }) } + end + + it 'counts each stub in turn, and the last one from then on' do + stub_lists + + expect(counts(4)).to eq([1, 2, 3, 3]) + end + + it 'counts what reading the records counts' do + stub_lists + + expect(Array.new(3) { client.users.search('x').to_a.size }).to eq([1, 2, 3]) + end + + it 'spells #size and #length the same way' do + stub_lists + + expect([client.users.search('x').size, client.users.search('x').length]).to eq([1, 2]) + end + + it 'records the request for the total and the walk that follows it' do + stub_lists + counts(1) + + expect(zammad.requests.map { it.query.slice('only_total_count', 'page').values.first }).to eq(%w[true 1 2]) + end + + it 'spends a stub on the request alone where the stub holds a total' do + zammad.stub(:get, path, body: { records: [{ id: 1 }], total_count: 1 }) + zammad.stub(:get, path, body: { total_count: 2 }) + zammad.stub(:get, path, body: [{ id: 1 }, { id: 2 }, { id: 3 }]) + + expect(counts(4)).to eq([1, 2, 3, 3]) + end + + it 'spends a stub on an attempt that failed, and counts the one after it' do + zammad.stub(:get, path, status: 503) + stub_lists + + expect(counts(3)).to eq([1, 2, 3]) + end + + it 'counts a stub declared after the last one has been counted' do + zammad.stub(:get, path, body: [{ id: 1 }]) + counts(2) + zammad.stub(:get, path, body: [{ id: 1 }, { id: 2 }]) + + expect(counts(2)).to eq([2, 2]) + end + + # A stub scoped to the request is the answer to it and to nothing else, + # whatever it holds, so each request for the total is a step. + it 'still sequences stubs written for the request for the total' do + zammad.stub(:get, path, body: [{ id: 1 }], query: { only_total_count: true }) + zammad.stub(:get, path, body: [{ id: 1 }, { id: 2 }], query: { only_total_count: true }) + + expect(Array.new(3) { client.get(path, query: { only_total_count: true }).body.size }).to eq([1, 2, 2]) + end + end + describe 'a list endpoint whose pages are stubbed by hand' do subject(:zammad) { described_class.new } From 7ac8ee91e071f48cecf7646180cc4151f7ed23da Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:50:59 +0200 Subject: [PATCH 073/121] chore: name csv in the bundle for the ticket report --- Gemfile | 4 ++++ Gemfile.lock | 1 + examples/README.md | 3 ++- examples/ticket_report.rb | 3 +++ 4 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index a8d8416..84076c9 100644 --- a/Gemfile +++ b/Gemfile @@ -6,6 +6,10 @@ source 'https://rubygems.org' gemspec group :development, :test do + # For examples/ticket_report.rb. A bundled gem from Ruby 3.4 on, which + # Bundler makes loadable only where the bundle names it. It was in the + # bundle as a dependency of steep alone, and so not without that group. + gem 'csv', require: false gem 'overcommit', require: false gem 'rake', require: false gem 'rspec', '~> 3.13' diff --git a/Gemfile.lock b/Gemfile.lock index ba12f34..fc6b4ca 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -191,6 +191,7 @@ PLATFORMS x86_64-linux-musl DEPENDENCIES + csv irb overcommit rake diff --git a/examples/README.md b/examples/README.md index c46f245..bfc0a82 100644 --- a/examples/README.md +++ b/examples/README.md @@ -14,7 +14,8 @@ bundle exec ruby examples/quickstart.rb Run from a checkout of this repository, they go through Bundler, which is what puts `lib/` on the load path: plain `ruby` would load an installed release of the gem, 1.x included, or none. Copied into a project that has `zammad_api` 2.0 in its bundle, they -run there the same way. +run there the same way. `ticket_report.rb` also needs `gem 'csv'` in that bundle: `csv` is +a bundled gem from Ruby 3.4 on, and `zammad_api` does not depend on it. `ZAMMAD_USER` and `ZAMMAD_PASSWORD` work instead of a token, as does `ZAMMAD_OAUTH2_TOKEN`. diff --git a/examples/ticket_report.rb b/examples/ticket_report.rb index f661bfd..e95f999 100755 --- a/examples/ticket_report.rb +++ b/examples/ticket_report.rb @@ -10,6 +10,9 @@ # # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ # bundle exec ruby examples/ticket_report.rb tickets.csv +# +# `csv` is a bundled gem from Ruby 3.4 on, and `zammad_api` does not depend +# on it: a project this is copied into needs `gem 'csv'` in its Gemfile. require 'zammad_api' require 'csv' From e117cd89ecb5c4d8b2762cdfd1c3122ee1ed8fb8 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:53:31 +0200 Subject: [PATCH 074/121] fix: read the record by its id for find_by(id:) --- CHANGELOG.md | 10 ++ README.md | 6 ++ lib/zammad_api/resource_proxy.rb | 61 ++++++++++- sig/zammad_api/resource_proxy.rbs | 3 + spec/unit/zammad_api/resource_proxy_spec.rb | 109 +++++++++++++++++++- 5 files changed, 186 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c75968..dbb4a0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1170,6 +1170,16 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a and 3 where `search('x').to_a.size` answered 1, 2 and 3. A request carrying `only_total_count` is answered by the stub whose turn it is and leaves the sequence where it was, unless that stub holds a total, fails, or was scoped to the request. +- `find_by(id: ...)` finds the record with that id. An id was looked for as any other + value is, which is the one way it cannot be found. As the String a request parameter is, + `client.tickets.find_by(id: params[:id])` searched for the text and asked each hit + whether its id was that String, so it answered `nil` for a ticket that was among the + hits. As an Integer it gave no String to search on, and the index was walked a page at a + time until the record came by: `find_by(id: 123456)` read every ticket before it. The + record is read by its id now, in the one request `find` makes, with `nil` where that + answers 404, and any other value given beside the id is matched against it. An id that is + neither an Integer nor a String of digits is the id of no record: `nil`, without a + request. ### Changed diff --git a/README.md b/README.md index dc3b12a..510ad3a 100644 --- a/README.md +++ b/README.md @@ -492,6 +492,12 @@ client.ticket_states.find_by(name: 'open') # no search end client.users.find_by(organization_id: 5) # no string to search on: walks the index ``` +An `id` is neither searched for nor walked to. `find_by(id: params[:id])` reads the record +the way `find` does, in one request, and answers `nil` where `find` raises `NotFoundError`. +The id may be the Integer or a String of its digits, and any other value given with it is +matched against the record that came back. Anything else, `nil` included, is the id of no +record, and is answered `nil` without a request. + A search is the cheap way, and is used wherever the resource has a search endpoint and one of the values is a string. The term is one string value, because Zammad matches words: a value of another type would go out as the word it prints as, so `active: true` would look diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index b57f6ec..f7f0d49 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -222,10 +222,15 @@ def find(id) = resource_class.fetch_one(@transport, id) # costs one per page of hits. The longest value is searched to keep # those few. # + # An +id+ among the attributes is not searched for and not walked to. The + # id is what addresses a record, so the record is read by it, as {#find} + # reads it, and then held against the other values: see {#find_by_id}. + # # @example # client.users.find_by(email: 'someone@example.com')&.id # client.ticket_states.find_by(name: 'open') # client.users.find_by(organization_id: 5, active: true) + # client.tickets.find_by(id: params[:id]) # # @param params [Hash] attribute names and the values to match exactly # @return [Resources::Base, nil] nil when nothing matched @@ -233,10 +238,13 @@ def find(id) = resource_class.fetch_one(@transport, id) def find_by(**params) raise ArgumentError, 'find_by needs at least one attribute to match' if params.empty? + id_key = params.keys.find { it.to_s == 'id' } + return find_by_id(params[id_key], params.except(id_key)) if id_key + term = resource_class.searchable? ? search_term_for(params) : nil candidates = term ? search(term) : all - candidates.detect { |record| params.all? { |key, value| record.key?(key) && record[key] == value } } + candidates.detect { |record| carries?(record, params) } end # Fetches the first record carrying all of these attribute values, raising @@ -641,6 +649,57 @@ def searchable! raise Error, "Zammad routes no search endpoint for #{resource_class.name}, so it cannot be searched by term: #{path}/search answers 404, which would arrive here as a NotFoundError about a record. Look one record up by attribute value with find_by, which walks the records where it cannot search, or pick several out with select { ... }." end + # The record with this id, where it carries the other values as well. + # + # {#find_by} looked for an id the way it looks for any value, and an id + # is the one value that cannot be found that way. Given as the Integer + # it is, there was no String to search on, so the index was walked a + # page at a time until the record came by: `tickets.find_by(id: 123456)` + # read every ticket before it. Given as the String a request parameter + # is, `find_by(id: params[:id])`, the text was searched for, and each hit + # was asked whether its id was that String, which the id of a record, + # an Integer, never is: nil, for a record that was among the hits. + # + # One request, the one {#find} makes, and nil where it answers 404. The + # id is taken as a number or as the digits of one, since that is what + # tells which record was asked for. Anything else is the id of no + # record, and is answered without a request: a nil out of a parameter + # that was not sent, or a word, which would be read as another endpoint + # of the same path, as `users/me` is. + # + # The record that comes back is held against the number as well: Zammad + # answers an organization it will not show with an object that carries + # no id, which is the record with no id of {#exists?}. + # + # @param id [Object] the value given for +id+ + # @param others [Hash] the other attribute values to match + # @return [Resources::Base, nil] + def find_by_id(id, others) + number = record_number(id) + return nil if number.nil? + + record = find(number) + record if record.id == number && carries?(record, others) + rescue NotFoundError + nil + end + + # The number an id names: the Integer it is, or the one a String of + # digits writes. + # + # @return [Integer, nil] nil for anything else + def record_number(id) + return id if id.is_a?(Integer) + + Integer(id, 10) if id.is_a?(String) && id.ascii_only? && id.match?(/\A\d+\z/) + end + + # Whether a record carries every one of these values. + # + # Read with +[]+ and not with a reader, which raises for an attribute + # the record in hand does not carry. + def carries?(record, params) = params.all? { |key, value| record.key?(key) && record[key] == value } + # The one value {#find_by} searches on: the longest, as the most selective # of them, which matters because a miss reads every page of hits. # diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs index 153f1c6..ab89383 100644 --- a/sig/zammad_api/resource_proxy.rbs +++ b/sig/zammad_api/resource_proxy.rbs @@ -62,6 +62,9 @@ module ZammadAPI def empty_search_filter?: (untyped value) -> bool def empty_search_filter_message: (Hash[Symbol, untyped] empty) -> String def searchable!: () -> void + def find_by_id: (untyped id, Hash[Symbol, untyped] others) -> R? + def record_number: (untyped id) -> Integer? + def carries?: (Resources::Base record, Hash[Symbol, untyped] params) -> bool def search_term_for: (Hash[Symbol, untyped]) -> String? def path: () -> String def member_path: (Integer | String id) -> String diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 3dfe875..7096c82 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -331,7 +331,7 @@ def stub_page(number, records) before do stub_request(:get, states_url).with(query: hash_including('page' => '1')) - .to_return(json_response([{ id: 1, name: 'new' }, { id: 2, name: 'open' }])) + .to_return(json_response([{ id: 1, name: 'new', state_type_id: 1 }, { id: 2, name: 'open', state_type_id: 2 }])) stub_request(:get, states_url).with(query: hash_including('page' => '2')).to_return(json_response([])) end @@ -354,7 +354,7 @@ def stub_page(number, records) end it 'matches on a value of any type' do - expect(client.ticket_states.find_by(id: 2).name).to eq('open') + expect(client.ticket_states.find_by(state_type_id: 2).name).to eq('open') end end @@ -405,6 +405,111 @@ def stub_page(number, records) end end + # An id is what addresses a record, and the one value a search for it or + # a walk to it is the wrong way to find: given as an Integer the index was + # walked until the record came by, and given as the String a request + # parameter is, no hit ever carried it. + describe '#find_by with an id' do + let(:member_url) { "#{url}/5" } + + def stub_member(body = { id: 5, name: 'Users', active: true }) + stub_request(:get, member_url).with(query: hash_including({})).to_return(json_response(body)) + end + + def requests_made = a_request(:get, /#{Regexp.escape(url)}/) + + it 'reads the record by its id, in one request' do + stub_member + + expect(proxy.find_by(id: 5).name).to eq('Users') + expect(requests_made).to have_been_made.once + end + + it 'reads it expanded, as a search and an index serve it' do + stub = stub_request(:get, member_url).with(query: { 'expand' => 'true' }).to_return(json_response({ id: 5 })) + + proxy.find_by(id: 5) + expect(stub).to have_been_requested + end + + it 'finds the record by the String a request parameter is' do + stub_member + + expect(proxy.find_by(id: '5').id).to eq(5) + end + + it 'takes the id under a String key' do + stub_member + + expect(proxy.find_by('id' => 5).id).to eq(5) + end + + it 'answers nil where Zammad has no such record' do + stub_request(:get, member_url).with(query: hash_including({})).to_return(json_response({ error: 'not found' }, status: 404)) + + expect(proxy.find_by(id: 5)).to be_nil + end + + it 'raises from find_by! where Zammad has no such record' do + stub_request(:get, member_url).with(query: hash_including({})).to_return(json_response({ error: 'not found' }, status: 404)) + + expect { proxy.find_by!(id: 5) }.to raise_error(ZammadAPI::NotFoundError, /find object by id/) + end + + it 'answers with the record where it carries the other values too' do + stub_member + + expect(proxy.find_by(id: 5, name: 'Users', active: true).id).to eq(5) + end + + it 'answers nil where it does not carry one of them' do + stub_member + + expect(proxy.find_by(id: 5, name: 'Support')).to be_nil + end + + it 'answers nil where it lacks an attribute that was asked for' do + stub_member + + expect(proxy.find_by(id: 5, note: nil)).to be_nil + end + + it 'leaves any other failure to say what it is' do + stub_request(:get, member_url).with(query: hash_including({})).to_return(json_response({ error: 'Not authorized' }, status: 403)) + + expect { proxy.find_by(id: 5) }.to raise_error(ZammadAPI::AuthorizationError) + end + + # Zammad answers `organizations/5` with `{}` for a customer who belongs + # to no organization, whichever organization 5 is. + it 'answers nil for an object that carries no id' do + stub_member({}) + + expect(proxy.find_by(id: 5)).to be_nil + end + + it 'reads a String of digits as the number it writes' do + stub_member + + expect(proxy.find_by(id: '05').id).to eq(5) + end + + [nil, '', 'me', '5abc', ' 5', :me, 5.0, [5], '5'.encode('UTF-16LE'), "5\xff"].each do |value| + it "answers nil for #{value.inspect}, the id of no record, without a request" do + expect(proxy.find_by(id: value)).to be_nil + expect(requests_made).not_to have_been_made + end + end + + it 'does the same for a resource with no search endpoint' do + states_url = "#{ClientHelper::BASE_URL}api/v1/ticket_states" + stub_request(:get, "#{states_url}/2").with(query: hash_including({})).to_return(json_response({ id: 2, name: 'open' })) + + expect(unit_client.ticket_states.find_by(id: 2, name: 'open').id).to eq(2) + expect(a_request(:get, states_url).with(query: hash_including({}))).not_to have_been_made + end + end + describe '#find_by!' do let(:search_url) { "#{url}/search" } From c5971d4fcaf461f357107f2a51ad241eedb0e7ca Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:56:07 +0200 Subject: [PATCH 075/121] fix: refuse a request path that climbs with a .. segment --- CHANGELOG.md | 9 +++++ README.md | 2 ++ lib/zammad_api/transport.rb | 50 ++++++++++++++++++++++++-- sig/zammad_api/transport.rbs | 2 ++ spec/unit/zammad_api/client_spec.rb | 56 +++++++++++++++++++++++++++++ spec/unit/zammad_api/test_spec.rb | 9 +++++ 6 files changed, 126 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbb4a0b..b60081f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1180,6 +1180,15 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a answers 404, and any other value given beside the id is matched against it. An id that is neither an Integer nor a String of digits is the id of no record: `nil`, without a request. +- A raw request refuses a path with a `..` segment. A path is joined to the instance URL the + way a link is resolved, so for a Zammad served from a sub-path such a segment left it: + with `url: 'https://host/zammad/'`, `client.get('../billing/export')` was sent to + `https://host/billing/export`, another application on that host, with the client's + `Authorization` header and its `on_behalf_of` scope. An absolute URL was refused already + so that the credentials stay with the instance they were configured for, and this was + the way round it. It raises `ArgumentError` now, with the dots written as they are or as + `%2e`, for every verb, and in `ZammadAPI::Test` as on the wire. A `..` in a query string + is left alone, and so is a record id, which is escaped into a segment of its own. ### Changed diff --git a/README.md b/README.md index 510ad3a..10209f7 100644 --- a/README.md +++ b/README.md @@ -420,6 +420,8 @@ pasted straight from the Zammad documentation. An absolute URL raises `ArgumentE client's credentials only ever go to the instance it was configured for, so a link taken from a response body has to be reduced to its path first. Any path that opens with a scheme counts as one, `http:/collect` as much as `https://other.example/collect`. A path +with a `..` segment raises it for the same reason, however the dots are written: for a +Zammad served from a sub-path, `../billing/export` is another application on its host. A path is written the way a URL is, so a space or a character outside ASCII has to be percent-encoded, `t%C3%A4gs` for `tägs`; one that cannot be read as a URL raises `ArgumentError` too, before anything is sent or logged. A non-2xx response raises the same diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index f71680e..75a37cf 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -229,6 +229,11 @@ class RefusedValue < StandardError; end # for this reason, and every path Zammad serves opens with `api/`. ABSOLUTE_URL = /\A[a-z][a-z0-9+.-]*:/i + # A `..` segment in the path of a request, with either dot written as it + # is or percent-encoded: see {.refuse_parent_segment!}. + PARENT_SEGMENT = %r{(?:\A|/)(?:\.|%2e){2}(?:/|\z)}i + private_constant :PARENT_SEGMENT + # @return [Config] attr_reader :config @@ -839,11 +844,14 @@ def self.not_a_record_id_message(value) # for a request that never left - what {#perform} stringifies the query # and the headers first to prevent. # + # A path that climbs out of the instance URL is refused for the reason an + # absolute one is: see {.refuse_parent_segment!}. + # # @api private # @param path [Object] # @return [String] - # @raise [ArgumentError] for an absolute URL, or a path that cannot be - # read as a URL + # @raise [ArgumentError] for an absolute URL, a path that cannot be read + # as a URL, or one with a `..` segment def self.relative_path(path) relative = path.to_s.sub(%r{\A/+}, '') if ABSOLUTE_URL.match?(relative) @@ -853,9 +861,47 @@ def self.relative_path(path) end refuse_unreadable_path!(relative) + refuse_parent_segment!(relative) relative end + # Refuses a request path with a `..` segment in it. + # + # A path is joined to the instance URL the way a link is resolved, and + # `..` climbs. For a Zammad served from a sub-path that leaves it: + # against `https://host/zammad/`, `client.get('../billing/export')` was + # sent to `https://host/billing/export`, another application on the same + # host, with this client's Authorization header and its on_behalf_of + # scope. A path put together from a value that was not checked - a + # filename, a link out of a response body - is how one gets there. An + # absolute URL is refused so that the credentials stay with the instance + # they were configured for, and this is the same door. + # + # Whatever the instance URL is, since no endpoint is reached by climbing. + # The dots are read percent-encoded as well: a client sends `%2e%2e` as + # it stands, and what receives it reads it as the dots. A `..` in a query + # string or after a `#` is no part of the path, and is left alone. + # + # A segment is what stands between two slashes that were written as + # slashes. A record id is escaped into one by {.escape_path_segment}, + # slashes and all, so `find('1/../x')` asks for the one segment + # `1%2F..%2Fx` and is not what this refuses. + # + # The message does not quote the path, for the reason {.relative_path} + # gives. + # + # @api private + # @param relative [String] a path that reads as a URL + # @return [void] + # @raise [ArgumentError] + def self.refuse_parent_segment!(relative) + return if !PARENT_SEGMENT.match?(relative[/\A[^?#]*/].to_s) + + raise ArgumentError, "a request path names an endpoint below the instance URL, and this one holds a '..' segment, which climbs " \ + "out of it: for a Zammad served from a sub-path, sending it would hand this client's credentials to " \ + "whatever else that host serves. Pass the path of the endpoint itself, such as 'api/v1/tickets'." + end + # Reads a path the two ways Faraday will: the whole of it as a URL, and # a query string written into it as parameters. # diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 48af0ef..3fb79a9 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -38,6 +38,7 @@ module ZammadAPI end TEXT_VALUE_TYPES: Array[Class] ABSOLUTE_URL: Regexp + PARENT_SEGMENT: Regexp RESERVED_HEADERS: Hash[String, String] HEADER_NAME: Regexp @@ -77,6 +78,7 @@ module ZammadAPI def self.not_a_record_id_message: (untyped value) -> String def self.relative_path: (untyped) -> String def self.refuse_unreadable_path!: (String relative) -> void + def self.refuse_parent_segment!: (String relative) -> void def self.unreadable_path_message: (String relative) -> String def self.encode_body: (untyped body, operation: String, ?resource_class: Class?) -> String? def self.json_value: (untyped value, untyped key) -> untyped diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index 12d3b71..88218ee 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -488,6 +488,62 @@ .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('s3cret') } end + # A path is joined to the instance URL the way a link is resolved, so + # `..` climbs out of the sub-path a Zammad is served from, and the + # request went to whatever else the host serves with the token on it. + context 'with a path that climbs out of the instance URL' do + let(:client) { unit_client(url: 'http://zammad.test/helpdesk/') } + + before { stub_request(:any, /zammad\.test/).to_return(json_response({})) } + + it 'refuses it rather than sending the credentials to another application' do + expect { client.get('../billing/export') } + .to raise_error(ArgumentError, /holds a '\.\.' segment, which climbs out of it/) + end + + it 'makes no request for it' do + expect { client.get('../billing/export') }.to raise_error(ArgumentError) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + + ['api/v1/../../../billing', 'api/v1/tickets/..', '..', '/../billing', '%2e%2e/billing', 'api/%2E%2e/x', 'api/.%2e/x'].each do |path| + it "refuses #{path}" do + expect { client.get(path) }.to raise_error(ArgumentError, /climbs out of it/) + end + end + + # An id is escaped into one segment, slashes included, and a segment + # that holds `..` among other things is not one that climbs. + it 'still sends a record id that was escaped into its segment' do + stub = stub_request(:get, 'http://zammad.test/helpdesk/api/v1/groups/1%2F..%2F..%2Fbilling').with(query: hash_including({})) + .to_return(json_response({ error: 'not found' }, status: 404)) + + expect { client.groups.find('1/../../billing') }.to raise_error(ZammadAPI::NotFoundError) + expect(stub).to have_been_requested + end + + it 'refuses it for every verb' do + %i[post put delete].each do |verb| + expect { client.public_send(verb, '../billing/export') }.to raise_error(ArgumentError, /climbs out of it/) + end + end + + it 'refuses it for a client whose instance is served from the root as well' do + expect { unit_client.get('api/v1/../../x') }.to raise_error(ArgumentError, /climbs out of it/) + end + + it 'does not quote the path it refuses, which may carry a secret' do + expect { client.get('../billing/export?token=s3cret') } + .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('s3cret') } + end + + ['api/v1/roles?path=../x', 'api/v1/roles#../x', 'api/v1/a..b', 'api/v1/.../x', './api/v1/roles', 'api/v1/..x'].each do |path| + it "takes #{path}, which holds two dots and no such segment" do + expect(client.get(path).status).to eq(200) + end + end + end + # Faraday reads the path with URI, and URI raises an error of its own # for one it cannot read: neither a ZammadAPI::Error nor the # ArgumentError a path is documented to raise, and raised after the diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 9eaf3fb..3cbf222 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -158,6 +158,15 @@ .to raise_error(ArgumentError, /a request path is relative to the instance URL/) end + it 'refuses a path that climbs out of the instance URL the way the real transport does' do + expect { client.get('../billing/export') }.to raise_error(ArgumentError, /holds a '\.\.' segment/) + expect(zammad.requests).to be_empty + end + + it 'refuses to stub such a path, which no request could reach' do + expect { zammad.stub(:get, 'api/v1/../x') }.to raise_error(ArgumentError, /holds a '\.\.' segment/) + end + it 'refuses a path that cannot be read as a URL the way the real transport does' do expect { client.get('api/v1/tägs') }.to raise_error(ArgumentError, /cannot be read as one: it holds a character outside ASCII/) expect(zammad.requests).to be_empty From 1861890661b77f0df2a611be41aa0a5e30dbe30e Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:58:22 +0200 Subject: [PATCH 076/121] fix: hold a stubbed 2xx to its Content-Length --- CHANGELOG.md | 6 + README.md | 9 ++ .../resources/ticket_article_attachment.rb | 2 +- lib/zammad_api/test.rb | 27 +++- lib/zammad_api/transport.rb | 139 ++++++++++-------- sig/zammad_api/test.rbs | 3 +- sig/zammad_api/transport.rbs | 4 +- spec/unit/zammad_api/test_spec.rb | 71 +++++++++ 8 files changed, 189 insertions(+), 72 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b60081f..44df713 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1189,6 +1189,12 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a the way round it. It raises `ArgumentError` now, with the dots written as they are or as `%2e`, for every verb, and in `ZammadAPI::Test` as on the wire. A `..` in a query string is left alone, and so is a record id, which is escaped into a segment of its own. +- `ZammadAPI::Test` raises `IncompleteResponseError` for a 2xx stub whose `Content-Length` + announces more than its body holds, as the transport does for that response. It handed + the response back as whole, so what a program does about a save or a destroy that was cut + short could not be tested against it, and a fixture carrying a stale `Content-Length` + passed there and failed against Zammad. The empty page it serves after a stubbed list is + given a length of its own. ### Changed diff --git a/README.md b/README.md index 10209f7..146ecca 100644 --- a/README.md +++ b/README.md @@ -1341,6 +1341,15 @@ names downcased, the way a real `Response` carries them; a value that is not tex spellings of one header name, are refused where the stub is written rather than turned into something the wire could not send. +A 2xx stubbed with a `Content-Length` that announces more than its body holds raises +`IncompleteResponseError`, as that response does on the wire. It is how a test says that a +save was answered and the answer cut short: + +```ruby +zammad.stub(:put, 'api/v1/tickets/1', body: '{"id":1,"ti', + headers: {'Content-Type' => 'application/json', 'Content-Length' => 30}) +``` + `query` and `headers` are recorded through the real transport's own stringification, so they hold what a request would have carried rather than the raw Ruby values — and a header the wire would refuse is refused here too. `headers` names only what the call asked for; diff --git a/lib/zammad_api/resources/ticket_article_attachment.rb b/lib/zammad_api/resources/ticket_article_attachment.rb index 0a9fd2e..b62eeb6 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -24,7 +24,7 @@ def initialize(transport, attributes = {}) # Asks for the file as it is stored. A response says how long it is in # the bytes that were sent, and the transport can hold that against # the bytes in hand only where nothing decoded them on the way: see - # {Transport#missing_bytes}. Left to itself Net::HTTP asks for gzip + # {Transport.missing_bytes}. Left to itself Net::HTTP asks for gzip # and inflates what arrives, without a word for a stream that stops # halfway, so a text attachment behind a proxy that compresses came # back as its first part when the connection was closed under it. diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index e1d4e5e..900a0c8 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -247,12 +247,19 @@ def inspect = @monitor.synchronize { "#<#{self.class.name} stubbed=#{@stubs.size # times here where the wire is asked once. The +timeout+ a # +Retry-After+ is held against is read the same way. # + # A 2xx stubbed with a +Content-Length+ that announces more than its + # body holds is the response the wire raises {IncompleteResponseError} + # for, and is raised for here: it is how a test says that a save was + # answered and the answer cut short. + # # @api private # @param config [Config] the configuration of the client that sent the # request # @return [Response] # @raise [ResponseError] for a stubbed non-2xx status, once the retries # it is due are spent + # @raise [IncompleteResponseError] for a stubbed 2xx whose body is + # shorter than its Content-Length # @raise [UnstubbedRequestError] when no stub matches def answer(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil, on_behalf_of: nil, config: self.config) relative = ::ZammadAPI::Transport.relative_path(path) @@ -277,7 +284,9 @@ def answer(method, path, operation:, query: nil, body: nil, headers: nil, resour response = attempt(request) end - return response if response.success? + # Held to its Content-Length as the wire holds it: see + # {Transport.whole}. + return ::ZammadAPI::Transport.whole(response, operation: operation, config: config) if response.success? raise ResponseError.build(response, operation: operation, resource_class: resource_class) end @@ -552,7 +561,17 @@ def response_for(stub, params) # the bytes the stub was written with for every other response. return build_response(stub, body, raw, json: json) if paged.equal?(body) - build_response(stub, paged, JSON.generate(paged), json: json) + emptied = JSON.generate(paged) + build_response(stub, paged, emptied, json: json, headers: recounted(stub[:headers], emptied)) + end + + # The headers of a stub for a body that paging replaced. A + # Content-Length written for the records does not count the empty page + # served after them, and would have it refused as cut short. + def recounted(headers, raw_body) + return headers if !headers.key?('content-length') + + headers.merge('content-length' => raw_body.bytesize.to_s) end # The bytes a stub's body would have arrived as. A Hash or Array is what a @@ -572,8 +591,8 @@ def raw_body_for(body) # editing a content-type to check a decode path, say - rewrote the # stand-in for every later request in the example. The real transport builds a fresh # hash per response, and this exists to behave like it. - def build_response(stub, body, raw_body, json:) - Response.new(status: stub[:status], headers: stub[:headers].dup.freeze, body: body, raw_body: raw_body, json: json) + def build_response(stub, body, raw_body, json:, headers: stub[:headers]) + Response.new(status: stub[:status], headers: headers.dup.freeze, body: body, raw_body: raw_body, json: json) end # Where the endpoint is stubbed and only the query kept every stub from diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 75a37cf..fc11773 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1278,6 +1278,79 @@ def self.retried?(config, method, response) !Faraday::Retry::Middleware.new(nil, options).calculate_sleep_amount(1, { response_headers: Faraday::Utils::Headers.new(response.headers) }).nil? end + # A Content-Length that can be compared: one figure, and nothing else. + # Two that were sent arrive joined by a comma, and say nothing certain. + CONTENT_LENGTH = /\A\d+\z/ + private_constant :CONTENT_LENGTH + + # A 2xx response, once its body is known to have arrived: see + # {.missing_bytes}. + # + # Raised with the response, as the one {ConnectionError} that has one: + # Zammad answered, so a write was applied, and {Resources::Base#save!} + # and {Resources::Base#destroy} have to hear that to settle the record. + # + # On the class and public for {Test}, like {.retried?}: the stand-in + # handed such a response back as whole, so code that handles a save cut + # short could not be exercised against it, and a fixture carrying a + # stale Content-Length passed there and failed on the wire. + # + # @api private + # @param response [Response] + # @param operation [String] + # @param config [Config] of the client that sent the request + # @return [Response] + # @raise [IncompleteResponseError] + def self.whole(response, operation:, config:) + missing = missing_bytes(response) + return response if missing.nil? + + raise IncompleteResponseError.new( + "Can't #{operation}: the response from #{config.redacted_url} ended #{missing} bytes short of the " \ + "#{response.headers['content-length']} its Content-Length announces, so the connection was closed " \ + 'before the body had arrived', + response: response + ) + end + + # How many bytes of its body a response stopped short by, where it did. + # + # A body framed by Content-Length ends where the count is reached, or + # where the connection does. Net::HTTP takes the second for the first + # without a word - its +ignore_eof+ is on by default - so a download + # the connection dropped under came back as the file: + # {Resources::TicketArticleAttachment#download} returned the first ten + # bytes of a thousand, and whatever wrote them to disk wrote a file that + # opens as a broken one. A chunked body cut short did raise, and a JSON + # one that no longer parses is refused where it is decoded, so this was + # the one response that came back wrong and looked right. + # + # Asked only where the bytes in hand are the bytes that were counted. A + # body under a Content-Encoding may have been decoded on the way here, + # by an adapter that leaves both headers as they arrived. The default + # one does: Net::HTTP drops the one and corrects the other while it + # reads the body, and Faraday has taken its copy of the headers by + # then. So a compressed body cut short is not caught here, and + # {Resources::TicketArticleAttachment#download} asks for its file + # uncompressed. A body under a Transfer-Encoding is not framed by the + # count at all, and a 204 has no body whatever a header beside it says. + # + # Only a body that is short. One that is longer was not cut off. + # + # @api private + # @param response [Response] + # @return [Integer, nil] nil for a response that is whole, or that + # cannot be told + def self.missing_bytes(response) + headers = response.headers + announced = headers['content-length'] + return nil if announced.nil? || !CONTENT_LENGTH.match?(announced) + return nil if response.status == 204 || headers.key?('content-encoding') || headers.key?('transfer-encoding') + + missing = announced.to_i - response.raw_body.bytesize + missing.positive? ? missing : nil + end + # What {#inspect} says of a transport or of a client, for a JSON # encoder. Public for {Client#as_json}, whose transport may be another # kind than this one. @@ -1399,7 +1472,7 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou response = decode(perform(method, path, query, payload, headers)) log_response(method, path, response, started) - return whole(response, operation) if response.success? + return Transport.whole(response, operation: operation, config: config) if response.success? raise ResponseError.build(response, operation: operation, resource_class: resource_class) rescue Faraday::TimeoutError, *TIMEOUT_ERRORS => e @@ -1416,68 +1489,6 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou private - # A Content-Length that can be compared: one figure, and nothing else. - # Two that were sent arrive joined by a comma, and say nothing certain. - CONTENT_LENGTH = /\A\d+\z/ - private_constant :CONTENT_LENGTH - - # A 2xx response, once its body is known to have arrived: see - # {#missing_bytes}. - # - # Raised with the response, as the one {ConnectionError} that has one: - # Zammad answered, so a write was applied, and {Resources::Base#save!} - # and {Resources::Base#destroy} have to hear that to settle the record. - # - # @return [Response] - # @raise [IncompleteResponseError] - def whole(response, operation) - missing = missing_bytes(response) - return response if missing.nil? - - raise IncompleteResponseError.new( - "Can't #{operation}: the response from #{config.redacted_url} ended #{missing} bytes short of the " \ - "#{response.headers['content-length']} its Content-Length announces, so the connection was closed " \ - 'before the body had arrived', - response: response - ) - end - - # How many bytes of its body a response stopped short by, where it did. - # - # A body framed by Content-Length ends where the count is reached, or - # where the connection does. Net::HTTP takes the second for the first - # without a word - its +ignore_eof+ is on by default - so a download - # the connection dropped under came back as the file: - # {Resources::TicketArticleAttachment#download} returned the first ten - # bytes of a thousand, and whatever wrote them to disk wrote a file that - # opens as a broken one. A chunked body cut short did raise, and a JSON - # one that no longer parses is refused where it is decoded, so this was - # the one response that came back wrong and looked right. - # - # Asked only where the bytes in hand are the bytes that were counted. A - # body under a Content-Encoding may have been decoded on the way here, - # by an adapter that leaves both headers as they arrived. The default - # one does: Net::HTTP drops the one and corrects the other while it - # reads the body, and Faraday has taken its copy of the headers by - # then. So a compressed body cut short is not caught here, and - # {Resources::TicketArticleAttachment#download} asks for its file - # uncompressed. A body under a Transfer-Encoding is not framed by the - # count at all, and a 204 has no body whatever a header beside it says. - # - # Only a body that is short. One that is longer was not cut off. - # - # @return [Integer, nil] nil for a response that is whole, or that - # cannot be told - def missing_bytes(response) - headers = response.headers - announced = headers['content-length'] - return nil if announced.nil? || !CONTENT_LENGTH.match?(announced) - return nil if response.status == 204 || headers.key?('content-encoding') || headers.key?('transfer-encoding') - - missing = announced.to_i - response.raw_body.bytesize - missing.positive? ? missing : nil - end - # Whether a connection failure is a timeout underneath. # # An exceeded +open_timeout+ is raised by Net::HTTP as Net::OpenTimeout, @@ -1753,7 +1764,7 @@ def apply_authentication(faraday) # The header values as text, as well as the names. Faraday keeps a value # as whatever wrote it: faraday-gzip sets Content-Length to the Integer - # length of what it inflated, and {#missing_bytes} asked a regexp of that, + # length of what it inflated, and {.missing_bytes} asked a regexp of that, # so every 2xx behind such a middleware raised a bare TypeError. def decode(faraday_response) headers = faraday_response.headers.to_h.to_h { |name, value| [name.to_s.downcase, value.to_s] }.freeze diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs index 66fef4c..e7d8101 100644 --- a/sig/zammad_api/test.rbs +++ b/sig/zammad_api/test.rbs @@ -67,7 +67,8 @@ module ZammadAPI def matches?: (Hash[untyped, untyped]? expected, Hash[String, untyped] params) -> bool def paged_body: (Hash[Symbol, untyped] stub, Hash[String, untyped] params, untyped body) -> untyped def response_for: (Hash[Symbol, untyped] stub, Hash[String, untyped] params) -> Response - def build_response: (Hash[Symbol, untyped] stub, untyped body, String raw_body, json: bool) -> Response + def recounted: (Hash[String, String] headers, String raw_body) -> Hash[String, String] + def build_response: (Hash[Symbol, untyped] stub, untyped body, String raw_body, json: bool, ?headers: Hash[String, String]) -> Response def unstubbed_message: (Symbol method, String path, Hash[String, untyped] params) -> String def unmatched_query_message: (String request, Hash[String, untyped] params, Array[Hash[String, untyped]?] scopes) -> String diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 3fb79a9..210812e 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -88,6 +88,8 @@ module ZammadAPI def self.not_a_json_value_message: (untyped value, untyped key) -> String def self.retry_options: (Config config) -> Hash[Symbol, untyped] def self.retried?: (Config config, Symbol method, Response response) -> bool + def self.whole: (Response response, operation: String, config: Config) -> Response + def self.missing_bytes: (Response response) -> Integer? def self.description: (Config config, String? on_behalf_of) -> Hash[Symbol, untyped] def initialize: (Config) -> void @@ -102,8 +104,6 @@ module ZammadAPI private - def whole: (Response response, String operation) -> Response - def missing_bytes: (Response response) -> Integer? def timed_out?: (untyped error) -> bool def perform: (Symbol, String, Hash[Symbol, untyped]?, String?, Hash[untyped, untyped]?) -> untyped def build_connection: () -> untyped diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 3cbf222..da76d3f 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -987,6 +987,77 @@ def find = client.groups.find(1) end end + # The wire refuses a 2xx whose body stops short of its Content-Length, and + # the stand-in handed it back: code that handles a save cut short could + # not be exercised here, and a fixture with a stale Content-Length passed + # here and failed against Zammad. + describe 'a 2xx stubbed with a Content-Length its body is short of' do + subject(:zammad) { described_class.new } + + let(:client) { zammad.client } + let(:cut_short) { { status: 200, body: '{"id":1,"na', headers: { 'Content-Type' => 'application/json', 'Content-Length' => '30' } } } + + it 'raises what the wire raises, in its words' do + zammad.stub(:get, 'api/v1/groups/1', **cut_short) + + expect { client.groups.find(1) } + .to raise_error(ZammadAPI::IncompleteResponseError, %r{Can't find object: the response from https://zammad\.test/ ended 19 bytes short of the 30}) + end + + it 'hands over the response as far as it was stubbed' do + zammad.stub(:get, 'api/v1/groups/1', **cut_short) + + expect { client.groups.find(1) } + .to raise_error(ZammadAPI::IncompleteResponseError) { expect(it.response.raw_body).to eq('{"id":1,"na') } + end + + it 'leaves a record whose save it answers saved, as the wire does' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) + zammad.stub(:put, 'api/v1/groups/1', **cut_short) + group = client.groups.find(1) + group.name = 'Support' + + expect { group.save }.to raise_error(ZammadAPI::IncompleteResponseError) + expect(group.changed?).to be(false) + end + + it 'records the request, and does not send a read again for it' do + zammad.stub(:get, 'api/v1/groups/1', **cut_short) + + expect { client.groups.find(1) }.to raise_error(ZammadAPI::IncompleteResponseError) + expect(zammad.requests.map(&:path)).to eq(['api/v1/groups/1']) + end + + it 'takes a body as long as its Content-Length, or longer' do + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }, headers: { 'Content-Length' => 8 }) + zammad.stub(:get, 'api/v1/groups/2', body: { id: 2 }, headers: { 'Content-Length' => 2 }) + + expect([client.groups.find(1).id, client.groups.find(2).id]).to eq([1, 2]) + end + + it 'takes a 204, which has no body whatever the header says' do + zammad.stub(:delete, 'api/v1/groups/1', status: 204, headers: { 'Content-Length' => 5 }) + + expect(client.groups.destroy(1)).to be(true) + end + + it 'raises the error of its status for a response that is no 2xx' do + zammad.stub(:get, 'api/v1/groups/1', status: 404, body: { error: 'gone' }, headers: { 'Content-Length' => 500 }) + + expect { client.groups.find(1) }.to raise_error(ZammadAPI::NotFoundError) + end + + # The page after a list is one the stand-in makes up, and the length + # written for the records does not count it. + it 'counts the empty page it serves after a list anew' do + records = [{ id: 1 }, { id: 2 }] + zammad.stub(:get, 'api/v1/groups', body: records, headers: { 'Content-Length' => JSON.generate(records).bytesize }) + + expect(client.groups.map(&:id)).to eq([1, 2]) + expect(client.get('api/v1/groups', query: { page: 2 }).headers['content-length']).to eq('2') + end + end + describe 'a list endpoint whose resource says it does not page' do let(:resource) do Class.new(ZammadAPI::Resources::Base) do From a48c4829d7313f9eb4921443283c812ca6513c60 Mon Sep 17 00:00:00 2001 From: Mantas Date: Mon, 23 Nov 2026 13:59:26 +0200 Subject: [PATCH 077/121] fix: take a user agent of only whitespace for unset --- CHANGELOG.md | 5 +++++ lib/zammad_api/config.rb | 17 ++++++++++++++++- sig/zammad_api/config.rbs | 1 + spec/unit/zammad_api/config_spec.rb | 12 ++++++++++++ spec/unit/zammad_api/transport_spec.rb | 6 ++++++ 5 files changed, 40 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44df713..8ddb28b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1195,6 +1195,11 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a short could not be tested against it, and a fixture carrying a stale `Content-Length` passed there and failed against Zammad. The empty page it serves after a stubbed list is given a length of its own. +- A `user_agent` of nothing but whitespace falls back to the gem's own, as `nil` and an + empty one do. The whitespace is taken off the value where it is sent, so + `user_agent: ' '`, which is what an environment variable set to a space gives, went out + as a `User-Agent` header with nothing in it, and the requests named no client in the + instance log. ### Changed diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index d9e42bc..2d69e34 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -211,7 +211,7 @@ def initialize( password: immutable(non_empty(password)), http_token: immutable(normalize_token(:http_token, http_token)), oauth2_token: immutable(normalize_token(:oauth2_token, oauth2_token)), - user_agent: immutable(non_empty(user_agent) || DEFAULT_USER_AGENT), + user_agent: immutable(normalize_user_agent(user_agent)), timeout: timeout, open_timeout: open_timeout, retries: retries, @@ -599,6 +599,21 @@ def normalize_token(name, value) self.class.blank_token?(value) ? nil : value end + # The user agent as it is held: the one given, or the gem's own where + # none was. + # + # One of nothing but whitespace is none, as a token of that is, and for + # the same reason: the transport takes the whitespace off the value it + # sends, so `user_agent: ' '` was sent as a `User-Agent` header with + # nothing in it. Faraday fills in its own only where there is no header + # at all, so the requests went out naming no client, in the instance log + # an operator greps to find them. + def normalize_user_agent(value) + return DEFAULT_USER_AGENT if non_empty(value).nil? || self.class.blank_token?(value) + + value + end + # A proxy is the second string here that may carry credentials, and the # only other one rendered rather than replaced wholesale. Unchecked, a # URI - what `URI(...)` hands back, and what prints as the URL - was diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index 44ff778..e265d7c 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -78,6 +78,7 @@ module ZammadAPI def redact_userinfo: (String) -> String def normalize_token: (Symbol name, untyped value) -> String? + def normalize_user_agent: (untyped value) -> untyped def normalize_proxy: (untyped) -> String? def normalize_adapter: (untyped) -> Symbol? def render: (Symbol, untyped) -> String diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 7b09225..dfbe467 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -264,6 +264,18 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect(build(user_agent: '').user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") end + # The transport takes the whitespace off the value it sends, so this one + # went out as a User-Agent header with nothing in it. + [' ', "\n", " \t\r\n"].each do |blank| + it "falls back to the default when it is #{blank.inspect}, which a header would carry nothing of" do + expect(build(user_agent: blank).user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + end + end + + it 'keeps one with whitespace around it, which is taken off where it is sent' do + expect(build(user_agent: ' my-app/1.0 ').user_agent).to eq(' my-app/1.0 ') + end + it 'rejects one that is not a string' do expect { build(user_agent: 42) } .to raise_error(ZammadAPI::ConfigurationError, 'config user_agent needs to be a string') diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index d73ccd6..07f535a 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -48,6 +48,12 @@ expect(stub).to have_been_requested end + it 'names itself where the user agent given is nothing but whitespace' do + stub = stub_request(:get, url).with(headers: { 'User-Agent' => "zammad_api-ruby/#{ZammadAPI::VERSION}" }).to_return(json_response([])) + unit_transport(user_agent: ' ').get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested + end + # Net::HTTP refused it at the request, quoting the value. it 'refuses a raw request header with a line break inside it, without quoting it' do expect { described_class.stringify_headers('X-Api-Key' => "abc\r\nsecret") } From de5109a8a24b902524d832ec81389f34bfb058e7 Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 24 Nov 2026 11:47:00 +0200 Subject: [PATCH 078/121] fix: use a proxy set for every Faraday connection --- CHANGELOG.md | 8 +++++ lib/zammad_api/transport.rb | 43 ++++++++++++++++++++++--- sig/vendor/faraday.rbs | 1 + sig/zammad_api/transport.rbs | 2 ++ spec/unit/zammad_api/transport_spec.rb | 44 ++++++++++++++++++++++++++ 5 files changed, 93 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ddb28b..3528ceb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1200,6 +1200,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `user_agent: ' '`, which is what an environment variable set to a space gives, went out as a `User-Agent` header with nothing in it, and the requests named no client in the instance log. +- A proxy set in `Faraday.default_connection_options` is used where `proxy:` names none, as + the README says of those options and as 1.x did. The connection was built with + `proxy: nil` for a client without one, and an option named as `nil` stands in for the + default as one with a value does, so that proxy was taken off this client's connection + alone: its requests went out directly, or nowhere where only the proxy reaches the + instance. A proxy the configuration names still comes first. One set there that cannot + be parsed is reported as a `ConfigurationError` with its credentials redacted, as a + configured one is. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index fc11773..73acd32 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1535,7 +1535,6 @@ def perform(method, path, query, payload, headers) def build_connection connection = Faraday.new( url: config.url, - proxy: config.proxy, ssl: { verify: config.ssl_verify }, # The encoder is this gem's own: see {QueryEncoder} for the one # structure Faraday's writes so that Rails reads another. @@ -1543,7 +1542,8 @@ def build_connection headers: { 'User-Agent' => Transport.stripped(config.user_agent), 'Accept' => 'application/json' }, # Named, and as nil, so that it stands in for the parameters of # `Faraday.default_connection_options`: see #drop_shared_headers. - params: nil + params: nil, + **configured_proxy ) do |faraday| drop_shared_headers(faraday) apply_authentication(faraday) @@ -1574,6 +1574,20 @@ def build_connection raise ConfigurationError, "config could not be used to build a connection: #{e.class}: #{redact_config_values(e.message)}", cause: reportable_cause(e) end + # The `proxy:` option, where one is configured, and no option where none + # is. + # + # What is named here stands in for what `Faraday.default_connection_options` + # holds under the same name, and a name given as nil does that as well as + # one given a value. `proxy: config.proxy` was passed whatever it was, so + # the proxy a process had set there for all of its Faraday connections + # was taken off this one: its requests went out directly, or nowhere + # where only the proxy reaches the instance, while the README said that a + # proxy set there applies and 1.x, which named no proxy, had used it. + # + # @return [Hash{Symbol => String}] + def configured_proxy = config.proxy ? { proxy: config.proxy } : {} + # Runs the caller's `middleware:` callable, and then settles the adapter. # # The adapter used to be set after the callable, unconditionally, and @@ -1654,10 +1668,11 @@ def reportable_cause(error) # because {Config} can only refuse the credentials in a url it can read: # one that is not a URL at all gets this far, and is quoted here. # - # And the proxies the environment names, which no option holds: see - # {#environment_proxies}. + # And the proxies the environment names, which no option holds, and the + # one a process set for all of its Faraday connections: see + # {#environment_proxies} and {#shared_proxies}. def redact_config_values(message) - [config.proxy, config.url, *environment_proxies].compact.inject(message.to_s) do |text, value| + [config.proxy, config.url, *shared_proxies, *environment_proxies].compact.inject(message.to_s) do |text, value| spellings = quoted_spellings(value) # Of the value as it can be read. A configured one is its own first # spelling, and redacting text with a broken byte in it raises. @@ -1709,6 +1724,24 @@ def environment_proxies ENV.filter_map { |name, value| value if name.match?(ENVIRONMENT_PROXY) && !value.empty? } end + # The proxy URL `Faraday.default_connection_options` names, to be + # scrubbed from an error as the configured one is. + # + # With no `proxy:` given, that one is this connection's: see + # {#configured_proxy}. So one URI cannot parse is quoted by the same + # error a configured one is, password included, and is a value of + # neither the configuration nor the environment. It is given there as + # the URL or as a Hash that holds it under `uri`, and one that is neither + # has been parsed already. + # + # @return [Array] + def shared_proxies + proxy = Faraday.default_connection_options.proxy + proxy = proxy[:uri] || proxy['uri'] if proxy.is_a?(Hash) + + proxy.is_a?(String) && !proxy.empty? ? [proxy] : [] + end + # The value as an error may have quoted it: as it is, as +inspect+ # writes it, and as +dump+ does. # diff --git a/sig/vendor/faraday.rbs b/sig/vendor/faraday.rbs index a811cfb..6b0f0a9 100644 --- a/sig/vendor/faraday.rbs +++ b/sig/vendor/faraday.rbs @@ -70,4 +70,5 @@ module Faraday def self.new: (**untyped) ?{ (Connection) -> void } -> Connection def self.default_adapter: () -> Symbol + def self.default_connection_options: () -> untyped end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 210812e..af4b48e 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -107,6 +107,7 @@ module ZammadAPI def timed_out?: (untyped error) -> bool def perform: (Symbol, String, Hash[Symbol, untyped]?, String?, Hash[untyped, untyped]?) -> untyped def build_connection: () -> untyped + def configured_proxy: () -> Hash[Symbol, String] def apply_middleware_and_adapter: (untyped faraday) -> void def refuse_unusable_middleware!: (untyped connection) -> void def refused_middleware: (Class klass) -> String? @@ -121,6 +122,7 @@ module ZammadAPI def unlogged_body: (String body) -> String def reportable_cause: (StandardError error) -> StandardError? def redact_config_values: (untyped message) -> String + def shared_proxies: () -> Array[String] def environment_proxies: () -> Array[String] def quoted_spellings: (String value) -> Array[String] def logger: () -> Logger diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 07f535a..06b97a2 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1930,6 +1930,50 @@ def sent = a_request(:get, url).with(query: hash_including({})) expect(a_request(:get, url).with(query: { 'tenant' => 'a' })).to have_been_made.once end + + # A name given as nil stands in for the default as well as one given a + # value, and `proxy:` was passed whatever the configuration held. So the + # proxy set there was taken off this connection alone, and its requests + # went out directly. + context 'with a proxy among them' do + before { Faraday.default_connection_options.proxy = shared } + + let(:shared) { 'http://shared.proxy.test:3128' } + + def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.uri.to_s + + it 'goes through that proxy where the configuration names none' do + expect(proxy_of(unit_transport)).to eq(shared) + end + + it 'goes through the configured proxy where it names one' do + expect(proxy_of(unit_transport(proxy: 'http://own.proxy.test:8080'))).to eq('http://own.proxy.test:8080') + end + + it 'takes an empty proxy: for none, as it is everywhere else' do + expect(proxy_of(unit_transport(proxy: ''))).to eq(shared) + end + + # It is this connection's proxy now, so it is this error that quotes + # one URI cannot parse, and it is a value of no option. + [ + 'http://puser:pa ss@shared.proxy.test:3128', + { uri: 'http://puser:pa ss@shared.proxy.test:3128' } + ].each do |unreadable| + context "when it is #{unreadable.class} and cannot be parsed" do + let(:shared) { unreadable } + + it 'reports it as a configuration error without its password' do + expect { unit_transport }.to raise_error(ZammadAPI::ConfigurationError) { |error| + report = error.full_message(highlight: false) + + expect(report).to include('[REDACTED]@shared.proxy.test:3128') + expect(report).not_to include('pa ss') + } + end + end + end + end end describe '#with_on_behalf_of' do From 2750f3829efd4c987d362c48ca59823da8a8ccd1 Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 24 Nov 2026 11:49:30 +0200 Subject: [PATCH 079/121] fix: make to_h of attributes plain at every depth --- CHANGELOG.md | 14 ++++- README.md | 15 +++++ lib/zammad_api/attributes.rb | 30 +++++++++- sig/zammad_api/attributes.rbs | 2 + spec/unit/zammad_api/attributes_spec.rb | 62 +++++++++++++++++++++ spec/unit/zammad_api/resources/base_spec.rb | 17 ++++++ 6 files changed, 136 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3528ceb..a2a0d4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1152,8 +1152,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `ZammadAPI::Attributes` now, as is every Hash inside them: a Hash that prints with the value under each key naming a credential blanked, through `inspect`, `to_s` and `pp`. It reads, compares and serializes as the Hash it was, to JSON and to YAML alike, and `to_h` - is a plain Hash. A String cannot be told how to print, so a write into the password - itself, `user.attributes[:password] << 'x'`, still quotes it. + is a plain Hash. A strict JSON encoder is the one thing that goes by the class: see + below. A String cannot be told how to print, so a write into the password itself, + `user.attributes[:password] << 'x'`, still quotes it. - `destroy` no longer reports a record destroyed where something that is not Zammad answered the request. Every 2xx settled it, so a single sign-on gateway that answered the DELETE with its login page and status 200 made `group.destroy` return `true` and left the record @@ -1208,6 +1209,15 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a instance. A proxy the configuration names still comes first. One set there that cannot be parsed is reported as a `ConfigurationError` with its credentials redacted, as a configured one is. +- `to_h` of a record's `attributes`, of its `changes` and of any Hash among them is plain + Hashes at every depth, and a writable copy. Each of those is a `ZammadAPI::Attributes`, + and a JSON encoder that takes nothing but the core types refuses a subclass of Hash by + its class: `JSON.generate(user.attributes, strict: true)` and `JSON::Coder.new.dump` + raise `ZammadAPI::Attributes not allowed in JSON`, for what 1.x handed out as Hashes. + `attributes.to_h` was plain no further than its first nested Hash, so it was refused the + same way, and only `record.to_h` could be handed to such an encoder. The README and the + migration table say that `to_h` is what a strict encoder is given. `to_json`, `as_json` + and `JSON.generate` without `strict:` are unchanged. ### Changed diff --git a/README.md b/README.md index 146ecca..ae44f2b 100644 --- a/README.md +++ b/README.md @@ -592,6 +592,20 @@ Hash that prints with the value under a key such as `password` or `token` blanke `inspect` of the record prints them, and that is a Hash in every other way. Reading from it hands over every value, and `to_h` is a plain Hash. +Every Hash inside them is one as well, and an encoder that takes nothing but the core types +goes by the class: `JSON.generate(group.attributes, strict: true)` and a `JSON::Coder` +without a block raise `ZammadAPI::Attributes not allowed in JSON`. Hand such an encoder +`to_h`, which is plain Hashes at every depth, of the record or of any Hash it holds: + +```ruby +JSON.generate(user.to_h, strict: true) # the record +JSON.generate(user.changes.to_h, strict: true) # what is staged +JSON.generate(user.preferences.to_h, strict: true) # one attribute +``` + +`to_json`, `as_json`, `JSON.generate` without `strict:` and YAML take the attributes as +they are. + ### Pattern matching Records implement `deconstruct_keys`, so they work with `case/in`: @@ -1631,6 +1645,7 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | ----------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------- | | `record.save` raised on a rejection | `save` → `false` with `record.error`; `save!` raises | Branching on a rejected attribute needed a begin/rescue | | `record.attributes[:x] = 1` | `record.x = 1`, or `record.to_h` for a copy | Writing through the reader staged no change, so `save` never sent it | +| `JSON.generate(record.attributes, strict: true)` | `JSON.generate(record.to_h, strict: true)` | `attributes` and every Hash in it is a `ZammadAPI::Attributes`, which a strict encoder refuses by its class; `to_h` is plain Hashes throughout | | `record.attributes = {...}` | `record.assign_attributes(...)` / `record.update(...)` | The writer is gone, and the name now stages an attribute of its own | | `record.id = 5` | `client.x.find(5)` | The id addresses the record, so a staged one deleted or updated a different record than it reported | | `record.new_instance` | `record.new_record?` / `record.persisted?` | Internal flag is no longer public; the old name raises `NoMethodError`, naming the attributes the record does carry | diff --git a/lib/zammad_api/attributes.rb b/lib/zammad_api/attributes.rb index 1ba5fdf..b985251 100644 --- a/lib/zammad_api/attributes.rb +++ b/lib/zammad_api/attributes.rb @@ -16,8 +16,14 @@ module ZammadAPI # # Only the printing. Every value reads as it is, and +to_h+, +to_json+ and # YAML write them out, because handing them over is what a record is for. - # A Hash made from this one, by +slice+, +select+ or +to_h+, is a plain - # Hash again. + # {#to_h} is a plain Hash at every depth. One made by +slice+ or +select+ + # is plain itself and holds the Hashes inside it as they are, which are of + # this class. + # + # One thing does ask for the class: a JSON encoder that takes nothing but + # the core types, `JSON.generate(value, strict: true)` and a `JSON::Coder` + # without a block, refuses a subclass of Hash by its name. {#to_h} is what + # to hand it. # # What it holds is not covered where that is not a Hash. A String cannot # be told how to print, so `user.attributes[:password] << 'x'` still @@ -35,6 +41,26 @@ def inspect = Transport.redact(self).inspect # Hash defines unless it is named again here. alias to_s inspect + # A plain Hash of plain Hashes, the caller's own to modify. + # + # +Hash#to_h+ answers with a plain Hash that holds what this one holds, + # and every Hash inside the attributes of a record is of this class too. + # So `user.attributes.to_h` was plain as far as its first nested Hash, + # and a strict JSON encoder refused it there as it refuses the + # attributes themselves: "ZammadAPI::Attributes not allowed in JSON", + # for what 1.x handed out as Hashes. What {Resources::Base#to_h} answers + # for the whole record, this answers for any part of it: + # `user.preferences.to_h`. + # + # With a block it is +Hash#to_h+, which builds a plain Hash from the + # pairs the block answers. + # + # The steep:ignore is for the two shapes of the method in one body: the + # checker holds each branch to both of them. + # + # @return [Hash] a writable deep copy + def to_h(&block) = block ? super : DeepCopy.writable_copy(self) # steep:ignore MethodBodyTypeMismatch + # What +pp+ prints, which is not what {#inspect} answers for a Hash. # # @param printer [PP] diff --git a/sig/zammad_api/attributes.rbs b/sig/zammad_api/attributes.rbs index a9377e6..a9ef1f1 100644 --- a/sig/zammad_api/attributes.rbs +++ b/sig/zammad_api/attributes.rbs @@ -3,6 +3,8 @@ module ZammadAPI class Attributes[unchecked out K, unchecked out V] < Hash[K, V] def inspect: () -> String def to_s: () -> String + def to_h: () -> Hash[K, V] + | [A, B] () { (K, V) -> [A, B] } -> Hash[A, B] def pretty_print: (untyped printer) -> void def encode_with: (untyped coder) -> void end diff --git a/spec/unit/zammad_api/attributes_spec.rb b/spec/unit/zammad_api/attributes_spec.rb index 2809fea..a63cd31 100644 --- a/spec/unit/zammad_api/attributes_spec.rb +++ b/spec/unit/zammad_api/attributes_spec.rb @@ -44,6 +44,68 @@ expect(JSON.generate(attributes)).to eq(JSON.generate(plain)) end + # Every Hash a record holds is of this class, whatever it is inside of. + # Hash#to_h answers with a plain Hash holding what the receiver held, so + # the conversion stopped at the first nested Hash. + describe '#to_h' do + subject(:attributes) { ZammadAPI::DeepCopy.frozen_copy(plain, symbolize_keys: true) } + + let(:plain) { { login: 'jane', preferences: { locale: 'de', devices: [{ name: 'phone' }] }, roles: [{ name: 'Agent' }] } } + + def classes_in(value) + case value + when Hash then [value.class, *value.each_value.flat_map { classes_in(it) }] + when Array then value.flat_map { classes_in(it) } + else [] + end + end + + it 'holds a Hash of this class at every depth to begin with' do + expect(classes_in(attributes).uniq).to eq([described_class]) + end + + it 'is a plain Hash at every depth, inside an Array as well' do + expect(classes_in(attributes.to_h).uniq).to eq([Hash]) + end + + it 'holds what the attributes hold' do + expect(attributes.to_h).to eq(plain) + end + + it 'is the caller\'s own to modify, down to a String' do + copy = attributes.to_h + copy[:preferences][:devices] << { name: 'tablet' } + copy[:login] << '.doe' + + expect(attributes).to eq(plain) + end + + it 'is the same for a Hash read out of the attributes' do + expect(classes_in(attributes[:preferences].to_h).uniq).to eq([Hash]) + end + + it 'builds a plain Hash from the pairs a block answers, as Hash#to_h does' do + expect(attributes.to_h { |key, _| [key.to_s, key.size] }).to eq('login' => 5, 'preferences' => 11, 'roles' => 5) + end + + # The encoders that take the core types and nothing else go by the class + # of the object, and name the one they refuse. + context 'with a JSON encoder that takes nothing but the core types' do + it 'is refused as it stands, by the name of its class' do + expect { JSON.generate(attributes, strict: true) } + .to raise_error(JSON::GeneratorError, /ZammadAPI::Attributes not allowed in JSON/) + end + + it 'is written by JSON.generate with strict: true' do + expect(JSON.generate(attributes.to_h, strict: true)).to eq(JSON.generate(plain)) + end + + it 'is written by a JSON::Coder' do + expect(JSON::Coder.new.dump(attributes.to_h)).to eq(JSON.generate(plain)) + end + end + end + # Psych tags a subclass of Hash with its class and refuses to load a tag # it was not told of, so the YAML of a record's attributes would not load. it 'is written to YAML as the mapping a Hash is, and loads as one' do diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index c59573e..88a43ea 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -278,6 +278,23 @@ def message_of it 'hands out plain Hashes from #to_h, which print what they hold' do expect(user.to_h).to be_an_instance_of(Hash).and(satisfy { it[:preferences].instance_of?(Hash) }) end + + # An encoder that takes nothing but the core types goes by the class, + # and `attributes.to_h` was plain no further than its first Hash. + it 'hands out plain Hashes from attributes.to_h, for a strict JSON encoder' do + expect(JSON.generate(user.attributes.to_h, strict: true)).to eq(JSON.generate(user.to_h)) + end + + it 'hands out plain Hashes from changes.to_h' do + user.preferences = { bind_pw: 'other', locale: 'en' } + + expect(JSON.generate(user.changes.to_h, strict: true)) + .to eq('{"preferences":[{"bind_pw":"s3cret","locale":"de"},{"bind_pw":"other","locale":"en"}]}') + end + + it 'hands out a plain Hash from to_h of a Hash it holds' do + expect(JSON.generate(user.preferences.to_h, strict: true)).to eq('{"bind_pw":"s3cret","locale":"de"}') + end end # A save whose answer cannot be read puts the record on what it sent, From 6e90d929f583c06717367947ea5f9872b8dbead9 Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 24 Nov 2026 11:53:50 +0200 Subject: [PATCH 080/121] fix: convert text of another encoding to UTF-8 for a URL --- CHANGELOG.md | 14 +++++ lib/zammad_api/resource_proxy.rb | 17 +++++- lib/zammad_api/transport.rb | 47 ++++++++++----- sig/zammad_api/resource_proxy.rbs | 1 + sig/zammad_api/transport.rbs | 1 + spec/unit/zammad_api/resource_proxy_spec.rb | 40 +++++++++++++ spec/unit/zammad_api/transport_spec.rb | 64 ++++++++++++++++++++- 7 files changed, 169 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a2a0d4a..6a16f1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1218,6 +1218,20 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a same way, and only `record.to_h` could be handed to such an encoder. The README and the migration table say that `to_h` is what a strict encoder is given. `to_json`, `as_json` and `JSON.generate` without `strict:` are unchanged. +- Text held in ISO-8859-1, Windows-1252 or any other encoding that is not UTF-8 goes into a + query and into a request path as the same text in UTF-8. Only an encoding ASCII is no part + of, such as UTF-16, was converted, so `client.users.search('Größe')` with the term read + from a Latin-1 file was sent as `query=Gr%F6%DFe`, the bytes it was held in, as 1.x sent + it. Rails answers a query it cannot read as UTF-8 with a 400, which arrived as a + `ClientError` for a term with nothing wrong with it, while the same String in a JSON body + was converted and arrived as the text it is. A record id in such an encoding was written + into the path the same way, and one in UTF-16 raised `Encoding::CompatibilityError`. A + header value and `on_behalf_of` are converted as well. `find_by` holds each hit against + the text it searched for: against the value as given, in ISO-8859-1 or UTF-16, the record + was found by the search and passed over by the comparison, so `find_by` answered `nil` + for a record that exists. Text that cannot be converted raises `ArgumentError`, which + names the parameter and does not quote it. A binary String is sent as its bytes, as + before. ### Changed diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index f7f0d49..a08ddc6 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -239,8 +239,9 @@ def find_by(**params) raise ArgumentError, 'find_by needs at least one attribute to match' if params.empty? id_key = params.keys.find { it.to_s == 'id' } - return find_by_id(params[id_key], params.except(id_key)) if id_key + return find_by_id(params[id_key], as_served(params.except(id_key))) if id_key + params = as_served(params) term = resource_class.searchable? ? search_term_for(params) : nil candidates = term ? search(term) : all @@ -694,6 +695,20 @@ def record_number(id) Integer(id, 10) if id.is_a?(String) && id.ascii_only? && id.match?(/\A\d+\z/) end + # The values to match, with text as Zammad serves it: in UTF-8. + # + # A value is searched for as the text {Transport.wire_text} sends, and + # every hit was then held against the value as it was given. Ruby takes + # two Strings in different encodings for different ones unless both are + # plain ASCII, so a name read from a file in ISO-8859-1, or held in + # UTF-16, was found by the search and passed over by the comparison: + # nil for a record that was among the hits, and + # `find_by(...) || create(...)` made its duplicate. + # + # @return [Hash] + # @raise [ArgumentError] for text that cannot be converted to UTF-8 + def as_served(params) = params.to_h { |key, value| [key, value.is_a?(String) ? Transport.wire_text(value, "find_by #{key}") : value] } + # Whether a record carries every one of these values. # # Read with +[]+ and not with a reader, which raises for an attribute diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 73acd32..c2b1e28 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -707,19 +707,35 @@ def self.stringify_on_behalf_of(identifier) # Encoding::CompatibilityError. BLANK = /\A[[:space:]]*\z/ - # A value as text a request can carry: in UTF-8 where it was given in an - # encoding ASCII is no part of, such as UTF-16. - # - # Such a String cannot be joined to the ASCII around it. Faraday's - # escaping of a query value and Net::HTTP's writing of a header both - # raised Encoding::CompatibilityError for one, as did {BLANK} asked of a - # +From+ scope or a search keyword: neither a {ZammadAPI::Error} nor the + # The encodings a value goes on the wire in as it stands: UTF-8, which is + # what Zammad reads, US-ASCII, which is the same bytes, and binary, which + # names no characters to convert. + WIRE_ENCODINGS = [Encoding::UTF_8, Encoding::US_ASCII, Encoding::BINARY].freeze + private_constant :WIRE_ENCODINGS + + # A value as text a request can carry: in UTF-8 where it was given in + # another encoding. + # + # A String in an encoding ASCII is no part of, such as UTF-16, cannot be + # joined to the ASCII around it. Faraday's escaping of a query value and + # Net::HTTP's writing of a header both raised + # Encoding::CompatibilityError for one, as did {BLANK} asked of a +From+ + # scope or a search keyword: neither a {ZammadAPI::Error} nor the # ArgumentError a malformed value is refused with, and for a non-blank # value, one that had nothing wrong with it but its encoding. Converted, # it is the same text, in the encoding Zammad reads. # - # An encoding ASCII is a part of is left as it was, binary included: its - # bytes are what went on the wire, and still are. + # One in an encoding ASCII is a part of can be joined, and was sent as + # the bytes it was held in. `search('Größe')` with the term read from a + # file in ISO-8859-1 or Windows-1252 went out as `query=Gr%F6%DFe`, + # which is no UTF-8, and Rails answers a query it cannot read as UTF-8 + # with a 400: a ClientError for a term with nothing wrong with it, while + # the same String in a JSON body was converted by the generator and + # arrived as the text it is. Converted here as well. + # + # A binary String is left as it was. It names no characters, so there + # is nothing to convert it from, and its bytes are what went on the + # wire. # # @api private # @param value [Object] @@ -728,7 +744,7 @@ def self.stringify_on_behalf_of(identifier) # @raise [ArgumentError] for text that cannot be converted to UTF-8 def self.wire_text(value, name) text = value.to_s - return text if text.encoding.ascii_compatible? + return text if WIRE_ENCODINGS.include?(text.encoding) begin text.encode(Encoding::UTF_8) @@ -783,6 +799,11 @@ def self.blank_on_behalf_of_message(identifier) # was right there. The message names the class and does not quote the # value, which for a record is every attribute it carries. # + # The bytes that are encoded are those of the id in UTF-8: see + # {.wire_text}. An id given in ISO-8859-1 was written as the bytes of + # that encoding, which name another record or none, and one given in + # UTF-16 raised Encoding::CompatibilityError from the pattern below. + # # Public for the same reason as {.stringify_query}: {Test} builds the # paths it records with it. # @@ -790,12 +811,12 @@ def self.blank_on_behalf_of_message(identifier) # @param value [Integer, String, Symbol, nil] # @return [String] # @raise [ArgumentError] when there is nothing to send, when the value - # is not an id at all, or when the id navigates instead of naming a - # record + # is not an id at all, when it is text that cannot be converted to + # UTF-8, or when the id navigates instead of naming a record def self.escape_path_segment(value) raise ArgumentError, not_a_record_id_message(value) if !value.nil? && RECORD_ID_TYPES.none? { value.is_a?(it) } - segment = value.to_s + segment = wire_text(value, 'a record id') raise ArgumentError, 'a record id is required, and this one is empty' if segment.empty? raise ArgumentError, "#{segment.inspect} points at another endpoint rather than naming a record" if DOT_SEGMENTS.include?(segment) diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs index ab89383..381cd24 100644 --- a/sig/zammad_api/resource_proxy.rbs +++ b/sig/zammad_api/resource_proxy.rbs @@ -64,6 +64,7 @@ module ZammadAPI def searchable!: () -> void def find_by_id: (untyped id, Hash[Symbol, untyped] others) -> R? def record_number: (untyped id) -> Integer? + def as_served: (Hash[Symbol, untyped] params) -> Hash[Symbol, untyped] def carries?: (Resources::Base record, Hash[Symbol, untyped] params) -> bool def search_term_for: (Hash[Symbol, untyped]) -> String? def path: () -> String diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index af4b48e..ca6f237 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -65,6 +65,7 @@ module ZammadAPI def self.stringify_headers: (Hash[untyped, untyped]) -> Hash[String, String] def self.stripped: (String text) -> String BLANK: Regexp + WIRE_ENCODINGS: Array[Encoding] def self.wire_text: (untyped value, String name) -> String LINE_BREAK_ADVICE: String def self.line_break?: (String text) -> bool diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 7096c82..b55db29 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -154,6 +154,46 @@ expect(proxy.find_by(name: 'Users').id).to eq(1) end + # The value is searched for as UTF-8, and Zammad serves UTF-8. Held + # against the value as it was given, the hit was passed over: Ruby takes + # two Strings in different encodings for different unless both are + # ASCII. + %w[ISO-8859-1 Windows-1252 UTF-16LE].each do |encoding| + context "with a value given in #{encoding}" do + let(:value) { 'Größe'.encode(encoding) } + + before do + stub_request(:get, search_url).with(query: hash_including('query' => 'Größe', 'page' => '1')).to_return(json_response([{ id: 1, name: 'Größe', note: 'ä' }])) + stub_request(:get, search_url).with(query: hash_including('query' => 'Größe', 'page' => '2')).to_return(json_response([])) + end + + it 'searches for the text in UTF-8 and returns the record that carries it' do + expect(proxy.find_by(name: value).id).to eq(1) + end + + it 'matches it beside an id as well' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Größe' })) + + expect(proxy.find_by(id: 1, name: value).id).to eq(1) + end + + it 'still answers nil where no hit carries it' do + expect(proxy.find_by(name: value, note: 'ö'.encode(encoding))).to be_nil + end + end + end + + it 'matches a value given in another encoding where the index is walked' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/ticket_states").with(query: hash_including({})).to_return(json_response([{ id: 4, name: 'geschlossen für immer' }])) + + expect(client.ticket_states.find_by(name: 'geschlossen für immer'.encode('ISO-8859-1')).id).to eq(4) + end + + it 'refuses a value that cannot be converted to UTF-8, naming the attribute and not the value' do + expect { proxy.find_by(name: "secret\x81".dup.force_encoding('Windows-1252')) } + .to raise_error(ArgumentError, /\Afind_by name was given as Windows-1252 text that cannot be converted to UTF-8/) + end + # Zammad's search sorts by updated_at, newest first, not by relevance, so # the exact match can sit on any page of hits. Reading only the first one # answered nil for a record that exists, and find_by(...) || create(...) diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 06b97a2..7c2a60e 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -324,12 +324,54 @@ def handed_to_the_adapter(**options) expect(stub).to have_been_requested end - it 'leaves a value in an encoding ASCII is a part of as it was' do + # An encoding ASCII is a part of can be joined to the text around it, + # so the value went out as the bytes it was held in: `query=Gr%F6%DFe`, + # which Rails answers with 400 for a query that is no UTF-8. + %w[ISO-8859-1 Windows-1252 Shift_JIS].each do |encoding| + it "sends a value given in #{encoding} as the same text in UTF-8" do + text = encoding == 'Shift_JIS' ? '検索 b' : 'Größe b' + stub = stub_request(:get, "#{url}/search").with(query: { 'query' => text }).to_return(json_response([])) + unit_transport.get('api/v1/groups/search', operation: 'test', query: { query: text.encode(encoding) }) + + expect(stub).to have_been_requested + end + end + + it 'writes the bytes of the UTF-8 text into the query string' do + query = described_class.stringify_query(query: 'Größe'.encode('ISO-8859-1')) + + expect(ZammadAPI::QueryEncoder.encode(query)).to eq('query=Gr%C3%B6%C3%9Fe') + end + + it 'converts such a value inside a list and a Hash as well' do + latin = 'Größe'.encode('ISO-8859-1') + + expect(described_class.stringify_query(tags: [latin], condition: { name: latin })) + .to eq('tags' => ['Größe'], 'condition' => { 'name' => 'Größe' }) + end + + it 'leaves a binary value as it was, which names no characters to convert' do value = "caf\xC3\xA9".b expect(described_class.stringify_query(q: value)['q']).to be(value) end + it 'leaves a value in UTF-8 or US-ASCII as it was' do + utf8 = 'Größe' + ascii = 'open'.encode('US-ASCII') + + expect(described_class.stringify_query(a: utf8, b: ascii).values).to match([be(utf8), be(ascii)]) + end + + it 'refuses a value with a byte its own encoding does not define, without quoting it' do + broken = "secret\x81".dup.force_encoding('Windows-1252') + + expect { described_class.stringify_query(token: broken) } + .to raise_error(ArgumentError, /\Aquery parameter token was given as Windows-1252 text that cannot be converted to UTF-8/) { |error| + expect(error.message).not_to include('secret') + } + end + it 'refuses a value that cannot be converted to UTF-8, without quoting it' do broken = "\xD8\x00".dup.force_encoding('UTF-16BE') @@ -756,6 +798,26 @@ def response(status, headers = {}) expect(described_class.escape_path_segment('ä')).to eq('%C3%A4') end + # The bytes of the id as it was held went into the path: `%E4` for an + # ä in ISO-8859-1, which is no UTF-8 and names no record. In UTF-16 the + # pattern raised Encoding::CompatibilityError. + %w[ISO-8859-1 Windows-1252 UTF-16LE].each do |encoding| + it "encodes the bytes of the UTF-8 text for an id given in #{encoding}" do + expect(described_class.escape_path_segment('ä/1'.encode(encoding))).to eq('%C3%A4%2F1') + end + end + + it 'raises for a dot segment given in UTF-16' do + expect { described_class.escape_path_segment('..'.encode('UTF-16LE')) }.to raise_error(ArgumentError, /points at another endpoint/) + end + + it 'raises for an id that cannot be converted to UTF-8, without quoting it' do + broken = "abc\x81".dup.force_encoding('Windows-1252') + + expect { described_class.escape_path_segment(broken) } + .to raise_error(ArgumentError, /\Aa record id was given as Windows-1252 text that cannot be converted to UTF-8/) + end + it 'raises for an id with nothing to send' do expect { described_class.escape_path_segment('') }.to raise_error(ArgumentError, /record id is required/) end From d88f789305113f10d2f940cd5d7a5bc519b446b5 Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 24 Nov 2026 11:58:41 +0200 Subject: [PATCH 081/121] fix: send a GET again for a body cut short --- CHANGELOG.md | 15 +++- README.md | 11 +-- lib/zammad_api/test.rb | 8 ++- lib/zammad_api/transport.rb | 94 +++++++++++++++++++++++--- sig/vendor/faraday.rbs | 8 +++ sig/vendor/internal.rbs | 14 ++++ sig/zammad_api/transport.rbs | 2 + spec/unit/zammad_api/test_spec.rb | 30 +++++++- spec/unit/zammad_api/transport_spec.rb | 71 +++++++++++++++++++ 9 files changed, 234 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a16f1b..c8a60e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -963,8 +963,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a without a word, so `attachment.download` returned the first bytes of a file as the file, and a raw request for anything that is not JSON did the same. Checked for a 2xx response that names one `Content-Length` and neither a `Content-Encoding` nor a - `Transfer-Encoding`; a chunked body cut short raised already. The request is not sent - again. + `Transfer-Encoding`; a chunked body cut short raised already. A `GET` is sent again for + it: see below. - A query value that is a number and neither an `Integer` nor a `Float` raises `ArgumentError`, as any other value a query string has no spelling for does. Every `Numeric` was taken as it prints: `client.users.search('smith', ids: [BigDecimal('5')])`, @@ -1232,6 +1232,17 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a for a record that exists. Text that cannot be converted raises `ArgumentError`, which names the parameter and does not quote it. A binary String is sent as its bytes, as before. +- A `GET` whose 2xx body stops short of its `Content-Length` is sent again, as often as + `retries` allows, before `IncompleteResponseError` is raised. The length was asked of the + response the retry middleware had already returned, so this was the one failure of a + connection a read was not repeated for: with `retries: 2`, an `attachment.download` the + connection dropped under raised after one request, while the same drop a moment earlier, + arriving as `ECONNRESET`, was asked again and answered. The check sits below the retry + now, in a middleware of the gem's own, and above the `middleware:` callable, so it reads + the body and the headers as that left them. A write is still sent once, since Zammad + answered it, and the error and the response it carries are what they were. + `ZammadAPI::Test` sends such a read again as well, each attempt taking the next stub of a + sequence. ### Changed diff --git a/README.md b/README.md index ae44f2b..6de1b95 100644 --- a/README.md +++ b/README.md @@ -1257,7 +1257,9 @@ repeated. ### Timeouts and retries A `GET` is retried on connection failures, timeouts and the transient statuses 429, 500, -502, 503 and 504, with exponential backoff. +502, 503 and 504, with exponential backoff. A 2xx whose body stopped short of its +`Content-Length` is a connection failure like any other: the `GET` is sent again, and +`IncompleteResponseError` is raised once the retries are spent. A `Retry-After` header on one of those responses is honoured: the client waits as long as the server asked before the next attempt, up to `timeout` seconds. A longer one is not @@ -1370,9 +1372,10 @@ the wire would refuse is refused here too. `headers` names only what the call as the ones the client sets from its configuration are not in it, and an `on_behalf_of` scope has a field of its own. -A read that is answered 429 or 5xx is sent again, as it is on the wire: a `GET`, up to -`retries` times, and never a write. Each attempt is in `requests` and takes the next stub -of a sequence, so a read that fails once and then succeeds is two stubs: +A read that is answered 429 or 5xx, or with a 2xx cut short of its `Content-Length`, is +sent again, as it is on the wire: a `GET`, up to `retries` times, and never a write. Each +attempt is in `requests` and takes the next stub of a sequence, so a read that fails once +and then succeeds is two stubs: ```ruby zammad.stub(:get, 'api/v1/tickets/1', status: 503) diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index 900a0c8..264b1f9 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -139,8 +139,9 @@ def initialize(**options) # keeps answering. # # A +GET+ answered with a status the client retries - 429, 500, 502, 503 - # or 504 - is asked again, as it is on the wire, and each attempt takes - # the next stub of the sequence: see {#answer}. + # or 504 - or with a 2xx cut short of its Content-Length is asked again, + # as it is on the wire, and each attempt takes the next stub of the + # sequence: see {#answer}. # # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ # @param path [String] path relative to the instance URL, leading slash @@ -225,7 +226,8 @@ def inspect = @monitor.synchronize { "#<#{self.class.name} stubbed=#{@stubs.size # test. # # A request the real transport would send again is sent again here: a - # +GET+ answered 429 or 5xx, as many times as {Config#retries} allows. + # +GET+ answered 429 or 5xx, or with a 2xx whose body is shorter than + # its Content-Length, as many times as {Config#retries} allows. # The first such answer used to be raised. Stubbed 503 and then 200, # `client.groups.find(1)` returns the group on the wire and raised # ServerError here, and a single stubbed 503 was recorded as one request diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index c2b1e28..cdf8cb4 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -102,10 +102,53 @@ module Verbs # error by the backoff. SSL_ERRORS = [OpenSSL::SSL::SSLError].freeze + # A 2xx response whose body stopped short of its Content-Length, as it + # is raised inside the connection: see {HeldToLength}. It never leaves + # {#request}, which reports it as an {IncompleteResponseError}. + # + # @api private + class CutShort < Faraday::Error; end + private_constant :CutShort + + # Holds a 2xx response to its Content-Length where the retry middleware + # sees the outcome: below it in the stack. + # + # {#request} asked this of the response it was handed, which is after + # the retry middleware has returned. So a read whose body the connection + # dropped under was asked once and raised, while the same drop a moment + # earlier, surfacing as ECONNRESET, was asked again: which of the two a + # flaky link produced decided whether `retries` meant anything, and a + # download of an attachment is the read most likely to be cut. + # + # Raised for every method, and sent again for the ones the retry + # middleware repeats, which a write is not among. + # + # Above the caller's `middleware:`, so the body and the headers are + # asked as that left them, which is how {#request} saw them. A body + # that is no text is left for {#raw_body!} to refuse. + # + # @api private + class HeldToLength < Faraday::Middleware + # @param env [Faraday::Env] + # @return [void] + # @raise [CutShort] + def on_complete(env) + body = env.body + return if !Response::SUCCESS_STATUSES.cover?(env.status) || !(body.nil? || body.is_a?(String)) + return if Transport.short_by(env.status, env.response_headers, body.to_s).nil? + + raise CutShort.new('the body ended short of its Content-Length', env.response) + end + end + private_constant :HeldToLength + # Failures worth retrying. Faraday::RetriableResponse is how the retry # middleware signals a retriable status internally and must stay in this # list, otherwise it escapes as an unhandled Faraday error. # + # {CutShort} is the one this class raises itself, for a response the + # connection closed under. + # # Composed from the two lists above rather than repeating them. Listed # by hand, CONNECTION_ERRORS was left out: a transient ECONNRESET through # an adapter that wraps it was retried as a Faraday::ConnectionFailed, @@ -118,6 +161,7 @@ module Verbs Faraday::RetriableResponse, Faraday::ConnectionFailed, Faraday::TimeoutError, + CutShort, *TIMEOUT_ERRORS, *CONNECTION_ERRORS ].freeze @@ -1272,8 +1316,17 @@ def self.retry_options(config) } end + # Whether a response is a 2xx whose body stopped short of its + # Content-Length: the one {HeldToLength} raises for. + # + # @api private + # @param response [Response] + # @return [Boolean] + def self.cut_short?(response) = response.success? && !missing_bytes(response).nil? + # Whether a request answered with +response+ is one the retry middleware - # sends again, while it has attempts left. + # sends again, while it has attempts left: one with a retriable status, + # or a 2xx that was cut short. # # Public for {Test}, for the reason {.stringify_query} is: a stand-in # that raised for the first 503 a +GET+ was answered with, where the @@ -1294,7 +1347,8 @@ def self.retry_options(config) # @return [Boolean] def self.retried?(config, method, response) options = retry_options(config) - return false if !options[:methods].include?(method) || !options[:retry_statuses].include?(response.status) + return false if !options[:methods].include?(method) + return false if !options[:retry_statuses].include?(response.status) && !cut_short?(response) !Faraday::Retry::Middleware.new(nil, options).calculate_sleep_amount(1, { response_headers: Faraday::Utils::Headers.new(response.headers) }).nil? end @@ -1362,13 +1416,27 @@ def self.whole(response, operation:, config:) # @param response [Response] # @return [Integer, nil] nil for a response that is whole, or that # cannot be told - def self.missing_bytes(response) - headers = response.headers - announced = headers['content-length'] - return nil if announced.nil? || !CONTENT_LENGTH.match?(announced) - return nil if response.status == 204 || headers.key?('content-encoding') || headers.key?('transfer-encoding') + def self.missing_bytes(response) = short_by(response.status, response.headers, response.raw_body) - missing = announced.to_i - response.raw_body.bytesize + # {.missing_bytes}, asked of the parts of a response, for + # {HeldToLength}, which holds a Faraday one. + # + # The headers are a {Response}'s or Faraday's own, which both answer to + # a lower-case name. Faraday keeps a value as whatever wrote it, an + # Integer for the length faraday-gzip sets, so the figure is read as + # text. + # + # @api private + # @param status [Integer] + # @param headers [Hash, Faraday::Utils::Headers] + # @param body [String] + # @return [Integer, nil] + def self.short_by(status, headers, body) + announced = headers['content-length'].to_s + return nil if !CONTENT_LENGTH.match?(announced) + return nil if status == 204 || headers.key?('content-encoding') || headers.key?('transfer-encoding') + + missing = announced.to_i - body.bytesize missing.positive? ? missing : nil end @@ -1493,6 +1561,8 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou response = decode(perform(method, path, query, payload, headers)) log_response(method, path, response, started) + # A response cut short has been through the retries a read is due by + # now: see {HeldToLength}, and {#perform} for how it gets here. return Transport.whole(response, operation: operation, config: config) if response.success? raise ResponseError.build(response, operation: operation, resource_class: resource_class) @@ -1551,6 +1621,13 @@ def perform(method, path, query, payload, headers) request.body = payload if payload request.headers['From'] = on_behalf_of if on_behalf_of end + rescue CutShort => e + # The response the connection raised for, once the retries a read is + # due are spent, and at once for a write. Handed on as the response it + # is, so that it is logged and decoded like any other, and + # {#request} raises for it with the status and the bytes that did + # arrive. + e.response end def build_connection @@ -1570,6 +1647,7 @@ def build_connection apply_authentication(faraday) faraday.request :json faraday.request :retry, Transport.retry_options(config) + faraday.use HeldToLength # Last in the stack, so a caller's middleware sees the request as this # gem finished building it and the response before anything else does. apply_middleware_and_adapter(faraday) diff --git a/sig/vendor/faraday.rbs b/sig/vendor/faraday.rbs index 6b0f0a9..397c65f 100644 --- a/sig/vendor/faraday.rbs +++ b/sig/vendor/faraday.rbs @@ -3,6 +3,14 @@ module Faraday class Error < StandardError + def initialize: (?untyped exc, ?untyped response) -> void + def response: () -> untyped + end + + # What a middleware of this gem's own is built on. See + # ZammadAPI::Transport::HeldToLength. + class Middleware + def initialize: (?untyped app, ?untyped options) -> void end class ConnectionFailed < Error diff --git a/sig/vendor/internal.rbs b/sig/vendor/internal.rbs index 620fdc7..6c10b63 100644 --- a/sig/vendor/internal.rbs +++ b/sig/vendor/internal.rbs @@ -12,3 +12,17 @@ module ZammadAPI extend Forwardable end end + +# The two classes the transport puts into its Faraday stack. Private +# constants, and built on Faraday types, which a published signature cannot +# name: see sig/zammad_api/transport.rbs. +module ZammadAPI + class Transport + class CutShort < Faraday::Error + end + + class HeldToLength < Faraday::Middleware + def on_complete: (untyped env) -> void + end + end +end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index ca6f237..1f921cd 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -91,6 +91,8 @@ module ZammadAPI def self.retried?: (Config config, Symbol method, Response response) -> bool def self.whole: (Response response, operation: String, config: Config) -> Response def self.missing_bytes: (Response response) -> Integer? + def self.short_by: (Integer status, untyped headers, String body) -> Integer? + def self.cut_short?: (Response response) -> bool def self.description: (Config config, String? on_behalf_of) -> Hash[Symbol, untyped] def initialize: (Config) -> void diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index da76d3f..fc82ece 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -1021,11 +1021,37 @@ def find = client.groups.find(1) expect(group.changed?).to be(false) end - it 'records the request, and does not send a read again for it' do + # A read is sent again for it on the wire, as it is for a connection + # that was reset, and each attempt takes the next stub of a sequence. + it 'sends a read again for it, as often as the client retries' do zammad.stub(:get, 'api/v1/groups/1', **cut_short) expect { client.groups.find(1) }.to raise_error(ZammadAPI::IncompleteResponseError) - expect(zammad.requests.map(&:path)).to eq(['api/v1/groups/1']) + expect(zammad.requests.map(&:path)).to eq(['api/v1/groups/1'] * (1 + zammad.config.retries)) + end + + it 'answers a read that is cut short once and then whole with the record' do + zammad.stub(:get, 'api/v1/groups/1', **cut_short) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) + + expect(client.groups.find(1).name).to eq('Users') + expect(zammad.requests.size).to eq(2) + end + + it 'sends a read once where the client was built without retries' do + zammad = described_class.new(retries: 0) + zammad.stub(:get, 'api/v1/groups/1', **cut_short) + + expect { zammad.client.groups.find(1) }.to raise_error(ZammadAPI::IncompleteResponseError) + expect(zammad.requests.size).to eq(1) + end + + it 'does not send a write again for it' do + zammad.stub(:post, 'api/v1/groups', **cut_short) + zammad.stub(:post, 'api/v1/groups', body: { id: 2, name: 'Support' }) + + expect { client.groups.create(name: 'Support') }.to raise_error(ZammadAPI::IncompleteResponseError) + expect(zammad.requests.size).to eq(1) end it 'takes a body as long as its Content-Length, or longer' do diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 7c2a60e..deafa22 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1326,6 +1326,77 @@ def counting(length) end end + # Asked of the response the retry middleware had already returned, so + # this was the one failure of a connection that a read was not sent + # again for: the drop a moment earlier, as ECONNRESET, was. + context 'with retries to spend' do + let(:transport) { unit_transport(retries: 2, retry_interval: 0.01) } + let(:short) { { status: 200, body: '0123', headers: { 'Content-Length' => '10' } } } + let(:whole) { { status: 200, body: '0123456789', headers: { 'Content-Length' => '10' } } } + + it 'sends a GET again, and returns the body that arrived whole' do + stub_request(:get, url).to_return(short, whole) + + expect(transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') + expect(a_request(:get, url)).to have_been_made.twice + end + + it 'sends it as often as a GET that met ECONNRESET' do + stub_request(:get, url).to_return(short, short, whole) + + expect(transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') + expect(a_request(:get, url)).to have_been_made.times(3) + end + + it 'raises once the retries are spent, with the response that came last' do + stub_request(:get, url).to_return(short, short, short.merge(body: '012345')) + + expect { transport.get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::IncompleteResponseError, /ended 4 bytes short of the 10/) { expect(it.response.raw_body).to eq('012345') } + expect(a_request(:get, url)).to have_been_made.times(3) + end + + # Zammad answered, so the write was applied, and sending it again + # would apply it again. + %i[post put delete].each do |verb| + it "does not send a #{verb.to_s.upcase} again" do + stub_request(verb, url).to_return(short, whole) + + expect { transport.public_send(verb, 'api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::IncompleteResponseError) + expect(a_request(verb, url)).to have_been_made.once + end + end + + it 'does not send a GET again for a body that is whole' do + stub_request(:get, url).to_return(whole) + transport.get('api/v1/groups', operation: 'test') + + expect(a_request(:get, url)).to have_been_made.once + end + + it 'asks the length of the body as the middleware callable left it' do + stub_request(:get, url).to_return(status: 200, body: '0123456789') + padded = lambda { |builder| + builder.use(Class.new(Faraday::Middleware) do + define_method(:on_complete) { |env| env.response_headers['Content-Length'] = 1000 } + end) + } + + expect { unit_transport(retries: 1, retry_interval: 0.01, middleware: padded).get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::IncompleteResponseError, /990 bytes short/) + expect(a_request(:get, url)).to have_been_made.twice + end + + it 'logs the response it raises for, once' do + log = StringIO.new + stub_request(:get, url).to_return(short) + + expect { unit_transport(retries: 2, retry_interval: 0.01, logger: Logger.new(log)).get('api/v1/groups', operation: 'test') } + .to raise_error(ZammadAPI::IncompleteResponseError) + expect(log.string.scan('Zammad API response: GET api/v1/groups -> 200').size).to eq(1) + end + end + it 'does not judge a 204, which has no body whatever is announced beside it' do stub_request(:delete, url).to_return(status: 204, body: '', headers: { 'Content-Length' => '5' }) From dc706dda7f4ef300789471aae40b72c1626330a5 Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 24 Nov 2026 12:01:48 +0200 Subject: [PATCH 082/121] fix: serve a stubbed list by the page size asked for --- CHANGELOG.md | 9 +++ README.md | 23 +++--- lib/zammad_api/test.rb | 72 ++++++++++++++++--- sig/zammad_api/test.rbs | 4 ++ spec/unit/zammad_api/test_spec.rb | 115 ++++++++++++++++++++++++++++++ 5 files changed, 206 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8a60e3..ea7a2e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1243,6 +1243,15 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a answered it, and the error and the response it carries are what they were. `ZammadAPI::Test` sends such a read again as well, each attempt taking the next stub of a sequence. +- `ZammadAPI::Test` serves a stubbed list a page at a time, of the size the request asks + for. Only the page number was read: the records went whole to page 1 whatever `per_page` + said, and every later page was empty. With five records stubbed, `page(1, per_page: 2)` + held all five, `page(2, per_page: 2)` none, and `in_batches(of: 2)` yielded one batch of + five, where Zammad serves two, two and one, so code that pages by hand or leans on a + batch size saw other records in a test than in production. A search stubbed with its + total is cut the same way and reports the total on every page. A stub that names a + `page` or a `per_page` in its `query:` is served as written, as is one written short of + its own `Content-Length`, and a request that names no `per_page` is answered as before. ### Changed diff --git a/README.md b/README.md index 6de1b95..c35a966 100644 --- a/README.md +++ b/README.md @@ -1399,16 +1399,22 @@ reporting it as an API failure. ### Stubbing a list endpoint -One stub is enough for a collection that fits in a page. The records it holds are one page -of them, so a request for any later page is answered the way an endpoint out of records -would answer it: +One stub is enough for a list. The records it holds are the list, and a request is served +the page of them it asks for. A page past the records is answered the way an endpoint out +of records would answer it: ```ruby -zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}, {id: 2, name: 'Sales'}]) +zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}, {id: 2, name: 'Sales'}, {id: 3, name: 'Support'}]) -client.groups.all.map(&:name) # => ["Users", "Sales"] +client.groups.all.map(&:name) # => ["Users", "Sales", "Support"] +client.groups.all.page(2, per_page: 2).map(&:name) # => ["Support"] +client.groups.in_batches(of: 2).map(&:size) # => [2, 1] ``` +The page is cut by the `page` and `per_page` the request carries. A request that names no +`per_page` gets every record on page 1 and none after it, and the endpoint's own limit on +a page is not applied. + Stub the endpoint again to describe a list that changes between reads. A read is one step of the sequence however many pages it asks for, so each read gets the next stub and the last one answers every read after it: @@ -1427,7 +1433,8 @@ which a stub holding records answers with the records, and then for the pages. The second stub may also be declared once the first has answered, between two steps of a test. It answers from the next request on. -Name a `page` to say what each one holds, and the stub is served exactly as written: +Name a `page` to say what each one holds, and the stub is served exactly as written. One +that names a `per_page` is not cut either: ```ruby zammad.stub(:get, 'api/v1/groups', body: first_hundred, query: {page: 1}) @@ -1436,8 +1443,8 @@ zammad.stub(:get, 'api/v1/groups', body: [{id: 101}], query: {page: 2}) A search that is walked asks for its total with `with_total_count`, and an Array answers it the way a Zammad before 6.5.1 does, with the records alone. To stand in for one that -reports the total, stub the object it answers with. It is paged like an Array: a later -page holds no records and the same total. +reports the total, stub the object it answers with. It is paged like an Array, and every +page reports the same total. ```ruby zammad.stub(:get, 'api/v1/users/search', body: {records: [{id: 1}, {id: 2}], total_count: 2}) diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index 264b1f9..e1ca130 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -529,16 +529,62 @@ def matches?(expected, params) # holds no records and reports the same total. Served again as written it # was the repeated page above, for the one stub that says how many hits # there are. + # + # And the page is of the size the request asks for. Only the page number + # was read, so the records were served whole to page 1 whatever + # +per_page+ said, and every later page was empty: five records stubbed, + # `page(1, per_page: 2)` held all five, `page(2, per_page: 2)` none, and + # `in_batches(of: 2)` yielded one batch of five, where Zammad serves two, + # two and one. Code that pages by hand, or leans on a batch size, saw + # other records here than on the wire. A stub that names a +per_page+ of + # its own is what a request of that size is answered, and is not cut. def paged_body(stub, params, body) - return body if !later_page?(stub[:query], params) + scope = stub[:query] + later = later_page?(scope, params) + window = scope&.key?('page') || scope&.key?('per_page') ? nil : page_window(params) + return body if window.nil? && !later case body - in Array then [] - in { records: Array, total_count: _ } then body.merge(records: []) + in Array then page_of(body, window) + in { records: Array => records, total_count: _ } + page = page_of(records, window) + page.equal?(records) ? body : body.merge(records: page) else body end end + # The records at the offset and of the size a request asks for, or none + # for a later page of a request that names no size. + # + # The records themselves where the page holds all of them, so that the + # response keeps the bytes the stub was written with. + def page_of(records, window) + return [] if window.nil? + + offset, size = window + return records if offset.zero? && records.size <= size + + records[offset, size] || [] + end + + # A whole number a query parameter writes, the way Zammad reads +page+ + # and +per_page+. + PAGE_NUMBER = /\A[1-9]\d*\z/ + private_constant :PAGE_NUMBER + + # Where the page a request asks for begins, and how many records it + # holds. + # + # @return [Array(Integer, Integer), nil] nil where the request names no + # +per_page+, or where either figure is not a number above zero + def page_window(params) + page = params.fetch('page', '1') + size = params['per_page'] + return nil if !PAGE_NUMBER.match?(page.to_s) || !PAGE_NUMBER.match?(size.to_s) + + [(page.to_i - 1) * size.to_i, size.to_i] + end + # Decoded by {Response.decode_body}, the rule {Transport#decode} reads, so # that a stub answers the way the wire does. # @@ -555,21 +601,29 @@ def paged_body(stub, params, body) # same records and every full read of that collection raised # PaginationError. Against Zammad the same code works, because page two # comes back empty. + # + # A stub written short of its own Content-Length is not paged. It is how + # a test says that the answer was cut short, and a page cut from it + # would be counted anew and served as whole. def response_for(stub, params) raw = raw_body_for(stub[:body]) body, json = Response.decode_body(stub[:headers]['content-type'], raw) - paged = paged_body(stub, params, body) + written = build_response(stub, body, raw, json: json) + return written if ::ZammadAPI::Transport.cut_short?(written) + + paged = paged_body(stub, params, body) # Re-serialized only where paging replaced the body, so `raw_body` stays # the bytes the stub was written with for every other response. - return build_response(stub, body, raw, json: json) if paged.equal?(body) + return written if paged.equal?(body) - emptied = JSON.generate(paged) - build_response(stub, paged, emptied, json: json, headers: recounted(stub[:headers], emptied)) + replaced = JSON.generate(paged) + build_response(stub, paged, replaced, json: json, headers: recounted(stub[:headers], replaced)) end # The headers of a stub for a body that paging replaced. A - # Content-Length written for the records does not count the empty page - # served after them, and would have it refused as cut short. + # Content-Length written for the records does not count the page cut + # from them, or the empty one served after them, and would have it + # refused as cut short. def recounted(headers, raw_body) return headers if !headers.key?('content-length') diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs index e7d8101..d3e559b 100644 --- a/sig/zammad_api/test.rbs +++ b/sig/zammad_api/test.rbs @@ -65,7 +65,11 @@ module ZammadAPI def most_specific: (Array[Hash[Symbol, untyped]] queued, Array[Integer] matching, Symbol method, String path) -> Array[Integer] def ambiguous_message: (Symbol method, String path, Array[Hash[String, untyped]?] scopes) -> String def matches?: (Hash[untyped, untyped]? expected, Hash[String, untyped] params) -> bool + PAGE_NUMBER: Regexp + def paged_body: (Hash[Symbol, untyped] stub, Hash[String, untyped] params, untyped body) -> untyped + def page_of: (Array[untyped] records, [Integer, Integer]? window) -> Array[untyped] + def page_window: (Hash[String, untyped] params) -> [Integer, Integer]? def response_for: (Hash[Symbol, untyped] stub, Hash[String, untyped] params) -> Response def recounted: (Hash[String, String] headers, String raw_body) -> Hash[String, String] def build_response: (Hash[Symbol, untyped] stub, untyped body, String raw_body, json: bool, ?headers: Hash[String, String]) -> Response diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index fc82ece..d83cdae 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -1138,6 +1138,109 @@ def self.name = 'ObjectAttribute' end end + # Only the page number was read. The records were served whole to page 1 + # whatever size was asked for, and every later page was empty, so code + # that pages by hand or leans on a batch size saw other records here than + # Zammad serves it. + describe 'a list endpoint stubbed once, read a page of a given size at a time' do + subject(:zammad) { described_class.new } + + let(:client) { zammad.client } + let(:records) { (1..5).map { { id: it, name: "group #{it}" } } } + + before { zammad.stub(:get, 'api/v1/groups', body: records) } + + it 'answers page 1 with as many records as were asked for' do + expect(client.groups.all.page(1, per_page: 2).map(&:id)).to eq([1, 2]) + end + + it 'answers a later page with the records that follow' do + expect(client.groups.all.page(2, per_page: 2).map(&:id)).to eq([3, 4]) + end + + it 'answers the last page with what is left' do + expect(client.groups.all.page(3, per_page: 2).map(&:id)).to eq([5]) + end + + it 'answers a page past the records as an endpoint out of records would' do + expect([4, 9].map { client.groups.all.page(it, per_page: 2).to_a }).to eq([[], []]) + end + + it 'hands in_batches the batches Zammad would' do + batches = [] + client.groups.in_batches(of: 2) { |batch| batches << batch.map(&:id) } + + expect(batches).to eq([[1, 2], [3, 4], [5]]) + end + + it 'hands find_each every record once, however small the batch' do + expect(client.groups.find_each(batch_size: 2).map(&:id)).to eq([1, 2, 3, 4, 5]) + end + + it 'asks for an empty page after a last one that was full' do + client.groups.find_each(batch_size: 5).to_a + + expect(zammad.requests.map { it.query['page'] }).to eq(%w[1 2]) + end + + it 'still reads the whole list where the page is larger than it' do + expect(client.groups.all.map(&:id)).to eq([1, 2, 3, 4, 5]) + end + + it 'serves a raw request that names no size every record' do + expect(client.get('api/v1/groups').body.size).to eq(5) + end + + it 'serves a raw request the page it names' do + expect(client.get('api/v1/groups', query: { page: 2, per_page: 3 }).body).to eq([{ id: 4, name: 'group 4' }, { id: 5, name: 'group 5' }]) + end + + it 'keeps the bytes of a stub it did not cut' do + zammad.stub(:get, 'api/v1/users', body: '[ {"id": 1} ]', headers: { 'Content-Type' => 'application/json' }) + + expect(client.get('api/v1/users', query: { per_page: 1 }).raw_body).to eq('[ {"id": 1} ]') + end + + it 'counts a page it cut anew, where the stub announced a length' do + zammad.stub(:get, 'api/v1/users', body: [{ id: 1 }, { id: 2 }], headers: { 'Content-Length' => 19 }) + + expect(client.get('api/v1/users', query: { per_page: 1 }).headers['content-length']).to eq('10') + end + + # A stub short of its own Content-Length says the answer was cut short, + # and a page cut from it would have been counted anew and served. + it 'does not cut a page from a stub that is short of its own Content-Length' do + zammad.stub(:get, 'api/v1/users', body: [{ id: 1 }, { id: 2 }], headers: { 'Content-Length' => 500 }) + + expect { zammad.client.with(retries: 0).users.all.page(1, per_page: 1).to_a }.to raise_error(ZammadAPI::IncompleteResponseError) + end + + it 'leaves a size that is no number above zero to the stub as it was written' do + expect(%w[0 -1 two].map { client.get('api/v1/groups', query: { per_page: it }).body.size }).to eq([5, 5, 5]) + end + + # Such a stub is what a request of that size is answered. + it 'does not cut a stub that names a per_page of its own' do + zammad.stub(:get, 'api/v1/users', body: [{ id: 1 }, { id: 2 }, { id: 3 }], query: { per_page: 2 }) + + expect(client.get('api/v1/users', query: { per_page: 2 }).body.size).to eq(3) + expect(client.get('api/v1/users', query: { per_page: 2, page: 2 }).body).to eq([]) + end + + it 'does not cut a stub that names its page' do + zammad.stub(:get, 'api/v1/users', body: [{ id: 1 }, { id: 2 }, { id: 3 }], query: { page: 1 }) + + expect(client.get('api/v1/users', query: { page: 1, per_page: 2 }).body.size).to eq(3) + end + + it 'spends one stub of a sequence on a read of several pages' do + zammad.stub(:get, 'api/v1/groups', body: [{ id: 9, name: 'later' }]) + + expect(client.groups.find_each(batch_size: 2).map(&:id)).to eq([1, 2, 3, 4, 5]) + expect(client.groups.find_each(batch_size: 2).map(&:id)).to eq([9]) + end + end + # The object a Zammad from 6.5.1 on answers a walked search with. It is a # list too, so the page after it holds no records - and reports the same # total, which is what a walk reads to tell that page from the end. @@ -1164,6 +1267,18 @@ def self.name = 'ObjectAttribute' expect(client.get('api/v1/users/search', query: { query: 'smith', page: 1 }).body).to eq(records: [{ id: 1 }, { id: 2 }], total_count: 2) end + it 'answers a page of a given size with its records and the same total' do + zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }, { id: 3 }], total_count: 3 }) + + expect(client.get('api/v1/users/search', query: { query: 'smith', page: 2, per_page: 2 }).body).to eq(records: [{ id: 3 }], total_count: 3) + end + + it 'hands a search read in batches every hit once' do + zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }, { id: 3 }], total_count: 3 }) + + expect(client.users.search('smith').find_each(batch_size: 2).map(&:id)).to eq([1, 2, 3]) + end + # The stub holds two records and says there are five hundred hits, so the # walk reads on, a page of two hundred at a time, until it has covered # them: the page it was served, and two that hold nothing. From a09a8a888af36178cbb582a6e69414ae5fa1417b Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 24 Nov 2026 12:03:39 +0200 Subject: [PATCH 083/121] fix: send binary-tagged UTF-8 text in a body as text --- CHANGELOG.md | 8 +++++ lib/zammad_api/transport.rb | 25 +++++++++++++ sig/zammad_api/transport.rbs | 1 + spec/unit/zammad_api/transport_spec.rb | 50 ++++++++++++++++++++++++++ 4 files changed, 84 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea7a2e6..3819c9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1252,6 +1252,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a total is cut the same way and reports the total on every page. A stub that names a `page` or a `per_page` in its `query:` is served as written, as is one written short of its own `Content-Length`, and a request that names no `per_page` is answered as before. +- Text in a request body that is tagged as binary is sent as the UTF-8 text its bytes are. + Text read with `File.binread`, off a socket or out of a mail library arrives tagged that + way, and the JSON generator goes by the tag: json 3 refuses a binary String with a byte + outside ASCII, where json 2 wrote one that was valid UTF-8 with a deprecation warning. So + `client.tickets.create(title: 'Größe'.b)` was sent, or raised `ZammadAPI::Error` with + the advice to Base64-encode an attachment, by which version of the generator a bundle + had resolved to. Bytes that are not valid UTF-8 are binary data and are refused with + that advice, as before. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index cdf8cb4..92fb588 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1182,6 +1182,7 @@ def self.encode_body(body, operation:, resource_class: nil) def self.json_value(value, key) case value when Float then value.finite? ? value : raise(RefusedValue, not_a_json_value_message(value, key)) + when String then json_text(value) when *JSON_VALUE_TYPES then value when Hash then json_hash(value, key) when Array then value.map { json_value(it, key) } @@ -1189,6 +1190,30 @@ def self.json_value(value, key) end end + # Text as the generator takes it: a String tagged as binary whose bytes + # are UTF-8 text, as the UTF-8 text it is. + # + # Text that was read with `File.binread`, off a socket, or handed over + # by a mail library arrives tagged that way, and the generator goes by + # the tag: json 3 refuses a binary String with a byte outside ASCII, + # where json 2 wrote one that was valid UTF-8 with a warning. So + # `tickets.create(title: 'Größe'.b)` was sent or raised the advice to + # Base64-encode an attachment, by which version of the generator a + # bundle had resolved to, and a query took the same String either way. + # + # Only bytes that are text. Any other are binary data, and are left for + # the generator to refuse, which is what that advice is for. + # + # @api private + # @param text [String] + # @return [String] +text+, or a copy of it tagged as UTF-8 + def self.json_text(text) + return text if text.encoding != Encoding::BINARY || text.ascii_only? + + tagged = text.dup.force_encoding(Encoding::UTF_8) + tagged.valid_encoding? ? tagged : text + end + # A Hash with every key as the text the generator writes it as, which # is its `to_s`, and two keys that are written alike refused. # diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 1f921cd..db1ad60 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -83,6 +83,7 @@ module ZammadAPI def self.unreadable_path_message: (String relative) -> String def self.encode_body: (untyped body, operation: String, ?resource_class: Class?) -> String? def self.json_value: (untyped value, untyped key) -> untyped + def self.json_text: (String text) -> String def self.json_hash: (Hash[untyped, untyped] hash, untyped key) -> Hash[String, untyped] def self.json_object: (untyped value, untyped key) -> untyped def self.writes_own_json?: (untyped value) -> bool diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index deafa22..0e2fecd 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1035,6 +1035,56 @@ def to_json(*) = '{"from":"to_json"}' end end + # The generator goes by the tag of a String. json 3 refuses a binary one + # with a byte outside ASCII and json 2 wrote one that was valid UTF-8, + # so text read with File.binread or off a socket was sent or refused by + # which of the two a bundle had resolved to. + context 'with text in the body that is tagged as binary' do + before { stub_request(:post, url).to_return(json_response({})) } + + it 'sends it as the UTF-8 text its bytes are' do + unit_transport.post('api/v1/groups', operation: 'test', body: { name: 'Größe'.b }) + + expect(a_request(:post, url).with(body: '{"name":"Größe"}')).to have_been_made + end + + it 'sends it inside a Hash and an Array as well' do + unit_transport.post('api/v1/groups', operation: 'test', body: { article: { subject: 'Grüße'.b, to: ['jürgen@example.com'.b] } }) + + expect(a_request(:post, url).with(body: '{"article":{"subject":"Grüße","to":["jürgen@example.com"]}}')).to have_been_made + end + + it 'encodes it without a warning from the generator' do + expect { described_class.encode_body({ name: 'Größe'.b }, operation: 'test') }.not_to output.to_stderr + end + + it 'leaves the String it was given tagged as it was' do + name = 'Größe'.b + described_class.encode_body({ name: name }, operation: 'test') + + expect(name.encoding).to eq(Encoding::BINARY) + end + + it 'hands on a String that needs no new tag as the object it is' do + ascii = 'plain'.b + utf8 = 'Größe' + + expect(described_class.json_value([ascii, utf8], nil)).to match([be(ascii), be(utf8)]) + end + + it 'still refuses bytes that are no text, with the advice for binary data' do + expect { described_class.encode_body({ data: "\x89PNG\r\n\x1A\n\xFF".b }, operation: 'test') } + .to raise_error(ZammadAPI::Error, /Base64-encode binary data/) + end + + it 'saves a record whose attribute is such text' do + stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 7, name: 'Größe' })) + unit_client.groups.create(name: 'Größe'.b) + + expect(a_request(:post, url).with(query: hash_including({}), body: '{"name":"Größe"}')).to have_been_made + end + end + # Faraday's JSON middleware raised JSON::GeneratorError from inside the # stack and nothing mapped it, so it went past the rescue of # ZammadAPI::Error every caller is told to write. From b5d891596c53830dc725038f784d3848b640c21d Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 24 Nov 2026 12:05:17 +0200 Subject: [PATCH 084/121] fix: take a variable of only whitespace for unset --- CHANGELOG.md | 8 +++++ README.md | 3 +- lib/zammad_api/client.rb | 25 ++++++++++---- spec/unit/zammad_api/client_spec.rb | 52 +++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3819c9a..aec0037 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1260,6 +1260,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a the advice to Base64-encode an attachment, by which version of the generator a bundle had resolved to. Bytes that are not valid UTF-8 are binary data and are refused with that advice, as before. +- `Client.from_env` takes an environment variable that holds nothing but whitespace for + unset, as it takes an empty one. With `ZAMMAD_TOKEN` holding a token and + `ZAMMAD_HTTP_TOKEN` set to a space, the blank variable took the token's place and was + then read as no token: `ConfigurationError: missing user in config`, for an environment + that held a valid token. A `ZAMMAD_USER` or `ZAMMAD_PASSWORD` of a space beside a token + was refused as a second way to authenticate, and a `ZAMMAD_URL` of one was reported as a + url with no scheme and is reported as missing now. A password that is nothing but spaces + can still be passed as `password:`. ### Changed diff --git a/README.md b/README.md index c35a966..de3cfbf 100644 --- a/README.md +++ b/README.md @@ -130,7 +130,8 @@ them. `ZAMMAD_PASSWORD`, or `ZAMMAD_OAUTH2_TOKEN`), so a script needs no configuration of its own. Anything passed in wins over the environment, credentials included — passing `user:` and `password:` replaces a token the environment holds rather than sitting beside -it. An environment that itself sets more than one way to authenticate is refused, until an +it. A variable that is empty, or holds nothing but whitespace, counts as unset. An +environment that itself sets more than one way to authenticate is refused, until an argument says which is meant: ```ruby diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index d88fd26..2903458 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -85,12 +85,21 @@ class Client # Anything passed in wins over the environment, and every other option # keeps its default. That includes the way to authenticate: passing # +user:+ and +password:+, or a token, replaces whichever credentials the - # environment holds rather than sitting beside them. An empty variable - # counts as unset, and +ZAMMAD_HTTP_TOKEN+ wins over +ZAMMAD_TOKEN+ if - # both are set. An environment that sets more than one way to - # authenticate - a token and a user with a password - is refused like - # any other configuration that does, unless an argument names the one to - # use. + # environment holds rather than sitting beside them. A variable that is + # empty, or holds nothing but whitespace, counts as unset, and + # +ZAMMAD_HTTP_TOKEN+ wins over +ZAMMAD_TOKEN+ if both are set. An + # environment that sets more than one way to authenticate - a token and + # a user with a password - is refused like any other configuration that + # does, unless an argument names the one to use. + # + # Only an empty variable used to count as unset. One set to a space, + # which is what `export ZAMMAD_HTTP_TOKEN=" "` and a blank line of an + # env file leave behind, was taken for a value: beside a valid + # +ZAMMAD_TOKEN+ it took that token's place and was then read as no + # token at all, "missing user in config" for an environment that held a + # token, and a +ZAMMAD_USER+ of a space beside a token was a second way + # to authenticate. A password of nothing but spaces is given as + # +password:+. # # @example # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=secret ruby report.rb @@ -105,7 +114,9 @@ class Client def self.from_env(**overrides) from_environment = ENV_OPTIONS.filter_map do |name, option| value = ENV.fetch(name, nil) - [option, value] if !value.to_s.empty? + # Of the bytes, as {Config.blank_token?} asks a token: a variable + # may hold a byte that is not text. + [option, value] if !value.to_s.b.strip.empty? end options = Config.merge_options(from_environment.to_h, overrides) diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index 88218ee..c505f01 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -80,6 +80,58 @@ expect(described_class.from_env(http_token: 'passed in').config.http_token).to eq('passed in') end + # Only an empty variable counted as unset. One holding a space was taken + # for a value, took the place of the variable beside it, and was then + # read as no credential, or as a second one. + context 'with a variable that holds nothing but whitespace' do + let(:environment) { { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' } } + + def from(variables) + stub_const('ENV', environment.merge(variables)) + described_class.from_env + end + + [' ', "\t", "\n", " \r\n "].each do |blank| + it "reads ZAMMAD_TOKEN past a ZAMMAD_HTTP_TOKEN of #{blank.inspect}" do + expect(from('ZAMMAD_HTTP_TOKEN' => blank).config.http_token).to eq('from-env') + end + end + + it 'reads ZAMMAD_TOKEN past an empty ZAMMAD_HTTP_TOKEN, as it did' do + expect(from('ZAMMAD_HTTP_TOKEN' => '').config.http_token).to eq('from-env') + end + + %w[ZAMMAD_USER ZAMMAD_PASSWORD ZAMMAD_OAUTH2_TOKEN].each do |name| + it "does not take a #{name} of a space for a second way to authenticate" do + expect(from(name => ' ').config.authentication_scheme).to eq(:http_token) + end + end + + it 'says that the url is missing for a ZAMMAD_URL of a space' do + expect { from('ZAMMAD_URL' => ' ') }.to raise_error(ZammadAPI::ConfigurationError, /\Amissing url: set ZAMMAD_URL/) + end + + it 'says what is missing where no variable holds a credential' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => ' ', 'ZAMMAD_USER' => "\t" }) + + expect { described_class.from_env }.to raise_error(ZammadAPI::ConfigurationError, /missing user in config/) + end + + it 'keeps the whitespace around a value that holds more than that' do + expect(from('ZAMMAD_HTTP_TOKEN' => " padded\n").config.http_token).to eq(" padded\n") + end + + it 'takes a variable with a byte that is not text for the value it is' do + expect(from('ZAMMAD_USER' => "j\xFFne", 'ZAMMAD_PASSWORD' => 'p', 'ZAMMAD_TOKEN' => ' ').config.authentication_scheme).to eq(:basic) + end + + it 'still takes a password of spaces that is passed in' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => ' ' }) + + expect(described_class.from_env(password: ' ').config.password).to eq(' ') + end + end + # A credential is read in a fixed order, so a plain merge left the # environment's token in charge of a client that was handed another way to # authenticate - and nothing said so. From 882ed14279e779c3054e946a29ecfb6c53fea80b Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 24 Nov 2026 12:07:31 +0200 Subject: [PATCH 085/121] fix: read the name of an environment variable as bytes --- CHANGELOG.md | 7 +++++ lib/zammad_api/transport.rb | 11 ++++++- spec/unit/zammad_api/transport_spec.rb | 43 ++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aec0037..682875a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1268,6 +1268,13 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a was refused as a second way to authenticate, and a `ZAMMAD_URL` of one was reported as a url with no scheme and is reported as missing now. A password that is nothing but spaces can still be passed as `password:`. +- A configuration that cannot be used is reported as a `ConfigurationError` whatever the + environment holds. Where it held a variable whose name is not valid UTF-8, which a + process can inherit, the search for proxy variables that redacts the error raised over + that name, and `Client.new(proxy: 'http://user:pa ss@host')` left as a bare + `ArgumentError: invalid byte sequence in UTF-8`, past a + `rescue ZammadAPI::ConfigurationError`. The name is read as its bytes, so a variable of + that kind ending in `_proxy` has its value scrubbed like any other. ### Changed diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 92fb588..d496cdf 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1843,9 +1843,18 @@ def redact_config_values(message) # process is a CGI, and a value that holds no credentials is not # changed by being looked for. # + # The name is asked as its bytes. The environment can hold a name that + # is not text in the encoding Ruby reads it in, and a pattern asked of + # one raises: with a variable called `caf\xE9_proxy` set, the + # ConfigurationError this is called for left as a bare `ArgumentError: + # invalid byte sequence in UTF-8`, past the rescue building a client is + # documented to need, and only where the configuration could not be + # used. Such a variable still names a proxy, so its value is scrubbed + # like any other. + # # @return [Array] def environment_proxies - ENV.filter_map { |name, value| value if name.match?(ENVIRONMENT_PROXY) && !value.empty? } + ENV.filter_map { |name, value| value if name.b.match?(ENVIRONMENT_PROXY) && !value.empty? } end # The proxy URL `Faraday.default_connection_options` names, to be diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 0e2fecd..8769125 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -2955,6 +2955,49 @@ def build = unit_transport(url: 'http://192.0.2.1/') end end + # The environment can hold a name that is not text either, and the + # pattern that picks out the proxy variables raised when asked of it: + # a bare ArgumentError in place of the ConfigurationError. + context 'when another variable has a name that is not text' do + around do |example| + ENV["caf\xE9_proxy"] = other + example.run + ensure + ENV["caf\xE9_proxy"] = nil + end + + let(:other) { 'http://other.proxy.test:1' } + + it 'is still reported as a configuration error, without the password' do + expect { build }.to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) { |error| + expect(error.full_message(highlight: false)).not_to include('hunter 2') + } + end + + it 'reports a configured proxy that cannot be parsed the same way' do + ENV['http_proxy'] = nil + + expect { unit_transport(url: 'http://192.0.2.1/', proxy: 'http://puser:pa ss@own.proxy.test') } + .to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@own\.proxy\.test}) + end + + it 'builds a client whose configuration can be used' do + ENV['http_proxy'] = nil + + expect(build).to be_a(described_class) + end + + # It ends in _proxy, so what it holds is scrubbed like any other. + it 'keeps the credentials that variable holds out of a report that quotes them' do + ENV['http_proxy'] = nil + ENV["caf\xE9_proxy"] = 'http://quser:qpass word@other.proxy.test:1' + quoting = ->(_) { raise ArgumentError, 'could not reach http://quser:qpass word@other.proxy.test:1' } + + expect { unit_transport(url: 'http://192.0.2.1/', middleware: quoting) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('qpass word') } + end + end + context 'when the environment names it in upper case' do around do |example| before = ENV.fetch('HTTPS_PROXY', nil) From acbfefe16ec9087d61055db3ae6344cfb2de1d03 Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 24 Nov 2026 23:12:59 +0200 Subject: [PATCH 086/121] refactor!: simplify the client to straightforward API usage Drop the handling of edge cases that ordinary use never hits, and keep what it needs. lib/ goes from 8,793 to 2,774 lines. Removed: - detection of a 2xx body cut short of its Content-Length, with IncompleteResponseError and the save/destroy bookkeeping behind it; an attachment download is one GET - query validation and the custom QueryEncoder; a query goes to Faraday - header name, value and line-break checks, and the refusal of Authorization and From in a raw request - JSON body type policing and the duplicate-key checks (DuplicateKeys) - path checks beyond refusing an absolute URL - the adapter/middleware conflict check, refused middleware, dropping Faraday's shared options, and proxy redaction in build errors - as_json/to_json/to_yaml of Client, Config and Transport, and the only:/except: options of a record's as_json - Config checks beyond the basics; url, token and proxy handling via URI - Collection: digest re-reads, widening, tie-breaking by id, with_total_count, the Enumerable overrides, and size/length - ResourceProxy: search_filters and its validation - records: the Attributes class, write guards, memo locks and per-class association proxies - the test kit's retry simulation, stub ranking, count routing and page windows The README, CHANGELOG and specs follow; the CHANGELOG's 2.0 Fixed section keeps only fixes to what 1.x users saw. --- CHANGELOG.md | 1331 ++-------- README.md | 758 ++---- Steepfile | 12 +- examples/error_handling.rb | 2 +- examples/manual_batches.rb | 9 +- examples/quickstart.rb | 2 +- lib/zammad_api/associations.rb | 120 +- lib/zammad_api/attribute_access.rb | 295 +-- lib/zammad_api/attributes.rb | 80 - lib/zammad_api/client.rb | 196 +- lib/zammad_api/collection.rb | 955 +------ lib/zammad_api/config.rb | 610 +---- lib/zammad_api/deep_copy.rb | 138 +- lib/zammad_api/duplicate_keys.rb | 49 - lib/zammad_api/errors.rb | 78 +- lib/zammad_api/query_encoder.rb | 162 -- lib/zammad_api/resource_proxy.rb | 626 +---- lib/zammad_api/resources/base.rb | 1042 +------- lib/zammad_api/resources/ticket.rb | 61 +- lib/zammad_api/resources/ticket_article.rb | 33 +- .../resources/ticket_article_attachment.rb | 51 +- lib/zammad_api/resources/user.rb | 9 - lib/zammad_api/response.rb | 160 +- lib/zammad_api/test.rb | 671 +---- lib/zammad_api/transport.rb | 1989 +-------------- script/check_connection.rb | 7 - sig/vendor/faraday.rbs | 31 - sig/vendor/internal.rbs | 14 - sig/zammad_api/associations.rbs | 24 +- sig/zammad_api/attribute_access.rbs | 9 +- sig/zammad_api/attributes.rbs | 11 - sig/zammad_api/client.rbs | 2 - sig/zammad_api/collection.rbs | 44 +- sig/zammad_api/config.rbs | 44 +- sig/zammad_api/deep_copy.rbs | 2 - sig/zammad_api/duplicate_keys.rbs | 9 - sig/zammad_api/errors.rbs | 10 +- sig/zammad_api/query_encoder.rbs | 13 - sig/zammad_api/resource_proxy.rbs | 31 +- sig/zammad_api/resources/base.rbs | 29 +- sig/zammad_api/resources/resources.rbs | 13 - sig/zammad_api/response.rbs | 13 +- sig/zammad_api/test.rbs | 50 +- sig/zammad_api/transport.rbs | 92 +- .../zammad_api/associations/proxy_spec.rb | 115 +- spec/unit/zammad_api/attribute_access_spec.rb | 198 +- spec/unit/zammad_api/attributes_spec.rb | 115 - spec/unit/zammad_api/client_spec.rb | 383 +-- spec/unit/zammad_api/collection_spec.rb | 1064 +------- spec/unit/zammad_api/config_spec.rb | 654 +---- spec/unit/zammad_api/query_encoder_spec.rb | 180 -- spec/unit/zammad_api/resource_proxy_spec.rb | 677 +---- spec/unit/zammad_api/resources/base_spec.rb | 996 +------- .../ticket_article_attachment_spec.rb | 67 - spec/unit/zammad_api/resources/ticket_spec.rb | 122 +- spec/unit/zammad_api/response_error_spec.rb | 53 +- spec/unit/zammad_api/response_spec.rb | 126 +- spec/unit/zammad_api/test_spec.rb | 923 +------ spec/unit/zammad_api/transport_spec.rb | 2251 ++--------------- 59 files changed, 1551 insertions(+), 16260 deletions(-) delete mode 100644 lib/zammad_api/attributes.rb delete mode 100644 lib/zammad_api/duplicate_keys.rb delete mode 100644 lib/zammad_api/query_encoder.rb delete mode 100644 sig/zammad_api/attributes.rbs delete mode 100644 sig/zammad_api/duplicate_keys.rbs delete mode 100644 sig/zammad_api/query_encoder.rbs delete mode 100644 spec/unit/zammad_api/attributes_spec.rb delete mode 100644 spec/unit/zammad_api/query_encoder_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 682875a..0e8f7a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,16 +12,14 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a ### Breaking - Minimum Ruby version is now 3.4. 3.0 through 3.2 are end-of-life, and 3.3 is in security - maintenance until March 2027. The library needs nothing from 3.4 but the `it` block - parameter, so the floor is a choice rather than a dependency. + maintenance until March 2027. - `Client.new` takes keyword arguments, so a configuration Hash has to be splatted: `Client.new(**config)`. A positional Hash raises `ArgumentError`. - An unknown client option raises `ArgumentError: unknown keyword` instead of being - ignored, so an option that is misspelled or no longer supported is no longer silent. + ignored. - `logger:` takes a `Logger` rather than a boolean flag. `logger: true` used to turn on - debug output to `$stderr`; pass `Logger.new($stderr)` for the same thing. Any object - whose `debug` can be called with a block and no argument, as `Logger#debug` is, is - accepted, and anything else raises `ConfigurationError`. + debug output to `$stderr`; pass `Logger.new($stderr)` for the same thing. Anything that + responds to `debug` is accepted, and anything else raises `ConfigurationError`. - `Collection#each` (`client.x.all`, `client.x.search`) now walks every page. Previously it fetched a single page, so iterating stopped silently at 100 records for `all` and at 10 for `search`. @@ -31,8 +29,7 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `search(query: 'zammad')` is `search('zammad')`, and `search(query: 'z', page: 2, per_page: 50)` is `search('z').page(2, per_page: 50)`. `all` accepted those keywords and then discarded them, so its page size was always - 100 and its filters never reached the request; `search` did honour `page` and - `per_page`. All of them now raise `ArgumentError` rather than being accepted. + 100 and its filters never reached the request. All of them now raise `ArgumentError`. - `page(number, per_page)` with a block was replaced by `page(number, per_page: size)`, which returns a new collection. `page_next` and `page_prev` were removed. - `Collection#[]` was removed. It cost a request per index and ignored the page a @@ -42,60 +39,36 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a to walk, `in_batches(of:)` to batch, `page(number, per_page:)` for one page. Everything else fetches as many records as the endpoint serves. - A collection fetches the endpoint's own page size rather than a fixed 100 — 1000 on the - index endpoints, 100 on `/api/v1/tickets`, 200 on a search — so a walk spends roughly a - tenth of the round trips, each of which is a fresh TLS handshake under Faraday's default - adapter. `page(n)` without `per_page:` is a page of that size, so pin it with - `page(n, per_page: 100)` where a persisted page number has to keep meaning what it did. -- A `nil` query value raises `ArgumentError`. 1.x dropped the parameter, so a filter that - happened to be `nil` requested every record and the caller iterated all of them - believing they had been narrowed. + index endpoints, 100 on `/api/v1/tickets`, 200 on a search. `page(n)` without `per_page:` + is a page of that size, so pin it with `page(n, per_page: 100)` where a persisted page + number has to keep meaning what it did. - `client.on_behalf_of = 'login'` and `client.perform_on_behalf_of` were replaced by - `client.on_behalf_of('login')`, which returns a new client and also accepts a block. + `client.on_behalf_of('login')`, which returns a new client and also accepts a block. A + blank identifier raises `ArgumentError`. - `ZammadAPI::ResourceNotFoundError` is now `ZammadAPI::UnknownResourceError`, freeing the 404 case to be `ZammadAPI::NotFoundError`. - `record.save` reports a validation failure as `false` and leaves the error in `record.error`, instead of raising. `record.save!` is the raising form. Every other - failure — an expired token, a missing record, an unreachable instance — still raises from - both, because no attribute the caller can fix would change the outcome. - `client..create` uses `save!`, so it keeps raising rather than returning a - record that looks created but is not. -- A resource's class-level memos — the association proxy class and the `belongs_to` - foreign keys — are built under a lock. They were plain `@x ||=`, so two threads building - clients or reading associations at once could each build a different anonymous proxy - class for one resource, and whichever write lost was still held by the records already - built from it. Harmless under CRuby's GVL, wrong on JRuby and TruffleRuby, which is not - the contract `README` writes down. -- `record[:x] = 1` stages the attribute it names. It reached the writer dispatch as `[]=` - and was taken for an attribute literally called `[]` whose value was the index, so the - write was lost without an error and the next `save` sent `{"[]": "x"}` to Zammad. Ruby's - operators end in `=` too, so `record <= 5` invented an attribute called `<` the same way; - a writer is now recognised only by a plain attribute name. -- `record.destroy` and `record.reload` refuse a record that was never saved, instead of - acting on an id it was merely built with. `client.groups.new(id: 99).destroy` reported - `new_record?` true and `persisted?` false and still sent `DELETE /api/v1/groups/99`. -- `record.id = ...` raises. The id is what addresses the record, so a staged one took - effect for every path that builds a URL from the attributes and not at all for the record - those paths then reported on: `group.id = 99; group.destroy` sent `DELETE` to group 99 - and left the record saying group 1 was the one destroyed. Zammad does not let an id be - set either, so no call that used to reach the server is lost. The constructor refuses it - too: `client.groups.new(id: 5)` raises, because a new record is sent in full, so the one - spelling that reached the wire was the one nothing checked. `Resource.from_response` is - how a body Zammad served becomes a record carrying its id. -- `record.destroy` marks the record `destroyed?`, and `persisted?` answers false for one. - 1.x left a destroyed record looking live, so a later `save` went out as a `PUT` to the - deleted id and came back a 404 one call after the mistake. + failure still raises from both. `client..create` uses `save!`. +- `record.destroy` and `record.reload` raise for a record that was never saved, instead of + acting on an id it was merely built with: `client.groups.new(id: 99).destroy` sent + `DELETE /api/v1/groups/99`. +- `record.id = ...` raises `ZammadAPI::Error`. The id is what addresses the record, so a + staged one made `destroy` and `save` act on another record than the one they reported on. +- `record.destroy` marks the record `destroyed?`, and `persisted?` answers false for one; + `save`, `reload` and attribute writers raise for it. 1.x left a destroyed record looking + live, so a later `save` went out as a `PUT` to the deleted id. - `record.attributes` and `record.changes` are deeply frozen, and `record.to_h` returns a deep copy rather than a shallow one. Writing through either reader used to change what a - record reported without staging anything, so the next `save` did not send it, and a - nested hash from `to_h` was shared with the record. + record reported without staging anything, so the next `save` did not send it. - The `record.attributes=` writer was removed. An unknown name is an ordinary attribute now, so `record.attributes = {name: 'Support'}` stages a change called `attributes` that `save` sends to Zammad. Use `assign_attributes` or `update`. - `ZammadAPI::Error` descends from `StandardError` instead of `RuntimeError`. - `ResponseError#response` returns a `ZammadAPI::Response`, not a Faraday object, and `#body` is the decoded payload rather than a raw JSON string. -- No Faraday exception escapes any more: an unreachable host or a timeout raises - `ZammadAPI::ConnectionError` or `ZammadAPI::TimeoutError`, so a +- No Faraday exception escapes from a request any more: an unreachable host or a timeout + raises `ZammadAPI::ConnectionError` or `ZammadAPI::TimeoutError`, so a `rescue Faraday::ConnectionFailed` stops matching. - `ZammadAPI::ListBase`, `ListAll` and `ListSearch` were replaced by `ZammadAPI::Collection`. - `ZammadAPI::Log` and `ZammadAPI::JsonHelper` were removed. Pass any `Logger` via `logger:`. @@ -103,1217 +76,203 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - The resource readers on a client are plural: `client.tickets`, `client.users`, `client.groups`, `client.organizations`, `client.ticket_articles`, `client.ticket_priorities` and `client.ticket_states`. A resource is `Enumerable` over - every record of its kind, so `client.ticket.each` and `client.ticket.first(5)` read as if - they acted on one ticket; the singular dates from 1.x, when a resource was only a - dispatcher for `find` and `create`. The singular names are gone: `client.ticket` raises - `UnknownResourceError`, which lists the plural names, and so does + every record of its kind, so `client.ticket.each` read as if it acted on one ticket. The + singular names raise `UnknownResourceError`, which lists the plural ones, and so does `client.resource(:ticket)`. `client.resource_names` lists the plural names. - The resource readers a client has are a fixed list. 1.x resolved `client.` to - `ZammadAPI::Resources::` through `const_get`, so a subclass of `Base` defined in - application code could be reached that way. `client.role` now raises - `UnknownResourceError`; hand the class over instead, with `client.resource(Role)`. + `ZammadAPI::Resources::` through `const_get`; `client.role` now raises + `UnknownResourceError`. Hand a class of your own over instead, with + `client.resource(Role)`. - The internal `new_instance` accessor was replaced by `new_record?` and `persisted?`, and the instance-level `url` accessor by the class-level `resource_path`. Both old names now - raise `NoMethodError` as unknown attributes, naming the attributes the record does carry. + raise `NoMethodError`. - A reader for an attribute the record does not carry raises `NoMethodError` instead of - answering `nil`. A typo read as `nil` and flowed on into whatever was written with it, - and `respond_to?` and `method` disagreed with the call throughout, so generic code that - asks before it calls was told the reader did not exist. `record[:x]`, + answering `nil`, so a typo no longer reads as `nil`. `record[:x]`, `record.fetch(:x, nil)` and `record.key?(:x)` are the readers for an attribute that may - legitimately be absent — which it may, because Zammad serves a reduced object where the - authenticated user may not see the whole record, and the message says so. -- `Collection#find` raises `ArgumentError` when given an id. `find` on a resource proxy is - the lookup by id; on a collection it is `Enumerable#find`, whose argument is an ifnone - callable — so `client.tickets.all.find(1)` answered with an `Enumerator`, made no request - and raised nothing. Use `client.tickets.find(1)`, or `detect { … }` for the block form. -- `TicketArticle#attachments` raises `ParseError` for attachment metadata that is not a - list of objects, where it used to die with a bare `NoMethodError` from inside the gem — - past the `rescue ZammadAPI::Error` every caller is told to write. -- `page(number, per_page: size)` raises `ArgumentError` when `size` is larger than the endpoint - serves, instead of quietly reducing it. A reduced page size moves the page: - `page(3, per_page: 500)` against `/api/v1/tickets` went out as `page=3&per_page=100` and - answered with records 201–300 rather than 1001–1500, so a job checkpointing a page - number re-read what it had already handled. `find_each(batch_size:)` and - `in_batches(of:)` are still reduced, because a batch size names how much to fetch per - request, not which records the call is about. -- `find_by` searches one string value — the longest. Zammad matches words, so - `find_by(active: true)` searched for `"true"` and found nothing. Every other value is - compared against the record, so `find_by(email: '…', active: true)` searches the email - and compares both, and a lookup with no string in it walks the index instead. The values are - never joined into a single term: an instance searching without Elasticsearch matches the - term literally, through a SQL `LIKE` over each string column, so - `find_by(firstname: 'Jane', lastname: 'Doe')` asked for one column containing - `"Jane Doe"` and reported a user that exists as `nil`. + legitimately be absent, which it may be where Zammad serves a reduced object. +- `Collection#find` raises `ArgumentError` when given an id. On a collection it is + `Enumerable#find`, whose argument is an ifnone callable, so `client.tickets.all.find(1)` + answered with an `Enumerator` and made no request. Use `client.tickets.find(1)`, or + `detect { … }` for the block form. +- `find_by` searches one string value, the longest, and compares every value against the + hits. A lookup with no string in it, or on a resource without a search endpoint, walks + the index instead. - `search` raises `ZammadAPI::Error` on a resource Zammad routes no search endpoint for — - `ticket_states`, `ticket_priorities` and `ticket_articles`. Those endpoints answered 404, - which arrived as a `NotFoundError` about a record from a call that asked for a list, and - reached `find_by` the same way, so `find_by(…) || create(…)` raised instead of creating. - `find_by` walks those lists instead of searching them. -- Nothing reads an `x-total-count` response header any more, because Zammad has never sent - one — from any endpoint, in any version. `Response#reported_total` was built on it, and - two guards read that: `Collection#each` would have ended a walk one request early on the - reported figure, and a `has_many` reader would have refused a list it judged truncated. - Both were dead, and the one that could have acted was the one that could have been - wrong, since it ends a walk on a figure the records do not corroborate. Zammad reports a - total in the body instead, and only where asked: `only_total_count` — which is what - `Collection#count` uses on a search — or `with_total_count` on `/search`, and `full` on - the index endpoints that render through `model_index_render`. -- A record id of `.` or `..` raises `ArgumentError`. Both are made entirely of unreserved - characters, so escaping carried them through and `find('..')` resolved one path level - up — onto the index endpoint, or through a `has_many` path onto every article on the - instance offered as one ticket's. + `ticket_states`, `ticket_priorities` and `ticket_articles` — instead of reaching a 404. - A configuration that names more than one way to authenticate raises `ConfigurationError`. - `http_token`, `oauth2_token` and `user` with `password` used to be accepted together, and - the first of them in that order was sent without a word about the others — which is what - let `from_env(user:, password:)` and `with(oauth2_token:)` keep sending an old token. A - client authenticates one way by construction now. `from_env` and `with` drop the - credentials an override replaces, so switching schemes through either still works, and an - environment that itself sets two schemes is refused until an argument says which is meant. + 1.x accepted a token beside a user and password and sent the first in its order without + a word about the others. `from_env` and `with` drop the credentials an override replaces. - `ticket.article(…)` is `ticket.add_article(…)`. A noun that sends a `POST` sat one letter - away from `ticket.articles`, which only reads. The old method is gone, which leaves - `article` an attribute reader like any other: called the old way it raises `NoMethodError` - on a ticket that has no article staged and `ArgumentError`, naming `add_article`, on one - that has, and sends nothing either way. + away from `ticket.articles`, which only reads. `article` is now an attribute reader like + any other, and the old call raises `NoMethodError`. ### Added -- `Collection#first` and `#take` size their own request: `all.first` is one request for one - record and `all.first(5)` one request for five, where `Enumerable` took them off the - front of a page sized for walking. The request is sized rather than the collection - limited to a page, so a read still walks on where a page comes back shorter than it was - asked for — `first(5)` answers with five records if five exist. A collection `page` - already limited keeps its own size, because that size says which records it holds. -- `client.get`, `#post`, `#put` and `#delete` take `headers:`, for an endpoint that needs - one. Names are case-insensitive and two spellings of one header are refused rather than - merged; `Authorization` and `From` are refused outright, being what the client's - credentials and `on_behalf_of` are for. -- `Test::Request#headers` records the headers a request asked for, stringified and - downcased through the real transport's own rules, so a stand-in cannot accept a header - the wire would refuse. - `client.get`, `client.post`, `client.put` and `client.delete` reach any endpoint of the - Zammad API, including the many this gem does not model. They return a - `ZammadAPI::Response` and keep authentication, timeouts, retries, credential redaction, - JSON decoding and the error classes. Previously the only way past the seven resource - classes was to build a Faraday connection by hand. + Zammad API, with `query:`, `body:` and `headers:`. They return a `ZammadAPI::Response` + and keep authentication, timeouts, retries, credential redaction, JSON decoding and the + error classes. A path is relative to the instance URL, and one that opens with a scheme + raises `ArgumentError`, so the credentials stay with the configured instance. - Request and connection timeouts (`timeout`, `open_timeout`), on by default at 60 and 10 seconds. 1.x waited as long as the server took, so a call that used to hang now raises `TimeoutError`. - Automatic retry with exponential backoff for a `GET` on connection failures, timeouts - and transient statuses. A write is never retried. `POST` would create a second record, - and `PUT` and `DELETE` are not safe to repeat against Zammad either: a ticket update - carrying an `article` adds that article, and sends its e-mail, once per delivery, and a - `DELETE` repeated after a lost answer comes back as a 404 for a record that was just - deleted, so `destroy` raised `NotFoundError` and left the record looking live. + and the statuses 429, 500, 502, 503 and 504. A `Retry-After` within `timeout` is + honoured, and a longer one ends the retries. A write is never retried: a repeated ticket + update carrying an `article` adds that article, and sends its e-mail, twice. - A specific error class per status: `AuthenticationError` (401), `AuthorizationError` (403), `NotFoundError` (404), `ValidationError` (422) and `RateLimitError` (429, with - `#retry_after`). Network failures raise `ConnectionError` or `TimeoutError` instead of - leaking Faraday exceptions. -- `Collection#order`, `#page`, `#in_batches`, `#find_each`, `#count` and lazy - enumeration, plus `client.x.order(...)` as a shorthand for `all.order(...)`. + `#retry_after`). Network failures raise `ConnectionError` or `TimeoutError`. +- `Collection#order`, `#page`, `#in_batches`, `#find_each`, `#count`, `#pluck` and + `#empty?`, plus `client.x.order(...)` as a shorthand for `all.order(...)`. - `order` sorts on the server: `order(:name)`, `order(name: :desc)`, `order(:active, name: :desc)`, read the way ActiveRecord reads them, and a second - `order` sorts within the first. Sorting is the one thing an index endpoint does besides - paging. `/api/v1/tickets` and `/api/v1/users` do not even do that — their controllers - hardcode id order — so `order` on those raises `ArgumentError` rather than handing back - records it would be calling sorted; a search sorts for every resource that can be + `order` sorts within the first. `/api/v1/tickets` and `/api/v1/users` hardcode id order, + so `order` on those raises `ArgumentError`; a search sorts for every resource that can be searched. -- `search` takes what a search endpoint narrows by besides the term as keywords: - `condition:` and `ids:` on every search, and `role_ids:`, `group_ids:` and `permissions:` - on users, the one search that reads them. Any other keyword raises `ArgumentError`, - because Zammad drops a parameter it does not know rather than refusing it, and the search - would come back unnarrowed with nothing to say so. That includes a user keyword on - another resource: `tickets.search('printer', group_ids: [2])` was sent as written and - answered with tickets from every group, where a `condition` on `ticket.group_id` is what - narrows them. A keyword with nothing in it raises too, an empty list, an empty Hash, a - Hash of nothing but empty Hashes, or a value that is sent as a blank String: Zammad reads - it as not given, so `search('smith', ids: [])` came back with - every user matching the term rather than none. A resource of your own declares what its search reads with - `search_filters`. `group_ids:` is a list of group ids, for the agents with `full` access - to them, or a Hash of group id to access, `group_ids: {2 => ['read']}`, for any other: - Zammad reads a group named without an access as `full`. `permissions:` is not an access - check: where Zammad searches through Elasticsearch, a permission no active role grants - leaves the search unnarrowed. `role_ids:` narrows on both paths and is not one either: it - matches a user holding a role that has been disabled. The README says what to check. -- There is no `where`. During the development of 2.0 there was one, which took `sort_by` - and `order_by` on a generic index, nothing at all on tickets and users, and the search - parameters on a search, and raised for everything else — an attribute filter above all, - since Zammad's index endpoints do not filter. The most familiar verb on a collection - refused nearly everything it was given, so the two things it did do have names of their - own: `order`, and the keywords of `search`. +- `search(term, **filters)` passes its keywords on to the search endpoint, for what it + narrows by besides the term: `condition:` and `ids:`, and `role_ids:`, `group_ids:` and + `permissions:` on users. A blank term raises `ArgumentError`; `'*'` asks for every record. +- There is no `where`: Zammad's index endpoints sort and page and drop every other + parameter, so filtering is `search` and `find_by`. - A resource proxy is `Enumerable` over `all`, so `client.tickets.each`, `client.tickets.first(5)`, `client.tickets.map`, `#find_each`, `#in_batches`, `#page`, `#pluck` and `#count` all work without naming `all`. `client.x.find(id)` keeps its own meaning rather than becoming `Enumerable#find`; `detect` is the block form. - `Collection#count` costs a single request on a search endpoint, which Zammad can count - without returning the records. -- `Collection#pluck(*attributes)`, for reading one or more attributes from every record. + without returning the records. Elsewhere it walks. +- `Collection#first` sizes its own request: `all.first` is one request for one record and + `all.first(5)` one request for five. `empty?` asks for one record the same way. +- A walk of an index ends at the first page shorter than the size it asked for, and a + search walk at the first empty page, since Zammad can serve a short page with more hits + behind it. - `client..find_by(**params)` and `#find_by!`, which look a record up by - attribute value, and `client..exists?(id)`. `find_by` answers on every - resource and for any kind of value: the first record that carries the values, `nil` if - it finds none. It fetches candidates and checks them itself, because Zammad's index - endpoints cannot filter — through a search where the resource has a search endpoint and - one of the values is a string, and by walking the index everywhere else, which is what - `ticket_states`, `ticket_priorities` and `ticket_articles` and a lookup such as - `find_by(active: true)` get. A walk costs a request per page until a record matches. It - returns a record that genuinely carries the attributes asked for, or nil; a record that - does not carry an attribute does not match it, not even for `nil`. What the search can - surface is Zammad's business, so `find_by(...) || create(...)` can still create a - duplicate — as writing the search out by hand would. Without Elasticsearch a search - reads only the string columns of a user, organization or group, and of a ticket only the - title, the number and its articles, so a lookup by anything else answers `nil` there; - the README lists what that covers and why `find_by` does not walk the index after a - miss. Every page of hits is read until - one matches, so a miss costs a request per page of hits: Zammad's search sorts by - `updated_at`, newest first, rather than by relevance, so the exact match can be on any - page. + attribute value, and `client..exists?(id)`. `find_by` answers with the first + record that carries all the values, or `nil`: by its id where `id:` is given, through a + search where the resource has one and a String value is given, and by walking the index + everywhere else. - `ResponseError` accepts a `detail:` describing a failure that has no HTTP response of its - own, so `find_by!` reads as `no record matched` rather than `no response`. Such an error - still reports the status its class is the name for, so a `NotFoundError` raised without a - request answers `404` like every other one. + own, so `find_by!` reads as `no record matched`. - The page size is clamped to what an endpoint serves (100 for `/api/v1/tickets`, 200 for a search, 1000 for the other index endpoints). Asking for more used to end iteration after the first page, because Zammad capped the response and the short page read as the - end of the list. A walk also learns the size the endpoint actually serves from its first - page, so an instance that pages smaller than those figures is still walked to the end - rather than truncated. -- `find_each(batch_size:)` and `in_batches(of:)` raise when the collection is already - limited to a page. `page(3, per_page: 50)` and a batch size are two ways of naming the same - thing, and re-sizing the page behind the caller would hand back different records. -- `ZammadAPI::PaginationError`, raised when an endpoint answers a page with the page - before it, instead of paging forever. -- `Base#reload`, `#persisted?`, `#[]`, `#fetch`, `#to_h` and a readable `#inspect`. + end of the list. +- `ZammadAPI::PaginationError`, raised when an endpoint answers a page with the records of + the page before it, instead of paging forever. +- `paginated false` declares an index endpoint that serves every record in one response, + such as `api/v1/object_manager_attributes`. It is then read in one request. +- `Base#reload`, `#persisted?`, `#destroyed?`, `#[]`, `#[]=`, `#fetch`, `#key?`, `#to_h` and + a readable `#inspect` that blanks attributes naming a credential. - `record.update(attributes)`, `record.update!(attributes)` and - `record.assign_attributes(attributes)`. Applying a hash of changes previously meant one - writer call per attribute before `save`. + `record.assign_attributes(attributes)`. Attributes can be a Hash or anything with + `to_hash`, such as permitted `ActionController::Parameters`. - `ssl_verify`, `proxy`, `user_agent`, `retries` and `retry_interval` client options. The default `User-Agent` is now `zammad_api-ruby/` rather than `Zammad API Ruby`. -- `adapter` and `middleware` client options, the seam into the Faraday stack. Swapping in a - persistent-connection adapter or adding instrumentation previously meant that the HTTP - stack was closed to callers. A Faraday error while building the connection surfaces as - `ConfigurationError`, so Faraday stays an implementation detail. +- `adapter` and `middleware` client options, the seam into the Faraday stack, for a + persistent-connection adapter or instrumentation. An adapter set inside the + `middleware:` callable takes the place of `adapter:`. A Faraday error while building the + connection surfaces as `ConfigurationError`. - RBS signatures in `sig/`, verified by Steep in CI. - `require 'zammad_api/test'` ships a stand-in Zammad for testing code that calls this client: `ZammadAPI::Test#stub` declares responses, `#client` hands back a real client - wired to them, and `#requests` records what was sent. Responses travel the same decoding, - error mapping and record building as real ones, so a stubbed 404 raises `NotFoundError`. - An unstubbed request raises rather than answering with something empty. Consumers - previously had to intercept HTTP to test against this client at all. -- `respond_to?` now answers correctly for attribute readers and resource methods. + wired to them, and `#requests` records what was sent, with the query as text and the + headers by downcased name. Responses travel the same decoding, error mapping and record + building as real ones, so a stubbed 404 raises `NotFoundError`. An unstubbed request + raises rather than answering with something empty. +- `respond_to?` answers correctly for attribute readers and resource methods. - Records implement `deconstruct_keys`, so they can be used with `case/in` pattern - matching, including against nested attributes. `Config` and `Response` are `Data` - objects and match as well. + matching. `Config` and `Response` are `Data` objects and match as well. - `Client#with(**options)` derives a new client with changed options. The options are re-validated and any `on_behalf_of` scope is carried over. - `Client.from_env` builds a client from `ZAMMAD_URL`, `ZAMMAD_TOKEN`, `ZAMMAD_HTTP_TOKEN`, `ZAMMAD_OAUTH2_TOKEN`, `ZAMMAD_USER` and `ZAMMAD_PASSWORD`, with - passed-in options winning. Every example script used to repeat the same `ENV.fetch` pair. + passed-in options winning. A blank variable counts as unset. - `Client#me`, the user the credentials authenticate as, and `Client#version`, the version of the Zammad instance. -- `Response#decoded(:object | :array)` validates the shape of a response body in one - place, so an unexpected payload raises `ParseError` with a consistent message instead of - failing further downstream. +- `Response#decoded(:object | :array)` checks the shape of a response body in one place, + so an unexpected payload raises `ParseError`. - `record.related` reaches the records a record points at: `ticket.related.customer`, `ticket.related.group`, `ticket.related.articles`, `user.related.organization`, and - `created_by` / `updated_by` on everything. Following a foreign key used to mean - `client.users.find(ticket.customer_id)` by hand. The readers sit under `related` rather - than on the record because Zammad expands an association into a name under the plain - attribute, and `ticket.customer` has to keep returning that name rather than turning - into a request. `Resource.associations` lists what a resource declares. + `created_by` / `updated_by` on everything. The readers sit under `related` because + Zammad expands an association into a name under the plain attribute, and + `ticket.customer` keeps returning that name. `Resource.associations` lists what a + resource declares. - Records compare as the Zammad records they came from: two records of the same kind with - the same id are equal, and `#hash` agrees, so `uniq`, `Set`, `include?` and records as - Hash keys all work. They previously compared by object identity, so the same ticket - fetched twice was two unequal records. A record with no id stays equal only to itself, - which means its first save changes its hash and a record used as a Hash key before that - save has to be rehashed after it. + the same id, read from the same Zammad URL, are equal, and `#hash` agrees, so `uniq`, + `Set`, `include?` and records as Hash keys all work. A record with no id stays equal only + to itself. - `record.to_json` and `record.as_json` render a record's attributes. `to_json` previously fell through to `Object#to_json`, which serialized a record as the string `"#"`. -- `Collection#empty?`, and `#size` / `#length` as names for `#count`. `Enumerable` supplies - none of the three, so `client.tickets.all.empty?` used to raise `NoMethodError`. `empty?` - costs one request and asks for a single record rather than a whole page, except on a - collection limited to one page, where the page size decides which records that page holds. - A resource proxy forwards all three. - `client.resource(SomeClass)` takes a subclass of `ZammadAPI::Resources::Base` and answers with a proxy for it, so an endpoint this gem does not model gets records, pagination, - `find_by`, change tracking and `save` from a class that declares its `path`: `class Role < - ZammadAPI::Resources::Base; path 'api/v1/roles'; end`, then `client.resource(Role).each { - … }`. `Base` already supported being subclassed, and `searchable`, `max_per_page`, - `sortable`, `belongs_to` and `has_many` are there to say what else is true of the - endpoint; what was missing since `const_get` went was a public way to a proxy for one, - which left raw requests as the only way to the rest of the API. An association on such a - class can point at another by its full name, `class_name: 'Acme::Role'`. + `find_by`, change tracking and `save` from a class that declares its `path`. `searchable`, + `max_per_page`, `sortable`, `paginated`, `belongs_to` and `has_many` say what else is + true of the endpoint. - Typed records. `ResourceProxy` and `Collection` are generic over the resource they hold, so `client.tickets` is a `ResourceProxy[Resources::Ticket]` and `find`, `first`, - `find_by`, the block of `each` and a search all answer with a `Ticket` where the - signatures said `untyped`. Each resource declares the attributes every supported Zammad - serves for it — the columns of its table, typed the way their JSON arrives — so - `ticket.title` is a `String` and `ticket.titel` is a type error. Attributes an - administrator added are read with `record[:name]` or declared by reopening the class in a - project's own signatures; the README's Type signatures section says what else is left - undeclared and why. `spec/typed/usage.rb` is checked by `rake steep` the way a caller's - code is, and pins these types from the outside. + `find_by`, the block of `each` and a search all answer with a `Ticket`. Each resource + declares the attributes every supported Zammad serves for it, so `ticket.title` is a + `String` and `ticket.titel` is a type error. `spec/typed/usage.rb` is checked by + `rake steep` the way a caller's code is. ### Fixed -- Credentials are no longer written to the debug log. The old transport logged - `user:password` on every client build; payload keys such as `password` and `token` are - now redacted, and `Config#inspect` redacts credentials. A `ConfigurationError` raised - while building the connection redacts the configured url and proxy out of the underlying - message too, including where that message quoted the value through `inspect` rather than - interpolating it — which is what `URI::InvalidURIError` does, for exactly the characters - that make a URL invalid — or through `dump`, which is how it quotes a URL holding a - character outside ASCII: a proxy password with an umlaut in it stayed in the message, and - in the error kept as its cause. -- The debug log redacts a body handed over as a String and a query string written into the - path. Redaction went by key, on a Hash or a list, so - `client.post(path, body: '{"password":"..."}')` was logged as it stood, and - `client.get('api/v1/users/password_reset_verify?token=...')` printed the token in the - request line and the response line. A String body is read for its keys where it is JSON - and replaced by its size where it is not. The path is redacted by parameter name, also - in the message of a timeout and in the operation a raw request is named by in every - error it raises. -- `on_behalf_of` no longer leaks: the old `perform_on_behalf_of` used `tap` without an - `ensure`, so an exception inside the block left the `From` header set on every later - request. -- `on_behalf_of` refuses an identifier that is `nil`, empty or blank with `ArgumentError`. - Zammad reads a `From` header with nothing in it as no header at all, and a `nil` sent - none, so `client.on_behalf_of(user&.login)` with no user handed back a client that - performed every request as the account it authenticates as, and read everything that - account can see, with no error. `Client#inspect` shows the scope of a client that has - one, where it printed as the client it was derived from. -- Zammad installations served from a sub-path (`https://example.com/zammad/`) now work. - Request paths are relative, so the prefix is no longer stripped. -- Query parameters are encoded by the HTTP layer, including arrays and characters that - need escaping. -- Nested attributes inside arrays are symbolized consistently. -- A malformed or non-JSON response body no longer degrades into an empty hash that - callers then iterate as key/value pairs. -- Unknown resource names no longer resolve to unrelated Ruby classes. -- Record ids are escaped everywhere they reach a path, including the attachment download - endpoint and `has_many` association paths, so an id carrying a traversal cannot redirect - a request onto another endpoint. -- A credential carrying an unencoded `@` is redacted whole. Redaction stopped at the first - `@`, so the tail of such a password survived into `Config#inspect` and into every - `ConnectionError` message. -- `Transport#with_config` keeps the transport's own class, so a stand-in written as a - `Transport` subclass survives `client.with(...)` instead of reverting to a real HTTP one. -- `save` on a persisted record with nothing staged sends no request. The empty `PUT` it - used to issue was applied by Zammad, bumping `updated_at` and `updated_by`. -- A nested query parameter is sent as a structure rather than as its Ruby `inspect`. - `condition`, which the search endpoints narrow by and which `search` takes, went out as - `condition=%7B%22ticket.state_id%22…`; Zammad could not parse it, dropped it, and - answered with an unnarrowed search. A `nil` is now refused at any depth, and the message - names the path to it. -- A `condition` that nests groups of conditions reaches Zammad as it was written. A list of - Hashes goes out as `list[][key]=value` pairs, and Rails begins a new element only at a - key the element before it has too. Faraday writes the keys of each Hash in alphabetical - order, so a group, `{operator: 'AND', conditions: [...]}`, after a condition went out - `conditions` first and was read into the condition before it, leaving a second element - that held only an operator. Zammad was handed a selector nobody wrote: it answered that - one with a 500, and the same two elements the other way round with every ticket. The - client writes the query itself now, and begins such an element with a key the two share. - A list no order can carry raises `ArgumentError`: one whose elements share no such key, - a list directly inside a list, and an empty Hash inside a list. Every other query is - written as it was. -- Bare socket failures are retried. `Errno::ECONNRESET` and the rest were mapped to - `ConnectionError` but were missing from the retriable list, so a transient failure - through an adapter that wraps it (net_http) was retried while the same failure through - an adapter that does not raised on the first attempt. -- A list body that is not made of objects raises `ParseError` instead of failing later. An - unexpanded search answering `[1, 2, 3]` stored an Integer as a record's attributes, and - the first reader died with `TypeError: no implicit conversion of Symbol into Integer`. - A `null` among the records is refused as well. It passed the check, which could not tell - a `nil` it had found from having found nothing, and a walk then raised `NoMethodError` - reading the ids of the page. -- `destroy` clears the staged changes and the last validation error, and refuses the - association readers. A destroyed record went on reporting `changed?` and a change set - that can never be sent, and `record.related` went on requesting a record that no longer - exists — dropping the memo was not enough on its own, because the reader rebuilt one on - the next call. `record.related`, `ticket.articles` and `ticket.add_article(…)` all raise - `ZammadAPI::Error` for a destroyed record now, rather than reaching the server for it. -- `Config#redacted_url` no longer mangles a URL whose query string contains an `@`. - `https://host?a=b@c` was rendered as `https://[REDACTED]@c`, a host that does not exist, - in every `ConnectionError` and `TimeoutError` message. -- The RBS signatures the gem ships validate on their own. They named Faraday types that - are declared only in `sig/vendor`, which is deliberately not published, so `rbs validate` - failed for every consumer with `Could not find Faraday::Connection`. -- `ZammadAPI::Test.new` no longer builds a Faraday stack it immediately discards, which a - suite using `let(:zammad) { ZammadAPI::Test.new }` paid for once per example. -- The trailing slash a base URL is normalised with lands on the path rather than at the end - of the string. `https://host/zammad?tenant=acme` became `https://host/zammad?tenant=acme/`, - which every request was then resolved against and every `ConnectionError` printed. -- `Config` refuses a URL with a scheme and no host, and one that is not a String. Both used - to be accepted: `'https://'` failed deep inside the adapter on the first request, and a - `URI` — what `URI(...)` hands back, and it prints as the URL — died as a `NoMethodError` - past the `ConfigurationError` the constructor is documented to raise. -- `user_agent: nil` falls back to the gem's own value instead of reaching Faraday as a nil - header, which Faraday filled in with its own — so the gem silently stopped identifying - itself in the instance log an operator greps to find its requests. A `user_agent` that is - not a String raises `ConfigurationError`. -- A line break inside `http_token`, `oauth2_token` or `user_agent` raises - `ConfigurationError` when the client is built, and one inside an `on_behalf_of` - identifier or a raw request's header raises `ArgumentError`. Each was taken and then - refused by Net::HTTP at the first request, with an `ArgumentError` that quoted the value, - the access token included. Neither message quotes it now. A line break at the end, as a - token read from a file has, is stripped by Net::HTTP and still taken. -- Proxy credentials are redacted whether or not the proxy URL carries a scheme. - `proxy: 'user:secret@proxy:8080'` — the shape an `http_proxy` setting is copied out of — - rendered in `Config#inspect` in full. -- A `proxy` that is not a URL, and a `middleware` callable that raises, are reported as - `ConfigurationError`. Only `Faraday::Error` was wrapped, so these escaped as - `URI::InvalidURIError` and as whatever the callable raised, past the - `rescue ZammadAPI::ConfigurationError` around building a client. -- The debug log redacts `api_key`, `apikey`, `passwd`, `pwd` and a bare `key` as well. The - pattern matched `private_key` but not the other key spellings, and `password` but not its - short forms, so those payload values were written out in full. -- `destroyed?` is sticky. `reload` re-read a record that no longer exists and cleared the - flag on the way back, so a destroyed record came back reporting itself as `persisted?` - and its next `save` issued a `PUT` against the deleted path; a second `destroy` surfaced - Zammad's 404 rather than saying the record was already gone. `save`, `reload` and - `destroy` now all refuse a destroyed record with the same local error. -- `record.fetch` refuses more than one fallback, the way `Hash#fetch` does. `fetch(:a, :b, - :c)` — a multi-key read this has never been — was answered with `:b`. -- A collection smaller than one page costs one request rather than two. The walk confirms - the end of a short page with another request, which could only ever come back empty; it - now stops on the total the endpoint reports alongside the page, and only falls back to - confirming when the endpoint reports none. The total has to be corroborated by the page - it arrived with — the page came back short of the size requested, and exactly as many - records were seen as the total names. It is the one stop condition not derived from the - records the endpoint served, and a total that under-reports (a count taken before - permission scoping, a stale cache, a proxy rewriting the header) ended the walk early: - 100 of 150 records came back, nothing was raised, and nothing told that result apart - from a complete one. -- The test kit records a request body by value. Held by reference, a test that built one - payload, sent it, then changed it for a second call rewrote the first recorded request - and asserted against a body that never went anywhere. `Test#inspect` also reads the - recorded requests under the monitor that guards them. -- A record is persisted because Zammad answered 2xx, not because the answer parsed. The - create response was decoded before the flag went down, so a 201 carrying something other - than a JSON object — a body cut off or rewritten on its way through a proxy — raised - `ParseError` with the record still looking new. The ticket existed in Zammad while the - record here did not, and a retried `save` POSTed a second one. What that leaves behind is - a record that is persisted and has no id, and `save`, `reload` and `destroy` all refuse - it by name rather than pretending: a record built by `new` has nothing staged, so the - retried `save` took the "nothing changed, nothing to send" short circuit and returned - `true` without making a single request, for a record that may or may not be in Zammad. -- A `ConfigurationError` raised while building the connection no longer quotes the proxy - credentials. `proxy: 'http://user:pa ss@host:3128'` came back as - `URI::InvalidURIError` with the whole URL, password included, in a message that lands in - every log and exception report — the case `Config#inspect` exists to prevent, reached by - another route. -- `Config` refuses a `proxy` that is not a String, an `adapter` that cannot be a Symbol, - and an `ssl_verify` that is not a boolean. A `URI` proxy was accepted and then died as a - `NoMethodError` inside `inspect`, so the object documented as safe to log raised at the - moment something logged it; `adapter: 1` and `adapter: true` escaped the constructor as - `NoMethodError`; and `ssl_verify: 'false'` — a plausible environment read — is the - truthy string `"false"`, so verification stayed on while the caller believed otherwise. -- An `OpenSSL::SSL::SSLError` that an adapter did not wrap is mapped to `ConnectionError` - like its Faraday counterpart. Unlisted, a certificate mismatch through such an adapter — - and this gem lets a caller choose one — escaped `request` raw, past every - `rescue ZammadAPI::Error`. It is not retried: a rejected certificate is a fact about the - instance, not a transient failure. -- A resource subclassed by a caller keeps its parent's API path. Class-level state is not - inherited, so `class MyTicket < Ticket; end` inherited all nine of Ticket's associations, - its page limit and its searchability, and lost only the path — `MyTicket.resource_path` - raised "does not declare an API path" from a class that plainly did. -- The test kit answers a later page of a singly-stubbed list endpoint the way an endpoint - out of records would. A stub that kept serving the same records to every page tripped the - repeated-page guard, so the obvious `stub(:get, 'api/v1/groups', body: [...])` made every - full read of that collection raise `PaginationError`. Against a real Zammad the same code - works, because page 2 comes back empty; the stand-in was what differed. A stub that names - a `page` is still served exactly as written. -- The test kit sequences stubs within an identical query scope rather than across every - scoped stub for an endpoint. Two stubs naming different parameters both match a request - carrying all of them, and they were read as a sequence: stubbing a search once for its - records and once for its count made `count` consume the records stub, hand back an Array - where a count belonged, and then report the endpoint as unstubbed. The most specific - scope now answers, and two that are equally specific raise - `ZammadAPI::Test::AmbiguousStubError` rather than one of them being picked. -- `Collection#count` reads the total from the header when a search endpoint ignores - `only_total_count`. The probe came back as the usual page of records and was thrown away, - so the answer cost 1 + N requests instead of N. -- `update` and `update!` refuse a destroyed record before staging anything. They assigned - first and saved second, and `save!` is where the destroyed check lives, so `update` on a - destroyed record raised and left it `changed?` with a change set that can never be - sent — the state `destroy` clears the staged changes to prevent. -- Writing an attribute the record does not carry is a change, and is sent. Zammad reduces - the object it serializes for a permission-scoped client, so a key being absent says - nothing about what is stored; read as a `nil` original, `group.note = nil` compared equal - to nil, staged nothing and was still merged into the attributes. The write was dropped - without a word, `save` returned `true` having sent no request, and the record went on - reporting a key Zammad never sent it, so `changes` and `attributes` disagreed. -- `ticket.add_article(...)` refuses a ticket that has not been saved instead of POSTing - `ticket_id: null` and leaving the caller to read Zammad's 422 for the reason. Every other - path in the gem that needs a stored id says so locally. -- The documentation no longer promises that a `has_many` reader refuses a partial list - with `ZammadAPI::PaginationError`. The check behind that promise read a total from an - `x-total-count` response header, which Zammad has never sent, so it never ran and was - removed — see the entry on that header under Breaking — while this entry, the README and - the comment on `has_many` went on describing it. A `has_many` list is read in a single - request because the association endpoints Zammad routes serve the whole thing: - `ticket_articles/by_ticket` renders every article of the ticket and reads no paging - parameter. Nothing in a response tells a whole list from the first page of one, so - there is no honest check to put in its place. -- The documented page sizes are sizes the endpoints actually serve. Every `find_each` and - `in_batches` example used `of: 500` against `client.tickets`, which caps at 100, so each - headline example did something other than what it showed. The clamp itself stands — a - batch size says how much to fetch at a time, not which records you get, which is why - `page` refuses an oversize size and a walk reduces it. -- A destroyed record reports the attributes Zammad last served, not a write that never - left the process. `destroy` dropped the staged change set and left the writes it - described standing, so `group.name = 'B'; group.destroy` answered `changed?` with false, - `changes` with `{}` and `name` with `"B"` — with nothing left to tell a local edit apart - from a value the server gave, in the one state where it can never be saved. -- A record Zammad served without an id is no longer told it "was saved". Zammad serves a - reduced object where the authenticated user may not see the whole record, so a plain read - can hand back a persisted record with no id; the message sent the caller to look at a - save that never happened instead of at what the client may read. -- `require 'zammad_api'` no longer depends on Faraday loading `net/http` for it. - `Timeout::Error` and `SocketError` are named in `Transport`'s class body and resolved - only because the default adapter pulled `timeout` and `socket` in transitively — so a - Faraday that stopped doing that, or a slimmer adapter, turned the require into a - `NameError` before a single request. -- `middleware:` that decodes the response body — `c.response :json` is the usual one — is - refused when the client is built, before anything is sent, with a `ConfigurationError` - naming it. Faraday's parsed Hash used to become a Ruby inspect string that `JSON.parse` - refused, which killed every record built from it with a `ParseError` naming Zammad for - what the caller's stack had done. This gem parses JSON itself and hands the undecoded - bytes to attachment downloads, so once a middleware has consumed the body there is - nothing faithful left to hand back. -- Two spellings of one query parameter raise instead of silently sending whichever Hash - order put last — at any depth, and in `search` at the call that wrote it as well as on - the wire. The same goes for two spellings of one response header in `ZammadAPI::Test`. Keys are normalised - in both places, so `search('x', 'ids' => [1], ids: [2])` and - `{state_id: 1, 'state_id' => 2}` each collapsed into one parameter and dropped the other - value without a word — including inside `condition`, the structured parameter the search - endpoints read. -- A stubbed response from `ZammadAPI::Test` carries `content-type` the way a real one does, - and is decoded by that header rather than by the Ruby type of the stub's body. Code that - branches on `response.headers['content-type']` passed against Zammad and failed against - the stand-in, or the reverse; and a stub declaring a non-JSON type still handed back a - decoded Hash, where Zammad gives the raw string and reading a record from it raises - `ParseError`. -- `record.fetch(:missing, default) { ... }` warns the way `Hash#fetch` warns, naming the - line that made the call. A bare `Kernel#warn` reports no source location, so the warning - identified neither the call site nor the library it came from. -- A raw request refuses an absolute URL with `ArgumentError`. Faraday lets one replace the - instance URL and still attaches the client's headers, so - `client.get('https://other.example/collect')` — a link taken from a response body, say — - sent the access token and the `on_behalf_of` scope to that host. The path is documented as - relative to the instance URL, and record ids were already held inside their segment; this - is the same escape one level up. The test kit refuses it too. -- A raw request refuses a path that cannot be read as a URL with `ArgumentError`. - `client.get('api/v1/tägs')` and `client.get(' api/v1/x')` raised `URI::InvalidURIError` - from inside the connection, which is neither a `ZammadAPI::Error` nor the `ArgumentError` - a path is documented to raise, after the debug log had already written a line for a - request that never left. A query string in the path that names one parameter as a value - and as a structure raised `TypeError` the same way. Both are refused before anything is - logged, with a message that does not quote the path. -- An instance `url` that carries credentials raises `ConfigurationError`. Faraday turns the - userinfo of a URL into a Basic `Authorization` header, and its authorization middleware - leaves a header that is already set alone, so with `url: 'https://old:pass@host/'` and - `http_token: 'new'` every request went out as the old account while `client.inspect` - reported `auth=http_token` — the token was never sent. Credentials belong in `user:` and - `password:`, or in one of the token options. -- `Client.from_env(**overrides)` and `Client#with` replace the credentials they override. A - credential is one of several options read in a fixed order, so a plain merge left the old - one in charge: with `ZAMMAD_TOKEN` set, `from_env(user: 'u', password: 'p')` still sent - the environment's token, and `client.with(oauth2_token: 'x')` on a token client went on - acting as the account the token belonged to, with no error. Naming one way to authenticate - now drops the others; overriding `password:` alone still keeps the `user` it pairs with. - `Config#with` does the same. -- `pp config` redacts credentials, and a transport no longer prints its connection. `Config` - is a `Data`, and `pp` — what IRB and the Rails console print a value with — has a printer - of its own for those that renders the members without going through `inspect`, so - `client.config` typed at a prompt showed the token, the password and a proxy's credentials - in full. `Transport` had no `inspect` at all, so Ruby's default printed the Faraday - connection it holds, proxy password and access token included, and every record holds its - transport. -- A proxy or instance URL whose password carries an unencoded `/`, `?` or `#` is redacted. - Each of those ends the authority early as far as URL syntax goes, so `proxy: - 'http://user:p#ss@proxy:3128'` left `user:p` as the authority, the redaction found no `@` - in it, and the password was printed by `Config#inspect` and quoted in the - `ConfigurationError` raised when the connection could not be built. Where a colon makes a - password possible, everything up to the last `@` of the whole value is blanked now. The - price is a URL with a port and an `@` further on, such as `https://host:8443/a@b`, which - renders with its host blanked: a colon cannot tell a port from a password, and that is the - mistake that leaks nothing. -- A wait before a retry is bounded by `timeout`, with only the jitter on top of it, at most - half a `retry_interval`. The retry middleware sleeps for - whatever a `Retry-After` header says and has no ceiling of its own by default, so a - maintenance page answering 503 or a rate limiter answering 429 with `Retry-After: 3600` - held the calling thread for an hour per retry — two by default — before raising the error, - whatever `timeout` and `retry_interval` said. A `Retry-After` within `timeout` is still - honoured; a longer one is not waited out, and the request fails at once with the error for - its status, `RateLimitError#retry_after` still carrying the figure. -- The test kit serves a sequence of list stubs one per read. Every full read of a collection - asks for the page after its last one, and that request took the next stub in the queue and - served it as an empty page: three stubs for `GET api/v1/groups` answered three reads with - the first, the third and the third, and the second was never seen. A request for a later - page is now answered by the stub its read began with and does not move the sequence on. -- An exceeded `open_timeout` raises `TimeoutError`. Net::HTTP reports it as - `Net::OpenTimeout`, which Faraday's default adapter wraps into `Faraday::ConnectionFailed` - with every other failure to connect, so it surfaced as `ConnectionError: … is unreachable - (execution expired)` and skipped the `rescue ZammadAPI::TimeoutError` documented to catch - it. -- A `dup` or `clone` of a record has a change set of its own. The attributes are frozen and - replaced on write, but the change set is written in place and the copy shared it: after - `copy = record.dup; copy.name = 'X'` the original reported `changed?` and a change to - `name` while still reading `name` as it was, and its next `save` sent the copy's value. - The copy also gets association readers of its own, rather than ones that read through the - original. -- An attribute write on a destroyed record raises. `update` and `update!` already refused - one, so as not to leave a change set that can never be sent, but the writers they are - built on did not ask: `group.destroy; group.name = 'Z'` left `changed?` true and `name` - reading `"Z"` on a record `destroy` promises to leave as it last was in Zammad, and the - `save` after it was the first thing to object. A named writer, `[]=` and - `assign_attributes` all refuse now, and stage nothing. -- A request body that cannot be encoded as JSON raises `ZammadAPI::Error`. Faraday's JSON - middleware raised `JSON::GeneratorError` from inside the stack and nothing mapped it, so - `client.post(path, body: {data: File.binread('a.png')})` with the bytes not - Base64-encoded, or any body holding `Float::NAN`, went past the `rescue ZammadAPI::Error` - callers are told to write — and so did a record `save` carrying such a value. The body is - encoded before the request is logged now, so a refused one leaves no line claiming a - request that was never made, and the test kit refuses it the same way. -- A walk no longer ends when the block empties the batch it was handed. The size of a page - was read after the block returned, so an `in_batches` consumer that worked its batch off - with `shift` looked like an empty page and the walk stopped after the first one, and a - batch the block shortened looked like the last. The records are counted before they are - handed over. -- A search is walked to its end where one of its pages comes back short. A walk stopped at - the first page shorter than the one before it, which is right for an index and not for a - search: Zammad has the search name the ids for a page and then loads the records by id, - so one deleted in between, or one Elasticsearch still lists after it was removed, is left - out and nothing fills its place. `search(...).each` then ended on that page with the - rest of the hits unread, and `find_by` answered `nil` for a record on a later one. Only - an empty page ends a search walk now, at the cost of one more request where the last page - of hits is part-filled. -- A search is read on past a page with nothing on it where Zammad says there are hits - behind it. A page comes back empty for the reason it comes back short, every id on it - having lost its record, and on the page of one that `first` and `empty?` ask for a single - stale hit does it: `search(term).first` answered `nil` and `empty?` answered `true` with - live hits behind a record deleted a moment before, and `each` ended on such a page. A - search that is walked sends `with_total_count` and ends on an empty page only once the - pages read cover the total reported beside it. The total never ends a walk on a page that - held records, because Elasticsearch stops counting at ten thousand hits. An empty page - still ends the walk where there is no total to go by: on a Zammad before 6.5.1, which - answers with the records alone, and past the ten thousandth hit on Elasticsearch. It can - also end the walk short of the total on an instance that serves a search in smaller pages - than were asked for, because the pages read are reckoned at the size asked for. The test - kit pages a search stubbed as `{records: [...], total_count: n}` the way it pages an - Array. -- `first`, `take` and `empty?` read on past stale search hits in pages that grow. They size - their request to the records they want, and held to that size, reading on past an empty - page cost a request for every stale hit in a row: 5000 requests for `empty?` behind 5000 - of them, on an instance whose Elasticsearch index has drifted from its database. Past an - empty page they now ask for the largest page that starts where the last one ended, - doubling up to the 200 a search serves, and the same read takes 34. No hit is passed over - or read twice. A batch size given to `in_batches` or `find_each` is left as it is. -- A `StopIteration` raised by the block a collection yields to is raised, not taken for the - end of the walk. The walk ran inside `Kernel#loop`, which rescues it, so a block calling - `next` on an enumerator of its own that ran out, as in `map { [it.id, labels.next] }`, - dropped the records and pages after that one and `map` answered with what it had. The - same block over an Array raises. -- A repeated page is recognised by the records on it rather than by their payload. A job - that writes to the records it is handed changes what they serialize as, so an endpoint - that ignores `page` served the same records with a different payload each time: the - guard never fired, and the job went round the same records, writing to them again, for - as long as it ran. Two consecutive pages holding the same ids, in any order, raise - `PaginationError` before the second is handed over. Records without an id are still - compared by payload. -- A search sends the term and the filters it was given. The collection `search` returns is - lazy and held the caller's own String, Array and Hash until it was enumerated, so - `search('printer', ids: ids)` followed by `ids << 7` searched for something the call was - never given, after the filters had been checked. `search` keeps a copy of its own, which - `page` and `order` carry on. -- A `related` kept in a variable follows its record. A save, a reload and a write to a - foreign key dropped the record's association proxy and built another on the next call, so - only a caller who asked the record again saw the change: after `related = ticket.related` - and `ticket.customer_id = 9`, `related.customer` went on answering with the user it had - resolved before, and the same after a reload. A record keeps one proxy now and empties - it. A kept one also refuses a destroyed record, as `related` does, where it used to - answer from its memo and request the articles of a ticket that is gone. A lookup that is - still on the wire when the foreign key is written, by a logger or a middleware that - reaches the record or by another thread, no longer leaves the record it fetched behind as - the answer for the new key. The proxy is emptied as well where a save answered with a 2xx - nothing could read puts the record back on what it sent: a key written while that request - was out, and an association read from it, left the record on the key it sent with the - other key's record still the answer. -- Records of two Zammad instances are no longer equal for sharing a class and an id. An id - is only unique within one installation, so a script reading two of them, such as a - migration or a sync, held ticket 1 of each as one record: `uniq` dropped one of the two, - and a Hash keyed by record answered for one instance with the other's value. `==`, - `eql?` and `hash` take in the `url` the record's client was configured with. Two clients - for one URL, and a client and its `on_behalf_of` scope, still hold the same record. -- An update Zammad acknowledged is not sent again. The staged changes were dropped only - once the response had decoded, so an update answered with a 2xx nothing could read, such - as a body a proxy cut off, raised `ParseError` with the whole change set still staged, and - the next `save` sent all of it again along with whatever had been staged since. For a - ticket's `article` that is a second article and a second e-mail. A 2xx now settles what - was sent before the body is read: the record holds the values it sent with nothing - staged, and `reload` brings in the rest. A save Zammad rejected keeps its changes staged, - as before. What is settled is what the request carried: a write that reaches the record - while the request is out, from a logger or a middleware that touches it or from another - thread, is dropped, as it is by a response that can be read, rather than settled as if - it had been sent. The body of the request is built from the same attributes it is then - settled on, read once, so a write from another thread cannot land between the two and be - sent without being settled. A key Zammad never served the record with is not kept either, which a - ticket's `article` is: kept, the same article assigned again compared equal to the first - and `save` reported `true` without sending the second reply. -- `ticket.add_article` adds to that ticket whatever its attributes say. A `ticket_id:` - among them was replaced by the ticket's own, but only under the Symbol spelling: given - `'ticket_id'` as well, the String key came later in the Hash and won when the article - symbolized its keys, so the article was posted to the ticket the caller's Hash named. - Both spellings are taken out before the ticket's id goes in. -- `on_behalf_of` keeps the user it was given. The scoped client held the caller's own - String, so a login buffer reused after `client.on_behalf_of(login)` changed who every - later request from that client was performed for. The scope is copied and frozen, in the - test kit's transport as well. -- A proxy password no longer reaches an exception report through `cause`. The - `ConfigurationError` for a connection that cannot be built had its message redacted, but - Ruby attached the error it replaced as the cause, and a report prints the whole chain: - `full_message`, a log formatter and an error tracker all showed `URI::InvalidURIError` - quoting the proxy URL in full. The cause is dropped where its report would print a - configured value that redaction changes, and kept everywhere else, so a `middleware:` - callable that raises still shows the backtrace into the caller's code. An error that - cannot render its report at all, such as one whose `detailed_message` takes no - `highlight:` keyword, is dropped as a cause too, rather than leaving in place of the - `ConfigurationError`. -- `middleware:` that adds `c.response :raise_error` is refused with a `ConfigurationError` - when the client is built, as `c.response :json` already is. It sits below the retry - middleware and raises for a 4xx or 5xx before this gem sees the response, so a `GET` - answered 503 was not retried and left as `Faraday::ServerError`, a 404 left as - `Faraday::ResourceNotFound`, which `exists?` does not rescue, and a 422 as an error - `save` does not turn into `false`. None of them is a `ZammadAPI::Error`. A subclass of - either middleware is refused as well: the stack was asked for the two by name, and - `class QuietRaiseError < Faraday::Response::RaiseError` has another. -- A `Cookie` header is redacted in the debug log, and so is `Proxy-Authorization`. A raw - request takes headers of its own and the request line prints them, and neither name - matched the words that mark a credential, so `client.get(path, headers: {'Cookie' => - ...})` wrote the session out in full. -- A record passed where its id belongs is refused with an `ArgumentError`. Whatever was - given went into the request path through `to_s`, which answers for every object, so - `client.tickets.exists?(ticket)` asked for a path spelling out the record's `inspect`, was - told 404 about it and answered `false` for a ticket that exists, and `destroy(ticket)` - raised `NotFoundError` for one that was right there. An id is an `Integer`, a `String` or - a `Symbol`; the message names the class of anything else and does not quote it. -- One attribute given under two spellings raises `ArgumentError` instead of keeping - whichever Hash order put last. A record symbolizes the keys of the attributes it is given, - so `client.groups.new('name' => 'Support', name: 'Sales')` built a record holding - `name: 'Sales'` alone, and an attribute Hash put together from form parameters and - defaults lost a value without a word. `create`, `assign_attributes`, `update` and a - writer handed a Hash refuse the pair the same way, at any depth, and nothing is staged - when they do. It is the refusal a query parameter and a header already had. -- A record's `inspect` blanks the value of an attribute that names a credential, by the - rule the debug log redacts a request with. The attributes were printed as they stood, so - `client.users.new(login: 'x', password: 'hunter2')` showed the password in IRB and under - `pp`, in an RSpec failure and in any exception report that interpolates the record. - `attributes`, `to_h` and `to_json` still hand the value over. -- The test kit sends a read again that the client would retry. It raised for the first - stubbed 429 or 5xx, where the real transport asks again: stubbed 503 and then 200, - `client.groups.find(1)` returns the group against Zammad and raised `ServerError` against - the stand-in, and a single stubbed 503 was recorded as one request where the wire carries - three. A `GET` is now attempted up to `retries` more times, each attempt recorded and - answered by the next stub, with no wait in between. Whether a response is retried is the - transport's own rule, so a write is not repeated and a `Retry-After` longer than - `timeout` ends the attempts. `ZammadAPI::Test.new(retries: 0)` raises for the first - failure, as before. -- A resource can declare that its index endpoint does not page, with `paginated false`, - and is then read in one request. A walk asks for the page after a full one, and an - endpoint that serves every record in one response and reads no `page` — - `api/v1/object_manager_attributes` is one — answers that with the same list. The guard - against an endpoint that ignores `page` raised `PaginationError` for it, so a resource - declared for such an endpoint could not be read at all: `to_a` raised with every record - in hand, and a `find_by` that missed raised instead of answering `nil`, which broke - `find_by(...) || create(...)`. Nothing in the responses tells such an endpoint from one - that serves only its first page, so it is declared rather than inferred, and the error - for an index that repeats its first page now says what to declare. `page` refuses a - resource declared this way. Whether its index sorts is still what `sortable` says. -- A proxy or instance URL with no host where the host belongs is redacted. A slash too - many, or the slashes without the scheme, end the authority before it has begun, so - `proxy: '//user:secret@proxy:8080'` was printed by `Config#inspect` with its password, and - `url: 'https:///admin:secret@host/'` was quoted in full by the `ConfigurationError` that - refuses a url without a host. With no host there to blank by mistake, everything up to - the last `@` is blanked, and that error quotes the url redacted. -- The debug log prints a request body as it is sent, and no longer by `inspect`. It - redacted by key through the Hashes and lists of the body it was handed and printed - anything else in it as it stood, so an object that writes its own JSON — a value object - with a `to_json`, as the body or under a key of it — was logged with the password the - request carries as a key. An object that does not is sent as its `to_s`, and the log - showed what `inspect` lists and the request never carried. The payload is now read back - from the JSON it was encoded to and redacted by key, however it was handed over, so the - line shows String keys: `{"login" => "jane", "password" => "[REDACTED]"}`. A body that is - one value is not logged, only its size. -- A query string written into the path of a raw request is redacted where its parameters - are separated by `;`. Zammad up to 7.0 runs on Rack 2, which ends a parameter at a `;` as - it does at an `&`, so `client.get('api/v1/x?page=2;token=...')` carries a token there. The - path was split at `&` alone, which made that the tail of a value named `page`, and it was - printed in the log and in the message of an error the request raised. A credential that - opens such a stretch is still blanked to the next `&`, since Rack 3, and Zammad since 7.1, - reads a `;` as part of the value. -- `assign_attributes`, `update` and `update!` raise `ArgumentError` for something that is - not a Hash, and take a key that cannot become a Symbol. `ticket.update(nil)` — which is - `update(params[:ticket])` with the key missing — raised `NoMethodError: undefined method - 'each_with_object' for nil` from inside the gem, and `assign_attributes(1 => 'x')` raised - one about `to_sym` for a Hash the constructor takes. The message names the class that was - given and does not quote the value. Nil is refused rather than read as nothing to assign: - an `update` that staged nothing would answer `true`. -- Strong parameters are read as the Hash they convert to. `ActionController::Parameters` is - not a Hash, so `client.users.new(params.require(:user).permit(:login, :password))` built - a record holding the caller's own object: `inspect` and the debug log printed the - password, `save` sent the parameters as one JSON string holding their `to_s`, where 1.x - sent `params.to_json`, and a later change to the parameters changed the record. `update` - and `assign_attributes` raised `NoMethodError` for them, and a `condition:` given to - `search` that way was written as its `to_s`, which Zammad drops. Whatever answers - `to_hash` is now converted wherever a structure is handed over: as the attributes of - `new`, `create`, `update`, `assign_attributes` and `add_article`, as the value of an - attribute at any depth, in a search filter, and in the `query:` and `body:` of a raw - request. Parameters that were not permitted raise their own - `ActionController::UnfilteredParameters`. Anything else given as a set of attributes — - a String, an Array of pairs, a Struct — raises `ArgumentError` naming its class, where it - raised `NoMethodError` or was stored as it was; `new(nil)` is still a record with no - attributes. A `query:` that is not a Hash raises `ArgumentError` the same way. -- The debug log prints the query of a request as it is sent, like its headers and its - body, so the line shows String keys and values: `query={"page" => "1"}`. -- An attribute reader called with arguments raises `ArgumentError`, as a reader written out - does. The arguments were never looked at, so `ticket.state('closed')` answered `"open"` - and changed nothing. On a ticket with an article staged, the call that added an article - in 1.x, `ticket.article(body: '…')`, answered with the staged article, sent nothing and - raised nothing; it now raises and names `add_article`. The message says where a value - for the attribute is written, on a record that takes writes. -- `any?` and `none?` without a block ask for one record, as `empty?` does. They were - `Enumerable`'s, which starts a walk at the page size for walking and stops at the first - record: `client.tickets.all.any?` fetched a hundred expanded tickets, and - `client.tickets.search('x').any?` two hundred hits, to answer what `empty?` answers with a - page of one. A resource proxy forwards both. With a block or a pattern they walk, as - before. -- An adapter set inside the `middleware:` callable is kept. The adapter was set after the - callable ran, which replaces the one that is there, so - `middleware: ->(f) { f.adapter :test, stubs }` left the connection on Net::HTTP without a - word: a test that believed itself stubbed sent real requests with the real token. The - callable is also the only place an adapter can be given arguments, such as - `f.adapter :net_http_persistent, pool_size: 5`. Naming an adapter there and in `adapter:` - as well raises `ConfigurationError`. -- A line break in a header value is refused beside bytes that are invalid in the value's - encoding too. The check stripped the value first, which raises for such text, and read - the error as no line break: `http_token: "abc\xFF\ndef"` built a client, a raw request - took the same in `headers:`, and an adapter that checks no header itself sent what - followed the break as a header of its own. The bytes are read now. `http_token`, - `oauth2_token` or `user_agent` given as UTF-16 text that cannot be converted raises - `ConfigurationError`; it was passed as holding no line break. -- The debug log and a record's `inspect` redact `bind_pw`, `passphrase`, `otp` and `salt`, - and a `key` spelled in camelCase such as `privateKey`. Zammad filters all of them from - its own log, and none matched here: creating an LDAP source logged the bind password - inside its `preferences`, importing a PGP key logged its passphrase beside the redacted - key, and a record of an LDAP source printed the password. `otp` and `salt` are matched - as words, as `key` is, with `totp` and `hotp` counted in. -- A client derived with `Client#with` from the test kit's client behaves as it is - configured. The stand-in's transport kept its own configuration, so - `zammad.client.with(retries: 0)` was asked three times for a stubbed 503 where a derived - client is asked once on the wire, `with(timeout:)` did not change which `Retry-After` - ends the attempts, and a record found through `with(url:)` compared equal to the same id - found through the client it was derived from. Only `client.config` showed the option. -- A raw request refuses any path that opens with a scheme, not only one followed by `://`. - `client.get('http:/collect')` passed as a relative path, and Faraday 2.9.0 and 2.9.1, - which the gemspec allows, resolve it as URI does: to an absolute URL with no host, where - the request then goes over plain HTTP with the client's `Authorization` header and any - `on_behalf_of` scope. Faraday from 2.9.2 on keeps such a path on the instance; the - refusal no longer depends on which is installed. -- A query value that is not text, a number, a boolean, a list or a structure raises - `ArgumentError`, at any depth. It was sent as its `to_s`: - `client.users.search('smith', ids: Set[1, 2])` asked for `ids=Set[1, 2]`, which names - neither user, `ids: (1..3)` for `ids=1..3`, and a record under a key went as it prints, - and Zammad narrowed by that text. `client.on_behalf_of(user)`, with the record where its - id or login belongs, built a client whose `From` header carried the record the same way, - and raises too. Both messages name the class and do not quote the value. -- The signatures no longer declare `ZammadAPI::Response::TOTAL_COUNT_HEADER`, a constant - the library does not have. Steep accepted code that named it, which then raised - `NameError` when it ran. -- A request body value JSON has no type for is no longer sent as its `to_s`. - `client.users.create(login: 'x', role_ids: Set[1, 2])` sent `"role_ids":"Set[1, 2]"`, a - String where the list belongs, and a Struct went as `#`. Where ActiveSupport - is loaded such an object is sent as its `as_json`, which is what 1.x sent there: the Set - as a list, `2.days` as `172800` and not as `"172800"`, a model as its attributes. - Elsewhere it raises `ZammadAPI::Error`, naming the key and the class and not the value. An - object with a `to_json` of its own still writes itself, and a `Time` or a `Date` is still - sent as its text, which Zammad reads. -- `to_json` and `as_json` of a configuration, a client and a transport hold no credential. - With ActiveSupport loaded, which serializes an object as what it holds, `config.to_json` - wrote the token, the password and the proxy credentials in full, and `client.to_json` - did the same and then requested every page of every resource, a proxy being Enumerable. - So did a log line or an error report that serialized something holding either. A - configuration is now written with what `inspect` blanks blanked, and a client as its URL, - the way it authenticates and any `on_behalf_of` scope. -- A raw request refuses a header name that is not one. Only the value was checked, and the - `Net::HTTP` that ships with Ruby 3.4 and 4.0 writes a name as it is given: - `headers: {"X-A: 1\r\nFrom: admin@example.com\r\nX-B" => 'v'}` sent a `From` header of - its own, the one refused by name, and an `Authorization` went the same way. `'From '` - passed that refusal as well, and an empty name was sent as `: v`. A name that is empty or - holds anything but letters, digits and the signs RFC 9110 allows raises `ArgumentError` - before the request is sent or logged, and the test kit refuses it too. net-http from - 0.10.0 on refuses a line break or a colon itself, with an error that quotes the name. -- `ZammadAPI::Test` answers with a stub declared after an earlier one for the same endpoint - has answered. The earlier one was served once more: stubbed open, read, stubbed closed - and read again, a ticket was open twice and closed only at the third read. A lone stub - stays in place to go on answering, and was taken for the first of the sequence the second - one began. -- A response the connection was closed under raises `ZammadAPI::ConnectionError` where its - body is shorter than its `Content-Length`. `Net::HTTP` hands over what had arrived - without a word, so `attachment.download` returned the first bytes of a file as the file, - and a raw request for anything that is not JSON did the same. Checked for a 2xx response - that names one `Content-Length` and neither a `Content-Encoding` nor a - `Transfer-Encoding`; a chunked body cut short raised already. A `GET` is sent again for - it: see below. -- A query value that is a number and neither an `Integer` nor a `Float` raises - `ArgumentError`, as any other value a query string has no spelling for does. Every - `Numeric` was taken as it prints: `client.users.search('smith', ids: [BigDecimal('5')])`, - with the id read from a decimal column, asked for `ids[]=0.5e1`, and user 5 was not among - the hits. A `Rational` went as `1/2` and a `Complex` as `1+2i`. A `Float` that is `NaN` or - infinite raises as well, where it was sent as that word. -- `deep_dup` of anything that holds a record or an attachment works with ActiveSupport - loaded. A private helper of that name answered in place of the public one ActiveSupport - gives every object, so `{ticket: ticket}.deep_dup` raised - `NoMethodError: undefined attribute deep_dup`, and so did a list of records. - `config.presence` raised the same way, for a private helper called `presence`. -- A logger whose `debug` requires an argument raises `ConfigurationError` when the client - is built. It was accepted, as anything that answers `debug` was, and each line is handed - over as a block: `def debug(message)` raised a bare `ArgumentError` at the first request - and at every one after it. -- `attachment.download` asks for the file with `Accept-Encoding: identity`, so that one the - connection was closed under raises `ZammadAPI::ConnectionError` behind a proxy that - compresses as well. `Net::HTTP` asks for gzip by itself and inflates what arrives, without - a word for a stream that stops halfway, and the length of a body under a - `Content-Encoding` is not checked: a text attachment of 180 kB came back as its first - 16 kB. A server that compresses the file all the same is asked a second time without the - header, and what it sends is decoded and not checked, as before. -- `Client.new` without a `url:` raises `ZammadAPI::ConfigurationError`, as it does for one - that is `nil` or empty and as 1.x did. It raised `ArgumentError: missing keyword: :url`, - past a `rescue ZammadAPI::ConfigurationError` written for an incomplete configuration. -- `RateLimitError#retry_after` reads the header in base ten. A zero in front made the figure - octal: `Retry-After: 010` was 8, and `08` was `nil`, so the `e.retry_after || 60` the - README shows waited a minute. `0x10`, which was 16, is `nil` now. -- The gem names `logger` among its dependencies. It requires it, and from Ruby 4.0 on - `logger` is a bundled gem, which Bundler makes loadable only where the bundle names it. - Faraday does from 2.10.0 on, so `require 'zammad_api'` worked by way of it, and raised - `LoadError` in a bundle resolved to Faraday 2.9, which the gem allows. -- A response whose `Content-Length` a middleware left as an Integer is read. `faraday-gzip` - writes the length of what it inflated that way, and the check for a body cut short asked a - regexp of it: every successful request behind `c.request :gzip` raised a bare `TypeError`, - past a `rescue ZammadAPI::Error`. `Response#headers` has every value as a String now, as - it is documented to. -- A `save` or `destroy` that Zammad answered 2xx leaves the record saved or destroyed where - the answer was cut short of its `Content-Length`, as it does where the answer does not - parse. The error was raised before the record heard of the response: a create answered - 201 left the record looking new, so a second `save` POSTed a second record, an update - kept its changes staged, so the next `save` sent a ticket's `article` and its e-mail - again, and a second `destroy` came back as a 404. The error is - `ZammadAPI::IncompleteResponseError` now, a `ConnectionError` that carries the `response` - as far as it arrived, so a raw `client.post` can tell from the status that it was applied. -- A token, a user agent, an `on_behalf_of` scope or a raw request header that ends in a line - break is handed to the adapter without it. One read from a file usually ends in one, and - it is taken because `Net::HTTP` strips the value. That was left to `Net::HTTP`: an - adapter set with `adapter:` was handed `"Token abc\n"`, and one that writes a header as it - stands ends the line, or the headers, where the value does. `ZammadAPI::Test` recorded the - scope with the break on it too. -- `as_json` on a record reads `only:` and `except:`. It dropped its options, so - `user.as_json(except: [:password])` answered with the password, as did a record inside a - Hash or a collection that ActiveSupport serialized with the option, while - `user.to_json(except: [:password])` left it out. `to_json` is written from `as_json` now, - and both take a name as a Symbol or a String: `except: ['password']` filtered nothing in - either. -- A fragment written into the path of a raw request is blanked where the path is printed: - in the log, in the message of a timeout and in the `operation` of an error. - `client.get('api/v1/x#token=...')` printed the token in all three, since only what - follows a `?` was read for credentials, and a fragment after a query was printed as the - tail of its last value. It is no part of the request, which is sent without it as before. -- The error for a request body that cannot be encoded quotes nothing from the body. Its - message repeated the JSON generator's and kept the generator's error as its cause, and - the generator quotes what it could not write: `client.users.create(login: 'a', password: - "hunter2\xFF")` raised an error whose backtrace printed `Invalid object: "hunter2\xFF"`, - and under json 3 a body naming one key twice was quoted whole in the message. The error - has no cause now and says only what this gem refused itself, by key and class, a Float - that is NaN or infinite included. A body that names one key twice, as `login:` and as - `'login'`, raises `ArgumentError` with both spellings, as a query does; json 2 sent both - and left the choice to Zammad. -- `to_yaml` of a configuration, a client, a collection and a record holds no credential. - Psych asks neither `inspect` nor `as_json`: it writes the members of a Data and the - instance variables of an object, and every record holds its transport, whose connection - holds the token and the proxy password. So `record.to_yaml`, which is what Rails' `debug` - view helper and a Delayed::Job handler write, printed both. A configuration is written as - the mapping its JSON holds, and a transport as its URL and the way it authenticates, the - test kit's included. `Marshal.dump` still holds the credentials where it writes anything: - it is what a copy is rebuilt from, and it raises `TypeError` for a client or a record - once the client has made a request. -- A walk sorted by an attribute that records share hands each record over once. `order` - sent the columns it was given, and Zammad sorts by those and by nothing after them, an - index and a search alike, so PostgreSQL was free to hand rows that tie back in another - order for each page. Against a Zammad that searches through SQL, - `client.tickets.search('*').order(:state_id)` over 214 tickets came back as 214 records - and 151 tickets at every page size tried, and no page repeated another, so nothing - raised. Every sorted request names `id` as its last column now, unless the order names it - already: `order(:state_id)` is sent as `sort_by=state_id,id`, and a stub of the test kit - that is scoped to `sort_by` has to spell it that way. A search that is given no order is - sent none, as before. -- A url with nothing where the host belongs, such as `http://:3000/`, raises - `ZammadAPI::ConfigurationError`. It is what `"http://#{ENV['ZAMMAD_HOST']}:3000/"` comes to - with the variable unset, and it was accepted, as 1.x accepted it: the check asked only - that something follows the scheme. `Net::HTTP` connects to localhost for an empty host, - so the client sent every request, and the token with it, to whatever listened on that - port of the machine it ran on. -- A `timeout`, `open_timeout` or `retry_interval` the HTTP stack cannot wait for raises - `ZammadAPI::ConfigurationError`. Any positive number was accepted, so `timeout: - Float::INFINITY`, the natural way to ask for the 1.x behaviour of no timeout, built a - client whose every request raised a bare `RangeError` from inside `Net::HTTP`, as did a - figure past what a C long holds, and an infinite `retry_interval` raised it from the wait - before the first retry. The three take at most 100000000 seconds, a little over three - years, which is the longest wait every platform takes: macOS refused a longer one, and - that came back as a `ConnectionError` calling the instance unreachable. -- A Hash with no value in it raises `ArgumentError` wherever it stands in the `query:` of a - raw request. A query string writes nothing for one, so - `client.get(path, query: {filter: {}, a: 1})` asked for `?a=1`, and Zammad answered as if - the parameter had been left out. A `nil` and an empty Hash inside a list were refused for - that reason already, and a `search` refused an empty `condition`; a condition holding an - empty Hash beside one that is written lost it in the same way, and is refused now too. -- An `http_token` or `oauth2_token` of nothing but whitespace is taken for unset, as an - empty one is, and one that is no String raises `ZammadAPI::ConfigurationError`. Reading an - empty token file gives `"\n"`, and with it the client was built, reported - `auth=http_token` and sent `Authorization: Token` with nothing after it. `http_token: - 12345`, `:abc` and `['a']` were sent as they print, and a Symbol was never asked for the - line break a String is refused for. -- A walk no longer raises `ZammadAPI::PaginationError` for a list that moved by exactly a - page between two requests. A page holding the records of the one before it was taken as - proof that the endpoint ignores `page`, and it is also what a list served newest first - answers with after that many records were created or updated at its front: - `client.tickets.search('state.name:open').in_batches(of: 2)` raised where two other open - tickets were updated between its first and second request, and on an index the message - advised `paginated false`, which would have read a list cut short. The walk asks for the - page before once more now. Where that holds the same records again it raises as before, - one request later. Where it holds others, the page that repeated is passed over, since - the block has had its records, and the walk goes on from the page after it. -- A save answered 2xx by something that is not Zammad is no longer recorded as applied. - Every 2xx settled the record before its body was read, and the 2xx that cannot be read is - most often the page of something in front of Zammad that never passed the request on: a - single sign-on login page, a captive portal, the default page of a load balancer. After - `ticket.update(state: 'closed')` raised `ParseError` for a `200 text/html`, the ticket - read as closed with nothing staged, and the retried `save` returned `true` without a - request while Zammad still had it open. A create was left persisted with no id, for a - record Zammad never made. Zammad answers a create and an update with JSON, so only a 2xx - that says it is JSON settles the record now, whether or not its body can then be read. - Any other leaves the changes staged and a new record new, and the `save` can be - repeated. That holds for a 2xx cut short of its Content-Length as well, and - `Response#json_content_type?` is what is asked. A `destroy` is asked another question, - since Zammad answers a ticket's DELETE with no body at all: see below. -- An `Authorization` header in `Faraday.default_connection_options` no longer replaces the - client's authentication. Every connection `Faraday.new` builds starts from those options, - and the authorization middleware leaves a header it finds, so a process that set - `Authorization: Bearer ...` there for another API sent that token to Zammad and the - configured one never, from a client whose `inspect` said `auth=http_token`. A `From` set - there was sent with every request, which Zammad reads as the user to act for, and - parameters set there went into every query. The connection is built without those three, - as 1.x never was. Everything else in the options still applies, and what the - `middleware:` callable sets on the connection stands. -- A `ConfigurationError` raised while building the connection no longer quotes the - credentials of a proxy the environment names. With no `proxy:` given, Faraday takes the - one in `http_proxy` or `https_proxy`, and the redaction of that error knew the configured - values only: `https_proxy='http://user:hunter 2@proxy.example:3128'` came back as - `URI::InvalidURIError: bad URI (is not URI?)` with the whole URL in the message and again - in the cause, as 1.x let it out unwrapped. Every variable of the environment whose name - ends in `_proxy` is scrubbed as the configured proxy is, and the cause is dropped where - it quotes one. -- `exists?` is `false` where Zammad answers with an object that carries no id. Any 2xx - counted as the record, and Zammad answers `organizations/5` with `200` and `{}` for a - customer who belongs to no organization, whether or not there is an organization 5, so - `client.organizations.exists?(5)` was `true` for it. `find` hands over what was served, - as before: a record with no id. -- A `belongs_to` declared after a record of the class was written to is followed. The - foreign keys of a resource are listed at the first write to an attribute and the list was - kept, so an association added later, on a class reopened for it, was not in it: a write - to its foreign key left what the association had resolved in place, and `related.role` - answered role 5 after `role_id = 6`. Declaring one drops the list, on the class and on - every class that inherits from it. -- `each_slice` and `each_cons` read the records once. Ruby asks the receiver for its `size` - before either starts, and the `size` of a collection is its `count`: a walk of every page - on an index, a request for the total on a search, the page once more on a collection - limited to one. So `client.tickets.each_slice(100)` read every ticket twice, and - `page(1, per_page: 50).each_slice(10)`, the call the errors of `page` point to, fetched - its page twice. The groups were also cut to the count the first of the two reads came - back with, whatever the second then held. Both run over the Enumerator of `each` now, on - a collection and on `client.tickets` alike, and `lazy` is made from it as well, since a - lazy enumerator hands the same question on to its source. An Enumerator that Ruby makes - from the collection itself, as `each_with_index` without a block is, still counts when it - is sliced: slice first, with `each_slice(10).with_index`. -- A write to the Hash `attributes` or `changes` hands out no longer raises an error that - quotes a staged password. Both are frozen, and Ruby prints a frozen object in the error - for a write to it: `user.attributes[:vip] = true`, which is how 1.x staged a change, - raised `FrozenError: can't modify frozen Hash: {login: "jane", password: "hunter2"}`, and - the message of an error is what a log and an error tracker keep. `inspect` of the record - blanked the same attributes, and the Hash it handed out printed itself. Both are a - `ZammadAPI::Attributes` now, as is every Hash inside them: a Hash that prints with the - value under each key naming a credential blanked, through `inspect`, `to_s` and `pp`. It - reads, compares and serializes as the Hash it was, to JSON and to YAML alike, and `to_h` - is a plain Hash. A strict JSON encoder is the one thing that goes by the class: see - below. A String cannot be told how to print, so a write into the password itself, - `user.attributes[:password] << 'x'`, still quotes it. -- `destroy` no longer reports a record destroyed where something that is not Zammad answered - the request. Every 2xx settled it, so a single sign-on gateway that answered the DELETE - with its login page and status 200 made `group.destroy` return `true` and left the record - `destroyed?`, refusing every call after it, with the group still in Zammad. - `client.groups.destroy(6)` returned `true` for the same page, as 1.x did. Zammad answers a - DELETE with no body, for a ticket, and with an empty JSON object for everything else, so - a 2xx whose body does not say it is JSON raises `ParseError` now, from both. The record - is left as it was, with what was staged, and the `destroy` can be repeated. A 2xx cut - short of its Content-Length leaves the record destroyed only where it said it was JSON. -- In `ZammadAPI::Test`, `count`, `size` and `length` on a search spend one stub of a - sequence, as reading its records does. `count` asks for the total alone first and walks - the pages where it is answered with records, and the stand-in took the two for two reads: - over three stubs holding one, two and three records, `search('x').count` answered 2, 3 - and 3 where `search('x').to_a.size` answered 1, 2 and 3. A request carrying - `only_total_count` is answered by the stub whose turn it is and leaves the sequence where - it was, unless that stub holds a total, fails, or was scoped to the request. -- `find_by(id: ...)` finds the record with that id. An id was looked for as any other - value is, which is the one way it cannot be found. As the String a request parameter is, - `client.tickets.find_by(id: params[:id])` searched for the text and asked each hit - whether its id was that String, so it answered `nil` for a ticket that was among the - hits. As an Integer it gave no String to search on, and the index was walked a page at a - time until the record came by: `find_by(id: 123456)` read every ticket before it. The - record is read by its id now, in the one request `find` makes, with `nil` where that - answers 404, and any other value given beside the id is matched against it. An id that is - neither an Integer nor a String of digits is the id of no record: `nil`, without a - request. -- A raw request refuses a path with a `..` segment. A path is joined to the instance URL the - way a link is resolved, so for a Zammad served from a sub-path such a segment left it: - with `url: 'https://host/zammad/'`, `client.get('../billing/export')` was sent to - `https://host/billing/export`, another application on that host, with the client's - `Authorization` header and its `on_behalf_of` scope. An absolute URL was refused already - so that the credentials stay with the instance they were configured for, and this was - the way round it. It raises `ArgumentError` now, with the dots written as they are or as - `%2e`, for every verb, and in `ZammadAPI::Test` as on the wire. A `..` in a query string - is left alone, and so is a record id, which is escaped into a segment of its own. -- `ZammadAPI::Test` raises `IncompleteResponseError` for a 2xx stub whose `Content-Length` - announces more than its body holds, as the transport does for that response. It handed - the response back as whole, so what a program does about a save or a destroy that was cut - short could not be tested against it, and a fixture carrying a stale `Content-Length` - passed there and failed against Zammad. The empty page it serves after a stubbed list is - given a length of its own. -- A `user_agent` of nothing but whitespace falls back to the gem's own, as `nil` and an - empty one do. The whitespace is taken off the value where it is sent, so - `user_agent: ' '`, which is what an environment variable set to a space gives, went out - as a `User-Agent` header with nothing in it, and the requests named no client in the - instance log. -- A proxy set in `Faraday.default_connection_options` is used where `proxy:` names none, as - the README says of those options and as 1.x did. The connection was built with - `proxy: nil` for a client without one, and an option named as `nil` stands in for the - default as one with a value does, so that proxy was taken off this client's connection - alone: its requests went out directly, or nowhere where only the proxy reaches the - instance. A proxy the configuration names still comes first. One set there that cannot - be parsed is reported as a `ConfigurationError` with its credentials redacted, as a - configured one is. -- `to_h` of a record's `attributes`, of its `changes` and of any Hash among them is plain - Hashes at every depth, and a writable copy. Each of those is a `ZammadAPI::Attributes`, - and a JSON encoder that takes nothing but the core types refuses a subclass of Hash by - its class: `JSON.generate(user.attributes, strict: true)` and `JSON::Coder.new.dump` - raise `ZammadAPI::Attributes not allowed in JSON`, for what 1.x handed out as Hashes. - `attributes.to_h` was plain no further than its first nested Hash, so it was refused the - same way, and only `record.to_h` could be handed to such an encoder. The README and the - migration table say that `to_h` is what a strict encoder is given. `to_json`, `as_json` - and `JSON.generate` without `strict:` are unchanged. -- Text held in ISO-8859-1, Windows-1252 or any other encoding that is not UTF-8 goes into a - query and into a request path as the same text in UTF-8. Only an encoding ASCII is no part - of, such as UTF-16, was converted, so `client.users.search('Größe')` with the term read - from a Latin-1 file was sent as `query=Gr%F6%DFe`, the bytes it was held in, as 1.x sent - it. Rails answers a query it cannot read as UTF-8 with a 400, which arrived as a - `ClientError` for a term with nothing wrong with it, while the same String in a JSON body - was converted and arrived as the text it is. A record id in such an encoding was written - into the path the same way, and one in UTF-16 raised `Encoding::CompatibilityError`. A - header value and `on_behalf_of` are converted as well. `find_by` holds each hit against - the text it searched for: against the value as given, in ISO-8859-1 or UTF-16, the record - was found by the search and passed over by the comparison, so `find_by` answered `nil` - for a record that exists. Text that cannot be converted raises `ArgumentError`, which - names the parameter and does not quote it. A binary String is sent as its bytes, as - before. -- A `GET` whose 2xx body stops short of its `Content-Length` is sent again, as often as - `retries` allows, before `IncompleteResponseError` is raised. The length was asked of the - response the retry middleware had already returned, so this was the one failure of a - connection a read was not repeated for: with `retries: 2`, an `attachment.download` the - connection dropped under raised after one request, while the same drop a moment earlier, - arriving as `ECONNRESET`, was asked again and answered. The check sits below the retry - now, in a middleware of the gem's own, and above the `middleware:` callable, so it reads - the body and the headers as that left them. A write is still sent once, since Zammad - answered it, and the error and the response it carries are what they were. - `ZammadAPI::Test` sends such a read again as well, each attempt taking the next stub of a - sequence. -- `ZammadAPI::Test` serves a stubbed list a page at a time, of the size the request asks - for. Only the page number was read: the records went whole to page 1 whatever `per_page` - said, and every later page was empty. With five records stubbed, `page(1, per_page: 2)` - held all five, `page(2, per_page: 2)` none, and `in_batches(of: 2)` yielded one batch of - five, where Zammad serves two, two and one, so code that pages by hand or leans on a - batch size saw other records in a test than in production. A search stubbed with its - total is cut the same way and reports the total on every page. A stub that names a - `page` or a `per_page` in its `query:` is served as written, as is one written short of - its own `Content-Length`, and a request that names no `per_page` is answered as before. -- Text in a request body that is tagged as binary is sent as the UTF-8 text its bytes are. - Text read with `File.binread`, off a socket or out of a mail library arrives tagged that - way, and the JSON generator goes by the tag: json 3 refuses a binary String with a byte - outside ASCII, where json 2 wrote one that was valid UTF-8 with a deprecation warning. So - `client.tickets.create(title: 'Größe'.b)` was sent, or raised `ZammadAPI::Error` with - the advice to Base64-encode an attachment, by which version of the generator a bundle - had resolved to. Bytes that are not valid UTF-8 are binary data and are refused with - that advice, as before. -- `Client.from_env` takes an environment variable that holds nothing but whitespace for - unset, as it takes an empty one. With `ZAMMAD_TOKEN` holding a token and - `ZAMMAD_HTTP_TOKEN` set to a space, the blank variable took the token's place and was - then read as no token: `ConfigurationError: missing user in config`, for an environment - that held a valid token. A `ZAMMAD_USER` or `ZAMMAD_PASSWORD` of a space beside a token - was refused as a second way to authenticate, and a `ZAMMAD_URL` of one was reported as a - url with no scheme and is reported as missing now. A password that is nothing but spaces - can still be passed as `password:`. -- A configuration that cannot be used is reported as a `ConfigurationError` whatever the - environment holds. Where it held a variable whose name is not valid UTF-8, which a - process can inherit, the search for proxy variables that redacts the error raised over - that name, and `Client.new(proxy: 'http://user:pa ss@host')` left as a bare - `ArgumentError: invalid byte sequence in UTF-8`, past a - `rescue ZammadAPI::ConfigurationError`. The name is read as its bytes, so a variable of - that kind ending in `_proxy` has its value scrubbed like any other. +- Credentials no longer reach the debug log or `inspect`: 1.x logged `user:password` when a + client was built and wrote payloads out as they stood. Keys, query parameters and headers + that name a credential are redacted, and a path is logged without its query string. +- An exception inside the block of `perform_on_behalf_of` no longer leaves the `From` + header set on every later request; the block form of `on_behalf_of` scopes a client of + its own. +- A Zammad served from a sub-path (`https://example.com/zammad/`) works; 1.x sent every + request to the root of the host. +- Query parameters are encoded by Faraday; 1.x sent a list or a Hash, such as a search + `condition`, as its Ruby `inspect`. +- A Hash inside an Array attribute has Symbol keys like every other; 1.x left it the + String keys Zammad sent. +- A response body that is not JSON is no longer read as an empty Hash: a 2xx where a + record was expected raises `ParseError`. +- An unknown resource name raises `UnknownResourceError` rather than resolving to a class + that is not a resource, as `client.base` resolved to `Resources::Base`. +- Record ids are percent-encoded wherever they go into a path, attachment downloads and + article lists included. +- `save` on a record with nothing staged sends no request; 1.x sent an empty `PUT`, which + bumped `updated_at` and `updated_by`. +- `record[:x] = 1` stages the attribute it names; 1.x took it for an attribute called `[]`. +- `add_article` on a ticket that has not been saved raises `ZammadAPI::Error`, where 1.x's + `article` posted it with `ticket_id: null`. +- A `url` carrying `user:password@` raises `ConfigurationError`, where 1.x sent those in + place of a configured token, and so does one without a host, such as `http://:3000/`, + which 1.x sent to localhost. +- A subclass of a resource inherits its API path; in 1.x `class MyTicket < Ticket; end` + had none. ### Changed -- `Response#headers` is frozen, and each response carries its own. Writing through it - changed nothing on the wire and, in `ZammadAPI::Test`, rewrote the stub for every later - request in the example. - +- `Response#headers` is frozen, and each response carries its own. - `client..destroy(id)` deletes directly instead of fetching the record first. - Resource dispatch is explicit rather than `method_missing` plus `const_get`. - A resource declares what its endpoint does — `searchable true`, `max_per_page 100`, - `sortable false` — the way it already declared `path`, rather than by setting - `SEARCHABLE`, `MAX_PER_PAGE` and `INDEX_QUERY_KEYS`. A misspelled constant was silently - ignored and the resource kept Base's default, so `SEARCHEABLE = true` left the resource - unsearchable and every `find_by` on it raised "Zammad routes no search endpoint" with no - hint that the declaration was the problem; a misspelled declaration is a `NoMethodError` - at load. + `sortable false`, `paginated false` — the way it declares `path`. - `client.` returns the same proxy each time rather than allocating one per call. - The proxies are built with the client and frozen, so a client stays immutable once built - and safe to share between threads without locking, as documented. Clients from `#with` - and `#on_behalf_of` get proxies of their own, so none is shared with the transport it was - derived from. + The proxies are built with the client, so a client stays immutable once built and safe to + share between threads. +- A request body that cannot be encoded as JSON raises `ZammadAPI::Error` rather than + `JSON::GeneratorError`. A String body is sent as it is. - The recursive copy behind frozen attributes, `to_h` and the test kit's recorded bodies lives in one place (`ZammadAPI::DeepCopy`) instead of being written once per caller. - Unit specs (`rake spec:unit`) run without a Zammad instance; the specs that need a live - server live in `spec/integration`. + server live in `spec/integration`, and run only where `TEST_URL` names one. - CI runs RuboCop, Steep and the unit specs on every supported stable Ruby, and publishes releases through RubyGems trusted publishing. -- The integration job now waits for Zammad to answer before running specs, promotes - Zammad's generated CI environment into the job so it survives across steps, pins the - Zammad ref (overridable via `workflow_dispatch`), carries a timeout, and uploads Zammad's - logs on failure. It also runs `script/check_connection.rb` as a preflight, so a broken - gem-to-Zammad link fails in seconds with a readable transcript instead of 53 spec errors. +- The integration job waits for Zammad to answer before running specs, pins the Zammad ref + (overridable via `workflow_dispatch`), carries a timeout, uploads Zammad's logs on + failure, and runs `script/check_connection.rb` as a preflight. - The integration suite no longer depends on spec file order to run Zammad's auto wizard, - and tolerates an instance that is already set up. Its lifecycle examples are pinned to - definition order and say what is missing when only part of a file is run. + and tolerates an instance that is already set up. - `Test::UnstubbedRequestError` is a `StandardError` rather than a `ZammadAPI::Error`, so a forgotten stub is not caught by the `rescue ZammadAPI::Error` in the code under test. -- The test kit matches array-valued query stubs, such as `query: {ids: [1, 2]}`, which - could never match before. ## [1.4.0] - 2026-08-25 - Follow up - c3af2a9 - Fixes #29 - [JSON::ParserError on gateway timeout when proxy responds with HTML](https://github.com/zammad/zammad-api-client-ruby/issues/29) diff --git a/README.md b/README.md index de3cfbf..f993275 100644 --- a/README.md +++ b/README.md @@ -126,13 +126,11 @@ them. ### From the environment -`from_env` reads `ZAMMAD_URL` and `ZAMMAD_TOKEN` (or `ZAMMAD_USER` and -`ZAMMAD_PASSWORD`, or `ZAMMAD_OAUTH2_TOKEN`), so a script needs no configuration of its -own. Anything passed in wins over the environment, credentials included — passing -`user:` and `password:` replaces a token the environment holds rather than sitting beside -it. A variable that is empty, or holds nothing but whitespace, counts as unset. An -environment that itself sets more than one way to authenticate is refused, until an -argument says which is meant: +`from_env` reads `ZAMMAD_URL` and `ZAMMAD_TOKEN` (or `ZAMMAD_HTTP_TOKEN`, +`ZAMMAD_OAUTH2_TOKEN`, or `ZAMMAD_USER` and `ZAMMAD_PASSWORD`), so a script needs no +configuration of its own. A variable that is empty or blank counts as unset. Anything +passed in wins over the environment, and credentials passed in replace the ones the +environment holds: ```ruby client = ZammadAPI::Client.from_env @@ -148,32 +146,22 @@ client = ZammadAPI::Client.from_env(timeout: 300) | `oauth2_token` | `nil` | OAuth2 bearer token. | | `user` | `nil` | Login for basic authentication. | | `password` | `nil` | Password for basic authentication. | -| `timeout` | `60` | Seconds to wait for a response, at most 100000000. It cannot be turned off, and `nil` is refused: pass the longest wait that is acceptable. | -| `open_timeout` | `10` | Seconds to wait for the connection, with the same limit. | +| `timeout` | `60` | Seconds to wait for a response. A positive number. | +| `open_timeout` | `10` | Seconds to wait for the connection. A positive number. | | `retries` | `2` | Retry attempts for a `GET` that failed transiently. `0` disables retrying. | | `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt, up to `timeout`. Up to half of it is added to each wait as jitter. | | `ssl_verify` | `true` | Set to `false` only against a server with a self-signed certificate. | | `proxy` | `nil` | Proxy URL. | | `user_agent` | `zammad_api-ruby/` | Value of the `User-Agent` header. | | `logger` | discards output | Any `Logger`; the client logs requests and responses at `debug`. | -| `adapter` | Faraday's default | Name of the Faraday adapter to use. | -| `middleware` | `nil` | Callable that receives the Faraday connection while it is built. | +| `adapter` | Faraday's default | Name of a Faraday adapter, such as `:net_http_persistent`. | +| `middleware` | `nil` | Callable that is handed the Faraday connection while it is built, after this gem's own middleware and the adapter. | Credentials are never written to the log, and `client.config` redacts them however it is -printed — `inspect`, `to_s` or `pp`, which is what a console shows — and however it is -serialized as text, with `to_json`, with the `as_json` ActiveSupport asks or with `to_yaml`, -so a configuration object is safe to include in an error report. A client serializes as its -URL and the way it authenticates, and no more, and so does the transport a record's YAML -names. `Marshal.dump` is the exception, where it works at all. It writes what the object is -rebuilt from, credentials included, and it writes a configuration whose logger is the -default one. A client and a record are dumped only until the client has made a request: -from then on the connection holds a lock, and `Marshal.dump` raises `TypeError`, as it does -from the start where the logger writes to a file or a stream. See -[Comparing and serializing](#comparing-and-serializing) for what to cache of a record. - -Credentials belong in the options above, not in the URL. `https://user:secret@host/` raises -`ZammadAPI::ConfigurationError`, because the HTTP stack would send those as basic -authentication in place of the token configured beside them. +printed — `inspect`, `to_s` or `pp`, which is what a console shows. + +Credentials belong in the options above, not in the URL: `https://user:secret@host/` +raises `ZammadAPI::ConfigurationError`. ### Checking the connection @@ -201,13 +189,10 @@ client = ZammadAPI::Client.new( ) ``` -The callable runs last, after this gem's own middleware and before the adapter, so it sees -requests as the client finished building them and responses before anything else does. -Faraday stays an implementation detail either way: an unregistered adapter raises -`ZammadAPI::ConfigurationError`, not a Faraday error. - -`adapter:` takes a name. An adapter that needs arguments is set inside the callable -instead, and is the one the client then uses: +The adapter is set first, and the callable runs after it, behind this gem's own +middleware, so it sees requests as the client finished building them and responses before +the client does. An adapter that needs arguments is set inside the callable, and takes the +place of one named with `adapter:`: ```ruby client = ZammadAPI::Client.new( @@ -217,31 +202,16 @@ client = ZammadAPI::Client.new( ) ``` -Naming an adapter both ways raises `ZammadAPI::ConfigurationError`, since one of the two -would be dropped. +A Faraday error while the connection is built, such as an adapter that is not registered, +raises `ZammadAPI::ConfigurationError`. This gem decodes JSON and maps error statuses +itself, so leave out middleware that does either, such as `response :json` or +`response :raise_error`. Faraday's default adapter, `net_http`, opens and closes a connection around every -request, so a walk of N pages is N TCP connections and N TLS handshakes. That is the -default because it needs no extra gem; for anything that pages, downloads attachments in a -loop, or runs a worker pool, add `faraday-net_http_persistent` to your Gemfile and pass -`adapter: :net_http_persistent` as above. Nothing else changes — the option is the whole of -it. - -Two things the seam will not take, and it says so with a `ZammadAPI::ConfigurationError` -when the client is built. One is middleware that decodes the response body, -`connection.response :json`: this gem parses JSON itself, and hands the undecoded bytes -back as the file from `attachment.download`, so a stack that has already consumed the body -leaves nothing faithful to return. The other is `connection.response :raise_error`, which -raises a Faraday error for a 4xx or 5xx before this gem sees the response: nothing would be -retried, and a missing record would arrive as `Faraday::ResourceNotFound` rather than the -`ZammadAPI::NotFoundError` your code rescues. A subclass of either is refused for what it -inherits. - -What a process sets in `Faraday.default_connection_options` for all of its Faraday -connections applies to this client's as well: other headers, TLS settings, a proxy. An -`Authorization` header, a `From` header and query parameters set there are left off. The -two headers are what `http_token:` and `on_behalf_of` say, and a request carries the query -it names. +request, so a walk of N pages is N TCP connections and N TLS handshakes. For anything that +pages, downloads attachments in a loop, or runs a worker pool, add +`faraday-net_http_persistent` to your Gemfile and pass `adapter: :net_http_persistent` as +above. ## Available resources @@ -325,8 +295,7 @@ Say what else is true of the endpoint, where it differs from the defaults: | ------------------ | ------- | -------------------------------------------------------------------- | | `path '…'` | *required* | The index endpoint, relative to the instance URL. | | `searchable true` | `false` | Zammad routes `/search`, so `search` works and `find_by` uses it. | -| `search_filters :role_ids` | none | What that search narrows by besides the term, `condition:` and `ids:`. `search` refuses any other keyword. | -| `max_per_page 100` | `1000` | The largest page the index endpoint serves. | +| `max_per_page 100` | `1000` | The largest page the index endpoint serves. A walk ends at the first page shorter than the size it asked for, so this has to be what the endpoint really serves. | | `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. | | `paginated false` | `true` | The index endpoint serves every record in one response and reads no `page`. It is read in one request, and `page` refuses it. | | `belongs_to :role, class_name: 'Role'` | — | A foreign key, read as a record through `record.related.role`. | @@ -336,11 +305,10 @@ Say what else is true of the endpoint, where it differs from the defaults: full name, `'Acme::Role'`. A subclass of a modelled resource works too, and inherits what its parent declares: `class MyTicket < ZammadAPI::Resources::Ticket`. -Most of Zammad's index endpoints page, and a collection walks them a page at a time. One -that does not — `api/v1/object_manager_attributes` serves every attribute in one response, -whatever it is asked — answers the request for a second page with the first again, which -a walk reports as `ZammadAPI::PaginationError` rather than read as the end. Declare such a -resource `paginated false`: +An endpoint that serves every record in one response and ignores `page` — +`api/v1/object_manager_attributes` is one — answers the request for a second page with the +first again, which a walk reports as `ZammadAPI::PaginationError`. Declare such a resource +`paginated false`, and it is read in one request: ```ruby class ObjectAttribute < ZammadAPI::Resources::Base @@ -352,11 +320,8 @@ end client.resource(ObjectAttribute).find_by(name: 'priority_id') # one request ``` -Declare it only where the endpoint does serve every record. One that ignores `page` and -caps what it serves would be read as far as its cap, with nothing to say that there is -more. Whether the endpoint sorts is a declaration of its own: this one reads no parameter -at all, so it says `sortable false` as well. A search always pages, whatever the index -beside it does. +This endpoint sorts nothing either, so it says `sortable false` as well. A search always +pages, whatever the index beside it does. Use raw requests for an endpoint that is not shaped like that — an action, a report, a setting. @@ -377,28 +342,16 @@ client.put('api/v1/roles/2', body: {note: 'Updated'}) client.delete('api/v1/tags/remove', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) ``` -All four take `headers:`, for an endpoint that needs one: +All four take `headers:`, for an endpoint that needs one. Names and values are sent as +text: ```ruby client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) ``` -Names are case-insensitive, and two spellings of one header are refused rather than merged. -`Authorization` and `From` are refused outright: the first is what the client's credentials -are for, the second is what `on_behalf_of` sets, and replacing either from a single request -would leave the client reporting something it no longer does. A name is letters, digits and -signs such as `-` and `_`; one that is empty, or holds a space, a colon or a line break, -raises `ArgumentError` before anything is sent or logged. - -A `body:` is sent as JSON, and so are the attributes a record is saved with. A value JSON -has no type for raises `ZammadAPI::Error` rather than going out as it prints, which is all -the encoder does with one: pass a `Set` or a `Range` as its `to_a`. An object that defines -`to_json` writes itself, a `Time` or a `Date` is sent as its text, which Zammad reads, and -what converts to a Hash, such as permitted `ActionController::Parameters`, is sent as that -Hash. Where ActiveSupport is loaded, any other object is sent as its `as_json`, as its -`to_json` there would write it. A Hash that names one key twice, as `login:` and as -`'login'`, raises `ArgumentError`, as it does in a query. Neither error quotes a value of -the body, so one with a password in it is safe to log. +A `body:` is sent as JSON, and a String body is sent as it is. A body that cannot be +encoded as JSON raises `ZammadAPI::Error`. A `query:` Hash is encoded by Faraday, nested +Hashes and lists included. Each returns a `ZammadAPI::Response`, so the status and headers stay reachable: @@ -407,26 +360,18 @@ response = client.get('api/v1/tickets') response.status # => 200 response.headers['content-type'] response.body # decoded JSON, or the raw body for anything else -response.raw_body # the bytes as they arrived -response.json? # => whether the body was decoded +response.raw_body # the body as it arrived ``` -Zammad reports the size of a result in the body rather than in a header, and only -where you ask for it: `only_total_count=true` or `with_total_count=true` on a `/search` -endpoint, and `full=true` on the index endpoints that render through -`model_index_render`. `count` on a search collection uses the first of those. +Zammad reports the size of a result in the body rather than in a header, and only where +you ask for it: `only_total_count=true` or `with_total_count=true` on a `/search` +endpoint. `count` on a search collection uses the first of those. Paths are relative to the instance URL, and a leading slash is ignored, so they can be -pasted straight from the Zammad documentation. An absolute URL raises `ArgumentError`: the -client's credentials only ever go to the instance it was configured for, so a link taken -from a response body has to be reduced to its path first. Any path that opens with a -scheme counts as one, `http:/collect` as much as `https://other.example/collect`. A path -with a `..` segment raises it for the same reason, however the dots are written: for a -Zammad served from a sub-path, `../billing/export` is another application on its host. A path -is written the way a URL is, so a space or a character outside ASCII has to be -percent-encoded, `t%C3%A4gs` for `tägs`; one that cannot be read as a URL raises -`ArgumentError` too, before anything is sent or logged. A non-2xx response raises the same -error class it would raise for a modelled resource, and only a `GET` is retried. +pasted straight from the Zammad documentation. A path that opens with a scheme, such as +`https://other.example/collect`, raises `ArgumentError`, so the client's credentials only +ever go to the instance it was configured for. A non-2xx response raises the same error +class it would raise for a modelled resource, and only a `GET` is retried. ## Working with records @@ -454,9 +399,6 @@ controller that is the permitted parameters, which `new`, `create`, `update`, client.users.create(params.require(:user).permit(:login, :email, :password)) ``` -Parameters that were not permitted raise `ActionController::UnfilteredParameters`, and -anything else that is not a Hash raises `ArgumentError`. - ### Fetch ```ruby @@ -476,111 +418,47 @@ client.users.find_by!(email: 'nobody@example.com') # raises NotFoundError client.groups.exists?(42) # => true ``` -`find_by` answers with the first record that carries those values, and `nil` if it finds -none, on every resource and for any kind of value. Zammad cannot be asked that directly, -because its index endpoints cannot filter — see [Narrowing](#narrowing) — so `find_by` -fetches candidates and checks them itself. A record it returns genuinely carries the -attributes you asked for, compared exactly and against the value as Zammad stores it, so -`find_by(email: 'Someone@Example.com')` does not match a login Zammad downcased. What a -`nil` means depends on how the candidates were fetched: after a walk, that no record this -client can read carries the values; after a search, that no hit does, and a search reads -less than the whole record, as described below. - -There are two ways it fetches the candidates, and they cost differently: +`find_by` answers with the first record that carries all of those values, compared +exactly, and `nil` if it finds none. Zammad's index endpoints cannot filter — see +[Narrowing](#narrowing) — so `find_by` fetches candidates and checks them itself: ```ruby -client.users.find_by(email: 'someone@example.com', active: true) # searches the email, matches both -client.users.find_by(firstname: 'Jane', lastname: 'Doe') # searches "Jane", matches both +client.users.find_by(email: 'someone@example.com', active: true) # searches the email, checks both client.ticket_states.find_by(name: 'open') # no search endpoint: walks the list -client.users.find_by(organization_id: 5) # no string to search on: walks the index +client.users.find_by(organization_id: 5) # no String to search on: walks the index ``` -An `id` is neither searched for nor walked to. `find_by(id: params[:id])` reads the record -the way `find` does, in one request, and answers `nil` where `find` raises `NotFoundError`. -The id may be the Integer or a String of its digits, and any other value given with it is -matched against the record that came back. Anything else, `nil` included, is the id of no -record, and is answered `nil` without a request. - -A search is the cheap way, and is used wherever the resource has a search endpoint and one -of the values is a string. The term is one string value, because Zammad matches words: a -value of another type would go out as the word it prints as, so `active: true` would look -for records containing `"true"`. Every other value is matched against the hits. - -Everywhere else `find_by` walks the index, a page at a time, until a record matches. That -is one request for a list of ticket states. Against every user or ticket on an instance it -is a request per page until the match, and the whole index for a miss — the same walk -`all.detect { ... }` makes, so give `find_by` a string to search on where there is one. - -The values are never joined into one term. An instance searching without Elasticsearch -matches the term literally, through a SQL `LIKE` over each string column, so `"Jane Doe"` -would ask for a single column containing the whole of it and match nobody. - -`find_by` reads the hits a page at a time until one matches, so a match usually costs one -request and a miss costs one per page of hits. It cannot stop at the first page: Zammad's -search sorts by `updated_at`, newest first, rather than by relevance, so where a few -hundred records contain the term the one that carries it exactly can be on any page. - -What the search can surface is Zammad's business: a value the instance has not indexed, or -cannot index, is a record `find_by` will not find. `find_by(...) || create(...)` can -therefore still create a duplicate — as writing the search out by hand would. - -Which values those are depends on the instance. With Elasticsearch the term is looked for -in everything a record is indexed with. Without it, Zammad reads a fixed set of columns: +An `id:` is read with `find`, in one request, and `nil` if it names no record. Otherwise, +where the resource has a search endpoint and one of the values is a String, the longest +one is the search term, and the hits are read a page at a time until one carries every +value. Otherwise the index is walked until a record matches, which against every user or +ticket on an instance is a request per page. -| Resource | What a search without Elasticsearch reads | -| ----------------------------------- | -------------------------------------------------------------- | -| `users`, `organizations`, `groups` | The string columns of the record's own table. | -| `tickets` | The title and number, and the from, to, subject and body of the ticket's articles. | - -Neither reads a name `expand` adds for an association, which is not a column, and a ticket -search reads no other attribute of the ticket. So on such an instance these look for the -word in fields that do not hold the value. They find the record only where the word -happens to appear in one of those fields as well, and otherwise answer `nil` for a record -that exists: - -```ruby -client.tickets.find_by(state: 'open') # the state is not among what a ticket search reads -client.tickets.find_by(external_ref: 'SO-1001') # nor is a custom attribute of a ticket -client.users.find_by(organization: 'Acme') # a name expand adds, not a column -``` - -`find_by` does not walk the index after a search that found nothing. A miss is the ordinary -case for `find_by(email: ...) || create(...)` on an address that is new, and that walk would -read every user on the instance to confirm it, a thousand to the request. Nothing in a -response says which backend answered, so `find_by` cannot tell that miss from one caused by -a field the search does not read. You can, and the walk is one word away: - -```ruby -client.tickets.detect { it[:state] == 'open' } # walks the index: every ticket this client may read -client.tickets.search('printer', condition: {'ticket.state_id' => {operator: 'is', value: [2]}}) -``` - -The walk compares `it[:state]`, as `find_by` does, and not `it.state`. Every record the -client may read goes through the block, and a reader raises for an attribute the record in -hand does not carry, which would end the walk on that record rather than pass it over. A -user without an organization carries no `organization`, and Zammad serves a reduced record -where the client may not see the whole of one. What the walk cannot find is a record the -client may not read, or a value on a record it only sees reduced. +What a search can find is up to Zammad. With Elasticsearch the term is looked for in +everything a record is indexed with; without it, Zammad reads the string columns of a +user, organization or group, and the title, number and articles of a ticket. On such an +instance `client.tickets.find_by(state: 'open')` answers `nil` for tickets that exist, and +`find_by(...) || create(...)` can create a duplicate. Walk the index where that matters: +`client.tickets.detect { it[:state] == 'open' }`. Zammad records can carry administrator-defined custom attributes, so readers are resolved against the attributes the record arrived with rather than declared ahead of time. A reader -for an attribute the record does not carry raises `NoMethodError`, naming what it does -carry — a typo is not worth a silent `nil` that flows on into whatever you write with it: +for an attribute the record does not carry raises `NoMethodError` rather than answering +`nil`: ```ruby -group.titel # NoMethodError: undefined attribute titel for ... -group[:titel] # => nil +group.titel # NoMethodError: undefined method 'titel' for an instance of ... +group[:titel] # => nil group.fetch(:titel, nil) # => nil -group.key?(:titel) # => false +group.key?(:titel) # => false ``` -That matters beyond typos: Zammad serves a reduced object where the authenticated user may -not see the whole record, so an attribute that exists in Zammad can be missing here. The -message says so. Use `[]`, `fetch` with a default, or `key?` wherever an attribute may -legitimately be absent. +Zammad also serves a reduced object where the authenticated user may not see the whole +record, so an attribute that exists in Zammad can be missing here. Use `[]`, `fetch` with a +default, or `key?` wherever an attribute may legitimately be absent. -`attributes` and `changes` are deeply frozen, because a record that let you write into -them would report a change it had never staged and would not send: +`attributes` and `changes` are deeply frozen. An attribute writer is the way to stage a +change, and `to_h` is a copy you may modify: ```ruby group.attributes[:name] = 'Support 2' # FrozenError @@ -588,25 +466,6 @@ group.name = 'Support 2' # the way to stage a change group.to_h # a deep copy, yours to modify ``` -Ruby quotes a frozen Hash in that `FrozenError`, so both are a `ZammadAPI::Attributes`: a -Hash that prints with the value under a key such as `password` or `token` blanked, the way -`inspect` of the record prints them, and that is a Hash in every other way. Reading from it -hands over every value, and `to_h` is a plain Hash. - -Every Hash inside them is one as well, and an encoder that takes nothing but the core types -goes by the class: `JSON.generate(group.attributes, strict: true)` and a `JSON::Coder` -without a block raise `ZammadAPI::Attributes not allowed in JSON`. Hand such an encoder -`to_h`, which is plain Hashes at every depth, of the record or of any Hash it holds: - -```ruby -JSON.generate(user.to_h, strict: true) # the record -JSON.generate(user.changes.to_h, strict: true) # what is staged -JSON.generate(user.preferences.to_h, strict: true) # one attribute -``` - -`to_json`, `as_json`, `JSON.generate` without `strict:` and YAML take the attributes as -they are. - ### Pattern matching Records implement `deconstruct_keys`, so they work with `case/in`: @@ -650,10 +509,7 @@ A `save` on a persisted record with nothing staged sends no request at all and r save would otherwise rewrite the record's audit trail. Writing back the value a record was loaded with is not a change, so it stages nothing. -Writing an attribute the record does not carry always is one, even when the value is `nil`: -Zammad reduces the object it serializes for a permission-scoped client, so a key being -absent says nothing about what is stored, and `group.note = nil` is a request to store -`nil` rather than a write to drop. +Writing an attribute the record does not carry always is one, even when the value is `nil`. Or in one call: @@ -716,10 +572,9 @@ ticket.related.created_by.email client.users.find(7).related.organization ``` -A `has_many` reader such as `articles` is the one list here that is read in a single -request and comes back as an Array rather than a paginating collection, because the -association endpoints Zammad routes serve the whole list: `ticket_articles/by_ticket` -renders every article of the ticket and takes no paging parameter. +A `has_many` reader such as `articles` is read in a single request and comes back as an +Array rather than a paginating collection, because the association endpoints Zammad routes +serve the whole list. A ticket's articles are also reachable without `related`, and `add_article` writes one: @@ -730,66 +585,34 @@ ticket.add_article(body: 'Reset link sent.', type: 'note') # => the created Tic The readers live under `related` rather than on the record so that `ticket.customer` keeps returning the name it always did — an attribute read that silently became an HTTP request -would be a poor trade. `belongs_to` targets are memoized, and `reload`, a save or a write -to the foreign key drops the memo; `has_many` lists are fetched each call, so an article -added in between shows up. A record hands out the same `related` every time, so one kept in -a variable follows the record too: after `related = ticket.related` and -`ticket.customer_id = 9`, `related.customer` is user 9. -`Ticket.associations` lists what a resource declares. +would be a poor trade. `belongs_to` targets are memoized until the next attribute write, +`reload` or save; `has_many` lists are fetched on each call, so an article added in between +shows up. `Ticket.associations` lists what a resource declares. ### Comparing and serializing A record is the Zammad record it came from, not the object that happens to hold it, so two -records of the same kind carrying the same id, read from the same Zammad, are equal. That -makes `uniq`, `Set`, `include?` and records-as-Hash-keys behave: +records of the same kind carrying the same id, read from the same Zammad URL, are equal. +That makes `uniq`, `Set`, `include?` and records-as-Hash-keys behave: ```ruby client.tickets.find(1) == client.tickets.find(1) # => true [client.tickets.find(1), client.tickets.find(1)].uniq.size # => 1 -Set[client.tickets.find(1), client.tickets.find(1)].size # => 1 -seen = { client.tickets.find(1) => :handled } -seen[client.tickets.find(1)] # => :handled ``` A record with no id is equal only to itself, because two unsaved records are two records -waiting to be created however alike their attributes are. One consequence: a record's first -save assigns its id and so changes its hash, and a record used as a Hash key before that -save has to be rehashed after it. - -Which Zammad a record came from is the `url` its client was configured with. A script that -reads two instances, such as a migration or a sync, therefore keeps ticket 1 of each apart, -while two clients for one URL, or a client and its `on_behalf_of` scope, hold the same -record. +waiting to be created however alike their attributes are. A record's first save assigns +its id and so changes its hash, and a record used as a Hash key before that save has to be +rehashed after it. -`to_json` renders the attributes, so a record can be cached, queued or logged as it stands, -and nests inside a structure being generated: +`to_json` renders the attributes, and `as_json` returns them as a Hash: ```ruby client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}" JSON.generate(group: client.groups.find(1)) ``` -`as_json` returns the same attributes as a Hash, for ActiveSupport and any encoder that -follows its convention. Both take `only:` and `except:` with attribute names, as Symbols or -Strings: - -```ruby -user.as_json(except: [:password]) -user.to_json(only: %w[id login]) -``` - -The record itself does not go through `Marshal`, so it does not go into a cache that -marshals what it is given, as `Rails.cache` does. A record holds the connection it was read -over, which cannot be dumped once it has carried a request, and `Marshal.dump(ticket)` -raises `TypeError`. Cache what the record holds, and read it again by its id where a record -is needed: - -```ruby -Rails.cache.write("ticket/#{ticket.id}", ticket.to_h) # a plain Hash of what it holds -client.tickets.find(ticket.id) # the record, read again -``` - ### Reload and destroy ```ruby @@ -798,9 +621,8 @@ group.destroy # => true group.destroyed? # => true group.persisted? # => false, so this is not the inverse of new_record? -group.save # raises: the record is gone, and a PUT would only 404 -group.update(...) # raises too, and stages nothing, so the record stays unchanged -group.name = 'X' # raises as well: a destroyed record reads as it last was in Zammad +group.save # raises: the record is gone +group.name = 'X' # raises as well client.groups.destroy(42) # delete by id, without fetching first ``` @@ -828,10 +650,10 @@ client.tickets.all.each do |ticket| puts ticket.title end -# Stops after the first page, because Enumerable stops consuming. +# One request, for five records. first_five = client.tickets.all.first(5) -# Lazy chains work as expected. +# Lazy chains stop fetching once they have enough. client.tickets.all.lazy.select { |t| t.state == 'open' }.first(10) # One array of records per request, e.g. for a bulk import. @@ -860,23 +682,14 @@ An attribute on its own sorts ascending and a keyword says which way one runs, a ActiveRecord. A second `order` sorts within the first, so `order(:active).order(name: :desc)` is the third line above. -Every sorted request names `id` as its last column as well, unless the order names it -already: `order(:active)` is sent as `sort_by=active,id`, which is also what the test kit -records. Zammad sorts by the columns it is given and by nothing after them, so records that -tie changed places from one page to the next, and a walk handed one over twice and passed -another by. A search that is given no order is sent none and keeps Zammad's own, latest -`updated_at` first for most resources, which breaks no tie either: give a search an `order` -before walking records that a bulk update left with the same `updated_at`. - Not every endpoint sorts. `/api/v1/tickets` and `/api/v1/users` are always served in id -order — their controllers hardcode it and drop `sort_by` along with everything else they -do not read — so `order` on those raises `ArgumentError` rather than handing back records -it would be calling sorted. A search sorts for every resource that can be searched: +order — their controllers hardcode it and drop `sort_by` — so `order` on those raises +`ArgumentError` rather than handing back records it would be calling sorted. A search +sorts for every resource that can be searched: ```ruby client.tickets.order(:title) -# ArgumentError: api/v1/tickets is always served in the same order and ignores sort_by, -# so order would hand back the records as they were. A search does sort: ... +# ArgumentError: api/v1/tickets is always served in the same order and ignores sort_by client.tickets.search('state.name:open').order(:title) ``` @@ -885,8 +698,7 @@ client.tickets.search('state.name:open').order(:title) **Zammad's index endpoints do not filter.** `ApplicationController#model_index_render` sorts and pages and drops every other parameter. Filtering by an attribute value exists -only on the `/search` endpoints, which is why a collection has no `where`: there is nothing -an index endpoint would do with what it was given. +only on the `/search` endpoints, which is why a collection has no `where`. Narrow by a value with [`find_by`](#fetch) for one record, or `search` for many: @@ -895,85 +707,30 @@ client.users.find_by(email: 'someone@example.com') client.tickets.search('state.name:open').first(10) ``` -`search` also takes the other things a search endpoint narrows by, as keywords: -`condition:` and `ids:` on every search, and `role_ids:`, `group_ids:` and `permissions:` -on users, the one search that reads them: +`search` passes any keywords on to the search endpoint as query parameters, for what it +narrows by besides the term: `condition:` and `ids:` on every search, and `role_ids:`, +`group_ids:` and `permissions:` on users: ```ruby client.users.search('smith', role_ids: [2]) -client.users.search('smith', group_ids: [1], permissions: ['ticket.agent']) client.users.search('smith', group_ids: {1 => ['read']}) client.tickets.search('printer', condition: {'ticket.state_id' => {operator: 'is', value: [1, 2]}}) client.tickets.search('printer', condition: {'ticket.group_id' => {operator: 'is', value: [2]}}) ``` -A `condition` may nest groups of conditions, the form Zammad calls expert mode: +Zammad ignores a parameter it does not read, so a misspelled keyword, or a user keyword on +another resource, comes back unnarrowed. Tickets are narrowed by group with a `condition` +on `ticket.group_id`, as above. -```ruby -client.tickets.search('printer', condition: { - operator: 'OR', - conditions: [ - {name: 'ticket.state_id', operator: 'is', value: [2]}, - {operator: 'AND', conditions: [ - {name: 'ticket.group_id', operator: 'is', value: [1]}, - {name: 'ticket.priority_id', operator: 'is', value: [3]} - ]} - ] -}) -``` - -A query string does not mark where one element of a list ends, and Rails begins a new one -only at a key the element before it has too. The elements above all carry `operator`, and -the client writes that first, so they arrive as written. A list whose elements share no -such key, a list directly inside a list, a Hash with no value in it and a key with an empty -name cannot be carried at all and raise `ArgumentError`; the JSON body of `client.post` takes -any structure. - -`group_ids:` narrows to the agents with access to a group, and its two forms ask for -different access. A list of ids names no access, and Zammad reads that as `full`: -`group_ids: [1]` leaves out an agent who may only read group 1. A Hash names the access -for each group — `read`, `create`, `change`, `overview` or `full`, one or several — and -an agent with `full` access always counts: `group_ids: {1 => ['read']}` is every agent -with `read` or `full` access to group 1. Access granted through a role counts like access -granted to the user, and an agent matching any one of the groups is kept. - -`permissions:` is not an access check. Zammad resolves it to the roles that grant one of -the permissions and adds those to `role_ids:`, so the two together keep a user with any -of the roles, not one with both. And where the instance searches through Elasticsearch, a -permission that no active role grants resolves to no role at all, and Zammad then leaves -the filter out: `permissions: ['ticket.agnet']`, or a permission nobody has been given, -comes back with every user matching the term. Without Elasticsearch the same search is -empty, and nothing in the response says which of the two answered. `role_ids:` narrows -on both. - -`role_ids:` is not an access check either. It asks who holds a role, and Zammad does not -ask whether the role still grants anything: a user matches a role that has been disabled, -and a user who has been deactivated matches as well, though neither can do what the role -allowed. So the hits are candidates. Where the result decides what someone may do, check -each one: the user's `active`, and the `active` and the permissions of the roles in -their `role_ids`, which `client.resource` reaches at `api/v1/roles`. - -Any other keyword raises `ArgumentError`. Zammad drops a parameter it does not know, so -`search('smith', active: true)` would come back unnarrowed with nothing to say so; an -attribute value goes in the term, a sort in `order`, and paging in `page`, `in_batches` or -`find_each`. A user keyword on another resource raises for the same reason: Zammad takes -`group_ids` on a ticket search and drops it, so tickets are narrowed by group with the -condition above. A `nil` value raises too: there is no query string that means "this field -is null". A value that is not text, an `Integer`, a `Float`, `true` or `false` raises as -well, alone or inside a list or a condition: `ids: Set[1, 2]` would be sent as that text, -which names no user, so pass a `Set` or a `Range` as its `to_a`, a time as the text Zammad -reads, and a record as its id. A number of another kind counts: `BigDecimal('5')` prints as -`0.5e1`, so pass it as an `Integer` or a `Float`, and a `Float` that is `NaN` or infinite -raises too. So does a keyword with nothing in it, such as `ids: []`, -`condition: {}`, or a condition that holds nothing but empty Hashes, which a query string -does not write. Zammad reads that as the keyword not having been given, so -`search('smith', ids: allowed_ids)` with no id allowed would come back with every user -matching the term rather than none. +`group_ids: [1]` names no access, and Zammad reads that as `full`; a Hash names the access +for each group, as in `group_ids: {1 => ['read']}`. Neither `role_ids:` nor `permissions:` +is an access check: a user matches a role that has been disabled, and a deactivated user +matches as well. Zammad routes a search endpoint per model, not for every model. `users`, `organizations`, `tickets` and `groups` have one; `ticket_states`, `ticket_priorities` and `ticket_articles` -do not, and `search` on those raises `ZammadAPI::Error` rather than reaching a 404 that -would read as a missing record. `find_by` works on them all the same, by walking the list: +do not, and `search` on those raises `ZammadAPI::Error`. `find_by` works on them all the +same, by walking the list: ```ruby client.ticket_states.find_by(name: 'open') @@ -988,17 +745,15 @@ client.organizations.search('zammad').each do |organization| end ``` -A term with nothing in it, Unicode spaces included, raises `ArgumentError`: Zammad reads it -as no term at all and answers with every record, which a search for an empty form field -should not come back with. `search('*')` asks for every record in so many words, and is -sent; it is how Zammad's own interface lists users, and the keywords above still narrow it. +A blank term raises `ArgumentError`: Zammad reads it as no term at all and answers with +every record. `search('*')` asks for every record in so many words. ### Explicit pages ```ruby tickets = client.tickets.all -tickets.page(2) # page 2 at the size the endpoint serves +tickets.page(2) # page 2 at the size the endpoint serves tickets.page(2, per_page: 10) # records 11 to 20 ``` @@ -1009,7 +764,8 @@ original untouched. A request fetches as many records as the endpoint will serve — 100 for `/api/v1/tickets`, 200 for a search, 1000 for the other index endpoints — so a walk spends as few round trips -as it can. Three calls take another size, each for its own kind of work: +as it can. Three calls take another size, each for its own kind of work, and a larger one +is reduced to that cap: ```ruby client.tickets.all.find_each(batch_size: 50) { |ticket| archive(ticket) } # walking @@ -1020,70 +776,18 @@ client.tickets.all.page(2, per_page: 100) # one `find_each` without a block is an Enumerator, so it is also how you read at a chosen page size: `client.tickets.all.find_each(batch_size: 50).first(7)`. -`page` and a batch size are two ways of naming the same thing, so combining them raises: -`page(3, per_page: 50)` already says which records the collection holds, and re-sizing it would -quietly hand back different ones. Size the page itself, or slice with `each_slice`. - -That cap is also the ceiling. `find_each` and `in_batches` are reduced to it: a -batch size is how much to fetch at a time, so a smaller one costs more requests and still -yields every record. `page` raises instead, because a page size also says *which* records -you get — `page(3, per_page: 500)` reduced to 100 hands back records 201 to 300 rather than 1001 -to 1500. So `in_batches(of: 500)` over tickets yields batches of 100, while -`page(3, per_page: 500)` over tickets is refused. -A walk learns the size the endpoint actually serves from the first page rather than trusting -that cap, so an instance that pages smaller than expected is walked to the end rather than -truncated at the first short page. -That keeps a walk complete: a page size the server silently shrank would otherwise end the -iteration at the first page. - -A search is walked until a page comes back empty, whatever the size of the pages before it. -Zammad has the search name the ids for a page and then loads those records, so a record -deleted in between, or one Elasticsearch still lists after it was removed, leaves the page -short with more hits behind it. A short page therefore ends the walk of an index and not of -a search, which costs a search one more request where its last page of hits is part-filled. - -A page can come back with nothing on it for the same reason, and on the page of one that -`first` and `empty?` ask for, one stale hit is enough — at the top of the result, since a -search serves the newest first. So a search that is walked asks Zammad for the size of the -whole result beside each page, with `with_total_count`, and an empty page ends the walk -only once the pages read have covered that many hits. The total is never what ends a walk -on a page that still held records. - -Three limits remain, and at each an empty page ends the walk whatever is behind it. A -Zammad before 6.5.1 does not report the total beside expanded records. Elasticsearch stops -counting at ten thousand hits, so past that many a page of stale hits reads as the end. And -the pages read are reckoned at the size that was asked for, 200 hits unless a batch size -says otherwise: an instance that serves a search in smaller pages than that has covered -fewer hits than the walk takes it to have. Asked for 200 and served 50, an empty first page -beside a total of 150 reads as the end, with the hits from the 51st on unread. On such an -instance `first`, `take` and `empty?` can also miss hits behind stale ones, since the -larger pages they ask for past an empty one (see below) are served from other positions -than the ones asked for. A hit served twice that way is handed back once. Zammad itself -serves a search 200 at a time. - -`first` and `take` size their own request rather than taking records off the front of one -sized for walking, so the cheap-looking call is cheap: +A walk of an index ends at the first page that is shorter than the size it asked for. A +search is walked until a page comes back empty, since Zammad leaves a hit whose record is +gone off its page, and a short page can have more hits behind it. + +`first` sizes its request to what it was asked for, so the cheap-looking call is cheap: ```ruby client.tickets.all.first # one request, for one record client.tickets.all.first(5) # one request, for five -client.tickets.all.take(5) # the same, and the same cost ``` -They size the request, not the collection, so they still read on where a page comes back -shorter than it was asked for — `first(5)` answers with five records if five exist, however -the endpoint chooses to page them. A collection `page` already limited keeps its own size, -since that size says which records it holds. - -On a search, the size is where the read starts and not what it is held to. Past a page with -nothing on it and hits still behind it, `first`, `take` and `empty?` ask for more at a -time, each page starting where the last one ended, up to the 200 a search serves and never -past the total it reported. Held to a page of one they paid a request for every stale hit -in a row, which is thousands of them where an Elasticsearch index has drifted from the -database. Held to the total, they stay inside an index whose result window was lowered -below the hits there are, which refuses a page reaching past it and is answered as no hits -at all. A batch size you chose, with `in_batches(of:)` or `find_each(batch_size:)`, is -never changed. +A collection that `page` already limited keeps its own size. ### Reading single attributes @@ -1097,49 +801,27 @@ shrinking the request. ### Counting -`count` is one request on a search, which Zammad can answer without serving the records. -Every other endpoint has to be walked, because an index endpoint offers nothing cheaper: -`model_index_render` reads `sort_by`, `order_by` and the paging and drops every other -parameter, so it has no answer for `only_total_count` and no total to report. +`count` on a search is one request, which Zammad answers without serving the records. +Every other collection is walked, because an index endpoint has no total to report: ```ruby client.tickets.search('state.name:open').count # one request client.tickets.all.count # one request per page -``` - -`size` and `length` are `count`, and cost the same. `empty?`, `any?`, `none?` and `first` -ask for a single record rather than a page: - -```ruby client.tickets.search('state.name:merged').empty? # one request, for one record -client.tickets.search('state.name:new').any? # the same -client.groups.all.size # => 12, having walked -``` - -A block or an argument is `Enumerable#count` counting matches, and walks either way: - -```ruby -client.tickets.all.count { it.state == 'open' } # walks every page ``` -Ruby asks for a `size` in places that do not look like a count. `each_slice`, `each_cons` -and `lazy` on a collection do not: they read the records once. An Enumerator that Ruby makes -from the collection does, so `each_with_index.each_slice(10)` counts before it slices, and -`each_slice(10).with_index` is the way to write it. - +A block or an argument is `Enumerable#count` counting matches, and walks either way. Nothing is cached, so every traversal of a collection fetches again. ### `find` is a lookup, not a filter `find` on a resource takes an id. On a collection it is `Enumerable#find`, which takes a -block — and its argument is an ifnone callable, not an id, so passing one is refused rather -than answered with an Enumerator and no request: +block, and passing an id there raises `ArgumentError`: ```ruby client.tickets.find(1) # the lookup by id client.tickets.all.detect { ... } # the block form -client.tickets.all.find { ... } # the same -client.tickets.all.find(1) # ArgumentError, naming both of the above +client.tickets.all.find(1) # ArgumentError ``` ## Deriving clients @@ -1181,13 +863,9 @@ end The identifier can be a login, an email address or a user id. This sends the standard HTTP `From` header and requires Zammad 5.0 or later. -An identifier that is `nil`, empty or blank raises `ArgumentError`. Zammad reads a `From` -header with nothing in it as no header at all, so `client.on_behalf_of(user&.login)` with -no user would otherwise perform every request as the account the client authenticates -as, and read everything that account can see. - -So does one that is neither text nor an Integer. Pass `user.id` or `user.login`, not the -record: `client.on_behalf_of(user)` would send the record as it prints, which names nobody. +An identifier that is `nil` or blank raises `ArgumentError`. Zammad reads an empty `From` +header as none at all, so `client.on_behalf_of(user&.login)` with no user would otherwise +perform every request as the account the client authenticates as. ## Error handling @@ -1201,7 +879,6 @@ ZammadAPI::Error ├── ZammadAPI::PaginationError endpoint ignored the page parameter ├── ZammadAPI::TransportError │ ├── ZammadAPI::ConnectionError unreachable host or TLS failure -│ │ └── ZammadAPI::IncompleteResponseError answered 2xx, body cut short │ └── ZammadAPI::TimeoutError exceeded timeout or open_timeout └── ZammadAPI::ResponseError carries the HTTP response ├── ZammadAPI::ClientError 4xx @@ -1231,49 +908,23 @@ end `resource_class`. A proxy that returns an HTML error page instead of JSON produces a `ServerError` describing the status, not a JSON parse failure. -A `TransportError` is a request with no whole answer, which is not the same as one Zammad -never saw: a write that timed out may have been applied. `IncompleteResponseError` is the -one case where that is known. Zammad answered 2xx, the connection closed before the body -had arrived, and `e.response` holds the status and what did arrive. A record whose `save` -or `destroy` raises it is left saved or destroyed, so the call is not to be repeated. After -an update, `reload` brings in what the lost answer would have. A record that was being -created is in Zammad as well, but its id was in that answer: it has none to reload by, and -`reload` raises `ZammadAPI::Error` saying so. Look it up again, with `find_by` for instance. - -A `save` that raises `ParseError` was answered 2xx without the record, and whose answer -that was decides what it leaves behind. One that says it is JSON is Zammad's, with a body -cut off or rewritten on the way: the save was applied, and the record is left as it is -after an `IncompleteResponseError`. One of any other content type, or of none, is the -answer of something in front of Zammad that did not pass the request on, such as a login -page served with status 200. The record is left as it was, its changes staged and a new -record still new, and the `save` can be repeated once the way is clear. An -`IncompleteResponseError` whose `e.response` is not JSON leaves a record being saved that -way as well. - -A `destroy` asks the same of its 2xx. Zammad answers a DELETE with no body or with JSON, so -a 2xx with a body of any other kind raises `ParseError`, from `record.destroy` and from -`client.groups.destroy(id)` alike. The record is not `destroyed?`, and the call can be -repeated. +A `TransportError` is a request with no answer, which is not the same as one Zammad never +saw: a write that timed out may have been applied. ### Timeouts and retries A `GET` is retried on connection failures, timeouts and the transient statuses 429, 500, -502, 503 and 504, with exponential backoff. A 2xx whose body stopped short of its -`Content-Length` is a connection failure like any other: the `GET` is sent again, and -`IncompleteResponseError` is raised once the retries are spent. +502, 503 and 504, with exponential backoff. A `Retry-After` header on one of those responses is honoured: the client waits as long as the server asked before the next attempt, up to `timeout` seconds. A longer one is not waited out. The request fails at once with the error for its status, and -`RateLimitError#retry_after` carries the figure, so a job can reschedule itself rather -than hold a thread for however long a maintenance page suggests. +`RateLimitError#retry_after` carries the figure, so a job can reschedule itself. A write is never retried. `POST` would create a second record, and `PUT` and `DELETE` are -not safe to repeat against Zammad either, whatever HTTP says about them: a ticket update -carrying an `article` adds that article — and sends its e-mail — once per delivery, and a -`DELETE` repeated after a lost answer comes back as a 404 for a record that was just -deleted. So a write that fails raises, and the code that knows what the request carried -decides whether to send it again: +not safe to repeat against Zammad either: a ticket update carrying an `article` adds that +article — and sends its e-mail — once per delivery. So a write that fails raises, and the +code that knows what the request carried decides whether to send it again: ```ruby begin @@ -1303,18 +954,13 @@ client = ZammadAPI::Client.new( ) ``` -Any object will do in place of a `Logger`, as long as its `debug` can be called with a block -and no argument: each line is handed over as a block, so that it is only built where it is -written. One whose `debug` requires an argument raises `ConfigurationError` when the client -is built. +Any object that responds to `debug` will do in place of a `Logger`. Each line is handed +over as a block, so that it is only built where it is written. Requests, response statuses and durations are logged at `debug` level. Payload keys, query parameters and headers that look like credentials (`password`, `token`, `secret`, `cookie`, -...) are redacted. That holds for a query string written into the path of a raw request, -in the log and in the message of an error the request raises. A request body is logged as -it is sent: read back from the JSON it was encoded to and redacted by key, whether it was -handed over as a Hash, as a JSON String or as an object that writes its own JSON. A body -that is not a JSON object or array is not logged, only its size. +...) are redacted, and a path is logged without its query string. A body that is not a +Hash or an Array, such as a JSON String, is not logged, only its size. ## Testing code that uses this client @@ -1344,81 +990,21 @@ raises `NotFoundError`, and one with `status: 422` makes `save` return `false`. | Method | What it does | | ------ | ------------ | -| `stub(verb, path, status:, body:, headers:, query:)` | Declares a response. Stubbing the same endpoint twice with the same scope describes a sequence; the last stub answers every later request. `query:` matches a subset, so it need not repeat `expand`, `page` or `per_page`. | +| `stub(verb, path, status:, body:, headers:, query:)` | Declares a response. `query:` matches a subset of the request's parameters, so it need not repeat `expand`, `page` or `per_page`. | | `client` | A client wired to this stand-in. | | `requests` | Every request made, oldest first, as `verb` / `path` / `query` / `body` / `headers` / `on_behalf_of`. | +| `stubbed` | One `"GET api/v1/groups"` per stubbed endpoint. | | `reset` | Forgets the stubs and the recorded requests. | A `Hash` or `Array` body is served as JSON and gets `content-type: application/json` -unless `headers:` says otherwise — and it is that header, not the Ruby type, that decides -whether the body comes back decoded, exactly as it does on the wire. So a `Hash` stubbed -as `text/html` comes back as the raw string and reading a record from it raises -`ParseError`, which is what Zammad would do. Header names and values are stringified and -names downcased, the way a real `Response` carries them; a value that is not text, or two -spellings of one header name, are refused where the stub is written rather than turned -into something the wire could not send. - -A 2xx stubbed with a `Content-Length` that announces more than its body holds raises -`IncompleteResponseError`, as that response does on the wire. It is how a test says that a -save was answered and the answer cut short: - -```ruby -zammad.stub(:put, 'api/v1/tickets/1', body: '{"id":1,"ti', - headers: {'Content-Type' => 'application/json', 'Content-Length' => 30}) -``` - -`query` and `headers` are recorded through the real transport's own stringification, so -they hold what a request would have carried rather than the raw Ruby values — and a header -the wire would refuse is refused here too. `headers` names only what the call asked for; -the ones the client sets from its configuration are not in it, and an `on_behalf_of` scope -has a field of its own. +unless `headers:` says otherwise, and it is that header that decides whether the body +comes back decoded, as it does on the wire. A recorded request's `query` has its keys and +values as text, and its `headers` have downcased names; the headers the client sets from +its configuration are not in it, and an `on_behalf_of` scope has a field of its own. -A read that is answered 429 or 5xx, or with a 2xx cut short of its `Content-Length`, is -sent again, as it is on the wire: a `GET`, up to `retries` times, and never a write. Each -attempt is in `requests` and takes the next stub of a sequence, so a read that fails once -and then succeeds is two stubs: - -```ruby -zammad.stub(:get, 'api/v1/tickets/1', status: 503) -zammad.stub(:get, 'api/v1/tickets/1', body: {id: 1, title: 'Help'}) - -zammad.client.tickets.find(1).title # => "Help" -zammad.requests.size # => 2 -``` - -A single failing stub answers every attempt, so the error is raised once the retries are -spent, with three requests recorded under the default of two retries. There is no wait -between attempts. A `Retry-After` longer than `timeout` ends them at once, as it does -against Zammad. `ZammadAPI::Test.new(retries: 0)` raises for the first failure, and so -does a client derived with `zammad.client.with(retries: 0)`. - -A request that was not stubbed raises `ZammadAPI::Test::UnstubbedRequestError`, listing -what is stubbed, rather than answering with something empty. It is deliberately not a -`ZammadAPI::Error`: a forgotten stub means the test is wrong, not that Zammad refused -something, so a `rescue ZammadAPI::Error` in the code under test lets it through instead of -reporting it as an API failure. - -### Stubbing a list endpoint - -One stub is enough for a list. The records it holds are the list, and a request is served -the page of them it asks for. A page past the records is answered the way an endpoint out -of records would answer it: - -```ruby -zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}, {id: 2, name: 'Sales'}, {id: 3, name: 'Support'}]) - -client.groups.all.map(&:name) # => ["Users", "Sales", "Support"] -client.groups.all.page(2, per_page: 2).map(&:name) # => ["Support"] -client.groups.in_batches(of: 2).map(&:size) # => [2, 1] -``` - -The page is cut by the `page` and `per_page` the request carries. A request that names no -`per_page` gets every record on page 1 and none after it, and the endpoint's own limit on -a page is not applied. - -Stub the endpoint again to describe a list that changes between reads. A read is one step -of the sequence however many pages it asks for, so each read gets the next stub and the -last one answers every read after it: +Stubbing the same endpoint again queues a second response. A request is answered by the +first stub whose `query:` it matches, and that stub is used up unless it is the last one +that matches, so the last answers every later request: ```ruby zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}]) @@ -1428,47 +1014,25 @@ client.groups.all.count # => 1 client.groups.all.count # => 2 ``` -A `count` on a search is one step as well, although it asks twice: for the total alone, -which a stub holding records answers with the records, and then for the pages. - -The second stub may also be declared once the first has answered, between two steps of a -test. It answers from the next request on. - -Name a `page` to say what each one holds, and the stub is served exactly as written. One -that names a `per_page` is not cut either: +One stub is enough for a list. It answers the first page as written, and a request for a +later page with an empty list, unless its `query:` names a `page`: ```ruby -zammad.stub(:get, 'api/v1/groups', body: first_hundred, query: {page: 1}) -zammad.stub(:get, 'api/v1/groups', body: [{id: 101}], query: {page: 2}) -``` +zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}, {id: 2, name: 'Sales'}]) -A search that is walked asks for its total with `with_total_count`, and an Array answers -it the way a Zammad before 6.5.1 does, with the records alone. To stand in for one that -reports the total, stub the object it answers with. It is paged like an Array, and every -page reports the same total. +client.groups.all.map(&:name) # => ["Users", "Sales"] -```ruby -zammad.stub(:get, 'api/v1/users/search', body: {records: [{id: 1}, {id: 2}], total_count: 2}) +zammad.stub(:get, 'api/v1/tickets', body: first_hundred, query: {page: 1}) +zammad.stub(:get, 'api/v1/tickets', body: [{id: 101}], query: {page: 2}) ``` -### Scopes that overlap - -A stub naming `query:` answers ahead of one that does not, so a scoped stub and a catch-all -are two separate answers rather than a sequence: - -```ruby -zammad.stub(:get, 'api/v1/tickets/search', body: {total_count: 42}, query: {only_total_count: true}) -zammad.stub(:get, 'api/v1/tickets/search', body: [{id: 1}]) - -client.tickets.search('urgent').count # => 42, however often it is asked -``` +The stand-in does not retry: a stubbed 429 or 5xx raises at once, where a client talking +to Zammad would ask again. -Two stubs whose scopes match a request equally well raise -`ZammadAPI::Test::AmbiguousStubError` rather than one of them being picked: `count` sends -the search term and `only_total_count` together, so a records stub scoped to -`{query: 'urgent'}` matches it just as well as the count stub does. Name what tells the -requests apart — here, the search term on the count stub too — or leave the more general -one unscoped as above. +A request that was not stubbed raises `ZammadAPI::Test::UnstubbedRequestError`, listing +what is stubbed, rather than answering with something empty. It is deliberately not a +`ZammadAPI::Error`: a forgotten stub means the test is wrong, not that Zammad refused +something, so a `rescue ZammadAPI::Error` in the code under test lets it through. ## Type signatures @@ -1630,7 +1194,7 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | -------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------- | | `Client.new(config_hash)` | `Client.new(**config_hash)` | Options are keyword arguments now, so a Hash has to be splatted | | an unknown option was ignored | raises `ArgumentError: unknown keyword` | A typo'd option used to be dropped without a word | -| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object, so you choose the device and level. Anything whose `debug` takes a block, as `Logger#debug` does, is accepted; `true` raises `ConfigurationError` | +| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object, so you choose the device and level. Anything that responds to `debug` is accepted; `true` raises `ConfigurationError` | | `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is `Enumerable` over every record now, so `client.ticket.each` read as if it acted on one ticket. The singular names raise `UnknownResourceError`, which lists the plural ones, and so does `client.resource(:ticket)` | | `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads | | `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised | @@ -1656,15 +1220,13 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | ----------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------- | | `record.save` raised on a rejection | `save` → `false` with `record.error`; `save!` raises | Branching on a rejected attribute needed a begin/rescue | | `record.attributes[:x] = 1` | `record.x = 1`, or `record.to_h` for a copy | Writing through the reader staged no change, so `save` never sent it | -| `JSON.generate(record.attributes, strict: true)` | `JSON.generate(record.to_h, strict: true)` | `attributes` and every Hash in it is a `ZammadAPI::Attributes`, which a strict encoder refuses by its class; `to_h` is plain Hashes throughout | | `record.attributes = {...}` | `record.assign_attributes(...)` / `record.update(...)` | The writer is gone, and the name now stages an attribute of its own | -| `record.id = 5` | `client.x.find(5)` | The id addresses the record, so a staged one deleted or updated a different record than it reported | -| `record.new_instance` | `record.new_record?` / `record.persisted?` | Internal flag is no longer public; the old name raises `NoMethodError`, naming the attributes the record does carry | +| `record.id = 5` | `client.x.find(5)` | The id addresses the record, so a staged one deleted or updated a different record than it reported. It raises `ZammadAPI::Error` now | +| `record.new_instance` | `record.new_record?` / `record.persisted?` | Internal flag is no longer public; the old name raises `NoMethodError` | | `resource.url` (instance) | `Resource.resource_path` (class) | Clashed with an attribute named `url` | | `record.unknown_attribute` → `nil` | raises `NoMethodError`; use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` | A typo read as `nil` and flowed on into whatever was written with it. Zammad also serves a reduced object where the user may not see the whole record, and that is worth being told about | -| `client.x.new(id: 5)` | `client.x.find(5)` | The constructor was the one door that did not refuse a staged id — and the only one whose value reached Zammad, since a new record is sent in full | | `client.users.find(ticket.customer_id)` | `ticket.related.customer` | Following a foreign key needed the client threaded through | -| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | A noun that sends a `POST`, one letter away from `ticket.articles`, which only reads. The method is gone: `article` is an attribute reader like any other, and the old call raises `NoMethodError` on a ticket that has no article staged and `ArgumentError`, naming `add_article`, on one that has | +| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | A noun that sends a `POST`, one letter away from `ticket.articles`, which only reads. The method is gone: `article` is an attribute reader like any other, and the old call raises `NoMethodError` | ### Errors diff --git a/Steepfile b/Steepfile index be45c0f..c0e6fbc 100644 --- a/Steepfile +++ b/Steepfile @@ -7,12 +7,12 @@ target :lib do # socket is here for SocketError and openssl for OpenSSL::SSL::SSLError, # both of which Transport maps to ConnectionError; forwardable is here for # the collection shorthands ResourceProxy delegates to Collection; uri is - # here for the parse Config makes to find credentials in the instance url; - # date is here for the Date a request body carries as text. None of the - # five is named in the signatures the gem publishes - see SSL_ERRORS in - # sig/zammad_api/transport.rbs and sig/vendor/internal.rbs - so this does - # not add anything a consumer has to load. - library 'json', 'logger', 'timeout', 'socket', 'openssl', 'forwardable', 'uri', 'date' + # here for the parse Config makes of the instance url and the escaping of + # record ids. None of the four is named in the signatures the gem + # publishes - see SSL_ERRORS in sig/zammad_api/transport.rbs and + # sig/vendor/internal.rbs - so this does not add anything a consumer has + # to load. + library 'json', 'logger', 'timeout', 'socket', 'openssl', 'forwardable', 'uri' configure_code_diagnostics do |hash| # Default keyword-argument hashes such as `attributes = {}` cannot be diff --git a/examples/error_handling.rb b/examples/error_handling.rb index 9af37ef..1854ab4 100755 --- a/examples/error_handling.rb +++ b/examples/error_handling.rb @@ -59,7 +59,7 @@ puts "client error: #{e.status}" rescue ZammadAPI::ServerError => e # any 5xx, including an HTML proxy page puts "server error: #{e.status}" -rescue ZammadAPI::TransportError => e # no whole answer arrived, retries spent +rescue ZammadAPI::TransportError => e # no answer arrived, retries spent puts "transport error: #{e.message}" end diff --git a/examples/manual_batches.rb b/examples/manual_batches.rb index 2fab1c0..b202365 100755 --- a/examples/manual_batches.rb +++ b/examples/manual_batches.rb @@ -57,12 +57,9 @@ # 3. A resumable page loop --------------------------------------------------- # # Own the page number when the job has to survive being interrupted. The -# loop ends on a page with nothing on it, and not on a page short of -# PER_PAGE: that is the size asked for, and what counts is the size served. -# An instance that serves 25 where 50 were asked for hands back a "short" -# page every time, and a loop that stops on one has stopped after the first -# with the checkpoint cleared. `find_each` and `in_batches` learn the size -# from the first page; here one more request at the end does the same job. +# loop ends on a page with nothing on it rather than on one short of +# PER_PAGE, at the cost of one more request at the end, so an instance that +# serves fewer records than were asked for is still read to the end. # # A page number is a position, not a record, so it only resumes where it left # off while nothing before it goes away. Delete one ticket from a page already diff --git a/examples/quickstart.rb b/examples/quickstart.rb index 357d41a..338c9f8 100755 --- a/examples/quickstart.rb +++ b/examples/quickstart.rb @@ -14,7 +14,7 @@ # `me` answers for any account. `client.version` would name the Zammad # version as well, but Zammad serves it to administrators only, and an # agent's token is answered with ZammadAPI::AuthorizationError. -puts "connected to #{client.config.redacted_url} as #{client.me.email}" +puts "connected to #{client.config.url} as #{client.me.email}" # Create a ticket together with its first article. ticket = client.tickets.create( diff --git a/lib/zammad_api/associations.rb b/lib/zammad_api/associations.rb index 31fa295..a94869a 100644 --- a/lib/zammad_api/associations.rb +++ b/lib/zammad_api/associations.rb @@ -32,107 +32,57 @@ def initialize(record) end def inspect - "#<#{Proxy.name} #{@record.class.name} id=#{@record.id.inspect} #{@record.class.associations.keys.join(', ')}>" + "#<#{Proxy.name} #{@record.class.name} id=#{@record.id.inspect} #{associations.keys.join(', ')}>" end + # Drops the records read so far, so the next read follows the record's + # current foreign keys. + # + # @api private + # @return [void] + def forget + @cache = {} + end + + def method_missing(name, *args) + spec = associations[name] + return super if spec.nil? || !args.empty? + + spec[:type] == :belongs_to ? belongs_to_target(name, spec) : has_many_target(name, spec) + end + + def respond_to_missing?(name, include_private = false) = associations.key?(name) || super + private - # Memoized: the record an id points at does not change under the caller, - # and an unmemoized reader would turn a loop over tickets into a request - # per ticket per mention. The record empties the memo through - # {#forget_targets} when what it was resolved from may no longer hold. - # - # What is resolved goes into the memo this call began with, not the one - # that is current once the request is back. They differ where the - # record was written to while the request was out - by a logger or a - # middleware of the caller's that reaches the record, or by another - # thread - and {#forget_targets} has swapped the memo for an empty one. - # Written to the current memo, the user fetched for `customer_id` 7 - # became the memoized answer for a record that by then says 9, and - # stayed it until the next write. - def belongs_to_target(name, class_name, foreign_key) - refuse_destroyed!(name) - memo = @cache - return memo[name] if memo.key?(name) - - id = @record[foreign_key] - # {Resources::Base.fetch_one} rather than a ResourceProxy built for the - # one call: {Client#setup} builds and freezes one proxy per resource so - # that callers get one proxy per resource, and a reader here that built - # a fresh one per association turned a walk over ten thousand tickets - # reading two associations each into twenty thousand objects that exist - # for a single method call. It is the read {ResourceProxy#find} makes - # too, so there is one of it rather than one here and one there. - memo[name] = id.nil? ? nil : resolve(class_name).fetch_one(@record.transport, id) + def associations = @record.class.associations + + # The record a foreign key points at, read once and kept: nil when the + # key is nil. + def belongs_to_target(name, spec) + return @cache[name] if @cache.key?(name) + + id = @record[spec[:foreign_key]] + @cache[name] = id.nil? ? nil : resolve(spec[:class_name]).fetch_one(@record.transport, id) end - # Deliberately not memoized: a list can grow while the record is held, - # and +ticket.related.articles+ after +ticket.add_article(...)+ has to show - # the article that was just added. - # - # The path proc is handed the escaped id rather than the record, so that - # a declaration cannot paste a raw id into a path. One that did resolved - # `related.articles` on a record carrying `id: "1/../../users"` onto the - # users endpoint, the same way an unescaped {Resources::Base#member_path} - # used to - and a proc is exactly where that is easy to forget. - def has_many_target(name, class_name, path) - refuse_destroyed!(name) + # The list an association endpoint serves, read anew on every call. + def has_many_target(name, spec) raise Error, "#{@record.class.name} has no id, so it has no #{name} to read; save it first" if @record.id.nil? - target_class = resolve(class_name) + target_class = resolve(spec[:class_name]) operation = "get #{name}" - - response = @record.transport.get( - path.call(Transport.escape_path_segment(@record.id)), + response = @record.transport.get( + spec[:path].call(Transport.escape_path_segment(@record.id)), operation: operation, resource_class: target_class, query: { expand: true } ) - records = response.decoded(:array, operation: operation, resource_class: target_class) - records.map { target_class.from_response(@record.transport, it) } - end - # Drops every resolved target, so that the next read fetches it again. - # - # Called by the record, which keeps one proxy for as long as it lives - # and empties it on a save, a reload, a destroy and a write to a foreign - # key. It used to drop the proxy and build another on the next call to - # {Resources::Base#related}, which reached only the callers that asked - # again: `related = ticket.related`, the natural thing to write before - # reading two associations, kept the proxy that had been dropped, and - # after `ticket.customer_id = 9` or a reload `related.customer` went on - # answering with the user it had resolved before. A memo can only be - # emptied where it is held, so it is emptied here. - # - # Replaced rather than cleared, so that a lookup still on the wire has - # nowhere to put what it resolved from the value before: see - # {#belongs_to_target}. - def forget_targets - @cache = {} + response.decoded(:array, operation: operation, resource_class: target_class).map { target_class.from_response(@record.transport, it) } end - # Refuses to read through a record that was destroyed. - # - # {Resources::Base#related} asks the same question, but a proxy handed - # out before the destroy is already past that door: it answered from - # its memo, and `articles` requested the articles of a ticket that is - # gone. - def refuse_destroyed!(name) - return if !@record.destroyed? - - raise Error, "#{@record.class.name} #{@record.id} was destroyed, there is nothing to read #{name} from" - end - - # The target is named rather than referenced so that resources may point - # at each other without a load order between their files. The name comes - # from a declaration in code - this gem's, or a resource class a caller - # wrote - and never from data. - # - # A resource of this gem is named on its own, +'User'+, and wins: an - # application is likely to have a +User+ of its own at the top level, - # and that is not what a ticket's customer is. Any other name is read - # from the top level, so that a resource a caller declares can point at - # another of theirs: +belongs_to :role, class_name: 'Acme::Role'+. + # A resource of this gem by its own name, or any class by its full name. def resolve(class_name) return Resources.const_get(class_name, false) if Resources.const_defined?(class_name, false) diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb index b8242b6..6e7cb00 100644 --- a/lib/zammad_api/attribute_access.rb +++ b/lib/zammad_api/attribute_access.rb @@ -12,99 +12,38 @@ module ZammadAPI # through +method_missing+. A reader for an attribute the record does not # carry raises +NoMethodError+; {#[]}, {#fetch} with a default, and {#key?} # are the readers for an attribute that may be absent. - # - # This also carries the object protocols a record is expected to answer: - # {#==} and {#hash} identify a record by its id and the Zammad it came - # from, {#deconstruct_keys} makes - # one matchable with +case/in+, and {#to_json} serializes its attributes. module AttributeAccess - # Suffixes that mark a method call as a predicate or bang method rather - # than an attribute, so that typos like +save!+ still raise NoMethodError. - NON_ATTRIBUTE_SUFFIXES = %w[! ?].freeze - - # What a writer for an attribute is named: a plain identifier and an `=`. - # - # Ending in `=` is not enough, because Ruby's operators do too. `record[:x] - # = 1` reaches `method_missing` as `:[]=` and used to stage an attribute - # literally called `[]` whose value was the index - the write was lost, no - # error was raised, and the next `save` sent `{"[]": "x"}` to Zammad. - # `record <= 5` did the same for an attribute called `<`. + # What a writer for an attribute is named: a plain identifier and an `=`, + # so that operators such as +<=+ are not taken for one. ATTRIBUTE_WRITER = /\A[a-zA-Z_]\w*=\z/ private_constant :ATTRIBUTE_WRITER - # All known attributes, deeply frozen. - # - # Writing through this hash would change what the record reports without - # staging a change, so the next +save+ would not send it. {#to_h} returns a - # copy that is safe to modify; an attribute writer is the way to stage one. + # All known attributes, deeply frozen. {#to_h} returns a copy that is safe + # to modify; an attribute writer is the way to stage a change. # - # An {Attributes}, here and for every Hash inside it: a Hash that prints - # with its credentials blanked, since the error Ruby raises for a write - # to a frozen Hash prints it. - # - # @return [Attributes{Symbol => Object}] + # @return [Hash{Symbol => Object}] attr_reader :attributes # @param key [Symbol, String] # @return [Object, nil] def [](key) = attributes[key.to_sym] - # Stages an attribute by name, the writer matching {#[]}. - # - # Defined rather than left to `method_missing`, which saw `:[]=` as a - # writer for an attribute called `[]` and staged the index as its value. - # A read-only record refuses this the way it refuses any other write, and - # {#respond_to?} says so before it is called. + # Stages a change to an attribute, like the attribute writer does. # # @param key [Symbol, String] # @param value [Object] # @return [Object] the staged value - # @raise [Error] when the attribute cannot be staged, such as +id+, or - # when the record was destroyed - # @raise [NoMethodError] when the record is read-only def []=(key, value) write_attribute(key.to_sym, value) end + # Reads an attribute the way +Hash#fetch+ does. + # # @param key [Symbol, String] - # @param default [Object] returned instead of raising - # @yieldparam key [Symbol] called instead of raising # @return [Object] - # @raise [ArgumentError] when more than one fallback was given - # @raise [KeyError] when the attribute is absent and no fallback was given - def fetch(key, *default) - # Hash#fetch refuses a third argument, and so does this: collecting the - # fallback with a splat and reading `default.first` accepted - # `fetch(:a, :b, :c)` - a multi-key read that this has never been - and - # answered it with `:b`. A method whose whole point is that a missing - # attribute is an error has no business swallowing a mistyped call. - raise ArgumentError, "wrong number of arguments (given #{default.size + 1}, expected 1..2)" if default.size > 1 - - # Hash#fetch warns for this and then ignores the default, so this does - # too rather than silently picking one of the two fallbacks a caller - # cannot have meant to pass together. - # - # `uplevel` so that this reads like the warning it mirrors: Hash#fetch - # names the line that made the call, and a bare Kernel#warn named - # nothing at all - neither the call site nor the library it came from, - # which in an application with several such calls is everything the - # reader needs. Kernel#warn writes the `warning: ` prefix itself when - # given `uplevel`, so the message must not carry its own. - # - # Nothing here has to consult $VERBOSE. Kernel#warn is already silent - # when warnings are off, so `ruby -W0` and `$VERBOSE = nil` quiet this - # the same way they quiet Hash#fetch's own warning. - warn('block supersedes default value argument', uplevel: 1) if block_given? && !default.empty? - - symbol = key.to_sym - # An explicit &block argument cannot be resolved against Hash#fetch's - # overloads by the type checker, so the block is forwarded with yield. - # rubocop:disable-next Style/ExplicitBlockArgument - return attributes.fetch(symbol) { |missing| yield(missing) } if block_given? - return attributes.fetch(symbol, default.first) if !default.empty? - - attributes.fetch(symbol) - end + # @raise [KeyError] when the record does not carry the attribute and + # neither a default nor a block is given + def fetch(key, *default, &block) = attributes.fetch(key.to_sym, *default, &block) # steep:ignore UnresolvedOverloading # @return [Boolean] def key?(key) = attributes.key?(key.to_sym) @@ -131,24 +70,8 @@ def id = attributes[:id] def deconstruct_keys(keys) = keys.nil? ? attributes : attributes.slice(*keys) # Whether +other+ is the same Zammad record: the same class, carrying the - # same id, read from the same Zammad. - # - # The last of those is the URL the client was configured with. An id is - # only unique within one installation, and a script that reads two of - # them - a migration, a sync - holds ticket 1 of each: compared by class - # and id alone they were one record, so `uniq` dropped one of the two and - # a Hash keyed by record handed back the other instance's value. Two - # clients for one URL, or one client and its {Client#on_behalf_of} scope, - # still read the same record. - # - # A record with no id is equal only to itself, because two unsaved records - # are two records waiting to be created however alike their attributes - # are. That also means the first save of a record changes its {#hash}, so - # one used as a Hash key before being saved has to be rehashed after. - # - # @example - # client.tickets.find(1) == client.tickets.find(1) # => true - # [client.tickets.find(1), client.tickets.find(1)].uniq.size # => 1 + # same id, read from the same Zammad. A record with no id is equal only + # to itself. # # @param other [Object] # @return [Boolean] @@ -165,222 +88,48 @@ def ==(other) # Consistent with {#==}, so that records can be deduplicated with +uniq+, # collected in a +Set+ and used as Hash keys. # - # The class is part of the digest because an id is only unique within one - # kind of record: ticket 1 and user 1 are different records. The - # installation is part of it for the same reason one level up. - # # @return [Integer] def hash id.nil? ? super : [self.class, installation, id].hash end - # The attributes, for a JSON encoder. - # - # Named the way ActiveSupport and its encoders expect, so that a record - # nested inside a structure being serialized renders as its attributes. - # - # With the two options those encoders hand on, +only:+ and +except:+. - # They were dropped here: `user.as_json(except: [:password])` answered - # with the password, as did a record inside a Hash or a collection that - # was serialized with the option, while `user.to_json(except: - # [:password])` left it out under ActiveSupport, by way of the Hash it - # is written from. A name is taken as a Symbol or a String, the way - # ActiveModel takes one: the attributes are keyed by Symbols, and a name - # given as a String filtered nothing in {#to_json} either. - # - # @example - # user.as_json(except: [:password]) - # user.as_json(only: %w[id login]) - # - # @param options [Hash, nil] +only:+ or +except:+ with attribute names; - # +only:+ is the one read where both are given - # @return [Hash{Symbol => Object}] - def as_json(options = nil) - attributes = to_h - return attributes if !options.is_a?(Hash) - - only = options[:only] - given = only || options[:except] - return attributes if !given - - names = Array(given) #: Array[untyped] - names = names.map { it.to_s.to_sym } - only ? attributes.slice(*names) : attributes.except(*names) - end + # @return [Hash{Symbol => Object}] the attributes, for a JSON encoder + def as_json(*) = to_h - # Without this, a record would serialize as its +to_s+, because that is - # what +Object#to_json+ falls back to. - # - # Written from {#as_json} where it is given options, so that the two - # leave out the same attributes whichever is asked. The two options are - # applied here and not handed on: they name attributes of the record, - # ActiveSupport would apply them again to every Hash an attribute holds, - # and the generator of the json gem refuses a keyword it does not know. - # - # @example - # client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}" - # - # @param state [JSON::State, Hash, nil] passed by +JSON.generate+ when a - # record is nested in a structure it is serializing, or the options - # {#as_json} reads beside any the generator does # @return [String] the attributes as a JSON object - def to_json(state = nil) - return to_h.to_json(state) if !state.is_a?(Hash) - - generator_options = state.except(:only, :except) #: untyped - as_json(state).to_json(generator_options) - end + def to_json(*args) = to_h.to_json(*args) # steep:ignore UnexpectedPositionalArgument def method_missing(name, *args) identifier = name.to_s - return super if NON_ATTRIBUTE_SUFFIXES.any? { identifier.end_with?(it) } - return write_attribute(identifier.delete_suffix('=').to_sym, args.first) if ATTRIBUTE_WRITER.match?(identifier) - - if attributes.key?(name) - # A reader takes no arguments, and says so as one written out - # would. They were never looked at: `ticket.state('closed')` - # answered "open" and changed nothing, and the call 1.x added an - # article with, `ticket.article(body: '...')`, answered with the - # article already staged on a ticket that had one, sent nothing - # and raised nothing. Keywords arrive here as one Hash, so they - # count as one. A block is not asked about, as it is not for any - # method that does not use one. - raise ArgumentError, reader_arguments_message(name, args.size) if !args.empty? - - return attributes[name] - end - - # An attribute the record does not carry used to read as nil, which made - # `ticket.titel` a silent nil that flowed on into whatever was written - # with it - and left this module the one place in the gem that answers a - # question it cannot answer instead of saying so. It also put - # `respond_to?` and the call itself at odds: `respond_to?(:titel)` was - # false and `method(:titel)` raised NameError while `ticket.titel` - # worked, so generic code that asks before it calls - a serializer, a - # delegator, `try` - was told the reader did not exist. - # - # Built rather than left to `super`, so that the message can name what - # to reach for instead, while `name` and `receiver` stay what a bare - # NoMethodError would have carried. - # - # The steep:ignore is for `name`: NameError.new takes a Symbol there and - # NoMethodError#name answers with one, while the core signature - # describes the parameter as a String. - raise NoMethodError.new(unknown_attribute_message(name), name, args, receiver: self) # steep:ignore ArgumentTypeMismatch - end - - # `[]=` is a defined method, so `respond_to_missing?` never sees it and a - # read-only record answered true for the one writer it has while answering - # false for every named one - then raised NoMethodError when it was called. - # That is the invariant the writer branch below is conditional for: generic - # code asks before it writes, and a record that claims a writer it would - # refuse leads it straight into the exception it was checking to avoid. - # - # Compared as a String, because `respond_to?` takes either spelling and - # Ruby does not normalise the argument before it reaches here. Compared to - # the Symbol alone, `respond_to?('[]=')` fell through to the definition - # and answered true on a record that refuses every write - the same wrong - # answer this method exists to prevent, reached by the other spelling. - # rubocop:disable-next Style/OptionalBooleanParameter -- Ruby's own signature - def respond_to?(name, include_private = false) - return writable_attributes? if name.to_s == '[]=' + return write_attribute(identifier.delete_suffix('=').to_sym, args.first) if ATTRIBUTE_WRITER.match?(identifier) && args.size == 1 + return attributes[name] if args.empty? && attributes.key?(name) super end def respond_to_missing?(name, include_private = false) identifier = name.to_s - return false if NON_ATTRIBUTE_SUFFIXES.any? { identifier.end_with?(it) } - # Not an unconditional true: a read-only record that claimed a writer and - # then raised NoMethodError when one was called would defeat the point of - # asking, and lead generic code - serializers, form binders, - # assign_attributes loops - straight into the exception it was checking - # to avoid. - return writable_attributes? && attribute_writable?(identifier.delete_suffix('=').to_sym) if ATTRIBUTE_WRITER.match?(identifier) + return writable_attributes? if ATTRIBUTE_WRITER.match?(identifier) attributes.key?(name) || super end protected - # Which Zammad this record was read from, for {#==} and {#hash}. + # The Zammad the record was read from, for {#==}: an id is only unique + # within one installation. # - # Overridden by the records that hold a transport, with the URL it is - # configured for. That is the URL as it was written, not the host it - # resolves to, so two spellings of one instance count as two: nothing - # here can know better, and telling one installation apart from itself - # only costs a duplicate, where taking two for one loses a record. - # - # Protected, because it is asked of the other record and of nobody else. - # - # @return [String, nil] nil for a record that has no transport + # @return [String, nil] def installation = nil private - # Why an attribute is missing is worth saying, because the two reasons - # lead somewhere quite different: a name that is simply wrong, and a - # record Zammad served less of than it holds. The second is the same fact - # {Resources::Base#no_id_message} and {Resources::Base#write_attribute} - # are written around - Zammad reduces the object it serializes for a - # client whose user may not see the whole record - and it is not - # something the spelling of the call can show. - def unknown_attribute_message(name) - # Sorted by the name rather than by the key, because a key that could - # not become a Symbol is left as it arrived - {DeepCopy.symbolize} says - # so - and `[:name, 1].sort` raises, which would replace this message - # with an ArgumentError from inside the method that explains it. - carried = attributes.keys.sort_by(&:to_s).join(', ') - - "undefined attribute #{name} for #{self.class.name}. This record carries " \ - "#{attributes.empty? ? 'no attributes at all' : carried}. " \ - "Check the spelling, or read it with [#{name.inspect}] or fetch(#{name.inspect}, nil) where it may be absent. " \ - 'Zammad also serves a reduced object where the authenticated user may not see the whole record, so an ' \ - 'attribute the record has in Zammad can still be missing here - check what this client may read.' - end - - # What a reader called with arguments raises with. - # - # It opens the way Ruby's own message for the mistake does, so that it - # reads as that mistake, and then says what Ruby cannot: that the name - # is an attribute, and where a value for it goes on a record that takes - # one. A record may add what it knows about a name: see - # {Resources::Ticket#reader_arguments_message}. - # - # @param name [Symbol] - # @param given [Integer] how many arguments the reader was called with - # @return [String] - def reader_arguments_message(name, given) - message = "wrong number of arguments (given #{given}, expected 0): #{name} reads the attribute of that name and takes no arguments." - return message if !writable_attributes? || !attribute_writable?(name) - - "#{message} To change it, write it with #{name} = ... or update(#{name}: ...)." - end - - # Whether this record stages attribute writes, so that {#respond_to?} and - # calling a writer agree. def writable_attributes? = false - # Whether one particular attribute may be written. Overridden by records - # that refuse one: a record that claimed `id=` and then raised when it was - # called would defeat the point of asking, which is the whole reason the - # writer branch above is not an unconditional true. - def attribute_writable?(_key) = true - - # Overridden by writable records; read-only ones fall back to NoMethodError. def write_attribute(key, _value) raise NoMethodError, "#{self.class.name} attributes are read-only (tried to set #{key})" end - # Recursively converts string keys to symbols, including inside arrays, so - # that user supplied attributes behave the same as decoded responses, and - # freezes the result. See {DeepCopy} for why the walk lives there. - # - # Its inverse, {DeepCopy.writable_copy}, is called where it is needed and - # has no helper here. It had one, named `deep_dup`, and a private method - # of that name answers in place of the public one ActiveSupport gives - # every object and calls on whatever a Hash or an Array holds: so - # `{ticket: ticket}.deep_dup` raised NoMethodError in a Rails app. def frozen_attributes(value) = DeepCopy.frozen_copy(value, symbolize_keys: true) end end diff --git a/lib/zammad_api/attributes.rb b/lib/zammad_api/attributes.rb deleted file mode 100644 index b985251..0000000 --- a/lib/zammad_api/attributes.rb +++ /dev/null @@ -1,80 +0,0 @@ -# frozen_string_literal: true - -module ZammadAPI - # The Hash a record hands its attributes out in. - # - # A Hash in every way but how it is printed, which is with the value under - # every key that names a credential blanked, the way - # {Resources::Base#inspect} prints a record. - # - # It is frozen where it is handed out, and Ruby quotes a frozen object in - # the error for a write to it. `user.attributes[:vip] = true`, which is how - # 1.x staged a change, raised `FrozenError: can't modify frozen Hash: - # {login: "jane", password: "hunter2"}`, and the message of an error is - # what a log and an error tracker keep. The record printed its attributes - # blanked, and the Hash it handed out printed itself. - # - # Only the printing. Every value reads as it is, and +to_h+, +to_json+ and - # YAML write them out, because handing them over is what a record is for. - # {#to_h} is a plain Hash at every depth. One made by +slice+ or +select+ - # is plain itself and holds the Hashes inside it as they are, which are of - # this class. - # - # One thing does ask for the class: a JSON encoder that takes nothing but - # the core types, `JSON.generate(value, strict: true)` and a `JSON::Coder` - # without a block, refuses a subclass of Hash by its name. {#to_h} is what - # to hand it. - # - # What it holds is not covered where that is not a Hash. A String cannot - # be told how to print, so `user.attributes[:password] << 'x'` still - # quotes the password it was asked to change, and an Array prints what is - # in it. - # - # @example - # user.attributes[:vip] = true - # # FrozenError: can't modify frozen ZammadAPI::Attributes: {login: "jane", password: "[REDACTED]"} - class Attributes < Hash - # @return [String] the Hash as Ruby prints one, credentials blanked - def inspect = Transport.redact(self).inspect - - # +Hash#to_s+ is +Hash#inspect+ under a second name, and stays the one - # Hash defines unless it is named again here. - alias to_s inspect - - # A plain Hash of plain Hashes, the caller's own to modify. - # - # +Hash#to_h+ answers with a plain Hash that holds what this one holds, - # and every Hash inside the attributes of a record is of this class too. - # So `user.attributes.to_h` was plain as far as its first nested Hash, - # and a strict JSON encoder refused it there as it refuses the - # attributes themselves: "ZammadAPI::Attributes not allowed in JSON", - # for what 1.x handed out as Hashes. What {Resources::Base#to_h} answers - # for the whole record, this answers for any part of it: - # `user.preferences.to_h`. - # - # With a block it is +Hash#to_h+, which builds a plain Hash from the - # pairs the block answers. - # - # The steep:ignore is for the two shapes of the method in one body: the - # checker holds each branch to both of them. - # - # @return [Hash] a writable deep copy - def to_h(&block) = block ? super : DeepCopy.writable_copy(self) # steep:ignore MethodBodyTypeMismatch - - # What +pp+ prints, which is not what {#inspect} answers for a Hash. - # - # @param printer [PP] - # @return [void] - def pretty_print(printer) = printer.pp(Transport.redact(self)) - - # Written to YAML as the plain mapping a Hash is. - # - # Psych tags a subclass of Hash with its class, and refuses to load a - # tag it was not told to expect, so `record.attributes.to_yaml` would - # have stopped loading with +YAML.load+. - # - # @param coder [Psych::Coder] - # @return [void] - def encode_with(coder) = coder.represent_map(nil, self) - end -end diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index 2903458..3e6a07e 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -26,13 +26,6 @@ module ZammadAPI # ) class Client # Maps the reader methods of this client to their resource classes. - # - # Plural, because what a reader hands back stands for every record of - # its kind: a {ResourceProxy} is +Enumerable+ over all of them, so - # +client.tickets.each+ and +client.tickets.first(5)+ say what they do, - # where the singular the readers had in 1.x read as if it acted on one - # ticket. That name dates from when a proxy was only a dispatcher for - # +find+ and +create+. RESOURCES = { groups: Resources::Group, organizations: Resources::Organization, @@ -81,25 +74,10 @@ class Client # Builds a client from the environment. # - # Reads {ENV_OPTIONS}, so a script needs no configuration of its own. - # Anything passed in wins over the environment, and every other option - # keeps its default. That includes the way to authenticate: passing - # +user:+ and +password:+, or a token, replaces whichever credentials the - # environment holds rather than sitting beside them. A variable that is - # empty, or holds nothing but whitespace, counts as unset, and - # +ZAMMAD_HTTP_TOKEN+ wins over +ZAMMAD_TOKEN+ if both are set. An - # environment that sets more than one way to authenticate - a token and - # a user with a password - is refused like any other configuration that - # does, unless an argument names the one to use. - # - # Only an empty variable used to count as unset. One set to a space, - # which is what `export ZAMMAD_HTTP_TOKEN=" "` and a blank line of an - # env file leave behind, was taken for a value: beside a valid - # +ZAMMAD_TOKEN+ it took that token's place and was then read as no - # token at all, "missing user in config" for an environment that held a - # token, and a +ZAMMAD_USER+ of a space beside a token was a second way - # to authenticate. A password of nothing but spaces is given as - # +password:+. + # Reads {ENV_OPTIONS}; a variable that is empty or blank counts as unset, + # and +ZAMMAD_HTTP_TOKEN+ wins over +ZAMMAD_TOKEN+. Anything passed in wins + # over the environment, and credentials passed in replace the ones the + # environment holds. # # @example # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=secret ruby report.rb @@ -114,9 +92,7 @@ class Client def self.from_env(**overrides) from_environment = ENV_OPTIONS.filter_map do |name, option| value = ENV.fetch(name, nil) - # Of the bytes, as {Config.blank_token?} asks a token: a variable - # may hold a byte that is not text. - [option, value] if !value.to_s.b.strip.empty? + [option, value] if !value.to_s.strip.empty? end options = Config.merge_options(from_environment.to_h, overrides) @@ -126,18 +102,10 @@ def self.from_env(**overrides) end # Builds a client from a {Config} that is already validated and a - # transport that is already built. - # - # The public constructor turns options into a Config and a Config into a - # Transport, and building a Transport means building a Faraday stack: - # authentication, JSON, the retry middleware, adapter resolution. Anything - # holding a transport of its own - {Test} - threw all of that away one - # line later, and paid for it again for every stand-in a suite builds. - # This is the way in for those, and the reason there is no public - # `with_transport` to swap one in after the fact. + # transport that is already built, for {Test}. # # @api private - # @param config [Config] an already validated configuration + # @param config [Config] # @param transport [Transport] anything with a {Transport} interface # @return [Client] def self.build(config, transport) @@ -157,16 +125,8 @@ def initialize(**options) setup(config, Transport.new(config)) end - # The proxy for a resource, by name or by class. - # - # A class is the way to the parts of the API this gem does not model. - # {Resources::Base} is built to be subclassed - a path, and whatever the - # endpoint needs said about it - and a proxy for such a class gives its - # records everything the modelled ones have: pagination, +find_by+, - # change tracking, +save+. 1.x reached any subclass through +const_get+ - # on a name a caller supplied, and 2.0 closed that, which left raw - # requests as the only way to the rest of the API; this is the same - # reach, with the class handed over rather than looked up. + # The proxy for a resource, by name or by class. A class is the way to + # the parts of the API this gem does not model. # # @example A resource this gem does not model # class Role < ZammadAPI::Resources::Base @@ -174,7 +134,6 @@ def initialize(**options) # end # # client.resource(Role).each { |role| puts role.name } - # client.resource(Role).find(2).update(note: 'Reviewed') # # @param name [Symbol, String, Class] a key of {RESOURCES}, or a subclass # of {Resources::Base} @@ -202,30 +161,18 @@ def resource_names = RESOURCES.keys # @return [Resources::User] # @raise [AuthenticationError] when the credentials are not valid def me - response = @transport.get( - # Derived from the resource that declares the endpoint, not spelled - # out again: `member_path` exists for the same reason, and a path kept - # in two places is one that moves in one of them. Spelled out here, - # `client.users` would follow the users endpoint wherever it went and - # `client.me` would keep requesting the old one. + operation = 'find current user' + response = @transport.get( "#{Resources::User.resource_path}/me", - operation: 'find current user', + operation: operation, resource_class: Resources::User, query: { expand: true } ) - Resources::User.from_response( - @transport, - response.decoded(:object, operation: 'find current user', resource_class: Resources::User) - ) + Resources::User.from_response(@transport, response.decoded(:object, operation: operation, resource_class: Resources::User)) end # The version of the Zammad instance, not of this gem — that is - # {ZammadAPI::VERSION}. - # - # Zammad serves it to administrators only: its VersionControllerPolicy - # permits +admin+ and nothing else. An agent's or a customer's - # credentials are answered with a 403, so to check that a client can - # reach Zammad at all, ask {#me}, which every account may. + # {ZammadAPI::VERSION}. Zammad serves it to administrators only. # # @example # client.version # => "6.4.0" @@ -234,47 +181,30 @@ def me # @raise [AuthorizationError] when the account is not an administrator def version response = @transport.get('api/v1/version', operation: 'get the Zammad version') - version = response.decoded(:object, operation: 'get the Zammad version')[:version] - version&.to_s + response.decoded(:object, operation: 'get the Zammad version')[:version]&.to_s end # @!group Raw requests - # Performs a +GET+ against any endpoint of the Zammad API. - # - # The resource classes cover a part of the API; these four methods reach - # the rest of it without giving up authentication, retries, credential - # redaction, JSON decoding or the error classes. - # - # +headers:+ is here because an escape hatch that cannot set one does not - # reach an endpoint that needs one. What it will not set is the two - # headers this client owns - see the +headers+ parameter below. + # Performs a +GET+ against any endpoint of the Zammad API, with the + # client's authentication, retries, JSON decoding and error classes. # # @example An endpoint this gem does not model # client.get('api/v1/roles').body # # => [{id: 1, name: "Admin", ...}, ...] # - # @example Reading a response header - # client.get('api/v1/tickets').headers['content-type'] - # # @example An endpoint that needs a header of its own # client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) # # @param path [String] path relative to {Config#url}; a leading slash is - # ignored, so paths can be pasted from the Zammad documentation. An - # absolute URL is refused, so the client's credentials only ever go to - # the instance it was configured for. It is written the way a URL is: - # a space or a character outside ASCII has to be percent-encoded. + # ignored, and an absolute URL is refused, so the client's credentials + # only ever go to the instance it was configured for # @param query [Hash, nil] query string parameters - # @param headers [Hash, nil] request headers. Names are case-insensitive, - # and +Authorization+ and +From+ are refused: the first is what the - # client's credentials are for, the second is what {#on_behalf_of} sets. + # @param headers [Hash, nil] request headers # @return [Response] # @raise [ResponseError] for any non-2xx response # @raise [TransportError] when the request could not be completed - # @raise [ArgumentError] for a header this client sets itself, a header - # name that is not one, a value that is not text, a path that is an - # absolute URL, or one that cannot be read as a URL + # @raise [ArgumentError] for a path that is an absolute URL def get(path, query: nil, headers: nil) = raw(:get, path, query: query, headers: headers) # Performs a +POST+ against any endpoint of the Zammad API. @@ -317,18 +247,10 @@ def delete(path, query: nil, headers: nil) = raw(:delete, path, query: query, he # Returns a new client with some configuration options changed. # # The options are re-validated, and any {#on_behalf_of} scope is carried - # over. The original client keeps its own connection and settings. - # - # Naming credentials replaces the ones this client has, whichever kind - # they were: +with(oauth2_token: 'x')+ on a client built with an access - # token authenticates with the OAuth2 token alone. - # - # The transport derives from the current one rather than being built from - # scratch, so a client wired to a stand-in stays wired to it. + # over. Naming credentials replaces the ones this client has. # # @example A longer timeout for one bulk job # bulk = client.with(timeout: 300, retries: 5) - # bulk.tickets.all.each { |ticket| archive(ticket) } # # @param options [Hash] any option accepted by {Config} # @return [Client] @@ -338,10 +260,7 @@ def with(**options) dup.send(:setup, derived_config, @transport.with_config(derived_config)) end - # Performs requests on behalf of another user. - # - # Returns a new client rather than mutating this one, so the original - # client is unaffected and both can be used concurrently. + # Performs requests on behalf of another user, through a new client. # # @example Scoped client # support = client.on_behalf_of('agent@example.com') @@ -352,58 +271,24 @@ def with(**options) # scoped.tickets.find(1) # end # - # An identifier that names nobody is refused. Zammad skips a +From+ - # header with nothing in it, and a nil sent none at all, so - # +client.on_behalf_of(current_user&.login)+ with nobody signed in - # handed back a client that looked scoped and was not: every request - # ran with the rights of the account the client authenticates as, and - # a list read through it held everything that account can see. No - # request failed, so nothing said the scope was missing. - # # @param identifier [String, Integer] login, email address or user id # @yieldparam scoped [Client] # @return [Client] when no block is given, otherwise the block's value - # @raise [ArgumentError] for an identifier that is nil, empty or blank, - # or neither text nor an Integer, such as the record of the user + # @raise [ArgumentError] for an identifier that is nil or blank, which + # would quietly leave the requests unscoped def on_behalf_of(identifier) - # Nil is what a transport takes for no scope, so it is refused here. - # The rest is refused by the rule every transport is meant to apply, - # applied here as well: Client.build takes anything with a transport's - # interface, and one that stored what it was given would send an empty - # From header for `on_behalf_of('')`. - raise ArgumentError, Transport.blank_on_behalf_of_message(identifier) if identifier.nil? - - scoped = dup.send(:setup, config, @transport.with_on_behalf_of(Transport.stringify_on_behalf_of(identifier))) + scoped = dup.send(:setup, config, @transport.with_on_behalf_of(Transport.on_behalf_of_header(identifier))) return scoped if !block_given? yield scoped end - # The scope is shown where there is one, so that a client acting for - # another user does not print as the one it was derived from. def inspect scope = @transport.on_behalf_of - "#<#{self.class.name} url=#{config.redacted_url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{scope.inspect}" if scope}>" + "#<#{self.class.name} url=#{config.url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{scope.inspect}" if scope}>" end - # The client for a JSON encoder: what {#inspect} says, and nothing else. - # - # ActiveSupport gives every object an +as_json+ that is its instance - # variables, and builds +to_json+ on it. For a client those are the - # configuration, the transport and the resource proxies, so in a Rails - # app +client.to_json+ - or a log line or an error report serializing - # something that holds the client - wrote the credentials through the - # first two, and then read every record of every resource through the - # third: a proxy is Enumerable, which is serialized as its elements. - # - # @return [Hash{Symbol => Object}] - def as_json(*) = Transport.description(config, @transport.on_behalf_of) - - # @param state [JSON::State, nil] passed by +JSON.generate+ - # @return [String] {#as_json} as a JSON object - def to_json(state = nil) = as_json.to_json(state) - def method_missing(name, *args) return super if CONVERSION_METHODS.include?(name) || name.to_s.end_with?('=', '!', '?') @@ -420,9 +305,6 @@ def raw(method, path, query: nil, body: nil, headers: nil) @transport.request( method, relative, - # Named by the path as it may be printed. The operation is in the - # message of every error the request raises, and a query string - # written into the path may carry a token. operation: "#{method.to_s.upcase} #{Transport.redact_path(relative)}", query: query, body: body, @@ -432,36 +314,18 @@ def raw(method, path, query: nil, body: nil, headers: nil) def unknown_resource_message(name) = "Unknown resource #{name}, available resources are: #{RESOURCES.keys.join(', ')}" - # One of the proxies built with this client for a class it models, and a - # new one for any other resource class. A new one each time, rather than - # a memo: the client is frozen in everything but name once it is built - - # see {#setup} - and a proxy holds nothing but the transport and the - # class. def proxy_for(resource_class) raise ArgumentError, "resource takes the name of a resource or a subclass of #{Resources::Base.name}, and #{resource_class.inspect} is neither" if !(resource_class <= Resources::Base) @resources.fetch(resource_class) do - # Asked for now, so that a class without a path is reported by the - # call that named it rather than by its first request. resource_class.resource_path ResourceProxy.new(@transport, resource_class) end end - # Everything a client is, in the one place all four ways of making one go - # through: {.new}, {.build}, {#with} and {#on_behalf_of}. Held apart, - # `build` restated `initialize`'s list of instance variables by hand, and - # the fourth one added to `initialize` would have left every client built - # for a test unset where it mattered. - # - # The proxies are built here rather than memoized on first use, because a - # client is documented - and used, in examples/concurrent_sync.rb - as - # immutable once built and safe to share between threads without locking. - # A memo populated by the first `client.tickets` in each worker is a write - # to shared state, and while CRuby's GVL makes it harmless, a contract - # that only holds on one implementation is not the contract that was - # written down. Building all seven up front costs an allocation each and - # keeps the object finished the moment it is handed back. + # Everything a client is, in the one place {.new}, {.build}, {#with} and + # {#on_behalf_of} go through. The proxies are built up front so that a + # client is immutable, and safe to share between threads, once built. # # @return [self] def setup(config, transport) diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb index 82aff8b..a1e65db 100644 --- a/lib/zammad_api/collection.rb +++ b/lib/zammad_api/collection.rb @@ -12,12 +12,10 @@ module ZammadAPI # {#each} walks every page until the server runs out of records, so it is # safe to iterate a collection larger than one page. {#first} reads one page # sized for what it was asked for, and +lazy+, +detect+ and the rest of - # +Enumerable+ stop the walk as soon as they have enough, so neither has to - # download everything. + # +Enumerable+ stop the walk as soon as they have enough. # - # An index that serves every record in one response and reads no +page+ is - # read in one request instead, where its resource says so: see - # {Resources::Base.paginated}. + # An index that serves every record in one response is read in one request + # instead, where its resource says so: see {Resources::Base.paginated}. # # @example Iterate every ticket # client.tickets.all.each { |ticket| puts ticket.title } @@ -36,65 +34,30 @@ module ZammadAPI class Collection include Enumerable - # The two directions a sort can run in, as Zammad spells them. - SORT_DIRECTIONS = %w[asc desc].freeze - private_constant :SORT_DIRECTIONS - - # What an attribute to sort by is named. Zammad takes several of them as - # one comma-separated parameter, so a name carrying a comma or a space - # would be read as something other than the one attribute it was. - SORT_ATTRIBUTE = /\A\w+\z/ - private_constant :SORT_ATTRIBUTE - # @api private # @param per_page [Integer, nil] records fetched per request, or nil for # as many as the endpoint serves - # @param search [Boolean] whether this is a search endpoint, which - # differs from an index in two ways a collection has to know about: it - # reports the size of the whole result, alone for +only_total_count+ - # and beside a page for +with_total_count+, and it can serve a page - # short of its size, or with nothing on it, before the last one - # @param sortable [Boolean] whether this endpoint reads +sort_by+ and - # +order_by+ - # @param unsortable_hint [String] what to do instead where it does not - # @param widens [Boolean] whether a walk may ask for a larger page than - # +per_page+ once one has come back with nothing on it, which a read - # sized by {#first} may and a batch size a caller chose may not: see - # {#widened} - # @param paginated [Boolean] whether this endpoint reads +page+ and - # +per_page+. One that does not serves every record in one response, - # and is read in one request: see {#read_whole} - def initialize(transport:, resource_class:, path:, operation:, max_per_page:, sortable:, unsortable_hint:, query: {}, per_page: nil, page: nil, search: false, widens: false, paginated: true) - @transport = transport - @resource_class = resource_class - @path = path - @operation = operation - @query = query - @max_per_page = max_per_page - @sortable = sortable - @unsortable_hint = unsortable_hint - # As many as the endpoint serves, unless a call asks for another size. - # - # A fixed default of 100 was the earlier answer, and it cost a request - # for every 100 records where the endpoint would have served 1000: a - # walk of the user index spent ten times the round trips it needed, and - # each of those is a TLS handshake of its own under Faraday's default - # adapter. The endpoint's own cap is the one number that is right for - # every resource without a caller looking each of them up - it is - # already what {#clamp_per_page} measures against. - # - # What that costs is a larger page held at once - a thousand expanded - # users rather than a hundred. {#first} is what made that affordable: - # the cheap-looking call that only wants a record or two now sizes its - # own page instead of taking them off the front of this one. - @per_page = clamp_per_page(per_page || max_per_page) - @page = page - @search = search - @widens = widens - @paginated = paginated - end - - # Yields every record, fetching further pages as needed. + # @param search [Boolean] whether this is a search endpoint, which can + # serve a short page before the last one and can count its results + # @param sortable [Boolean] whether this endpoint reads +sort_by+ and +order_by+ + # @param paginated [Boolean] whether this endpoint reads +page+ and +per_page+ + def initialize(transport:, resource_class:, path:, operation:, max_per_page:, sortable:, query: {}, per_page: nil, page: nil, search: false, paginated: true) + raise ArgumentError, 'per_page needs to be a positive integer' if per_page && (!per_page.is_a?(Integer) || !per_page.positive?) + + @transport = transport + @resource_class = resource_class + @path = path + @operation = operation + @query = query + @max_per_page = max_per_page + @sortable = sortable + @per_page = [per_page || max_per_page, max_per_page].min + @page = page + @search = search + @paginated = paginated + end + + # Yields every record, fetching pages as needed. # # @yieldparam record [Resources::Base] # @return [Enumerator] when no block is given @@ -105,128 +68,81 @@ def each(&block) self end - # Yields every record, like {#each}, with the page size set inline. + # Yields every record, fetching +batch_size+ records per request. # - # @param batch_size [Integer, nil] records fetched per request + # @param batch_size [Integer, nil] # @yieldparam record [Resources::Base] # @return [Enumerator] when no block is given def find_each(batch_size: nil, &block) return to_enum(:find_each, batch_size: batch_size) if !block - return with(per_page: page_size!(batch_size, 'batch_size')).find_each(&block) if batch_size + return with(per_page: batch_size).find_each(&block) if batch_size each(&block) end # Yields one array of records per page. # - # A batch is one response: what a request returned is what the block gets, - # so +of+ is what sizes it. For groups of a size the API knows nothing - # about, slice the records instead: +find_each.each_slice(12)+. - # - # An index that is not paginated has one response for every record, so - # there a batch is a slice of it, of the same size at most. - # # @param of [Integer, nil] records fetched per request # @yieldparam records [Array] # @return [Enumerator] when no block is given def in_batches(of: nil, &block) return to_enum(:in_batches, of: of) if !block - return with(per_page: page_size!(of, 'of')).in_batches(&block) if of + return with(per_page: of).in_batches(&block) if of - @paginated ? walk(&block) : read_whole(&block) + @paginated ? walk(&block) : fetch(nil).each_slice(@per_page, &block) self end # Returns a new collection limited to a single page. # - # +per_page+ decides how big that page is, and so which records it holds: - # +page(2, per_page: 50)+ is records 51 to 100. A size larger than the endpoint - # serves is refused rather than reduced, because reducing it moves the - # page: +page(3, per_page: 500)+ against an endpoint capping at 100 was sent as - # +page=3&per_page=100+ and answered with records 201 to 300 instead of - # 1001 to 1500. A job that checkpoints a page number then re-read what it - # had already handled and never reached the rest. - # # @example # client.tickets.all.page(2, per_page: 50).to_a # # @param number [Integer] one-based page number - # @param per_page [Integer, nil] records on the page, as many as the endpoint - # serves by default + # @param per_page [Integer, nil] records on the page, at most what the + # endpoint serves # @return [Collection] - # @raise [ArgumentError] for a page size the endpoint does not serve, or - # an endpoint that does not page at all + # @raise [ArgumentError] for a page number that is not a positive Integer, + # or an endpoint that does not page def page(number, per_page: nil) raise ArgumentError, 'page needs to be a positive integer' if !number.is_a?(Integer) || !number.positive? - raise ArgumentError, "#{@path} serves every record in one response and reads no page parameter, so page(#{number}) would hold all of them, whatever the number. Read them with each, or in groups with each_slice." if !@paginated - return with(page: number) if per_page.nil? - - size = positive_integer!(per_page, 'per_page') - raise ArgumentError, "#{@path} serves at most #{@max_per_page} records per page, so page(#{number}, per_page: #{size}) would be sent as page #{number} of #{@max_per_page} and hold different records. Ask for page(#{number}, per_page: #{@max_per_page}) or fewer, or walk the records with find_each." if size > @max_per_page + raise ArgumentError, "#{@path} serves every record in one response, so it has no pages" if !@paginated - with(page: number, per_page: size) + with(page: number, per_page: per_page || @per_page) end # Returns a new collection sorted by the server. # # Attributes named on their own sort ascending, and a keyword says which - # way one runs, the way ActiveRecord reads the same call. A second - # +order+ sorts within the first, so +order(:active).order(name: :desc)+ - # is +order(:active, name: :desc)+. - # - # This is the one thing an index endpoint does besides paging, which is - # why it has a name of its own. It used to be reached as - # +where(sort_by: 'name', order_by: 'desc')+, on a method that refused - # nearly everything else it was given: an index endpoint does not filter - # by attribute value, so +where(state: 'open')+ could only raise, and on - # tickets and users +where+ accepted nothing at all. Narrowing by a value - # is what {ResourceProxy#search} and {ResourceProxy#find_by} are for. - # - # Not every endpoint sorts. +/api/v1/tickets+ and +/api/v1/users+ are - # always served in id order, and drop +sort_by+ along with everything - # else they do not read, so this refuses them rather than handing back - # records it would be calling sorted. A search does sort, for every - # resource that can be searched. + # way one runs. A second +order+ sorts within the first. # # @example # client.groups.order(:name).first(5) # client.organizations.order(name: :desc) - # client.tickets.search('state.name:open').order(:priority_id, created_at: :desc) # - # @param attributes [Array] attributes to sort by, - # ascending + # @param attributes [Array] attributes to sort by, ascending # @param directions [Hash{Symbol => Symbol, String}] attributes to sort by, # each with +:asc+ or +:desc+ # @return [Collection] - # @raise [ArgumentError] for an endpoint that does not sort, no - # attribute at all, an attribute named twice, or a direction that is - # neither +:asc+ nor +:desc+ + # @raise [ArgumentError] for an endpoint that does not sort, or no attribute def order(*attributes, **directions) - raise ArgumentError, "#{@path} is always served in the same order and ignores sort_by, so order would hand back the records as they were. #{@unsortable_hint}" if !@sortable + raise ArgumentError, "#{@path} is always served in the same order and ignores sort_by" if !@sortable - requested = sort_columns(attributes, directions) + requested = attributes.to_h { [it.to_s, 'asc'] }.merge(directions.to_h { |name, direction| [name.to_s, direction.to_s] }) raise ArgumentError, 'order needs at least one attribute to sort by: order(:name), or order(name: :desc)' if requested.empty? - sorted = sorted_by - repeated = requested.keys & sorted.keys - raise ArgumentError, "order was given #{repeated.join(', ')}, which this collection is already sorted by" if !repeated.empty? - - columns = sorted.merge(requested) + columns = sorted_by.merge(requested) with(query: @query.merge(sort_by: columns.keys.join(','), order_by: columns.values.join(','))) end # Reads one or more attributes from every record. # - # Zammad has no way to ask an index endpoint for a subset of the fields, so - # this shapes the result rather than shrinking the request. - # # @example # client.users.all.pluck(:email) # => ["a@example.com", ...] # client.tickets.all.pluck(:id, :title) # => [[1, "Help"], ...] # # @param keys [Array] attribute names - # @return [Array] one value per record for a single key, one array of - # values per record for several + # @return [Array] # @raise [ArgumentError] when no attribute name was given def pluck(*keys) raise ArgumentError, 'pluck needs at least one attribute name' if keys.empty? @@ -235,792 +151,111 @@ def pluck(*keys) map { |record| keys.map { record[it] } } end - # The first record, or the first +count+ of them. - # - # Sized to what was asked for, which +Enumerable#first+ cannot be: it - # takes its records off the front of a page this collection sized for - # walking, so +all.first+ downloaded a page of a thousand users to hand - # back one of them. - # - # The request is sized, not the collection. Limiting it to one page of - # +count+ records would have been the shorter way to write this and - # answers wrongly where the endpoint serves a smaller page than the - # +max_per_page+ this resource declares: +first(500)+ against a server - # capping at 100 came back with 100 records and nothing to say that the - # other 400 were there to be read. Sizing the request instead leaves the - # walk able to fetch a second page, and +Enumerable#first+ stops it as - # soon as it has what it asked for - so the ordinary case is still the one - # request it looks like. - # - # A collection {#page} already limited is left as it is. Its page size - # says which records it holds, so re-sizing it would move them - the same - # reason {#page_size!} refuses to. - # - # The size is where the read starts, and not what it is held to. A - # search can serve a page with nothing on it and hits still behind it, - # and a read that stayed this small then paid a request for every one - # of them: see {#widened}. - # - # A read that sizes its own request leaves out a record it has already - # handed over. The larger pages it asks for past an empty one are where - # an endpoint that pages smaller than it is asked hands a hit back twice, - # and a caller acting on the records - `first(5).each { notify(it) }` - - # would act on that one twice. It holds no more ids than records wanted, - # and asks for nothing more to do it: the read goes on to the next - # record, as it does past a stale hit. + # The first record, or the first +count+ of them, read with a request sized + # for what was asked rather than a whole page. # - # @param count [Integer, nil] how many records to read - # @return [Resources::Base, Array, nil] one record, or an - # array of them when +count+ was given + # @param count [Integer, nil] + # @return [Resources::Base, Array, nil] def first(count = nil) - wanted = count || 1 - # Through an enumerator rather than `super`, so that the sized - # collection does the reading and this method is not asked to be both - # the caller and the callee of Enumerable#first. - records = own_request_for_first?(wanted) ? with(per_page: wanted, widens: true).to_enum(:each_distinct) : each - count.nil? ? records.first : records.first(count) - end + wanted = count || 1 + source = @page || !@paginated || !wanted.is_a?(Integer) || !wanted.positive? ? self : with(per_page: wanted) - # The first +count+ records, read the way {#first} reads them. - # - # +take(n)+ and +first(n)+ ask one question, and +Enumerable+ answers both - # by taking records off the front of a page this collection sized for - # walking. With {#first} sizing its own request and this one left alone, - # what the same read cost depended on which of the two words was typed. - # - # @param count [Integer] how many records to read - # @return [Array] - def take(count) - # Enumerable#take always answers with an Array, and {#first} only does - # when it is given a count - a nil is "just the one" there. Refused with - # the error Enumerable#take raises for it, rather than quietly answering - # a different question with a different type. - raise TypeError, 'no implicit conversion from nil to integer' if count.nil? - - first(count) + count.nil? ? source.each.first : source.each.first(count) end - # +Enumerable#find+, which takes a block. - # - # Defined only to refuse the other reading of it. {ResourceProxy#find} - # takes an id - +client.tickets.find(1)+ is the lookup by id - and the same - # word on a collection is +Enumerable#find+, whose argument is an ifnone - # callable rather than an id. So +client.tickets.all.find(1)+ made no - # request, raised nothing, and answered with an Enumerator: a silent - # no-op, on the one spelling a caller is most likely to reach for. - # - # A collection cannot do the lookup either, even where it would be - # unambiguous - a search has already narrowed what it holds, so an id - # found through one collection would mean something different from an id - # found through another. + # +Enumerable#find+, which takes a block. Look a record up by id on the + # resource instead: +client.tickets.find(1)+. # # @yieldparam record [Resources::Base] # @return [Resources::Base, nil] # @raise [ArgumentError] when given an id where a block belongs def find(*args, &block) - raise ArgumentError, find_by_id_message(args.first) if block.nil? && !args.empty? + raise ArgumentError, "find on a collection takes a block; look a record up by id with client..find(#{args.first.inspect})" if block.nil? && !args.empty? super end - # Number of records in this collection. - # - # One request on a search, which Zammad can count without serving the - # records: +only_total_count+ is the first thing - # ApplicationController#model_search_render looks at, and it answers with - # the figure alone. + # Number of records in this collection: one request on a search, which + # Zammad can count without serving the records, and a walk otherwise. # - # Every other endpoint has to be walked. An index endpoint drops - # +only_total_count+ along with every other parameter it does not know - - # model_index_render reads +sort_by+, +order_by+ and the paging and - # nothing else - and there is no header to read a total from either, so - # there is nothing cheaper to ask. Probing anyway cost a wasted request - # before the walk that had to happen regardless. + # There is no +size+ or +length+: +each_slice+ and +each_cons+ ask for + # the size before they start, and that would read every record twice. # # @return [Integer] def count(*args, &block) - # A block or an argument is Enumerable counting matches, not this asking - # how large the result is. A collection limited to one page has to read - # that page, because the total describes the whole query. return super if !args.empty? || block || @page || !@search total_count || super end - # Number of records in this collection. - # - # An alias of {#count}, and so the same cost: one request on a search - # endpoint, a walk of every page on any other. - # - # @return [Integer] - # @see #count - alias size count - - # @return [Integer] - # @see #count - alias length count - - # Yields the records in groups of +size+, the last group being what is - # left over. - # - # +Enumerable#each_slice+, run over the Enumerator of {#each} rather than - # over the collection. Ruby asks the receiver for its +size+ before it - # slices, to hold no more than there is to hold, and {#size} here is - # {#count}: a walk of every page on an index, a request for the total on - # a search, the page over again on a collection limited to one. So - # `page(1, per_page: 50).each_slice(10)` fetched its page twice and - # `client.tickets.each_slice(100)` read every ticket twice, and the - # groups were cut to the count the first of the two reads came back - # with, whatever the second then held. The Enumerator has no size to be - # asked for. - # - # An Enumerator that Ruby makes from the collection itself still has: - # `each_with_index` and `map` without a block report the size of what - # they were made from, so slicing one of those counts first. Slice - # first, and number the groups: `each_slice(10).with_index`. - # - # @example - # client.users.each_slice(25) { |users| mailer.deliver(users) } - # - # @param size [Integer] records in a group - # @yieldparam records [Array] - # @return [Enumerator] when no block is given - def each_slice(size, &block) - return each.each_slice(size) if !block - - each.each_slice(size, &block) - self - end - - # Yields every run of +size+ records that follow one another. - # - # Run over the Enumerator of {#each}, for the reason {#each_slice} is: - # +Enumerable#each_cons+ asks for the +size+ in the same way. - # - # @param size [Integer] records in a run - # @yieldparam records [Array] - # @return [Enumerator] when no block is given - def each_cons(size, &block) - return each.each_cons(size) if !block - - each.each_cons(size, &block) - self - end - - # A lazy enumerator over the records. - # - # Made from the Enumerator of {#each} as well. A lazy enumerator answers - # +size+ with what its source answers, so `lazy.each_slice(10).first(2)` - # counted the collection on its way to two groups. - # - # @return [Enumerator::Lazy] - def lazy = each.lazy - - # Whether this collection has no records. - # - # Costs the one request {#first} costs: a page of a single record, except - # on a collection limited to one page, where the page size decides which - # records that page holds and so cannot be narrowed. A search whose - # first hits have lost their records costs the few more it takes to read - # past them. - # - # @example - # client.tickets.search('state.name:merged').empty? - # - # @return [Boolean] + # @return [Boolean] whether the collection holds no records, read with + # one request for one record def empty? = first.nil? - # Whether this collection has a record. - # - # Without a block or a pattern it is {#empty?} asked the other way - # round, and costs what that costs. It was +Enumerable#any?+, which - # starts a walk at the page size for walking and stops at the first - # record, so +client.tickets.all.any?+ fetched a hundred expanded - # tickets, and two hundred hits on a search, to learn what one record - # says - the argument made above {#take}, that what a read costs should - # not depend on which word it was written with. A record is never nil - # or false, so the answer is the same. - # - # A block or a pattern asks about the records themselves, which is a - # walk, and is left to +Enumerable+. - # - # @example - # notify(agent) if client.tickets.search("owner.login:#{login} AND state.name:open").any? - # - # @yieldparam record [Resources::Base] - # @return [Boolean] - def any?(*pattern, &block) - return super if block || !pattern.empty? - - !empty? - end - - # Whether this collection has no record: {#empty?}, unless a block or a - # pattern is given. See {#any?}. - # - # @yieldparam record [Resources::Base] - # @return [Boolean] - def none?(*pattern, &block) - return super if block || !pattern.empty? - - empty? - end - def inspect "#<#{self.class.name} #{@resource_class.name} path=#{@path.inspect} per_page=#{@per_page}#{" page=#{@page}" if @page}#{' paginated=false' if !@paginated}>" end private - # Yields each record whose id has not been yielded already. A record - # without an id is yielded, there being nothing to tell it by. - def each_distinct - seen = {} - each do |record| - id = record.id - next if !id.nil? && seen.key?(id) - - seen[id] = true if !id.nil? - yield record - end - end - - # Whether a read of this many records is worth sizing the request for. - # - # Not where this collection is already limited to a page, whose size says - # which records it holds, and not where the count is larger than the - # endpoint serves - {#clamp_per_page} would reduce it to the same size the - # collection already has. A zero or negative count is left to - # Enumerable#first, which has its own answers for both. + # Fetches page after page until one comes back empty. An index also stops + # at a short page; a search can serve one before the last. # - # And not where the endpoint does not page: it serves every record - # whatever it is asked for, so there is no request to size. - def own_request_for_first?(count) - return false if @page || !@paginated - - count.is_a?(Integer) && count.positive? && count <= @max_per_page - end + # Not `loop`, which would end the walk quietly on a StopIteration raised + # by the caller's block; and the page is judged before the block gets it, + # since the block may change the Array. + def walk + number = @page || 1 + previous = nil + last = false - def find_by_id_message(id) - "find on a #{self.class.name} is Enumerable#find, which takes a block: #{id.inspect} would be read as its " \ - 'ifnone argument and answered with an Enumerator, without a request. ' \ - "Look a record up by id on the resource itself - #{resource_reader}.find(#{id.inspect}) - " \ - 'or pick one out of the records this collection holds with detect { ... }.' - end + until last + records = fetch(number) + break if records.empty? - # How a caller reaches this resource from a client: - # ZammadAPI::Resources::TicketArticle is client.ticket_articles, and a - # resource class the caller declared is client.resource(TheirClass). Looked - # up at the moment it is needed, in an error message, so that this file - # does not have to load the client that loads it. - def resource_reader - name = Client::RESOURCES.key(@resource_class) - name ? "client.#{name}" : "client.resource(#{@resource_class.name})" - end - - # The attributes an +order+ call names, each with its direction, in the - # order they were written. - # - # @return [Hash{String => String}] - def sort_columns(attributes, directions) - # `order(:name, :desc)` is the spelling several other clients use, and - # read literally it sorts by an attribute called desc - which Zammad - # answers with a server error about an invalid column. - misplaced = attributes.find { SORT_DIRECTIONS.include?(it.to_s.downcase) } - raise ArgumentError, "order reads #{misplaced.inspect} as an attribute to sort by. A direction goes with its attribute: order(name: #{misplaced.to_s.downcase.to_sym.inspect})" if misplaced + ids = records.map(&:id) + raise PaginationError.build(operation: @operation, page: number, resource_class: @resource_class) if ids == previous - columns = {} #: Hash[String, String] - (attributes.map { [it, 'asc'] } + directions.to_a).each do |attribute, direction| - name = sort_attribute!(attribute) - raise ArgumentError, "order was given #{name} twice" if columns.key?(name) + last = !@page.nil? || (!@search && records.size < @per_page) + yield records - columns[name] = sort_direction!(name, direction) + previous = ids + number += 1 end - columns end - def sort_attribute!(attribute) - name = attribute.to_s - raise ArgumentError, "order needs the name of an attribute to sort by, got #{attribute.inspect}" if (!attribute.is_a?(Symbol) && !attribute.is_a?(String)) || !SORT_ATTRIBUTE.match?(name) + # One page, or with no number the whole of an index that does not page. + def fetch(number) + query = number ? @query.merge(page: number, per_page: @per_page) : @query + response = @transport.get(@path, operation: @operation, resource_class: @resource_class, query: query) - name + response.decoded(:array, operation: @operation, resource_class: @resource_class).map { @resource_class.from_response(@transport, it) } end - def sort_direction!(name, direction) - normalized = direction.to_s.downcase - raise ArgumentError, "order sorts #{name} either :asc or :desc, got #{direction.inspect}" if !SORT_DIRECTIONS.include?(normalized) - - normalized + def total_count + response = @transport.get(@path, operation: @operation, resource_class: @resource_class, query: @query.merge(only_total_count: true)) + total = response.body.is_a?(Hash) ? response.body[:total_count] : nil + total if total.is_a?(Integer) end - # What this collection is already sorted by, read back out of the query - # it will send. - # - # @return [Hash{String => String}] def sorted_by @query.fetch(:sort_by, '').to_s.split(',').zip(@query.fetch(:order_by, '').to_s.split(',')).to_h end - def positive_integer!(value, name) - raise ArgumentError, "#{name} needs a positive integer" if !value.is_a?(Integer) || !value.positive? - - value - end - - # Re-sizing the page of a collection that {#page} already limited would - # change which records it holds: `page(3, per_page: 50)` names records 101 to - # 150, and re-sizing to 10 behind the caller's back served records 21 to - # 30 instead - a different answer to the same question, with nothing said - # about it. The two ways of naming a page cannot both be honoured, so this - # says so rather than picking one. - def page_size!(value, name) - size = positive_integer!(value, name) - raise ArgumentError, "#{name} cannot be combined with page: page(#{@page}, per_page: #{@per_page}) already named which records this collection holds. Size that page with page(#{@page}, per_page: #{size}), or slice the records with each_slice(#{size})." if @page - - size - end - - # The one read of an index that does not page: every record it serves, - # from one request that names no page. - # - # Walked like the others, such an index never got past its first page. - # A walk learns the page size from the first page and asks for the next - # while pages come back that full, so a whole list was always followed - # by a request for page two - and an endpoint that reads no +page+ - # answers that with the same list. The repeated-page guard is there for - # exactly that answer, so `to_a` raised PaginationError with every - # record in hand, and a `find_by` that found nothing on the first page - # raised it instead of answering nil. - # - # Nothing in the two responses tells such an endpoint from one that - # ignores +page+ and serves the first hundred of a thousand records. - # Reading that one in a single request would return a truncated list and - # call it whole, which is what the guard exists to refuse. So this is - # not inferred from a page that repeats: the resource says it, with - # {Resources::Base.paginated}, and the guard stays as it is for every - # resource that does not. - # - # The batches are slices of the one response, so that `in_batches(of: - # 50)` hands a block fifty records at most here as everywhere else. - def read_whole(&block) - records, = fetch(1, @per_page) - - records.each_slice(@per_page, &block) - end - - def walk - page = @page || 1 - previous = nil - page_size = 0 - # `while`, and not `loop`. Kernel#loop rescues StopIteration, which is - # there for an enumerator driven by hand inside it, and the block this - # yields to is the caller's: one that calls `next` on an enumerator of - # its own - `map { [it.id, labels.next] }` with fewer labels than - # records - raised it from in here, and the walk took it for its own - # end. The records and the pages after that were dropped and `map` - # answered with what it had, where the same block over an Array raises. - # Every way out of this loop is a `break` below. - per_page = @per_page - while page - records, digest, total = fetch(page, per_page) - - # Counted before the block has the page, not after. The Array handed - # over is the block's to do with as it likes, and a consumer that - # works a batch off with `shift` hands it back empty: read afterwards, - # that was an empty page, and an import stopped after its first batch - # with every later page still on the server. - received = records.size - - # Before the records are handed over, not after. Yielding first meant - # an endpoint that ignores `page` had its repeated page imported, - # queued or written by the block, and only then did the guard that - # exists to prevent that get to look at it. - # - # A digest rather than the pages themselves, because holding the - # previous page across the next fetch doubled a walk's peak memory for - # a guard that only ever asks whether two pages are equal. What it is - # a digest of is in #page_digest: the ids, where every record has one. - # - # Where it is the payload, it is the decoded one, not the bytes it - # arrived as. Hashing raw_body is cheaper and looks equivalent - - # identical bytes do mean identical records - but the implication that - # matters here runs the other way: an endpoint that ignores `page` and - # re-serializes the same records with a different key order produces - # different bytes every time, so the guard never fires, and because - # every page is full the short-page break does not fire either. A - # missed repeat is not a missed error, it is a walk that never ends. - # `Hash#hash` ignores key order and whitespace, which is exactly the - # insensitivity this needs - and taking it from the decoded payload - # rather than from the built records costs nothing extra, because that - # payload is what the records were built from one line earlier. - # - # An empty page is not held against the one before it. Two in a row - # are what a search serves for two pages of hits whose records are - # gone, with more beyond them - see #hits_past? - and there is nothing - # on either for the block to be handed twice. - # - # A repeat alone does not say that `page` is ignored: see - # #refuse_ignored_page!. Where the list moved instead, this page is - # the one the block has had, so it is passed over and the walk goes - # on from the page after it. - if received.positive? && digest == previous - refuse_ignored_page!(page, per_page, digest) - page += 1 - next - end - - yield records if received.positive? - - # A collection limited to a single page never advances. - break if @page - - # The hits the pages read so far have covered, reckoned in the size - # asked for. Every page this walk asks for starts where the one - # before it ended, whatever size either was, so the last page's - # number and size say it all. - covered = page * per_page - # An empty page ends the walk, unless it is a search saying that it - # has hits beyond this one. - break if received.zero? && !hits_past?(covered, total) - - # Every stop condition here is derived from the records the endpoint - # actually served, and the one figure read beside them - a search's - # total, in #hits_past? - can only keep a walk going. There was a - # stop condition that was not: an index endpoint was believed to - # report the size of the whole result in a header, which would have - # ended a short walk one request earlier. Zammad sends no such header - # from any endpoint, so it never once fired. What it did leave behind - # was a stop condition that could end a walk early on a figure the - # records did not corroborate, which is the one way a walk can be - # wrong rather than merely slow. - # - # How big a page this endpoint actually serves, learned from the first - # one rather than assumed. The requested size is clamped to a per- - # resource page limit, and where that guess was higher than the - # server's real cap - a lowered setting, a custom deployment, an - # endpoint whose cap was never this generous - every page came back - # short and the walk stopped on page one with a truncated result and - # nothing to show for it. - # - # Asked of an index endpoint only. Its page is one SQL query with an - # offset and a limit, so a page short of the size it has been serving - # is the last one. A search page is put together in two steps: - # ApplicationController#model_search_render has the search - through - # Elasticsearch, or through SQL - name the ids for the page, and then - # loads the records with `where(id: ids)`. An id whose record is gone - # by the second step is left out and nothing fills its place: a ticket - # deleted in between, or one Elasticsearch still lists because its - # index has drifted from the database. So a search can serve 199 of - # 200 on page two with page three still to come, and stopping there - # truncated the result with nothing to say so. Only an empty page - # ends a search walk, which costs one more request where the last - # page of hits is part-filled - and not every empty page does, for - # the same reason: see #hits_past?. - page_size = received if page_size.zero? - break if !@search && received < page_size - - previous = digest - page, per_page = page_after(page, per_page, received, total) - end - end - - # Raises where a page that came back holding the records of the one - # before it means that the endpoint ignores +page+, and returns where it - # means that the list moved under the walk. - # - # Such a page is what an endpoint serves that ignores +page+, and it is - # also what one serves that pages as it should, where the list grew at - # its front by exactly a page between the two requests: a search is - # served most recently updated first, so two tickets updated elsewhere - # while `in_batches(of: 2)` was between its first and second request put - # the first page's tickets on the second. That walk raised - # PaginationError, and on an index the message went on to advise - # `paginated false`, which reads the list in one request and would have - # cut it short. - # - # The page before tells the two apart. Asked for again, it holds what it - # held, where the endpoint answers every page alike, and other records, - # where the ones it held have moved on to the next page. The page after - # would tell them apart as well and is one the walk needs anyway, but it - # repeats too where the list moves by a page a second time, which a small - # batch on a busy instance makes likely enough. For the page before to - # hold the same records again, the list has to move back. - # - # A page that repeats always follows one of its own size: only a page - # with nothing on it is followed by one of another size, and a page with - # records on it never compares equal to that. - # - # @param page [Integer] the page that repeated the one before it - # @param digest [Integer] what both pages held - # @raise [PaginationError] - def refuse_ignored_page!(page, per_page, digest) - _, again, = fetch(page - 1, per_page) - return if again != digest - - raise PaginationError.build(operation: @operation, page: page, resource_class: @resource_class, index: !@search) - end - - # The page that follows one a walk has read, and its size: the next of - # the same size, except past an empty page in a read sized by {#first}, - # which asks for more at a time from there. Only a search gets this far - # with nothing received. - # - # @return [Array(Integer, Integer)] the page to ask for and its size - def page_after(page, per_page, received, total) - received.zero? && @widens ? widened(page * per_page, total) : [page + 1, per_page] - end - - # The page to ask for after an empty one, in a read that may widen: the - # largest the endpoint serves that starts exactly where the pages read so - # far ended. - # - # {#first} and {#empty?} size their request to the records they want, - # and a search is read on past a page with nothing on it while the total - # says there are hits behind it. Kept at that size, the two together - # cost a request for every stale hit: on an instance whose Elasticsearch - # index has drifted from its database - one restored without a reindex - - # `search(term).empty?` behind five thousand of them made five thousand - # requests, one after the other, before it answered. - # - # The size that was asked for stopped being the right one at the first - # empty page: it was chosen to fetch no more than was wanted, and what it - # fetched was nothing. But a larger page cannot simply be asked for from - # there. A page is a position - page 3 of 50 is hits 101 to 150 - so one - # of another size starts somewhere else, and a read that moved to it - # would pass over hits or be handed records a second time. - # - # So the next page is one whose size divides what has been covered, - # which makes its start fall exactly on the end of the last: with 8 hits - # covered, page 2 of 8 is hits 9 to 16. The size doubles that way from a - # page of one, and from the endpoint's own limit on it is the largest - # divisor that fits. Five thousand stale hits are read past in - # thirty-four requests. - # - # No page reaches past the total the search last reported, though the - # endpoint would serve one: with 256 hits covered of 300, the next page - # is 32 hits rather than 128. Zammad hands the offset and the size to - # Elasticsearch as they are, and an index whose result window was - # lowered below them - the per-model settings allow it - refuses the - # request, which Zammad answers as no hits and a total of nought. Asked - # for hits 257 to 384 against a window of 300, a read with a live hit - # at 280 answered nil where a page of one would have found it. The - # window cannot be seen from here, so a total beyond it still leaves the - # read to end there; the default window is a million hits. - # - # It takes the endpoint to serve the size it is asked for, up to - # +max_per_page+, which is what #hits_past? takes as well. One that - # serves less pages by its own size, so page 3 of 192 served as 100 is - # hits 201 to 300: hits are passed over, and the pages read cover less - # than the walk takes them to. A hit served twice is left out by - # {#first}. A page of one, which every endpoint serves, could not go - # wrong that way. Zammad serves a search the 200 this asks for at most, - # so it takes an instance whose cap was lowered, and the README says so - # beside the walk's own limits. - # - # Not for a size a caller chose. `in_batches(of: 10)` says how many - # records a batch may hold, and a page of 160 is not one of those. - # - # @param covered [Integer] the hits the pages read so far have covered - # @param total [Integer, nil] the hits the search last reported - # @return [Array(Integer, Integer)] the page to ask for and its size - def widened(covered, total) - limit = total ? (total - covered).clamp(1, @max_per_page) : @max_per_page - pages = covered.fdiv(limit).ceil - pages += 1 until (covered % pages).zero? - - [pages + 1, covered / pages] - end - - def with(page: @page, per_page: @per_page, query: @query, widens: false) + def with(page: @page, per_page: @per_page, query: @query) self.class.new( - transport: @transport, - resource_class: @resource_class, - path: @path, - operation: @operation, - max_per_page: @max_per_page, - sortable: @sortable, - unsortable_hint: @unsortable_hint, - query: query, - per_page: per_page, - page: page, - search: @search, - widens: widens, - paginated: @paginated - ) - end - - # Whether a search reports hits beyond the page just read, which is what - # tells a page with nothing on it from the end of the result. - # - # A search page can come back empty with hits still to come, for the - # reason it can come back short: every id the search named for it has - # lost its record. On a page of 200 that takes 200 stale hits in a row. - # On the page of one that {#first} and {#empty?} ask for it takes one, - # and a search sorts by `updated_at`, newest first - so the hit likeliest - # to be stale, a record deleted a moment ago that Elasticsearch has yet - # to drop, is the first one served. `search(term).first` answered nil and - # `empty?` true for a search with live hits right behind it, and `each` - # ended on such a page with the rest unread. - # - # So a search that is walked asks for the size of the whole result beside - # every page - see #page_query - and an empty page ends the walk only - # once the pages read have covered it. - # - # The figure is not used the other way round, to end a walk on a page - # that still held records and save the request after it. Elasticsearch - # stops counting at ten thousand hits and reports that as the total, so - # a walk ended on the figure would stop there with the rest unread - - # which is the stop condition the note in #walk is about. Past that - # figure an empty page ends the walk, as it does where there is no figure - # at all: a Zammad before 6.5.1 answers `with_total_count` under `expand` - # with the bare array. That is the gap this leaves. - # - # Reckoned in the page sizes that were asked for. An endpoint that pages - # smaller has covered fewer hits than this takes it to have, and the - # walk then ends on an empty page it might have read past - no earlier - # than it ended before the figure was read at all. - # - # What reading on costs is bounded by the same figure: a request per - # page of the hits the endpoint reports, and none beyond them. How large - # those pages are is what #widened is about. - # - # @param covered [Integer] the hits the pages read so far have covered - def hits_past?(covered, total) = !total.nil? && covered < total - - # Fetches one page: the records, the digest the repeated-page guard - # compares, and the size of the whole result where the endpoint reported - # it beside them. - # - # @return [Array(Array, Integer, Integer)] the records, - # the digest and the total - # @return [Array(Array, Integer, nil)] where no total - # was reported - def fetch(page, per_page) - response = @transport.get( - @path, - operation: @operation, + transport: @transport, resource_class: @resource_class, - query: page_query(page, per_page) - ) - decoded, total = response.decoded_list(operation: @operation, resource_class: @resource_class) - # The digest for the repeated-page guard is taken here, from the decoded - # payload, which is the one structure that has everything the guard needs - # and is already in hand. See the guard in `walk` for why it is this and - # not the records or the raw body. - [decoded.map { @resource_class.from_response(@transport, it) }, page_digest(decoded), total] - end - - # The parameters of a request for one page. - # - # `with_total_count` goes out where the answer is read, which is a search - # being walked: see #hits_past?. An index drops the parameter along with - # everything else it does not know, and a collection limited to one page - # has no walk to end, so both are sent what they always were. - # - # It costs Zammad nothing it was not doing. model_search_render asks the - # search for the total on every request and leaves it out of the answer - # unless the parameter is there. - # - # An endpoint that does not page is sent neither parameter. It would - # drop both, and a request that names a page reads as one of several. - def page_query(page, per_page) - return @query if !@paginated - - query = tie_broken.merge(page: page, per_page: per_page) - - @search && @page.nil? ? query.merge(with_total_count: true) : query - end - - # The query with +id+ as the last column of the sort it names. - # - # Zammad orders by the columns it is given and by nothing after them, - # an index and a search alike, and PostgreSQL does not hand rows that - # tie back in the same order from one LIMIT and OFFSET to the next. So - # the pages of `order(:state_id)` did not add up to the records: a - # ticket could be on two of them and another on none. A search of 214 - # tickets walked ten at a time came back as 214 records and 151 - # tickets, and no page repeated another, so nothing raised. - # - # Only the request is given the column. What {#order} recorded is what - # the caller wrote, and `order(:name).order(:id)` is still theirs to - # write. A sort that names +id+ anywhere has no ties left to break. - # - # A collection that names no sort is sent none. An index is served by - # id then, and what a search sorts by where it is not told differs by - # resource, so naming a column here would replace that order. - # - # @return [Hash{Symbol => Object}] - def tie_broken - columns = sorted_by - return @query if columns.empty? || columns.key?('id') - - @query.merge(sort_by: [*columns.keys, 'id'].join(','), order_by: [*columns.values, 'asc'].join(',')) - end - - # What the repeated-page guard compares two pages by: which records they - # hold, where every record says which it is. - # - # The whole payload was the first answer, and it misses the repeat that - # matters most. A job that writes to the records it is handed changes - # what they serialize as - `updated_at`, if nothing else - so an endpoint - # that ignores `page` served the same records with a different payload - # every time. No two pages compared equal, every page was full, and the - # job went round the same records, writing to each of them again, for as - # long as it was left running. - # - # The ids as a set rather than as a list, because a write can reorder - # them too: a search sorts by `updated_at` unless told otherwise. - # - # The payload is still what is compared where a record carries no id. - # Compared by id, a page of those is a list of nils equal to every other - # such page, and a perfectly good paginator was reported as stuck. - # - # @return [Integer] - def page_digest(decoded) - ids = decoded.map { it[:id] } - - ids.include?(nil) ? decoded.hash : ids.to_set.hash - end - - # Asked only of a search endpoint, which is the only kind that answers - # +only_total_count+. Every one of them routes through - # model_search_render, which reads it before it reads anything else, so a - # shape other than the +{total_count: n}+ object means something has - # answered that is not the endpoint this was addressed to - a proxy error - # page, a login form - and the walk is the honest fallback. - # - # A negative figure is refused rather than trusted: it cannot describe a - # result, and a count is the one answer nothing downstream can sanity - # check - `Array.new(collection.count)` and `count.zero?` both take it at - # its word. - # - # @return [Integer, nil] nil when the endpoint did not report a total - def total_count - response = @transport.get( - @path, + path: @path, operation: @operation, - resource_class: @resource_class, - query: @query.merge(only_total_count: true) + max_per_page: @max_per_page, + sortable: @sortable, + query: query, + per_page: per_page, + page: page, + search: @search, + paginated: @paginated ) - return nil if !response.body.is_a?(Hash) - - total = response.body[:total_count] - total if total.is_a?(Integer) && !total.negative? - end - - # Reduced rather than refused, unlike the size {#page} takes. The - # asymmetry is deliberate: a batch size says how much to fetch at a time, - # so a smaller one costs more requests and still walks to the same last - # record, while {#page}'s size also decides which records the page holds, - # and reducing that answers a different question than the one asked. - # - # It is also what lets one batch size be written against resources that - # cap differently - the index endpoints allow 1000, tickets 100, a search - # 200 - without the caller looking each of them up. - def clamp_per_page(size) - raise ArgumentError, 'per_page needs to be a positive integer' if !size.is_a?(Integer) || !size.positive? - - [size, @max_per_page].min end end end diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 2d69e34..cb6cd8f 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -1,6 +1,5 @@ # frozen_string_literal: true -require 'json' require 'logger' require 'uri' @@ -36,26 +35,18 @@ module ZammadAPI # @return [Integer] retry attempts for a request that only reads # @!attribute [r] retry_interval # @return [Numeric] seconds before the first retry, doubling after that - # up to {#timeout}. A +Retry-After+ header takes its place where it - # asks for longer, up to {#timeout} as well. Up to half of this is - # added to a wait that is not a +Retry-After+, as jitter, so one can be - # that much longer than {#timeout}. + # up to {#timeout}, with up to half of it added as jitter # @!attribute [r] ssl_verify # @return [Boolean] whether TLS certificates are verified # @!attribute [r] proxy # @return [String, nil] proxy URL # @!attribute [r] adapter - # @return [Symbol, nil] name of the Faraday adapter, +nil+ for Faraday's - # default or for one the +middleware+ callable sets + # @return [Symbol, nil] name of the Faraday adapter, +nil+ for Faraday's default # @!attribute [r] middleware # @return [Proc, nil] called with the Faraday connection while it is - # being built. An adapter it sets is the one used, which is how an - # adapter is given arguments; one named in +adapter+ as well is - # refused when the connection is built + # being built, after this gem's own middleware # @!attribute [r] logger - # @return [Logger] where debug output goes. Any object will do whose - # +debug+ can be called with a block and no argument, which is how - # each line is handed over + # @return [Logger] where debug output goes Config = Data.define( :url, :user, @@ -75,123 +66,71 @@ module ZammadAPI ) class Config - # Seconds to wait for a response before raising {TimeoutError}. + # Seconds to wait for a response. DEFAULT_TIMEOUT = 60 - # Seconds to wait for the connection to be established. + # Seconds to wait for the connection. DEFAULT_OPEN_TIMEOUT = 10 - # How often a request that only reads is retried on a transient failure. + # Retry attempts for a request that only reads. DEFAULT_RETRIES = 2 - # Seconds to wait before the first retry; doubles on each attempt. + # Seconds before the first retry. DEFAULT_RETRY_INTERVAL = 0.5 - # The longest wait a configuration takes, in seconds: a little over - # three years, and the longest one every platform takes. macOS refuses a - # wait on a socket that is one second longer, and what came of it was a - # ConnectionError calling the instance unreachable. - MAX_SECONDS = 100_000_000 - - # Attributes whose values must never be rendered. - REDACTED_ATTRIBUTES = %i[password http_token oauth2_token].freeze - - # Placeholder rendered in place of a credential. - REDACTION = '[REDACTED]' - - # Identifies this gem in the +User-Agent+ header. + # Value of the +User-Agent+ header unless one is configured. DEFAULT_USER_AGENT = "zammad_api-ruby/#{ZammadAPI::VERSION}".freeze - SCHEME_PATTERN = %r{\Ahttps?://}i - - # An absolute http(s) URL, authority included. The host is part of the - # pattern because a bare scheme - +https://+ - passed a scheme-only check - # and was accepted here, then failed deep inside the adapter on the first - # request instead of at construction, which is the opposite of the - # up-front validation the rest of this class exists for. - URL_PATTERN = %r{\Ahttps?://[^/?\#]+}i - - # Where a URL stops being the part a trailing slash belongs on. - URL_SUFFIX_PATTERN = /[?\#]/ - - # The scheme of a URL, where it has one. A proxy is configured without - # one as often as with - +u:p@proxy:8080+ is the shape an +http_proxy+ - # style setting is copied out of - so the redaction below cannot assume - # it. - URL_SCHEME_PATTERN = %r{\A[a-z][a-z0-9+.-]*://}i - - # What RFC 3986 calls the authority of a URL: everything up to the first - # +/+, +?+ or +#+ after the scheme. - URL_AUTHORITY_PATTERN = %r{\A[^/?\#]*} + # What {#inspect} prints in place of a credential. + REDACTION = '[REDACTED]' - # The options each authentication scheme is made of. + # The options of each way to authenticate. CREDENTIAL_OPTIONS = { http_token: %i[http_token], oauth2_token: %i[oauth2_token], basic: %i[user password] }.freeze - # The credentials that are sent as they stand, in a header of their own. - TOKEN_OPTIONS = %i[http_token oauth2_token].freeze - # Lays +overrides+ over +options+, dropping the credentials they replace. # - # A configuration authenticates one way, so an override that names - # another has to take the old one's place, not sit beside it. A plain - # merge left both, and the old scheme in charge: with +ZAMMAD_TOKEN+ set, - # +Client.from_env(user: 'u', password: 'p')+ still sent the - # environment's token, and +client.with(oauth2_token: 'x')+ on a token - # client went on acting as the account the token belonged to. Neither - # raised, and both read as if they had switched identity. Two schemes - # side by side are refused outright now, which is what makes dropping - # the old one here necessary rather than merely right. - # - # An override that names a scheme therefore takes the place of every - # other scheme. The options of its own scheme are kept, so overriding - # +password:+ alone still pairs it with the +user+ already there. + # A configuration authenticates one way, so an override that names one + # takes the place of every other. The options of its own scheme are kept, + # so overriding +password:+ alone still pairs it with the +user+ there. # # @api private # @param options [Hash{Symbol => Object}] the options being overridden # @param overrides [Hash{Symbol => Object}] # @return [Hash{Symbol => Object}] def self.merge_options(options, overrides) - named = CREDENTIAL_OPTIONS.select { |_, keys| keys.any? { names_credential?(it, overrides[it]) } } + named = CREDENTIAL_OPTIONS.select { |_, keys| keys.any? { !overrides[it].to_s.strip.empty? } } replaced = named.empty? ? [] : CREDENTIAL_OPTIONS.except(*named.keys).values.flatten options.except(*replaced).merge(overrides) end - # Whether an override holds a credential, and so names its scheme. Not - # where it is nil or empty, and not a token of nothing but whitespace, - # which {#normalize_token} takes for none as well. - # - # @api private - # @return [Boolean] - def self.names_credential?(name, value) - !value.to_s.empty? && !(TOKEN_OPTIONS.include?(name) && blank_token?(value)) - end - - # Whether a token is one a header would carry nothing of. - # - # Asked of the bytes with +strip+, which is how {Transport.stripped} - # takes the whitespace off the token it sends. - # - # @api private - # @return [Boolean] - def self.blank_token?(value) = value.is_a?(String) && value.b.strip.empty? - - # `url:` has a default so that leaving it out is answered by - # {#normalize_url}, with the ConfigurationError that building a client is - # documented to raise and that 1.x raised. As a required keyword it was - # Ruby that answered, with `ArgumentError: missing keyword: :url`, past - # the rescue a caller had written for an incomplete configuration. + # @param url [String] base URL of the Zammad instance + # @param user [String, nil] login for basic authentication + # @param password [String, nil] password for basic authentication + # @param http_token [String, nil] Zammad access token + # @param oauth2_token [String, nil] OAuth2 bearer token + # @param user_agent [String, nil] value of the +User-Agent+ header + # @param timeout [Numeric] seconds to wait for a response + # @param open_timeout [Numeric] seconds to wait for the connection + # @param retries [Integer] retry attempts for a request that only reads + # @param retry_interval [Numeric] seconds before the first retry + # @param ssl_verify [Boolean] whether TLS certificates are verified + # @param proxy [String, nil] proxy URL + # @param adapter [Symbol, String, nil] name of a Faraday adapter + # @param middleware [#call, nil] called with the Faraday connection while it is built + # @param logger [Logger, nil] where debug output goes; discarded by default + # @raise [ConfigurationError] when the options are incomplete or invalid def initialize( url: nil, user: nil, password: nil, http_token: nil, oauth2_token: nil, - user_agent: DEFAULT_USER_AGENT, + user_agent: nil, timeout: DEFAULT_TIMEOUT, open_timeout: DEFAULT_OPEN_TIMEOUT, retries: DEFAULT_RETRIES, @@ -202,63 +141,30 @@ def initialize( middleware: nil, logger: nil ) - # RBS cannot describe the initializer that Data.define generates, so - # these keyword arguments are invisible to the type checker. + # RBS cannot describe the initializer that Data.define generates. # steep:ignore:start super( - url: immutable(normalize_url(url)), - user: immutable(non_empty(user)), - password: immutable(non_empty(password)), - http_token: immutable(normalize_token(:http_token, http_token)), - oauth2_token: immutable(normalize_token(:oauth2_token, oauth2_token)), - user_agent: immutable(normalize_user_agent(user_agent)), + url: normalize_url(url), + user: present(user), + password: present(password), + http_token: stripped(http_token), + oauth2_token: stripped(oauth2_token), + user_agent: stripped(user_agent) || DEFAULT_USER_AGENT, timeout: timeout, open_timeout: open_timeout, retries: retries, retry_interval: retry_interval, ssl_verify: ssl_verify, - proxy: immutable(normalize_proxy(proxy)), - adapter: normalize_adapter(adapter), + proxy: present(proxy), + adapter: present(adapter)&.to_sym, middleware: middleware, logger: logger || Logger.new(IO::NULL) ) # steep:ignore:end - validate_credentials! - validate_numbers! - validate_user_agent! - validate_header_options! - validate_ssl_verify! - validate_middleware! - validate_logger! - end - # The instance URL, with any inline credentials blanked. - # - # A URL that carries credentials is refused when the configuration is - # built - see {#normalize_url} - but only where it can be read as a URL - # at all. One that cannot, such as a password with an unencoded +#+ in - # it, is still held here until building the connection rejects it, and - # this is what that error and {#inspect} print in the meantime. The host - # has to stay readable for the URL to be worth printing, so the - # credentials are replaced rather than the whole value. - # - # @return [String] - def redacted_url = redacted(url) - - # Blanks the credentials in any URL this configuration holds. - # - # Public because {Transport} has to scrub the values it configured out of - # an error message raised from deep inside Faraday or URI, which quotes - # the proxy URL it rejected - credentials and all. - # - # @api private - # @param value [String] a URL that may carry inline credentials - # @return [String] the same URL with the credentials blanked - def redacted(value) = redact_userinfo(value) + validate! + end - # The one way this configuration authenticates. There is never more than - # one to choose between: see {#validate_credentials!}. - # # @return [Symbol] +:http_token+, +:oauth2_token+ or +:basic+ def authentication_scheme return :http_token if http_token @@ -267,10 +173,8 @@ def authentication_scheme :basic end - # Returns a copy with some options changed, re-validated. - # - # Through {.merge_options} rather than Data's own merge, so that naming - # one authentication scheme replaces the one this configuration had. + # Returns a copy with some options changed, re-validated. Naming one way + # to authenticate replaces the one this configuration had. # # @param options [Hash] any option this class accepts # @return [Config] @@ -284,427 +188,79 @@ def inspect end alias to_s inspect - # What +pp+ prints, which is what IRB and the Rails console show for a - # value typed at the prompt. - # - # +pp+ does not go through {#inspect} for a Data object: it has a printer - # of its own that renders the members directly. So +client.config+ in a - # console, or +pp config+ in a script, printed the token, the password - # and the credentials of a proxy in full - from the class documented as - # safe to log, and through the one route most likely to be looked at. + # What +pp+, and so a console, prints: {#inspect}, rather than every member. # # @api private # @param printer [PP] # @return [void] def pretty_print(printer) = printer.text(inspect) - # The configuration for a JSON encoder: every option, with what - # {#inspect} blanks blanked. - # - # ActiveSupport gives a Data an +as_json+ that is its members as they - # are, and builds +to_json+ on it. So in a Rails app +config.to_json+ - # wrote the token, the password and the credentials of a proxy in full, - # and so did a log line or an error report that serialized something - # holding the configuration - the third way out of the class documented - # as safe to log, after {#inspect} and +pp+, and the one a structured - # logger takes. - # - # @return [Hash{Symbol => Object}] - def as_json(*) = to_h.to_h { |key, value| [key, placeholder(key, value) || printable(key, value)] } - - # Without this, +JSON.generate+ would write the configuration as one - # String, its {#to_s}, and ActiveSupport would not come by {#as_json} - # where +to_json+ is what is called. - # - # @param state [JSON::State, nil] passed by +JSON.generate+ - # @return [String] {#as_json} as a JSON object - def to_json(state = nil) = as_json.to_json(state) - - # What Psych writes for a configuration: {#as_json}, as a plain mapping - # of what its JSON reads back as. - # - # Psych asks none of the above. It writes the members of a Data as - # they are, so +config.to_yaml+ held the token, the password and the - # credentials of a proxy in full - the fourth way out of the class - # documented as safe to log, and the one Rails' +debug+ view helper and - # a Delayed::Job handler take. - # - # No tag is written, so the mapping loads as the Hash it is and not as - # a configuration with placeholders where its credentials were. And it - # goes through the JSON, so that nothing in it is an object Psych would - # write by its instance variables in turn. - # - # @api private - # @param coder [Psych::Coder] - # @return [void] - def encode_with(coder) = coder.represent_object(nil, JSON.parse(to_json)) - private - # Blanks the +user:password@+ part of a URL, keeping the host visible. - # - # Everything up to the last +@+ goes, rather than up to the first: a - # password may carry an unencoded one, and +pa@ss+ used to leave +@ss+ in - # the rendered URL. - # - # Which +@+ is the last one depends on whether a password can be there at - # all. Without a colon in the authority there is none, so the search - # stays inside the authority and an +@+ in a path, a query string or a - # fragment is left alone: +https://host?a=b@c+ used to render as - # +https://[REDACTED]@c+, a host that does not exist, in every - # ConnectionError message. - # - # With a colon, the search runs to the end of the value. A password is - # not obliged to be URL-safe, and one carrying +/+, +?+ or +#+ ends the - # authority early as far as the syntax goes: +http://user:p#ss@proxy+ has - # the authority +user:p+, which holds no +@+, so a search bounded by it - # found nothing to blank and printed the password - in {#inspect}, and in - # the ConfigurationError that quotes a proxy URL the HTTP stack rejected. - # The cost is a URL with a port and an +@+ further on, such as - # +https://host:8443/a@b+, which renders with its host blanked. A colon - # cannot tell a port from a password, and of the two mistakes that is the - # one that leaks nothing. - # - # An empty authority is searched the same way, for the same reason and - # at no cost: there is no host in it to blank by mistake. It is what a - # slash too many leaves, or the slashes without the scheme - the - # authority ends at the first slash, so +//user:secret@proxy:8080+ and - # +https:///user:secret@host/+ have none, with no colon and no +@+ in it, - # and were printed as they stood: the proxy by {#inspect}, and the url - # by the ConfigurationError that refuses a url without a host. - # - # @param value [String] a URL that may carry inline credentials - # @return [String] the same URL with the credentials blanked - def redact_userinfo(value) - scheme = value[URL_SCHEME_PATTERN].to_s - rest = value.delete_prefix(scheme) - authority = rest[URL_AUTHORITY_PATTERN].to_s - boundary = authority.empty? || authority.include?(':') ? rest.rindex('@') : authority.rindex('@') - return value if boundary.nil? - - "#{scheme}#{REDACTION}#{rest[boundary..]}" - end - - # One option as {#inspect} prints it. What stands in for a value is - # printed bare, and a value as it inspects. - def render(key, value) = placeholder(key, value) || printable(key, value).inspect - - # What is shown in place of an option that is not shown itself, where it - # is one of those. One rule for {#inspect} and {#as_json}: a second - # copy of which options are credentials is the copy that misses the - # next one. - # - # @return [String, nil] - def placeholder(key, value) - return REDACTION if REDACTED_ATTRIBUTES.include?(key) && value - - # Loggers and procs have verbose default inspect output that would drown - # out the rest of the configuration, and an encoder walks into whatever - # they hold. - "#<#{value.class}>" if key == :logger || (key == :middleware && value) - end - - # An option that is shown, as it may be: a URL without the credentials - # it carries. - def printable(key, value) - return redacted_url if key == :url - return redact_userinfo(value) if key == :proxy && value + def render(key, value) + return value.inspect if value.nil? - value + case key + when :password, :http_token, :oauth2_token then REDACTION + when :proxy then value.to_s.sub(%r{//[^/@]*@}, "//#{REDACTION}@").inspect + when :logger, :middleware then "#<#{value.class}>" + else value.inspect + end end - # The type check comes before the pattern, because every check after it - # is a String method. A URI is the plausible mistake here - it is what - # `URI(...)` hands back and it prints as the URL - and it used to reach - # `end_with?` and die there as a NoMethodError, past the ConfigurationError - # a caller had wrapped the constructor in. def normalize_url(value) - raise ConfigurationError, 'missing url in config' if non_empty(value).nil? - raise ConfigurationError, "config url needs to be a string, got #{value.class}" if !value.is_a?(String) - raise ConfigurationError, 'config url needs to start with http:// or https://' if !SCHEME_PATTERN.match?(value) - # Quoted through the redaction: what follows the scheme here is not a - # host, and may be the credentials of a url with a slash too many. - raise ConfigurationError, "config url needs a host after the scheme, got #{redact_userinfo(value).inspect}" if !URL_PATTERN.match?(value) || hostless?(value) - raise ConfigurationError, inline_credentials_message(value) if inline_credentials?(value) - - # A trailing slash keeps Zammad installations served from a sub-path - # (e.g. https://example.com/zammad/) working, because request paths are - # appended relative to this prefix. - # - # Onto the path, not onto the end of the string. Appended blindly it - # landed behind a query string or fragment, so a url of - # `https://host/zammad?a=1` became `https://host/zammad?a=1/` - the base - # every request is resolved against, and the value {#redacted_url} - # prints in every ConnectionError and TimeoutError message. - path, separator, rest = value.partition(URL_SUFFIX_PATTERN) - path.end_with?('/') ? value : "#{path}/#{separator}#{rest}" - end + raise ConfigurationError, 'missing url in config' if value.to_s.empty? - # Whether what follows the scheme names no host, though something - # stands there: a port alone, as in +http://:3000/+. - # - # It is what `"http://#{ENV['ZAMMAD_HOST']}:3000/"` comes to where the - # variable is not set, and {URL_PATTERN} asks only for a character that - # ends no authority. Net::HTTP connects to localhost for an empty host, - # so the client was built and then sent every request, with the token - # in its header, to whatever listens on that port of the machine it - # runs on. - # - # Asked of URI for the reason {#inline_credentials?} is, and a URL that - # URI cannot read is left to the connection for the same one. - def hostless?(value) - URI.parse(value).host.to_s.empty? - rescue URI::InvalidURIError - false - end + uri = URI.parse(value.to_s) + raise ConfigurationError, 'config url needs to start with http:// or https:// and name a host' if !uri.is_a?(URI::HTTP) || uri.host.to_s.empty? + raise ConfigurationError, 'config url carries credentials: pass user: and password:, or a token, instead' if uri.userinfo - # Whether the URL carries a +user:password@+ of its own. - # - # Asked of URI, because that is the parser Faraday reads the URL with: - # whatever it finds there, Faraday turns into a Basic +Authorization+ - # header on the connection, and its authorization middleware then leaves - # a header that is already set alone. So a URL with credentials silently - # replaced the scheme this class validated - an access token configured - # beside it was never sent, while {Client#inspect} went on reporting - # +auth=http_token+. - # - # A URL that URI cannot read is left for the connection to reject, which - # it does before any request is made. - def inline_credentials?(value) - !URI.parse(value).userinfo.nil? + value.end_with?('/') ? value : "#{value}/" rescue URI::InvalidURIError - false + raise ConfigurationError, 'config url is not a valid URL' end - def inline_credentials_message(value) - "config url carries credentials of its own (#{redact_userinfo(value)}), which would be sent as basic authentication " \ - 'in place of the ones this configuration names. Leave them out of the url and pass user: and password:, ' \ - 'or http_token: or oauth2_token:, instead.' + def validate! + validate_credentials! + validate_numbers! + validate_proxy! + raise ConfigurationError, "config ssl_verify needs to be true or false, got #{ssl_verify.inspect}" if ![true, false].include?(ssl_verify) + raise ConfigurationError, 'config middleware needs to respond to call' if middleware && !middleware.respond_to?(:call) + raise ConfigurationError, 'config logger needs to respond to debug' if !logger.respond_to?(:debug) end - # One way to authenticate, and only one. - # - # Several used to be accepted together, and {#authentication_scheme} - # picked the first of them in a fixed order without a word. That is what - # let an override leave the old credential in charge - a token beside a - # user and password it was meant to replace - and it is the same mistake - # wherever it comes from: a client that holds two identities sends one of - # them, and which one is not something the call site shows. Refused here, - # a configuration says how it authenticates by construction, and the - # merges that build one - {.merge_options} - have to drop what an - # override replaces rather than keep it beside the new value. - # - # Half of a scheme counts as naming it, so a token beside a +user+ that - # has no password is refused as two schemes rather than passed as one. def validate_credentials! given = CREDENTIAL_OPTIONS.select { |_, options| options.any? { !public_send(it).nil? } }.keys - raise ConfigurationError, multiple_credentials_message(given) if given.size > 1 + if given.size > 1 + named = given.map { CREDENTIAL_OPTIONS.fetch(it).join(' and ') }.join(', ') + raise ConfigurationError, "config names more than one way to authenticate (#{named}): pass http_token:, or oauth2_token:, or user: and password:" + end return if http_token || oauth2_token raise ConfigurationError, 'missing user in config' if user.nil? raise ConfigurationError, 'missing password in config' if password.nil? end - def too_long_message(name, value) - "config #{name} needs to be at most #{MAX_SECONDS} seconds, got #{value}. No value stands for no #{name == :retry_interval ? 'limit' : 'timeout'}: " \ - 'pass the longest wait that is acceptable.' - end - - def multiple_credentials_message(schemes) - named = schemes.map { CREDENTIAL_OPTIONS.fetch(it).join(' and ') }.join(', ') - - "config names more than one way to authenticate (#{named}), and a request can carry only one. " \ - 'Pass http_token:, or oauth2_token:, or user: and password:, and leave the others out.' - end - - # Numeric is not the whole test. Complex is one and answers neither - # `positive?` nor `>`, so `timeout: Complex(1, 2)` left a NoMethodError - # where every other rejected option raises ConfigurationError - the same - # escape normalize_adapter, normalize_proxy and validate_logger! were each - # written to close. - def positive_number?(value) = value.is_a?(Numeric) && value.respond_to?(:positive?) && value.positive? - - # A number has to be one the HTTP stack can wait for as well, and that - # is not every positive one. `timeout: Float::INFINITY`, the natural way - # to ask for no timeout, which is what 1.x had, was accepted, and every - # request then raised a bare RangeError from inside Net::HTTP, as it did - # for a figure past what a C long holds. An infinite +retry_interval+ - # raised the same from the sleep before the first retry. def validate_numbers! { timeout: timeout, open_timeout: open_timeout, retry_interval: retry_interval }.each do |name, value| - raise ConfigurationError, "config #{name} needs to be a positive number" if !positive_number?(value) - raise ConfigurationError, too_long_message(name, value) if value > MAX_SECONDS + raise ConfigurationError, "config #{name} needs to be a positive number" if !value.is_a?(Numeric) || !value.real? || !value.positive? end - raise ConfigurationError, 'config retries needs to be a non-negative integer' if !retries.is_a?(Integer) || retries.negative? end - # Not just a default: `user_agent: nil` reached Faraday as a nil header, - # and Faraday filled in its own, so the gem stopped identifying itself in - # the instance log an operator greps to find its requests - silently, and - # on every request. - def validate_user_agent! - return if user_agent.is_a?(String) - - raise ConfigurationError, 'config user_agent needs to be a string' - end - - # The options that are sent as a header: the two tokens in - # +Authorization+, and the user agent. - HEADER_OPTIONS = %i[http_token oauth2_token user_agent].freeze - private_constant :HEADER_OPTIONS - - # A line break inside one of these was taken here and refused by - # Net::HTTP at the first request, with the value in the message: see - # {Transport.line_break?}. Refused here instead, without the value. A - # user and password are not checked: basic authentication sends them - # Base64-encoded, which carries a line break like anything else. - def validate_header_options! - HEADER_OPTIONS.each do |name| - value = public_send(name) - next if !value.is_a?(String) || !Transport.line_break?(header_text(name, value)) - - raise ConfigurationError, "config #{name} holds a line break, which a header cannot carry: #{Transport::LINE_BREAK_ADVICE}" - end - end - - # The option as text whose bytes are the ones a header carries: see - # {Transport.wire_text}. Text that cannot be converted cannot be shown - # to hold no line break, and was passed as holding none. Refused - # without the error underneath as its cause, which quotes the bytes it - # stopped at. - def header_text(name, value) - Transport.wire_text(value, "config #{name}") - rescue ArgumentError => e - raise ConfigurationError, e.message, cause: nil - end - - # A token as it is held: text, or nil where there is none to send. - # - # One of nothing but whitespace is none. It is what reading an empty - # token file gives, and the transport takes the whitespace off the value - # it sends, so the client was built, reported +auth=http_token+ and - # sent +Authorization: Token+ with nothing after it. Taken for unset, as - # an empty String is, it is answered here with what is missing. - # - # And one that is no String is refused. It was sent as it prints, an - # Array as +["a"]+, and it passed {#validate_header_options!}, which - # asks a String for its line breaks and had nothing to ask a Symbol - # holding one. The class is named and the value is not: it is a - # credential, or was meant to be. - def normalize_token(name, value) - return nil if non_empty(value).nil? - raise ConfigurationError, "config #{name} needs to be a string, got #{value.class}" if !value.is_a?(String) - - self.class.blank_token?(value) ? nil : value - end - - # The user agent as it is held: the one given, or the gem's own where - # none was. - # - # One of nothing but whitespace is none, as a token of that is, and for - # the same reason: the transport takes the whitespace off the value it - # sends, so `user_agent: ' '` was sent as a `User-Agent` header with - # nothing in it. Faraday fills in its own only where there is no header - # at all, so the requests went out naming no client, in the instance log - # an operator greps to find them. - def normalize_user_agent(value) - return DEFAULT_USER_AGENT if non_empty(value).nil? || self.class.blank_token?(value) - - value - end - - # A proxy is the second string here that may carry credentials, and the - # only other one rendered rather than replaced wholesale. Unchecked, a - # URI - what `URI(...)` hands back, and what prints as the URL - was - # accepted here and reached String#sub inside {#inspect}, so the object - # this class documents as safe to log raised NoMethodError at exactly the - # moment something tried to log it. The same mistake {#normalize_url} - # already refuses for the instance URL. - def normalize_proxy(value) - return nil if non_empty(value).nil? - raise ConfigurationError, "config proxy needs to be a string, got #{value.class}" if !value.is_a?(String) - - value - end - - # `adapter&.to_sym` accepted anything that answered to_sym and died with - # a bare NoMethodError on anything that did not - `adapter: 1` and - # `adapter: true` both escaped the ConfigurationError that building a - # client is documented to need, from inside the constructor, before any - # of the validators below ran. - def normalize_adapter(value) - return nil if non_empty(value).nil? - raise ConfigurationError, "config adapter needs to be a symbol or a string, got #{value.class}" if !value.is_a?(Symbol) && !value.is_a?(String) - - value.to_sym - end - - # The one option that fails open. Every other value here is checked up - # front, while ssl_verify was passed to Faraday as it arrived: read from - # an environment variable, `ssl_verify: 'false'` is the string "false", - # which is truthy, so the setting a caller believed they had turned off - # was silently still on. That direction is the safe one, which is why it - # went unnoticed - `ssl_verify: 'no'` disables nothing either way, but a - # caller who cannot tell which of their settings took effect has no way - # to find out. - def validate_ssl_verify! - return if [true, false].include?(ssl_verify) - - raise ConfigurationError, "config ssl_verify needs to be true or false, got #{ssl_verify.inspect}" - end - - def validate_middleware! - return if middleware.nil? || middleware.respond_to?(:call) - - raise ConfigurationError, 'config middleware needs to respond to call' - end - - # In 1.x this option was a flag, so `logger: true` is a plausible thing to - # carry over. Without this it would be accepted here and raise NoMethodError - # at the first request instead. - # - # Answering `debug` is not the whole of it. The transport calls it the - # way a Logger is called for a line that costs something to build, with - # a block and no argument, so a logger written as `def debug(message)` - # was accepted here and raised a bare ArgumentError at every request. - def validate_logger! - raise ConfigurationError, 'config logger needs to respond to debug' if !logger.respond_to?(:debug) - return if !debug_needs_argument? - - raise ConfigurationError, 'config logger needs a debug that can be called with a block and no argument, as Logger#debug is: ' \ - 'this one requires an argument' - end - - # A logger that answers `respond_to?` for a method it does not have - - # one that forwards through `method_missing` and says so nowhere else - - # cannot be asked, and is taken at its word. - def debug_needs_argument? - logger.method(:debug).parameters.any? { |kind, _| %i[req keyreq].include?(kind) } - rescue NameError - false + # Here rather than where Faraday parses it, whose error quotes the URL + # with its password. + def validate_proxy! + URI.parse(proxy.to_s) if proxy + rescue URI::InvalidURIError + raise ConfigurationError, 'config proxy is not a valid URL' end - # Not called `presence`: that is the name of a public method ActiveSupport - # gives every object, and a private one here answered in its place, so - # `config.presence` raised NoMethodError in a Rails app. - def non_empty(value) - return nil if value.nil? - return nil if value.respond_to?(:empty?) && value.empty? + def present(value) = value.nil? || value.to_s.empty? ? nil : value - value - end - - # Ruby leaves the members of a Data object mutable, so a caller-supplied - # String would otherwise stay writable through the config - and shared - # with the caller's own variable. Freezing a copy keeps a Config, and any - # Transport built from one, genuinely immutable. - # - # This deliberately copies rather than using String#-@: interning would - # keep a credential in the global fstring table for the life of the - # process, well past the config that held it. - def immutable(value) - value.is_a?(String) ? value.dup.freeze : value + def stripped(value) + text = value.to_s.strip + text.empty? ? nil : text end end end diff --git a/lib/zammad_api/deep_copy.rb b/lib/zammad_api/deep_copy.rb index 57c1cf8..3a88b99 100644 --- a/lib/zammad_api/deep_copy.rb +++ b/lib/zammad_api/deep_copy.rb @@ -1,148 +1,33 @@ # frozen_string_literal: true -require_relative 'attributes' -require_relative 'duplicate_keys' - module ZammadAPI # Recursive copies of the plain JSON structures this gem passes around. # - # Three places need the same walk - a record freezing the attributes it was - # built with, a record handing a copy of them back, and the test kit - # recording the payload a request carried - and each used to carry its own. - # A rule written three times is one that gets fixed in one of them: the - # test kit's copy already differed by not symbolizing keys, and nothing - # said whether that was the point or an oversight. - # - # Only Hash, Array and String are walked, because that is the whole of what - # +JSON.parse+ builds and what a caller may hand in as attributes. Numbers, - # booleans and nil are immutable already and are passed through untouched. - # - # A caller may also hand in what is not a Hash and converts to one, and - # that is read as the Hash it converts to: see {frozen_object}. - # - # One walk, deliberately. A record built from a response copies every String - # of a body +JSON.parse+ has just built and nothing else holds, so a variant - # that froze such a body in place would save that copy on the paging hot - # path - which is a real cost, and still not a reason for a second walk: - # three of them is what this module replaced, and the one that differed did - # so without anything to say whether the difference was the point. If the - # copy is worth removing, it is an argument to this walk and it applies to - # the one place that can prove nothing else references the value. - # # @api private module DeepCopy module_function - # A frozen deep copy. - # - # Named for what it returns rather than `freeze`/`dup`, which would shadow - # the Object methods of those names inside this module and read as them at - # every call site. - # - # Freezing is what makes a record's attribute hash safe to hand out: one - # that gave away a writable hash would report changes it never staged and - # so never sent. Strings are copied before being frozen, so freezing a - # value the caller passed in does not reach back into their own variable. - # - # Keys are left alone. Ruby copies and freezes an unfrozen String key on - # insertion, so a Hash built here never holds the caller's own String, and - # symbolizing produces an immutable key anyway - which leaves only an - # Array or a custom object as a key that this walk would change. `JSON` - # cannot build one, so it could only come from a caller's own attribute - # hash, and paying a call per key on the record-building path for it is - # the cost this module's own note above weighs and declines. + # A frozen deep copy, so a record's attributes cannot change behind its + # back. Strings are copied before they are frozen, so the caller's own + # values are left alone. # # @param value [Object] # @param symbolize_keys [Boolean] whether Hash keys become Symbols, so # that caller-supplied attributes behave the same as decoded responses # @return [Object] a frozen copy - # @raise [ArgumentError] when symbolizing lands two keys of one Hash on - # one name def frozen_copy(value, symbolize_keys: false) - # Ordered by how often each kind turns up in a record Zammad serves, - # where nil, a String and an Integer are nine values in ten. Every - # value that has nothing to copy is answered before {frozen_object} is - # asked, and in this order asking it costs the record-building path - # nothing that a benchmark of a page of tickets shows: copying one - # hundred of them took the same time with the question as without. case value - when nil then nil - when String then value.dup.freeze - when Integer, true, false, Float, Symbol then value - when Hash then frozen_hash(value, symbolize_keys) + when Hash then value.to_h { |key, nested| [symbolize_keys ? symbolize(key) : key, frozen_copy(nested, symbolize_keys: symbolize_keys)] }.freeze when Array then value.map { frozen_copy(it, symbolize_keys: symbolize_keys) }.freeze - else frozen_object(value, symbolize_keys) + when String then value.dup.freeze + else value end end - # What is none of the above: copied as the Hash it converts to, where it - # converts to one, and handed back as it is otherwise. - # - # `ActionController::Parameters` is the reason. It is not a Hash, so the - # walk passed it through, and it is what a Rails controller holds: - # `client.users.new(params.require(:user).permit(:login, :password))` - # built a record whose attributes were the caller's own object, unfrozen - # and with String keys. Its `inspect` and the debug log redact by key - # through a Hash and printed the password, and the body of its `save` - # was that object's `to_s` as one JSON string, where 1.x sent - # `params.to_json`. Nested under an attribute it did the same one level - # down. - # - # +to_hash+ is what is asked, which is how Ruby itself asks whether - # something may stand in for a Hash - a Struct and a Data have +to_h+ - # and do not claim that. Strong parameters answer it with plain Hashes - # all the way down, and refuse where they were not permitted, with - # `ActionController::UnfilteredParameters`: that error is left to say - # so. - # - # @api private - # @return [Object] a frozen copy, or +value+ - def frozen_object(value, symbolize_keys) - converted = Hash.try_convert(value) - - converted ? frozen_hash(converted, symbolize_keys) : value - end - - # The Hash branch of {frozen_copy}. - # - # Two keys that symbolize to one name are refused rather than merged. - # Symbolizing is what creates the collision, the way stringifying does - # for a query - see {DuplicateKeys} - and here it went unrefused: - # `client.groups.new('name' => 'Support', name: 'Sales')` built a record - # holding `name: 'Sales'` alone, and an attribute Hash put together from - # form parameters and defaults lost a value to Hash order without a word. - # {Resources::Ticket#add_article} had to take both spellings of - # `ticket_id` out by hand for it. - # - # Asked of the sizes, so that a Hash with no collision in it - every one - # built from a response - pays one comparison and no call per key. The - # walk that names the two spellings is made only once there is a pair to - # name. - # - # A copy with Symbol keys is the attributes of a record, at whatever - # depth, and those are handed out: see {Attributes} for why such a Hash - # is one that prints its credentials blanked. Made from the copy rather - # than filled key by key, which costs a page of a thousand tickets a - # millisecond. The payload the test kit records is copied with its keys - # as they are and stays a plain Hash, since a failed expectation is read - # from how it prints. - # - # @api private - # @return [Hash] a frozen copy - # @raise [ArgumentError] - def frozen_hash(hash, symbolize_keys) - copy = hash.to_h { |key, nested| [symbolize_keys ? symbolize(key) : key, frozen_copy(nested, symbolize_keys: symbolize_keys)] } - return copy.freeze if !symbolize_keys - - DuplicateKeys.normalize(hash, noun: 'attribute') { symbolize(it) } if copy.size != hash.size - Attributes[copy].freeze - end - - # A writable deep copy, for handing out something callers may treat as - # their own. The inverse of {frozen_copy}. + # A writable deep copy of a frozen structure. # # @param value [Object] - # @return [Object] an unfrozen copy + # @return [Object] def writable_copy(value) case value when Hash then value.to_h { |key, nested| [key, writable_copy(nested)] } @@ -152,11 +37,8 @@ def writable_copy(value) end end - # A key that cannot become a Symbol is left as it is rather than refused: - # it came from a caller's attribute hash, and a record is not the place - # to decide that Zammad will not accept it. - # - # @api private + # @param key [Object] + # @return [Object] the key as a Symbol, where it converts to one def symbolize(key) = key.respond_to?(:to_sym) ? key.to_sym : key end end diff --git a/lib/zammad_api/duplicate_keys.rb b/lib/zammad_api/duplicate_keys.rb deleted file mode 100644 index 24e6aad..0000000 --- a/lib/zammad_api/duplicate_keys.rb +++ /dev/null @@ -1,49 +0,0 @@ -# frozen_string_literal: true - -module ZammadAPI - # One rule for two keys that name the same parameter. - # - # Both places that normalise caller-supplied parameter names had to refuse a - # collision, because normalising is what creates one: {ResourceProxy#search} - # maps every keyword to a Symbol and {Transport.stringify_query} maps every key to a - # String, so `sort_by` and `'sort_by'` become one key and the value that - # arrived first is dropped without a word. Written twice, the two refusals - # had already drifted into two different sentences for the same mistake. - # - # @api private - module DuplicateKeys - module_function - - # Maps every key through the block, refusing two that land on one name. - # - # The key each name was first seen as is kept, so the message can print - # both spellings: naming only the second left the reader to guess the - # first, which in a parameter hash assembled across several merges is the - # whole of the debugging. - # - # @param hash [Hash] - # @param prefix [String, nil] the parameter path this Hash sits at, for a - # nested structure - # @param noun [String] what the caller calls one of these, for the message - # @yieldparam key [Object] a key to normalise - # @return [Hash] the hash with normalised keys and untouched values - # @raise [ArgumentError] for two keys that name the same thing - def normalize(hash, prefix: nil, noun: 'parameter') - seen = {} - - hash.each_with_object({}) do |(key, value), result| - name = yield(key) - raise ArgumentError, message(noun, prefix ? "#{prefix}[#{name}]" : name, seen[name], key) if seen.key?(name) - - seen[name] = key - result[name] = value - end - end - - # @api private - def message(noun, path, first, second) - "#{noun} #{path} was given twice, as #{first.inspect} and as #{second.inspect}: " \ - 'pass it once, so that which value reaches the endpoint does not depend on Hash order' - end - end -end diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index 24efbb6..745f0e6 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -28,42 +28,17 @@ class UnknownResourceError < Error; end class TransportError < Error; end # Raised when the connection to the Zammad instance could not be - # established (DNS, refused connection, TLS failure, ...), or was closed - # before the body of a response had arrived: see {IncompleteResponseError} - # for the second. + # established: DNS, a refused connection, a TLS failure. class ConnectionError < TransportError; end - # Raised when Zammad answered 2xx and the connection was closed before the - # body it announced had arrived. - # - # A {ConnectionError}, and caught as one. It has a class of its own for the - # one thing that sets it apart from the others: the request was received and - # answered. A write that raises this was applied, so it is not to be sent - # again, and a record that was being saved or destroyed is left as saved or - # destroyed. A save is taken as applied only where the answer said it was - # JSON, as Zammad's does: see {Resources::Base#save!}. - class IncompleteResponseError < ConnectionError - # @return [Response, nil] the response as far as it arrived - attr_reader :response - - # @param message [String, nil] - # @param response [Response, nil] - def initialize(message = nil, response: nil) - super(message) - @response = response - end - end - # Raised when a request exceeded {Config#open_timeout} or {Config#timeout}. class TimeoutError < TransportError; end # Raised when a response did not have the shape the caller expected. class ParseError < Error # @param operation [String] - # @param expected [Symbol, String] +:object+, +:array+, or a longer - # description of the shape that was wanted - # @param actual [Class, String] the class that was decoded instead, or a - # description of it + # @param expected [Symbol, String] +:object+ or +:array+ + # @param actual [Class, String] what was decoded instead # @param resource_class [Class, nil] # @return [ParseError] def self.build(operation:, expected:, actual:, resource_class: nil) @@ -71,29 +46,18 @@ def self.build(operation:, expected:, actual:, resource_class: nil) end end - # Raised when the server answers a page request with the page before it, - # and that page, asked for again, still holds the same records. It is - # ignoring +page+ then, and a collection walk would never end. + # Raised when an endpoint answers a page request with the same records as + # the page before it. It is ignoring +page+ then, and a walk would never end. class PaginationError < Error - # What to do about an index that repeats its first page, which is what - # one that serves every record in a single response does. Said as a - # condition, because the same two pages come from an endpoint that - # serves only the first of many and ignores +page+, and that one is not - # to be read as whole. - UNPAGINATED_ADVICE = 'If this endpoint serves every record in one response, declare `paginated false` on the resource, ' \ - 'and it is read in one request.' - # @param operation [String] # @param page [Integer] the page that repeated its predecessor # @param resource_class [Class, nil] - # @param index [Boolean] whether an index endpoint was being walked, - # which is the kind a resource may declare as not paginated. A search - # always pages. # @return [PaginationError] - def self.build(operation:, page:, resource_class: nil, index: false) - message = "Can't #{subject_for(operation, resource_class)}: page #{page} repeated page #{page - 1}, so the endpoint is ignoring the page parameter" - - new(index && page == 2 ? "#{message}. #{UNPAGINATED_ADVICE}" : message) + def self.build(operation:, page:, resource_class: nil) + new( + "Can't #{subject_for(operation, resource_class)}: page #{page} repeated page #{page - 1}, so the endpoint is " \ + 'ignoring the page parameter. If it serves every record in one response, declare `paginated false` on the resource.' + ) end end @@ -148,12 +112,8 @@ def initialize(operation:, response: nil, resource_class: nil, detail: nil) super(build_message) end - # The status this error carries, or - for one this gem raised without a - # request, such as {ResourceProxy#find_by!} finding nothing - the status - # its class is the name for. A NotFoundError used to answer nil there, - # so `rescue NotFoundError => e; retry if e.status == 404` quietly stopped - # retrying for the one NotFoundError that came from this gem rather than - # from Zammad, while every other one carried 404. + # The status of the response, or, for an error raised without one such as + # {ResourceProxy#find_by!} finding nothing, the status its class stands for. # # @return [Integer, nil] HTTP status code def status @@ -175,9 +135,6 @@ def headers def server_message return nil if !body.is_a?(Hash) - # Symbol keys only: both decode paths - Transport#decode_body and the - # test kit - parse with symbolize_names, so a string-keyed body cannot - # reach here and the fallbacks that read one were never run. value = body[:error_human] || body[:error] value.to_s.empty? ? nil : value.to_s end @@ -213,20 +170,11 @@ class ValidationError < ClientError; end # 429 - too many requests. class RateLimitError < ClientError - # @return [Integer, nil] value of the +Retry-After+ response header + # @return [Integer, nil] value of the +Retry-After+ response header, in seconds def retry_after - # Downcased, because every {Response} is built with its header keys - # downcased - {Transport#decode} and {Test#stub} both do it - so there - # is no capitalised spelling left to fall back to. value = headers['retry-after'] return nil if value.nil? - # In base ten, said outright. Left to itself Integer reads a prefix as - # a radix, so `010` was 8 and `08`, which is no octal number, was nil - - # where the retry middleware waited ten seconds and eight - and `0x10` - # was 16, which is no figure this header carries. A base is only taken - # with text, hence the `to_s`: a Response built by hand may hold the - # figure as an Integer. Integer(value.to_s, 10, exception: false) end end diff --git a/lib/zammad_api/query_encoder.rb b/lib/zammad_api/query_encoder.rb deleted file mode 100644 index fc90b6a..0000000 --- a/lib/zammad_api/query_encoder.rb +++ /dev/null @@ -1,162 +0,0 @@ -# frozen_string_literal: true - -require 'faraday' - -module ZammadAPI - # Writes a query the way Rails reads it back into the structure it was. - # - # Faraday's own encoder did this, and does it for everything but a list of - # Hashes that do not all carry the same keys. A query string has no mark for - # where one element of a list ends: a list of Hashes goes out as - # `list[][key]=value` pairs, and Rack - and the parser Rails 8.1 has of its - # own, which follows it - starts a new element only when a pair names a key - # the element it is filling already has. Faraday writes the keys of every - # Hash in alphabetical order, so the first pair of an element named - # whichever of its keys sorts first, whether or not the element before had - # it. - # - # Zammad's expert conditions are such a list. A group of conditions nests - # them, and a group and a condition share `operator` and nothing else: - # - # conditions: [ - # {name: 'ticket.state_id', operator: 'is', value: [2]}, - # {operator: 'AND', conditions: [a, b]} - # ] - # - # The second element went out `conditions` first, which the first element - # does not have, so Rails read that into the first element and began the - # second at `operator`: one condition holding the whole group, followed by - # a group holding nothing. Zammad was handed a selector nobody wrote. It - # answered this one with a 500, and the same two elements the other way - # round with every ticket there is, as if no condition had been given. - # - # So an element that follows another Hash is written with a value the two - # both have a place for first - see {.lead_path} - and the rest in the - # order they always were. Where there is no such value no order works, and - # {Transport.stringify_query} refuses the query before it gets here. - # - # The escaping is still Faraday's: this hands it the pairs in order, which - # its encoder keeps for a list where it sorts a Hash. - # - # @api private - module QueryEncoder - module_function - - # @param params [Hash, nil] a query as {Transport.stringify_query} leaves - # it - # @return [String, nil] the query string, nil for no query - def encode(params) - return nil if params.nil? - - Faraday::NestedParamsEncoder.encode(hash_pairs(nil, params.to_hash, nil)) - end - - # Reading a query string back is not this module's business, and Faraday - # asks whatever encodes for it: a query written into the instance URL is - # decoded on the way in. - # - # @param query [String, nil] - # @return [Hash, nil] - def decode(query) = Faraday::NestedParamsEncoder.decode(query) - - # The value to write first for a Hash that follows another in a list, so - # that Rails begins a new element with it: one the element before has a - # place for as well, named by the keys that lead to it. - # - # A plain value, reached through Hashes alone. The pair that writes it - # names every key on the way down, and Rails begins a new element where - # the element it is filling has all of them already. A value inside a - # list never begins one, whatever the element before holds. - # - # @param element [Hash] - # @param previous [Object] the element before it - # @return [Array, nil] the keys leading to the value, outermost first. - # nil where no value will do, and where none is needed: the element is - # the first, or follows something that is not a Hash, and begins a new - # one whatever is written first - def lead_path(element, previous) - return nil if !previous.is_a?(Hash) - - sorted_keys(element).each do |key| - # Taken in the element before only where something was written for - # it there. A Hash with no value in it is not written, so the key is - # missing from what Rails read, and a pair naming it is read into - # that element rather than beginning the next. - next if !previous.key?(key) || !written?(previous[key]) - - value = element[key] - next if value.is_a?(Array) - return [key] if !value.is_a?(Hash) - - inner = lead_path(value, previous[key]) - return [key, *inner] if inner - end - - nil - end - - # Why Rails could not read an element of a list back as it was written, - # where it could not. - # - # +:merged+ is a Hash it would read into the Hash before it, there being - # no value to begin a new element with. +:empty+ is a Hash nothing is - # written for, which leaves the list one element short. +:list+ is a - # list directly inside a list: both are written `[]`, and each value of - # the inner one is read as a list of its own. - # - # @param element [Object] - # @param previous [Object] the element before it, nil for the first - # @return [Symbol, nil] nil for an element that is read back as it was - def misread(element, previous) - return :list if element.is_a?(Array) - return nil if !element.is_a?(Hash) - return :empty if !written?(element) - - :merged if previous.is_a?(Hash) && lead_path(element, previous).nil? - end - - # Whether anything is written for a value. Nothing is for a Hash with - # nothing in it, or with nothing but such Hashes in it, so as an element - # of a list it is not there for Rails to read. - # - # @return [Boolean] - def written?(value) = !value.is_a?(Hash) || value.each_value.any? { written?(it) } - - # @param lead [Array, nil] the keys leading to the value to write first - # @return [Array] one pair per value, in the order - # they are written - def hash_pairs(prefix, hash, lead) - keys = sorted_keys(hash) - keys = [lead.first, *(keys - [lead.first])] if lead - - keys.flat_map do |key| - # The rest of the way to the value, for the key that leads to it. - inner = lead && key == lead.first && lead.size > 1 ? lead.drop(1) : nil - - value_pairs(prefix ? "#{prefix}[#{key}]" : key.to_s, hash[key], inner) - end - end - - def value_pairs(path, value, lead = nil) - case value - when Hash then hash_pairs(path, value, lead) - when Array then array_pairs("#{path}[]", value) - else [[path, value]] - end - end - - def array_pairs(path, array) - # A list with nothing in it is written as its name alone, which is what - # Faraday wrote for one. - return [[path, nil]] if array.empty? - - array.each_with_index.flat_map do |element, index| - next value_pairs(path, element) if !element.is_a?(Hash) - - hash_pairs(path, element, index.zero? ? nil : lead_path(element, array[index - 1])) - end - end - - def sorted_keys(hash) = hash.keys.sort_by(&:to_s) - end -end diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index a08ddc6..e0b914b 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -3,8 +3,6 @@ require 'forwardable' require_relative 'collection' -require_relative 'deep_copy' -require_relative 'duplicate_keys' require_relative 'errors' require_relative 'transport' @@ -36,35 +34,9 @@ class ResourceProxy include Enumerable extend Forwardable - # Largest page size Zammad's search endpoints serve, from - # ApplicationController#model_search_render. + # Largest page size Zammad's search endpoints serve. SEARCH_MAX_PER_PAGE = 200 - # What every one of Zammad's search endpoints narrows by besides the term: - # the two parameters that CanSearch, the part all of them share, reads out - # of the call ApplicationController#model_search_render makes into - # Model.search. Unlike an index endpoint a search does narrow, but through - # these parameters and the term - never through an attribute name of its - # own. - # - # That call hands over +role_ids+, +group_ids+ and +permissions+ as well, - # and they used to be in this list for it. Only the user search reads - # them, so a resource says which of them its search takes: see - # {Resources::Base.search_filters}. - SEARCH_FILTER_KEYS = %i[condition ids].freeze - - # Why a search term with nothing in it is refused, and what to write - # for the answer Zammad would have given it: see {#search}. - BLANK_TERM_MESSAGE = 'search needs a non-empty query string: Zammad reads a blank one as no term at all and answers with ' \ - "every record. Search for '*' to ask for every record." - - # Said at the end of the error for sorting an index endpoint that is - # always served in id order, on a resource that can be searched. - SEARCHABLE_UNSORTABLE_HINT = 'A search does sort: search(term).order(...). Or sort what this collection yields, with sort_by { ... }.' - - # The same, for a resource Zammad routes no search endpoint for. - UNSORTABLE_HINT = 'Sort what this collection yields instead, with sort_by { ... }.' - # @return [Class] the resource class this proxy operates on attr_reader :resource_class @@ -84,8 +56,7 @@ def new(attributes = {}) # Builds and immediately saves a record. # - # This raises when Zammad rejects the attributes, rather than handing back - # a record that looks created but is not. Use +new+ and + # This raises when Zammad rejects the attributes. Use +new+ and # {Resources::Base#save} to branch on a validation failure instead. # # @param attributes [Hash] @@ -104,157 +75,36 @@ def create(attributes = {}) # @raise [NotFoundError] when no such record exists def find(id) = resource_class.fetch_one(@transport, id) - # Fetches the first record carrying all of these attribute values, from - # the candidates Zammad hands over: nil if none of them does. - # - # It answers for every resource and every kind of value. Where it walks - # the index, the candidates are every record this client can read, and nil - # means there is no such record. Where it searches, they are the hits, and - # nil means no hit carried the values - which is the same thing only for a - # value the search looks at. See "What the search can surface" below for - # which those are. Zammad cannot be asked the question directly - - # its index endpoints do not filter: ApplicationController#model_index_render - # sorts and pages and drops every other parameter, so a query parameter on - # the index, which is how this was first written, asked for - # +email=someone@example.com+ and got back the whole user index, of which - # it returned the first record. So the candidates are fetched and checked - # here, and there are two ways to fetch them: - # - # - A search, where the resource has a search endpoint and one of the - # values is a string to search on. That is the cheap way: Zammad narrows - # the candidates, and only the hits are read. - # - A walk of the index, everywhere else: +ticket_states+, - # +ticket_priorities+ and +ticket_articles+, which Zammad routes no - # search endpoint for, and a lookup such as +find_by(active: true)+ or - # +find_by(organization_id: 5)+ that has no string in it. That costs a - # request per page of records until one matches, and the whole index for - # a miss - nothing for a list of ticket states, and worth knowing before - # it is run against every ticket on an instance. - # - # Both used to be refused instead: a resource without a search endpoint - # raised, and so did a lookup without a string value. The caller was left - # to write +all.detect { ... }+, which is the walk this now makes, so the - # refusals kept nothing from happening and made +find_by+ a method that - # worked on four resources out of seven. - # - # Values are compared exactly, and against the record as Zammad stores it: - # +find_by(email: 'Someone@Example.com')+ does not match a login Zammad - # downcased. A record that does not carry an attribute does not match it, - # whatever the value - not even +nil+, which would otherwise match every - # record a misspelled name was asked of. - # - # The search term is one string value. Zammad searches by word, so a value - # of another type would go out as the word it prints as: +find_by(active: - # true)+ searched for "true" and matched records carrying that word, which - # is essentially none of them. Such a value is compared here instead. - # - # One value, never all of them joined. An instance searching without - # Elasticsearch matches the term literally, through a SQL LIKE over the - # string columns, so a joined term asks every column to contain the whole - # of it: +find_by(firstname: 'Jane', lastname: 'Doe')+ went out as "Jane - # Doe" and no column of Jane Doe's holds that, so a user that exists came - # back as nil and the +find_by(...) || create(...)+ this documents made a - # duplicate on every run. Single-attribute lookups were unaffected, which - # is why it stood. The longest value goes out, as the most selective of - # them, and every other value is compared here - which is where the - # non-string ones are compared anyway, so +find_by(email: ..., active: - # true)+ searches the email and then checks both. - # - # Values go out as they are. Quoting one that carries search syntax, so - # that it is looked for rather than obeyed, sounds like an improvement and - # is not: an instance searching without Elasticsearch matches the term - # literally, through a SQL LIKE over the string columns, so the quotes - # become characters the value has to contain. That made - # +find_by(name: 'support-eu')+ - a hyphen is syntax - find nothing on - # every such instance, which is how this was found. + # The first record carrying all of these attribute values, or nil. # - # So a value carrying syntax is searched as syntax, and what that surfaces - # depends on the backend. On Elasticsearch +find_by(note: 'a AND b')+ goes - # out as a boolean query, and a value Elasticsearch cannot parse at all - - # an unbalanced +(+ or +"+ - takes SearchIndexBackend#search_by_index down - # the branch that logs the error and returns no hits, so it arrives here - # as a miss rather than as a failure. - # - # What the search can surface is Zammad's business. A value the instance - # has not indexed, or cannot index, is a record this does not find, so - # +find_by(...) || create(...)+ can still create a duplicate - exactly as - # writing the search out by hand would. - # - # Which values those are depends on the backend. Elasticsearch looks for - # the term in everything a record is indexed with. Without it the term is - # matched by the SQL LIKE mentioned above, and that reads a fixed set of - # columns: CanSearch takes the string columns of the model's own table, - # which covers users, organizations and groups, and Ticket::Search - # replaces that with the ticket's title and number and the from, to, - # subject and body of its articles. A name +expand+ adds for an - # association is not a column at all. So on such an instance - # +tickets.find_by(state: 'open')+, a ticket looked up by a custom - # attribute, and +users.find_by(organization: 'Acme')+ are searches for a - # word in fields that do not hold the value. They find the record only - # where the word happens to appear in one of those fields too, and - # otherwise answer nil for a record that exists. - # - # There is no walk of the index after a search that found nothing, which - # would close that gap. A miss is the ordinary case for what this is most - # used for - +find_by(email: ...) || create(...)+ on an address that is - # new - and the walk would turn each of them into a read of every user on - # the instance, a thousand to the request, to confirm what the search had - # already said correctly. Nothing here can tell that miss from one caused - # by a field the search does not read, because nothing in a response says - # which backend answered. The caller does know which lookup they are - # writing: +detect { ... }+ on the resource is the walk, over every - # record this client may read. Compared with +[]+ there, as it is below, - # because a reader raises for an attribute the record in hand does not - # carry and would end the walk on it. - # - # Every page of hits is read until one matches. Only the first - # {SEARCH_MAX_PER_PAGE} used to be, to keep a miss at one request, on the - # premise that hits come back by relevance and an exact match is at the - # top of them or nowhere. They do not: Zammad's search endpoints sort by - # +updated_at+, newest first, unless told otherwise, on the SQL path and - # the Elasticsearch one alike. So where more than a page of records - # matched the term - +find_by(name: 'Support')+ among a few hundred - # organizations with "Support" in their name - the one called exactly - # that could sit on any page, +find_by+ answered +nil+ for a record that - # exists, and +find_by(...) || create(...)+ created its duplicate. - # - # So a match costs as many requests as it takes to reach it, and a miss - # costs one per page of hits. The longest value is searched to keep - # those few. - # - # An +id+ among the attributes is not searched for and not walked to. The - # id is what addresses a record, so the record is read by it, as {#find} - # reads it, and then held against the other values: see {#find_by_id}. + # An +id:+ is read with {#find}, in one request. Otherwise, where the + # resource can be searched, the longest String value is the + # search term and the hits are checked against every value. Otherwise + # the index is walked until a record matches. Values are compared + # exactly, and a record that does not carry an attribute does not match it. # # @example - # client.users.find_by(email: 'someone@example.com')&.id + # client.users.find_by(email: 'someone@example.com') # client.ticket_states.find_by(name: 'open') - # client.users.find_by(organization_id: 5, active: true) - # client.tickets.find_by(id: params[:id]) # - # @param params [Hash] attribute names and the values to match exactly - # @return [Resources::Base, nil] nil when nothing matched + # @param params [Hash{Symbol => Object}] + # @return [Resources::Base, nil] # @raise [ArgumentError] when no attribute was given def find_by(**params) raise ArgumentError, 'find_by needs at least one attribute to match' if params.empty? + return find_by_id(params) if params.key?(:id) - id_key = params.keys.find { it.to_s == 'id' } - return find_by_id(params[id_key], as_served(params.except(id_key))) if id_key - - params = as_served(params) - term = resource_class.searchable? ? search_term_for(params) : nil - candidates = term ? search(term) : all + term = params.values.grep(String).reject { it.strip.empty? }.max_by(&:length) + candidates = resource_class.searchable? && term ? search(term) : all - candidates.detect { |record| carries?(record, params) } + candidates.detect { |record| params.all? { |key, value| record.key?(key) && record[key] == value } } end - # Fetches the first record carrying all of these attribute values, raising - # when nothing matched. + # Like {#find_by}, but raises when nothing matched. # - # @param params [Hash] attribute names and the values to match exactly + # @param params [Hash{Symbol => Object}] # @return [Resources::Base] - # @raise [NotFoundError] when nothing matched - # @see #find_by + # @raise [NotFoundError] when no record matched def find_by!(**params) find_by(**params) || raise( NotFoundError.new( @@ -265,37 +115,22 @@ def find_by!(**params) ) end - # Whether a record with this id exists. - # - # This costs one request, and reads the record to find out, because Zammad - # has no cheaper answer for a single id. - # - # A record is one that says which it is. Any 2xx used to count, and - # Zammad answers one with an empty object where it has nothing to show - # the client: `organizations/5` is `{}` for a customer who belongs to no - # organization, whether or not there is an organization 5. That came - # back as true. {#find} still hands over what was served, a record with - # no id. - # # @param id [Integer, String] - # @return [Boolean] + # @return [Boolean] whether a record with that id exists and can be read def exists?(id) - !find(id).id.nil? + find(id) + true rescue NotFoundError false end - # Deletes a record by id, without fetching it first. + # Deletes a record by id, without reading it first. # # @param id [Integer, String] # @return [true] - # @raise [ResponseError] when Zammad rejected the request - # @raise [ParseError] when the request was answered 2xx with a body that - # is not JSON, by something that is not Zammad: see - # {Resources::Base.confirm_destroyed!} + # @raise [NotFoundError] when no such record exists def destroy(id) - response = @transport.delete(member_path(id), operation: 'destroy object', resource_class: resource_class) - resource_class.confirm_destroyed!(response) + @transport.delete(resource_class.member_path(id), operation: 'destroy object', resource_class: resource_class) true end @@ -307,238 +142,36 @@ def all end # @!group Collection shorthands - - # Everything below forwards to {#all}, the {Collection} that decides for - # itself what a missing block means and what a page size is measured - # against. - # - # Named once rather than written out one +def+ at a time. Each was a body - # that did nothing but pass its arguments on, and three carried a - # +steep:ignore+ because forwarding into {Collection}'s with-block and - # without-block overloads cannot be resolved - forwarded by name there is - # no call site left to resolve. What callers are checked against is - # sig/zammad_api/resource_proxy.rbs, where each of these is declared with - # the types {Collection} gives it. - - # @!method order(*attributes, **directions) - # Every record of this kind, sorted by the server. Shorthand for - # +all.order(...)+. - # @example - # client.groups.order(:name) - # client.organizations.order(name: :desc) - # @param attributes [Array] attributes to sort by, - # ascending - # @param directions [Hash{Symbol => Symbol, String}] attributes to sort - # by, each with +:asc+ or +:desc+ - # @return [Collection] - # @raise [ArgumentError] for a resource whose index endpoint does not - # sort - # @see Collection#order - - # @!method each(&block) - # Yields every record of this kind, fetching pages as needed. - # - # This is what makes a proxy +Enumerable+, so +first+, +map+, +lazy+ - # and the rest work straight off +client.groups+. - # @yieldparam record [Resources::Base] - # @return [Enumerator] when no block is given - # @see Collection#each - - # @!method find_each(batch_size: nil, &block) - # @param batch_size [Integer, nil] records fetched per request - # @yieldparam record [Resources::Base] - # @return [Enumerator] when no block is given - # @see Collection#find_each - - # @!method in_batches(of: nil, &block) - # @param of [Integer, nil] records fetched per request - # @yieldparam records [Array] - # @return [Enumerator] when no block is given - # @see Collection#in_batches - - # @!method page(number, per_page: nil) - # @param number [Integer] one-based page number - # @param per_page [Integer, nil] records on the page, as many as the - # endpoint serves by default - # @return [Collection] - # @see Collection#page - - # @!method pluck(*keys) - # @param keys [Array] attribute names - # @return [Array] - # @see Collection#pluck - - # @!method count(*args, &block) - # Overrides +Enumerable#count+ so that a collection counts the way it - # knows how. - # @return [Integer] - # @see Collection#count - - # @!method size - # @return [Integer] - # @see Collection#size - - # @!method length - # @return [Integer] - # @see Collection#size - - # @!method empty? - # @return [Boolean] - # @see Collection#empty? - - # @!method any?(*pattern, &block) - # Overrides +Enumerable#any?+ so that, without a block or a pattern, it - # asks for one record rather than a page. - # @return [Boolean] - # @see Collection#any? - - # @!method none?(*pattern, &block) - # Overrides +Enumerable#none?+ the same way. - # @return [Boolean] - # @see Collection#none? - - # @!method first(count = nil) - # Overrides +Enumerable#first+ so that it reads one sized page rather - # than taking records off the front of one sized for walking. - # @param count [Integer, nil] how many records to read - # @return [Resources::Base, Array, nil] - # @see Collection#first - - # @!method take(count) - # @param count [Integer] how many records to read - # @return [Array] - # @see Collection#take - - # @!method each_slice(size, &block) - # Overrides +Enumerable#each_slice+, which asks for the +size+ before it - # slices, and so read every record twice. - # @param size [Integer] records in a group - # @yieldparam records [Array] - # @return [Enumerator] when no block is given - # @see Collection#each_slice - - # @!method each_cons(size, &block) - # Overrides +Enumerable#each_cons+ the same way. - # @param size [Integer] records in a run - # @yieldparam records [Array] - # @return [Enumerator] when no block is given - # @see Collection#each_cons - - # @!method lazy - # Overrides +Enumerable#lazy+, whose enumerator hands the same question - # on to +size+. - # @return [Enumerator::Lazy] - # @see Collection#lazy - - def_delegators :all, :order, :each, :find_each, :in_batches, :page, :pluck, :count, :size, :length, :empty?, :any?, :none?, :first, :take, :each_slice, :each_cons, :lazy - + # These forward to {#all}; see {Collection} for each. + def_delegators :all, :order, :each, :find_each, :in_batches, :page, :pluck, :count, :empty?, :first # @!endgroup # Records matching a Zammad search term, as a lazily paginated collection. # - # The keywords are the other things a search endpoint narrows by. They - # are named here, on the call that searches, because they mean nothing - # anywhere else: they used to be passed to +where+ on the collection this - # returns, the one place that method accepted more than a sort. - # - # Anything else is refused rather than sent. Zammad drops a parameter it - # does not know, so +search('smith', active: true)+ would come back - # unnarrowed and nothing would say so. An attribute value belongs in the - # term, and a sort in {Collection#order}. - # - # That goes for a keyword another resource's search reads, too. - # +role_ids:+, +group_ids:+ and +permissions:+ narrow a user search and no - # other, and +client.tickets.search('printer', group_ids: [2])+ was sent - # as written and answered with tickets from every group the client can - # read. Tickets are narrowed by group through a +condition+ on - # +ticket.group_id+. - # - # +group_ids:+ comes in two forms, and they do not ask for the same - # thing. User::Search walks it as pairs of a group and an access, and - # HasGroups.group_access reads an access that is missing as +full+. So a - # list of ids, which names none, is the agents with full access to those - # groups, and +group_ids: [2]+ leaves out an agent who may only read - # group 2. A Hash names the access for each group, and +full+ always - # counts as having it: +group_ids: {2 => ['read']}+ is every agent with - # read or full access to group 2. - # - # A keyword with nothing in it is refused as well: an empty list, an - # empty Hash, a blank String. Zammad reads each of those as the keyword - # not having been given, the way it reads one it does not know. CanSearch - # narrows by +ids+ only where +params[:ids].present?+, so - # +search('smith', ids: allowed_ids)+ with no id allowed came back with - # every user matching the term, where the caller had asked for none of - # them. +role_ids+, +group_ids+ and +permissions+ are skipped the same - # way where the search runs through Elasticsearch, and an empty - # +condition+ does not reach the request at all. - # - # +permissions:+ is not an access check, and is sent as it is given all - # the same, because what it does is Zammad's to decide. User::Search - # resolves it to the roles granting one of the permissions and adds them - # to +role_ids+, so the two together widen each other. On the - # Elasticsearch path the role clause is then written only where there is - # a role to put in it: a permission no active role grants - a misspelt - # one, or one nobody has been given - resolves to none, the clause is - # left out, and the search answers with every user matching the term. - # The SQL path joins the roles against the empty list and answers with - # nobody. Nothing in a response says which path answered, and a user - # record carries role ids rather than permissions, so there is nothing - # here to check the hits against. +role_ids:+ with at least one id - # narrows on both paths. - # - # +role_ids:+ is no access check either. Both paths ask who holds the - # role - the SQL one joins the roles a user has, the Elasticsearch one - # matches the role ids a user is indexed with - and neither asks whether - # the role is active, which is what Zammad asks before it grants - # anything through one: Role.with_permissions leaves a disabled role - # out. Neither asks whether the user is active. So a user matches a role - # that grants nothing any more, and the hits are who to look at, not who - # may. + # Keywords are passed to the search endpoint as they are, for what it + # narrows by besides the term, such as +condition:+ and +ids:+, or + # +role_ids:+ for users. # # @example - # client.users.search('smith') + # client.tickets.search('state.name:open').first(10) # client.users.search('smith', role_ids: [2]) - # client.users.search('smith', group_ids: [2]) # full access to group 2 - # client.users.search('smith', group_ids: {2 => ['read']}) # read or full access to it - # client.tickets.search('printer', condition: {'ticket.state_id' => {operator: 'is', value: [1, 2]}}) - # client.tickets.search('state.name:open').order(created_at: :desc) # - # A term with nothing in it is refused: Zammad reads it as no term, and - # answers with every record the filters and the account allow, which is - # what a search for a blank +params[:q]+ ought not to come back with. - # Nothing is what Rails calls blank, Unicode spaces included. `'*'` - # asks for that answer in so many words, which is how Zammad's own - # interface lists every user or organization, and is sent. - # - # @param term [String] the Zammad search term, `'*'` for every record - # @param filters [Hash] +condition:+ and +ids:+ on every search, and on - # users +role_ids:+, +permissions:+ and +group_ids:+ - the last as a - # list of group ids, for agents with full access to them, or as a Hash - # of group id to +read+, +create+, +change+, +overview+ or +full+, one - # or several + # @param term [String] a Zammad search query; +'*'+ matches every record + # @param filters [Hash{Symbol => Object}] further search parameters # @return [Collection] - # @raise [ArgumentError] when +term+ is not a non-empty string, or for a - # keyword the search endpoint does not read, a nil value, a keyword - # with nothing in it, two spellings of one key, or a list a query - # string cannot carry: see {Transport.stringify_query_list} - # @raise [Error] when Zammad routes no search endpoint for this resource + # @raise [Error] for a resource Zammad routes no search endpoint for + # @raise [ArgumentError] for a blank term, which Zammad reads as no term + # and answers with every record def search(term, **filters) - searchable! - raise ArgumentError, BLANK_TERM_MESSAGE if !term.is_a?(String) || Transport::BLANK.match?(Transport.wire_text(term, 'the search term')) + raise Error, "Zammad routes no search endpoint for #{resource_class.name}: look a record up with find_by, which walks the records instead" if !resource_class.searchable? + raise ArgumentError, "search needs a non-empty query string. Search for '*' to ask for every record." if !term.is_a?(String) || term.strip.empty? collection( "#{path}/search", 'get .search of object', - # A copy of the term and the filters, taken here. The collection is - # lazy, so it reads them when it is enumerated, and it was reading the - # caller's own objects: `search('printer', ids: ids)` followed by - # `ids << 7`, or a term built up in a buffer that is then reused, - # searched for something other than what this call was given - after - # it had been checked, and with the collection already handed on. - query: DeepCopy.frozen_copy({ query: term }.merge(search_filters(filters))), + query: { query: term, **filters }, max_per_page: SEARCH_MAX_PER_PAGE, sortable: true, - # Every search endpoint pages, whatever the index beside it does. paginated: true, search: true ) @@ -550,184 +183,25 @@ def inspect = "#<#{self.class.name} #{resource_class.name}>" def collection(path, operation, query: {}, max_per_page: resource_class.page_limit, sortable: resource_class.sortable?, paginated: resource_class.paginated?, search: false) Collection.new( - transport: @transport, - resource_class: resource_class, - path: path, - operation: operation, - max_per_page: max_per_page, - sortable: sortable, - unsortable_hint: resource_class.searchable? ? SEARCHABLE_UNSORTABLE_HINT : UNSORTABLE_HINT, - search: search, - paginated: paginated, - query: { expand: true }.merge(query) + transport: @transport, + resource_class: resource_class, + path: path, + operation: operation, + max_per_page: max_per_page, + sortable: sortable, + search: search, + paginated: paginated, + query: { expand: true }.merge(query) ) end - # The keywords of a search, checked at the call that wrote them. - # - # Through what {Transport.stringify_query} is made of, for the refusals - # it makes at any depth - a nil value, two spellings of one key inside a - # +condition+, a list of conditions a query string cannot keep apart - # and, once the keywords themselves were asked, a Hash further in that - # holds no value - because left to the request they would be reported - # when the collection is first enumerated, some lines away from the - # search that wrote them. - # What it returns is what each keyword is asked about below, and not what - # is sent: the collection sends the values as they were given - a copy of - # them, see {#search} - and the transport stringifies them then, the - # same way. - # - # @return [Hash{Symbol => Object}] - # @raise [ArgumentError] - def search_filters(filters) - normalized = DuplicateKeys.normalize(filters) { it.to_s.to_sym } - unknown = normalized.keys - search_filter_keys - raise ArgumentError, unknown_search_filter_message(unknown) if !unknown.empty? - - sent = Transport.stringify_query_hash(normalized, nil) - empty = normalized.select { |name, _| empty_search_filter?(sent.fetch(name.to_s)) } - raise ArgumentError, empty_search_filter_message(empty) if !empty.empty? - - Transport.refuse_unwritten!(sent, nil) - normalized - end - - # Whether Zammad would read a keyword's value as the keyword not having - # been given: what Rails calls blank, asked of the value as it goes on - # the wire. Asked of that and not of the value as given, because a - # Symbol or anything else with an empty +to_s+ is sent as an empty - # String, and a Hash that holds nothing but empty Hashes is not written - # at all - `condition: {'ticket.state_id' => {}}` left the request - # without a +condition+. - # - # Asked of the keyword's own value and not of what is nested in it - a - # +condition+ naming an attribute with an empty +value+ is a selector, - # and what that selects is Zammad's to say. An empty list is written, - # so a Hash holding one is not empty here. - # - # Blank as Rails reads it, Unicode spaces included: see - # {Transport::BLANK}. - # - # @param value [String, Array, Hash] as {Transport.stringify_query} - # leaves it - def empty_search_filter?(value) - case value - when String then Transport::BLANK.match?(value) - when Array then value.empty? - else !QueryEncoder.written?(value) - end - end - - def empty_search_filter_message(empty) - given = empty.map { |name, value| "#{name}: #{value.inspect}" }.join(', ') - - "search was given #{given} on #{path}, and Zammad reads a keyword with nothing in it as one that was not given: " \ - 'the search would come back with everything matching the term, not narrowed to nothing. ' \ - 'Leave the keyword out to search without it, and skip the search where there is nothing it may find.' - end - - # What the search endpoint of this resource narrows by besides the term. - # - # @return [Array] - def search_filter_keys = SEARCH_FILTER_KEYS + resource_class.search_filter_names - - def unknown_search_filter_message(unknown) - "search does not take #{unknown.join(', ')} on #{path}: this search endpoint narrows by the term, and by #{search_filter_keys.join(', ')}, " \ - 'and drops anything else, which would hand back an unnarrowed search. ' \ - "Put an attribute value in the term - search('state.name:open') - or in a condition - " \ - "search(term, condition: {'ticket.group_id' => {operator: 'is', value: [2]}}) - " \ - 'sort with search(term).order(...), and page with page, in_batches or find_each.' - end - - # Zammad routes a search endpoint per model, not for every model: users, - # organizations, tickets and groups have one, ticket states, ticket - # priorities and ticket articles do not. Asking one of the latter for - # `.../search` is a 404, which would arrive as a NotFoundError about a - # record from a call that asked for a list. - def searchable! - return if resource_class.searchable? - - raise Error, "Zammad routes no search endpoint for #{resource_class.name}, so it cannot be searched by term: #{path}/search answers 404, which would arrive here as a NotFoundError about a record. Look one record up by attribute value with find_by, which walks the records where it cannot search, or pick several out with select { ... }." - end - - # The record with this id, where it carries the other values as well. - # - # {#find_by} looked for an id the way it looks for any value, and an id - # is the one value that cannot be found that way. Given as the Integer - # it is, there was no String to search on, so the index was walked a - # page at a time until the record came by: `tickets.find_by(id: 123456)` - # read every ticket before it. Given as the String a request parameter - # is, `find_by(id: params[:id])`, the text was searched for, and each hit - # was asked whether its id was that String, which the id of a record, - # an Integer, never is: nil, for a record that was among the hits. - # - # One request, the one {#find} makes, and nil where it answers 404. The - # id is taken as a number or as the digits of one, since that is what - # tells which record was asked for. Anything else is the id of no - # record, and is answered without a request: a nil out of a parameter - # that was not sent, or a word, which would be read as another endpoint - # of the same path, as `users/me` is. - # - # The record that comes back is held against the number as well: Zammad - # answers an organization it will not show with an object that carries - # no id, which is the record with no id of {#exists?}. - # - # @param id [Object] the value given for +id+ - # @param others [Hash] the other attribute values to match - # @return [Resources::Base, nil] - def find_by_id(id, others) - number = record_number(id) - return nil if number.nil? - - record = find(number) - record if record.id == number && carries?(record, others) + def find_by_id(params) + record = find(params.fetch(:id)) + record if params.except(:id).all? { |key, value| record.key?(key) && record[key] == value } rescue NotFoundError nil end - # The number an id names: the Integer it is, or the one a String of - # digits writes. - # - # @return [Integer, nil] nil for anything else - def record_number(id) - return id if id.is_a?(Integer) - - Integer(id, 10) if id.is_a?(String) && id.ascii_only? && id.match?(/\A\d+\z/) - end - - # The values to match, with text as Zammad serves it: in UTF-8. - # - # A value is searched for as the text {Transport.wire_text} sends, and - # every hit was then held against the value as it was given. Ruby takes - # two Strings in different encodings for different ones unless both are - # plain ASCII, so a name read from a file in ISO-8859-1, or held in - # UTF-16, was found by the search and passed over by the comparison: - # nil for a record that was among the hits, and - # `find_by(...) || create(...)` made its duplicate. - # - # @return [Hash] - # @raise [ArgumentError] for text that cannot be converted to UTF-8 - def as_served(params) = params.to_h { |key, value| [key, value.is_a?(String) ? Transport.wire_text(value, "find_by #{key}") : value] } - - # Whether a record carries every one of these values. - # - # Read with +[]+ and not with a reader, which raises for an attribute - # the record in hand does not carry. - def carries?(record, params) = params.all? { |key, value| record.key?(key) && record[key] == value } - - # The one value {#find_by} searches on: the longest, as the most selective - # of them, which matters because a miss reads every page of hits. - # - # One value rather than all of them joined, and unquoted - both spellings - # find nothing on an instance without Elasticsearch, for the same reason. - # See {#find_by}. - # - # @return [String, nil] nil when no value can be searched on, in which - # case the index is walked instead - def search_term_for(params) = params.values.grep(String).reject { it.strip.empty? }.max_by(&:length) - def path = resource_class.resource_path - - def member_path(id) = resource_class.member_path(id) end end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 807ef57..65bd027 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -3,7 +3,6 @@ require_relative '../associations' require_relative '../attribute_access' require_relative '../deep_copy' -require_relative '../duplicate_keys' require_relative '../errors' require_relative '../transport' @@ -22,28 +21,12 @@ module Resources class Base include AttributeAccess - # Largest page size Zammad's generic index endpoints serve, from - # ApplicationController#model_index_render via CanPaginate. Resources + # Largest page size Zammad's generic index endpoints serve. Resources # whose endpoint caps lower declare +max_per_page+. DEFAULT_MAX_PER_PAGE = 1000 - # Guards the class-level memos on the singleton below. One lock for every - # resource, because it is held only while a memo is first built. - MEMO_LOCK = Mutex.new - private_constant :MEMO_LOCK - - # Staged changes as +attribute => [old_value, new_value]+. - # - # A copy, and frozen: writing to the change set a record hands out would - # decide what the next +save+ sends. An {Attributes}, so that the error - # for such a write does not quote a password that is staged. - # - # @return [Hash{Symbol => Array(Object, Object)}] - def changes = Attributes[@changes].freeze - # The validation failure from the most recent {#save}, so that a +false+ - # return value can be acted on. Cleared when the next save is attempted, - # so it never describes anything but the most recent one. + # return value can be acted on. # # @return [ValidationError, nil] attr_reader :error @@ -62,46 +45,13 @@ def path(value) # Declares that Zammad routes a +/search+ endpoint for this resource. # - # Declared rather than assumed, and false unless a resource says - # otherwise: an unrouted `.../search` answers 404, which arrives as a - # NotFoundError from inside {ResourceProxy#find_by} - a method - # documented to return nil when nothing matched. A resource that - # forgets to declare this is refused at the call site instead, which - # is a question about the resource rather than a wrong answer about a - # record. - # # @param value [Boolean] # @return [void] def searchable(value) @searchable = value end - # Declares what this resource's search endpoint narrows by, besides - # the term and the two filters every search reads. - # - # Every search endpoint goes through - # ApplicationController#model_search_render, which hands the same - # parameters to the search of whichever model it was asked for. What - # that search does with them is the model's own business. +condition+ - # and +ids+ are read by the part all of them share, CanSearch, and - # need no declaring. +role_ids+, +group_ids+ and +permissions+ are - # read by User::Search and by no other: a ticket search handed - # +group_ids+ takes it, drops it and answers unnarrowed, on the SQL - # path and the Elasticsearch one alike. - # - # Declared rather than accepted everywhere, so that - # {ResourceProxy#search} can refuse a keyword this resource's search - # would drop - the same refusal it makes for a keyword no search - # reads at all. - # - # @param names [Array] - # @return [void] - def search_filters(*names) - @search_filters = names.map(&:to_sym).freeze - end - - # Declares the largest page size this resource's index endpoint - # serves. + # Declares the largest page size this resource's index endpoint serves. # # @param value [Integer] # @return [void] @@ -109,18 +59,8 @@ def max_per_page(value) @max_per_page = value end - # Declares whether this resource's index endpoint sorts. - # - # ApplicationController#model_index_render builds its query as - # `reorder(order_sql).offset(...).limit(...)`: it reads +sort_by+ and - # +order_by+, pages, and drops every other parameter. That is the - # default, so a resource says nothing. One whose controller hardcodes - # the order declares +sortable false+, and {Collection#order} then - # refuses it rather than handing back records it would be calling - # sorted. - # - # There is no attribute filtering on an index endpoint at all; that - # is what /search is for. + # Declares whether this resource's index endpoint reads +sort_by+ and + # +order_by+. One that does not is refused by {Collection#order}. # # @param value [Boolean] # @return [void] @@ -128,32 +68,8 @@ def sortable(value) @sortable = value end - # Declares whether this resource's index endpoint pages. - # - # ApplicationController#model_index_render reads +page+ and - # +per_page+, and every resource this gem models is served by it. - # That is the default, so a resource says nothing. Not every index - # is: ObjectManagerAttributesController#index renders - # `ObjectManager::Attribute.list_full`, every attribute in one - # response, and reads no parameter at all. - # - # Such an index could not be read. A {Collection} asks for the page - # after a full one, was answered with the same list again, and - # raised {PaginationError} for it - correctly, as far as it could - # tell, because an endpoint that ignores +page+ and serves only the - # first of many pages looks the same. A resource that declares - # +paginated false+ says which of the two it is: its index is read - # in one request, and {Collection#page} refuses it. - # - # Declare it only for an endpoint that does serve every record. One - # that caps what it serves and ignores +page+ would be read as far - # as its cap and no further, with nothing to say so. - # - # A search is not affected. Every search endpoint pages. - # - # Whether the index sorts is not affected either: that is - # {.sortable}, a declaration of its own. An endpoint that reads no - # parameter at all, as the one below, says both. + # Declares whether this resource's index endpoint pages. One that + # serves every record in one response is read in one request. # # @example # class ObjectAttribute < ZammadAPI::Resources::Base @@ -169,6 +85,7 @@ def paginated(value) end # @return [String] the API path of this resource + # @raise [Error] when the resource declares none def resource_path declaration(:path) || raise(Error, "#{name} does not declare an API path") end @@ -176,185 +93,58 @@ def resource_path # @return [Boolean] whether Zammad routes a +/search+ endpoint here def searchable? = declaration(:searchable) { false } - # @return [Array] what this resource's search endpoint narrows - # by besides the term, +condition+ and +ids+ - def search_filter_names - declaration(:search_filters) do - [] #: Array[Symbol] - end - end - # @return [Integer] the largest page size this endpoint serves def page_limit = declaration(:max_per_page) { DEFAULT_MAX_PER_PAGE } - # @return [Boolean] whether this resource's index endpoint reads - # +sort_by+ and +order_by+ + # @return [Boolean] whether the index endpoint reads +sort_by+ and +order_by+ def sortable? = declaration(:sortable) { true } - # @return [Boolean] whether this resource's index endpoint reads - # +page+ and +per_page+ + # @return [Boolean] whether the index endpoint reads +page+ and +per_page+ def paginated? = declaration(:paginated) { true } - # The API path of one record of this kind. - # - # The id is escaped rather than interpolated, so that one taken from a - # request parameter cannot walk out of its segment into another - # endpoint. Held here because {ResourceProxy} builds this path too, - # from an id a caller handed it, and an escaping rule kept in two - # places is one that gets changed in one of them. + # The API path of one record of this kind, with the id escaped. # # @api private # @param id [Integer, String] # @return [String] - # @raise [ArgumentError] when the id cannot go into a path segment def member_path(id) = "#{resource_path}/#{Transport.escape_path_segment(id)}" # Reads one record by id. # - # On the resource rather than on {ResourceProxy}, because both callers - # of it need a proxy for nothing else: {ResourceProxy#find} has one, - # and {Associations::Proxy} was building a throwaway per association - # read until it grew a second copy of this instead. The resource - # already knows its member path and how to build itself from a body, - # which is the whole of the read. - # # @api private # @param transport [Transport] # @param id [Integer, String] # @return [Base] def fetch_one(transport, id) operation = 'find object' - response = transport.get( - member_path(id), - operation: operation, - resource_class: self, - query: { expand: true } - ) - from_response(transport, response.decoded(:object, operation: operation, resource_class: self)) - end - - # Refuses a 2xx to a DELETE that is not an answer Zammad gives to one. - # - # Zammad answers a DELETE with no body at all, for a ticket, and - # with an empty JSON object for what it destroys through - # ApplicationController#model_destroy_render. So a 2xx with a body - # that does not say it is JSON is the page of something in front of - # Zammad that never passed the request on - the login page of a - # single sign-on gateway, the default page of a load balancer - and - # the record is still there. Every 2xx was taken for Zammad's: - # `group.destroy` answered true to such a page and left the record - # destroyed, so nothing more could be asked of it, with the group - # still in Zammad. - # - # A 2xx with no body cannot be told from Zammad's own, and is taken - # for it. - # - # Here for the two callers that send a DELETE, {#destroy} and - # {ResourceProxy#destroy}. - # - # @api private - # @param response [Response] - # @return [Response] - # @raise [ParseError] when the body is neither empty nor JSON - def confirm_destroyed!(response) - return response if response.raw_body.to_s.empty? || response.json? || response.json_content_type? + response = transport.get(member_path(id), operation: operation, resource_class: self, query: { expand: true }) - content_type = response.headers['content-type'].to_s - raise ParseError.build( - operation: 'destroy object', - expected: 'body or none', - actual: content_type.empty? ? 'a body that names no content type' : content_type, - resource_class: self - ) + from_response(transport, response.decoded(:object, operation: operation, resource_class: self)) end # Builds a record that is already stored in Zammad. # - # Straight to the state, past the constructor's refusal of attributes - # a caller may not stage. Zammad serves +id+ in every body it answers - # with, and +id+ is the one attribute that refusal exists for. - # # @api private # @param transport [Transport] # @param attributes [Hash] # @return [Base] def from_response(transport, attributes) - record = allocate - record.send(:setup, transport, attributes) + record = new(transport, attributes) record.send(:mark_persisted!) record end - # Every association declared on this resource, including inherited - # ones. + # Every association this resource declares, including inherited ones. # # @return [Hash{Symbol => Hash}] def associations - ancestors - .select { it.respond_to?(:declared_associations, true) } - .reverse - .inject({}) { |result, ancestor| result.merge(ancestor.send(:declared_associations)) } - end - - # The attributes a +belongs_to+ reader resolves through, so that - # writing one can drop the record it had already resolved to. - # - # Both of the class-level memos here are built under one lock, because - # a plain `@x ||=` is a write to shared state that two threads can - # reach at once: on JRuby or TruffleRuby each could see the ivar unset - # and build a different anonymous proxy class for the same resource, - # and whichever write lost would still be held by the records already - # built from it. - # - # Populating them eagerly was the earlier answer, first on first use, - # then in `Client#setup`, then at require time. Each move shrank the - # window without closing it: `Client.new` is itself something two - # threads can call, and a resource a caller subclasses themselves - - # `class MyTicket < Ticket; end`, which this gem supports - is never in - # any list built ahead of time. - # - # The unlocked read first, so the settled case stays a plain ivar read: - # this is asked on every attribute write, and a lock on that path would - # cost far more than the one build it guards. - # - # @api private - # @return [Array] - def belongs_to_foreign_keys - @belongs_to_foreign_keys || MEMO_LOCK.synchronize { @belongs_to_foreign_keys ||= associations.filter_map { |_, spec| spec[:foreign_key] if spec[:type] == :belongs_to } } - end - - # The class carrying this resource's association readers, reached - # through {Base#related}. - # - # @api private - # @return [Class] - def related_class - return @related_class if @related_class - - # A resource's proxy inherits its parent's readers, so Base's - # created_by and updated_by reach every resource. The parent is - # resolved before the lock is taken, because resolving it may build - # the parent's own proxy through this same method and a Mutex is not - # reentrant. - parent = superclass.respond_to?(:related_class) ? superclass.related_class : Associations::Proxy # steep:ignore NoMethod - MEMO_LOCK.synchronize { @related_class ||= Class.new(parent) } + inherited = superclass.respond_to?(:associations) ? superclass.associations : {} # steep:ignore NoMethod + inherited.merge(declared_associations) end private - # Reads a declaration from this class, or failing that from the - # resource it inherits from. - # - # A plain class-level ivar is not inherited, so `class MyTicket < - # Ticket; end` used to inherit all nine of Ticket's associations, its - # page limit and its searchability, and lose only its API path - - # `MyTicket.resource_path` raised "does not declare an API path" from - # a class that plainly did. {.associations} and {.related_class} both - # walk the ancestry deliberately; these read through the same way. - # - # `instance_variable_defined?` rather than a truth test, so that a - # resource may declare a value that is false or nil and have it - # override an inherited one. + # A declaration of this class, or failing that of the class it inherits from. def declaration(name, &default) variable = :"@#{name}" return instance_variable_get(variable) if instance_variable_defined?(variable) @@ -366,64 +156,19 @@ def declaration(name, &default) def declared_associations = @declared_associations ||= {} # Declares that this resource points at a single other record, through - # a foreign key on itself. - # - # The reader lands on {Base#related}, not on the record, because Zammad - # already expands the association into a name under the plain - # attribute: +ticket.customer+ is a login, +ticket.related.customer+ is - # the User record. + # a foreign key on itself. Read through +record.related.+. # # @param name [Symbol] name of the reader on {Base#related} - # @param class_name [String] the target resource, named rather than - # referenced so that two resources may point at each other. A - # resource of this gem by its own name, +'User'+; one a caller - # declared by its full name, +'Acme::Role'+ + # @param class_name [String] the target resource: one of this gem by its + # own name, +'User'+, or another by its full name, +'Acme::Role'+ # @param foreign_key [Symbol] attribute holding the target's id # @return [void] def belongs_to(name, class_name:, foreign_key: :"#{name}_id") - # Under the lock the list of foreign keys is built under, so that - # one being built meanwhile is either built with this declaration - # in it or dropped here once it stands. - MEMO_LOCK.synchronize do - declared_associations[name] = { type: :belongs_to, class_name: class_name, foreign_key: foreign_key } - forget_foreign_keys - end - # The block runs against a Proxy instance, which the type checker - # cannot see through define_method. - related_class.define_method(name) { belongs_to_target(name, class_name, foreign_key) } # steep:ignore NoMethod - end - - # Drops the list {.belongs_to_foreign_keys} keeps, here and on every - # class that inherits what this one declares. - # - # The list is built at the first write to an attribute of a record - # and was kept from then on. A `belongs_to` declared after that - on - # a class reopened to add one, or declared late in a file that had - # built a record further up - was never in it, so a write to its - # foreign key left the association alone: `related.role` went on - # answering role 5 after `role_id = 6`. A subclass keeps a list of - # its own that holds the keys of its ancestors, so its list goes too. - def forget_foreign_keys - @belongs_to_foreign_keys = nil - subclasses.each { it.send(:forget_foreign_keys) } + declared_associations[name] = { type: :belongs_to, class_name: class_name, foreign_key: foreign_key } end - # Declares that this resource points at a list of other records, - # served by an endpoint of its own. - # - # The path has to name an endpoint that serves the whole list in one - # response, which is what the association endpoints Zammad routes do: - # TicketArticlesController#index_by_ticket renders every article of - # the ticket and reads no paging parameter. The reader spends one - # request and hands back an Array rather than a walking {Collection}. - # - # Nothing here can tell a whole list from the first page of one, so - # declaring this for an endpoint that pages would return that page - # and no more. This comment used to promise a refusal instead. The - # check behind that promise read a total from a response header - # Zammad has never sent, so it never ran, and it was removed for that - # reason. For an endpoint that pages, declare a resource and walk it - # as a {Collection}. + # Declares that this resource points at a list of other records, served + # whole by an endpoint of its own. Read through +record.related.+. # # @param name [Symbol] name of the reader on {Base#related} # @param class_name [String] the target resource @@ -432,7 +177,6 @@ def forget_foreign_keys # @return [void] def has_many(name, class_name:, path:) declared_associations[name] = { type: :has_many, class_name: class_name, path: path } - related_class.define_method(name) { has_many_target(name, class_name, path) } # steep:ignore NoMethod end end @@ -444,178 +188,72 @@ def has_many(name, class_name:, path:) # @param transport [Transport] # @param attributes [Hash, nil] or what converts to a Hash, such as # permitted `ActionController::Parameters` - # @raise [Error] when an attribute cannot be staged, such as +id+ - # @raise [ArgumentError] when given something that is neither, or when - # an attribute is named twice, as a String and as a Symbol, at any - # depth def initialize(transport, attributes = {}) - # Nil alone is no attributes. Anything else is read as a Hash or - # refused: see {#attribute_hash}. - given = nil.equal?(attributes) ? {} : attribute_hash(attributes) - # The same refusal the writers make, at the one door that did not make - # it. `group.id = 99` is refused with a sentence about what an id is - # for, and `client.groups.new(id: 99)` was accepted in silence - and - # then `save` POSTed `{"id": 99, ...}`, because a new record is sent in - # full. So the one spelling that reached the wire was the one nothing - # checked, and Zammad's answer to it was the first news of the - # mistake. {.from_response} is the way in for a body Zammad served, - # which carries an id precisely because it is a record that has one. - given.each { |key, value| refuse_unwritable!(DeepCopy.symbolize(key), value) } - setup(transport, given) + @transport = transport + @attributes = frozen_attributes(Hash(attributes)) # steep:ignore UnresolvedOverloading + @baseline = @attributes + @new_record = true + @destroyed = false + @error = nil + @related = nil end - # Gives a +dup+ or +clone+ the state of its own that a write changes. - # - # The attributes need nothing done: they are frozen and replaced on - # write, so a copy sharing them never sees the original's next write. - # The change set is written in place, and the copy shared it: after - # +copy = record.dup; copy.name = 'X'+ the original reported - # +changed?+ and a change to +name+ while still reading +name+ as it - # was, and its next +save+ sent the copy's value - a change it had - # never shown. - # - # The association proxy goes too. It reads through the record it was - # built for, so a copy holding the original's would resolve its - # associations from the original's foreign keys. - # # @api private # @param source [Base] # @return [void] def initialize_copy(source) super - @changes = @changes.dup @related = nil end # @return [Boolean] whether this record has not been stored yet def new_record? = @new_record - # Whether this record exists in Zammad. - # - # False both before the first save and after {#destroy}, so this is not - # the inverse of {#new_record?}. + # Whether this record exists in Zammad: false both before the first save + # and after {#destroy}. # # @return [Boolean] def persisted? = !@new_record && !@destroyed - # Whether {#destroy} removed this record from Zammad. - # - # The attributes stay readable, so a destroyed record can still be logged - # or reported on; it just no longer stands for anything on the server. - # - # @return [Boolean] + # @return [Boolean] whether {#destroy} removed this record from Zammad def destroyed? = @destroyed - # @return [Boolean] whether there are unsaved changes - def changed? = !@changes.empty? - - # The records this one points at, each fetched on demand. + # Staged changes as +attribute => [old_value, new_value]+. # - # Zammad expands an association into a name under the plain attribute, - # so +ticket.customer+ is already the customer's login. These readers - # return the whole record instead, which costs a request. + # @return [Hash{Symbol => Array(Object, Object)}] + def changes + @attributes.filter_map { |key, value| [key, [@baseline[key], value].freeze] if !@baseline.key?(key) || @baseline[key] != value }.to_h.freeze + end + + # @return [Boolean] whether there are staged changes + def changed? = !changes.empty? + + # The records this one points at. # # @example - # ticket.customer # => "customer@example.com", already loaded - # ticket.related.customer.email # => the same, from the User record - # ticket.related.articles # => [TicketArticle, ...] + # ticket.related.customer # => the User record, one request # # @return [Associations::Proxy] # @raise [Error] when the record was destroyed - # @see .associations def related - # Asked here rather than left to the request. `destroy` drops the memo, - # and that was taken to be the whole of it - but this reader rebuilds - # on the next call, so a destroyed record went on handing out a working - # proxy and `related.articles` fetched the articles of a ticket that is - # gone. Clearing a memo is not refusing a reader, and only the refusal - # is worth asserting: the spec that covered this compared proxy - # identity, so it passed throughout. raise_if_destroyed!('read related records from') - # One proxy for as long as the record lives. What a save, a reload or - # a write to a foreign key invalidates is what the proxy has resolved, - # and {#forget_related_targets} empties that where it is held. - @related ||= self.class.related_class.new(self) + + @related ||= Associations::Proxy.new(self) end - # Stages several attributes as changes, without saving. - # - # @example - # group.assign_attributes(name: 'Support 2', note: 'Renamed') - # group.changed? # => true + # Stages several changes at once. # - # @param attributes [Hash] attribute names and their new values, or - # what converts to a Hash, such as permitted - # `ActionController::Parameters` + # @param attributes [Hash] # @return [self] - # @raise [Error] when an attribute cannot be staged, such as +id+, or - # when the record was destroyed. Nothing is staged in either case, so - # the record is left as it was. - # @raise [ArgumentError] when given something that is neither, nil - # included, or when an attribute is named twice, as a String and as - # a Symbol. Nothing is staged then either. def assign_attributes(attributes) - # Asked before anything else, because everything below is a method - # of Hash. Nil raised NoMethodError naming `each_with_object`, from - # inside the gem, and so did `update(params[:group])` with the key - # missing; an Array of pairs was read as a Hash, by the accident of - # how it is iterated. Refused rather than read as nothing to assign, - # which is what the constructor makes of nil: a record built from - # nothing says so by being empty, and an `update` that staged - # nothing answers true as if it had stored something. - attributes = attribute_hash(attributes) - - # Two spellings of one attribute are refused before anything is - # written, for the reason the constructor refuses them - see - # {DeepCopy.frozen_hash}. Each key is written by its Symbol, so - # `assign_attributes('name' => 'A', name: 'B')` wrote the attribute - # twice and kept whichever Hash order put last. - # - # A key becomes a Symbol by the constructor's rule, which keeps one - # that cannot: through `to_sym`, `assign_attributes(1 => 'x')` raised - # NoMethodError for a Hash `new` takes. - # - # The values are copied here as well, which is where a pair inside - # one of them is refused. Left to the writes below, a value that - # names a nested key twice raised from the middle of them, with the - # attributes before it already staged. - staged = frozen_attributes(DuplicateKeys.normalize(attributes, noun: 'attribute') { DeepCopy.symbolize(it) }) - - # rubocop:disable Style/CombinableLoops -- combining them is the bug - # Two passes on purpose: every key is checked before any of them is - # written. Combined, `assign_attributes(name: 'X', id: 9, note: 'Y')` - # staged the name, raised on the id and never reached the note, leaving - # the record dirty with half a change set - the state `update` takes - # its own guard one line early to avoid. - # - # `write_attribute` checks again for each key, because it is also the - # direct writer's own guard and cannot assume a caller came through - # here. That is a second Symbol comparison per attribute, which is not - # worth a bypass to avoid. - staged.each { |key, value| refuse_unwritable!(key, value) } - staged.each { |key, value| write_attribute(key, value) } - # rubocop:enable Style/CombinableLoops + Hash(attributes).each { |key, value| write_attribute(DeepCopy.symbolize(key), value) } self end - # Creates or updates the record, reporting a validation failure as - # +false+ rather than by raising. - # - # Only a rejection of the submitted attributes is caught, and it is left - # in {#error}. A missing record, an expired token or an unreachable - # instance still raises, because retrying or branching on those is not - # the caller's business here. + # Persists this record, creating it if it is new. # - # @example - # if group.save - # puts group.id - # else - # warn group.error.server_message - # end - # - # @return [Boolean] whether the record was stored - # @raise [ResponseError] for any failure other than a validation error - # @see #save! + # @return [Boolean] false when Zammad rejected the attributes; see {#error} + # @raise [ResponseError] for any other failure def save save! rescue ValidationError => e @@ -623,629 +261,117 @@ def save false end - # Creates or updates the record, raising on any failure. - # - # New records are sent in full; existing records send only the attributes - # that changed. + # Persists this record, creating it if it is new. An existing record + # sends only the attributes that changed, and nothing when none did. # # @return [true] - # @raise [ResponseError] when Zammad rejected the request - # @raise [IncompleteResponseError] when Zammad stored the record and the - # connection was closed before its answer had arrived. The record is - # persisted and holds what it sent; {#reload} brings in the rest, and - # a record that was being created has no id to be reloaded by. - # @raise [ParseError] when a 2xx did not carry the record. One that said - # it was JSON was Zammad's, and leaves the record as the error above - # does. Any other was the answer of something in front of Zammad, and - # leaves the record as it was, changes staged, to be saved again. - # @see #save + # @raise [ValidationError] when Zammad rejected the attributes + # @raise [Error] when the record was destroyed def save! raise_if_destroyed!('save') - - # Before the request, not after it. Only the success path and the - # rescue in `save` used to clear this, so a save that raised anything - # else left the previous attempt's ValidationError in place and a - # caller reading #error to report the failure read the wrong cause. @error = nil - # What the request carries, held from before it goes out. The - # attributes are frozen and replaced on write, so this is the Hash the - # request is built from and stays that whatever is written meanwhile: - # see #acknowledge_changes!. - # - # Built from, and not only held beside. The body of an update used to - # be read out of the change set a few lines after this was taken, and - # those are two reads of a record another thread may write to in - # between: title "B" held here, "C" staged before the body was built, - # and the PUT carried "C" while an answer nothing could read settled - # the record on "B" - with nothing staged, so writing "B" again to - # put it right compared equal and sent nothing. One Hash is read once - # now, and both the body and what is settled come out of it. - sent = @attributes - if new_record? - response = applied(sent) { create_record(sent) } + response = transport.post(self.class.resource_path, operation: 'save object', resource_class: self.class, query: { expand: true }, body: @attributes) else - # An existing record is addressed by its id, so establish there is - # one before anything here can report success. Only a record left - # behind by a 2xx that did not decode reaches this without one, and - # for that record the short circuit below is a lie: nothing is - # staged, so `save` answered true without sending a request. - require_id! - - # An unchanged record has nothing to send. The empty PUT this used - # to issue was not just a wasted round trip: Zammad applies it, - # bumping updated_at and updated_by, so re-saving a record that - # nobody touched rewrote its audit trail and moved the timestamp - # that other callers use to tell whether it changed under them. - unsaved = unsaved_attributes(sent) + unsaved = changes.transform_values(&:last) return true if unsaved.empty? - response = applied(sent) { update_record(unsaved) } + response = transport.put(member_path, operation: 'save object', resource_class: self.class, query: { expand: true }, body: unsaved) end - replace_attributes!(response, operation: 'save object', sent: sent) + load_response!(response, 'save object') true end - # Stages several attributes and saves in one call. + # Stages the attributes and saves. # - # @example - # ticket.update(state: 'closed', priority: '1 low') - # - # @param attributes [Hash] attribute names and their new values - # @return [Boolean] whether the record was stored - # @raise [Error] when the record was destroyed, or when an attribute - # cannot be staged, such as +id+ - # @raise [ArgumentError] when given something that is not a Hash, nil - # included, or an attribute named twice: see {#assign_attributes} - # @raise [ResponseError] for any failure other than a validation error - # @see #save + # @param attributes [Hash] + # @return [Boolean] see {#save} def update(attributes) - # Before the attributes are staged, not after. `save!` asks the same - # question one line later, but by then `assign_attributes` has already - # written into @changes, so `update` on a destroyed record raised and - # left it dirty with a change set that can never be sent - exactly the - # state `destroy` clears the staged changes to prevent. - raise_if_destroyed!('save') assign_attributes(attributes) save end - # Stages several attributes and saves in one call, raising on any - # failure. + # Stages the attributes and saves. # - # @param attributes [Hash] attribute names and their new values + # @param attributes [Hash] # @return [true] - # @raise [Error] when the record was destroyed, or when an attribute - # cannot be staged, such as +id+ - # @raise [ArgumentError] when given something that is not a Hash, nil - # included, or an attribute named twice: see {#assign_attributes} - # @raise [ResponseError] when Zammad rejected the request - # @see #save! + # @raise [ValidationError] see {#save!} def update!(attributes) - raise_if_destroyed!('save') assign_attributes(attributes) save! end - # Re-reads the record from Zammad, discarding unsaved changes. + # Reads this record again, dropping staged changes. # # @return [self] - # @raise [Error] when the record was destroyed - # @raise [ResponseError] when Zammad rejected the request - # @raise [ParseError] when the response is not a JSON object + # @raise [Error] when the record is new or was destroyed def reload raise_if_destroyed!('reload') raise_if_new!('reload') - response = transport.get( - member_path, - operation: 'reload object', - resource_class: self.class, - query: { expand: true } - ) - replace_attributes!(response, operation: 'reload object') + response = transport.get(member_path, operation: 'reload object', resource_class: self.class, query: { expand: true }) + load_response!(response, 'reload object') self end - # Deletes the record. - # - # The record is marked {#destroyed?} rather than left looking live, so - # that a later {#save}, {#reload} or second {#destroy} fails here with - # the reason rather than one call later as a 404 from Zammad. The - # attributes stay readable, but the state that only meant something - # while the record existed does not: staged changes, the last validation - # failure, and the association readers all go, and a write to an - # attribute is refused from then on. - # - # Readable as the record last was in Zammad, which is not what dropping - # the staged changes alone left behind: `reset_pending_state!` empties - # `@changes` and leaves the writes those changes described standing in - # `@attributes`, so `group.name = 'B'; group.destroy` answered - # `changed?` with false, `changes` with `{}` and `name` with "B" - a - # value Zammad never saw, with nothing left to tell it apart from one it - # served. `@baseline` is what the record arrived with, and every other - # path through this state moves the two together. - # - # Destroyed too where Zammad answered 2xx and the answer did not arrive - # whole, for the reason {#applied} gives: the record is gone, and one - # that still looked live sent a second DELETE, which came back as a 404. - # - # Only where the 2xx is Zammad's, as a save is settled only by one that - # is: see {.confirm_destroyed!} for what tells them apart after a - # DELETE. A 2xx that is not leaves the record as it was, and the - # +destroy+ can be repeated. + # Deletes this record in Zammad. # # @return [true] - # @raise [Error] when the record was already destroyed - # @raise [ResponseError] when Zammad rejected the request - # @raise [ParseError] when the request was answered 2xx with a body - # that is not JSON, by something that is not Zammad. The record is - # not {#destroyed?}. - # @raise [IncompleteResponseError] when Zammad destroyed the record and - # the connection was closed before its answer had arrived. The record - # is {#destroyed?} all the same, unless the answer did not say it was - # JSON. + # @raise [Error] when the record is new or was destroyed already def destroy raise_if_destroyed!('destroy') raise_if_new!('destroy') - begin - response = transport.delete(member_path, operation: 'destroy object', resource_class: self.class) - rescue IncompleteResponseError => e - mark_destroyed! if applied_by?(e.response) - raise - end - self.class.confirm_destroyed!(response) - mark_destroyed! + transport.delete(member_path, operation: 'destroy object', resource_class: self.class) + @destroyed = true true end - # Says which record this is and what it holds, with the value of an - # attribute that names a credential blanked. - # - # The attributes were printed as they stood, and a record can hold a - # credential: `client.users.new(login: 'x', password: 'hunter2')` is - # how a user is given one. Its `inspect` is what IRB and `pp` show, - # what an RSpec failure diffs and what an exception report prints for - # a record it interpolates, so the password staged for one request - # was written wherever any of those went. The log has blanked the same - # key in the same request all along, by {Transport.redact}, which is - # the rule applied here. - # - # Only what is printed. {#attributes}, {#to_h} and {#to_json} hand over - # the values, because sending them is what a record is for. - # - # @return [String] def inspect = "#<#{self.class.name} id=#{id.inspect} new_record=#{new_record?}#{' destroyed=true' if destroyed?} attributes=#{Transport.redact(attributes).inspect}>" protected - # @see AttributeAccess#installation def installation = transport.config.url private - # Everything a record is, in the one place both ways of building one go - # through. Held apart, {.from_response} would restate this list by hand - # and the next field added to the constructor would be left unset on - # every record built from a response - the argument {Client#setup} is - # written around, one class over. - # - # @return [void] - def setup(transport, attributes) - @transport = transport - @attributes = frozen_attributes(attributes) - # What #changes measures against: the attributes this record arrived - # with, kept apart from the ones it currently holds. The two share the - # one frozen Hash until the first write copies it. - @baseline = @attributes - @changes = {} - @new_record = true - @destroyed = false - @error = nil - @related = nil - # Whether what this record holds came back from a save rather than - # from a read. Only {#no_id_message} asks, and only for a record left - # without an id, where the two lead somewhere quite different. - @saved = false - end - def mark_persisted! @new_record = false end - def mark_destroyed! - @destroyed = true - @attributes = @baseline - reset_pending_state! - end - - # A set of attributes a caller handed over, as the Hash it is read as. - # - # A Hash, or what converts to one. `ActionController::Parameters` is - # not a Hash, and it is what `client.users.new(params.require(:user) - # .permit(:login, :password))` hands over: the constructor took it as - # it was - see {DeepCopy.frozen_object} for what became of the record - - # and {#assign_attributes} raised NoMethodError for it. Converted here, - # at the door, so that everything behind it is handed a Hash. - # - # Anything else is refused, and named by its class alone: what was - # given may hold a credential. It used to raise NoMethodError from - # whichever method of Hash was called on it first, or be taken, as an - # Array of pairs was. - # - # @param given [Object] - # @return [Hash] - # @raise [ArgumentError] - def attribute_hash(given) - Hash.try_convert(given) || raise(ArgumentError, "attributes need to be a Hash of names and values, got #{given.class}") + def load_response!(response, operation) + @attributes = frozen_attributes(response.decoded(:object, operation: operation, resource_class: self.class)) + @baseline = @attributes + @new_record = false + @related&.forget end - # Refuses an operation on a record Zammad never had. - # - # `destroyed?` was the only thing these asked, so a record built with an - # id it was simply handed - `client.groups.new(id: 99)`, which the - # attribute writers refuse but the constructor still allows - reported - # `new_record?` true and `persisted?` false and then issued a real DELETE - # against group 99. The id addresses a record this one does not stand - # for, and nothing about it came from Zammad. def raise_if_new!(operation) raise Error, "#{self.class.name} has not been saved, so there is nothing to #{operation}" if new_record? end - # Refuses an operation on a record Zammad no longer holds. - # - # `destroyed?` is sticky, and all three state-changing paths ask here. - # Only `save!` used to: `reload` re-read a record that no longer exists - # and cleared the flag on the way back, so a destroyed record came back - # reporting itself as persisted and its next `save` issued a PUT against - # the deleted path, while a second `destroy` surfaced Zammad's 404 - # instead of the local reason. A record that is gone is gone, and every - # path that acts on the server says so here rather than one request - # later. def raise_if_destroyed!(action) raise Error, "#{self.class.name} #{id} was destroyed, there is nothing to #{action}" if destroyed? end def writable_attributes? = true - # Asked by {#write_attribute} and by {AttributeAccess#respond_to_missing?}, - # so that a record never claims a writer it would then refuse. That is - # the invariant the writer branch of `respond_to_missing?` exists for. - def attribute_writable?(key) = key != :id - - # Everything a freshly loaded record has to forget, in the one place that - # every load path goes through. Held apart, `save!` and `reload` drifted - # the moment a sixth field was added to only one of them, and nothing - # would have caught a reloaded record still holding an association proxy - # from before the reload. - # The flag goes down before the body is decoded, because what makes a - # record persisted is that Zammad answered 2xx, not that the answer - # parsed. Decoded first, a create whose 201 carried something other than - # a JSON object - a body cut off or rewritten on its way through a - # proxy - raised ParseError with @new_record still true, so the ticket - # existed in Zammad while the record here still looked unsaved and a - # retried `save` POSTed a second one. - # - # What that leaves behind is a record which is persisted and carries no - # id, and the rest of this class has to treat it as the unusable thing - # it is: a record built by `new` has nothing staged, so without a word - # from {#require_id!} the retried `save` would have taken the "nothing - # to send" short circuit and reported true, having made no request at - # all, for a record that may or may not be in Zammad. - # - # Only where the 2xx is Zammad's, which {#applied_by?} asks: one that - # is not settles nothing, and the ParseError its body raises below - # leaves the record as the save found it. - # - # +sent+ is what a save was sent with, and is what tells one from a - # read. - def replace_attributes!(response, operation:, sent: nil) - mark_answered!(sent) if sent.nil? || applied_by?(response) - @attributes = frozen_attributes(response.decoded(:object, operation: operation, resource_class: self.class)) - @baseline = @attributes - reset_pending_state! - end - - # What a 2xx settles before its body is read, and all it settles where - # the body cannot be: see {#replace_attributes!} and {#applied}. - def mark_answered!(sent) - # First, while #new_record? still says whether this was a create. - acknowledge_changes!(sent) if sent - @new_record = false - @saved = !sent.nil? - end - - # The request of a save, with the record settled where Zammad applied - # it and the answer did not arrive whole. - # - # A 2xx whose body stops short of its Content-Length is refused inside - # the transport, so it never came back to {#replace_attributes!}, which - # is where a 2xx that cannot be read settles the record. Raised past it, - # a create answered 201 left the record looking unsaved, and the retried - # `save` POSTed a second one; an update left its whole change set - # staged, so the next `save` sent a ticket's `article` again. The same - # response with a body that does not parse had done neither since - # {#acknowledge_changes!}. - # - # @yieldreturn [Response] - # @return [Response] - # @raise [IncompleteResponseError] once the record is settled - def applied(sent) - yield - rescue IncompleteResponseError => e - mark_answered!(sent) if applied_by?(e.response) - raise - end - - # Whether a 2xx says that Zammad applied the save it answers. - # - # Every 2xx was taken to. But the 2xx whose body cannot be read is, more - # often than a record Zammad served mangled, the page of something in - # front of Zammad that never passed the request on: the login page of a - # single sign-on gateway, a captive portal, the default page of a load - # balancer. Settled on that, `ticket.update(state: 'closed')` raised - # ParseError and left the ticket reading closed with nothing staged, so - # the retried `save` answered true without a request while Zammad still - # had it open, and a create was left persisted with no id for a record - # Zammad never made. - # - # The content type tells the two apart. Zammad answers a create and an - # update with JSON, from every controller, so a 2xx that says it is - # JSON is its own, readable or not, and one that says anything else, or - # nothing, is not. A body that was decoded from JSON counts as said, - # for a transport of the caller's that hands over a {Response} without - # the header. - # - # A destroy is asked this only of an answer that was cut short. Zammad - # answers a ticket's DELETE with no body at all, so a whole one is - # asked what {.confirm_destroyed!} asks instead. - # - # @param response [Response, nil] nil where an error that says Zammad - # answered carries none, which leaves its word for it - def applied_by?(response) - response.nil? || response.json? || response.json_content_type? - end - - # The same argument, for what was staged: a 2xx is Zammad saying it - # applied the changes, whether or not the rest of the answer parsed. - # - # They used to stay staged until the body had decoded. An update - # answered with a 2xx nothing could read - the same mangled body - raised - # ParseError with the whole change set still in place, so the next - # `save` sent all of it again along with whatever had been staged - # since. For most attributes that is the same value twice. For a - # ticket's `article` it is a second article, and a second e-mail to - # the customer: the one write {Transport::RETRIABLE_METHODS} leaves - # PUT out to keep from being repeated, repeated by the caller's next - # unrelated save instead. - # - # So the baseline moves up to what was sent, before the body is read. - # If that then raises, the record holds the values it sent and nothing - # staged: it is not what Zammad would serve - `updated_at` is behind, - # and anything Zammad derived is missing - and {#reload} is what - # brings that in. A save Zammad rejected never gets here, so what it - # was sent stays staged to be corrected and sent again. - # - # What was sent, and not what the record holds by the time the answer - # is in. The two differ where the record was written to while the - # request was out - by a logger or a middleware of the caller's that - # reaches the record, or by another thread - and the baseline used to - # be taken from the record as it then stood: a PUT that carried title - # "B", with "C" staged before the answer came, left the record reading - # "C" with nothing staged, so the next `save` reported true without a - # request for a value Zammad was never sent. A write made meanwhile is - # dropped instead, which is what a response that can be read does to - # it: the attributes it carries replace the record's, whatever was - # written to them since the request left. - # - # And of what was sent, only the attributes Zammad has served this - # record with. A key written since that it never sent back is not known - # to be an attribute at all. A ticket's `article` is the case that - # matters: a command that travels in the body of the same PUT and makes - # an article, and no part of what a ticket is served as. Settled into - # the baseline with the rest, it was remembered as the ticket's own - # state, so the same article assigned again - a second reply with the - # text of the first - compared equal to it, staged nothing, and `save` - # reported true without a request. A response that can be read leaves - # no such key behind, and neither does this. - # - # A record being created has nothing it was served with to measure - # against, and keeps all it sent. It has no id to be saved again by, - # so there is no second request for a key to be missing from. - # - # What the association proxy has resolved goes with the attributes it - # was resolved from. This puts the record back on what it sent, which - # is a write to every attribute at once, and it was the one write to a - # foreign key that left the proxy alone: `customer_id` sent as 9, - # written to 10 while the request was out and `related.customer` read - # then, and the record was back on 9 with user 10 still memoized as - # its customer. {#reset_pending_state!} empties the proxy too, but - # only once the body has decoded, and a body that does not is what - # this method is here for. - def acknowledge_changes!(sent) - # `slice` answers with a plain Hash, whatever it was called on. - settled = new_record? ? sent : Attributes[sent.slice(*@baseline.keys)].freeze - @attributes = settled - @baseline = settled - @changes = {} - forget_related_targets - end - - # The part of that which is not about arriving with new attributes, but - # about the record's state on the server having changed underneath what - # is held here. `destroy` is the third path through this, and was the - # one left out: a destroyed record went on reporting `changed?` and a - # change set that can never be sent, and went on handing out a `related` - # proxy that would happily request a record that no longer exists. - def reset_pending_state! - @changes = {} - @error = nil - forget_related_targets - end - - # Empties the association proxy, rather than dropping it. - # - # Dropping it was the earlier answer: `@related = nil`, and the next - # call to {#related} built a fresh one. That reached every caller who - # asked again and none who had kept what they were handed, so after - # `related = ticket.related` a reload, a save or `ticket.customer_id = 9` - # left `related.customer` answering with the record it had resolved - # before - the stale read these calls exist to prevent, one variable - # away from where it was fixed. - def forget_related_targets - @related&.send(:forget_targets) - end - - # The baseline is the value this record was loaded with, not the value - # the previous assignment happened to leave behind. Writing twice must - # still report the original, and writing a value back to the original - # is not a change at all - but only where the record was loaded - # carrying that attribute in the first place. - # - # That last part is why the baseline is held rather than read back out - # of @attributes: an attribute the record does not carry - Zammad - # reduces the object it serializes for a permission-scoped client - - # compared nil against nil on the way in, staged nothing, and was still - # merged into @attributes below. The write was dropped without a word, - # no request was ever sent for it, and the record went on reporting a - # key Zammad had never sent it, so #changes and #attributes disagreed. - # - # A destroyed record takes no writes. `update` has refused one all - # along, so as not to leave a change set that can never be sent, but - # the writers themselves did not ask: `group.destroy; group.name = 'Z'` - # left `changed?` true and `name` reading "Z" on a record `destroy` - # promises to leave as it last was in Zammad, and the `save` after it - # was the first thing to object. Asked here, it holds for a named - # writer, `[]=` and `assign_attributes` alike, since all three write - # through this method. def write_attribute(key, value) raise_if_destroyed!('change') - refuse_unwritable!(key, value) - - staged = frozen_attributes(value) - - if @baseline.key?(key) && @baseline[key] == staged - @changes.delete(key) - else - @changes[key] = [@baseline[key], staged].freeze - end + raise Error, "#{self.class.name}#id cannot be changed: it is what addresses this record" if key == :id - # Copy on write, because @attributes is frozen for the benefit of - # every reader that hands it out. + staged = frozen_attributes(value) @attributes = @attributes.merge(key => staged).freeze - # A resolved association is only correct for the id it was resolved - # from. `replace_attributes!` forgets them on save and reload, but - # the write that actually changes a foreign key did not, so - # `ticket.customer_id = 9` left `ticket.related.customer` answering - # with user 3 and no request to show for it. Every target goes: - # evicting one reader means reaching into the cache by name for a - # saving that is one request at most. - forget_related_targets if self.class.belongs_to_foreign_keys.include?(key) + @related&.forget staged end - # The attributes of +held+ that differ from what this record arrived - # with, which is what an update sends. - # - # The same question {#write_attribute} asks before it stages a change, - # asked of one Hash of attributes rather than of the change set: see - # {#save!} for why the body of a request is not read from there. - # - # @param held [Hash{Symbol => Object}] attributes of this record - # @return [Hash{Symbol => Object}] - def unsaved_attributes(held) - baseline = @baseline - - held.reject { |key, value| baseline.key?(key) && baseline[key] == value } - end - - def create_record(body) - transport.post( - self.class.resource_path, - operation: 'save object', - resource_class: self.class, - query: { expand: true }, - body: body - ) - end - - def update_record(body) - transport.put( - member_path, - operation: 'save object', - resource_class: self.class, - query: { expand: true }, - body: body - ) - end - - # The id is what addresses the record, so it is not an attribute a caller - # stages. Written, it took effect immediately for every path that builds - # a URL from `@attributes` and not at all for the record those paths then - # reported on: `group.id = 99; group.destroy` sent DELETE to group 99 and - # left the record saying group 1 was the one destroyed. Zammad would not - # have applied it either - an id is not something its endpoints let you - # set - so there is no call here that a refusal takes away. - def refuse_unwritable!(key, value) - return if attribute_writable?(key) - - message = "#{self.class.name}##{key} cannot be staged as an attribute" - # `attribute_writable?` is a hook a resource may override, so the - # reason belongs to the key that was refused rather than to the raise. - if key == :id - message += ', because it is what addresses this record; look up the record you meant ' \ - "with find(#{value.inspect})" - end - raise Error, message - end - def member_path = self.class.member_path(require_id!) - # This record's id, for the paths and bodies that cannot be built - # without one. - # - # @return [Integer] the id - # @raise [Error] when the record has none def require_id! - # Read once into a local, so that the guard below narrows what is - # handed on - `id` is an attribute reader, and the type checker cannot - # tell that two calls to one answer the same thing. - record_id = id - raise Error, no_id_message if record_id.nil? - - record_id - end - - # A record has no id in three quite different situations, and one message - # for more than one of them sends people looking in the wrong place. - # - # Before the first save there is simply nothing to address yet. - # - # After one there is - Zammad answered 2xx, so the record is in Zammad - - # but the response carried no id to address it by, which is what - # {#replace_attributes!} leaves behind when a 2xx body does not decode - # as the object it claims to be. - # - # And a record can arrive without one from a plain read: Zammad reduces - # the object it serializes for a permission-scoped client, which is the - # same thing {#write_attribute} is written around. Such a record is - # persisted, so it used to be told it "was saved" - pointing the caller - # at a save that never happened, when what they need to look at is which - # user the client authenticates as. - def no_id_message - return "#{self.class.name} has no id, save it first" if new_record? - - if @saved - return "#{self.class.name} was saved, but the response carried no id to address it by, " \ - 'so this record cannot act on the server. Look it up again to get one that can.' - end - - "#{self.class.name} was loaded without an id, so this record cannot act on the server. " \ - 'Zammad serves a reduced object where the authenticated user may not see the whole record, ' \ - 'so check what this client may read, then look it up again to get one that can.' + id || raise(Error, "#{self.class.name} has no id, save it first") end end end diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index 168c5de..7bf0bb1 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -27,11 +27,8 @@ class Ticket < Base has_many :articles, class_name: 'TicketArticle', path: ->(id) { "api/v1/ticket_articles/by_ticket/#{id}" } - # Every article of this ticket, refetched on each call. - # - # The same list as +ticket.related.articles+; this is the older name and - # stays because it reads better than reaching through +related+ for the - # one association a ticket is usually asked for. + # Every article of this ticket, refetched on each call: the same list as + # +ticket.related.articles+. # # @return [Array] # @raise [ResponseError] when Zammad rejected the request @@ -39,68 +36,18 @@ def articles = related.articles # Adds an article to this ticket. # - # Named for what it does. It was +article+, a noun that sends a POST, - # next to +articles+, a noun that only reads - so the one letter - # between them was the difference between reading a ticket's history - # and writing to it. - # # @example # ticket.add_article(subject: 'Update', body: 'Reset link sent.', type: 'note') # # @param attributes [Hash] article attributes, e.g. +body:+, +type:+ # @return [TicketArticle] the created article - # @raise [Error] when the ticket has no id yet, or was destroyed + # @raise [Error] when the ticket has no id yet # @raise [ResponseError] when Zammad rejected the request def add_article(attributes = {}) - # A destroyed ticket takes no articles, and says so here rather than - # one request later. `require_id!` passes on its own, because destroy - # leaves the id readable, so without this the POST went out naming a - # ticket that is gone and Zammad's 422 about ticket_id was the first - # news of it - the fourth state-changing path, after the three that - # already ask. - raise_if_destroyed!('add an article to') - - # An article belongs to a ticket by id, so ask for one here rather - # than merging nil. Unchecked, this POSTed `ticket_id: null` and left - # the caller reading Zammad's 422 to work out that the ticket they - # were adding to had never been saved - the one path in the gem that - # needed a stored id and went to the server to find out it had none. - # - # Both spellings of the key are taken out before this ticket's id - # goes in. `merge(ticket_id: ...)` replaces a Symbol key and leaves a - # String one standing beside it, and the article symbolizes its keys - # in the order they come: given `ticket_id` under both spellings, the - # String one came last and won, so `add_article` on ticket 7 POSTed - # an article naming whichever ticket the caller's Hash did. An - # article refuses two spellings of one attribute now, and a String - # `ticket_id` left beside this ticket's would be refused as a pair - # the caller never wrote. - # - # Read as a Hash first, by the rule the article's own constructor - # has - see {Base#attribute_hash} - so that what is taken apart here - # is one: the strong parameters of a controller, converted, and - # anything that is no set of attributes refused before `reject` is - # called on it. - own = attribute_hash(attributes).reject { |key, _| key.to_s == 'ticket_id' } - record = TicketArticle.new(transport, own.merge(ticket_id: require_id!)) + record = TicketArticle.new(transport, Hash(attributes).merge(ticket_id: require_id!)) record.save! record end - - private - - # `ticket.article(body: '...')` is the call that added an article in - # 1.x. On a ticket with an article staged - one built with `article:` - # whose save was rejected, say - +article+ is an attribute it carries, - # and the call reaches the reader with an argument. Whoever wrote it - # meant {#add_article}, so the refusal names it. - # - # @see AttributeAccess#reader_arguments_message - def reader_arguments_message(name, given) - return super if name != :article - - "#{super} To add an article to this ticket, which is what article(...) did in 1.x, call add_article(...)." - end end end end diff --git a/lib/zammad_api/resources/ticket_article.rb b/lib/zammad_api/resources/ticket_article.rb index 88a0434..9492e34 100644 --- a/lib/zammad_api/resources/ticket_article.rb +++ b/lib/zammad_api/resources/ticket_article.rb @@ -1,6 +1,5 @@ # frozen_string_literal: true -require_relative '../errors' require_relative 'base' require_relative 'ticket_article_attachment' @@ -9,39 +8,13 @@ module Resources class TicketArticle < Base path 'api/v1/ticket_articles' - # Named the way a has_many reader names its own read - `get articles` - - # so the refusal below reads like every other one this gem raises. - ATTACHMENTS_OPERATION = 'get attachments' - private_constant :ATTACHMENTS_OPERATION - belongs_to :ticket, class_name: 'Ticket' # @return [Array] the article's attachments - # @raise [ParseError] when the article does not carry attachment - # metadata in the shape Zammad serves def attachments - list = attributes[:attachments] || [] - # The same check {Response#decoded} makes on a list of records, for - # the same reason: this metadata comes off a response body, and an - # element that is not an object reached `raw.merge` and died there as - # `undefined method 'merge' for an instance of String` - a bare - # NoMethodError from inside the gem, past the `rescue ZammadAPI::Error` - # every caller is told to write, for a body that was simply not what - # it claimed to be. - raise ParseError.build(operation: ATTACHMENTS_OPERATION, expected: 'array of objects', actual: list.class, resource_class: self.class) if !list.is_a?(Array) - - list.map { attachment(it) } - end - - private - - def attachment(raw) - raise ParseError.build(operation: ATTACHMENTS_OPERATION, expected: 'array of objects', actual: "an array holding #{raw.class}", resource_class: self.class) if !raw.is_a?(Hash) - - TicketArticleAttachment.new( - transport, - raw.merge(ticket_id: attributes[:ticket_id], article_id: id) - ) + (attributes[:attachments] || []).map do |raw| + TicketArticleAttachment.new(transport, raw.merge(ticket_id: attributes[:ticket_id], article_id: id)) + end end end end diff --git a/lib/zammad_api/resources/ticket_article_attachment.rb b/lib/zammad_api/resources/ticket_article_attachment.rb index b62eeb6..5b0745b 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true require_relative '../attribute_access' -require_relative '../errors' require_relative '../transport' module ZammadAPI @@ -18,39 +17,22 @@ class TicketArticleAttachment # @param attributes [Hash] def initialize(transport, attributes = {}) @transport = transport - @attributes = frozen_attributes(attributes || {}) + @attributes = frozen_attributes(Hash(attributes)) # steep:ignore UnresolvedOverloading end - # Asks for the file as it is stored. A response says how long it is in - # the bytes that were sent, and the transport can hold that against - # the bytes in hand only where nothing decoded them on the way: see - # {Transport.missing_bytes}. Left to itself Net::HTTP asks for gzip - # and inflates what arrives, without a word for a stream that stops - # halfway, so a text attachment behind a proxy that compresses came - # back as its first part when the connection was closed under it. - UNENCODED = { 'Accept-Encoding' => 'identity' }.freeze - private_constant :UNENCODED - # Downloads the attachment. # - # The file is asked for with +Accept-Encoding: identity+, so that one - # the connection was closed under is told from a whole one. - # # @return [String] the file contents, in +ASCII-8BIT+ encoding # @raise [ResponseError] when Zammad rejected the request - # @raise [IncompleteResponseError] when the connection was closed before the - # whole file had arrived. The part that did arrive is not returned. def download - response = request_file(UNENCODED) - # A server that encodes the body all the same has sent what only - # the adapter reads, and an adapter handed the header leaves that - # to its caller: the bytes would be the compressed ones. Asked - # again the way every other request is, the file is decoded as it - # was before, and its length goes unchecked as it did before. - response = request_file(nil) if response.headers.key?('content-encoding') - # Attachments are arbitrary binary data; the transport's charset - # guess must not corrupt them. - response.raw_body.dup.force_encoding(Encoding::BINARY) + segments = %i[ticket_id article_id id].map { Transport.escape_path_segment(fetch(it)) } + response = @transport.get( + "api/v1/ticket_attachment/#{segments.join('/')}", + operation: 'download attachment', + resource_class: self.class + ) + + response.raw_body.b end def inspect @@ -59,21 +41,8 @@ def inspect protected - # @see AttributeAccess#installation + # @return [String] the Zammad this attachment was read from def installation = @transport.config.url - - private - - def request_file(headers) - segments = %i[ticket_id article_id id].map { Transport.escape_path_segment(fetch(it)) } - - @transport.get( - "api/v1/ticket_attachment/#{segments.join('/')}", - operation: 'download attachment', - headers: headers, - resource_class: self.class - ) - end end end end diff --git a/lib/zammad_api/resources/user.rb b/lib/zammad_api/resources/user.rb index a879277..a261fa9 100644 --- a/lib/zammad_api/resources/user.rb +++ b/lib/zammad_api/resources/user.rb @@ -13,15 +13,6 @@ class User < Base searchable true - # User::Search is the one search that reads these: it joins the roles - # for +role_ids+, resolves +permissions+ to the roles that carry them, - # and +group_ids+ to the agents with access to those groups - full - # access where it is a list of ids, the access named for each group - # where it is a Hash. See {ResourceProxy#search}, also for what - # +permissions+ does not narrow where Zammad searches through - # Elasticsearch. - search_filters :role_ids, :group_ids, :permissions - belongs_to :organization, class_name: 'Organization' end end diff --git a/lib/zammad_api/response.rb b/lib/zammad_api/response.rb index b7d2a2d..abc0ef0 100644 --- a/lib/zammad_api/response.rb +++ b/lib/zammad_api/response.rb @@ -19,172 +19,40 @@ module ZammadAPI # keys; every other content type is left as the raw body # @!attribute [r] raw_body # @return [String] the undecoded response body - # @!attribute [r] json - # @return [Boolean] whether {#body} was decoded from JSON - Response = Data.define(:status, :headers, :body, :raw_body, :json) + Response = Data.define(:status, :headers, :body, :raw_body) class Response SUCCESS_STATUSES = (200..299) - # There is no reader here for the size of the whole result, and the - # absence is deliberate. This class carried a `reported_total` that read - # an `x-total-count` response header, and two stop conditions were built - # on it: {Collection#each} ended a walk one request early on it, and a - # has_many reader refused a list it judged truncated by it. - # - # Zammad has never sent that header, from any endpoint. Its only custom - # response header is `X-Failure`, and the totals it does report are - # fields in a JSON body: `only_total_count` and `with_total_count` on a - # search, `full` on the endpoints that render through - # model_index_render. So the reader answered nil every time, both guards - # were dead, and the one of them that could have acted - ending a walk on - # a figure the records did not corroborate - was the one that could have - # been wrong. {Collection#total_count} asks a search endpoint for its - # figure the way Zammad actually offers it, and {#decoded_list} reads - # the one a search reports beside a page. - # @return [Boolean] whether the status code is in the 2xx range def success? = SUCCESS_STATUSES.cover?(status) - # Recorded at decode time, where the answer is known, rather than derived - # from `body` and `raw_body` being the same object. That identity held only - # while every producer was careful to hand the same String to both, and any - # edit that duped, re-encoded or normalised the raw body would have flipped - # this to true with nothing asserting otherwise. - # - # @return [Boolean] whether {#body} was decoded from JSON - def json? = json - - # Whether the response says that its body is JSON, which is not whether - # the body then decoded as that: an empty one and one that does not parse - # are left as they arrived, and {#json?} is false for both. - # - # What an answer says it is tells whose it is. Zammad answers a request - # to its API with JSON, so a 2xx of another type - a login page, the - # default page of a load balancer - is the answer of something in front - # of it: see {Resources::Base#save!}. - # - # @return [Boolean] - def json_content_type? = Response.json_type?(headers['content-type']) - - # The one reading of a content-type, for {.decode_body} and - # {#json_content_type?} alike. - # - # @api private - # @param content_type [String, nil] - # @return [Boolean] - def self.json_type?(content_type) = content_type.to_s.include?('json') - - # Decodes a body the way this gem decodes every body, and says whether it - # did. - # - # Only JSON responses are decoded. Anything else - a proxy error page, a - # file download - is handed back untouched so that callers and error - # messages can still work with it. - # - # Here rather than on {Transport}, because {Test} has to answer the same - # way and was deciding from the Ruby type of the stub's body instead: a - # stub could declare `content-type: text/html` and still hand back a - # decoded Hash with `json?` true, where Zammad would have given the raw - # string and a ParseError. A stand-in whose decoding disagrees with the - # wire is the thing that kit exists to rule out. - # - # Public for that reason and no other, the way {Transport.stringify_query} - # is: both transports call it from outside this class. It is not part of - # what this gem promises a caller. + # Decodes a JSON body with symbol keys. Anything else - a proxy error page, + # a file download, a body that does not parse - is handed back as it is. # # @api private # @param content_type [String, nil] # @param raw_body [String] - # @return [Array(Hash | Array | String, bool)] the body and whether it was - # decoded from JSON + # @return [Hash, Array, String] def self.decode_body(content_type, raw_body) - return [raw_body, false] if !json_type?(content_type) - return [raw_body, false] if raw_body.empty? + return raw_body if !content_type.to_s.include?('json') || raw_body.empty? - [JSON.parse(raw_body, symbolize_names: true), true] + JSON.parse(raw_body, symbolize_names: true) rescue JSON::ParserError - [raw_body, false] + raw_body end - # Returns the decoded body once it matches the expected shape. - # - # Zammad answers with an object for a single record and an array for a - # list; anything else (a proxy error page, an unexpanded search result) - # is a {ParseError} rather than a confusing failure further downstream. + # The body, checked to be the JSON object or array the caller expects. # - # @param shape [Symbol] +:object+ or +:array+ - # @param operation [String] description used in the error message - # @param resource_class [Class, nil] used in the error message + # @param shape [:object, :array] + # @param operation [String] + # @param resource_class [Class, nil] # @return [Hash, Array] - # @raise [ParseError] when the body has a different shape + # @raise [ParseError] when the body has another shape def decoded(shape, operation:, resource_class: nil) - case [shape, body] - in [:object, Hash => object] then object - in [:array, Array => array] then array_of_objects!(array, operation: operation, resource_class: resource_class) - else - raise ParseError.build( - operation: operation, - expected: shape, - actual: body.class, - resource_class: resource_class - ) - end - end - - # Returns the records of a list, and the size of the whole result where - # the endpoint reports it beside them. - # - # A list is an array. A search asked for +with_total_count+ answers with - # an object instead, +{records: [...], total_count: n}+, where its Zammad - # reads that parameter under +expand+ - 6.5.1 and later - and with the - # array it always did where it does not. Both are a list, and - # {Collection} reads either. - # - # A total that cannot be one - a negative figure, a string - is reported - # as none rather than refused. The records beside it are still the page, - # and a walk without a total is a walk as it was before there was one. - # - # @param operation [String] description used in the error message - # @param resource_class [Class, nil] used in the error message - # @return [Array(Array, Integer)] the records and the total - # @return [Array(Array, nil)] where the endpoint reported no total - # @raise [ParseError] when the body is neither shape - def decoded_list(operation:, resource_class: nil) - case body - in { records: Array => records, total_count: total } - [array_of_objects!(records, operation: operation, resource_class: resource_class), total.is_a?(Integer) && !total.negative? ? total : nil] - else - [decoded(:array, operation: operation, resource_class: resource_class), nil] - end - end - - private - - # Only the top-level shape used to be checked, which is not what the - # promise above says. A search answering `[1, 2, 3]` - what an unexpanded - # one looks like - passed as an array, and every element went to - # `from_response`, which stored the Integer as a record's attributes. The - # first `record.id` then died with `TypeError: no implicit conversion of - # Symbol into Integer` from deep inside the gem: precisely the confusing - # failure further downstream. - # - # Asked for by position, because the element itself cannot say whether - # one was found. `find` answers nil for no offender and for an offender - # that is nil, so a list holding a JSON null - `[null]`, or one null - # among the records - passed as a list of objects, and the same failure - # came back one type over: NoMethodError for `nil[:id]`, from the walk - # that reads the ids of a page. - def array_of_objects!(array, operation:, resource_class:) - position = array.index { !it.is_a?(Hash) } - return array if position.nil? + return body if body.is_a?(shape == :object ? Hash : Array) - raise ParseError.build( - operation: operation, - expected: 'array of objects', - actual: "an array holding #{array.fetch(position).class}", - resource_class: resource_class - ) + raise ParseError.build(operation: operation, expected: shape, actual: body.class, resource_class: resource_class) end end end diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index e1ca130..e2de89b 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -27,167 +27,78 @@ module ZammadAPI # @example An error path # zammad.stub(:get, 'api/v1/tickets/9', status: 404, body: {error: 'not found'}) # # the code under test sees ZammadAPI::NotFoundError - # - # @example A read the client retries - # zammad.stub(:get, 'api/v1/tickets/1', status: 503) - # zammad.stub(:get, 'api/v1/tickets/1', body: {id: 1, title: 'Help'}) - # # the code under test sees the ticket, and zammad.requests holds both attempts class Test # Raised when the code under test reaches an endpoint that was not stubbed. # - # The message lists what is stubbed, because the usual cause is a path that - # differs from the expected one. - # # Deliberately outside {ZammadAPI::Error}: this says the test is wrong, not - # that Zammad refused something, and code under test is written to handle - # the latter. Inside the hierarchy, the `rescue ZammadAPI::Error` that this - # gem's own examples recommend swallowed a forgotten stub and reported it - # as an API failure - so a test asserting the error path passed green over - # a request it had never declared. + # that Zammad refused something, so a +rescue ZammadAPI::Error+ in the code + # under test does not swallow it. class UnstubbedRequestError < StandardError; end - # Raised when two stubs describe one request equally well. - # - # Two stubs that name different query parameters can both match a request - # carrying all of them, and there is no honest way to rank them: a search - # stubbed once for its records and once for its count is matched by both - # when `count` sends the search term and +only_total_count+ together. The - # stand-in used to pick one, hand back the wrong body, consume the stub on - # the way past, and then report the endpoint as unstubbed - three - # confusing symptoms for one fixable declaration. - # - # Outside {ZammadAPI::Error} for the same reason as - # {UnstubbedRequestError}: it says the test is wrong, not that Zammad - # refused anything. - class AmbiguousStubError < StandardError; end - # One request the code under test made. # - # The verb is +verb+ rather than +method+, because a member named +method+ - # would shadow +Object#method+ on every recorded request. - # # @!attribute [r] verb # @return [Symbol] +:get+, +:post+, +:put+ or +:delete+ # @!attribute [r] path # @return [String] path relative to the instance URL # @!attribute [r] query - # @return [Hash{String => String, Array}] query parameters as the - # client sent them, stringified the way the real transport sends them + # @return [Hash{String => Object}] query parameters, with keys and + # values as text # @!attribute [r] body # @return [Hash, nil] the request payload # @!attribute [r] headers - # @return [Hash{String => String}] the headers the call asked for, - # downcased and stringified the way the real transport sends them. - # Empty for a request that named none; the headers the client sets - # from its own configuration are not in here, and the +From+ scope has - # a member of its own below. + # @return [Hash{String => String}] the headers the call asked for, names + # downcased. The +From+ scope has a member of its own below. # @!attribute [r] on_behalf_of - # @return [String, nil] the +From+ scope in effect, stringified the way - # the +From+ header carries it + # @return [String, nil] the +From+ scope in effect Request = Data.define(:verb, :path, :query, :body, :headers, :on_behalf_of) # @return [Config] the configuration the stand-in client reports attr_reader :config - # @param options [Hash] any option accepted by {Config}; the defaults are - # enough for a client that never opens a connection - def initialize(**options) - # Through the merge a client's own overrides go through, so that - # `Test.new(user: 'u', password: 'p')` replaces the stand-in token - # rather than being refused for naming a second way to authenticate. - @config = Config.new(**Config.merge_options({ url: 'https://zammad.test/', http_token: 'test-token' }, options)) - @stubs = {} - # The stub each scope of each endpoint last answered a first page with, - # which is the one a later page of the same read belongs to. See #take. - @served = {} - @requests = [] - @monitor = Mutex.new - @transport = Transport.new(self) - # Built once, and built straight onto the stand-in. Going through - # `Client.new` re-validated the config assembled one line above and then - # assembled a whole Faraday stack - auth, JSON, retries, adapter - only - # to swap it straight back out, which is the cost the comment here used - # to claim it was avoiding. A suite writing - # `let(:zammad) { ZammadAPI::Test.new }` paid it once per example. - @client = Client.build(@config, @transport) - end - # A client that talks to this stand-in instead of to a Zammad. # - # The same client every time; it holds no per-request state, and - # {Client#on_behalf_of} and {Client#with} return copies of their own. - # # @return [Client] attr_reader :client + # @param options [Hash] any option accepted by {Config}; the defaults are + # enough for a client that never opens a connection + def initialize(**options) + @config = Config.new(**Config.merge_options({ url: 'https://zammad.test/', http_token: 'test-token' }, options)) + @stubs = {} + @requests = [] + @monitor = Mutex.new + @client = Client.build(@config, Transport.new(self)) + end + # Declares the response for one endpoint. # # Stubbing the same method and path again queues a second response: the - # first request gets the first, and the last stub answers every request - # after it. One declared after an earlier one has answered takes over - # from the next request on. A collection read is one step of such a - # sequence however many pages it asks for, so three list stubs answer - # three reads in turn. A +query+ matches when every parameter it names - # is present in the request with that value, so a stub does not have to - # repeat the +expand+, +page+ and +per_page+ parameters the client adds - # itself. - # - # A stub that names a +query+ is more specific than one that does not, and - # answers ahead of it however they were declared. Queueing applies within - # a scope: two stubs carrying the same +query+ describe a sequence, while - # a scoped stub and a catch-all are two separate answers, each of which - # keeps answering. + # first request gets the first, and the last one answers every request + # after it. A +query+ matches when every parameter it names is present in + # the request with that value, so a stub does not have to repeat the + # +expand+, +page+ and +per_page+ parameters the client adds itself. # - # A +GET+ answered with a status the client retries - 429, 500, 502, 503 - # or 504 - or with a 2xx cut short of its Content-Length is asked again, - # as it is on the wire, and each attempt takes the next stub of the - # sequence: see {#answer}. + # A list read asks for pages until one is short or empty. A stub whose + # +query+ names no +page+ answers the first page, and every page after it + # with an empty list. # # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ # @param path [String] path relative to the instance URL, leading slash # optional # @param status [Integer] HTTP status to answer with - # @param body [Hash, Array, String, nil] a Hash or Array is serialized to - # JSON bytes, anything else is served as it is. Whether those bytes are - # then decoded is decided by the content-type, the way a real response - # decides it - so a Hash served as +text/html+ comes back undecoded, and - # a JSON String served as +application/json+ comes back decoded. - # @param headers [Hash] response headers. Names and values are stringified - # and names downcased, the way a {Response} carries them. A Hash or Array - # body is given +content-type: application/json+ unless this says - # otherwise. + # @param body [Hash, Array, String, nil] a Hash or Array is served as JSON, + # anything else as it is + # @param headers [Hash] response headers; a Hash or Array body is given + # +content-type: application/json+ unless this says otherwise # @param query [Hash, nil] only answer requests carrying these parameters # @return [self] def stub(method, path, status: 200, body: nil, headers: {}, query: nil) - # Stringified here rather than on each request, so that a query the - # transport would refuse - a nil value - is reported against the line - # that wrote the stub instead of against whichever request reached it. - scope = query && ::ZammadAPI::Transport.stringify_query(query) - # A scope that names nothing matches every request, which is what a stub - # with no query at all is. Kept apart, the two were equally specific and - # `query: {}` collided with a catch-all as an ambiguous pair rather than - # joining it. - scope = nil if scope.nil? || scope.empty? - - # Refused here rather than stringified into something the wire could not - # carry, and for the same reason the query above is: the error names the - # line that wrote the stub. A nil `Content-Type` became `''`, which then - # beat the JSON default this method supplies and served a Hash body - # undecoded, so the test failed inside the code under test with nothing - # to say the stub was at fault. - headers.each do |name, value| - next if value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(Numeric) - - raise ArgumentError, "header #{name} was stubbed as #{value.inspect}, and a response header is always text: pass a String" - end + headers = headers.to_h { |name, value| [name.to_s.downcase, value.to_s] } + headers = { 'content-type' => 'application/json' }.merge(headers) if body.is_a?(Hash) || body.is_a?(Array) @monitor.synchronize do - (@stubs[key(method, path)] ||= []) << { - status: status, - body: body, - headers: response_headers(headers, body), - query: scope - } + (@stubs[key(method, path)] ||= []) << { status: status, body: body, headers: headers.freeze, query: query && stringify(query) } end self end @@ -203,483 +114,102 @@ def requests = @monitor.synchronize { @requests.dup.freeze } def reset @monitor.synchronize do @stubs.clear - @served.clear @requests.clear end self end # @return [Array] one +"GET api/v1/groups"+ per stubbed endpoint - def stubbed = @monitor.synchronize { @stubs.keys.map { |method, path| "#{method.to_s.upcase} #{path}" } } - - # Reads both collections under the monitor, and reaches for @stubs rather - # than {#stubbed} because the monitor is a plain Mutex and would deadlock - # on the way back in. The counts used to be read outside it, so printing a - # stand-in from a failure message or a debugger raced the thread under - # test appending to @requests - which is the one thing the monitor is here - # to prevent. + def stubbed = @monitor.synchronize { stubbed_endpoints } + def inspect = @monitor.synchronize { "#<#{self.class.name} stubbed=#{@stubs.size} requests=#{@requests.size}>" } - # Answers a request from the stubs, recording it first. - # - # This is the {Transport} interface, called by the client rather than by a - # test. - # - # A request the real transport would send again is sent again here: a - # +GET+ answered 429 or 5xx, or with a 2xx whose body is shorter than - # its Content-Length, as many times as {Config#retries} allows. - # The first such answer used to be raised. Stubbed 503 and then 200, - # `client.groups.find(1)` returns the group on the wire and raised - # ServerError here, and a single stubbed 503 was recorded as one request - # where the wire carries three - so a test of code that leans on the - # retry passed or failed the other way round from production. - # - # Each attempt is recorded and takes a stub of its own, which is what - # makes "fails once, then answers" two stubs in a row. There is no wait - # between them: the backoff is the one part of a retry a test has no use - # for. Whether a response is retried at all is {Transport.retried?}, the - # real transport's own rule, so a +Retry-After+ longer than the timeout - # ends the attempts here as it does there. - # - # The count is the client's that sent the request, which is this - # stand-in's own unless the client was derived with {Client#with}: - # `ZammadAPI::Test.new(retries: 0)` raises for the first failure, and - # so does `zammad.client.with(retries: 0)`. It used to be read from the - # stand-in whichever client asked, so the derived one was asked three - # times here where the wire is asked once. The +timeout+ a - # +Retry-After+ is held against is read the same way. - # - # A 2xx stubbed with a +Content-Length+ that announces more than its - # body holds is the response the wire raises {IncompleteResponseError} - # for, and is raised for here: it is how a test says that a save was - # answered and the answer cut short. + # Answers a request from the stubs, recording it first. This is the + # {Transport} interface, called by the client rather than by a test. # # @api private - # @param config [Config] the configuration of the client that sent the - # request # @return [Response] - # @raise [ResponseError] for a stubbed non-2xx status, once the retries - # it is due are spent - # @raise [IncompleteResponseError] for a stubbed 2xx whose body is - # shorter than its Content-Length + # @raise [ResponseError] for a stubbed non-2xx status # @raise [UnstubbedRequestError] when no stub matches - def answer(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil, on_behalf_of: nil, config: self.config) + def answer(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil, on_behalf_of: nil) relative = ::ZammadAPI::Transport.relative_path(path) - # Through the real transport's own stringification, so that {Request#query} - # and {Request#headers} hold what a request would have carried rather - # than the raw Ruby values. A stand-in that records a different shape - # than the wire makes an assertion pass here and fail in production, or - # the other way round - and the header rules are where that matters - # most, because a reserved name or a non-text value is refused on the - # wire and would otherwise sail through here. - params = ::ZammadAPI::Transport.stringify_query(query || {}) - fields = ::ZammadAPI::Transport.stringify_headers(headers || {}) - # For the refusal alone: a body the wire could not carry is refused here - # too, before anything is recorded. What is recorded is the body as the - # test wrote it, which is what a test asserts against. ::ZammadAPI::Transport.encode_body(body, operation: operation, resource_class: resource_class) - request = Request.new(verb: method, path: relative, query: params, body: snapshot(body), headers: fields, on_behalf_of: on_behalf_of) + params = stringify(query || {}) + request = Request.new( + verb: method, + path: relative, + query: params, + body: DeepCopy.frozen_copy(body), + headers: (headers || {}).to_h { |name, value| [name.to_s.downcase, value.to_s] }, + on_behalf_of: on_behalf_of + ) - response = attempt(request) - config.retries.times do - break if !::ZammadAPI::Transport.retried?(config, method, response) - - response = attempt(request) - end - # Held to its Content-Length as the wire holds it: see - # {Transport.whole}. - return ::ZammadAPI::Transport.whole(response, operation: operation, config: config) if response.success? - - raise ResponseError.build(response, operation: operation, resource_class: resource_class) - end - - private - - # One delivery of a request: recorded, and answered by the stub whose - # turn it is. - # - # @return [Response] - # @raise [UnstubbedRequestError] when no stub matches - def attempt(request) stub = @monitor.synchronize do @requests << request - take(request.verb, request.path, request.query) + take(method, relative, params) end + raise UnstubbedRequestError, unstubbed_message(request) if stub.nil? - raise UnstubbedRequestError, unstubbed_message(request.verb, request.path, request.query) if stub.nil? - - response_for(stub, request.query) - end - - def key(method, path) = [method.to_sym, ::ZammadAPI::Transport.relative_path(path)] - - # The headers a stub answers with, downcased the way a {Response} carries - # them. - # - # A Hash or Array body is served as JSON, so it gets the content-type a - # real one would. {Transport#decode} always hands over a response whose - # headers name the type - it is what the decode branches on - while this - # set `json: true` directly and left the headers as written, so every - # stubbed response differed from the wire in a header a test can read. - # Code that branches on `response.headers['content-type']` passed against - # Zammad and failed against the stand-in, or the reverse, which is the - # divergence this kit exists to keep out. - # - # A caller's own content-type wins, so a test can still say the endpoint - # answered with something else. - def response_headers(headers, body) - # Values stringified as well as names. Only the name was normalised, so - # `headers: { 'X-Total-Count' => 7 }` reached the code under test as an - # Integer where the wire always carries "7": an assertion written the - # natural way passed against Zammad and failed here, or the reverse, and - # the one reader inside this gem had to tolerate both types to cope. - # Downcasing is what creates the collision, so it is refused here rather - # than merged: `{'Content-Type' => 'text/html', 'content-type' => - # 'application/json'}` kept whichever Hash order put last and dropped the - # other without a word - the same silent drop DuplicateKeys refuses for a - # query parameter, and here it decided whether the body was decoded. - normalized = DuplicateKeys - .normalize(headers, noun: 'header') { it.to_s.downcase } - .transform_values(&:to_s) - return normalized if !body.is_a?(Hash) && !body.is_a?(Array) - - { 'content-type' => 'application/json' }.merge(normalized) - end + response = response_for(stub) + return response if response.success? - # A copy of the payload, frozen, for the record of what was sent. - # - # The caller's Hash used to be recorded by reference, so a test that built - # one payload, sent it, then changed it for a second call rewrote the - # first recorded request and asserted against a body that never went - # anywhere. `query` is already a fresh structure by the time it gets here, - # because the transport's stringification builds one; `body` is handed - # over untouched, and was the one shape left sharing state with the test. - def snapshot(value) = DeepCopy.frozen_copy(value) - - # Picks the stub that answers this request, and keeps the last one of its - # kind in place so that one stub can answer any number of requests while - # two describe a sequence. - # - # Sequencing runs within a query scope, not across the endpoint. Keying it - # on the last stub queued meant a query-scoped stub was consumed on its - # first use as soon as any other stub for the same verb and path existed - # behind it - the pair a `search(...).count` test needs - so the second - # count silently fell through to the records stub and walked the pages. - # - # A scope here is the exact set of parameters a stub names, not merely the - # fact that it names some. Grouped by whether a stub was scoped at all, - # two stubs carrying *different* scopes were read as a sequence and the - # first was consumed: stubbing a search once for its records and once for - # its count made `count` eat the records stub, hand back an Array where a - # count belonged, and then raise UnstubbedRequestError for a page that was - # stubbed all along. - # - # The most specific scope answers, counting the parameters it pins, so a - # stub written for one request still wins over a catch-all for the - # endpoint however they were declared. Scopes that tie are genuinely - # ambiguous and say so. - # - # A request for a later page does not move the sequence on. Every full - # read of a collection asks for the page after its last one, to learn - # that there is none, and that request used to take the next stub in the - # queue and serve it as the empty page {#paged_body} makes of it: with - # three list stubs A, B and C, three reads answered A, C and C, and B was - # never seen. The trailing request belongs to the read that made it, so it - # is answered by the stub that read's first page came from. - # - # A stub that answered while it was the last of its kind has had its - # turn, and gives way to one declared after it. It is kept in place so - # that it can go on answering, and so it was still at the head once a - # second one was queued behind it, and was taken for the first of a - # sequence that had not begun: stubbed open, read, stubbed closed and - # read again, a ticket was open twice and closed at the third read. A - # test that changes what an endpoint answers as it goes is the same - # sequence as one that declares it up front. - # - # A request for the count of a search does not move the sequence on - # either, where the stub whose turn it is holds records rather than a - # total. `count` asks with +only_total_count+ first, is answered with the - # records the way a Zammad before 6.5.0 answers it, and walks the pages - # instead, so the request and the walk are one read. Taken for two, they - # spent a stub each: three stubs of one, two and three records counted - # two, three and three, where `to_a.size` over the same stubs is one, two - # and three. See {#counted_alone?}. - def take(method, path, params) - endpoint = key(method, path) - queued = @stubs[endpoint] - return nil if queued.nil? - - matching = queued.each_index.select { matches?(queued[it][:query], params) } - return nil if matching.empty? - - group = most_specific(queued, matching, method, path) - scope = queued[group.first][:query] - served = @served[[endpoint, scope]] - # The stub at the head of the queue is the fallback, for a later page - # that is the first thing asked: `page(3)` on a list nothing has read. - return served || queued[group.first] if later_page?(scope, params) - - # A stub that answered while it was the last of its kind has had its - # turn, so the one behind it is due. - turn_over = group.size > 1 && queued[group.first].equal?(served) - due = queued[turn_over ? group[1] : group.first] - return due if count_request?(scope, params) && !counted_alone?(due) - - @served[[endpoint, scope]] = advance(queued, group, turn_over) - end - - # Moves a sequence on by one read, and hands over the stub that read is - # answered by. The last of its kind is kept in place, to go on answering. - def advance(queued, group, turn_over) - if turn_over - queued.delete_at(group.first) - # Every other stub of the group sat behind the one that went. - group = group.drop(1).map(&:pred) - end - - group.one? ? queued[group.first] : queued.delete_at(group.first) - end - - # Whether a request asks a search for its total alone, of a stub that - # was not written for that request in particular. One scoped to - # +only_total_count+ is the answer to this request and to no other, and - # is sequenced as any stub is. - def count_request?(scope, params) - params.key?('only_total_count') && !scope&.key?('only_total_count') - end - - # Whether a stub answers a request for the total with one, which makes - # that request the whole of a `count`. {Collection#total_count} reads a - # total off a 2xx whose body is an object holding a count, and walks the - # pages for anything else. - # - # A stub of another status is no part of a walk: the request it answers - # fails, or is sent again, and either way has had a stub of its own. - def counted_alone?(stub) - return true if !Response::SUCCESS_STATUSES.cover?(stub[:status]) - - body, = Response.decode_body(stub[:headers]['content-type'], raw_body_for(stub[:body])) - total = body.is_a?(Hash) ? body[:total_count] : nil - total.is_a?(Integer) && !total.negative? - end - - # Whether a request asks for a page beyond the first of a list whose stub - # did not say what its pages hold. Such a stub is one page of records, so - # the request is the tail of a read rather than a read of its own. - def later_page?(scope, params) - return false if scope&.key?('page') - - ![nil, '1'].include?(params['page']) - end - - # The matching stubs that share the most specific scope, in the order they - # were declared. - # - # @raise [AmbiguousStubError] when two scopes are equally specific - def most_specific(queued, matching, method, path) - scopes = matching.group_by { queued[it][:query] } - depth = scopes.keys.to_h { [it, it.nil? ? 0 : it.size] } - best = depth.values.max - - winners = scopes.select { |scope, _| depth[scope] == best } - raise AmbiguousStubError, ambiguous_message(method, path, winners.keys) if winners.size > 1 - - winners.values.first + raise ResponseError.build(response, operation: operation, resource_class: resource_class) end - def ambiguous_message(method, path, scopes) - rendered = scopes.map { "query: #{it.inspect}" }.join(' and ') - "#{method.to_s.upcase} #{path} is matched equally well by #{scopes.size} stubs (#{rendered}), " \ - 'and this stand-in will not guess which one you meant. Name the parameters that tell the requests apart ' \ - '- a count stub that also carries the search term is more specific than one that does not - or leave the ' \ - 'more general stub unscoped, which makes it a catch-all that answers only what the scoped ones do not.' - end + private - # Both sides have been through the transport's own stringification, the - # stub's when it was declared. Comparing a raw value against a stringified - # one worked for a scalar - `1.to_s` is `"1"` either way - and could never - # match for an Array: `[1, 2].to_s` is `"[1, 2]"` while the recorded - # `["1", "2"].to_s` is `"[\"1\", \"2\"]"`. `ids`, `role_ids`, `group_ids` - # and `permissions` are all array-valued search parameters, so a stub - # scoped to any of them silently never answered and the request came back - # as unstubbed. - def matches?(expected, params) - return true if expected.nil? - - expected.all? { |name, value| params[name] == value } - end + def key(method, path) = [method.to_sym, ::ZammadAPI::Transport.relative_path(path)] - # The records a stub holds are one page of them, not the answer to every - # page. - # - # A collection walks until a page repeats, comes back short, or comes back - # empty. A stub that keeps serving the same records to every page trips - # the first of those, so the obvious way to stand in for a list endpoint - - # one `stub(:get, 'api/v1/groups', body: [...])` - made every full read of - # that collection raise PaginationError, and the only way to find that out - # was to hit it. Against a real Zammad the same code works, because page 2 - # comes back empty; the stand-in is what differed. - # - # So a stub that does not name a page answers one, and a request for any - # page after it gets an empty one. A stub that does name a page is left - # exactly as written - that is how a test says what the second page holds. - # - # A search stubbed with its total beside the records, the object Zammad - # answers `with_total_count` with, is a list as well: the page after it - # holds no records and reports the same total. Served again as written it - # was the repeated page above, for the one stub that says how many hits - # there are. - # - # And the page is of the size the request asks for. Only the page number - # was read, so the records were served whole to page 1 whatever - # +per_page+ said, and every later page was empty: five records stubbed, - # `page(1, per_page: 2)` held all five, `page(2, per_page: 2)` none, and - # `in_batches(of: 2)` yielded one batch of five, where Zammad serves two, - # two and one. Code that pages by hand, or leans on a batch size, saw - # other records here than on the wire. A stub that names a +per_page+ of - # its own is what a request of that size is answered, and is not cut. - def paged_body(stub, params, body) - scope = stub[:query] - later = later_page?(scope, params) - window = scope&.key?('page') || scope&.key?('per_page') ? nil : page_window(params) - return body if window.nil? && !later - - case body - in Array then page_of(body, window) - in { records: Array => records, total_count: _ } - page = page_of(records, window) - page.equal?(records) ? body : body.merge(records: page) - else body + def stringify(value) + case value + when Hash then value.to_h { |name, nested| [name.to_s, stringify(nested)] } + when Array then value.map { stringify(it) } + else value.to_s end end - # The records at the offset and of the size a request asks for, or none - # for a later page of a request that names no size. - # - # The records themselves where the page holds all of them, so that the - # response keeps the bytes the stub was written with. - def page_of(records, window) - return [] if window.nil? - - offset, size = window - return records if offset.zero? && records.size <= size + # What a later page is answered with where the stub names no page. + EMPTY_PAGE = { status: 200, body: [].freeze, headers: { 'content-type' => 'application/json' }.freeze, query: nil }.freeze + private_constant :EMPTY_PAGE - records[offset, size] || [] - end + # The first stub of the endpoint whose query matches, spent unless it is + # the last that does. A later page, where that stub names no page, is an + # empty list and spends nothing. + def take(method, path, params) + queued = @stubs[key(method, path)] || [] + matching = queued.each_index.select { |index| matches?(queued.fetch(index)[:query], params) } + return nil if matching.empty? - # A whole number a query parameter writes, the way Zammad reads +page+ - # and +per_page+. - PAGE_NUMBER = /\A[1-9]\d*\z/ - private_constant :PAGE_NUMBER + stub = queued.fetch(matching.first) - # Where the page a request asks for begins, and how many records it - # holds. - # - # @return [Array(Integer, Integer), nil] nil where the request names no - # +per_page+, or where either figure is not a number above zero - def page_window(params) - page = params.fetch('page', '1') - size = params['per_page'] - return nil if !PAGE_NUMBER.match?(page.to_s) || !PAGE_NUMBER.match?(size.to_s) - - [(page.to_i - 1) * size.to_i, size.to_i] - end + return EMPTY_PAGE if !['1', nil].include?(params['page']) && !stub[:query]&.key?('page') - # Decoded by {Response.decode_body}, the rule {Transport#decode} reads, so - # that a stub answers the way the wire does. - # - # `json:` used to be set from the Ruby type of the stub's body, which made - # the content-type beside it decorative: a stub could say `text/html` and - # still hand back a decoded Hash with `json?` true, where Zammad gives the - # raw string and `decoded(:object)` raises ParseError. A test asserting - # that path passed here and failed in production, which is the divergence - # this kit exists to rule out. - # Paged after decoding, not before. Paging read the stub's body as written, - # which was the same thing only while a list could arrive as an Array - and - # once the content-type decided decoding, a list stubbed as a JSON string - # decoded to one and was never paged, so it answered every page with the - # same records and every full read of that collection raised - # PaginationError. Against Zammad the same code works, because page two - # comes back empty. - # - # A stub written short of its own Content-Length is not paged. It is how - # a test says that the answer was cut short, and a page cut from it - # would be counted anew and served as whole. - def response_for(stub, params) - raw = raw_body_for(stub[:body]) - body, json = Response.decode_body(stub[:headers]['content-type'], raw) - written = build_response(stub, body, raw, json: json) - return written if ::ZammadAPI::Transport.cut_short?(written) - - paged = paged_body(stub, params, body) - # Re-serialized only where paging replaced the body, so `raw_body` stays - # the bytes the stub was written with for every other response. - return written if paged.equal?(body) - - replaced = JSON.generate(paged) - build_response(stub, paged, replaced, json: json, headers: recounted(stub[:headers], replaced)) + queued.delete_at(matching.first) if matching.size > 1 + stub end - # The headers of a stub for a body that paging replaced. A - # Content-Length written for the records does not count the page cut - # from them, or the empty one served after them, and would have it - # refused as cut short. - def recounted(headers, raw_body) - return headers if !headers.key?('content-length') - - headers.merge('content-length' => raw_body.bytesize.to_s) - end + def matches?(expected, params) = expected.nil? || expected.all? { |name, value| params[name] == value } - # The bytes a stub's body would have arrived as. A Hash or Array is what a - # test writes when it means JSON, so that is what it is serialized to; - # anything else is already the body. - def raw_body_for(body) - case body - when Hash, Array then JSON.generate(body) - when nil then '' - else body.to_s - end - end + def response_for(stub) + raw = case stub[:body] + when Hash, Array then JSON.generate(stub[:body]) + when nil then '' + else stub[:body].to_s + end - # A copy, because the stub keeps serving after this response is built and - # Response is a value. Handing out the stub's own Hash made every response - # from one stub share it, so a test that wrote to `response.headers` - - # editing a content-type to check a decode path, say - rewrote the - # stand-in for every later request in the example. The real transport builds a fresh - # hash per response, and this exists to behave like it. - def build_response(stub, body, raw_body, json:, headers: stub[:headers]) - Response.new(status: stub[:status], headers: headers.dup.freeze, body: body, raw_body: raw_body, json: json) + Response.new(status: stub[:status], headers: stub[:headers], body: Response.decode_body(stub[:headers]['content-type'], raw), raw_body: raw) end - # Where the endpoint is stubbed and only the query kept every stub from - # answering, the message says so, with the query the request carried - # and the scopes the stubs name. Listing the endpoint among what is - # stubbed, as it does for a wrong path, read as a contradiction: a read - # over stubs for pages 1 and 2 asks for page 3, and was told that - # `GET api/v1/users/search was not stubbed (stubbed: GET - # api/v1/users/search)`. - def unstubbed_message(method, path, params) - request = "#{method.to_s.upcase} #{path}" - scopes = @monitor.synchronize { @stubs[key(method, path)]&.map { it[:query] }&.uniq } - return unmatched_query_message(request, params, scopes) if scopes - - stubbed_endpoints = stubbed.empty? ? 'nothing is stubbed' : "stubbed: #{stubbed.join(', ')}" - "#{request} was not stubbed on this #{self.class.name} (#{stubbed_endpoints})" - end + def stubbed_endpoints = @stubs.keys.map { |method, path| "#{method.to_s.upcase} #{path}" } - def unmatched_query_message(request, params, scopes) - message = "#{request} with query #{params.inspect} was not stubbed on this #{self.class.name}: " \ - "its stubs answer only #{scopes.map { "query: #{it.inspect}" }.join(', ')}." - return message if !params.key?('page') || !scopes.all? { it&.key?('page') } + def unstubbed_message(request) + stubbed = @monitor.synchronize { stubbed_endpoints } - "#{message} A read asks for the page after the last one it was served, to learn that there are no more: " \ - 'stub that page as well, with body: [], or leave page out of the scope, and the stub serves its records as one ' \ - 'page and an empty page after it.' + "#{request.verb.to_s.upcase} #{request.path} with query #{request.query.inspect} was not stubbed on this " \ + "#{self.class.name} (#{stubbed.empty? ? 'nothing is stubbed' : "stubbed: #{stubbed.join(', ')}"})" end - # Routes the client's requests to {Test#answer}, and carries the - # +on_behalf_of+ scope and the configuration the way the real transport - # does. + # The transport a {Test} client talks through. # # @api private class Transport @@ -687,35 +217,17 @@ class Transport attr_reader :test, :config, :on_behalf_of - # The scope is stringified, copied and checked by the real transport's - # own rule, so that a recorded scope is what a request would have - # carried. Here rather than in {#with_on_behalf_of} alone, which left - # one built directly holding whatever it was given. + # @param test [Test] + # @param on_behalf_of [String, nil] + # @param config [Config] def initialize(test, on_behalf_of: nil, config: test.config) @test = test @config = config - @on_behalf_of = ::ZammadAPI::Transport.stringify_on_behalf_of(on_behalf_of) + @on_behalf_of = on_behalf_of end def with_on_behalf_of(identifier) = self.class.new(test, on_behalf_of: identifier, config: config) - # What the real transport writes for Psych, so that a record's YAML - # is the same under the stand-in and does not carry every stub and - # every recorded request with it. - # - # @param coder [Psych::Coder] - # @return [void] - def encode_with(coder) = coder.represent_object(nil, JSON.parse(::ZammadAPI::Transport.description(config, on_behalf_of).to_json)) - - # {Client#with} re-validates the options and hands them here. There is - # no connection to rebuild, and the same stand-in keeps answering, but - # the configuration is the transport's to carry as well as the - # client's. This returned self, and everything read from the transport - # stayed the stand-in's own: `client.with(retries: 0)` was asked as - # often as the stand-in retries, and a record found through - # `client.with(url:)` named the stand-in's URL as its installation, so - # it compared equal to the same id found through the client it was - # derived from. def with_config(config) = self.class.new(test, on_behalf_of: on_behalf_of, config: config) def request(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) @@ -727,8 +239,7 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou body: body, headers: headers, resource_class: resource_class, - on_behalf_of: on_behalf_of, - config: config + on_behalf_of: on_behalf_of ) end end diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index d496cdf..aeeaf5d 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1,16 +1,14 @@ # frozen_string_literal: true -require 'date' require 'faraday' require 'faraday/retry' require 'json' require 'openssl' require 'socket' require 'timeout' +require 'uri' -require_relative 'duplicate_keys' require_relative 'errors' -require_relative 'query_encoder' require_relative 'response' module ZammadAPI @@ -22,15 +20,8 @@ module ZammadAPI # # @api private class Transport - # The verb shorthands, defined once for the two transports that answer - # them. - # - # {Test::Transport} stands in for this class precisely so that the code - # under test cannot tell them apart, and it carried its own copy of this - # loop - so a fifth verb added here would have left the stand-in unable to - # answer one the real transport had. The same argument as - # {Transport.relative_path} and {Resources::Base.member_path}: a rule kept - # in two places is one that gets changed in one of them. + # The verb shorthands, shared with {Test::Transport} so that the two answer + # the same calls. # # @api private module Verbs @@ -48,39 +39,17 @@ module Verbs include Verbs - # HTTP methods that are safe to repeat against Zammad: the ones that only - # read. - # - # PUT and DELETE are idempotent in HTTP and used to be here for that - # reason, but neither is safe to repeat against Zammad. A ticket update - # carrying an `article` creates that article on every delivery, so an - # update answered with a 504 and then a 200 added the article twice and - # sent its e-mail twice, while `update` reported success once. And a - # DELETE whose first answer was lost was repeated into a 404, so - # `destroy` raised NotFoundError for a record it had just deleted. A - # write that fails is reported instead, the way a POST always was, and - # the caller - who knows what the request carried - decides. + # Methods that are retried: the ones that only read. A write that timed + # out may still have been applied, so it is not sent twice. RETRIABLE_METHODS = %i[get head options].freeze - # Transient statuses worth retrying. + # Statuses a read is retried on. RETRIABLE_STATUSES = [429, 500, 502, 503, 504].freeze - # Socket failures that mean the request ran out of time. Most adapters - # wrap these into a Faraday error, but not all do, and this gem lets a - # caller choose the adapter. - # - # `timeout` and `socket` are required above for this list and the next - # one. Both constants used to resolve only because `require 'faraday'` - # reaches net/http, which loads them - so the day Faraday stops eagerly - # loading its default adapter, or a caller picks a slimmer one, this class - # body raises NameError and `require 'zammad_api'` fails before a single - # request. The Steepfile has declared both libraries all along. + # Errors that mean the request timed out. TIMEOUT_ERRORS = [Errno::ETIMEDOUT, Timeout::Error].freeze - # Socket failures that mean the instance could not be reached. Listed - # rather than caught as SystemCallError, so that an unrelated Errno - a - # logger writing to a full disk, say - is not relabelled as a network - # problem. + # Socket errors an adapter may raise without wrapping them. CONNECTION_ERRORS = [ Errno::ECONNREFUSED, Errno::ECONNRESET, @@ -90,1021 +59,93 @@ module Verbs SocketError ].freeze - # TLS failures, for the same reason the socket errors above are listed: - # most adapters wrap one into a Faraday::SSLError, but this gem lets a - # caller choose the adapter and not every adapter does. Unlisted, a - # certificate mismatch through such an adapter left `request` raw, past - # the `rescue ZammadAPI::TransportError` a caller had written - the one - # thing the rescue clauses there exist to prevent. - # - # Not in {RETRIABLE_EXCEPTIONS}: a rejected certificate is a fact about - # the instance, not a transient failure, and retrying it only delays the - # error by the backoff. + # TLS errors an adapter may raise without wrapping them. SSL_ERRORS = [OpenSSL::SSL::SSLError].freeze - # A 2xx response whose body stopped short of its Content-Length, as it - # is raised inside the connection: see {HeldToLength}. It never leaves - # {#request}, which reports it as an {IncompleteResponseError}. - # - # @api private - class CutShort < Faraday::Error; end - private_constant :CutShort - - # Holds a 2xx response to its Content-Length where the retry middleware - # sees the outcome: below it in the stack. - # - # {#request} asked this of the response it was handed, which is after - # the retry middleware has returned. So a read whose body the connection - # dropped under was asked once and raised, while the same drop a moment - # earlier, surfacing as ECONNRESET, was asked again: which of the two a - # flaky link produced decided whether `retries` meant anything, and a - # download of an attachment is the read most likely to be cut. - # - # Raised for every method, and sent again for the ones the retry - # middleware repeats, which a write is not among. - # - # Above the caller's `middleware:`, so the body and the headers are - # asked as that left them, which is how {#request} saw them. A body - # that is no text is left for {#raw_body!} to refuse. - # - # @api private - class HeldToLength < Faraday::Middleware - # @param env [Faraday::Env] - # @return [void] - # @raise [CutShort] - def on_complete(env) - body = env.body - return if !Response::SUCCESS_STATUSES.cover?(env.status) || !(body.nil? || body.is_a?(String)) - return if Transport.short_by(env.status, env.response_headers, body.to_s).nil? - - raise CutShort.new('the body ended short of its Content-Length', env.response) - end - end - private_constant :HeldToLength - - # Failures worth retrying. Faraday::RetriableResponse is how the retry - # middleware signals a retriable status internally and must stay in this - # list, otherwise it escapes as an unhandled Faraday error. - # - # {CutShort} is the one this class raises itself, for a response the - # connection closed under. - # - # Composed from the two lists above rather than repeating them. Listed - # by hand, CONNECTION_ERRORS was left out: a transient ECONNRESET through - # an adapter that wraps it was retried as a Faraday::ConnectionFailed, - # while the same failure through an adapter that does not raised on the - # first attempt - so how often a request was retried depended on which - # adapter a caller picked, and `request` already documents these as - # failures this class expects to see. The retry middleware still only - # retries RETRIABLE_METHODS, so a write is not repeated. + # Errors a read is retried on. RETRIABLE_EXCEPTIONS = [ Faraday::RetriableResponse, Faraday::ConnectionFailed, Faraday::TimeoutError, - CutShort, *TIMEOUT_ERRORS, *CONNECTION_ERRORS ].freeze - # Substrings that mark a key of what a request carries - its payload, its - # query, its headers - as holding a credential. - # Matching on a substring rather than the whole key covers the variants - # Zammad and OAuth actually send - password_confirm, access_token, - # refresh_token, client_secret - which an exact-match list silently let - # through to the log. - # - # The same argument reaches further than the first version of this list - # took it. `password` alone wrote `passwd` and `pwd` out in full, and - # `private_key` covered exactly one of the key spellings, so `api_key` - # and a bare `key` went to the log intact. `key` is matched as a word - # rather than as a substring, so `ssh_key` and `key` are covered while - # `keyboard` and `monkey_id` are not; `apikey` is spelled out because - # nothing separates the word there. - # - # `cookie` and `authorization` are here for the headers. A raw request - # takes headers of its own, and the log prints them: `Cookie` carries a - # session and matched nothing above, so `client.get(path, headers: - # {'Cookie' => ...})` wrote it out in full at debug level, and - # `Proxy-Authorization` went the same way. `Authorization` itself never - # gets this far - {RESERVED_HEADERS} refuses it - but every header named - # after it carries what it carries. - # - # `bind_pw` and `passphrase` are Zammad's own: the password an LDAP - # source binds with, which sits inside its +preferences+, and the - # passphrase of a PGP key. Neither matched a word above, so creating - # either wrote it to the log, and a record of an LDAP source printed - # it. Both are in the list Zammad filters its own log by, in - # config/initializers/filter_parameter_logging.rb, and so are `otp` and - # `salt`. Those two are matched as words, as `key` is: `footprint` - # holds one and `basalt` the other. `totp` and `hotp` are the two kinds - # of one-time password, and count. - # - # `key` as a word did not see the one in `privateKey`, where no - # separator stands in front of it. A capital K after a lower-case - # letter or a digit begins the word as well, which is where camelCase - # puts it. `hotKeyboard` is left alone, as `keyboard` is. + # Keys whose values are never written to the log. SENSITIVE_KEY_PATTERN = / password|passwd|pwd|bind_pw|passphrase|token|secret|credential|cookie|authorization|api_?key |(? 2}` used to collapse - # into one parameter and send whichever Hash insertion order put last, - # dropping the other value without a word - the same silent-wrong-result - # shape as the dropped nil above, and the reason {ResourceProxy#search} - # normalises its keywords before they ever reach here. - # - # What is not a Hash and converts to one is read as that Hash, at the - # top and at any depth, as a record reads its attributes: see - # {DeepCopy.frozen_object}. `ActionController::Parameters` is the case. - # A +condition+ handed to {ResourceProxy#search} as one went on the wire - # as its +to_s+, which is the unnarrowed search described below, and a - # whole +query:+ given as one raised NoMethodError from inside the gem. - # So did anything else that is no Hash, and that is refused here by - # name. - # - # @api private - # @param query [Hash] - # @return [Hash{String => String, Array, Hash}] - # @raise [ArgumentError] for a query that is not a Hash, for a nil - # value, for a value that is neither text, a number, a boolean, a - # list nor a structure, for two keys that name the same parameter, - # for a list a query string cannot carry, or for a Hash with no value - # in it, the last five at any depth - def self.stringify_query(query) - hash = Hash.try_convert(query) || raise(ArgumentError, "query needs to be a Hash of parameter names and values, got #{query.class}") - - refuse_unwritten!(stringify_query_hash(hash, nil), nil) - end - - # Refuses a Hash a query string says nothing of: one with no value in - # it, or with nothing but such Hashes. - # - # {QueryEncoder} writes a pair for each value and has none to write - # here, so the parameter was not in the request, and Zammad answered as - # if it had been left out: `client.get(path, query: {filter: {}, a: - # 1})` asked for `?a=1`, and a `condition` built from nothing searched - # unnarrowed. A nil is refused for the same reason, and so is an empty - # Hash inside a list. It is named by the outermost parameter nothing is - # written for. - # - # Apart from {.stringify_query_hash}, so that {ResourceProxy#search} - # can say it in its own words for a keyword of its own first. - # - # @api private - # @param query [Hash] as {.stringify_query_hash} leaves it - # @param prefix [String, nil] the parameter path the Hash sits at - # @return [Hash] the query - # @raise [ArgumentError] - def self.refuse_unwritten!(query, prefix) - query.each do |name, value| - path = prefix ? "#{prefix}[#{name}]" : name - - case value - when Hash - raise ArgumentError, unwritten_query_message(path) if !QueryEncoder.written?(value) - - refuse_unwritten!(value, path) - when Array - value.each_with_index { |element, index| refuse_unwritten!(element, "#{path}[#{index}]") if element.is_a?(Hash) } - end - end - end - - # @api private - # @return [String] - def self.unwritten_query_message(path) - "query parameter #{path} is a Hash with no value in it, and a query string writes nothing for one: Zammad would " \ - 'answer as if the parameter had been left out. Pass a value, or leave the parameter out' - end - - # Stringifies one level of a query, at whatever depth it sits. - # - # The duplicate check lives here rather than at the top level alone, - # because `condition` - which the search endpoints read, and which - # {ResourceProxy#search} takes as a keyword - is a Hash, and two - # spellings inside it collapsed exactly - # the way two spellings at the top level did. The nil check below has been - # at every depth all along; this is the same kind of rule. - # - # The key each name was first seen as is kept, so the message can print - # both spellings. Naming only the second left the reader to guess the - # first, which in a query assembled across several merges is the whole of - # the debugging. - # - # @api private - # @param hash [Hash] - # @param prefix [String, nil] the parameter path this Hash sits at - # @return [Hash{String => String, Array, Hash}] - # - # A key with an empty name is refused, for the reason a list Rails - # cannot read back is: a query string has no way to write one. Inside a - # structure it is written `[]`, which Rails reads as a list - `{list: - # [{'' => '1'}]}` arrives as `[['1']]` - and at the top level as - # `=value`, which Rails drops. - def self.stringify_query_hash(hash, prefix) - DuplicateKeys - .normalize(hash, prefix: prefix, &:to_s) - .to_h do |name, value| - raise ArgumentError, empty_query_name_message(prefix) if name.empty? - - [name, stringify_query_value(prefix ? "#{prefix}[#{name}]" : name, value)] - end - end - - # @api private - # @return [String] - def self.empty_query_name_message(prefix) - found = if prefix - "query parameter #{prefix} holds a key with an empty name, and a query string writes that as #{prefix}[], which Rails reads as a list" - else - 'a query parameter has an empty name, and a query string writes that as nothing but its value, which Rails drops' - end - - "#{found}. Name the key, or put a structure a query string cannot carry in the JSON body of a raw request, such as client.post." - end - - # Stringifies the scalars and leaves the structure to {QueryEncoder}. - # - # A nested value used to be rendered with to_s, so the `condition` that - # Zammad's search endpoints read - and that {ResourceProxy#search} takes - # as a keyword - went on the wire as a Ruby inspect string. Zammad could not parse that, dropped the parameter, and - # answered with an unnarrowed search that nothing marked as unnarrowed. - # A Hash is written as `condition[ticket.state_id][operator]=is`, which - # is the shape Rails reads back. - # - # The same happened one kind of value further out. Whatever was neither - # a Hash nor an Array was still rendered with to_s: `ids: Set[1, 2]` - # went on the wire as `ids=Set[1, 2]` and `ids: (1..3)` as `ids=1..3`, - # text that names no record and that Zammad narrows by all the same, - # and a record under a key went as `#`. - # Refused, as a record where an id belongs is by - # {.escape_path_segment}, and for its reason: the answer to such a - # request is the wrong one, and nothing marks it. See - # {QUERY_VALUE_TYPES} for what is written. - # - # @api private - # @param key [String] the parameter path, for the error message - # @param value [Object] - # @return [String, Array, Hash] - # @raise [ArgumentError] for a nil value, a value a query string has no - # spelling for, or a list it cannot carry - def self.stringify_query_value(key, value) - case value - when nil then raise ArgumentError, "query parameter #{key} is nil, and Zammad has no way to read that: pass a value, or leave the parameter out" - when Hash then stringify_query_hash(value, key) - when Array then stringify_query_list(key, value) - when *QUERY_VALUE_TYPES then stringify_query_scalar(key, value) - else - converted = Hash.try_convert(value) || raise(ArgumentError, not_a_query_value_message(key, value)) - - stringify_query_hash(converted, key) - end - end - - # One of {QUERY_VALUE_TYPES} as text. - # - # A Float that is not a number, or not a finite one, is refused. It is - # of a type the list names and prints as `NaN` or `Infinity`, which is - # the text Zammad then narrowed by - the result of a division nothing - # checked, sent as a filter. - # - # @api private - # @return [String] - # @raise [ArgumentError] - def self.stringify_query_scalar(key, value) - if value.is_a?(Float) && !value.finite? - raise ArgumentError, "query parameter #{key} is #{value}, and a query string has no spelling for a Float that is not finite: " \ - 'it would be sent as that text, and Zammad would narrow by it. Pass a number, or leave the parameter out.' - end - - wire_text(value, "query parameter #{key}") - end - - # Names the class and does not quote the value, which for a record is - # every attribute it carries. - # - # @api private - # @return [String] - def self.not_a_query_value_message(key, value) - "query parameter #{key} was given as #{value.class}, and a query string carries text, Integers, Floats and " \ - 'booleans, alone or in an Array or a Hash: it would be sent as that object prints, and Zammad would narrow by that ' \ - 'text. Pass a Set or a Range as its to_a, a number of another kind as an Integer or a Float, a time as text ' \ - 'Zammad reads, such as its iso8601, and a record as its id.' - end - - # Stringifies a list, and refuses one Rails could not read back as the - # list it was. - # - # A query string does not mark where an element of a list ends, so one - # Hash after another is a new element only once it is written with a - # value the one before has a place for too - see {QueryEncoder} - and two - # with none are read as one: `[{a: 1}, {b: 2}]` arrives as - # `[{a: 1, b: 2}]`. A Hash with nothing in it is not written at all, and - # the list arrives one element short. A list directly inside a list is - # written `[]` like the one around it, and `[[1, 2], [3]]` arrives as - # three lists of one. - # - # Refused, because the other answer is a request that carries something - # the caller did not write, to an endpoint that then narrows by it. - # - # @api private - # @param key [String] the parameter path, for the error message - # @param list [Array] - # @return [Array] - # @raise [ArgumentError] - def self.stringify_query_list(key, list) - elements = list.each_with_index.map { |inner, index| stringify_query_value("#{key}[#{index}]", inner) } - - elements.each_with_index do |element, index| - reason = QueryEncoder.misread(element, index.zero? ? nil : elements[index - 1]) - raise ArgumentError, misread_element_message("#{key}[#{index}]", reason) if reason - end - - elements - end - - # What a query string does to each kind of element {QueryEncoder.misread} - # names. - MISREAD_ELEMENTS = { - merged: 'has no plain value under a key the element before it has as well, and that is all a query string has to say ' \ - 'where one element of a list ends and the next begins: Rails would read the two as one. Every condition and ' \ - 'every group of conditions in a Zammad selector carries `operator`, which is such a key', - empty: 'is a Hash with no value in it, and a query string writes nothing for one: Rails would read the list one ' \ - 'element short', - list: 'is a list directly inside a list, and a query string writes both as `[]`: Rails would read each value of ' \ - 'the inner list as a list of its own' - }.freeze - private_constant :MISREAD_ELEMENTS - - # @api private - # @return [String] - def self.misread_element_message(path, reason) - "query parameter #{path} #{MISREAD_ELEMENTS.fetch(reason)}. To send a structure a query string cannot carry, " \ - 'put it in the JSON body of a raw request, such as client.post, which carries it as it is.' - end - - # Header names this class sets from the configuration, and will not take - # from a caller. - # - # +Authorization+ is built from the credentials {Config} validated, and - # +From+ is what {Client#on_behalf_of} means. Faraday's authorization - # middleware leaves a header that is already set alone, so a raw request - # carrying one of these would have replaced the client's own - quietly, - # and while {Client#inspect} went on reporting the authentication scheme - # it was built with. Naming the option that does mean it is the useful - # answer; overwriting in silence is not. - RESERVED_HEADERS = { - 'authorization' => 'authentication is configured on the client: pass http_token:, oauth2_token:, or user: and password:, or build a second client with Client#with', - 'from' => 'the From header is what on_behalf_of sets: use client.on_behalf_of(...) to perform requests for another user' - }.freeze - - # The part of a header name that is one, from its start: what RFC 9110 - # calls a token, which is letters, digits and these signs. Read from - # the bytes, as a name is ASCII in every encoding a request can carry. - HEADER_NAME = /\A[!\#$%&'*+\-.^_`|~0-9A-Za-z]*/ - - # The headers a request carries beyond the ones this class sets. - # - # Names are downcased, which is what makes two spellings of one header - # comparable at all: HTTP treats them as the same header, so - # +{'Accept' => 'a', 'accept' => 'b'}+ would otherwise send whichever Hash - # order put last and drop the other without a word - the silent drop - # {DuplicateKeys} exists to refuse. - # - # A name that is not one is refused: see {.header_name}. - # - # Values are stringified for the reason {#with_on_behalf_of} stringifies - # the +From+ scope: a header is text on the wire, and a value of another - # type reaches Net::HTTP intact and dies there with - # `undefined method 'strip' for an instance of Integer`. - # - # Public for the same reason as {.stringify_query}: {Test} records what a - # request would have carried, and a stand-in whose recorded values - # disagree with the wire makes green tests mean less than they appear to. - # - # @api private - # @param headers [Hash] - # @return [Hash{String => String}] - # @raise [ArgumentError] for a name that is not a header name, a nil - # value, a value that is not text, two spellings of one header, or a - # header this class sets itself - def self.stringify_headers(headers) - DuplicateKeys - .normalize(headers, noun: 'header') { header_name(it) } - .to_h { |name, value| [name, stringify_header_value(name, value)] } - end - - # A header name as it is compared and sent: downcased, and refused - # where it is not a name. - # - # Only the value was checked. A name went to the adapter as it was, and - # the Net::HTTP that ships with Ruby 3.4 and 4.0 writes it to the socket - # as it is: `headers: {"X-A: 1\r\nFrom: admin@example.com\r\nX-B" => - # 'v'}` sent a From header of its own, which is the one {RESERVED_HEADERS} - # refuses by name, and an Authorization went the same way. `'From '` - # passed that lookup too, and was sent as `From : v`, and a name with - # nothing in it as `: v`. net-http refuses a control character or a - # colon from 0.10.0 on, with an ArgumentError of its own that quotes the - # name, raised after the request was logged, and takes the other two. + # The value of a +From+ header for {Client#on_behalf_of}. # - # @api private - # @param name [Object] - # @return [String] - # @raise [ArgumentError] - def self.header_name(name) - text = name.to_s - bytes = text.b - start = bytes[HEADER_NAME].to_s - raise ArgumentError, not_a_header_name_message(start) if start.empty? || start.bytesize != bytes.bytesize - - text.downcase - end - - # Quotes the name as far as it is one, and no further. - # - # @api private - # @param start [String] the part of the name that is a name - # @return [String] - def self.not_a_header_name_message(start) - found = start.empty? ? 'a header name is empty or begins' : "the header name that begins #{start.inspect} goes on" - - "#{found} with a character no header name carries: a name is letters, digits and signs such as - and _, " \ - 'without a space, a colon or a line break. The rest of it is not quoted here: what follows a line break in a ' \ - 'name would be sent as header lines of their own, and may be a credential.' - end - - # @api private - # @return [String] - def self.stringify_header_value(name, value) - reserved = RESERVED_HEADERS[name] - raise ArgumentError, "header #{name} is set by this client, not by a request: #{reserved}" if reserved - raise ArgumentError, "header #{name} is nil, and a header is always text: pass a value, or leave the header out" if value.nil? - raise ArgumentError, "header #{name} was given as #{value.inspect}, and a header is always text: pass a String" if !value.is_a?(String) && !value.is_a?(Symbol) && !value.is_a?(Numeric) - - text = wire_text(value, "header #{name}") - raise ArgumentError, "header #{name} holds a line break, which a header cannot carry: #{LINE_BREAK_ADVICE}" if line_break?(text) - - stripped(text) - end - - # What to do about a line break in a header value, said wherever one is - # refused. - LINE_BREAK_ADVICE = 'the value is not quoted here, as it may be a credential. Read it without the line break - ' \ - 'a value read from a file usually ends in one, which is taken, but one inside it is not.' - - # Whether a header value holds a line break no header can carry. - # - # Net::HTTP strips the whitespace around a header value and refuses one - # with a line break left in it, with an ArgumentError that quotes the - # value: `http_token: "abc\ndef"` was taken when the client was built - # and raised at its first request, neither as a {ZammadAPI::Error} nor - # where the token was configured, with the token in the message. The - # +From+ scope and a raw request's headers went the same way. A line - # break at either end is stripped there, so a token read from a file - # with its newline still on works, and is still taken. - # - # Asked of the bytes. +strip+ raises for text that holds a byte sequence - # its encoding does not allow, and that error was read here as "no line - # break": `http_token: "abc\xFF\ndef"` was taken, and an adapter that - # does not check a header itself sent what follows the break as a header - # of its own. A line break is the same byte in every encoding ASCII is a - # part of, and binary text has no sequence that is not allowed. - # - # Asked of a String {.wire_text} has had, as {BLANK} is: the bytes of - # UTF-16 are not the bytes a request carries. - # - # @api private - # @param text [String] - # @return [Boolean] - def self.line_break?(text) = /[\r\n]/.match?(text.b.strip) - - # A header value without what Net::HTTP strips from around it. - # - # {.line_break?} takes a value that only ends in a line break, because - # Net::HTTP strips one before it writes the header. That is the default - # adapter and not the only one, and the value was handed on with the - # break still on it: to an adapter that writes a header as it stands, - # the break ends the line, and `\r\n\r\n` ends the headers. Stripped - # here, every adapter is handed the value Net::HTTP sent. - # - # Of the bytes, as {.line_break?} asks of them and for its reason. Text - # in an encoding ASCII is no part of is left as it is: its bytes are not - # the ones a request carries, see {.wire_text}. - # - # @api private - # @param text [String] - # @return [String] the text itself where there is nothing to strip - def self.stripped(text) - return text if !text.encoding.ascii_compatible? - - bare = text.b.strip - bare.bytesize == text.bytesize ? text : bare.force_encoding(text.encoding) - end - - # The +From+ scope as a transport holds it: text, and a copy of its own. - # - # Text, because a user id is a documented way to name the user and - # arrives as an Integer, which reached Net::HTTP intact and died there - # with `undefined method 'strip' for an instance of Integer`. - # - # A copy, because `String#to_s` hands back the receiver. The scoped - # client held the caller's own String, so a login buffer that was reused - # after `client.on_behalf_of(login)` changed who every later request from - # that client was performed for - the one thing a scope exists to pin. - # Copied rather than interned, for the reason {Config} copies what it is - # given: nothing a caller passed in should outlive what holds it. - # - # Public for the same reason as {.stringify_query}: {Test} carries the - # scope the way this class does, so that what it records is what the - # header would have carried. - # - # An identifier that names nobody is refused here, the one place every - # way to a +From+ header goes through, rather than only by - # {Client#on_behalf_of}. Zammad skips a header with nothing in it, so a - # transport scoped to one sent every request as the account it - # authenticates as. Nothing in it is what Rails calls blank, which - # counts Unicode spaces as well as ASCII ones: Zammad asks - # `request_header_from.blank?`. - # - # So is one that is neither text nor an Integer. Every object has a - # `to_s`, and `client.on_behalf_of(user)`, with the record where its - # login belongs, built a client whose From header read - # `#`. The types are the ones a - # record id is written as: see {RECORD_ID_TYPES}. - # - # @api private - # @param identifier [String, Integer, nil] login, email or user id - # @return [String, nil] frozen, or nil for no scope - # @raise [ArgumentError] for an identifier that is neither text nor an - # Integer, or has nothing in it - def self.stringify_on_behalf_of(identifier) - return nil if identifier.nil? - raise ArgumentError, not_an_identifier_message(identifier) if RECORD_ID_TYPES.none? { identifier.is_a?(it) } - - text = stripped(wire_text(identifier, 'on_behalf_of')) - raise ArgumentError, blank_on_behalf_of_message(identifier) if BLANK.match?(text) - raise ArgumentError, "on_behalf_of holds a line break, which the From header cannot carry: #{LINE_BREAK_ADVICE}" if line_break?(text) - - text.dup.freeze - end - - # What Rails calls blank, for a String: nothing but whitespace, Unicode - # spaces included. +strip+ removes the ASCII ones only, so a no-break - # space passed a check built on it and was then read as nothing. - # - # Asked of a String {.wire_text} has had: the pattern is US-ASCII, and - # matching it against text in an encoding ASCII is no part of raises - # Encoding::CompatibilityError. - BLANK = /\A[[:space:]]*\z/ - - # The encodings a value goes on the wire in as it stands: UTF-8, which is - # what Zammad reads, US-ASCII, which is the same bytes, and binary, which - # names no characters to convert. - WIRE_ENCODINGS = [Encoding::UTF_8, Encoding::US_ASCII, Encoding::BINARY].freeze - private_constant :WIRE_ENCODINGS - - # A value as text a request can carry: in UTF-8 where it was given in - # another encoding. - # - # A String in an encoding ASCII is no part of, such as UTF-16, cannot be - # joined to the ASCII around it. Faraday's escaping of a query value and - # Net::HTTP's writing of a header both raised - # Encoding::CompatibilityError for one, as did {BLANK} asked of a +From+ - # scope or a search keyword: neither a {ZammadAPI::Error} nor the - # ArgumentError a malformed value is refused with, and for a non-blank - # value, one that had nothing wrong with it but its encoding. Converted, - # it is the same text, in the encoding Zammad reads. - # - # One in an encoding ASCII is a part of can be joined, and was sent as - # the bytes it was held in. `search('Größe')` with the term read from a - # file in ISO-8859-1 or Windows-1252 went out as `query=Gr%F6%DFe`, - # which is no UTF-8, and Rails answers a query it cannot read as UTF-8 - # with a 400: a ClientError for a term with nothing wrong with it, while - # the same String in a JSON body was converted by the generator and - # arrived as the text it is. Converted here as well. - # - # A binary String is left as it was. It names no characters, so there - # is nothing to convert it from, and its bytes are what went on the - # wire. - # - # @api private - # @param value [Object] - # @param name [String] what the value is, for the error message - # @return [String] - # @raise [ArgumentError] for text that cannot be converted to UTF-8 - def self.wire_text(value, name) - text = value.to_s - return text if WIRE_ENCODINGS.include?(text.encoding) - - begin - text.encode(Encoding::UTF_8) - rescue EncodingError - raise ArgumentError, "#{name} was given as #{text.encoding} text that cannot be converted to UTF-8, which is what " \ - 'a request carries: it holds a byte sequence that is not valid in its own encoding.' - end - end - - # Names the class and does not quote the identifier, which for a record - # is every attribute it carries. + # A blank identifier is refused: Zammad reads an empty +From+ header as + # none, so every request would quietly run as the authenticated account. # - # @api private - # @return [String] - def self.not_an_identifier_message(identifier) - "on_behalf_of needs the login, email address or id of a user, as a String or an Integer, and was given #{identifier.class}: " \ - 'the From header would carry that object as it prints, which names no user. To act for a user you hold a record of, pass its id.' - end + # @param identifier [String, Integer] login, email address or user id + # @return [String] frozen + # @raise [ArgumentError] for an identifier that is nil or blank + def self.on_behalf_of_header(identifier) + text = identifier.to_s.strip + raise ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{identifier.inspect}" if text.empty? - # @api private - # @return [String] - def self.blank_on_behalf_of_message(identifier) - "on_behalf_of needs the login, email address or id of a user, and was given #{identifier.inspect}. " \ - 'Zammad reads a From header with nothing in it as no header at all, so every request would be performed ' \ - 'as the account this client authenticates as, with nothing to say the scope was missing.' + text.freeze end - # Percent-encodes one segment of a request path. - # - # Record ids are pasted into the path, and an id taken straight from a - # request parameter used to be pasted in whole: `find("1/../../api/v1/ - # users/1")` resolved to the users endpoint, so the parameter, not the - # call, chose which records the verb applied to. Encoding everything - # outside the unreserved set keeps a separator inside the segment it was - # written in, and a caller that really means a sub-path can spell it out - # with the raw request methods. - # - # A dot segment is refused rather than encoded. `.` and `..` are unreserved - # all the way through, so the encoding below returns them exactly as they - # arrived and `find('..')` still resolved one path level up - onto the - # index endpoint, and through a has_many path onto every article on the - # instance offered as one ticket's. Percent-encoding the dots would hold - # them inside the segment here, but a proxy that normalises a path before - # routing it would undo that, and no Zammad record is named for one. - # - # Anything that is not an id is refused rather than printed. `to_s` - # answers for every object, so a record where its id belongs was pasted - # in as it inspects: `exists?(ticket)` asked for - # `tickets/%23%3CZammadAPI%3A%3AResources%3A%3ATicket...%3E`, was told - # 404 about a path that names nothing, and answered false for a ticket - # that exists, while `destroy(ticket)` raised NotFoundError for one that - # was right there. The message names the class and does not quote the - # value, which for a record is every attribute it carries. - # - # The bytes that are encoded are those of the id in UTF-8: see - # {.wire_text}. An id given in ISO-8859-1 was written as the bytes of - # that encoding, which name another record or none, and one given in - # UTF-16 raised Encoding::CompatibilityError from the pattern below. - # - # Public for the same reason as {.stringify_query}: {Test} builds the - # paths it records with it. + # A record id as a path segment, percent-encoded. # - # @api private - # @param value [Integer, String, Symbol, nil] + # @param value [Integer, String] # @return [String] - # @raise [ArgumentError] when there is nothing to send, when the value - # is not an id at all, when it is text that cannot be converted to - # UTF-8, or when the id navigates instead of naming a record + # @raise [ArgumentError] for an id that is nil or empty def self.escape_path_segment(value) - raise ArgumentError, not_a_record_id_message(value) if !value.nil? && RECORD_ID_TYPES.none? { value.is_a?(it) } - - segment = wire_text(value, 'a record id') - raise ArgumentError, 'a record id is required, and this one is empty' if segment.empty? - raise ArgumentError, "#{segment.inspect} points at another endpoint rather than naming a record" if DOT_SEGMENTS.include?(segment) + segment = value.to_s + raise ArgumentError, 'a record id is required' if segment.empty? - segment.gsub(UNRESERVED_IN_PATH) { |character| character.bytes.map { format('%%%02X', it) }.join } + URI.encode_uri_component(segment) end - # @api private - # @return [String] - def self.not_a_record_id_message(value) - "a record id is an Integer or a String, and this one is #{value.class}: it would go into the request path as " \ - 'that object prints, which names no record. To address a record you hold, pass its id.' - end - - # Strips the leading slashes from a path so that it resolves against the - # instance URL rather than against the host. - # - # {Config#url} always ends in a slash and every request path is appended - # relative to it, so a leading slash would drop the sub-path of a Zammad - # served from one - `https://host/zammad/` + `/api/v1/tickets` resolves to - # `https://host/api/v1/tickets`. + # A request path relative to the instance URL. A leading slash is + # dropped, so paths can be pasted from the Zammad documentation. # - # A path that names a host of its own is refused. Faraday lets an absolute - # URL replace the instance URL and still attaches this client's headers, - # so `client.get('https://other.example/collect')` - a link lifted from a - # response body, say - sent the access token and the on_behalf_of scope - # to that host. Record ids are held inside their segment by - # {.escape_path_segment}; this is the same escape, one level up. The - # message does not quote the path, which may carry a secret of its own. - # What counts as absolute is {ABSOLUTE_URL}: a path that opens with a - # scheme, with or without a host after it. - # - # Public for the same reason as {.stringify_query} and - # {.escape_path_segment}: {Client} and {Test} both apply this rule, the - # latter to decide which stub a request matches, and a path rule kept in - # three places is one that gets changed in one of them - at which point - # the stand-in quietly stops matching what the client sends. - # - # A path that cannot be read as a URL is refused here as well, which is - # where it stops being Faraday's to refuse. Faraday reads the path with - # URI when the request is built, and URI raises an error of its own for - # one it cannot read: `client.get('api/v1/tägs')` and - # `client.get(' api/v1/x')` left as URI::InvalidURIError, which is - # neither a {ZammadAPI::Error} nor the ArgumentError a raw request - # documents for a path, so no rescue a caller was told to write caught - # it. And it was raised after the request had been logged, leaving a line - # for a request that never left - what {#perform} stringifies the query - # and the headers first to prevent. - # - # A path that climbs out of the instance URL is refused for the reason an - # absolute one is: see {.refuse_parent_segment!}. - # - # @api private - # @param path [Object] + # @param path [String] # @return [String] - # @raise [ArgumentError] for an absolute URL, a path that cannot be read - # as a URL, or one with a `..` segment + # @raise [ArgumentError] for an absolute URL, which would carry this + # client's credentials to another host def self.relative_path(path) relative = path.to_s.sub(%r{\A/+}, '') if ABSOLUTE_URL.match?(relative) - raise ArgumentError, 'a request path is relative to the instance URL, and this one opens with a scheme, which makes it an ' \ - "absolute URL: sending it would hand this client's credentials to another host. Pass the path alone, " \ - "such as 'api/v1/tickets'." + raise ArgumentError, "a request path is relative to the instance URL, and this one is an absolute URL: pass the path alone, such as 'api/v1/tickets'" end - refuse_unreadable_path!(relative) - refuse_parent_segment!(relative) relative end - # Refuses a request path with a `..` segment in it. - # - # A path is joined to the instance URL the way a link is resolved, and - # `..` climbs. For a Zammad served from a sub-path that leaves it: - # against `https://host/zammad/`, `client.get('../billing/export')` was - # sent to `https://host/billing/export`, another application on the same - # host, with this client's Authorization header and its on_behalf_of - # scope. A path put together from a value that was not checked - a - # filename, a link out of a response body - is how one gets there. An - # absolute URL is refused so that the credentials stay with the instance - # they were configured for, and this is the same door. - # - # Whatever the instance URL is, since no endpoint is reached by climbing. - # The dots are read percent-encoded as well: a client sends `%2e%2e` as - # it stands, and what receives it reads it as the dots. A `..` in a query - # string or after a `#` is no part of the path, and is left alone. + # A path as it may be logged or named in an error: without a query string + # or fragment, which may carry a token. # - # A segment is what stands between two slashes that were written as - # slashes. A record id is escaped into one by {.escape_path_segment}, - # slashes and all, so `find('1/../x')` asks for the one segment - # `1%2F..%2Fx` and is not what this refuses. - # - # The message does not quote the path, for the reason {.relative_path} - # gives. - # - # @api private - # @param relative [String] a path that reads as a URL - # @return [void] - # @raise [ArgumentError] - def self.refuse_parent_segment!(relative) - return if !PARENT_SEGMENT.match?(relative[/\A[^?#]*/].to_s) - - raise ArgumentError, "a request path names an endpoint below the instance URL, and this one holds a '..' segment, which climbs " \ - "out of it: for a Zammad served from a sub-path, sending it would hand this client's credentials to " \ - "whatever else that host serves. Pass the path of the endpoint itself, such as 'api/v1/tickets'." - end - - # Reads a path the two ways Faraday will: the whole of it as a URL, and - # a query string written into it as parameters. - # - # The second can fail where the first does not. `?a=1&a[b]=2` names one - # parameter as a value and as a structure, and decoding it raised - # TypeError from inside the connection. - # - # Neither message quotes the path, for the reason the one above does - # not, and neither passes on the error underneath, which does quote it: - # not its message, and not the error itself as the cause, which Ruby - # attaches to an error raised in a rescue and prints with it, so an - # exception tracker recorded the path, credentials and all. - # - # @api private - # @param relative [String] - # @return [void] - # @raise [ArgumentError] - def self.refuse_unreadable_path!(relative) - begin - URI.parse(relative) - rescue URI::InvalidURIError - raise ArgumentError, unreadable_path_message(relative), cause: nil - end - - begin - QueryEncoder.decode(relative.partition('#').first.partition('?').last) - rescue TypeError, Faraday::Error - raise ArgumentError, 'the query string written into this request path cannot be read as parameters: it names one of them ' \ - 'both as a value and as a structure, or nests them deeper than a query string is read. ' \ - 'Pass the parameters as query: instead, which takes them as a Hash.', cause: nil - end - end - - # @api private - # @return [String] - def self.unreadable_path_message(relative) - found = relative.ascii_only? ? 'a space, or another character a URL does not allow, or a % that begins no escape' : 'a character outside ASCII' - - "a request path is written the way a URL is, and this one cannot be read as one: it holds #{found}. " \ - 'Percent-encode what a URL cannot hold as it is - a space is %20, and ä is %C3%A4 - ' \ - 'or pass a parameter as query:, which encodes its value.' - end - - # A request path as it may be printed: with the credentials of a query - # string written into it blanked. - # - # A raw request may carry its query in the path - - # `client.get('api/v1/users/password_reset_verify?token=...')` is how the - # Zammad documentation spells that endpoint - and the path is printed in - # three places: the two log lines for a request, the message of a - # timeout, and the operation a raw request is named by in every error it - # raises. The `query:` Hash is redacted by key before it is logged, and - # the same parameter written into the path went out in full in all - # three. - # - # Redacted by name, as the Hash is, and written back as it was given - # otherwise. A name that cannot be decoded cannot be read, so its value - # is blanked rather than assumed to be harmless. - # - # A fragment is blanked whole. What follows a +#+ is no part of the - # request, and Faraday leaves it out of what it sends, but it was - # printed with the path: `api/v1/x#token=...` has no +?+ to be read as a - # query from, and came back as it stood, and after a query the fragment - # was printed as the tail of the last value. Blanked and not dropped, so - # that what is printed still says the path was written with one. - # - # Public for {Client}, which names a raw request by its path. - # - # @api private - # @param path [Object] + # @param path [String] # @return [String] - def self.redact_path(path) - sent, hash, = path.to_s.partition('#') - base, mark, query = sent.partition('?') - printed = mark.empty? ? base : "#{base}?#{query.split('&', -1).map { redact_query_pair(it) }.join('&')}" - - hash.empty? ? printed : "#{printed}##{REDACTED}" - end + def self.redact_path(path) = path.to_s.sub(/[?#].*/m, '') - # One stretch of a query string between two +&+, as it may be printed. + # Replaces the values of sensitive keys, at any depth, for the log. # - # Usually that is one parameter. Rack 2 ends a parameter at a +;+ as - # well, though, and Zammad ran on it up to 7.0: there - # `?page=2;token=...` carries a token, and read as one parameter it was - # the tail of a value named +page+ and printed. Rack 3, and Zammad - # since 7.1, reads the +;+ as part of the value. - # - # Both readings are covered, since nothing here knows which server is - # asked. A credential the stretch opens with is blanked to its end, the - # +;+ and what follows included, which is the whole of its value as - # Rack 3 reads it. Any other is followed past each +;+, and a parameter - # named like a credential there is blanked as far as the next one, - # which is where Rack 2 ends it. - # - # @api private - # @return [String] - def self.redact_query_pair(pair) - return blank_query_value(pair) if credential_parameter?(pair) - - first, separator, later = pair.partition(';') - return pair if separator.empty? - - "#{first};#{later.split(';', -1).map { credential_parameter?(it) ? blank_query_value(it) : it }.join(';')}" - end - - # Whether +name=value+ is named like a credential. A name that cannot - # be decoded cannot be read, and counts as one. - # - # @api private - # @return [Boolean] - def self.credential_parameter?(parameter) - name, mark, = parameter.partition('=') - return false if mark.empty? - - decoded = begin - URI.decode_www_form_component(name) - rescue ArgumentError - nil - end - - decoded.nil? || SENSITIVE_KEY_PATTERN.match?(decoded) - end - - # @api private - # @return [String] - def self.blank_query_value(parameter) = "#{parameter.partition('=').first}=#{REDACTED}" - - # A structure as it may be printed: with the value under every key that - # names a credential blanked, at any depth. See {SENSITIVE_KEY_PATTERN} - # for which keys those are. - # - # Public for {Resources::Base#inspect}. This was the log's own rule, and - # a record printed the same attributes with nothing applied to them. - # - # @api private # @param value [Object] - # @return [Object] a copy where anything was blanked, or holds a Hash or - # an Array + # @return [Object] def self.redact(value) case value when Hash then value.to_h { |key, nested| [key, SENSITIVE_KEY_PATTERN.match?(key.to_s) ? REDACTED : redact(nested)] } @@ -1113,942 +154,157 @@ def self.redact(value) end end - # The bytes a request body goes out as. + # A request body as JSON. A String is sent as it is. # - # Encoded here rather than left to Faraday's JSON middleware, because a - # body that cannot be encoded raised JSON::GeneratorError from inside the - # stack and nothing mapped it: `client.post(path, body: {data: - # File.binread('a.png')})` with the bytes not Base64-encoded, or any body - # holding a Float::NAN, went past the +rescue ZammadAPI::Error+ every - # caller is told to write, and a record whose +save+ carried the same - # value took the same way out. It is also encoded before the request is - # logged, for the reason the query and the headers are stringified - # first: a refused body leaves no line claiming a request that was never - # made. - # - # A String is passed through, as the middleware passes it: it is the - # caller saying the body is already encoded. - # - # The error says nothing the generator said, and has no cause. The - # generator quotes what it could not write: a value with invalid bytes - # as `Invalid object: "hunter2\xFF"` in the detailed message, which a - # backtrace prints for a cause too, and a Hash with one key twice whole, - # so a body with a password in it put the password into the log of - # whoever rescued the error. Only what {.json_value} refused itself is - # quoted, and that names a key and a class. - # - # Public for the same reason as {.stringify_query}: {Test} refuses what - # the wire would refuse. - # - # @api private - # @param body [Object] - # @param operation [String] description used in the error message + # @param body [Hash, Array, String, nil] + # @param operation [String] used in the error message # @param resource_class [Class, nil] used in the error message - # @return [String, nil] nil for a request without a body + # @return [String, nil] # @raise [Error] when the body cannot be encoded as JSON - # @raise [ArgumentError] for a Hash in it that names one key twice def self.encode_body(body, operation:, resource_class: nil) return body if body.nil? || body.is_a?(String) - JSON.generate(json_value(body, nil)) - rescue RefusedValue, JSON::JSONError => e - detail = " (#{e.message})" if e.is_a?(RefusedValue) - raise Error, "Can't #{Error.subject_for(operation, resource_class)}: the request body cannot be encoded as JSON#{detail}. " \ - 'Every value has to be a JSON type, and text has to be valid UTF-8: Base64-encode binary data such as an ' \ - 'attachment, and leave out a Float that is NaN or infinite.', cause: nil - end - - # A body as the generator may be handed it: every value in it one JSON - # has a type for, or an object that says what it is written as. - # - # The generator writes whatever is neither as the object's `to_s`, and - # every object has one. `client.users.create(login: 'x', role_ids: - # Set[1, 2])` sent `"role_ids":"Set[1, 2]"`, a String where the list - # belongs, and a Struct went as `#`. Nothing raised, and - # what Zammad made of the text was the answer. It is what - # {.stringify_query_value} refuses in a query, one request part over. - # - # A Float that is not finite is refused here as well, by its key. The - # generator refuses it too, and names no key. - # - # @api private - # @param value [Object] - # @param key [Object, nil] the key the value sits under, for the error - # message - # @return [Object] - # @raise [RefusedValue] for a value JSON has no type for, which - # {.encode_body} words like any other body that cannot be encoded - # @raise [ArgumentError] for a Hash that names one key twice - def self.json_value(value, key) - case value - when Float then value.finite? ? value : raise(RefusedValue, not_a_json_value_message(value, key)) - when String then json_text(value) - when *JSON_VALUE_TYPES then value - when Hash then json_hash(value, key) - when Array then value.map { json_value(it, key) } - else json_object(value, key) - end - end - - # Text as the generator takes it: a String tagged as binary whose bytes - # are UTF-8 text, as the UTF-8 text it is. - # - # Text that was read with `File.binread`, off a socket, or handed over - # by a mail library arrives tagged that way, and the generator goes by - # the tag: json 3 refuses a binary String with a byte outside ASCII, - # where json 2 wrote one that was valid UTF-8 with a warning. So - # `tickets.create(title: 'Größe'.b)` was sent or raised the advice to - # Base64-encode an attachment, by which version of the generator a - # bundle had resolved to, and a query took the same String either way. - # - # Only bytes that are text. Any other are binary data, and are left for - # the generator to refuse, which is what that advice is for. - # - # @api private - # @param text [String] - # @return [String] +text+, or a copy of it tagged as UTF-8 - def self.json_text(text) - return text if text.encoding != Encoding::BINARY || text.ascii_only? - - tagged = text.dup.force_encoding(Encoding::UTF_8) - tagged.valid_encoding? ? tagged : text - end - - # A Hash with every key as the text the generator writes it as, which - # is its `to_s`, and two keys that are written alike refused. - # - # `{login: 'a', 'login' => 'b'}` is one key twice in JSON. json 3 raises - # for it and quotes the whole Hash, and json 2 wrote both and left the - # choice to the reader, which for Rails is the last. It is refused by - # name, as a query and a record's attributes refuse it: see - # {DuplicateKeys}. - # - # @api private - # @param hash [Hash] - # @param key [Object, nil] the key the Hash sits under - # @return [Hash{String => Object}] - # @raise [ArgumentError] - def self.json_hash(hash, key) - DuplicateKeys - .normalize(hash, prefix: key, noun: 'body key', &:to_s) - .to_h { |name, nested| [name, json_value(nested, name)] } - end - - # What is none of the above, as what the object itself says it is, in - # the order the object is asked. - # - # What converts to a Hash is that Hash, as it is for a record's - # attributes: see {DeepCopy.frozen_object}. The generator has no - # spelling for `ActionController::Parameters` either, so `client.post(path, - # body: permitted)` sent its `to_s` in place of an object, password - # included, and a body holding one sent it under the key. - # - # An object with a `to_json` of its own is left to the generator, which - # calls it: a record of this gem, or a value object written to be sent. - # - # An object with an `as_json` is what that returns, and what it holds is - # walked in turn. ActiveSupport gives every object one and builds its - # `to_json` on it, which is what 1.x sent a body with. `JSON.generate` - # does not ask it, so in a Rails app `role_ids: Set[1, 2]` was the list - # under 1.x and the String above here, `ttl: 2.days` was `"172800"`, and - # a model went as `#`. - # - # A Time and a Date are left to print: see {TEXT_VALUE_TYPES}. - # - # @api private - # @return [Object] - # @raise [RefusedValue] - def self.json_object(value, key) - converted = Hash.try_convert(value) - return json_value(converted, key) if converted - return value if writes_own_json?(value) - - described = value.respond_to?(:as_json) ? value.as_json : value - case described - when *JSON_VALUE_TYPES, Hash, Array then json_value(described, key) - when *TEXT_VALUE_TYPES then described - else raise RefusedValue, not_a_json_value_message(value, key) - end - end - - # Whether an object has a `to_json` of its own, and not the one the - # generator gives every object - or ActiveSupport, around that one - - # which writes the object's `to_s`. - # - # Asked of where the method is defined, which is the same place for - # every object that has only the generic one, whichever of the two - # libraries put it there. And asked through Kernel, because a Struct or - # a Data may have a member called `method`. - # - # @api private - # @return [Boolean] - def self.writes_own_json?(value) - Kernel.instance_method(:method).bind_call(value, :to_json).owner != Object.instance_method(:to_json).owner + JSON.generate(body) + rescue JSON::GeneratorError => e + # Without the cause, whose report quotes the value that failed. + raise Error, "Can't #{Error.subject_for(operation, resource_class)}: the request body cannot be encoded as JSON (#{e.message})", cause: nil end - # Names the class and the key, and does not quote the value, as - # {.not_a_query_value_message} does not. - # - # @api private - # @return [String] - def self.not_a_json_value_message(value, key) - subject = key.nil? ? 'it' : "its key #{key}" - return "#{subject} was given as #{value}, which JSON has no number for" if value.is_a?(Float) - - "#{subject} was given as #{value.class}, which is no JSON type and would be sent as that " \ - 'object prints: pass a Set or a Range as its to_a, a number as an Integer or a Float, and any other object as ' \ - 'a Hash of what it holds' - end - - # What the retry middleware is built with. - # - # +max_interval+ is what bounds a wait. The retry middleware sleeps for - # whatever a +Retry-After+ header says, and its own ceiling defaults to - # no ceiling at all: a maintenance page answering 503 with - # +Retry-After: 3600+ held the calling thread for an hour per retry, - # whatever +timeout+ and +retry_interval+ said, before raising the error - # it could have raised at once. - # - # +timeout+ is the bound, because it is already how long this client - # was told it may wait for an answer. A +Retry-After+ within it is - # honoured; a longer one is not waited out, and the response it came - # with is reported as the error it is, with the figure still readable - # from {RateLimitError#retry_after}. - # - # It bounds the backoff and a +Retry-After+, and not the jitter: the - # middleware adds up to +interval_randomness+ of +interval+ once it has - # applied the ceiling. So a wait of its own is at most +timeout+ and - # half a +retry_interval+, which is a quarter of a second with the - # defaults and five on top of two for `timeout: 2, retry_interval: 10`. - # Lowering the ceiling by that much would refuse a +Retry-After+ that - # is within +timeout+, so the documentation says it instead. - # - # Public for {.retried?}, which {Test} asks. - # - # @api private # @param config [Config] - # @return [Hash{Symbol => Object}] - def self.retry_options(config) - { - max: config.retries, - interval: config.retry_interval, - max_interval: config.timeout, - interval_randomness: 0.5, - backoff_factor: 2, - retry_statuses: RETRIABLE_STATUSES, - methods: RETRIABLE_METHODS, - exceptions: RETRIABLE_EXCEPTIONS - } - end - - # Whether a response is a 2xx whose body stopped short of its - # Content-Length: the one {HeldToLength} raises for. - # - # @api private - # @param response [Response] - # @return [Boolean] - def self.cut_short?(response) = response.success? && !missing_bytes(response).nil? - - # Whether a request answered with +response+ is one the retry middleware - # sends again, while it has attempts left: one with a retriable status, - # or a 2xx that was cut short. - # - # Public for {Test}, for the reason {.stringify_query} is: a stand-in - # that raised for the first 503 a +GET+ was answered with, where the - # wire asks again, made a test of code that leans on the retry pass or - # fail the other way round from production. - # - # The wait is asked of the middleware itself, built from the options - # above, and not worked out a second time here. It answers nil where a - # +Retry-After+ - or a +RateLimit-Reset+, or either as a date - asks - # for longer than it may wait, which is the one response with a - # retriable status that it does not send again. A copy of that reading - # is the kind that gets changed in one place. - # - # @api private - # @param config [Config] - # @param method [Symbol] - # @param response [Response] - # @return [Boolean] - def self.retried?(config, method, response) - options = retry_options(config) - return false if !options[:methods].include?(method) - return false if !options[:retry_statuses].include?(response.status) && !cut_short?(response) - - !Faraday::Retry::Middleware.new(nil, options).calculate_sleep_amount(1, { response_headers: Faraday::Utils::Headers.new(response.headers) }).nil? - end - - # A Content-Length that can be compared: one figure, and nothing else. - # Two that were sent arrive joined by a comma, and say nothing certain. - CONTENT_LENGTH = /\A\d+\z/ - private_constant :CONTENT_LENGTH - - # A 2xx response, once its body is known to have arrived: see - # {.missing_bytes}. - # - # Raised with the response, as the one {ConnectionError} that has one: - # Zammad answered, so a write was applied, and {Resources::Base#save!} - # and {Resources::Base#destroy} have to hear that to settle the record. - # - # On the class and public for {Test}, like {.retried?}: the stand-in - # handed such a response back as whole, so code that handles a save cut - # short could not be exercised against it, and a fixture carrying a - # stale Content-Length passed there and failed on the wire. - # - # @api private - # @param response [Response] - # @param operation [String] - # @param config [Config] of the client that sent the request - # @return [Response] - # @raise [IncompleteResponseError] - def self.whole(response, operation:, config:) - missing = missing_bytes(response) - return response if missing.nil? - - raise IncompleteResponseError.new( - "Can't #{operation}: the response from #{config.redacted_url} ended #{missing} bytes short of the " \ - "#{response.headers['content-length']} its Content-Length announces, so the connection was closed " \ - 'before the body had arrived', - response: response - ) - end - - # How many bytes of its body a response stopped short by, where it did. - # - # A body framed by Content-Length ends where the count is reached, or - # where the connection does. Net::HTTP takes the second for the first - # without a word - its +ignore_eof+ is on by default - so a download - # the connection dropped under came back as the file: - # {Resources::TicketArticleAttachment#download} returned the first ten - # bytes of a thousand, and whatever wrote them to disk wrote a file that - # opens as a broken one. A chunked body cut short did raise, and a JSON - # one that no longer parses is refused where it is decoded, so this was - # the one response that came back wrong and looked right. - # - # Asked only where the bytes in hand are the bytes that were counted. A - # body under a Content-Encoding may have been decoded on the way here, - # by an adapter that leaves both headers as they arrived. The default - # one does: Net::HTTP drops the one and corrects the other while it - # reads the body, and Faraday has taken its copy of the headers by - # then. So a compressed body cut short is not caught here, and - # {Resources::TicketArticleAttachment#download} asks for its file - # uncompressed. A body under a Transfer-Encoding is not framed by the - # count at all, and a 204 has no body whatever a header beside it says. - # - # Only a body that is short. One that is longer was not cut off. - # - # @api private - # @param response [Response] - # @return [Integer, nil] nil for a response that is whole, or that - # cannot be told - def self.missing_bytes(response) = short_by(response.status, response.headers, response.raw_body) - - # {.missing_bytes}, asked of the parts of a response, for - # {HeldToLength}, which holds a Faraday one. - # - # The headers are a {Response}'s or Faraday's own, which both answer to - # a lower-case name. Faraday keeps a value as whatever wrote it, an - # Integer for the length faraday-gzip sets, so the figure is read as - # text. - # - # @api private - # @param status [Integer] - # @param headers [Hash, Faraday::Utils::Headers] - # @param body [String] - # @return [Integer, nil] - def self.short_by(status, headers, body) - announced = headers['content-length'].to_s - return nil if !CONTENT_LENGTH.match?(announced) - return nil if status == 204 || headers.key?('content-encoding') || headers.key?('transfer-encoding') - - missing = announced.to_i - body.bytesize - missing.positive? ? missing : nil - end - - # What {#inspect} says of a transport or of a client, for a JSON - # encoder. Public for {Client#as_json}, whose transport may be another - # kind than this one. - # - # @api private - # @param config [Config] - # @param on_behalf_of [String, nil] - # @return [Hash{Symbol => Object}] - def self.description(config, on_behalf_of) - { url: config.redacted_url, auth: config.authentication_scheme, on_behalf_of: on_behalf_of }.compact - end - - # @param config [Config] - def initialize(config) + # @param on_behalf_of [String, nil] see {.on_behalf_of_header} + # @raise [ConfigurationError] when the connection cannot be built + def initialize(config, on_behalf_of: nil) @config = config - @on_behalf_of = nil + @on_behalf_of = on_behalf_of @connection = build_connection end - # Returns a copy of this transport that sends the +From+ header. - # - # The scope is stringified here rather than at the point the header is - # set, so that {Test} records the value the wire would carry: an Integer - # used to die inside Net::HTTP while the test kit accepted it happily. - # See {.stringify_on_behalf_of} for what is held. - # - # @param identifier [String, Integer, nil] login, email or user id - # @return [Transport] + # @param identifier [String, nil] see {.on_behalf_of_header} + # @return [Transport] a copy that performs requests for that user def with_on_behalf_of(identifier) copy = dup - copy.instance_variable_set(:@on_behalf_of, Transport.stringify_on_behalf_of(identifier)) + copy.instance_variable_set(:@on_behalf_of, identifier) copy end - # Returns a transport of this kind configured with +config+, keeping any - # {#with_on_behalf_of} scope. - # - # {Client#with} goes through here rather than building a Transport itself, - # so that a client whose transport was replaced - the test kit's stand-in, - # say - derives another of the same kind instead of silently reverting to - # a real HTTP one. - # # @param config [Config] - # @return [Transport] - def with_config(config) = self.class.new(config).with_on_behalf_of(on_behalf_of) + # @return [Transport] a new transport for +config+, for the same user + def with_config(config) = self.class.new(config, on_behalf_of: on_behalf_of) - # Says where this transport points and how it authenticates, and nothing - # else. - # - # Left to Ruby, this printed the instance variables, and one of them is - # the Faraday connection: its proxy options carry the proxy password and - # its middleware stack carries the arguments it was built with, the - # access token among them. Every record holds its transport, so that was - # one +inspect+ away from any of them. Defining this covers +pp+ as well, - # which uses an +inspect+ a class defines for itself. - # - # @return [String] def inspect - "#<#{self.class.name} url=#{config.redacted_url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{on_behalf_of.inspect}" if on_behalf_of}>" + "#<#{self.class.name} url=#{config.url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{on_behalf_of.inspect}" if on_behalf_of}>" end - # The transport for a JSON encoder: what {#inspect} says, and nothing - # else. - # - # ActiveSupport serializes an object as its instance variables, and - # here one of them is the Faraday connection, for which {#inspect} has - # said why it is not printed. Every record holds its transport. - # - # @return [Hash{Symbol => Object}] - def as_json(*) = Transport.description(config, on_behalf_of) - - # @param state [JSON::State, nil] passed by +JSON.generate+ - # @return [String] {#as_json} as a JSON object - def to_json(state = nil) = as_json.to_json(state) - - # What Psych writes for a transport: {#as_json}, as a plain mapping. - # - # Psych writes an object as its instance variables, as ActiveSupport - # does for JSON, and the connection among them holds the token in its - # middleware stack and the proxy password in its options. Every record - # holds its transport, so +record.to_yaml+ wrote both. - # - # @api private - # @param coder [Psych::Coder] - # @return [void] - # @see Config#encode_with - def encode_with(coder) = coder.represent_object(nil, JSON.parse(to_json)) - # Performs a request and raises on anything but a 2xx response. # # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ # @param path [String] path relative to {Config#url} # @param operation [String] description used in error messages # @param query [Hash, nil] query string parameters - # @param body [Hash, nil] request payload, encoded as JSON - # @param headers [Hash, nil] request headers, beyond the ones this class - # sets from the configuration + # @param body [Hash, Array, String, nil] request payload, encoded as JSON + # @param headers [Hash, nil] request headers # @param resource_class [Class, nil] used in error messages # @return [Response] # @raise [ResponseError] for non-2xx responses # @raise [TimeoutError] when the request timed out # @raise [ConnectionError] when the instance was unreachable - # @raise [IncompleteResponseError] when the connection was closed before - # the body of a 2xx response had arrived - # # @raise [Error] when the body cannot be encoded as JSON - # - # Every failure leaves here as a {ZammadAPI::Error}. The bare socket - # errors are caught alongside the Faraday ones because they are already - # in {RETRIABLE_EXCEPTIONS}, which is this class saying it expects to see - # them: an adapter that does not wrap them used to let them out raw once - # the retries were spent, past every rescue a caller had written. def request(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) - # Here as well as in {Client}, because this is the one door every - # request goes through, whichever caller built the path. - path = Transport.relative_path(path) - payload = Transport.encode_body(body, operation: operation, resource_class: resource_class) + path = Transport.relative_path(path) + payload = Transport.encode_body(body, operation: operation, resource_class: resource_class) + log_request(method, path, query, body, headers) + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) response = decode(perform(method, path, query, payload, headers)) log_response(method, path, response, started) - - # A response cut short has been through the retries a read is due by - # now: see {HeldToLength}, and {#perform} for how it gets here. - return Transport.whole(response, operation: operation, config: config) if response.success? + return response if response.success? raise ResponseError.build(response, operation: operation, resource_class: resource_class) rescue Faraday::TimeoutError, *TIMEOUT_ERRORS => e raise TimeoutError, "Can't #{operation}: request to #{Transport.redact_path(path)} timed out (#{e.message})" rescue Faraday::SSLError, *SSL_ERRORS => e - raise ConnectionError, "Can't #{operation}: TLS handshake with #{config.redacted_url} failed (#{e.message})" + raise ConnectionError, "Can't #{operation}: TLS handshake with #{config.url} failed (#{e.message})" rescue Faraday::ConnectionFailed, *CONNECTION_ERRORS => e - # Before it is called unreachable, because one kind of connection - # failure is a timeout. See #timed_out?. - raise TimeoutError, "Can't #{operation}: connecting to #{config.redacted_url} timed out (#{e.message})" if timed_out?(e) + raise TimeoutError, "Can't #{operation}: connecting to #{config.url} timed out (#{e.message})" if timed_out?(e) - raise ConnectionError, "Can't #{operation}: #{config.redacted_url} is unreachable (#{e.message})" + raise ConnectionError, "Can't #{operation}: #{config.url} is unreachable (#{e.message})" end private - # Whether a connection failure is a timeout underneath. - # - # An exceeded +open_timeout+ is raised by Net::HTTP as Net::OpenTimeout, - # and the default adapter wraps that into Faraday::ConnectionFailed along - # with every other failure to connect. So it was reported as "is - # unreachable (execution expired)", a ConnectionError, and skipped the - # +rescue ZammadAPI::TimeoutError+ that is documented to catch an - # exceeded +open_timeout+. - # - # Both places an adapter can leave the original are looked at: Faraday's - # own +wrapped_exception+, and the +cause+ Ruby records for an error - # raised while another was being handled. + # Whether a connection failure is a timeout underneath: the default + # adapter wraps an exceeded +open_timeout+ into Faraday::ConnectionFailed. def timed_out?(error) wrapped = error.respond_to?(:wrapped_exception) ? error.wrapped_exception : nil [wrapped, error.cause].any? { |inner| TIMEOUT_ERRORS.any? { inner.is_a?(it) } } end - # +payload+ is the body as it is sent, and it is what the log reads as - # well: see {#loggable_body}. def perform(method, path, query, payload, headers) - # Built before the request is logged, so a rejected query or header does - # not leave a line claiming a request that was never made. - params = query && Transport.stringify_query(query) - fields = headers && Transport.stringify_headers(headers) - # The query as it is sent, like the headers and the body. The one the - # caller handed over was logged, redacted by key through its Hashes, - # and what it held that converts to a Hash and is sent as one - see - # {.stringify_query} - was printed by `inspect`, under whatever key - # it sat. - log_request(method, path, params, payload, fields) - @connection.public_send(method, path) do |request| - request.params.update(params) if params - # One at a time rather than in bulk, so that every name goes through - # Faraday's own case-insensitive writer and replaces the header it - # names rather than sitting beside it under another spelling. - fields&.each { |name, value| request.headers[name] = value } - request.body = payload if payload + request.params.update(query) if query + headers&.each { |name, value| request.headers[name.to_s] = value.to_s } request.headers['From'] = on_behalf_of if on_behalf_of + request.body = payload if payload end - rescue CutShort => e - # The response the connection raised for, once the retries a read is - # due are spent, and at once for a write. Handed on as the response it - # is, so that it is logged and decoded like any other, and - # {#request} raises for it with the status and the bytes that did - # arrive. - e.response end def build_connection - connection = Faraday.new( + Faraday.new( url: config.url, ssl: { verify: config.ssl_verify }, - # The encoder is this gem's own: see {QueryEncoder} for the one - # structure Faraday's writes so that Rails reads another. - request: { timeout: config.timeout, open_timeout: config.open_timeout, params_encoder: QueryEncoder }, - headers: { 'User-Agent' => Transport.stripped(config.user_agent), 'Accept' => 'application/json' }, - # Named, and as nil, so that it stands in for the parameters of - # `Faraday.default_connection_options`: see #drop_shared_headers. - params: nil, - **configured_proxy + proxy: config.proxy, + request: { timeout: config.timeout, open_timeout: config.open_timeout }, + headers: { 'User-Agent' => config.user_agent, 'Accept' => 'application/json' } ) do |faraday| - drop_shared_headers(faraday) apply_authentication(faraday) faraday.request :json - faraday.request :retry, Transport.retry_options(config) - faraday.use HeldToLength - # Last in the stack, so a caller's middleware sees the request as this - # gem finished building it and the response before anything else does. - apply_middleware_and_adapter(faraday) + faraday.request :retry, retry_options + faraday.adapter(config.adapter) if config.adapter + config.middleware&.call(faraday) end - - refuse_unusable_middleware!(connection) - connection - rescue ZammadAPI::Error - raise - rescue => e - # An unregistered adapter, a proxy that is not a URL, or a middleware - # that rejects its options is a configuration mistake, and neither - # Faraday nor URI is part of this gem's surface. - # - # Caught as StandardError rather than as Faraday::Error, because the - # failures that do not come from Faraday are the ones a caller is least - # equipped to place: `proxy: 'http://user:pa ss@host'` escaped as - # URI::InvalidURIError and a `middleware` callable that raises escaped - # as whatever it raised, both straight past the - # `rescue ZammadAPI::ConfigurationError` that building a client is - # documented to need. The class is named in the message because - # "bad URI (is not URI?)" on its own says nothing about where to look. - raise ConfigurationError, "config could not be used to build a connection: #{e.class}: #{redact_config_values(e.message)}", cause: reportable_cause(e) - end - - # The `proxy:` option, where one is configured, and no option where none - # is. - # - # What is named here stands in for what `Faraday.default_connection_options` - # holds under the same name, and a name given as nil does that as well as - # one given a value. `proxy: config.proxy` was passed whatever it was, so - # the proxy a process had set there for all of its Faraday connections - # was taken off this one: its requests went out directly, or nowhere - # where only the proxy reaches the instance, while the README said that a - # proxy set there applies and 1.x, which named no proxy, had used it. - # - # @return [Hash{Symbol => String}] - def configured_proxy = config.proxy ? { proxy: config.proxy } : {} - - # Runs the caller's `middleware:` callable, and then settles the adapter. - # - # The adapter used to be set after the callable, unconditionally, and - # setting one replaces the one that is there. So an adapter the callable - # chose was dropped without a word: `middleware: ->(f) { f.adapter - # :test, stubs }` left the connection on Net::HTTP, and a test that - # believed itself stubbed sent real requests with the real token. The - # callable is also the one place an adapter can be given arguments - - # `f.adapter :net_http_persistent, pool_size: 5` - since `adapter:` - # takes a name. - # - # An adapter the callable set is kept. Whether it set one is asked of - # the handler's identity: Faraday puts its default in before the block - # runs and builds a new handler for every `adapter` call, so one that - # names the default again, to hand it a block, is seen as well. - # - # Named in both places, it is refused. One of the two would be dropped, - # and which one is not something either spelling says. - def apply_middleware_and_adapter(faraday) - preset = faraday.builder.adapter - config.middleware&.call(faraday) - chosen = faraday.builder.adapter - - return faraday.adapter(config.adapter || Faraday.default_adapter) if chosen.equal?(preset) - return if config.adapter.nil? - - raise ConfigurationError, - "config adapter is #{config.adapter.inspect}, and the `middleware:` callable set an adapter as well (#{chosen.name}): " \ - 'a connection has one adapter. Drop the `adapter:` option to use the one the callable sets, with the arguments ' \ - 'it gives it, or drop the call from the callable.' - end - - # The error to keep as the cause of the ConfigurationError above, where - # it can be kept. - # - # Ruby attaches the error being rescued to the one raised in its place, - # and a report prints the whole chain: `full_message`, a logger's - # formatter, an error tracker. So the message above was scrubbed and the - # original went out right behind it, `caused by URI::InvalidURIError: bad - # URI (is not URI?): "http://user:pa ss@host:3128"`, password and all. - # - # Dropped only where that is what would happen. The whole report is - # asked, causes of its own included, because the whole report is what - # gets printed, and it is asked the question the message was: whether it - # quotes a configured value that redaction changes. Every other failure - # keeps its cause. A `middleware:` callable that raises is a bug in the - # caller's own code, and the backtrace into it is the one thing the - # message cannot carry. - # - # An error that cannot render its report is dropped as well. Rendering is - # the error's own code - `detailed_message` is there to be overridden, - # and one written without the `highlight:` keyword raises ArgumentError - # from inside `full_message` - and this runs in the rescue above, so what - # it raised left in place of the ConfigurationError, past the rescue - # building a client is documented to need. A report that cannot be read - # cannot be shown to quote nothing, which is the one condition a cause is - # kept on. - def reportable_cause(error) - report = error.full_message(highlight: false) - - redact_config_values(report) == report ? error : nil - rescue - nil + rescue Faraday::Error => e + raise ConfigurationError, "config could not be used to build a connection: #{e.message}" end - # The underlying error quotes the value it rejected, and for a proxy that - # value carries its credentials: `proxy: 'http://user:pa ss@host:3128'` - # came back as URI::InvalidURIError with the whole URL, password included, - # in its message - and that message goes into the ConfigurationError - # above, which lands in every log and exception report. The one case - # {Config#inspect} and {Config#redacted} exist to prevent, reached by - # another route. - # - # The configured values are swapped for their redacted forms rather than - # the message being dropped, because "bad URI (is not URI?)" without the - # URI says nothing about where to look. Substring replacement, because - # the message embeds the value verbatim, and the url as well as the proxy - # because {Config} can only refuse the credentials in a url it can read: - # one that is not a URL at all gets this far, and is quoted here. - # - # And the proxies the environment names, which no option holds, and the - # one a process set for all of its Faraday connections: see - # {#environment_proxies} and {#shared_proxies}. - def redact_config_values(message) - [config.proxy, config.url, *shared_proxies, *environment_proxies].compact.inject(message.to_s) do |text, value| - spellings = quoted_spellings(value) - # Of the value as it can be read. A configured one is its own first - # spelling, and redacting text with a broken byte in it raises. - redacted = config.redacted(spellings.first) - - # The block form. A String replacement expands the backslash - # sequences it contains, and the replacement here is the configured - # value with its userinfo blanked - so a value carrying `\0` or `\&` - # put the whole matched text back, credentials included, into the - # message it had just been taken out of, and one carrying `\1` cut - # the replacement short instead. - # - # Every spelling of the value, because the error being quoted may - # have inspected it rather than interpolated it: URI::InvalidURIError - # does, and inspect escapes exactly the backslashes, quotes and - # control characters that make a URL invalid in the first place. The - # escaped text no longer equals the value as configured, so the swap - # matched nothing and left the password standing in full - the case - # this method exists for, reached through the quoting rather than - # the value. - spellings.inject(text) { |scrubbed, spelling| scrubbed.gsub(spelling) { redacted } } - end - end - - # A variable of the environment that names a proxy, in either case: - # `https_proxy`, `HTTP_PROXY`, and `no_proxy` among them, which is a - # list of hosts and comes through the redaction as it went in. - ENVIRONMENT_PROXY = /_proxy\z/i - private_constant :ENVIRONMENT_PROXY - - # The proxy URLs the environment names, to be scrubbed from an error as - # the configured one is. - # - # With no `proxy:` given, Faraday takes the one `http_proxy` or - # `https_proxy` names, and it is URI that reads it: one it cannot parse - # was quoted whole in the ConfigurationError above and kept as its - # cause. `https_proxy='http://user:hunter 2@proxy.example:3128'`, a - # password with a space left unencoded, printed that password wherever - # the error was logged. The redaction knew the values of the - # configuration only, and this one is in none of them. - # - # Every such variable rather than the two Faraday is known to read: - # which of them URI consults depends on the scheme and on whether the - # process is a CGI, and a value that holds no credentials is not - # changed by being looked for. - # - # The name is asked as its bytes. The environment can hold a name that - # is not text in the encoding Ruby reads it in, and a pattern asked of - # one raises: with a variable called `caf\xE9_proxy` set, the - # ConfigurationError this is called for left as a bare `ArgumentError: - # invalid byte sequence in UTF-8`, past the rescue building a client is - # documented to need, and only where the configuration could not be - # used. Such a variable still names a proxy, so its value is scrubbed - # like any other. - # - # @return [Array] - def environment_proxies - ENV.filter_map { |name, value| value if name.b.match?(ENVIRONMENT_PROXY) && !value.empty? } - end - - # The proxy URL `Faraday.default_connection_options` names, to be - # scrubbed from an error as the configured one is. - # - # With no `proxy:` given, that one is this connection's: see - # {#configured_proxy}. So one URI cannot parse is quoted by the same - # error a configured one is, password included, and is a value of - # neither the configuration nor the environment. It is given there as - # the URL or as a Hash that holds it under `uri`, and one that is neither - # has been parsed already. - # - # @return [Array] - def shared_proxies - proxy = Faraday.default_connection_options.proxy - proxy = proxy[:uri] || proxy['uri'] if proxy.is_a?(Hash) - - proxy.is_a?(String) && !proxy.empty? ? [proxy] : [] - end - - # The value as an error may have quoted it: as it is, as +inspect+ - # writes it, and as +dump+ does. - # - # The last two part ways at the first character outside ASCII, which - # +inspect+ leaves standing and +dump+ writes as an escape, and URI - # rejects a URL holding one with the +dump+ spelling: "URI must be ascii - # only" and the value with every such character as `\u00E4`. A password - # with an umlaut in it therefore matched neither of the two spellings - # that were looked for, and stayed in the message - and in the cause, - # which is kept wherever redaction finds nothing to change. - # - # Only the spellings that can be looked for. A value with a byte that is - # not text in its encoding, which the environment can hold, raises from - # the search for it, and an error can only have quoted it escaped. - def quoted_spellings(value) = [value, value.inspect[1...-1], value.dump[1...-1]].compact.uniq.select(&:valid_encoding?) - - # Takes off the connection what `Faraday.default_connection_options` put - # on it that only this client's configuration is to say. - # - # `Faraday.new` starts every connection from those options, which a - # process sets once for all of its Faraday clients. An `Authorization` - # among their headers, there for another API, stood on this connection - # before the authorization middleware ran, and that middleware leaves a - # header it finds: the token of the other service was sent to Zammad and - # the configured one never, by a client whose `inspect` said - # `auth=http_token`. A `From` there was sent with every request, which - # Zammad reads as the user to act for, and their parameters went into - # the query of every request, beside the ones the request named and - # where no log line showed them. - # - # The two headers are the ones {RESERVED_HEADERS} refuses a raw request, - # for the same reason. The parameters are left out where the connection - # is built, with `params: nil`, and not cleared here: a query the - # configured url carries is on the connection as parameters by now, and - # is this client's own. - # - # Everything else those options hold is kept: other headers, TLS - # settings, a proxy. And this runs before the `middleware:` callable, so - # what that sets on the connection it was handed stands, as it did. - def drop_shared_headers(faraday) - RESERVED_HEADERS.each_key { faraday.headers.delete(it) } + def retry_options + { + max: config.retries, + interval: config.retry_interval, + max_interval: config.timeout, + interval_randomness: 0.5, + backoff_factor: 2, + retry_statuses: RETRIABLE_STATUSES, + methods: RETRIABLE_METHODS, + exceptions: RETRIABLE_EXCEPTIONS + } end - # A token as every adapter is to be handed it: see {Transport.stripped}. - # A user and password are sent Base64-encoded, whatever is around them. def apply_authentication(faraday) case config.authentication_scheme - when :http_token then faraday.request :authorization, 'Token', Transport.stripped(config.http_token.to_s) - when :oauth2_token then faraday.request :authorization, 'Bearer', Transport.stripped(config.oauth2_token.to_s) + when :http_token then faraday.request :authorization, 'Token', config.http_token + when :oauth2_token then faraday.request :authorization, 'Bearer', config.oauth2_token else faraday.request :authorization, :basic, config.user, config.password end end - # The header values as text, as well as the names. Faraday keeps a value - # as whatever wrote it: faraday-gzip sets Content-Length to the Integer - # length of what it inflated, and {.missing_bytes} asked a regexp of that, - # so every 2xx behind such a middleware raised a bare TypeError. def decode(faraday_response) - headers = faraday_response.headers.to_h.to_h { |name, value| [name.to_s.downcase, value.to_s] }.freeze - raw_body = raw_body!(faraday_response.body) - body, json = Response.decode_body(headers['content-type'], raw_body) + headers = faraday_response.headers.to_h.to_h { |name, value| [name.to_s.downcase, value.to_s] }.freeze + raw_body = faraday_response.body.to_s Response.new( status: faraday_response.status, headers: headers, - body: body, - raw_body: raw_body, - json: json + body: Response.decode_body(headers['content-type'], raw_body), + raw_body: raw_body ) end - # Middleware this gem cannot do its own work behind, each with what it - # takes away and how it is usually spelled. Matched by name so that naming - # one does not require it to be loaded, and looked for among the ancestors - # of what is in the stack: see {#refused_middleware}. - # - # The first reads the body before this gem can. The second raises for a - # 4xx or 5xx before this gem sees the response, and it sits below the - # retry middleware, which is where a caller's middleware goes: a GET - # answered 503 left as Faraday::ServerError without being retried, a 404 - # as Faraday::ResourceNotFound, so `exists?` raised for a record that is - # merely absent, and a 422 as an error `save` does not turn into false. - # None of them is a {ZammadAPI::Error}, which is what every failure is - # documented to leave as. - REFUSED_MIDDLEWARE = { - 'Faraday::Response::Json' => ['which decodes the response body before this gem can. This gem parses JSON itself, and hands ' \ - 'the undecoded bytes to attachment downloads, so it needs the body as it arrives', - 'c.response :json'].freeze, - 'Faraday::Response::RaiseError' => ['which raises a Faraday error for a 4xx or 5xx response before this gem sees it. This gem ' \ - 'raises its own error for each status, and retries a read that was answered 429 or 5xx, ' \ - 'and behind this middleware it does neither', - 'c.response :raise_error'].freeze - }.freeze - private_constant :REFUSED_MIDDLEWARE - - # Refuses a stack this gem cannot work behind, while the stack is still - # the only thing that has happened. - # - # `raw_body!` below catches a decoded body too, but only once a response - # is in hand - which is one request too late: `client.groups.create(...)` - # sent the POST, Zammad created the group, and only then did a - # ConfigurationError come back, so a caller retrying what looked like a - # configuration failure created a second one. The middleware is fully - # visible here, where the unregistered adapter and the unusable proxy are - # already refused before anything is sent. - def refuse_unusable_middleware!(connection) - connection.builder.handlers.each do |handler| - refused = refused_middleware(handler.klass) - raise ConfigurationError, refused_middleware_message(handler.klass, refused) if refused - end - end - - # Which refused middleware a class in the stack is, if it is one: itself, - # or the one it inherits from. - # - # Only the class's own name used to be asked, and a subclass has another. - # `class QuietRaiseError < Faraday::Response::RaiseError`, the usual way - # to adjust what that middleware raises, went through `c.use` unrefused, - # and its inherited handler then raised Faraday::ResourceNotFound for a - # 404 before this gem saw the response - everything the refusal is there - # to prevent, one `<` away from it. - # - # @return [String, nil] the name it is refused under - def refused_middleware(klass) = klass.ancestors.filter_map(&:name).find { REFUSED_MIDDLEWARE.key?(it) } - - # A subclass is named along with what it inherits from, because the - # reason describes the parent - and it is told to drop "it", because the - # line that added a subclass is not the one the parent is usually spelled - # with. - def refused_middleware_message(klass, refused) - reason, spelling = REFUSED_MIDDLEWARE.fetch(refused) - found, drop = klass.name == refused ? [refused, "`#{spelling}`"] : ["#{klass.name || 'an anonymous class'}, a subclass of #{refused}", 'it'] - - "the configured middleware includes #{found}, #{reason}: drop #{drop} from the `middleware:` callable." - end - - # The body as it came off the wire. - # - # `middleware:` is a documented seam and `c.response :json` is a - # reasonable thing to put through it, at which point Faraday hands over a - # Hash rather than the bytes. `to_s` turned that into a Ruby inspect - # string, which JSON.parse then refused, so every record built from the - # response died in {Response#decoded} with a ParseError naming Zammad for - # what the caller's own stack had done. - # - # A backstop rather than the first line of defence: the stack is checked - # when it is built, which catches `c.response :json` before a request goes - # out. This is what is left for a middleware that decodes without being one - # of the names that check knows. - # - # Said plainly instead. Re-encoding the parsed structure was the other - # way out, and it is worse than it looks: {Response#raw_body} is - # documented as the undecoded body and - # {Resources::TicketArticleAttachment#download} hands exactly those bytes - # back as the file, so a re-encoding silently returns something that is - # not what Zammad stored - and JSON.generate has its own failures, which - # would escape from here past the `rescue ZammadAPI::Error` every caller - # is told to write. Once the bytes are gone they cannot be recovered, so - # the honest answer is to name the cause while it is still visible. - def raw_body!(body) - return body.to_s if body.nil? || body.is_a?(String) - - raise ConfigurationError, - 'the configured middleware decoded the response body before this gem could ' \ - "(Faraday handed over #{body.class} rather than the raw body). This gem parses JSON itself, " \ - 'and hands the undecoded bytes to attachment downloads, so it needs the body as it arrived: ' \ - 'drop the parsing middleware - `c.response :json` is the usual one - from the `middleware:` callable.' - end - - def log_request(method, path, query, payload, headers) + def log_request(method, path, query, body, headers) logger.debug do "Zammad API request: #{method.to_s.upcase} #{Transport.redact_path(path)}#{" query=#{Transport.redact(query).inspect}" if query}#{" headers=#{Transport.redact(headers).inspect}" if headers}" end - logger.debug { "Zammad API payload: #{loggable_body(payload).inspect}" } if payload + logger.debug { "Zammad API payload: #{loggable_body(body)}" } if body end def log_response(method, path, response, started) @@ -2056,38 +312,11 @@ def log_response(method, path, response, started) logger.debug { "Zammad API response: #{method.to_s.upcase} #{Transport.redact_path(path)} -> #{response.status} in #{duration}ms" } end - # What the log prints for a request body: the body as it is sent, read - # back for its keys and redacted by them. - # - # Read from the encoded payload and not from what the caller handed - # over, because {.redact} works by key and only a Hash has keys. What - # was handed over was printed by +inspect+ wherever it was anything - # else, and there are two ways for that to be a credential. - # - # One is a String, which is the caller's own encoding: - # `client.post(path, body: '{"login":"a","password":"hunter2"}')` was - # written to the log as it stood. - # - # The other is an object inside the body. One that writes its own JSON - # goes out as keys and values like any Hash - a value object with a - # +to_json+, as the whole body or under a key of it - and +inspect+ - # printed every one of them. So does one that is sent as its +as_json+: - # see {.json_object}. - # - # So the payload is parsed, and the log holds what the wire holds. Where - # it is a JSON object or array it is redacted like the structure it - # spells. Where it is not - a form body, a file, a single value - - # nothing in it can be told from a credential, and its size is logged - # in its place. Parsed only where the line is written: this runs inside - # the logger's block. - def loggable_body(payload) - decoded = JSON.parse(payload) - decoded.is_a?(Hash) || decoded.is_a?(Array) ? Transport.redact(decoded) : unlogged_body(payload) - rescue JSON::JSONError, EncodingError - unlogged_body(payload) - end + def loggable_body(body) + return Transport.redact(body).inspect if body.is_a?(Hash) || body.is_a?(Array) - def unlogged_body(body) = "[#{body.bytesize} bytes that are not a JSON object or array, not logged]" + "[#{body.to_s.bytesize} bytes, not logged]" + end def logger = config.logger end diff --git a/script/check_connection.rb b/script/check_connection.rb index 6d96977..ba5771e 100755 --- a/script/check_connection.rb +++ b/script/check_connection.rb @@ -271,13 +271,6 @@ def finish "#{CLIENT.groups.search("smoke-#{SUFFIX}").order(:name, id: :desc).to_a.size} hit(s)" end -check('search refuses a keyword the endpoint would drop') do - CLIENT.groups.search('smoke', name: "smoke-#{SUFFIX}").to_a - raise 'expected ArgumentError' -rescue ArgumentError => e - e.message.split(':').first -end - section 'Tickets' check!('create a ticket with its first article') do diff --git a/sig/vendor/faraday.rbs b/sig/vendor/faraday.rbs index 397c65f..9db943e 100644 --- a/sig/vendor/faraday.rbs +++ b/sig/vendor/faraday.rbs @@ -7,12 +7,6 @@ module Faraday def response: () -> untyped end - # What a middleware of this gem's own is built on. See - # ZammadAPI::Transport::HeldToLength. - class Middleware - def initialize: (?untyped app, ?untyped options) -> void - end - class ConnectionFailed < Error end @@ -53,30 +47,5 @@ module Faraday def use: (untyped, *untyped) -> void end - # The encoder a connection writes its query with by default. An Array of - # pairs is written in the order it is given, where a Hash is sorted. - class NestedParamsEncoder - def self.encode: (untyped params) -> String? - def self.decode: (String? query) -> untyped - end - - # The retry middleware, asked what it would do with a response. See - # ZammadAPI::Transport.retried?. - module Retry - class Middleware - def initialize: (untyped app, ?untyped options) -> void - def calculate_sleep_amount: (Integer retries, untyped env) -> Float? - end - end - - module Utils - # Response headers, read whatever the case of the name. - class Headers - def initialize: (?Hash[untyped, untyped] hash) -> void - end - end - def self.new: (**untyped) ?{ (Connection) -> void } -> Connection - def self.default_adapter: () -> Symbol - def self.default_connection_options: () -> untyped end diff --git a/sig/vendor/internal.rbs b/sig/vendor/internal.rbs index 6c10b63..620fdc7 100644 --- a/sig/vendor/internal.rbs +++ b/sig/vendor/internal.rbs @@ -12,17 +12,3 @@ module ZammadAPI extend Forwardable end end - -# The two classes the transport puts into its Faraday stack. Private -# constants, and built on Faraday types, which a published signature cannot -# name: see sig/zammad_api/transport.rbs. -module ZammadAPI - class Transport - class CutShort < Faraday::Error - end - - class HeldToLength < Faraday::Middleware - def on_complete: (untyped env) -> void - end - end -end diff --git a/sig/zammad_api/associations.rbs b/sig/zammad_api/associations.rbs index 44d58c9..3aebf29 100644 --- a/sig/zammad_api/associations.rbs +++ b/sig/zammad_api/associations.rbs @@ -1,18 +1,21 @@ module ZammadAPI module Associations - # The readers are defined by the belongs_to and has_many declarations in - # lib/zammad_api/resources, onto a per-resource subclass of this one that - # has no name to declare. They are listed here so that callers get types - # and completion; every name is declared once and means the same target - # wherever it is declared, so the type of a given reader is accurate. The - # class is wider than any one resource, so a reader the record does not - # declare type-checks here and raises NoMethodError at runtime. + # The readers are answered through method_missing, from the belongs_to + # and has_many declarations in lib/zammad_api/resources. The ones this gem + # declares are listed here so that callers get types and completion; every + # name means the same target wherever it is declared, so the type of a + # given reader is accurate. The class is wider than any one resource, so + # a reader the record does not declare type-checks here and raises + # NoMethodError at runtime. class Proxy @record: Resources::Base @cache: Hash[Symbol, untyped] def initialize: (Resources::Base record) -> void def inspect: () -> String + def forget: () -> void + def method_missing: (Symbol, *untyped) -> untyped + def respond_to_missing?: (Symbol, ?bool) -> bool def created_by: () -> Resources::User? def updated_by: () -> Resources::User? @@ -27,10 +30,9 @@ module ZammadAPI private - def belongs_to_target: (Symbol name, String class_name, Symbol foreign_key) -> untyped - def has_many_target: (Symbol name, String class_name, ^(String) -> String path) -> Array[untyped] - def forget_targets: () -> void - def refuse_destroyed!: (Symbol name) -> void + def associations: () -> Hash[Symbol, Hash[Symbol, untyped]] + def belongs_to_target: (Symbol name, Hash[Symbol, untyped] spec) -> untyped + def has_many_target: (Symbol name, Hash[Symbol, untyped] spec) -> Array[untyped] def resolve: (String class_name) -> untyped end end diff --git a/sig/zammad_api/attribute_access.rbs b/sig/zammad_api/attribute_access.rbs index 77d38b9..3f6b908 100644 --- a/sig/zammad_api/attribute_access.rbs +++ b/sig/zammad_api/attribute_access.rbs @@ -1,6 +1,5 @@ module ZammadAPI module AttributeAccess - NON_ATTRIBUTE_SUFFIXES: Array[String] # private_constant in the source; RBS has no way to say so. ATTRIBUTE_WRITER: Regexp @@ -18,10 +17,9 @@ module ZammadAPI def ==: (untyped other) -> bool def eql?: (untyped other) -> bool def hash: () -> Integer - def as_json: (?untyped options) -> Hash[Symbol, untyped] - def to_json: (?untyped state) -> String + def as_json: (*untyped) -> Hash[Symbol, untyped] + def to_json: (*untyped) -> String def method_missing: (Symbol, *untyped) -> untyped - def respond_to?: (untyped name, ?bool include_private) -> bool def respond_to_missing?: (Symbol, ?bool) -> bool private @@ -29,10 +27,7 @@ module ZammadAPI # Protected in the source, which RBS has no way to say: it is asked of # the other record in `==`, and of nobody else. def installation: () -> String? - def unknown_attribute_message: (Symbol name) -> String - def reader_arguments_message: (Symbol name, Integer given) -> String def writable_attributes?: () -> bool - def attribute_writable?: (Symbol key) -> bool def write_attribute: (Symbol, untyped) -> untyped def frozen_attributes: (untyped) -> untyped end diff --git a/sig/zammad_api/attributes.rbs b/sig/zammad_api/attributes.rbs deleted file mode 100644 index a9ef1f1..0000000 --- a/sig/zammad_api/attributes.rbs +++ /dev/null @@ -1,11 +0,0 @@ -module ZammadAPI - # A Hash in every way but how it is printed: see lib/zammad_api/attributes.rb. - class Attributes[unchecked out K, unchecked out V] < Hash[K, V] - def inspect: () -> String - def to_s: () -> String - def to_h: () -> Hash[K, V] - | [A, B] () { (K, V) -> [A, B] } -> Hash[A, B] - def pretty_print: (untyped printer) -> void - def encode_with: (untyped coder) -> void - end -end diff --git a/sig/zammad_api/client.rbs b/sig/zammad_api/client.rbs index b340a72..0ac96c6 100644 --- a/sig/zammad_api/client.rbs +++ b/sig/zammad_api/client.rbs @@ -41,8 +41,6 @@ module ZammadAPI def on_behalf_of: (String | Integer identifier) -> Client | [T] (String | Integer identifier) { (Client) -> T } -> T def inspect: () -> String - def as_json: (*untyped) -> Hash[Symbol, untyped] - def to_json: (?untyped state) -> String def method_missing: (Symbol, *untyped) -> untyped def respond_to_missing?: (Symbol, ?bool) -> bool diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs index 847b59a..a273790 100644 --- a/sig/zammad_api/collection.rbs +++ b/sig/zammad_api/collection.rbs @@ -5,10 +5,6 @@ module ZammadAPI class Collection[R < Resources::Base] include Enumerable[R] - # Both are private_constant in the source; RBS has no way to say so. - SORT_DIRECTIONS: Array[String] - SORT_ATTRIBUTE: Regexp - @transport: Transport @resource_class: untyped @path: String @@ -16,11 +12,9 @@ module ZammadAPI @query: Hash[Symbol, untyped] @max_per_page: Integer @sortable: bool - @unsortable_hint: String @per_page: Integer @page: Integer? @search: bool - @widens: bool @paginated: bool def initialize: ( @@ -30,12 +24,10 @@ module ZammadAPI operation: String, max_per_page: Integer, sortable: bool, - unsortable_hint: String, ?query: Hash[Symbol, untyped], ?per_page: Integer?, ?page: Integer?, ?search: bool, - ?widens: bool, ?paginated: bool ) -> void @@ -48,50 +40,20 @@ module ZammadAPI def page: (Integer number, ?per_page: Integer?) -> Collection[R] def first: () -> R? | (Integer count) -> Array[R] - def take: (Integer count) -> Array[R] def find: (?untyped ifnone) { (R) -> boolish } -> R? | (*untyped) -> untyped def order: (*(Symbol | String) attributes, **(Symbol | String) directions) -> Collection[R] def pluck: (*(Symbol | String) keys) -> Array[untyped] def count: (*untyped) ?{ (R) -> boolish } -> Integer - def size: (*untyped) ?{ (R) -> boolish } -> Integer - def length: (*untyped) ?{ (R) -> boolish } -> Integer - def each_slice: (Integer size) { (Array[R]) -> void } -> Collection[R] - | (Integer size) -> Enumerator[Array[R], untyped] - def each_cons: (Integer size) { (Array[R]) -> void } -> Collection[R] - | (Integer size) -> Enumerator[Array[R], untyped] - def lazy: () -> Enumerator::Lazy[R, void] def empty?: () -> bool - def any?: () -> bool - | ... - def none?: () -> bool - | ... def inspect: () -> String private - def own_request_for_first?: (untyped count) -> bool - def find_by_id_message: (untyped) -> String - def resource_reader: () -> String - def sort_columns: (Array[untyped] attributes, Hash[untyped, untyped] directions) -> Hash[String, String] - def sort_attribute!: (untyped attribute) -> String - def sort_direction!: (String name, untyped direction) -> String - def sorted_by: () -> Hash[String, String] - def positive_integer!: (untyped, String) -> Integer - def page_size!: (untyped, String) -> Integer def walk: () { (Array[R]) -> void } -> void - def read_whole: () { (Array[R]) -> void } -> void - def refuse_ignored_page!: (Integer page, Integer per_page, Integer digest) -> void - def page_after: (Integer page, Integer per_page, Integer received, Integer? total) -> [ Integer, Integer ] - def widened: (Integer covered, Integer? total) -> [ Integer, Integer ] - def each_distinct: () { (Resources::Base) -> void } -> void - def with: (?page: Integer?, ?per_page: Integer, ?query: Hash[Symbol, untyped], ?widens: bool) -> Collection[R] - def hits_past?: (Integer covered, Integer? total) -> bool - def fetch: (Integer, Integer) -> [ Array[R], Integer, Integer? ] - def page_query: (Integer page, Integer per_page) -> Hash[Symbol, untyped] - def tie_broken: () -> Hash[Symbol, untyped] - def page_digest: (Array[Hash[Symbol, untyped]] decoded) -> Integer + def fetch: (Integer? number) -> Array[R] def total_count: () -> Integer? - def clamp_per_page: (untyped) -> Integer + def sorted_by: () -> Hash[String, String] + def with: (?page: Integer?, ?per_page: Integer?, ?query: Hash[Symbol, untyped]) -> Collection[R] end end diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index e265d7c..35365b5 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -11,22 +11,12 @@ module ZammadAPI DEFAULT_OPEN_TIMEOUT: Integer DEFAULT_RETRIES: Integer DEFAULT_RETRY_INTERVAL: Float - MAX_SECONDS: Integer - REDACTED_ATTRIBUTES: Array[Symbol] REDACTION: String DEFAULT_USER_AGENT: String - SCHEME_PATTERN: Regexp - URL_PATTERN: Regexp - URL_SUFFIX_PATTERN: Regexp - URL_SCHEME_PATTERN: Regexp - URL_AUTHORITY_PATTERN: Regexp CREDENTIAL_OPTIONS: Hash[Symbol, Array[Symbol]] def self.new: (**untyped) -> instance - TOKEN_OPTIONS: Array[Symbol] def self.merge_options: (Hash[Symbol, untyped] options, Hash[Symbol, untyped] overrides) -> Hash[Symbol, untyped] - def self.names_credential?: (Symbol name, untyped value) -> bool - def self.blank_token?: (untyped value) -> bool attr_reader url: String attr_reader user: String? @@ -50,7 +40,7 @@ module ZammadAPI ?password: String?, ?http_token: String?, ?oauth2_token: String?, - ?user_agent: String, + ?user_agent: String?, ?timeout: untyped, ?open_timeout: untyped, ?retries: untyped, @@ -62,46 +52,22 @@ module ZammadAPI ?logger: Logger? ) -> void - def redacted_url: () -> String - def redacted: (String value) -> String def authentication_scheme: () -> Symbol def with: (**untyped) -> Config def inspect: () -> String def to_s: () -> String def pretty_print: (untyped printer) -> void - def as_json: (*untyped) -> Hash[Symbol, untyped] - def to_json: (?untyped state) -> String - def encode_with: (untyped coder) -> void def to_h: () -> Hash[Symbol, untyped] private - def redact_userinfo: (String) -> String - def normalize_token: (Symbol name, untyped value) -> String? - def normalize_user_agent: (untyped value) -> untyped - def normalize_proxy: (untyped) -> String? - def normalize_adapter: (untyped) -> Symbol? def render: (Symbol, untyped) -> String - def placeholder: (Symbol, untyped) -> String? - def printable: (Symbol, untyped) -> untyped def normalize_url: (untyped) -> String - def hostless?: (String) -> bool - def inline_credentials?: (String) -> bool - def inline_credentials_message: (String) -> String + def validate!: () -> void def validate_credentials!: () -> void - def multiple_credentials_message: (Array[Symbol] schemes) -> String - def positive_number?: (untyped) -> bool def validate_numbers!: () -> void - def too_long_message: (Symbol name, untyped value) -> String - def validate_user_agent!: () -> void - HEADER_OPTIONS: Array[Symbol] - def validate_header_options!: () -> void - def header_text: (Symbol name, String value) -> String - def validate_ssl_verify!: () -> void - def validate_middleware!: () -> void - def validate_logger!: () -> void - def debug_needs_argument?: () -> bool - def non_empty: (untyped) -> untyped - def immutable: (untyped) -> untyped + def validate_proxy!: () -> void + def present: (untyped) -> untyped + def stripped: (untyped) -> String? end end diff --git a/sig/zammad_api/deep_copy.rbs b/sig/zammad_api/deep_copy.rbs index d9a37ab..09526b8 100644 --- a/sig/zammad_api/deep_copy.rbs +++ b/sig/zammad_api/deep_copy.rbs @@ -1,8 +1,6 @@ module ZammadAPI module DeepCopy def self?.frozen_copy: (untyped value, ?symbolize_keys: bool) -> untyped - def self?.frozen_hash: (Hash[untyped, untyped] hash, bool symbolize_keys) -> Hash[untyped, untyped] - def self?.frozen_object: (untyped value, bool symbolize_keys) -> untyped def self?.writable_copy: (untyped value) -> untyped def self?.symbolize: (untyped key) -> untyped end diff --git a/sig/zammad_api/duplicate_keys.rbs b/sig/zammad_api/duplicate_keys.rbs deleted file mode 100644 index 3f26306..0000000 --- a/sig/zammad_api/duplicate_keys.rbs +++ /dev/null @@ -1,9 +0,0 @@ -module ZammadAPI - module DuplicateKeys - def self.normalize: (Hash[untyped, untyped] hash, ?prefix: String?, ?noun: String) { (untyped key) -> untyped } -> Hash[untyped, untyped] - def self.message: (String noun, untyped path, untyped first, untyped second) -> String - - def normalize: (Hash[untyped, untyped] hash, ?prefix: String?, ?noun: String) { (untyped key) -> untyped } -> Hash[untyped, untyped] - def message: (String noun, untyped path, untyped first, untyped second) -> String - end -end diff --git a/sig/zammad_api/errors.rbs b/sig/zammad_api/errors.rbs index 4093c84..2b255eb 100644 --- a/sig/zammad_api/errors.rbs +++ b/sig/zammad_api/errors.rbs @@ -15,12 +15,6 @@ module ZammadAPI class ConnectionError < TransportError end - class IncompleteResponseError < ConnectionError - attr_reader response: Response? - - def initialize: (?String? message, ?response: Response?) -> void - end - class TimeoutError < TransportError end @@ -29,9 +23,7 @@ module ZammadAPI end class PaginationError < Error - UNPAGINATED_ADVICE: String - - def self.build: (operation: String, page: Integer, ?resource_class: Class?, ?index: bool) -> PaginationError + def self.build: (operation: String, page: Integer, ?resource_class: Class?) -> PaginationError end class ResponseError < Error diff --git a/sig/zammad_api/query_encoder.rbs b/sig/zammad_api/query_encoder.rbs deleted file mode 100644 index 7404b7e..0000000 --- a/sig/zammad_api/query_encoder.rbs +++ /dev/null @@ -1,13 +0,0 @@ -module ZammadAPI - module QueryEncoder - def self?.encode: (untyped params) -> String? - def self?.decode: (String? query) -> untyped - def self?.lead_path: (Hash[untyped, untyped] element, untyped previous) -> Array[untyped]? - def self?.misread: (untyped element, untyped previous) -> Symbol? - def self?.written?: (untyped value) -> bool - def self?.hash_pairs: (String? prefix, Hash[untyped, untyped] hash, Array[untyped]? lead) -> Array[[ String, untyped ]] - def self?.value_pairs: (String path, untyped value, ?Array[untyped]? lead) -> Array[[ String, untyped ]] - def self?.array_pairs: (String path, Array[untyped] array) -> Array[[ String, untyped ]] - def self?.sorted_keys: (Hash[untyped, untyped] hash) -> Array[untyped] - end -end diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs index 381cd24..363e7fd 100644 --- a/sig/zammad_api/resource_proxy.rbs +++ b/sig/zammad_api/resource_proxy.rbs @@ -6,10 +6,6 @@ module ZammadAPI include Enumerable[R] SEARCH_MAX_PER_PAGE: Integer - SEARCH_FILTER_KEYS: Array[Symbol] - BLANK_TERM_MESSAGE: String - SEARCHABLE_UNSORTABLE_HINT: String - UNSORTABLE_HINT: String attr_reader resource_class: untyped @@ -35,39 +31,16 @@ module ZammadAPI def page: (Integer number, ?per_page: Integer?) -> Collection[R] def pluck: (*(Symbol | String) keys) -> Array[untyped] def count: (*untyped) ?{ (R) -> boolish } -> Integer - def size: () -> Integer - def length: () -> Integer def empty?: () -> bool - def any?: () -> bool - | ... - def none?: () -> bool - | ... def first: () -> R? | (Integer count) -> Array[R] - def take: (Integer count) -> Array[R] - def each_slice: (Integer size) { (Array[R]) -> void } -> Collection[R] - | (Integer size) -> Enumerator[Array[R], untyped] - def each_cons: (Integer size) { (Array[R]) -> void } -> Collection[R] - | (Integer size) -> Enumerator[Array[R], untyped] - def lazy: () -> Enumerator::Lazy[R, void] - def search: (String term, ?condition: Hash[untyped, untyped], ?ids: Array[Integer | String], ?role_ids: Array[Integer | String], ?group_ids: Array[Integer | String] | Hash[Integer | String, String | Symbol | Array[String | Symbol]], ?permissions: Array[String]) -> Collection[R] + def search: (String term, **untyped filters) -> Collection[R] def inspect: () -> String private def collection: (String, String, ?query: Hash[Symbol, untyped], ?max_per_page: Integer, ?sortable: bool, ?paginated: bool, ?search: bool) -> Collection[R] - def search_filters: (Hash[untyped, untyped] filters) -> Hash[Symbol, untyped] - def search_filter_keys: () -> Array[Symbol] - def unknown_search_filter_message: (Array[Symbol] unknown) -> String - def empty_search_filter?: (untyped value) -> bool - def empty_search_filter_message: (Hash[Symbol, untyped] empty) -> String - def searchable!: () -> void - def find_by_id: (untyped id, Hash[Symbol, untyped] others) -> R? - def record_number: (untyped id) -> Integer? - def as_served: (Hash[Symbol, untyped] params) -> Hash[Symbol, untyped] - def carries?: (Resources::Base record, Hash[Symbol, untyped] params) -> bool - def search_term_for: (Hash[Symbol, untyped]) -> String? + def find_by_id: (Hash[Symbol, untyped] params) -> R? def path: () -> String - def member_path: (Integer | String id) -> String end end diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 715dedd..b73f452 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -4,7 +4,6 @@ module ZammadAPI include AttributeAccess DEFAULT_MAX_PER_PAGE: Integer - MEMO_LOCK: Thread::Mutex attr_reader error: ValidationError? attr_reader transport: Transport @@ -23,45 +22,34 @@ module ZammadAPI @new_record: bool @destroyed: bool - @saved: bool @error: ValidationError? - @changes: Hash[Symbol, Array[untyped]] @related: Associations::Proxy? @baseline: Hash[Symbol, untyped] - self.@related_class: untyped - self.@belongs_to_foreign_keys: Array[Symbol]? self.@declared_associations: Hash[Symbol, Hash[Symbol, untyped]]? self.@path: String? self.@searchable: bool? self.@max_per_page: Integer? - self.@search_filters: Array[Symbol]? self.@sortable: bool? self.@paginated: bool? def self.path: (String) -> void def self.searchable: (bool) -> void def self.max_per_page: (Integer) -> void - def self.search_filters: (*Symbol | String names) -> void def self.sortable: (bool) -> void def self.paginated: (bool) -> void def self.resource_path: () -> String def self.searchable?: () -> bool - def self.search_filter_names: () -> Array[Symbol] def self.page_limit: () -> Integer def self.sortable?: () -> bool def self.paginated?: () -> bool def self.member_path: ((Integer | String) id) -> String def self.fetch_one: (Transport transport, (Integer | String) id) -> Base - def self.confirm_destroyed!: (Response response) -> Response def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> Base def self.associations: () -> Hash[Symbol, Hash[Symbol, untyped]] - def self.belongs_to_foreign_keys: () -> Array[Symbol] - def self.related_class: () -> untyped def self.declaration: [T] (Symbol name) { () -> T } -> T | (Symbol name) -> untyped def self.declared_associations: () -> Hash[Symbol, Hash[Symbol, untyped]] def self.belongs_to: (Symbol name, class_name: String, ?foreign_key: Symbol) -> void - def self.forget_foreign_keys: () -> void def self.has_many: (Symbol name, class_name: String, path: ^(String) -> String) -> void def initialize: (Transport, ?hash[untyped, untyped]? attributes) -> void @@ -83,29 +71,14 @@ module ZammadAPI private def initialize_copy: (self source) -> void - def setup: (Transport, Hash[untyped, untyped] attributes) -> void def mark_persisted!: () -> void - def mark_destroyed!: () -> void - def attribute_hash: (untyped given) -> Hash[untyped, untyped] + def load_response!: (Response response, String operation) -> void def raise_if_destroyed!: (String action) -> void def raise_if_new!: (String operation) -> void def writable_attributes?: () -> bool - def attribute_writable?: (Symbol key) -> bool - def refuse_unwritable!: (Symbol key, untyped value) -> void - def replace_attributes!: (Response, operation: String, ?sent: Hash[Symbol, untyped]?) -> void - def mark_answered!: (Hash[Symbol, untyped]? sent) -> void - def applied: (Hash[Symbol, untyped] sent) { () -> Response } -> Response - def applied_by?: (Response? response) -> bool - def acknowledge_changes!: (Hash[Symbol, untyped] sent) -> void - def reset_pending_state!: () -> void - def forget_related_targets: () -> void def write_attribute: (Symbol, untyped) -> untyped - def unsaved_attributes: (Hash[Symbol, untyped] held) -> Hash[Symbol, untyped] - def create_record: (Hash[Symbol, untyped] body) -> Response - def update_record: (Hash[Symbol, untyped] body) -> Response def member_path: () -> String def require_id!: () -> Integer - def no_id_message: () -> String end end end diff --git a/sig/zammad_api/resources/resources.rbs b/sig/zammad_api/resources/resources.rbs index 77c9dfb..4bce2e5 100644 --- a/sig/zammad_api/resources/resources.rbs +++ b/sig/zammad_api/resources/resources.rbs @@ -158,9 +158,6 @@ module ZammadAPI # Narrowed from Base so callers get the concrete article type. def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> TicketArticle - # private_constant in the source; RBS has no way to say so. - ATTACHMENTS_OPERATION: String - attr_accessor ticket_id: Integer attr_accessor type_id: Integer attr_accessor sender_id: Integer @@ -185,10 +182,6 @@ module ZammadAPI attr_reader origin_by_id: Integer? def attachments: () -> Array[TicketArticleAttachment] - - private - - def attachment: (untyped raw) -> TicketArticleAttachment end class TicketArticleAttachment @@ -204,12 +197,6 @@ module ZammadAPI def initialize: (Transport, ?Hash[untyped, untyped]? attributes) -> void def download: () -> String def inspect: () -> String - - private - - UNENCODED: Hash[String, String] - - def request_file: (Hash[String, String]? headers) -> Response end end end diff --git a/sig/zammad_api/response.rbs b/sig/zammad_api/response.rbs index 439aca3..2b47905 100644 --- a/sig/zammad_api/response.rbs +++ b/sig/zammad_api/response.rbs @@ -5,22 +5,13 @@ module ZammadAPI attr_reader headers: Hash[String, String] attr_reader body: untyped attr_reader raw_body: String - attr_reader json: bool - def self.new: (status: Integer, headers: Hash[String, String], body: untyped, raw_body: String, json: bool) -> instance + def self.new: (status: Integer, headers: Hash[String, String], body: untyped, raw_body: String) -> instance SUCCESS_STATUSES: Range[Integer] - def self.decode_body: (String?, String) -> [untyped, bool] - def self.json_type?: (String?) -> bool + def self.decode_body: (String?, String) -> untyped def success?: () -> bool - def json?: () -> bool - def json_content_type?: () -> bool def decoded: (Symbol shape, operation: String, ?resource_class: Class?) -> untyped - def decoded_list: (operation: String, ?resource_class: Class?) -> [ Array[Hash[Symbol, untyped]], Integer? ] - - private - - def array_of_objects!: (Array[untyped], operation: String, resource_class: Class?) -> Array[untyped] end end diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs index d3e559b..9ad52f1 100644 --- a/sig/zammad_api/test.rbs +++ b/sig/zammad_api/test.rbs @@ -1,15 +1,10 @@ module ZammadAPI class Test - # Both are deliberately outside ZammadAPI::Error: they say the test is - # wrong, not that Zammad refused anything, and the signature said - # otherwise - so a `rescue ZammadAPI::Error` type-checked as catching a - # forgotten stub that it does not in fact catch. + # Deliberately outside ZammadAPI::Error: it says the test is wrong, not + # that Zammad refused anything. class UnstubbedRequestError < ::StandardError end - class AmbiguousStubError < ::StandardError - end - class Request < ::Data attr_reader verb: Symbol attr_reader path: String @@ -26,10 +21,7 @@ module ZammadAPI @stubs: Hash[[Symbol, String], Array[Hash[Symbol, untyped]]] @requests: Array[Request] - @served: Hash[[[Symbol, String], Hash[String, untyped]?], Hash[Symbol, untyped]] @monitor: Thread::Mutex - @transport: Test::Transport - @client: Client def initialize: (**untyped options) -> void def stub: (Symbol method, String path, ?status: Integer, ?body: untyped, ?headers: Hash[untyped, untyped], ?query: Hash[untyped, untyped]?) -> self @@ -46,35 +38,21 @@ module ZammadAPI ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?, - ?on_behalf_of: String?, - ?config: Config + ?on_behalf_of: String? ) -> Response private - def attempt: (Request request) -> Response + # private_constant in the source; RBS has no way to say so. + EMPTY_PAGE: Hash[Symbol, untyped] + def key: (Symbol method, String path) -> [Symbol, String] - def raw_body_for: (untyped body) -> String - def response_headers: (Hash[untyped, untyped] headers, untyped body) -> Hash[String, String] - def snapshot: (untyped) -> untyped + def stringify: (untyped value) -> untyped def take: (Symbol method, String path, Hash[String, untyped] params) -> Hash[Symbol, untyped]? - def later_page?: (Hash[String, untyped]? scope, Hash[String, untyped] params) -> bool - def advance: (Array[Hash[Symbol, untyped]] queued, Array[Integer] group, bool turn_over) -> Hash[Symbol, untyped] - def count_request?: (Hash[String, untyped]? scope, Hash[String, untyped] params) -> bool - def counted_alone?: (Hash[Symbol, untyped] stub) -> bool - def most_specific: (Array[Hash[Symbol, untyped]] queued, Array[Integer] matching, Symbol method, String path) -> Array[Integer] - def ambiguous_message: (Symbol method, String path, Array[Hash[String, untyped]?] scopes) -> String - def matches?: (Hash[untyped, untyped]? expected, Hash[String, untyped] params) -> bool - PAGE_NUMBER: Regexp - - def paged_body: (Hash[Symbol, untyped] stub, Hash[String, untyped] params, untyped body) -> untyped - def page_of: (Array[untyped] records, [Integer, Integer]? window) -> Array[untyped] - def page_window: (Hash[String, untyped] params) -> [Integer, Integer]? - def response_for: (Hash[Symbol, untyped] stub, Hash[String, untyped] params) -> Response - def recounted: (Hash[String, String] headers, String raw_body) -> Hash[String, String] - def build_response: (Hash[Symbol, untyped] stub, untyped body, String raw_body, json: bool, ?headers: Hash[String, String]) -> Response - def unstubbed_message: (Symbol method, String path, Hash[String, untyped] params) -> String - def unmatched_query_message: (String request, Hash[String, untyped] params, Array[Hash[String, untyped]?] scopes) -> String + def matches?: (Hash[String, untyped]? expected, Hash[String, untyped] params) -> bool + def response_for: (Hash[Symbol, untyped] stub) -> Response + def stubbed_endpoints: () -> Array[String] + def unstubbed_message: (Request request) -> String class Transport include ::ZammadAPI::Transport::Verbs @@ -83,11 +61,9 @@ module ZammadAPI attr_reader config: Config attr_reader on_behalf_of: String? - def initialize: (Test test, ?on_behalf_of: (String | Integer)?, ?config: Config) -> void - def with_on_behalf_of: ((String | Integer)? identifier) -> Test::Transport + def initialize: (Test test, ?on_behalf_of: String?, ?config: Config) -> void + def with_on_behalf_of: (String? identifier) -> Test::Transport def with_config: (Config) -> Test::Transport - def encode_with: (untyped coder) -> void - def request: (Symbol method, String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index db1ad60..9d8e5fd 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -15,94 +15,34 @@ module ZammadAPI RETRIABLE_METHODS: Array[Symbol] RETRIABLE_STATUSES: Array[Integer] - RETRIABLE_EXCEPTIONS: Array[untyped] TIMEOUT_ERRORS: Array[untyped] CONNECTION_ERRORS: Array[untyped] # Untyped for the same reason as the Faraday ones above: naming # OpenSSL::SSL::SSLError here would make the published signatures need # openssl declarations that a consumer has not loaded. SSL_ERRORS: Array[untyped] - # private_constant in the source; RBS has no way to say so. - REFUSED_MIDDLEWARE: Hash[String, [String, String]] - CONTENT_LENGTH: Regexp - ENVIRONMENT_PROXY: Regexp - MISREAD_ELEMENTS: Hash[Symbol, String] + RETRIABLE_EXCEPTIONS: Array[untyped] SENSITIVE_KEY_PATTERN: Regexp REDACTED: String - UNRESERVED_IN_PATH: Regexp - DOT_SEGMENTS: Array[String] - RECORD_ID_TYPES: Array[Class] - QUERY_VALUE_TYPES: Array[Class] - JSON_VALUE_TYPES: Array[Class] - class RefusedValue < StandardError - end - TEXT_VALUE_TYPES: Array[Class] + # private_constant in the source; RBS has no way to say so. ABSOLUTE_URL: Regexp - PARENT_SEGMENT: Regexp - RESERVED_HEADERS: Hash[String, String] - HEADER_NAME: Regexp attr_reader config: Config attr_reader on_behalf_of: String? @connection: untyped - def self.redact_path: (untyped path) -> String - def self.redact_query_pair: (String pair) -> String - def self.credential_parameter?: (String parameter) -> bool - def self.blank_query_value: (String parameter) -> String - def self.redact: (untyped value) -> untyped - def self.stringify_query: (untyped) -> Hash[String, untyped] - def self.refuse_unwritten!: (Hash[String, untyped] query, String? prefix) -> Hash[String, untyped] - def self.unwritten_query_message: (String path) -> String - def self.stringify_query_hash: (Hash[untyped, untyped], String?) -> Hash[String, untyped] - def self.stringify_query_value: (String, untyped) -> untyped - def self.stringify_query_scalar: (String key, untyped value) -> String - def self.not_a_query_value_message: (String key, untyped value) -> String - def self.stringify_query_list: (String, Array[untyped]) -> Array[untyped] - def self.misread_element_message: (String, Symbol) -> String - def self.empty_query_name_message: (String? prefix) -> String - def self.stringify_headers: (Hash[untyped, untyped]) -> Hash[String, String] - def self.stripped: (String text) -> String - BLANK: Regexp - WIRE_ENCODINGS: Array[Encoding] - def self.wire_text: (untyped value, String name) -> String - LINE_BREAK_ADVICE: String - def self.line_break?: (String text) -> bool - def self.stringify_on_behalf_of: ((String | Integer)? identifier) -> String? - def self.not_an_identifier_message: (untyped identifier) -> String - def self.blank_on_behalf_of_message: (untyped identifier) -> String - def self.header_name: (untyped name) -> String - def self.not_a_header_name_message: (String start) -> String - def self.stringify_header_value: (String, untyped) -> String + def self.on_behalf_of_header: (untyped identifier) -> String def self.escape_path_segment: (untyped) -> String - def self.not_a_record_id_message: (untyped value) -> String def self.relative_path: (untyped) -> String - def self.refuse_unreadable_path!: (String relative) -> void - def self.refuse_parent_segment!: (String relative) -> void - def self.unreadable_path_message: (String relative) -> String + def self.redact_path: (untyped path) -> String + def self.redact: (untyped value) -> untyped def self.encode_body: (untyped body, operation: String, ?resource_class: Class?) -> String? - def self.json_value: (untyped value, untyped key) -> untyped - def self.json_text: (String text) -> String - def self.json_hash: (Hash[untyped, untyped] hash, untyped key) -> Hash[String, untyped] - def self.json_object: (untyped value, untyped key) -> untyped - def self.writes_own_json?: (untyped value) -> bool - def self.not_a_json_value_message: (untyped value, untyped key) -> String - def self.retry_options: (Config config) -> Hash[Symbol, untyped] - def self.retried?: (Config config, Symbol method, Response response) -> bool - def self.whole: (Response response, operation: String, config: Config) -> Response - def self.missing_bytes: (Response response) -> Integer? - def self.short_by: (Integer status, untyped headers, String body) -> Integer? - def self.cut_short?: (Response response) -> bool - def self.description: (Config config, String? on_behalf_of) -> Hash[Symbol, untyped] - def initialize: (Config) -> void - def with_on_behalf_of: ((String | Integer)? identifier) -> Transport + def initialize: (Config, ?on_behalf_of: String?) -> void + def with_on_behalf_of: (String? identifier) -> Transport def with_config: (Config) -> Transport def inspect: () -> String - def as_json: (*untyped) -> Hash[Symbol, untyped] - def to_json: (?untyped state) -> String - def encode_with: (untyped coder) -> void def request: (Symbol method, String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response @@ -111,24 +51,12 @@ module ZammadAPI def timed_out?: (untyped error) -> bool def perform: (Symbol, String, Hash[Symbol, untyped]?, String?, Hash[untyped, untyped]?) -> untyped def build_connection: () -> untyped - def configured_proxy: () -> Hash[Symbol, String] - def apply_middleware_and_adapter: (untyped faraday) -> void - def refuse_unusable_middleware!: (untyped connection) -> void - def refused_middleware: (Class klass) -> String? - def refused_middleware_message: (Class klass, String refused) -> String - def drop_shared_headers: (untyped) -> void + def retry_options: () -> Hash[Symbol, untyped] def apply_authentication: (untyped) -> void def decode: (untyped) -> Response - def raw_body!: (untyped) -> String - def log_request: (Symbol, String, Hash[String, untyped]?, String?, Hash[String, String]?) -> void + def log_request: (Symbol, String, Hash[Symbol, untyped]?, untyped, Hash[untyped, untyped]?) -> void def log_response: (Symbol, String, Response, Float) -> void - def loggable_body: (String payload) -> untyped - def unlogged_body: (String body) -> String - def reportable_cause: (StandardError error) -> StandardError? - def redact_config_values: (untyped message) -> String - def shared_proxies: () -> Array[String] - def environment_proxies: () -> Array[String] - def quoted_spellings: (String value) -> Array[String] + def loggable_body: (untyped body) -> String def logger: () -> Logger end end diff --git a/spec/unit/zammad_api/associations/proxy_spec.rb b/spec/unit/zammad_api/associations/proxy_spec.rb index 8ff8285..d1d8bd4 100644 --- a/spec/unit/zammad_api/associations/proxy_spec.rb +++ b/spec/unit/zammad_api/associations/proxy_spec.rb @@ -133,12 +133,6 @@ .to raise_error(ZammadAPI::ParseError, /Can't get articles \(ZammadAPI::Resources::TicketArticle\)/) end - # The one list in the gem read in a single request, because the endpoint - # it is declared against serves the whole thing: index_by_ticket iterates - # `ticket.articles` and renders them all, with no pagination to opt into. - # A guard used to sit here for a target that paged anyway, reading a total - # from a response header - a header Zammad sends from no endpoint, so it - # never once looked at a figure. it 'reads the whole list in one request' do stub_request(:get, articles_url).with(query: hash_including({})) .to_return(json_response([{ id: 1 }, { id: 2 }])) @@ -226,13 +220,13 @@ expect(held.related.customer.id).to eq(9) end - it 'survives a write to an attribute no association resolves through' do + it 'is dropped by a write to any attribute' do held = ticket held.related.customer held.title = 'Renamed' held.related.customer - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.once + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice end it 'is dropped by assign_attributes touching a foreign key' do @@ -247,10 +241,6 @@ end end - # `related = ticket.related` is the natural thing to write before reading - # two associations. The record used to drop its proxy and build another, so - # everything under 'the memo' above held for a caller who asked the record - # again and for nobody who had kept what they were handed. describe 'a proxy the caller kept' do let(:related) { ticket.related } @@ -307,59 +297,12 @@ expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice end - it 'keeps its memo across a write no association resolves through' do + it 'fetches the target again after a write to any attribute' do related.customer ticket.title = 'Renamed' related.customer - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.once - end - - context 'when the record was destroyed' do - before do - stub_request(:delete, ticket_url).to_return(json_response({})) - related.customer - ticket.destroy - end - - it 'refuses a target it had already resolved' do - expect { related.customer } - .to raise_error(ZammadAPI::Error, 'ZammadAPI::Resources::Ticket 42 was destroyed, there is nothing to read customer from') - end - - it 'refuses a list, rather than requesting it for a record that is gone' do - expect { related.articles }.to raise_error(ZammadAPI::Error, /was destroyed/) - expect(a_request(:get, %r{ticket_articles/by_ticket})).not_to have_been_made - end - end - - # The write clears the memo, and the lookup that was already out then - # filled it again, with the record behind the value from before. A logger - # or a middleware of the caller's that reaches the record is enough, on - # one thread; so is a second thread. - context 'when the foreign key is written while a lookup is on the wire' do - before do - stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return do - ticket.customer_id = 9 - json_response({ id: 7 }) - end - end - - it 'answers that lookup with the record it asked for' do - expect(related.customer.id).to eq(7) - end - - it 'does not keep that answer for the record the key now names' do - related.customer - - expect(related.customer.id).to eq(9) - end - - it 'memoizes the lookup made after it' do - 3.times { related.customer } - - expect(a_request(:get, "#{users_url}/9").with(query: hash_including({}))).to have_been_made.once - end + expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice end it 'leaves the proxy of a copy to the copy' do @@ -372,56 +315,6 @@ end end - describe '.belongs_to_foreign_keys' do - it 'lists the keys a resource resolves associations through' do - expect(ZammadAPI::Resources::Ticket.belongs_to_foreign_keys) - .to include(:customer_id, :owner_id, :group_id, :state_id, :priority_id, :organization_id) - end - - it 'includes the ones inherited from Base' do - expect(ZammadAPI::Resources::Group.belongs_to_foreign_keys).to eq(%i[created_by_id updated_by_id]) - end - - # The list is built at the first write to an attribute and kept. An - # association declared after that was never in it, so a write to its - # foreign key left the record it had resolved in place. - context 'when an association is declared after the list was built' do - let(:resource) { Class.new(ZammadAPI::Resources::Base) { path 'api/v1/memberships' } } - - before { stub_const('Acme::Role', Class.new(ZammadAPI::Resources::Base) { path 'api/v1/roles' }) } - - def declare_role = resource.send(:belongs_to, :role, class_name: 'Acme::Role') - - it 'takes in its foreign key' do - resource.belongs_to_foreign_keys - declare_role - - expect(resource.belongs_to_foreign_keys).to eq(%i[created_by_id updated_by_id role_id]) - end - - it 'takes it in on a class that inherits the declaration' do - subclass = Class.new(resource) - subclass.belongs_to_foreign_keys - declare_role - - expect(subclass.belongs_to_foreign_keys).to include(:role_id) - end - - it 'drops what the association resolved when its foreign key is written' do - [5, 6].each do |id| - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/roles/#{id}").with(query: hash_including({})).to_return(json_response({ id: id })) - end - record = resource.from_response(unit_transport, id: 1, role_id: 5) - record.note = 'written before the declaration' - declare_role - record.related.role - record.role_id = 6 - - expect(record.related.role.id).to eq(6) - end - end - end - describe '#inspect' do it 'names the record and what can be reached from it' do expect(ticket.related.inspect) diff --git a/spec/unit/zammad_api/attribute_access_spec.rb b/spec/unit/zammad_api/attribute_access_spec.rb index d5a24f6..d53cc28 100644 --- a/spec/unit/zammad_api/attribute_access_spec.rb +++ b/spec/unit/zammad_api/attribute_access_spec.rb @@ -37,30 +37,6 @@ def initialize(attributes) it 'leaves keys alone that cannot become symbols' do expect(record_class.new(1 => 'one').attributes).to eq(1 => 'one') end - - # Symbolizing is what makes two keys one, and the value that came first - # was dropped without a word. - context 'with one attribute under two spellings' do - it 'refuses the pair rather than keeping whichever came last' do - expect { record_class.new('name' => 'Support', name: 'Sales') } - .to raise_error(ArgumentError, /attribute name was given twice, as "name" and as :name/) - end - - it 'refuses a pair inside a nested Hash' do - expect { record_class.new(preferences: { 'locale' => 'de', locale: 'en' }) } - .to raise_error(ArgumentError, /attribute locale was given twice/) - end - - it 'refuses a pair inside a Hash in an Array' do - expect { record_class.new(notes: [{ 'body' => 'a', body: 'b' }]) } - .to raise_error(ArgumentError, /attribute body was given twice/) - end - - it 'takes the same name at two depths, which is two attributes' do - expect(record_class.new('name' => 'Support', preferences: { name: 'Sales' }).attributes) - .to eq(name: 'Support', preferences: { name: 'Sales' }) - end - end end describe 'reading' do @@ -80,68 +56,12 @@ def initialize(attributes) expect(record.id).to eq(1) end - # The arguments were never looked at, so `record.name('Other')` answered - # with the name and changed nothing, where a reader written out raises. - context 'when a reader is given arguments' do - it 'raises ArgumentError, as a reader written out would' do - expect { record.name('Other') }.to raise_error(ArgumentError, /\Awrong number of arguments \(given 1, expected 0\)/) - end - - it 'counts them' do - expect { record.name(1, 2, 3) }.to raise_error(ArgumentError, /given 3, expected 0/) - end - - it 'counts keywords as the one Hash they arrive as' do - expect { record.name(to: 'Other') }.to raise_error(ArgumentError, /given 1, expected 0/) - end - - it 'says what the reader reads' do - expect { record.name('Other') }.to raise_error(ArgumentError, /name reads the attribute of that name and takes no arguments/) - end - - it 'does not point a record that takes no writes at a writer' do - expect { record.name('Other') }.to raise_error(ArgumentError) { expect(it.message).not_to include('name =') } - end - - it 'still reads with a block, which any method takes' do - expect(record.name { 'ignored' }).to eq('Support') - end - - it 'still raises NoMethodError for an attribute the record does not carry' do - expect { record.custom_field('x') }.to raise_error(NoMethodError, /undefined attribute custom_field/) - end - end - - # A reader used to answer nil here, which made a typo a silent nil that - # flowed on into whatever was written with it - and put respond_to? and - # the call itself at odds, since respond_to?(:custom_field) was false - # throughout. - it 'raises for an attribute the record does not carry' do - expect { record.custom_field }.to raise_error(NoMethodError, /undefined attribute custom_field/) - end - - it 'names the readers that tolerate an absent attribute' do - expect { record.custom_field }.to raise_error(NoMethodError, /fetch\(:custom_field, nil\)/) + it 'raises NoMethodError for an attribute the record does not carry' do + expect { record.custom_field }.to raise_error(NoMethodError, /undefined method 'custom_field'/) end - it 'says the record may be one Zammad served less of' do - expect { record.custom_field }.to raise_error(NoMethodError, /reduced object/) - end - - it 'lists what the record does carry, so the spelling can be compared' do - expect { record.custom_field }.to raise_error(NoMethodError, /carries id, name, preferences/) - end - - # A key that could not become a Symbol is left as it arrived, so sorting - # the keys themselves would raise from inside the message. - it 'lists mixed keys without raising from the message itself' do - expect { record_class.new(1 => 'one', 'name' => 'X').custom_field } - .to raise_error(NoMethodError, /carries 1, name/) - end - - it 'says so plainly for a record that carries nothing' do - expect { record_class.new({}).custom_field } - .to raise_error(NoMethodError, /carries no attributes at all/) + it 'raises NoMethodError for a reader given arguments' do + expect { record.name('Other') }.to raise_error(NoMethodError, /undefined method 'name'/) end it 'carries the name and the receiver a bare NoMethodError would' do @@ -219,42 +139,16 @@ def initialize(attributes) expect(record.fetch(:nope, 'fallback')).to eq('fallback') end - # Hash#fetch refuses a third argument, and so does this: collected with a - # splat and read as `default.first`, `fetch(:a, :b, :c)` - a multi-key read - # this has never been - was answered with `:b`. + it 'supports a block' do + expect(record.fetch(:nope) { |key| "no #{key}" }).to eq('no nope') + end + it 'refuses more than one fallback, the way Hash#fetch does' do expect { record.fetch(:nope, 'one', 'two') } .to raise_error(ArgumentError, 'wrong number of arguments (given 3, expected 1..2)') end - - # Hash#fetch warns and then ignores the default. Silently picking one of - # two fallbacks a caller cannot have meant to pass together is the same - # swallowed mistyped call the arity check above refuses. - # rubocop:disable Lint/UselessDefaultValueArgument -- the call under test - it 'says so when a block supersedes the default, the way Hash#fetch does' do - expect { record.fetch(:nope, 'fallback') { 'block' } } - .to output(/block supersedes default value argument/).to_stderr - end - - it 'still answers from the block when both were given' do - expect { expect(record.fetch(:nope, 'fallback') { 'block' }).to eq('block') }.to output.to_stderr - end - - # Hash#fetch names the line that made the call. A bare Kernel#warn named - # nothing at all - neither the call site nor the library it came from, - # which in an application with several such calls is everything the reader - # needs. `uplevel` supplies both that location and the `warning: ` prefix. - it 'names the line that made the call, the way Hash#fetch does' do - expect { record.fetch(:nope, 'fallback') { 'block' } } - .to output(/attribute_access_spec\.rb:\d+: warning: block supersedes/).to_stderr - end - # rubocop:enable Lint/UselessDefaultValueArgument end - # `record[:x] = v` reached method_missing as `:[]=`, which the writer branch - # took for an attribute called `[]` - it staged the index as the value, lost - # the write, and sent `{"[]": "x"}` on the next save. Ruby's operators end in - # `=` too, so `record <= 5` did the same for an attribute called `<`. describe '#[]=' do it 'goes through the same refusal a named writer does on a read-only record' do expect { record[:note] = 'x' }.to raise_error(NoMethodError, /attributes are read-only/) @@ -263,26 +157,6 @@ def initialize(attributes) it 'names the attribute that was tried, not the operator' do expect { record[:note] = 'x' }.to raise_error(NoMethodError, /tried to set note/) end - - # `[]=` is a defined method, so respond_to_missing? never sees it: a - # read-only record claimed the one writer it has while denying every named - # one, then raised when it was called - the invariant the writer branch of - # respond_to_missing? is conditional for. - it 'is not claimed by a record that would refuse it' do - expect(record).not_to respond_to(:[]=) - end - - it 'agrees with the named writers on the same record' do - expect(record.respond_to?(:[]=)).to eq(record.respond_to?(:name=)) - end - - # `respond_to?` takes either spelling and Ruby does not normalise the - # argument, so a Symbol-only comparison let the String fall through to the - # definition and answer true on a record that refuses every write. - it 'answers the same for the String spelling' do - # rubocop:disable-next Performance/StringIdentifierArgument -- the String spelling is the point - expect(record.respond_to?('[]=')).to eq(record.respond_to?(:[]=)) - end end describe 'a name that only looks like a writer' do @@ -442,64 +316,10 @@ def initialize(attributes) it 'hands #as_json a copy rather than the frozen attributes' do expect(record.as_json).not_to be_frozen end - - # ActiveSupport hands them to every object it serializes, a record - # inside a Hash or a collection included, and they were dropped: - # `user.as_json(except: [:password])` answered with the password. - context 'with the options an ActiveSupport encoder hands on' do - it 'leaves out what except: names' do - expect(record.as_json(except: [:preferences])).to eq(id: 1, name: 'Support') - end - - it 'keeps only what only: names' do - expect(record.as_json(only: [:id])).to eq(id: 1) - end - - it 'takes one name as well as a list' do - expect(record.as_json(except: :preferences)).to eq(id: 1, name: 'Support') - end - - # The attributes are keyed by Symbols, and a String matched none. - it 'takes a name given as a String' do - expect(record.as_json(except: ['preferences'])).to eq(id: 1, name: 'Support') - expect(record.as_json(only: %w[id name])).to eq(id: 1, name: 'Support') - end - - it 'reads only: where both are given, as ActiveSupport does' do - expect(record.as_json(only: [:id], except: [:id])).to eq(id: 1) - end - - it 'keeps nothing for an only: that names nothing' do - expect(record.as_json(only: [])).to eq({}) - end - - it 'returns every attribute for options that name neither, and for none' do - expect(record.as_json({})).to eq(record.to_h) - expect(record.as_json(nil)).to eq(record.to_h) - end - - it 'still hands over a copy' do - expect(record.as_json(only: [:preferences])[:preferences]).not_to be_frozen - end - - # The json gem raises for a keyword its generator does not know, so - # the two are applied and not handed on. - it 'leaves the same attributes out of #to_json' do - expect(JSON.parse(record.to_json(except: ['preferences']))).to eq('id' => 1, 'name' => 'Support') - expect(JSON.parse(record.to_json(only: [:id]))).to eq('id' => 1) - end - - it 'still hands #to_json the options that are the generator\'s' do - expect(record.to_json(only: [:id], space: ' ')).to eq('{"id": 1}') - end - end end # ActiveSupport gives every object a public `deep_dup`, and calls it on - # whatever a Hash or an Array holds. A private helper of that name here - # answered in its place, so `{ticket: ticket}.deep_dup` raised - # NoMethodError. It is not loaded here: what is asked is that the name is - # left to it. + # whatever a Hash or an Array holds. describe 'the names ActiveSupport gives every object' do it 'defines no deep_dup of its own' do expect(described_class.private_method_defined?(:deep_dup)).to be(false) diff --git a/spec/unit/zammad_api/attributes_spec.rb b/spec/unit/zammad_api/attributes_spec.rb deleted file mode 100644 index a63cd31..0000000 --- a/spec/unit/zammad_api/attributes_spec.rb +++ /dev/null @@ -1,115 +0,0 @@ -# frozen_string_literal: true - -require 'pp' -require 'yaml' - -RSpec.describe ZammadAPI::Attributes do - subject(:attributes) { described_class[plain].freeze } - - let(:plain) { { login: 'jane', password: 'hunter2', preferences: { api_key: 'k', locale: 'de' } } } - - it 'is a Hash, and equal to one holding the same' do - expect(attributes).to be_a(Hash).and eq(plain) - end - - it 'reads every value as it is' do - expect(attributes[:password]).to eq('hunter2') - end - - it 'prints with the value under every key that names a credential blanked' do - expect(attributes.inspect).to eq('{login: "jane", password: "[REDACTED]", preferences: {api_key: "[REDACTED]", locale: "de"}}') - end - - it 'prints the same way where it is written into a String' do - expect("#{attributes}").to eq(attributes.inspect) # rubocop:disable Style/RedundantInterpolation - end - - # pp prints a Hash pair by pair and does not ask it for inspect. The width - # keeps it on one line. - it 'is printed the same way by pp' do - expect(PP.pp(attributes, +'', 200)).to eq("#{attributes.inspect}\n") - end - - # What Ruby raises for a write quotes the Hash, which is why this class is. - it 'is quoted with its credentials blanked by the error for a write to it' do - expect { attributes[:vip] = true } - .to raise_error(FrozenError, %(can't modify frozen ZammadAPI::Attributes: #{attributes.inspect})) - end - - it 'converts to a plain Hash, which prints what it holds' do - expect(attributes.to_h).to be_an_instance_of(Hash).and(satisfy { it.inspect.include?('hunter2') }) - end - - it 'writes its values to JSON' do - expect(JSON.generate(attributes)).to eq(JSON.generate(plain)) - end - - # Every Hash a record holds is of this class, whatever it is inside of. - # Hash#to_h answers with a plain Hash holding what the receiver held, so - # the conversion stopped at the first nested Hash. - describe '#to_h' do - subject(:attributes) { ZammadAPI::DeepCopy.frozen_copy(plain, symbolize_keys: true) } - - let(:plain) { { login: 'jane', preferences: { locale: 'de', devices: [{ name: 'phone' }] }, roles: [{ name: 'Agent' }] } } - - def classes_in(value) - case value - when Hash then [value.class, *value.each_value.flat_map { classes_in(it) }] - when Array then value.flat_map { classes_in(it) } - else [] - end - end - - it 'holds a Hash of this class at every depth to begin with' do - expect(classes_in(attributes).uniq).to eq([described_class]) - end - - it 'is a plain Hash at every depth, inside an Array as well' do - expect(classes_in(attributes.to_h).uniq).to eq([Hash]) - end - - it 'holds what the attributes hold' do - expect(attributes.to_h).to eq(plain) - end - - it 'is the caller\'s own to modify, down to a String' do - copy = attributes.to_h - copy[:preferences][:devices] << { name: 'tablet' } - copy[:login] << '.doe' - - expect(attributes).to eq(plain) - end - - it 'is the same for a Hash read out of the attributes' do - expect(classes_in(attributes[:preferences].to_h).uniq).to eq([Hash]) - end - - it 'builds a plain Hash from the pairs a block answers, as Hash#to_h does' do - expect(attributes.to_h { |key, _| [key.to_s, key.size] }).to eq('login' => 5, 'preferences' => 11, 'roles' => 5) - end - - # The encoders that take the core types and nothing else go by the class - # of the object, and name the one they refuse. - context 'with a JSON encoder that takes nothing but the core types' do - it 'is refused as it stands, by the name of its class' do - expect { JSON.generate(attributes, strict: true) } - .to raise_error(JSON::GeneratorError, /ZammadAPI::Attributes not allowed in JSON/) - end - - it 'is written by JSON.generate with strict: true' do - expect(JSON.generate(attributes.to_h, strict: true)).to eq(JSON.generate(plain)) - end - - it 'is written by a JSON::Coder' do - expect(JSON::Coder.new.dump(attributes.to_h)).to eq(JSON.generate(plain)) - end - end - end - - # Psych tags a subclass of Hash with its class and refuses to load a tag - # it was not told of, so the YAML of a record's attributes would not load. - it 'is written to YAML as the mapping a Hash is, and loads as one' do - expect(attributes.to_yaml).to eq(plain.to_yaml) - expect(YAML.load(attributes.to_yaml, permitted_classes: [Symbol])).to eq(plain) - end -end diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index c505f01..ec11178 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require 'zammad_api/test' - RSpec.describe ZammadAPI::Client do let(:url) { "#{ClientHelper::BASE_URL}api/v1/users/1" } @@ -15,8 +13,6 @@ expect(described_class.new(url: 'http://zammad.test/', http_token: 'token')).to be_a(described_class) end - # A required keyword, this was Ruby's `ArgumentError: missing keyword`, - # past the rescue written for an incomplete configuration. it 'surfaces configuration errors' do expect { described_class.new(http_token: 'token') } .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') @@ -80,10 +76,7 @@ expect(described_class.from_env(http_token: 'passed in').config.http_token).to eq('passed in') end - # Only an empty variable counted as unset. One holding a space was taken - # for a value, took the place of the variable beside it, and was then - # read as no credential, or as a second one. - context 'with a variable that holds nothing but whitespace' do + context 'with a variable that is empty or only whitespace' do let(:environment) { { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' } } def from(variables) @@ -91,16 +84,12 @@ def from(variables) described_class.from_env end - [' ', "\t", "\n", " \r\n "].each do |blank| + ['', " \n"].each do |blank| it "reads ZAMMAD_TOKEN past a ZAMMAD_HTTP_TOKEN of #{blank.inspect}" do expect(from('ZAMMAD_HTTP_TOKEN' => blank).config.http_token).to eq('from-env') end end - it 'reads ZAMMAD_TOKEN past an empty ZAMMAD_HTTP_TOKEN, as it did' do - expect(from('ZAMMAD_HTTP_TOKEN' => '').config.http_token).to eq('from-env') - end - %w[ZAMMAD_USER ZAMMAD_PASSWORD ZAMMAD_OAUTH2_TOKEN].each do |name| it "does not take a #{name} of a space for a second way to authenticate" do expect(from(name => ' ').config.authentication_scheme).to eq(:http_token) @@ -117,12 +106,8 @@ def from(variables) expect { described_class.from_env }.to raise_error(ZammadAPI::ConfigurationError, /missing user in config/) end - it 'keeps the whitespace around a value that holds more than that' do - expect(from('ZAMMAD_HTTP_TOKEN' => " padded\n").config.http_token).to eq(" padded\n") - end - - it 'takes a variable with a byte that is not text for the value it is' do - expect(from('ZAMMAD_USER' => "j\xFFne", 'ZAMMAD_PASSWORD' => 'p', 'ZAMMAD_TOKEN' => ' ').config.authentication_scheme).to eq(:basic) + it 'strips the whitespace around a token that holds more than that' do + expect(from('ZAMMAD_HTTP_TOKEN' => " padded\n").config.http_token).to eq('padded') end it 'still takes a password of spaces that is passed in' do @@ -132,9 +117,6 @@ def from(variables) end end - # A credential is read in a fixed order, so a plain merge left the - # environment's token in charge of a client that was handed another way to - # authenticate - and nothing said so. context 'when an argument names another way to authenticate' do before do stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' }) @@ -162,8 +144,6 @@ def from(variables) end end - # Two ways to authenticate in the environment, and nothing passed in to - # say which is meant. it 'refuses an environment that sets more than one way to authenticate' do stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 't', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'p' }) @@ -285,9 +265,6 @@ def from(variables) end end - # A proxy is Enumerable over every record of its kind, so the readers are - # plural. The singular names are what they were called in 1.x, when a proxy - # was only a dispatcher for find and create, and they are gone. describe 'the singular names the readers had in 1.x' do %i[group organization ticket ticket_article ticket_priority ticket_state user].each do |old_name| it "does not answer ##{old_name}" do @@ -324,9 +301,6 @@ def from(variables) expect { unit_client.resource(:unicorn) }.to raise_error(/available resources are: groups, organizations/) end - # The way to the parts of the API this gem does not model: 1.x reached any - # subclass of Base through const_get, 2.0 closed that, and raw requests - # were all that was left. context 'with a resource class a caller declared' do let(:client) { unit_client } let(:roles_url) { "#{ClientHelper::BASE_URL}api/v1/roles" } @@ -398,16 +372,11 @@ def from(variables) .to raise_error(ArgumentError, /resource takes the name of a resource or a subclass of ZammadAPI::Resources::Base, and String is neither/) end - # Reported by the call that named the class, not by its first request. it 'refuses a resource class that declares no path' do stub_const('Pathless', Class.new(ZammadAPI::Resources::Base)) expect { client.resource(Pathless) }.to raise_error(ZammadAPI::Error, /Pathless does not declare an API path/) end - - it 'names the class in the hint a collection gives for a lookup by id' do - expect { client.resource(Role).all.find(1) }.to raise_error(ArgumentError, /client\.resource\(Role\)\.find\(1\)/) - end end it 'raises for a singular name from 1.x' do @@ -482,8 +451,6 @@ def from(variables) expect(stub).to have_been_requested end - # Faraday lets an absolute URL replace the instance URL and still sends - # the client's headers, so this handed the access token to another host. it 'refuses an absolute URL rather than sending the credentials to another host' do expect { client.get('https://other.example/collect') } .to raise_error(ArgumentError, /a request path is relative to the instance URL/) @@ -504,17 +471,8 @@ def from(variables) expect { client.get('/https://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) end - # The guard asked for `://` after the scheme. Faraday 2.9.0 and 2.9.1 - # join such a path to the instance URL as URI does, which makes it an - # absolute URL with no host, and send the client's headers there. - ['http:/collect', 'HTTP:/collect', 'http:collect', '/http:/collect', 'file:/etc/hosts', 'api:v1/tickets'].each do |path| - it "refuses #{path}, which opens with a scheme and no host" do - expect { client.get(path) }.to raise_error(ArgumentError, /opens with a scheme, which makes it an absolute URL/) - end - end - - it 'reads such a path as URI does, which is what an older Faraday resolves it with' do - expect(URI('https://zammad.test/').merge('http:/collect').host).to be_nil + it 'refuses a path that opens with a scheme and no host' do + expect { client.get('http:/collect') }.to raise_error(ArgumentError, /absolute URL/) end it 'takes a colon after the first segment, which leaves the path relative' do @@ -540,141 +498,11 @@ def from(variables) .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('s3cret') } end - # A path is joined to the instance URL the way a link is resolved, so - # `..` climbs out of the sub-path a Zammad is served from, and the - # request went to whatever else the host serves with the token on it. - context 'with a path that climbs out of the instance URL' do - let(:client) { unit_client(url: 'http://zammad.test/helpdesk/') } - - before { stub_request(:any, /zammad\.test/).to_return(json_response({})) } - - it 'refuses it rather than sending the credentials to another application' do - expect { client.get('../billing/export') } - .to raise_error(ArgumentError, /holds a '\.\.' segment, which climbs out of it/) - end - - it 'makes no request for it' do - expect { client.get('../billing/export') }.to raise_error(ArgumentError) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - ['api/v1/../../../billing', 'api/v1/tickets/..', '..', '/../billing', '%2e%2e/billing', 'api/%2E%2e/x', 'api/.%2e/x'].each do |path| - it "refuses #{path}" do - expect { client.get(path) }.to raise_error(ArgumentError, /climbs out of it/) - end - end - - # An id is escaped into one segment, slashes included, and a segment - # that holds `..` among other things is not one that climbs. - it 'still sends a record id that was escaped into its segment' do - stub = stub_request(:get, 'http://zammad.test/helpdesk/api/v1/groups/1%2F..%2F..%2Fbilling').with(query: hash_including({})) - .to_return(json_response({ error: 'not found' }, status: 404)) - - expect { client.groups.find('1/../../billing') }.to raise_error(ZammadAPI::NotFoundError) - expect(stub).to have_been_requested - end - - it 'refuses it for every verb' do - %i[post put delete].each do |verb| - expect { client.public_send(verb, '../billing/export') }.to raise_error(ArgumentError, /climbs out of it/) - end - end - - it 'refuses it for a client whose instance is served from the root as well' do - expect { unit_client.get('api/v1/../../x') }.to raise_error(ArgumentError, /climbs out of it/) - end - - it 'does not quote the path it refuses, which may carry a secret' do - expect { client.get('../billing/export?token=s3cret') } - .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('s3cret') } - end - - ['api/v1/roles?path=../x', 'api/v1/roles#../x', 'api/v1/a..b', 'api/v1/.../x', './api/v1/roles', 'api/v1/..x'].each do |path| - it "takes #{path}, which holds two dots and no such segment" do - expect(client.get(path).status).to eq(200) - end - end - end - - # Faraday reads the path with URI, and URI raises an error of its own - # for one it cannot read: neither a ZammadAPI::Error nor the - # ArgumentError a path is documented to raise, and raised after the - # request had been logged. - describe 'a path that cannot be read as a URL' do - it 'refuses one holding a character outside ASCII' do - expect { client.get('api/v1/tägs') } - .to raise_error(ArgumentError, /this one cannot be read as one: it holds a character outside ASCII/) - end - - it 'refuses one holding a space' do - expect { client.get(' api/v1/roles') }.to raise_error(ArgumentError, /it holds a space, or another character a URL does not allow/) - end - - it 'refuses one holding a % that begins no escape' do - expect { client.get('api/v1/roles%zz') }.to raise_error(ArgumentError, /cannot be read as one/) - end - - it 'refuses one whose query string holds what a URL cannot' do - expect { client.get('api/v1/roles?name=prüfung') }.to raise_error(ArgumentError, /a character outside ASCII/) - end - - it 'says how to write it' do - expect { client.get('api/v1/tägs') }.to raise_error(ArgumentError, /a space is %20, and ä is %C3%A4 - or pass a parameter as query:/) - end - - it 'refuses a query string that names a parameter as two kinds of thing' do - expect { client.get('api/v1/roles?a=1&a[b]=2') } - .to raise_error(ArgumentError, /the query string written into this request path cannot be read as parameters/) - end - - it 'does not quote the path, which may carry a secret' do - expect { client.get('api/v1/ro les?token=s3cret') } - .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('s3cret') } - end - - # Ruby attaches the error a rescue raised in to the one it raises, - # and prints it with it. URI's quotes the path. - it 'does not carry the error that quotes the path along as its cause' do - expect { client.get('api/v1/ro les?token=s3cret') }.to raise_error(ArgumentError) { |error| - expect(error.cause).to be_nil - expect(error.full_message(highlight: false)).not_to include('s3cret') - } - end + it 'sends a query string written into the path' do + stub = stub_request(:get, roles_url).with(query: { 'name' => 'prüfung', 'page' => '2' }).to_return(json_response([])) - it 'does not carry one along for a query string it cannot read either' do - expect { client.get('api/v1/roles?token=s3cret&token[b]=2') } - .to raise_error(ArgumentError) { |error| expect(error.cause).to be_nil } - end - - it 'refuses it for every verb' do - %i[post put delete].each do |verb| - expect { client.public_send(verb, 'api/v1/tägs') }.to raise_error(ArgumentError, /cannot be read as one/) - end - end - - it 'makes no request and leaves no log line for one' do - log = StringIO.new - logged = unit_client(logger: Logger.new(log, level: Logger::DEBUG)) - stub_request(:any, /zammad\.test/) - - expect { logged.get('api/v1/tägs') }.to raise_error(ArgumentError) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - expect(log.string).to be_empty - end - - it 'still sends the same path percent-encoded' do - stub = stub_request(:get, 'http://zammad.test/api/v1/t%C3%A4gs').to_return(json_response([])) - - client.get('api/v1/t%C3%A4gs') - expect(stub).to have_been_requested - end - - it 'still sends a query string written into the path' do - stub = stub_request(:get, roles_url).with(query: { 'name' => 'prüfung', 'page' => '2' }).to_return(json_response([])) - - client.get('api/v1/roles?name=pr%C3%BCfung&page=2') - expect(stub).to have_been_requested - end + client.get('api/v1/roles?name=pr%C3%BCfung&page=2') + expect(stub).to have_been_requested end it 'keeps a protocol-relative path on the instance' do @@ -684,13 +512,6 @@ def from(variables) expect(stub).to have_been_requested end - it 'still sends a path that merely contains a colon' do - stub = stub_request(:get, 'http://zammad.test/api/v1/tags:search').to_return(json_response([])) - - client.get('api/v1/tags:search') - expect(stub).to have_been_requested - end - it 'passes query parameters' do stub = stub_request(:get, roles_url).with(query: { 'active' => 'true' }).to_return(json_response([])) @@ -716,8 +537,6 @@ def from(variables) expect(stub).to have_been_requested end - # An escape hatch that cannot set a header does not reach an endpoint - # that needs one. it 'sends the headers it was given' do stub = stub_request(:get, roles_url) .with(headers: { 'Accept-Language' => 'de-de' }) @@ -727,7 +546,7 @@ def from(variables) expect(stub).to have_been_requested end - it 'stringifies a header value the wire could not carry' do + it 'sends a header value that is not a String as text' do stub = stub_request(:get, roles_url) .with(headers: { 'X-Retry' => '3' }) .to_return(json_response([])) @@ -736,46 +555,6 @@ def from(variables) expect(stub).to have_been_requested end - # Faraday's authorization middleware leaves a header that is already set - # alone, so this would have replaced the client's own credentials - - # quietly, while #inspect went on reporting the scheme it was built with. - it 'refuses to replace the configured authentication' do - expect { client.get('api/v1/roles', headers: { 'Authorization' => 'Token other' }) } - .to raise_error(ArgumentError, /header authorization is set by this client/) - end - - it 'names the option that does mean it' do - expect { client.get('api/v1/roles', headers: { 'Authorization' => 'Token other' }) } - .to raise_error(ArgumentError, /pass http_token:, oauth2_token:, or user: and password:/) - end - - it 'refuses the From header that on_behalf_of owns' do - expect { client.get('api/v1/roles', headers: { from: 'agent@example.com' }) } - .to raise_error(ArgumentError, /use client\.on_behalf_of/) - end - - it 'refuses a nil header value rather than sending an empty one' do - expect { client.get('api/v1/roles', headers: { 'X-Trace' => nil }) } - .to raise_error(ArgumentError, /header x-trace is nil/) - end - - it 'refuses a header value that is not text' do - expect { client.get('api/v1/roles', headers: { 'X-Trace' => ['a'] }) } - .to raise_error(ArgumentError, /a header is always text/) - end - - # HTTP reads the two names as one header, so a merge would send whichever - # Hash order put last and drop the other without a word. - it 'refuses two spellings of one header' do - expect { client.get('api/v1/roles', headers: { 'Accept-Language' => 'de', 'accept-language' => 'en' }) } - .to raise_error(ArgumentError, /header accept-language was given twice/) - end - - it 'makes no request for a header it refuses' do - expect { client.get('api/v1/roles', headers: { 'X-Trace' => nil }) }.to raise_error(ArgumentError) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - it 'raises the mapped error class' do stub_request(:get, roles_url).to_return(json_response({ error: 'nope' }, status: 403)) @@ -789,13 +568,11 @@ def from(variables) .to raise_error(ZammadAPI::ServerError, "Can't GET api/v1/roles: HTTP 500") end - # The path names the request in every error it raises, and a query - # written into it went along: a token in an exception report. - it 'names it without a credential in a query written into the path' do + it 'leaves a query string written into the path out of the error message' do stub_request(:get, roles_url).with(query: hash_including({})).to_return(json_response({}, status: 500)) expect { client.get('api/v1/roles?token=path-s3cret&page=2') } - .to raise_error(ZammadAPI::ServerError, "Can't GET api/v1/roles?token=[REDACTED]&page=2: HTTP 500") + .to raise_error(ZammadAPI::ServerError, "Can't GET api/v1/roles: HTTP 500") end it 'hands back a non-JSON body untouched' do @@ -886,8 +663,6 @@ def from(variables) end end - # The scope is set after the caller's headers, so a request cannot take the - # header out from under the client that was scoped. it 'keeps the on_behalf_of scope alongside a caller header' do stub = stub_request(:get, roles_url) .with(headers: { 'From' => 'agent@example.com', 'X-Trace' => 'abc' }) @@ -938,62 +713,26 @@ def from(variables) .to have_been_made.twice end - # `client.on_behalf_of(user)` built a client whose From header carried - # the record as it prints. - describe 'the record of a user where its login belongs' do - let(:user) { unit_client.users.find(1) } + it 'takes a user id' do + stub = stub_request(:get, url).with(query: hash_including({}), headers: { 'From' => '7' }).to_return(json_response({ id: 1 })) + unit_client.on_behalf_of(7).users.find(1) - it 'is refused by its class, without printing it' do - expect { unit_client.on_behalf_of(user) } - .to raise_error(ArgumentError, /and was given ZammadAPI::Resources::User: .* pass its id\.\z/) { |error| - expect(error.message).not_to include('#<') - } - end + expect(stub).to have_been_requested + end - it 'is what its id is taken from' do - expect(unit_client.on_behalf_of(user.id).inspect).to include('on_behalf_of="1"') - end + it 'strips whitespace around the identifier' do + stub = stub_request(:get, url).with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }).to_return(json_response({ id: 1 })) + unit_client.on_behalf_of(" agent@example.com\n").users.find(1) + + expect(stub).to have_been_requested end - # Zammad skips a From header with nothing in it, and a nil sent none, so - # each of these handed back a client that ran every request as the - # account it authenticates as - with no error to say the scope was gone. describe 'an identifier that names nobody' do - [nil, '', ' ', "\t\n", "\u00A0", "\u3000"].each do |blank| + [nil, '', ' ', "\t\n"].each do |blank| it "refuses #{blank.inspect}" do expect { unit_client.on_behalf_of(blank) } - .to raise_error(ArgumentError, /on_behalf_of needs the login, email address or id of a user, and was given #{Regexp.escape(blank.inspect)}/) - end - end - - # Client.build takes anything with a transport's interface. One whose - # with_on_behalf_of stores what it is given would otherwise send an - # empty From header. - it 'refuses one through a transport that does not check it' do - storing = Class.new do - attr_reader :on_behalf_of - - def initialize(on_behalf_of = nil) = @on_behalf_of = on_behalf_of - def with_on_behalf_of(identifier) = self.class.new(identifier) - end - client = described_class.build(unit_client.config, storing.new) - - expect { client.on_behalf_of("\u00A0") }.to raise_error(ArgumentError, /on_behalf_of needs the login/) - end - - it 'hands such a transport the scope as the text the header carries' do - storing = Class.new do - attr_reader :on_behalf_of - - def initialize(on_behalf_of = nil) = @on_behalf_of = on_behalf_of - def with_on_behalf_of(identifier) = self.class.new(identifier) + .to raise_error(ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{blank.inspect}") end - - expect(described_class.build(unit_client.config, storing.new).on_behalf_of(7).inspect).to include('on_behalf_of="7"') - end - - it 'says what the request would have run as' do - expect { unit_client.on_behalf_of(nil) }.to raise_error(ArgumentError, /performed as the account this client authenticates as/) end it 'refuses it before the block is run' do @@ -1002,13 +741,6 @@ def with_on_behalf_of(identifier) = self.class.new(identifier) expect(ran).to be(false) end - - it 'still takes a user id' do - stub = stub_request(:get, url).with(query: hash_including({}), headers: { 'From' => '7' }).to_return(json_response({ id: 1 })) - unit_client.on_behalf_of(7).users.find(1) - - expect(stub).to have_been_requested - end end describe 'block form' do @@ -1059,8 +791,6 @@ def with_on_behalf_of(identifier) = self.class.new(identifier) .to raise_error(ZammadAPI::ConfigurationError, /positive number/) end - # Merged beside the token it was meant to replace, the new credential was - # never sent: the derived client went on acting as the old account. context 'when it names another way to authenticate' do it 'switches to an OAuth2 token' do expect(unit_client.with(oauth2_token: 'x').config.authentication_scheme).to eq(:oauth2_token) @@ -1166,66 +896,12 @@ def with_on_behalf_of(identifier) = self.class.new(identifier) expect(unit_client(http_token: 'super-secret').inspect).not_to include('super-secret') end - # A scoped client printed as the one it was derived from, so nothing in a - # log told the two apart. it 'shows the user a scoped client acts for' do expect(unit_client.on_behalf_of('agent@example.com').inspect) .to eq('#') end - - # They used to be sent in place of the configured token, while this went - # on reporting auth=http_token. - it 'cannot be built from a url that carries credentials, so it never reports a scheme it does not use' do - expect { unit_client(url: 'https://admin:url-s3cret@zammad.example.com/') } - .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials of its own/) - end - end - - # ActiveSupport serializes an object as its instance variables. For a - # client that was the configuration and the transport, credentials - # included, and then every record of every resource: a proxy is - # Enumerable, which is serialized as its elements. It is not loaded here: - # what is asked is what it asks, and that the answer is this class's own. - describe 'serializing as JSON' do - it 'answers as_json itself, where ActiveSupport would answer for any object' do - expect(described_class.instance_method(:as_json).owner).to be(described_class) - end - - it 'is the url and the auth scheme' do - expect(unit_client.as_json).to eq({ url: 'http://zammad.test/', auth: :http_token }) - end - - it 'names the user a scoped client acts for' do - expect(unit_client.on_behalf_of('agent@example.com').as_json).to include(on_behalf_of: 'agent@example.com') - end - - it 'writes that as a JSON object' do - expect(unit_client.to_json).to eq('{"url":"http://zammad.test/","auth":"http_token"}') - end - - it 'does not leak the token' do - expect(unit_client(http_token: 'super-secret').to_json).not_to include('super-secret') - end - - it 'stays that nested inside another structure' do - expect(JSON.generate(event: 'sync', client: unit_client(http_token: 'super-secret'))) - .to eq('{"event":"sync","client":{"url":"http://zammad.test/","auth":"http_token"}}') - end - - it 'makes no request' do - unit_client.to_json - - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'does not ask the transport, which may be the test kit\'s' do - expect(ZammadAPI::Test.new.client.as_json).to eq({ url: 'https://zammad.test/', auth: :http_token }) - end end - # A proxy holds nothing but the client's transport and the resource class, - # and `client.tickets` is the idiom every call starts with - each one used to - # allocate a fresh one. describe 'resource proxies' do subject(:client) { unit_client } @@ -1235,11 +911,6 @@ def with_on_behalf_of(identifier) = self.class.new(identifier) expect(client.tickets).to be(first) end - # Built up front rather than memoized on first use. A client is documented - # as immutable once built and safe to share between threads without - # locking, and a memo filled in by the first `client.tickets` in each worker - # is a write to shared state - harmless under CRuby's GVL, but not the - # contract that was written down. it 'is not mutated by reading a proxy off it' do before_read = client.instance_variable_get(:@resources) client.tickets @@ -1259,8 +930,6 @@ def with_on_behalf_of(identifier) = self.class.new(identifier) expect(client.tickets).not_to be(client.users) end - # The cache belongs to one transport, so a derived client must not be - # handed proxies still wired to the transport it was derived from. it 'does not carry a proxy over to an on_behalf_of client' do expect(client.on_behalf_of('agent@example.com').tickets).not_to be(client.tickets) end @@ -1269,8 +938,6 @@ def with_on_behalf_of(identifier) = self.class.new(identifier) expect(client.with(timeout: 5).tickets).not_to be(client.tickets) end - # The point of not sharing the cache: a proxy from the derived client has - # to send that client's From header, not the original's. it 'gives a derived client a proxy that carries its own scope' do stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/1") .with(query: hash_including({})).to_return(json_response({ id: 1 })) diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb index 8e7d413..e2e5165 100644 --- a/spec/unit/zammad_api/collection_spec.rb +++ b/spec/unit/zammad_api/collection_spec.rb @@ -7,8 +7,7 @@ let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } # What a collection over this endpoint fetches per request when nothing asks - # for another size: as many as the endpoint serves. Read off the resource - # rather than written out, so that these stubs follow the declaration. + # for another size: as many as the endpoint serves. def default_per_page = ZammadAPI::Resources::Group.page_limit def stub_page(page, records, per_page: default_per_page) @@ -17,20 +16,11 @@ def stub_page(page, records, per_page: default_per_page) .to_return(json_response(records)) end - # The walk asks for another page only after a full one, so anything about - # walking needs a page of the size that was requested. + # The walk asks for another page only after a full one. def full_page(first_id = 1) Array.new(default_per_page) { { id: first_id + it } } end - # A short page cannot be told apart from one the server shrank, so the walk - # confirms the end with one more request. Stubbing that empty page is what a - # collection that fits in a single page looks like from out here. - def stub_last_page(page, records, per_page: default_per_page) - stub_page(page, records, per_page: per_page) - stub_page(page + 1, [], per_page: per_page) - end - # Mirrors Zammad's CanPaginate::Pagination: the endpoint reduces per_page to # its own maximum and pages by that reduced size. def stub_capped_endpoint(url, total:, max:) @@ -54,11 +44,11 @@ def stub_capped_endpoint(url, total:, max:) expect(collection.map(&:id)).to eq((1..(default_per_page + 1)).to_a) end - it 'confirms the end of a short first page rather than assuming it' do - stub_last_page(1, [{ id: 1 }]) + it 'stops on a short first page without asking for the next' do + stub_page(1, [{ id: 1 }]) expect(collection.map(&:id)).to eq([1]) - expect(a_request(:get, url).with(query: hash_including('page' => '2'))).to have_been_made + expect(a_request(:get, url).with(query: hash_including('page' => '2'))).not_to have_been_made end it 'stops on a page shorter than the one the endpoint has been serving' do @@ -69,12 +59,6 @@ def stub_capped_endpoint(url, total:, max:) expect(a_request(:get, url).with(query: hash_including('page' => '3'))).not_to have_been_made end - it 'walks an endpoint that serves a smaller page than it was asked for' do - stub_capped_endpoint(url, total: 120, max: 50) - - expect(collection.map(&:id)).to eq((1..120).to_a) - end - it 'stops on an empty page' do stub_page(1, full_page) stub_page(2, []) @@ -128,7 +112,7 @@ def stub_capped_endpoint(url, total:, max:) .to_return(json_response(full_page)) expect { collection.to_a } - .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) + .to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1, so the endpoint is ignoring the page parameter/) end it 'keeps walking records that carry no id' do @@ -158,34 +142,7 @@ def stub_capped_endpoint(url, total:, max:) expect(seen).to eq(default_per_page) end - # The guard compares the decoded payload, not the bytes it arrived as. - # Hashing raw_body is cheaper and looks equivalent - identical bytes do - # mean identical records - but the implication that matters runs the other - # way: an endpoint that ignores `page` and re-serializes the same records - # with a different key order produces different bytes every time, so the - # guard never fires. Every page is full, so neither the short-page break - # nor the total break fires either, and the walk never ends. - it 'raises PaginationError when a repeated page is re-serialized differently' do - forwards = Array.new(default_per_page) { { id: it, name: "a#{it}" } } - backwards = forwards.map { { name: it[:name], id: it[:id] } } - # Every page differs from the one before it in bytes and from none of - # them in records, which a fixed sequence cannot express: WebMock repeats - # its last response, so two pages running would come back byte-identical - # and a byte digest would catch them one page later. - order = [forwards, backwards].cycle - stub_request(:get, url).with(query: hash_including({})).to_return { json_response(order.next) } - - # Bounded, because what this guards against is a walk that never ends - # rather than one that ends wrongly - unbounded, a regression here hangs - # the suite instead of failing it. - expect { Timeout.timeout(5) { collection.to_a } } - .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) - end - - # A job that writes to the records it is handed changes what they - # serialize as, so the page an endpoint repeats is never the same payload - # twice. Compared by payload the guard never fired: every page was full, - # and the job went round the same records for as long as it ran. + # Pages are compared by the ids they hold, not by their payload. it 'raises PaginationError when a repeated page comes back with its records changed' do round = 0 stub_request(:get, url).with(query: hash_including({})).to_return do @@ -200,20 +157,6 @@ def stub_capped_endpoint(url, total:, max:) expect(batches).to eq(1) end - # A search sorts by updated_at, so the write that changes a record's - # payload moves it within the page as well. - it 'raises PaginationError when a repeated page comes back changed and in another order' do - round = 0 - stub_request(:get, url).with(query: hash_including({})).to_return do - round += 1 - page = Array.new(default_per_page) { { id: it + 1, note: "round #{round}" } } - json_response(round.odd? ? page : page.reverse) - end - - expect { Timeout.timeout(5) { collection.to_a } } - .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) - end - it 'does not take two pages that share some of their records for a repeat' do stub_page(1, full_page) stub_page(2, full_page(2)) @@ -230,95 +173,12 @@ def stub_capped_endpoint(url, total:, max:) .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) end - # A page that repeats the one before it is what an endpoint serves that - # ignores `page`, and also what one serves that pages as it should, where - # the list grew at its front by exactly a page between the two requests. - # The page before, asked for again, tells the two apart. - describe 'a page that repeats the one before it' do - # A list served newest first, paged as Zammad pages it. - def stub_list(url, list) - asked = [] - stub_request(:get, url).with(query: hash_including({})).to_return do |request| - params = URI.decode_www_form(URI(request.uri).query).to_h - page = Integer(params['page']) - size = Integer(params['per_page']) - asked << page - json_response(list[(page - 1) * size, size].to_a.map { { id: it } }) - end - asked - end - - def walk(list, of:, grows_by:) - seen = [] - collection.in_batches(of: of) do |batch| - list.unshift(*grows_by) if seen.empty? - seen.concat(batch.map(&:id)) - end - seen - end - - it 'reads on where the list grew by a page between two requests' do - list = [5, 4, 3, 2, 1] - stub_list(url, list) - - expect(walk(list, of: 1, grows_by: [6])).to eq([5, 4, 3, 2, 1]) - end - - it 'hands the page that repeated over once' do - list = [6, 5, 4, 3, 2, 1] - stub_list(url, list) - - expect(walk(list, of: 2, grows_by: [8, 7])).to eq([6, 5, 4, 3, 2, 1]) - end - - it 'asks for the page before once more to tell, and goes on from the page after' do - list = [3, 2, 1] - asked = stub_list(url, list) - walk(list, of: 1, grows_by: [4]) - - expect(asked).to eq([1, 2, 1, 3, 4, 5]) - end - - it 'ends where the page after the repeated one is empty' do - list = [2, 1] - stub_list(url, list) - - expect(walk(list, of: 2, grows_by: [4, 3])).to eq([2, 1]) - end - - it 'asks an endpoint that ignores the page parameter once more before it raises' do - stub_request(:get, url).with(query: hash_including({})).to_return(json_response(full_page)) - - expect { collection.to_a }.to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1/) - expect(a_request(:get, url).with(query: hash_including('page' => '1'))).to have_been_made.twice - expect(a_request(:get, url).with(query: hash_including('page' => '2'))).to have_been_made.once - end - - # The list has to move back for the page before to hold what it held, - # so one that moves on by a page a second time, while the walk is - # asking, repeats a page twice over and is still read to its end. - it 'reads on where the list grew by a page twice running' do - list = [3, 2, 1] - grows = [[4], [5]] - stub_request(:get, url).with(query: hash_including({})).to_return do |request| - params = URI.decode_www_form(URI(request.uri).query).to_h - served = list[Integer(params['page']) - 1, 1].to_a - list.unshift(*grows.shift) - json_response(served.map { { id: it } }) - end - - expect(Timeout.timeout(5) { collection.in_batches(of: 1).to_a.flatten.map(&:id) }).to eq([3, 2, 1]) - end - end - - # The walk ran inside Kernel#loop, which rescues StopIteration for an - # enumerator driven by hand inside it. The block here is the caller's, and - # one raised from it was taken for the end of the walk: the rest of the - # records were dropped and `map` answered with the ones before it. + # The block is the caller's: a StopIteration raised from it is not the + # end of the walk. context 'when the block raises StopIteration' do let(:labels) { %w[x y].each } - before { stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) } + before { stub_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) } it 'raises it, as the same block over an Array does' do expect { collection.map { |group| [group.id, labels.next] } }.to raise_error(StopIteration) @@ -336,8 +196,6 @@ def walk(list, of:, grows_by:) end end - # What Enumerable does with a walk it has had enough of is not an error, - # and still ends it there. it 'still ends a walk that a break leaves early' do stub_page(1, full_page) @@ -357,7 +215,7 @@ def walk(list, of:, grows_by:) end it 'walks at the default page size without one' do - stub_last_page(1, [{ id: 1 }]) + stub_page(1, [{ id: 1 }]) ids = [] collection.find_each { ids << it.id } @@ -365,7 +223,7 @@ def walk(list, of:, grows_by:) end it 'takes the page size inline' do - stub_last_page(1, [{ id: 1 }], per_page: 50) + stub_page(1, [{ id: 1 }], per_page: 50) expect(collection.find_each(batch_size: 50).map(&:id)).to eq([1]) end @@ -376,20 +234,7 @@ def walk(list, of:, grows_by:) it 'rejects a non-positive page size' do expect { collection.find_each(batch_size: 0) { nil } } - .to raise_error(ArgumentError, 'batch_size needs a positive integer') - end - - # Re-sizing the page silently changed which records the collection held: - # page(3, per_page: 50) names records 101 to 150, and a batch_size of 10 turned - # that into records 21 to 30 with nothing said about it. - it 'refuses to re-size a collection already limited to a page' do - expect { collection.page(3, per_page: 50).find_each(batch_size: 10) { nil } } - .to raise_error(ArgumentError, /batch_size cannot be combined with page/) - end - - it 'says how to name the page it would have served' do - expect { collection.page(3, per_page: 50).find_each(batch_size: 10) { nil } } - .to raise_error(ArgumentError, /page\(3, per_page: 10\)/) + .to raise_error(ArgumentError, 'per_page needs to be a positive integer') end end @@ -404,7 +249,7 @@ def walk(list, of:, grows_by:) end it 'yields a whole page at the default size without one' do - stub_last_page(1, [{ id: 1 }, { id: 2 }]) + stub_page(1, [{ id: 1 }, { id: 2 }]) batches = [] collection.in_batches { batches << it.map(&:id) } @@ -412,9 +257,7 @@ def walk(list, of:, grows_by:) end # The batch is the block's own Array, and working it off with `shift` is - # an ordinary way to consume one. The walk used to read the size of that - # Array after the block returned, so a drained batch looked like an empty - # page and ended the walk. + # an ordinary way to consume one. it 'keeps walking when the block empties the batch it was handed' do stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) stub_page(2, [{ id: 3 }], per_page: 2) @@ -442,11 +285,6 @@ def walk(list, of:, grows_by:) expect(collection.in_batches).to be_a(Enumerator) end - it 'refuses to re-size a collection already limited to a page' do - expect { collection.page(3, per_page: 50).in_batches(of: 10) { nil } } - .to raise_error(ArgumentError, /of cannot be combined with page/) - end - it 'pulls one page per Enumerator#next' do stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) @@ -456,7 +294,7 @@ def walk(list, of:, grows_by:) it 'rejects a non-positive page size' do expect { collection.in_batches(of: 0) { nil } } - .to raise_error(ArgumentError, 'of needs a positive integer') + .to raise_error(ArgumentError, 'per_page needs to be a positive integer') end end @@ -481,7 +319,7 @@ def walk(list, of:, grows_by:) end it 'returns a new collection and leaves the original unpaged' do - stub_last_page(1, [{ id: 1 }]) + stub_page(1, [{ id: 1 }]) expect(collection.page(2)).not_to be(collection) expect(collection.map(&:id)).to eq([1]) @@ -496,11 +334,11 @@ def walk(list, of:, grows_by:) end it 'rejects a non-positive page size' do - expect { collection.page(1, per_page: 0) }.to raise_error(ArgumentError, 'per_page needs a positive integer') + expect { collection.page(1, per_page: 0) }.to raise_error(ArgumentError, 'per_page needs to be a positive integer') end it 'rejects a non-integer page size' do - expect { collection.page(1, per_page: '7') }.to raise_error(ArgumentError, 'per_page needs a positive integer') + expect { collection.page(1, per_page: '7') }.to raise_error(ArgumentError, 'per_page needs to be a positive integer') end end @@ -512,29 +350,19 @@ def walk(list, of:, grows_by:) expect(a_request(:get, url).with(query: hash_including('per_page' => '1000'))).to have_been_made end - it 'refuses a page larger than a generic index endpoint serves' do - expect { client.groups.all.page(1, per_page: 5000) } - .to raise_error(ArgumentError, /serves at most 1000 records per page/) - end + it 'clamps an explicit page to what a generic index endpoint serves' do + stub_page(2, [], per_page: 1000) - it 'refuses a page larger than the ticket index endpoint serves' do - expect { client.tickets.all.page(1, per_page: 5000) } - .to raise_error(ArgumentError, /serves at most 100 records per page/) + collection.page(2, per_page: 5000).to_a + expect(a_request(:get, url).with(query: hash_including('page' => '2', 'per_page' => '1000'))).to have_been_made end - it 'refuses a page larger than a search endpoint serves' do - expect { client.users.search('smith').page(1, per_page: 5000) } - .to raise_error(ArgumentError, /serves at most 200 records per page/) + it 'clamps an explicit page to what the ticket index endpoint serves' do + expect(client.tickets.all.page(3, per_page: 500).inspect).to include('page=3').and include('per_page=100') end - it 'names the page that would have been served instead' do - expect { client.tickets.all.page(3, per_page: 500) } - .to raise_error(ArgumentError, /page\(3, per_page: 500\) would be sent as page 3 of 100/) - end - - it 'names a page size the endpoint does serve' do - expect { client.tickets.all.page(3, per_page: 500) } - .to raise_error(ArgumentError, /Ask for page\(3, per_page: 100\) or fewer/) + it 'clamps an explicit page to what a search endpoint serves' do + expect(client.users.search('smith').page(1, per_page: 5000).inspect).to include('per_page=200') end it 'accepts a page exactly the size the endpoint serves' do @@ -548,16 +376,6 @@ def walk(list, of:, grows_by:) end end - it 'raises rather than building records out of a list of ids' do - stub_page(1, [1, 2, 3]) - - expect { collection.to_a } - .to raise_error(ZammadAPI::ParseError, /expected a JSON array of objects, got an array holding Integer/) - end - - # An index endpoint sorts and pages and does nothing else, so sorting has a - # name of its own. It was reached through `where`, which refused nearly - # everything else it was given. describe '#order' do def sorted_request(sort_by, order_by) a_request(:get, url).with(query: hash_including('sort_by' => sort_by, 'order_by' => order_by)) @@ -567,73 +385,41 @@ def sorted_request(sort_by, order_by) it 'sorts ascending by an attribute named on its own' do collection.order(:name).to_a - expect(sorted_request('name,id', 'asc,asc')).to have_been_made + expect(sorted_request('name', 'asc')).to have_been_made end it 'sorts the way a keyword says' do collection.order(name: :desc).to_a - expect(sorted_request('name,id', 'desc,asc')).to have_been_made + expect(sorted_request('name', 'desc')).to have_been_made end # Zammad pairs the two lists by position and skips an attribute that has # no direction, so each attribute is sent with one. it 'sorts by several attributes, each with a direction' do collection.order(:active, name: :desc).to_a - expect(sorted_request('active,name,id', 'asc,desc,asc')).to have_been_made + expect(sorted_request('active,name', 'asc,desc')).to have_been_made end it 'takes an attribute and a direction as strings' do - collection.order('active', 'name' => 'DESC').to_a - expect(sorted_request('active,name,id', 'asc,desc,asc')).to have_been_made + collection.order('active', 'name' => 'desc').to_a + expect(sorted_request('active,name', 'asc,desc')).to have_been_made end it 'sorts within an earlier order when chained' do collection.order(:active).order(name: :desc).to_a - expect(sorted_request('active,name,id', 'asc,desc,asc')).to have_been_made + expect(sorted_request('active,name', 'asc,desc')).to have_been_made + end + + it 'turns an attribute an earlier order named the way the later one says' do + collection.order(:name).order(name: :desc).to_a + expect(sorted_request('name', 'desc')).to have_been_made end it 'keeps the sort on every page it walks' do stub_request(:get, url).with(query: hash_including('page' => '1')).to_return(json_response(full_page)) collection.order(:name).to_a - expect(a_request(:get, url).with(query: hash_including('sort_by' => 'name,id', 'order_by' => 'asc,asc', 'page' => '2'))).to have_been_made - end - - # Zammad orders by the columns it is given and by nothing after them, and - # PostgreSQL does not hand rows that tie back in the same order from one - # LIMIT and OFFSET to the next. Seen against a Zammad that searches - # through SQL: 214 tickets sorted by state_id and walked ten at a time - # came back as 214 records and 151 tickets. - context 'with records that tie on what they are sorted by' do - it 'sorts them by id last, so that they keep one order from page to page' do - collection.order(:active).to_a - expect(sorted_request('active,id', 'asc,asc')).to have_been_made - end - - it 'does so for a single page, whose number means nothing otherwise' do - collection.order(:active).page(3, per_page: 10).to_a - expect(a_request(:get, url).with(query: hash_including('sort_by' => 'active,id', 'order_by' => 'asc,asc', 'page' => '3'))).to have_been_made - end - - it 'adds nothing to a sort by id' do - collection.order(id: :desc).to_a - expect(sorted_request('id', 'desc')).to have_been_made - end - - it 'adds nothing where id is named among the attributes, wherever it stands' do - collection.order(:id, name: :desc).to_a - expect(sorted_request('id,name', 'asc,desc')).to have_been_made - end - - it 'leaves a further order by id to the caller' do - collection.order(:active).order(id: :desc).to_a - expect(sorted_request('active,id', 'asc,desc')).to have_been_made - end - - it 'sends no sort for a collection that asked for none' do - collection.to_a - expect(a_request(:get, url).with(query: hash_including({})) { !it.uri.query.match?(/sort_by|order_by/) }).to have_been_made - end + expect(a_request(:get, url).with(query: hash_including('sort_by' => 'name', 'order_by' => 'asc', 'page' => '2'))).to have_been_made end it 'keeps the sort on an explicit page' do @@ -641,6 +427,11 @@ def sorted_request(sort_by, order_by) expect(sorted_request('name', 'asc').with(query: hash_including('page' => '2', 'per_page' => '10'))).to have_been_made end + it 'sends no sort for a collection that asked for none' do + collection.to_a + expect(a_request(:get, url).with(query: hash_including({})) { !it.uri.query.match?(/sort_by|order_by/) }).to have_been_made + end + it 'returns a new collection' do expect(collection.order(:name)).not_to be(collection) end @@ -662,37 +453,6 @@ def sorted_request(sort_by, order_by) expect { collection.order }.to raise_error(ArgumentError, /order needs at least one attribute to sort by/) end - it 'raises for an attribute named twice in one call' do - expect { collection.order(:name, name: :desc) }.to raise_error(ArgumentError, /order was given name twice/) - end - - it 'raises for an attribute the collection is already sorted by' do - expect { collection.order(:name).order(name: :desc) } - .to raise_error(ArgumentError, /order was given name, which this collection is already sorted by/) - end - - it 'raises for a direction that is neither asc nor desc' do - expect { collection.order(name: :down) } - .to raise_error(ArgumentError, /order sorts name either :asc or :desc, got :down/) - end - - # The spelling several other clients use. Read literally it sorts by an - # attribute called desc, which Zammad answers with a server error. - it 'raises for a direction written where an attribute belongs, and says how to write it' do - expect { collection.order(:name, :desc) } - .to raise_error(ArgumentError, /order reads :desc as an attribute to sort by.*order\(name: :desc\)/) - end - - # Several attributes go out as one comma-separated parameter. - it 'raises for a name that would be read as more than one attribute' do - expect { collection.order('name,id') } - .to raise_error(ArgumentError, /order needs the name of an attribute to sort by, got "name,id"/) - end - - it 'raises for something that is not a name at all' do - expect { collection.order(1) }.to raise_error(ArgumentError, /order needs the name of an attribute/) - end - # TicketsController#index and UsersController#index hardcode the order and # drop sort_by with everything else they do not read. context 'with an index endpoint that is always served in id order' do @@ -705,10 +465,6 @@ def sorted_request(sort_by, order_by) expect { client.users.all.order(:login) }.to raise_error(ArgumentError, %r{api/v1/users is always served}) end - it 'points at a search, which does sort' do - expect { client.tickets.all.order(:title) }.to raise_error(ArgumentError, /search\(term\)\.order\(\.\.\.\)/) - end - it 'makes no request' do expect { client.tickets.all.order(:title) }.to raise_error(ArgumentError) expect(a_request(:any, /zammad\.test/)).not_to have_been_made @@ -723,7 +479,7 @@ def sorted_request(sort_by, order_by) it 'sorts, though the index of the same resource does not' do client.tickets.search('printer').order(created_at: :desc).to_a - expect(a_request(:get, search_url).with(query: hash_including('query' => 'printer', 'sort_by' => 'created_at,id', 'order_by' => 'desc,asc'))) + expect(a_request(:get, search_url).with(query: hash_including('query' => 'printer', 'sort_by' => 'created_at', 'order_by' => 'desc'))) .to have_been_made end @@ -735,41 +491,29 @@ def sorted_request(sort_by, order_by) expect(a_request(:get, search_url).with(query: hash_including({})) { !it.uri.query.match?(/sort_by|order_by/) }).to have_been_made end end - - # Pointing at a search would send the caller in a circle where the - # resource has none. - it 'points at sort_by alone for an unsortable resource Zammad does not search' do - unsortable = Class.new(ZammadAPI::Resources::Base) do - path 'api/v1/things' - sortable false - end - - expect { ZammadAPI::ResourceProxy.new(unit_transport, unsortable).order(:name) } - .to raise_error(ArgumentError, /ignores sort_by, so order would hand back the records as they were\. Sort what this collection yields instead/) - end end describe '#pluck' do it 'returns one value per record for a single attribute' do - stub_last_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) expect(collection.pluck(:name)).to eq(%w[Users Support]) end it 'returns one array per record for several attributes' do - stub_last_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) expect(collection.pluck(:id, :name)).to eq([[1, 'Users'], [2, 'Support']]) end it 'accepts string keys' do - stub_last_page(1, [{ id: 1, name: 'Users' }]) + stub_page(1, [{ id: 1, name: 'Users' }]) expect(collection.pluck('name')).to eq(['Users']) end it 'yields nil for an attribute a record does not carry' do - stub_last_page(1, [{ id: 1 }]) + stub_page(1, [{ id: 1 }]) expect(collection.pluck(:name)).to eq([nil]) end @@ -797,11 +541,9 @@ def sorted_request(sort_by, order_by) expect(client.users.search('smith').count).to eq(4711) end - # model_index_render reads sort_by, order_by and the paging and drops - # every other parameter, so only_total_count means nothing to it, and - # there is no header to read a total from either. Probing anyway spent a - # request before the walk that had to happen regardless. - it 'walks an index endpoint rather than probing it for a total it cannot give' do + # An index drops only_total_count with every other parameter it does not + # read, so there is no total to ask it for. + it 'walks an index endpoint rather than asking it for a total' do stub_page(1, full_page) stub_page(2, [{ id: default_per_page + 1 }]) @@ -809,19 +551,6 @@ def sorted_request(sort_by, order_by) expect(a_request(:get, url).with(query: hash_including('only_total_count' => 'true'))).not_to have_been_made end - # A count is the one answer nothing downstream can sanity check: - # `Array.new(collection.count)` and `count.zero?` both take it at its word. - it 'walks rather than reporting a total that cannot describe a result' do - stub_request(:get, search_url).with(query: hash_including('page' => '1')) - .to_return(json_response([{ id: 1 }])) - stub_request(:get, search_url).with(query: hash_including('page' => '2')) - .to_return(json_response([])) - stub_request(:get, search_url).with(query: hash_including('only_total_count' => 'true')) - .to_return(json_response({ total_count: -3 })) - - expect(client.users.search('smith').count).to eq(1) - end - it 'walks the pages when a search endpoint answers with no total at all' do stub_request(:get, search_url).with(query: hash_including('page' => '1')) .to_return(json_response([{ id: 1 }])) @@ -844,10 +573,6 @@ def sorted_request(sort_by, order_by) expect(client.users.search('smith').count).to eq(1) end - # Not an endpoint Zammad has - all four search actions route through - # model_search_render, which reads only_total_count before it reads - # anything else - but something other than the endpoint can answer: a - # proxy error page, a login form, an HTML body with a 200 on it. it 'walks the pages when something answers with records instead of a total' do stub_request(:get, search_url).with(query: hash_including('page' => '1')) .to_return(json_response([{ id: 1 }, { id: 2 }])) @@ -866,162 +591,19 @@ def sorted_request(sort_by, order_by) end it 'counts matches when given a block' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + stub_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) expect(collection.count { it.id > 1 }).to eq(2) end - end - - describe '#size' do - it 'walks the pages, like #count' do - stub_last_page(1, [{ id: 1 }, { id: 2 }]) - expect(collection.size).to eq(2) - end + # Enumerable#each_slice asks for the size before it starts, and a size + # would be a count, which is a walk of its own. + it 'has no size, so each_slice reads the records once' do + stub_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - it 'asks a search endpoint for the total in one request' do - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/search") - .with(query: { 'expand' => 'true', 'query' => 'smith', 'only_total_count' => 'true' }) - .to_return(json_response({ total_count: 4711 })) - - expect(client.users.search('smith').size).to eq(4711) - end - - it 'is also spelled #length' do - stub_last_page(1, [{ id: 1 }]) - - expect(collection.length).to eq(1) - end - end - - # Enumerable#each_slice and #each_cons ask the receiver for its size before - # they start, and the size of a collection is a count of it. - describe '#each_slice' do - let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/users/search" } - - def requests_made = a_request(:get, url).with(query: hash_including({})) - - it 'yields the records in groups, the last one being what is left' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - groups = [] - collection.each_slice(2) { groups << it.map(&:id) } - expect(groups).to eq([[1, 2], [3]]) - end - - it 'walks the pages once' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - collection.each_slice(2) { nil } - expect(requests_made).to have_been_made.twice - end - - it 'fetches a page once' do - stub_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }], per_page: 3) - - collection.page(1, per_page: 3).each_slice(2) { nil } - expect(requests_made).to have_been_made.once - end - - it 'does not ask a search for its total' do - stub_request(:get, search_url).with(query: hash_including('page' => '1')).to_return(json_response([{ id: 1 }])) - stub_request(:get, search_url).with(query: hash_including('page' => '2')).to_return(json_response([])) - - client.users.search('smith').each_slice(2) { nil } - expect(a_request(:get, search_url).with(query: hash_including('only_total_count' => 'true'))).not_to have_been_made - end - - # The groups were cut to the count that came back first, so a list that - # grew between the two reads was handed over in groups of that many. - it 'groups the records it reads, whatever a read before it held' do - stub_request(:get, url).with(query: hash_including('page' => '1')) - .to_return(json_response([{ id: 1 }]), json_response([{ id: 1 }, { id: 2 }])) - stub_request(:get, url).with(query: hash_including('page' => '2')).to_return(json_response([])) - - groups = [] - collection.each_slice(5) { groups << it.map(&:id) } - expect(groups).to eq([[1]]) - end - - it 'returns the collection' do - stub_last_page(1, [{ id: 1 }]) - - expect(collection.each_slice(2) { nil }).to equal(collection) - end - - it 'returns an Enumerator without a block, and asks for nothing' do - expect(collection.each_slice(2)).to be_a(Enumerator) - expect(requests_made).not_to have_been_made - end - - it 'numbers the groups without counting the records' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - expect(collection.each_slice(2).with_index.map { |group, index| [index, group.size] }).to eq([[0, 2], [1, 1]]) - expect(requests_made).to have_been_made.twice - end - - it 'refuses a size that is not positive, with or without a block' do - expect { collection.each_slice(0) }.to raise_error(ArgumentError, 'invalid slice size') - expect { collection.each_slice(0) { nil } }.to raise_error(ArgumentError, 'invalid slice size') - end - end - - describe '#each_cons' do - def requests_made = a_request(:get, url).with(query: hash_including({})) - - it 'yields every run of records that follow one another' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - runs = [] - collection.each_cons(2) { runs << it.map(&:id) } - expect(runs).to eq([[1, 2], [2, 3]]) - end - - it 'walks the pages once' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - collection.each_cons(2) { nil } - expect(requests_made).to have_been_made.twice - end - - it 'returns the collection' do - stub_last_page(1, [{ id: 1 }]) - - expect(collection.each_cons(2) { nil }).to equal(collection) - end - - it 'returns an Enumerator without a block, and asks for nothing' do - expect(collection.each_cons(2)).to be_a(Enumerator) - expect(requests_made).not_to have_been_made - end - - it 'refuses a size that is not positive' do - expect { collection.each_cons(0) }.to raise_error(ArgumentError, 'invalid size') - end - end - - describe '#lazy' do - def requests_made = a_request(:get, url).with(query: hash_including({})) - - it 'stops the walk as soon as it has enough' do - stub_page(1, full_page) - - expect(collection.lazy.map(&:id).first(2)).to eq([1, 2]) - expect(requests_made).to have_been_made.once - end - - # A lazy enumerator answers size with its source's, which was the count. - it 'slices without counting the records first' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - expect(collection.lazy.each_slice(2).map { it.map(&:id) }.to_a).to eq([[1, 2], [3]]) - expect(requests_made).to have_been_made.twice - end - - it 'has no size to report' do - expect(collection.lazy.size).to be_nil - expect(requests_made).not_to have_been_made + expect(collection).not_to respond_to(:size) + expect(collection.each_slice(2).map { it.map(&:id) }).to eq([[1, 2], [3]]) + expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once end end @@ -1053,146 +635,18 @@ def requests_made = a_request(:get, url).with(query: hash_including({})) end end - # The question #empty? asks, in the words more often typed. They were - # Enumerable's, which starts a walk at the page size for walking and stops - # at the first record: up to a full page of expanded records fetched to - # learn whether there is one. - describe '#any? and #none?' do - context 'with a record at the endpoint' do - before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) } - - it 'answers any? with true' do - expect(collection.any?).to be(true) - end - - it 'answers none? with false' do - expect(collection.none?).to be(false) - end - - it 'asks for a single record to answer any?' do - collection.any? - - expect(a_request(:get, url).with(query: hash_including('per_page' => '1'))).to have_been_made.once - expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once - end - - it 'asks for a single record to answer none?' do - collection.none? - - expect(a_request(:get, url).with(query: hash_including('per_page' => '1'))).to have_been_made.once - expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once - end - - it 'leaves the page size alone on a collection limited to one page' do - collection.page(2, per_page: 5).any? - - expect(a_request(:get, url).with(query: hash_including('page' => '2', 'per_page' => '5'))).to have_been_made - end - end - - context 'with no record at the endpoint' do - before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) } - - it 'answers any? with false' do - expect(collection.any?).to be(false) - end - - it 'answers none? with true' do - expect(collection.none?).to be(true) - end - end - - # A block or a pattern asks about the records, and that is a walk. - context 'with a block or a pattern' do - before do - stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) - stub_page(2, []) - end - - it 'leaves any? with a block to Enumerable' do - expect(collection.any? { it.name == 'Support' }).to be(true) - expect(collection.any? { it.name == 'Sales' }).to be(false) - end - - it 'leaves none? with a block to Enumerable' do - expect(collection.none? { it.name == 'Sales' }).to be(true) - end - - it 'leaves a pattern to Enumerable' do - expect(collection.any?(ZammadAPI::Resources::Group)).to be(true) - expect(collection.none?(ZammadAPI::Resources::Group)).to be(false) - end - end - end - - # `take(n)` and `first(n)` ask one question. Enumerable answers both by - # taking records off the front of a page sized for walking, so with #first - # sizing its own page and this one left alone, what the same read cost - # depended on which word was typed. - describe '#take' do - it 'reads a page sized for what was asked for' do - stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) - - expect(collection.take(2).map(&:id)).to eq([1, 2]) - end - - it 'costs what the same read through #first costs' do - stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) - - collection.take(2) - expect(a_request(:get, url).with(query: hash_including('per_page' => '2'))).to have_been_made.once - end - - it 'walks when more records are asked for than the endpoint serves' do - stub_page(1, full_page) - stub_page(2, [{ id: default_per_page + 1 }]) - - expect(collection.take(default_per_page + 1).size).to eq(default_per_page + 1) - end - - it 'leaves a zero count to Enumerable' do - expect(collection.take(0)).to eq([]) - end - - # Enumerable#take always answers with an Array, where `first` reads a nil - # as "just the one" and answers with a record. - it 'refuses a nil the way Enumerable#take does' do - expect { collection.take(nil) }.to raise_error(TypeError, /no implicit conversion/) - end - - it 'reads on where the endpoint serves a smaller page than it was asked for' do - stub_capped_endpoint(url, total: 5, max: 2) - - expect(collection.take(5).map(&:id)).to eq([1, 2, 3, 4, 5]) - end - end - - # `find` on the proxy is the lookup by id, and Enumerable#find reads its - # argument as an ifnone callable - so `all.find(1)` answered with an - # Enumerator, made no request and raised nothing. + # `find` on the proxy is the lookup by id, so the collection refuses an id + # rather than reading it as Enumerable#find's ifnone callable. describe '#find' do it 'is Enumerable#find with a block' do - stub_last_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) expect(collection.find { it.name == 'Support' }.id).to eq(2) end - it 'refuses an id where a block belongs' do + it 'refuses an id where a block belongs, and names the lookup that takes one' do expect { collection.find(1) } - .to raise_error(ArgumentError, /find on a ZammadAPI::Collection is Enumerable#find, which takes a block/) - end - - it 'names the lookup that does take an id' do - expect { collection.find(1) }.to raise_error(ArgumentError, /client\.groups\.find\(1\)/) - end - - it 'names the resource the way a client does, for a multi-word one' do - expect { client.ticket_articles.all.find(7) } - .to raise_error(ArgumentError, /client\.ticket_articles\.find\(7\)/) - end - - it 'points at detect for the block form' do - expect { collection.find(1) }.to raise_error(ArgumentError, /detect \{ \.\.\. \}/) + .to raise_error(ArgumentError, 'find on a collection takes a block; look a record up by id with client..find(1)') end it 'makes no request for the id it refuses' do @@ -1205,9 +659,6 @@ def requests_made = a_request(:get, url).with(query: hash_including({})) end end - # Enumerable#first takes its records off the front of a page this collection - # sized for walking, so `all.first` downloaded a whole page to hand back one - # record. describe '#first' do it 'reads a page of one for a single record' do stub_page(1, [{ id: 1 }], per_page: 1) @@ -1235,38 +686,17 @@ def requests_made = a_request(:get, url).with(query: hash_including({})) end # The page size of a collection limited to one says which records it - # holds, so re-sizing it would move them - the same reason batch_size - # cannot be combined with page. + # holds, so re-sizing it would move them. it 'leaves a collection already limited to a page at its own size' do stub_page(3, [{ id: 5 }, { id: 6 }], per_page: 2) expect(collection.page(3, per_page: 2).first.id).to eq(5) end - it 'leaves a zero count to Enumerable' do - expect(collection.first(0)).to eq([]) - end - it 'makes no request for a zero count' do expect(collection.first(0)).to eq([]) expect(a_request(:any, /zammad\.test/)).not_to have_been_made end - - # Sizing the request rather than limiting the collection to one page: - # limited, this came back with whatever the first page held and nothing to - # say the rest were there to be read. - it 'reads on where the endpoint serves a smaller page than it was asked for' do - stub_capped_endpoint(url, total: 5, max: 2) - - expect(collection.first(5).map(&:id)).to eq([1, 2, 3, 4, 5]) - end - - it 'stops as soon as it has what it asked for' do - stub_capped_endpoint(url, total: 500, max: 2) - - expect(collection.first(3).map(&:id)).to eq([1, 2, 3]) - expect(a_request(:get, url).with(query: hash_including('page' => '3'))).not_to have_been_made - end end describe '#inspect' do @@ -1281,9 +711,7 @@ def requests_made = a_request(:get, url).with(query: hash_including({})) end # ObjectManagerAttributesController#index renders every attribute in one - # response and reads no parameter. Walked like a paged index, it was asked - # for page two, answered with the same list, and the guard against an - # endpoint that ignores `page` raised with every record already in hand. + # response and reads no parameter. describe 'an index that serves every record in one response' do subject(:collection) { client.resource(resource).all } @@ -1315,7 +743,7 @@ def self.name = 'ObjectAttribute' expect(a_request(:get, url).with(query: { 'expand' => 'true' })).to have_been_made.once end - context 'without the declaration' do + context 'without the declaration, and a list as long as a page' do let(:resource) do Class.new(ZammadAPI::Resources::Base) do def self.name = 'ObjectAttribute' @@ -1323,13 +751,11 @@ def self.name = 'ObjectAttribute' path 'api/v1/object_manager_attributes' end end + let(:records) { full_page } - it 'raises PaginationError, as for any endpoint that repeats a page' do - expect { collection.to_a }.to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1/) - end - - it 'says what to declare where the endpoint does serve every record' do - expect { collection.to_a }.to raise_error(ZammadAPI::PaginationError, /declare `paginated false` on the resource/) + it 'raises PaginationError, and says what to declare' do + expect { collection.to_a } + .to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1.*declare `paginated false` on the resource/) end end @@ -1375,15 +801,14 @@ def self.name = 'ObjectAttribute' # Every number would name the same records. it 'refuses a page' do - expect { collection.page(2) }.to raise_error(ArgumentError, /serves every record in one response and reads no page parameter/) + expect { collection.page(2) }.to raise_error(ArgumentError, /serves every record in one response, so it has no pages/) end it 'still refuses a page that is not a number first' do expect { collection.page(0) }.to raise_error(ArgumentError, /positive integer/) end - # Whether an index sorts is a declaration of its own, and sorts unless - # the resource says otherwise, as it does for an index that pages. + # Whether an index sorts is a declaration of its own. it 'sends a sort, and still no page' do collection.order(:name).to_a @@ -1412,30 +837,16 @@ def self.name = 'ObjectAttribute' end describe ZammadAPI::PaginationError do - def message(**) = described_class.build(operation: 'get .all of object', **).message - - it 'says what to declare for an index that repeats its first page' do - expect(message(page: 2, index: true)).to include('declare `paginated false` on the resource') - end + it 'names the page that repeated and what to declare for an endpoint that does not page' do + message = described_class.build(operation: 'get .all of object', page: 3).message - # An endpoint that served two different pages reads `page`. - it 'does not say so for a page further on' do - expect(message(page: 3, index: true)).not_to include('paginated false') - end - - it 'does not say so for a search, which always pages' do - expect(message(page: 2)).not_to include('paginated false') + expect(message).to include('page 3 repeated page 2').and include('declare `paginated false` on the resource') end end - # A walk stops on what the endpoint served, and the size it serves is - # learned from the first page rather than taken from `max_per_page`. Where - # the server's cap is lower than the request - a cap the gem's declaration - # has gone stale on - every page is short of what was asked for, and reading - # the requested size would make each one look like the last. # A search names the ids for a page and then loads the records by id, so an - # id whose record is gone by then leaves the page one short - on any page, - # not only the last. An index page is a single query and has no such gap. + # id whose record is gone by then leaves the page one short, on any page. + # A search is therefore walked on to an empty page. describe 'a search, which can serve a page short before the last one' do subject(:search) { client.users.search('smith') } @@ -1467,11 +878,7 @@ def hits(range) = range.map { { id: it } } expect(search.map(&:id)).to eq((1..(page_size * 2)).to_a) end - # The bare array is what a Zammad before 6.5.1 answers with, and it says - # nothing about how many hits there are. An empty page is then all there - # is to end on, hits behind it or not: see the next group for an endpoint - # that does say. - it 'ends on the empty page where the endpoint reports no total' do + it 'ends on an empty page' do stub_search_page(1, hits(1..3)) last = stub_search_page(2, []) stub_search_page(3, hits([4])) @@ -1487,13 +894,6 @@ def hits(range) = range.map { { id: it } } expect { search.to_a }.to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) end - # `paginated false` is a declaration about an index. Every search pages. - it 'does not suggest declaring the resource as not paginated' do - stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response(hits(1..3))) - - expect { search.to_a }.to raise_error(ZammadAPI::PaginationError) { |error| expect(error.message).not_to include('paginated false') } - end - it 'still reads only the one page a search was limited to' do stub_search_page(2, hits(1..3)) @@ -1501,308 +901,4 @@ def hits(range) = range.map { { id: it } } expect(a_request(:get, search_url).with(query: hash_including('page' => '3'))).not_to have_been_made end end - - # A page of a search can hold nothing with hits still behind it, for the - # reason it can come back short: every id the search named for it has lost - # its record. It takes one stale hit on the page of one that `first` and - # `empty?` ask for, and a search serves the newest first. A Zammad from 6.5.1 - # on reports the size of the whole result beside the page where it is asked - # to, which is what tells such a page from the end. - describe 'a search that reports its total beside each page' do - subject(:search) { client.users.search('smith') } - - let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/users/search" } - - def stub_counted_page(page, ids, total:) - stub_request(:get, search_url) - .with(query: hash_including('page' => page.to_s)) - .to_return(json_response({ records: ids.map { { id: it } }, total_count: total })) - end - - def walked_ids(per_page:) = search.find_each(batch_size: per_page).map(&:id) - - it 'asks for the total with every page of a walk' do - stub_counted_page(1, [1], total: 2) - stub_counted_page(2, [2], total: 2) - stub_counted_page(3, [], total: 2) - walked_ids(per_page: 1) - - expect(a_request(:get, search_url).with(query: hash_including('with_total_count' => 'true'))).to have_been_made.times(3) - end - - it 'reads the records out of the object the total arrives in' do - stub_counted_page(1, [1, 2, 3], total: 3) - stub_counted_page(2, [], total: 3) - - expect(search.map(&:id)).to eq([1, 2, 3]) - end - - it 'reads on past an empty page the total says has hits behind it' do - stub_counted_page(1, [1], total: 3) - stub_counted_page(2, [], total: 3) - stub_counted_page(3, [3], total: 3) - stub_counted_page(4, [], total: 3) - - expect(walked_ids(per_page: 1)).to eq([1, 3]) - end - - # Two empty pages hold the same nothing, and the guard against a page - # that repeats used to read that as an endpoint ignoring `page`. - it 'reads on past two empty pages in a row' do - stub_counted_page(1, [1], total: 4) - stub_counted_page(2, [], total: 4) - stub_counted_page(3, [], total: 4) - stub_counted_page(4, [4], total: 4) - stub_counted_page(5, [], total: 4) - - expect(walked_ids(per_page: 1)).to eq([1, 4]) - end - - it 'ends on an empty page once the pages read cover the total' do - stub_counted_page(1, [1, 2], total: 4) - last = stub_counted_page(2, [], total: 4) - stub_counted_page(3, [5], total: 4) - - expect(walked_ids(per_page: 2)).to eq([1, 2]) - expect(last).to have_been_requested.once - expect(a_request(:get, search_url).with(query: hash_including('page' => '3'))).not_to have_been_made - end - - # Elasticsearch stops counting at ten thousand hits and reports that as - # the total. A walk ended on the figure would stop there. - it 'does not end on the total while a page still holds records' do - stub_counted_page(1, [1], total: 2) - stub_counted_page(2, [2], total: 2) - stub_counted_page(3, [3], total: 2) - stub_counted_page(4, [], total: 2) - - expect(walked_ids(per_page: 1)).to eq([1, 2, 3]) - end - - it 'makes no more requests than the total has pages' do - (1..5).each { stub_counted_page(it, [], total: 3) } - - expect(walked_ids(per_page: 1)).to eq([]) - expect(a_request(:get, search_url).with(query: hash_including({}))).to have_been_made.times(3) - end - - it 'finds the first live hit behind a stale one' do - stub_counted_page(1, [], total: 3) - stub_counted_page(2, [2], total: 3) - - expect(search.first.id).to eq(2) - end - - it 'is not empty where the first hit is stale and the next is live' do - stub_counted_page(1, [], total: 3) - stub_counted_page(2, [2], total: 3) - - expect(search.empty?).to be(false) - end - - it 'is empty, in one request, where the stale hit was the only one' do - stub_counted_page(1, [], total: 1) - - expect(search.empty?).to be(true) - expect(a_request(:get, search_url).with(query: hash_including({}))).to have_been_made.once - end - - # `first` and `empty?` ask for a page of the size they want, and a search - # is read on past an empty one. Held to that size, the two cost a request - # for every stale hit in a row: five thousand of them for `empty?` on an - # instance whose index has drifted from its database. - describe 'read by first, behind hits that have lost their records' do - # A search over `hits`, of which `stale` have lost their record, served - # the way Zammad serves one: the ids for the page first, and then the - # records that are still there. Answers with every page it was asked - # for, as page and size. - # - # `serves` is a page size the endpoint holds to whatever it is asked - # for, paging by it. `window` is an Elasticsearch result window: a page - # that reaches past it is refused, and Zammad answers that as no hits - # and a total of nought. - def stub_search_over(hits, stale: [], serves: nil, window: nil) - asked = [] - stub_request(:get, search_url).with(query: hash_including({})).to_return do |request| - params = URI.decode_www_form(URI(request.uri).query).to_h - page = Integer(params['page']) - size = Integer(params['per_page']) - asked << [page, size] - next json_response({ records: [], total_count: 0 }) if window && page * size > window - - size = [size, serves].min if serves - json_response({ records: (Array(hits)[(page - 1) * size, size].to_a - Array(stale)).map { { id: it } }, total_count: Array(hits).size }) - end - asked - end - - it 'asks for a larger page after each empty one, starting where the last ended' do - asked = stub_search_over(1..32, stale: 1..32) - - expect(search.empty?).to be(true) - expect(asked).to eq([[1, 1], [2, 1], [2, 2], [2, 4], [2, 8], [2, 16]]) - end - - # A page that reaches past the total is one an index whose result - # window was lowered may refuse. - it 'asks for no page that reaches past the total the search reported' do - asked = stub_search_over(1..20, stale: 1..20) - search.empty? - - expect(asked).to eq([[1, 1], [2, 1], [2, 2], [2, 4], [2, 8], [5, 4]]) - end - - # Hits 257 to 384 were asked for, past the window, which Zammad answers - # as nothing at all, and the read ended there with the live hit unread. - it 'finds a live hit inside a lowered result window behind stale ones' do - stub_search_over(1..300, stale: 1..279, window: 300) - - expect(search.first.id).to eq(280) - end - - # Larger pages served by a smaller size start at other positions than - # the ones asked for, behind hits already read: hit 100 came back twice. - it 'hands back no record twice where the endpoint pages smaller than it is asked' do - stub_search_over(1..1000, stale: (1..1000).to_a - [100, 160], serves: 50) - - expect(search.first(2).map(&:id)).to eq([100, 160]) - end - - it 'reads past five thousand stale hits in tens of requests, not thousands' do - asked = stub_search_over(1..5000, stale: 1..5000) - - expect(search.empty?).to be(true) - expect(asked.size).to eq(34) - end - - it 'never asks for a page larger than the endpoint serves' do - asked = stub_search_over(1..5000, stale: 1..5000) - search.first(3) - - expect(asked.map(&:last).max).to be <= ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE - end - - it 'covers every hit once, however the pages were sized' do - asked = stub_search_over(1..5000, stale: 1..5000) - search.first(7) - - covered = asked.flat_map { |page, size| Array.new(size) { ((page - 1) * size) + it + 1 } } - expect(covered.first(5000)).to eq((1..5000).to_a) - end - - it 'finds the first live hit behind a run of stale ones' do - stub_search_over(1..300, stale: 1..137) - - expect(search.first.id).to eq(138) - end - - # Whatever is stale, the answer is the live hits in the order they are - # served: none passed over where a page changed size, none handed over - # twice. - [ - { stale: [], wanted: 3 }, - { stale: [1], wanted: 3 }, - { stale: [2, 3, 4, 5, 6, 7], wanted: 3 }, - { stale: (1..40).to_a - [17], wanted: 2 }, - { stale: (2..90).to_a, wanted: 5 }, - { stale: (1..300).step(2), wanted: 9 }, - { stale: (4..250).to_a, wanted: 4 } - ].each do |example| - it "reads the first #{example[:wanted]} live hits in order with #{example[:stale].to_a.size} of 300 stale" do - stub_search_over(1..300, stale: example[:stale]) - - expect(search.first(example[:wanted]).map(&:id)).to eq(((1..300).to_a - example[:stale].to_a).first(example[:wanted])) - end - end - - it 'still costs one request where the first hit is live' do - asked = stub_search_over(1..300) - search.first - - expect(asked).to eq([[1, 1]]) - end - - # A batch size is the caller saying how many records a batch may hold. - it 'does not widen a batch size the caller chose' do - asked = stub_search_over(1..100, stale: 1..100) - search.in_batches(of: 10) { nil } - - expect(asked.map(&:last).uniq).to eq([10]) - end - end - - it 'still raises PaginationError for a search that repeats a page of records' do - stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response({ records: [{ id: 1 }], total_count: 9 })) - - expect { search.to_a }.to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) - end - - # A search is served most recently updated first, so hits that are - # updated or created while it is walked go to its front. - it 'reads on where the hits moved by a page between two requests' do - list = [5, 4, 3, 2, 1] - stub_request(:get, search_url).with(query: hash_including({})).to_return do |request| - params = URI.decode_www_form(URI(request.uri).query).to_h - size = Integer(params['per_page']) - json_response({ records: list[(Integer(params['page']) - 1) * size, size].to_a.map { { id: it } }, total_count: list.size }) - end - seen = [] - search.in_batches(of: 2) do |batch| - list.unshift(7, 6) if seen.empty? - seen.concat(batch.map(&:id)) - end - - expect(seen).to eq([5, 4, 3, 2, 1]) - end - - it 'ends on the empty page where the total is not a count' do - stub_counted_page(1, [1], total: 'lots') - stub_counted_page(2, [], total: -4) - stub_counted_page(3, [3], total: 'lots') - - expect(walked_ids(per_page: 1)).to eq([1]) - end - - it 'raises ParseError for an object that is not a page of records' do - stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response({ total_count: 3 })) - - expect { search.to_a }.to raise_error(ZammadAPI::ParseError, /expected a JSON array, got Hash/) - end - - # The walk reads the id of every record on a page, so a null that got - # past the shape check died there as NoMethodError rather than as the - # ParseError a response of the wrong shape is. - it 'raises ParseError for a null among the records' do - stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response({ records: [nil, { id: 2 }], total_count: 2 })) - - expect { search.to_a }.to raise_error(ZammadAPI::ParseError, /an array holding NilClass/) - end - - # One page is one request whatever it holds, so there is no walk for a - # total to end, and the request is the one it always was. - it 'does not ask a search limited to one page for the total' do - stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) - search.page(2).to_a - - expect(a_request(:get, search_url).with(query: { 'expand' => 'true', 'query' => 'smith', 'page' => '2', 'per_page' => '200' })).to have_been_made.once - end - - # model_index_render drops the parameter with every other it does not - # know, so asking would be noise on every request of every walk. - it 'does not ask an index for the total' do - index_url = "#{ClientHelper::BASE_URL}api/v1/users" - stub_request(:get, index_url).with(query: hash_including({})).to_return(json_response([])) - client.users.all.to_a - - expect(a_request(:get, index_url).with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => '1000' })).to have_been_made.once - end - end - - describe 'an endpoint that pages smaller than it was asked for' do - it 'is walked to the end rather than truncated at the first short page' do - stub_capped_endpoint(url, total: 5, max: 2) - - expect(collection.map(&:id)).to eq([1, 2, 3, 4, 5]) - end - end end diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index dfbe467..8383356 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true require 'pp' -require 'yaml' RSpec.describe ZammadAPI::Config do def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) @@ -34,69 +33,31 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) it 'rejects a non-http scheme' do expect { build(url: 'ftp://example.com') } - .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https://') + .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https:// and name a host') end - # Appended blindly, the slash landed behind the query string and every - # request was resolved against a base ending in `?tenant=acme/`. - it 'puts the trailing slash on the path, not behind a query string' do - expect(build(url: 'https://example.com/zammad?tenant=acme').url) - .to eq('https://example.com/zammad/?tenant=acme') - end - - it 'puts the trailing slash on the path, not behind a fragment' do - expect(build(url: 'https://example.com/zammad#top').url) - .to eq('https://example.com/zammad/#top') - end - - # Accepted, this failed deep inside the adapter on the first request - # instead of here. - it 'rejects a scheme with no host after it' do + it 'rejects a url without a host' do expect { build(url: 'https://') } - .to raise_error(ZammadAPI::ConfigurationError, 'config url needs a host after the scheme, got "https://"') + .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https:// and name a host') end - # What `"http://#{ENV['ZAMMAD_HOST']}:3000/"` comes to with the variable - # unset. Net::HTTP connects to localhost for an empty host, so every - # request went, token and all, to whatever listens on that port. - ['http://:3000/', 'http://:3000', 'https://:443/zammad/', 'http://:/'].each do |url| - it "rejects #{url}, which has a port where the host belongs" do - expect { build(url: url) } - .to raise_error(ZammadAPI::ConfigurationError, "config url needs a host after the scheme, got #{url.inspect}") - end - end - - it 'rejects a url with a user and no host, without quoting the user' do - expect { build(url: 'http://admin:url-s3cret@:3000/') } - .to raise_error(ZammadAPI::ConfigurationError, 'config url needs a host after the scheme, got "http://[REDACTED]@:3000/"') + it 'rejects a url that does not parse' do + expect { build(url: 'https://zammad example.com') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url is not a valid URL') end - ['http://localhost:3000/', 'http://[::1]:3000/', 'http://192.168.0.1:8080/api/', 'http://host:/'].each do |url| - it "accepts #{url}, which names one" do - expect(build(url: url).url).to eq(url) - end - end - - # The value was quoted as it stood, and what stands where the host - # belongs may be credentials: a slash too many, and the userinfo is the - # start of a path as far as the syntax goes. - it 'does not quote the credentials of a url with a slash too many' do - expect { build(url: 'https:///admin:url-s3cret@zammad.example.com/') } - .to raise_error(ZammadAPI::ConfigurationError, 'config url needs a host after the scheme, got "https://[REDACTED]@zammad.example.com/"') + it 'refuses credentials in the url, without quoting them' do + expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url carries credentials: pass user: and password:, or a token, instead') end - it 'does not quote them where a ? or a # stands in for the host' do - %w[https://?admin:url-s3cret@zammad.example.com/ https://#admin:url-s3cret@zammad.example.com/].each do |url| - expect { build(url: url) }.to raise_error(ZammadAPI::ConfigurationError) { expect(it.message).not_to include('s3cret') } - end + it 'refuses a user name in the url without a password' do + expect { build(url: 'https://admin@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials/) end - # URI(...) is what a caller reaches for, and it prints as the URL, so it - # reached String#end_with? and died there as a NoMethodError - past the - # ConfigurationError the constructor is documented to raise. - it 'rejects a url that is not a string' do - expect { build(url: URI('https://example.com/')) } - .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to be a string, got URI::HTTPS') + it 'accepts a url whose path merely contains an @' do + expect(build(url: 'https://zammad.example.com/tenant@acme/').url).to eq('https://zammad.example.com/tenant@acme/') end end @@ -113,9 +74,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect(build(http_token: nil, user: 'u', password: 'p').authentication_scheme).to eq(:basic) end - # Several used to be accepted together, and the first in a fixed order - # was sent without a word about the others - which is what let an override - # leave the credential it was meant to replace in charge. context 'with more than one way to authenticate' do it 'refuses a token beside a user and password' do expect { build(http_token: 'token', user: 'u', password: 'p') } @@ -134,10 +92,9 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) it 'says what to pass instead' do expect { build(http_token: 'token', oauth2_token: 'other') } - .to raise_error(ZammadAPI::ConfigurationError, /Pass http_token:, or oauth2_token:, or user: and password:, and leave the others out/) + .to raise_error(ZammadAPI::ConfigurationError, /: pass http_token:, or oauth2_token:, or user: and password:\z/) end - # Half a scheme is still a second one being named. it 'refuses a token beside a user that has no password' do expect { build(http_token: 'token', user: 'u') } .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate/) @@ -168,15 +125,14 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') end - # What reading an empty token file gives. The transport takes the - # whitespace off the token it sends, so the client was built, reported - # auth=http_token and sent `Authorization: Token` with nothing after it. - context 'with a token of nothing but whitespace' do - [" \n", "\t", "\r\n", ' '].each do |blank| - it "treats #{blank.inspect} as absent, for either token" do - expect { build(http_token: blank) }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') - expect { build(http_token: nil, oauth2_token: blank) }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') - end + it 'strips whitespace around a token' do + expect(build(http_token: " secret\n").http_token).to eq('secret') + end + + context 'with a token of only whitespace' do + it 'treats it as absent, for either token' do + expect { build(http_token: " \n") }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + expect { build(http_token: nil, oauth2_token: " \n") }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') end it 'does not count it as a second way to authenticate' do @@ -186,35 +142,10 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) it 'leaves the scheme it would have replaced in an override alone' do expect(build(http_token: nil, user: 'u', password: 'p').with(http_token: " \n")).to have_attributes(http_token: nil, user: 'u', password: 'p') end - - it 'still replaces the scheme for a token with something in it' do - expect(build(http_token: nil, user: 'u', password: 'p').with(http_token: " abc\n")).to have_attributes(http_token: " abc\n", user: nil, password: nil) - end - - it 'keeps a password of spaces, which basic authentication carries as it is' do - expect(build(http_token: nil, user: 'u', password: ' ').password).to eq(' ') - end end - # It was sent as it prints, and a Symbol holding a line break passed the - # check that asks a String for one. - context 'with a token that is no String' do - { 12_345 => 'Integer', :abc => 'Symbol', ['a'] => 'Array', true => 'TrueClass' }.each do |value, kind| - it "rejects #{kind == 'Integer' ? 'an' : 'a'} #{kind}" do - expect { build(http_token: value) } - .to raise_error(ZammadAPI::ConfigurationError, "config http_token needs to be a string, got #{kind}") - end - end - - it 'rejects one for oauth2_token' do - expect { build(http_token: nil, oauth2_token: 99) } - .to raise_error(ZammadAPI::ConfigurationError, 'config oauth2_token needs to be a string, got Integer') - end - - it 'rejects a Symbol that holds a line break, which was never asked for one' do - expect { build(http_token: :"abc\r\nX-Injected: 1") } - .to raise_error(ZammadAPI::ConfigurationError, 'config http_token needs to be a string, got Symbol') - end + it 'keeps a password of spaces, which basic authentication carries as it is' do + expect(build(http_token: nil, user: 'u', password: ' ').password).to eq(' ') end end @@ -253,9 +184,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) end describe 'the user agent' do - # Handed to Faraday as a nil header, Faraday filled in its own, so the gem - # stopped identifying itself in the instance log an operator greps to find - # its requests - on every request, with nothing said about it. it 'falls back to the default when it is nil' do expect(build(user_agent: nil).user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") end @@ -264,78 +192,12 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect(build(user_agent: '').user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") end - # The transport takes the whitespace off the value it sends, so this one - # went out as a User-Agent header with nothing in it. - [' ', "\n", " \t\r\n"].each do |blank| - it "falls back to the default when it is #{blank.inspect}, which a header would carry nothing of" do - expect(build(user_agent: blank).user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") - end - end - - it 'keeps one with whitespace around it, which is taken off where it is sent' do - expect(build(user_agent: ' my-app/1.0 ').user_agent).to eq(' my-app/1.0 ') + it 'falls back to the default when it is only whitespace' do + expect(build(user_agent: " \t\n").user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") end - it 'rejects one that is not a string' do - expect { build(user_agent: 42) } - .to raise_error(ZammadAPI::ConfigurationError, 'config user_agent needs to be a string') - end - end - - # Each is sent as a header. Net::HTTP refused a line break inside one at - # the first request, with an ArgumentError that quoted the value. - describe 'a line break in an option sent as a header' do - { - http_token: { http_token: "secret-abc\nsecret-def" }, - oauth2_token: { http_token: nil, oauth2_token: "secret-abc\r\nsecret-def" }, - user_agent: { user_agent: "my-app\nsecret-def" } - }.each do |name, options| - it "refuses one inside #{name}, without quoting it" do - expect { build(**options) }.to raise_error(ZammadAPI::ConfigurationError) { |error| - expect(error.message).to start_with("config #{name} holds a line break, which a header cannot carry") - expect(error.message).not_to include('secret-def') - } - end - end - - # `strip` raises for text holding a byte sequence that is invalid in its - # encoding, and the error was read as "no line break": the token was - # taken, and an adapter that checks nothing sent the second line. - it 'refuses one beside a byte sequence that is invalid in the encoding' do - expect { build(http_token: "secret-abc\xFF\nX-Injected: secret-def") }.to raise_error(ZammadAPI::ConfigurationError) { |error| - expect(error.message).to start_with('config http_token holds a line break, which a header cannot carry') - expect(error.message).not_to include('secret-def') - } - end - - it 'refuses one in a token given as binary text' do - expect { build(http_token: "secret-abc\xFF\nsecret-def".b) } - .to raise_error(ZammadAPI::ConfigurationError, /\Aconfig http_token holds a line break/) - end - - # It cannot be shown to hold no line break, and was passed as holding - # none. - it 'refuses UTF-16 text that cannot be converted, without quoting it or the error underneath' do - broken = "secret-abc\nsecret-def".encode('UTF-16LE').b[0..-2].force_encoding('UTF-16LE') - - expect { build(user_agent: broken) }.to raise_error(ZammadAPI::ConfigurationError) { |error| - expect(error.message).to start_with('config user_agent was given as UTF-16LE text that cannot be converted to UTF-8') - expect(error.cause).to be_nil - } - end - - # Net::HTTP strips it, so a token read from a file with its newline on - # worked, and still does. - it 'takes a token that only ends in one' do - expect(build(http_token: "secret\n").http_token).to eq("secret\n") - end - - it 'takes a token that only ends in one after bytes that are invalid in the encoding' do - expect(build(http_token: "secret\xFF\n").http_token).to eq("secret\xFF\n") - end - - it 'does not check a password, which basic authentication encodes' do - expect(build(http_token: nil, user: 'agent', password: "pass\nword").password).to eq("pass\nword") + it 'strips whitespace around it' do + expect(build(user_agent: ' my-app/1.0 ').user_agent).to eq('my-app/1.0') end end @@ -375,53 +237,13 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect(build(logger: logger).logger).to be(logger) end - # 1.x took `logger: true` as "log to $stderr". - it 'rejects a boolean, as 1.x accepted' do + it 'rejects a logger that cannot log at debug' do expect { build(logger: true) } .to raise_error(ZammadAPI::ConfigurationError, 'config logger needs to respond to debug') end - - # Each line is handed over as a block, so this was accepted and raised - # a bare ArgumentError at every request. - it 'rejects a debug that requires an argument' do - logger = Class.new { def debug(message) = message }.new - - expect { build(logger: logger) } - .to raise_error(ZammadAPI::ConfigurationError, /\Aconfig logger needs a debug that can be called with a block and no argument/) - end - - it 'rejects a debug that requires a keyword' do - logger = Class.new { def debug(message = nil, level:) = [message, level] }.new - - expect { build(logger: logger) }.to raise_error(ZammadAPI::ConfigurationError, /requires an argument/) - end - - it 'accepts a debug that takes its message as an option, as Logger#debug does' do - logger = Class.new { def debug(message = nil) = message || yield }.new - - expect(build(logger: logger).logger).to be(logger) - end - - # Such a logger cannot be asked what its debug takes. - it 'accepts a logger that forwards debug without having the method' do - logger = Class.new do - def respond_to?(name, *) = name == :debug || super - def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Style/MissingRespondToMissing - end.new - - expect(build(logger: logger).logger).to be(logger) - end end describe 'numeric validation' do - # Complex is a Numeric and answers neither `positive?` nor `>`, so this - # left a NoMethodError where every other rejected option raises the error - # building a client is documented to need. - it 'rejects a Numeric that cannot be compared, as a configuration error' do - expect { build(timeout: Complex(1, 2)) } - .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') - end - it 'rejects a zero timeout' do expect { build(timeout: 0) } .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') @@ -432,47 +254,13 @@ def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Sty .to raise_error(ZammadAPI::ConfigurationError, 'config open_timeout needs to be a positive number') end - it 'rejects a non-numeric timeout' do - expect { build(timeout: 'soon') } - .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') - end - - # The natural way to ask for no timeout, which is what 1.x had. Accepted, - # every request raised a bare RangeError from inside Net::HTTP. - it 'rejects an infinite timeout' do - expect { build(timeout: Float::INFINITY) } - .to raise_error(ZammadAPI::ConfigurationError, /\Aconfig timeout needs to be at most 100000000 seconds, got Infinity\. No value stands for no timeout/) - end - - it 'rejects an infinite open_timeout' do - expect { build(open_timeout: Float::INFINITY) } - .to raise_error(ZammadAPI::ConfigurationError, /config open_timeout needs to be at most 100000000 seconds, got Infinity/) - end - - # It raised the same from the sleep before the first retry. - it 'rejects an infinite retry_interval' do - expect { build(retry_interval: Float::INFINITY) } - .to raise_error(ZammadAPI::ConfigurationError, /config retry_interval needs to be at most 100000000 seconds, got Infinity\. No value stands for no limit/) - end - - it 'rejects a timeout too large for a C long' do - expect { build(timeout: 10**20) } - .to raise_error(ZammadAPI::ConfigurationError, /config timeout needs to be at most 100000000 seconds, got 100000000000000000000/) + it 'rejects a non-numeric retry_interval' do + expect { build(retry_interval: 'soon') } + .to raise_error(ZammadAPI::ConfigurationError, 'config retry_interval needs to be a positive number') end - # macOS refuses a wait on a socket that is longer, and that came back as - # a ConnectionError calling the instance unreachable. - it 'rejects a timeout one second past the longest every platform takes' do - expect { build(timeout: 100_000_001) }.to raise_error(ZammadAPI::ConfigurationError, /at most 100000000 seconds/) - end - - it 'accepts the longest one' do - expect(build(timeout: 100_000_000, open_timeout: 100_000_000.0, retry_interval: Rational(100_000_000))) - .to have_attributes(timeout: 100_000_000, open_timeout: 100_000_000.0, retry_interval: Rational(100_000_000)) - end - - it 'still says a Float that is no number needs to be one' do - expect { build(timeout: Float::NAN) } + it 'rejects a Numeric that cannot be compared' do + expect { build(timeout: Complex(1, 2)) } .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') end @@ -481,6 +269,11 @@ def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Sty .to raise_error(ZammadAPI::ConfigurationError, 'config retries needs to be a non-negative integer') end + it 'rejects retries that are not an integer' do + expect { build(retries: 1.5) } + .to raise_error(ZammadAPI::ConfigurationError, 'config retries needs to be a non-negative integer') + end + it 'allows disabling retries' do expect(build(retries: 0).retries).to eq(0) end @@ -542,85 +335,20 @@ def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Sty end end - it 'redacts a proxy password carrying an unencoded @' do - rendered = build(proxy: 'http://puser:pa@ss-s3cret@proxy.test:8080').inspect - - expect(rendered).to include('proxy="http://[REDACTED]@proxy.test:8080"') - expect(rendered).not_to include('ss-s3cret') - end - - # A password is not obliged to be URL-safe, and each of these ends the - # authority early as far as the syntax goes: `user:p` is all that is left - # of it, with no @ in it, so a search bounded by the authority found no - # credential to blank and printed the password. - { - 'a #' => 'http://puser:pa#ss-s3cret@proxy.test:8080', - 'a /' => 'http://puser:pa/ss-s3cret@proxy.test:8080', - 'a ?' => 'http://puser:pa?ss-s3cret@proxy.test:8080' - }.each do |character, proxy| - it "redacts a proxy password carrying #{character}" do - rendered = build(proxy: proxy).inspect - - expect(rendered).to include('proxy="http://[REDACTED]@proxy.test:8080"') - expect(rendered).not_to match(/pa.ss|s3cret/) - end - end - - it 'redacts such a password on a proxy configured without a scheme' do - rendered = build(proxy: 'puser:pa#ss-s3cret@proxy.test:8080').inspect - - expect(rendered).to include('proxy="[REDACTED]@proxy.test:8080"') - expect(rendered).not_to include('s3cret') + it 'refuses a proxy that is not a URL without quoting it' do + expect { build(proxy: 'http://puser:p s3cret@proxy.test:8080') } + .to raise_error(ZammadAPI::ConfigurationError, 'config proxy is not a valid URL') end it 'leaves a proxy without credentials alone' do expect(build(proxy: 'http://proxy.test:8080').inspect).to include('proxy="http://proxy.test:8080"') end - # The shape an http_proxy style setting is copied out of. Anchored on a - # `://` lookbehind, the redaction never fired and the password went into - # every log line and exception report this class promises to be safe in. - it 'redacts the credentials of a proxy configured without a scheme' do - rendered = build(proxy: 'puser:pproxy-s3cret@proxy.test:8080').inspect - - expect(rendered).to include('proxy="[REDACTED]@proxy.test:8080"') - expect(rendered).not_to include('pproxy-s3cret') - end - - it 'leaves a scheme-less proxy without credentials alone' do - expect(build(proxy: 'proxy.test:8080').inspect).to include('proxy="proxy.test:8080"') - end - - # A proxy written with the slashes and without the scheme, or with a - # slash too many. The authority was looked for where the scheme ended, - # and found to end at once, at the slash it began with: an empty - # authority holds no colon and no @, so nothing was blanked. - { - 'two slashes and no scheme' => ['//puser:pproxy-s3cret@proxy.test:8080', '[REDACTED]@proxy.test:8080'], - 'one slash' => ['/puser:pproxy-s3cret@proxy.test:8080', '[REDACTED]@proxy.test:8080'], - 'a scheme and three' => ['http:///puser:pproxy-s3cret@proxy.test:8080', 'http://[REDACTED]@proxy.test:8080'], - 'two and a # in a password' => ['//puser:pa#ss-s3cret@proxy.test:8080', '[REDACTED]@proxy.test:8080'] - }.each do |opening, (proxy, redacted)| - it "redacts the credentials of a proxy that opens with #{opening}" do - rendered = build(proxy: proxy).inspect - - expect(rendered).to include("proxy=#{redacted.inspect}") - expect(rendered).not_to include('s3cret') - end - end - - it 'leaves a proxy that opens with two slashes and has no credentials alone' do - expect(build(proxy: '//proxy.test:8080').inspect).to include('proxy="//proxy.test:8080"') - end - it 'leaves a url without credentials alone' do expect(build(url: 'https://zammad.example.com/').inspect).to include('url="https://zammad.example.com/"') end end - # pp has a printer of its own for a Data object, which renders the members - # without going through #inspect - and pp is what IRB and the Rails console - # print a value with. describe 'pretty printing' do it 'redacts the password' do expect(build(http_token: nil, user: 'u', password: 'pw-s3cret').pretty_inspect).not_to include('pw-s3cret') @@ -648,227 +376,6 @@ def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Sty end end - # ActiveSupport gives a Data an as_json that is its members as they are, - # and builds to_json on it, so in a Rails app `config.to_json` wrote the - # credentials in full. It is not loaded here: what is asked is what it - # asks, and that the answer is this class's own. - describe 'serializing as JSON' do - it 'answers as_json itself, where ActiveSupport would answer for a Data' do - expect(described_class.instance_method(:as_json).owner).to be(described_class) - end - - it 'redacts the password' do - expect(build(http_token: nil, user: 'u', password: 'pw-s3cret').as_json).to include(user: 'u', password: '[REDACTED]') - end - - it 'redacts the access token' do - expect(build(http_token: 'tok-s3cret').as_json).to include(http_token: '[REDACTED]', password: nil) - end - - it 'redacts the OAuth2 token' do - expect(build(http_token: nil, oauth2_token: 'oauth-s3cret').as_json).to include(oauth2_token: '[REDACTED]') - end - - it 'redacts the proxy credentials' do - expect(build(proxy: 'http://puser:pproxy-s3cret@proxy.test:8080').as_json).to include(proxy: 'http://[REDACTED]@proxy.test:8080') - end - - it 'names the logger and the middleware, and does not hand them to the encoder' do - expect(build(middleware: ->(faraday) { faraday }).as_json).to include(logger: '#', middleware: '#') - end - - it 'keeps every other option as it is' do - expect(build(timeout: 7, adapter: :net_http).as_json).to include(url: 'https://zammad.example.com/', timeout: 7, adapter: :net_http, ssl_verify: true) - end - - it 'writes that as a JSON object' do - written = JSON.parse(build(http_token: 'tok-s3cret', timeout: 7).to_json) - - expect(written).to include('url' => 'https://zammad.example.com/', 'http_token' => '[REDACTED]', 'timeout' => 7, 'logger' => '#') - end - - it 'holds no credential in what it writes' do - config = build(http_token: nil, user: 'u', password: 'pw-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') - - expect(config.to_json).not_to match(/pw-s3cret|pproxy-s3cret/) - end - - it 'stays redacted nested inside another structure' do - expect(JSON.generate(config: build(http_token: 'tok-s3cret'))).not_to include('tok-s3cret') - end - end - - # Psych writes the members of a Data as they are and asks neither inspect - # nor as_json, so `config.to_yaml` held every credential in full. It is - # what Rails' `debug` view helper and a Delayed::Job handler write. - describe 'serializing as YAML' do - let(:config) { build(http_token: nil, user: 'u', password: 'pw-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') } - - it 'holds no credential in what it writes' do - expect(config.to_yaml).not_to match(/pw-s3cret|pproxy-s3cret/) - end - - it 'writes neither token' do - expect(build(http_token: 'tok-s3cret').to_yaml + build(http_token: nil, oauth2_token: 'oauth-s3cret').to_yaml).not_to match(/tok-s3cret|oauth-s3cret/) - end - - it 'writes what its JSON holds, as a mapping any loader reads' do - expect(YAML.safe_load(config.to_yaml)).to eq(JSON.parse(config.to_json)) - end - - it 'keeps the options that are no secret readable' do - expect(YAML.safe_load(build(timeout: 7).to_yaml)).to include('url' => 'https://zammad.example.com/', 'timeout' => 7, 'http_token' => '[REDACTED]', 'logger' => '#') - end - - it 'stays redacted nested inside another structure' do - expect({ config: config, list: [config] }.to_yaml).not_to match(/pw-s3cret|pproxy-s3cret/) - end - end - - # ActiveSupport gives every object a public `presence`. A private helper of - # that name here answered in its place, so `config.presence` raised - # NoMethodError. It is not loaded here: what is asked is that the name is - # left to it. - describe 'the names ActiveSupport gives every object' do - it 'defines no presence of its own' do - expect(described_class.private_method_defined?(:presence)).to be(false) - end - - it 'still reads an empty option as one that was not given' do - expect(build(http_token: nil, user: 'u', password: 'p', oauth2_token: '', proxy: '')).to have_attributes(oauth2_token: nil, proxy: nil) - end - end - - # Faraday turns the userinfo of a URL into a Basic Authorization header, and - # its authorization middleware leaves a header that is already set alone - - # so the credentials in the URL were sent in place of the configured ones. - describe 'credentials in the instance url' do - it 'refuses them' do - expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } - .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials of its own/) - end - - it 'says where they belong instead' do - expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } - .to raise_error(ZammadAPI::ConfigurationError, /pass user: and password:/) - end - - it 'keeps the password out of the message' do - expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('url-s3cret') } - end - - it 'still names the instance in the message' do - expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } - .to raise_error(ZammadAPI::ConfigurationError, %r{https://\[REDACTED\]@zammad\.example\.com/}) - end - - it 'refuses them beside basic authentication too, where they would win just the same' do - expect { build(url: 'https://old:creds@zammad.example.com/', http_token: nil, user: 'u', password: 'p') } - .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials of its own/) - end - - it 'refuses a user name without a password' do - expect { build(url: 'https://admin@zammad.example.com/') } - .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials of its own/) - end - - it 'accepts a url whose path merely contains an @' do - expect(build(url: 'https://zammad.example.com/tenant@acme/').url).to eq('https://zammad.example.com/tenant@acme/') - end - end - - describe '#redacted' do - it 'blanks inline credentials' do - expect(build.redacted('https://admin:s3cret@zammad.example.com/')) - .to eq('https://[REDACTED]@zammad.example.com/') - end - - # Anchoring on the first @ left the tail of the password in the rendered - # URL, which is interpolated into every ConnectionError message. - it 'blanks a password carrying an unencoded @' do - expect(build.redacted('https://admin:pa@ss-s3cret@zammad.example.com/')) - .to eq('https://[REDACTED]@zammad.example.com/') - end - - # The same three characters, in the instance url. URI cannot read these, - # so they are not refused the way a readable url with credentials is, and - # stay printable until the connection rejects them. - it 'blanks a password carrying a #, which ends the authority early' do - expect(build.redacted('https://admin:pa#ss-s3cret@zammad.example.com/')) - .to eq('https://[REDACTED]@zammad.example.com/') - end - - it 'blanks a password carrying a /' do - expect(build.redacted('https://admin:pa/ss-s3cret@zammad.example.com/')) - .to eq('https://[REDACTED]@zammad.example.com/') - end - - it 'blanks a password carrying a ?' do - expect(build.redacted('https://admin:pa?ss-s3cret@zammad.example.com/')) - .to eq('https://[REDACTED]@zammad.example.com/') - end - - it 'blanks a password carrying both an @ and a /' do - expect(build.redacted('https://admin:pa@ss/w0rd@zammad.example.com/')) - .to eq('https://[REDACTED]@zammad.example.com/') - end - - it 'leaves a host and port alone' do - expect(build.redacted('https://zammad.example.com:8443/helpdesk/')).to eq('https://zammad.example.com:8443/helpdesk/') - end - - it 'leaves an IPv6 host alone' do - expect(build.redacted('http://[::1]:3128')).to eq('http://[::1]:3128') - end - - # A colon cannot tell a port from a password, and `user:8443/s3cret@host` - # is a password with a slash in it just as much as it is a port and a - # path. Blanking too much shows a wrong host; blanking too little shows a - # password. - it 'blanks rather than guesses where a colon could be either a port or a password' do - expect(build.redacted('https://zammad.example.com:8443/tenant@acme/')).to eq('https://[REDACTED]@acme/') - end - - # No host stands in an empty authority, so there is none to blank by - # mistake, and what follows it is searched to its last @. - it 'blanks what stands behind an empty authority' do - expect(build.redacted('https:///admin:s3cret@zammad.example.com/')).to eq('https://[REDACTED]@zammad.example.com/') - end - - it 'leaves a value with an empty authority and no @ alone' do - expect(build.redacted('https:///helpdesk/')).to eq('https:///helpdesk/') - end - end - - describe '#redacted_url' do - it 'blanks a password the url is too malformed to be refused for' do - expect(build(url: 'https://admin:pa#ss-s3cret@zammad.example.com/').redacted_url) - .to eq('https://[REDACTED]@zammad.example.com/') - end - - it 'leaves an @ in the path alone' do - expect(build(url: 'https://zammad.example.com/tenant@acme/').redacted_url) - .to eq('https://zammad.example.com/tenant@acme/') - end - - # Bounded only by the path, the match crossed into the query string and - # rendered a host that does not exist - into every ConnectionError message. - it 'leaves an @ in a query string alone' do - expect(build(url: 'https://zammad.example.com?tenant=a@acme').redacted_url) - .to eq('https://zammad.example.com/?tenant=a@acme') - end - - it 'leaves an @ in a fragment alone' do - expect(build(url: 'https://zammad.example.com#a@b').redacted_url) - .to eq('https://zammad.example.com/#a@b') - end - - it 'leaves a url without credentials alone' do - expect(build(url: 'https://zammad.example.com/').redacted_url).to eq('https://zammad.example.com/') - end - end - describe '#with' do it 'changes an option' do expect(build.with(timeout: 5).timeout).to eq(5) @@ -891,8 +398,6 @@ def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Sty expect(build.with(oauth2_token: nil).authentication_scheme).to eq(:http_token) end - # The refusal of two schemes is what makes this necessary: merged beside - # the token, the new credential would no longer be ignored but refused. it 'can switch to any scheme from any other without naming two at once' do switched = build.with(oauth2_token: 'o').with(user: 'u', password: 'p').with(http_token: 't') expect(switched.to_h.slice(:http_token, :oauth2_token, :user, :password)) @@ -924,78 +429,11 @@ def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Sty end end - describe 'immutability of string members' do - it 'freezes the url' do - expect(build.url).to be_frozen - end - - it 'does not share the url with the caller' do - supplied = +'https://zammad.example.com/' - config = described_class.new(url: supplied, http_token: 'tok') - supplied << 'mutated' - expect(config.url).to eq('https://zammad.example.com/') - end - - it 'freezes the credentials' do - config = build(user: 'u', password: +'pw', http_token: nil) - expect(config.password).to be_frozen - end - - it 'freezes the proxy' do - expect(build(proxy: +'http://proxy.test:8080').proxy).to be_frozen - end - - it 'freezes the user agent' do - expect(build(user_agent: +'custom/1.0').user_agent).to be_frozen - end - end - it 'is immutable' do expect(build).to be_frozen end - # Every other option is checked up front; these three were not, so a bad - # value escaped the ConfigurationError that building a client is documented - # to need - two as a bare NoMethodError, one by silently staying on. - describe 'option validation' do - it 'rejects a proxy that is not a string' do - expect { build(proxy: URI('http://user:secret@proxy:3128')) } - .to raise_error(ZammadAPI::ConfigurationError, 'config proxy needs to be a string, got URI::HTTP') - end - - # The whole point of refusing it: a URI reached String#sub inside #inspect - # and died there, so the object this class documents as safe to log raised - # at the moment something logged it. - it 'keeps a proxy-bearing config renderable' do - expect { build(proxy: 'http://user:secret@proxy:3128').inspect }.not_to raise_error - end - - it 'redacts the credentials in a proxy it renders' do - rendered = build(proxy: 'http://user:secret@proxy:3128').inspect - - expect(rendered).to include('proxy="http://[REDACTED]@proxy:3128"') - expect(rendered).not_to include('secret') - end - - it 'rejects an adapter that cannot be a symbol' do - expect { build(adapter: 1) } - .to raise_error(ZammadAPI::ConfigurationError, 'config adapter needs to be a symbol or a string, got Integer') - end - - # `adapter: true` is the 1.x-flavoured mistake: it answered to_sym on - # nothing and raised NoMethodError from inside the constructor. - it 'rejects a boolean adapter' do - expect { build(adapter: true) } - .to raise_error(ZammadAPI::ConfigurationError, /config adapter needs to be a symbol or a string/) - end - - it 'accepts an adapter named as a string' do - expect(build(adapter: 'net_http').adapter).to eq(:net_http) - end - - # Read from an environment variable this is the string "false", which is - # truthy, so verification stayed on while the caller believed they had - # turned it off. + describe 'other options' do it 'rejects an ssl_verify that is not a boolean' do expect { build(ssl_verify: 'false') } .to raise_error(ZammadAPI::ConfigurationError, 'config ssl_verify needs to be true or false, got "false"') @@ -1004,5 +442,9 @@ def method_missing(name, *) = name == :debug ? nil : super # rubocop:disable Sty it 'accepts ssl_verify: false' do expect(build(ssl_verify: false).ssl_verify).to be(false) end + + it 'reads an empty proxy as none' do + expect(build(proxy: '').proxy).to be_nil + end end end diff --git a/spec/unit/zammad_api/query_encoder_spec.rb b/spec/unit/zammad_api/query_encoder_spec.rb deleted file mode 100644 index 05e6369..0000000 --- a/spec/unit/zammad_api/query_encoder_spec.rb +++ /dev/null @@ -1,180 +0,0 @@ -# frozen_string_literal: true - -# What is asserted here is the order the pairs of a query are written in, -# because that order is all a query string has to say where one element of a -# list ends. Rack, and the parser Rails 8.1 has of its own, fill the element -# they are on until a pair names a place in it that is already taken, and -# begin a new one there. The orders below were read back with both, from the -# Zammad this gem is developed against, and came out as written. -RSpec.describe ZammadAPI::QueryEncoder do - def written(query) = URI.decode_www_form(described_class.encode(ZammadAPI::Transport.stringify_query(query))) - - def faraday(query) = Faraday::NestedParamsEncoder.encode(ZammadAPI::Transport.stringify_query(query)) - - let(:by_group) { { name: 'ticket.group_id', operator: 'is', value: [1] } } - let(:by_title) { { name: 'ticket.title', operator: 'contains', value: 'x' } } - - describe '.encode' do - # Everything but a list of Hashes that differ is written as it was. - { - 'plain values' => { query: 'smith', page: 2, expand: true }, - 'a list of plain values' => { ids: [3, 1, 2] }, - 'a Hash of lists' => { group_ids: { 3 => %w[read change], 4 => 'full' } }, - 'a condition keyed by name' => { condition: { 'ticket.state_id' => { operator: 'is', value: [1, 2] } } }, - 'a list of Hashes alike' => { condition: { operator: 'AND', conditions: [{ name: 'a', operator: 'is', value: [1] }, { name: 'b', operator: 'is', value: [2] }] } }, - 'a list with nothing in it' => { ids: [] }, - 'a value that needs escaping' => { query: 'a b&c=d[e]' }, - 'a list of Hashes of Hashes' => { list: [{ a: { x: 1 } }, { a: { x: 2 } }] }, - 'plain values among the Hashes' => { list: [1, { a: 1 }, 2, { b: 3 }] } - }.each do |name, query| - it "writes #{name} as Faraday does" do - expect(described_class.encode(ZammadAPI::Transport.stringify_query(query))).to eq(faraday(query)) - end - end - - # A condition and a group of conditions share `operator` and nothing - # else. Written `conditions` first, the group was read into the condition - # before it, and what was left of it began an element holding nothing but - # its operator. - it 'begins a group of conditions with the key it shares with the condition before it' do - condition = { operator: 'OR', conditions: [{ name: 'ticket.state_id', operator: 'is', value: [2] }, { operator: 'AND', conditions: [by_group, by_title] }] } - - expect(written(condition: condition)).to eq( - [ - ['condition[conditions][][name]', 'ticket.state_id'], - ['condition[conditions][][operator]', 'is'], - ['condition[conditions][][value][]', '2'], - ['condition[conditions][][operator]', 'AND'], - ['condition[conditions][][conditions][][name]', 'ticket.group_id'], - ['condition[conditions][][conditions][][operator]', 'is'], - ['condition[conditions][][conditions][][value][]', '1'], - ['condition[conditions][][conditions][][name]', 'ticket.title'], - ['condition[conditions][][conditions][][operator]', 'contains'], - ['condition[conditions][][conditions][][value]', 'x'], - ['condition[operator]', 'OR'] - ] - ) - end - - # The other way round: `name` sorts first, and the group before has none. - it 'begins a condition with the key it shares with the group before it' do - condition = { operator: 'OR', conditions: [{ operator: 'AND', conditions: [by_group] }, { name: 'ticket.state_id', operator: 'is', value: [2] }] } - - expect(written(condition: condition).last(4)).to eq( - [ - ['condition[conditions][][operator]', 'is'], - ['condition[conditions][][name]', 'ticket.state_id'], - ['condition[conditions][][value][]', '2'], - ['condition[operator]', 'OR'] - ] - ) - end - - it 'begins every group in a row of them with its operator' do - condition = { conditions: [{ operator: 'OR', conditions: [by_group] }, { operator: 'NOT', conditions: [by_title] }, { operator: 'AND', conditions: [by_group] }] } - - expect(written(condition: condition).map(&:first).each_cons(2).count { |before, pair| pair == 'condition[conditions][][operator]' && before != pair }) - .to eq(2) - end - - # The shared place may be further down, and every key on the way to it - # goes first. - it 'begins an element with a value it shares further down' do - list = [{ a: { x: 1, y: { z: 1 } }, b: [1] }, { a: { w: [2], y: { q: 3, z: 2 } }, c: 4 }] - - expect(written(list: list).drop(3)).to eq([['list[][a][y][z]', '2'], ['list[][a][y][q]', '3'], ['list[][a][w][]', '2'], ['list[][c]', '4']]) - end - - it 'writes nothing for no query' do - expect(described_class.encode(nil)).to be_nil - end - - it 'writes an empty string for a query with nothing in it' do - expect(described_class.encode({})).to eq('') - end - end - - describe '.decode' do - it 'reads a query string the way Faraday does' do - expect(described_class.decode('a[]=1&a[]=2&b[c]=3')).to eq('a' => %w[1 2], 'b' => { 'c' => '3' }) - end - end - - describe '.lead_path' do - it 'is the first key both have that holds a plain value' do - expect(described_class.lead_path({ 'conditions' => [], 'operator' => 'AND' }, { 'name' => 'a', 'operator' => 'is' })).to eq(['operator']) - end - - it 'is not needed after something that is not a Hash' do - expect(described_class.lead_path({ 'a' => '1' }, 'x')).to be_nil - end - - it 'does not go through a list' do - expect(described_class.lead_path({ 'a' => ['1'] }, { 'a' => ['2'] })).to be_nil - end - - it 'goes through a Hash to a place the element before has too' do - expect(described_class.lead_path({ 'a' => { 'x' => '1' } }, { 'a' => { 'x' => '2' } })).to eq(%w[a x]) - end - - it 'does not go through a Hash where the element before holds a plain value' do - expect(described_class.lead_path({ 'a' => { 'x' => '1' } }, { 'a' => '2' })).to be_nil - end - - it 'is nil where the two share no key' do - expect(described_class.lead_path({ 'a' => '1' }, { 'b' => '2' })).to be_nil - end - - # Nothing is written for an empty Hash, so Rails never saw the key in the - # element before, and a pair naming it is read into that element. - it 'does not take a key the element before holds an empty Hash under' do - expect(described_class.lead_path({ 'a' => '2', 'c' => '3' }, { 'a' => {}, 'b' => '1' })).to be_nil - end - - it 'does not take one further down either' do - expect(described_class.lead_path({ 'a' => { 'x' => '2' } }, { 'a' => { 'x' => {} } })).to be_nil - end - - it 'takes another key the two share instead' do - expect(described_class.lead_path({ 'a' => '2', 'b' => '3' }, { 'a' => {}, 'b' => '1' })).to eq(['b']) - end - end - - describe '.misread' do - it 'is nil for a plain value' do - expect(described_class.misread('x', { 'a' => '1' })).to be_nil - end - - it 'is nil for the first Hash of a list' do - expect(described_class.misread({ 'a' => ['1'] }, nil)).to be_nil - end - - it 'is nil for a Hash after a plain value' do - expect(described_class.misread({ 'a' => '1' }, 'x')).to be_nil - end - - it 'is nil for a Hash that shares a plain value with the one before' do - expect(described_class.misread({ 'operator' => 'AND', 'conditions' => [] }, { 'operator' => 'is', 'name' => 'a' })).to be_nil - end - - it 'names a Hash that would be read into the one before' do - expect(described_class.misread({ 'b' => '2' }, { 'a' => '1' })).to eq(:merged) - end - - it 'names a Hash nothing is written for' do - expect(described_class.misread({}, nil)).to eq(:empty) - end - - it 'names a Hash holding nothing but such Hashes' do - expect(described_class.misread({ 'a' => { 'b' => {} } }, nil)).to eq(:empty) - end - - it 'names a Hash whose only shared key holds an empty Hash in the element before' do - expect(described_class.misread({ 'a' => '2', 'c' => '3' }, { 'a' => {}, 'b' => '1' })).to eq(:merged) - end - - it 'names a list directly inside a list' do - expect(described_class.misread(%w[1 2], nil)).to eq(:list) - end - end -end diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index b55db29..653aaf3 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -88,26 +88,6 @@ expect { proxy.find('') }.to raise_error(ArgumentError, /record id is required/) expect(a_request(:any, /zammad\.test/)).not_to have_been_made end - - # A record where its id belongs went into the path as it inspects, and - # the 404 for that path was read as an answer about the record. - context 'with a record where its id belongs' do - let(:record) { ZammadAPI::Resources::Group.from_response(client.instance_variable_get(:@transport), { id: 1, name: 'Users' }) } - - it 'refuses exists? rather than answering false for a record that exists' do - expect { proxy.exists?(record) }.to raise_error(ArgumentError, /pass its id/) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'refuses find' do - expect { proxy.find(record) }.to raise_error(ArgumentError, /pass its id/) - end - - it 'refuses destroy rather than raising NotFoundError for a record that is there' do - expect { proxy.destroy(record) }.to raise_error(ArgumentError, /pass its id/) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - end end describe '#create' do @@ -137,6 +117,27 @@ describe '#find_by' do let(:search_url) { "#{url}/search" } + context 'with an id' do + it 'reads the record by its id, given as text' do + stub_request(:get, "#{url}/5").with(query: { expand: 'true' }).to_return(json_response({ id: 5, name: 'Users' })) + + expect(proxy.find_by(id: '5').id).to eq(5) + expect(a_request(:get, search_url).with(query: hash_including({}))).not_to have_been_made + end + + it 'checks the other values against it' do + stub_request(:get, "#{url}/5").with(query: { expand: 'true' }).to_return(json_response({ id: 5, name: 'Users' })) + + expect(proxy.find_by(id: 5, name: 'Other')).to be_nil + end + + it 'answers nil for an id that names no record' do + stub_request(:get, "#{url}/9").with(query: { expand: 'true' }).to_return(json_response({ error: 'not found' }, status: 404)) + + expect(proxy.find_by(id: 9)).to be_nil + end + end + it 'searches instead of filtering an index that cannot filter' do stub = stub_request(:get, search_url) .with(query: hash_including('query' => 'Users')) @@ -154,50 +155,8 @@ expect(proxy.find_by(name: 'Users').id).to eq(1) end - # The value is searched for as UTF-8, and Zammad serves UTF-8. Held - # against the value as it was given, the hit was passed over: Ruby takes - # two Strings in different encodings for different unless both are - # ASCII. - %w[ISO-8859-1 Windows-1252 UTF-16LE].each do |encoding| - context "with a value given in #{encoding}" do - let(:value) { 'Größe'.encode(encoding) } - - before do - stub_request(:get, search_url).with(query: hash_including('query' => 'Größe', 'page' => '1')).to_return(json_response([{ id: 1, name: 'Größe', note: 'ä' }])) - stub_request(:get, search_url).with(query: hash_including('query' => 'Größe', 'page' => '2')).to_return(json_response([])) - end - - it 'searches for the text in UTF-8 and returns the record that carries it' do - expect(proxy.find_by(name: value).id).to eq(1) - end - - it 'matches it beside an id as well' do - stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Größe' })) - - expect(proxy.find_by(id: 1, name: value).id).to eq(1) - end - - it 'still answers nil where no hit carries it' do - expect(proxy.find_by(name: value, note: 'ö'.encode(encoding))).to be_nil - end - end - end - - it 'matches a value given in another encoding where the index is walked' do - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/ticket_states").with(query: hash_including({})).to_return(json_response([{ id: 4, name: 'geschlossen für immer' }])) - - expect(client.ticket_states.find_by(name: 'geschlossen für immer'.encode('ISO-8859-1')).id).to eq(4) - end - - it 'refuses a value that cannot be converted to UTF-8, naming the attribute and not the value' do - expect { proxy.find_by(name: "secret\x81".dup.force_encoding('Windows-1252')) } - .to raise_error(ArgumentError, /\Afind_by name was given as Windows-1252 text that cannot be converted to UTF-8/) - end - # Zammad's search sorts by updated_at, newest first, not by relevance, so - # the exact match can sit on any page of hits. Reading only the first one - # answered nil for a record that exists, and find_by(...) || create(...) - # then created its duplicate. + # the exact match can sit on any page of hits. context 'when more records match the term than one page holds' do let(:page_size) { ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE } let(:others) { Array.new(page_size) { { id: it + 1, name: 'Users Archive' } } } @@ -263,11 +222,6 @@ def stub_page(number, records) expect(proxy.find_by(name: 'Users')).to be_nil end - # Quoting a value that carries search syntax, to have it looked for rather - # than obeyed, cost more than it bought: an instance searching without - # Elasticsearch matches the term literally through a SQL LIKE, so the - # quotes became characters the value had to contain, and a hyphen is - # syntax - so `find_by(name: 'support-eu')` found nothing at all there. it 'sends a value carrying search syntax as it is' do stub = stub_request(:get, search_url) .with(query: hash_including('query' => 'support-eu')) @@ -309,11 +263,6 @@ def stub_page(number, records) expect(proxy.find_by(name: 'Users', active: true).id).to eq(2) end - # What a caller is promised: a record carrying both values comes back. - # The spec here asserted the query string instead - that "Users Support" - # went out - which a stub answers whatever it is handed, so nothing could - # see that an instance without Elasticsearch matches that term through a - # SQL LIKE per column and so finds neither of them. it 'finds a record by two string attributes' do stub_request(:get, search_url).with(query: hash_including({})) .to_return(json_response([{ id: 1, name: 'Users', note: 'Other' }, { id: 2, name: 'Users', note: 'Support' }])) @@ -321,7 +270,6 @@ def stub_page(number, records) expect(proxy.find_by(name: 'Users', note: 'Support').id).to eq(2) end - # The fence for the above: one value goes out, never the values joined. # Joined, the term is one no single column holds. it 'searches a single value rather than joining them' do stub = stub_request(:get, search_url) @@ -341,9 +289,6 @@ def stub_page(number, records) expect(stub).to have_been_requested end - # A non-string went to the search engine as the word it prints as, so - # `find_by(name: 'Users', active: true)` searched for "Users true" and - # matched nothing. it 'keeps a non-string value out of the search term, and still matches on it' do stub = stub_request(:get, search_url) .with(query: hash_including('query' => 'Users')) @@ -364,15 +309,12 @@ def stub_page(number, records) expect { proxy.find_by }.to raise_error(ArgumentError, /at least one attribute/) end - # find_by used to raise here, which left it working on four resources out - # of seven, and the caller writing all.detect by hand - the walk this makes. context 'with a resource Zammad routes no search endpoint for' do let(:states_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_states" } before do - stub_request(:get, states_url).with(query: hash_including('page' => '1')) + stub_request(:get, states_url).with(query: hash_including({})) .to_return(json_response([{ id: 1, name: 'new', state_type_id: 1 }, { id: 2, name: 'open', state_type_id: 2 }])) - stub_request(:get, states_url).with(query: hash_including('page' => '2')).to_return(json_response([])) end it 'walks the records and answers with the one that matches' do @@ -388,24 +330,17 @@ def stub_page(number, records) expect(a_request(:get, "#{states_url}/search").with(query: hash_including({}))).not_to have_been_made end - it 'stops at the page the match is on' do - client.ticket_states.find_by(name: 'new') - expect(a_request(:get, states_url).with(query: hash_including('page' => '2'))).not_to have_been_made - end - it 'matches on a value of any type' do expect(client.ticket_states.find_by(state_type_id: 2).name).to eq('open') end end - # A value that is not a string cannot be searched on - Zammad matches - # words, so it would go out as the word it prints as - and this used to - # raise for want of one. + # Zammad matches words, so a value that is not a string would go out as + # the word it prints as. context 'with no string value to search on' do before do - stub_request(:get, url).with(query: hash_including('page' => '1')) + stub_request(:get, url).with(query: hash_including({})) .to_return(json_response([{ id: 1, name: 'Users', active: false }, { id: 2, name: 'Support', active: true }])) - stub_request(:get, url).with(query: hash_including('page' => '2')).to_return(json_response([])) end it 'walks the index and answers with the first record that matches' do @@ -417,9 +352,8 @@ def stub_page(number, records) expect(a_request(:get, search_url).with(query: hash_including({}))).not_to have_been_made end - it 'answers nil once the whole index has been read' do + it 'answers nil where no record matches' do expect(proxy.find_by(active: nil)).to be_nil - expect(a_request(:get, url).with(query: hash_including('page' => '2'))).to have_been_made end it 'walks for a string value that is blank, which is nothing to search on either' do @@ -428,128 +362,21 @@ def stub_page(number, records) end end - # record[key] is nil for an attribute a record does not carry, so a nil - # value matched every record a misspelled name was asked of. it 'does not match nil against an attribute the record does not carry' do stub_request(:get, url).with(query: hash_including({})) - .to_return(json_response([{ id: 1, name: 'Users' }]), json_response([])) + .to_return(json_response([{ id: 1, name: 'Users' }])) expect(proxy.find_by(nmae: nil)).to be_nil end it 'does match nil against an attribute the record carries as nil' do stub_request(:get, url).with(query: hash_including({})) - .to_return(json_response([{ id: 1, name: 'Users', note: nil }]), json_response([])) + .to_return(json_response([{ id: 1, name: 'Users', note: nil }])) expect(proxy.find_by(note: nil).id).to eq(1) end end - # An id is what addresses a record, and the one value a search for it or - # a walk to it is the wrong way to find: given as an Integer the index was - # walked until the record came by, and given as the String a request - # parameter is, no hit ever carried it. - describe '#find_by with an id' do - let(:member_url) { "#{url}/5" } - - def stub_member(body = { id: 5, name: 'Users', active: true }) - stub_request(:get, member_url).with(query: hash_including({})).to_return(json_response(body)) - end - - def requests_made = a_request(:get, /#{Regexp.escape(url)}/) - - it 'reads the record by its id, in one request' do - stub_member - - expect(proxy.find_by(id: 5).name).to eq('Users') - expect(requests_made).to have_been_made.once - end - - it 'reads it expanded, as a search and an index serve it' do - stub = stub_request(:get, member_url).with(query: { 'expand' => 'true' }).to_return(json_response({ id: 5 })) - - proxy.find_by(id: 5) - expect(stub).to have_been_requested - end - - it 'finds the record by the String a request parameter is' do - stub_member - - expect(proxy.find_by(id: '5').id).to eq(5) - end - - it 'takes the id under a String key' do - stub_member - - expect(proxy.find_by('id' => 5).id).to eq(5) - end - - it 'answers nil where Zammad has no such record' do - stub_request(:get, member_url).with(query: hash_including({})).to_return(json_response({ error: 'not found' }, status: 404)) - - expect(proxy.find_by(id: 5)).to be_nil - end - - it 'raises from find_by! where Zammad has no such record' do - stub_request(:get, member_url).with(query: hash_including({})).to_return(json_response({ error: 'not found' }, status: 404)) - - expect { proxy.find_by!(id: 5) }.to raise_error(ZammadAPI::NotFoundError, /find object by id/) - end - - it 'answers with the record where it carries the other values too' do - stub_member - - expect(proxy.find_by(id: 5, name: 'Users', active: true).id).to eq(5) - end - - it 'answers nil where it does not carry one of them' do - stub_member - - expect(proxy.find_by(id: 5, name: 'Support')).to be_nil - end - - it 'answers nil where it lacks an attribute that was asked for' do - stub_member - - expect(proxy.find_by(id: 5, note: nil)).to be_nil - end - - it 'leaves any other failure to say what it is' do - stub_request(:get, member_url).with(query: hash_including({})).to_return(json_response({ error: 'Not authorized' }, status: 403)) - - expect { proxy.find_by(id: 5) }.to raise_error(ZammadAPI::AuthorizationError) - end - - # Zammad answers `organizations/5` with `{}` for a customer who belongs - # to no organization, whichever organization 5 is. - it 'answers nil for an object that carries no id' do - stub_member({}) - - expect(proxy.find_by(id: 5)).to be_nil - end - - it 'reads a String of digits as the number it writes' do - stub_member - - expect(proxy.find_by(id: '05').id).to eq(5) - end - - [nil, '', 'me', '5abc', ' 5', :me, 5.0, [5], '5'.encode('UTF-16LE'), "5\xff"].each do |value| - it "answers nil for #{value.inspect}, the id of no record, without a request" do - expect(proxy.find_by(id: value)).to be_nil - expect(requests_made).not_to have_been_made - end - end - - it 'does the same for a resource with no search endpoint' do - states_url = "#{ClientHelper::BASE_URL}api/v1/ticket_states" - stub_request(:get, "#{states_url}/2").with(query: hash_including({})).to_return(json_response({ id: 2, name: 'open' })) - - expect(unit_client.ticket_states.find_by(id: 2, name: 'open').id).to eq(2) - expect(a_request(:get, states_url).with(query: hash_including({}))).not_to have_been_made - end - end - describe '#find_by!' do let(:search_url) { "#{url}/search" } @@ -587,9 +414,6 @@ def requests_made = a_request(:get, /#{Regexp.escape(url)}/) end end - # An index that serves its whole list and reads no page was walked into the - # guard against an endpoint that ignores `page`, so a lookup that missed on - # the first page raised instead of answering nil. describe 'a resource whose index does not page' do subject(:proxy) { client.resource(resource) } @@ -636,7 +460,7 @@ def self.name = 'ObjectAttribute' resource.searchable true search = stub_request(:get, "#{url}/search") .with(query: hash_including('page' => '1', 'per_page' => described_class::SEARCH_MAX_PER_PAGE.to_s)) - .to_return(json_response({ records: [], total_count: 0 })) + .to_return(json_response([])) proxy.search('a').to_a expect(search).to have_been_requested @@ -657,14 +481,6 @@ def self.name = 'ObjectAttribute' expect(proxy.exists?(404)).to be(false) end - # What Zammad answers a customer who belongs to no organization with, - # for any organization id: 200 and an object with nothing in it. - it 'is false where Zammad answers with an object that names no record' do - stub_request(:get, "#{url}/5").with(query: hash_including({})).to_return(json_response({})) - - expect(proxy.exists?(5)).to be(false) - end - it 'does not swallow an authorization failure' do stub_request(:get, "#{url}/1").with(query: hash_including({})) .to_return(json_response({ error: 'no' }, status: 403)) @@ -693,20 +509,10 @@ def self.name = 'ObjectAttribute' expect(proxy.destroy(1)).to be(true) end - - # The page of something in front of Zammad that never passed the DELETE - # on. This answered true for it, with the record still in Zammad. - it 'raises ParseError for a 2xx whose body is not JSON' do - stub_request(:delete, "#{url}/1").to_return(status: 200, body: 'Please sign in', headers: { 'Content-Type' => 'text/html' }) - - expect { proxy.destroy(1) } - .to raise_error(ZammadAPI::ParseError, "Can't destroy object (ZammadAPI::Resources::Group): expected a JSON body or none, got text/html") - end end # What a collection over this endpoint fetches per request when nothing asks - # for another size: as many as the endpoint serves. Read off the resource - # rather than written out, so that these stubs follow the declaration. + # for another size: as many as the endpoint serves. def default_per_page = ZammadAPI::Resources::Group.page_limit describe '#all' do @@ -731,7 +537,7 @@ def default_per_page = ZammadAPI::Resources::Group.page_limit describe '#order' do it 'returns a sorted collection of every record' do stub = stub_request(:get, url) - .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s, 'sort_by' => 'name,id', 'order_by' => 'desc,asc' }) + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s, 'sort_by' => 'name', 'order_by' => 'desc' }) .to_return(json_response([])) proxy.order(name: :desc).to_a @@ -747,8 +553,6 @@ def default_per_page = ZammadAPI::Resources::Group.page_limit .to raise_error(ArgumentError, %r{api/v1/tickets is always served in the same order}) end - # where took a sort and refused nearly everything else, which is why it - # went: the name promised a filter an index endpoint does not have. it 'has no where to reach for instead' do expect(proxy).not_to respond_to(:where) end @@ -761,19 +565,12 @@ def stub_page(page, records, per_page: default_per_page) .to_return(json_response(records)) end - # The walk confirms a short page with one more request, so a collection - # that fits in a single page needs the empty page after it. - def stub_last_page(page, records, per_page: default_per_page) - stub_page(page, records, per_page: per_page) - stub_page(page + 1, [], per_page: per_page) - end - it 'is Enumerable' do expect(proxy).to be_a(Enumerable) end it 'yields every record from #each' do - stub_last_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) expect(proxy.map(&:name)).to eq(%w[Users Support]) end @@ -821,7 +618,7 @@ def stub_last_page(page, records, per_page: default_per_page) end it 'forwards #find_each' do - stub_last_page(1, [{ id: 1 }], per_page: 5) + stub_page(1, [{ id: 1 }], per_page: 5) ids = [] proxy.find_each(batch_size: 5) { ids << it.id } @@ -829,7 +626,7 @@ def stub_last_page(page, records, per_page: default_per_page) end it 'forwards #in_batches' do - stub_last_page(1, [{ id: 1 }], per_page: 5) + stub_page(1, [{ id: 1 }], per_page: 5) sizes = [] proxy.in_batches(of: 5) { sizes << it.size } @@ -837,56 +634,11 @@ def stub_last_page(page, records, per_page: default_per_page) end it 'forwards #pluck' do - stub_last_page(1, [{ id: 1, name: 'Users' }]) + stub_page(1, [{ id: 1, name: 'Users' }]) expect(proxy.pluck(:name)).to eq(['Users']) end - it 'forwards #size' do - stub_last_page(1, [{ id: 1 }]) - - expect(proxy.size).to eq(1) - end - - it 'forwards #length' do - stub_last_page(1, [{ id: 1 }]) - - expect(proxy.length).to eq(1) - end - - # A proxy is Enumerable, and Enumerable's own two ask for the size before - # they start, which is a walk of its own. - it 'forwards #each_slice, which walks the pages once' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - groups = [] - proxy.each_slice(2) { groups << it.map(&:id) } - expect(groups).to eq([[1, 2], [3]]) - expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.twice - end - - it 'forwards #each_cons, which walks the pages once' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - runs = [] - proxy.each_cons(2) { runs << it.map(&:id) } - expect(runs).to eq([[1, 2], [2, 3]]) - expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.twice - end - - it 'forwards #lazy, which slices without counting first' do - stub_last_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - expect(proxy.lazy.each_slice(2).first(1).map { it.map(&:id) }).to eq([[1, 2]]) - expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once - end - - it 'forwards #take, so it costs what #first costs' do - stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) - - expect(proxy.take(2).map(&:id)).to eq([1, 2]) - end - it 'forwards #first' do stub_page(1, [{ id: 1, name: 'Users' }], per_page: 1) @@ -899,22 +651,6 @@ def stub_last_page(page, records, per_page: default_per_page) expect(proxy).to be_empty end - # A proxy is Enumerable, so it had Enumerable's own, which read a page - # sized for walking to answer what one record answers. - it 'forwards #any? and #none?, which ask for a single record' do - stub_page(1, [{ id: 1, name: 'Users' }], per_page: 1) - - expect(proxy.any?).to be(true) - expect(proxy.none?).to be(false) - expect(a_request(:get, url).with(query: hash_including('per_page' => '1'))).to have_been_made.twice - end - - it 'forwards the block of #any? as well' do - stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }]), json_response([])) - - expect(proxy.any? { it.name == 'Users' }).to be(true) - end - it 'keeps #find as a lookup by id rather than Enumerable#find' do stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) @@ -945,16 +681,16 @@ def stub_last_page(page, records, per_page: default_per_page) it 'requests the search endpoint' do stub = stub_request(:get, "#{url}/search") - .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE.to_s, 'query' => 'support', 'with_total_count' => 'true' }) + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE.to_s, 'query' => 'support' }) .to_return(json_response([])) proxy.search('support').to_a expect(stub).to have_been_requested end - # The other things a search endpoint narrows by, named on the call that - # searches rather than passed to where on what it returned. - context 'with keywords the search endpoint reads' do + # Keywords go to the search endpoint as they are, for what it narrows by + # besides the term. + context 'with keywords' do let(:users_search) { "#{ClientHelper::BASE_URL}api/v1/users/search" } before { stub_request(:get, /search/).with(query: hash_including({})).to_return(json_response([])) } @@ -978,11 +714,6 @@ def stub_last_page(page, records, per_page: default_per_page) # Read off the URL Faraday built rather than asked of WebMock, which # takes a Hash keyed by numbers for an Array and reports # `group_ids[][0]=read` for a request that was never sent that way. - # - # Every pair naming a group, and not only the three that were written. - # Looked for as a substring, they were found in a query that named a - # fourth group beside them as well, and a group nobody asked for is a - # set of agents the search then keeps. it 'sends group_ids as a map of group to access, the way Rails reads a nested parameter back' do sent = nil recorder = Class.new(Faraday::Middleware) do @@ -1004,22 +735,6 @@ def stub_last_page(page, records, per_page: default_per_page) .to have_been_made end - # `condition: params.require(:condition).permit!`. It is not a Hash, - # so it was written as its `to_s`, which Zammad cannot read and drops: - # the search came back unnarrowed. - it 'sends a condition given as strong parameters the same way' do - condition = StrongParameters.new('ticket.state_id' => StrongParameters.new(operator: 'is', value: [1])) - client.tickets.search('x', condition: condition).to_a - - expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/search") - .with(query: hash_including('condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => ['1'] } }))) - .to have_been_made - end - - it 'refuses a condition given as strong parameters with nothing in them, as it does an empty Hash' do - expect { client.tickets.search('x', condition: StrongParameters.new({})) }.to raise_error(ArgumentError, /search was given condition/) - end - it 'accepts a keyword spelled as a string' do expect(client.users.search('x', 'ids' => [1])).to be_a(ZammadAPI::Collection) end @@ -1029,311 +744,15 @@ def stub_last_page(page, records, per_page: default_per_page) expect(a_request(:get, users_search).with(query: hash_including('query' => 'smith'))).to have_been_made end - # A collection is lazy: nothing is sent until it is enumerated. It held - # the caller's own Array, Hash and String until then, so changing one of - # them afterwards changed a search that had already been written and - # checked. - context 'when what it was given changes before the collection is read' do - it 'sends the ids it was given' do - ids = [1] - search = client.users.search('x', ids: ids) - ids << 2 - search.to_a - - expect(a_request(:get, users_search).with(query: hash_including('ids' => ['1']))).to have_been_made - end - - it 'sends the term it was given' do - term = +'smith' - search = client.users.search(term) - term << ' jones' - search.to_a - - expect(a_request(:get, users_search).with(query: hash_including('query' => 'smith'))).to have_been_made - end - - it 'sends the condition it was given, at every depth' do - condition = { 'ticket.state_id' => { operator: 'is', value: [1] } } - search = client.tickets.search('x', condition: condition) - condition['ticket.state_id'][:value] << 2 - condition['ticket.owner_id'] = { operator: 'is', value: [3] } - search.to_a - - expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/search") - .with(query: hash_including('condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => ['1'] } }))) - .to have_been_made - end - - it 'carries the copy through page and order' do - ids = [1] - search = client.users.search('x', ids: ids).order(:login).page(2) - ids << 2 - search.to_a - - expect(a_request(:get, users_search).with(query: hash_including('ids' => ['1'], 'page' => '2', 'sort_by' => 'login,id'))) - .to have_been_made - end - - it 'leaves what it was given writable' do - ids = [1] - client.users.search('x', ids: ids) - - expect(ids).not_to be_frozen - end - end - end - - # Zammad drops a parameter it does not know, so these would come back - # unnarrowed with nothing to say so. - context 'with a keyword the search endpoint would drop' do - it 'refuses an attribute name' do - expect { proxy.search('support', name: 'Users') } - .to raise_error(ArgumentError, %r{search does not take name on api/v1/groups: this search endpoint narrows by the term, and by condition, ids, and drops}) - end - - it 'says where an attribute value goes instead' do - expect { proxy.search('support', name: 'Users') } - .to raise_error(ArgumentError, /Put an attribute value in the term - search\('state\.name:open'\)/) - end - - it 'refuses a sort, and names order' do - expect { proxy.search('support', sort_by: 'name') } - .to raise_error(ArgumentError, /search does not take sort_by.*sort with search\(term\)\.order\(\.\.\.\)/) - end - - it 'refuses to replace the search term' do - expect { proxy.search('login failure', query: 'anything') }.to raise_error(ArgumentError, /search does not take query/) - end - - %i[page per_page expand only_total_count].each do |owned| - it "refuses #{owned}, which the collection controls itself" do - expect { proxy.search('support', owned => 1) }.to raise_error(ArgumentError, /search does not take #{owned}/) - end - end - - it 'makes no request' do - expect { proxy.search('support', name: 'Users') }.to raise_error(ArgumentError) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - end - - # model_search_render hands role_ids, group_ids and permissions to the - # search of every model, and only User::Search reads them. A ticket - # search given group_ids was sent as written and answered with tickets - # from every group the client can read. - context 'with a keyword only the user search reads' do - it 'refuses group_ids on tickets' do - expect { client.tickets.search('printer', group_ids: [2]) } - .to raise_error(ArgumentError, %r{search does not take group_ids on api/v1/tickets: this search endpoint narrows by the term, and by condition, ids, and drops}) - end - - it 'says how tickets are narrowed by group instead' do - expect { client.tickets.search('printer', group_ids: [2]) } - .to raise_error(ArgumentError, /or in a condition - search\(term, condition: \{'ticket\.group_id' => \{operator: 'is', value: \[2\]\}\}\)/) - end - - it 'refuses role_ids and permissions on organizations' do - expect { client.organizations.search('acme', role_ids: [2], permissions: ['ticket.agent']) } - .to raise_error(ArgumentError, /search does not take role_ids, permissions on/) - end - - it 'refuses them on groups' do - expect { proxy.search('support', group_ids: [1]) }.to raise_error(ArgumentError, /search does not take group_ids on/) - end - - it 'makes no request' do - expect { client.tickets.search('printer', group_ids: [2]) }.to raise_error(ArgumentError) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'still takes all three on users, and names them among what that search narrows by' do - expect(client.users.search('smith', role_ids: [2], group_ids: [3], permissions: ['ticket.agent'])).to be_a(ZammadAPI::Collection) - expect { client.users.search('smith', active: true) } - .to raise_error(ArgumentError, /and by condition, ids, role_ids, group_ids, permissions, and drops/) - end - - it 'still takes condition and ids on every search' do - expect(client.tickets.search('printer', ids: [1], condition: { 'ticket.group_id' => { operator: 'is', value: [2] } })) - .to be_a(ZammadAPI::Collection) - end - end - - context 'with a resource a caller declared' do - let(:role_class) do - Class.new(ZammadAPI::Resources::Base) do - def self.name = 'Role' - - path 'api/v1/roles' - searchable true - end - end - - it 'takes condition and ids, which every search reads' do - expect(client.resource(role_class).search('agent', ids: [1])).to be_a(ZammadAPI::Collection) - end - - it 'refuses a keyword it did not declare' do - expect { client.resource(role_class).search('agent', permissions: ['admin']) } - .to raise_error(ArgumentError, %r{search does not take permissions on api/v1/roles}) - end - - it 'takes a keyword it declared' do - role_class.search_filters :permissions - - expect(client.resource(role_class).search('agent', permissions: ['admin'])).to be_a(ZammadAPI::Collection) - end - end - - # Every one of these is refused at the call that wrote it, rather than - # when the collection is first read some lines away. - context 'with a keyword it cannot send' do - it 'refuses a nil value, which no query string can spell' do - expect { client.users.search('x', ids: nil) }.to raise_error(ArgumentError, /query parameter ids is nil/) - end - - # Zammad narrows by a keyword only where it is `present?`, so each of - # these was sent and answered with everything matching the term - for - # `ids: allowed_ids` with nothing allowed, where none was asked for. - { - ids: [], - role_ids: [], - permissions: [], - group_ids: {}, - condition: {} - }.each do |name, value| - it "refuses #{name}: #{value.inspect}, which Zammad reads as no #{name} at all" do - expect { client.users.search('smith', name => value) } - .to raise_error(ArgumentError, %r{search was given #{name}: #{Regexp.escape(value.inspect)} on api/v1/users}) - end - end - - it 'refuses a keyword given as a blank String' do - expect { client.users.search('smith', ids: ' ') }.to raise_error(ArgumentError, /search was given ids: " "/) - end - - # `present?` is false for it, so Zammad skips the filter. - it 'refuses one that holds only a Unicode space' do - expect { client.users.search('smith', permissions: "\u3000") }.to raise_error(ArgumentError, /search was given permissions:/) - end - - it 'refuses one that is blank in UTF-16, the way it does one in UTF-8' do - expect { client.users.search('smith', permissions: "\u3000".encode('UTF-16LE')) }.to raise_error(ArgumentError, /search was given permissions:/) - end - - it 'takes one given in UTF-16 that is not blank' do - expect(client.users.search('smith', permissions: 'admin'.encode('UTF-16LE'))).to be_a(ZammadAPI::Collection) - end - - # Sent as `permissions=`, which is as blank as a String with nothing in - # it: the check is of what is sent, not of the class it was given as. - it 'refuses one given as a value whose text is empty' do - expect { client.users.search('smith', permissions: :'') }.to raise_error(ArgumentError, /search was given permissions: :""/) - end - - # Nothing is written for an empty Hash, so the request went out with no - # condition at all. - it 'refuses a condition that holds nothing but empty Hashes' do - expect { client.tickets.search('printer', condition: { 'ticket.state_id' => {} }) } - .to raise_error(ArgumentError, /search was given condition: \{"ticket.state_id" => \{\}\}/) - end - - # The keyword itself is written, by its other condition, and the one - # that holds nothing was dropped from the request. - it 'refuses a condition that holds an empty Hash beside one that is written' do - condition = { 'ticket.state_id' => {}, 'ticket.title' => { operator: 'contains', value: 'printer' } } - - expect { client.tickets.search('printer', condition: condition) } - .to raise_error(ArgumentError, /query parameter condition\[ticket\.state_id\] is a Hash with no value in it/) - end - - it 'refuses group_ids naming a group with nothing under it' do - expect { client.users.search('smith', group_ids: { 2 => {} }) }.to raise_error(ArgumentError, /search was given group_ids:/) - end - - it 'says what the search would have come back with' do - expect { client.users.search('smith', ids: []) } - .to raise_error(ArgumentError, /everything matching the term, not narrowed to nothing/) - end - - it 'names every empty keyword at once' do - expect { client.users.search('smith', ids: [], role_ids: []) }.to raise_error(ArgumentError, /search was given ids: \[\], role_ids: \[\] on/) - end - - it 'makes no request for one' do - stub = stub_request(:get, /search/).with(query: hash_including({})) - - expect { client.users.search('smith', ids: []).to_a }.to raise_error(ArgumentError) - expect(stub).not_to have_been_requested - end - - # What is nested in a condition is a selector, and Zammad's to read. - it 'still takes a condition whose value is empty' do - expect(client.tickets.search('x', condition: { 'ticket.tags' => { operator: 'contains all', value: [] } })).to be_a(ZammadAPI::Collection) - end - - # An empty list is written, as `condition[ticket.tags][value][]`, so - # the condition reaches Zammad. - it 'still takes a condition that holds nothing but an empty list' do - expect(client.tickets.search('x', condition: { 'ticket.tags' => { value: [] } })).to be_a(ZammadAPI::Collection) - end - - it 'still takes a value that is not empty for being false or zero' do - expect(client.users.search('smith', ids: [0])).to be_a(ZammadAPI::Collection) - end - - it 'refuses two spellings of one keyword rather than dropping a value' do - expect { client.users.search('x', 'ids' => [1], :ids => [2]) } - .to raise_error(ArgumentError, /ids was given twice, as "ids" and as :ids/) - end - - it 'refuses two spellings of one key nested inside a condition' do - expect { client.tickets.search('x', condition: { 'state_id' => 1, :state_id => 2 }) } - .to raise_error(ArgumentError, /parameter condition\[state_id\] was given twice/) - end - - # A group of conditions and a condition share `operator`, which is what - # lets a query string keep them apart. Two elements that share nothing - # would reach Zammad as one, so the search says so here. - it 'refuses a list of conditions a query string cannot keep apart' do - expect { client.tickets.search('x', condition: { conditions: [{ name: 'ticket.state_id' }, { operator: 'AND' }] }) } - .to raise_error(ArgumentError, /query parameter condition\[conditions\]\[1\] has no plain value under a key the element before it has/) - end - - # Read off the URL Faraday built, in the order it was written: WebMock - # sorts a query before it compares one, and the order is the point. - # Rails begins the second element at its `operator`, so that has to - # come before the conditions it holds, or the group is read into the - # condition before it. - it 'takes a condition that holds a group of conditions, and sends the group as an element of its own' do - nested = { operator: 'OR', conditions: [{ name: 'ticket.state_id', operator: 'is', value: [2] }, { operator: 'AND', conditions: [{ name: 'ticket.group_id', operator: 'is', value: [1] }] }] } - sent = nil - recorder = Class.new(Faraday::Middleware) do - define_method(:on_request) { |env| sent = URI.decode_www_form(env.url.query).map(&:first) } - end - stub_request(:get, /search/).with(query: hash_including({})).to_return(json_response([])) - - search = unit_client(middleware: ->(builder) { builder.use(recorder) }).tickets.search('x', condition: nested) - expect(search).to be_a(ZammadAPI::Collection) - - search.to_a - expect(sent.grep(/\Acondition\[conditions\]/)).to eq( - [ - 'condition[conditions][][name]', 'condition[conditions][][operator]', 'condition[conditions][][value][]', - 'condition[conditions][][operator]', 'condition[conditions][][conditions][][name]', - 'condition[conditions][][conditions][][operator]', 'condition[conditions][][conditions][][value][]' - ] - ) - end - - it 'still accepts a condition whose keys only look alike' do - expect(client.tickets.search('x', condition: { 'ticket.state_id' => { operator: 'is' }, 'ticket.group_id' => { operator: 'is' } })) - .to be_a(ZammadAPI::Collection) + it 'sends any other keyword as it is, for Zammad to read or drop' do + proxy.search('support', name: 'Users').to_a + expect(a_request(:get, "#{url}/search").with(query: hash_including('query' => 'support', 'name' => 'Users'))).to have_been_made end end it 'sorts through order on the collection it returns' do stub = stub_request(:get, "#{url}/search") - .with(query: hash_including('query' => 'support', 'sort_by' => 'name,id', 'order_by' => 'asc,asc')) + .with(query: hash_including('query' => 'support', 'sort_by' => 'name', 'order_by' => 'asc')) .to_return(json_response([])) proxy.search('support').order(:name).to_a @@ -1348,14 +767,6 @@ def self.name = 'Role' expect { proxy.search(' ') }.to raise_error(ArgumentError, /non-empty query string/) end - # Zammad asks `blank?`, which counts Unicode spaces, and answers a blank - # term with every record. - ["\u00A0", "\u3000", "\u3000".encode('UTF-16LE')].each do |blank| - it "rejects #{blank.inspect}, which Zammad reads as no term" do - expect { proxy.search(blank) }.to raise_error(ArgumentError, /non-empty query string/) - end - end - it "says that '*' asks for every record" do expect { proxy.search('') }.to raise_error(ArgumentError, /Search for '\*' to ask for every record/) end diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index 88a43ea..a4750a6 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -34,30 +34,11 @@ def self.name expect(group.note).to eq('from a string key') end - # A record built from a Hash put together across several merges held - # whichever spelling Hash order put last, and sent that. - it 'refuses one attribute under two spellings rather than keeping the last' do - expect { client.groups.new('name' => 'Support', name: 'Sales') } - .to raise_error(ArgumentError, /attribute name was given twice, as "name" and as :name/) - end - - it 'refuses two spellings on create before anything is sent' do - expect { client.groups.create('name' => 'Support', name: 'Sales') }.to raise_error(ArgumentError, /given twice/) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'refuses two spellings inside a value a writer is given' do - expect { group.preferences = { 'locale' => 'de', locale: 'en' } }.to raise_error(ArgumentError, /attribute locale was given twice/) - expect(group).not_to be_changed - end - it 'starts without changes' do expect(group).not_to be_changed end - # What a Rails controller holds. It is not a Hash, so it was stored as - # it was handed over: the record held the caller's own object, printed - # its password, and saved it as one JSON string. + # What a Rails controller holds: not a Hash, but it converts to one. context 'when given strong parameters, which convert to a Hash and are not one' do subject(:user) { client.users.new(permitted) } @@ -85,39 +66,13 @@ def self.name expect(stub).to have_been_requested end - it 'reads them as a Hash where they are the value of an attribute' do - expect(client.users.new(login: 'jane', preferences: StrongParameters.new(locale: 'de')).preferences).to eq(locale: 'de') - end - - it 'reads them as a Hash where a writer is given them' do - user.preferences = StrongParameters.new(locale: 'en') - - expect(user.preferences).to eq(locale: 'en') - end - it 'leaves the refusal of parameters that were not permitted to say so' do expect { client.users.new(StrongParameters.new({ login: 'jane' }, permitted: false)) }.to raise_error(StrongParameters::Unfiltered) end end - # Each of these reached a method of Hash and raised NoMethodError for - # it, and an Array of pairs was stored as the attributes. - context 'when given what is no set of attributes' do - it 'refuses a String, naming its class' do - expect { client.groups.new('name') }.to raise_error(ArgumentError, 'attributes need to be a Hash of names and values, got String') - end - - it 'refuses an Array of pairs' do - expect { client.groups.new([[:name, 'Support']]) }.to raise_error(ArgumentError, /got Array/) - end - - it 'refuses a Struct, which has a to_h and does not claim to be a Hash' do - expect { client.groups.new(Struct.new(:name).new('Support')) }.to raise_error(ArgumentError, /attributes need to be a Hash/) - end - - it 'still takes nil for no attributes' do - expect(client.groups.new(nil).attributes).to eq({}) - end + it 'takes nil for no attributes' do + expect(client.groups.new(nil).attributes).to eq({}) end it 'records a change as old and new value' do @@ -171,12 +126,7 @@ def self.name expect(carrying_nil.changes).to be_empty end - # An attribute the record does not carry is not an attribute whose value - # is nil: Zammad reduces the object it serializes for a permission-scoped - # client, so the key being absent says nothing about what is stored. Read - # as a nil original, writing nil to one compared equal, staged nothing and - # was still merged into the attributes - the write was dropped without a - # word and the record went on reporting a key Zammad never sent it. + # An attribute the record does not carry is not one whose value is nil. it 'stages a write of an attribute the record does not carry' do group.active = nil expect(group.changes).to eq(active: [nil, nil]) @@ -235,80 +185,6 @@ def self.name group.save! expect { group.attributes[:preferences][:note] << '!' }.to raise_error(FrozenError) end - - # Ruby quotes the frozen object in the error for a write to it, and the - # message of an error is what a log and an error tracker keep. - context 'with a credential among the attributes' do - subject(:user) { client.users.new(login: 'jane', password: 'hunter2', preferences: { bind_pw: 's3cret', locale: 'de' }) } - - def message_of - yield - nil - rescue FrozenError => e - e.message - end - - it 'does not quote a staged password in the error for a write to #attributes' do - expect(message_of { user.attributes[:vip] = true }) - .to eq(%(can't modify frozen ZammadAPI::Attributes: {login: "jane", password: "[REDACTED]", preferences: {bind_pw: "[REDACTED]", locale: "de"}})) - end - - it 'does not quote a credential in the error for a write to a nested Hash' do - expect(message_of { user.attributes[:preferences][:x] = 1 }) - .to eq(%(can't modify frozen ZammadAPI::Attributes: {bind_pw: "[REDACTED]", locale: "de"})) - end - - it 'does not quote either password in the error for a write to #changes' do - user.password = 'correct horse' - - expect(message_of { user.changes[:x] = 1 }) - .to eq(%(can't modify frozen ZammadAPI::Attributes: {password: "[REDACTED]"})) - end - - it 'does not quote one that was written after the record was built' do - user.password = 'correct horse' - - expect(message_of { user.attributes[:vip] = true }).to include('password: "[REDACTED]"') - end - - it 'still reads every value as it is' do - expect(user.attributes).to eq(login: 'jane', password: 'hunter2', preferences: { bind_pw: 's3cret', locale: 'de' }) - end - - it 'hands out plain Hashes from #to_h, which print what they hold' do - expect(user.to_h).to be_an_instance_of(Hash).and(satisfy { it[:preferences].instance_of?(Hash) }) - end - - # An encoder that takes nothing but the core types goes by the class, - # and `attributes.to_h` was plain no further than its first Hash. - it 'hands out plain Hashes from attributes.to_h, for a strict JSON encoder' do - expect(JSON.generate(user.attributes.to_h, strict: true)).to eq(JSON.generate(user.to_h)) - end - - it 'hands out plain Hashes from changes.to_h' do - user.preferences = { bind_pw: 'other', locale: 'en' } - - expect(JSON.generate(user.changes.to_h, strict: true)) - .to eq('{"preferences":[{"bind_pw":"s3cret","locale":"de"},{"bind_pw":"other","locale":"en"}]}') - end - - it 'hands out a plain Hash from to_h of a Hash it holds' do - expect(JSON.generate(user.preferences.to_h, strict: true)).to eq('{"bind_pw":"s3cret","locale":"de"}') - end - end - - # A save whose answer cannot be read puts the record on what it sent, - # cut to the attributes it arrived with, and `slice` hands back a plain - # Hash whatever it was called on. - it 'hands out an Attributes after a save whose answer could not be read' do - stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) - stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return(unreadable_json_response) - found = client.groups.find(1) - found.name = 'Support' - - expect { found.save! }.to raise_error(ZammadAPI::ParseError) - expect(found.attributes).to be_a(ZammadAPI::Attributes).and be_frozen - end end describe '#save' do @@ -540,58 +416,13 @@ def message_of expect(group).not_to be_changed end - # Each key is written by its Symbol, so the attribute was written twice - # and whichever spelling came last in the Hash was the one staged. - context 'with one attribute under two spellings' do - it 'refuses the pair' do - expect { group.assign_attributes('name' => 'A', name: 'B') } - .to raise_error(ArgumentError, /attribute name was given twice, as "name" and as :name/) - end - - it 'stages nothing' do - expect { group.assign_attributes(:note => 'Why', 'name' => 'A', :name => 'B') }.to raise_error(ArgumentError) - expect(group).not_to be_changed - end - - it 'stages nothing where the pair is inside a later value' do - expect { group.assign_attributes(note: 'Why', preferences: { 'locale' => 'de', locale: 'en' }) } - .to raise_error(ArgumentError, /attribute locale was given twice/) - expect(group).not_to be_changed - end - end - - # The constructor makes a Symbol of a key where it can and keeps one it - # cannot. Here every key went through `to_sym`, so the Hash the - # constructor takes raised NoMethodError from inside the gem. it 'keeps a key that cannot become a Symbol, as the constructor does' do group.assign_attributes(1 => 'x') expect(group.attributes).to eq(client.groups.new(:name => 'Support', 1 => 'x').attributes) end - # Handed straight to a method of Hash, so what was not one raised - # NoMethodError naming that method, and an Array was read as pairs. - context 'with something that is not a Hash' do - it 'refuses nil, and names the class it was given' do - expect { group.assign_attributes(nil) }.to raise_error(ArgumentError, 'attributes need to be a Hash of names and values, got NilClass') - end - - it 'refuses a String' do - expect { group.assign_attributes('name') }.to raise_error(ArgumentError, /got String/) - end - - it 'refuses an Array of pairs rather than reading it as a Hash' do - expect { group.assign_attributes([[:name, 'Renamed']]) }.to raise_error(ArgumentError, /got Array/) - expect(group).not_to be_changed - end - - it 'does not quote what it was given, which may hold a credential' do - expect { group.assign_attributes('password=hunter2') }.to raise_error(ArgumentError) { expect(it.message).not_to include('hunter2') } - end - end - - # `record.update(params.require(:group).permit(:name))`. It raised - # NoMethodError naming `each_with_object`. + # `record.update(params.require(:group).permit(:name))` context 'with strong parameters' do it 'stages what they convert to' do group.assign_attributes(StrongParameters.new(name: 'Renamed', note: 'Why')) @@ -655,23 +486,11 @@ def message_of expect(client.groups.new.update(name: 'Support')).to be(true) expect(stub).to have_been_requested end - - # `update(params[:group])` with the key missing. It raised NoMethodError - # for nil, from inside the gem. - it 'refuses nil, and sends nothing' do - expect { group.update(nil) }.to raise_error(ArgumentError, /attributes need to be a Hash of names and values, got NilClass/) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end end describe '#update!' do subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, note: 'old') } - it 'refuses nil, and sends nothing' do - expect { group.update!(nil) }.to raise_error(ArgumentError, /got NilClass/) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - it 'returns true' do stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1 })) @@ -749,10 +568,6 @@ def message_of it 'escapes an id that would otherwise leave its segment' do expect(ZammadAPI::Resources::Group.member_path('1/../users')).to eq('api/v1/groups/1%2F..%2Fusers') end - - it 'refuses an id that navigates' do - expect { ZammadAPI::Resources::Group.member_path('..') }.to raise_error(ArgumentError) - end end describe '#destroy' do @@ -764,19 +579,29 @@ def message_of expect(stub).to have_been_requested end + it 'takes a 204 for a deleted record' do + stub_request(:delete, "#{url}/1").to_return(status: 204) + + expect(group.destroy).to be(true) + expect(group).to be_destroyed + end + + it 'takes the empty object Zammad answers with for a group' do + stub_request(:delete, "#{url}/1").to_return(json_response({})) + + expect(group.destroy).to be(true) + expect(group).to be_destroyed + end + it 'raises for a record that was never saved' do expect { client.groups.new.destroy }.to raise_error(ZammadAPI::Error, /has not been saved, so there is nothing to destroy/) end - # `destroy` asked only whether the record was already destroyed, so one - # built with an id it was simply handed issued a real DELETE for a record - # it does not stand for. The constructor refuses that id now, so there is - # no such record left to destroy. it 'sends nothing for a record built with an id it was never saved with' do stub = stub_request(:delete, "#{url}/99") expect { client.groups.new(id: 99, name: 'X').destroy } - .to raise_error(ZammadAPI::Error, /is what addresses this record/) + .to raise_error(ZammadAPI::Error, /has not been saved, so there is nothing to destroy/) expect(stub).not_to have_been_requested end @@ -802,9 +627,6 @@ def message_of expect { group.save }.to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to save/) end - # `reload` re-read a record that no longer exists and cleared the flag on - # the way back, so the record came back reporting itself as persisted and - # its next save issued a PUT against the deleted path. it 'refuses a reload rather than resurrecting the record' do expect { group.reload } .to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to reload/) @@ -831,58 +653,20 @@ def message_of group.name = 'Support' end - it 'drops a change that can never be sent' do + it 'leaves the attributes as they are, the staged change included' do group.destroy - expect(group).not_to be_changed - expect(group.changes).to be_empty - end - - # Readable as Zammad last served them. The staged write above was never - # sent, and dropping the change set without it left the record reporting - # "Support" while `changed?` was false and `changes` was empty - so - # nothing was left to tell a local edit apart from a value the server - # gave, in the one state where it can never be saved. - it 'keeps the attributes readable, so a destroyed record can still be reported on' do - group.destroy - - expect(group.id).to eq(1) - expect(group.name).to eq('Users') - end - - it 'does not report a write Zammad never saw' do - group.destroy - - expect(group.attributes).to eq({ id: 1, name: 'Users' }) - expect(group.inspect).not_to include('Support') + expect(group.name).to eq('Support') + expect(group.changes).to eq(name: %w[Users Support]) end it 'refuses the association readers, which would request a record that is gone' do group.destroy - # The guarantee, not the mechanism that was expected to deliver it. - # This compared the proxy against the one from before the destroy, - # which clearing the memo satisfied - while `related` went on - # rebuilding a working proxy on the very next call. It passed for as - # long as the behaviour it is named for was broken. expect { group.related }.to raise_error(ZammadAPI::Error, /was destroyed/) end - - it 'drops the failure of a save that is over' do - stub_request(:put, "#{url}/1").with(query: hash_including({})) - .to_return(json_response({ error: 'Name is required' }, status: 422)) - group.save - - expect(group.error).to be_a(ZammadAPI::ValidationError) - group.destroy - expect(group.error).to be_nil - end end - # `update` stages before it saves, and `save!` is where the destroyed - # check used to live. That order left a destroyed record holding a change - # set that can never be sent - the state destroy clears the staged changes - # to prevent - so the refusal happens before anything is written. context 'when an update is attempted after it was destroyed' do before do stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') @@ -919,9 +703,6 @@ def message_of end end - # `update` refused a destroyed record, and the writers it is built on did - # not: a write left the record changed and reading a value Zammad never - # saw, and the save after it was the first thing to object. context 'when an attribute is written after it was destroyed' do subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'A') } @@ -955,15 +736,9 @@ def message_of expect { group.assign_attributes(note: 'n', name: 'Z') }.to raise_error(ZammadAPI::Error) expect(group.to_h).to eq({ id: 1, name: 'A' }) end - - it 'still refuses the id for the reason an id is refused' do - expect { group.assign_attributes(id: 9) }.to raise_error(ZammadAPI::Error, /cannot be staged/) - end end end - # The attributes are frozen and replaced on write, so a copy never saw the - # original's next write. The change set is written in place, and was shared. describe 'a copy made with dup or clone' do let(:original) { client.groups.find(1) } @@ -1156,10 +931,6 @@ def message_of end end - # A plain class-level ivar is not inherited, so a subclass used to inherit - # every association, the page limit and the searchability, and lose only the - # API path - raising "does not declare an API path" from a class that - # plainly did. describe 'a resource subclassed by a caller' do subject(:subclass) { Class.new(ZammadAPI::Resources::Ticket) { def self.name = 'MyTicket' } } @@ -1175,20 +946,6 @@ def message_of expect(subclass.searchable?).to be(true) end - it 'inherits the filters its parent\'s search reads' do - expect(Class.new(ZammadAPI::Resources::User).search_filter_names).to eq(%i[role_ids group_ids permissions]) - end - - it 'has no search filters of its own unless it or a parent declares some' do - expect(subclass.search_filter_names).to eq([]) - end - - it 'takes filter names as strings too' do - subclass.search_filters 'role_ids' - - expect(subclass.search_filter_names).to eq([:role_ids]) - end - it 'inherits the page limit' do expect(subclass.page_limit).to eq(100) end @@ -1203,7 +960,7 @@ def message_of expect(Class.new(unpaged).paginated?).to be(false) end - it 'inherits the associations, as it always did' do + it 'inherits the associations' do expect(subclass.associations.keys).to eq(ZammadAPI::Resources::Ticket.associations.keys) end @@ -1223,10 +980,6 @@ def message_of end end - # Declared as bare constants, a misspelled override was silently ignored and - # the resource kept Base's default: SEARCHEABLE = true left the resource - # unsearchable, and every find_by on it raised "Zammad routes no search - # endpoint" with no hint that the declaration was the problem. describe 'the endpoint declarations' do it 'refuses a misspelled declaration at load' do expect { Class.new(described_class) { searcheable true } } @@ -1279,26 +1032,6 @@ def message_of end end - # The id is what addresses the record. Staged, it took effect for every path - # that builds a path from the attributes and not at all for the record those - # paths then reported on: `group.id = 99; group.destroy` sent DELETE to group - # 99 and left the record saying group 1 was the one destroyed. - # The parent is resolved before MEMO_LOCK is taken, because resolving it may - # build the parent's own proxy through this same method and a Mutex is not - # reentrant. Folded back inside the lock this raises - # `ThreadError: deadlock; recursive locking`, and a caller subclassing a - # resource is the case that lock exists to cover in the first place. - describe 'the association proxy of a subclass whose parent has none yet' do - it 'builds without deadlocking on the memo lock' do - leaf = Class.new(Class.new(ZammadAPI::Resources::Group)) - - expect(leaf.related_class).to be_a(Class) - end - end - - # `record[:x] = v` reached method_missing as `:[]=`, which the writer branch - # took for an attribute called `[]`: it staged the index as the value, lost - # the write, and sent `{"[]": "x"}` on the next save. describe '#[]=' do subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } @@ -1321,7 +1054,7 @@ def message_of end it 'refuses what the named writer refuses' do - expect { group[:id] = 9 }.to raise_error(ZammadAPI::Error, /cannot be staged as an attribute/) + expect { group[:id] = 9 }.to raise_error(ZammadAPI::Error, /cannot be changed/) end it 'invents no attribute from the operator itself' do @@ -1334,14 +1067,6 @@ def message_of expect(group).to respond_to(:[]=) end - it 'is claimed under either spelling' do - # rubocop:disable-next Performance/StringIdentifierArgument -- the String spelling is the point - expect(group.respond_to?('[]=')).to be(true) - end - - # The production case for recognising a writer by name rather than by a - # trailing `=`: on a record that stages writes, an operator reached the - # writer branch and invented an attribute from its stem. it 'invents no attribute from a comparison operator' do expect { group.public_send(:<=, 5) }.to raise_error(NoMethodError) @@ -1359,64 +1084,17 @@ def message_of subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } it 'is refused' do - expect { group.id = 99 }.to raise_error(ZammadAPI::Error, /is what addresses this record/) - end - - it 'points at the lookup that was meant' do - expect { group.id = 99 }.to raise_error(ZammadAPI::Error, /look up the record you meant with find\(99\)/) + expect { group.id = 99 } + .to raise_error(ZammadAPI::Error, 'ZammadAPI::Resources::Group#id cannot be changed: it is what addresses this record') end it 'is refused through assign_attributes too' do - expect { group.assign_attributes(id: 99) }.to raise_error(ZammadAPI::Error, /is what addresses this record/) - end - - # The message exists to name the id the caller passed, and the pre-check - # that runs for these two paths dropped it - so a serializer or a form - # binder, which reach the writer this way, were told to call find(nil). - it 'names the id that was passed through assign_attributes' do - expect { group.assign_attributes(id: 99) }.to raise_error(ZammadAPI::Error, /find\(99\)/) - end - - it 'names the id that was passed through update' do - expect { group.update(id: 99) }.to raise_error(ZammadAPI::Error, /find\(99\)/) - end - - it 'names the attribute it refused' do - expect { group.id = 99 }.to raise_error(ZammadAPI::Error, /Group#id cannot be staged/) + expect { group.assign_attributes(id: 99) }.to raise_error(ZammadAPI::Error, /cannot be changed/) end - # Checked before anything is written, not on the way past: refusing - # mid-loop staged the keys that came first and left the record dirty with - # half a change set, which is the state `update` takes its own guard one - # line early to avoid. - it 'stages nothing at all when one key in the hash is refused' do - expect { group.assign_attributes(name: 'X', id: 99, note: 'Y') }.to raise_error(ZammadAPI::Error) - - expect(group).not_to be_changed - expect(group.changes).to be_empty - end - - it 'leaves the attributes it had already reached alone' do - expect { group.assign_attributes(name: 'X', id: 99, note: 'Y') }.to raise_error(ZammadAPI::Error) - - expect(group.name).to eq('Users') - end - - it 'stages nothing through update either' do - expect { group.update(name: 'X', id: 99) }.to raise_error(ZammadAPI::Error) - - expect(group).not_to be_changed - end - - # A record that claimed a writer and then raised when it was called would - # defeat the point of asking, and lead a serializer or form binder straight - # into the exception it was checking to avoid. - it 'does not claim a writer it would refuse' do - expect(group).not_to respond_to(:id=) - end - - it 'still claims the writers it honours' do - expect(group).to respond_to(:name=) + it 'is refused through update too, and sends nothing' do + expect { group.update(id: 99) }.to raise_error(ZammadAPI::Error, /cannot be changed/) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made end it 'leaves the record addressing what it did before' do @@ -1426,11 +1104,8 @@ def message_of expect(group).not_to be_changed end - # The constructor was the one door that did not make this refusal, and - # the only one whose value reached the wire: a new record is sent in full, - # so `new(id: 5).save` POSTed the id nothing had checked. - it 'is refused by the constructor too' do - expect { client.groups.new(id: 5) }.to raise_error(ZammadAPI::Error, /is what addresses this record/) + it 'is taken by the constructor' do + expect(client.groups.new(id: 5).id).to eq(5) end it 'still lets a record Zammad served carry one' do @@ -1438,516 +1113,35 @@ def message_of end end - # The third way a record ends up persisted without an id, and the one that - # has nothing to do with a save: Zammad serves a reduced object where the - # authenticated user may not see the whole record, which is the same thing - # #write_attribute is written around. Such a record used to be told it "was - # saved, but the response carried no id" - sending the caller to look at a - # save that never happened, when what they need is which user the client - # authenticates as. describe 'a record Zammad served without an id' do subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, name: 'Users') } it 'refuses a reload it cannot address' do - expect { group.reload }.to raise_error(ZammadAPI::Error, /was loaded without an id/) + expect { group.reload }.to raise_error(ZammadAPI::Error, 'ZammadAPI::Resources::Group has no id, save it first') end - it 'points at what this client may read' do - expect { group.destroy }.to raise_error(ZammadAPI::Error, /check what this client may read/) - end - - it 'does not claim a save that never happened' do - expect { group.reload }.to raise_error(ZammadAPI::Error) { |error| expect(error.message).not_to include('was saved') } - end - - it 'does not tell the caller to save a record Zammad already holds' do - expect { group.destroy }.to raise_error(ZammadAPI::Error) { |error| expect(error.message).not_to include('save it first') } + it 'refuses a destroy it cannot address' do + expect { group.destroy }.to raise_error(ZammadAPI::Error, /has no id/) end it 'refuses a save it cannot address' do group.name = 'Support' - expect { group.save! }.to raise_error(ZammadAPI::Error, /was loaded without an id/) - end - - it 'still says the record was saved where a save is what left it this way' do - stub_request(:post, url).with(query: hash_including({})).to_return(unreadable_json_response(status: 201)) - new_group = client.groups.new(name: 'Support') - begin - new_group.save - rescue ZammadAPI::ParseError - nil - end - - expect { new_group.reload }.to raise_error(ZammadAPI::Error, /was saved, but the response carried no id/) - end - end - - # What makes a record persisted is that Zammad answered 2xx, not that the - # answer parsed. Decoded first, a create whose 201 carried a body cut off - # or rewritten on its way through a proxy raised ParseError with the record - # still looking new - so the ticket existed in Zammad and a retried save - # POSTed a second one. Marked persisted, the record has no id to be - # addressed by either, and nothing staged to send, so the retry has to say - # so rather than take the "nothing to send" short circuit and report - # success. - describe 'a create whose success body cannot be parsed' do - subject(:group) { client.groups.new(name: 'Support') } - - before { stub_request(:post, url).with(query: hash_including({})).to_return(unreadable_json_response(status: 201)) } - - it 'still reports the parse failure' do - expect { group.save }.to raise_error(ZammadAPI::ParseError) - end - - it 'does not leave the record looking unsaved' do - begin - group.save - rescue ZammadAPI::ParseError - nil - end - - expect(group.new_record?).to be(false) - end - - it 'does not create a second record when the save is retried' do - 2.times do - group.save - rescue ZammadAPI::Error - nil - end - - expect(a_request(:post, url).with(query: hash_including({}))).to have_been_made.once - end - - it 'refuses the retried save rather than reporting it stored' do - begin - group.save - rescue ZammadAPI::ParseError - nil - end - - expect { group.save }.to raise_error(ZammadAPI::Error, /carried no id/) - end - - it 'refuses to reload a record it cannot address' do - begin - group.save - rescue ZammadAPI::ParseError - nil - end - - expect { group.reload }.to raise_error(ZammadAPI::Error, /carried no id/) - end - - it 'does not tell the caller to save a record that was already saved' do - begin - group.save - rescue ZammadAPI::ParseError - nil - end - - expect { group.destroy }.to raise_error(ZammadAPI::Error, /was saved/) - end - - # An update keeps only what Zammad had served the record with. A record - # being created was served nothing, and what it sent is all there is to - # read from it. - it 'goes on reading everything it sent, written after it was built or not' do - group.note = 'Second line' - begin - group.save - rescue ZammadAPI::ParseError - nil - end - - expect(group.attributes).to eq(name: 'Support', note: 'Second line') + expect { group.save! }.to raise_error(ZammadAPI::Error, /has no id/) end end - # The same argument for what was staged. Zammad answered 2xx, so it applied - # the changes, and they used to stay staged because the body did not parse: - # the next save sent all of them again. For a ticket's `article` that is a - # second article and a second e-mail, from a save that was about the title. - describe 'an update whose success body cannot be parsed' do - subject(:ticket) { client.tickets.find(1) } - - let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/1" } - let(:article) { { body: 'Reset link sent.', type: 'email', to: 'customer@example.com' } } - - before do - stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, title: 'Help', note: nil })) - stub_request(:put, ticket_url).with(query: hash_including({})) - .to_return(unreadable_json_response, json_response({ id: 1, title: 'Renamed' })) - - ticket.article = article - begin - ticket.save - rescue ZammadAPI::ParseError - nil - end - end - - it 'still reports the parse failure' do - other = client.tickets.find(1) - other.note = 'x' - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(unreadable_json_response) - - expect { other.save }.to raise_error(ZammadAPI::ParseError) - end - - it 'no longer holds the changes Zammad acknowledged as staged' do - expect(ticket.changed?).to be(false) - expect(ticket.changes).to eq({}) - end - - it 'does not send the acknowledged changes again with the next save' do - ticket.title = 'Renamed' - ticket.save - - expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { title: 'Renamed' })).to have_been_made.once - expect(a_request(:put, ticket_url).with(query: hash_including({}), body: hash_including('article' => anything))).to have_been_made.once - end - - it 'sends nothing for a save with nothing new staged' do - expect(ticket.save).to be(true) - expect(a_request(:put, ticket_url).with(query: hash_including({}))).to have_been_made.once - end - - it 'goes on reading the values it sent for the attributes Zammad serves' do - other = client.tickets.find(1) - other.title = 'Sent' - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(unreadable_json_response) - begin - other.save - rescue ZammadAPI::ParseError - nil - end - - expect(other.title).to eq('Sent') - expect(other.attributes).to eq(id: 1, title: 'Sent', note: nil) - end - - # `article` is not an attribute of a ticket. It is a command in the body - # of the PUT, and Zammad never serves it back. Settled into the baseline - # with the attributes, it was remembered as the ticket's own state, and - # the same article assigned again compared equal to it. - it 'does not keep a key Zammad never served the record with' do - expect(ticket.key?(:article)).to be(false) - expect(ticket.attributes).to eq(id: 1, title: 'Help', note: nil) - end - - it 'stages the same article when it is assigned again' do - ticket.article = article - - expect(ticket.changes).to eq(article: [nil, article]) - end - - it 'sends the same article again when it is assigned again, as a second reply' do - ticket.article = article - ticket.save - - expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { article: article })).to have_been_made.twice - end - - it 'stages a value written back to what it was before the save, which Zammad no longer holds' do - other = client.tickets.find(1) - other.title = 'Sent' - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(unreadable_json_response) - begin - other.save - rescue ZammadAPI::ParseError - nil - end - - other.title = 'Help' - - expect(other.changes).to eq(title: %w[Sent Help]) - end - - it 'is brought up to date by a reload' do - stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, title: 'Help', article_count: 2 })) - ticket.reload - - expect(ticket.key?(:article)).to be(false) - expect(ticket.article_count).to eq(2) - end - - it 'keeps a change Zammad rejected staged, to be corrected and sent again' do - other = client.tickets.find(1) - other.title = '' - stub_request(:put, ticket_url).with(query: hash_including({})) - .to_return(json_response({ error: 'Title is required' }, status: 422)) - - expect(other.save).to be(false) - expect(other.changes).to eq(title: ['Help', '']) - end - - # What Zammad acknowledged is what the request carried. The baseline used - # to be taken from the record once the answer was in, so a write that - # landed while the request was out - from a logger or a middleware of the - # caller's that reaches the record, or from another thread - was settled - # along with it, for a value that was never sent. - context 'when the record is written to while the request is out' do - subject(:other) { client.tickets.find(1) } - - before do - stub_request(:put, ticket_url).with(query: hash_including({})).to_return do - other.title = 'C' - unreadable_json_response - end - - other.title = 'B' - begin - other.save - rescue ZammadAPI::ParseError - nil - end - end - - it 'sent the value that was staged when the request left' do - expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { title: 'B' })).to have_been_made.once - end - - it 'reads the value Zammad was sent, not the one written since' do - expect(other.title).to eq('B') - end - - it 'has nothing staged, as after a response it could read' do - expect(other.changes).to eq({}) - end - - it 'stages the later value when it is written again' do - other.title = 'C' - - expect(other.changes).to eq(title: %w[B C]) - end - end - - # The interval before that one: between the attributes being held and the - # request being built from them. Nothing of the caller's runs there on one - # thread, so the path being built stands in for a second thread writing to - # the record. The body used to be read from the change set at that point, - # so the PUT carried "C" and the record was settled on "B". - context 'when the record is written to before the request is built' do - subject(:other) { client.tickets.find(1) } - - before do - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(unreadable_json_response) - - other.title = 'B' - allow(ZammadAPI::Resources::Ticket).to receive(:member_path).and_wrap_original do |original, id| - other.title = 'C' - original.call(id) - end - begin - other.save - rescue ZammadAPI::ParseError - nil - end - end - - it 'sent the value that was held when the save began' do - expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { title: 'B' })).to have_been_made.once - end - - it 'reads the value it sent, with nothing staged' do - expect(other.title).to eq('B') - expect(other.changes).to eq({}) - end - end - - # Settling the record on what it sent is a write to its foreign keys like - # any other, and what the association proxy resolved from a value written - # meanwhile is not the answer for the one the record is put back on. - context 'when an association is resolved from a key written while the request is out' do - subject(:other) { client.tickets.find(1) } - - let(:related) { other.related } - - before do - stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, customer_id: 3 })) - [9, 10].each do |id| - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/#{id}").with(query: hash_including({})).to_return(json_response({ id: id })) - end - stub_request(:put, ticket_url).with(query: hash_including({})).to_return do - other.customer_id = 10 - related.customer - unreadable_json_response - end - - other.customer_id = 9 - begin - other.save - rescue ZammadAPI::ParseError - nil - end - end - - it 'is back on the key it sent' do - expect(other.customer_id).to eq(9) - end - - it 'resolves the association from the key it sent, on a proxy held from before' do - expect(related.customer.id).to eq(9) - end - end - - # The same write under a response that can be read, which is what the - # above is held to: the attributes it carries replace the record's. - it 'drops a write made while the request was out where the response can be read, too' do - other = client.tickets.find(1) - stub_request(:put, ticket_url).with(query: hash_including({})).to_return do - other.title = 'C' - json_response({ id: 1, title: 'B' }) - end - other.update!(title: 'B') - - expect(other.title).to eq('B') - expect(other.changes).to eq({}) - end - end - - # The third answer a write can get that says Zammad applied it and tells - # nothing more: a 2xx whose body stops short of its Content-Length. The - # transport refuses it before the record sees a response, so the record - # was not settled the way it is for a body that does not parse. - describe 'a write whose success body was cut short' do - def cut_short(status) - { status: status, body: '{"id":1,"na', headers: { 'Content-Type' => 'application/json', 'Content-Length' => '30' } } - end - - def swallow - yield - rescue ZammadAPI::IncompleteResponseError - nil - end - - context 'when it was a create' do - subject(:group) { client.groups.new(name: 'Support') } - - before { stub_request(:post, url).with(query: hash_including({})).to_return(cut_short(201)) } - - it 'still reports the response as cut short, with the status Zammad answered' do - expect { group.save }.to raise_error(ZammadAPI::IncompleteResponseError, /19 bytes short of the 30/) { |error| - expect(error.response.status).to eq(201) - } - end - - it 'is caught as the ConnectionError it was before' do - expect { group.save }.to raise_error(ZammadAPI::ConnectionError) - end - - it 'does not leave the record looking unsaved' do - swallow { group.save } - - expect(group.new_record?).to be(false) - end - - it 'does not create a second record when the save is retried' do - 2.times do - group.save - rescue ZammadAPI::Error - nil - end - - expect(a_request(:post, url).with(query: hash_including({}))).to have_been_made.once - end - - it 'refuses the retried save rather than reporting it stored' do - swallow { group.save } - - expect { group.save }.to raise_error(ZammadAPI::Error, /was saved, but the response carried no id/) - end - end - - context 'when it was an update' do - subject(:ticket) { client.tickets.find(1) } - - let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/1" } - - before do - stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, title: 'Help', note: nil })) - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(cut_short(200), json_response({ id: 1, title: 'Renamed' })) - - ticket.article = { body: 'Reset link sent.', type: 'email', to: 'customer@example.com' } - swallow { ticket.save } - end - - it 'no longer holds the changes Zammad acknowledged as staged' do - expect(ticket.changed?).to be(false) - expect(ticket.changes).to eq({}) - end - - it 'does not send the article again with the next save' do - ticket.title = 'Renamed' - ticket.save - - expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { title: 'Renamed' })).to have_been_made.once - expect(a_request(:put, ticket_url).with(query: hash_including({}), body: hash_including('article' => anything))).to have_been_made.once - end - - it 'keeps the id it is addressed by' do - expect(ticket.attributes).to eq(id: 1, title: 'Help', note: nil) - end - end - - context 'when it was a destroy' do - subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Support') } - - before { stub_request(:delete, "#{url}/1").to_return(cut_short(200)) } - - it 'still reports the response as cut short' do - expect { group.destroy }.to raise_error(ZammadAPI::IncompleteResponseError) - end - - it 'leaves the record destroyed' do - swallow { group.destroy } - - expect(group).to be_destroyed - end - - it 'refuses a second destroy rather than surfacing Zammad\'s 404' do - swallow { group.destroy } - - expect { group.destroy }.to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to destroy/) - expect(a_request(:delete, "#{url}/1")).to have_been_made.once - end - - it 'drops what was staged, as a destroy that was answered whole does' do - group.name = 'Renamed' - swallow { group.destroy } - - expect(group.name).to eq('Support') - expect(group.changed?).to be(false) - end - end - - # A read was not applied to anything, and settles nothing. - it 'leaves a record alone whose reload was cut short' do - group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Support') - stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(cut_short(200)) - group.name = 'Renamed' - swallow { group.reload } - - expect(group.changes).to eq(name: %w[Support Renamed]) - end - end - - # A 2xx says that Zammad applied a save only where the 2xx is Zammad's. - # It answers a create and an update with JSON, so a 2xx that says it is - # anything else, or does not say, is the page of something in front of - # Zammad that never passed the request on: a login page, a captive portal, - # the default page of a load balancer. Settled on that, the record read as - # saved and the retried save sent nothing, with Zammad none the wiser. + # Zammad answers a create and an update with a JSON object, so a 2xx with + # anything else is the page of something in front of it: a login page, a + # captive portal, the default page of a load balancer. describe 'a save answered 2xx by something that is not Zammad' do - def login_page(**headers) - { status: 200, body: 'Please sign in', headers: { 'Content-Type' => 'text/html' }.merge(headers) } + def login_page + { status: 200, body: 'Please sign in', headers: { 'Content-Type' => 'text/html' } } end def swallow yield - rescue ZammadAPI::ParseError, ZammadAPI::IncompleteResponseError + rescue ZammadAPI::ParseError nil end @@ -2001,17 +1195,6 @@ def swallow expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { state: 'closed' })).to have_been_made.twice expect(ticket.changed?).to be(false) end - - it 'keeps a write made while the request was out, as after any save that failed' do - other = client.tickets.find(1) - stub_request(:put, ticket_url).with(query: hash_including({})).to_return do - other.title = 'Written meanwhile' - login_page - end - swallow { other.update(state: 'closed') } - - expect(other.changes).to eq(state: %w[open closed], title: ['Help', 'Written meanwhile']) - end end it 'takes a 2xx that names no content type the same way' do @@ -2022,99 +1205,12 @@ def swallow expect(group.new_record?).to be(true) end - # The transport refuses this one before the record sees a response, and - # the record is asked the same question of the response the error holds. - it 'takes a page cut short of its Content-Length the same way' do - stub_request(:post, url).with(query: hash_including({})).to_return(login_page('Content-Length' => '300')) + it 'takes a body that says it is JSON and cannot be read the same way' do + stub_request(:post, url).with(query: hash_including({})).to_return(unreadable_json_response(status: 201)) group = client.groups.new(name: 'Support') - expect { group.save }.to raise_error(ZammadAPI::IncompleteResponseError) + expect { group.save }.to raise_error(ZammadAPI::ParseError) expect(group.new_record?).to be(true) end - - # Zammad answers a ticket's DELETE with no body at all, and with an empty - # JSON object for everything else it destroys. A 2xx whose body is - # neither is not its answer, and the record is still there. - context 'when it was a destroy' do - subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Support') } - - let(:member_url) { "#{url}/1" } - - it 'reports the page, naming what it was served as' do - stub_request(:delete, member_url).to_return(login_page) - - expect { group.destroy } - .to raise_error(ZammadAPI::ParseError, "Can't destroy object (ZammadAPI::Resources::Group): expected a JSON body or none, got text/html") - end - - it 'leaves the record as it was, with what was staged' do - stub_request(:delete, member_url).to_return(login_page) - group.name = 'Renamed' - swallow { group.destroy } - - expect(group).not_to be_destroyed - expect(group.changes).to eq(name: %w[Support Renamed]) - end - - it 'sends the DELETE again with the next destroy, which is the first Zammad sees' do - stub_request(:delete, member_url).to_return(login_page, json_response({})) - swallow { group.destroy } - - expect(group.destroy).to be(true) - expect(group).to be_destroyed - expect(a_request(:delete, member_url)).to have_been_made.twice - end - - it 'takes a body that names no content type the same way' do - stub_request(:delete, member_url).to_return(status: 200, body: 'OK') - - expect { group.destroy }.to raise_error(ZammadAPI::ParseError, /got a body that names no content type/) - expect(group).not_to be_destroyed - end - - it 'takes a page cut short of its Content-Length the same way' do - stub_request(:delete, member_url).to_return(login_page('Content-Length' => '300')) - - expect { group.destroy }.to raise_error(ZammadAPI::IncompleteResponseError) - expect(group).not_to be_destroyed - end - - it 'is destroyed by a 2xx with no body, as Zammad answers for a ticket' do - stub_request(:delete, member_url).to_return(status: 200, body: '', headers: { 'Content-Type' => 'text/html' }) - - expect(group.destroy).to be(true) - expect(group).to be_destroyed - end - - it 'is destroyed by a 204' do - stub_request(:delete, member_url).to_return(status: 204) - - expect(group.destroy).to be(true) - end - - it 'is destroyed by the empty object Zammad answers with for a group' do - stub_request(:delete, member_url).to_return(json_response({})) - - expect(group.destroy).to be(true) - expect(group).to be_destroyed - end - - it 'is destroyed by a body that says it is JSON and cannot be read as it' do - stub_request(:delete, member_url).to_return(unreadable_json_response) - - expect(group.destroy).to be(true) - end - end - - # A transport of the caller's can hand over a Response without the - # header. One whose body was decoded from JSON has said as much. - it 'takes a response decoded from JSON for Zammad\'s, with or without the header' do - response = ZammadAPI::Response.new(status: 201, headers: {}, body: { id: 7, name: 'Support' }, raw_body: '', json: true) - transport = instance_double(ZammadAPI::Transport, post: response) - group = ZammadAPI::Resources::Group.new(transport, name: 'Support') - - expect(group.save).to be(true) - expect(group.persisted?).to be(true) - end end end diff --git a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb index 21d112a..f3e02eb 100644 --- a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb @@ -49,31 +49,6 @@ bare = ZammadAPI::Resources::TicketArticle.from_response(transport, id: 9) expect(bare.attachments).to eq([]) end - - # This metadata comes off a response body like any other, and an element - # that is not an object reached `raw.merge` and died there as a bare - # NoMethodError from inside the gem - past the `rescue ZammadAPI::Error` - # every caller is told to write. - it 'refuses metadata that is not a list' do - article = ZammadAPI::Resources::TicketArticle.from_response(transport, id: 9, attachments: 'none') - - expect { article.attachments } - .to raise_error(ZammadAPI::ParseError, /expected a JSON array of objects, got String/) - end - - it 'refuses a list holding something that is not an object' do - article = ZammadAPI::Resources::TicketArticle.from_response(transport, id: 9, attachments: [3]) - - expect { article.attachments } - .to raise_error(ZammadAPI::ParseError, /got an array holding Integer/) - end - - it 'names the article in the refusal' do - article = ZammadAPI::Resources::TicketArticle.from_response(transport, id: 9, attachments: 'none') - - expect { article.attachments } - .to raise_error(ZammadAPI::ParseError, /ZammadAPI::Resources::TicketArticle/) - end end describe '#download' do @@ -103,48 +78,6 @@ expect(attachment.download.encoding).to eq(Encoding::BINARY) end - # Net::HTTP hands over what had arrived when the connection dropped, - # and that was returned as the file. - it 'raises for a file the connection was closed under, and does not return the part that arrived' do - stub_request(:get, download_url) - .to_return(status: 200, body: "\x89PNG\r\n".b, headers: { 'Content-Type' => 'image/png', 'Content-Length' => '1000' }) - - expect { attachment.download } - .to raise_error(ZammadAPI::ConnectionError, /\ACan't download attachment: the response from .+ ended 994 bytes short of the 1000/) - end - - # Net::HTTP asks for gzip by itself and inflates what arrives, without a - # word for a stream that stops halfway, and the length of a body that - # was decoded on the way cannot be checked. - it 'asks for the file as it is stored, so that its length can be checked' do - stub = stub_request(:get, download_url).with(headers: { 'Accept-Encoding' => 'identity' }).to_return(status: 200, body: 'contents') - attachment.download - - expect(stub).to have_been_requested - end - - # An adapter handed the header leaves the decoding to its caller, so - # these would have been the compressed bytes. - context 'when the server encodes the file all the same' do - let(:unencoded) { { headers: { 'Accept-Encoding' => 'identity' } } } - - before do - stub_request(:get, download_url).to_return(status: 200, body: 'contents') - stub_request(:get, download_url).with(unencoded).to_return(status: 200, body: "\x1F\x8B\b".b, headers: { 'Content-Encoding' => 'gzip' }) - end - - it 'returns the file from a second request, sent the way every other request is' do - expect(attachment.download).to eq('contents') - end - - it 'asks twice, and once of the two as the file is stored' do - attachment.download - - expect(a_request(:get, download_url)).to have_been_made.twice - expect(a_request(:get, download_url).with(unencoded)).to have_been_made.once - end - end - it 'raises when the attachment is gone' do stub_request(:get, download_url).to_return(json_response({ error: 'not found' }, status: 404)) expect { attachment.download }.to raise_error(ZammadAPI::NotFoundError) diff --git a/spec/unit/zammad_api/resources/ticket_spec.rb b/spec/unit/zammad_api/resources/ticket_spec.rb index a51b4bc..a2b632a 100644 --- a/spec/unit/zammad_api/resources/ticket_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -41,10 +41,6 @@ ticket.destroy end - # Each of these says what the caller gets, not which ivar was cleared. - # `destroy` dropped the `related` memo and was taken to have closed this, - # but the reader rebuilt one on the next call, so every path below went - # on reaching a ticket that is gone. it 'refuses the articles reader rather than fetching a deleted ticket' do expect { ticket.articles }.to raise_error(ZammadAPI::Error, /was destroyed/) end @@ -52,20 +48,6 @@ it 'refuses the related proxy' do expect { ticket.related }.to raise_error(ZammadAPI::Error, /was destroyed/) end - - it 'refuses to add an article rather than POSTing a dead ticket_id' do - expect { ticket.add_article(body: 'hello') }.to raise_error(ZammadAPI::Error, /was destroyed/) - end - - it 'makes no request at all when an article is refused' do - stub = stub_request(:post, article_url).with(query: hash_including({})) - begin - ticket.add_article(body: 'hello') - rescue ZammadAPI::Error # rubocop:disable Lint/SuppressedException - end - - expect(stub).not_to have_been_requested - end end describe '#add_article' do @@ -103,60 +85,24 @@ expect(stub).to have_been_requested end - it 'refuses what is no set of attributes, and sends nothing' do - expect { ticket.add_article('hello') }.to raise_error(ArgumentError, 'attributes need to be a Hash of names and values, got String') - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - # The article goes to the ticket it was added to, whatever the attributes - # say. Given `ticket_id` under both spellings, the Symbol was replaced and - # the String, coming later in the Hash, replaced it again when the article - # symbolized its keys - so the POST named the caller's ticket. - context 'when the attributes name a ticket of their own' do - before do - stub_request(:post, article_url).with(query: hash_including({})) - .to_return(json_response({ id: 9, ticket_id: 42 }, status: 201)) - end - - def posted_ticket_ids - ids = [] - expect(a_request(:post, article_url).with(query: hash_including({})) { |request| ids << JSON.parse(request.body)['ticket_id'] }) - .to have_been_made.once - ids - end - - it 'uses its own id over a Symbol key' do - ticket.add_article(ticket_id: 9, body: 'hello') - expect(posted_ticket_ids).to eq([42]) - end - - it 'uses its own id over a String key' do - ticket.add_article('body' => 'hello', 'ticket_id' => 9) - expect(posted_ticket_ids).to eq([42]) - end - - it 'uses its own id over both spellings at once' do - ticket.add_article(:ticket_id => 1, 'ticket_id' => 9, :body => 'hello', :type => 'note') - expect(posted_ticket_ids).to eq([42]) - end - - it 'sends ticket_id once' do - ticket.add_article(:ticket_id => 1, 'ticket_id' => 9, :body => 'hello') + it 'uses its own id over a ticket_id in the attributes' do + stub = stub_request(:post, article_url) + .with(query: { 'expand' => 'true' }, body: '{"ticket_id":42,"body":"hello"}') + .to_return(json_response({ id: 9, ticket_id: 42 }, status: 201)) - expect(a_request(:post, article_url).with(query: hash_including({}), body: '{"body":"hello","ticket_id":42}')).to have_been_made - end + ticket.add_article(ticket_id: 9, body: 'hello') + expect(stub).to have_been_requested + end - it 'leaves the Hash it was given as it was' do - attributes = { :ticket_id => 1, 'ticket_id' => 9, :body => 'hello' } - ticket.add_article(attributes) + it 'leaves the Hash it was given as it was' do + stub_request(:post, article_url).with(query: hash_including({})) + .to_return(json_response({ id: 9, ticket_id: 42 }, status: 201)) + attributes = { ticket_id: 9, body: 'hello' } + ticket.add_article(attributes) - expect(attributes).to eq(:ticket_id => 1, 'ticket_id' => 9, :body => 'hello') - end + expect(attributes).to eq(ticket_id: 9, body: 'hello') end - # An article belongs to a ticket by id. Unchecked, this POSTed - # `ticket_id: null` and left the caller reading Zammad's 422 to work out - # that the ticket had never been saved. context 'when the ticket has not been saved' do subject(:ticket) { described_class.new(unit_transport, title: 'Help') } @@ -178,26 +124,14 @@ def posted_ticket_ids end end - # The name add_article had in 1.x: a noun that sends a POST, one letter away - # from the reader beside it. It is gone, which leaves `article` what it is - # everywhere else on a record - an attribute. describe '#article' do it 'is not a method of a ticket' do expect(described_class.method_defined?(:article)).to be(false) end - it 'raises NoMethodError for the call 1.x made' do + it 'raises NoMethodError when called to add an article, and sends nothing' do expect { ticket.article(body: 'hello') }.to raise_error(NoMethodError) - end - - it 'sends nothing for the call 1.x made' do - begin - ticket.article(body: 'hello') - rescue NoMethodError - nil - end - - expect(a_request(:post, article_url).with(query: hash_including({}))).not_to have_been_made + expect(a_request(:any, /zammad\.test/)).not_to have_been_made end it 'reads the article staged for the next save' do @@ -205,31 +139,5 @@ def posted_ticket_ids expect(ticket.article).to eq(body: 'reply') end - - # With an article staged the reader is there, and it never looked at - # its arguments: the call 1.x made answered with the staged article, - # sent nothing and raised nothing. - context 'when an article is staged and the call 1.x made is made' do - before { ticket.article = { body: 'draft' } } - - it 'raises ArgumentError rather than answering with the staged article' do - expect { ticket.article(body: 'reply') }.to raise_error(ArgumentError, /wrong number of arguments \(given 1, expected 0\)/) - end - - it 'names add_article' do - expect { ticket.article(body: 'reply') }.to raise_error(ArgumentError, /add_article\(\.\.\.\)/) - end - - it 'sends nothing' do - expect { ticket.article(body: 'reply') }.to raise_error(ArgumentError) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - end - - it 'tells a reader given a value where the value is written' do - ticket.assign_attributes(state: 'open') - - expect { ticket.state('closed') }.to raise_error(ArgumentError, /write it with state = \.\.\. or update\(state: \.\.\.\)/) - end end end diff --git a/spec/unit/zammad_api/response_error_spec.rb b/spec/unit/zammad_api/response_error_spec.rb index ad9eee5..d85822a 100644 --- a/spec/unit/zammad_api/response_error_spec.rb +++ b/spec/unit/zammad_api/response_error_spec.rb @@ -6,8 +6,7 @@ def response(status, body, headers = {}) status: status, headers: headers, body: body, - raw_body: body.is_a?(String) ? body : JSON.generate(body), - json: !body.is_a?(String) + raw_body: body.is_a?(String) ? body : JSON.generate(body) ) end @@ -16,6 +15,7 @@ def response(status, body, headers = {}) ZammadAPI::ConfigurationError => ZammadAPI::Error, ZammadAPI::UnknownResourceError => ZammadAPI::Error, ZammadAPI::ParseError => ZammadAPI::Error, + ZammadAPI::PaginationError => ZammadAPI::Error, ZammadAPI::ConnectionError => ZammadAPI::TransportError, ZammadAPI::TimeoutError => ZammadAPI::TransportError, ZammadAPI::ClientError => described_class, @@ -151,9 +151,6 @@ def response(status, body, headers = {}) expect([bare.status, bare.body, bare.headers, bare.server_message]).to eq([nil, nil, {}, nil]) end - # A NotFoundError this gem raises itself - find_by! finding nothing - used - # to answer nil here, so `retry if e.status == 404` stopped retrying for - # the one NotFoundError that did not come from Zammad. it 'reports the status its class is the name for, without a response' do bare = ZammadAPI::NotFoundError.new(operation: 'find object by name', detail: 'no record matched') expect(bare.status).to eq(404) @@ -170,56 +167,34 @@ def response(status, body, headers = {}) end describe ZammadAPI::RateLimitError do + def retry_after(value) + headers = value.nil? ? {} : { 'retry-after' => value } + + ZammadAPI::ResponseError.build(response(429, {}, headers), operation: 'find object').retry_after + end + it 'exposes Retry-After as an integer' do - error = ZammadAPI::ResponseError.build( - ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => '30' }, body: {}, raw_body: '{}', json: true), - operation: 'find object' - ) - expect(error.retry_after).to eq(30) + expect(retry_after('30')).to eq(30) end it 'returns nil when the header is absent' do - error = ZammadAPI::ResponseError.build( - ZammadAPI::Response.new(status: 429, headers: {}, body: {}, raw_body: '{}', json: true), - operation: 'find object' - ) - expect(error.retry_after).to be_nil + expect(retry_after(nil)).to be_nil end it 'returns nil when the header is not a number' do - error = ZammadAPI::ResponseError.build( - ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => 'later' }, body: {}, raw_body: '{}', json: true), - operation: 'find object' - ) - expect(error.retry_after).to be_nil + expect(retry_after('later')).to be_nil end - # Integer reads a prefix as a radix unless it is told the base, so a - # zero in front made the figure octal: `010` was 8, and `08` was nil. it 'reads a figure with a zero in front in base ten' do - figures = %w[010 08 0030].map do |value| - response = ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => value }, body: {}, raw_body: '{}', json: true) - - ZammadAPI::ResponseError.build(response, operation: 'find object').retry_after - end - - expect(figures).to eq([10, 8, 30]) + expect(%w[010 08 0030].map { retry_after(it) }).to eq([10, 8, 30]) end it 'returns nil for a figure in another base' do - error = ZammadAPI::ResponseError.build( - ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => '0x10' }, body: {}, raw_body: '{}', json: true), - operation: 'find object' - ) - expect(error.retry_after).to be_nil + expect(retry_after('0x10')).to be_nil end it 'reads a figure held as an Integer' do - error = ZammadAPI::ResponseError.build( - ZammadAPI::Response.new(status: 429, headers: { 'retry-after' => 30 }, body: {}, raw_body: '{}', json: true), - operation: 'find object' - ) - expect(error.retry_after).to eq(30) + expect(retry_after(30)).to eq(30) end end end diff --git a/spec/unit/zammad_api/response_spec.rb b/spec/unit/zammad_api/response_spec.rb index 95fc531..0731ded 100644 --- a/spec/unit/zammad_api/response_spec.rb +++ b/spec/unit/zammad_api/response_spec.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true RSpec.describe ZammadAPI::Response do - def build(status: 200, body: { a: 1 }, raw_body: '{"a":1}', headers: {}, json: !body.is_a?(String)) - described_class.new(status: status, headers: headers, body: body, raw_body: raw_body, json: json) + def build(status: 200, body: { a: 1 }, raw_body: '{"a":1}', headers: {}) + described_class.new(status: status, headers: headers, body: body, raw_body: raw_body) end describe '#success?' do @@ -19,41 +19,25 @@ def build(status: 200, body: { a: 1 }, raw_body: '{"a":1}', headers: {}, json: ! end end - describe '#json?' do - it 'is true when the body was decoded' do - expect(build).to be_json + describe '.decode_body' do + it 'decodes a JSON body with symbol keys' do + expect(described_class.decode_body('application/json; charset=utf-8', '{"a":{"b":1}}')).to eq(a: { b: 1 }) end - it 'is false when the body is the untouched raw body' do - raw = '' - expect(build(body: raw, raw_body: raw)).not_to be_json + it 'leaves a body of another content type as it is' do + expect(described_class.decode_body('text/html', '{"a":1}')).to eq('{"a":1}') end - it 'reports what the decoder recorded, not whether the two bodies differ' do - expect(build(body: '"a string"', raw_body: '"a string"', json: true)).to be_json - end - end - - # What a response says it carries, which is not what it turned out to: a - # JSON body that did not parse still came from something that speaks JSON. - describe '#json_content_type?' do - it 'is true for a JSON content type' do - expect(build(headers: { 'content-type' => 'application/json; charset=utf-8' })).to be_json_content_type - end - - it 'is true where the body then did not decode' do - response = build(body: '{"id":', raw_body: '{"id":', headers: { 'content-type' => 'application/json' }) - - expect(response).to be_json_content_type - expect(response).not_to be_json + it 'leaves a body as it is when there is no content type' do + expect(described_class.decode_body(nil, '{"a":1}')).to eq('{"a":1}') end - it 'is false for another content type' do - expect(build(headers: { 'content-type' => 'text/html' })).not_to be_json_content_type + it 'leaves an empty JSON body as it is' do + expect(described_class.decode_body('application/json', '')).to eq('') end - it 'is false where the response names none' do - expect(build).not_to be_json_content_type + it 'leaves a JSON body that does not parse as it is' do + expect(described_class.decode_body('application/json', '{"id":')).to eq('{"id":') end end @@ -89,90 +73,6 @@ def build(status: 200, body: { a: 1 }, raw_body: '{"a":1}', headers: {}, json: ! it 'accepts an empty list' do expect(build(body: []).decoded(:array, operation: 'get list')).to eq([]) end - - # An unexpanded search answers with ids. Passing them on stored an Integer - # as a record's attributes, and the first reader died with a TypeError - # from deep inside the gem. - it 'raises for a list of scalars rather than building records from them' do - expect { build(body: [1, 2, 3]).decoded(:array, operation: 'get list') } - .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array of objects, got an array holding Integer") - end - - it 'raises for a list that is only partly objects' do - expect { build(body: [{ id: 1 }, 'nope']).decoded(:array, operation: 'get list') } - .to raise_error(ZammadAPI::ParseError, /an array holding String/) - end - - # `find` cannot tell "no offender" from "the offender is nil", so a null - # passed as an object and the first read of it died with NoMethodError. - it 'raises for a list holding a null' do - expect { build(body: [nil]).decoded(:array, operation: 'get list') } - .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array of objects, got an array holding NilClass") - end - - it 'raises for a null among the objects of a list' do - expect { build(body: [{ id: 1 }, nil, { id: 3 }]).decoded(:array, operation: 'get list') } - .to raise_error(ZammadAPI::ParseError, /an array holding NilClass/) - end - - it 'names the resource class when a list element has the wrong shape' do - expect { build(body: [1]).decoded(:array, operation: 'get list', resource_class: ZammadAPI::Resources::User) } - .to raise_error(/\(ZammadAPI::Resources::User\)/) - end - end - - # A list is an array, and a search asked for its total answers with an - # object holding the array and the figure. A walk reads either. - describe '#decoded_list' do - it 'returns an array body, and no total' do - expect(build(body: [{ a: 1 }]).decoded_list(operation: 'get list')).to eq([[{ a: 1 }], nil]) - end - - it 'returns the records and the total of a counted list' do - expect(build(body: { records: [{ a: 1 }], total_count: 7 }).decoded_list(operation: 'get list')).to eq([[{ a: 1 }], 7]) - end - - it 'accepts a counted list with no records' do - expect(build(body: { records: [], total_count: 0 }).decoded_list(operation: 'get list')).to eq([[], 0]) - end - - it 'reports a negative total as none, and keeps the records' do - expect(build(body: { records: [{ a: 1 }], total_count: -1 }).decoded_list(operation: 'get list')).to eq([[{ a: 1 }], nil]) - end - - it 'reports a total that is not a number as none' do - expect(build(body: { records: [], total_count: '7' }).decoded_list(operation: 'get list')).to eq([[], nil]) - end - - it 'raises for records that are not objects' do - expect { build(body: { records: [1, 2], total_count: 2 }).decoded_list(operation: 'get list') } - .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array of objects, got an array holding Integer") - end - - it 'raises for a null among the records of a counted list' do - expect { build(body: { records: [nil, { a: 1 }], total_count: 2 }).decoded_list(operation: 'get list') } - .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array of objects, got an array holding NilClass") - end - - it 'raises for an object that holds no records' do - expect { build(body: { total_count: 2 }).decoded_list(operation: 'get list') } - .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array, got Hash") - end - - it 'raises for records that are not a list' do - expect { build(body: { records: 'none', total_count: 0 }).decoded_list(operation: 'get list') } - .to raise_error(ZammadAPI::ParseError, /expected a JSON array, got Hash/) - end - - it 'raises when the body was never JSON' do - expect { build(body: '', raw_body: '').decoded_list(operation: 'get list') } - .to raise_error(ZammadAPI::ParseError, /got String/) - end - - it 'names the resource class in the message' do - expect { build(body: {}).decoded_list(operation: 'get list', resource_class: ZammadAPI::Resources::User) } - .to raise_error(/\(ZammadAPI::Resources::User\)/) - end end it 'is immutable' do diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index d83cdae..fcd06b2 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -1,6 +1,5 @@ # frozen_string_literal: true -require 'yaml' require 'zammad_api/test' RSpec.describe ZammadAPI::Test do @@ -28,9 +27,6 @@ expect(client.config).to be(zammad.config) end - # Going through Client.new assembled a Faraday stack - auth, JSON, - # retries, adapter - only for it to be swapped straight back out, once per - # stand-in. it 'builds no HTTP stack on the way to the stand-in transport' do allow(ZammadAPI::Transport).to receive(:new).and_call_original @@ -73,37 +69,8 @@ expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') end - # The stand-in's transport answered `with_config` with itself, so what - # is read from the transport stayed the stand-in's own: the derived - # client reported the option and went on as if it had not been given. - it 'retries as often as the derived client is told to' do - zammad.stub(:get, 'api/v1/groups/1', status: 503) - - expect { zammad.client.with(retries: 0).groups.find(1) }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(1) - end - - it 'leaves the retries of the client it was derived from as they were' do - zammad.stub(:get, 'api/v1/groups/1', status: 503) - zammad.client.with(retries: 0) - - expect { zammad.client.groups.find(1) }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(1 + zammad.config.retries) - end - - it 'holds a Retry-After against the derived timeout' do - zammad.stub(:get, 'api/v1/groups/1', status: 429, headers: { 'Retry-After' => '30' }) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - - expect { zammad.client.with(timeout: 5).groups.find(1) }.to raise_error(ZammadAPI::RateLimitError) - expect(zammad.requests.size).to eq(1) - end - it 'keeps the derived options under an on_behalf_of scope taken afterwards' do - zammad.stub(:get, 'api/v1/groups/1', status: 503) - - expect { zammad.client.with(retries: 0).on_behalf_of('agent@example.com').groups.find(1) }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(1) + expect(zammad.client.with(timeout: 5).on_behalf_of('agent@example.com').config.timeout).to eq(5) end # A record names its installation by the URL of its transport. @@ -158,20 +125,6 @@ .to raise_error(ArgumentError, /a request path is relative to the instance URL/) end - it 'refuses a path that climbs out of the instance URL the way the real transport does' do - expect { client.get('../billing/export') }.to raise_error(ArgumentError, /holds a '\.\.' segment/) - expect(zammad.requests).to be_empty - end - - it 'refuses to stub such a path, which no request could reach' do - expect { zammad.stub(:get, 'api/v1/../x') }.to raise_error(ArgumentError, /holds a '\.\.' segment/) - end - - it 'refuses a path that cannot be read as a URL the way the real transport does' do - expect { client.get('api/v1/tägs') }.to raise_error(ArgumentError, /cannot be read as one: it holds a character outside ASCII/) - expect(zammad.requests).to be_empty - end - it 'records nothing for a path it refuses' do expect { client.get('https://other.example/collect') }.to raise_error(ArgumentError) expect(zammad.requests).to be_empty @@ -187,31 +140,6 @@ expect(zammad.requests).to be_empty end - it 'refuses a header name that is not one, the way the real transport does' do - zammad.stub(:get, 'api/v1/roles', body: []) - - expect { client.get('api/v1/roles', headers: { "X-A\r\nFrom: admin@example.com" => 'v' }) } - .to raise_error(ArgumentError, /goes on with a character no header name carries/) - expect(zammad.requests).to be_empty - end - - it 'refuses a body holding a value JSON has no type for, the way the real transport does' do - zammad.stub(:post, 'api/v1/users', body: { id: 1 }) - - expect { client.users.create(login: 'jane', role_ids: Set[1, 2]) } - .to raise_error(ZammadAPI::Error, /its key role_ids was given as Set, which is no JSON type/) - expect(zammad.requests).to be_empty - end - - # And for a query a query string could not carry as it was written. - it 'refuses a list of Hashes Rails would read as one, the way the real transport does' do - zammad.stub(:get, 'api/v1/roles', body: []) - - expect { client.get('api/v1/roles', query: { list: [{ a: 1 }, { b: 2 }] }) } - .to raise_error(ArgumentError, /Rails would read the two as one/) - expect(zammad.requests).to be_empty - end - it 'raises the mapped error class for a non-2xx status' do zammad.stub(:get, 'api/v1/groups/1', status: 404, body: { error: 'not found' }) @@ -226,6 +154,20 @@ expect(group.error.server_message).to eq('Name is required') end + it 'raises a rate limit with the wait Zammad asked for' do + zammad.stub(:get, 'api/v1/groups/1', status: 429, headers: { 'Retry-After' => '30' }) + + expect { client.groups.find(1) }.to raise_error(ZammadAPI::RateLimitError) { expect(it.retry_after).to eq(30) } + end + + it 'raises for a failure at once, without the retries the real transport makes' do + zammad.stub(:get, 'api/v1/groups/1', status: 503) + zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) + + expect { client.groups.find(1) }.to raise_error(ZammadAPI::ServerError) + expect(zammad.requests.size).to eq(1) + end + it 'serves a non-JSON body untouched, e.g. an attachment' do zammad.stub(:get, 'api/v1/ticket_attachment/1/2/3', body: 'binary-ish') @@ -251,19 +193,11 @@ expect(client.get('api/v1/groups').headers['x-total-count']).to eq('7') end - # The stand-in exists so that the code under test cannot tell it from the - # real transport, and it carried its own copy of the verb loop - so a fifth - # verb added to one would have left the other unable to answer it. it 'answers every verb the real transport answers' do expect(ZammadAPI::Test::Transport.new(zammad)) .to respond_to(*ZammadAPI::Transport::Verbs.instance_methods) end - # Transport#decode always hands over a response whose headers name the - # type - it is what the decode branches on - while this set `json: true` - # directly and left the headers as written. Code that branches on - # `response.headers['content-type']` passed against Zammad and failed - # against the stand-in, or the reverse. it 'serves a JSON body with the content-type a real response carries' do zammad.stub(:get, 'api/v1/groups', body: []) @@ -282,16 +216,9 @@ expect(client.get('api/v1/groups').headers['content-type']).to eq('application/json; charset=utf-8') end - # The header used to be decorative: `json:` came from the Ruby type of the - # stub's body, so a stub could say `text/html` and still hand back a - # decoded Hash, where Zammad gives the raw string and `decoded` raises. context 'when a stub declares a type that is not JSON' do before { zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }, headers: { 'Content-Type' => 'text/html' }) } - it 'does not decode the body' do - expect(client.get('api/v1/groups/1')).not_to be_json - end - it 'hands back the raw body Zammad would have sent' do expect(client.get('api/v1/groups/1').body).to eq('{"id":1}') end @@ -301,49 +228,18 @@ end end - # A nil Content-Type stringified to '', which then beat the JSON default - # this kit supplies and served a Hash body undecoded - so the test failed - # inside the code under test with nothing to say the stub was at fault. - it 'refuses two spellings of one header rather than dropping a value' do - expect { zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'Content-Type' => 'text/html', 'content-type' => 'application/json' }) } - .to raise_error(ArgumentError, /header content-type was given twice/) - end - - it 'refuses a header value the wire could not carry' do - expect { zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'Content-Type' => nil }) } - .to raise_error(ArgumentError, /header Content-Type was stubbed as nil/) - end - - it 'names what a response header has to be' do - expect { zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => [7] }) } - .to raise_error(ArgumentError, /a response header is always text: pass a String/) - end - - # Only the name used to be normalised, so a count written as an Integer - # reached the code under test as one, where the wire always carries "7". it 'carries a header value as the String the wire would have sent' do zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => 7 }) expect(client.get('api/v1/groups').headers['x-total-count']).to eq('7') end - # Paging read the stub's body as written, which was the same thing only - # while a list could arrive as an Array. Once the content-type decided - # decoding, a list stubbed as a JSON string decoded to one and was never - # paged, so it answered every page with the same records and every full - # read raised PaginationError - where Zammad answers page two empty. - it 'pages a list stubbed as a JSON string the way it pages an Array' do + it 'reads a list stubbed as a JSON string' do zammad.stub(:get, 'api/v1/groups', body: '[{"id":1,"name":"a"},{"id":2,"name":"b"}]', headers: { 'Content-Type' => 'application/json' }) expect(client.groups.all.map(&:name)).to eq(%w[a b]) end - it 'answers a later page of a string-bodied list as an endpoint out of records would' do - zammad.stub(:get, 'api/v1/groups', body: '[{"id":1}]', headers: { 'Content-Type' => 'application/json' }) - - expect(client.get('api/v1/groups', query: { page: 2 }).body).to eq([]) - end - it 'keeps the raw body of a page it did not replace' do zammad.stub(:get, 'api/v1/groups/1', body: '{"id":1}', headers: { 'Content-Type' => 'application/json' }) @@ -362,19 +258,6 @@ expect(client.get('api/v1/groups/1/avatar').headers).not_to have_key('content-type') end - # The stub keeps serving after a response is built, and Response is a - # value. Handing out the stub's own Hash made every response from one stub - # share it, so writing to `response.headers` in one example rewrote the - # stand-in for every later request in it. - it 'gives each response its own headers rather than the stub\'s' do - zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => '7' }) - - first = client.get('api/v1/groups') - second = client.get('api/v1/groups') - - expect(first.headers).not_to be(second.headers) - end - it 'hands out headers a caller cannot write through' do zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => '7' }) @@ -403,95 +286,27 @@ expect(Array.new(3) { client.groups.find(1).name }).to eq(%w[Users Users Users]) end - - # A lone stub stays in place to go on answering, so it was still at - # the head when a second one was queued, and answered once more. - context 'when a stub is declared after an earlier one has answered' do - before do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'First' }) - client.groups.find(1) - end - - it 'answers the next request with the later one' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) - - expect(Array.new(2) { client.groups.find(1).name }).to eq(%w[Second Second]) - end - - it 'does so however often the earlier one answered' do - 2.times { client.groups.find(1) } - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) - - expect(client.groups.find(1).name).to eq('Second') - end - - it 'serves several declared after it in turn' do - %w[Second Third].each { zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: it }) } - - expect(Array.new(3) { client.groups.find(1).name }).to eq(%w[Second Third Third]) - end - - it 'does so again for one declared after the last of a sequence has answered' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) - client.groups.find(1) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Third' }) - - expect(client.groups.find(1).name).to eq('Third') - end - - it 'leaves a stub of another scope where it is' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Scoped' }, query: { full: true }) - - expect(client.groups.find(1).name).to eq('First') - expect(client.get('api/v1/groups/1', query: { full: true }).body).to eq({ id: 1, name: 'Scoped' }) - end - - it 'answers a failure the client retried with the stub declared after it' do - zammad.stub(:get, 'api/v1/groups/2', status: 503) - expect { client.groups.find(2) }.to raise_error(ZammadAPI::ServerError) - zammad.stub(:get, 'api/v1/groups/2', body: { id: 2, name: 'Back' }) - - expect(client.groups.find(2).name).to eq('Back') - end - end end describe 'query matching' do it 'matches a stub that names a subset of the parameters' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name,id' }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) expect(client.groups.order(:name).first.id).to eq(1) end it 'does not answer a request without those parameters' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name,id' }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) expect { client.groups.all.to_a }.to raise_error(described_class::UnstubbedRequestError) end it 'ignores the parameters the client adds itself' do - zammad.stub(:get, 'api/v1/groups', body: [], query: { sort_by: 'name,id' }) + zammad.stub(:get, 'api/v1/groups', body: [], query: { sort_by: 'name' }) expect { client.groups.order(:name).to_a }.not_to raise_error end - it 'keeps answering when a catch-all for the same endpoint follows it' do - zammad.stub(:get, 'api/v1/groups/search', body: { total_count: 42 }, query: { only_total_count: true }) - zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1 }]) - - expect(Array.new(3) { client.groups.search('x').count }).to eq([42, 42, 42]) - end - - it 'leaves the catch-all answering the requests it does not match' do - zammad.stub(:get, 'api/v1/groups/search', body: { total_count: 42 }, query: { only_total_count: true }) - zammad.stub(:get, 'api/v1/groups/search', body: [], query: { page: 2 }) - zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1 }]) - - expect(client.groups.search('x').count).to eq(42) - expect(client.groups.search('x').map(&:id)).to eq([1]) - expect(client.groups.search('x').count).to eq(42) - end - it 'matches an array-valued parameter' do zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { ids: [1, 2], page: 1 }) zammad.stub(:get, 'api/v1/users/search', body: [], query: { ids: [1, 2], page: 2 }) @@ -499,11 +314,6 @@ expect(client.users.search('x', ids: [1, 2]).map(&:id)).to eq([1]) end - it 'reports a nil query value against the stub that wrote it' do - expect { zammad.stub(:get, 'api/v1/users/search', body: [], query: { ids: nil }) } - .to raise_error(ArgumentError, /query parameter ids is nil/) - end - it 'does not match an array whose values differ' do zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { ids: [1, 2] }) @@ -511,20 +321,25 @@ .to raise_error(described_class::UnstubbedRequestError) end - it 'answers ahead of a catch-all declared before it' do - zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1 }]) + it 'answers a search count from a stub for the request for the total' do zammad.stub(:get, 'api/v1/groups/search', body: { total_count: 42 }, query: { only_total_count: true }) expect(client.groups.search('x').count).to eq(42) + expect(zammad.requests.size).to eq(1) + end + + it 'sequences two stubs that share a scope' do + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }], query: { sort_by: 'name' }) + + expect(Array.new(3) { client.groups.all.order(:name).page(1, per_page: 1).map(&:id) }).to eq([[1], [2], [2]]) end - it 'still sequences two stubs that share a scope' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name,id' }) - zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }], query: { sort_by: 'name,id' }) + it 'spends the first matching stub where a later one matches too' do + zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) + zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }]) - expect(client.groups.all.order(:name).page(1, per_page: 1).map(&:id)).to eq([1]) - expect(client.groups.all.order(:name).page(1, per_page: 1).map(&:id)).to eq([2]) - expect(client.groups.all.order(:name).page(1, per_page: 1).map(&:id)).to eq([2]) + expect(Array.new(3) { client.get('api/v1/groups', query: { sort_by: 'name' }).body }).to eq([[{ id: 1 }], [{ id: 2 }], [{ id: 2 }]]) end end end @@ -536,7 +351,7 @@ it 'names the request that was not stubbed' do expect { client.groups.find(1) } - .to raise_error(%r{GET api/v1/groups/1 was not stubbed}) + .to raise_error(described_class::UnstubbedRequestError, 'GET api/v1/groups/1 with query {"expand" => "true"} was not stubbed on this ZammadAPI::Test (nothing is stubbed)') end it 'says so when nothing at all is stubbed' do @@ -549,31 +364,14 @@ expect { client.groups.find(1) }.to raise_error(%r{stubbed: GET api/v1/groups/2}) end - # Listing the endpoint among what is stubbed read as a contradiction. - context 'when the endpoint is stubbed for other queries' do - before do - zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { page: 1 }) - zammad.stub(:get, 'api/v1/users/search', body: [{ id: 2 }], query: { page: 2 }) - end - - it 'names the query the request carried and the scopes its stubs answer' do - expect { client.users.search('x').to_a }.to raise_error( - described_class::UnstubbedRequestError, - %r{GET api/v1/users/search with query \{.*"page" => "3".*\} was not stubbed .*: its stubs answer only query: \{"page" => "1"\}, query: \{"page" => "2"\}\.} - ) - end - - it 'says that a read asks for the page after its last one' do - expect { client.users.search('x').to_a } - .to raise_error(described_class::UnstubbedRequestError, /A read asks for the page after the last one it was served/) - end - - it 'says nothing about pages where the scopes do not name one' do - zammad.reset.stub(:get, 'api/v1/users/search', body: [], query: { ids: [1] }) + it 'names the query of a request for a page no stub answers' do + zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { page: 1 }) + zammad.stub(:get, 'api/v1/users/search', body: [{ id: 2 }], query: { page: 2 }) - expect { client.users.search('x', ids: [2]).to_a } - .to raise_error(described_class::UnstubbedRequestError) { |error| expect(error.message).not_to include('page after') } - end + expect { client.users.search('x').to_a }.to raise_error( + described_class::UnstubbedRequestError, + %r{\AGET api/v1/users/search with query \{.*"page" => "3".*\} was not stubbed on this ZammadAPI::Test \(stubbed: GET api/v1/users/search\)\z} + ) end it 'is outside ZammadAPI::Error, so code under test cannot rescue it as an API failure' do @@ -613,9 +411,6 @@ expect(zammad.requests.last.body).to eq({ name: 'Renamed' }) end - # Recorded by reference, a test that built one payload, sent it, then - # changed it for a second call rewrote the first recorded request and - # asserted against a body that never went anywhere. it 'records the body as it was sent, not as the test left it afterwards' do zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) payload = { name: 'Support', note: { internal: 'yes' } } @@ -634,16 +429,7 @@ expect(zammad.requests.last.body).to be_frozen end - # The wire carries strong parameters as the Hash they convert to, so - # that is what the record of a request holds, and not the object. - it 'records strong parameters as the Hash they are sent as' do - zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) - client.post('api/v1/groups', body: { group: StrongParameters.new(name: 'Support') }) - - expect(zammad.requests.last.body).to eq({ group: { 'name' => 'Support' } }) - end - - it 'records a record built from them as the attributes it sends' do + it 'records a record built from strong parameters as the attributes it sends' do zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) client.groups.create(StrongParameters.new(name: 'Support')) @@ -664,14 +450,11 @@ .to eq({ 'expand' => 'true', 'page' => '2', 'per_page' => '50' }) end - it 'rejects a nil query value the way the transport does' do - expect { client.get('api/v1/groups', query: { sort_by: nil }) } - .to raise_error(ArgumentError, /query parameter sort_by is nil/) - end + it 'records a nested query stringified throughout' do + zammad.stub(:get, 'api/v1/roles', body: []) + client.get('api/v1/roles', query: { ids: [1, 2], filter: { active: true } }) - it 'rejects a query value with nothing in it the way the transport does' do - expect { client.get('api/v1/groups', query: { filter: {} }) } - .to raise_error(ArgumentError, /query parameter filter is a Hash with no value in it/) + expect(zammad.requests.last.query).to eq('ids' => %w[1 2], 'filter' => { 'active' => 'true' }) end it 'records requests oldest first' do @@ -713,24 +496,6 @@ expect(zammad.requests.last.on_behalf_of).to be_nil end - # The stand-in carries the scope by the real transport's rule, so it - # refuses one the wire would carry as no scope at all. - it 'refuses a blank scope reached through the transport, the way the real transport does' do - expect { client.instance_variable_get(:@transport).with_on_behalf_of(' ') } - .to raise_error(ArgumentError, /on_behalf_of needs the login/) - end - - it 'refuses one it is built with directly' do - expect { ZammadAPI::Test::Transport.new(zammad, on_behalf_of: ' ') }.to raise_error(ArgumentError, /on_behalf_of needs the login/) - end - - it 'holds one it is built with as the text the header carries' do - expect(ZammadAPI::Test::Transport.new(zammad, on_behalf_of: 7).on_behalf_of).to eq('7') - end - - # Through the real transport's own rules, so that a stand-in cannot accept - # a header the wire would refuse or record it in a shape the wire would - # not carry. it 'records the headers a raw request asked for' do zammad.stub(:get, 'api/v1/roles', body: []) client.get('api/v1/roles', headers: { 'Accept-Language' => 'de-de' }) @@ -751,11 +516,6 @@ expect(zammad.requests.last.headers).to eq({}) end - it 'refuses a header the real transport would refuse' do - expect { client.get('api/v1/roles', headers: { 'Authorization' => 'Token other' }) } - .to raise_error(ArgumentError, /header authorization is set by this client/) - end - it 'records a request that was not stubbed, so the failure can be inspected' do expect { client.groups.find(2) }.to raise_error(described_class::UnstubbedRequestError) expect(zammad.requests.map(&:path)).to eq(['api/v1/groups/2']) @@ -797,9 +557,6 @@ expect(zammad.inspect).to eq('#') end - # The request count used to be read outside the monitor, so printing a - # stand-in from a failure message or a debugger raced a thread under test - # appending to it - which is the one thing the monitor is here to prevent. it 'reads the recorded requests under the monitor' do zammad.stub(:get, 'api/v1/groups', body: []) writers = Array.new(4) { Thread.new { 25.times { client.groups.all.to_a } } } @@ -810,280 +567,6 @@ end end - # A record holds its transport, and Psych writes an object as its instance - # variables. The real transport writes where it points and how it - # authenticates, and the stand-in's wrote the stand-in: every stub and - # every recorded request, under each record. - describe 'a record written as YAML' do - let(:zammad) { described_class.new(http_token: 'tok-s3cret') } - - it 'names the transport the way the real one does' do - expect(YAML.unsafe_load(client.groups.new(name: 'Support').to_yaml.sub(/\A--- .*$/, '---'))) - .to include('transport' => { 'url' => 'https://zammad.test/', 'auth' => 'http_token' }) - end - - it 'names an on_behalf_of scope' do - expect(client.on_behalf_of('agent@example.com').groups.new(name: 'Support').to_yaml).to include('on_behalf_of: agent@example.com') - end - - it 'holds neither the token nor what was stubbed' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'stubbed-name' }) - - expect(client.groups.new(name: 'Support').to_yaml).not_to match(/tok-s3cret|stubbed-name/) - end - end - - # A collection walks until a page repeats, comes back short, or comes back - # empty. A stub that served the same records to every page tripped the - # first of those, so the obvious way to stand in for a list endpoint made - # every full read of it raise PaginationError - against a real Zammad the - # same code works, because page 2 comes back empty. - # The real transport sends a GET again that was answered 429 or 5xx. The - # stand-in raised for the first such answer, so a test of code that leans - # on the retry passed or failed the other way round from production. - describe 'a read the client retries' do - def find = client.groups.find(1) - - context 'when it fails once and is then answered' do - before do - zammad.stub(:get, 'api/v1/groups/1', status: 503, body: { error: 'down' }) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) - end - - it 'answers with the record, as the wire does' do - expect(find.name).to eq('Users') - end - - it 'records both attempts' do - find - expect(zammad.requests.map(&:path)).to eq(%w[api/v1/groups/1 api/v1/groups/1]) - end - - it 'records the second attempt as the request the first was' do - find - expect(zammad.requests.last).to eq(zammad.requests.first) - end - end - - [429, 500, 502, 503, 504].each do |status| - it "asks again past a #{status}" do - zammad.stub(:get, 'api/v1/groups/1', status: status) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - - expect(find.id).to eq(1) - end - end - - context 'when it keeps failing' do - before { zammad.stub(:get, 'api/v1/groups/1', status: 503, body: { error: 'down' }) } - - it 'raises the error for the status once the retries are spent' do - expect { find }.to raise_error(ZammadAPI::ServerError, /down/) - end - - it 'records as many requests as the wire would carry' do - expect { find }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(1 + zammad.config.retries) - end - end - - it 'follows the number of retries it was built with' do - zammad = described_class.new(retries: 4) - zammad.stub(:get, 'api/v1/groups/1', status: 500) - - expect { zammad.client.groups.find(1) }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(5) - end - - it 'raises for the first failure where it was built without retries' do - zammad = described_class.new(retries: 0) - zammad.stub(:get, 'api/v1/groups/1', status: 503) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - - expect { zammad.client.groups.find(1) }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(1) - end - - it 'does not ask again past a status the client does not retry' do - zammad.stub(:get, 'api/v1/groups/1', status: 404) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - - expect { find }.to raise_error(ZammadAPI::NotFoundError) - expect(zammad.requests.size).to eq(1) - end - - # A write is never repeated on the wire, so it is not repeated here. - it 'does not repeat a POST' do - zammad.stub(:post, 'api/v1/groups', status: 503) - zammad.stub(:post, 'api/v1/groups', status: 201, body: { id: 1 }) - - expect { client.groups.create(name: 'Users') }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(1) - end - - it 'does not repeat a PUT' do - zammad.stub(:put, 'api/v1/groups/1', status: 504) - - expect { client.put('api/v1/groups/1', body: { name: 'Users' }) }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(1) - end - - it 'does not repeat a DELETE' do - zammad.stub(:delete, 'api/v1/groups/1', status: 500) - - expect { client.groups.destroy(1) }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(1) - end - - # The wire does not wait out a Retry-After longer than the timeout: it - # reports the response at once. - context 'when the answer asks for a longer wait than the timeout' do - before do - zammad.stub(:get, 'api/v1/groups/1', status: 429, headers: { 'Retry-After' => '3600' }) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - end - - it 'does not ask again' do - expect { find }.to raise_error(ZammadAPI::RateLimitError) - expect(zammad.requests.size).to eq(1) - end - - it 'leaves the wait readable from the error' do - expect { find }.to raise_error(ZammadAPI::RateLimitError) { |error| expect(error.retry_after).to eq(3600) } - end - end - - context 'when the answer asks for a wait within the timeout' do - before do - zammad.stub(:get, 'api/v1/groups/1', status: 429, headers: { 'Retry-After' => '30' }) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - end - - it 'asks again' do - expect(find.id).to eq(1) - end - - it 'does not wait first' do - started = Process.clock_gettime(Process::CLOCK_MONOTONIC) - find - - expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 5 - end - end - - it 'asks again for a page of a list, and reads the list from the stub after' do - zammad.stub(:get, 'api/v1/groups', status: 502) - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'A' }]) - - expect(client.groups.map(&:name)).to eq(['A']) - end - - it 'carries the scope of a client acting for another user on every attempt' do - zammad.stub(:get, 'api/v1/groups/1', status: 503) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - client.on_behalf_of('agent@example.com').groups.find(1) - - expect(zammad.requests.map(&:on_behalf_of)).to eq(%w[agent@example.com agent@example.com]) - end - end - - # The wire refuses a 2xx whose body stops short of its Content-Length, and - # the stand-in handed it back: code that handles a save cut short could - # not be exercised here, and a fixture with a stale Content-Length passed - # here and failed against Zammad. - describe 'a 2xx stubbed with a Content-Length its body is short of' do - subject(:zammad) { described_class.new } - - let(:client) { zammad.client } - let(:cut_short) { { status: 200, body: '{"id":1,"na', headers: { 'Content-Type' => 'application/json', 'Content-Length' => '30' } } } - - it 'raises what the wire raises, in its words' do - zammad.stub(:get, 'api/v1/groups/1', **cut_short) - - expect { client.groups.find(1) } - .to raise_error(ZammadAPI::IncompleteResponseError, %r{Can't find object: the response from https://zammad\.test/ ended 19 bytes short of the 30}) - end - - it 'hands over the response as far as it was stubbed' do - zammad.stub(:get, 'api/v1/groups/1', **cut_short) - - expect { client.groups.find(1) } - .to raise_error(ZammadAPI::IncompleteResponseError) { expect(it.response.raw_body).to eq('{"id":1,"na') } - end - - it 'leaves a record whose save it answers saved, as the wire does' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) - zammad.stub(:put, 'api/v1/groups/1', **cut_short) - group = client.groups.find(1) - group.name = 'Support' - - expect { group.save }.to raise_error(ZammadAPI::IncompleteResponseError) - expect(group.changed?).to be(false) - end - - # A read is sent again for it on the wire, as it is for a connection - # that was reset, and each attempt takes the next stub of a sequence. - it 'sends a read again for it, as often as the client retries' do - zammad.stub(:get, 'api/v1/groups/1', **cut_short) - - expect { client.groups.find(1) }.to raise_error(ZammadAPI::IncompleteResponseError) - expect(zammad.requests.map(&:path)).to eq(['api/v1/groups/1'] * (1 + zammad.config.retries)) - end - - it 'answers a read that is cut short once and then whole with the record' do - zammad.stub(:get, 'api/v1/groups/1', **cut_short) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) - - expect(client.groups.find(1).name).to eq('Users') - expect(zammad.requests.size).to eq(2) - end - - it 'sends a read once where the client was built without retries' do - zammad = described_class.new(retries: 0) - zammad.stub(:get, 'api/v1/groups/1', **cut_short) - - expect { zammad.client.groups.find(1) }.to raise_error(ZammadAPI::IncompleteResponseError) - expect(zammad.requests.size).to eq(1) - end - - it 'does not send a write again for it' do - zammad.stub(:post, 'api/v1/groups', **cut_short) - zammad.stub(:post, 'api/v1/groups', body: { id: 2, name: 'Support' }) - - expect { client.groups.create(name: 'Support') }.to raise_error(ZammadAPI::IncompleteResponseError) - expect(zammad.requests.size).to eq(1) - end - - it 'takes a body as long as its Content-Length, or longer' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }, headers: { 'Content-Length' => 8 }) - zammad.stub(:get, 'api/v1/groups/2', body: { id: 2 }, headers: { 'Content-Length' => 2 }) - - expect([client.groups.find(1).id, client.groups.find(2).id]).to eq([1, 2]) - end - - it 'takes a 204, which has no body whatever the header says' do - zammad.stub(:delete, 'api/v1/groups/1', status: 204, headers: { 'Content-Length' => 5 }) - - expect(client.groups.destroy(1)).to be(true) - end - - it 'raises the error of its status for a response that is no 2xx' do - zammad.stub(:get, 'api/v1/groups/1', status: 404, body: { error: 'gone' }, headers: { 'Content-Length' => 500 }) - - expect { client.groups.find(1) }.to raise_error(ZammadAPI::NotFoundError) - end - - # The page after a list is one the stand-in makes up, and the length - # written for the records does not count it. - it 'counts the empty page it serves after a list anew' do - records = [{ id: 1 }, { id: 2 }] - zammad.stub(:get, 'api/v1/groups', body: records, headers: { 'Content-Length' => JSON.generate(records).bytesize }) - - expect(client.groups.map(&:id)).to eq([1, 2]) - expect(client.get('api/v1/groups', query: { page: 2 }).headers['content-length']).to eq('2') - end - end - describe 'a list endpoint whose resource says it does not page' do let(:resource) do Class.new(ZammadAPI::Resources::Base) do @@ -1133,179 +616,15 @@ def self.name = 'ObjectAttribute' expect(client.groups.all.page(2).map(&:id)).to eq([]) end - it 'stops walking rather than reporting the stand-in as a broken paginator' do - expect { client.groups.all.to_a }.not_to raise_error - end - end - - # Only the page number was read. The records were served whole to page 1 - # whatever size was asked for, and every later page was empty, so code - # that pages by hand or leans on a batch size saw other records here than - # Zammad serves it. - describe 'a list endpoint stubbed once, read a page of a given size at a time' do - subject(:zammad) { described_class.new } - - let(:client) { zammad.client } - let(:records) { (1..5).map { { id: it, name: "group #{it}" } } } - - before { zammad.stub(:get, 'api/v1/groups', body: records) } - - it 'answers page 1 with as many records as were asked for' do - expect(client.groups.all.page(1, per_page: 2).map(&:id)).to eq([1, 2]) - end - - it 'answers a later page with the records that follow' do - expect(client.groups.all.page(2, per_page: 2).map(&:id)).to eq([3, 4]) - end - - it 'answers the last page with what is left' do - expect(client.groups.all.page(3, per_page: 2).map(&:id)).to eq([5]) - end - - it 'answers a page past the records as an endpoint out of records would' do - expect([4, 9].map { client.groups.all.page(it, per_page: 2).to_a }).to eq([[], []]) - end - - it 'hands in_batches the batches Zammad would' do - batches = [] - client.groups.in_batches(of: 2) { |batch| batches << batch.map(&:id) } - - expect(batches).to eq([[1, 2], [3, 4], [5]]) - end - - it 'hands find_each every record once, however small the batch' do - expect(client.groups.find_each(batch_size: 2).map(&:id)).to eq([1, 2, 3, 4, 5]) - end - - it 'asks for an empty page after a last one that was full' do - client.groups.find_each(batch_size: 5).to_a - - expect(zammad.requests.map { it.query['page'] }).to eq(%w[1 2]) - end - - it 'still reads the whole list where the page is larger than it' do - expect(client.groups.all.map(&:id)).to eq([1, 2, 3, 4, 5]) - end - - it 'serves a raw request that names no size every record' do - expect(client.get('api/v1/groups').body.size).to eq(5) - end - - it 'serves a raw request the page it names' do - expect(client.get('api/v1/groups', query: { page: 2, per_page: 3 }).body).to eq([{ id: 4, name: 'group 4' }, { id: 5, name: 'group 5' }]) - end - - it 'keeps the bytes of a stub it did not cut' do - zammad.stub(:get, 'api/v1/users', body: '[ {"id": 1} ]', headers: { 'Content-Type' => 'application/json' }) - - expect(client.get('api/v1/users', query: { per_page: 1 }).raw_body).to eq('[ {"id": 1} ]') - end - - it 'counts a page it cut anew, where the stub announced a length' do - zammad.stub(:get, 'api/v1/users', body: [{ id: 1 }, { id: 2 }], headers: { 'Content-Length' => 19 }) - - expect(client.get('api/v1/users', query: { per_page: 1 }).headers['content-length']).to eq('10') - end - - # A stub short of its own Content-Length says the answer was cut short, - # and a page cut from it would have been counted anew and served. - it 'does not cut a page from a stub that is short of its own Content-Length' do - zammad.stub(:get, 'api/v1/users', body: [{ id: 1 }, { id: 2 }], headers: { 'Content-Length' => 500 }) - - expect { zammad.client.with(retries: 0).users.all.page(1, per_page: 1).to_a }.to raise_error(ZammadAPI::IncompleteResponseError) - end - - it 'leaves a size that is no number above zero to the stub as it was written' do - expect(%w[0 -1 two].map { client.get('api/v1/groups', query: { per_page: it }).body.size }).to eq([5, 5, 5]) - end - - # Such a stub is what a request of that size is answered. - it 'does not cut a stub that names a per_page of its own' do - zammad.stub(:get, 'api/v1/users', body: [{ id: 1 }, { id: 2 }, { id: 3 }], query: { per_page: 2 }) - - expect(client.get('api/v1/users', query: { per_page: 2 }).body.size).to eq(3) - expect(client.get('api/v1/users', query: { per_page: 2, page: 2 }).body).to eq([]) - end - - it 'does not cut a stub that names its page' do - zammad.stub(:get, 'api/v1/users', body: [{ id: 1 }, { id: 2 }, { id: 3 }], query: { page: 1 }) - - expect(client.get('api/v1/users', query: { page: 1, per_page: 2 }).body.size).to eq(3) - end - - it 'spends one stub of a sequence on a read of several pages' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 9, name: 'later' }]) - - expect(client.groups.find_each(batch_size: 2).map(&:id)).to eq([1, 2, 3, 4, 5]) - expect(client.groups.find_each(batch_size: 2).map(&:id)).to eq([9]) - end - end - - # The object a Zammad from 6.5.1 on answers a walked search with. It is a - # list too, so the page after it holds no records - and reports the same - # total, which is what a walk reads to tell that page from the end. - describe 'a search stubbed once with its total beside the records' do - subject(:zammad) { described_class.new } - - let(:client) { zammad.client } - - it 'reads the whole search without a second stub' do - zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }], total_count: 2 }) - - expect(client.users.search('smith').map(&:id)).to eq([1, 2]) - end - - it 'answers a later page with no records and the same total' do - zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }], total_count: 2 }) - - expect(client.get('api/v1/users/search', query: { query: 'smith', page: 2 }).body).to eq(records: [], total_count: 2) - end - - it 'answers page 1 as it was written' do - zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }], total_count: 2 }) - - expect(client.get('api/v1/users/search', query: { query: 'smith', page: 1 }).body).to eq(records: [{ id: 1 }, { id: 2 }], total_count: 2) - end - - it 'answers a page of a given size with its records and the same total' do - zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }, { id: 3 }], total_count: 3 }) - - expect(client.get('api/v1/users/search', query: { query: 'smith', page: 2, per_page: 2 }).body).to eq(records: [{ id: 3 }], total_count: 3) - end - - it 'hands a search read in batches every hit once' do - zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }, { id: 3 }], total_count: 3 }) - - expect(client.users.search('smith').find_each(batch_size: 2).map(&:id)).to eq([1, 2, 3]) - end - - # The stub holds two records and says there are five hundred hits, so the - # walk reads on, a page of two hundred at a time, until it has covered - # them: the page it was served, and two that hold nothing. - it 'is read on past, where the total says there are hits beyond the stub' do - zammad.stub(:get, 'api/v1/users/search', body: { records: [{ id: 1 }, { id: 2 }], total_count: 500 }) - - expect(client.users.search('smith').map(&:id)).to eq([1, 2]) - expect(zammad.requests.map { it.query['page'] }).to eq(%w[1 2 3]) - end - - it 'records the parameter a walked search asks for the total with' do - zammad.stub(:get, 'api/v1/users/search', body: []) - client.users.search('smith').to_a - - expect(zammad.requests.last.query).to include('with_total_count' => 'true') + it 'answers page 1 with every record it holds, whatever size was asked for' do + expect(client.groups.all.page(1, per_page: 1).map(&:id)).to eq([1, 2]) end - it 'leaves an object that is not a counted list as it was written' do - zammad.stub(:get, 'api/v1/settings', body: { records: 'none' }) - - expect(client.get('api/v1/settings', query: { page: 2 }).body).to eq(records: 'none') + it 'stops walking rather than reporting the stand-in as a broken paginator' do + expect { client.groups.all.to_a }.not_to raise_error end end - # Every full read asks for the page after its last one, and that request - # used to take the next stub in the queue and serve it as an empty page: - # three stubs answered three reads with the first, the third and the third. describe 'a list endpoint stubbed as a sequence' do subject(:zammad) { described_class.new } @@ -1327,20 +646,11 @@ def names = client.groups.all.map(&:name) end it 'spends one stub on a read, however many pages the read asks for' do - names + expect(client.groups.find_each(batch_size: 1).map(&:name)).to eq(['A']) expect(zammad.requests.map { it.query['page'] }).to eq(%w[1 2]) expect(names).to eq(['B']) end - it 'answers the trailing page from the stub the read began with, not the next one' do - zammad.reset - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'A' }]) - zammad.stub(:get, 'api/v1/groups', status: 500, body: { error: 'down' }) - - expect(names).to eq(['A']) - expect { names }.to raise_error(ZammadAPI::ServerError) - end - it 'does not spend a stub on a later page asked for first' do expect(client.groups.all.page(3).to_a).to eq([]) expect(names).to eq(['A']) @@ -1365,87 +675,13 @@ def names = client.groups.all.map(&:name) expect(Array.new(2) { client.groups.search('x').map(&:name) }).to eq([['A'], ['B']]) end - # The read before it asked for a page after its last, and that request - # belongs to the stub the read began with. - it 'answers a read with a stub declared after the last one has answered a whole read' do - 3.times { names } - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'D' }]) - - expect(Array.new(2) { names }).to eq([['D'], ['D']]) - end - end - - # `count` on a search asks for the total alone first, and walks the pages - # where it is answered with records instead. Each of the two took a stub: - # the first of a sequence was never counted, and the last was counted - # twice. - describe 'a search stubbed as a sequence, and counted' do - subject(:zammad) { described_class.new } - - let(:client) { zammad.client } - let(:path) { 'api/v1/users/search' } - - def counts(times) = Array.new(times) { client.users.search('x').count } - - def stub_lists - [1, 2, 3].each { |records| zammad.stub(:get, path, body: Array.new(records) { { id: it + 1 } }) } - end - - it 'counts each stub in turn, and the last one from then on' do - stub_lists - - expect(counts(4)).to eq([1, 2, 3, 3]) - end - - it 'counts what reading the records counts' do - stub_lists - - expect(Array.new(3) { client.users.search('x').to_a.size }).to eq([1, 2, 3]) - end - - it 'spells #size and #length the same way' do - stub_lists - - expect([client.users.search('x').size, client.users.search('x').length]).to eq([1, 2]) - end - - it 'records the request for the total and the walk that follows it' do - stub_lists - counts(1) - - expect(zammad.requests.map { it.query.slice('only_total_count', 'page').values.first }).to eq(%w[true 1 2]) - end - - it 'spends a stub on the request alone where the stub holds a total' do - zammad.stub(:get, path, body: { records: [{ id: 1 }], total_count: 1 }) - zammad.stub(:get, path, body: { total_count: 2 }) - zammad.stub(:get, path, body: [{ id: 1 }, { id: 2 }, { id: 3 }]) - - expect(counts(4)).to eq([1, 2, 3, 3]) - end - - it 'spends a stub on an attempt that failed, and counts the one after it' do - zammad.stub(:get, path, status: 503) - stub_lists - - expect(counts(3)).to eq([1, 2, 3]) - end - - it 'counts a stub declared after the last one has been counted' do - zammad.stub(:get, path, body: [{ id: 1 }]) - counts(2) - zammad.stub(:get, path, body: [{ id: 1 }, { id: 2 }]) - - expect(counts(2)).to eq([2, 2]) - end - - # A stub scoped to the request is the answer to it and to nothing else, - # whatever it holds, so each request for the total is a step. - it 'still sequences stubs written for the request for the total' do - zammad.stub(:get, path, body: [{ id: 1 }], query: { only_total_count: true }) - zammad.stub(:get, path, body: [{ id: 1 }, { id: 2 }], query: { only_total_count: true }) + it 'answers the page after a list with an empty one, whatever stub is queued next' do + zammad.reset + zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1, name: 'A' }]) + zammad.stub(:get, 'api/v1/groups/search', status: 500) - expect(Array.new(3) { client.get(path, query: { only_total_count: true }).body.size }).to eq([1, 2, 2]) + expect(client.groups.search('x').map(&:name)).to eq(['A']) + expect { client.groups.search('x').to_a }.to raise_error(ZammadAPI::ServerError) end end @@ -1461,7 +697,7 @@ def stub_lists zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }], query: { page: 2 }) zammad.stub(:get, 'api/v1/groups', body: [], query: { page: 3 }) - expect(client.groups.all.map(&:id)).to eq([1, 2]) + expect(client.groups.find_each(batch_size: 1).map(&:id)).to eq([1, 2]) end it 'keeps a body that is not a list alone' do @@ -1470,49 +706,4 @@ def stub_lists expect(client.groups.find(1).name).to eq('a') end end - - # Two stubs naming different parameters both match a request carrying all of - # them. Grouped only by whether they were scoped at all, they were read as a - # sequence and the first was consumed: the count ate the records stub, - # handed back an Array where a count belonged, and then reported the - # endpoint as unstubbed. - describe 'two stubs that describe one request equally well' do - subject(:zammad) { described_class.new } - - let(:client) { zammad.client } - - before do - zammad.stub(:get, 'api/v1/tickets/search', body: [{ id: 1 }], query: { query: 'foo' }) - zammad.stub(:get, 'api/v1/tickets/search', body: { total_count: 2 }, query: { only_total_count: true }) - end - - it 'refuses to guess which one was meant' do - expect { client.tickets.search('foo').count }.to raise_error(described_class::AmbiguousStubError) - end - - it 'names both scopes, so the fix is visible from the message' do - expect { client.tickets.search('foo').count } - .to raise_error(described_class::AmbiguousStubError, /only_total_count.*|.*only_total_count/) - end - - it 'says the test is wrong rather than that Zammad refused something' do - expect(described_class::AmbiguousStubError.ancestors).not_to include(ZammadAPI::Error) - end - - it 'answers the request a more specific stub names' do - zammad.reset - zammad.stub(:get, 'api/v1/tickets/search', body: [{ id: 1 }], query: { query: 'foo' }) - zammad.stub(:get, 'api/v1/tickets/search', body: { total_count: 2 }, query: { query: 'foo', only_total_count: true }) - - expect(client.tickets.search('foo').count).to eq(2) - end - - it 'leaves the less specific stub answering the requests it alone matches' do - zammad.reset - zammad.stub(:get, 'api/v1/tickets/search', body: [{ id: 1 }], query: { query: 'foo' }) - zammad.stub(:get, 'api/v1/tickets/search', body: { total_count: 2 }, query: { query: 'foo', only_total_count: true }) - - expect(client.tickets.search('foo').map(&:id)).to eq([1]) - end - end end diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 8769125..17586f6 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -1,8 +1,6 @@ # frozen_string_literal: true -require 'bigdecimal' require 'pp' -require 'yaml' RSpec.describe ZammadAPI::Transport do let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } @@ -54,46 +52,6 @@ expect(stub).to have_been_requested end - # Net::HTTP refused it at the request, quoting the value. - it 'refuses a raw request header with a line break inside it, without quoting it' do - expect { described_class.stringify_headers('X-Api-Key' => "abc\r\nsecret") } - .to raise_error(ArgumentError, /\Aheader x-api-key holds a line break, which a header cannot carry/) { |error| - expect(error.message).not_to include('secret') - } - end - - # The check stripped the value first, which raises for such text, and - # read the error as "no line break". - it 'refuses a line break beside a byte sequence that is invalid in the encoding' do - expect { described_class.stringify_headers('Accept-Language' => "de\xFF\nX-Injected: secret") } - .to raise_error(ArgumentError, /\Aheader accept-language holds a line break, which a header cannot carry/) { |error| - expect(error.message).not_to include('secret') - } - end - - # Net::HTTP strips it, and it was left to: an adapter that does not was - # handed the value with the break on it. - it 'takes one that only ends in a line break, and hands it on without' do - expect(described_class.stringify_headers('X-Note' => "abc\n")).to eq('x-note' => 'abc') - end - - it 'strips what Net::HTTP does from both ends, and nothing inside' do - expect(described_class.stringify_headers('X-Note' => " \tone two\r\n\r\n")).to eq('x-note' => 'one two') - end - - it 'strips a line break after bytes that are invalid in the encoding, and keeps the encoding' do - value = described_class.stringify_headers('X-Note' => "abc\xFF\n").fetch('x-note') - - expect(value).to eq("abc\xFF") - expect(value.encoding).to eq(Encoding::UTF_8) - end - - it 'hands a value with nothing around it on as the String it was given' do - value = 'abc' - - expect(described_class.stripped(value)).to be(value) - end - # WebMock is asked by Net::HTTP, which has stripped the headers by then. # A middleware sees them as the adapter is handed them. context 'with a configured header value that ends in a line break' do @@ -118,74 +76,14 @@ def handed_to_the_adapter(**options) it 'hands the adapter a user agent without it' do expect(handed_to_the_adapter(user_agent: "my-app/1.0\n")['User-Agent']).to eq('my-app/1.0') end - - it 'hands the adapter a raw request header without it' do - seen = nil - recorder = Class.new(Faraday::Middleware) do - define_method(:on_request) { |env| seen = env.request_headers['x-trace'] } - end - stub_request(:get, url).to_return(json_response([])) - unit_transport(middleware: ->(builder) { builder.use(recorder) }) - .get('api/v1/groups', operation: 'test', headers: { 'X-Trace' => "t\r\n" }) - - expect(seen).to eq('t') - end - end - - it 'carries a header value given in UTF-16 as the same text in UTF-8' do - expect(described_class.stringify_headers('X-Note' => 'ä'.encode('UTF-16LE'))).to eq('x-note' => 'ä') end end - # Only the value of a raw request's header was checked. The Net::HTTP that - # ships with Ruby 3.4 and 4.0 writes a name to the socket as it is, so one - # holding a line break sent header lines of its own, a From or an - # Authorization among them. - describe 'header names' do - it 'downcases a name, and takes it as text or as a Symbol' do - expect(described_class.stringify_headers('Accept-Language' => 'de', :'X-Trace' => 'abc')).to eq('accept-language' => 'de', 'x-trace' => 'abc') - end - - it 'takes every sign a name may hold' do - expect(described_class.stringify_headers("X!#$%&'*+-.^_`|~9" => 'v')).to eq("x!#$%&'*+-.^_`|~9" => 'v') - end - - it 'refuses a name with a line break in it, and header lines of its own after that' do - expect { described_class.stringify_headers("X-A: 1\r\nFrom: admin@example.com\r\nX-B" => 'v') } - .to raise_error(ArgumentError, /\Athe header name that begins "X-A" goes on with a character no header name carries/) - end - - it 'does not quote what follows, which may be a credential' do - expect { described_class.stringify_headers("X-A: 1\r\nAuthorization: Token name-s3cret\r\nX-B" => 'v') } - .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('name-s3cret') } - end - - # Each passed the lookup that refuses a From header by name. - ['From ', ' From', "From\t", 'From:', "From\n"].each do |name| - it "refuses #{name.inspect}, which is no spelling of a header" do - expect { described_class.stringify_headers(name => 'agent@example.com') }.to raise_error(ArgumentError, /no header name carries/) - end - end - - ['', nil, 'X Trace', 'Träce', 'X-Trace'.encode('UTF-16LE')].each do |name| - it "refuses #{name.inspect}" do - expect { described_class.stringify_headers(name => 'abc') }.to raise_error(ArgumentError, /no header name carries/) - end - end - - # `downcase` raises for such text, with a message of its own. - it 'refuses a name with a byte sequence that is invalid in its encoding' do - expect { described_class.stringify_headers("X-\xFFTrace" => 'abc') } - .to raise_error(ArgumentError, /\Athe header name that begins "X-" goes on with a character no header name carries/) - end - - it 'makes no request for one, and logs none' do - log = StringIO.new - - expect { unit_transport(logger: Logger.new(log)).get('api/v1/groups', operation: 'test', headers: { "X-A\r\nFrom: x" => 'v' }) } - .to raise_error(ArgumentError) - expect(log.string).to be_empty - expect(a_request(:any, /zammad\.test/)).not_to have_been_made + describe 'request headers' do + it 'sends the headers given for a request, each value as text' do + stub = stub_request(:get, url).with(headers: { 'X-Trace' => 'abc', 'X-Count' => '2' }).to_return(json_response([])) + unit_transport.get('api/v1/groups', operation: 'test', headers: { 'X-Trace' => 'abc', 'X-Count' => 2 }) + expect(stub).to have_been_requested end end @@ -217,8 +115,7 @@ def handed_to_the_adapter(**options) end # `condition` is what Zammad's search endpoints narrow by, and it is - # nested. Rendered with to_s it went out as a Ruby inspect string, which - # Zammad dropped, answering an unnarrowed search. + # nested. it 'encodes a nested hash the way Rails reads it back' do stub = stub_request(:get, "#{url}/search") .with(query: { 'condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => %w[1 2] } } }) @@ -230,353 +127,22 @@ def handed_to_the_adapter(**options) ) expect(stub).to have_been_requested end + end - it 'stringifies the scalars inside a nested hash' do - expect(described_class.stringify_query(condition: { open: { active: true, limit: 5 } })) - .to eq({ 'condition' => { 'open' => { 'active' => 'true', 'limit' => '5' } } }) - end - - # Whatever was neither a Hash nor an Array went on the wire as its - # `to_s`, which names nothing, and Zammad narrowed by it all the same. - context 'with a value a query string has no spelling for' do - { 'a Set' => Set[1, 2], 'a Range' => (1..3), 'a Time' => Time.at(0), 'any other object' => Object.new }.each do |kind, value| - it "refuses #{kind} by its class, without quoting it" do - expect { described_class.stringify_query(ids: value) } - .to raise_error(ArgumentError, /\Aquery parameter ids was given as #{value.class}, and a query string carries text, Integers, Floats and booleans/) { |error| - expect(error.message).not_to include(value.to_s) - } - end - end - - it 'refuses one inside a list, naming where' do - expect { described_class.stringify_query(ids: [1, Set[2]]) }.to raise_error(ArgumentError, /\Aquery parameter ids\[1\] was given as Set/) - end - - it 'refuses one inside a structure, naming where' do - expect { described_class.stringify_query(condition: { 'ticket.id' => { operator: 'is', value: (1..3) } }) } - .to raise_error(ArgumentError, /\Aquery parameter condition\[ticket\.id\]\[value\] was given as Range/) - end - - it 'sends nothing for a request that carries one' do - expect { unit_transport.get('api/v1/groups', operation: 'test', query: { ids: Set[1, 2] }) }.to raise_error(ArgumentError) - expect(a_request(:any, //)).not_to have_been_made - end - - it 'still writes text, a Symbol, a number and a boolean' do - expect(described_class.stringify_query(a: 'x', b: :y, c: 1, d: 1.5, e: true, f: false)) - .to eq({ 'a' => 'x', 'b' => 'y', 'c' => '1', 'd' => '1.5', 'e' => 'true', 'f' => 'false' }) - end - - # Every Numeric was taken for a number a query string spells, and - # these print as `0.5e1`, `1/2` and `1+2i`. - { 'a BigDecimal' => BigDecimal('5'), 'a Rational' => Rational(1, 2), 'a Complex' => Complex(1, 2) }.each do |kind, value| - it "refuses #{kind}, which is a number and prints as something else" do - expect { described_class.stringify_query(ids: [value]) } - .to raise_error(ArgumentError, /\Aquery parameter ids\[0\] was given as #{value.class}, .+ a number of another kind as an Integer or a Float/) - end - end - - [Float::NAN, Float::INFINITY, -Float::INFINITY].each do |value| - it "refuses #{value}, which is a Float and no number a query string spells" do - expect { described_class.stringify_query(condition: { weight: value }) } - .to raise_error(ArgumentError, /\Aquery parameter condition\[weight\] is #{value}, and a query string has no spelling for a Float that is not finite/) - end - end - - it 'still writes a Float of any size' do - expect(described_class.stringify_query(a: 0.0, b: -2.5, c: 1e20)).to eq({ 'a' => '0.0', 'b' => '-2.5', 'c' => '1.0e+20' }) - end - end - - # `ActionController::Parameters` is not a Hash. Nested, it was written - # as its `to_s`; as the whole query it raised NoMethodError. - context 'with what converts to a Hash and is not one' do - it 'reads it as that Hash where it is a value' do - expect(described_class.stringify_query(condition: StrongParameters.new(open: StrongParameters.new(limit: 5)))) - .to eq({ 'condition' => { 'open' => { 'limit' => '5' } } }) - end - - it 'reads it as that Hash where it is the query' do - expect(described_class.stringify_query(StrongParameters.new(page: 2))).to eq({ 'page' => '2' }) - end - - it 'refuses two spellings of one key in it, as in a Hash' do - expect { described_class.stringify_query(condition: StrongParameters.new(a: 1), 'condition' => 2) }.to raise_error(ArgumentError, /given twice/) - end - - it 'sends it the way Rails reads a nested parameter back' do - stub = stub_request(:get, "#{url}/search").with(query: { 'condition' => { 'state' => { 'operator' => 'is' } } }).to_return(json_response([])) - unit_transport.get('api/v1/groups/search', operation: 'test', query: { condition: StrongParameters.new(state: { operator: 'is' }) }) - - expect(stub).to have_been_requested - end - end - - it 'refuses a query that is no Hash, naming its class' do - expect { described_class.stringify_query('page=2') } - .to raise_error(ArgumentError, 'query needs to be a Hash of parameter names and values, got String') - end - - # Faraday's escaping raised Encoding::CompatibilityError for one. - it 'sends a value given in UTF-16 as the same text in UTF-8' do - stub = stub_request(:get, "#{url}/search").with(query: { 'query' => 'ä b' }).to_return(json_response([])) - unit_transport.get('api/v1/groups/search', operation: 'test', query: { query: 'ä b'.encode('UTF-16LE') }) - expect(stub).to have_been_requested - end - - # An encoding ASCII is a part of can be joined to the text around it, - # so the value went out as the bytes it was held in: `query=Gr%F6%DFe`, - # which Rails answers with 400 for a query that is no UTF-8. - %w[ISO-8859-1 Windows-1252 Shift_JIS].each do |encoding| - it "sends a value given in #{encoding} as the same text in UTF-8" do - text = encoding == 'Shift_JIS' ? '検索 b' : 'Größe b' - stub = stub_request(:get, "#{url}/search").with(query: { 'query' => text }).to_return(json_response([])) - unit_transport.get('api/v1/groups/search', operation: 'test', query: { query: text.encode(encoding) }) - - expect(stub).to have_been_requested - end - end - - it 'writes the bytes of the UTF-8 text into the query string' do - query = described_class.stringify_query(query: 'Größe'.encode('ISO-8859-1')) - - expect(ZammadAPI::QueryEncoder.encode(query)).to eq('query=Gr%C3%B6%C3%9Fe') - end - - it 'converts such a value inside a list and a Hash as well' do - latin = 'Größe'.encode('ISO-8859-1') - - expect(described_class.stringify_query(tags: [latin], condition: { name: latin })) - .to eq('tags' => ['Größe'], 'condition' => { 'name' => 'Größe' }) - end - - it 'leaves a binary value as it was, which names no characters to convert' do - value = "caf\xC3\xA9".b - - expect(described_class.stringify_query(q: value)['q']).to be(value) - end - - it 'leaves a value in UTF-8 or US-ASCII as it was' do - utf8 = 'Größe' - ascii = 'open'.encode('US-ASCII') - - expect(described_class.stringify_query(a: utf8, b: ascii).values).to match([be(utf8), be(ascii)]) - end - - it 'refuses a value with a byte its own encoding does not define, without quoting it' do - broken = "secret\x81".dup.force_encoding('Windows-1252') - - expect { described_class.stringify_query(token: broken) } - .to raise_error(ArgumentError, /\Aquery parameter token was given as Windows-1252 text that cannot be converted to UTF-8/) { |error| - expect(error.message).not_to include('secret') - } - end - - it 'refuses a value that cannot be converted to UTF-8, without quoting it' do - broken = "\xD8\x00".dup.force_encoding('UTF-16BE') - - expect { described_class.stringify_query(token: broken) } - .to raise_error(ArgumentError, /\Aquery parameter token was given as UTF-16BE text that cannot be converted to UTF-8/) - end - - it 'raises on a nil value rather than dropping the parameter' do - expect { unit_transport.get('api/v1/groups', operation: 'test', query: { page: 1, note: nil }) } - .to raise_error(ArgumentError, /query parameter note is nil/) - end - - it 'names the path to a nil buried in a nested value' do - expect { described_class.stringify_query(condition: { state: { value: nil } }) } - .to raise_error(ArgumentError, /parameter condition\[state\]\[value\] is nil/) - end - - it 'refuses two spellings of one parameter rather than sending whichever came last' do - expect { described_class.stringify_query(state_id: 1, 'state_id' => 2) } - .to raise_error(ArgumentError, /parameter state_id was given twice/) - end - - it 'refuses the collision whichever order it arrives in' do - expect { described_class.stringify_query('state_id' => 2, state_id: 1) } - .to raise_error(ArgumentError, /parameter state_id was given twice/) - end - - it 'names both spellings, so the caller does not have to guess the other' do - expect { described_class.stringify_query(state_id: 1, 'state_id' => 2) } - .to raise_error(ArgumentError, /as :state_id and as "state_id"/) - end - - # `condition` is a Hash the search endpoints read, and two spellings inside - # it collapsed exactly the way two at the top level did. - it 'refuses a collision nested inside a structured parameter' do - expect { described_class.stringify_query(condition: { 'state_id' => 1, state_id: 2 }) } - .to raise_error(ArgumentError, /parameter condition\[state_id\] was given twice/) - end - - it 'still sends a structured parameter whose keys only look alike' do - expect(described_class.stringify_query(condition: { 'ticket.state_id' => { operator: 'is' } })) - .to eq({ 'condition' => { 'ticket.state_id' => { 'operator' => 'is' } } }) - end - - it 'still accepts two parameters that only look alike' do - expect(described_class.stringify_query(state_id: 1, state_ids: [2])) - .to eq({ 'state_id' => '1', 'state_ids' => ['2'] }) - end - - it 'names the index of a nil inside an array' do - expect { described_class.stringify_query(ids: [1, nil]) } - .to raise_error(ArgumentError, /query parameter ids\[1\] is nil/) - end - - it 'makes no request for a query it rejects' do - stub = stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) - - expect { unit_transport.get('api/v1/groups', operation: 'test', query: { note: nil }) } - .to raise_error(ArgumentError) - expect(stub).not_to have_been_requested - end - - # A query string does not mark where an element of a list ends. Rails - # begins a new one where a pair names a place the element it is filling - # has taken already, so a list is refused where it would not be read - # back as the list it was: the request would carry something the caller - # did not write, to an endpoint that narrows by it. - describe 'a list a query string cannot carry' do - it 'refuses a Hash that shares no key with the one before it, which Rails would read into it' do - expect { described_class.stringify_query(condition: { conditions: [{ a: 1 }, { b: 2 }] }) } - .to raise_error(ArgumentError, /query parameter condition\[conditions\]\[1\] has no plain value under a key the element before it has as well/) - end - - it 'refuses one that shares a key holding only a list' do - expect { described_class.stringify_query(list: [{ value: [1] }, { value: [2] }]) } - .to raise_error(ArgumentError, /Rails would read the two as one/) - end - - it 'refuses a Hash with nothing in it, which is not written at all' do - expect { described_class.stringify_query(list: [{ a: 1 }, {}]) } - .to raise_error(ArgumentError, /query parameter list\[1\] is a Hash with no value in it.*one element short/) - end - - it 'refuses a list directly inside a list' do - expect { described_class.stringify_query(list: [[1, 2], [3]]) } - .to raise_error(ArgumentError, /query parameter list\[0\] is a list directly inside a list/) - end - - it 'says where such a structure can be sent as it is' do - expect { described_class.stringify_query(list: [{ a: 1 }, { b: 2 }]) } - .to raise_error(ArgumentError, /put it in the JSON body of a raw request, such as client\.post/) - end - - it 'takes a group of conditions beside a condition, which share an operator' do - conditions = [{ name: 'ticket.state_id', operator: 'is', value: [2] }, { operator: 'AND', conditions: [{ name: 'a', operator: 'is', value: 1 }] }] - - expect(described_class.stringify_query(condition: { operator: 'OR', conditions: conditions }).dig('condition', 'conditions', 1, 'operator')).to eq('AND') - end - - it 'takes Hashes among plain values, each of which begins an element of its own' do - expect(described_class.stringify_query(list: [{ a: 1 }, 2, { b: 3 }])).to eq('list' => [{ 'a' => '1' }, '2', { 'b' => '3' }]) - end - - it 'makes no request for one' do - stub = stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) - - expect { unit_transport.get('api/v1/groups', operation: 'test', query: { list: [{ a: 1 }, { b: 2 }] }) }.to raise_error(ArgumentError) - expect(stub).not_to have_been_requested - end - end - - # The encoder writes a pair for each value and has none to write for a - # Hash without one, so the parameter was not in the request and Zammad - # answered as if it had been left out: `query: {filter: {}, a: 1}` asked - # for `?a=1`. - context 'with a Hash that holds no value' do - it 'refuses one under a parameter, by its name' do - expect { described_class.stringify_query(filter: {}, a: 1) } - .to raise_error(ArgumentError, /query parameter filter is a Hash with no value in it.*as if the parameter had been left out/) - end - - it 'refuses one that holds nothing but such Hashes, which is not written either' do - expect { described_class.stringify_query(filter: { a: { b: {} } }) } - .to raise_error(ArgumentError, /query parameter filter is a Hash with no value in it/) - end - - it 'refuses one further in, beside a value that is written' do - expect { described_class.stringify_query(filter: { a: { b: {} }, c: 1 }) } - .to raise_error(ArgumentError, /query parameter filter\[a\] is a Hash with no value in it/) - end - - it 'refuses one inside an element of a list' do - expect { described_class.stringify_query(list: [{ operator: 'is', value: {} }]) } - .to raise_error(ArgumentError, /query parameter list\[0\]\[value\] is a Hash with no value in it/) - end - - it 'refuses what converts to one' do - expect { described_class.stringify_query(filter: StrongParameters.new({})) } - .to raise_error(ArgumentError, /query parameter filter is a Hash with no value in it/) - end - - it 'takes a query with no parameter at all' do - expect(described_class.stringify_query({})).to eq({}) - end - - it 'takes an empty list and an empty String, which are written' do - expect(described_class.stringify_query(filter: { ids: [], name: '' })).to eq('filter' => { 'ids' => [], 'name' => '' }) - end - - it 'makes no request for one' do - stub = stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) - - expect { unit_transport.get('api/v1/groups', operation: 'test', query: { filter: {}, a: 1 }) }.to raise_error(ArgumentError) - expect(stub).not_to have_been_requested - end + describe '.relative_path' do + it 'drops a leading slash' do + expect(described_class.relative_path('/api/v1/tickets')).to eq('api/v1/tickets') end - # A query string has no way to write a key with an empty name: `[]` - # inside a structure, which Rails reads as a list, and nothing but the - # value at the top level, which Rails drops. - describe 'a key with an empty name' do - it 'refuses one in a Hash inside a list, which Rails would read as a list' do - expect { described_class.stringify_query(list: [{ '' => '1' }]) } - .to raise_error(ArgumentError, /query parameter list\[0\] holds a key with an empty name.*list\[0\]\[\], which Rails reads as a list/) - end - - it 'refuses one in a Hash further down' do - expect { described_class.stringify_query(condition: { a: { '' => '1' } }) } - .to raise_error(ArgumentError, /query parameter condition\[a\] holds a key with an empty name/) - end - - it 'refuses one given as an empty Symbol' do - expect { described_class.stringify_query(condition: { '': '1' }) }.to raise_error(ArgumentError, /holds a key with an empty name/) - end - - it 'refuses one at the top level, which Rails drops' do - expect { described_class.stringify_query('' => '1') }.to raise_error(ArgumentError, /a query parameter has an empty name.*which Rails drops/) - end - - it 'still takes a Hash in a list with an ordinary key' do - expect(described_class.stringify_query(list: [{ 'a' => '1' }])).to eq('list' => [{ 'a' => '1' }]) - end - - it 'still takes a key that is a space' do - expect(described_class.stringify_query(condition: { ' ' => '1' })).to eq('condition' => { ' ' => '1' }) - end + # Faraday would send the request, credentials and all, to that host. + it 'refuses an absolute URL' do + expect { described_class.relative_path('https://other.example/collect') } + .to raise_error(ArgumentError, /this one is an absolute URL: pass the path alone/) end - # Read off the URL Faraday built, in the order it was written: WebMock - # sorts a query before it compares one, and the order is the point. See - # the QueryEncoder specs for why this is the order Rails needs. - it 'writes the query with the encoder that keeps a list of Hashes apart' do - sent = nil - recorder = Class.new(Faraday::Middleware) do - define_method(:on_request) { |env| sent = URI.decode_www_form(env.url.query).map(&:first) } - end - stub_request(:get, "#{url}/search").with(query: hash_including({})).to_return(json_response([])) - - unit_transport(middleware: ->(builder) { builder.use(recorder) }).get( - 'api/v1/groups/search', - operation: 'test', - query: { condition: { conditions: [{ name: 'a', operator: 'is', value: 1 }, { operator: 'AND', conditions: [{ name: 'b', operator: 'is', value: 2 }] }] } } - ) - - expect(sent.drop(3).first(2)).to eq(['condition[conditions][][operator]', 'condition[conditions][][conditions][][name]']) + it 'makes no request for one' do + expect { unit_transport.get('https://other.example/collect', operation: 'test') }.to raise_error(ArgumentError) + expect(a_request(:any, //)).not_to have_been_made end end @@ -588,165 +154,33 @@ def handed_to_the_adapter(**options) expect(described_class.redact_path('api/v1/tickets/1')).to eq('api/v1/tickets/1') end - it 'blanks the value of a parameter named like a credential' do - expect(described_class.redact_path('api/v1/x?token=s3cret')).to eq('api/v1/x?token=[REDACTED]') + it 'drops a query string, which may carry a token' do + expect(described_class.redact_path('api/v1/x?page=2&token=s3cret')).to eq('api/v1/x') end - it 'keeps every other parameter as it was written' do - expect(described_class.redact_path('api/v1/x?page=2&password=s3cret&q=a%20b')).to eq('api/v1/x?page=2&password=[REDACTED]&q=a%20b') + it 'drops a fragment' do + expect(described_class.redact_path('api/v1/x#token=s3cret')).to eq('api/v1/x') end - it 'reads a name that was percent-encoded' do - expect(described_class.redact_path('api/v1/x?user%5Bpassword%5D=s3cret')).to eq('api/v1/x?user%5Bpassword%5D=[REDACTED]') - end - - it 'blanks a value whose name cannot be read' do - expect(described_class.redact_path('api/v1/x?%zz=s3cret')).to eq('api/v1/x?%zz=[REDACTED]') - end + context 'when a raw request is written with a fragment' do + let(:log) { StringIO.new } - it 'keeps a parameter with no value' do - expect(described_class.redact_path('api/v1/x?expand&token=s3cret')).to eq('api/v1/x?expand&token=[REDACTED]') - end - - it 'blanks a value that holds a = of its own' do - expect(described_class.redact_path('api/v1/x?token=a=b')).to eq('api/v1/x?token=[REDACTED]') - end - - # Rack 2 ends a parameter at a `;` as it does at an `&`, and Zammad ran - # on it up to 7.0. There `?page=2;token=s3cret` carries a token, and - # split at `&` alone it was the tail of a value named `page`. - context 'with parameters separated by a semicolon' do - it 'blanks the value of one named like a credential' do - expect(described_class.redact_path('api/v1/x?page=2;token=s3cret')).to eq('api/v1/x?page=2;token=[REDACTED]') - end - - it 'keeps the parameters around it as they were written' do - expect(described_class.redact_path('api/v1/x?page=2;token=s3cret;q=a%20b&locale=de')).to eq('api/v1/x?page=2;token=[REDACTED];q=a%20b&locale=de') - end - - it 'reads the name behind a parameter with no value' do - expect(described_class.redact_path('api/v1/x?expand;page=2;password=s3cret')).to eq('api/v1/x?expand;page=2;password=[REDACTED]') - end - - it 'reads a name behind the space Rack skips after a separator' do - expect(described_class.redact_path('api/v1/x?page=2; token=s3cret')).to eq('api/v1/x?page=2; token=[REDACTED]') - end + before { stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/x").to_return(json_response({}, status: 404)) } - it 'blanks a value whose name cannot be read' do - expect(described_class.redact_path('api/v1/x?page=2;%zz=s3cret')).to eq('api/v1/x?page=2;%zz=[REDACTED]') - end - - # Rack 3 reads a `;` as part of the value, and so does every Zammad - # since 7.1. A credential is blanked to the next `&`, so that neither - # reading leaves the rest of it standing. - it 'blanks a credential that holds one to the end of its value' do - expect(described_class.redact_path('api/v1/x?token=s3;cret&page=2')).to eq('api/v1/x?token=[REDACTED]&page=2') - end - - it 'leaves a query without a credential as it was written' do - expect(described_class.redact_path('api/v1/x?page=2;q=a;b&c;')).to eq('api/v1/x?page=2;q=a;b&c;') - end - end - - # No part of the request, and printed with the path all the same. With - # no `?` before it, it was not read as a query, whatever it was named. - context 'with a fragment' do - it 'blanks one written straight after the path' do - expect(described_class.redact_path('api/v1/x#token=s3cret')).to eq('api/v1/x#[REDACTED]') - end - - it 'blanks one that names nothing' do - expect(described_class.redact_path('api/v1/x#s3cret')).to eq('api/v1/x#[REDACTED]') - end - - it 'blanks one after a query, which is still redacted by name' do - expect(described_class.redact_path('api/v1/x?page=2&token=abc#access_token=s3cret')).to eq('api/v1/x?page=2&token=[REDACTED]#[REDACTED]') - end - - it 'does not print one as the tail of the value before it' do - expect(described_class.redact_path('api/v1/x?page=2#s3cret')).to eq('api/v1/x?page=2#[REDACTED]') - end - - it 'reads a ? after the # as part of it' do - expect(described_class.redact_path('api/v1/x#a?page=2')).to eq('api/v1/x#[REDACTED]') - end - - context 'when a raw request is written with one' do - let(:log) { StringIO.new } - - before { stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/x").to_return(json_response({}, status: 404)) } - - it 'keeps it out of the error the request raises' do - expect { unit_client.get('api/v1/x#token=s3cret') } - .to raise_error(ZammadAPI::NotFoundError) { |error| - expect(error.message).not_to include('s3cret') - expect(error.operation).to eq('GET api/v1/x#[REDACTED]') - } - end - - it 'keeps it out of the log' do - expect { unit_client(logger: Logger.new(log)).get('api/v1/x#token=s3cret') }.to raise_error(ZammadAPI::NotFoundError) - - expect(log.string).to include('Zammad API request: GET api/v1/x#[REDACTED]') - expect(log.string).not_to include('s3cret') - end - end - end - end - - # The question the test kit asks, so that it sends again what the wire - # sends again. - describe '.retried?' do - let(:config) { ZammadAPI::Config.new(**unit_config(retries: 2, timeout: 60)) } - - def response(status, headers = {}) - ZammadAPI::Response.new(status: status, headers: headers, body: nil, raw_body: '', json: false) - end - - described_class::RETRIABLE_STATUSES.each do |status| - it "is true for a GET answered #{status}" do - expect(described_class.retried?(config, :get, response(status))).to be(true) - end - end - - [200, 404, 422].each do |status| - it "is false for a GET answered #{status}" do - expect(described_class.retried?(config, :get, response(status))).to be(false) - end - end - - %i[post put delete].each do |verb| - it "is false for a #{verb.to_s.upcase}, which is never sent twice" do - expect(described_class.retried?(config, verb, response(503))).to be(false) + it 'keeps it out of the error the request raises' do + expect { unit_client.get('api/v1/x#token=s3cret') } + .to raise_error(ZammadAPI::NotFoundError) { |error| + expect(error.message).not_to include('s3cret') + expect(error.operation).to eq('GET api/v1/x') + } end - end - - it 'is false where Retry-After asks for longer than the timeout' do - expect(described_class.retried?(config, :get, response(429, 'retry-after' => '61'))).to be(false) - end - it 'is true where Retry-After asks for no longer than the timeout' do - expect(described_class.retried?(config, :get, response(429, 'retry-after' => '60'))).to be(true) - end + it 'keeps it out of the log' do + expect { unit_client(logger: Logger.new(log)).get('api/v1/x#token=s3cret') }.to raise_error(ZammadAPI::NotFoundError) - it 'reads a Retry-After that is a date' do - expect(described_class.retried?(config, :get, response(503, 'retry-after' => (Time.now + 3600).utc.strftime('%a, %d %b %Y %H:%M:%S GMT')))).to be(false) - end - - it 'reads a RateLimit-Reset the same way' do - expect(described_class.retried?(config, :get, response(429, 'ratelimit-reset' => '3600'))).to be(false) - end - - # What makes this the transport's own answer and not a second reading of - # the same rules: a stack that was answered this way made one request. - it 'agrees with what a request does' do - stub_request(:get, url).to_return({ status: 429, headers: { 'Retry-After' => '3600' } }, json_response([])) - transport = unit_transport(retries: 2, retry_interval: 0.01, timeout: 2) - - expect { transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::RateLimitError) do |error| - expect(described_class.retried?(transport.config, :get, error.response)).to be(false) + expect(log.string).to include("Zammad API request: GET api/v1/x\n") + expect(log.string).not_to include('s3cret') end - expect(a_request(:get, url)).to have_been_made.once end end @@ -798,73 +232,20 @@ def response(status, headers = {}) expect(described_class.escape_path_segment('ä')).to eq('%C3%A4') end - # The bytes of the id as it was held went into the path: `%E4` for an - # ä in ISO-8859-1, which is no UTF-8 and names no record. In UTF-16 the - # pattern raised Encoding::CompatibilityError. - %w[ISO-8859-1 Windows-1252 UTF-16LE].each do |encoding| - it "encodes the bytes of the UTF-8 text for an id given in #{encoding}" do - expect(described_class.escape_path_segment('ä/1'.encode(encoding))).to eq('%C3%A4%2F1') - end - end - - it 'raises for a dot segment given in UTF-16' do - expect { described_class.escape_path_segment('..'.encode('UTF-16LE')) }.to raise_error(ArgumentError, /points at another endpoint/) - end - - it 'raises for an id that cannot be converted to UTF-8, without quoting it' do - broken = "abc\x81".dup.force_encoding('Windows-1252') - - expect { described_class.escape_path_segment(broken) } - .to raise_error(ArgumentError, /\Aa record id was given as Windows-1252 text that cannot be converted to UTF-8/) - end - - it 'raises for an id with nothing to send' do - expect { described_class.escape_path_segment('') }.to raise_error(ArgumentError, /record id is required/) - end - - it 'raises for a parent dot segment, which the unreserved set would carry through' do - expect { described_class.escape_path_segment('..') }.to raise_error(ArgumentError, /points at another endpoint/) - end - - it 'raises for a current-directory dot segment' do - expect { described_class.escape_path_segment('.') }.to raise_error(ArgumentError, /points at another endpoint/) - end - - it 'leaves an id that merely starts with dots alone' do - expect(described_class.escape_path_segment('..1')).to eq('..1') - end - - it 'encodes an already-encoded dot segment rather than passing it on' do - expect(described_class.escape_path_segment('%2e%2e')).to eq('%252e%252e') + it 'encodes a percent sign rather than passing an encoded id on' do + expect(described_class.escape_path_segment('%2F')).to eq('%252F') end it 'takes a Symbol, for a member that is named rather than numbered' do expect(described_class.escape_path_segment(:me)).to eq('me') end - # `to_s` answers for every object, so a record where its id belongs was - # pasted into the path as it inspects and answered with a 404. - it 'raises for a record where its id belongs' do - record = ZammadAPI::Resources::Group.from_response(unit_transport, { id: 1, name: 'Users' }) - - expect { described_class.escape_path_segment(record) } - .to raise_error(ArgumentError, /record id is an Integer or a String, and this one is ZammadAPI::Resources::Group/) - end - - it 'does not quote what it refuses, which for a record is its attributes' do - record = ZammadAPI::Resources::Group.from_response(unit_transport, { id: 1, name: 'Users' }) - - expect { described_class.escape_path_segment(record) }.to raise_error(ArgumentError) { |error| expect(error.message).not_to include('Users') } - end - - [[1], { id: 1 }, 1.0, true, Object.new].each do |value| - it "raises for #{value.class}, which only prints as something" do - expect { described_class.escape_path_segment(value) }.to raise_error(ArgumentError, /this one is #{value.class}/) - end + it 'raises for an id with nothing to send' do + expect { described_class.escape_path_segment('') }.to raise_error(ArgumentError, 'a record id is required') end - it 'still says that an id is missing for nil' do - expect { described_class.escape_path_segment(nil) }.to raise_error(ArgumentError, /record id is required/) + it 'raises for nil' do + expect { described_class.escape_path_segment(nil) }.to raise_error(ArgumentError, 'a record id is required') end end @@ -885,310 +266,78 @@ def response(status, headers = {}) expect(stub).to have_been_requested end - # The generator has no spelling for `ActionController::Parameters` and - # writes its `to_s`, so the body was one JSON string holding a Ruby - # inspect of the parameters. - context 'with a body that converts to a Hash and is not one' do + context 'with values that are not JSON types' do before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } - it 'sends it as the JSON object it converts to' do - unit_transport.post('api/v1/groups', operation: 'test', body: StrongParameters.new(name: 'Support', preferences: StrongParameters.new(locale: 'de'))) - - expect(a_request(:post, url).with(body: '{"name":"Support","preferences":{"locale":"de"}}')).to have_been_made - end - - it 'sends one that a Hash or an Array holds the same way' do - unit_transport.post('api/v1/groups', operation: 'test', body: { groups: [StrongParameters.new(name: 'Support')] }) - - expect(a_request(:post, url).with(body: '{"groups":[{"name":"Support"}]}')).to have_been_made - end - - it 'sends nothing where it refuses to convert' do - expect { unit_transport.post('api/v1/groups', operation: 'test', body: StrongParameters.new({ name: 'Support' }, permitted: false)) } - .to raise_error(StrongParameters::Unfiltered) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - end - - # The generator writes an object JSON has no type for as its `to_s`, so - # `role_ids: Set[1, 2]` went out as the String "Set[1, 2]" where the - # list belongs, and nothing raised. - context 'with a value JSON has no type for' do - let(:url) { "#{ClientHelper::BASE_URL}api/v1/users" } - - before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } - - { 'a Set' => Set[1, 2], 'a Range' => (1..3), 'a Struct' => Struct.new(:id).new(1), 'a Rational' => Rational(1, 2), 'any other object' => Object.new }.each do |kind, value| - it "raises a ZammadAPI::Error for #{kind}, which only prints as something" do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: { role_ids: value }) } - .to raise_error(ZammadAPI::Error, /request body cannot be encoded as JSON \(its key role_ids was given as #{Regexp.escape(value.class.to_s)}, which is no JSON type/) - end - end - - it 'raises for one further in' do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: { users: [{ role_ids: Set[1] }] }) } - .to raise_error(ZammadAPI::Error, /its key role_ids was given as Set/) - end - - it 'raises for one that is the whole body' do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: Set[1]) } - .to raise_error(ZammadAPI::Error, /\(it was given as Set/) - end - - it 'says what to pass in its place' do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: { role_ids: Set[1, 2] }) } - .to raise_error(ZammadAPI::Error, /pass a Set or a Range as its to_a/) - end - - it 'does not quote what it refuses' do - holder = Class.new { def initialize = @password = 'object-s3cret' }.new - - expect { unit_transport.post('api/v1/users', operation: 'save object', body: { user: holder }) } - .to raise_error(ZammadAPI::Error) { |error| expect(error.message).not_to include('object-s3cret') } - end - - it 'makes no request' do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: { role_ids: Set[1, 2] }) }.to raise_error(ZammadAPI::Error) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'is raised by a record save carrying such a value' do - user = unit_client.users.new(login: 'jane', role_ids: Set[1, 2]) - expect { user.save }.to raise_error(ZammadAPI::Error, /its key role_ids was given as Set/) - end - - it 'sends a Symbol as text, as the generator writes it' do - unit_transport.post('api/v1/users', operation: 'test', body: { state: :open, 1 => nil }) + it 'sends a Symbol as text' do + unit_transport.post('api/v1/groups', operation: 'test', body: { state: :open, 1 => nil }) expect(a_request(:post, url).with(body: '{"state":"open","1":null}')).to have_been_made end # Zammad reads a time or a date attribute from the text either prints. it 'sends a Time and a Date as they print' do - unit_transport.post('api/v1/users', operation: 'test', body: { pending_time: Time.utc(2026, 1, 2, 3, 4, 5), due: Date.new(2026, 1, 2) }) + unit_transport.post('api/v1/groups', operation: 'test', body: { pending_time: Time.utc(2026, 1, 2, 3, 4, 5), due: Date.new(2026, 1, 2) }) expect(a_request(:post, url).with(body: '{"pending_time":"2026-01-02 03:04:05 UTC","due":"2026-01-02"}')).to have_been_made end - # A member called `method` is in the way of asking the object where - # its `to_json` comes from, and is not asked. it 'leaves an object with a to_json of its own to write itself' do - # rubocop:disable-next Lint/DataDefineOverride -- the member in the way is the point - point = Data.define(:method, :id) { def to_json(*) = to_h.to_json(*) }.new('get', 1) - unit_transport.post('api/v1/users', operation: 'test', body: { point: point, points: [point] }) + point = Data.define(:x, :y) { def to_json(*) = to_h.to_json(*) }.new(1, 2) + unit_transport.post('api/v1/groups', operation: 'test', body: { point: point, points: [point] }) - expect(a_request(:post, url).with(body: '{"point":{"method":"get","id":1},"points":[{"method":"get","id":1}]}')).to have_been_made + expect(a_request(:post, url).with(body: '{"point":{"x":1,"y":2},"points":[{"x":1,"y":2}]}')).to have_been_made end it 'sends a record of this gem as its attributes' do group = ZammadAPI::Resources::Group.from_response(unit_transport, { id: 1, name: 'Users' }) - unit_transport.post('api/v1/users', operation: 'test', body: { group: group }) + unit_transport.post('api/v1/groups', operation: 'test', body: { group: group }) expect(a_request(:post, url).with(body: '{"group":{"id":1,"name":"Users"}}')).to have_been_made end end - # ActiveSupport gives every object an `as_json` and builds `to_json` on - # it, which is what 1.x sent a body with. `JSON.generate` does not ask - # it, so in a Rails app a Set was the list under 1.x and its `to_s` - # here, and `2.days` was "172800". Stood in for by objects that define - # the method, as ActiveSupport is not loaded here. - context 'with an object that says what it is as JSON' do - let(:as_json_class) { Struct.new(:described) { def as_json(*) = described } } - - before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } - - it 'sends what its as_json returns' do - unit_transport.post('api/v1/groups', operation: 'test', body: { ids: as_json_class.new([1, 2]), ttl: as_json_class.new(172_800) }) - - expect(a_request(:post, url).with(body: '{"ids":[1,2],"ttl":172800}')).to have_been_made - end - - it 'sends one that is the whole body the same way' do - unit_transport.post('api/v1/groups', operation: 'test', body: as_json_class.new({ 'name' => 'Support' })) - - expect(a_request(:post, url).with(body: '{"name":"Support"}')).to have_been_made - end - - it 'asks what its as_json returns in turn' do - unit_transport.post('api/v1/groups', operation: 'test', body: { group: as_json_class.new({ 'ids' => as_json_class.new([1]) }) }) - - expect(a_request(:post, url).with(body: '{"group":{"ids":[1]}}')).to have_been_made - end - - it 'raises where its as_json is no JSON type either' do - number = as_json_class.new(Rational(1, 2)) - - expect { unit_transport.post('api/v1/groups', operation: 'save object', body: { weight: number }) } - .to raise_error(ZammadAPI::Error, /its key weight was given as #{Regexp.escape(number.class.to_s)}, which is no JSON type/) - end - - it 'prefers the to_json an object has of its own' do - both = Class.new do - def as_json(*) = { 'from' => 'as_json' } - def to_json(*) = '{"from":"to_json"}' - end - - unit_transport.post('api/v1/groups', operation: 'test', body: { value: both.new }) - - expect(a_request(:post, url).with(body: '{"value":{"from":"to_json"}}')).to have_been_made - end - end - - # The generator goes by the tag of a String. json 3 refuses a binary one - # with a byte outside ASCII and json 2 wrote one that was valid UTF-8, - # so text read with File.binread or off a socket was sent or refused by - # which of the two a bundle had resolved to. - context 'with text in the body that is tagged as binary' do - before { stub_request(:post, url).to_return(json_response({})) } - - it 'sends it as the UTF-8 text its bytes are' do - unit_transport.post('api/v1/groups', operation: 'test', body: { name: 'Größe'.b }) - - expect(a_request(:post, url).with(body: '{"name":"Größe"}')).to have_been_made - end - - it 'sends it inside a Hash and an Array as well' do - unit_transport.post('api/v1/groups', operation: 'test', body: { article: { subject: 'Grüße'.b, to: ['jürgen@example.com'.b] } }) - - expect(a_request(:post, url).with(body: '{"article":{"subject":"Grüße","to":["jürgen@example.com"]}}')).to have_been_made - end - - it 'encodes it without a warning from the generator' do - expect { described_class.encode_body({ name: 'Größe'.b }, operation: 'test') }.not_to output.to_stderr - end - - it 'leaves the String it was given tagged as it was' do - name = 'Größe'.b - described_class.encode_body({ name: name }, operation: 'test') - - expect(name.encoding).to eq(Encoding::BINARY) - end - - it 'hands on a String that needs no new tag as the object it is' do - ascii = 'plain'.b - utf8 = 'Größe' - - expect(described_class.json_value([ascii, utf8], nil)).to match([be(ascii), be(utf8)]) - end - - it 'still refuses bytes that are no text, with the advice for binary data' do - expect { described_class.encode_body({ data: "\x89PNG\r\n\x1A\n\xFF".b }, operation: 'test') } - .to raise_error(ZammadAPI::Error, /Base64-encode binary data/) - end - - it 'saves a record whose attribute is such text' do - stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 7, name: 'Größe' })) - unit_client.groups.create(name: 'Größe'.b) - - expect(a_request(:post, url).with(query: hash_including({}), body: '{"name":"Größe"}')).to have_been_made - end - end - - # Faraday's JSON middleware raised JSON::GeneratorError from inside the - # stack and nothing mapped it, so it went past the rescue of - # ZammadAPI::Error every caller is told to write. + # Faraday's JSON middleware would raise JSON::GeneratorError from inside + # the stack, past the rescue of ZammadAPI::Error every caller is told to + # write. context 'with a body that cannot be encoded as JSON' do let(:binary) { { data: "\xFF\xD8\xFF".b } } it 'raises a ZammadAPI::Error for bytes that are not text' do expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary) } - .to raise_error(ZammadAPI::Error, /Can't save object: the request body cannot be encoded as JSON/) - end - - it 'raises a ZammadAPI::Error for a Float that JSON has no spelling for, naming its key' do - expect { unit_transport.put('api/v1/groups/1', operation: 'save object', body: { weight: Float::NAN }) } - .to raise_error(ZammadAPI::Error, /cannot be encoded as JSON \(its key weight was given as NaN, which JSON has no number for\)/) - end - - it 'says what to do about binary data' do - expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary) } - .to raise_error(ZammadAPI::Error, /Base64-encode binary data/) - end - - it 'names the resource it was sending' do - expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary, resource_class: ZammadAPI::Resources::Group) } - .to raise_error(ZammadAPI::Error, /save object \(ZammadAPI::Resources::Group\)/) - end - - it 'makes no request' do - expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary) }.to raise_error(ZammadAPI::Error) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'leaves no log line claiming a request that was never made' do - log = StringIO.new - expect { unit_transport(logger: Logger.new(log)).post('api/v1/groups', operation: 'save object', body: binary) } - .to raise_error(ZammadAPI::Error) - expect(log.string).to be_empty - end - - it 'is raised by a record save carrying such a value' do - group = unit_client.groups.new(name: 'Support', weight: Float::INFINITY) - expect { group.save }.to raise_error(ZammadAPI::Error, /its key weight was given as Infinity/) - end - - # The generator quotes what it could not write, in its message or in - # the detailed message a backtrace prints for a cause, so the error - # for a body with a password in it carried the password. - context 'with a secret in the value that cannot be encoded' do - let(:secret) { { login: 'a', password: "hunter2\xFF" } } - - def refusal(body) - unit_transport.post('api/v1/users', operation: 'save object', body: body) - rescue ZammadAPI::Error, ArgumentError => e - e - end - - it 'says nothing of the value' do - expect(refusal(secret).full_message(highlight: false)).not_to include('hunter2') - end - - it 'carries no cause that would' do - expect(refusal(secret)).to be_a(ZammadAPI::Error).and have_attributes(cause: nil) - end - - it 'still says what a body has to be' do - expect(refusal(secret).message).to include('cannot be encoded as JSON. Every value has to be a JSON type') - end - end - end - - # One key twice in JSON. json 3 raises for it and quotes the whole Hash, - # password and all, and json 2 wrote both and left the choice to Rails. - context 'with a body that names one key twice' do - let(:body) { { login: 'a', password: 'hunter2', 'login' => 'b' } } - - it 'raises an ArgumentError naming both spellings' do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: body) } - .to raise_error(ArgumentError, /body key login was given twice, as :login and as "login"/) + .to raise_error(ZammadAPI::Error, /\ACan't save object: the request body cannot be encoded as JSON/) end - it 'says nothing of the values beside it' do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: body) } - .to(raise_error { expect(it.full_message(highlight: false)).not_to include('hunter2') }) + it 'raises a ZammadAPI::Error for a Float that JSON has no spelling for' do + expect { unit_transport.put('api/v1/groups/1', operation: 'save object', body: { weight: Float::NAN }) } + .to raise_error(ZammadAPI::Error, /\ACan't save object: the request body cannot be encoded as JSON/) end - it 'raises for one further in, with the key it sits under' do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: { users: [{ user: body }] }) } - .to raise_error(ArgumentError, /body key user\[login\] was given twice/) + it 'carries no cause, whose report would quote the value' do + expect { unit_transport.post('api/v1/groups', operation: 'save object', body: { password: "s3cret\xFF" }) } + .to raise_error(ZammadAPI::Error) { |error| expect(error.full_message(highlight: false)).not_to include('s3cret') } end - it 'raises for two keys that are only written alike' do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: { 1 => 'a', '1' => 'b' }) } - .to raise_error(ArgumentError, /body key 1 was given twice, as 1 and as "1"/) + it 'names the resource it was sending' do + expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary, resource_class: ZammadAPI::Resources::Group) } + .to raise_error(ZammadAPI::Error, /save object \(ZammadAPI::Resources::Group\)/) end it 'makes no request' do - expect { unit_transport.post('api/v1/users', operation: 'save object', body: body) }.to raise_error(ArgumentError) + expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary) }.to raise_error(ZammadAPI::Error) expect(a_request(:any, /zammad\.test/)).not_to have_been_made end - it 'sends a body whose keys differ as it did' do - stub_request(:post, "#{ClientHelper::BASE_URL}api/v1/users").to_return(json_response({ id: 1 }, status: 201)) - unit_transport.post('api/v1/users', operation: 'save object', body: { login: 'a', 'email' => 'a@b.c', 7 => [{ x: nil }] }) + it 'leaves no log line claiming a request that was never made' do + log = StringIO.new + expect { unit_transport(logger: Logger.new(log)).post('api/v1/groups', operation: 'save object', body: binary) } + .to raise_error(ZammadAPI::Error) + expect(log.string).to be_empty + end - expect(a_request(:post, "#{ClientHelper::BASE_URL}api/v1/users").with(body: '{"login":"a","email":"a@b.c","7":[{"x":null}]}')).to have_been_made + it 'is raised by a record save carrying such a value' do + group = unit_client.groups.new(name: 'Support', weight: Float::INFINITY) + expect { group.save }.to raise_error(ZammadAPI::Error, /cannot be encoded as JSON/) end end end @@ -1264,222 +413,14 @@ def refusal(body) .to raise_error(ZammadAPI::TimeoutError, %r{Can't find object: request to api/v1/groups timed out}) end - it 'keeps a credential in a query written into the path out of the message' do + it 'keeps a query string written into the path out of the message' do stub_request(:get, url).with(query: hash_including({})).to_raise(Net::ReadTimeout) expect { unit_transport.get('api/v1/groups?token=path-s3cret', operation: 'find object') } - .to raise_error(ZammadAPI::TimeoutError, %r{request to api/v1/groups\?token=\[REDACTED\] timed out}) - end - - # Net::HTTP reads a body framed by Content-Length until the count is - # reached or the connection ends, and takes the second for the first. - # The bytes that had arrived came back as the response. - context 'when the connection closes before the body has arrived' do - def cut_off(headers = {}, status: 200, body: '0123456789') - stub_request(:get, url).to_return(status: status, body: body, headers: { 'Content-Length' => '1000' }.merge(headers)) - end - - it 'raises a ConnectionError for a body shorter than its Content-Length' do - cut_off({ 'Content-Type' => 'image/png' }) - - expect { unit_transport.get('api/v1/groups', operation: 'download attachment') } - .to raise_error(ZammadAPI::ConnectionError, %r{\ACan't download attachment: the response from http://zammad\.test/ ended 990 bytes short of the 1000}) - end - - # The one ConnectionError raised for a request that was answered, and - # the status is what tells a caller its write was applied. - it 'raises it as an IncompleteResponseError that carries the response' do - cut_off({ 'Content-Type' => 'image/png' }) - - expect { unit_transport.get('api/v1/groups', operation: 'download attachment') } - .to raise_error(ZammadAPI::IncompleteResponseError) { |error| - expect(error.response.status).to eq(200) - expect(error.response.raw_body).to eq('0123456789') - } - end - - it 'raises for a JSON body that is short, and still parses' do - cut_off({ 'Content-Type' => 'application/json' }, body: '[]') - - expect { unit_transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::ConnectionError, /998 bytes short/) - end - - it 'raises for a body of which nothing arrived' do - cut_off(body: '') - - expect { unit_transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::ConnectionError, /1000 bytes short/) - end - - it 'counts the bytes, not the characters' do - stub_request(:get, url).to_return(status: 200, body: 'ää', headers: { 'Content-Length' => '4', 'Content-Type' => 'text/plain; charset=utf-8' }) - - expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body.bytesize).to eq(4) - end - - it 'returns a body as long as its Content-Length' do - stub_request(:get, url).to_return(status: 200, body: '0123456789', headers: { 'Content-Length' => '10' }) - - expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') - end - - it 'returns a body that names no Content-Length' do - stub_request(:get, url).to_return(status: 200, body: '0123456789') - - expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') - end - - # The bytes in hand may be the decoded ones, beside a count of the - # encoded ones, and a chunked body is not framed by the count. - it 'does not judge a body under a Content-Encoding or a Transfer-Encoding' do - [{ 'Content-Encoding' => 'br' }, { 'Transfer-Encoding' => 'chunked' }].each do |header| - cut_off(header) - - expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') - end - end - - it 'does not judge a Content-Length that is not one figure' do - ['1000, 1000', 'many', ''].each do |announced| - cut_off({ 'Content-Length' => announced }) - - expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') - end - end - - # faraday-gzip writes the length of what it inflated as an Integer, and - # a regexp asked of one raised TypeError for every 2xx. - context 'with a Content-Length that a middleware left as an Integer' do - def counting(length) - lambda { |builder| - builder.use(Class.new(Faraday::Middleware) do - define_method(:on_complete) { |env| env.response_headers['Content-Length'] = length } - end) - } - end - - before { stub_request(:get, url).to_return(status: 200, body: '0123456789') } - - it 'returns a body as long as it' do - response = unit_transport(middleware: counting(10)).get('api/v1/groups', operation: 'test') - - expect(response.raw_body).to eq('0123456789') - end - - it 'serves the header as text' do - response = unit_transport(middleware: counting(10)).get('api/v1/groups', operation: 'test') - - expect(response.headers['content-length']).to eq('10') - end - - it 'still raises for a body that is shorter' do - expect { unit_transport(middleware: counting(1000)).get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::ConnectionError, /990 bytes short of the 1000/) - end - end - - # Asked of the response the retry middleware had already returned, so - # this was the one failure of a connection that a read was not sent - # again for: the drop a moment earlier, as ECONNRESET, was. - context 'with retries to spend' do - let(:transport) { unit_transport(retries: 2, retry_interval: 0.01) } - let(:short) { { status: 200, body: '0123', headers: { 'Content-Length' => '10' } } } - let(:whole) { { status: 200, body: '0123456789', headers: { 'Content-Length' => '10' } } } - - it 'sends a GET again, and returns the body that arrived whole' do - stub_request(:get, url).to_return(short, whole) - - expect(transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') - expect(a_request(:get, url)).to have_been_made.twice - end - - it 'sends it as often as a GET that met ECONNRESET' do - stub_request(:get, url).to_return(short, short, whole) - - expect(transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') - expect(a_request(:get, url)).to have_been_made.times(3) - end - - it 'raises once the retries are spent, with the response that came last' do - stub_request(:get, url).to_return(short, short, short.merge(body: '012345')) - - expect { transport.get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::IncompleteResponseError, /ended 4 bytes short of the 10/) { expect(it.response.raw_body).to eq('012345') } - expect(a_request(:get, url)).to have_been_made.times(3) - end - - # Zammad answered, so the write was applied, and sending it again - # would apply it again. - %i[post put delete].each do |verb| - it "does not send a #{verb.to_s.upcase} again" do - stub_request(verb, url).to_return(short, whole) - - expect { transport.public_send(verb, 'api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::IncompleteResponseError) - expect(a_request(verb, url)).to have_been_made.once - end - end - - it 'does not send a GET again for a body that is whole' do - stub_request(:get, url).to_return(whole) - transport.get('api/v1/groups', operation: 'test') - - expect(a_request(:get, url)).to have_been_made.once - end - - it 'asks the length of the body as the middleware callable left it' do - stub_request(:get, url).to_return(status: 200, body: '0123456789') - padded = lambda { |builder| - builder.use(Class.new(Faraday::Middleware) do - define_method(:on_complete) { |env| env.response_headers['Content-Length'] = 1000 } - end) - } - - expect { unit_transport(retries: 1, retry_interval: 0.01, middleware: padded).get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::IncompleteResponseError, /990 bytes short/) - expect(a_request(:get, url)).to have_been_made.twice - end - - it 'logs the response it raises for, once' do - log = StringIO.new - stub_request(:get, url).to_return(short) - - expect { unit_transport(retries: 2, retry_interval: 0.01, logger: Logger.new(log)).get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::IncompleteResponseError) - expect(log.string.scan('Zammad API response: GET api/v1/groups -> 200').size).to eq(1) - end - end - - it 'does not judge a 204, which has no body whatever is announced beside it' do - stub_request(:delete, url).to_return(status: 204, body: '', headers: { 'Content-Length' => '5' }) - - expect(unit_transport.delete('api/v1/groups', operation: 'test').status).to eq(204) - end - - it 'leaves a body that is longer than announced alone' do - stub_request(:get, url).to_return(status: 200, body: '0123456789', headers: { 'Content-Length' => '4' }) - - expect(unit_transport.get('api/v1/groups', operation: 'test').raw_body).to eq('0123456789') - end - - # The status is what such a response says, and the body is read for - # the message only. - it 'still raises the error its status names for one that is not a 2xx' do - cut_off({ 'Content-Type' => 'application/json' }, status: 404, body: '{"error":') - - expect { unit_transport.get('api/v1/groups', operation: 'find object') }.to raise_error(ZammadAPI::NotFoundError) - end - - it 'logs the response it then refuses' do - log = StringIO.new - cut_off - - expect { unit_transport(logger: Logger.new(log)).get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::ConnectionError) - expect(log.string).to include('Zammad API response: GET api/v1/groups -> 200') - end + .to raise_error(ZammadAPI::TimeoutError, %r{request to api/v1/groups timed out}) { |error| expect(error.message).not_to include('s3cret') } end # Net::HTTP raises Net::OpenTimeout for it, and the default adapter wraps - # that into Faraday::ConnectionFailed with every other failure to connect, - # so it was reported as an unreachable host and skipped the rescue that is - # documented to catch it. + # that into Faraday::ConnectionFailed with every other failure to connect. context 'when the connection is not established within open_timeout' do before { stub_request(:get, url).to_raise(Net::OpenTimeout.new('execution expired')) } @@ -1586,9 +527,8 @@ def raising(error) expect(response.status).to eq(200) end - # The retry middleware sleeps for whatever Retry-After says, and its own - # ceiling defaults to none: this held the calling thread for an hour per - # retry before raising the error it could have raised at once. + # The retry middleware sleeps for whatever Retry-After says, up to a + # ceiling that is set to the timeout. context 'when the server asks for a longer wait than the timeout' do let(:transport) { unit_transport(retries: 2, retry_interval: 0.01, timeout: 2) } @@ -1643,8 +583,8 @@ def raising(error) expect(a_request(:post, url)).to have_been_made.once end - # A ticket update carrying an article creates that article on every - # delivery, so repeating it sent the article - and its e-mail - twice. + # A ticket update carrying an article creates that article, and sends its + # e-mail, on every delivery. it 'does not retry PUT, which Zammad does not always handle idempotently' do stub_request(:put, "#{url}/1").to_return({ status: 504 }, json_response({ id: 1 })) expect { unit_transport(retries: 2, retry_interval: 0.01).put('api/v1/groups/1', operation: 'test', body: { a: 1 }) } @@ -1659,8 +599,8 @@ def raising(error) expect(a_request(:put, "#{url}/1")).to have_been_made.once end - # Repeated after a lost answer, the second DELETE met a 404 and reported a - # record that had just been deleted as one that could not be found. + # Repeated after a lost answer, a DELETE meets a 404 for the record it has + # just deleted. it 'does not retry DELETE, which would answer a lost success with a 404' do stub_request(:delete, "#{url}/1").to_raise(Net::ReadTimeout).then.to_return(json_response({ error: 'gone' }, status: 404)) expect { unit_transport(retries: 2, retry_interval: 0.01).delete('api/v1/groups/1', operation: 'test') } @@ -1676,10 +616,8 @@ def raising(error) end end - # Most adapters wrap a socket failure into Faraday::ConnectionFailed, which - # was retried; the same failure raw was not, so how often a request was - # retried depended on which adapter the caller picked - through an option - # this gem offers. + # Most adapters wrap a socket failure into Faraday::ConnectionFailed. One + # that does not is retried as often. describe 'retries through an adapter that does not wrap socket errors' do before { BareSocketAdapter.attempts = [] } @@ -1749,156 +687,6 @@ def bare_socket_transport(**overrides) expect(seen).to eq(200) end - # `c.response :json` is a reasonable thing to put through a documented - # seam, and Faraday then hands over a Hash rather than the bytes. `to_s` - # turned that into a Ruby inspect string, which JSON.parse refused, so - # every record built from the response died in Response#decoded with a - # ParseError naming Zammad for what the caller's own stack had done. - # - # Re-encoding the parsed structure was the other way out, and it is worse: - # `raw_body` is what an attachment download hands back as the file, so a - # re-encoding returns something Zammad never stored. The bytes are gone - # either way, so this names the cause while it is still visible. - context 'with middleware that decodes the body first' do - it 'refuses it when the stack is built, before anything is sent' do - expect { unit_transport(middleware: ->(builder) { builder.response(:json) }) } - .to raise_error(ZammadAPI::ConfigurationError, /decodes the response body before this gem can/) - end - - it 'names the middleware it found' do - expect { unit_transport(middleware: ->(builder) { builder.response(:json) }) } - .to raise_error(ZammadAPI::ConfigurationError, /Faraday::Response::Json/) - end - - it 'says which middleware to drop' do - expect { unit_transport(middleware: ->(builder) { builder.response(:json) }) } - .to raise_error(ZammadAPI::ConfigurationError, /c\.response :json/) - end - - it 'is catchable as the gem error every caller rescues' do - expect { unit_transport(middleware: ->(builder) { builder.response(:json) }) }.to raise_error(ZammadAPI::Error) - end - - # The check used to live in `decode`, which is one request too late: the - # POST went out, Zammad created the record, and only then did a - # "configuration" error come back - so a caller retrying it made a second. - it 'sends nothing before refusing' do - stub = stub_request(:post, url).with(query: hash_including({})) - - expect { unit_client(middleware: ->(builder) { builder.response(:json) }).groups.create(name: 'X') } - .to raise_error(ZammadAPI::ConfigurationError) - expect(stub).not_to have_been_requested - end - end - - # `c.response :raise_error` is in most Faraday stacks people have written - # before, so it is what a caller adds by habit. It sits below the retry - # middleware and raises for a 4xx or 5xx before this gem sees the - # response: a GET answered 503 left as Faraday::ServerError without being - # retried, and a 404 as Faraday::ResourceNotFound rather than the - # NotFoundError that `exists?` and every caller's rescue are written for. - context 'with middleware that raises for an error status first' do - let(:raising) { ->(builder) { builder.response(:raise_error) } } - - it 'refuses it when the stack is built' do - expect { unit_transport(middleware: raising) } - .to raise_error(ZammadAPI::ConfigurationError, /raises a Faraday error for a 4xx or 5xx response before this gem sees it/) - end - - it 'names the middleware it found' do - expect { unit_transport(middleware: raising) } - .to raise_error(ZammadAPI::ConfigurationError, /the configured middleware includes Faraday::Response::RaiseError/) - end - - it 'says which middleware to drop' do - expect { unit_transport(middleware: raising) }.to raise_error(ZammadAPI::ConfigurationError, /drop `c\.response :raise_error`/) - end - - it 'refuses it where it was added by class' do - expect { unit_transport(middleware: ->(builder) { builder.use(Faraday::Response::RaiseError) }) } - .to raise_error(ZammadAPI::ConfigurationError, /Faraday::Response::RaiseError/) - end - - # The stub is for the path `find(1)` asks, and answers with a group. One - # for the index, which this was, is not a request `find` makes, so the - # assertion below held whether or not the GET went out before the - # refusal. - it 'sends nothing before refusing' do - stub = stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) - - expect { unit_client(middleware: raising).groups.find(1) }.to raise_error(ZammadAPI::ConfigurationError) - expect(stub).not_to have_been_requested - end - end - - # A subclass has a name of its own, and only the name was asked. It is how - # a caller adjusts what `raise_error` raises, and what it inherits is the - # handler that raises before this gem sees the response. - context 'with a subclass of a middleware it refuses' do - let(:subclass) { stub_const('QuietRaiseError', Class.new(Faraday::Response::RaiseError)) } - - it 'refuses it for what it inherits' do - expect { unit_transport(middleware: ->(builder) { builder.use(subclass) }) } - .to raise_error(ZammadAPI::ConfigurationError, /raises a Faraday error for a 4xx or 5xx response before this gem sees it/) - end - - it 'names the subclass and the middleware it inherits from' do - expect { unit_transport(middleware: ->(builder) { builder.use(subclass) }) } - .to raise_error(ZammadAPI::ConfigurationError, /includes QuietRaiseError, a subclass of Faraday::Response::RaiseError, which raises/) - end - - # `c.response :raise_error` is not the line that added it. - it 'says to drop the subclass rather than the spelling its parent has' do - expect { unit_transport(middleware: ->(builder) { builder.use(subclass) }) } - .to raise_error(ZammadAPI::ConfigurationError, /it does neither: drop it from the `middleware:` callable\./) - end - - it 'refuses one that was never given a name' do - expect { unit_transport(middleware: ->(builder) { builder.use(Class.new(Faraday::Response::RaiseError)) }) } - .to raise_error(ZammadAPI::ConfigurationError, /includes an anonymous class, a subclass of Faraday::Response::RaiseError,/) - end - - it 'refuses a subclass of the decoding middleware too' do - expect { unit_transport(middleware: ->(builder) { builder.use(Class.new(Faraday::Response::Json)) }) } - .to raise_error(ZammadAPI::ConfigurationError, /decodes the response body before this gem can/) - end - - it 'sends nothing before refusing' do - stub = stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) - - expect { unit_client(middleware: ->(builder) { builder.use(subclass) }).groups.find(1) }.to raise_error(ZammadAPI::ConfigurationError) - expect(stub).not_to have_been_requested - end - end - - # The build-time check knows the two above by name; anything - # else that consumes the body is caught only once a response is in hand. - context 'with a decoder the build-time check does not know by name' do - subject(:transport) do - unit_transport(middleware: lambda { |builder| - builder.use(Class.new(Faraday::Middleware) do - def on_complete(env) = env.body = { id: 1 } - end) - }) - end - - before { stub_request(:get, url).to_return(json_response([{ id: 1 }])) } - - it 'builds, because nothing named is in the stack' do - expect { transport }.not_to raise_error - end - - it 'refuses the response rather than stringifying what it got' do - expect { transport.get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::ConfigurationError, /decoded the response body before this gem could/) - end - - it 'names what it was handed instead of the body' do - expect { transport.get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::ConfigurationError, /Faraday handed over Hash rather than the raw body/) - end - end - it 'leaves a middleware that does not touch the body alone' do stub_request(:get, url).to_return(json_response([{ id: 1, name: 'Users' }])) @@ -1913,354 +701,113 @@ def on_complete(env) = env.body = { id: 1 } expect(transport.instance_variable_get(:@connection).adapter.name).to include('Adapter::Test') end - # The adapter was set after the callable ran, and setting one replaces - # the one that is there. A test that put the test adapter in through - # the callable was on Net::HTTP, with nothing to say so. - context 'with an adapter chosen inside the middleware callable' do - let(:stubs) { Faraday::Adapter::Test::Stubs.new { it.get('/api/v1/groups') { [200, { 'Content-Type' => 'application/json' }, '[{"id":7}]'] } } } - - it 'keeps it' do - transport = unit_transport(middleware: ->(faraday) { faraday.adapter :test, stubs }) - - expect(transport.instance_variable_get(:@connection).adapter.name).to include('Adapter::Test') - end - - it 'sends requests through it, with the arguments it was given' do - transport = unit_transport(middleware: ->(faraday) { faraday.adapter :test, stubs }) - - expect(transport.get('api/v1/groups', operation: 'test').body).to eq([{ id: 7 }]) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'keeps it where it is the default adapter, named again to give it a block' do - configured = nil - transport = unit_transport(middleware: ->(faraday) { faraday.adapter(Faraday.default_adapter) { configured = true } }) - stub_request(:get, url).to_return(json_response([])) - transport.get('api/v1/groups', operation: 'test') - - expect(configured).to be(true) - end - - it 'still puts the default adapter in where the callable chose none' do - transport = unit_transport(middleware: ->(faraday) { faraday.use(Class.new(Faraday::Middleware)) }) - - expect(transport.instance_variable_get(:@connection).adapter.name).to eq(Faraday::Adapter.lookup_middleware(Faraday.default_adapter).name) - end - - # Two answers to one question, and whichever was kept the other was - # dropped without a word. - it 'refuses one named in the adapter option as well' do - expect { unit_transport(adapter: :net_http, middleware: ->(faraday) { faraday.adapter :test, stubs }) } - .to raise_error(ZammadAPI::ConfigurationError, /config adapter is :net_http, and the `middleware:` callable set an adapter as well \(Faraday::Adapter::Test\)/) - end - - it 'refuses the pair even where both name the same adapter' do - expect { unit_transport(adapter: :test, middleware: ->(faraday) { faraday.adapter :test, stubs }) } - .to raise_error(ZammadAPI::ConfigurationError, /set an adapter as well/) - end - end - - it 'reports an unregistered adapter as a configuration error' do - expect { unit_transport(adapter: :nonsense) } - .to raise_error(ZammadAPI::ConfigurationError, /is not registered on Faraday::Adapter/) - end - - it 'does not leak a Faraday error out of the client constructor' do - expect { unit_client(adapter: :nonsense) }.to raise_error(ZammadAPI::ConfigurationError) - end - - # Only Faraday::Error used to be wrapped, so the failures that do not come - # from Faraday - the ones a caller is least equipped to place - escaped - # raw, past the `rescue ZammadAPI::ConfigurationError` the constructor is - # documented to need. - it 'reports a proxy that is not a url as a configuration error' do - expect { unit_transport(proxy: 'http://user:pa ss@host') } - .to raise_error(ZammadAPI::ConfigurationError, /URI::InvalidURIError/) - end - - it 'reports a middleware that raises as a configuration error' do - expect { unit_transport(middleware: ->(_) { raise NameError, 'boom' }) } - .to raise_error(ZammadAPI::ConfigurationError, /NameError: boom/) - end - - # The backtrace into the caller's own code is the one thing the message - # cannot carry, so the cause stays wherever it gives nothing away. - it 'keeps the error a middleware raised as the cause' do - failure = NameError.new('boom') - - expect { unit_transport(middleware: ->(_) { raise failure }) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be(failure) } - end - - # The middleware is on a line of its own on purpose. A NameError's report - # quotes the source line it was raised on, so with the proxy written on - # that line the report would carry the password after all - and the cause - # would be dropped, rightly. - it 'keeps it beside a proxy that carries credentials, where the report does not quote them' do - failure = NameError.new('boom') - raising = ->(_) { raise failure } - - expect { unit_transport(proxy: 'http://user:s3cret@proxyhost:3128', middleware: raising) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be(failure) } - end - - # Rendering a report is the error's own code, and this asks for it from - # inside the rescue that turns the error into a ConfigurationError. A - # `detailed_message` written without the `highlight:` keyword is all it - # takes: `full_message` passes it one and gets ArgumentError back. - context 'when the error a middleware raised cannot render its own report' do - let(:failure) do - Class.new(StandardError) do - def detailed_message = "unreadable: #{message}" - end.new('boom') - end - - it 'has a report that raises, which is what this is about' do - expect { failure.full_message(highlight: false) }.to raise_error(ArgumentError) - end - - it 'still reports a configuration error' do - expect { unit_transport(middleware: ->(_) { raise failure }) } - .to raise_error(ZammadAPI::ConfigurationError, /config could not be used to build a connection: .*: boom/) - end - - it 'drops the cause, which cannot be shown to quote nothing' do - expect { unit_transport(middleware: ->(_) { raise failure }) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_nil } - end - end - - it 'keeps the cause of an unregistered adapter' do - expect { unit_transport(adapter: :nonsense) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_a(Faraday::Error) } - end - - it 'does not relabel an error this gem raised itself' do - failure = ZammadAPI::NotFoundError.new(operation: 'test', resource_class: nil, detail: 'gone') - - expect { unit_transport(middleware: ->(_) { raise failure }) } - .to raise_error(ZammadAPI::NotFoundError) - end - end - - # `Faraday.default_connection_options` is where a process says what every - # Faraday connection it makes starts from, and `Faraday.new` starts this - # one from it too. What only this client's configuration is to say was - # taken from there all the same: a default Authorization stood in for the - # configured token, because the authorization middleware leaves a header - # it finds. - describe 'options a process set for every Faraday connection' do - around do |example| - before = Faraday.default_connection_options - Faraday.default_connection_options = Faraday::ConnectionOptions.new( - headers: { 'Authorization' => 'Bearer other-service-token', 'From' => 'someone@else.example', 'X-Source' => 'app' }, - params: { api_key: 'other-service-key' } - ) - example.run - ensure - Faraday.default_connection_options = before - end - - before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) } - - def sent = a_request(:get, url).with(query: hash_including({})) - - it 'sends the configured token, not an Authorization set there' do - unit_transport.get('api/v1/groups', operation: 'test') - - expect(sent.with(headers: { 'Authorization' => 'Token test-token' })).to have_been_made.once - end - - it 'sends the configured user and password, not an Authorization set there' do - unit_transport(http_token: nil, user: 'u', password: 'p').get('api/v1/groups', operation: 'test') - - expect(a_request(:get, url).with(basic_auth: %w[u p])).to have_been_made.once - end - - it 'sends no From set there, which Zammad would read as the user to act for' do - unit_transport.get('api/v1/groups', operation: 'test') - - expect(sent.with { |request| !request.headers.key?('From') }).to have_been_made.once - end - - it 'sends the From of on_behalf_of, not one set there' do - unit_transport.with_on_behalf_of('agent@example.com').get('api/v1/groups', operation: 'test') - - expect(sent.with(headers: { 'From' => 'agent@example.com' })).to have_been_made.once - end - - it 'sends no parameter set there' do - unit_transport.get('api/v1/groups', operation: 'test', query: { page: 1 }) - - expect(a_request(:get, url).with(query: { 'page' => '1' })).to have_been_made.once - end - - it 'keeps a query the configured url carries, which is this client\'s own' do - stub_request(:get, 'http://zammad.test/helpdesk/api/v1/groups').with(query: hash_including({})).to_return(json_response([])) - unit_transport(url: 'http://zammad.test/helpdesk?tenant=a').get('api/v1/groups', operation: 'test') - - expect(a_request(:get, 'http://zammad.test/helpdesk/api/v1/groups').with(query: { 'tenant' => 'a' })).to have_been_made.once - end - - it 'keeps a header set there that this client does not configure' do - unit_transport.get('api/v1/groups', operation: 'test') - - expect(sent.with(headers: { 'X-Source' => 'app' })).to have_been_made.once - end - - it 'keeps what the middleware callable sets on the connection it is handed' do - unit_transport(middleware: ->(connection) { connection.params['tenant'] = 'a' }).get('api/v1/groups', operation: 'test') - - expect(a_request(:get, url).with(query: { 'tenant' => 'a' })).to have_been_made.once - end - - # A name given as nil stands in for the default as well as one given a - # value, and `proxy:` was passed whatever the configuration held. So the - # proxy set there was taken off this connection alone, and its requests - # went out directly. - context 'with a proxy among them' do - before { Faraday.default_connection_options.proxy = shared } - - let(:shared) { 'http://shared.proxy.test:3128' } + # The callable runs after the adapter option is applied, and setting an + # adapter replaces the one that is there. + context 'with an adapter chosen inside the middleware callable' do + let(:stubs) { Faraday::Adapter::Test::Stubs.new { it.get('/api/v1/groups') { [200, { 'Content-Type' => 'application/json' }, '[{"id":7}]'] } } } - def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.uri.to_s + it 'keeps it' do + transport = unit_transport(middleware: ->(faraday) { faraday.adapter :test, stubs }) - it 'goes through that proxy where the configuration names none' do - expect(proxy_of(unit_transport)).to eq(shared) + expect(transport.instance_variable_get(:@connection).adapter.name).to include('Adapter::Test') end - it 'goes through the configured proxy where it names one' do - expect(proxy_of(unit_transport(proxy: 'http://own.proxy.test:8080'))).to eq('http://own.proxy.test:8080') - end + it 'sends requests through it, with the arguments it was given' do + transport = unit_transport(middleware: ->(faraday) { faraday.adapter :test, stubs }) - it 'takes an empty proxy: for none, as it is everywhere else' do - expect(proxy_of(unit_transport(proxy: ''))).to eq(shared) + expect(transport.get('api/v1/groups', operation: 'test').body).to eq([{ id: 7 }]) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made end - # It is this connection's proxy now, so it is this error that quotes - # one URI cannot parse, and it is a value of no option. - [ - 'http://puser:pa ss@shared.proxy.test:3128', - { uri: 'http://puser:pa ss@shared.proxy.test:3128' } - ].each do |unreadable| - context "when it is #{unreadable.class} and cannot be parsed" do - let(:shared) { unreadable } + it 'keeps it where it is the default adapter, named again to give it a block' do + configured = nil + transport = unit_transport(middleware: ->(faraday) { faraday.adapter(Faraday.default_adapter) { configured = true } }) + stub_request(:get, url).to_return(json_response([])) + transport.get('api/v1/groups', operation: 'test') + + expect(configured).to be(true) + end - it 'reports it as a configuration error without its password' do - expect { unit_transport }.to raise_error(ZammadAPI::ConfigurationError) { |error| - report = error.full_message(highlight: false) + it 'takes it over the one the adapter option names' do + transport = unit_transport(adapter: :net_http, middleware: ->(faraday) { faraday.adapter :test, stubs }) - expect(report).to include('[REDACTED]@shared.proxy.test:3128') - expect(report).not_to include('pa ss') - } - end - end + expect(transport.get('api/v1/groups', operation: 'test').body).to eq([{ id: 7 }]) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made end - end - end - describe '#with_on_behalf_of' do - it 'sends the From header' do - stub = stub_request(:get, url).with(headers: { 'From' => 'agent@example.com' }).to_return(json_response([])) - unit_transport.with_on_behalf_of('agent@example.com').get('api/v1/groups', operation: 'test') - expect(stub).to have_been_requested - end + it 'still puts the default adapter in where the callable chose none' do + transport = unit_transport(middleware: ->(faraday) { faraday.use(Class.new(Faraday::Middleware)) }) - it 'sends an integer user id, which Net::HTTP will not stringify itself' do - stub = stub_request(:get, url).with(headers: { 'From' => '42' }).to_return(json_response([])) - unit_transport.with_on_behalf_of(42).get('api/v1/groups', operation: 'test') - expect(stub).to have_been_requested + expect(transport.instance_variable_get(:@connection).adapter.name).to eq(Faraday::Adapter.lookup_middleware(Faraday.default_adapter).name) + end end - it 'records the scope as the string the header carries' do - expect(unit_transport.with_on_behalf_of(42).on_behalf_of).to eq('42') + it 'reports an unregistered adapter as a configuration error' do + expect { unit_transport(adapter: :nonsense) } + .to raise_error(ZammadAPI::ConfigurationError, /\Aconfig could not be used to build a connection: .*is not registered on Faraday::Adapter/) end - it 'keeps an unscoped transport unscoped' do - expect(unit_transport.with_on_behalf_of(nil).on_behalf_of).to be_nil + it 'does not leak a Faraday error out of the client constructor' do + expect { unit_client(adapter: :nonsense) }.to raise_error(ZammadAPI::ConfigurationError) end - # Every way to a From header goes through here, not only - # Client#on_behalf_of, and a header with nothing in it is no scope. - ['', ' ', "\u00A0"].each do |blank| - it "refuses #{blank.inspect}, which Zammad reads as no From header" do - expect { unit_transport.with_on_behalf_of(blank) }.to raise_error(ArgumentError, /on_behalf_of needs the login/) - end + it 'keeps the cause of an unregistered adapter' do + expect { unit_transport(adapter: :nonsense) } + .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_a(Faraday::Error) } end + end - # Every object has a `to_s`, and the From header carried it. - { 'an Array' => ['agent'], 'a Float' => 1.5, 'true' => true, 'any other object' => Object.new }.each do |kind, value| - it "refuses #{kind}, which names no user, by its class" do - expect { unit_transport.with_on_behalf_of(value) } - .to raise_error(ArgumentError, /\Aon_behalf_of needs the login, email address or id of a user, as a String or an Integer, and was given #{value.class}:/) - end + describe '.on_behalf_of_header' do + it 'hands back a login as it is' do + expect(described_class.on_behalf_of_header('agent@example.com')).to eq('agent@example.com') end it 'takes a user id given as an Integer' do - expect(unit_transport.with_on_behalf_of(7).on_behalf_of).to eq('7') + expect(described_class.on_behalf_of_header(7)).to eq('7') end it 'takes a login given as a Symbol' do - expect(unit_transport.with_on_behalf_of(:agent).on_behalf_of).to eq('agent') - end - - # The blank check raised Encoding::CompatibilityError for text in an - # encoding ASCII is no part of, for an identifier that names someone too. - it 'refuses an identifier with a line break inside it' do - expect { unit_transport.with_on_behalf_of("agent\nadmin") }.to raise_error(ArgumentError, /on_behalf_of holds a line break/) + expect(described_class.on_behalf_of_header(:agent)).to eq('agent') end - # Net::HTTP strips it. The scope was held, and handed to any other - # adapter, with the break on it. - it 'holds an identifier that only ends in a line break without it' do - expect(unit_transport.with_on_behalf_of("agent\n").on_behalf_of).to eq('agent') + it 'strips the whitespace around an identifier' do + expect(described_class.on_behalf_of_header(" agent@example.com\n")).to eq('agent@example.com') end - it 'refuses an identifier that is nothing once it is stripped' do - expect { unit_transport.with_on_behalf_of("\0") }.to raise_error(ArgumentError, /on_behalf_of needs the login/) + # Zammad reads an empty From header as none, so every request would run + # as the authenticated account. + [nil, '', ' '].each do |blank| + it "refuses #{blank.inspect}" do + expect { described_class.on_behalf_of_header(blank) } + .to raise_error(ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{blank.inspect}") + end end - it 'refuses a blank identifier given in UTF-16' do - expect { unit_transport.with_on_behalf_of(' '.encode('UTF-16LE')) }.to raise_error(ArgumentError, /on_behalf_of needs the login/) - end + it 'hands back a frozen copy, which a later change to the String it was given does not reach' do + login = +'agent@example.com' + header = described_class.on_behalf_of_header(login) + login.replace('admin@example.com') - it 'holds an identifier given in UTF-16 as the same text in UTF-8' do - expect(unit_transport.with_on_behalf_of('bob'.encode('UTF-16LE')).on_behalf_of).to eq('bob').and(have_attributes(encoding: Encoding::UTF_8)) + expect(header).to eq('agent@example.com').and be_frozen end - # `String#to_s` hands back the receiver, so the scoped transport held the - # caller's own String: a login buffer reused after the scope was taken - # changed who every later request was performed for. - context 'when the string it was given changes afterwards' do - let(:login) { +'agent@example.com' } - let(:scoped) { unit_transport.with_on_behalf_of(login) } - - before do - scoped - login.replace('admin@example.com') - end - - it 'goes on sending the scope it was given' do - stub = stub_request(:get, url).with(headers: { 'From' => 'agent@example.com' }).to_return(json_response([])) - scoped.get('api/v1/groups', operation: 'test') - - expect(stub).to have_been_requested - end + it 'leaves the String it was given writable' do + login = +'agent@example.com' + described_class.on_behalf_of_header(login) - it 'goes on reporting the scope it was given' do - expect(scoped.on_behalf_of).to eq('agent@example.com') - end + expect(login).not_to be_frozen end + end - it 'holds the scope frozen' do - expect(unit_transport.with_on_behalf_of(+'agent@example.com').on_behalf_of).to be_frozen + describe '#with_on_behalf_of' do + it 'sends the From header' do + stub = stub_request(:get, url).with(headers: { 'From' => 'agent@example.com' }).to_return(json_response([])) + unit_transport.with_on_behalf_of('agent@example.com').get('api/v1/groups', operation: 'test') + expect(stub).to have_been_requested end - it 'leaves the string it was given writable' do - login = +'agent@example.com' - unit_transport.with_on_behalf_of(login) - - expect(login).not_to be_frozen + it 'keeps an unscoped transport unscoped' do + expect(unit_transport.with_on_behalf_of(nil).on_behalf_of).to be_nil end it 'returns a different transport' do @@ -2291,9 +838,9 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u end end - # Left to Ruby, inspect printed the Faraday connection, whose proxy options - # carry the proxy password and whose middleware stack carries the token it - # was built with. + # Left to Ruby, inspect would print the Faraday connection, whose proxy + # options carry the proxy password and whose middleware stack carries the + # token it was built with. describe '#inspect' do let(:transport) do unit_transport(http_token: 'tok-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') @@ -2325,66 +872,6 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u end end - # ActiveSupport serializes an object as its instance variables, and one of - # a transport's is the Faraday connection. It is not loaded here: what is - # asked is what it asks, and that the answer is this class's own. - describe 'serializing as JSON' do - let(:transport) do - unit_transport(http_token: 'tok-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') - end - - it 'answers as_json itself, where ActiveSupport would answer for any object' do - expect(described_class.instance_method(:as_json).owner).to be(described_class) - end - - it 'is the instance and the authentication scheme' do - expect(transport.as_json).to eq({ url: 'http://zammad.test/', auth: :http_token }) - end - - it 'names an on_behalf_of scope' do - expect(transport.with_on_behalf_of('agent@example.com').as_json).to include(on_behalf_of: 'agent@example.com') - end - - it 'writes that as a JSON object, with neither the token nor the proxy password' do - expect(JSON.generate(transport: transport)).to eq('{"transport":{"url":"http://zammad.test/","auth":"http_token"}}') - end - end - - # Psych writes an object as its instance variables too, and asks neither - # inspect nor as_json. Every record holds its transport. - describe 'serializing as YAML' do - let(:transport) do - unit_transport(http_token: 'tok-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') - end - - it 'is the instance and the authentication scheme, with neither the token nor the proxy password' do - expect(YAML.safe_load(transport.to_yaml)).to eq({ 'url' => 'http://zammad.test/', 'auth' => 'http_token' }) - end - - it 'names an on_behalf_of scope' do - expect(YAML.safe_load(transport.with_on_behalf_of('agent@example.com').to_yaml)).to include('on_behalf_of' => 'agent@example.com') - end - - it 'writes no credential for a record, which holds it' do - written = ZammadAPI::Resources::Group.new(transport, { name: 'Users' }).to_yaml - - expect(written).to include('name: Users') - expect(written).not_to match(/tok-s3cret|pproxy-s3cret/) - end - - it 'writes none for a client or a collection either' do - client = unit_client(http_token: 'tok-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') - - expect(client.to_yaml + client.groups.to_yaml + client.groups.all.to_yaml).not_to match(/tok-s3cret|pproxy-s3cret/) - end - - it 'makes no request' do - unit_client.groups.all.to_yaml - - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - end - describe '#with_config' do it 'applies the new configuration' do expect(unit_transport.with_config(ZammadAPI::Config.new(**unit_config(timeout: 7))).config.timeout).to eq(7) @@ -2437,11 +924,11 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u end it 'marks the redacted payload value' do - expect(log).to include('"password" => "[REDACTED]"') + expect(log).to include('password: "[REDACTED]"') end it 'keeps non-sensitive payload values' do - expect(log).to include('"login" => "jane"') + expect(log).to include('login: "jane"') end it 'stays silent by default' do @@ -2507,7 +994,7 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u # Matched as a word, so that a key merely containing the letters stays # readable in the log rather than being blanked for nothing. it 'leaves a key whose name only contains one of the words alone' do - expect(log).to include('"keyboard_layout" => "de"') + expect(log).to include('keyboard_layout: "de"') end it 'redacts a client_secret' do @@ -2515,14 +1002,12 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u end it 'still keeps a non-sensitive value' do - expect(log).to include('"login" => "jane"') + expect(log).to include('login: "jane"') end end # The names Zammad filters from its own log, in - # config/initializers/filter_parameter_logging.rb, that matched no word - # here: an LDAP source's bind password and a PGP key's passphrase were - # logged beside a redacted `key`. + # config/initializers/filter_parameter_logging.rb. describe 'the keys Zammad filters from its own log' do %w[bind_pw passphrase privateKey sshKeys publicKeyId otp otp_code totp hotp salt pw_salt].each do |name| it "redacts #{name}" do @@ -2542,16 +1027,9 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u expect(described_class.redact({ name: 'x', preferences: { bind_user: 'cn=admin', bind_pw: 'hunter2' } })) .to eq({ name: 'x', preferences: { bind_user: 'cn=admin', bind_pw: '[REDACTED]' } }) end - - it 'redacts them where they are written into a request path' do - expect(described_class.redact_path('api/v1/x?passphrase=opensesame&privateKey=abc&page=2')) - .to eq('api/v1/x?passphrase=[REDACTED]&privateKey=[REDACTED]&page=2') - end end - # A body handed over as a String is the caller's own encoding. Redaction - # goes by key and found none in a String, so the payload line printed it - # as it stood. + # Redaction goes by key, and a String has none. context 'with a body handed over as a String' do subject(:log) { log_device.string } @@ -2560,40 +1038,11 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } - it 'redacts a credential in one that is JSON' do - transport.post('api/v1/groups', operation: 'test', body: '{"login":"jane","password":"string-s3cret"}') - - expect(log).not_to include('string-s3cret') - end - - it 'keeps what is not a credential readable, redacted by key like a Hash' do + it 'does not log it, and says how much was left out' do transport.post('api/v1/groups', operation: 'test', body: '{"login":"jane","password":"string-s3cret"}') - expect(log).to include('Zammad API payload: {"login" => "jane", "password" => "[REDACTED]"}') - end - - it 'redacts one nested in a JSON list' do - transport.post('api/v1/groups', operation: 'test', body: '[{"user":{"api_key":"string-s3cret"}}]') - - expect(log).not_to include('string-s3cret') - end - - it 'does not log one that is not JSON, and says how much was left out' do - transport.post('api/v1/groups', operation: 'test', body: 'login=jane&password=string-s3cret') - - expect(log).not_to include('string-s3cret') - expect(log).to include('Zammad API payload: "[33 bytes that are not a JSON object or array, not logged]"') - end - - it 'does not log a JSON value with no keys to go by' do - transport.post('api/v1/groups', operation: 'test', body: '"string-s3cret"') - - expect(log).not_to include('string-s3cret') - end - - it 'does not raise for bytes that are not text' do - expect { transport.post('api/v1/groups', operation: 'test', body: "\xFF\xFEstring-s3cret".b) }.not_to raise_error expect(log).not_to include('string-s3cret') + expect(log).to include('Zammad API payload: [43 bytes, not logged]') end it 'still sends the body as it was given' do @@ -2603,80 +1052,6 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u end end - # The payload line printed the body the caller handed over, redacted by - # key through its Hashes and Arrays, and anything else in it by - # `inspect`. An object that writes its own JSON goes out as keys and - # values like any Hash, and was printed with every one of them. - context 'with a body holding an object that is neither a Hash nor an Array' do - subject(:log) { log_device.string } - - let(:log_device) { StringIO.new } - let(:transport) { unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)) } - let(:credentials) { Data.define(:login, :password) { def to_json(*) = to_h.to_json(*) }.new(login: 'jane', password: 'object-s3cret') } - - before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } - - it 'redacts a credential in one that writes its own JSON' do - transport.post('api/v1/groups', operation: 'test', body: credentials) - - expect(log).not_to include('object-s3cret') - end - - it 'prints it as it is sent, redacted by key' do - transport.post('api/v1/groups', operation: 'test', body: credentials) - - expect(log).to include('Zammad API payload: {"login" => "jane", "password" => "[REDACTED]"}') - end - - it 'redacts a credential in one that a Hash holds' do - transport.post('api/v1/groups', operation: 'test', body: { note: 'x', user: credentials }) - - expect(log).to include('Zammad API payload: {"note" => "x", "user" => {"login" => "jane", "password" => "[REDACTED]"}}') - end - - it 'redacts a credential in one that an Array holds' do - transport.post('api/v1/groups', operation: 'test', body: [credentials]) - - expect(log).not_to include('object-s3cret') - end - - # An object that is sent as its `as_json` goes out as keys and values - # too, and `inspect` printed the object in their place. - it 'redacts a credential in one that is sent as its as_json' do - described = Struct.new(:password) { def as_json(*) = to_h.transform_keys(&:to_s) }.new('object-s3cret') - transport.post('api/v1/groups', operation: 'test', body: { user: described }) - - expect(log).to include('Zammad API payload: {"user" => {"password" => "[REDACTED]"}}') - end - - # JSON has no type for such an object, and it is refused before the - # request is logged. It was sent as its `to_s`, which names the class - # and no more, while the log printed its `inspect`, which lists what - # it holds. - it 'does not print what an object holds and no request carries' do - holder = Class.new { def initialize = @password = 'object-s3cret' }.new - - expect { transport.post('api/v1/groups', operation: 'test', body: { user: holder }) }.to raise_error(ZammadAPI::Error) - expect(log).not_to include('object-s3cret') - end - - it 'does not log a body that is one value with no keys to go by' do - transport.post('api/v1/groups', operation: 'test', body: :'object-s3cret') - - expect(log).not_to include('object-s3cret') - expect(log).to include('Zammad API payload: "[15 bytes that are not a JSON object or array, not logged]"') - end - - it 'still sends the body as it was given' do - transport.post('api/v1/groups', operation: 'test', body: { user: credentials }) - - expect(a_request(:post, url).with(body: '{"user":{"login":"jane","password":"object-s3cret"}}')).to have_been_made - end - end - - # The request line printed the `query:` the caller handed over, redacted - # by key through its Hashes. What it held that converts to a Hash, and - # is sent as one, was printed by `inspect` under the key it sat at. context 'with a query that carries a credential' do subject(:log) { log_device.string } @@ -2685,23 +1060,15 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) } - it 'redacts it by key, in the query as it is sent' do + it 'redacts it by key' do transport.get('api/v1/groups', operation: 'test', query: { page: 1, token: 'query-s3cret' }) - expect(log).to include('Zammad API request: GET api/v1/groups query={"page" => "1", "token" => "[REDACTED]"}') - end - - it 'redacts it in strong parameters the query holds' do - transport.get('api/v1/groups', operation: 'test', query: { filter: StrongParameters.new(page: 1, token: 'query-s3cret') }) - - expect(log).to include('query={"filter" => {"page" => "1", "token" => "[REDACTED]"}}') - expect(log).not_to include('query-s3cret') + expect(log).to include('Zammad API request: GET api/v1/groups query={page: 1, token: "[REDACTED]"}') end end - # A raw request may carry its query in the path. The `query:` Hash is - # redacted by key, and the same parameter written into the path was - # printed in full, in the request line and in the response line. + # A raw request may carry its query in the path, where there is no key + # to redact it by. context 'with a query string written into the path' do subject(:log) { log_device.string } @@ -2713,16 +1080,16 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)).get(verify, operation: 'test') end - it 'redacts a credential in it' do + it 'keeps the credential in it out of the log' do expect(log).not_to include('path-s3cret') end - it 'marks it in the request line, and keeps the other parameters' do - expect(log).to include('Zammad API request: GET api/v1/users/password_reset_verify?token=[REDACTED]&locale=de') + it 'logs the request line without it' do + expect(log).to include("Zammad API request: GET api/v1/users/password_reset_verify\n") end - it 'marks it in the response line' do - expect(log).to include('Zammad API response: GET api/v1/users/password_reset_verify?token=[REDACTED]&locale=de -> 200') + it 'logs the response line without it' do + expect(log).to include('Zammad API response: GET api/v1/users/password_reset_verify -> 200') end it 'still sends the query as it was given' do @@ -2731,9 +1098,7 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u end end - # A raw request takes headers of its own and the request line prints - # them. `Cookie` carries a session and matched none of the credential - # words, so it was written out in full. + # A raw request takes headers of its own and the request line prints them. context 'with credential-bearing headers' do subject(:log) { log_device.string } @@ -2757,8 +1122,8 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u expect(log).not_to include('cookie-s3cret') end - it 'marks the redacted header, under the name it is sent as' do - expect(log).to include('"cookie" => "[REDACTED]"') + it 'marks the redacted header' do + expect(log).to include('"Cookie" => "[REDACTED]"') end it 'redacts a Proxy-Authorization' do @@ -2770,7 +1135,7 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u end it 'keeps a header that carries no credential' do - expect(log).to include('"x-request-id" => "request-123"') + expect(log).to include('"X-Request-Id" => "request-123"') end it 'still sends the headers as they were given' do @@ -2780,10 +1145,8 @@ def proxy_of(transport) = transport.instance_variable_get(:@connection).proxy&.u end end - # `request` documents that every failure leaves it as a ZammadAPI::Error. - # Faraday::SSLError was handled and its unwrapped counterpart was not, so a - # certificate mismatch through an adapter that does not wrap - an adapter - # this gem lets a caller choose - went straight past the rescue. + # Through an adapter that does not wrap OpenSSL::SSL::SSLError into + # Faraday::SSLError. describe 'a TLS failure through an adapter that does not wrap it' do before { BareTlsAdapter.attempts = [] } @@ -2813,268 +1176,4 @@ def bare_tls_transport(**overrides) expect(described_class::RETRIABLE_EXCEPTIONS).not_to include(*described_class::SSL_ERRORS) end end - - # The error Faraday or URI raises quotes the value it rejected, and for a - # proxy that value carries its credentials - into a message that lands in - # every log and exception report. - describe 'a connection that cannot be built from a credential-bearing proxy' do - let(:proxy) { 'http://user:pa ss@proxyhost:3128' } - - it 'reports it as a configuration error' do - expect { unit_transport(proxy: proxy) }.to raise_error(ZammadAPI::ConfigurationError) - end - - it 'keeps the proxy password out of the message' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('pa ss') } - end - - it 'still says which value was rejected' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) - end - - # The message is not what a log or an error tracker prints. They print - # the report, and Ruby had attached the error being rescued as the cause: - # the redacted message went out with the original, password and all, - # right behind it. - it 'keeps the proxy password out of the whole report, not just the message' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('pa ss') } - end - - it 'does not carry the error that quotes the password along as its cause' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_nil } - end - - it 'still names the class of the error it replaced' do - expect { unit_transport(proxy: proxy) }.to raise_error(ZammadAPI::ConfigurationError, /URI::InvalidURIError/) - end - - # The error being replaced may be clean itself and still have the - # password one level down, and a report prints every level. - context 'when the error quotes the proxy only further down its own chain' do - let(:proxy) { 'http://user:s3cret@proxyhost:3128' } - - let(:wrapping) do - lambda do |_| - raise URI::InvalidURIError, "bad URI: #{proxy}" - rescue URI::InvalidURIError - raise ArgumentError, 'the proxy could not be used' - end - end - - it 'has nothing to redact in the message' do - expect { unit_transport(proxy: proxy, middleware: wrapping) } - .to raise_error(ZammadAPI::ConfigurationError, /ArgumentError: the proxy could not be used/) - end - - it 'keeps the password out of the whole report all the same' do - expect { unit_transport(proxy: proxy, middleware: wrapping) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('s3cret') } - end - end - - # A # ends the authority early, so the redaction found no credential in - # what was left of it and the message quoted the password in full. - context 'when the password carries a character that ends the authority' do - let(:proxy) { 'http://user:pa#ss-s3cret@proxyhost:3128' } - - it 'keeps the password out of the message' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to match(/pa#ss|s3cret/) } - end - - it 'still says which value was rejected' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) - end - - it 'keeps the password out of the whole report' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to match(/pa#ss|s3cret/) } - end - end - - context 'when it is the instance url that carries such a password' do - it 'keeps the password out of the message' do - expect { unit_transport(url: 'https://admin:pa#ss-s3cret@zammad.test/') } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to match(/pa#ss|s3cret/) } - end - end - - # With no `proxy:` given, Faraday takes the one the environment names, - # and URI quotes one it cannot parse as it quotes a configured one. The - # redaction knew the values of the configuration, and this is in none. - context 'when the proxy is the one the environment names' do - let(:proxy) { 'http://user:hunter 2@proxyhost:3128' } - - around do |example| - before = ENV.fetch('http_proxy', nil) - ENV['http_proxy'] = proxy - example.run - ensure - ENV['http_proxy'] = before - end - - # An address, so that URI has no name to look up before it reads the - # proxy. - def build = unit_transport(url: 'http://192.0.2.1/') - - it 'reports it as a configuration error' do - expect { build }.to raise_error(ZammadAPI::ConfigurationError, /URI::InvalidURIError/) - end - - it 'keeps the proxy password out of the message' do - expect { build }.to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('hunter 2') } - end - - it 'still says which value was rejected' do - expect { build }.to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) - end - - it 'keeps the proxy password out of the whole report' do - expect { build } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('hunter 2') } - end - - it 'does not carry the error that quotes the password along as its cause' do - expect { build }.to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_nil } - end - - # The environment can hold what no option is accepted with, and text - # with a broken byte in it raises from being searched for. - context 'when its password holds a byte that is not text' do - let(:proxy) { "http://user:hunter\xFF2@proxyhost:3128" } - - it 'is still reported as a configuration error, without the password' do - expect { build }.to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) { |error| - expect(error.full_message(highlight: false)).not_to include('hunter') - } - end - end - - # The environment can hold a name that is not text either, and the - # pattern that picks out the proxy variables raised when asked of it: - # a bare ArgumentError in place of the ConfigurationError. - context 'when another variable has a name that is not text' do - around do |example| - ENV["caf\xE9_proxy"] = other - example.run - ensure - ENV["caf\xE9_proxy"] = nil - end - - let(:other) { 'http://other.proxy.test:1' } - - it 'is still reported as a configuration error, without the password' do - expect { build }.to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@proxyhost:3128}) { |error| - expect(error.full_message(highlight: false)).not_to include('hunter 2') - } - end - - it 'reports a configured proxy that cannot be parsed the same way' do - ENV['http_proxy'] = nil - - expect { unit_transport(url: 'http://192.0.2.1/', proxy: 'http://puser:pa ss@own.proxy.test') } - .to raise_error(ZammadAPI::ConfigurationError, %r{http://\[REDACTED\]@own\.proxy\.test}) - end - - it 'builds a client whose configuration can be used' do - ENV['http_proxy'] = nil - - expect(build).to be_a(described_class) - end - - # It ends in _proxy, so what it holds is scrubbed like any other. - it 'keeps the credentials that variable holds out of a report that quotes them' do - ENV['http_proxy'] = nil - ENV["caf\xE9_proxy"] = 'http://quser:qpass word@other.proxy.test:1' - quoting = ->(_) { raise ArgumentError, 'could not reach http://quser:qpass word@other.proxy.test:1' } - - expect { unit_transport(url: 'http://192.0.2.1/', middleware: quoting) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('qpass word') } - end - end - - context 'when the environment names it in upper case' do - around do |example| - before = ENV.fetch('HTTPS_PROXY', nil) - ENV['http_proxy'] = nil - ENV['HTTPS_PROXY'] = proxy - example.run - ensure - ENV['HTTPS_PROXY'] = before - end - - it 'keeps the proxy password out of the whole report' do - expect { unit_transport(url: 'https://192.0.2.1/') } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to include('hunter 2') } - end - end - end - - # The error quotes what it rejected through `inspect`, which escapes the - # backslash - so the text in the message stopped matching the configured - # value and the substring swap redacted nothing at all. - context 'when the value carries a backslash, which inspect escapes' do - let(:proxy) { 'http://user:secret@proxyhost/a\0b' } - - it 'still keeps the password out of the message' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('secret') } - end - end - - # URI turns away a URL holding a character outside ASCII, and quotes it - # through `dump`, which writes that character as an escape where - # `inspect` leaves it standing. Neither spelling that was looked for - # matched, so the password stayed in the message and in the cause. - context 'when the password carries a character outside ASCII, which dump escapes' do - let(:proxy) { 'http://user:pässwörd@proxyhost:3128' } - - it 'keeps the password out of the message' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to match(/ssw|user:/) } - end - - it 'still says which value was rejected' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError, %r{URI must be ascii only "http://\[REDACTED\]@proxyhost:3128"}) - end - - it 'keeps the password out of the whole report' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to match(/ssw|user:/) } - end - - it 'does not carry the error that quotes the password along as its cause' do - expect { unit_transport(proxy: proxy) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_nil } - end - - it 'keeps it out of the message where the instance url carries it' do - expect { unit_transport(url: 'https://admin:pässwörd@zammad.test/') } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.full_message(highlight: false)).not_to match(/ssw|admin:/) } - end - end - - # `\0` in a gsub replacement String expands to the matched text, which is - # the unredacted value. - context 'when the value carries a sequence a gsub replacement would expand' do - let(:proxy) { 'http://user:secret@proxyhost/a\0b' } - - it 'does not put the credential back through the replacement' do - message = begin - unit_transport(proxy: proxy) - nil - rescue ZammadAPI::ConfigurationError => e - e.message - end - - expect(message.scan('user:secret')).to be_empty - end - end - end end From 69e5d78690e1b5776ead00b58690813f9efa2dc1 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 25 Nov 2026 00:11:28 +0200 Subject: [PATCH 087/121] refactor!: drop the remaining edge-case guards A second pass over the 2.0 client for straightforward API usage. lib/ goes from 2,774 to 2,688 lines. - The connection's :json middleware encodes a request body; the gem no longer encodes it first to turn a JSON::GeneratorError into an Error. - Network failures are rescued and retried as Faraday's own errors. The default adapter wraps socket and TLS errors into them, so the lists of raw Errno, SocketError and OpenSSL errors go. - A destroyed record no longer refuses save, reload, destroy, attribute writes and related; Zammad answers 404 for the record that is gone. - Records compare by class and id; the Zammad URL is no longer part of equality. - Config drops the proxy URL parse and the check against Complex numbers. - from_env reads the access token from ZAMMAD_TOKEN only, not also from ZAMMAD_HTTP_TOKEN. - Log redaction matches a plain list of words anywhere in a key, as Zammad's own log filter does, rather than word-bounded patterns. --- CHANGELOG.md | 15 +- README.md | 13 +- Steepfile | 15 +- lib/zammad_api/attribute_access.rb | 20 +-- lib/zammad_api/client.rb | 8 +- lib/zammad_api/config.rb | 11 +- lib/zammad_api/resources/base.rb | 20 +-- .../resources/ticket_article_attachment.rb | 5 - lib/zammad_api/test.rb | 1 - lib/zammad_api/transport.rb | 81 +++------ sig/zammad_api/attribute_access.rbs | 3 - sig/zammad_api/config.rbs | 1 - sig/zammad_api/resources/base.rbs | 1 - sig/zammad_api/transport.rbs | 8 +- spec/support/bare_socket_adapter.rb | 46 ----- spec/unit/zammad_api/client_spec.rb | 14 +- spec/unit/zammad_api/config_spec.rb | 10 -- spec/unit/zammad_api/resources/base_spec.rb | 121 +------------ .../ticket_article_attachment_spec.rb | 9 - spec/unit/zammad_api/resources/ticket_spec.rb | 17 -- spec/unit/zammad_api/test_spec.rb | 17 -- spec/unit/zammad_api/transport_spec.rb | 161 +----------------- 22 files changed, 54 insertions(+), 543 deletions(-) delete mode 100644 spec/support/bare_socket_adapter.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e8f7a0..5462489 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,9 +55,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `DELETE /api/v1/groups/99`. - `record.id = ...` raises `ZammadAPI::Error`. The id is what addresses the record, so a staged one made `destroy` and `save` act on another record than the one they reported on. -- `record.destroy` marks the record `destroyed?`, and `persisted?` answers false for one; - `save`, `reload` and attribute writers raise for it. 1.x left a destroyed record looking - live, so a later `save` went out as a `PUT` to the deleted id. +- `record.destroy` marks the record `destroyed?`, and `persisted?` answers false for one. + 1.x left a destroyed record looking live. - `record.attributes` and `record.changes` are deeply frozen, and `record.to_h` returns a deep copy rather than a shallow one. Writing through either reader used to change what a record reported without staging anything, so the next `save` did not send it. @@ -186,7 +185,7 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `Client#with(**options)` derives a new client with changed options. The options are re-validated and any `on_behalf_of` scope is carried over. - `Client.from_env` builds a client from `ZAMMAD_URL`, `ZAMMAD_TOKEN`, - `ZAMMAD_HTTP_TOKEN`, `ZAMMAD_OAUTH2_TOKEN`, `ZAMMAD_USER` and `ZAMMAD_PASSWORD`, with + `ZAMMAD_OAUTH2_TOKEN`, `ZAMMAD_USER` and `ZAMMAD_PASSWORD`, with passed-in options winning. A blank variable counts as unset. - `Client#me`, the user the credentials authenticate as, and `Client#version`, the version of the Zammad instance. @@ -199,9 +198,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `ticket.customer` keeps returning that name. `Resource.associations` lists what a resource declares. - Records compare as the Zammad records they came from: two records of the same kind with - the same id, read from the same Zammad URL, are equal, and `#hash` agrees, so `uniq`, - `Set`, `include?` and records as Hash keys all work. A record with no id stays equal only - to itself. + the same id are equal, and `#hash` agrees, so `uniq`, `Set`, `include?` and records as + Hash keys all work. A record with no id stays equal only to itself. - `record.to_json` and `record.as_json` render a record's attributes. `to_json` previously fell through to `Object#to_json`, which serialized a record as the string `"#"`. @@ -258,8 +256,7 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `client.` returns the same proxy each time rather than allocating one per call. The proxies are built with the client, so a client stays immutable once built and safe to share between threads. -- A request body that cannot be encoded as JSON raises `ZammadAPI::Error` rather than - `JSON::GeneratorError`. A String body is sent as it is. +- A String request body is sent as it is rather than encoded as a JSON string. - The recursive copy behind frozen attributes, `to_h` and the test kit's recorded bodies lives in one place (`ZammadAPI::DeepCopy`) instead of being written once per caller. - Unit specs (`rake spec:unit`) run without a Zammad instance; the specs that need a live diff --git a/README.md b/README.md index f993275..91f6c66 100644 --- a/README.md +++ b/README.md @@ -126,8 +126,8 @@ them. ### From the environment -`from_env` reads `ZAMMAD_URL` and `ZAMMAD_TOKEN` (or `ZAMMAD_HTTP_TOKEN`, -`ZAMMAD_OAUTH2_TOKEN`, or `ZAMMAD_USER` and `ZAMMAD_PASSWORD`), so a script needs no +`from_env` reads `ZAMMAD_URL` and `ZAMMAD_TOKEN` (or `ZAMMAD_OAUTH2_TOKEN`, or +`ZAMMAD_USER` and `ZAMMAD_PASSWORD`), so a script needs no configuration of its own. A variable that is empty or blank counts as unset. Anything passed in wins over the environment, and credentials passed in replace the ones the environment holds: @@ -349,9 +349,8 @@ text: client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) ``` -A `body:` is sent as JSON, and a String body is sent as it is. A body that cannot be -encoded as JSON raises `ZammadAPI::Error`. A `query:` Hash is encoded by Faraday, nested -Hashes and lists included. +A `body:` is sent as JSON, and a String body is sent as it is. A `query:` Hash is encoded +by Faraday, nested Hashes and lists included. Each returns a `ZammadAPI::Response`, so the status and headers stay reachable: @@ -592,7 +591,7 @@ shows up. `Ticket.associations` lists what a resource declares. ### Comparing and serializing A record is the Zammad record it came from, not the object that happens to hold it, so two -records of the same kind carrying the same id, read from the same Zammad URL, are equal. +records of the same kind carrying the same id are equal. That makes `uniq`, `Set`, `include?` and records-as-Hash-keys behave: ```ruby @@ -621,8 +620,6 @@ group.destroy # => true group.destroyed? # => true group.persisted? # => false, so this is not the inverse of new_record? -group.save # raises: the record is gone -group.name = 'X' # raises as well client.groups.destroy(42) # delete by id, without fetching first ``` diff --git a/Steepfile b/Steepfile index c0e6fbc..6efc07c 100644 --- a/Steepfile +++ b/Steepfile @@ -4,15 +4,12 @@ target :lib do signature 'sig' check 'lib' - # socket is here for SocketError and openssl for OpenSSL::SSL::SSLError, - # both of which Transport maps to ConnectionError; forwardable is here for - # the collection shorthands ResourceProxy delegates to Collection; uri is - # here for the parse Config makes of the instance url and the escaping of - # record ids. None of the four is named in the signatures the gem - # publishes - see SSL_ERRORS in sig/zammad_api/transport.rbs and - # sig/vendor/internal.rbs - so this does not add anything a consumer has - # to load. - library 'json', 'logger', 'timeout', 'socket', 'openssl', 'forwardable', 'uri' + # forwardable is here for the collection shorthands ResourceProxy delegates + # to Collection; uri is here for the parse Config makes of the instance url + # and the escaping of record ids. Neither is named in the signatures the + # gem publishes - see sig/vendor/internal.rbs - so this does not add + # anything a consumer has to load. + library 'json', 'logger', 'timeout', 'forwardable', 'uri' configure_code_diagnostics do |hash| # Default keyword-argument hashes such as `attributes = {}` cannot be diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb index 6e7cb00..c5666dd 100644 --- a/lib/zammad_api/attribute_access.rb +++ b/lib/zammad_api/attribute_access.rb @@ -70,18 +70,14 @@ def id = attributes[:id] def deconstruct_keys(keys) = keys.nil? ? attributes : attributes.slice(*keys) # Whether +other+ is the same Zammad record: the same class, carrying the - # same id, read from the same Zammad. A record with no id is equal only - # to itself. + # same id. A record with no id is equal only to itself. # # @param other [Object] # @return [Boolean] def ==(other) - return true if equal?(other) - return false if !other.instance_of?(self.class) + return true if equal?(other) - # The steep:ignore is for `installation`, which is protected: RBS has - # no word for that, so the signature declares it private. - !id.nil? && other.id == id && other.installation == installation # steep:ignore NoMethod + other.instance_of?(self.class) && !id.nil? && other.id == id end alias eql? == @@ -90,7 +86,7 @@ def ==(other) # # @return [Integer] def hash - id.nil? ? super : [self.class, installation, id].hash + id.nil? ? super : [self.class, id].hash end # @return [Hash{Symbol => Object}] the attributes, for a JSON encoder @@ -114,14 +110,6 @@ def respond_to_missing?(name, include_private = false) attributes.key?(name) || super end - protected - - # The Zammad the record was read from, for {#==}: an id is only unique - # within one installation. - # - # @return [String, nil] - def installation = nil - private def writable_attributes? = false diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index 3e6a07e..4b89975 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -66,7 +66,6 @@ class Client ENV_OPTIONS = { 'ZAMMAD_URL' => :url, 'ZAMMAD_TOKEN' => :http_token, - 'ZAMMAD_HTTP_TOKEN' => :http_token, 'ZAMMAD_OAUTH2_TOKEN' => :oauth2_token, 'ZAMMAD_USER' => :user, 'ZAMMAD_PASSWORD' => :password @@ -74,10 +73,9 @@ class Client # Builds a client from the environment. # - # Reads {ENV_OPTIONS}; a variable that is empty or blank counts as unset, - # and +ZAMMAD_HTTP_TOKEN+ wins over +ZAMMAD_TOKEN+. Anything passed in wins - # over the environment, and credentials passed in replace the ones the - # environment holds. + # Reads {ENV_OPTIONS}; a variable that is empty or blank counts as unset. + # Anything passed in wins over the environment, and credentials passed in + # replace the ones the environment holds. # # @example # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=secret ruby report.rb diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index cb6cd8f..1b9da7e 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -223,7 +223,6 @@ def normalize_url(value) def validate! validate_credentials! validate_numbers! - validate_proxy! raise ConfigurationError, "config ssl_verify needs to be true or false, got #{ssl_verify.inspect}" if ![true, false].include?(ssl_verify) raise ConfigurationError, 'config middleware needs to respond to call' if middleware && !middleware.respond_to?(:call) raise ConfigurationError, 'config logger needs to respond to debug' if !logger.respond_to?(:debug) @@ -243,19 +242,11 @@ def validate_credentials! def validate_numbers! { timeout: timeout, open_timeout: open_timeout, retry_interval: retry_interval }.each do |name, value| - raise ConfigurationError, "config #{name} needs to be a positive number" if !value.is_a?(Numeric) || !value.real? || !value.positive? + raise ConfigurationError, "config #{name} needs to be a positive number" if !value.is_a?(Numeric) || !value.positive? end raise ConfigurationError, 'config retries needs to be a non-negative integer' if !retries.is_a?(Integer) || retries.negative? end - # Here rather than where Faraday parses it, whose error quotes the URL - # with its password. - def validate_proxy! - URI.parse(proxy.to_s) if proxy - rescue URI::InvalidURIError - raise ConfigurationError, 'config proxy is not a valid URL' - end - def present(value) = value.nil? || value.to_s.empty? ? nil : value def stripped(value) diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 65bd027..b44b0d9 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -234,10 +234,7 @@ def changed? = !changes.empty? # ticket.related.customer # => the User record, one request # # @return [Associations::Proxy] - # @raise [Error] when the record was destroyed def related - raise_if_destroyed!('read related records from') - @related ||= Associations::Proxy.new(self) end @@ -266,9 +263,7 @@ def save # # @return [true] # @raise [ValidationError] when Zammad rejected the attributes - # @raise [Error] when the record was destroyed def save! - raise_if_destroyed!('save') @error = nil if new_record? @@ -306,9 +301,8 @@ def update!(attributes) # Reads this record again, dropping staged changes. # # @return [self] - # @raise [Error] when the record is new or was destroyed + # @raise [Error] when the record is new def reload - raise_if_destroyed!('reload') raise_if_new!('reload') response = transport.get(member_path, operation: 'reload object', resource_class: self.class, query: { expand: true }) @@ -319,9 +313,8 @@ def reload # Deletes this record in Zammad. # # @return [true] - # @raise [Error] when the record is new or was destroyed already + # @raise [Error] when the record is new def destroy - raise_if_destroyed!('destroy') raise_if_new!('destroy') transport.delete(member_path, operation: 'destroy object', resource_class: self.class) @@ -331,10 +324,6 @@ def destroy def inspect = "#<#{self.class.name} id=#{id.inspect} new_record=#{new_record?}#{' destroyed=true' if destroyed?} attributes=#{Transport.redact(attributes).inspect}>" - protected - - def installation = transport.config.url - private def mark_persisted! @@ -352,14 +341,9 @@ def raise_if_new!(operation) raise Error, "#{self.class.name} has not been saved, so there is nothing to #{operation}" if new_record? end - def raise_if_destroyed!(action) - raise Error, "#{self.class.name} #{id} was destroyed, there is nothing to #{action}" if destroyed? - end - def writable_attributes? = true def write_attribute(key, value) - raise_if_destroyed!('change') raise Error, "#{self.class.name}#id cannot be changed: it is what addresses this record" if key == :id staged = frozen_attributes(value) diff --git a/lib/zammad_api/resources/ticket_article_attachment.rb b/lib/zammad_api/resources/ticket_article_attachment.rb index 5b0745b..7204982 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -38,11 +38,6 @@ def download def inspect "#<#{self.class.name} id=#{id.inspect} filename=#{self[:filename].inspect} size=#{self[:size].inspect}>" end - - protected - - # @return [String] the Zammad this attachment was read from - def installation = @transport.config.url end end end diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index e2de89b..7ba10a6 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -133,7 +133,6 @@ def inspect = @monitor.synchronize { "#<#{self.class.name} stubbed=#{@stubs.size # @raise [UnstubbedRequestError] when no stub matches def answer(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil, on_behalf_of: nil) relative = ::ZammadAPI::Transport.relative_path(path) - ::ZammadAPI::Transport.encode_body(body, operation: operation, resource_class: resource_class) params = stringify(query || {}) request = Request.new( verb: method, diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index aeeaf5d..31a084d 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -2,9 +2,6 @@ require 'faraday' require 'faraday/retry' -require 'json' -require 'openssl' -require 'socket' require 'timeout' require 'uri' @@ -46,37 +43,17 @@ module Verbs # Statuses a read is retried on. RETRIABLE_STATUSES = [429, 500, 502, 503, 504].freeze - # Errors that mean the request timed out. + # Errors that mean the request timed out, found inside the + # Faraday::ConnectionFailed an adapter wraps an open timeout into. TIMEOUT_ERRORS = [Errno::ETIMEDOUT, Timeout::Error].freeze - # Socket errors an adapter may raise without wrapping them. - CONNECTION_ERRORS = [ - Errno::ECONNREFUSED, - Errno::ECONNRESET, - Errno::EHOSTUNREACH, - Errno::ENETUNREACH, - Errno::EPIPE, - SocketError - ].freeze - - # TLS errors an adapter may raise without wrapping them. - SSL_ERRORS = [OpenSSL::SSL::SSLError].freeze - - # Errors a read is retried on. - RETRIABLE_EXCEPTIONS = [ - Faraday::RetriableResponse, - Faraday::ConnectionFailed, - Faraday::TimeoutError, - *TIMEOUT_ERRORS, - *CONNECTION_ERRORS - ].freeze - - # Keys whose values are never written to the log. - SENSITIVE_KEY_PATTERN = / - password|passwd|pwd|bind_pw|passphrase|token|secret|credential|cookie|authorization|api_?key - |(? e - # Without the cause, whose report quotes the value that failed. - raise Error, "Can't #{Error.subject_for(operation, resource_class)}: the request body cannot be encoded as JSON (#{e.message})", cause: nil - end - # @param config [Config] # @param on_behalf_of [String, nil] see {.on_behalf_of_header} # @raise [ConfigurationError] when the connection cannot be built @@ -201,30 +162,29 @@ def inspect # @param path [String] path relative to {Config#url} # @param operation [String] description used in error messages # @param query [Hash, nil] query string parameters - # @param body [Hash, Array, String, nil] request payload, encoded as JSON + # @param body [Hash, Array, String, nil] request payload; a Hash or Array + # is encoded as JSON, a String is sent as it is # @param headers [Hash, nil] request headers # @param resource_class [Class, nil] used in error messages # @return [Response] # @raise [ResponseError] for non-2xx responses # @raise [TimeoutError] when the request timed out # @raise [ConnectionError] when the instance was unreachable - # @raise [Error] when the body cannot be encoded as JSON def request(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) - path = Transport.relative_path(path) - payload = Transport.encode_body(body, operation: operation, resource_class: resource_class) + path = Transport.relative_path(path) log_request(method, path, query, body, headers) started = Process.clock_gettime(Process::CLOCK_MONOTONIC) - response = decode(perform(method, path, query, payload, headers)) + response = decode(perform(method, path, query, body, headers)) log_response(method, path, response, started) return response if response.success? raise ResponseError.build(response, operation: operation, resource_class: resource_class) - rescue Faraday::TimeoutError, *TIMEOUT_ERRORS => e + rescue Faraday::TimeoutError => e raise TimeoutError, "Can't #{operation}: request to #{Transport.redact_path(path)} timed out (#{e.message})" - rescue Faraday::SSLError, *SSL_ERRORS => e + rescue Faraday::SSLError => e raise ConnectionError, "Can't #{operation}: TLS handshake with #{config.url} failed (#{e.message})" - rescue Faraday::ConnectionFailed, *CONNECTION_ERRORS => e + rescue Faraday::ConnectionFailed => e raise TimeoutError, "Can't #{operation}: connecting to #{config.url} timed out (#{e.message})" if timed_out?(e) raise ConnectionError, "Can't #{operation}: #{config.url} is unreachable (#{e.message})" @@ -235,17 +195,16 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou # Whether a connection failure is a timeout underneath: the default # adapter wraps an exceeded +open_timeout+ into Faraday::ConnectionFailed. def timed_out?(error) - wrapped = error.respond_to?(:wrapped_exception) ? error.wrapped_exception : nil - - [wrapped, error.cause].any? { |inner| TIMEOUT_ERRORS.any? { inner.is_a?(it) } } + [error.wrapped_exception, error.cause].any? { |inner| TIMEOUT_ERRORS.any? { inner.is_a?(it) } } end - def perform(method, path, query, payload, headers) + # The connection's :json middleware encodes a Hash or Array body. + def perform(method, path, query, body, headers) @connection.public_send(method, path) do |request| request.params.update(query) if query headers&.each { |name, value| request.headers[name.to_s] = value.to_s } request.headers['From'] = on_behalf_of if on_behalf_of - request.body = payload if payload + request.body = body if body end end diff --git a/sig/zammad_api/attribute_access.rbs b/sig/zammad_api/attribute_access.rbs index 3f6b908..47eb217 100644 --- a/sig/zammad_api/attribute_access.rbs +++ b/sig/zammad_api/attribute_access.rbs @@ -24,9 +24,6 @@ module ZammadAPI private - # Protected in the source, which RBS has no way to say: it is asked of - # the other record in `==`, and of nobody else. - def installation: () -> String? def writable_attributes?: () -> bool def write_attribute: (Symbol, untyped) -> untyped def frozen_attributes: (untyped) -> untyped diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index 35365b5..94c2518 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -66,7 +66,6 @@ module ZammadAPI def validate!: () -> void def validate_credentials!: () -> void def validate_numbers!: () -> void - def validate_proxy!: () -> void def present: (untyped) -> untyped def stripped: (untyped) -> String? end diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index b73f452..9e27f80 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -73,7 +73,6 @@ module ZammadAPI def initialize_copy: (self source) -> void def mark_persisted!: () -> void def load_response!: (Response response, String operation) -> void - def raise_if_destroyed!: (String action) -> void def raise_if_new!: (String operation) -> void def writable_attributes?: () -> bool def write_attribute: (Symbol, untyped) -> untyped diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 9d8e5fd..f05a771 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -16,11 +16,6 @@ module ZammadAPI RETRIABLE_METHODS: Array[Symbol] RETRIABLE_STATUSES: Array[Integer] TIMEOUT_ERRORS: Array[untyped] - CONNECTION_ERRORS: Array[untyped] - # Untyped for the same reason as the Faraday ones above: naming - # OpenSSL::SSL::SSLError here would make the published signatures need - # openssl declarations that a consumer has not loaded. - SSL_ERRORS: Array[untyped] RETRIABLE_EXCEPTIONS: Array[untyped] SENSITIVE_KEY_PATTERN: Regexp REDACTED: String @@ -37,7 +32,6 @@ module ZammadAPI def self.relative_path: (untyped) -> String def self.redact_path: (untyped path) -> String def self.redact: (untyped value) -> untyped - def self.encode_body: (untyped body, operation: String, ?resource_class: Class?) -> String? def initialize: (Config, ?on_behalf_of: String?) -> void def with_on_behalf_of: (String? identifier) -> Transport @@ -49,7 +43,7 @@ module ZammadAPI private def timed_out?: (untyped error) -> bool - def perform: (Symbol, String, Hash[Symbol, untyped]?, String?, Hash[untyped, untyped]?) -> untyped + def perform: (Symbol, String, Hash[Symbol, untyped]?, untyped, Hash[untyped, untyped]?) -> untyped def build_connection: () -> untyped def retry_options: () -> Hash[Symbol, untyped] def apply_authentication: (untyped) -> void diff --git a/spec/support/bare_socket_adapter.rb b/spec/support/bare_socket_adapter.rb deleted file mode 100644 index 6e6f870..0000000 --- a/spec/support/bare_socket_adapter.rb +++ /dev/null @@ -1,46 +0,0 @@ -# frozen_string_literal: true - -require 'faraday' -require 'openssl' - -# A Faraday adapter that lets a socket error out raw. -# -# Most adapters wrap one into Faraday::ConnectionFailed, but this gem lets a -# caller choose the adapter, and an adapter that does not wrap is the only way -# to tell apart the two halves of the retry configuration: which failures are -# mapped to a ZammadAPI error, and which are retried before being mapped. -class BareSocketAdapter < Faraday::Adapter - class << self - # @return [Array] the verb of every request that reached here - attr_accessor :attempts - end - self.attempts = [] - - def call(env) - self.class.attempts << env.method - raise Errno::ECONNRESET - end -end - -Faraday::Adapter.register_middleware(bare_socket: BareSocketAdapter) - -# A Faraday adapter that lets a TLS failure out raw. -# -# The counterpart of BareSocketAdapter for OpenSSL::SSL::SSLError, which most -# adapters wrap into Faraday::SSLError. Unwrapped and unlisted, it escaped -# `request` entirely, past every `rescue ZammadAPI::Error` a caller had -# written. -class BareTlsAdapter < Faraday::Adapter - class << self - # @return [Array] the verb of every request that reached here - attr_accessor :attempts - end - self.attempts = [] - - def call(env) - self.class.attempts << env.method - raise OpenSSL::SSL::SSLError, 'certificate verify failed' - end -end - -Faraday::Adapter.register_middleware(bare_tls: BareTlsAdapter) diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index ec11178..4929d9e 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -64,12 +64,6 @@ expect(described_class.from_env.config.oauth2_token).to eq('oauth') end - it 'prefers ZAMMAD_HTTP_TOKEN over ZAMMAD_TOKEN' do - stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'short', 'ZAMMAD_HTTP_TOKEN' => 'explicit' }) - - expect(described_class.from_env.config.http_token).to eq('explicit') - end - it 'lets an argument win over the environment' do stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' }) @@ -84,12 +78,6 @@ def from(variables) described_class.from_env end - ['', " \n"].each do |blank| - it "reads ZAMMAD_TOKEN past a ZAMMAD_HTTP_TOKEN of #{blank.inspect}" do - expect(from('ZAMMAD_HTTP_TOKEN' => blank).config.http_token).to eq('from-env') - end - end - %w[ZAMMAD_USER ZAMMAD_PASSWORD ZAMMAD_OAUTH2_TOKEN].each do |name| it "does not take a #{name} of a space for a second way to authenticate" do expect(from(name => ' ').config.authentication_scheme).to eq(:http_token) @@ -107,7 +95,7 @@ def from(variables) end it 'strips the whitespace around a token that holds more than that' do - expect(from('ZAMMAD_HTTP_TOKEN' => " padded\n").config.http_token).to eq('padded') + expect(from('ZAMMAD_TOKEN' => " padded\n").config.http_token).to eq('padded') end it 'still takes a password of spaces that is passed in' do diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 8383356..66de493 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -259,11 +259,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) .to raise_error(ZammadAPI::ConfigurationError, 'config retry_interval needs to be a positive number') end - it 'rejects a Numeric that cannot be compared' do - expect { build(timeout: Complex(1, 2)) } - .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') - end - it 'rejects negative retries' do expect { build(retries: -1) } .to raise_error(ZammadAPI::ConfigurationError, 'config retries needs to be a non-negative integer') @@ -335,11 +330,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) end end - it 'refuses a proxy that is not a URL without quoting it' do - expect { build(proxy: 'http://puser:p s3cret@proxy.test:8080') } - .to raise_error(ZammadAPI::ConfigurationError, 'config proxy is not a valid URL') - end - it 'leaves a proxy without credentials alone' do expect(build(proxy: 'http://proxy.test:8080').inspect).to include('proxy="http://proxy.test:8080"') end diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index a4750a6..bdba08d 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -623,25 +623,10 @@ def self.name expect(group.inspect).to include('destroyed=true') end - it 'refuses a save rather than letting it 404' do - expect { group.save }.to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to save/) - end - - it 'refuses a reload rather than resurrecting the record' do - expect { group.reload } - .to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to reload/) - end - - it 'stays destroyed after a refused reload' do - expect { group.reload }.to raise_error(ZammadAPI::Error) - - expect(group).to be_destroyed - expect(group).not_to be_persisted - end + it 'leaves a second destroy to Zammad, which answers 404' do + stub_request(:delete, "#{url}/1").to_return(status: 404, body: '') - it 'refuses a second destroy rather than surfacing Zammad\'s 404' do - expect { group.destroy } - .to raise_error(ZammadAPI::Error, /was destroyed, there is nothing to destroy/) + expect { group.destroy }.to raise_error(ZammadAPI::NotFoundError) end end @@ -659,83 +644,6 @@ def self.name expect(group.name).to eq('Support') expect(group.changes).to eq(name: %w[Users Support]) end - - it 'refuses the association readers, which would request a record that is gone' do - group.destroy - - expect { group.related }.to raise_error(ZammadAPI::Error, /was destroyed/) - end - end - - context 'when an update is attempted after it was destroyed' do - before do - stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') - group.destroy - end - - it 'refuses the update' do - expect { group.update(name: 'Renamed') }.to raise_error(ZammadAPI::Error, /was destroyed/) - end - - it 'refuses the raising update' do - expect { group.update!(name: 'Renamed') }.to raise_error(ZammadAPI::Error, /was destroyed/) - end - - it 'leaves nothing staged behind the refusal' do - begin - group.update(name: 'Renamed') - rescue ZammadAPI::Error - nil - end - - expect(group).not_to be_changed - expect(group.changes).to be_empty - end - - it 'leaves the attributes as they were' do - begin - group.update(name: 'Renamed') - rescue ZammadAPI::Error - nil - end - - expect(group.key?(:name)).to be(false) - end - end - - context 'when an attribute is written after it was destroyed' do - subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'A') } - - before do - stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') - group.destroy - end - - it 'refuses a named writer' do - expect { group.name = 'Z' }.to raise_error(ZammadAPI::Error, /Group 1 was destroyed, there is nothing to change/) - end - - it 'refuses []=' do - expect { group[:name] = 'Z' }.to raise_error(ZammadAPI::Error, /was destroyed/) - end - - it 'refuses assign_attributes' do - expect { group.assign_attributes(name: 'Z') }.to raise_error(ZammadAPI::Error, /was destroyed/) - end - - it 'refuses a writer for an attribute the record never carried' do - expect { group.note = 'Z' }.to raise_error(ZammadAPI::Error, /was destroyed/) - end - - it 'leaves nothing staged behind the refusal' do - expect { group.name = 'Z' }.to raise_error(ZammadAPI::Error) - expect(group).not_to be_changed - end - - it 'leaves the record reading as it last was in Zammad' do - expect { group.assign_attributes(note: 'n', name: 'Z') }.to raise_error(ZammadAPI::Error) - expect(group.to_h).to eq({ id: 1, name: 'A' }) - end end end @@ -817,29 +725,6 @@ def self.name expect(group).not_to eq(user) end - # An id is only unique within one installation. A script that reads two - # of them holds a group 1 from each, and they are two records. - context 'with records of two Zammad instances' do - let(:here) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) } - let(:there) { ZammadAPI::Resources::Group.from_response(unit_transport(url: 'http://other.test/'), id: 1) } - - it 'tells the same id apart' do - expect(here).not_to eq(there) - end - - it 'keeps both through uniq' do - expect([here, there].uniq.size).to eq(2) - end - - it 'keeps both as members of a Set' do - expect(Set[here, there].size).to eq(2) - end - - it 'does not answer for one with the value stored under the other' do - expect({ here => :handled }[there]).to be_nil - end - end - context 'with a record read through two clients for one instance' do let(:record) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) } diff --git a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb index f3e02eb..f892c69 100644 --- a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb @@ -24,15 +24,6 @@ expect(attachment).to eq(article.attachments.first) end - it 'is not the attachment with that id on another Zammad instance' do - elsewhere = ZammadAPI::Resources::TicketArticle - .from_response(unit_transport(url: 'http://other.test/'), article.to_h) - .attachments.first - - expect(attachment).not_to eq(elsewhere) - expect([attachment, elsewhere].uniq.size).to eq(2) - end - it 'carries the filename' do expect(attachment.filename).to eq('note.txt') end diff --git a/spec/unit/zammad_api/resources/ticket_spec.rb b/spec/unit/zammad_api/resources/ticket_spec.rb index a2b632a..6f98734 100644 --- a/spec/unit/zammad_api/resources/ticket_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -33,23 +33,6 @@ end end - describe 'once destroyed' do - let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/42" } - - before do - stub_request(:delete, ticket_url).with(query: hash_including({})).to_return(json_response({})) - ticket.destroy - end - - it 'refuses the articles reader rather than fetching a deleted ticket' do - expect { ticket.articles }.to raise_error(ZammadAPI::Error, /was destroyed/) - end - - it 'refuses the related proxy' do - expect { ticket.related }.to raise_error(ZammadAPI::Error, /was destroyed/) - end - end - describe '#add_article' do it 'creates the article for this ticket' do stub = stub_request(:post, article_url) diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index fcd06b2..730d241 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -73,13 +73,6 @@ expect(zammad.client.with(timeout: 5).on_behalf_of('agent@example.com').config.timeout).to eq(5) end - # A record names its installation by the URL of its transport. - it 'tells a record found through another URL from one of its own' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - - expect(zammad.client.with(url: 'https://other.test/').groups.find(1)).not_to eq(zammad.client.groups.find(1)) - end - it 'still takes two records found through the same derived client as one' do zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) derived = zammad.client.with(timeout: 5) @@ -130,16 +123,6 @@ expect(zammad.requests).to be_empty end - # The same for a body the wire could not carry: a stand-in that took it - # would let a test pass over a save production raises on. - it 'refuses a body that cannot be encoded as JSON, the way the real transport does' do - zammad.stub(:post, 'api/v1/groups', body: { id: 1 }) - - expect { client.groups.create(name: 'Support', weight: Float::NAN) } - .to raise_error(ZammadAPI::Error, /the request body cannot be encoded as JSON/) - expect(zammad.requests).to be_empty - end - it 'raises the mapped error class for a non-2xx status' do zammad.stub(:get, 'api/v1/groups/1', status: 404, body: { error: 'not found' }) diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 17586f6..8b082f2 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -296,50 +296,6 @@ def handed_to_the_adapter(**options) expect(a_request(:post, url).with(body: '{"group":{"id":1,"name":"Users"}}')).to have_been_made end end - - # Faraday's JSON middleware would raise JSON::GeneratorError from inside - # the stack, past the rescue of ZammadAPI::Error every caller is told to - # write. - context 'with a body that cannot be encoded as JSON' do - let(:binary) { { data: "\xFF\xD8\xFF".b } } - - it 'raises a ZammadAPI::Error for bytes that are not text' do - expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary) } - .to raise_error(ZammadAPI::Error, /\ACan't save object: the request body cannot be encoded as JSON/) - end - - it 'raises a ZammadAPI::Error for a Float that JSON has no spelling for' do - expect { unit_transport.put('api/v1/groups/1', operation: 'save object', body: { weight: Float::NAN }) } - .to raise_error(ZammadAPI::Error, /\ACan't save object: the request body cannot be encoded as JSON/) - end - - it 'carries no cause, whose report would quote the value' do - expect { unit_transport.post('api/v1/groups', operation: 'save object', body: { password: "s3cret\xFF" }) } - .to raise_error(ZammadAPI::Error) { |error| expect(error.full_message(highlight: false)).not_to include('s3cret') } - end - - it 'names the resource it was sending' do - expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary, resource_class: ZammadAPI::Resources::Group) } - .to raise_error(ZammadAPI::Error, /save object \(ZammadAPI::Resources::Group\)/) - end - - it 'makes no request' do - expect { unit_transport.post('api/v1/groups', operation: 'save object', body: binary) }.to raise_error(ZammadAPI::Error) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'leaves no log line claiming a request that was never made' do - log = StringIO.new - expect { unit_transport(logger: Logger.new(log)).post('api/v1/groups', operation: 'save object', body: binary) } - .to raise_error(ZammadAPI::Error) - expect(log.string).to be_empty - end - - it 'is raised by a record save carrying such a value' do - group = unit_client.groups.new(name: 'Support', weight: Float::INFINITY) - expect { group.save }.to raise_error(ZammadAPI::Error, /cannot be encoded as JSON/) - end - end end describe 'response decoding' do @@ -472,41 +428,6 @@ def handed_to_the_adapter(**options) .to raise_error(ZammadAPI::ConnectionError, %r{http://zammad\.test/ is unreachable}) end - context 'with an adapter that does not wrap socket errors' do - # The middleware seam raises from inside the stack, past the point where - # an adapter would normally translate the error into a Faraday one. - def raising(error) - unit_transport(middleware: lambda { |faraday| - faraday.use(Class.new(Faraday::Middleware) { define_method(:call) { |_env| raise error } }) - }) - end - - it 'wraps a bare Errno::ETIMEDOUT' do - expect { raising(Errno::ETIMEDOUT).get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::TimeoutError, /timed out/) - end - - it 'wraps a bare Timeout::Error' do - expect { raising(Timeout::Error).get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::TimeoutError) - end - - it 'wraps a bare Errno::ECONNREFUSED' do - expect { raising(Errno::ECONNREFUSED).get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::ConnectionError, /is unreachable/) - end - - it 'wraps a SocketError' do - expect { raising(SocketError).get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::ConnectionError) - end - - it 'leaves an unrelated Errno alone rather than calling it a network problem' do - expect { raising(Errno::ENOSPC).get('api/v1/groups', operation: 'find object') } - .to raise_error(Errno::ENOSPC) - end - end - it 'raises a TransportError subclass so both can be rescued together' do stub_request(:get, url).to_raise(Errno::ECONNREFUSED) expect { unit_transport.get('api/v1/groups', operation: 'find object') } @@ -616,41 +537,6 @@ def raising(error) end end - # Most adapters wrap a socket failure into Faraday::ConnectionFailed. One - # that does not is retried as often. - describe 'retries through an adapter that does not wrap socket errors' do - before { BareSocketAdapter.attempts = [] } - - def bare_socket_transport(**overrides) - unit_transport(adapter: :bare_socket, retry_interval: 0.01, **overrides) - end - - it 'retries an unwrapped socket error as often as a wrapped one' do - expect { bare_socket_transport(retries: 2).get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::ConnectionError) - expect(BareSocketAdapter.attempts.size).to eq(3) - end - - it 'still maps it to ConnectionError once the retries are spent' do - expect { bare_socket_transport(retries: 1).get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::ConnectionError, /is unreachable/) - end - - it 'does not repeat a POST, which could duplicate records' do - expect { bare_socket_transport(retries: 2).post('api/v1/groups', operation: 'test', body: { a: 1 }) } - .to raise_error(ZammadAPI::ConnectionError) - expect(BareSocketAdapter.attempts).to eq([:post]) - end - - it 'retries every socket failure it maps to ConnectionError' do - expect(described_class::RETRIABLE_EXCEPTIONS).to include(*described_class::CONNECTION_ERRORS) - end - - it 'retries every socket failure it maps to TimeoutError' do - expect(described_class::RETRIABLE_EXCEPTIONS).to include(*described_class::TIMEOUT_ERRORS) - end - end - describe 'the Faraday seam' do it 'calls the middleware with the connection being built' do seen = nil @@ -950,7 +836,6 @@ def bare_socket_transport(**overrides) operation: 'test', body: { login: 'jane', - keyboard_layout: 'de', password_confirm: 'confirm-s3cret', passwd: 'passwd-s3cret', access_token: 'access-s3cret', @@ -991,12 +876,6 @@ def bare_socket_transport(**overrides) expect(log).not_to include('passwd-s3cret') end - # Matched as a word, so that a key merely containing the letters stays - # readable in the log rather than being blanked for nothing. - it 'leaves a key whose name only contains one of the words alone' do - expect(log).to include('keyboard_layout: "de"') - end - it 'redacts a client_secret' do expect(log).not_to include('client-s3cret') end @@ -1015,12 +894,8 @@ def bare_socket_transport(**overrides) end end - # Matched as words, so that a key merely containing the letters stays - # readable. - %w[footprint basalt hotKeyboard Keyboard monkey_id bind_user].each do |name| - it "leaves #{name} alone" do - expect(described_class.redact({ name => 'shown' })).to eq({ name => 'shown' }) - end + it 'leaves bind_user alone' do + expect(described_class.redact({ 'bind_user' => 'shown' })).to eq({ 'bind_user' => 'shown' }) end it 'redacts a bind password inside the preferences of an LDAP source' do @@ -1144,36 +1019,4 @@ def bare_socket_transport(**overrides) end end end - - # Through an adapter that does not wrap OpenSSL::SSL::SSLError into - # Faraday::SSLError. - describe 'a TLS failure through an adapter that does not wrap it' do - before { BareTlsAdapter.attempts = [] } - - def bare_tls_transport(**overrides) - unit_transport(adapter: :bare_tls, retry_interval: 0.01, **overrides) - end - - it 'maps it to ConnectionError rather than letting it out raw' do - expect { bare_tls_transport.get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::ConnectionError, /TLS handshake with .* failed/) - end - - it 'is catchable as the gem error every caller rescues' do - expect { bare_tls_transport.get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::Error) - end - - # A rejected certificate is a fact about the instance, not a transient - # failure: retrying only delays the error by the backoff. - it 'does not retry it' do - expect { bare_tls_transport(retries: 2).get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::ConnectionError) - expect(BareTlsAdapter.attempts.size).to eq(1) - end - - it 'keeps the unwrapped TLS error out of the retry list' do - expect(described_class::RETRIABLE_EXCEPTIONS).not_to include(*described_class::SSL_ERRORS) - end - end end From 82e27e298f87f2a1f60b4f70005a3697f9f23f53 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 25 Nov 2026 00:25:45 +0200 Subject: [PATCH 088/121] refactor!: drop has_many and the open-timeout reclassification A third pass over the 2.0 client for straightforward API usage. lib/ goes from 2,688 to 2626 lines. - An open timeout raises ConnectionError, as Faraday reports it, rather than being dug out of Faraday::ConnectionFailed to raise TimeoutError. Both are TransportError, and a GET is still retried. - The has_many declaration goes: Ticket#articles was its one use, and it now reads api/v1/ticket_articles/by_ticket/ itself. related keeps belongs_to; ticket.related.articles is gone, ticket.articles stays. - client.resource(SomeClass) builds the proxy without checking the class or its path first; a wrong one fails on the first request. - Client#raw leaves the path to Transport#request, which normalises it. - ResponseError.build no longer takes a nil response, which nothing in lib/ passed. --- CHANGELOG.md | 13 ++-- README.md | 22 +++---- lib/zammad_api/associations.rb | 25 +------- lib/zammad_api/client.rb | 25 +------- lib/zammad_api/errors.rb | 9 ++- lib/zammad_api/resources/base.rb | 14 +---- lib/zammad_api/resources/ticket.rb | 13 ++-- lib/zammad_api/transport.rb | 18 +----- sig/zammad_api/associations.rbs | 6 +- sig/zammad_api/client.rbs | 1 - sig/zammad_api/errors.rbs | 4 +- sig/zammad_api/resources/base.rbs | 1 - sig/zammad_api/transport.rbs | 2 - .../zammad_api/associations/proxy_spec.rb | 61 +------------------ spec/unit/zammad_api/client_spec.rb | 11 ---- spec/unit/zammad_api/resources/ticket_spec.rb | 25 +++++++- spec/unit/zammad_api/response_error_spec.rb | 8 +-- spec/unit/zammad_api/transport_spec.rb | 23 +------ 18 files changed, 70 insertions(+), 211 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5462489..4096e63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,7 +114,7 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a raises `ArgumentError`, so the credentials stay with the configured instance. - Request and connection timeouts (`timeout`, `open_timeout`), on by default at 60 and 10 seconds. 1.x waited as long as the server took, so a call that used to hang now - raises `TimeoutError`. + raises `TimeoutError`, or `ConnectionError` when the connection is not opened in time. - Automatic retry with exponential backoff for a `GET` on connection failures, timeouts and the statuses 429, 500, 502, 503 and 504. A `Retry-After` within `timeout` is honoured, and a longer one ends the retries. A write is never retried: a repeated ticket @@ -192,10 +192,9 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `Response#decoded(:object | :array)` checks the shape of a response body in one place, so an unexpected payload raises `ParseError`. - `record.related` reaches the records a record points at: `ticket.related.customer`, - `ticket.related.group`, `ticket.related.articles`, `user.related.organization`, and - `created_by` / `updated_by` on everything. The readers sit under `related` because - Zammad expands an association into a name under the plain attribute, and - `ticket.customer` keeps returning that name. `Resource.associations` lists what a + `ticket.related.group`, `user.related.organization`, and `created_by` / `updated_by` on + everything. The readers sit under `related` because Zammad expands an association into + a name under the plain attribute, and `ticket.customer` keeps returning that name. `Resource.associations` lists what a resource declares. - Records compare as the Zammad records they came from: two records of the same kind with the same id are equal, and `#hash` agrees, so `uniq`, `Set`, `include?` and records as @@ -206,8 +205,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `client.resource(SomeClass)` takes a subclass of `ZammadAPI::Resources::Base` and answers with a proxy for it, so an endpoint this gem does not model gets records, pagination, `find_by`, change tracking and `save` from a class that declares its `path`. `searchable`, - `max_per_page`, `sortable`, `paginated`, `belongs_to` and `has_many` say what else is - true of the endpoint. + `max_per_page`, `sortable`, `paginated` and `belongs_to` say what else is true of the + endpoint. - Typed records. `ResourceProxy` and `Collection` are generic over the resource they hold, so `client.tickets` is a `ResourceProxy[Resources::Ticket]` and `find`, `first`, `find_by`, the block of `each` and a search all answer with a `Ticket`. Each resource diff --git a/README.md b/README.md index 91f6c66..890018d 100644 --- a/README.md +++ b/README.md @@ -299,7 +299,6 @@ Say what else is true of the endpoint, where it differs from the defaults: | `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. | | `paginated false` | `true` | The index endpoint serves every record in one response and reads no `page`. It is read in one request, and `page` refuses it. | | `belongs_to :role, class_name: 'Role'` | — | A foreign key, read as a record through `record.related.role`. | -| `has_many :members, class_name: 'User', path: ->(id) { "…/#{id}" }` | — | A list served whole by an endpoint of its own. | `class_name` is a resource of this gem by its own name, `'User'`, or a class of yours by its full name, `'Acme::Role'`. A subclass of a modelled resource works too, and inherits what @@ -565,27 +564,23 @@ ticket.customer_id # => 7 ```ruby ticket.related.customer.firstname # => "Nicole" ticket.related.group.note -ticket.related.articles # => [TicketArticle, ...] ticket.related.created_by.email client.users.find(7).related.organization ``` -A `has_many` reader such as `articles` is read in a single request and comes back as an -Array rather than a paginating collection, because the association endpoints Zammad routes -serve the whole list. - -A ticket's articles are also reachable without `related`, and `add_article` writes one: +A ticket's articles come from an endpoint of their own. `articles` reads the whole list in +one request, as an Array, and `add_article` writes one: ```ruby -ticket.articles # the same list +ticket.articles # => [TicketArticle, ...] ticket.add_article(body: 'Reset link sent.', type: 'note') # => the created TicketArticle ``` The readers live under `related` rather than on the record so that `ticket.customer` keeps returning the name it always did — an attribute read that silently became an HTTP request -would be a poor trade. `belongs_to` targets are memoized until the next attribute write, -`reload` or save; `has_many` lists are fetched on each call, so an article added in between +would be a poor trade. `related` targets are memoized until the next attribute write, +`reload` or save; `articles` is fetched on each call, so an article added in between shows up. `Ticket.associations` lists what a resource declares. ### Comparing and serializing @@ -875,8 +870,8 @@ ZammadAPI::Error ├── ZammadAPI::ParseError unexpected response shape ├── ZammadAPI::PaginationError endpoint ignored the page parameter ├── ZammadAPI::TransportError -│ ├── ZammadAPI::ConnectionError unreachable host or TLS failure -│ └── ZammadAPI::TimeoutError exceeded timeout or open_timeout +│ ├── ZammadAPI::ConnectionError unreachable host, TLS failure or open_timeout +│ └── ZammadAPI::TimeoutError exceeded timeout └── ZammadAPI::ResponseError carries the HTTP response ├── ZammadAPI::ClientError 4xx │ ├── ZammadAPI::AuthenticationError 401 @@ -1253,7 +1248,8 @@ roughly a tenth of the round trips. `page(n)` without `per_page:` is a page of t it with `page(n, per_page: 100)` if a persisted page number has to keep meaning what it did. A request now times out after 60 seconds (10 to connect) where 1.x waited as long as the -server took, so a call that used to hang raises `ZammadAPI::TimeoutError`. A `GET` is +server took, so a call that used to hang raises `ZammadAPI::TimeoutError` (or +`ZammadAPI::ConnectionError` when the connection is not opened in time). A `GET` is retried twice with exponential backoff on connection failures, timeouts and the transient statuses, which means a genuinely broken endpoint takes a little longer to report itself; a `POST`, `PUT` or `DELETE` is never retried. Both are options — see diff --git a/lib/zammad_api/associations.rb b/lib/zammad_api/associations.rb index a94869a..e698fcb 100644 --- a/lib/zammad_api/associations.rb +++ b/lib/zammad_api/associations.rb @@ -1,8 +1,5 @@ # frozen_string_literal: true -require_relative 'errors' -require_relative 'transport' - module ZammadAPI # Readers for the records a record points at. module Associations @@ -21,8 +18,6 @@ module Associations # ticket.customer # => "customer@example.com", already loaded # ticket.related.customer # => the User record, one request # ticket.related.customer.email # => "customer@example.com" - # - # ticket.related.articles # => [TicketArticle, ...] class Proxy # @api private # @param record [Resources::Base] @@ -48,7 +43,7 @@ def method_missing(name, *args) spec = associations[name] return super if spec.nil? || !args.empty? - spec[:type] == :belongs_to ? belongs_to_target(name, spec) : has_many_target(name, spec) + target(name, spec) end def respond_to_missing?(name, include_private = false) = associations.key?(name) || super @@ -59,29 +54,13 @@ def associations = @record.class.associations # The record a foreign key points at, read once and kept: nil when the # key is nil. - def belongs_to_target(name, spec) + def target(name, spec) return @cache[name] if @cache.key?(name) id = @record[spec[:foreign_key]] @cache[name] = id.nil? ? nil : resolve(spec[:class_name]).fetch_one(@record.transport, id) end - # The list an association endpoint serves, read anew on every call. - def has_many_target(name, spec) - raise Error, "#{@record.class.name} has no id, so it has no #{name} to read; save it first" if @record.id.nil? - - target_class = resolve(spec[:class_name]) - operation = "get #{name}" - response = @record.transport.get( - spec[:path].call(Transport.escape_path_segment(@record.id)), - operation: operation, - resource_class: target_class, - query: { expand: true } - ) - - response.decoded(:array, operation: operation, resource_class: target_class).map { target_class.from_response(@record.transport, it) } - end - # A resource of this gem by its own name, or any class by its full name. def resolve(class_name) return Resources.const_get(class_name, false) if Resources.const_defined?(class_name, false) diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index 4b89975..e0699c5 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -137,10 +137,8 @@ def initialize(**options) # of {Resources::Base} # @return [ResourceProxy] # @raise [UnknownResourceError] when no resource has that name - # @raise [ArgumentError] for a class that is not a resource - # @raise [Error] for a resource class that declares no path def resource(name) - return proxy_for(name) if name.is_a?(Class) + return @resources.fetch(name) { ResourceProxy.new(@transport, name) } if name.is_a?(Class) resource_class = RESOURCES.fetch(name.to_sym) { raise UnknownResourceError, unknown_resource_message(name) } @@ -298,29 +296,12 @@ def respond_to_missing?(_name, _include_private = false) = false private def raw(method, path, query: nil, body: nil, headers: nil) - relative = Transport.relative_path(path) - - @transport.request( - method, - relative, - operation: "#{method.to_s.upcase} #{Transport.redact_path(relative)}", - query: query, - body: body, - headers: headers - ) + operation = "#{method.to_s.upcase} #{Transport.redact_path(path)}" + @transport.request(method, path, operation: operation, query: query, body: body, headers: headers) end def unknown_resource_message(name) = "Unknown resource #{name}, available resources are: #{RESOURCES.keys.join(', ')}" - def proxy_for(resource_class) - raise ArgumentError, "resource takes the name of a resource or a subclass of #{Resources::Base.name}, and #{resource_class.inspect} is neither" if !(resource_class <= Resources::Base) - - @resources.fetch(resource_class) do - resource_class.resource_path - ResourceProxy.new(@transport, resource_class) - end - end - # Everything a client is, in the one place {.new}, {.build}, {#with} and # {#on_behalf_of} go through. The proxies are built up front so that a # client is immutable, and safe to share between threads, once built. diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index 745f0e6..bfbb8a1 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -28,10 +28,11 @@ class UnknownResourceError < Error; end class TransportError < Error; end # Raised when the connection to the Zammad instance could not be - # established: DNS, a refused connection, a TLS failure. + # established: DNS, a refused connection, a TLS failure, or no connection + # within {Config#open_timeout}. class ConnectionError < TransportError; end - # Raised when a request exceeded {Config#open_timeout} or {Config#timeout}. + # Raised when a response took longer than {Config#timeout}. class TimeoutError < TransportError; end # Raised when a response did not have the shape the caller expected. @@ -77,7 +78,7 @@ class ResponseError < Error # Returns the most specific error class for +response+ and instantiates it. # - # @param response [Response, nil] + # @param response [Response] # @param operation [String] # @param resource_class [Class, nil] # @return [ResponseError] @@ -91,8 +92,6 @@ def self.build(response, operation:, resource_class: nil) # @api private def self.error_class_for(response) - return self if response.nil? - STATUS_ERRORS.fetch(response.status) do response.status >= 500 ? ServerError : ClientError end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index b44b0d9..42834be 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -164,19 +164,7 @@ def declared_associations = @declared_associations ||= {} # @param foreign_key [Symbol] attribute holding the target's id # @return [void] def belongs_to(name, class_name:, foreign_key: :"#{name}_id") - declared_associations[name] = { type: :belongs_to, class_name: class_name, foreign_key: foreign_key } - end - - # Declares that this resource points at a list of other records, served - # whole by an endpoint of its own. Read through +record.related.+. - # - # @param name [Symbol] name of the reader on {Base#related} - # @param class_name [String] the target resource - # @param path [Proc] called with the record id, already escaped for - # a path segment, and returns the API path - # @return [void] - def has_many(name, class_name:, path:) - declared_associations[name] = { type: :has_many, class_name: class_name, path: path } + declared_associations[name] = { class_name: class_name, foreign_key: foreign_key } end end diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index 7bf0bb1..0edebc0 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -25,14 +25,17 @@ class Ticket < Base belongs_to :state, class_name: 'TicketState' belongs_to :priority, class_name: 'TicketPriority' - has_many :articles, class_name: 'TicketArticle', path: ->(id) { "api/v1/ticket_articles/by_ticket/#{id}" } - - # Every article of this ticket, refetched on each call: the same list as - # +ticket.related.articles+. + # Every article of this ticket, read in one request on each call. # # @return [Array] + # @raise [Error] when the ticket has no id yet # @raise [ResponseError] when Zammad rejected the request - def articles = related.articles + def articles + path = "#{TicketArticle.resource_path}/by_ticket/#{Transport.escape_path_segment(require_id!)}" + response = transport.get(path, operation: 'get articles', resource_class: TicketArticle, query: { expand: true }) + + response.decoded(:array, operation: 'get articles', resource_class: TicketArticle).map { TicketArticle.from_response(transport, it) } + end # Adds an article to this ticket. # diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 31a084d..d8a0df3 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -2,7 +2,6 @@ require 'faraday' require 'faraday/retry' -require 'timeout' require 'uri' require_relative 'errors' @@ -43,10 +42,6 @@ module Verbs # Statuses a read is retried on. RETRIABLE_STATUSES = [429, 500, 502, 503, 504].freeze - # Errors that mean the request timed out, found inside the - # Faraday::ConnectionFailed an adapter wraps an open timeout into. - TIMEOUT_ERRORS = [Errno::ETIMEDOUT, Timeout::Error].freeze - # Errors a read is retried on. The adapter wraps socket and TLS errors # into Faraday's own classes. RETRIABLE_EXCEPTIONS = [Faraday::RetriableResponse, Faraday::ConnectionFailed, Faraday::TimeoutError].freeze @@ -168,8 +163,9 @@ def inspect # @param resource_class [Class, nil] used in error messages # @return [Response] # @raise [ResponseError] for non-2xx responses - # @raise [TimeoutError] when the request timed out - # @raise [ConnectionError] when the instance was unreachable + # @raise [TimeoutError] when the response took longer than {Config#timeout} + # @raise [ConnectionError] when the instance was unreachable, including + # a connection not opened within {Config#open_timeout} def request(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) path = Transport.relative_path(path) log_request(method, path, query, body, headers) @@ -185,19 +181,11 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou rescue Faraday::SSLError => e raise ConnectionError, "Can't #{operation}: TLS handshake with #{config.url} failed (#{e.message})" rescue Faraday::ConnectionFailed => e - raise TimeoutError, "Can't #{operation}: connecting to #{config.url} timed out (#{e.message})" if timed_out?(e) - raise ConnectionError, "Can't #{operation}: #{config.url} is unreachable (#{e.message})" end private - # Whether a connection failure is a timeout underneath: the default - # adapter wraps an exceeded +open_timeout+ into Faraday::ConnectionFailed. - def timed_out?(error) - [error.wrapped_exception, error.cause].any? { |inner| TIMEOUT_ERRORS.any? { inner.is_a?(it) } } - end - # The connection's :json middleware encodes a Hash or Array body. def perform(method, path, query, body, headers) @connection.public_send(method, path) do |request| diff --git a/sig/zammad_api/associations.rbs b/sig/zammad_api/associations.rbs index 3aebf29..3544661 100644 --- a/sig/zammad_api/associations.rbs +++ b/sig/zammad_api/associations.rbs @@ -1,7 +1,7 @@ module ZammadAPI module Associations # The readers are answered through method_missing, from the belongs_to - # and has_many declarations in lib/zammad_api/resources. The ones this gem + # declarations in lib/zammad_api/resources. The ones this gem # declares are listed here so that callers get types and completion; every # name means the same target wherever it is declared, so the type of a # given reader is accurate. The class is wider than any one resource, so @@ -26,13 +26,11 @@ module ZammadAPI def state: () -> Resources::TicketState? def priority: () -> Resources::TicketPriority? def ticket: () -> Resources::Ticket? - def articles: () -> Array[Resources::TicketArticle] private def associations: () -> Hash[Symbol, Hash[Symbol, untyped]] - def belongs_to_target: (Symbol name, Hash[Symbol, untyped] spec) -> untyped - def has_many_target: (Symbol name, Hash[Symbol, untyped] spec) -> Array[untyped] + def target: (Symbol name, Hash[Symbol, untyped] spec) -> untyped def resolve: (String class_name) -> untyped end end diff --git a/sig/zammad_api/client.rbs b/sig/zammad_api/client.rbs index 0ac96c6..866ca9b 100644 --- a/sig/zammad_api/client.rbs +++ b/sig/zammad_api/client.rbs @@ -48,7 +48,6 @@ module ZammadAPI def raw: (Symbol method, String path, ?query: Hash[untyped, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?) -> Response def unknown_resource_message: (Symbol | String) -> String - def proxy_for: (untyped resource_class) -> ResourceProxy[untyped] def setup: (Config config, untyped transport) -> self end end diff --git a/sig/zammad_api/errors.rbs b/sig/zammad_api/errors.rbs index 2b255eb..254b949 100644 --- a/sig/zammad_api/errors.rbs +++ b/sig/zammad_api/errors.rbs @@ -35,8 +35,8 @@ module ZammadAPI @detail: String? - def self.build: (Response? response, operation: String, ?resource_class: Class?) -> ResponseError - def self.error_class_for: (Response?) -> singleton(ResponseError) + def self.build: (Response response, operation: String, ?resource_class: Class?) -> ResponseError + def self.error_class_for: (Response) -> singleton(ResponseError) def initialize: (operation: String, ?response: Response?, ?resource_class: Class?, ?detail: String?) -> void def status: () -> Integer? diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 9e27f80..7019f4f 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -50,7 +50,6 @@ module ZammadAPI | (Symbol name) -> untyped def self.declared_associations: () -> Hash[Symbol, Hash[Symbol, untyped]] def self.belongs_to: (Symbol name, class_name: String, ?foreign_key: Symbol) -> void - def self.has_many: (Symbol name, class_name: String, path: ^(String) -> String) -> void def initialize: (Transport, ?hash[untyped, untyped]? attributes) -> void def new_record?: () -> bool diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index f05a771..6adb519 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -15,7 +15,6 @@ module ZammadAPI RETRIABLE_METHODS: Array[Symbol] RETRIABLE_STATUSES: Array[Integer] - TIMEOUT_ERRORS: Array[untyped] RETRIABLE_EXCEPTIONS: Array[untyped] SENSITIVE_KEY_PATTERN: Regexp REDACTED: String @@ -42,7 +41,6 @@ module ZammadAPI private - def timed_out?: (untyped error) -> bool def perform: (Symbol, String, Hash[Symbol, untyped]?, untyped, Hash[untyped, untyped]?) -> untyped def build_connection: () -> untyped def retry_options: () -> Hash[Symbol, untyped] diff --git a/spec/unit/zammad_api/associations/proxy_spec.rb b/spec/unit/zammad_api/associations/proxy_spec.rb index d1d8bd4..cf40862 100644 --- a/spec/unit/zammad_api/associations/proxy_spec.rb +++ b/spec/unit/zammad_api/associations/proxy_spec.rb @@ -101,65 +101,6 @@ end end - describe 'has_many' do - let(:articles_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_articles/by_ticket/42" } - - it 'fetches the list from the association endpoint' do - stub_request(:get, articles_url).with(query: { 'expand' => 'true' }) - .to_return(json_response([{ id: 1, body: 'first' }])) - - expect(ticket.related.articles.map(&:body)).to eq(['first']) - end - - it 'returns records of the target class' do - stub_request(:get, articles_url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) - - expect(ticket.related.articles.first).to be_a(ZammadAPI::Resources::TicketArticle) - end - - it 'is not memoized, so an article added afterwards shows up' do - stub_request(:get, articles_url).with(query: hash_including({})) - .to_return(json_response([{ id: 1 }]), json_response([{ id: 1 }, { id: 2 }])) - - held = ticket - expect(held.related.articles.size).to eq(1) - expect(held.related.articles.size).to eq(2) - end - - it 'names the association in a parse failure' do - stub_request(:get, articles_url).with(query: hash_including({})).to_return(json_response({ id: 1 })) - - expect { ticket.related.articles } - .to raise_error(ZammadAPI::ParseError, /Can't get articles \(ZammadAPI::Resources::TicketArticle\)/) - end - - it 'reads the whole list in one request' do - stub_request(:get, articles_url).with(query: hash_including({})) - .to_return(json_response([{ id: 1 }, { id: 2 }])) - - expect(ticket.related.articles.size).to eq(2) - end - - it 'says to save an unsaved record rather than requesting a path without an id' do - unsaved = ZammadAPI::Resources::Ticket.new(unit_transport, title: 'Help') - - expect { unsaved.related.articles } - .to raise_error(ZammadAPI::Error, /has no id, so it has no articles to read; save it first/) - end - - it 'escapes a traversal in the id instead of reaching another endpoint' do - escaped = "#{ClientHelper::BASE_URL}api/v1/ticket_articles/by_ticket/1%2F..%2F..%2Fusers" - stub = stub_request(:get, escaped).with(query: hash_including({})).to_return(json_response([])) - escaping = ZammadAPI::Resources::Ticket.from_response(unit_transport, id: '1/../../users') - - escaping.related.articles - - expect(stub).to have_been_requested - expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/users").with(query: hash_including({}))) - .not_to have_been_made - end - end - describe 'inheritance' do it 'gives every resource the stamps Zammad puts on every object' do expect(ZammadAPI::Resources::Group.associations.keys).to eq(%i[created_by updated_by]) @@ -320,7 +261,7 @@ expect(ticket.related.inspect) .to eq( '#' + 'created_by, updated_by, customer, owner, organization, group, state, priority>' ) end end diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index 4929d9e..f85e1a2 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -354,17 +354,6 @@ def from(variables) it 'leaves the client as it was built' do expect { client.resource(Role) }.not_to(change { client.instance_variable_get(:@resources).size }) end - - it 'refuses a class that is not a resource' do - expect { client.resource(String) } - .to raise_error(ArgumentError, /resource takes the name of a resource or a subclass of ZammadAPI::Resources::Base, and String is neither/) - end - - it 'refuses a resource class that declares no path' do - stub_const('Pathless', Class.new(ZammadAPI::Resources::Base)) - - expect { client.resource(Pathless) }.to raise_error(ZammadAPI::Error, /Pathless does not declare an API path/) - end end it 'raises for a singular name from 1.x' do diff --git a/spec/unit/zammad_api/resources/ticket_spec.rb b/spec/unit/zammad_api/resources/ticket_spec.rb index 6f98734..f8163c9 100644 --- a/spec/unit/zammad_api/resources/ticket_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -29,7 +29,30 @@ it 'raises ParseError when the response is not a list' do stub_request(:get, articles_url).with(query: hash_including({})).to_return(json_response({ id: 1 })) - expect { ticket.articles }.to raise_error(ZammadAPI::ParseError, /expected a JSON array, got Hash/) + expect { ticket.articles } + .to raise_error(ZammadAPI::ParseError, /Can't get articles \(ZammadAPI::Resources::TicketArticle\): expected a JSON array, got Hash/) + end + + it 'reads the list again on each call, so an article added in between shows up' do + stub_request(:get, articles_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1 }]), json_response([{ id: 1 }, { id: 2 }])) + + expect([ticket.articles.size, ticket.articles.size]).to eq([1, 2]) + end + + it 'says to save an unsaved ticket rather than requesting a path without an id' do + unsaved = described_class.new(unit_transport, title: 'Help') + + expect { unsaved.articles }.to raise_error(ZammadAPI::Error, /Ticket has no id, save it first/) + end + + it 'escapes a traversal in the id instead of reaching another endpoint' do + escaped = "#{ClientHelper::BASE_URL}api/v1/ticket_articles/by_ticket/1%2F..%2F..%2Fusers" + stub = stub_request(:get, escaped).with(query: hash_including({})).to_return(json_response([])) + + described_class.from_response(unit_transport, id: '1/../../users').articles + + expect(stub).to have_been_requested end end diff --git a/spec/unit/zammad_api/response_error_spec.rb b/spec/unit/zammad_api/response_error_spec.rb index d85822a..9b56d67 100644 --- a/spec/unit/zammad_api/response_error_spec.rb +++ b/spec/unit/zammad_api/response_error_spec.rb @@ -59,10 +59,6 @@ def response(status, body, headers = {}) expect(result).to be_an_instance_of(error_class) end end - - it 'falls back to the base class without a response' do - expect(described_class.build(nil, operation: 'find object')).to be_an_instance_of(described_class) - end end describe '#message' do @@ -103,7 +99,7 @@ def response(status, body, headers = {}) end it 'reports a missing response' do - expect(described_class.build(nil, operation: 'find object').message) + expect(described_class.new(operation: 'find object').message) .to eq("Can't find object: no response") end @@ -147,7 +143,7 @@ def response(status, body, headers = {}) end it 'returns nil accessors without a response' do - bare = described_class.build(nil, operation: 'find object') + bare = described_class.new(operation: 'find object') expect([bare.status, bare.body, bare.headers, bare.server_message]).to eq([nil, nil, {}, nil]) end diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 8b082f2..313dea1 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -380,35 +380,18 @@ def handed_to_the_adapter(**options) context 'when the connection is not established within open_timeout' do before { stub_request(:get, url).to_raise(Net::OpenTimeout.new('execution expired')) } - it 'raises TimeoutError, not ConnectionError' do + it 'raises ConnectionError, as Faraday reports it' do expect { unit_transport.get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::TimeoutError) - end - - it 'says it was the connection that timed out' do - expect { unit_transport.get('api/v1/groups', operation: 'find object') } - .to raise_error(%r{Can't find object: connecting to http://zammad\.test/ timed out \(execution expired\)}) + .to raise_error(ZammadAPI::ConnectionError, %r{Can't find object: http://zammad\.test/ is unreachable \(execution expired\)}) end it 'is still retried, as a read that never reached the server' do expect { unit_transport(retries: 2, retry_interval: 0.01).get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::TimeoutError) + .to raise_error(ZammadAPI::ConnectionError) expect(a_request(:get, url)).to have_been_made.times(3) end end - it 'reports the timeout WebMock simulates as one' do - stub_request(:get, url).to_timeout - expect { unit_transport.get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::TimeoutError) - end - - it 'reads a timeout out of a connection failure that only wraps one' do - stub_request(:get, url).to_raise(Faraday::ConnectionFailed.new(Errno::ETIMEDOUT.new)) - expect { unit_transport.get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::TimeoutError, /connecting to/) - end - it 'wraps a refused connection' do stub_request(:get, url).to_raise(Errno::ECONNREFUSED) expect { unit_transport.get('api/v1/groups', operation: 'find object') } From ce76b1f7eb7592e4e955fad7b2ee8280bae86f48 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 25 Nov 2026 00:31:48 +0200 Subject: [PATCH 089/121] docs: trim two examples to everyday scripts manual_batches.rb keeps its three ways to drive pagination by hand, with a plain checkpoint file in place of one named by a hash of the instance, user, path and page size, the atomic rename, and the essay on records deleted mid-walk. onboard_customer.rb is find-or-create for the organization and the user, then the ticket as that user, without the check that an existing user belongs to the organization. pagination.rb printed "immutable false": it showed whether page(2) was the same object as the collection. It now shows that it is a new one. --- examples/manual_batches.rb | 81 +++++------------------------------- examples/onboard_customer.rb | 44 ++++---------------- examples/pagination.rb | 6 +-- 3 files changed, 21 insertions(+), 110 deletions(-) diff --git a/examples/manual_batches.rb b/examples/manual_batches.rb index b202365..53bdd67 100755 --- a/examples/manual_batches.rb +++ b/examples/manual_batches.rb @@ -8,31 +8,19 @@ # bundle exec ruby examples/manual_batches.rb require 'zammad_api' -require 'digest' require 'fileutils' require 'tmpdir' PER_PAGE = 50 +CURSOR = File.join(Dir.tmpdir, 'zammad_batch_cursor') client = ZammadAPI::Client.from_env tickets = client.tickets.all -# Where the loop in part 3 keeps its checkpoint. A page number says which -# tickets come next only together with the instance it was counted on, the -# user whose tickets they are - the index serves what that user may read - -# the list it pages and the size of the pages, so the file is named for all -# of them. Under one name for every run, a job stopped at page 4 of one -# Zammad had the next run against another start at page 4 there, with the -# first three pages never read - and remove the first job's checkpoint when -# it finished. The user costs a request to look up. -JOB = Digest::SHA256.hexdigest("#{client.config.url} #{client.me.id} api/v1/tickets #{PER_PAGE}")[0, 16] -CURSOR = File.join(Dir.tmpdir, "zammad_batch_cursor_#{JOB}") -NEXT_CURSOR = "#{CURSOR}.next".freeze - # 1. Pull a page when you are ready for it ----------------------------------- # # `in_batches` without a block is an Enumerator: nothing is fetched until -# `next`, and each `next` costs exactly one request. +# `next`, and each `next` costs one request. puts '1. pulling two pages, leaving the rest unfetched' @@ -45,8 +33,6 @@ end # 2. Numbered batches -------------------------------------------------------- -# -# `with_index` is Ruby's own, and works for the same reason: an Enumerator. puts '2. every batch, numbered' @@ -57,48 +43,13 @@ # 3. A resumable page loop --------------------------------------------------- # # Own the page number when the job has to survive being interrupted. The -# loop ends on a page with nothing on it rather than on one short of -# PER_PAGE, at the cost of one more request at the end, so an instance that -# serves fewer records than were asked for is still read to the end. -# -# A page number is a position, not a record, so it only resumes where it left -# off while nothing before it goes away. Delete one ticket from a page already -# handled and every later ticket moves up a place: the next page then starts -# one ticket further on, and the ticket that moved into the handled page is -# never seen. New tickets are no trouble here, because this index is served in -# id order and they arrive at the end. -# -# So this loop is for a set that only grows. Where tickets can be deleted -# between two runs of the job, checkpoint the id of the last ticket handled -# instead, and skip up to it on the way back in: -# -# tickets.find_each.lazy.drop_while { it.id <= last_id }.each { ... } -# -# That reads the earlier pages again, so a ticket deleted while the job was -# down no longer moves the place it picks up from. -# -# It does nothing about a ticket deleted while a walk is under way, and -# neither does anything else here. `find_each` pages by position too: delete -# ticket 1 once page 1 has been read, and page 2 starts one ticket further -# on, with the ticket that moved up into page 1 never handed over. No way of -# reading an index that is paged by position rules that out, and walking -# again does not either: a second walk that tickets are deleted under can -# pass over the same ticket and turn up nothing new. What settles it is a -# walk nothing was deleted during, which the job has to be able to vouch -# for - by holding deletions off while it runs, say - and which turns up -# no ticket it has not handled. +# checkpoint is written once a page is handled, so a rerun repeats at most +# one page. A page number is a position, so this suits a set that only grows: +# tickets are served in id order, and new ones arrive at the end. puts '3. resumable page loop' -page = 1 - -if File.exist?(CURSOR) - # A checkpoint holds a page number or it holds nothing this loop can use. - # Said here, rather than left to `Integer` or to `page` to raise about. - page = Integer(File.read(CURSOR), exception: false) - abort " #{CURSOR} does not hold a page number. Remove it to start from page 1." if page.nil? || !page.positive? -end - +page = File.exist?(CURSOR) ? Integer(File.read(CURSOR)) : 1 puts " starting at page #{page}" loop do @@ -107,21 +58,11 @@ puts " page #{page}: #{batch.size} tickets" - # Checkpoint once the batch is safely handled, so an interrupted run - # repeats a batch rather than skipping one - on a set nothing is deleted - # from, see above. - # - # Written beside the checkpoint and renamed over it, which replaces it in - # one step. `File.write` on the checkpoint itself empties the file before - # it fills it, and a run stopped in between leaves a checkpoint with - # nothing in it, where the page before was still worth having. - File.write(NEXT_CURSOR, page + 1) - File.rename(NEXT_CURSOR, CURSOR) - page += 1 + File.write(CURSOR, page) end -FileUtils.rm_f([CURSOR, NEXT_CURSOR]) +FileUtils.rm_f(CURSOR) puts <<~NOTE @@ -131,9 +72,7 @@ in_batches you want one whole response at a time in_batches.next you want to pull batches as a consumer is ready in_batches.with_index you want the batches numbered as they arrive - page(n, per_page: m) the page number must be persisted, retried or skipped, - and nothing is deleted from the set meanwhile + page(n, per_page: m) the page number must be persisted, retried or skipped - Pacing is not on this list: the client already backs off and retries a 429, - so a manual sleep loop only duplicates it. + Pacing is not on this list: the client already backs off and retries a 429. NOTE diff --git a/examples/onboard_customer.rb b/examples/onboard_customer.rb index 27c9099..ec54cae 100755 --- a/examples/onboard_customer.rb +++ b/examples/onboard_customer.rb @@ -12,47 +12,19 @@ require 'zammad_api' -client = ZammadAPI::Client.from_env +abort "usage: #{$PROGRAM_NAME} COMPANY EMAIL FIRSTNAME LASTNAME" if ARGV.size < 4 company, email, firstname, lastname = ARGV -abort "usage: #{$PROGRAM_NAME} COMPANY EMAIL FIRSTNAME LASTNAME" if [company, email, firstname, lastname].any?(&:nil?) - -# Zammad stores an address trimmed and in lower case, and `find_by` matches a -# value exactly. Looked up as typed, Jane@Acme.Test misses the jane@acme.test -# Zammad holds: the check below then sees no user, and the script makes the -# organization before Zammad refuses the address as taken. -email = email.strip.downcase - -# `find_by` searches and then checks the hits itself, because Zammad's index -# endpoints cannot filter. It returns a record that genuinely carries the -# attribute, or nil - never an unrelated one. -# -# What the search surfaces is Zammad's business, so a value it has not indexed -# is a record this will not find, and the `||= create` below would then make a -# second organization. Searching by hand has the same gap. -organization = client.organizations.find_by(name: company) -user = client.users.find_by(email: email) - -# An address Zammad already knows is only this customer's if it sits in this -# organization. Reused regardless, a jane@acme.test who belongs to Contoso -# got Acme's welcome ticket and a report that all was well, with nothing -# having put that user in Acme. Moving a user is not this script's call -# either, so it stops, before anything is created. `[]` rather than a reader, -# because a user with no organization may not carry the attribute at all. -if user && (organization.nil? || user[:organization_id] != organization.id) - # Named where the response carries the name, by id where it carries only - # that, and "no organization" only for a user that has neither. - current = user[:organization] || (user[:organization_id] ? "organization id=#{user[:organization_id]}" : 'no organization') +email = email.downcase # Zammad stores addresses in lower case, and find_by matches exactly - abort "#{email} is already a user (id=#{user.id}) of #{current}, not of #{company}. " \ - 'Nothing was created or changed. Move the user in Zammad first, if that is what is meant.' -end +client = ZammadAPI::Client.from_env -organization ||= client.organizations.create(name: company) +# `find_by` returns the first record carrying exactly these values, or nil. +organization = client.organizations.find_by(name: company) || client.organizations.create(name: company) puts "organization: #{organization.name} (id=#{organization.id})" -user ||= client.users.create( +user = client.users.find_by(email: email) || client.users.create( firstname: firstname, lastname: lastname, email: email, @@ -62,8 +34,8 @@ puts "user: #{user.firstname} #{user.lastname} <#{user.email}> (id=#{user.id})" -# `on_behalf_of` returns a new client rather than mutating this one, so the -# admin client stays unscoped and both remain safe to use. +# `on_behalf_of` returns a new client rather than changing this one, so the +# admin client stays unscoped. as_customer = client.on_behalf_of(user.email) ticket = as_customer.tickets.create( diff --git a/examples/pagination.rb b/examples/pagination.rb index 2742866..12992f5 100755 --- a/examples/pagination.rb +++ b/examples/pagination.rb @@ -58,9 +58,9 @@ puts "search.count #{client.tickets.search('state.name:open').count}, one request" puts "empty? #{client.tickets.search('state.name:merged').empty?}, asks for a single record" -# `search` and `page` return a new collection, so scoping one never disturbs -# the original. -puts "immutable #{tickets.page(2).equal?(tickets)}" +# `search`, `order` and `page` return a new collection, so scoping one never +# disturbs the original. +puts "page(2) is new #{!tickets.page(2).equal?(tickets)}, tickets still reads every page" puts <<~NOTE From 79bf3cddcf033d3bf242a01b677990173839e6a9 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 25 Nov 2026 10:03:14 +0200 Subject: [PATCH 090/121] refactor!: drop paginated and the argument and config checks A fourth pass over the 2.0 client for straightforward API usage. lib/ goes from 2,626 to 2,536 lines. - The paginated declaration goes. An index that serves every record in one response, such as api/v1/object_manager_attributes, is still read in one request, because its list is shorter than the page asked for. Asked for smaller pages it raises PaginationError, which now points at client.get. - A Collection reads its page limit and whether it sorts from its resource class, rather than having both passed in by ResourceProxy. SEARCH_MAX_PER_PAGE moves from ResourceProxy to Collection. - Each resource declaration defines the reader it sets, so a subclass inherits it the Ruby way and the declaration lookup helper goes. - Collection no longer polices its arguments: per_page and page numbers go to Zammad as given, order() and pluck() with nothing are no-ops, and first(count) sizes its page without checking the count. - Config checks the URL and the credentials only. A non-boolean ssl_verify, a middleware that cannot be called, a logger without debug and a non-positive timeout or retry count fail where they are used. - RateLimitError#retry_after is one line. --- CHANGELOG.md | 9 +- README.md | 14 +- lib/zammad_api/collection.rb | 53 +++---- lib/zammad_api/config.rb | 17 +-- lib/zammad_api/errors.rb | 9 +- lib/zammad_api/resource_proxy.rb | 18 +-- lib/zammad_api/resources/base.rb | 59 ++------ script/check_connection.rb | 2 +- sig/zammad_api/collection.rbs | 12 +- sig/zammad_api/config.rbs | 2 - sig/zammad_api/resource_proxy.rbs | 4 +- sig/zammad_api/resources/base.rbs | 9 -- spec/unit/zammad_api/client_spec.rb | 4 +- spec/unit/zammad_api/collection_spec.rb | 144 ++------------------ spec/unit/zammad_api/config_spec.rb | 48 +------ spec/unit/zammad_api/resource_proxy_spec.rb | 24 +--- spec/unit/zammad_api/resources/base_spec.rb | 27 ---- spec/unit/zammad_api/test_spec.rb | 22 --- 18 files changed, 71 insertions(+), 406 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4096e63..1e26330 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a ignored. - `logger:` takes a `Logger` rather than a boolean flag. `logger: true` used to turn on debug output to `$stderr`; pass `Logger.new($stderr)` for the same thing. Anything that - responds to `debug` is accepted, and anything else raises `ConfigurationError`. + responds to `debug` works. - `Collection#each` (`client.x.all`, `client.x.search`) now walks every page. Previously it fetched a single page, so iterating stopped silently at 100 records for `all` and at 10 for `search`. @@ -158,8 +158,6 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a end of the list. - `ZammadAPI::PaginationError`, raised when an endpoint answers a page with the records of the page before it, instead of paging forever. -- `paginated false` declares an index endpoint that serves every record in one response, - such as `api/v1/object_manager_attributes`. It is then read in one request. - `Base#reload`, `#persisted?`, `#destroyed?`, `#[]`, `#[]=`, `#fetch`, `#key?`, `#to_h` and a readable `#inspect` that blanks attributes naming a credential. - `record.update(attributes)`, `record.update!(attributes)` and @@ -205,8 +203,7 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `client.resource(SomeClass)` takes a subclass of `ZammadAPI::Resources::Base` and answers with a proxy for it, so an endpoint this gem does not model gets records, pagination, `find_by`, change tracking and `save` from a class that declares its `path`. `searchable`, - `max_per_page`, `sortable`, `paginated` and `belongs_to` say what else is true of the - endpoint. + `max_per_page`, `sortable` and `belongs_to` say what else is true of the endpoint. - Typed records. `ResourceProxy` and `Collection` are generic over the resource they hold, so `client.tickets` is a `ResourceProxy[Resources::Ticket]` and `find`, `first`, `find_by`, the block of `each` and a search all answer with a `Ticket`. Each resource @@ -251,7 +248,7 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `client..destroy(id)` deletes directly instead of fetching the record first. - Resource dispatch is explicit rather than `method_missing` plus `const_get`. - A resource declares what its endpoint does — `searchable true`, `max_per_page 100`, - `sortable false`, `paginated false` — the way it declares `path`. + `sortable false` — the way it declares `path`. - `client.` returns the same proxy each time rather than allocating one per call. The proxies are built with the client, so a client stays immutable once built and safe to share between threads. diff --git a/README.md b/README.md index 890018d..d90e9a0 100644 --- a/README.md +++ b/README.md @@ -297,7 +297,6 @@ Say what else is true of the endpoint, where it differs from the defaults: | `searchable true` | `false` | Zammad routes `/search`, so `search` works and `find_by` uses it. | | `max_per_page 100` | `1000` | The largest page the index endpoint serves. A walk ends at the first page shorter than the size it asked for, so this has to be what the endpoint really serves. | | `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. | -| `paginated false` | `true` | The index endpoint serves every record in one response and reads no `page`. It is read in one request, and `page` refuses it. | | `belongs_to :role, class_name: 'Role'` | — | A foreign key, read as a record through `record.related.role`. | `class_name` is a resource of this gem by its own name, `'User'`, or a class of yours by its @@ -305,22 +304,21 @@ full name, `'Acme::Role'`. A subclass of a modelled resource works too, and inhe its parent declares: `class MyTicket < ZammadAPI::Resources::Ticket`. An endpoint that serves every record in one response and ignores `page` — -`api/v1/object_manager_attributes` is one — answers the request for a second page with the -first again, which a walk reports as `ZammadAPI::PaginationError`. Declare such a resource -`paginated false`, and it is read in one request: +`api/v1/object_manager_attributes` is one — is still read in one request, because its first +page is shorter than the 1000 records asked for: ```ruby class ObjectAttribute < ZammadAPI::Resources::Base path 'api/v1/object_manager_attributes' - paginated false sortable false end client.resource(ObjectAttribute).find_by(name: 'priority_id') # one request ``` -This endpoint sorts nothing either, so it says `sortable false` as well. A search always -pages, whatever the index beside it does. +Asked for smaller pages, with `in_batches(of: 50)`, such an endpoint answers the second page +with the first again, which a walk reports as `ZammadAPI::PaginationError`. Read it with +`client.get` instead. A search always pages and sorts, whatever the index beside it does. Use raw requests for an endpoint that is not shaped like that — an action, a report, a setting. @@ -1186,7 +1184,7 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | -------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------- | | `Client.new(config_hash)` | `Client.new(**config_hash)` | Options are keyword arguments now, so a Hash has to be splatted | | an unknown option was ignored | raises `ArgumentError: unknown keyword` | A typo'd option used to be dropped without a word | -| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object, so you choose the device and level. Anything that responds to `debug` is accepted; `true` raises `ConfigurationError` | +| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object, so you choose the device and level. Anything that responds to `debug` works; `true` raises `NoMethodError` on the first request | | `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is `Enumerable` over every record now, so `client.ticket.each` read as if it acted on one ticket. The singular names raise `UnknownResourceError`, which lists the plural ones, and so does `client.resource(:ticket)` | | `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads | | `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised | diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb index a1e65db..13b37b1 100644 --- a/lib/zammad_api/collection.rb +++ b/lib/zammad_api/collection.rb @@ -14,9 +14,6 @@ module ZammadAPI # sized for what it was asked for, and +lazy+, +detect+ and the rest of # +Enumerable+ stop the walk as soon as they have enough. # - # An index that serves every record in one response is read in one request - # instead, where its resource says so: see {Resources::Base.paginated}. - # # @example Iterate every ticket # client.tickets.all.each { |ticket| puts ticket.title } # @@ -34,27 +31,26 @@ module ZammadAPI class Collection include Enumerable + # Largest page size Zammad's search endpoints serve. + SEARCH_MAX_PER_PAGE = 200 + # @api private # @param per_page [Integer, nil] records fetched per request, or nil for # as many as the endpoint serves # @param search [Boolean] whether this is a search endpoint, which can - # serve a short page before the last one and can count its results - # @param sortable [Boolean] whether this endpoint reads +sort_by+ and +order_by+ - # @param paginated [Boolean] whether this endpoint reads +page+ and +per_page+ - def initialize(transport:, resource_class:, path:, operation:, max_per_page:, sortable:, query: {}, per_page: nil, page: nil, search: false, paginated: true) - raise ArgumentError, 'per_page needs to be a positive integer' if per_page && (!per_page.is_a?(Integer) || !per_page.positive?) + # serve a short page before the last one, can count its results and + # always sorts + def initialize(transport:, resource_class:, path:, operation:, query: {}, per_page: nil, page: nil, search: false) + max_per_page = search ? SEARCH_MAX_PER_PAGE : resource_class.page_limit @transport = transport @resource_class = resource_class @path = path @operation = operation @query = query - @max_per_page = max_per_page - @sortable = sortable @per_page = [per_page || max_per_page, max_per_page].min @page = page @search = search - @paginated = paginated end # Yields every record, fetching pages as needed. @@ -89,7 +85,7 @@ def in_batches(of: nil, &block) return to_enum(:in_batches, of: of) if !block return with(per_page: of).in_batches(&block) if of - @paginated ? walk(&block) : fetch(nil).each_slice(@per_page, &block) + walk(&block) self end @@ -102,14 +98,7 @@ def in_batches(of: nil, &block) # @param per_page [Integer, nil] records on the page, at most what the # endpoint serves # @return [Collection] - # @raise [ArgumentError] for a page number that is not a positive Integer, - # or an endpoint that does not page - def page(number, per_page: nil) - raise ArgumentError, 'page needs to be a positive integer' if !number.is_a?(Integer) || !number.positive? - raise ArgumentError, "#{@path} serves every record in one response, so it has no pages" if !@paginated - - with(page: number, per_page: per_page || @per_page) - end + def page(number, per_page: nil) = with(page: number, per_page: per_page || @per_page) # Returns a new collection sorted by the server. # @@ -124,14 +113,12 @@ def page(number, per_page: nil) # @param directions [Hash{Symbol => Symbol, String}] attributes to sort by, # each with +:asc+ or +:desc+ # @return [Collection] - # @raise [ArgumentError] for an endpoint that does not sort, or no attribute + # @raise [ArgumentError] for an endpoint that does not sort def order(*attributes, **directions) - raise ArgumentError, "#{@path} is always served in the same order and ignores sort_by" if !@sortable + raise ArgumentError, "#{@path} is always served in the same order and ignores sort_by" if !@search && !@resource_class.sortable? requested = attributes.to_h { [it.to_s, 'asc'] }.merge(directions.to_h { |name, direction| [name.to_s, direction.to_s] }) - raise ArgumentError, 'order needs at least one attribute to sort by: order(:name), or order(name: :desc)' if requested.empty? - - columns = sorted_by.merge(requested) + columns = sorted_by.merge(requested) with(query: @query.merge(sort_by: columns.keys.join(','), order_by: columns.values.join(','))) end @@ -143,9 +130,7 @@ def order(*attributes, **directions) # # @param keys [Array] attribute names # @return [Array] - # @raise [ArgumentError] when no attribute name was given def pluck(*keys) - raise ArgumentError, 'pluck needs at least one attribute name' if keys.empty? return map { it[keys.first] } if keys.one? map { |record| keys.map { record[it] } } @@ -157,8 +142,7 @@ def pluck(*keys) # @param count [Integer, nil] # @return [Resources::Base, Array, nil] def first(count = nil) - wanted = count || 1 - source = @page || !@paginated || !wanted.is_a?(Integer) || !wanted.positive? ? self : with(per_page: wanted) + source = @page ? self : with(per_page: count || 1) count.nil? ? source.each.first : source.each.first(count) end @@ -193,7 +177,7 @@ def count(*args, &block) def empty? = first.nil? def inspect - "#<#{self.class.name} #{@resource_class.name} path=#{@path.inspect} per_page=#{@per_page}#{" page=#{@page}" if @page}#{' paginated=false' if !@paginated}>" + "#<#{self.class.name} #{@resource_class.name} path=#{@path.inspect} per_page=#{@per_page}#{" page=#{@page}" if @page}>" end private @@ -224,10 +208,8 @@ def walk end end - # One page, or with no number the whole of an index that does not page. def fetch(number) - query = number ? @query.merge(page: number, per_page: @per_page) : @query - response = @transport.get(@path, operation: @operation, resource_class: @resource_class, query: query) + response = @transport.get(@path, operation: @operation, resource_class: @resource_class, query: @query.merge(page: number, per_page: @per_page)) response.decoded(:array, operation: @operation, resource_class: @resource_class).map { @resource_class.from_response(@transport, it) } end @@ -248,13 +230,10 @@ def with(page: @page, per_page: @per_page, query: @query) resource_class: @resource_class, path: @path, operation: @operation, - max_per_page: @max_per_page, - sortable: @sortable, query: query, per_page: per_page, page: page, - search: @search, - paginated: @paginated + search: @search ) end end diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 1b9da7e..bbe4292 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -162,7 +162,7 @@ def initialize( ) # steep:ignore:end - validate! + validate_credentials! end # @return [Symbol] +:http_token+, +:oauth2_token+ or +:basic+ @@ -220,14 +220,6 @@ def normalize_url(value) raise ConfigurationError, 'config url is not a valid URL' end - def validate! - validate_credentials! - validate_numbers! - raise ConfigurationError, "config ssl_verify needs to be true or false, got #{ssl_verify.inspect}" if ![true, false].include?(ssl_verify) - raise ConfigurationError, 'config middleware needs to respond to call' if middleware && !middleware.respond_to?(:call) - raise ConfigurationError, 'config logger needs to respond to debug' if !logger.respond_to?(:debug) - end - def validate_credentials! given = CREDENTIAL_OPTIONS.select { |_, options| options.any? { !public_send(it).nil? } }.keys if given.size > 1 @@ -240,13 +232,6 @@ def validate_credentials! raise ConfigurationError, 'missing password in config' if password.nil? end - def validate_numbers! - { timeout: timeout, open_timeout: open_timeout, retry_interval: retry_interval }.each do |name, value| - raise ConfigurationError, "config #{name} needs to be a positive number" if !value.is_a?(Numeric) || !value.positive? - end - raise ConfigurationError, 'config retries needs to be a non-negative integer' if !retries.is_a?(Integer) || retries.negative? - end - def present(value) = value.nil? || value.to_s.empty? ? nil : value def stripped(value) diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index bfbb8a1..5ae167b 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -57,7 +57,7 @@ class PaginationError < Error def self.build(operation:, page:, resource_class: nil) new( "Can't #{subject_for(operation, resource_class)}: page #{page} repeated page #{page - 1}, so the endpoint is " \ - 'ignoring the page parameter. If it serves every record in one response, declare `paginated false` on the resource.' + 'ignoring the page parameter. If it serves every record in one response, read it with client.get instead.' ) end end @@ -170,12 +170,7 @@ class ValidationError < ClientError; end # 429 - too many requests. class RateLimitError < ClientError # @return [Integer, nil] value of the +Retry-After+ response header, in seconds - def retry_after - value = headers['retry-after'] - return nil if value.nil? - - Integer(value.to_s, 10, exception: false) - end + def retry_after = Integer(headers['retry-after'].to_s, 10, exception: false) end class ResponseError diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index e0b914b..8ace8f6 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -34,9 +34,6 @@ class ResourceProxy include Enumerable extend Forwardable - # Largest page size Zammad's search endpoints serve. - SEARCH_MAX_PER_PAGE = 200 - # @return [Class] the resource class this proxy operates on attr_reader :resource_class @@ -166,31 +163,20 @@ def search(term, **filters) raise Error, "Zammad routes no search endpoint for #{resource_class.name}: look a record up with find_by, which walks the records instead" if !resource_class.searchable? raise ArgumentError, "search needs a non-empty query string. Search for '*' to ask for every record." if !term.is_a?(String) || term.strip.empty? - collection( - "#{path}/search", - 'get .search of object', - query: { query: term, **filters }, - max_per_page: SEARCH_MAX_PER_PAGE, - sortable: true, - paginated: true, - search: true - ) + collection("#{path}/search", 'get .search of object', query: { query: term, **filters }, search: true) end def inspect = "#<#{self.class.name} #{resource_class.name}>" private - def collection(path, operation, query: {}, max_per_page: resource_class.page_limit, sortable: resource_class.sortable?, paginated: resource_class.paginated?, search: false) + def collection(path, operation, query: {}, search: false) Collection.new( transport: @transport, resource_class: resource_class, path: path, operation: operation, - max_per_page: max_per_page, - sortable: sortable, search: search, - paginated: paginated, query: { expand: true }.merge(query) ) end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 42834be..16c175d 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -35,72 +35,46 @@ class Base attr_reader :transport class << self + # Each declaration defines the reader of the same setting on this + # class, which a subclass inherits and can declare again. + # Declares the API path of this resource, relative to the instance URL. # # @param value [String] # @return [void] - def path(value) - @path = value - end + def path(value) = define_singleton_method(:resource_path) { value } - # Declares that Zammad routes a +/search+ endpoint for this resource. + # Declares whether Zammad routes a +/search+ endpoint for this resource. # # @param value [Boolean] # @return [void] - def searchable(value) - @searchable = value - end + def searchable(value) = define_singleton_method(:searchable?) { value } # Declares the largest page size this resource's index endpoint serves. # # @param value [Integer] # @return [void] - def max_per_page(value) - @max_per_page = value - end + def max_per_page(value) = define_singleton_method(:page_limit) { value } # Declares whether this resource's index endpoint reads +sort_by+ and # +order_by+. One that does not is refused by {Collection#order}. # # @param value [Boolean] # @return [void] - def sortable(value) - @sortable = value - end - - # Declares whether this resource's index endpoint pages. One that - # serves every record in one response is read in one request. - # - # @example - # class ObjectAttribute < ZammadAPI::Resources::Base - # path 'api/v1/object_manager_attributes' - # paginated false - # sortable false - # end - # - # @param value [Boolean] - # @return [void] - def paginated(value) - @paginated = value - end + def sortable(value) = define_singleton_method(:sortable?) { value } # @return [String] the API path of this resource # @raise [Error] when the resource declares none - def resource_path - declaration(:path) || raise(Error, "#{name} does not declare an API path") - end + def resource_path = raise(Error, "#{name} does not declare an API path") # @return [Boolean] whether Zammad routes a +/search+ endpoint here - def searchable? = declaration(:searchable) { false } + def searchable? = false # @return [Integer] the largest page size this endpoint serves - def page_limit = declaration(:max_per_page) { DEFAULT_MAX_PER_PAGE } + def page_limit = DEFAULT_MAX_PER_PAGE # @return [Boolean] whether the index endpoint reads +sort_by+ and +order_by+ - def sortable? = declaration(:sortable) { true } - - # @return [Boolean] whether the index endpoint reads +page+ and +per_page+ - def paginated? = declaration(:paginated) { true } + def sortable? = true # The API path of one record of this kind, with the id escaped. # @@ -144,15 +118,6 @@ def associations private - # A declaration of this class, or failing that of the class it inherits from. - def declaration(name, &default) - variable = :"@#{name}" - return instance_variable_get(variable) if instance_variable_defined?(variable) - return superclass.send(:declaration, name, &default) if superclass.respond_to?(:declaration, true) - - default&.call - end - def declared_associations = @declared_associations ||= {} # Declares that this resource points at a single other record, through diff --git a/script/check_connection.rb b/script/check_connection.rb index ba5771e..d5d5011 100755 --- a/script/check_connection.rb +++ b/script/check_connection.rb @@ -114,7 +114,7 @@ def finish check('derived client re-validates options') do CLIENT.with(timeout: 45) - CLIENT.with(timeout: -1) + CLIENT.with(url: 'zammad.example.com') raise 'expected ConfigurationError' rescue ZammadAPI::ConfigurationError 'invalid option rejected' diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs index a273790..d8e18ee 100644 --- a/sig/zammad_api/collection.rbs +++ b/sig/zammad_api/collection.rbs @@ -5,30 +5,26 @@ module ZammadAPI class Collection[R < Resources::Base] include Enumerable[R] + SEARCH_MAX_PER_PAGE: Integer + @transport: Transport @resource_class: untyped @path: String @operation: String @query: Hash[Symbol, untyped] - @max_per_page: Integer - @sortable: bool @per_page: Integer @page: Integer? @search: bool - @paginated: bool def initialize: ( transport: Transport, resource_class: untyped, path: String, operation: String, - max_per_page: Integer, - sortable: bool, ?query: Hash[Symbol, untyped], ?per_page: Integer?, ?page: Integer?, - ?search: bool, - ?paginated: bool + ?search: bool ) -> void def each: () { (R) -> void } -> Collection[R] @@ -51,7 +47,7 @@ module ZammadAPI private def walk: () { (Array[R]) -> void } -> void - def fetch: (Integer? number) -> Array[R] + def fetch: (Integer number) -> Array[R] def total_count: () -> Integer? def sorted_by: () -> Hash[String, String] def with: (?page: Integer?, ?per_page: Integer?, ?query: Hash[Symbol, untyped]) -> Collection[R] diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index 94c2518..b523171 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -63,9 +63,7 @@ module ZammadAPI def render: (Symbol, untyped) -> String def normalize_url: (untyped) -> String - def validate!: () -> void def validate_credentials!: () -> void - def validate_numbers!: () -> void def present: (untyped) -> untyped def stripped: (untyped) -> String? end diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs index 363e7fd..0ef1d3f 100644 --- a/sig/zammad_api/resource_proxy.rbs +++ b/sig/zammad_api/resource_proxy.rbs @@ -5,8 +5,6 @@ module ZammadAPI class ResourceProxy[R < Resources::Base] include Enumerable[R] - SEARCH_MAX_PER_PAGE: Integer - attr_reader resource_class: untyped @transport: Transport @@ -39,7 +37,7 @@ module ZammadAPI private - def collection: (String, String, ?query: Hash[Symbol, untyped], ?max_per_page: Integer, ?sortable: bool, ?paginated: bool, ?search: bool) -> Collection[R] + def collection: (String, String, ?query: Hash[Symbol, untyped], ?search: bool) -> Collection[R] def find_by_id: (Hash[Symbol, untyped] params) -> R? def path: () -> String end diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 7019f4f..8d46eba 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -26,28 +26,19 @@ module ZammadAPI @related: Associations::Proxy? @baseline: Hash[Symbol, untyped] self.@declared_associations: Hash[Symbol, Hash[Symbol, untyped]]? - self.@path: String? - self.@searchable: bool? - self.@max_per_page: Integer? - self.@sortable: bool? - self.@paginated: bool? def self.path: (String) -> void def self.searchable: (bool) -> void def self.max_per_page: (Integer) -> void def self.sortable: (bool) -> void - def self.paginated: (bool) -> void def self.resource_path: () -> String def self.searchable?: () -> bool def self.page_limit: () -> Integer def self.sortable?: () -> bool - def self.paginated?: () -> bool def self.member_path: ((Integer | String) id) -> String def self.fetch_one: (Transport transport, (Integer | String) id) -> Base def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> Base def self.associations: () -> Hash[Symbol, Hash[Symbol, untyped]] - def self.declaration: [T] (Symbol name) { () -> T } -> T - | (Symbol name) -> untyped def self.declared_associations: () -> Hash[Symbol, Hash[Symbol, untyped]] def self.belongs_to: (Symbol name, class_name: String, ?foreign_key: Symbol) -> void diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index f85e1a2..aad4da5 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -764,8 +764,8 @@ def from(variables) end it 're-validates the resulting configuration' do - expect { unit_client.with(timeout: -1) } - .to raise_error(ZammadAPI::ConfigurationError, /positive number/) + expect { unit_client.with(url: 'zammad.example.com') } + .to raise_error(ZammadAPI::ConfigurationError, /needs to start with http/) end context 'when it names another way to authenticate' do diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb index e2e5165..73b4c30 100644 --- a/spec/unit/zammad_api/collection_spec.rb +++ b/spec/unit/zammad_api/collection_spec.rb @@ -231,11 +231,6 @@ def stub_capped_endpoint(url, total:, max:) it 'returns an Enumerator without a block' do expect(collection.find_each).to be_a(Enumerator) end - - it 'rejects a non-positive page size' do - expect { collection.find_each(batch_size: 0) { nil } } - .to raise_error(ArgumentError, 'per_page needs to be a positive integer') - end end describe '#in_batches' do @@ -291,11 +286,6 @@ def stub_capped_endpoint(url, total:, max:) expect(collection.in_batches(of: 2).next.map(&:id)).to eq([1, 2]) expect(a_request(:get, url).with(query: hash_including('page' => '2'))).not_to have_been_made end - - it 'rejects a non-positive page size' do - expect { collection.in_batches(of: 0) { nil } } - .to raise_error(ArgumentError, 'per_page needs to be a positive integer') - end end describe '#page' do @@ -324,22 +314,6 @@ def stub_capped_endpoint(url, total:, max:) expect(collection.page(2)).not_to be(collection) expect(collection.map(&:id)).to eq([1]) end - - it 'rejects page zero' do - expect { collection.page(0) }.to raise_error(ArgumentError, /positive integer/) - end - - it 'rejects a non-integer page' do - expect { collection.page('2') }.to raise_error(ArgumentError, /positive integer/) - end - - it 'rejects a non-positive page size' do - expect { collection.page(1, per_page: 0) }.to raise_error(ArgumentError, 'per_page needs to be a positive integer') - end - - it 'rejects a non-integer page size' do - expect { collection.page(1, per_page: '7') }.to raise_error(ArgumentError, 'per_page needs to be a positive integer') - end end describe 'page size caps' do @@ -449,10 +423,6 @@ def sorted_request(sort_by, order_by) expect(a_request(:get, url).with(query: hash_including({}))).not_to have_been_made end - it 'raises without an attribute to sort by' do - expect { collection.order }.to raise_error(ArgumentError, /order needs at least one attribute to sort by/) - end - # TicketsController#index and UsersController#index hardcode the order and # drop sort_by with everything else they do not read. context 'with an index endpoint that is always served in id order' do @@ -524,10 +494,6 @@ def sorted_request(sort_by, order_by) expect(collection.pluck(:id)).to eq((1..(default_per_page + 1)).to_a) end - - it 'needs at least one attribute name' do - expect { collection.pluck }.to raise_error(ArgumentError, 'pluck needs at least one attribute name') - end end describe '#count' do @@ -720,7 +686,6 @@ def sorted_request(sort_by, order_by) def self.name = 'ObjectAttribute' path 'api/v1/object_manager_attributes' - paginated false end end let(:url) { "#{ClientHelper::BASE_URL}api/v1/object_manager_attributes" } @@ -729,118 +694,31 @@ def self.name = 'ObjectAttribute' # The same list whatever it is asked, which is what such an endpoint does. before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response(records)) } - it 'reads every record' do + # The list is shorter than the page asked for, so it is the last one. + it 'reads every record in one request' do expect(collection.map(&:id)).to eq([1, 2, 3]) - end - - it 'spends one request on it' do - collection.to_a expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once end - it 'names no page in that request' do - collection.to_a - expect(a_request(:get, url).with(query: { 'expand' => 'true' })).to have_been_made.once + it 'raises PaginationError where smaller pages are asked for' do + expect { collection.in_batches(of: 2).to_a } + .to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1.*read it with client.get instead/) end - context 'without the declaration, and a list as long as a page' do - let(:resource) do - Class.new(ZammadAPI::Resources::Base) do - def self.name = 'ObjectAttribute' - - path 'api/v1/object_manager_attributes' - end - end + context 'with a list as long as a page' do let(:records) { full_page } - it 'raises PaginationError, and says what to declare' do - expect { collection.to_a } - .to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1.*declare `paginated false` on the resource/) + it 'raises PaginationError' do + expect { collection.to_a }.to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1/) end end - - it 'hands the list over as one batch' do - expect(collection.in_batches.map { |batch| batch.map(&:id) }).to eq([[1, 2, 3]]) - end - - it 'slices the list where a batch size is asked for' do - expect(collection.in_batches(of: 2).map { |batch| batch.map(&:id) }).to eq([[1, 2], [3]]) - end - - it 'still spends one request where a batch size is asked for' do - collection.find_each(batch_size: 1).to_a - expect(a_request(:get, url).with(query: { 'expand' => 'true' })).to have_been_made.once - end - - it 'yields no batch for a list with nothing on it' do - stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) - - expect(collection.in_batches.to_a).to eq([]) - end - - it 'reads the first record off the one response' do - expect(collection.first.id).to eq(1) - expect(a_request(:get, url).with(query: { 'expand' => 'true' })).to have_been_made.once - end - - it 'reads the first few' do - expect(collection.first(2).map(&:id)).to eq([1, 2]) - end - - it 'counts the records' do - expect(collection.count).to eq(3) - end - - it 'says whether there are any' do - expect(collection).not_to be_empty - end - - it 'finds a record by what it carries' do - expect(collection.detect { it.name == 'b' }.id).to eq(3) - end - - # Every number would name the same records. - it 'refuses a page' do - expect { collection.page(2) }.to raise_error(ArgumentError, /serves every record in one response, so it has no pages/) - end - - it 'still refuses a page that is not a number first' do - expect { collection.page(0) }.to raise_error(ArgumentError, /positive integer/) - end - - # Whether an index sorts is a declaration of its own. - it 'sends a sort, and still no page' do - collection.order(:name).to_a - - expect(a_request(:get, url).with(query: { 'expand' => 'true', 'sort_by' => 'name', 'order_by' => 'asc' })).to have_been_made.once - end - - context 'when the resource says the endpoint does not sort either' do - let(:resource) do - Class.new(ZammadAPI::Resources::Base) do - def self.name = 'ObjectAttribute' - - path 'api/v1/object_manager_attributes' - paginated false - sortable false - end - end - - it 'refuses a sort, which such an endpoint drops' do - expect { collection.order(:name) }.to raise_error(ArgumentError, /ignores sort_by/) - end - end - - it 'says so in inspect' do - expect(collection.inspect).to end_with('paginated=false>') - end end describe ZammadAPI::PaginationError do - it 'names the page that repeated and what to declare for an endpoint that does not page' do + it 'names the page that repeated and how to read an endpoint that does not page' do message = described_class.build(operation: 'get .all of object', page: 3).message - expect(message).to include('page 3 repeated page 2').and include('declare `paginated false` on the resource') + expect(message).to include('page 3 repeated page 2').and include('read it with client.get instead') end end @@ -851,7 +729,7 @@ def self.name = 'ObjectAttribute' subject(:search) { client.users.search('smith') } let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/users/search" } - let(:page_size) { ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE } + let(:page_size) { ZammadAPI::Collection::SEARCH_MAX_PER_PAGE } def stub_search_page(page, records) stub_request(:get, search_url) diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index 66de493..c24124c 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -215,11 +215,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect(build(middleware: hook).middleware).to be(hook) end - it 'rejects middleware that cannot be called' do - expect { build(middleware: 'not callable') } - .to raise_error(ZammadAPI::ConfigurationError, 'config middleware needs to respond to call') - end - it 'accepts any callable, not only a proc' do callable = Class.new { def call(builder) = builder }.new expect(build(middleware: callable).middleware).to be(callable) @@ -236,42 +231,10 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) logger = Class.new { def debug(...) = nil }.new expect(build(logger: logger).logger).to be(logger) end - - it 'rejects a logger that cannot log at debug' do - expect { build(logger: true) } - .to raise_error(ZammadAPI::ConfigurationError, 'config logger needs to respond to debug') - end end - describe 'numeric validation' do - it 'rejects a zero timeout' do - expect { build(timeout: 0) } - .to raise_error(ZammadAPI::ConfigurationError, 'config timeout needs to be a positive number') - end - - it 'rejects a negative open_timeout' do - expect { build(open_timeout: -1) } - .to raise_error(ZammadAPI::ConfigurationError, 'config open_timeout needs to be a positive number') - end - - it 'rejects a non-numeric retry_interval' do - expect { build(retry_interval: 'soon') } - .to raise_error(ZammadAPI::ConfigurationError, 'config retry_interval needs to be a positive number') - end - - it 'rejects negative retries' do - expect { build(retries: -1) } - .to raise_error(ZammadAPI::ConfigurationError, 'config retries needs to be a non-negative integer') - end - - it 'rejects retries that are not an integer' do - expect { build(retries: 1.5) } - .to raise_error(ZammadAPI::ConfigurationError, 'config retries needs to be a non-negative integer') - end - - it 'allows disabling retries' do - expect(build(retries: 0).retries).to eq(0) - end + it 'allows disabling retries' do + expect(build(retries: 0).retries).to eq(0) end describe '#inspect' do @@ -376,7 +339,7 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) end it 're-validates' do - expect { build.with(retries: -1) }.to raise_error(ZammadAPI::ConfigurationError, /non-negative integer/) + expect { build.with(url: 'zammad.example.com') }.to raise_error(ZammadAPI::ConfigurationError, /needs to start with http/) end it 'replaces the authentication scheme rather than adding a second one' do @@ -424,11 +387,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) end describe 'other options' do - it 'rejects an ssl_verify that is not a boolean' do - expect { build(ssl_verify: 'false') } - .to raise_error(ZammadAPI::ConfigurationError, 'config ssl_verify needs to be true or false, got "false"') - end - it 'accepts ssl_verify: false' do expect(build(ssl_verify: false).ssl_verify).to be(false) end diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 653aaf3..34b0b23 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -158,7 +158,7 @@ # Zammad's search sorts by updated_at, newest first, not by relevance, so # the exact match can sit on any page of hits. context 'when more records match the term than one page holds' do - let(:page_size) { ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE } + let(:page_size) { ZammadAPI::Collection::SEARCH_MAX_PER_PAGE } let(:others) { Array.new(page_size) { { id: it + 1, name: 'Users Archive' } } } def stub_page(number, records) @@ -194,7 +194,7 @@ def stub_page(number, records) it 'asks for hits at the size the search endpoint serves' do stub = stub_request(:get, search_url) - .with(query: hash_including('page' => '1', 'per_page' => ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE.to_s)) + .with(query: hash_including('page' => '1', 'per_page' => ZammadAPI::Collection::SEARCH_MAX_PER_PAGE.to_s)) .to_return(json_response([{ id: 1, name: 'Users' }])) proxy.find_by(name: 'Users') @@ -414,7 +414,9 @@ def stub_page(number, records) end end - describe 'a resource whose index does not page' do + # Such an index serves a list shorter than the page asked for, which a walk + # reads as the last page. + describe 'a resource whose index serves every record in one response' do subject(:proxy) { client.resource(resource) } let(:resource) do @@ -422,7 +424,6 @@ def stub_page(number, records) def self.name = 'ObjectAttribute' path 'api/v1/object_manager_attributes' - paginated false end end let(:url) { "#{ClientHelper::BASE_URL}api/v1/object_manager_attributes" } @@ -441,7 +442,7 @@ def self.name = 'ObjectAttribute' it 'spends one request on a miss' do proxy.find_by(name: 'missing') - expect(a_request(:get, url).with(query: { 'expand' => 'true' })).to have_been_made.once + expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once end it 'lets a miss go on to create the record' do @@ -454,17 +455,6 @@ def self.name = 'ObjectAttribute' it 'reads every record straight off the proxy' do expect(proxy.map(&:name)).to eq(%w[a b]) end - - # The declaration is about the index. A search endpoint always pages. - it 'still pages a search' do - resource.searchable true - search = stub_request(:get, "#{url}/search") - .with(query: hash_including('page' => '1', 'per_page' => described_class::SEARCH_MAX_PER_PAGE.to_s)) - .to_return(json_response([])) - - proxy.search('a').to_a - expect(search).to have_been_requested - end end describe '#exists?' do @@ -681,7 +671,7 @@ def stub_page(page, records, per_page: default_per_page) it 'requests the search endpoint' do stub = stub_request(:get, "#{url}/search") - .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => ZammadAPI::ResourceProxy::SEARCH_MAX_PER_PAGE.to_s, 'query' => 'support' }) + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => ZammadAPI::Collection::SEARCH_MAX_PER_PAGE.to_s, 'query' => 'support' }) .to_return(json_response([])) proxy.search('support').to_a diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index bdba08d..830e173 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -839,12 +839,6 @@ def self.name expect(subclass.sortable?).to be(false) end - it 'inherits whether the index endpoint pages' do - unpaged = Class.new(described_class) { paginated false } - - expect(Class.new(unpaged).paginated?).to be(false) - end - it 'inherits the associations' do expect(subclass.associations.keys).to eq(ZammadAPI::Resources::Ticket.associations.keys) end @@ -883,27 +877,6 @@ def self.name expect(Class.new(described_class).sortable?).to be(true) end - it 'defaults to an index endpoint that pages, as the generic ones do' do - expect(Class.new(described_class).paginated?).to be(true) - end - - it 'records a declaration that the index endpoint does not page' do - expect(Class.new(described_class) { paginated false }.paginated?).to be(false) - end - - # Two declarations, and neither reads the other. - it 'leaves whether the index endpoint sorts to its own declaration' do - expect(Class.new(described_class) { paginated false }.sortable?).to be(true) - end - - it 'leaves whether the index endpoint pages to its own declaration' do - expect(Class.new(described_class) { sortable false }.paginated?).to be(true) - end - - it 'pages every resource this gem models' do - expect(ZammadAPI::Client::RESOURCES.values).to all(be_paginated) - end - it 'records a declared page limit' do expect(Class.new(described_class) { max_per_page 25 }.page_limit).to eq(25) end diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 730d241..84131a0 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -550,28 +550,6 @@ end end - describe 'a list endpoint whose resource says it does not page' do - let(:resource) do - Class.new(ZammadAPI::Resources::Base) do - def self.name = 'ObjectAttribute' - - path 'api/v1/object_manager_attributes' - paginated false - end - end - - before { zammad.stub(:get, 'api/v1/object_manager_attributes', body: [{ id: 1, name: 'a' }]) } - - it 'is read from the one stub' do - expect(client.resource(resource).map(&:name)).to eq(['a']) - end - - it 'is recorded as the one request it is, naming no page' do - client.resource(resource).to_a - expect(zammad.requests.map(&:query)).to eq([{ 'expand' => 'true' }]) - end - end - describe 'a list endpoint stubbed once' do subject(:zammad) { described_class.new } From f3c9cf3e61777b8402a7d71b19a4c1cd07338d96 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 25 Nov 2026 10:29:46 +0200 Subject: [PATCH 091/121] refactor!: drop related and belongs_to A fifth pass over the 2.0 client for straightforward API usage. lib/ goes from 2,536 to 2,400 lines. - record.related and the belongs_to declaration go, with Resource.associations. The record behind a foreign key is a find by its id, the same single request: client.users.find(ticket.customer_id) for ticket.related.customer. A key that may be nil, such as a user's organization_id, needs a nil check before the find. - Nothing outside a record reads its transport any more, so the reader is private. ticket.articles, ticket.add_article and article.attachments still use it, so they keep working with only the record in hand. - Base#initialize_copy goes: it only reset the association cache. --- CHANGELOG.md | 7 +- README.md | 35 +- lib/zammad_api.rb | 1 - lib/zammad_api/associations.rb | 72 ----- lib/zammad_api/resources/base.rb | 56 +--- lib/zammad_api/resources/ticket.rb | 7 - lib/zammad_api/resources/ticket_article.rb | 2 - lib/zammad_api/resources/user.rb | 2 - sig/zammad_api/associations.rbs | 37 --- sig/zammad_api/resources/base.rbs | 10 +- spec/typed/usage.rb | 2 +- .../zammad_api/associations/proxy_spec.rb | 306 ------------------ spec/unit/zammad_api/resources/base_spec.rb | 8 - spec/unit/zammad_api/test_spec.rb | 2 +- 14 files changed, 23 insertions(+), 524 deletions(-) delete mode 100644 lib/zammad_api/associations.rb delete mode 100644 sig/zammad_api/associations.rbs delete mode 100644 spec/unit/zammad_api/associations/proxy_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e26330..ff7bed4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -189,11 +189,6 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a of the Zammad instance. - `Response#decoded(:object | :array)` checks the shape of a response body in one place, so an unexpected payload raises `ParseError`. -- `record.related` reaches the records a record points at: `ticket.related.customer`, - `ticket.related.group`, `user.related.organization`, and `created_by` / `updated_by` on - everything. The readers sit under `related` because Zammad expands an association into - a name under the plain attribute, and `ticket.customer` keeps returning that name. `Resource.associations` lists what a - resource declares. - Records compare as the Zammad records they came from: two records of the same kind with the same id are equal, and `#hash` agrees, so `uniq`, `Set`, `include?` and records as Hash keys all work. A record with no id stays equal only to itself. @@ -203,7 +198,7 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `client.resource(SomeClass)` takes a subclass of `ZammadAPI::Resources::Base` and answers with a proxy for it, so an endpoint this gem does not model gets records, pagination, `find_by`, change tracking and `save` from a class that declares its `path`. `searchable`, - `max_per_page`, `sortable` and `belongs_to` say what else is true of the endpoint. + `max_per_page` and `sortable` say what else is true of the endpoint. - Typed records. `ResourceProxy` and `Collection` are generic over the resource they hold, so `client.tickets` is a `ResourceProxy[Resources::Ticket]` and `find`, `first`, `find_by`, the block of `each` and a search all answer with a `Ticket`. Each resource diff --git a/README.md b/README.md index d90e9a0..c3a179a 100644 --- a/README.md +++ b/README.md @@ -297,11 +297,9 @@ Say what else is true of the endpoint, where it differs from the defaults: | `searchable true` | `false` | Zammad routes `/search`, so `search` works and `find_by` uses it. | | `max_per_page 100` | `1000` | The largest page the index endpoint serves. A walk ends at the first page shorter than the size it asked for, so this has to be what the endpoint really serves. | | `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. | -| `belongs_to :role, class_name: 'Role'` | — | A foreign key, read as a record through `record.related.role`. | -`class_name` is a resource of this gem by its own name, `'User'`, or a class of yours by its -full name, `'Acme::Role'`. A subclass of a modelled resource works too, and inherits what -its parent declares: `class MyTicket < ZammadAPI::Resources::Ticket`. +A subclass of a modelled resource works too, and inherits what its parent declares: +`class MyTicket < ZammadAPI::Resources::Ticket`. An endpoint that serves every record in one response and ignores `page` — `api/v1/object_manager_attributes` is one — is still read in one request, because its first @@ -557,14 +555,19 @@ ticket.group # => "Users" ticket.customer_id # => 7 ``` -`related` reaches the whole record behind one of those, which costs a request: +The whole record behind one of those is a `find` by its id, which costs a request: ```ruby -ticket.related.customer.firstname # => "Nicole" -ticket.related.group.note -ticket.related.created_by.email +client.users.find(ticket.customer_id).firstname # => "Nicole" +client.groups.find(ticket.group_id).note +client.users.find(ticket.created_by_id).email +``` + +A foreign key that may be empty, such as a user's `organization_id`, is `nil` then, and +`find` needs an id: -client.users.find(7).related.organization +```ruby +user.organization_id && client.organizations.find(user.organization_id) ``` A ticket's articles come from an endpoint of their own. `articles` reads the whole list in @@ -575,11 +578,7 @@ ticket.articles # => [TicketArticle ticket.add_article(body: 'Reset link sent.', type: 'note') # => the created TicketArticle ``` -The readers live under `related` rather than on the record so that `ticket.customer` keeps -returning the name it always did — an attribute read that silently became an HTTP request -would be a poor trade. `related` targets are memoized until the next attribute write, -`reload` or save; `articles` is fetched on each call, so an article added in between -shows up. `Ticket.associations` lists what a resource declares. +`articles` is fetched on each call, so an article added in between shows up. ### Comparing and serializing @@ -1037,10 +1036,9 @@ supported Zammad serves for it: ```ruby ticket = client.tickets.find(1) -ticket.title # String -ticket.organization_id # Integer? -ticket.related.customer&.email # String? -ticket.titel # a type error, where it used to be untyped +ticket.title # String +ticket.organization_id # Integer? +ticket.titel # a type error, where it used to be untyped ``` Three things are deliberately not declared, and each has a way through: @@ -1215,7 +1213,6 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | `record.new_instance` | `record.new_record?` / `record.persisted?` | Internal flag is no longer public; the old name raises `NoMethodError` | | `resource.url` (instance) | `Resource.resource_path` (class) | Clashed with an attribute named `url` | | `record.unknown_attribute` → `nil` | raises `NoMethodError`; use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` | A typo read as `nil` and flowed on into whatever was written with it. Zammad also serves a reduced object where the user may not see the whole record, and that is worth being told about | -| `client.users.find(ticket.customer_id)` | `ticket.related.customer` | Following a foreign key needed the client threaded through | | `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | A noun that sends a `POST`, one letter away from `ticket.articles`, which only reads. The method is gone: `article` is an attribute reader like any other, and the old call raises `NoMethodError` | ### Errors diff --git a/lib/zammad_api.rb b/lib/zammad_api.rb index 4e1a126..7bbba75 100644 --- a/lib/zammad_api.rb +++ b/lib/zammad_api.rb @@ -7,7 +7,6 @@ require_relative 'zammad_api/response' require_relative 'zammad_api/transport' require_relative 'zammad_api/attribute_access' -require_relative 'zammad_api/associations' require_relative 'zammad_api/collection' require_relative 'zammad_api/resources' require_relative 'zammad_api/resource_proxy' diff --git a/lib/zammad_api/associations.rb b/lib/zammad_api/associations.rb deleted file mode 100644 index e698fcb..0000000 --- a/lib/zammad_api/associations.rb +++ /dev/null @@ -1,72 +0,0 @@ -# frozen_string_literal: true - -module ZammadAPI - # Readers for the records a record points at. - module Associations - # Fetches the records an association points at. - # - # Reached through +record.related+, never built directly. The readers live - # here rather than on the record itself because Zammad already expands an - # association into a name: +ticket.customer+ is the customer's login and - # +ticket.state+ is +"open"+, both free of charge. An association reader - # returns the whole record and costs a request, so it is worth telling the - # two apart at the call site. - # - # @example - # ticket = client.tickets.find(1) - # - # ticket.customer # => "customer@example.com", already loaded - # ticket.related.customer # => the User record, one request - # ticket.related.customer.email # => "customer@example.com" - class Proxy - # @api private - # @param record [Resources::Base] - def initialize(record) - @record = record - @cache = {} - end - - def inspect - "#<#{Proxy.name} #{@record.class.name} id=#{@record.id.inspect} #{associations.keys.join(', ')}>" - end - - # Drops the records read so far, so the next read follows the record's - # current foreign keys. - # - # @api private - # @return [void] - def forget - @cache = {} - end - - def method_missing(name, *args) - spec = associations[name] - return super if spec.nil? || !args.empty? - - target(name, spec) - end - - def respond_to_missing?(name, include_private = false) = associations.key?(name) || super - - private - - def associations = @record.class.associations - - # The record a foreign key points at, read once and kept: nil when the - # key is nil. - def target(name, spec) - return @cache[name] if @cache.key?(name) - - id = @record[spec[:foreign_key]] - @cache[name] = id.nil? ? nil : resolve(spec[:class_name]).fetch_one(@record.transport, id) - end - - # A resource of this gem by its own name, or any class by its full name. - def resolve(class_name) - return Resources.const_get(class_name, false) if Resources.const_defined?(class_name, false) - - Object.const_get(class_name) - end - end - end -end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 16c175d..bc5ffdc 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -1,6 +1,5 @@ # frozen_string_literal: true -require_relative '../associations' require_relative '../attribute_access' require_relative '../deep_copy' require_relative '../errors' @@ -31,9 +30,6 @@ class Base # @return [ValidationError, nil] attr_reader :error - # @api private - attr_reader :transport - class << self # Each declaration defines the reader of the same setting on this # class, which a subclass inherits and can declare again. @@ -107,37 +103,8 @@ def from_response(transport, attributes) record.send(:mark_persisted!) record end - - # Every association this resource declares, including inherited ones. - # - # @return [Hash{Symbol => Hash}] - def associations - inherited = superclass.respond_to?(:associations) ? superclass.associations : {} # steep:ignore NoMethod - inherited.merge(declared_associations) - end - - private - - def declared_associations = @declared_associations ||= {} - - # Declares that this resource points at a single other record, through - # a foreign key on itself. Read through +record.related.+. - # - # @param name [Symbol] name of the reader on {Base#related} - # @param class_name [String] the target resource: one of this gem by its - # own name, +'User'+, or another by its full name, +'Acme::Role'+ - # @param foreign_key [Symbol] attribute holding the target's id - # @return [void] - def belongs_to(name, class_name:, foreign_key: :"#{name}_id") - declared_associations[name] = { class_name: class_name, foreign_key: foreign_key } - end end - # Zammad stamps every object with the user that created and last - # touched it. - belongs_to :created_by, class_name: 'User' - belongs_to :updated_by, class_name: 'User' - # @param transport [Transport] # @param attributes [Hash, nil] or what converts to a Hash, such as # permitted `ActionController::Parameters` @@ -148,15 +115,6 @@ def initialize(transport, attributes = {}) @new_record = true @destroyed = false @error = nil - @related = nil - end - - # @api private - # @param source [Base] - # @return [void] - def initialize_copy(source) - super - @related = nil end # @return [Boolean] whether this record has not been stored yet @@ -181,16 +139,6 @@ def changes # @return [Boolean] whether there are staged changes def changed? = !changes.empty? - # The records this one points at. - # - # @example - # ticket.related.customer # => the User record, one request - # - # @return [Associations::Proxy] - def related - @related ||= Associations::Proxy.new(self) - end - # Stages several changes at once. # # @param attributes [Hash] @@ -279,6 +227,8 @@ def inspect = "#<#{self.class.name} id=#{id.inspect} new_record=#{new_record?}#{ private + attr_reader :transport + def mark_persisted! @new_record = false end @@ -287,7 +237,6 @@ def load_response!(response, operation) @attributes = frozen_attributes(response.decoded(:object, operation: operation, resource_class: self.class)) @baseline = @attributes @new_record = false - @related&.forget end def raise_if_new!(operation) @@ -301,7 +250,6 @@ def write_attribute(key, value) staged = frozen_attributes(value) @attributes = @attributes.merge(key => staged).freeze - @related&.forget staged end diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index 0edebc0..62bfb6f 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -18,13 +18,6 @@ class Ticket < Base searchable true - belongs_to :customer, class_name: 'User' - belongs_to :owner, class_name: 'User' - belongs_to :organization, class_name: 'Organization' - belongs_to :group, class_name: 'Group' - belongs_to :state, class_name: 'TicketState' - belongs_to :priority, class_name: 'TicketPriority' - # Every article of this ticket, read in one request on each call. # # @return [Array] diff --git a/lib/zammad_api/resources/ticket_article.rb b/lib/zammad_api/resources/ticket_article.rb index 9492e34..136dd2a 100644 --- a/lib/zammad_api/resources/ticket_article.rb +++ b/lib/zammad_api/resources/ticket_article.rb @@ -8,8 +8,6 @@ module Resources class TicketArticle < Base path 'api/v1/ticket_articles' - belongs_to :ticket, class_name: 'Ticket' - # @return [Array] the article's attachments def attachments (attributes[:attachments] || []).map do |raw| diff --git a/lib/zammad_api/resources/user.rb b/lib/zammad_api/resources/user.rb index a261fa9..db2ec1c 100644 --- a/lib/zammad_api/resources/user.rb +++ b/lib/zammad_api/resources/user.rb @@ -12,8 +12,6 @@ class User < Base sortable false searchable true - - belongs_to :organization, class_name: 'Organization' end end end diff --git a/sig/zammad_api/associations.rbs b/sig/zammad_api/associations.rbs deleted file mode 100644 index 3544661..0000000 --- a/sig/zammad_api/associations.rbs +++ /dev/null @@ -1,37 +0,0 @@ -module ZammadAPI - module Associations - # The readers are answered through method_missing, from the belongs_to - # declarations in lib/zammad_api/resources. The ones this gem - # declares are listed here so that callers get types and completion; every - # name means the same target wherever it is declared, so the type of a - # given reader is accurate. The class is wider than any one resource, so - # a reader the record does not declare type-checks here and raises - # NoMethodError at runtime. - class Proxy - @record: Resources::Base - @cache: Hash[Symbol, untyped] - - def initialize: (Resources::Base record) -> void - def inspect: () -> String - def forget: () -> void - def method_missing: (Symbol, *untyped) -> untyped - def respond_to_missing?: (Symbol, ?bool) -> bool - - def created_by: () -> Resources::User? - def updated_by: () -> Resources::User? - def customer: () -> Resources::User? - def owner: () -> Resources::User? - def organization: () -> Resources::Organization? - def group: () -> Resources::Group? - def state: () -> Resources::TicketState? - def priority: () -> Resources::TicketPriority? - def ticket: () -> Resources::Ticket? - - private - - def associations: () -> Hash[Symbol, Hash[Symbol, untyped]] - def target: (Symbol name, Hash[Symbol, untyped] spec) -> untyped - def resolve: (String class_name) -> untyped - end - end -end diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 8d46eba..39b4cb1 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -6,7 +6,6 @@ module ZammadAPI DEFAULT_MAX_PER_PAGE: Integer attr_reader error: ValidationError? - attr_reader transport: Transport # What Zammad stamps every record with. These four are columns of every # table, and the two names beside them are what `expand` adds: the login @@ -23,9 +22,7 @@ module ZammadAPI @new_record: bool @destroyed: bool @error: ValidationError? - @related: Associations::Proxy? @baseline: Hash[Symbol, untyped] - self.@declared_associations: Hash[Symbol, Hash[Symbol, untyped]]? def self.path: (String) -> void def self.searchable: (bool) -> void @@ -38,9 +35,6 @@ module ZammadAPI def self.member_path: ((Integer | String) id) -> String def self.fetch_one: (Transport transport, (Integer | String) id) -> Base def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> Base - def self.associations: () -> Hash[Symbol, Hash[Symbol, untyped]] - def self.declared_associations: () -> Hash[Symbol, Hash[Symbol, untyped]] - def self.belongs_to: (Symbol name, class_name: String, ?foreign_key: Symbol) -> void def initialize: (Transport, ?hash[untyped, untyped]? attributes) -> void def new_record?: () -> bool @@ -48,7 +42,6 @@ module ZammadAPI def destroyed?: () -> bool def changes: () -> Hash[Symbol, Array[untyped]] def changed?: () -> bool - def related: () -> Associations::Proxy def assign_attributes: (hash[untyped, untyped] attributes) -> self def save: () -> bool def save!: () -> true @@ -60,7 +53,8 @@ module ZammadAPI private - def initialize_copy: (self source) -> void + attr_reader transport: Transport + def mark_persisted!: () -> void def load_response!: (Response response, String operation) -> void def raise_if_new!: (String operation) -> void diff --git a/spec/typed/usage.rb b/spec/typed/usage.rb index c90fd91..f36f307 100644 --- a/spec/typed/usage.rb +++ b/spec/typed/usage.rb @@ -50,7 +50,7 @@ def self.batches(client) sizes end - def self.customer_email(client) = client.tickets.find(1).related.customer&.email + def self.customer_email(client) = client.users.find(client.tickets.find(1).customer_id).email def self.article_bodies(client) = client.tickets.find(1).articles.map(&:body) diff --git a/spec/unit/zammad_api/associations/proxy_spec.rb b/spec/unit/zammad_api/associations/proxy_spec.rb deleted file mode 100644 index cf40862..0000000 --- a/spec/unit/zammad_api/associations/proxy_spec.rb +++ /dev/null @@ -1,306 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe ZammadAPI::Associations::Proxy do - subject(:ticket) { client.tickets.find(42) } - - let(:client) { unit_client } - let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/42" } - let(:users_url) { "#{ClientHelper::BASE_URL}api/v1/users" } - - let(:ticket_attributes) do - { - id: 42, - title: 'Help', - customer: 'customer@example.com', - customer_id: 7, - state: 'open', - state_id: 2, - group: 'Users', - group_id: 1 - } - end - - before do - stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response(ticket_attributes)) - end - - describe 'belongs_to' do - it 'fetches the whole record behind a foreign key' do - stub_request(:get, "#{users_url}/7").with(query: { 'expand' => 'true' }) - .to_return(json_response({ id: 7, email: 'customer@example.com', firstname: 'Nicole' })) - - expect(ticket.related.customer.firstname).to eq('Nicole') - end - - it 'returns the resource class of the target' do - stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) - - expect(ticket.related.customer).to be_a(ZammadAPI::Resources::User) - end - - it 'returns a persisted record' do - stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) - - expect(ticket.related.customer).to be_persisted - end - - it 'leaves the expanded attribute alone, so reading a name stays free' do - expect(ticket.customer).to eq('customer@example.com') - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).not_to have_been_made - end - - it 'does not shadow an expanded attribute that names a state' do - expect(ticket.state).to eq('open') - end - - it 'is nil when the foreign key is not set' do - stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 42 })) - - expect(ticket.related.customer).to be_nil - end - - it 'makes no request when the foreign key is not set' do - stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 42 })) - - ticket.related.customer - expect(a_request(:get, %r{api/v1/users}).with(query: hash_including({}))).not_to have_been_made - end - - it 'memoizes, so a loop does not refetch the same record' do - stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) - - held = ticket - 3.times { held.related.customer } - - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.once - end - - it 'uses the declared foreign key rather than the association name' do - stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/ticket_states/2") - .with(query: hash_including({})) - .to_return(json_response({ id: 2, name: 'open' })) - - ticket.related.state - expect(stub).to have_been_requested - end - - it 'reaches the group resource' do - stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/groups/1") - .with(query: hash_including({})) - .to_return(json_response({ id: 1, name: 'Users' })) - - expect(ticket.related.group.name).to eq('Users') - expect(stub).to have_been_requested - end - - it 'propagates a failure to load the target' do - stub_request(:get, "#{users_url}/7").with(query: hash_including({})) - .to_return(json_response({ error: 'not found' }, status: 404)) - - expect { ticket.related.customer }.to raise_error(ZammadAPI::NotFoundError) - end - end - - describe 'inheritance' do - it 'gives every resource the stamps Zammad puts on every object' do - expect(ZammadAPI::Resources::Group.associations.keys).to eq(%i[created_by updated_by]) - end - - it 'adds a resource its own associations on top' do - expect(ZammadAPI::Resources::User.associations.keys).to include(:created_by, :organization) - end - - it 'does not leak one resource\'s associations into another' do - expect(ZammadAPI::Resources::Group.associations).not_to have_key(:customer) - end - - it 'does not define another resource\'s reader on the proxy' do - group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) - expect(group.related).not_to respond_to(:customer) - end - - it 'raises NoMethodError for an association that was never declared' do - expect { ticket.related.unicorn }.to raise_error(NoMethodError) - end - end - - describe 'the memo' do - before do - stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) - end - - it 'is dropped by reload, because the foreign key may have moved' do - held = ticket - held.related.customer - held.reload - held.related.customer - - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice - end - - it 'is dropped by a save' do - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(json_response(ticket_attributes)) - - held = ticket - held.related.customer - held.update!(title: 'Renamed') - held.related.customer - - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice - end - - it 'is dropped when the foreign key it resolved from is written' do - stub_request(:get, "#{users_url}/9").with(query: hash_including({})) - .to_return(json_response({ id: 9, email: 'nine@example.com' })) - - held = ticket - expect(held.related.customer.id).to eq(7) - - held.customer_id = 9 - - expect(held.related.customer.id).to eq(9) - end - - it 'is dropped by a write to any attribute' do - held = ticket - held.related.customer - held.title = 'Renamed' - held.related.customer - - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice - end - - it 'is dropped by assign_attributes touching a foreign key' do - stub_request(:get, "#{users_url}/9").with(query: hash_including({})) - .to_return(json_response({ id: 9 })) - - held = ticket - held.related.customer - held.assign_attributes(title: 'Renamed', customer_id: 9) - - expect(held.related.customer.id).to eq(9) - end - end - - describe 'a proxy the caller kept' do - let(:related) { ticket.related } - - before do - stub_request(:get, "#{users_url}/7").with(query: hash_including({})).to_return(json_response({ id: 7 })) - stub_request(:get, "#{users_url}/9").with(query: hash_including({})).to_return(json_response({ id: 9 })) - end - - it 'is the one the record goes on handing out' do - related.customer - ticket.customer_id = 9 - - expect(ticket.related).to be(related) - end - - it 'follows a foreign key that was written' do - expect(related.customer.id).to eq(7) - - ticket.customer_id = 9 - - expect(related.customer.id).to eq(9) - end - - it 'follows a foreign key that assign_attributes wrote' do - related.customer - ticket.assign_attributes(title: 'Renamed', customer_id: 9) - - expect(related.customer.id).to eq(9) - end - - it 'follows a foreign key that a reload moved' do - related.customer - stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response(ticket_attributes.merge(customer_id: 9))) - ticket.reload - - expect(related.customer.id).to eq(9) - end - - it 'fetches the target again after a reload that left the foreign key alone' do - related.customer - ticket.reload - related.customer - - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice - end - - it 'fetches the target again after a save' do - stub_request(:put, ticket_url).with(query: hash_including({})).to_return(json_response(ticket_attributes)) - - related.customer - ticket.update!(title: 'Renamed') - related.customer - - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice - end - - it 'fetches the target again after a write to any attribute' do - related.customer - ticket.title = 'Renamed' - related.customer - - expect(a_request(:get, "#{users_url}/7").with(query: hash_including({}))).to have_been_made.twice - end - - it 'leaves the proxy of a copy to the copy' do - related.customer - copy = ticket.dup - copy.customer_id = 9 - - expect(related.customer.id).to eq(7) - expect(copy.related.customer.id).to eq(9) - end - end - - describe '#inspect' do - it 'names the record and what can be reached from it' do - expect(ticket.related.inspect) - .to eq( - '#' - ) - end - end - - # A resource a caller declares can point at another of theirs, which is in - # no namespace of this gem. - describe 'an association declared on a resource a caller wrote' do - before do - stub_const('Acme::Role', Class.new(ZammadAPI::Resources::Base) { path 'api/v1/roles' }) - stub_const('Acme::Membership', Class.new(ZammadAPI::Resources::Base) do - path 'api/v1/memberships' - belongs_to :role, class_name: 'Acme::Role' - belongs_to :user, class_name: 'User' - end) - end - - let(:membership) { Acme::Membership.from_response(unit_transport, id: 1, role_id: 2, user_id: 3) } - - it 'resolves a target named by its full name' do - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/roles/2").with(query: hash_including({})) - .to_return(json_response({ id: 2, name: 'Agent' })) - - expect(membership.related.role).to be_a(Acme::Role) - end - - it 'still resolves a resource of this gem by its own name' do - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/3").with(query: hash_including({})) - .to_return(json_response({ id: 3, login: 'agent' })) - - expect(membership.related.user).to be_a(ZammadAPI::Resources::User) - end - - # An application is likely to have a User of its own at the top level. - it 'prefers the resource of this gem over a top-level constant of the same name' do - stub_const('User', Class.new) - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/3").with(query: hash_including({})) - .to_return(json_response({ id: 3, login: 'agent' })) - - expect(membership.related.user).to be_a(ZammadAPI::Resources::User) - end - end -end diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index 830e173..7ec0cea 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -699,10 +699,6 @@ def self.name it 'is still the same Zammad record' do expect(copy).to eq(original) end - - it 'gets association readers of its own, not the ones bound to the original' do - expect(copy.related).not_to be(original.related) - end end end end @@ -839,10 +835,6 @@ def self.name expect(subclass.sortable?).to be(false) end - it 'inherits the associations' do - expect(subclass.associations.keys).to eq(ZammadAPI::Resources::Ticket.associations.keys) - end - it 'lets a subclass declare a path of its own' do own = Class.new(ZammadAPI::Resources::Ticket) { path 'api/v1/my_tickets' } diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 84131a0..332e9ec 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -155,7 +155,7 @@ zammad.stub(:get, 'api/v1/ticket_attachment/1/2/3', body: 'binary-ish') attachment = ZammadAPI::Resources::TicketArticleAttachment - .new(zammad.client.tickets.new.transport, id: 3, ticket_id: 1, article_id: 2) + .new(zammad.client.instance_variable_get(:@transport), id: 3, ticket_id: 1, article_id: 2) expect(attachment.download).to eq('binary-ish') end From 40795e0618ff61485f2e2555c7a2a95782bee375 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 25 Nov 2026 10:30:25 +0200 Subject: [PATCH 092/121] refactor: read Client#me through users.find users.find('me') sends the same GET to api/v1/users/me with expand, checks the body is an object and builds the same User record. A failure now reads "Can't find object (ZammadAPI::Resources::User)" rather than "Can't find current user"; the error class is the same. --- lib/zammad_api/client.rb | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index e0699c5..9b7f69d 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -156,16 +156,7 @@ def resource_names = RESOURCES.keys # # @return [Resources::User] # @raise [AuthenticationError] when the credentials are not valid - def me - operation = 'find current user' - response = @transport.get( - "#{Resources::User.resource_path}/me", - operation: operation, - resource_class: Resources::User, - query: { expand: true } - ) - Resources::User.from_response(@transport, response.decoded(:object, operation: operation, resource_class: Resources::User)) - end + def me = users.find('me') # The version of the Zammad instance, not of this gem — that is # {ZammadAPI::VERSION}. Zammad serves it to administrators only. From 66faa6473c70120712fcc9c094d027f124c9660f Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 25 Nov 2026 10:30:29 +0200 Subject: [PATCH 093/121] chore: drop the has_many exemption from the RuboCop config has_many and has_many_target went in 82e27e2, and nothing else in the code needs Naming/PredicatePrefix relaxed. --- .rubocop.yml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index f6254f4..feb48e9 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -42,13 +42,6 @@ Layout/HashAlignment: Style/ClassAndModuleChildren: Enabled: false -Naming/PredicatePrefix: - # `has_many` is the established name for the declaration, and neither it nor - # the reader behind it is a predicate. - AllowedMethods: - - has_many - - has_many_target - Naming/MethodParameterName: # `of` is ActiveRecord's name for a batch size, see Collection#in_batches. AllowedNames: [id, to, of] From e1b737f1a53b51d2725654c6bc0bc7629c12f764 Mon Sep 17 00:00:00 2001 From: Mantas Date: Wed, 25 Nov 2026 10:35:03 +0200 Subject: [PATCH 094/121] docs: drop cruft from the README, CHANGELOG and examples README: - The Development section names rake rbs_published, which the default task has run alongside Steep. - Two notes about rare cases go: rehashing a record used as a Hash key before its first save, and how Zammad reads group_ids, role_ids and permissions on a user search. CHANGELOG, 2.0.0.alpha1: - Changed loses the entries that compared against earlier 2.0 drafts rather than 1.x (frozen Response#headers, DeepCopy, the class of UnstubbedRequestError) and two that repeated an entry above it (explicit resource dispatch, the endpoint declarations). - Added loses the internal detail: keyword of ResponseError, and the test kit entry names UnstubbedRequestError and why it is not a ZammadAPI::Error. examples/README.md no longer says linting keeps the examples from rotting: RuboCop does not catch a call to a method that is gone, and nothing runs or type-checks them. --- CHANGELOG.md | 13 ++----------- README.md | 12 +++--------- examples/README.md | 3 --- 3 files changed, 5 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff7bed4..1ef778d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -150,8 +150,6 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a record that carries all the values, or `nil`: by its id where `id:` is given, through a search where the resource has one and a String value is given, and by walking the index everywhere else. -- `ResponseError` accepts a `detail:` describing a failure that has no HTTP response of its - own, so `find_by!` reads as `no record matched`. - The page size is clamped to what an endpoint serves (100 for `/api/v1/tickets`, 200 for a search, 1000 for the other index endpoints). Asking for more used to end iteration after the first page, because Zammad capped the response and the short page read as the @@ -176,7 +174,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a wired to them, and `#requests` records what was sent, with the query as text and the headers by downcased name. Responses travel the same decoding, error mapping and record building as real ones, so a stubbed 404 raises `NotFoundError`. An unstubbed request - raises rather than answering with something empty. + raises `ZammadAPI::Test::UnstubbedRequestError` rather than answering with something + empty. It is not a `ZammadAPI::Error`, so the code under test cannot rescue it. - `respond_to?` answers correctly for attribute readers and resource methods. - Records implement `deconstruct_keys`, so they can be used with `case/in` pattern matching. `Config` and `Response` are `Data` objects and match as well. @@ -239,17 +238,11 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a ### Changed -- `Response#headers` is frozen, and each response carries its own. - `client..destroy(id)` deletes directly instead of fetching the record first. -- Resource dispatch is explicit rather than `method_missing` plus `const_get`. -- A resource declares what its endpoint does — `searchable true`, `max_per_page 100`, - `sortable false` — the way it declares `path`. - `client.` returns the same proxy each time rather than allocating one per call. The proxies are built with the client, so a client stays immutable once built and safe to share between threads. - A String request body is sent as it is rather than encoded as a JSON string. -- The recursive copy behind frozen attributes, `to_h` and the test kit's recorded bodies - lives in one place (`ZammadAPI::DeepCopy`) instead of being written once per caller. - Unit specs (`rake spec:unit`) run without a Zammad instance; the specs that need a live server live in `spec/integration`, and run only where `TEST_URL` names one. - CI runs RuboCop, Steep and the unit specs on every supported stable Ruby, and publishes @@ -259,8 +252,6 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a failure, and runs `script/check_connection.rb` as a preflight. - The integration suite no longer depends on spec file order to run Zammad's auto wizard, and tolerates an instance that is already set up. -- `Test::UnstubbedRequestError` is a `StandardError` rather than a `ZammadAPI::Error`, so - a forgotten stub is not caught by the `rescue ZammadAPI::Error` in the code under test. ## [1.4.0] - 2026-08-25 - Follow up - c3af2a9 - Fixes #29 - [JSON::ParserError on gateway timeout when proxy responds with HTML](https://github.com/zammad/zammad-api-client-ruby/issues/29) diff --git a/README.md b/README.md index c3a179a..fea9fba 100644 --- a/README.md +++ b/README.md @@ -593,9 +593,7 @@ client.tickets.find(1) == client.tickets.find(1) # => true ``` A record with no id is equal only to itself, because two unsaved records are two records -waiting to be created however alike their attributes are. A record's first save assigns -its id and so changes its hash, and a record used as a Hash key before that save has to be -rehashed after it. +waiting to be created however alike their attributes are. `to_json` renders the attributes, and `as_json` returns them as a Hash: @@ -711,11 +709,6 @@ Zammad ignores a parameter it does not read, so a misspelled keyword, or a user another resource, comes back unnarrowed. Tickets are narrowed by group with a `condition` on `ticket.group_id`, as above. -`group_ids: [1]` names no access, and Zammad reads that as `full`; a Hash names the access -for each group, as in `group_ids: {1 => ['read']}`. Neither `role_ids:` nor `permissions:` -is an access check: a user matches a role that has been disabled, and a deactivated user -matches as well. - Zammad routes a search endpoint per model, not for every model. `users`, `organizations`, `tickets` and `groups` have one; `ticket_states`, `ticket_priorities` and `ticket_articles` do not, and `search` on those raises `ZammadAPI::Error`. `find_by` works on them all the @@ -1079,7 +1072,7 @@ attachments, error handling and threaded use live in [`examples/`](examples/READ ```sh bin/setup # or: bundle install -bundle exec rake # unit specs, RuboCop and Steep +bundle exec rake # unit specs, RuboCop, Steep and the shipped signatures ``` | Task | What it does | @@ -1089,6 +1082,7 @@ bundle exec rake # unit specs, RuboCop and Steep | `rake check_connection` | Drives a live Zammad end to end and prints a transcript | | `rake rubocop` | Style checks | | `rake steep` | Type-check `lib/` against `sig/`, and `spec/typed/` the way a caller is checked | +| `rake rbs_published` | Validate the signatures the gem ships, without `sig/vendor/` | Set `COVERAGE=true` to produce a coverage report in `coverage/`. diff --git a/examples/README.md b/examples/README.md index bfc0a82..763e7df 100644 --- a/examples/README.md +++ b/examples/README.md @@ -39,6 +39,3 @@ examples show what is left for your own code to do. A write is never repeated; | [`download_attachments.rb`](download_attachments.rb) | Saves a ticket's attachments to disk | `articles`, attachment metadata, binary-safe `download` | | [`error_handling.rb`](error_handling.rb) | Handles the failures that are yours to handle | The error hierarchy, `save` → `false` with `record.error`, rescuing by category, `client.with` for different retry settings | | [`concurrent_sync.rb`](concurrent_sync.rb) | Syncs tickets with a worker pool sharing one client | Immutable clients are thread-safe; also sketches the Rails initializer pattern | - -The examples are linted along with the rest of the repository (`rake rubocop`), -so they cannot silently rot. From 8996febb66ccd14bec72fb481aa0ae5fe4119d23 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 13:33:08 +0200 Subject: [PATCH 095/121] refactor: drop the internal requires that lib/zammad_api.rb already makes Each file under lib/zammad_api repeated its internal dependencies, though nothing loads one of them on its own and the entry file requires them all in order. --- lib/zammad_api/attribute_access.rb | 2 -- lib/zammad_api/client.rb | 6 ------ lib/zammad_api/collection.rb | 2 -- lib/zammad_api/config.rb | 3 --- lib/zammad_api/resource_proxy.rb | 4 ---- lib/zammad_api/resources/base.rb | 5 ----- lib/zammad_api/resources/group.rb | 2 -- lib/zammad_api/resources/organization.rb | 2 -- lib/zammad_api/resources/ticket.rb | 3 --- lib/zammad_api/resources/ticket_article.rb | 3 --- lib/zammad_api/resources/ticket_article_attachment.rb | 3 --- lib/zammad_api/resources/ticket_priority.rb | 2 -- lib/zammad_api/resources/ticket_state.rb | 2 -- lib/zammad_api/resources/user.rb | 2 -- lib/zammad_api/response.rb | 2 -- lib/zammad_api/transport.rb | 3 --- 16 files changed, 46 deletions(-) diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb index c5666dd..9b03170 100644 --- a/lib/zammad_api/attribute_access.rb +++ b/lib/zammad_api/attribute_access.rb @@ -2,8 +2,6 @@ require 'json' -require_relative 'deep_copy' - module ZammadAPI # Read access to a Zammad record's attributes. # diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index 9b7f69d..2fdd0e0 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -1,11 +1,5 @@ # frozen_string_literal: true -require_relative 'config' -require_relative 'errors' -require_relative 'resource_proxy' -require_relative 'resources' -require_relative 'transport' - module ZammadAPI # The entry point of this gem. # diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb index 13b37b1..cff8f60 100644 --- a/lib/zammad_api/collection.rb +++ b/lib/zammad_api/collection.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require_relative 'errors' - module ZammadAPI # A lazily fetched, automatically paginated list of records. # diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index bbe4292..0a53878 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -3,9 +3,6 @@ require 'logger' require 'uri' -require_relative 'errors' -require_relative 'version' - module ZammadAPI # Immutable, validated client configuration. # diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index 8ace8f6..42a7dbf 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -2,10 +2,6 @@ require 'forwardable' -require_relative 'collection' -require_relative 'errors' -require_relative 'transport' - module ZammadAPI # Entry point for working with one kind of Zammad record. # diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index bc5ffdc..82ceeaf 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -1,10 +1,5 @@ # frozen_string_literal: true -require_relative '../attribute_access' -require_relative '../deep_copy' -require_relative '../errors' -require_relative '../transport' - module ZammadAPI module Resources # Shared behaviour for every Zammad record. diff --git a/lib/zammad_api/resources/group.rb b/lib/zammad_api/resources/group.rb index 7e3cd64..7e95657 100644 --- a/lib/zammad_api/resources/group.rb +++ b/lib/zammad_api/resources/group.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require_relative 'base' - module ZammadAPI module Resources class Group < Base diff --git a/lib/zammad_api/resources/organization.rb b/lib/zammad_api/resources/organization.rb index 2ffd0a3..1935985 100644 --- a/lib/zammad_api/resources/organization.rb +++ b/lib/zammad_api/resources/organization.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require_relative 'base' - module ZammadAPI module Resources class Organization < Base diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index 62bfb6f..31afed2 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -1,8 +1,5 @@ # frozen_string_literal: true -require_relative 'base' -require_relative 'ticket_article' - module ZammadAPI module Resources class Ticket < Base diff --git a/lib/zammad_api/resources/ticket_article.rb b/lib/zammad_api/resources/ticket_article.rb index 136dd2a..f9620d2 100644 --- a/lib/zammad_api/resources/ticket_article.rb +++ b/lib/zammad_api/resources/ticket_article.rb @@ -1,8 +1,5 @@ # frozen_string_literal: true -require_relative 'base' -require_relative 'ticket_article_attachment' - module ZammadAPI module Resources class TicketArticle < Base diff --git a/lib/zammad_api/resources/ticket_article_attachment.rb b/lib/zammad_api/resources/ticket_article_attachment.rb index 7204982..70ef348 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -1,8 +1,5 @@ # frozen_string_literal: true -require_relative '../attribute_access' -require_relative '../transport' - module ZammadAPI module Resources # An attachment of a ticket article. diff --git a/lib/zammad_api/resources/ticket_priority.rb b/lib/zammad_api/resources/ticket_priority.rb index a02df3c..cd68656 100644 --- a/lib/zammad_api/resources/ticket_priority.rb +++ b/lib/zammad_api/resources/ticket_priority.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require_relative 'base' - module ZammadAPI module Resources class TicketPriority < Base diff --git a/lib/zammad_api/resources/ticket_state.rb b/lib/zammad_api/resources/ticket_state.rb index 091aa4d..ec9c4fe 100644 --- a/lib/zammad_api/resources/ticket_state.rb +++ b/lib/zammad_api/resources/ticket_state.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require_relative 'base' - module ZammadAPI module Resources class TicketState < Base diff --git a/lib/zammad_api/resources/user.rb b/lib/zammad_api/resources/user.rb index db2ec1c..6442735 100644 --- a/lib/zammad_api/resources/user.rb +++ b/lib/zammad_api/resources/user.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require_relative 'base' - module ZammadAPI module Resources class User < Base diff --git a/lib/zammad_api/response.rb b/lib/zammad_api/response.rb index abc0ef0..d652894 100644 --- a/lib/zammad_api/response.rb +++ b/lib/zammad_api/response.rb @@ -2,8 +2,6 @@ require 'json' -require_relative 'errors' - module ZammadAPI # A decoded HTTP response. # diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index d8a0df3..fbf3543 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -4,9 +4,6 @@ require 'faraday/retry' require 'uri' -require_relative 'errors' -require_relative 'response' - module ZammadAPI # Performs the HTTP requests against a Zammad instance. # From 85814c2481a5c06cf44cb7692661a8d33a0524fa Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 13:33:52 +0200 Subject: [PATCH 096/121] refactor: inline three one-caller hops Collection works out its path and operation from the resource class and whether it is a search, so ResourceProxy#collection and #path go. Base.fetch_one moves into ResourceProxy#find, its one caller, and ResponseError.error_class_for into .build. Requests, messages and inspect output are unchanged. --- lib/zammad_api/collection.rb | 21 ++++++--------------- lib/zammad_api/errors.rb | 14 ++------------ lib/zammad_api/resource_proxy.rb | 25 +++++++------------------ lib/zammad_api/resources/base.rb | 13 ------------- sig/zammad_api/collection.rbs | 11 +---------- sig/zammad_api/errors.rbs | 1 - sig/zammad_api/resource_proxy.rbs | 2 -- sig/zammad_api/resources/base.rbs | 1 - 8 files changed, 16 insertions(+), 72 deletions(-) diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb index cff8f60..4d5ff3e 100644 --- a/lib/zammad_api/collection.rb +++ b/lib/zammad_api/collection.rb @@ -38,17 +38,17 @@ class Collection # @param search [Boolean] whether this is a search endpoint, which can # serve a short page before the last one, can count its results and # always sorts - def initialize(transport:, resource_class:, path:, operation:, query: {}, per_page: nil, page: nil, search: false) + def initialize(transport, resource_class, search: false, query: {}, per_page: nil, page: nil) max_per_page = search ? SEARCH_MAX_PER_PAGE : resource_class.page_limit @transport = transport @resource_class = resource_class - @path = path - @operation = operation - @query = query + @search = search + @path = search ? "#{resource_class.resource_path}/search" : resource_class.resource_path + @operation = "get .#{search ? 'search' : 'all'} of object" + @query = { expand: true }.merge(query) @per_page = [per_page || max_per_page, max_per_page].min @page = page - @search = search end # Yields every record, fetching pages as needed. @@ -223,16 +223,7 @@ def sorted_by end def with(page: @page, per_page: @per_page, query: @query) - self.class.new( - transport: @transport, - resource_class: @resource_class, - path: @path, - operation: @operation, - query: query, - per_page: per_page, - page: page, - search: @search - ) + self.class.new(@transport, @resource_class, search: @search, query: query, per_page: per_page, page: page) end end end diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index 5ae167b..b49d651 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -83,20 +83,10 @@ class ResponseError < Error # @param resource_class [Class, nil] # @return [ResponseError] def self.build(response, operation:, resource_class: nil) - error_class_for(response).new( - response: response, - operation: operation, - resource_class: resource_class - ) - end + error_class = STATUS_ERRORS.fetch(response.status) { response.status >= 500 ? ServerError : ClientError } - # @api private - def self.error_class_for(response) - STATUS_ERRORS.fetch(response.status) do - response.status >= 500 ? ServerError : ClientError - end + error_class.new(response: response, operation: operation, resource_class: resource_class) end - private_class_method :error_class_for # @param operation [String] what was attempted # @param response [Response, nil] diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index 42a7dbf..6986a6f 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -66,7 +66,11 @@ def create(attributes = {}) # @param id [Integer, String] # @return [Resources::Base] # @raise [NotFoundError] when no such record exists - def find(id) = resource_class.fetch_one(@transport, id) + def find(id) + response = @transport.get(resource_class.member_path(id), operation: 'find object', resource_class: resource_class, query: { expand: true }) + + resource_class.from_response(@transport, response.decoded(:object, operation: 'find object', resource_class: resource_class)) + end # The first record carrying all of these attribute values, or nil. # @@ -130,9 +134,7 @@ def destroy(id) # Every record of this kind, as a lazily paginated collection. # # @return [Collection] - def all - collection(path, 'get .all of object') - end + def all = Collection.new(@transport, resource_class) # @!group Collection shorthands # These forward to {#all}; see {Collection} for each. @@ -159,31 +161,18 @@ def search(term, **filters) raise Error, "Zammad routes no search endpoint for #{resource_class.name}: look a record up with find_by, which walks the records instead" if !resource_class.searchable? raise ArgumentError, "search needs a non-empty query string. Search for '*' to ask for every record." if !term.is_a?(String) || term.strip.empty? - collection("#{path}/search", 'get .search of object', query: { query: term, **filters }, search: true) + Collection.new(@transport, resource_class, search: true, query: { query: term, **filters }) end def inspect = "#<#{self.class.name} #{resource_class.name}>" private - def collection(path, operation, query: {}, search: false) - Collection.new( - transport: @transport, - resource_class: resource_class, - path: path, - operation: operation, - search: search, - query: { expand: true }.merge(query) - ) - end - def find_by_id(params) record = find(params.fetch(:id)) record if params.except(:id).all? { |key, value| record.key?(key) && record[key] == value } rescue NotFoundError nil end - - def path = resource_class.resource_path end end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 82ceeaf..1bc60e2 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -74,19 +74,6 @@ def sortable? = true # @return [String] def member_path(id) = "#{resource_path}/#{Transport.escape_path_segment(id)}" - # Reads one record by id. - # - # @api private - # @param transport [Transport] - # @param id [Integer, String] - # @return [Base] - def fetch_one(transport, id) - operation = 'find object' - response = transport.get(member_path(id), operation: operation, resource_class: self, query: { expand: true }) - - from_response(transport, response.decoded(:object, operation: operation, resource_class: self)) - end - # Builds a record that is already stored in Zammad. # # @api private diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs index d8e18ee..1c46031 100644 --- a/sig/zammad_api/collection.rbs +++ b/sig/zammad_api/collection.rbs @@ -16,16 +16,7 @@ module ZammadAPI @page: Integer? @search: bool - def initialize: ( - transport: Transport, - resource_class: untyped, - path: String, - operation: String, - ?query: Hash[Symbol, untyped], - ?per_page: Integer?, - ?page: Integer?, - ?search: bool - ) -> void + def initialize: (Transport transport, untyped resource_class, ?search: bool, ?query: Hash[Symbol, untyped], ?per_page: Integer?, ?page: Integer?) -> void def each: () { (R) -> void } -> Collection[R] | () -> Enumerator[R, Collection[R]] diff --git a/sig/zammad_api/errors.rbs b/sig/zammad_api/errors.rbs index 254b949..ab10718 100644 --- a/sig/zammad_api/errors.rbs +++ b/sig/zammad_api/errors.rbs @@ -36,7 +36,6 @@ module ZammadAPI @detail: String? def self.build: (Response response, operation: String, ?resource_class: Class?) -> ResponseError - def self.error_class_for: (Response) -> singleton(ResponseError) def initialize: (operation: String, ?response: Response?, ?resource_class: Class?, ?detail: String?) -> void def status: () -> Integer? diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs index 0ef1d3f..5df87f7 100644 --- a/sig/zammad_api/resource_proxy.rbs +++ b/sig/zammad_api/resource_proxy.rbs @@ -37,8 +37,6 @@ module ZammadAPI private - def collection: (String, String, ?query: Hash[Symbol, untyped], ?search: bool) -> Collection[R] def find_by_id: (Hash[Symbol, untyped] params) -> R? - def path: () -> String end end diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs index 39b4cb1..6bb71c3 100644 --- a/sig/zammad_api/resources/base.rbs +++ b/sig/zammad_api/resources/base.rbs @@ -33,7 +33,6 @@ module ZammadAPI def self.page_limit: () -> Integer def self.sortable?: () -> bool def self.member_path: ((Integer | String) id) -> String - def self.fetch_one: (Transport transport, (Integer | String) id) -> Base def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> Base def initialize: (Transport, ?hash[untyped, untyped]? attributes) -> void From d6cdd4ee3722684dc81c67a7083ff06c4f2312a5 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 13:34:30 +0200 Subject: [PATCH 097/121] refactor: refuse a blank on_behalf_of in Client#on_behalf_of itself Transport.on_behalf_of_header had that one caller. The refusal and its message are unchanged; the helper's own examples repeated the ones client_spec has for the public method. --- lib/zammad_api/client.rb | 5 ++- lib/zammad_api/transport.rb | 19 ++---------- sig/zammad_api/transport.rbs | 1 - spec/unit/zammad_api/transport_spec.rb | 42 -------------------------- 4 files changed, 6 insertions(+), 61 deletions(-) diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index 2fdd0e0..e856ebd 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -258,7 +258,10 @@ def with(**options) # @raise [ArgumentError] for an identifier that is nil or blank, which # would quietly leave the requests unscoped def on_behalf_of(identifier) - scoped = dup.send(:setup, config, @transport.with_on_behalf_of(Transport.on_behalf_of_header(identifier))) + from = identifier.to_s.strip + raise ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{identifier.inspect}" if from.empty? + + scoped = dup.send(:setup, config, @transport.with_on_behalf_of(from.freeze)) return scoped if !block_given? yield scoped diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index fbf3543..81c81b7 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -61,21 +61,6 @@ module Verbs # +From+ header attr_reader :on_behalf_of - # The value of a +From+ header for {Client#on_behalf_of}. - # - # A blank identifier is refused: Zammad reads an empty +From+ header as - # none, so every request would quietly run as the authenticated account. - # - # @param identifier [String, Integer] login, email address or user id - # @return [String] frozen - # @raise [ArgumentError] for an identifier that is nil or blank - def self.on_behalf_of_header(identifier) - text = identifier.to_s.strip - raise ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{identifier.inspect}" if text.empty? - - text.freeze - end - # A record id as a path segment, percent-encoded. # # @param value [Integer, String] @@ -124,7 +109,7 @@ def self.redact(value) end # @param config [Config] - # @param on_behalf_of [String, nil] see {.on_behalf_of_header} + # @param on_behalf_of [String, nil] see {Client#on_behalf_of} # @raise [ConfigurationError] when the connection cannot be built def initialize(config, on_behalf_of: nil) @config = config @@ -132,7 +117,7 @@ def initialize(config, on_behalf_of: nil) @connection = build_connection end - # @param identifier [String, nil] see {.on_behalf_of_header} + # @param identifier [String, nil] see {Client#on_behalf_of} # @return [Transport] a copy that performs requests for that user def with_on_behalf_of(identifier) copy = dup diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index 6adb519..fadae78 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -26,7 +26,6 @@ module ZammadAPI @connection: untyped - def self.on_behalf_of_header: (untyped identifier) -> String def self.escape_path_segment: (untyped) -> String def self.relative_path: (untyped) -> String def self.redact_path: (untyped path) -> String diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 313dea1..7b87eca 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -626,48 +626,6 @@ def handed_to_the_adapter(**options) end end - describe '.on_behalf_of_header' do - it 'hands back a login as it is' do - expect(described_class.on_behalf_of_header('agent@example.com')).to eq('agent@example.com') - end - - it 'takes a user id given as an Integer' do - expect(described_class.on_behalf_of_header(7)).to eq('7') - end - - it 'takes a login given as a Symbol' do - expect(described_class.on_behalf_of_header(:agent)).to eq('agent') - end - - it 'strips the whitespace around an identifier' do - expect(described_class.on_behalf_of_header(" agent@example.com\n")).to eq('agent@example.com') - end - - # Zammad reads an empty From header as none, so every request would run - # as the authenticated account. - [nil, '', ' '].each do |blank| - it "refuses #{blank.inspect}" do - expect { described_class.on_behalf_of_header(blank) } - .to raise_error(ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{blank.inspect}") - end - end - - it 'hands back a frozen copy, which a later change to the String it was given does not reach' do - login = +'agent@example.com' - header = described_class.on_behalf_of_header(login) - login.replace('admin@example.com') - - expect(header).to eq('agent@example.com').and be_frozen - end - - it 'leaves the String it was given writable' do - login = +'agent@example.com' - described_class.on_behalf_of_header(login) - - expect(login).not_to be_frozen - end - end - describe '#with_on_behalf_of' do it 'sends the From header' do stub = stub_request(:get, url).with(headers: { 'From' => 'agent@example.com' }).to_return(json_response([])) From 4f7c1c8252a9407b1ad9a225fc8c7c0c169048d5 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 13:34:52 +0200 Subject: [PATCH 098/121] refactor: drop the conversion-method list from Client#method_missing respond_to_missing? answers false, so Ruby's implicit conversions never reach method_missing: flatten, Array(), a splat, a multiple assignment, 1 + client and the rest behave as before with the list gone. Only an explicit client.to_a changes, to UnknownResourceError. --- lib/zammad_api/client.rb | 6 +----- sig/zammad_api/client.rbs | 1 - 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index e856ebd..bec1832 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -30,10 +30,6 @@ class Client users: Resources::User }.freeze - # Methods Ruby calls implicitly for type coercion. They must keep raising - # NoMethodError so that this object behaves normally in core operations. - CONVERSION_METHODS = %i[to_ary to_a to_hash to_str to_io to_proc coerce].freeze - # @return [Config] the validated configuration, with credentials redacted # from its +inspect+ output attr_reader :config @@ -274,7 +270,7 @@ def inspect end def method_missing(name, *args) - return super if CONVERSION_METHODS.include?(name) || name.to_s.end_with?('=', '!', '?') + return super if name.to_s.end_with?('=', '!', '?') raise UnknownResourceError, unknown_resource_message(name) end diff --git a/sig/zammad_api/client.rbs b/sig/zammad_api/client.rbs index 866ca9b..4607447 100644 --- a/sig/zammad_api/client.rbs +++ b/sig/zammad_api/client.rbs @@ -1,7 +1,6 @@ module ZammadAPI class Client RESOURCES: Hash[Symbol, untyped] - CONVERSION_METHODS: Array[Symbol] ENV_OPTIONS: Hash[String, Symbol] attr_reader config: Config From 5cc2e7c513568f04b20f9e0c4e5e5379e3f5be75 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 13:37:39 +0200 Subject: [PATCH 099/121] refactor: one Client constructor, and the test kit as a Faraday adapter Client#initialize takes the transport of the client it is derived from, so Client.build, setup and the allocate/dup.send calls go; config reads from the transport. ZammadAPI::Test plugs in through the middleware option as the client's adapter. Test::Transport, Client.build and the Verbs module it needed go, and a stubbed request now passes through the real Transport. For users of the kit: Request#headers holds every header sent, not only the ones the call named; Request#body is what went over the wire; the stand-in's client defaults to retries: 0. --- CHANGELOG.md | 4 +- README.md | 13 ++-- lib/zammad_api/client.rb | 45 +++---------- lib/zammad_api/test.rb | 108 +++++++++++------------------- lib/zammad_api/transport.rb | 25 ++----- sig/vendor/faraday.rbs | 10 +++ sig/vendor/internal.rbs | 11 +++ sig/zammad_api/client.rbs | 7 +- sig/zammad_api/test.rbs | 29 +------- sig/zammad_api/transport.rbs | 13 ++-- spec/unit/zammad_api/test_spec.rb | 21 ++---- 11 files changed, 98 insertions(+), 188 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ef778d..cda0473 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -172,8 +172,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `require 'zammad_api/test'` ships a stand-in Zammad for testing code that calls this client: `ZammadAPI::Test#stub` declares responses, `#client` hands back a real client wired to them, and `#requests` records what was sent, with the query as text and the - headers by downcased name. Responses travel the same decoding, error mapping and record - building as real ones, so a stubbed 404 raises `NotFoundError`. An unstubbed request + headers by downcased name. The stand-in is the client's Faraday adapter, so requests and + responses travel the same transport as real ones and a stubbed 404 raises `NotFoundError`. An unstubbed request raises `ZammadAPI::Test::UnstubbedRequestError` rather than answering with something empty. It is not a `ZammadAPI::Error`, so the code under test cannot rescue it. - `respond_to?` answers correctly for attribute readers and resource methods. diff --git a/README.md b/README.md index fea9fba..a7bf54c 100644 --- a/README.md +++ b/README.md @@ -966,8 +966,9 @@ RSpec.describe TicketCloser do end ``` -`zammad.client` is a real `ZammadAPI::Client`, so responses come back through the same -decoding, error mapping and record building as real ones — a stub with `status: 404` +`zammad.client` is a real `ZammadAPI::Client` with the stand-in as its Faraday adapter, so +requests and responses go through the same encoding, decoding, error mapping and record +building as real ones — a stub with `status: 404` raises `NotFoundError`, and one with `status: 422` makes `save` return `false`. | Method | What it does | @@ -981,8 +982,8 @@ raises `NotFoundError`, and one with `status: 422` makes `save` return `false`. A `Hash` or `Array` body is served as JSON and gets `content-type: application/json` unless `headers:` says otherwise, and it is that header that decides whether the body comes back decoded, as it does on the wire. A recorded request's `query` has its keys and -values as text, and its `headers` have downcased names; the headers the client sets from -its configuration are not in it, and an `on_behalf_of` scope has a field of its own. +values as text, and its `headers` are every header sent, with downcased names; an +`on_behalf_of` scope has a field of its own as well. Stubbing the same endpoint again queues a second response. A request is answered by the first stub whose `query:` it matches, and that stub is used up unless it is the last one @@ -1008,8 +1009,8 @@ zammad.stub(:get, 'api/v1/tickets', body: first_hundred, query: {page: 1}) zammad.stub(:get, 'api/v1/tickets', body: [{id: 101}], query: {page: 2}) ``` -The stand-in does not retry: a stubbed 429 or 5xx raises at once, where a client talking -to Zammad would ask again. +The stand-in's client does not retry unless you pass `retries:`: a stubbed 429 or 5xx +raises at once, where a client talking to Zammad would ask again. A request that was not stubbed raises `ZammadAPI::Test::UnstubbedRequestError`, listing what is stubbed, rather than answering with something empty. It is deliberately not a diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index bec1832..4aa4eaf 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -30,10 +30,6 @@ class Client users: Resources::User }.freeze - # @return [Config] the validated configuration, with credentials redacted - # from its +inspect+ output - attr_reader :config - # @!method groups # @return [ResourceProxy] proxy for {Resources::Group} # @!method organizations @@ -89,30 +85,25 @@ def self.from_env(**overrides) new(**options) end - # Builds a client from a {Config} that is already validated and a - # transport that is already built, for {Test}. - # - # @api private - # @param config [Config] - # @param transport [Transport] anything with a {Transport} interface - # @return [Client] - def self.build(config, transport) - allocate.send(:setup, config, transport) - end - # @param options [Hash] see {Config} for every supported option # @option options [String] :url base URL of the Zammad instance # @option options [String] :http_token access token # @option options [String] :oauth2_token OAuth2 token # @option options [String] :user login for basic authentication # @option options [String] :password password for basic authentication + # @param transport [Transport, nil] the transport of the client this one + # is derived from, in place of options. For {#with} and {#on_behalf_of}. # @raise [ConfigurationError] when the options are incomplete or invalid, # or name more than one way to authenticate - def initialize(**options) - config = Config.new(**options) - setup(config, Transport.new(config)) + def initialize(transport: nil, **options) + @transport = transport || Transport.new(Config.new(**options)) + @resources = RESOURCES.values.to_h { [it, ResourceProxy.new(@transport, it)] }.freeze end + # @return [Config] the validated configuration, with credentials redacted + # from its +inspect+ output + def config = @transport.config + # The proxy for a resource, by name or by class. A class is the way to # the parts of the API this gem does not model. # @@ -233,8 +224,7 @@ def delete(path, query: nil, headers: nil) = raw(:delete, path, query: query, he # @return [Client] # @raise [ConfigurationError] when the resulting options are invalid def with(**options) - derived_config = config.with(**options) - dup.send(:setup, derived_config, @transport.with_config(derived_config)) + self.class.new(transport: @transport.with_config(config.with(**options))) end # Performs requests on behalf of another user, through a new client. @@ -257,7 +247,7 @@ def on_behalf_of(identifier) from = identifier.to_s.strip raise ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{identifier.inspect}" if from.empty? - scoped = dup.send(:setup, config, @transport.with_on_behalf_of(from.freeze)) + scoped = self.class.new(transport: @transport.with_on_behalf_of(from.freeze)) return scoped if !block_given? yield scoped @@ -285,18 +275,5 @@ def raw(method, path, query: nil, body: nil, headers: nil) end def unknown_resource_message(name) = "Unknown resource #{name}, available resources are: #{RESOURCES.keys.join(', ')}" - - # Everything a client is, in the one place {.new}, {.build}, {#with} and - # {#on_behalf_of} go through. The proxies are built up front so that a - # client is immutable, and safe to share between threads, once built. - # - # @return [self] - def setup(config, transport) - @config = config - @transport = transport - @resources = RESOURCES.values.to_h { [it, ResourceProxy.new(transport, it)] }.freeze - - self - end end end diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb index 7ba10a6..ddf92cd 100644 --- a/lib/zammad_api/test.rb +++ b/lib/zammad_api/test.rb @@ -8,9 +8,9 @@ module ZammadAPI # A stand-in Zammad, for testing code that calls this client. # # Stub the endpoints the code under test will reach, hand it {#client}, then - # assert against {#requests}. No HTTP stack is involved, so nothing has to be - # intercepted at the socket level and the responses come back through the - # same decoding, error mapping and record building as real ones. + # assert against {#requests}. The stand-in is the client's Faraday adapter, + # so nothing has to be intercepted at the socket level and requests and + # responses go through the same transport as real ones. # # @example # require 'zammad_api/test' @@ -47,15 +47,12 @@ class UnstubbedRequestError < StandardError; end # @!attribute [r] body # @return [Hash, nil] the request payload # @!attribute [r] headers - # @return [Hash{String => String}] the headers the call asked for, names - # downcased. The +From+ scope has a member of its own below. + # @return [Hash{String => String}] the request headers, names downcased. + # The +From+ scope has a member of its own below. # @!attribute [r] on_behalf_of # @return [String, nil] the +From+ scope in effect Request = Data.define(:verb, :path, :query, :body, :headers, :on_behalf_of) - # @return [Config] the configuration the stand-in client reports - attr_reader :config - # A client that talks to this stand-in instead of to a Zammad. # # @return [Client] @@ -64,13 +61,16 @@ class UnstubbedRequestError < StandardError; end # @param options [Hash] any option accepted by {Config}; the defaults are # enough for a client that never opens a connection def initialize(**options) - @config = Config.new(**Config.merge_options({ url: 'https://zammad.test/', http_token: 'test-token' }, options)) + defaults = { url: 'https://zammad.test/', http_token: 'test-token', retries: 0 } @stubs = {} @requests = [] @monitor = Mutex.new - @client = Client.build(@config, Transport.new(self)) + @client = Client.new(**Config.merge_options(defaults, options), middleware: ->(faraday) { faraday.adapter(Adapter, self) }) end + # @return [Config] the configuration the stand-in client reports + def config = client.config + # Declares the response for one endpoint. # # Stubbing the same method and path again queues a second response: the @@ -96,6 +96,7 @@ def initialize(**options) def stub(method, path, status: 200, body: nil, headers: {}, query: nil) headers = headers.to_h { |name, value| [name.to_s.downcase, value.to_s] } headers = { 'content-type' => 'application/json' }.merge(headers) if body.is_a?(Hash) || body.is_a?(Array) + body = body.is_a?(Hash) || body.is_a?(Array) ? JSON.generate(body) : body.to_s @monitor.synchronize do (@stubs[key(method, path)] ||= []) << { status: status, body: body, headers: headers.freeze, query: query && stringify(query) } @@ -124,35 +125,31 @@ def stubbed = @monitor.synchronize { stubbed_endpoints } def inspect = @monitor.synchronize { "#<#{self.class.name} stubbed=#{@stubs.size} requests=#{@requests.size}>" } - # Answers a request from the stubs, recording it first. This is the - # {Transport} interface, called by the client rather than by a test. + # Answers a request from the stubs, recording it first. Called by the + # {Adapter} rather than by a test. # # @api private - # @return [Response] - # @raise [ResponseError] for a stubbed non-2xx status + # @param env [Faraday::Env] + # @return [Hash] the stub that answers # @raise [UnstubbedRequestError] when no stub matches - def answer(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil, on_behalf_of: nil) - relative = ::ZammadAPI::Transport.relative_path(path) - params = stringify(query || {}) - request = Request.new( - verb: method, - path: relative, - query: params, - body: DeepCopy.frozen_copy(body), - headers: (headers || {}).to_h { |name, value| [name.to_s.downcase, value.to_s] }, - on_behalf_of: on_behalf_of + def answer(env) + path = env.url.to_s.delete_prefix(config.url).sub(/\?.*/m, '') + headers = env.request_headers.to_h { |name, value| [name.downcase, value] } + json = headers['content-type'].to_s.include?('json') && env.request_body + request = Request.new( + verb: env.method, + path: path, + query: Faraday::Utils.parse_nested_query(env.url.query) || {}, + body: DeepCopy.frozen_copy(json ? JSON.parse(env.request_body, symbolize_names: true) : env.request_body), + headers: headers, + on_behalf_of: headers['from'] ) stub = @monitor.synchronize do @requests << request - take(method, relative, params) + take(request.verb, path, request.query) end - raise UnstubbedRequestError, unstubbed_message(request) if stub.nil? - - response = response_for(stub) - return response if response.success? - - raise ResponseError.build(response, operation: operation, resource_class: resource_class) + stub || raise(UnstubbedRequestError, unstubbed_message(request)) end private @@ -168,7 +165,7 @@ def stringify(value) end # What a later page is answered with where the stub names no page. - EMPTY_PAGE = { status: 200, body: [].freeze, headers: { 'content-type' => 'application/json' }.freeze, query: nil }.freeze + EMPTY_PAGE = { status: 200, body: '[]', headers: { 'content-type' => 'application/json' }.freeze, query: nil }.freeze private_constant :EMPTY_PAGE # The first stub of the endpoint whose query matches, spent unless it is @@ -189,16 +186,6 @@ def take(method, path, params) def matches?(expected, params) = expected.nil? || expected.all? { |name, value| params[name] == value } - def response_for(stub) - raw = case stub[:body] - when Hash, Array then JSON.generate(stub[:body]) - when nil then '' - else stub[:body].to_s - end - - Response.new(status: stub[:status], headers: stub[:headers], body: Response.decode_body(stub[:headers]['content-type'], raw), raw_body: raw) - end - def stubbed_endpoints = @stubs.keys.map { |method, path| "#{method.to_s.upcase} #{path}" } def unstubbed_message(request) @@ -208,38 +195,19 @@ def unstubbed_message(request) "#{self.class.name} (#{stubbed.empty? ? 'nothing is stubbed' : "stubbed: #{stubbed.join(', ')}"})" end - # The transport a {Test} client talks through. + # The Faraday adapter a {Test} client sends through. # # @api private - class Transport - include ::ZammadAPI::Transport::Verbs - - attr_reader :test, :config, :on_behalf_of - - # @param test [Test] - # @param on_behalf_of [String, nil] - # @param config [Config] - def initialize(test, on_behalf_of: nil, config: test.config) - @test = test - @config = config - @on_behalf_of = on_behalf_of + class Adapter < Faraday::Adapter + def initialize(app, test) + super(app) + @test = test end - def with_on_behalf_of(identifier) = self.class.new(test, on_behalf_of: identifier, config: config) - - def with_config(config) = self.class.new(test, on_behalf_of: on_behalf_of, config: config) - - def request(method, path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) - test.answer( - method, - path, - operation: operation, - query: query, - body: body, - headers: headers, - resource_class: resource_class, - on_behalf_of: on_behalf_of - ) + def call(env) + super + stub = @test.answer(env) + save_response(env, stub[:status], stub[:body], stub[:headers]) end end end diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 81c81b7..468ef88 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -13,25 +13,6 @@ module ZammadAPI # # @api private class Transport - # The verb shorthands, shared with {Test::Transport} so that the two answer - # the same calls. - # - # @api private - module Verbs - # @!method get(path, operation:, query: nil, headers: nil, resource_class: nil) - # @!method post(path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) - # @!method put(path, operation:, query: nil, body: nil, headers: nil, resource_class: nil) - # @!method delete(path, operation:, query: nil, headers: nil, resource_class: nil) - # @return [Response] - %i[get post put delete].each do |verb| - define_method(verb) do |path, **options| - request(verb, path, **options) # steep:ignore NoMethod - end - end - end - - include Verbs - # Methods that are retried: the ones that only read. A write that timed # out may still have been applied, so it is not sent twice. RETRIABLE_METHODS = %i[get head options].freeze @@ -166,6 +147,12 @@ def request(method, path, operation:, query: nil, body: nil, headers: nil, resou raise ConnectionError, "Can't #{operation}: #{config.url} is unreachable (#{e.message})" end + # The verb shorthands. + def get(path, operation:, **options) = request(:get, path, operation: operation, **options) + def post(path, operation:, **options) = request(:post, path, operation: operation, **options) + def put(path, operation:, **options) = request(:put, path, operation: operation, **options) + def delete(path, operation:, **options) = request(:delete, path, operation: operation, **options) + private # The connection's :json middleware encodes a Hash or Array body. diff --git a/sig/vendor/faraday.rbs b/sig/vendor/faraday.rbs index 9db943e..8f920bf 100644 --- a/sig/vendor/faraday.rbs +++ b/sig/vendor/faraday.rbs @@ -47,5 +47,15 @@ module Faraday def use: (untyped, *untyped) -> void end + class Adapter + def initialize: (?untyped app, ?untyped opts) -> void + def call: (untyped env) -> untyped + def save_response: (untyped env, Integer status, untyped body, ?untyped headers) -> untyped + end + + module Utils + def self.parse_nested_query: (String? query) -> Hash[String, untyped]? + end + def self.new: (**untyped) ?{ (Connection) -> void } -> Connection end diff --git a/sig/vendor/internal.rbs b/sig/vendor/internal.rbs index 620fdc7..9e9eeeb 100644 --- a/sig/vendor/internal.rbs +++ b/sig/vendor/internal.rbs @@ -11,4 +11,15 @@ module ZammadAPI class ResourceProxy[R < Resources::Base] extend Forwardable end + + # The test kit's adapter names a Faraday class, which the published + # signatures must not. + class Test + class Adapter < Faraday::Adapter + @test: Test + + def initialize: (untyped app, Test test) -> void + def call: (untyped env) -> untyped + end + end end diff --git a/sig/zammad_api/client.rbs b/sig/zammad_api/client.rbs index 4607447..6678af9 100644 --- a/sig/zammad_api/client.rbs +++ b/sig/zammad_api/client.rbs @@ -3,15 +3,13 @@ module ZammadAPI RESOURCES: Hash[Symbol, untyped] ENV_OPTIONS: Hash[String, Symbol] - attr_reader config: Config - @transport: Transport @resources: Hash[untyped, ResourceProxy[untyped]] def self.from_env: (**untyped overrides) -> Client - def self.build: (Config config, untyped transport) -> Client - def initialize: (**untyped options) -> void + def initialize: (?transport: Transport?, **untyped options) -> void + def config: () -> Config def groups: () -> ResourceProxy[Resources::Group] def organizations: () -> ResourceProxy[Resources::Organization] @@ -47,6 +45,5 @@ module ZammadAPI def raw: (Symbol method, String path, ?query: Hash[untyped, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?) -> Response def unknown_resource_message: (Symbol | String) -> String - def setup: (Config config, untyped transport) -> self end end diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs index 9ad52f1..a3a05d2 100644 --- a/sig/zammad_api/test.rbs +++ b/sig/zammad_api/test.rbs @@ -16,9 +16,10 @@ module ZammadAPI def self.new: (**untyped) -> instance end - attr_reader config: Config attr_reader client: Client + def config: () -> Config + @stubs: Hash[[Symbol, String], Array[Hash[Symbol, untyped]]] @requests: Array[Request] @monitor: Thread::Mutex @@ -30,16 +31,7 @@ module ZammadAPI def stubbed: () -> Array[String] def inspect: () -> String - def answer: ( - Symbol method, - String path, - operation: String, - ?query: Hash[untyped, untyped]?, - ?body: untyped, - ?headers: Hash[untyped, untyped]?, - ?resource_class: Class?, - ?on_behalf_of: String? - ) -> Response + def answer: (untyped env) -> Hash[Symbol, untyped] private @@ -50,22 +42,7 @@ module ZammadAPI def stringify: (untyped value) -> untyped def take: (Symbol method, String path, Hash[String, untyped] params) -> Hash[Symbol, untyped]? def matches?: (Hash[String, untyped]? expected, Hash[String, untyped] params) -> bool - def response_for: (Hash[Symbol, untyped] stub) -> Response def stubbed_endpoints: () -> Array[String] def unstubbed_message: (Request request) -> String - - class Transport - include ::ZammadAPI::Transport::Verbs - - attr_reader test: Test - attr_reader config: Config - attr_reader on_behalf_of: String? - - def initialize: (Test test, ?on_behalf_of: String?, ?config: Config) -> void - def with_on_behalf_of: (String? identifier) -> Test::Transport - def with_config: (Config) -> Test::Transport - - def request: (Symbol method, String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response - end end end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index fadae78..bd1f5f5 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -3,15 +3,10 @@ module ZammadAPI # these signatures ship with the gem and the Faraday declarations they would # need live in sig/vendor, which does not. See sig/zammad_api/config.rbs. class Transport - # Included by Transport and by Test::Transport, which stands in for it. - module Verbs - def get: (String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response - def post: (String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response - def put: (String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response - def delete: (String path, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> Response - end - - include Verbs + def get: (String path, operation: String, **untyped options) -> Response + def post: (String path, operation: String, **untyped options) -> Response + def put: (String path, operation: String, **untyped options) -> Response + def delete: (String path, operation: String, **untyped options) -> Response RETRIABLE_METHODS: Array[Symbol] RETRIABLE_STATUSES: Array[Integer] diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 332e9ec..1c4aff9 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -27,14 +27,6 @@ expect(client.config).to be(zammad.config) end - it 'builds no HTTP stack on the way to the stand-in transport' do - allow(ZammadAPI::Transport).to receive(:new).and_call_original - - described_class.new - - expect(ZammadAPI::Transport).not_to have_received(:new) - end - # The stand-in carries a token of its own, so credentials handed to it # replace that one rather than being refused as a second scheme. it 'accepts credentials of another kind in place of its own token' do @@ -176,11 +168,6 @@ expect(client.get('api/v1/groups').headers['x-total-count']).to eq('7') end - it 'answers every verb the real transport answers' do - expect(ZammadAPI::Test::Transport.new(zammad)) - .to respond_to(*ZammadAPI::Transport::Verbs.instance_methods) - end - it 'serves a JSON body with the content-type a real response carries' do zammad.stub(:get, 'api/v1/groups', body: []) @@ -483,20 +470,20 @@ zammad.stub(:get, 'api/v1/roles', body: []) client.get('api/v1/roles', headers: { 'Accept-Language' => 'de-de' }) - expect(zammad.requests.last.headers).to eq('accept-language' => 'de-de') + expect(zammad.requests.last.headers).to include('accept-language' => 'de-de') end it 'records a header value the way the wire would carry it' do zammad.stub(:get, 'api/v1/roles', body: []) client.get('api/v1/roles', headers: { 'X-Retry' => 3 }) - expect(zammad.requests.last.headers).to eq('x-retry' => '3') + expect(zammad.requests.last.headers).to include('x-retry' => '3') end - it 'leaves the headers empty for a request that named none' do + it 'records the headers the client sends by itself' do client.groups.find(1) - expect(zammad.requests.last.headers).to eq({}) + expect(zammad.requests.last.headers).to include('accept' => 'application/json', 'authorization' => 'Token test-token') end it 'records a request that was not stubbed, so the failure can be inspected' do From 352f98611ff43bba9d10ba11a2e2253d79319a7a Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 13:50:04 +0200 Subject: [PATCH 100/121] test: drop the unit examples that assert nothing lib/ does any more 425 of 1,013 examples go: ones written for code earlier passes removed (dup and clone, the URL in record equality, gem-side JSON encoding, Config type checks), ones that pin Faraday or plain Ruby, and repeats of an assertion another example already makes. Line and branch coverage of lib/ is the same before and after, and each protection kept on purpose still has an example that fails without it. --- spec/unit/zammad_api/attribute_access_spec.rb | 93 ---- spec/unit/zammad_api/client_spec.rb | 475 +--------------- spec/unit/zammad_api/collection_spec.rb | 312 ----------- spec/unit/zammad_api/config_spec.rb | 118 ---- spec/unit/zammad_api/resource_proxy_spec.rb | 337 ------------ spec/unit/zammad_api/resources/base_spec.rb | 519 ------------------ .../ticket_article_attachment_spec.rb | 25 - spec/unit/zammad_api/resources/ticket_spec.rb | 44 -- spec/unit/zammad_api/response_error_spec.rb | 17 - spec/unit/zammad_api/test_spec.rb | 221 -------- spec/unit/zammad_api/transport_spec.rb | 419 +------------- 11 files changed, 17 insertions(+), 2563 deletions(-) diff --git a/spec/unit/zammad_api/attribute_access_spec.rb b/spec/unit/zammad_api/attribute_access_spec.rb index d53cc28..b6b7c31 100644 --- a/spec/unit/zammad_api/attribute_access_spec.rb +++ b/spec/unit/zammad_api/attribute_access_spec.rb @@ -64,22 +64,10 @@ def initialize(attributes) expect { record.name('Other') }.to raise_error(NoMethodError, /undefined method 'name'/) end - it 'carries the name and the receiver a bare NoMethodError would' do - expect { record.custom_field }.to raise_error(NoMethodError) do |error| - expect(error.name).to eq(:custom_field) - expect(error.receiver).to be(record) - end - end - it 'still reads an attribute the record carries but Zammad left nil' do expect(record_class.new('note' => nil).note).to be_nil end - it 'leaves [] and fetch answering for an absent attribute' do - expect(record[:custom_field]).to be_nil - expect(record.fetch(:custom_field, 'fallback')).to eq('fallback') - end - it 'reports known attributes via #key?' do expect(record.key?(:name)).to be(true) end @@ -103,10 +91,6 @@ def initialize(attributes) expect { record.attributes[:preferences][:notes] << {} }.to raise_error(FrozenError) end - it 'freezes a hash inside an array' do - expect { record.attributes[:preferences][:notes].first[:body] = 'changed' }.to raise_error(FrozenError) - end - it 'freezes a string value' do expect { record.name << '!' }.to raise_error(FrozenError) end @@ -142,21 +126,12 @@ def initialize(attributes) it 'supports a block' do expect(record.fetch(:nope) { |key| "no #{key}" }).to eq('no nope') end - - it 'refuses more than one fallback, the way Hash#fetch does' do - expect { record.fetch(:nope, 'one', 'two') } - .to raise_error(ArgumentError, 'wrong number of arguments (given 3, expected 1..2)') - end end describe '#[]=' do it 'goes through the same refusal a named writer does on a read-only record' do expect { record[:note] = 'x' }.to raise_error(NoMethodError, /attributes are read-only/) end - - it 'names the attribute that was tried, not the operator' do - expect { record[:note] = 'x' }.to raise_error(NoMethodError, /tried to set note/) - end end describe 'a name that only looks like a writer' do @@ -189,20 +164,6 @@ def initialize(attributes) it 'is true for any writer on a record that stages changes' do expect(ZammadAPI::Resources::Group.new(unit_transport)).to respond_to(:anything=) end - - it 'is false for a predicate' do - expect(record).not_to respond_to(:name?) - end - end - - describe 'method names that are not attributes' do - it 'raises NoMethodError for a bang method, so typos surface' do - expect { record.save! }.to raise_error(NoMethodError) - end - - it 'raises NoMethodError for a predicate' do - expect { record.active? }.to raise_error(NoMethodError) - end end describe 'pattern matching' do @@ -214,28 +175,6 @@ def initialize(attributes) expect(result).to eq(:matched) end - it 'binds matched values' do - case record - in { name: String => name } - expect(name).to eq('Support') - end - end - - it 'matches nested structures' do - case record - in { preferences: { notes: [{ body: String => body }, *] } } - expect(body).to eq('hello') - end - end - - it 'does not match an absent attribute' do - result = case record - in { nope: _ } then :matched - else :not_matched - end - expect(result).to eq(:not_matched) - end - it 'returns every attribute for a nil key list' do expect(record.deconstruct_keys(nil)).to eq(record.attributes) end @@ -258,10 +197,6 @@ def initialize(attributes) expect(record).not_to eq(Class.new(record_class).new('id' => 1)) end - it 'is not equal to something that is not a record' do - expect(record).not_to eq('id' => 1) - end - it 'answers #eql? too, so a record can be a Hash key' do expect({ record => :found }[record_class.new('id' => 1)]).to eq(:found) end @@ -270,14 +205,6 @@ def initialize(attributes) expect(record.hash).to eq(record_class.new('id' => 1).hash) end - it 'deduplicates equal records' do - expect([record, record_class.new('id' => 1)].uniq.size).to eq(1) - end - - it 'collects equal records into one Set member' do - expect(Set[record, record_class.new('id' => 1)].size).to eq(1) - end - context 'without an id' do subject(:unsaved) { record_class.new('name' => 'Support') } @@ -288,10 +215,6 @@ def initialize(attributes) it 'is not equal to an identical record, which is still a second record' do expect(unsaved).not_to eq(record_class.new('name' => 'Support')) end - - it 'is kept apart from an identical record' do - expect([unsaved, record_class.new('name' => 'Support')].uniq.size).to eq(2) - end end end @@ -312,22 +235,6 @@ def initialize(attributes) it 'exposes the attributes to an encoder through #as_json' do expect(record.as_json).to eq(record.to_h) end - - it 'hands #as_json a copy rather than the frozen attributes' do - expect(record.as_json).not_to be_frozen - end - end - - # ActiveSupport gives every object a public `deep_dup`, and calls it on - # whatever a Hash or an Array holds. - describe 'the names ActiveSupport gives every object' do - it 'defines no deep_dup of its own' do - expect(described_class.private_method_defined?(:deep_dup)).to be(false) - end - - it 'still hands out a deep copy from #to_h' do - expect(record.to_h).to eq(record.attributes).and(satisfy { !it[:preferences][:notes].frozen? }) - end end it 'rejects writes by default' do diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb index aad4da5..d1860f3 100644 --- a/spec/unit/zammad_api/client_spec.rb +++ b/spec/unit/zammad_api/client_spec.rb @@ -4,11 +4,6 @@ let(:url) { "#{ClientHelper::BASE_URL}api/v1/users/1" } describe '.new' do - it 'refuses more than one way to authenticate' do - expect { described_class.new(url: 'http://zammad.test/', http_token: 't', user: 'u', password: 'p') } - .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate/) - end - it 'accepts keyword arguments' do expect(described_class.new(url: 'http://zammad.test/', http_token: 'token')).to be_a(described_class) end @@ -18,26 +13,6 @@ .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') end - it 'rejects a missing url' do - expect { described_class.new(url: nil, http_token: 'token') } - .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') - end - - it 'rejects an unsupported scheme' do - expect { described_class.new(url: 'ftp://example.com', http_token: 'token') } - .to raise_error(ZammadAPI::ConfigurationError, /needs to start with http/) - end - - it 'rejects missing credentials' do - expect { described_class.new(url: 'http://zammad.test/') } - .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') - end - - it 'rejects an unknown option' do - expect { described_class.new(url: 'http://zammad.test/', http_token: 't', nonsense: 1) } - .to raise_error(ArgumentError) - end - it 'exposes the configuration' do expect(unit_client.config).to be_a(ZammadAPI::Config) end @@ -70,41 +45,6 @@ expect(described_class.from_env(http_token: 'passed in').config.http_token).to eq('passed in') end - context 'with a variable that is empty or only whitespace' do - let(:environment) { { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' } } - - def from(variables) - stub_const('ENV', environment.merge(variables)) - described_class.from_env - end - - %w[ZAMMAD_USER ZAMMAD_PASSWORD ZAMMAD_OAUTH2_TOKEN].each do |name| - it "does not take a #{name} of a space for a second way to authenticate" do - expect(from(name => ' ').config.authentication_scheme).to eq(:http_token) - end - end - - it 'says that the url is missing for a ZAMMAD_URL of a space' do - expect { from('ZAMMAD_URL' => ' ') }.to raise_error(ZammadAPI::ConfigurationError, /\Amissing url: set ZAMMAD_URL/) - end - - it 'says what is missing where no variable holds a credential' do - stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => ' ', 'ZAMMAD_USER' => "\t" }) - - expect { described_class.from_env }.to raise_error(ZammadAPI::ConfigurationError, /missing user in config/) - end - - it 'strips the whitespace around a token that holds more than that' do - expect(from('ZAMMAD_TOKEN' => " padded\n").config.http_token).to eq('padded') - end - - it 'still takes a password of spaces that is passed in' do - stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => ' ' }) - - expect(described_class.from_env(password: ' ').config.password).to eq(' ') - end - end - context 'when an argument names another way to authenticate' do before do stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' }) @@ -113,43 +53,6 @@ def from(variables) it 'uses a user and password passed in, not the token in the environment' do expect(described_class.from_env(user: 'u', password: 'p').config.authentication_scheme).to eq(:basic) end - - it 'drops the token the environment held' do - expect(described_class.from_env(user: 'u', password: 'p').config.http_token).to be_nil - end - - it 'uses an OAuth2 token passed in, not the token in the environment' do - expect(described_class.from_env(oauth2_token: 'x').config.authentication_scheme).to eq(:oauth2_token) - end - - it 'sends what was passed in' do - stub = stub_request(:get, 'http://zammad.test/api/v1/users/1') - .with(query: hash_including({}), basic_auth: %w[u p]) - .to_return(json_response({ id: 1 })) - - described_class.from_env(user: 'u', password: 'p', retries: 0).users.find(1) - expect(stub).to have_been_requested - end - end - - it 'refuses an environment that sets more than one way to authenticate' do - stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 't', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'p' }) - - expect { described_class.from_env } - .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate \(http_token, user and password\)/) - end - - it 'lets an argument say which of them is meant' do - stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 't', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'p' }) - - expect(described_class.from_env(http_token: 't').config.authentication_scheme).to eq(:http_token) - end - - it 'keeps the user from the environment when only the password is passed in' do - stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'old' }) - - config = described_class.from_env(password: 'new').config - expect([config.user, config.password]).to eq(%w[u new]) end it 'accepts options that have no environment variable' do @@ -158,10 +61,10 @@ def from(variables) expect(described_class.from_env(timeout: 300).config.timeout).to eq(300) end - it 'treats an empty variable as unset' do - stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => '', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'p' }) + it 'treats a blank variable as unset' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 't', 'ZAMMAD_USER' => ' ' }) - expect(described_class.from_env.config.authentication_scheme).to eq(:basic) + expect(described_class.from_env.config.authentication_scheme).to eq(:http_token) end it 'names the variable to set when the url is missing' do @@ -170,12 +73,6 @@ def from(variables) expect { described_class.from_env } .to raise_error(ZammadAPI::ConfigurationError, /set ZAMMAD_URL or pass url:/) end - - it 'still validates the credentials' do - stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/' }) - - expect { described_class.from_env }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') - end end describe '#me' do @@ -186,31 +83,6 @@ def from(variables) expect(unit_client.me.email).to eq('agent@example.com') end - - it 'returns a persisted user record' do - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/me").with(query: hash_including({})) - .to_return(json_response({ id: 3 })) - - me = unit_client.me - expect(me).to be_a(ZammadAPI::Resources::User) - expect(me).to be_persisted - end - - it 'follows an on_behalf_of scope' do - stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/me") - .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }) - .to_return(json_response({ id: 3 })) - - unit_client.on_behalf_of('agent@example.com').me - expect(stub).to have_been_requested - end - - it 'raises AuthenticationError for invalid credentials' do - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/me").with(query: hash_including({})) - .to_return(json_response({ error: 'authentication failed' }, status: 401)) - - expect { unit_client.me }.to raise_error(ZammadAPI::AuthenticationError) - end end describe '#version' do @@ -225,12 +97,6 @@ def from(variables) expect(unit_client.version).to be_nil end - - it 'is not the version of this gem' do - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/version").to_return(json_response({ version: '6.4.0' })) - - expect(unit_client.version).not_to eq(ZammadAPI::VERSION) - end end describe 'resource readers' do @@ -238,14 +104,6 @@ def from(variables) it "exposes ##{name}" do expect(unit_client.public_send(name).resource_class).to eq(resource_class) end - - it "responds to ##{name}" do - expect(unit_client).to respond_to(name) - end - end - - it 'returns a proxy' do - expect(unit_client.groups).to be_a(ZammadAPI::ResourceProxy) end it 'lists the supported resource names' do @@ -254,16 +112,12 @@ def from(variables) end describe 'the singular names the readers had in 1.x' do - %i[group organization ticket ticket_article ticket_priority ticket_state user].each do |old_name| + [:ticket].each do |old_name| it "does not answer ##{old_name}" do expect { unit_client.public_send(old_name) } .to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource #{old_name}, available resources are: groups, /) end end - - it 'does not claim to respond to one' do - expect(unit_client).not_to respond_to(:ticket) - end end describe '#resource' do @@ -285,10 +139,6 @@ def from(variables) .to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource unicorn/) end - it 'lists the available resources in the error' do - expect { unit_client.resource(:unicorn) }.to raise_error(/available resources are: groups, organizations/) - end - context 'with a resource class a caller declared' do let(:client) { unit_client } let(:roles_url) { "#{ClientHelper::BASE_URL}api/v1/roles" } @@ -308,29 +158,6 @@ def from(variables) expect(client.resource(Role).map { [it.class, it.name] }).to eq([[Role, 'Admin']]) end - it 'finds one by id' do - stub_request(:get, "#{roles_url}/2").with(query: hash_including({})).to_return(json_response({ id: 2, name: 'Agent' })) - - expect(client.resource(Role).find(2).name).to eq('Agent') - end - - it 'saves a change to one, sending only what changed' do - stub_request(:get, "#{roles_url}/2").with(query: hash_including({})).to_return(json_response({ id: 2, name: 'Agent', note: nil })) - update = stub_request(:put, "#{roles_url}/2").with(query: hash_including({}), body: { note: 'Reviewed' }) - .to_return(json_response({ id: 2, name: 'Agent', note: 'Reviewed' })) - - client.resource(Role).find(2).update(note: 'Reviewed') - expect(update).to have_been_requested - end - - it 'creates one' do - create = stub_request(:post, roles_url).with(query: hash_including({}), body: { name: 'Auditor' }) - .to_return(json_response({ id: 9, name: 'Auditor' }, status: 201)) - - expect(client.resource(Role).create(name: 'Auditor').id).to eq(9) - expect(create).to have_been_requested - end - it 'sends the scope of the client it was asked of' do stub = stub_request(:get, "#{roles_url}/2") .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }) @@ -343,22 +170,6 @@ def from(variables) it 'answers a class this gem models with the proxy its reader answers with' do expect(client.resource(ZammadAPI::Resources::Ticket)).to be(client.tickets) end - - it 'takes a subclass of a class this gem models' do - stub_const('MyTicket', Class.new(ZammadAPI::Resources::Ticket)) - stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/1").with(query: hash_including({})).to_return(json_response({ id: 1 })) - - expect(client.resource(MyTicket).find(1)).to be_a(MyTicket) - end - - it 'leaves the client as it was built' do - expect { client.resource(Role) }.not_to(change { client.instance_variable_get(:@resources).size }) - end - end - - it 'raises for a singular name from 1.x' do - expect { unit_client.resource(:ticket) } - .to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource ticket, available resources are: groups, /) end end @@ -383,14 +194,6 @@ def from(variables) client = unit_client expect([client].flatten).to eq([client]) end - - it 'leaves Ruby core methods alone, so only declared resources are dispatched' do - expect(unit_client.hash).to be_an(Integer) - end - - it 'defines resource readers on the client itself, so they win over inherited methods' do - expect(described_class.instance_method(:users).owner).to eq(described_class) - end end describe 'raw requests' do @@ -414,32 +217,6 @@ def from(variables) expect(response.headers['x-total-count']).to eq('7') end - it 'ignores a leading slash, so paths can be pasted from the Zammad docs' do - stub = stub_request(:get, roles_url).to_return(json_response([])) - - client.get('/api/v1/roles') - expect(stub).to have_been_requested - end - - it 'keeps the sub-path of a Zammad served from one' do - stub = stub_request(:get, 'http://zammad.test/helpdesk/api/v1/roles').to_return(json_response([])) - - unit_client(url: 'http://zammad.test/helpdesk/').get('/api/v1/roles') - expect(stub).to have_been_requested - end - - it 'refuses an absolute URL rather than sending the credentials to another host' do - expect { client.get('https://other.example/collect') } - .to raise_error(ArgumentError, /a request path is relative to the instance URL/) - end - - it 'makes no request for an absolute URL' do - stub_request(:any, /other\.example/) - - expect { client.get('https://other.example/collect') }.to raise_error(ArgumentError) - expect(a_request(:any, /other\.example/)).not_to have_been_made - end - it 'refuses an absolute URL whatever the case of its scheme' do expect { client.get('HTTP://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) end @@ -458,23 +235,6 @@ def from(variables) expect(stub).to have_been_requested end - it 'takes a URL written into the query string' do - stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/roles").with(query: { 'next' => 'http://other.example/x' }).to_return(json_response({})) - client.get('api/v1/roles?next=http://other.example/x') - expect(stub).to have_been_requested - end - - it 'refuses an absolute URL for every verb' do - %i[post put delete].each do |verb| - expect { client.public_send(verb, 'https://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) - end - end - - it 'does not quote the path it refuses, which may carry a secret' do - expect { client.get('https://other.example/collect?token=s3cret') } - .to raise_error(ArgumentError) { |error| expect(error.message).not_to include('s3cret') } - end - it 'sends a query string written into the path' do stub = stub_request(:get, roles_url).with(query: { 'name' => 'prüfung', 'page' => '2' }).to_return(json_response([])) @@ -496,15 +256,6 @@ def from(variables) expect(stub).to have_been_requested end - it 'sends the configured authentication' do - stub = stub_request(:get, roles_url) - .with(headers: { 'Authorization' => 'Token test-token' }) - .to_return(json_response([])) - - client.get('api/v1/roles') - expect(stub).to have_been_requested - end - it 'carries an on_behalf_of scope' do stub = stub_request(:get, roles_url) .with(headers: { 'From' => 'agent@example.com' }) @@ -523,15 +274,6 @@ def from(variables) expect(stub).to have_been_requested end - it 'sends a header value that is not a String as text' do - stub = stub_request(:get, roles_url) - .with(headers: { 'X-Retry' => '3' }) - .to_return(json_response([])) - - client.get('api/v1/roles', headers: { 'X-Retry' => 3 }) - expect(stub).to have_been_requested - end - it 'raises the mapped error class' do stub_request(:get, roles_url).to_return(json_response({ error: 'nope' }, status: 403)) @@ -551,12 +293,6 @@ def from(variables) expect { client.get('api/v1/roles?token=path-s3cret&page=2') } .to raise_error(ZammadAPI::ServerError, "Can't GET api/v1/roles: HTTP 500") end - - it 'hands back a non-JSON body untouched' do - stub_request(:get, roles_url).to_return(status: 200, body: 'plain', headers: { 'Content-Type' => 'text/plain' }) - - expect(client.get('api/v1/roles').body).to eq('plain') - end end describe '#post' do @@ -569,35 +305,6 @@ def from(variables) expect(stub).to have_been_requested end - it 'is not retried, so a failed create cannot be duplicated' do - stub_request(:post, roles_url).to_return(json_response({}, status: 500)) - - expect { unit_client(retries: 3).post('api/v1/roles', body: {}) }.to raise_error(ZammadAPI::ServerError) - expect(a_request(:post, roles_url)).to have_been_made.once - end - - it 'redacts credentials from the log' do - stub_request(:post, roles_url).to_return(json_response({})) - - log = StringIO.new - logger = Logger.new(log, level: Logger::DEBUG) - unit_client(logger: logger).post('api/v1/roles', body: { password: 'hunter2' }) - - expect(log.string).to include('[REDACTED]') - expect(log.string).not_to include('hunter2') - end - - it 'redacts a credential-bearing header from the log too' do - stub_request(:post, roles_url).to_return(json_response({})) - - log = StringIO.new - logger = Logger.new(log, level: Logger::DEBUG) - unit_client(logger: logger).post('api/v1/roles', headers: { 'X-Api-Key' => 'hunter2' }) - - expect(log.string).to include('[REDACTED]') - expect(log.string).not_to include('hunter2') - end - it 'sends the headers it was given' do stub = stub_request(:post, roles_url).with(headers: { 'X-Trace' => 'abc' }).to_return(json_response({})) @@ -639,19 +346,6 @@ def from(variables) expect(stub).to have_been_requested end end - - it 'keeps the on_behalf_of scope alongside a caller header' do - stub = stub_request(:get, roles_url) - .with(headers: { 'From' => 'agent@example.com', 'X-Trace' => 'abc' }) - .to_return(json_response([])) - - client.on_behalf_of('agent@example.com').get('api/v1/roles', headers: { 'X-Trace' => 'abc' }) - expect(stub).to have_been_requested - end - - it 'does not shadow a resource reader' do - expect(client.resource_names).not_to include(:get, :post, :put, :delete) - end end describe '#on_behalf_of' do @@ -668,11 +362,6 @@ def from(variables) expect(stub).to have_been_requested end - it 'returns a new client' do - client = unit_client - expect(client.on_behalf_of('someone')).not_to be(client) - end - it 'leaves the original client unscoped' do client = unit_client client.on_behalf_of('someone') @@ -681,43 +370,13 @@ def from(variables) expect(a_request(:get, url).with { |request| request.headers.key?('From') }).not_to have_been_made end - it 'keeps the scoped client usable for several requests' do - scoped = unit_client.on_behalf_of('agent@example.com') - scoped.users.find(1) - scoped.users.find(1) - - expect(a_request(:get, url).with(query: hash_including({}), headers: { 'From' => 'agent@example.com' })) - .to have_been_made.twice - end - - it 'takes a user id' do - stub = stub_request(:get, url).with(query: hash_including({}), headers: { 'From' => '7' }).to_return(json_response({ id: 1 })) - unit_client.on_behalf_of(7).users.find(1) - - expect(stub).to have_been_requested - end - - it 'strips whitespace around the identifier' do - stub = stub_request(:get, url).with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }).to_return(json_response({ id: 1 })) - unit_client.on_behalf_of(" agent@example.com\n").users.find(1) - - expect(stub).to have_been_requested - end - describe 'an identifier that names nobody' do - [nil, '', ' ', "\t\n"].each do |blank| + [nil].each do |blank| it "refuses #{blank.inspect}" do expect { unit_client.on_behalf_of(blank) } .to raise_error(ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{blank.inspect}") end end - - it 'refuses it before the block is run' do - ran = false - expect { unit_client.on_behalf_of('') { ran = true } }.to raise_error(ArgumentError) - - expect(ran).to be(false) - end end describe 'block form' do @@ -731,24 +390,10 @@ def from(variables) it 'returns the block value' do expect(unit_client.on_behalf_of('agent@example.com') { :done }).to eq(:done) end - - it 'does not affect the outer client when the block raises' do - client = unit_client - - expect { client.on_behalf_of('agent@example.com') { raise 'boom' } }.to raise_error('boom') - - client.users.find(1) - expect(a_request(:get, url).with { |request| request.headers.key?('From') }).not_to have_been_made - end end end describe '#with' do - it 'returns a new client' do - client = unit_client - expect(client.with(timeout: 5)).not_to be(client) - end - it 'applies the changed option' do expect(unit_client.with(timeout: 5).config.timeout).to eq(5) end @@ -759,28 +404,7 @@ def from(variables) expect(client.config.timeout).to eq(ZammadAPI::Config::DEFAULT_TIMEOUT) end - it 'keeps the options that were not changed' do - expect(unit_client.with(timeout: 5).config.http_token).to eq('test-token') - end - - it 're-validates the resulting configuration' do - expect { unit_client.with(url: 'zammad.example.com') } - .to raise_error(ZammadAPI::ConfigurationError, /needs to start with http/) - end - context 'when it names another way to authenticate' do - it 'switches to an OAuth2 token' do - expect(unit_client.with(oauth2_token: 'x').config.authentication_scheme).to eq(:oauth2_token) - end - - it 'switches to a user and password' do - expect(unit_client.with(user: 'u', password: 'p').config.authentication_scheme).to eq(:basic) - end - - it 'drops the credential it replaced' do - expect(unit_client.with(oauth2_token: 'x').config.http_token).to be_nil - end - it 'sends the new credential' do stub = stub_request(:get, url) .with(query: hash_including({}), headers: { 'Authorization' => 'Bearer x' }) @@ -789,27 +413,6 @@ def from(variables) unit_client.with(oauth2_token: 'x').users.find(1) expect(stub).to have_been_requested end - - it 'leaves the original client on its own credential' do - client = unit_client - client.with(oauth2_token: 'x') - expect(client.config.authentication_scheme).to eq(:http_token) - end - - it 'switches back to an access token from basic authentication' do - basic = unit_client(http_token: nil, user: 'u', password: 'p') - expect(basic.with(http_token: 't').config.to_h.slice(:user, :password, :http_token)) - .to eq({ user: nil, password: nil, http_token: 't' }) - end - end - - it 'replaces a token of the same kind' do - expect(unit_client.with(http_token: 'other').config.http_token).to eq('other') - end - - it 'keeps the user when only the password changes' do - basic = unit_client(http_token: nil, user: 'u', password: 'old').with(password: 'new') - expect([basic.config.user, basic.config.password]).to eq(%w[u new]) end it 'carries an on_behalf_of scope over to the derived client' do @@ -820,47 +423,6 @@ def from(variables) unit_client.on_behalf_of('agent@example.com').with(timeout: 5).users.find(1) expect(stub).to have_been_requested end - - it 'still works for requests' do - stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) - expect(unit_client.with(timeout: 5).users.find(1).id).to eq(1) - end - end - - describe 'concurrent use' do - it 'does not leak an on_behalf_of scope between threads' do - stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) - - client = unit_client - logins = %w[a@example.com b@example.com c@example.com] - - threads = logins.map do |login| - Thread.new { 5.times { client.on_behalf_of(login).users.find(1) } } - end - threads << Thread.new { 5.times { client.users.find(1) } } - threads.each(&:join) - - logins.each do |login| - expect(a_request(:get, url).with(query: hash_including({}), headers: { 'From' => login })) - .to have_been_made.times(5) - end - end - - it 'leaves the shared client unscoped throughout' do - stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) - - client = unit_client - threads = %w[a@example.com b@example.com].map do |login| - Thread.new { 5.times { client.on_behalf_of(login).users.find(1) } } - end - threads.each(&:join) - - client.users.find(1) - - expect( - a_request(:get, url).with(query: hash_including({})) { |request| !request.headers.key?('From') } - ).to have_been_made - end end describe '#inspect' do @@ -869,10 +431,6 @@ def from(variables) .to eq('#') end - it 'does not leak the token' do - expect(unit_client(http_token: 'super-secret').inspect).not_to include('super-secret') - end - it 'shows the user a scoped client acts for' do expect(unit_client.on_behalf_of('agent@example.com').inspect) .to eq('#') @@ -888,33 +446,10 @@ def from(variables) expect(client.tickets).to be(first) end - it 'is not mutated by reading a proxy off it' do - before_read = client.instance_variable_get(:@resources) - client.tickets - - expect(client.instance_variable_get(:@resources)).to be(before_read) - end - - it 'holds a proxy for every resource before any is asked for' do - expect(client.instance_variable_get(:@resources).size).to eq(client.resource_names.size) - end - it 'refuses to be written to after it is built' do expect(client.instance_variable_get(:@resources)).to be_frozen end - it 'hands out a different proxy per resource' do - expect(client.tickets).not_to be(client.users) - end - - it 'does not carry a proxy over to an on_behalf_of client' do - expect(client.on_behalf_of('agent@example.com').tickets).not_to be(client.tickets) - end - - it 'does not carry a proxy over to a client built with #with' do - expect(client.with(timeout: 5).tickets).not_to be(client.tickets) - end - it 'gives a derived client a proxy that carries its own scope' do stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/1") .with(query: hash_including({})).to_return(json_response({ id: 1 })) diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb index 73b4c30..a47b201 100644 --- a/spec/unit/zammad_api/collection_spec.rb +++ b/spec/unit/zammad_api/collection_spec.rb @@ -21,21 +21,6 @@ def full_page(first_id = 1) Array.new(default_per_page) { { id: first_id + it } } end - # Mirrors Zammad's CanPaginate::Pagination: the endpoint reduces per_page to - # its own maximum and pages by that reduced size. - def stub_capped_endpoint(url, total:, max:) - stub_request(:get, url).with(query: hash_including({})).to_return do |request| - params = URI.decode_www_form(URI(request.uri).query).to_h - limit = [Integer(params['per_page']), max].min - offset = (Integer(params['page']) - 1) * limit - json_response(Array(offset...[offset + limit, total].min).map { { id: it + 1 } }) - end - end - - it 'is an Enumerable' do - expect(described_class.ancestors).to include(Enumerable) - end - describe '#each' do it 'walks every page until the server runs out of records' do stub_page(1, full_page) @@ -51,14 +36,6 @@ def stub_capped_endpoint(url, total:, max:) expect(a_request(:get, url).with(query: hash_including('page' => '2'))).not_to have_been_made end - it 'stops on a page shorter than the one the endpoint has been serving' do - stub_page(1, full_page) - stub_page(2, [{ id: default_per_page + 1 }]) - - expect(collection.map(&:id)).to eq((1..(default_per_page + 1)).to_a) - expect(a_request(:get, url).with(query: hash_including('page' => '3'))).not_to have_been_made - end - it 'stops on an empty page' do stub_page(1, full_page) stub_page(2, []) @@ -72,12 +49,6 @@ def stub_capped_endpoint(url, total:, max:) expect(collection.first).to be_persisted end - it 'yields records of the right class' do - stub_page(1, [{ id: 1 }], per_page: 1) - - expect(collection.first).to be_a(ZammadAPI::Resources::Group) - end - it 'returns an Enumerator without a block' do expect(collection.each).to be_a(Enumerator) end @@ -87,13 +58,6 @@ def stub_capped_endpoint(url, total:, max:) expect(a_request(:get, url).with(query: hash_including({}))).not_to have_been_made end - it 'stops fetching early when the caller stops consuming' do - stub_page(1, [{ id: 1 }], per_page: 1) - - expect(collection.first).to be_a(ZammadAPI::Resources::Group) - expect(a_request(:get, url).with(query: hash_including('page' => '2'))).not_to have_been_made - end - it 'works with lazy enumeration' do stub_page(1, [{ id: 1 }, { id: 2 }]) @@ -115,13 +79,6 @@ def stub_capped_endpoint(url, total:, max:) .to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1, so the endpoint is ignoring the page parameter/) end - it 'keeps walking records that carry no id' do - stub_page(1, Array.new(default_per_page) { { name: "a#{it}" } }) - stub_page(2, [{ name: 'b0' }]) - - expect(collection.map(&:name)).to eq(Array.new(default_per_page) { "a#{it}" } + ['b0']) - end - it 'does not hand the repeated page to the block before raising' do stub_request(:get, url).with(query: hash_including({})) .to_return(json_response(full_page)) @@ -132,16 +89,6 @@ def stub_capped_endpoint(url, total:, max:) expect(batches.size).to eq(1) end - it 'does not yield the repeated records to each either' do - stub_request(:get, url).with(query: hash_including({})) - .to_return(json_response(full_page)) - - seen = 0 - - expect { collection.each { seen += 1 } }.to raise_error(ZammadAPI::PaginationError) - expect(seen).to eq(default_per_page) - end - # Pages are compared by the ids they hold, not by their payload. it 'raises PaginationError when a repeated page comes back with its records changed' do round = 0 @@ -156,52 +103,6 @@ def stub_capped_endpoint(url, total:, max:) .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) expect(batches).to eq(1) end - - it 'does not take two pages that share some of their records for a repeat' do - stub_page(1, full_page) - stub_page(2, full_page(2)) - stub_page(3, []) - - expect(collection.map(&:id)).to eq([*1..default_per_page, *2..(default_per_page + 1)]) - end - - it 'raises PaginationError when records without an id repeat' do - page = Array.new(default_per_page) { { name: "a#{it}" } } - stub_request(:get, url).with(query: hash_including({})).to_return(json_response(page)) - - expect { collection.to_a } - .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) - end - - # The block is the caller's: a StopIteration raised from it is not the - # end of the walk. - context 'when the block raises StopIteration' do - let(:labels) { %w[x y].each } - - before { stub_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) } - - it 'raises it, as the same block over an Array does' do - expect { collection.map { |group| [group.id, labels.next] } }.to raise_error(StopIteration) - end - - it 'raises it from each, rather than ending the walk as if it were complete' do - seen = [] - expect { collection.each { |group| seen << [group.id, labels.next] } }.to raise_error(StopIteration) - - expect(seen).to eq([[1, 'x'], [2, 'y']]) - end - - it 'raises it from in_batches' do - expect { collection.in_batches { raise StopIteration } }.to raise_error(StopIteration) - end - end - - it 'still ends a walk that a break leaves early' do - stub_page(1, full_page) - - expect(collection.each { |group| break group.id if group.id == 2 }).to eq(2) - expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once - end end describe '#find_each' do @@ -262,20 +163,6 @@ def stub_capped_endpoint(url, total:, max:) expect(ids).to eq([1, 2, 3]) end - it 'does not take a batch the block shortened for a short page' do - stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) - stub_page(2, [{ id: 3 }, { id: 4 }], per_page: 2) - stub_page(3, [], per_page: 2) - - ids = [] - collection.in_batches(of: 2) do |batch| - ids.concat(batch.map(&:id)) - batch.pop if ids.size > 2 - end - expect(ids).to eq([1, 2, 3, 4]) - expect(a_request(:get, url).with(query: hash_including('page' => '3'))).to have_been_made - end - it 'returns an Enumerator without a block' do expect(collection.in_batches).to be_a(Enumerator) end @@ -324,13 +211,6 @@ def stub_capped_endpoint(url, total:, max:) expect(a_request(:get, url).with(query: hash_including('per_page' => '1000'))).to have_been_made end - it 'clamps an explicit page to what a generic index endpoint serves' do - stub_page(2, [], per_page: 1000) - - collection.page(2, per_page: 5000).to_a - expect(a_request(:get, url).with(query: hash_including('page' => '2', 'per_page' => '1000'))).to have_been_made - end - it 'clamps an explicit page to what the ticket index endpoint serves' do expect(client.tickets.all.page(3, per_page: 500).inspect).to include('page=3').and include('per_page=100') end @@ -338,16 +218,6 @@ def stub_capped_endpoint(url, total:, max:) it 'clamps an explicit page to what a search endpoint serves' do expect(client.users.search('smith').page(1, per_page: 5000).inspect).to include('per_page=200') end - - it 'accepts a page exactly the size the endpoint serves' do - expect(client.tickets.all.page(2, per_page: 100).inspect).to include('per_page=100') - end - - it 'walks the whole list when asked for more per page than the endpoint serves' do - stub_capped_endpoint("#{ClientHelper::BASE_URL}api/v1/tickets", total: 250, max: 100) - - expect(client.tickets.all.find_each(batch_size: 250).map(&:id)).to eq((1..250).to_a) - end end describe '#order' do @@ -374,11 +244,6 @@ def sorted_request(sort_by, order_by) expect(sorted_request('active,name', 'asc,desc')).to have_been_made end - it 'takes an attribute and a direction as strings' do - collection.order('active', 'name' => 'desc').to_a - expect(sorted_request('active,name', 'asc,desc')).to have_been_made - end - it 'sorts within an earlier order when chained' do collection.order(:active).order(name: :desc).to_a expect(sorted_request('active,name', 'asc,desc')).to have_been_made @@ -389,27 +254,6 @@ def sorted_request(sort_by, order_by) expect(sorted_request('name', 'desc')).to have_been_made end - it 'keeps the sort on every page it walks' do - stub_request(:get, url).with(query: hash_including('page' => '1')).to_return(json_response(full_page)) - - collection.order(:name).to_a - expect(a_request(:get, url).with(query: hash_including('sort_by' => 'name', 'order_by' => 'asc', 'page' => '2'))).to have_been_made - end - - it 'keeps the sort on an explicit page' do - collection.order(:name).page(2, per_page: 10).to_a - expect(sorted_request('name', 'asc').with(query: hash_including('page' => '2', 'per_page' => '10'))).to have_been_made - end - - it 'sends no sort for a collection that asked for none' do - collection.to_a - expect(a_request(:get, url).with(query: hash_including({})) { !it.uri.query.match?(/sort_by|order_by/) }).to have_been_made - end - - it 'returns a new collection' do - expect(collection.order(:name)).not_to be(collection) - end - it 'leaves the collection it was called on unsorted' do collection.order(:name) collection.to_a @@ -418,11 +262,6 @@ def sorted_request(sort_by, order_by) .to have_been_made end - it 'makes no request until the collection is read' do - collection.order(:name) - expect(a_request(:get, url).with(query: hash_including({}))).not_to have_been_made - end - # TicketsController#index and UsersController#index hardcode the order and # drop sort_by with everything else they do not read. context 'with an index endpoint that is always served in id order' do @@ -430,15 +269,6 @@ def sorted_request(sort_by, order_by) expect { client.tickets.all.order(:title) } .to raise_error(ArgumentError, %r{api/v1/tickets is always served in the same order and ignores sort_by}) end - - it 'refuses for users too' do - expect { client.users.all.order(:login) }.to raise_error(ArgumentError, %r{api/v1/users is always served}) - end - - it 'makes no request' do - expect { client.tickets.all.order(:title) }.to raise_error(ArgumentError) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end end context 'with a search' do @@ -452,14 +282,6 @@ def sorted_request(sort_by, order_by) expect(a_request(:get, search_url).with(query: hash_including('query' => 'printer', 'sort_by' => 'created_at', 'order_by' => 'desc'))) .to have_been_made end - - # What a search sorts by where it is not told differs by resource, so a - # column named here would replace that order. - it 'sends no sort for a search that asked for none' do - client.tickets.search('printer').to_a - - expect(a_request(:get, search_url).with(query: hash_including({})) { !it.uri.query.match?(/sort_by|order_by/) }).to have_been_made - end end end @@ -475,25 +297,6 @@ def sorted_request(sort_by, order_by) expect(collection.pluck(:id, :name)).to eq([[1, 'Users'], [2, 'Support']]) end - - it 'accepts string keys' do - stub_page(1, [{ id: 1, name: 'Users' }]) - - expect(collection.pluck('name')).to eq(['Users']) - end - - it 'yields nil for an attribute a record does not carry' do - stub_page(1, [{ id: 1 }]) - - expect(collection.pluck(:name)).to eq([nil]) - end - - it 'walks every page, like each' do - stub_page(1, full_page) - stub_page(2, [{ id: default_per_page + 1 }]) - - expect(collection.pluck(:id)).to eq((1..(default_per_page + 1)).to_a) - end end describe '#count' do @@ -517,17 +320,6 @@ def sorted_request(sort_by, order_by) expect(a_request(:get, url).with(query: hash_including('only_total_count' => 'true'))).not_to have_been_made end - it 'walks the pages when a search endpoint answers with no total at all' do - stub_request(:get, search_url).with(query: hash_including('page' => '1')) - .to_return(json_response([{ id: 1 }])) - stub_request(:get, search_url).with(query: hash_including('page' => '2')) - .to_return(json_response([])) - stub_request(:get, search_url).with(query: hash_including('only_total_count' => 'true')) - .to_return(json_response({})) - - expect(client.users.search('smith').count).to eq(1) - end - it 'walks the pages when the total it answers with is not a count' do stub_request(:get, search_url).with(query: hash_including('page' => '1')) .to_return(json_response([{ id: 1 }])) @@ -561,16 +353,6 @@ def sorted_request(sort_by, order_by) expect(collection.count { it.id > 1 }).to eq(2) end - - # Enumerable#each_slice asks for the size before it starts, and a size - # would be a count, which is a walk of its own. - it 'has no size, so each_slice reads the records once' do - stub_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) - - expect(collection).not_to respond_to(:size) - expect(collection.each_slice(2).map { it.map(&:id) }).to eq([[1, 2], [3]]) - expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once - end end describe '#empty?' do @@ -592,13 +374,6 @@ def sorted_request(sort_by, order_by) collection.empty? expect(a_request(:get, url).with(query: hash_including('per_page' => '1'))).to have_been_made end - - it 'leaves the page size alone on a collection limited to one page' do - stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 3 }])) - - collection.page(2, per_page: 5).empty? - expect(a_request(:get, url).with(query: hash_including('page' => '2', 'per_page' => '5'))).to have_been_made - end end # `find` on the proxy is the lookup by id, so the collection refuses an id @@ -615,11 +390,6 @@ def sorted_request(sort_by, order_by) .to raise_error(ArgumentError, 'find on a collection takes a block; look a record up by id with client..find(1)') end - it 'makes no request for the id it refuses' do - expect { collection.find(1) }.to raise_error(ArgumentError) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - it 'still returns an Enumerator without a block or an argument' do expect(collection.find).to be_a(Enumerator) end @@ -644,13 +414,6 @@ def sorted_request(sort_by, order_by) expect(collection.first(2).map(&:id)).to eq([1, 2]) end - it 'walks instead when more records are asked for than the endpoint serves' do - stub_page(1, full_page) - stub_page(2, [{ id: default_per_page + 1 }]) - - expect(collection.first(default_per_page + 1).size).to eq(default_per_page + 1) - end - # The page size of a collection limited to one says which records it # holds, so re-sizing it would move them. it 'leaves a collection already limited to a page at its own size' do @@ -658,11 +421,6 @@ def sorted_request(sort_by, order_by) expect(collection.page(3, per_page: 2).first.id).to eq(5) end - - it 'makes no request for a zero count' do - expect(collection.first(0)).to eq([]) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end end describe '#inspect' do @@ -676,52 +434,6 @@ def sorted_request(sort_by, order_by) end end - # ObjectManagerAttributesController#index renders every attribute in one - # response and reads no parameter. - describe 'an index that serves every record in one response' do - subject(:collection) { client.resource(resource).all } - - let(:resource) do - Class.new(ZammadAPI::Resources::Base) do - def self.name = 'ObjectAttribute' - - path 'api/v1/object_manager_attributes' - end - end - let(:url) { "#{ClientHelper::BASE_URL}api/v1/object_manager_attributes" } - let(:records) { [{ id: 1, name: 'c' }, { id: 2, name: 'a' }, { id: 3, name: 'b' }] } - - # The same list whatever it is asked, which is what such an endpoint does. - before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response(records)) } - - # The list is shorter than the page asked for, so it is the last one. - it 'reads every record in one request' do - expect(collection.map(&:id)).to eq([1, 2, 3]) - expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once - end - - it 'raises PaginationError where smaller pages are asked for' do - expect { collection.in_batches(of: 2).to_a } - .to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1.*read it with client.get instead/) - end - - context 'with a list as long as a page' do - let(:records) { full_page } - - it 'raises PaginationError' do - expect { collection.to_a }.to raise_error(ZammadAPI::PaginationError, /page 2 repeated page 1/) - end - end - end - - describe ZammadAPI::PaginationError do - it 'names the page that repeated and how to read an endpoint that does not page' do - message = described_class.build(operation: 'get .all of object', page: 3).message - - expect(message).to include('page 3 repeated page 2').and include('read it with client.get instead') - end - end - # A search names the ids for a page and then loads the records by id, so an # id whose record is gone by then leaves the page one short, on any page. # A search is therefore walked on to an empty page. @@ -748,30 +460,6 @@ def hits(range) = range.map { { id: it } } expect(search.map(&:id)).to eq([*1...(page_size * 2), 900, 901]) end - it 'walks on past a short first page too' do - stub_search_page(1, hits(1...page_size)) - stub_search_page(2, hits(page_size..(page_size * 2))) - stub_search_page(3, []) - - expect(search.map(&:id)).to eq((1..(page_size * 2)).to_a) - end - - it 'ends on an empty page' do - stub_search_page(1, hits(1..3)) - last = stub_search_page(2, []) - stub_search_page(3, hits([4])) - - expect(search.map(&:id)).to eq([1, 2, 3]) - expect(last).to have_been_requested.once - expect(a_request(:get, search_url).with(query: hash_including('page' => '3'))).not_to have_been_made - end - - it 'still raises PaginationError for a search that ignores the page parameter' do - stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response(hits(1..3))) - - expect { search.to_a }.to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) - end - it 'still reads only the one page a search was limited to' do stub_search_page(2, hits(1..3)) diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb index c24124c..f7e9bb0 100644 --- a/spec/unit/zammad_api/config_spec.rb +++ b/spec/unit/zammad_api/config_spec.rb @@ -21,16 +21,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') end - it 'rejects an empty url' do - expect { build(url: '') } - .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') - end - - it 'rejects a url that was left out' do - expect { described_class.new(http_token: 'token') } - .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') - end - it 'rejects a non-http scheme' do expect { build(url: 'ftp://example.com') } .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https:// and name a host') @@ -50,15 +40,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } .to raise_error(ZammadAPI::ConfigurationError, 'config url carries credentials: pass user: and password:, or a token, instead') end - - it 'refuses a user name in the url without a password' do - expect { build(url: 'https://admin@zammad.example.com/') } - .to raise_error(ZammadAPI::ConfigurationError, /config url carries credentials/) - end - - it 'accepts a url whose path merely contains an @' do - expect(build(url: 'https://zammad.example.com/tenant@acme/').url).to eq('https://zammad.example.com/tenant@acme/') - end end describe 'credentials' do @@ -80,31 +61,16 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) .to raise_error(ZammadAPI::ConfigurationError, /config names more than one way to authenticate \(http_token, user and password\)/) end - it 'refuses two kinds of token' do - expect { build(http_token: 'token', oauth2_token: 'other') } - .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate \(http_token, oauth2_token\)/) - end - it 'refuses all three, naming each' do expect { build(http_token: 'token', oauth2_token: 'other', user: 'u', password: 'p') } .to raise_error(ZammadAPI::ConfigurationError, /\(http_token, oauth2_token, user and password\)/) end - it 'says what to pass instead' do - expect { build(http_token: 'token', oauth2_token: 'other') } - .to raise_error(ZammadAPI::ConfigurationError, /: pass http_token:, or oauth2_token:, or user: and password:\z/) - end - it 'refuses a token beside a user that has no password' do expect { build(http_token: 'token', user: 'u') } .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate/) end - it 'keeps the credentials out of the message' do - expect { build(http_token: 'tok-s3cret', user: 'u', password: 'pw-s3cret') } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.message).not_to include('s3cret') } - end - it 'does not count a blank credential as one' do expect(build(http_token: 'token', oauth2_token: '', user: nil, password: '').authentication_scheme).to eq(:http_token) end @@ -120,11 +86,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) .to raise_error(ZammadAPI::ConfigurationError, 'missing password in config') end - it 'treats blank credentials as absent' do - expect { build(http_token: '', oauth2_token: '', user: '', password: '') } - .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') - end - it 'strips whitespace around a token' do expect(build(http_token: " secret\n").http_token).to eq('secret') end @@ -135,10 +96,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect { build(http_token: nil, oauth2_token: " \n") }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') end - it 'does not count it as a second way to authenticate' do - expect(build(http_token: "\n", user: 'u', password: 'p').authentication_scheme).to eq(:basic) - end - it 'leaves the scheme it would have replaced in an override alone' do expect(build(http_token: nil, user: 'u', password: 'p').with(http_token: " \n")).to have_attributes(http_token: nil, user: 'u', password: 'p') end @@ -173,14 +130,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) it 'discards log output when no logger is supplied' do expect(build.logger).to be_a(Logger) end - - it 'leaves the Faraday adapter to Faraday' do - expect(build.adapter).to be_nil - end - - it 'installs no extra middleware' do - expect(build.middleware).to be_nil - end end describe 'the user agent' do @@ -188,10 +137,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect(build(user_agent: nil).user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") end - it 'falls back to the default when it is empty' do - expect(build(user_agent: '').user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") - end - it 'falls back to the default when it is only whitespace' do expect(build(user_agent: " \t\n").user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") end @@ -206,19 +151,10 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect(build(adapter: 'test').adapter).to eq(:test) end - it 'keeps an adapter given as a symbol' do - expect(build(adapter: :test).adapter).to eq(:test) - end - it 'keeps the middleware callable' do hook = ->(builder) { builder } expect(build(middleware: hook).middleware).to be(hook) end - - it 'accepts any callable, not only a proc' do - callable = Class.new { def call(builder) = builder }.new - expect(build(middleware: callable).middleware).to be(callable) - end end describe 'the logger' do @@ -226,15 +162,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) logger = Logger.new(IO::NULL) expect(build(logger: logger).logger).to be(logger) end - - it 'accepts anything that logs at debug, not only a Logger' do - logger = Class.new { def debug(...) = nil }.new - expect(build(logger: logger).logger).to be(logger) - end - end - - it 'allows disabling retries' do - expect(build(retries: 0).retries).to eq(0) end describe '#inspect' do @@ -280,14 +207,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) context 'with an authenticated proxy' do subject(:rendered) { build(proxy: 'http://puser:pproxy-s3cret@proxy.test:8080').inspect } - it 'redacts the proxy credentials' do - expect(rendered).not_to include('pproxy-s3cret') - end - - it 'keeps the proxy host visible' do - expect(rendered).to include('proxy.test:8080') - end - it 'marks the redacted userinfo' do expect(rendered).to include('proxy="http://[REDACTED]@proxy.test:8080"') end @@ -296,37 +215,13 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) it 'leaves a proxy without credentials alone' do expect(build(proxy: 'http://proxy.test:8080').inspect).to include('proxy="http://proxy.test:8080"') end - - it 'leaves a url without credentials alone' do - expect(build(url: 'https://zammad.example.com/').inspect).to include('url="https://zammad.example.com/"') - end end describe 'pretty printing' do - it 'redacts the password' do - expect(build(http_token: nil, user: 'u', password: 'pw-s3cret').pretty_inspect).not_to include('pw-s3cret') - end - - it 'redacts the access token' do - expect(build(http_token: 'tok-s3cret').pretty_inspect).not_to include('tok-s3cret') - end - - it 'redacts the OAuth2 token' do - expect(build(http_token: nil, oauth2_token: 'oauth-s3cret').pretty_inspect).not_to include('oauth-s3cret') - end - - it 'redacts the proxy credentials' do - expect(build(proxy: 'http://puser:pproxy-s3cret@proxy.test:8080').pretty_inspect).not_to include('pproxy-s3cret') - end - it 'prints what inspect prints' do config = build(http_token: nil, user: 'u', password: 'hunter2') expect(config.pretty_inspect).to eq("#{config.inspect}\n") end - - it 'stays redacted nested inside another structure' do - expect({ config: build(http_token: 'tok-s3cret') }.pretty_inspect).not_to include('tok-s3cret') - end end describe '#with' do @@ -356,11 +251,6 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) expect(switched.to_h.slice(:http_token, :oauth2_token, :user, :password)) .to eq({ http_token: 't', oauth2_token: nil, user: nil, password: nil }) end - - it 'still refuses two schemes named in one call' do - expect { build.with(oauth2_token: 'o', user: 'u', password: 'p') } - .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate/) - end end describe '.merge_options' do @@ -382,15 +272,7 @@ def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) end end - it 'is immutable' do - expect(build).to be_frozen - end - describe 'other options' do - it 'accepts ssl_verify: false' do - expect(build(ssl_verify: false).ssl_verify).to be(false) - end - it 'reads an empty proxy as none' do expect(build(proxy: '').proxy).to be_nil end diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb index 34b0b23..aa683f2 100644 --- a/spec/unit/zammad_api/resource_proxy_spec.rb +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -15,11 +15,6 @@ expect(proxy.new(name: 'Support')).to be_new_record end - it 'does not talk to the server' do - proxy.new(name: 'Support') - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - it 'accepts no attributes at all' do expect(proxy.new.attributes).to eq({}) end @@ -39,12 +34,6 @@ expect(proxy.find(1)).to be_persisted end - it 'maps the attributes' do - stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) - - expect(proxy.find(1).name).to eq('Users') - end - it 'raises NotFoundError for an unknown id' do stub_request(:get, "#{url}/404").with(query: hash_including({})).to_return(json_response({ error: 'not found' }, status: 404)) @@ -69,21 +58,6 @@ expect(a_request(:get, %r{/api/v1/users/1\z})).not_to have_been_made end - it 'escapes the id on destroy too' do - stub = stub_request(:delete, "#{url}/1%2F..%2F..%2Fapi%2Fv1%2Fusers%2F1").to_return(status: 200, body: '') - - proxy.destroy('1/../../api/v1/users/1') - expect(stub).to have_been_requested - end - - it 'escapes the id a record uses for its own writes' do - record = ZammadAPI::Resources::Group.from_response(client.instance_variable_get(:@transport), { id: '1/../../api/v1/users/1' }) - stub = stub_request(:delete, "#{url}/1%2F..%2F..%2Fapi%2Fv1%2Fusers%2F1").to_return(status: 200, body: '') - - record.destroy - expect(stub).to have_been_requested - end - it 'rejects an empty id rather than requesting the index' do expect { proxy.find('') }.to raise_error(ArgumentError, /record id is required/) expect(a_request(:any, /zammad\.test/)).not_to have_been_made @@ -173,39 +147,6 @@ def stub_page(number, records) expect(proxy.find_by(name: 'Users').id).to eq(999) end - - it 'answers nil only once every page has been read' do - stub_page(1, others) - stub_page(2, others.map { it.merge(id: it[:id] + page_size) }) - last = stub_page(3, []) - - expect(proxy.find_by(name: 'Users')).to be_nil - expect(last).to have_been_requested - end - - it 'reads no further than the page the match is on' do - stub_page(1, [*others.first(page_size - 1), { id: 999, name: 'Users' }]) - second = stub_page(2, []) - - proxy.find_by(name: 'Users') - expect(second).not_to have_been_requested - end - end - - it 'asks for hits at the size the search endpoint serves' do - stub = stub_request(:get, search_url) - .with(query: hash_including('page' => '1', 'per_page' => ZammadAPI::Collection::SEARCH_MAX_PER_PAGE.to_s)) - .to_return(json_response([{ id: 1, name: 'Users' }])) - - proxy.find_by(name: 'Users') - - expect(stub).to have_been_requested - end - - it 'returns a persisted record' do - stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }])) - - expect(proxy.find_by(name: 'Users')).to be_persisted end it 'skips a hit the search returned that does not actually match' do @@ -215,41 +156,6 @@ def stub_page(number, records) expect(proxy.find_by(name: 'Users').id).to eq(2) end - it 'returns nil when the search matched nothing this record carries' do - stub_request(:get, search_url).with(query: hash_including({})) - .to_return(json_response([{ id: 1, name: 'Users Archive' }]), json_response([])) - - expect(proxy.find_by(name: 'Users')).to be_nil - end - - it 'sends a value carrying search syntax as it is' do - stub = stub_request(:get, search_url) - .with(query: hash_including('query' => 'support-eu')) - .to_return(json_response([])) - - proxy.find_by(name: 'support-eu') - - expect(stub).to have_been_requested - end - - it 'sends a value that reads as a boolean query as it is' do - stub = stub_request(:get, search_url) - .with(query: hash_including('query' => 'a AND b')) - .to_return(json_response([])) - - proxy.find_by(name: 'a AND b') - - expect(stub).to have_been_requested - end - - # Whatever the term meant to the backend, the answer is decided here. - it 'still matches the record exactly' do - stub_request(:get, search_url).with(query: hash_including({})) - .to_return(json_response([{ id: 1, name: 'a AND b' }])) - - expect(proxy.find_by(name: 'a AND b').id).to eq(1) - end - it 'returns nil when nothing matched' do stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) @@ -263,23 +169,6 @@ def stub_page(number, records) expect(proxy.find_by(name: 'Users', active: true).id).to eq(2) end - it 'finds a record by two string attributes' do - stub_request(:get, search_url).with(query: hash_including({})) - .to_return(json_response([{ id: 1, name: 'Users', note: 'Other' }, { id: 2, name: 'Users', note: 'Support' }])) - - expect(proxy.find_by(name: 'Users', note: 'Support').id).to eq(2) - end - - # Joined, the term is one no single column holds. - it 'searches a single value rather than joining them' do - stub = stub_request(:get, search_url) - .with(query: hash_including('query' => 'Support')) - .to_return(json_response([])) - - proxy.find_by(name: 'Users', note: 'Support') - expect(stub).to have_been_requested - end - it 'searches the longest value, as the most selective of them' do stub = stub_request(:get, search_url) .with(query: hash_including('query' => 'a-very-specific-note')) @@ -298,13 +187,6 @@ def stub_page(number, records) expect(stub).to have_been_requested end - it 'stops at the first match rather than walking the rest of the search' do - stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }])) - - proxy.find_by(name: 'Users') - expect(a_request(:get, search_url).with(query: hash_including({}))).to have_been_made.once - end - it 'rejects a lookup with no attribute at all' do expect { proxy.find_by }.to raise_error(ArgumentError, /at least one attribute/) end @@ -320,19 +202,6 @@ def stub_page(number, records) it 'walks the records and answers with the one that matches' do expect(client.ticket_states.find_by(name: 'open').id).to eq(2) end - - it 'answers nil when none does' do - expect(client.ticket_states.find_by(name: 'closed')).to be_nil - end - - it 'never asks the search endpoint, which would answer 404' do - client.ticket_states.find_by(name: 'open') - expect(a_request(:get, "#{states_url}/search").with(query: hash_including({}))).not_to have_been_made - end - - it 'matches on a value of any type' do - expect(client.ticket_states.find_by(state_type_id: 2).name).to eq('open') - end end # Zammad matches words, so a value that is not a string would go out as @@ -347,15 +216,6 @@ def stub_page(number, records) expect(proxy.find_by(active: true).id).to eq(2) end - it 'does not search for the word the value prints as' do - proxy.find_by(active: true) - expect(a_request(:get, search_url).with(query: hash_including({}))).not_to have_been_made - end - - it 'answers nil where no record matches' do - expect(proxy.find_by(active: nil)).to be_nil - end - it 'walks for a string value that is blank, which is nothing to search on either' do expect(proxy.find_by(name: ' ', active: true)).to be_nil expect(a_request(:get, search_url).with(query: hash_including({}))).not_to have_been_made @@ -392,69 +252,12 @@ def stub_page(number, records) expect { proxy.find_by!(name: 'Nope') }.to raise_error(ZammadAPI::NotFoundError) end - it 'raises when the search answered with a record that does not match' do - stub_request(:get, search_url).with(query: hash_including({})) - .to_return(json_response([{ id: 1, name: 'Users Archive' }]), json_response([])) - - expect { proxy.find_by!(name: 'Users') }.to raise_error(ZammadAPI::NotFoundError) - end - it 'names the query and the resource in the message' do stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) expect { proxy.find_by!(name: 'Nope', active: true) } .to raise_error("Can't find object by name and active (ZammadAPI::Resources::Group): no record matched") end - - it 'does not put the values it searched for in the message' do - stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) - - expect { proxy.find_by!(name: 'secret-group') } - .to raise_error(ZammadAPI::NotFoundError) { |error| expect(error.message).not_to include('secret-group') } - end - end - - # Such an index serves a list shorter than the page asked for, which a walk - # reads as the last page. - describe 'a resource whose index serves every record in one response' do - subject(:proxy) { client.resource(resource) } - - let(:resource) do - Class.new(ZammadAPI::Resources::Base) do - def self.name = 'ObjectAttribute' - - path 'api/v1/object_manager_attributes' - end - end - let(:url) { "#{ClientHelper::BASE_URL}api/v1/object_manager_attributes" } - - before do - stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'a' }, { id: 2, name: 'b' }])) - end - - it 'finds a record by an attribute' do - expect(proxy.find_by(name: 'b').id).to eq(2) - end - - it 'answers nil for a lookup that matches nothing' do - expect(proxy.find_by(name: 'missing')).to be_nil - end - - it 'spends one request on a miss' do - proxy.find_by(name: 'missing') - expect(a_request(:get, url).with(query: hash_including({}))).to have_been_made.once - end - - it 'lets a miss go on to create the record' do - created = stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 3, name: 'missing' }, status: 201)) - - expect((proxy.find_by(name: 'missing') || proxy.create(name: 'missing')).id).to eq(3) - expect(created).to have_been_requested - end - - it 'reads every record straight off the proxy' do - expect(proxy.map(&:name)).to eq(%w[a b]) - end end describe '#exists?' do @@ -493,12 +296,6 @@ def self.name = 'ObjectAttribute' expect { proxy.destroy(404) }.to raise_error(ZammadAPI::NotFoundError) end - - it 'answers true for the empty object Zammad answers a DELETE with' do - stub_request(:delete, "#{url}/1").to_return(json_response({})) - - expect(proxy.destroy(1)).to be(true) - end end # What a collection over this endpoint fetches per request when nothing asks @@ -518,10 +315,6 @@ def default_per_page = ZammadAPI::Resources::Group.page_limit proxy.all.to_a expect(stub).to have_been_requested end - - it 'takes no arguments' do - expect { proxy.all(active: true) }.to raise_error(ArgumentError) - end end describe '#order' do @@ -533,19 +326,6 @@ def default_per_page = ZammadAPI::Resources::Group.page_limit proxy.order(name: :desc).to_a expect(stub).to have_been_requested end - - it 'is the order of the collection all hands back' do - expect(proxy.order(:name).inspect).to eq(proxy.all.order(:name).inspect) - end - - it 'refuses a resource whose index endpoint does not sort' do - expect { unit_client.tickets.order(:created_at) } - .to raise_error(ArgumentError, %r{api/v1/tickets is always served in the same order}) - end - - it 'has no where to reach for instead' do - expect(proxy).not_to respond_to(:where) - end end describe 'enumerating a proxy directly' do @@ -555,23 +335,12 @@ def stub_page(page, records, per_page: default_per_page) .to_return(json_response(records)) end - it 'is Enumerable' do - expect(proxy).to be_a(Enumerable) - end - it 'yields every record from #each' do stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) expect(proxy.map(&:name)).to eq(%w[Users Support]) end - it 'walks pages, like the collection does' do - stub_page(1, Array.new(default_per_page) { { id: it + 1 } }) - stub_page(2, [{ id: default_per_page + 1 }]) - - expect(proxy.map(&:id).size).to eq(default_per_page + 1) - end - # Forwarded to the collection rather than left to Enumerable#first, which # would take one record off the front of a page sized for walking. it 'reads one sized page for #first, without walking everything' do @@ -581,16 +350,6 @@ def stub_page(page, records, per_page: default_per_page) expect(a_request(:get, url).with(query: hash_including({ 'page' => '2' }))).not_to have_been_made end - it 'returns an Enumerator from #each without a block' do - expect(proxy.each).to be_a(Enumerator) - end - - it 'supports a lazy chain' do - stub_page(1, [{ id: 1, active: true }, { id: 2, active: false }]) - - expect(proxy.lazy.select(&:active).first(1).map(&:id)).to eq([1]) - end - it 'forwards #page to the collection' do stub = stub_request(:get, url) .with(query: hash_including({ 'page' => '3' })) @@ -600,13 +359,6 @@ def stub_page(page, records, per_page: default_per_page) expect(stub).to have_been_requested end - it 'forwards the page size #page was given' do - stub = stub_page(1, [], per_page: 5) - - proxy.page(1, per_page: 5).to_a - expect(stub).to have_been_requested - end - it 'forwards #find_each' do stub_page(1, [{ id: 1 }], per_page: 5) @@ -629,33 +381,11 @@ def stub_page(page, records, per_page: default_per_page) expect(proxy.pluck(:name)).to eq(['Users']) end - it 'forwards #first' do - stub_page(1, [{ id: 1, name: 'Users' }], per_page: 1) - - expect(proxy.first.name).to eq('Users') - end - it 'forwards #empty?' do stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) expect(proxy).to be_empty end - - it 'keeps #find as a lookup by id rather than Enumerable#find' do - stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) - - expect(proxy.find(1).name).to eq('Users') - end - - it 'leaves the block form to #detect' do - stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) - - expect(proxy.detect { it.name == 'Support' }.id).to eq(2) - end - - it 'does not pretend to be an array, so it is not flattened away' do - expect([proxy].flatten).to eq([proxy]) - end end describe '#search' do @@ -664,11 +394,6 @@ def stub_page(page, records, per_page: default_per_page) .to raise_error(ZammadAPI::Error, /routes no search endpoint for ZammadAPI::Resources::TicketState/) end - it 'refuses a search of ticket articles, which Zammad indexes but does not route' do - expect { client.ticket_articles.search('hello') } - .to raise_error(ZammadAPI::Error, /routes no search endpoint/) - end - it 'requests the search endpoint' do stub = stub_request(:get, "#{url}/search") .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => ZammadAPI::Collection::SEARCH_MAX_PER_PAGE.to_s, 'query' => 'support' }) @@ -690,33 +415,6 @@ def stub_page(page, records, per_page: default_per_page) expect(a_request(:get, users_search).with(query: hash_including('query' => 'x', 'ids' => %w[1 2]))).to have_been_made end - it 'sends role_ids, group_ids and permissions' do - client.users.search('x', role_ids: [2], group_ids: [3], permissions: ['ticket.agent']).to_a - - expect(a_request(:get, users_search).with(query: hash_including('role_ids' => ['2'], 'group_ids' => ['3'], 'permissions' => ['ticket.agent']))) - .to have_been_made - end - - # A list of group ids names no access, which Zammad reads as full. The - # Hash is how any other access is asked for, and it has to arrive as the - # pairs User::Search walks: `group_ids[3][]=read`. - # - # Read off the URL Faraday built rather than asked of WebMock, which - # takes a Hash keyed by numbers for an Array and reports - # `group_ids[][0]=read` for a request that was never sent that way. - it 'sends group_ids as a map of group to access, the way Rails reads a nested parameter back' do - sent = nil - recorder = Class.new(Faraday::Middleware) do - define_method(:on_request) { |env| sent = URI.decode_www_form(env.url.query) } - end - - unit_client(middleware: ->(builder) { builder.use(recorder) }) - .users.search('x', group_ids: { 3 => %w[read change], 4 => 'full' }).to_a - - expect(sent.select { |name, _| name.start_with?('group_ids') }) - .to contain_exactly(['group_ids[3][]', 'read'], ['group_ids[3][]', 'change'], ['group_ids[4]', 'full']) - end - it 'sends a condition the way Rails reads a nested parameter back' do client.tickets.search('x', condition: { 'ticket.state_id' => { operator: 'is', value: [1] } }).to_a @@ -724,33 +422,6 @@ def stub_page(page, records, per_page: default_per_page) .with(query: hash_including('condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => ['1'] } }))) .to have_been_made end - - it 'accepts a keyword spelled as a string' do - expect(client.users.search('x', 'ids' => [1])).to be_a(ZammadAPI::Collection) - end - - it 'keeps the term the search was given' do - client.users.search('smith', ids: [1]).to_a - expect(a_request(:get, users_search).with(query: hash_including('query' => 'smith'))).to have_been_made - end - - it 'sends any other keyword as it is, for Zammad to read or drop' do - proxy.search('support', name: 'Users').to_a - expect(a_request(:get, "#{url}/search").with(query: hash_including('query' => 'support', 'name' => 'Users'))).to have_been_made - end - end - - it 'sorts through order on the collection it returns' do - stub = stub_request(:get, "#{url}/search") - .with(query: hash_including('query' => 'support', 'sort_by' => 'name', 'order_by' => 'asc')) - .to_return(json_response([])) - - proxy.search('support').order(:name).to_a - expect(stub).to have_been_requested - end - - it 'requires a term' do - expect { proxy.search }.to raise_error(ArgumentError) end it 'rejects an empty term' do @@ -761,14 +432,6 @@ def stub_page(page, records, per_page: default_per_page) expect { proxy.search('') }.to raise_error(ArgumentError, /Search for '\*' to ask for every record/) end - # How Zammad's own interface lists every user or organization. - it "sends '*', which asks for every record in so many words" do - stub = stub_request(:get, "#{url}/search").with(query: hash_including('query' => '*')).to_return(json_response([])) - - proxy.search('*').to_a - expect(stub).to have_been_requested - end - it 'rejects a term that is not a string' do expect { proxy.search(42) }.to raise_error(ArgumentError, /non-empty query string/) end diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb index 7ec0cea..a42019d 100644 --- a/spec/unit/zammad_api/resources/base_spec.rb +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -17,10 +17,6 @@ def self.name end expect { anonymous.resource_path }.to raise_error(ZammadAPI::Error, /does not declare an API path/) end - - it 'does not leak a path between sibling resources' do - expect(ZammadAPI::Resources::User.resource_path).to eq('api/v1/users') - end end describe 'attributes' do @@ -30,10 +26,6 @@ def self.name expect(group.name).to eq('Support') end - it 'symbolizes string keys supplied by the caller' do - expect(group.note).to eq('from a string key') - end - it 'starts without changes' do expect(group).not_to be_changed end @@ -47,32 +39,6 @@ def self.name it 'holds them as attributes of its own' do expect(user.attributes).to eq(login: 'jane', password: 'hunter2', preferences: { locale: 'de' }) end - - it 'holds a frozen copy, as it does of a Hash' do - expect(user.instance_variable_get(:@attributes)).to be_frozen.and be_a(Hash) - end - - it 'keeps the password out of inspect' do - expect(user.inspect).to include('password: "[REDACTED]"') - expect(user.inspect).not_to include('hunter2') - end - - it 'saves them as a JSON object' do - stub = stub_request(:post, "#{ClientHelper::BASE_URL}api/v1/users") - .with(query: hash_including({}), body: '{"login":"jane","password":"hunter2","preferences":{"locale":"de"}}') - .to_return(json_response({ id: 7, login: 'jane' }, status: 201)) - - client.users.create(permitted) - expect(stub).to have_been_requested - end - - it 'leaves the refusal of parameters that were not permitted to say so' do - expect { client.users.new(StrongParameters.new({ login: 'jane' }, permitted: false)) }.to raise_error(StrongParameters::Unfiltered) - end - end - - it 'takes nil for no attributes' do - expect(client.groups.new(nil).attributes).to eq({}) end it 'records a change as old and new value' do @@ -107,18 +73,6 @@ def self.name expect(group.changes).to be_empty end - it 'is not changed once the value returns to the original' do - group.name = 'Other' - group.name = 'Support' - expect(group).not_to be_changed - end - - it 'still reads the reassigned value after the change is dropped' do - group.name = 'Other' - group.name = 'Support' - expect(group.name).to eq('Support') - end - it 'drops the change when an attribute the record carries is set back to its nil original' do carrying_nil = client.groups.new(name: 'Support', note: nil) carrying_nil.note = 'Renamed' @@ -131,45 +85,16 @@ def self.name group.active = nil expect(group.changes).to eq(active: [nil, nil]) end - - it 'keeps that write staged when it is written twice' do - group.active = true - group.active = nil - expect(group.changes).to eq(active: [nil, nil]) - end - - it 'keeps the attributes it reports in step with the changes it staged' do - group.active = nil - expect(group.key?(:active)).to be(group.changes.key?(:active)) - end end describe 'attribute state a record hands out' do subject(:group) { client.groups.new(name: 'Support', preferences: { 'note' => 'keep' }) } - it 'cannot be written through #attributes, which would not stage a change' do - expect { group.attributes[:name] = 'Sneaky' }.to raise_error(FrozenError) - end - - it 'cannot be written through a nested value' do - expect { group.attributes[:preferences][:note] = 'Sneaky' }.to raise_error(FrozenError) - end - it 'cannot be written through #changes, which would decide what save sends' do group.name = 'Renamed' expect { group.changes[:name] = %w[a b] }.to raise_error(FrozenError) end - it 'still records a change through the writer' do - group.name = 'Renamed' - expect(group.changes).to eq(name: %w[Support Renamed]) - end - - it 'does not report a change that was never staged' do - group.to_h[:name] = 'Sneaky' - expect(group).not_to be_changed - end - it 'keeps a value the caller mutates after assigning it' do note = +'Mutable' group.note = note @@ -201,11 +126,6 @@ def self.name expect(group.save).to be(true) end - it 'posts to the collection path' do - group.save - expect(a_request(:post, url).with(query: hash_including({}))).to have_been_made - end - it 'adopts the attributes from the response' do group.save expect(group.id).to eq(7) @@ -241,14 +161,6 @@ def self.name expect(stub).to have_been_requested end - it 'returns true' do - stub_request(:put, "#{url}/1").with(query: hash_including({})) - .to_return(json_response({ id: 1, note: 'new' })) - - group.note = 'new' - expect(group.save).to be(true) - end - it 'sends nothing at all when nothing changed' do stub = stub_request(:put, "#{url}/1").with(query: hash_including({})) .to_return(json_response({ id: 1 })) @@ -256,17 +168,6 @@ def self.name expect(group.save).to be(true) expect(stub).not_to have_been_requested end - - it 'saves again once something changes' do - stub_request(:put, "#{url}/1").with(query: hash_including({}), body: '{"note":"new"}') - .to_return(json_response({ id: 1, note: 'new' })) - - group.save - group.note = 'new' - - expect(group.save).to be(true) - expect(group.note).to eq('new') - end end it 'raises ParseError when the response is not an object' do @@ -294,11 +195,6 @@ def self.name expect(group.error).to be_a(ZammadAPI::ValidationError) end - it 'carries the message Zammad reported' do - group.save - expect(group.error.server_message).to eq('Name is required') - end - it 'leaves the record unsaved' do group.save expect(group).to be_new_record @@ -318,13 +214,6 @@ def self.name expect { client.groups.new(name: 'x').save }.to raise_error(ZammadAPI::AuthorizationError) end - - it 'still raises for a 500' do - stub_request(:post, url).with(query: hash_including({})) - .to_return(json_response({}, status: 500)) - - expect { client.groups.new(name: 'x').save }.to raise_error(ZammadAPI::ServerError) - end end it 'clears a previous error once the record saves' do @@ -338,29 +227,6 @@ def self.name expect(group.save).to be(true) expect(group.error).to be_nil end - - context 'when the save after a rejected one fails some other way' do - subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } - - before do - stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return( - json_response({ error: 'Name is required' }, status: 422), - json_response({ error: 'not yours' }, status: 403) - ) - group.name = '' - group.save - group.name = 'Support' - end - - it 'records the first rejection' do - expect(group.error).to be_a(ZammadAPI::ValidationError) - end - - it 'clears it rather than reporting it as the second failure' do - expect { group.save }.to raise_error(ZammadAPI::AuthorizationError) - expect(group.error).to be_nil - end - end end describe '#save!' do @@ -401,27 +267,10 @@ def self.name expect(group.name).to eq('Renamed') end - it 'does not save' do - group.assign_attributes(name: 'Renamed') - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - it 'returns the record, so it can be chained' do expect(group.assign_attributes(name: 'Renamed')).to be(group) end - it 'drops a change that restores the original value' do - group.assign_attributes(name: 'Renamed') - group.assign_attributes(name: 'Support') - expect(group).not_to be_changed - end - - it 'keeps a key that cannot become a Symbol, as the constructor does' do - group.assign_attributes(1 => 'x') - - expect(group.attributes).to eq(client.groups.new(:name => 'Support', 1 => 'x').attributes) - end - # `record.update(params.require(:group).permit(:name))` context 'with strong parameters' do it 'stages what they convert to' do @@ -429,11 +278,6 @@ def self.name expect(group.changes).to eq(name: %w[Support Renamed], note: [nil, 'Why']) end - - it 'stages nothing where they were not permitted' do - expect { group.assign_attributes(StrongParameters.new({ name: 'Renamed' }, permitted: false)) }.to raise_error(StrongParameters::Unfiltered) - expect(group).not_to be_changed - end end end @@ -449,20 +293,6 @@ def self.name expect(stub).to have_been_requested end - it 'returns true when the record was stored' do - stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, note: 'new' })) - - expect(group.update(note: 'new')).to be(true) - end - - it 'adopts the attributes from the response' do - stub_request(:put, "#{url}/1").with(query: hash_including({})) - .to_return(json_response({ id: 1, name: 'Renamed by Zammad' })) - - group.update(note: 'new') - expect(group.name).to eq('Renamed by Zammad') - end - it 'returns false and records the error when Zammad rejects the attributes' do stub_request(:put, "#{url}/1").with(query: hash_including({})) .to_return(json_response({ error: 'Note is too long' }, status: 422)) @@ -470,22 +300,6 @@ def self.name expect(group.update(note: 'new')).to be(false) expect(group.error.server_message).to eq('Note is too long') end - - it 'keeps the staged changes after a rejection, so they can be corrected' do - stub_request(:put, "#{url}/1").with(query: hash_including({})) - .to_return(json_response({ error: 'Note is too long' }, status: 422)) - - group.update(note: 'new') - expect(group.changes).to eq(note: %w[old new]) - end - - it 'creates a record that has not been saved yet' do - stub = stub_request(:post, url).with(query: hash_including({}), body: '{"name":"Support"}') - .to_return(json_response({ id: 7, name: 'Support' }, status: 201)) - - expect(client.groups.new.update(name: 'Support')).to be(true) - expect(stub).to have_been_requested - end end describe '#update!' do @@ -532,30 +346,6 @@ def self.name expect { ZammadAPI::Resources::Group.new(transport).reload } .to raise_error(ZammadAPI::Error, /has not been saved, so there is nothing to reload/) end - - it 'raises ParseError when the response is not an object' do - stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }) - .to_return(json_response([])) - - expect { group.reload } - .to raise_error(ZammadAPI::ParseError, /expected a JSON object, got Array/) - end - - it 'raises ParseError when the response is not JSON' do - stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }) - .to_return(status: 200, body: 'Gateway Timeout', headers: { 'Content-Type' => 'text/html' }) - - expect { group.reload } - .to raise_error(ZammadAPI::ParseError, /expected a JSON object, got String/) - end - - it 'keeps the previous attributes when the response cannot be decoded' do - stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }) - .to_return(json_response([])) - - expect { group.reload }.to raise_error(ZammadAPI::ParseError) - expect(group.name).to eq('Users') - end end describe '.member_path' do @@ -579,24 +369,6 @@ def self.name expect(stub).to have_been_requested end - it 'takes a 204 for a deleted record' do - stub_request(:delete, "#{url}/1").to_return(status: 204) - - expect(group.destroy).to be(true) - expect(group).to be_destroyed - end - - it 'takes the empty object Zammad answers with for a group' do - stub_request(:delete, "#{url}/1").to_return(json_response({})) - - expect(group.destroy).to be(true) - expect(group).to be_destroyed - end - - it 'raises for a record that was never saved' do - expect { client.groups.new.destroy }.to raise_error(ZammadAPI::Error, /has not been saved, so there is nothing to destroy/) - end - it 'sends nothing for a record built with an id it was never saved with' do stub = stub_request(:delete, "#{url}/99") @@ -622,84 +394,6 @@ def self.name it 'says so in inspect' do expect(group.inspect).to include('destroyed=true') end - - it 'leaves a second destroy to Zammad, which answers 404' do - stub_request(:delete, "#{url}/1").to_return(status: 404, body: '') - - expect { group.destroy }.to raise_error(ZammadAPI::NotFoundError) - end - end - - context 'with state staged before it was destroyed' do - subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } - - before do - stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') - group.name = 'Support' - end - - it 'leaves the attributes as they are, the staged change included' do - group.destroy - - expect(group.name).to eq('Support') - expect(group.changes).to eq(name: %w[Users Support]) - end - end - end - - describe 'a copy made with dup or clone' do - let(:original) { client.groups.find(1) } - - before do - stub_request(:get, "#{url}/1").with(query: { expand: 'true' }).to_return(json_response({ id: 1, name: 'A', note: 'n' })) - end - - %i[dup clone].each do |copier| - context "with #{copier}" do - let(:copy) { original.public_send(copier) } - - it 'does not mark the original as changed when the copy is written' do - copy.name = 'X' - expect(original).not_to be_changed - end - - it 'does not stage the write on the original' do - copy.name = 'X' - expect(original.changes).to eq({}) - end - - it 'stages the write on the copy' do - copy.name = 'X' - expect(copy.changes).to eq({ name: %w[A X] }) - end - - it 'sends nothing when the original is saved after the copy was written' do - copy.name = 'X' - original.save - expect(a_request(:put, "#{url}/1")).not_to have_been_made - end - - it 'does not stage a write to the original on the copy' do - copy - original.name = 'Y' - expect(copy.changes).to eq({}) - end - - it 'carries over what was staged when it was made' do - original.name = 'Y' - expect(copy.changes).to eq({ name: %w[A Y] }) - end - - it 'keeps those two change sets apart afterwards' do - original.name = 'Y' - copy.note = 'other' - expect(original.changes.keys).to eq([:name]) - end - - it 'is still the same Zammad record' do - expect(copy).to eq(original) - end - end end end @@ -713,53 +407,6 @@ def self.name expect(first_fetch).not_to equal(second_fetch) expect(first_fetch).to eq(second_fetch) end - - it 'tells records of different resources with the same id apart' do - group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) - user = ZammadAPI::Resources::User.from_response(unit_transport, id: 1) - - expect(group).not_to eq(user) - end - - context 'with a record read through two clients for one instance' do - let(:record) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) } - - it 'is the same record through a client with other options' do - other = ZammadAPI::Resources::Group.from_response(unit_transport(timeout: 5, http_token: 'another'), id: 1) - - expect(record).to eq(other) - expect(record.hash).to eq(other.hash) - end - - it 'is the same record through an on_behalf_of scope' do - scoped = ZammadAPI::Resources::Group.from_response(unit_transport.with_on_behalf_of('agent@example.com'), id: 1) - - expect([record, scoped].uniq.size).to eq(1) - end - - it 'is the same record whether or not the url was written with its trailing slash' do - other = ZammadAPI::Resources::Group.from_response(unit_transport(url: ClientHelper::BASE_URL.chomp('/')), id: 1) - - expect(record).to eq(other) - end - end - - it 'identifies a record by its id once its first save assigns one' do - stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 7, name: 'Support' })) - group = client.groups.new(name: 'Support') - - expect(group).not_to eq(ZammadAPI::Resources::Group.from_response(unit_transport, id: 7)) - group.save! - expect(group).to eq(ZammadAPI::Resources::Group.from_response(unit_transport, id: 7)) - end - end - - describe '#to_json' do - it 'renders the attributes rather than the object' do - group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') - - expect(group.to_json).to eq('{"id":1,"name":"Users"}') - end end describe '#inspect' do @@ -777,32 +424,6 @@ def self.name it 'blanks a staged password' do expect(user.inspect).to include('password: "[REDACTED]"').and include('login: "x"') end - - it 'does not print the password anywhere' do - expect(user.inspect).not_to include('hunter2') - end - - it 'blanks a credential nested in another attribute' do - expect(user.inspect).not_to include('s3cret') - end - - it 'leaves what sits beside a nested credential readable' do - expect(user.inspect).to include('locale: "de"') - end - - it 'is what pp prints as well' do - expect(PP.pp(user, +'')).not_to include('hunter2') - end - - it 'blanks one that was written after the record was built' do - user.password = 'correct horse' - expect(user.inspect).not_to include('correct horse') - end - - it 'still hands the value over to what sends it' do - expect(user.attributes[:password]).to eq('hunter2') - expect(user.to_h[:password]).to eq('hunter2') - end end end @@ -819,44 +440,14 @@ def self.name expect(subclass.resource_path).to eq('api/v1/tickets') end - it 'inherits the member path built from it' do - expect(subclass.member_path(7)).to eq('api/v1/tickets/7') - end - - it 'inherits searchability' do - expect(subclass.searchable?).to be(true) - end - - it 'inherits the page limit' do - expect(subclass.page_limit).to eq(100) - end - - it 'inherits whether the index endpoint sorts' do - expect(subclass.sortable?).to be(false) - end - it 'lets a subclass declare a path of its own' do own = Class.new(ZammadAPI::Resources::Ticket) { path 'api/v1/my_tickets' } expect(own.resource_path).to eq('api/v1/my_tickets') end - - # An override has to win even when it is the falsey value, which is why - # the lookup asks whether the ivar is defined rather than whether it is - # truthy. - it 'lets a subclass declare itself unsearchable' do - own = Class.new(ZammadAPI::Resources::Ticket) { searchable false } - - expect(own.searchable?).to be(false) - end end describe 'the endpoint declarations' do - it 'refuses a misspelled declaration at load' do - expect { Class.new(described_class) { searcheable true } } - .to raise_error(NoMethodError, /searcheable/) - end - it 'defaults to unsearchable, so an unrouted /search is refused at the call site' do expect(Class.new(described_class).searchable?).to be(false) end @@ -891,43 +482,11 @@ def self.name expect(group.changes).to eq({ note: [nil, 'x'] }) end - it 'reads back through the matching reader' do - group[:note] = 'x' - - expect(group[:note]).to eq('x') - end - it 'takes a string key the way the reader does' do group['note'] = 'x' expect(group[:note]).to eq('x') end - - it 'refuses what the named writer refuses' do - expect { group[:id] = 9 }.to raise_error(ZammadAPI::Error, /cannot be changed/) - end - - it 'invents no attribute from the operator itself' do - group[:note] = 'x' - - expect(group.attributes.keys).not_to include(:[]) - end - - it 'is claimed by a record that stages writes' do - expect(group).to respond_to(:[]=) - end - - it 'invents no attribute from a comparison operator' do - expect { group.public_send(:<=, 5) }.to raise_error(NoMethodError) - - expect(group.attributes.keys).not_to include(:<) - end - - it 'stages nothing for a comparison operator' do - expect { group.public_send(:<=, 5) }.to raise_error(NoMethodError) - - expect(group).not_to be_changed - end end describe 'writing the id' do @@ -938,29 +497,9 @@ def self.name .to raise_error(ZammadAPI::Error, 'ZammadAPI::Resources::Group#id cannot be changed: it is what addresses this record') end - it 'is refused through assign_attributes too' do - expect { group.assign_attributes(id: 99) }.to raise_error(ZammadAPI::Error, /cannot be changed/) - end - - it 'is refused through update too, and sends nothing' do - expect { group.update(id: 99) }.to raise_error(ZammadAPI::Error, /cannot be changed/) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'leaves the record addressing what it did before' do - expect { group.id = 99 }.to raise_error(ZammadAPI::Error) - - expect(group.id).to eq(1) - expect(group).not_to be_changed - end - it 'is taken by the constructor' do expect(client.groups.new(id: 5).id).to eq(5) end - - it 'still lets a record Zammad served carry one' do - expect(ZammadAPI::Resources::Group.from_response(unit_transport, id: 5).id).to eq(5) - end end describe 'a record Zammad served without an id' do @@ -969,16 +508,6 @@ def self.name it 'refuses a reload it cannot address' do expect { group.reload }.to raise_error(ZammadAPI::Error, 'ZammadAPI::Resources::Group has no id, save it first') end - - it 'refuses a destroy it cannot address' do - expect { group.destroy }.to raise_error(ZammadAPI::Error, /has no id/) - end - - it 'refuses a save it cannot address' do - group.name = 'Support' - - expect { group.save! }.to raise_error(ZammadAPI::Error, /has no id/) - end end # Zammad answers a create and an update with a JSON object, so a 2xx with @@ -1013,54 +542,6 @@ def swallow expect(group.new_record?).to be(true) expect(group.persisted?).to be(false) end - - it 'sends the record with the next save, which is the first Zammad sees' do - swallow { group.save } - - expect(group.save).to be(true) - expect(group.id).to eq(7) - expect(a_request(:post, url).with(query: hash_including({}), body: { name: 'Support' })).to have_been_made.twice - end - end - - context 'when it was an update' do - subject(:ticket) { client.tickets.find(1) } - - let(:ticket_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/1" } - - before do - stub_request(:get, ticket_url).with(query: hash_including({})).to_return(json_response({ id: 1, title: 'Help', state: 'open' })) - stub_request(:put, ticket_url).with(query: hash_including({})) - .to_return(login_page, json_response({ id: 1, title: 'Help', state: 'closed' })) - - swallow { ticket.update(state: 'closed') } - end - - it 'keeps the changes staged' do - expect(ticket.changes).to eq(state: %w[open closed]) - end - - it 'sends them with the next save rather than reporting it stored' do - expect(ticket.save).to be(true) - expect(a_request(:put, ticket_url).with(query: hash_including({}), body: { state: 'closed' })).to have_been_made.twice - expect(ticket.changed?).to be(false) - end - end - - it 'takes a 2xx that names no content type the same way' do - stub_request(:post, url).with(query: hash_including({})).to_return(status: 200, body: 'OK') - group = client.groups.new(name: 'Support') - swallow { group.save } - - expect(group.new_record?).to be(true) - end - - it 'takes a body that says it is JSON and cannot be read the same way' do - stub_request(:post, url).with(query: hash_including({})).to_return(unreadable_json_response(status: 201)) - group = client.groups.new(name: 'Support') - - expect { group.save }.to raise_error(ZammadAPI::ParseError) - expect(group.new_record?).to be(true) end end end diff --git a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb index f892c69..f6c5343 100644 --- a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb @@ -20,10 +20,6 @@ expect(attachment.id).to eq(3) end - it 'is the same attachment as another read of it' do - expect(attachment).to eq(article.attachments.first) - end - it 'carries the filename' do expect(attachment.filename).to eq('note.txt') end @@ -56,14 +52,6 @@ expect(attachment.download).to eq('contents') end - it 'returns binary data undisturbed' do - png = "\x89PNG\r\n\x1A\n\x00\xFF".b - stub_request(:get, download_url) - .to_return(status: 200, body: png, headers: { 'Content-Type' => 'image/png' }) - - expect(attachment.download).to eq(png) - end - it 'uses binary encoding' do stub_request(:get, download_url).to_return(status: 200, body: 'contents') expect(attachment.download.encoding).to eq(Encoding::BINARY) @@ -88,15 +76,6 @@ expect(stub).to have_been_requested expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/9/3")).not_to have_been_made end - - it 'escapes the article id and the attachment id too' do - stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/ticket_attachment/42/9%2F..%2Fx/3%2F..%2Fy") - .to_return(status: 200, body: 'contents') - - described_class.new(transport, id: '3/../y', ticket_id: 42, article_id: '9/../x').download - - expect(stub).to have_been_requested - end end it 'is read-only' do @@ -104,10 +83,6 @@ expect { attachment.filename = 'other.txt' }.to raise_error(NoMethodError, /read-only/) end - it 'does not claim a writer it would refuse' do - expect(described_class.new(transport, id: 3)).not_to respond_to(:filename=) - end - describe '#inspect' do it 'summarizes the attachment' do attachment = described_class.new(transport, id: 3, filename: 'note.txt', size: '12') diff --git a/spec/unit/zammad_api/resources/ticket_spec.rb b/spec/unit/zammad_api/resources/ticket_spec.rb index f8163c9..c44dea1 100644 --- a/spec/unit/zammad_api/resources/ticket_spec.rb +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -33,13 +33,6 @@ .to raise_error(ZammadAPI::ParseError, /Can't get articles \(ZammadAPI::Resources::TicketArticle\): expected a JSON array, got Hash/) end - it 'reads the list again on each call, so an article added in between shows up' do - stub_request(:get, articles_url).with(query: hash_including({})) - .to_return(json_response([{ id: 1 }]), json_response([{ id: 1 }, { id: 2 }])) - - expect([ticket.articles.size, ticket.articles.size]).to eq([1, 2]) - end - it 'says to save an unsaved ticket rather than requesting a path without an id' do unsaved = described_class.new(unit_transport, title: 'Help') @@ -73,13 +66,6 @@ expect(ticket.add_article(body: 'hello')).to be_a(ZammadAPI::Resources::TicketArticle) end - it 'returns a persisted article' do - stub_request(:post, article_url).with(query: hash_including({})) - .to_return(json_response({ id: 9 }, status: 201)) - - expect(ticket.add_article(body: 'hello')).to be_persisted - end - # `ticket.add_article(params.require(:article).permit(:body))`, which is # taken apart here before the article is built from it. it 'reads strong parameters as the Hash they convert to' do @@ -100,46 +86,16 @@ expect(stub).to have_been_requested end - it 'leaves the Hash it was given as it was' do - stub_request(:post, article_url).with(query: hash_including({})) - .to_return(json_response({ id: 9, ticket_id: 42 }, status: 201)) - attributes = { ticket_id: 9, body: 'hello' } - ticket.add_article(attributes) - - expect(attributes).to eq(ticket_id: 9, body: 'hello') - end - context 'when the ticket has not been saved' do subject(:ticket) { described_class.new(unit_transport, title: 'Help') } it 'refuses locally' do expect { ticket.add_article(body: 'hello') }.to raise_error(ZammadAPI::Error, /has no id, save it first/) end - - it 'sends nothing' do - stub = stub_request(:post, article_url).with(query: hash_including({})) - - begin - ticket.add_article(body: 'hello') - rescue ZammadAPI::Error - nil - end - - expect(stub).not_to have_been_requested - end end end describe '#article' do - it 'is not a method of a ticket' do - expect(described_class.method_defined?(:article)).to be(false) - end - - it 'raises NoMethodError when called to add an article, and sends nothing' do - expect { ticket.article(body: 'hello') }.to raise_error(NoMethodError) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - it 'reads the article staged for the next save' do ticket.article = { body: 'reply' } diff --git a/spec/unit/zammad_api/response_error_spec.rb b/spec/unit/zammad_api/response_error_spec.rb index 9b56d67..2c265b8 100644 --- a/spec/unit/zammad_api/response_error_spec.rb +++ b/spec/unit/zammad_api/response_error_spec.rb @@ -48,11 +48,7 @@ def response(status, body, headers = {}) 422 => ZammadAPI::ValidationError, 429 => ZammadAPI::RateLimitError, 400 => ZammadAPI::ClientError, - 408 => ZammadAPI::ClientError, - 418 => ZammadAPI::ClientError, 500 => ZammadAPI::ServerError, - 502 => ZammadAPI::ServerError, - 503 => ZammadAPI::ServerError }.each do |status, error_class| it "maps #{status} to #{error_class}" do result = described_class.build(response(status, {}), operation: 'find object') @@ -151,15 +147,6 @@ def response(status, body, headers = {}) bare = ZammadAPI::NotFoundError.new(operation: 'find object by name', detail: 'no record matched') expect(bare.status).to eq(404) end - - it 'still has no body or headers to report without a response' do - bare = ZammadAPI::NotFoundError.new(operation: 'find object by name', detail: 'no record matched') - expect([bare.body, bare.headers]).to eq([nil, {}]) - end - - it 'leaves a generic ResponseError without a status' do - expect(described_class.new(operation: 'find object').status).to be_nil - end end describe ZammadAPI::RateLimitError do @@ -185,10 +172,6 @@ def retry_after(value) expect(%w[010 08 0030].map { retry_after(it) }).to eq([10, 8, 30]) end - it 'returns nil for a figure in another base' do - expect(retry_after('0x10')).to be_nil - end - it 'reads a figure held as an Integer' do expect(retry_after(30)).to eq(30) end diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb index 1c4aff9..47eec15 100644 --- a/spec/unit/zammad_api/test_spec.rb +++ b/spec/unit/zammad_api/test_spec.rb @@ -23,10 +23,6 @@ expect(client.config.url).to eq('https://zammad.test/') end - it 'reports the very configuration the stand-in was built with' do - expect(client.config).to be(zammad.config) - end - # The stand-in carries a token of its own, so credentials handed to it # replace that one rather than being refused as a second scheme. it 'accepts credentials of another kind in place of its own token' do @@ -38,10 +34,6 @@ expect(described_class.new(url: 'https://other.test/').client.config.url).to eq('https://other.test/') end - it 'is the same client every time, rather than a new HTTP stack per call' do - expect(zammad.client).to equal(zammad.client) - end - describe 'a client derived with #with' do it 'still answers from the stand-in instead of opening a connection' do zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Support' }) @@ -64,14 +56,6 @@ it 'keeps the derived options under an on_behalf_of scope taken afterwards' do expect(zammad.client.with(timeout: 5).on_behalf_of('agent@example.com').config.timeout).to eq(5) end - - it 'still takes two records found through the same derived client as one' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - derived = zammad.client.with(timeout: 5) - found = derived.groups.find(1) - - expect(derived.groups.find(1)).to eq(found) - end end end @@ -82,14 +66,6 @@ expect(client.groups.find(1).name).to eq('Users') end - it 'builds records that behave like fetched ones' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) - - group = client.groups.find(1) - expect(group).to be_persisted - expect { group.attributes[:name] = 'x' }.to raise_error(FrozenError) - end - it 'answers a collection with every page' do zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }], query: { page: 1 }) zammad.stub(:get, 'api/v1/groups', body: [], query: { page: 2 }) @@ -110,39 +86,18 @@ .to raise_error(ArgumentError, /a request path is relative to the instance URL/) end - it 'records nothing for a path it refuses' do - expect { client.get('https://other.example/collect') }.to raise_error(ArgumentError) - expect(zammad.requests).to be_empty - end - it 'raises the mapped error class for a non-2xx status' do zammad.stub(:get, 'api/v1/groups/1', status: 404, body: { error: 'not found' }) expect { client.groups.find(1) }.to raise_error(ZammadAPI::NotFoundError, /not found/) end - it 'raises a validation error that save reports as false' do - zammad.stub(:post, 'api/v1/groups', status: 422, body: { error: 'Name is required' }) - - group = client.groups.new(name: '') - expect(group.save).to be(false) - expect(group.error.server_message).to eq('Name is required') - end - it 'raises a rate limit with the wait Zammad asked for' do zammad.stub(:get, 'api/v1/groups/1', status: 429, headers: { 'Retry-After' => '30' }) expect { client.groups.find(1) }.to raise_error(ZammadAPI::RateLimitError) { expect(it.retry_after).to eq(30) } end - it 'raises for a failure at once, without the retries the real transport makes' do - zammad.stub(:get, 'api/v1/groups/1', status: 503) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - - expect { client.groups.find(1) }.to raise_error(ZammadAPI::ServerError) - expect(zammad.requests.size).to eq(1) - end - it 'serves a non-JSON body untouched, e.g. an attachment' do zammad.stub(:get, 'api/v1/ticket_attachment/1/2/3', body: 'binary-ish') @@ -156,12 +111,6 @@ expect(zammad.stub(:get, 'api/v1/groups', body: [])).to be(zammad) end - it 'accepts string keys in the body' do - zammad.stub(:get, 'api/v1/groups/1', body: { 'id' => 1, 'name' => 'Users' }) - - expect(client.groups.find(1).name).to eq('Users') - end - it 'exposes response headers' do zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => '7' }) @@ -174,12 +123,6 @@ expect(client.get('api/v1/groups').headers['content-type']).to eq('application/json') end - it 'serves an object body with the same content-type' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - - expect(client.get('api/v1/groups/1').headers['content-type']).to eq('application/json') - end - it 'lets a test say the endpoint answered with something else' do zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'Content-Type' => 'application/json; charset=utf-8' }) @@ -192,10 +135,6 @@ it 'hands back the raw body Zammad would have sent' do expect(client.get('api/v1/groups/1').body).to eq('{"id":1}') end - - it 'fails the way a real one would when a record is read from it' do - expect { client.groups.find(1) }.to raise_error(ZammadAPI::ParseError) - end end it 'carries a header value as the String the wire would have sent' do @@ -204,18 +143,6 @@ expect(client.get('api/v1/groups').headers['x-total-count']).to eq('7') end - it 'reads a list stubbed as a JSON string' do - zammad.stub(:get, 'api/v1/groups', body: '[{"id":1,"name":"a"},{"id":2,"name":"b"}]', headers: { 'Content-Type' => 'application/json' }) - - expect(client.groups.all.map(&:name)).to eq(%w[a b]) - end - - it 'keeps the raw body of a page it did not replace' do - zammad.stub(:get, 'api/v1/groups/1', body: '{"id":1}', headers: { 'Content-Type' => 'application/json' }) - - expect(client.get('api/v1/groups/1').raw_body).to eq('{"id":1}') - end - it 'decodes a string body a stub declares as JSON' do zammad.stub(:get, 'api/v1/groups/1', body: '{"id":1,"name":"Users"}', headers: { 'Content-Type' => 'application/json' }) @@ -250,12 +177,6 @@ 3.times { client.groups.find(1) } expect(client.groups.find(1).name).to eq('Second') end - - it 'reuses a single stub for any number of requests' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) - - expect(Array.new(3) { client.groups.find(1).name }).to eq(%w[Users Users Users]) - end end describe 'query matching' do @@ -271,12 +192,6 @@ expect { client.groups.all.to_a }.to raise_error(described_class::UnstubbedRequestError) end - it 'ignores the parameters the client adds itself' do - zammad.stub(:get, 'api/v1/groups', body: [], query: { sort_by: 'name' }) - - expect { client.groups.order(:name).to_a }.not_to raise_error - end - it 'matches an array-valued parameter' do zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { ids: [1, 2], page: 1 }) zammad.stub(:get, 'api/v1/users/search', body: [], query: { ids: [1, 2], page: 2 }) @@ -284,13 +199,6 @@ expect(client.users.search('x', ids: [1, 2]).map(&:id)).to eq([1]) end - it 'does not match an array whose values differ' do - zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { ids: [1, 2] }) - - expect { client.users.search('x', ids: [3]).to_a } - .to raise_error(described_class::UnstubbedRequestError) - end - it 'answers a search count from a stub for the request for the total' do zammad.stub(:get, 'api/v1/groups/search', body: { total_count: 42 }, query: { only_total_count: true }) @@ -315,51 +223,21 @@ end describe 'an unstubbed request' do - it 'raises rather than returning something empty' do - expect { client.groups.find(1) }.to raise_error(described_class::UnstubbedRequestError) - end - it 'names the request that was not stubbed' do expect { client.groups.find(1) } .to raise_error(described_class::UnstubbedRequestError, 'GET api/v1/groups/1 with query {"expand" => "true"} was not stubbed on this ZammadAPI::Test (nothing is stubbed)') end - it 'says so when nothing at all is stubbed' do - expect { client.groups.find(1) }.to raise_error(/nothing is stubbed/) - end - it 'lists what is stubbed, because a wrong path is the usual cause' do zammad.stub(:get, 'api/v1/groups/2', body: { id: 2 }) expect { client.groups.find(1) }.to raise_error(%r{stubbed: GET api/v1/groups/2}) end - it 'names the query of a request for a page no stub answers' do - zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { page: 1 }) - zammad.stub(:get, 'api/v1/users/search', body: [{ id: 2 }], query: { page: 2 }) - - expect { client.users.search('x').to_a }.to raise_error( - described_class::UnstubbedRequestError, - %r{\AGET api/v1/users/search with query \{.*"page" => "3".*\} was not stubbed on this ZammadAPI::Test \(stubbed: GET api/v1/users/search\)\z} - ) - end - it 'is outside ZammadAPI::Error, so code under test cannot rescue it as an API failure' do expect(described_class::UnstubbedRequestError.ancestors).not_to include(ZammadAPI::Error) expect(described_class::UnstubbedRequestError.ancestors).to include(StandardError) end - - it 'escapes a rescue of the gem\'s errors, the way the examples write one' do - zammad.stub(:get, 'api/v1/groups/2', body: { id: 2 }) - - caller_with_a_rescue = lambda do - client.groups.find(1) - rescue ZammadAPI::Error - :handled_as_an_api_failure - end - - expect { caller_with_a_rescue.call }.to raise_error(described_class::UnstubbedRequestError) - end end describe '#requests' do @@ -392,20 +270,6 @@ expect(zammad.requests.last.body).to eq({ name: 'Support', note: { internal: 'yes' } }) end - it 'hands out a recorded body that cannot be written through' do - zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) - client.post('api/v1/groups', body: { name: 'Support' }) - - expect(zammad.requests.last.body).to be_frozen - end - - it 'records a record built from strong parameters as the attributes it sends' do - zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) - client.groups.create(StrongParameters.new(name: 'Support')) - - expect(zammad.requests.last.body).to eq({ name: 'Support' }) - end - it 'records the query parameters the client sent' do client.groups.find(1) @@ -439,27 +303,6 @@ expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') end - it 'records an integer user id the way the wire carries it' do - client.on_behalf_of(42).groups.find(1) - - expect(zammad.requests.last.on_behalf_of).to eq('42') - end - - it 'records a scope that ends in a line break the way the wire carries it' do - client.on_behalf_of("agent@example.com\n").groups.find(1) - - expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') - end - - it 'records the scope a client was given, not what its string became afterwards' do - login = +'agent@example.com' - scoped = client.on_behalf_of(login) - login.replace('admin@example.com') - scoped.groups.find(1) - - expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') - end - it 'leaves on_behalf_of nil for an unscoped client' do client.groups.find(1) @@ -548,29 +391,9 @@ expect(client.groups.all.map(&:id)).to eq([1, 2]) end - it 'counts it' do - expect(client.groups.all.count).to eq(2) - end - - it 'plucks from it' do - expect(client.groups.all.pluck(:name)).to eq(%w[a b]) - end - - it 'answers page 1 with the records it holds' do - expect(client.groups.all.page(1).map(&:id)).to eq([1, 2]) - end - it 'answers a later page as an endpoint out of records would' do expect(client.groups.all.page(2).map(&:id)).to eq([]) end - - it 'answers page 1 with every record it holds, whatever size was asked for' do - expect(client.groups.all.page(1, per_page: 1).map(&:id)).to eq([1, 2]) - end - - it 'stops walking rather than reporting the stand-in as a broken paginator' do - expect { client.groups.all.to_a }.not_to raise_error - end end describe 'a list endpoint stubbed as a sequence' do @@ -588,49 +411,11 @@ def names = client.groups.all.map(&:name) expect(Array.new(3) { names }).to eq([['A'], ['B'], ['C']]) end - it 'keeps answering with the last one' do - 3.times { names } - expect(names).to eq(['C']) - end - it 'spends one stub on a read, however many pages the read asks for' do expect(client.groups.find_each(batch_size: 1).map(&:name)).to eq(['A']) expect(zammad.requests.map { it.query['page'] }).to eq(%w[1 2]) expect(names).to eq(['B']) end - - it 'does not spend a stub on a later page asked for first' do - expect(client.groups.all.page(3).to_a).to eq([]) - expect(names).to eq(['A']) - end - - it 'spends one stub on a read sized for a single record' do - expect(Array.new(3) { client.groups.first.name }).to eq(%w[A B C]) - end - - it 'starts over after a reset' do - names - zammad.reset - zammad.stub(:get, 'api/v1/groups', body: [{ id: 2, name: 'D' }]) - - expect(Array.new(2) { names }).to eq([['D'], ['D']]) - end - - it 'sequences a scoped list the same way' do - zammad.reset - %w[A B].each { zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1, name: it }], query: { query: 'x' }) } - - expect(Array.new(2) { client.groups.search('x').map(&:name) }).to eq([['A'], ['B']]) - end - - it 'answers the page after a list with an empty one, whatever stub is queued next' do - zammad.reset - zammad.stub(:get, 'api/v1/groups/search', body: [{ id: 1, name: 'A' }]) - zammad.stub(:get, 'api/v1/groups/search', status: 500) - - expect(client.groups.search('x').map(&:name)).to eq(['A']) - expect { client.groups.search('x').to_a }.to raise_error(ZammadAPI::ServerError) - end end describe 'a list endpoint whose pages are stubbed by hand' do @@ -647,11 +432,5 @@ def names = client.groups.all.map(&:name) expect(client.groups.find_each(batch_size: 1).map(&:id)).to eq([1, 2]) end - - it 'keeps a body that is not a list alone' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'a' }) - - expect(client.groups.find(1).name).to eq('a') - end end end diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb index 7b87eca..1ebb820 100644 --- a/spec/unit/zammad_api/transport_spec.rb +++ b/spec/unit/zammad_api/transport_spec.rb @@ -45,38 +45,6 @@ unit_transport(user_agent: 'my-app/1.0').get('api/v1/groups', operation: 'test') expect(stub).to have_been_requested end - - it 'names itself where the user agent given is nothing but whitespace' do - stub = stub_request(:get, url).with(headers: { 'User-Agent' => "zammad_api-ruby/#{ZammadAPI::VERSION}" }).to_return(json_response([])) - unit_transport(user_agent: ' ').get('api/v1/groups', operation: 'test') - expect(stub).to have_been_requested - end - - # WebMock is asked by Net::HTTP, which has stripped the headers by then. - # A middleware sees them as the adapter is handed them. - context 'with a configured header value that ends in a line break' do - def handed_to_the_adapter(**options) - seen = nil - recorder = Class.new(Faraday::Middleware) do - define_method(:on_request) { |env| seen = env.request_headers.to_h } - end - stub_request(:get, url).to_return(json_response([])) - unit_transport(middleware: ->(builder) { builder.use(recorder) }, **options).get('api/v1/groups', operation: 'test') - seen - end - - it 'hands the adapter an access token without it' do - expect(handed_to_the_adapter(http_token: "abc\n")['Authorization']).to eq('Token abc') - end - - it 'hands the adapter an OAuth2 token without it' do - expect(handed_to_the_adapter(http_token: nil, oauth2_token: "abc\r\n")['Authorization']).to eq('Bearer abc') - end - - it 'hands the adapter a user agent without it' do - expect(handed_to_the_adapter(user_agent: "my-app/1.0\n")['User-Agent']).to eq('my-app/1.0') - end - end end describe 'request headers' do @@ -101,32 +69,6 @@ def handed_to_the_adapter(**options) unit_transport.get('api/v1/groups', operation: 'test', query: { page: 1, expand: true }) expect(stub).to have_been_requested end - - it 'escapes values that need it' do - stub = stub_request(:get, "#{url}/search").with(query: { 'query' => 'a b&c' }).to_return(json_response([])) - unit_transport.get('api/v1/groups/search', operation: 'test', query: { query: 'a b&c' }) - expect(stub).to have_been_requested - end - - it 'encodes arrays' do - stub = stub_request(:get, url).with(query: { 'ids' => %w[1 2] }).to_return(json_response([])) - unit_transport.get('api/v1/groups', operation: 'test', query: { ids: [1, 2] }) - expect(stub).to have_been_requested - end - - # `condition` is what Zammad's search endpoints narrow by, and it is - # nested. - it 'encodes a nested hash the way Rails reads it back' do - stub = stub_request(:get, "#{url}/search") - .with(query: { 'condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => %w[1 2] } } }) - .to_return(json_response([])) - unit_transport.get( - 'api/v1/groups/search', - operation: 'test', - query: { condition: { 'ticket.state_id' => { operator: 'is', value: [1, 2] } } } - ) - expect(stub).to have_been_requested - end end describe '.relative_path' do @@ -161,27 +103,6 @@ def handed_to_the_adapter(**options) it 'drops a fragment' do expect(described_class.redact_path('api/v1/x#token=s3cret')).to eq('api/v1/x') end - - context 'when a raw request is written with a fragment' do - let(:log) { StringIO.new } - - before { stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/x").to_return(json_response({}, status: 404)) } - - it 'keeps it out of the error the request raises' do - expect { unit_client.get('api/v1/x#token=s3cret') } - .to raise_error(ZammadAPI::NotFoundError) { |error| - expect(error.message).not_to include('s3cret') - expect(error.operation).to eq('GET api/v1/x') - } - end - - it 'keeps it out of the log' do - expect { unit_client(logger: Logger.new(log)).get('api/v1/x#token=s3cret') }.to raise_error(ZammadAPI::NotFoundError) - - expect(log.string).to include("Zammad API request: GET api/v1/x\n") - expect(log.string).not_to include('s3cret') - end - end end describe '.redact' do @@ -212,6 +133,17 @@ def handed_to_the_adapter(**options) it 'hands back anything that is not a structure' do expect(described_class.redact('password')).to eq('password') end + + # One key per alternative of SENSITIVE_KEY_PATTERN, which nothing else in it matches. + %w[password pwd bind_pw passphrase client_secret access_token credentials Cookie Proxy-Authorization privateKey otp_code pw_salt].each do |name| + it "redacts #{name}" do + expect(described_class.redact({ name => 's3cret' })).to eq({ name => '[REDACTED]' }) + end + end + + it 'leaves bind_user alone' do + expect(described_class.redact({ 'bind_user' => 'shown' })).to eq({ 'bind_user' => 'shown' }) + end end describe '.escape_path_segment' do @@ -265,37 +197,6 @@ def handed_to_the_adapter(**options) unit_transport.post('api/v1/groups', operation: 'test', body: '{"name":"Raw"}') expect(stub).to have_been_requested end - - context 'with values that are not JSON types' do - before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } - - it 'sends a Symbol as text' do - unit_transport.post('api/v1/groups', operation: 'test', body: { state: :open, 1 => nil }) - - expect(a_request(:post, url).with(body: '{"state":"open","1":null}')).to have_been_made - end - - # Zammad reads a time or a date attribute from the text either prints. - it 'sends a Time and a Date as they print' do - unit_transport.post('api/v1/groups', operation: 'test', body: { pending_time: Time.utc(2026, 1, 2, 3, 4, 5), due: Date.new(2026, 1, 2) }) - - expect(a_request(:post, url).with(body: '{"pending_time":"2026-01-02 03:04:05 UTC","due":"2026-01-02"}')).to have_been_made - end - - it 'leaves an object with a to_json of its own to write itself' do - point = Data.define(:x, :y) { def to_json(*) = to_h.to_json(*) }.new(1, 2) - unit_transport.post('api/v1/groups', operation: 'test', body: { point: point, points: [point] }) - - expect(a_request(:post, url).with(body: '{"point":{"x":1,"y":2},"points":[{"x":1,"y":2}]}')).to have_been_made - end - - it 'sends a record of this gem as its attributes' do - group = ZammadAPI::Resources::Group.from_response(unit_transport, { id: 1, name: 'Users' }) - unit_transport.post('api/v1/groups', operation: 'test', body: { group: group }) - - expect(a_request(:post, url).with(body: '{"group":{"id":1,"name":"Users"}}')).to have_been_made - end - end end describe 'response decoding' do @@ -311,24 +212,6 @@ def handed_to_the_adapter(**options) expect(response.raw_body).to eq('{"id":1}') end - it 'leaves non-JSON bodies untouched' do - stub_request(:get, url).to_return(status: 200, body: 'plain text', headers: { 'Content-Type' => 'text/plain' }) - response = unit_transport.get('api/v1/groups', operation: 'test') - expect(response.body).to eq('plain text') - end - - it 'keeps a malformed JSON body as a string instead of raising' do - stub_request(:get, url).to_return(status: 200, body: 'not json', headers: { 'Content-Type' => 'application/json' }) - response = unit_transport.get('api/v1/groups', operation: 'test') - expect(response.body).to eq('not json') - end - - it 'handles an empty body' do - stub_request(:get, url).to_return(status: 200, body: '', headers: { 'Content-Type' => 'application/json' }) - response = unit_transport.get('api/v1/groups', operation: 'test') - expect(response.body).to eq('') - end - it 'downcases header names' do stub_request(:get, url).to_return(json_response([], headers: { 'X-Request-Id' => 'abc' })) response = unit_transport.get('api/v1/groups', operation: 'test') @@ -343,18 +226,6 @@ def handed_to_the_adapter(**options) .to raise_error(ZammadAPI::NotFoundError, "Can't find object: nope") end - it 'raises AuthenticationError for 401' do - stub_request(:get, url).to_return(json_response({ error: 'authentication failed' }, status: 401)) - expect { unit_transport.get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::AuthenticationError) - end - - it 'raises ServerError with the status when a proxy returns HTML' do - stub_request(:get, url).to_return(status: 502, body: 'Bad Gateway', headers: { 'Content-Type' => 'text/html' }) - expect { unit_transport.get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::ServerError, "Can't find object: HTTP 502") - end - it 'includes the resource class in the message' do stub_request(:get, url).to_return(json_response({ error: 'nope' }, status: 404)) expect { unit_transport.get('api/v1/groups', operation: 'find object', resource_class: ZammadAPI::Resources::Group) } @@ -380,11 +251,6 @@ def handed_to_the_adapter(**options) context 'when the connection is not established within open_timeout' do before { stub_request(:get, url).to_raise(Net::OpenTimeout.new('execution expired')) } - it 'raises ConnectionError, as Faraday reports it' do - expect { unit_transport.get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::ConnectionError, %r{Can't find object: http://zammad\.test/ is unreachable \(execution expired\)}) - end - it 'is still retried, as a read that never reached the server' do expect { unit_transport(retries: 2, retry_interval: 0.01).get('api/v1/groups', operation: 'find object') } .to raise_error(ZammadAPI::ConnectionError) @@ -395,7 +261,7 @@ def handed_to_the_adapter(**options) it 'wraps a refused connection' do stub_request(:get, url).to_raise(Errno::ECONNREFUSED) expect { unit_transport.get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::ConnectionError, /is unreachable/) + .to raise_error(ZammadAPI::ConnectionError, %r{http://zammad.test/ is unreachable}) end it 'wraps a TLS failure' do @@ -403,19 +269,6 @@ def handed_to_the_adapter(**options) expect { unit_transport.get('api/v1/groups', operation: 'find object') } .to raise_error(ZammadAPI::ConnectionError, /TLS handshake/) end - - it 'names the instance it could not reach' do - stub_request(:get, url).to_raise(Faraday::ConnectionFailed.new('down')) - - expect { unit_transport.get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::ConnectionError, %r{http://zammad\.test/ is unreachable}) - end - - it 'raises a TransportError subclass so both can be rescued together' do - stub_request(:get, url).to_raise(Errno::ECONNREFUSED) - expect { unit_transport.get('api/v1/groups', operation: 'find object') } - .to raise_error(ZammadAPI::TransportError) - end end describe 'retries' do @@ -440,37 +293,10 @@ def handed_to_the_adapter(**options) stub_request(:get, url).to_return({ status: 429, headers: { 'Retry-After' => '3600' } }, json_response([])) end - it 'reports the response instead of waiting it out' do - expect { transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::RateLimitError) - end - it 'does not retry' do expect { transport.get('api/v1/groups', operation: 'test') }.to raise_error(ZammadAPI::RateLimitError) expect(a_request(:get, url)).to have_been_made.once end - - it 'leaves the wait the server asked for readable from the error' do - expect { transport.get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::RateLimitError) { |error| expect(error.retry_after).to eq(3600) } - end - end - - it 'does not wait out a long Retry-After on a 503 either' do - stub_request(:get, url).to_return({ status: 503, headers: { 'Retry-After' => '3600' } }, json_response([])) - - expect { unit_transport(retries: 2, retry_interval: 0.01, timeout: 2).get('api/v1/groups', operation: 'test') } - .to raise_error(ZammadAPI::ServerError) - expect(a_request(:get, url)).to have_been_made.once - end - - it 'still waits as long as the server asks, where that is within the timeout' do - stub_request(:get, url).to_return({ status: 429, headers: { 'Retry-After' => '0.2' } }, json_response([])) - - started = Process.clock_gettime(Process::CLOCK_MONOTONIC) - response = unit_transport(retries: 1, retry_interval: 0.01).get('api/v1/groups', operation: 'test') - - expect(response.status).to eq(200) - expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be >= 0.2 end it 'gives up after the configured number of attempts' do @@ -496,13 +322,6 @@ def handed_to_the_adapter(**options) expect(a_request(:put, "#{url}/1")).to have_been_made.once end - it 'does not retry PUT after a timeout either' do - stub_request(:put, "#{url}/1").to_raise(Net::ReadTimeout).then.to_return(json_response({ id: 1 })) - expect { unit_transport(retries: 2, retry_interval: 0.01).put('api/v1/groups/1', operation: 'test', body: { a: 1 }) } - .to raise_error(ZammadAPI::TimeoutError) - expect(a_request(:put, "#{url}/1")).to have_been_made.once - end - # Repeated after a lost answer, a DELETE meets a 404 for the record it has # just deleted. it 'does not retry DELETE, which would answer a lost success with a 404' do @@ -542,29 +361,6 @@ def handed_to_the_adapter(**options) expect(seen).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") end - it 'lets the middleware see the response' do - stub_request(:get, url).to_return(json_response([{ id: 1 }])) - - seen = nil - transport = unit_transport(middleware: lambda { |builder| - builder.use(Class.new(Faraday::Middleware) do - define_method(:on_complete) { |env| seen = env.status } - end) - }) - transport.get('api/v1/groups', operation: 'test') - - expect(seen).to eq(200) - end - - it 'leaves a middleware that does not touch the body alone' do - stub_request(:get, url).to_return(json_response([{ id: 1, name: 'Users' }])) - - response = unit_transport(middleware: ->(builder) { builder.response(:logger, Logger.new(File::NULL)) }) - .get('api/v1/groups', operation: 'test') - - expect(response.body).to eq([{ id: 1, name: 'Users' }]) - end - it 'uses the configured adapter' do transport = unit_transport(adapter: :test) expect(transport.instance_variable_get(:@connection).adapter.name).to include('Adapter::Test') @@ -575,55 +371,18 @@ def handed_to_the_adapter(**options) context 'with an adapter chosen inside the middleware callable' do let(:stubs) { Faraday::Adapter::Test::Stubs.new { it.get('/api/v1/groups') { [200, { 'Content-Type' => 'application/json' }, '[{"id":7}]'] } } } - it 'keeps it' do - transport = unit_transport(middleware: ->(faraday) { faraday.adapter :test, stubs }) - - expect(transport.instance_variable_get(:@connection).adapter.name).to include('Adapter::Test') - end - - it 'sends requests through it, with the arguments it was given' do - transport = unit_transport(middleware: ->(faraday) { faraday.adapter :test, stubs }) - - expect(transport.get('api/v1/groups', operation: 'test').body).to eq([{ id: 7 }]) - expect(a_request(:any, /zammad\.test/)).not_to have_been_made - end - - it 'keeps it where it is the default adapter, named again to give it a block' do - configured = nil - transport = unit_transport(middleware: ->(faraday) { faraday.adapter(Faraday.default_adapter) { configured = true } }) - stub_request(:get, url).to_return(json_response([])) - transport.get('api/v1/groups', operation: 'test') - - expect(configured).to be(true) - end - it 'takes it over the one the adapter option names' do transport = unit_transport(adapter: :net_http, middleware: ->(faraday) { faraday.adapter :test, stubs }) expect(transport.get('api/v1/groups', operation: 'test').body).to eq([{ id: 7 }]) expect(a_request(:any, /zammad\.test/)).not_to have_been_made end - - it 'still puts the default adapter in where the callable chose none' do - transport = unit_transport(middleware: ->(faraday) { faraday.use(Class.new(Faraday::Middleware)) }) - - expect(transport.instance_variable_get(:@connection).adapter.name).to eq(Faraday::Adapter.lookup_middleware(Faraday.default_adapter).name) - end end it 'reports an unregistered adapter as a configuration error' do expect { unit_transport(adapter: :nonsense) } .to raise_error(ZammadAPI::ConfigurationError, /\Aconfig could not be used to build a connection: .*is not registered on Faraday::Adapter/) end - - it 'does not leak a Faraday error out of the client constructor' do - expect { unit_client(adapter: :nonsense) }.to raise_error(ZammadAPI::ConfigurationError) - end - - it 'keeps the cause of an unregistered adapter' do - expect { unit_transport(adapter: :nonsense) } - .to raise_error(ZammadAPI::ConfigurationError) { |error| expect(error.cause).to be_a(Faraday::Error) } - end end describe '#with_on_behalf_of' do @@ -633,31 +392,12 @@ def handed_to_the_adapter(**options) expect(stub).to have_been_requested end - it 'keeps an unscoped transport unscoped' do - expect(unit_transport.with_on_behalf_of(nil).on_behalf_of).to be_nil - end - - it 'returns a different transport' do - transport = unit_transport - expect(transport.with_on_behalf_of('someone')).not_to be(transport) - end - it 'leaves the original transport unscoped' do transport = unit_transport transport.with_on_behalf_of('someone') expect(transport.on_behalf_of).to be_nil end - it 'does not send a From header from the original transport' do - transport = unit_transport - transport.with_on_behalf_of('someone') - - stub_request(:get, url).to_return(json_response([])) - transport.get('api/v1/groups', operation: 'test') - - expect(a_request(:get, url).with { |request| request.headers.key?('From') }).not_to have_been_made - end - it 'shares the underlying connection instead of rebuilding it' do transport = unit_transport scoped = transport.with_on_behalf_of('someone') @@ -684,19 +424,6 @@ def handed_to_the_adapter(**options) it 'does not print the access token' do expect(transport.inspect).not_to include('tok-s3cret') end - - it 'does not print the proxy password' do - expect(transport.inspect).not_to include('pproxy-s3cret') - end - - it 'does not print a basic authentication password' do - basic = unit_transport(http_token: nil, user: 'u', password: 'pw-s3cret') - expect(basic.inspect).not_to include('pw-s3cret') - end - - it 'keeps both out of what pp prints too' do - expect(transport.pretty_inspect).not_to match(/tok-s3cret|pproxy-s3cret/) - end end describe '#with_config' do @@ -710,20 +437,6 @@ def handed_to_the_adapter(**options) expect(derived.on_behalf_of).to eq('agent@example.com') end - - it 'keeps a subclass on its own kind, rather than reverting to a real one' do - recording = Class.new(described_class) - stub_const('RecordingTransport', recording) - - derived = recording.new(ZammadAPI::Config.new(**unit_config)).with_config(ZammadAPI::Config.new(**unit_config(timeout: 7))) - - expect(derived).to be_a(recording) - end - - it 'returns a different transport' do - transport = unit_transport - expect(transport.with_config(transport.config)).not_to be(transport) - end end describe 'logging' do @@ -765,86 +478,6 @@ def handed_to_the_adapter(**options) .to output('').to_stdout.and output('').to_stderr end - context 'with credential-bearing payload keys' do - subject(:log) { log_device.string } - - let(:log_device) { StringIO.new } - - before do - stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) - unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)).post( - 'api/v1/groups', - operation: 'test', - body: { - login: 'jane', - password_confirm: 'confirm-s3cret', - passwd: 'passwd-s3cret', - access_token: 'access-s3cret', - refresh_token: 'refresh-s3cret', - client_secret: 'client-s3cret', - api_key: 'api-key-s3cret', - apikey: 'apikey-s3cret', - key: 'key-s3cret' - } - ) - end - - it 'redacts a password_confirm' do - expect(log).not_to include('confirm-s3cret') - end - - it 'redacts an access_token' do - expect(log).not_to include('access-s3cret') - end - - it 'redacts a refresh_token' do - expect(log).not_to include('refresh-s3cret') - end - - it 'redacts an api_key' do - expect(log).not_to include('api-key-s3cret') - end - - it 'redacts an apikey, which nothing separates the word in' do - expect(log).not_to include('apikey-s3cret') - end - - it 'redacts a bare key' do - expect(log).not_to include('key-s3cret') - end - - it 'redacts a passwd' do - expect(log).not_to include('passwd-s3cret') - end - - it 'redacts a client_secret' do - expect(log).not_to include('client-s3cret') - end - - it 'still keeps a non-sensitive value' do - expect(log).to include('login: "jane"') - end - end - - # The names Zammad filters from its own log, in - # config/initializers/filter_parameter_logging.rb. - describe 'the keys Zammad filters from its own log' do - %w[bind_pw passphrase privateKey sshKeys publicKeyId otp otp_code totp hotp salt pw_salt].each do |name| - it "redacts #{name}" do - expect(described_class.redact({ name => 's3cret' })).to eq({ name => '[REDACTED]' }) - end - end - - it 'leaves bind_user alone' do - expect(described_class.redact({ 'bind_user' => 'shown' })).to eq({ 'bind_user' => 'shown' }) - end - - it 'redacts a bind password inside the preferences of an LDAP source' do - expect(described_class.redact({ name: 'x', preferences: { bind_user: 'cn=admin', bind_pw: 'hunter2' } })) - .to eq({ name: 'x', preferences: { bind_user: 'cn=admin', bind_pw: '[REDACTED]' } }) - end - end - # Redaction goes by key, and a String has none. context 'with a body handed over as a String' do subject(:log) { log_device.string } @@ -860,12 +493,6 @@ def handed_to_the_adapter(**options) expect(log).not_to include('string-s3cret') expect(log).to include('Zammad API payload: [43 bytes, not logged]') end - - it 'still sends the body as it was given' do - transport.post('api/v1/groups', operation: 'test', body: '{"login":"jane","password":"string-s3cret"}') - - expect(a_request(:post, url).with(body: '{"login":"jane","password":"string-s3cret"}')).to have_been_made - end end context 'with a query that carries a credential' do @@ -907,11 +534,6 @@ def handed_to_the_adapter(**options) it 'logs the response line without it' do expect(log).to include('Zammad API response: GET api/v1/users/password_reset_verify -> 200') end - - it 'still sends the query as it was given' do - expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/password_reset_verify").with(query: { 'token' => 'path-s3cret', 'locale' => 'de' })) - .to have_been_made - end end # A raw request takes headers of its own and the request line prints them. @@ -934,30 +556,13 @@ def handed_to_the_adapter(**options) ) end - it 'redacts a Cookie' do - expect(log).not_to include('cookie-s3cret') - end - it 'marks the redacted header' do expect(log).to include('"Cookie" => "[REDACTED]"') end - it 'redacts a Proxy-Authorization' do - expect(log).not_to include('proxy-s3cret') - end - - it 'redacts a token header' do - expect(log).not_to include('csrf-s3cret') - end - it 'keeps a header that carries no credential' do expect(log).to include('"X-Request-Id" => "request-123"') end - - it 'still sends the headers as they were given' do - expect(a_request(:get, url).with(headers: { 'Cookie' => '_zammad_session=cookie-s3cret', 'Proxy-Authorization' => 'Basic proxy-s3cret' })) - .to have_been_made - end end end end From 88c22327d2367b024aef66cf845bbfa47fe79b8f Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 15:34:30 +0200 Subject: [PATCH 101/121] feat!: drop the test kit ZammadAPI::Test was new in 2.0 and never released. Code that calls this client can stub HTTP with WebMock, or hand a Faraday test adapter to the client through middleware:. --- CHANGELOG.md | 7 - README.md | 76 ------ lib/zammad_api/test.rb | 214 --------------- sig/vendor/faraday.rbs | 10 - sig/vendor/internal.rbs | 11 - sig/zammad_api/test.rbs | 48 ---- spec/unit/zammad_api/test_spec.rb | 436 ------------------------------ 7 files changed, 802 deletions(-) delete mode 100644 lib/zammad_api/test.rb delete mode 100644 sig/zammad_api/test.rbs delete mode 100644 spec/unit/zammad_api/test_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index cda0473..1e951bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -169,13 +169,6 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `middleware:` callable takes the place of `adapter:`. A Faraday error while building the connection surfaces as `ConfigurationError`. - RBS signatures in `sig/`, verified by Steep in CI. -- `require 'zammad_api/test'` ships a stand-in Zammad for testing code that calls this - client: `ZammadAPI::Test#stub` declares responses, `#client` hands back a real client - wired to them, and `#requests` records what was sent, with the query as text and the - headers by downcased name. The stand-in is the client's Faraday adapter, so requests and - responses travel the same transport as real ones and a stubbed 404 raises `NotFoundError`. An unstubbed request - raises `ZammadAPI::Test::UnstubbedRequestError` rather than answering with something - empty. It is not a `ZammadAPI::Error`, so the code under test cannot rescue it. - `respond_to?` answers correctly for attribute readers and resource methods. - Records implement `deconstruct_keys`, so they can be used with `case/in` pattern matching. `Config` and `Response` are `Data` objects and match as well. diff --git a/README.md b/README.md index a7bf54c..569564c 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,6 @@ > > - Which 1.x calls in **your** code the [migration table](#migrating-from-1x) does not cover. > - Endpoints you reach with [raw requests](#raw-requests) that should be modelled resources. -> - Anything the [test kit](#testing-code-that-uses-this-client) cannot stand in for. > - Naming that made you look twice, and defaults you had to override every time. > > Rough notes are welcome — a half-formed "this felt off" is worth more to us now than a @@ -39,8 +38,6 @@ Ruby client for the Zammad API v1.0. - **Your own resources** — `client.resource(Role)` gives a class you declare everything a modelled one has — and **raw requests** reach the rest of the API, without giving up authentication, retries or the error classes. -- A **test kit** (`zammad_api/test`) stands in for a Zammad, so your own tests need no - HTTP interception. > **Upgrading from 1.x?** See [Migrating from 1.x](#migrating-from-1x), which lists every > call that changed. @@ -944,79 +941,6 @@ parameters and headers that look like credentials (`password`, `token`, `secret` ...) are redacted, and a path is logged without its query string. A body that is not a Hash or an Array, such as a JSON String, is not logged, only its size. -## Testing code that uses this client - -`zammad_api/test` ships a stand-in Zammad, so your own tests need no HTTP interception: - -```ruby -require 'zammad_api/test' - -RSpec.describe TicketCloser do - let(:zammad) { ZammadAPI::Test.new } - - it 'closes the ticket' do - zammad.stub(:get, 'api/v1/tickets/1', body: {id: 1, title: 'Help', state: 'open'}) - zammad.stub(:put, 'api/v1/tickets/1', body: {id: 1, state: 'closed'}) - - described_class.new(zammad.client).close(1) - - expect(zammad.requests.last.verb).to eq(:put) - expect(zammad.requests.last.body).to eq({state: 'closed'}) - end -end -``` - -`zammad.client` is a real `ZammadAPI::Client` with the stand-in as its Faraday adapter, so -requests and responses go through the same encoding, decoding, error mapping and record -building as real ones — a stub with `status: 404` -raises `NotFoundError`, and one with `status: 422` makes `save` return `false`. - -| Method | What it does | -| ------ | ------------ | -| `stub(verb, path, status:, body:, headers:, query:)` | Declares a response. `query:` matches a subset of the request's parameters, so it need not repeat `expand`, `page` or `per_page`. | -| `client` | A client wired to this stand-in. | -| `requests` | Every request made, oldest first, as `verb` / `path` / `query` / `body` / `headers` / `on_behalf_of`. | -| `stubbed` | One `"GET api/v1/groups"` per stubbed endpoint. | -| `reset` | Forgets the stubs and the recorded requests. | - -A `Hash` or `Array` body is served as JSON and gets `content-type: application/json` -unless `headers:` says otherwise, and it is that header that decides whether the body -comes back decoded, as it does on the wire. A recorded request's `query` has its keys and -values as text, and its `headers` are every header sent, with downcased names; an -`on_behalf_of` scope has a field of its own as well. - -Stubbing the same endpoint again queues a second response. A request is answered by the -first stub whose `query:` it matches, and that stub is used up unless it is the last one -that matches, so the last answers every later request: - -```ruby -zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}]) -zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}, {id: 2, name: 'Sales'}]) - -client.groups.all.count # => 1 -client.groups.all.count # => 2 -``` - -One stub is enough for a list. It answers the first page as written, and a request for a -later page with an empty list, unless its `query:` names a `page`: - -```ruby -zammad.stub(:get, 'api/v1/groups', body: [{id: 1, name: 'Users'}, {id: 2, name: 'Sales'}]) - -client.groups.all.map(&:name) # => ["Users", "Sales"] - -zammad.stub(:get, 'api/v1/tickets', body: first_hundred, query: {page: 1}) -zammad.stub(:get, 'api/v1/tickets', body: [{id: 101}], query: {page: 2}) -``` - -The stand-in's client does not retry unless you pass `retries:`: a stubbed 429 or 5xx -raises at once, where a client talking to Zammad would ask again. - -A request that was not stubbed raises `ZammadAPI::Test::UnstubbedRequestError`, listing -what is stubbed, rather than answering with something empty. It is deliberately not a -`ZammadAPI::Error`: a forgotten stub means the test is wrong, not that Zammad refused -something, so a `rescue ZammadAPI::Error` in the code under test lets it through. - ## Type signatures RBS signatures ship in `sig/` and are checked in CI with [Steep](https://github.com/soutaro/steep). diff --git a/lib/zammad_api/test.rb b/lib/zammad_api/test.rb deleted file mode 100644 index ddf92cd..0000000 --- a/lib/zammad_api/test.rb +++ /dev/null @@ -1,214 +0,0 @@ -# frozen_string_literal: true - -require 'json' - -require_relative '../zammad_api' - -module ZammadAPI - # A stand-in Zammad, for testing code that calls this client. - # - # Stub the endpoints the code under test will reach, hand it {#client}, then - # assert against {#requests}. The stand-in is the client's Faraday adapter, - # so nothing has to be intercepted at the socket level and requests and - # responses go through the same transport as real ones. - # - # @example - # require 'zammad_api/test' - # - # zammad = ZammadAPI::Test.new - # zammad.stub(:get, 'api/v1/tickets/1', body: {id: 1, title: 'Help', state: 'open'}) - # zammad.stub(:put, 'api/v1/tickets/1', body: {id: 1, state: 'closed'}) - # - # TicketCloser.new(zammad.client).close(1) - # - # zammad.requests.last.verb # => :put - # zammad.requests.last.body # => {state: "closed"} - # - # @example An error path - # zammad.stub(:get, 'api/v1/tickets/9', status: 404, body: {error: 'not found'}) - # # the code under test sees ZammadAPI::NotFoundError - class Test - # Raised when the code under test reaches an endpoint that was not stubbed. - # - # Deliberately outside {ZammadAPI::Error}: this says the test is wrong, not - # that Zammad refused something, so a +rescue ZammadAPI::Error+ in the code - # under test does not swallow it. - class UnstubbedRequestError < StandardError; end - - # One request the code under test made. - # - # @!attribute [r] verb - # @return [Symbol] +:get+, +:post+, +:put+ or +:delete+ - # @!attribute [r] path - # @return [String] path relative to the instance URL - # @!attribute [r] query - # @return [Hash{String => Object}] query parameters, with keys and - # values as text - # @!attribute [r] body - # @return [Hash, nil] the request payload - # @!attribute [r] headers - # @return [Hash{String => String}] the request headers, names downcased. - # The +From+ scope has a member of its own below. - # @!attribute [r] on_behalf_of - # @return [String, nil] the +From+ scope in effect - Request = Data.define(:verb, :path, :query, :body, :headers, :on_behalf_of) - - # A client that talks to this stand-in instead of to a Zammad. - # - # @return [Client] - attr_reader :client - - # @param options [Hash] any option accepted by {Config}; the defaults are - # enough for a client that never opens a connection - def initialize(**options) - defaults = { url: 'https://zammad.test/', http_token: 'test-token', retries: 0 } - @stubs = {} - @requests = [] - @monitor = Mutex.new - @client = Client.new(**Config.merge_options(defaults, options), middleware: ->(faraday) { faraday.adapter(Adapter, self) }) - end - - # @return [Config] the configuration the stand-in client reports - def config = client.config - - # Declares the response for one endpoint. - # - # Stubbing the same method and path again queues a second response: the - # first request gets the first, and the last one answers every request - # after it. A +query+ matches when every parameter it names is present in - # the request with that value, so a stub does not have to repeat the - # +expand+, +page+ and +per_page+ parameters the client adds itself. - # - # A list read asks for pages until one is short or empty. A stub whose - # +query+ names no +page+ answers the first page, and every page after it - # with an empty list. - # - # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ - # @param path [String] path relative to the instance URL, leading slash - # optional - # @param status [Integer] HTTP status to answer with - # @param body [Hash, Array, String, nil] a Hash or Array is served as JSON, - # anything else as it is - # @param headers [Hash] response headers; a Hash or Array body is given - # +content-type: application/json+ unless this says otherwise - # @param query [Hash, nil] only answer requests carrying these parameters - # @return [self] - def stub(method, path, status: 200, body: nil, headers: {}, query: nil) - headers = headers.to_h { |name, value| [name.to_s.downcase, value.to_s] } - headers = { 'content-type' => 'application/json' }.merge(headers) if body.is_a?(Hash) || body.is_a?(Array) - body = body.is_a?(Hash) || body.is_a?(Array) ? JSON.generate(body) : body.to_s - - @monitor.synchronize do - (@stubs[key(method, path)] ||= []) << { status: status, body: body, headers: headers.freeze, query: query && stringify(query) } - end - self - end - - # Every request the code under test made, oldest first. - # - # @return [Array] - def requests = @monitor.synchronize { @requests.dup.freeze } - - # Forgets the stubs and the recorded requests. - # - # @return [self] - def reset - @monitor.synchronize do - @stubs.clear - @requests.clear - end - self - end - - # @return [Array] one +"GET api/v1/groups"+ per stubbed endpoint - def stubbed = @monitor.synchronize { stubbed_endpoints } - - def inspect = @monitor.synchronize { "#<#{self.class.name} stubbed=#{@stubs.size} requests=#{@requests.size}>" } - - # Answers a request from the stubs, recording it first. Called by the - # {Adapter} rather than by a test. - # - # @api private - # @param env [Faraday::Env] - # @return [Hash] the stub that answers - # @raise [UnstubbedRequestError] when no stub matches - def answer(env) - path = env.url.to_s.delete_prefix(config.url).sub(/\?.*/m, '') - headers = env.request_headers.to_h { |name, value| [name.downcase, value] } - json = headers['content-type'].to_s.include?('json') && env.request_body - request = Request.new( - verb: env.method, - path: path, - query: Faraday::Utils.parse_nested_query(env.url.query) || {}, - body: DeepCopy.frozen_copy(json ? JSON.parse(env.request_body, symbolize_names: true) : env.request_body), - headers: headers, - on_behalf_of: headers['from'] - ) - - stub = @monitor.synchronize do - @requests << request - take(request.verb, path, request.query) - end - stub || raise(UnstubbedRequestError, unstubbed_message(request)) - end - - private - - def key(method, path) = [method.to_sym, ::ZammadAPI::Transport.relative_path(path)] - - def stringify(value) - case value - when Hash then value.to_h { |name, nested| [name.to_s, stringify(nested)] } - when Array then value.map { stringify(it) } - else value.to_s - end - end - - # What a later page is answered with where the stub names no page. - EMPTY_PAGE = { status: 200, body: '[]', headers: { 'content-type' => 'application/json' }.freeze, query: nil }.freeze - private_constant :EMPTY_PAGE - - # The first stub of the endpoint whose query matches, spent unless it is - # the last that does. A later page, where that stub names no page, is an - # empty list and spends nothing. - def take(method, path, params) - queued = @stubs[key(method, path)] || [] - matching = queued.each_index.select { |index| matches?(queued.fetch(index)[:query], params) } - return nil if matching.empty? - - stub = queued.fetch(matching.first) - - return EMPTY_PAGE if !['1', nil].include?(params['page']) && !stub[:query]&.key?('page') - - queued.delete_at(matching.first) if matching.size > 1 - stub - end - - def matches?(expected, params) = expected.nil? || expected.all? { |name, value| params[name] == value } - - def stubbed_endpoints = @stubs.keys.map { |method, path| "#{method.to_s.upcase} #{path}" } - - def unstubbed_message(request) - stubbed = @monitor.synchronize { stubbed_endpoints } - - "#{request.verb.to_s.upcase} #{request.path} with query #{request.query.inspect} was not stubbed on this " \ - "#{self.class.name} (#{stubbed.empty? ? 'nothing is stubbed' : "stubbed: #{stubbed.join(', ')}"})" - end - - # The Faraday adapter a {Test} client sends through. - # - # @api private - class Adapter < Faraday::Adapter - def initialize(app, test) - super(app) - @test = test - end - - def call(env) - super - stub = @test.answer(env) - save_response(env, stub[:status], stub[:body], stub[:headers]) - end - end - end -end diff --git a/sig/vendor/faraday.rbs b/sig/vendor/faraday.rbs index 8f920bf..9db943e 100644 --- a/sig/vendor/faraday.rbs +++ b/sig/vendor/faraday.rbs @@ -47,15 +47,5 @@ module Faraday def use: (untyped, *untyped) -> void end - class Adapter - def initialize: (?untyped app, ?untyped opts) -> void - def call: (untyped env) -> untyped - def save_response: (untyped env, Integer status, untyped body, ?untyped headers) -> untyped - end - - module Utils - def self.parse_nested_query: (String? query) -> Hash[String, untyped]? - end - def self.new: (**untyped) ?{ (Connection) -> void } -> Connection end diff --git a/sig/vendor/internal.rbs b/sig/vendor/internal.rbs index 9e9eeeb..620fdc7 100644 --- a/sig/vendor/internal.rbs +++ b/sig/vendor/internal.rbs @@ -11,15 +11,4 @@ module ZammadAPI class ResourceProxy[R < Resources::Base] extend Forwardable end - - # The test kit's adapter names a Faraday class, which the published - # signatures must not. - class Test - class Adapter < Faraday::Adapter - @test: Test - - def initialize: (untyped app, Test test) -> void - def call: (untyped env) -> untyped - end - end end diff --git a/sig/zammad_api/test.rbs b/sig/zammad_api/test.rbs deleted file mode 100644 index a3a05d2..0000000 --- a/sig/zammad_api/test.rbs +++ /dev/null @@ -1,48 +0,0 @@ -module ZammadAPI - class Test - # Deliberately outside ZammadAPI::Error: it says the test is wrong, not - # that Zammad refused anything. - class UnstubbedRequestError < ::StandardError - end - - class Request < ::Data - attr_reader verb: Symbol - attr_reader path: String - attr_reader query: Hash[String, untyped] - attr_reader body: untyped - attr_reader headers: Hash[String, String] - attr_reader on_behalf_of: String? - - def self.new: (**untyped) -> instance - end - - attr_reader client: Client - - def config: () -> Config - - @stubs: Hash[[Symbol, String], Array[Hash[Symbol, untyped]]] - @requests: Array[Request] - @monitor: Thread::Mutex - - def initialize: (**untyped options) -> void - def stub: (Symbol method, String path, ?status: Integer, ?body: untyped, ?headers: Hash[untyped, untyped], ?query: Hash[untyped, untyped]?) -> self - def requests: () -> Array[Request] - def reset: () -> self - def stubbed: () -> Array[String] - def inspect: () -> String - - def answer: (untyped env) -> Hash[Symbol, untyped] - - private - - # private_constant in the source; RBS has no way to say so. - EMPTY_PAGE: Hash[Symbol, untyped] - - def key: (Symbol method, String path) -> [Symbol, String] - def stringify: (untyped value) -> untyped - def take: (Symbol method, String path, Hash[String, untyped] params) -> Hash[Symbol, untyped]? - def matches?: (Hash[String, untyped]? expected, Hash[String, untyped] params) -> bool - def stubbed_endpoints: () -> Array[String] - def unstubbed_message: (Request request) -> String - end -end diff --git a/spec/unit/zammad_api/test_spec.rb b/spec/unit/zammad_api/test_spec.rb deleted file mode 100644 index 47eec15..0000000 --- a/spec/unit/zammad_api/test_spec.rb +++ /dev/null @@ -1,436 +0,0 @@ -# frozen_string_literal: true - -require 'zammad_api/test' - -RSpec.describe ZammadAPI::Test do - subject(:zammad) { described_class.new } - - let(:client) { zammad.client } - - describe '#client' do - it 'is a real client' do - expect(client).to be_a(ZammadAPI::Client) - end - - it 'opens no connection at all' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - client.groups.find(1) - - expect(a_request(:any, //)).not_to have_been_made - end - - it 'reports the stand-in configuration' do - expect(client.config.url).to eq('https://zammad.test/') - end - - # The stand-in carries a token of its own, so credentials handed to it - # replace that one rather than being refused as a second scheme. - it 'accepts credentials of another kind in place of its own token' do - zammad = described_class.new(user: 'u', password: 'p') - expect(zammad.client.config.authentication_scheme).to eq(:basic) - end - - it 'accepts configuration overrides' do - expect(described_class.new(url: 'https://other.test/').client.config.url).to eq('https://other.test/') - end - - describe 'a client derived with #with' do - it 'still answers from the stand-in instead of opening a connection' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Support' }) - - expect(zammad.client.with(timeout: 5).groups.find(1).name).to eq('Support') - expect(a_request(:any, //)).not_to have_been_made - end - - it 'reports the derived option' do - expect(zammad.client.with(timeout: 5).config.timeout).to eq(5) - end - - it 'keeps an on_behalf_of scope' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - zammad.client.on_behalf_of('agent@example.com').with(timeout: 5).groups.find(1) - - expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') - end - - it 'keeps the derived options under an on_behalf_of scope taken afterwards' do - expect(zammad.client.with(timeout: 5).on_behalf_of('agent@example.com').config.timeout).to eq(5) - end - end - end - - describe '#stub' do - it 'answers a find with a record' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) - - expect(client.groups.find(1).name).to eq('Users') - end - - it 'answers a collection with every page' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }], query: { page: 1 }) - zammad.stub(:get, 'api/v1/groups', body: [], query: { page: 2 }) - - expect(client.groups.pluck(:name)).to eq(%w[Users Support]) - end - - it 'ignores a leading slash on the stub' do - zammad.stub(:get, '/api/v1/groups/1', body: { id: 1 }) - - expect(client.groups.find(1).id).to eq(1) - end - - # The real transport refuses this, so a stand-in that answered it would - # let a test pass over a request production never sends. - it 'refuses an absolute URL the way the real transport does' do - expect { client.get('https://other.example/collect') } - .to raise_error(ArgumentError, /a request path is relative to the instance URL/) - end - - it 'raises the mapped error class for a non-2xx status' do - zammad.stub(:get, 'api/v1/groups/1', status: 404, body: { error: 'not found' }) - - expect { client.groups.find(1) }.to raise_error(ZammadAPI::NotFoundError, /not found/) - end - - it 'raises a rate limit with the wait Zammad asked for' do - zammad.stub(:get, 'api/v1/groups/1', status: 429, headers: { 'Retry-After' => '30' }) - - expect { client.groups.find(1) }.to raise_error(ZammadAPI::RateLimitError) { expect(it.retry_after).to eq(30) } - end - - it 'serves a non-JSON body untouched, e.g. an attachment' do - zammad.stub(:get, 'api/v1/ticket_attachment/1/2/3', body: 'binary-ish') - - attachment = ZammadAPI::Resources::TicketArticleAttachment - .new(zammad.client.instance_variable_get(:@transport), id: 3, ticket_id: 1, article_id: 2) - - expect(attachment.download).to eq('binary-ish') - end - - it 'returns itself, so stubs can be chained' do - expect(zammad.stub(:get, 'api/v1/groups', body: [])).to be(zammad) - end - - it 'exposes response headers' do - zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => '7' }) - - expect(client.get('api/v1/groups').headers['x-total-count']).to eq('7') - end - - it 'serves a JSON body with the content-type a real response carries' do - zammad.stub(:get, 'api/v1/groups', body: []) - - expect(client.get('api/v1/groups').headers['content-type']).to eq('application/json') - end - - it 'lets a test say the endpoint answered with something else' do - zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'Content-Type' => 'application/json; charset=utf-8' }) - - expect(client.get('api/v1/groups').headers['content-type']).to eq('application/json; charset=utf-8') - end - - context 'when a stub declares a type that is not JSON' do - before { zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }, headers: { 'Content-Type' => 'text/html' }) } - - it 'hands back the raw body Zammad would have sent' do - expect(client.get('api/v1/groups/1').body).to eq('{"id":1}') - end - end - - it 'carries a header value as the String the wire would have sent' do - zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => 7 }) - - expect(client.get('api/v1/groups').headers['x-total-count']).to eq('7') - end - - it 'decodes a string body a stub declares as JSON' do - zammad.stub(:get, 'api/v1/groups/1', body: '{"id":1,"name":"Users"}', headers: { 'Content-Type' => 'application/json' }) - - expect(client.groups.find(1).name).to eq('Users') - end - - it 'claims no content-type for a body it does not serve as JSON' do - zammad.stub(:get, 'api/v1/groups/1/avatar', body: 'binary') - - expect(client.get('api/v1/groups/1/avatar').headers).not_to have_key('content-type') - end - - it 'hands out headers a caller cannot write through' do - zammad.stub(:get, 'api/v1/groups', body: [], headers: { 'X-Total-Count' => '7' }) - - expect { client.get('api/v1/groups').headers['x-total-count'] = '999' }.to raise_error(FrozenError) - end - - describe 'a sequence' do - it 'serves stubs in the order they were declared' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'First' }) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) - - expect(client.groups.find(1).name).to eq('First') - expect(client.groups.find(1).name).to eq('Second') - end - - it 'keeps answering with the last one' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'First' }) - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Second' }) - - 3.times { client.groups.find(1) } - expect(client.groups.find(1).name).to eq('Second') - end - end - - describe 'query matching' do - it 'matches a stub that names a subset of the parameters' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) - - expect(client.groups.order(:name).first.id).to eq(1) - end - - it 'does not answer a request without those parameters' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) - - expect { client.groups.all.to_a }.to raise_error(described_class::UnstubbedRequestError) - end - - it 'matches an array-valued parameter' do - zammad.stub(:get, 'api/v1/users/search', body: [{ id: 1 }], query: { ids: [1, 2], page: 1 }) - zammad.stub(:get, 'api/v1/users/search', body: [], query: { ids: [1, 2], page: 2 }) - - expect(client.users.search('x', ids: [1, 2]).map(&:id)).to eq([1]) - end - - it 'answers a search count from a stub for the request for the total' do - zammad.stub(:get, 'api/v1/groups/search', body: { total_count: 42 }, query: { only_total_count: true }) - - expect(client.groups.search('x').count).to eq(42) - expect(zammad.requests.size).to eq(1) - end - - it 'sequences two stubs that share a scope' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) - zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }], query: { sort_by: 'name' }) - - expect(Array.new(3) { client.groups.all.order(:name).page(1, per_page: 1).map(&:id) }).to eq([[1], [2], [2]]) - end - - it 'spends the first matching stub where a later one matches too' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { sort_by: 'name' }) - zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }]) - - expect(Array.new(3) { client.get('api/v1/groups', query: { sort_by: 'name' }).body }).to eq([[{ id: 1 }], [{ id: 2 }], [{ id: 2 }]]) - end - end - end - - describe 'an unstubbed request' do - it 'names the request that was not stubbed' do - expect { client.groups.find(1) } - .to raise_error(described_class::UnstubbedRequestError, 'GET api/v1/groups/1 with query {"expand" => "true"} was not stubbed on this ZammadAPI::Test (nothing is stubbed)') - end - - it 'lists what is stubbed, because a wrong path is the usual cause' do - zammad.stub(:get, 'api/v1/groups/2', body: { id: 2 }) - - expect { client.groups.find(1) }.to raise_error(%r{stubbed: GET api/v1/groups/2}) - end - - it 'is outside ZammadAPI::Error, so code under test cannot rescue it as an API failure' do - expect(described_class::UnstubbedRequestError.ancestors).not_to include(ZammadAPI::Error) - expect(described_class::UnstubbedRequestError.ancestors).to include(StandardError) - end - end - - describe '#requests' do - before do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1, name: 'Users' }) - zammad.stub(:put, 'api/v1/groups/1', body: { id: 1, name: 'Renamed' }) - end - - it 'records the verb and path' do - client.groups.find(1) - - expect(zammad.requests.last.verb).to eq(:get) - expect(zammad.requests.last.path).to eq('api/v1/groups/1') - end - - it 'records only what a save actually sends' do - client.groups.find(1).update!(name: 'Renamed') - - expect(zammad.requests.last.body).to eq({ name: 'Renamed' }) - end - - it 'records the body as it was sent, not as the test left it afterwards' do - zammad.stub(:post, 'api/v1/groups', body: { id: 2 }) - payload = { name: 'Support', note: { internal: 'yes' } } - client.post('api/v1/groups', body: payload) - - payload[:name] = 'Mutated' - payload[:note][:internal] = 'no' - - expect(zammad.requests.last.body).to eq({ name: 'Support', note: { internal: 'yes' } }) - end - - it 'records the query parameters the client sent' do - client.groups.find(1) - - expect(zammad.requests.last.query).to eq({ 'expand' => 'true' }) - end - - it 'records them stringified, the way the transport sends them' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }]) - client.groups.all.page(2, per_page: 50).to_a - - expect(zammad.requests.last.query) - .to eq({ 'expand' => 'true', 'page' => '2', 'per_page' => '50' }) - end - - it 'records a nested query stringified throughout' do - zammad.stub(:get, 'api/v1/roles', body: []) - client.get('api/v1/roles', query: { ids: [1, 2], filter: { active: true } }) - - expect(zammad.requests.last.query).to eq('ids' => %w[1 2], 'filter' => { 'active' => 'true' }) - end - - it 'records requests oldest first' do - client.groups.find(1).update!(name: 'Renamed') - - expect(zammad.requests.map(&:verb)).to eq(%i[get put]) - end - - it 'records an on_behalf_of scope' do - client.on_behalf_of('agent@example.com').groups.find(1) - - expect(zammad.requests.last.on_behalf_of).to eq('agent@example.com') - end - - it 'leaves on_behalf_of nil for an unscoped client' do - client.groups.find(1) - - expect(zammad.requests.last.on_behalf_of).to be_nil - end - - it 'records the headers a raw request asked for' do - zammad.stub(:get, 'api/v1/roles', body: []) - client.get('api/v1/roles', headers: { 'Accept-Language' => 'de-de' }) - - expect(zammad.requests.last.headers).to include('accept-language' => 'de-de') - end - - it 'records a header value the way the wire would carry it' do - zammad.stub(:get, 'api/v1/roles', body: []) - client.get('api/v1/roles', headers: { 'X-Retry' => 3 }) - - expect(zammad.requests.last.headers).to include('x-retry' => '3') - end - - it 'records the headers the client sends by itself' do - client.groups.find(1) - - expect(zammad.requests.last.headers).to include('accept' => 'application/json', 'authorization' => 'Token test-token') - end - - it 'records a request that was not stubbed, so the failure can be inspected' do - expect { client.groups.find(2) }.to raise_error(described_class::UnstubbedRequestError) - expect(zammad.requests.map(&:path)).to eq(['api/v1/groups/2']) - end - - it 'hands out a frozen list' do - expect { zammad.requests << :nonsense }.to raise_error(FrozenError) - end - - it 'is recorded from several threads without losing any' do - threads = Array.new(4) { Thread.new { 5.times { client.groups.find(1) } } } - threads.each(&:join) - - expect(zammad.requests.size).to eq(20) - end - end - - describe '#reset' do - it 'forgets the stubs' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - zammad.reset - - expect { client.groups.find(1) }.to raise_error(described_class::UnstubbedRequestError) - end - - it 'forgets the recorded requests' do - zammad.stub(:get, 'api/v1/groups/1', body: { id: 1 }) - client.groups.find(1) - - expect(zammad.reset.requests).to be_empty - end - end - - describe '#inspect' do - it 'reports the stubs and the requests' do - zammad.stub(:get, 'api/v1/groups', body: []) - client.groups.all.to_a - - expect(zammad.inspect).to eq('#') - end - - it 'reads the recorded requests under the monitor' do - zammad.stub(:get, 'api/v1/groups', body: []) - writers = Array.new(4) { Thread.new { 25.times { client.groups.all.to_a } } } - readers = Array.new(4) { Thread.new { 25.times { zammad.inspect } } } - - expect { (writers + readers).each(&:join) }.not_to raise_error - expect(zammad.requests.size).to eq(100) - end - end - - describe 'a list endpoint stubbed once' do - subject(:zammad) { described_class.new } - - let(:client) { zammad.client } - - before { zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: 'a' }, { id: 2, name: 'b' }]) } - - it 'reads the whole collection without a second stub' do - expect(client.groups.all.map(&:id)).to eq([1, 2]) - end - - it 'answers a later page as an endpoint out of records would' do - expect(client.groups.all.page(2).map(&:id)).to eq([]) - end - end - - describe 'a list endpoint stubbed as a sequence' do - subject(:zammad) { described_class.new } - - let(:client) { zammad.client } - - def names = client.groups.all.map(&:name) - - before do - %w[A B C].each { zammad.stub(:get, 'api/v1/groups', body: [{ id: 1, name: it }]) } - end - - it 'answers each read with the next stub' do - expect(Array.new(3) { names }).to eq([['A'], ['B'], ['C']]) - end - - it 'spends one stub on a read, however many pages the read asks for' do - expect(client.groups.find_each(batch_size: 1).map(&:name)).to eq(['A']) - expect(zammad.requests.map { it.query['page'] }).to eq(%w[1 2]) - expect(names).to eq(['B']) - end - end - - describe 'a list endpoint whose pages are stubbed by hand' do - subject(:zammad) { described_class.new } - - let(:client) { zammad.client } - - # A stub that names a page is left exactly as written - that is how a test - # says what the second page holds. - it 'serves each page as declared' do - zammad.stub(:get, 'api/v1/groups', body: [{ id: 1 }], query: { page: 1 }) - zammad.stub(:get, 'api/v1/groups', body: [{ id: 2 }], query: { page: 2 }) - zammad.stub(:get, 'api/v1/groups', body: [], query: { page: 3 }) - - expect(client.groups.find_each(batch_size: 1).map(&:id)).to eq([1, 2]) - end - end -end From be1dc69c789a00b4abae117708a513974a9572e0 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 16:35:58 +0200 Subject: [PATCH 102/121] Docs: make the README readable from the top Add a quick start, put records and collections before the endpoints the gem does not model, and say each thing once. The 1.x migration guide moves to UPGRADING.md, which the gem ships, and the contributor notes move to CONTRIBUTING.md. Corrects what no longer matched the code: timeouts are not checked for being positive, with does not re-validate every option, the page-size comparison with 1.x, and ResponseError#response. --- CHANGELOG.md | 2 +- CONTRIBUTING.md | 47 ++ README.md | 1168 +++++++++++++------------------------------- UPGRADING.md | 153 ++++++ zammad_api.gemspec | 5 +- 5 files changed, 548 insertions(+), 827 deletions(-) create mode 100644 CONTRIBUTING.md create mode 100644 UPGRADING.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e951bd..dd440bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## [2.0.0.alpha1] - 2026-11-17 The first prerelease of 2.0, a breaking release that modernises the whole gem. See -[Migrating from 1.x](README.md#migrating-from-1x) for the complete before/after guide. +[UPGRADING.md](UPGRADING.md) for the complete before/after guide. Everything below is what changed since 1.4.0. It is published as an alpha so that it can still change: names, defaults and behaviour may differ in 2.0.0. A prerelease has to be diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..4f0a0d6 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,47 @@ +# Contributing + +```sh +bin/setup # bundle install, plus the overcommit git hooks +bundle exec rake # unit specs, RuboCop, Steep and the shipped signatures +``` + +| Task | What it does | +| ------------------------ | ----------------------------------------------------- | +| `rake spec:unit` | Unit specs; stubbed, no Zammad needed | +| `rake spec:integration` | Integration specs against a live Zammad | +| `rake spec` | Both; needs `TEST_URL`, like the integration specs | +| `rake check_connection` | Drives a live Zammad end to end and prints a transcript | +| `rake rubocop` | Style checks | +| `rake steep` | Type-check `lib/` against `sig/`, and `spec/typed/` the way a caller is checked | +| `rake rbs_published` | Validate the signatures the gem ships, without `sig/vendor/` | + +Set `COVERAGE=true` to produce a coverage report in `coverage/`. + +## Testing against a live Zammad + +The integration specs and `check_connection` need a reachable Zammad instance and **will +create and delete records**, so they run only where `TEST_URL` names one, and there is no +default: point it at something disposable. Without it, `rspec` runs the unit specs and +says the integration specs were left out, `rspec spec/integration` fails for having +nothing to run, and `rake spec:integration`, `rake spec` and `rake check_connection` stop +before running anything. + +```sh +export TEST_URL=https://zammad.example/ # a disposable Zammad, never one you keep data in +export TEST_USER=admin@example.com +export TEST_PASSWORD=test + +bundle exec rake check_connection # one linear pass, readable transcript +bundle exec rake spec:integration # the full spec suite +``` + +`check_connection` walks the documented workflows in order — create, find, update, reload, +pattern match, paginate, search, ticket with articles, attachment download, acting on +behalf of a user, and each error class — printing `ok` or `FAIL` per step and cleaning up +after itself. It stops early if a precondition fails, so a broken instance produces one +clear line rather than a cascade. + +CI runs both against a Zammad booted from source: the `integration` job clones Zammad, +starts it, waits for it to answer, runs `check_connection` as a fast preflight, then runs +the integration specs. Trigger it by hand from the Actions tab (`workflow_dispatch`) to +test against a specific Zammad ref. diff --git a/README.md b/README.md index 569564c..a98f2a5 100644 --- a/README.md +++ b/README.md @@ -3,51 +3,23 @@ [![Gem Version](https://badge.fury.io/rb/zammad_api.svg)](https://badge.fury.io/rb/zammad_api) [![CI](https://github.com/zammad/zammad-api-client-ruby/actions/workflows/ci.yml/badge.svg)](https://github.com/zammad/zammad-api-client-ruby/actions/workflows/ci.yml) ---- - > [!IMPORTANT] -> ## 📣 2.0 is taking shape — tell us what you think -> -> **Version 2.0 is a breaking release, and it is not finished yet: this is `2.0.0.alpha1`, -> its first prerelease.** This is the moment when your feedback can still change it: names, -> defaults, what is missing, what reads wrong, and anything that makes upgrading from 1.x -> harder than it should be. -> -> **[→ Open an issue and tell us](https://github.com/zammad/zammad-api-client-ruby/issues/new)** -> -> Especially useful to hear: -> -> - Which 1.x calls in **your** code the [migration table](#migrating-from-1x) does not cover. -> - Endpoints you reach with [raw requests](#raw-requests) that should be modelled resources. -> - Naming that made you look twice, and defaults you had to override every time. -> -> Rough notes are welcome — a half-formed "this felt off" is worth more to us now than a -> polished report after the release. - ---- +> `2.0.0.alpha1` is the first prerelease of a breaking 2.0. Names and defaults can still +> change: [open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) with +> anything that reads wrong, is missing, or makes upgrading hard. Rough notes are welcome. +> On 1.x? See [UPGRADING.md](UPGRADING.md), which also says how to stay on 1.x. Ruby client for the Zammad API v1.0. -- Requires **Ruby 3.4** or later. -- Ships **RBS signatures** in `sig/`, so typed projects get completion and checking out of the box. -- Requests carry **timeouts** and **retry with backoff** for transient failures by default. -- Collections are **lazily paginated** `Enumerable`s, with a familiar - `order` / `page` / `in_batches` / `find_each` surface. -- Records support **pattern matching**, and clients are **immutable** and safe to share - between threads. -- **Your own resources** — `client.resource(Role)` gives a class you declare everything a - modelled one has — and **raw requests** reach the rest of the API, without giving up - authentication, retries or the error classes. - -> **Upgrading from 1.x?** See [Migrating from 1.x](#migrating-from-1x), which lists every -> call that changed. -> -> **Staying on 1.x?** See [Staying on 1.x](#staying-on-1x) for where its code lives and how -> to install it. +- Tickets, articles, attachments, users, organizations, groups, ticket states and + priorities as records you `find`, `create`, `update` and `destroy`. +- Collections that paginate themselves: `each`, `first`, `search`, `find_each`. +- Timeouts, and retries for `GET`, on by default, and one error class per kind of failure. +- Any other endpoint through a resource you declare or a raw request. ## Installation -2.0 is a prerelease for now, `2.0.0.alpha1`, and a prerelease has to be asked for: +Requires Ruby 3.4 or later. 2.0 is a prerelease, and a prerelease has to be asked for: ```ruby gem 'zammad_api', '~> 2.0.0.alpha' @@ -59,37 +31,44 @@ Or: gem install zammad_api --pre ``` -`'~> 2.0'` does not match an alpha, and `gem install zammad_api` without `--pre` installs -1.x. +## Quick start -### Staying on 1.x +```ruby +require 'zammad_api' -1.x stays available for a project that is not ready for 2.0, or that runs on a Ruby older -than 3.4: 1.x needs Ruby 3.0 or later. +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'your-access-token' +) -Its code lives on the -[`1-stable`](https://github.com/zammad/zammad-api-client-ruby/tree/1-stable) branch, and -the [README there](https://github.com/zammad/zammad-api-client-ruby/blob/1-stable/README.md) -documents the 1.x API. To install it, keep the version below 2: +client.tickets.first(5).each { |ticket| puts ticket.title } -```ruby -gem 'zammad_api', '~> 1.4' -``` +ticket = client.tickets.create( + title: 'Cannot log in', + group: 'Users', + customer: 'nicole.braun@zammad.org', + article: {subject: 'Cannot log in', body: 'My password stopped working.', type: 'note'} +) -Or: +ticket.add_article(body: 'Reset link sent.', type: 'note') +ticket.update(state: 'closed') -```sh -gem install zammad_api -v '~> 1.4' +client.tickets.search('state.name:open').each { |open_ticket| puts open_ticket.number } + +begin + client.tickets.find(123_456) +rescue ZammadAPI::NotFoundError => e + warn e.server_message +end ``` -1.x is in maintenance mode, and will stay there for the foreseeable future: it still gets -fixes, while new features go into 2.0 only. Report a 1.x problem in the same -[issue tracker](https://github.com/zammad/zammad-api-client-ruby/issues), naming the -version, and open a pull request for it against `1-stable`. +The sections below cover [creating a client](#creating-a-client), +[records](#working-with-records), [collections](#collections) and +[error handling](#error-handling). Runnable scripts live in [`examples/`](examples/README.md). ## Creating a client -### Access token +### Authentication ```ruby client = ZammadAPI::Client.new( @@ -98,36 +77,13 @@ client = ZammadAPI::Client.new( ) ``` -### OAuth2 - -```ruby -client = ZammadAPI::Client.new( - url: 'https://zammad.example.com/', - oauth2_token: 'your-oauth2-token' -) -``` - -### Username and password - -```ruby -client = ZammadAPI::Client.new( - url: 'https://zammad.example.com/', - user: 'user@example.com', - password: 'some_pass' -) -``` - -A client authenticates one way. Passing more than one of these — a token beside a user and -password, say — raises `ZammadAPI::ConfigurationError` rather than quietly sending one of -them. +Or pass `oauth2_token:`, or `user:` and `password:`. Pass one kind of credentials: more +than one raises `ZammadAPI::ConfigurationError`. ### From the environment -`from_env` reads `ZAMMAD_URL` and `ZAMMAD_TOKEN` (or `ZAMMAD_OAUTH2_TOKEN`, or -`ZAMMAD_USER` and `ZAMMAD_PASSWORD`), so a script needs no -configuration of its own. A variable that is empty or blank counts as unset. Anything -passed in wins over the environment, and credentials passed in replace the ones the -environment holds: +`from_env` reads `ZAMMAD_URL` and one of `ZAMMAD_TOKEN`, `ZAMMAD_OAUTH2_TOKEN`, or +`ZAMMAD_USER` with `ZAMMAD_PASSWORD`. Options passed to it override the environment: ```ruby client = ZammadAPI::Client.from_env @@ -143,248 +99,74 @@ client = ZammadAPI::Client.from_env(timeout: 300) | `oauth2_token` | `nil` | OAuth2 bearer token. | | `user` | `nil` | Login for basic authentication. | | `password` | `nil` | Password for basic authentication. | -| `timeout` | `60` | Seconds to wait for a response. A positive number. | -| `open_timeout` | `10` | Seconds to wait for the connection. A positive number. | +| `timeout` | `60` | Seconds to wait for a response. | +| `open_timeout` | `10` | Seconds to wait for the connection. | | `retries` | `2` | Retry attempts for a `GET` that failed transiently. `0` disables retrying. | -| `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt, up to `timeout`. Up to half of it is added to each wait as jitter. | +| `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt. | | `ssl_verify` | `true` | Set to `false` only against a server with a self-signed certificate. | | `proxy` | `nil` | Proxy URL. | | `user_agent` | `zammad_api-ruby/` | Value of the `User-Agent` header. | -| `logger` | discards output | Any `Logger`; the client logs requests and responses at `debug`. | -| `adapter` | Faraday's default | Name of a Faraday adapter, such as `:net_http_persistent`. | -| `middleware` | `nil` | Callable that is handed the Faraday connection while it is built, after this gem's own middleware and the adapter. | +| `logger` | discards output | Any `Logger`; see [Logging](#logging). | +| `adapter` | Faraday's default | Name of a Faraday adapter; see [Adapter and middleware](#adapter-and-middleware). | +| `middleware` | `nil` | Callable that is handed the Faraday connection while it is built. | -Credentials are never written to the log, and `client.config` redacts them however it is -printed — `inspect`, `to_s` or `pp`, which is what a console shows. +Credentials are never logged, and `client.config` redacts them when printed. -Credentials belong in the options above, not in the URL: `https://user:secret@host/` -raises `ZammadAPI::ConfigurationError`. +### Changing options -### Checking the connection +A client is immutable. `with` returns a new one with some options changed, carrying over +any `on_behalf_of` scope: ```ruby -client.me.email # => "agent@example.com", the account the credentials belong to -client.version # => "6.4.0", the Zammad instance's version, for an administrator +bulk = client.with(timeout: 300, retries: 5) +bulk.tickets.each { |ticket| archive(ticket) } ``` -`client.me` answers for any account, so it is the check that the client can reach Zammad -and authenticate. `client.version` is the version of the Zammad instance, and Zammad serves -it to administrators only: with an agent's or a customer's credentials it raises -`ZammadAPI::AuthorizationError`. `ZammadAPI::VERSION` is the version of this gem. - -### Adapter and middleware - -The HTTP stack is Faraday's, and these two options are the seam into it — for a -persistent-connection adapter, instrumentation, or a cache: - -```ruby -client = ZammadAPI::Client.new( - url: 'https://zammad.example.com/', - http_token: 'token', - adapter: :net_http_persistent, - middleware: ->(connection) { connection.use(MyInstrumentation) } -) -``` +Naming credentials replaces the ones the client has, whichever kind they were. Because +clients are immutable, one client and anything derived from it can be shared between +threads. -The adapter is set first, and the callable runs after it, behind this gem's own -middleware, so it sees requests as the client finished building them and responses before -the client does. An adapter that needs arguments is set inside the callable, and takes the -place of one named with `adapter:`: +### Checking the connection ```ruby -client = ZammadAPI::Client.new( - url: 'https://zammad.example.com/', - http_token: 'token', - middleware: ->(connection) { connection.adapter :net_http_persistent, pool_size: 5 } -) +client.me.email # => "agent@example.com", the account the credentials belong to +client.version # => "6.4.0", the Zammad instance's version, for an administrator ``` -A Faraday error while the connection is built, such as an adapter that is not registered, -raises `ZammadAPI::ConfigurationError`. This gem decodes JSON and maps error statuses -itself, so leave out middleware that does either, such as `response :json` or -`response :raise_error`. - -Faraday's default adapter, `net_http`, opens and closes a connection around every -request, so a walk of N pages is N TCP connections and N TLS handshakes. For anything that -pages, downloads attachments in a loop, or runs a worker pool, add -`faraday-net_http_persistent` to your Gemfile and pass `adapter: :net_http_persistent` as -above. +`client.me` works for any account, so use it to check that the client can reach Zammad and +authenticate. Zammad serves `client.version` to administrators only: with an agent's or a +customer's credentials it raises `ZammadAPI::AuthorizationError`. `ZammadAPI::VERSION` is +the version of this gem. -## Available resources +## Resources `groups`, `organizations`, `tickets`, `ticket_articles`, `ticket_priorities`, `ticket_states`, `users` -`client.resource_names` returns the current list. - -The names are plural because what each one hands back stands for every record of its kind: -`client.tickets.each` walks them all, and `client.tickets.find(1)` picks one out. The -singular names from 1.x — `client.ticket` and the rest — are gone and raise -`UnknownResourceError`; see [Migrating from 1.x](#the-client). - -Anything not in that list is reachable by [declaring a resource](#resources-this-gem-does-not-model) -for it, or with [raw requests](#raw-requests). - -### Coverage - -What each major version of this gem models, set against what Zammad's API serves. A check -is a class or a method of the gem's own; an empty box is something 2.0 does not model yet. - -| | 1.x | 2.0 | -| ------------------------------------------------ | :-: | :-: | -| **Records** | | | -| Tickets | ✅ | ✅ | -| Ticket articles | ✅ | ✅ | -| Article attachments | ✅ | ✅ | -| Ticket states | ✅ | ✅ | -| Ticket priorities | ✅ | ✅ | -| Users | ✅ | ✅ | -| Organizations | ✅ | ✅ | -| Groups | ✅ | ✅ | -| Text modules | | ⬜ | -| **Ticket features** | | | -| Tags | | ⬜ | -| Links | | ⬜ | -| Mentions | | ⬜ | -| Time accounting | | ⬜ | -| Checklists | | ⬜ | -| Shared drafts | | ⬜ | -| Merge | | ⬜ | -| History | | ⬜ | -| **Knowledge base** | | | -| Knowledge bases | | ⬜ | -| Categories | | ⬜ | -| Answers, and publishing them | | ⬜ | -| Answer attachments | | ⬜ | -| Search | | ⬜ | -| **Across resources** | | | -| Global search | | ⬜ | -| CSV imports (users, organizations, text modules) | | ⬜ | - -An empty box in the 2.0 column is not out of reach: [declare a resource](#resources-this-gem-does-not-model) -for an endpoint that serves records, or use [raw requests](#raw-requests) for one that does -not. The empty boxes are also where this gem grows next — -[open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) for the one -you need, so we know what to model first. - -### Resources this gem does not model - -A resource is a class with a path. Declare one for an endpoint that serves records the way -the modelled ones do — an index, and a member under its id — and `client.resource` hands -you the same thing `client.tickets` is: - -```ruby -class Role < ZammadAPI::Resources::Base - path 'api/v1/roles' -end - -roles = client.resource(Role) - -roles.each { |role| puts role.name } # paginated, like any other -roles.find(2).update(note: 'Reviewed') # change tracking and save -roles.create(name: 'Auditor') -roles.find_by(name: 'Agent') -``` - -Say what else is true of the endpoint, where it differs from the defaults: - -| Declaration | Default | Says | -| ------------------ | ------- | -------------------------------------------------------------------- | -| `path '…'` | *required* | The index endpoint, relative to the instance URL. | -| `searchable true` | `false` | Zammad routes `/search`, so `search` works and `find_by` uses it. | -| `max_per_page 100` | `1000` | The largest page the index endpoint serves. A walk ends at the first page shorter than the size it asked for, so this has to be what the endpoint really serves. | -| `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. | - -A subclass of a modelled resource works too, and inherits what its parent declares: -`class MyTicket < ZammadAPI::Resources::Ticket`. - -An endpoint that serves every record in one response and ignores `page` — -`api/v1/object_manager_attributes` is one — is still read in one request, because its first -page is shorter than the 1000 records asked for: - -```ruby -class ObjectAttribute < ZammadAPI::Resources::Base - path 'api/v1/object_manager_attributes' - sortable false -end - -client.resource(ObjectAttribute).find_by(name: 'priority_id') # one request -``` - -Asked for smaller pages, with `in_batches(of: 50)`, such an endpoint answers the second page -with the first again, which a walk reports as `ZammadAPI::PaginationError`. Read it with -`client.get` instead. A search always pages and sorts, whatever the index beside it does. - -Use raw requests for an endpoint that is not shaped like that — an action, a report, a -setting. - -## Raw requests - -`get`, `post`, `put` and `delete` reach any endpoint of the Zammad API, without giving up -authentication, timeouts, retries, credential redaction, JSON decoding or the error -classes. Use them for the endpoints that are not a list of records, and for a one-off call -to one that is. - -```ruby -client.get('api/v1/roles').body -# => [{id: 1, name: "Admin", ...}, ...] - -client.post('api/v1/tags/add', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) -client.put('api/v1/roles/2', body: {note: 'Updated'}) -client.delete('api/v1/tags/remove', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) -``` - -All four take `headers:`, for an endpoint that needs one. Names and values are sent as -text: - -```ruby -client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) -``` - -A `body:` is sent as JSON, and a String body is sent as it is. A `query:` Hash is encoded -by Faraday, nested Hashes and lists included. - -Each returns a `ZammadAPI::Response`, so the status and headers stay reachable: - -```ruby -response = client.get('api/v1/tickets') -response.status # => 200 -response.headers['content-type'] -response.body # decoded JSON, or the raw body for anything else -response.raw_body # the body as it arrived -``` - -Zammad reports the size of a result in the body rather than in a header, and only where -you ask for it: `only_total_count=true` or `with_total_count=true` on a `/search` -endpoint. `count` on a search collection uses the first of those. - -Paths are relative to the instance URL, and a leading slash is ignored, so they can be -pasted straight from the Zammad documentation. A path that opens with a scheme, such as -`https://other.example/collect`, raises `ArgumentError`, so the client's credentials only -ever go to the instance it was configured for. A non-2xx response raises the same error -class it would raise for a modelled resource, and only a `GET` is retried. +`client.resource_names` returns the current list. Anything else is reachable by declaring +a resource or with raw requests; see +[Endpoints this gem does not model](#endpoints-this-gem-does-not-model). ## Working with records ### Create ```ruby -group = client.groups.new(name: 'Support', note: 'Some note') -group.save +user = client.users.new(firstname: 'Nicole', lastname: 'Braun', email: 'nicole.braun@zammad.org') +user.save -group.id # => 42 -group.name # => "Support" +user.id # => 42 +user.email # => "nicole.braun@zammad.org" ``` Or in one call: ```ruby -group = client.groups.create(name: 'Support', note: 'Some note') +user = client.users.create(firstname: 'Nicole', lastname: 'Braun', email: 'nicole.braun@zammad.org') ``` Attributes are a Hash, or anything that converts to one with `to_hash`. In a Rails -controller that is the permitted parameters, which `new`, `create`, `update`, -`assign_attributes` and `add_article` take as they are: +controller that is the permitted parameters: ```ruby client.users.create(params.require(:user).permit(:login, :email, :password)) @@ -393,120 +175,56 @@ client.users.create(params.require(:user).permit(:login, :email, :password)) ### Fetch ```ruby -group = client.groups.find(42) -group.name # => "Support" -group[:name] # same, and nil rather than an error when it is absent -group.fetch(:name) # raises KeyError if the attribute is absent -group.key?(:name) # => true -group.to_h # every attribute, as a Hash you may modify -``` - -Or by attribute value: +user = client.users.find(42) # raises NotFoundError if there is none -```ruby client.users.find_by(email: 'someone@example.com') # => the record, or nil client.users.find_by!(email: 'nobody@example.com') # raises NotFoundError -client.groups.exists?(42) # => true -``` - -`find_by` answers with the first record that carries all of those values, compared -exactly, and `nil` if it finds none. Zammad's index endpoints cannot filter — see -[Narrowing](#narrowing) — so `find_by` fetches candidates and checks them itself: - -```ruby -client.users.find_by(email: 'someone@example.com', active: true) # searches the email, checks both -client.ticket_states.find_by(name: 'open') # no search endpoint: walks the list -client.users.find_by(organization_id: 5) # no String to search on: walks the index -``` - -An `id:` is read with `find`, in one request, and `nil` if it names no record. Otherwise, -where the resource has a search endpoint and one of the values is a String, the longest -one is the search term, and the hits are read a page at a time until one carries every -value. Otherwise the index is walked until a record matches, which against every user or -ticket on an instance is a request per page. - -What a search can find is up to Zammad. With Elasticsearch the term is looked for in -everything a record is indexed with; without it, Zammad reads the string columns of a -user, organization or group, and the title, number and articles of a ticket. On such an -instance `client.tickets.find_by(state: 'open')` answers `nil` for tickets that exist, and -`find_by(...) || create(...)` can create a duplicate. Walk the index where that matters: -`client.tickets.detect { it[:state] == 'open' }`. - -Zammad records can carry administrator-defined custom attributes, so readers are resolved -against the attributes the record arrived with rather than declared ahead of time. A reader -for an attribute the record does not carry raises `NoMethodError` rather than answering -`nil`: - -```ruby -group.titel # NoMethodError: undefined method 'titel' for an instance of ... -group[:titel] # => nil -group.fetch(:titel, nil) # => nil -group.key?(:titel) # => false +client.users.exists?(42) # => true ``` -Zammad also serves a reduced object where the authenticated user may not see the whole -record, so an attribute that exists in Zammad can be missing here. Use `[]`, `fetch` with a -default, or `key?` wherever an attribute may legitimately be absent. +`find_by` returns the first record carrying all of the given values, or `nil`. It searches +where the resource has a search endpoint and one of the values is a String; otherwise it +reads the index page by page, which can take many requests on a large instance. What a +search matches is up to Zammad's search index, so where a miss must be certain, read the +index yourself: `client.tickets.detect { it[:state] == 'open' }`. -`attributes` and `changes` are deeply frozen. An attribute writer is the way to stage a -change, and `to_h` is a copy you may modify: +### Reading attributes ```ruby -group.attributes[:name] = 'Support 2' # FrozenError -group.name = 'Support 2' # the way to stage a change -group.to_h # a deep copy, yours to modify +user.email # => "nicole.braun@zammad.org" +user[:email] # the same, and nil when the attribute is absent +user.fetch(:email) # raises KeyError when the attribute is absent +user.key?(:email) # => true +user.to_h # every attribute, as a Hash you may modify ``` -### Pattern matching +A reader for an attribute the record does not carry raises `NoMethodError`, so a typo does +not read as `nil`. Use `record[:name]` or `fetch(:name, nil)` where an attribute may be +absent: custom attributes, or records the authenticated user may only partly see. -Records implement `deconstruct_keys`, so they work with `case/in`: - -```ruby -case client.tickets.find(1) -in {state: 'closed'} - nil -in {state: String => state, priority: '3 high'} - escalate(state) -in {group: 'Support'} - notify_support -end -``` - -`Config` and `Response` are `Data` objects, so their members match too: - -```ruby -case client.config -in {http_token: String} - :token_auth -in {user: String, password: String} - warn 'prefer an access token over basic auth' -end -``` +`attributes` and `changes` are frozen. Assign through a writer (`user.email = '...'`) to +stage a change. ### Update ```ruby -group = client.groups.find(42) -group.name = 'Support 2' +user = client.users.find(42) +user.firstname = 'Nicola' -group.changed? # => true -group.changes # => {name: ["Support", "Support 2"]} +user.changed? # => true +user.changes # => {firstname: ["Nicole", "Nicola"]} -group.save # sends only the changed attributes +user.save # sends only the changed attributes ``` -A `save` on a persisted record with nothing staged sends no request at all and returns -`true`. Zammad applies an empty update, bumping `updated_at` and `updated_by`, so a no-op -save would otherwise rewrite the record's audit trail. - -Writing back the value a record was loaded with is not a change, so it stages nothing. -Writing an attribute the record does not carry always is one, even when the value is `nil`. +`save` with no changes sends no request and returns `true`. Assigning the value an +attribute already has is not a change. Or in one call: ```ruby -group.update(name: 'Support 2', note: 'Renamed') # assigns, then saves -group.assign_attributes(name: 'Support 3') # assigns without saving +user.update(firstname: 'Nicola', note: 'Renamed') # assigns, then saves +user.assign_attributes(firstname: 'Nicola') # assigns without saving ``` ### Saving and validation failures @@ -523,25 +241,33 @@ else end ``` -Only a rejection of the attributes (HTTP 422) is reported that way. An expired token, a -missing record or an unreachable instance still raises, because those are not something -the calling code can correct by fixing an attribute. +Only a validation failure (HTTP 422) is reported this way. Every other failure raises. -`save!` and `update!` raise on every failure, including validation, which is what you want -in a script: +`save!` and `update!` raise on every failure, including validation: ```ruby group.save! # raises ZammadAPI::ValidationError group.update!(name: '') # the same, in one call ``` -`client.groups.create(...)` uses `save!`, so it raises rather than handing back a record -that looks created but is not. Use `new` plus `save` when you need to branch instead. +`create` raises on a validation failure, like `save!`. Use `new` and `save` to branch +instead. + +### Reload and destroy + +```ruby +user.reload # re-reads from Zammad, discarding unsaved changes +user.destroy # => true + +user.destroyed? # => true +user.persisted? # => false + +client.users.destroy(42) # delete by id, without fetching first +``` ### Associations -Zammad expands an association into a name under the plain attribute, so those reads are -already loaded and free: +Zammad expands an association into a name beside the id, so those reads cost nothing: ```ruby ticket = client.tickets.find(1) @@ -556,8 +282,6 @@ The whole record behind one of those is a `find` by its id, which costs a reques ```ruby client.users.find(ticket.customer_id).firstname # => "Nicole" -client.groups.find(ticket.group_id).note -client.users.find(ticket.created_by_id).email ``` A foreign key that may be empty, such as a user's `organization_id`, is `nil` then, and @@ -567,264 +291,157 @@ A foreign key that may be empty, such as a user's `organization_id`, is `nil` th user.organization_id && client.organizations.find(user.organization_id) ``` -A ticket's articles come from an endpoint of their own. `articles` reads the whole list in -one request, as an Array, and `add_article` writes one: +### Articles and attachments ```ruby -ticket.articles # => [TicketArticle, ...] +ticket.articles # => [TicketArticle, ...] ticket.add_article(body: 'Reset link sent.', type: 'note') # => the created TicketArticle + +ticket.articles.each do |article| + article.attachments.each do |attachment| + File.binwrite(File.basename(attachment.filename), attachment.download) + end +end ``` -`articles` is fetched on each call, so an article added in between shows up. +`articles` is one request, and is fetched on each call. `download` returns the file +contents as a binary String. ### Comparing and serializing -A record is the Zammad record it came from, not the object that happens to hold it, so two -records of the same kind carrying the same id are equal. -That makes `uniq`, `Set`, `include?` and records-as-Hash-keys behave: +Two records of the same kind with the same id are equal, so `uniq`, `Set` and `include?` +work as expected: ```ruby client.tickets.find(1) == client.tickets.find(1) # => true - -[client.tickets.find(1), client.tickets.find(1)].uniq.size # => 1 ``` -A record with no id is equal only to itself, because two unsaved records are two records -waiting to be created however alike their attributes are. - `to_json` renders the attributes, and `as_json` returns them as a Hash: ```ruby -client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}" -JSON.generate(group: client.groups.find(1)) +client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}" ``` -### Reload and destroy - -```ruby -group.reload # re-reads from Zammad, discarding unsaved changes -group.destroy # => true +### Pattern matching -group.destroyed? # => true -group.persisted? # => false, so this is not the inverse of new_record? +Records implement `deconstruct_keys`, so they work with `case/in`: -client.groups.destroy(42) # delete by id, without fetching first +```ruby +case client.tickets.find(1) +in {state: 'closed'} + nil +in {state: String => state, priority: '3 high'} + escalate(state) +in {group: 'Support'} + notify_support +end ``` ## Collections -`all`, `order` and `search` return a lazily paginated `ZammadAPI::Collection`. No request -is made until you iterate, and pages are fetched as needed. +`all`, `search` and `order` return a `ZammadAPI::Collection`. It is `Enumerable`, makes no +request until you iterate, and fetches pages as needed. -A resource proxy is itself `Enumerable` over `all`, so `.all` is optional: +### Iterating ```ruby client.tickets.each { |ticket| puts ticket.title } -client.tickets.first(5) -client.tickets.pluck(:title) -client.tickets.find_each(batch_size: 50) { |ticket| archive(ticket) } -``` - -`find` keeps its own meaning there — `client.tickets.find(1)` is a lookup by id, not -`Enumerable#find`. Use `detect` for the block form. - -```ruby -# Walks every page automatically. -client.tickets.all.each do |ticket| - puts ticket.title -end # One request, for five records. -first_five = client.tickets.all.first(5) +client.tickets.first(5) # Lazy chains stop fetching once they have enough. -client.tickets.all.lazy.select { |t| t.state == 'open' }.first(10) +client.tickets.lazy.select { |ticket| ticket.state == 'open' }.first(10) # One array of records per request, e.g. for a bulk import. -client.tickets.all.in_batches(of: 50) do |tickets| - import(tickets) -end - -# Record by record, with the page size set inline. -client.tickets.all.find_each(batch_size: 50) do |ticket| - archive(ticket) -end -``` - -### Sorting - -`order` sorts on the server: - -```ruby -client.groups.order(:name) # ascending -client.organizations.order(name: :desc) -client.groups.order(:active, name: :desc) # by active, then by name descending -client.tickets.search('state.name:open').order(created_at: :desc) -``` +client.tickets.in_batches(of: 50) { |tickets| import(tickets) } -An attribute on its own sorts ascending and a keyword says which way one runs, as in -ActiveRecord. A second `order` sorts within the first, so -`order(:active).order(name: :desc)` is the third line above. - -Not every endpoint sorts. `/api/v1/tickets` and `/api/v1/users` are always served in id -order — their controllers hardcode it and drop `sort_by` — so `order` on those raises -`ArgumentError` rather than handing back records it would be calling sorted. A search -sorts for every resource that can be searched: - -```ruby -client.tickets.order(:title) -# ArgumentError: api/v1/tickets is always served in the same order and ignores sort_by +# Record by record, 50 per request. +client.tickets.find_each(batch_size: 50) { |ticket| archive(ticket) } -client.tickets.search('state.name:open').order(:title) +# Attribute values instead of records. +client.users.pluck(:email) # => ["a@example.com", ...] +client.tickets.pluck(:id, :title) # => [[1, "Help"], ...] ``` -### Narrowing - -**Zammad's index endpoints do not filter.** `ApplicationController#model_index_render` -sorts and pages and drops every other parameter. Filtering by an attribute value exists -only on the `/search` endpoints, which is why a collection has no `where`. +`client.tickets` and `client.tickets.all` are the same collection. Nothing is cached, so +iterating again fetches again. -Narrow by a value with [`find_by`](#fetch) for one record, or `search` for many: +`client.tickets.find(1)` looks up by id. To find with a block, use `detect`. -```ruby -client.users.find_by(email: 'someone@example.com') -client.tickets.search('state.name:open').first(10) -``` - -`search` passes any keywords on to the search endpoint as query parameters, for what it -narrows by besides the term: `condition:` and `ids:` on every search, and `role_ids:`, -`group_ids:` and `permissions:` on users: +### Searching ```ruby -client.users.search('smith', role_ids: [2]) -client.users.search('smith', group_ids: {1 => ['read']}) -client.tickets.search('printer', condition: {'ticket.state_id' => {operator: 'is', value: [1, 2]}}) -client.tickets.search('printer', condition: {'ticket.group_id' => {operator: 'is', value: [2]}}) +client.tickets.search('state.name:open').each { |ticket| puts ticket.title } +client.organizations.search('zammad').first(10) ``` -Zammad ignores a parameter it does not read, so a misspelled keyword, or a user keyword on -another resource, comes back unnarrowed. Tickets are narrowed by group with a `condition` -on `ticket.group_id`, as above. - -Zammad routes a search endpoint per model, not for every model. `users`, `organizations`, -`tickets` and `groups` have one; `ticket_states`, `ticket_priorities` and `ticket_articles` -do not, and `search` on those raises `ZammadAPI::Error`. `find_by` works on them all the -same, by walking the list: +Zammad's index endpoints do not filter; only the search endpoints do. That is why a +collection has no `where`. `users`, `organizations`, `tickets` and `groups` can be +searched. On the others `search` raises `ZammadAPI::Error`, so use `find_by` or `select`: ```ruby client.ticket_states.find_by(name: 'open') client.ticket_priorities.select { it.active } ``` -### Search - -```ruby -client.organizations.search('zammad').each do |organization| - puts organization.name -end -``` - -A blank term raises `ArgumentError`: Zammad reads it as no term at all and answers with -every record. `search('*')` asks for every record in so many words. - -### Explicit pages +Keywords are passed on to the search endpoint as query parameters: `condition:` and `ids:` +on every search, and `role_ids:`, `group_ids:` and `permissions:` on users. Zammad ignores +a parameter it does not read. ```ruby -tickets = client.tickets.all - -tickets.page(2) # page 2 at the size the endpoint serves -tickets.page(2, per_page: 10) # records 11 to 20 +client.users.search('smith', role_ids: [2]) +client.tickets.search('printer', condition: {'ticket.group_id' => {operator: 'is', value: [2]}}) ``` -Collections are immutable: `order` and `page` return a new collection and leave the -original untouched. +A blank term raises `ArgumentError`. `search('*')` asks for every record. -### Page size +### Sorting -A request fetches as many records as the endpoint will serve — 100 for `/api/v1/tickets`, -200 for a search, 1000 for the other index endpoints — so a walk spends as few round trips -as it can. Three calls take another size, each for its own kind of work, and a larger one -is reduced to that cap: +`order` sorts on the server: ```ruby -client.tickets.all.find_each(batch_size: 50) { |ticket| archive(ticket) } # walking -client.tickets.all.in_batches(of: 50) { |tickets| import(tickets) } # batching -client.tickets.all.page(2, per_page: 100) # one page +client.groups.order(:name) # ascending +client.organizations.order(name: :desc) +client.groups.order(:active, name: :desc) # by active, then by name descending ``` -`find_each` without a block is an Enumerator, so it is also how you read at a chosen page -size: `client.tickets.all.find_each(batch_size: 50).first(7)`. - -A walk of an index ends at the first page that is shorter than the size it asked for. A -search is walked until a page comes back empty, since Zammad leaves a hit whose record is -gone off its page, and a short page can have more hits behind it. - -`first` sizes its request to what it was asked for, so the cheap-looking call is cheap: +`/api/v1/tickets` and `/api/v1/users` are always served in id order, so `order` on +`client.tickets` or `client.users` raises `ArgumentError`. Sort a search instead: ```ruby -client.tickets.all.first # one request, for one record -client.tickets.all.first(5) # one request, for five +client.tickets.search('state.name:open').order(created_at: :desc) ``` -A collection that `page` already limited keeps its own size. - -### Reading single attributes +### Pages ```ruby -client.users.all.pluck(:email) # => ["a@example.com", ...] -client.tickets.all.pluck(:id, :title) # => [[1, "Help"], ...] +client.tickets.page(2) # page 2 at the size the endpoint serves +client.tickets.page(2, per_page: 10) # records 11 to 20 ``` -Zammad cannot be asked for a subset of the fields, so this shapes the result rather than -shrinking the request. +By default a request asks for the largest page the endpoint serves: 100 for tickets, 200 +for a search, 1000 elsewhere. Pass a smaller size with `find_each(batch_size:)`, +`in_batches(of:)` or `page(n, per_page:)`; a larger one is capped. + +Collections are immutable: `order` and `page` return a new collection. ### Counting -`count` on a search is one request, which Zammad answers without serving the records. -Every other collection is walked, because an index endpoint has no total to report: +`count` on a search is one request. Every other collection is read page by page, because +an index endpoint reports no total: ```ruby -client.tickets.search('state.name:open').count # one request -client.tickets.all.count # one request per page +client.tickets.search('state.name:open').count # one request +client.tickets.count # one request per page client.tickets.search('state.name:merged').empty? # one request, for one record ``` -A block or an argument is `Enumerable#count` counting matches, and walks either way. -Nothing is cached, so every traversal of a collection fetches again. - -### `find` is a lookup, not a filter - -`find` on a resource takes an id. On a collection it is `Enumerable#find`, which takes a -block, and passing an id there raises `ArgumentError`: - -```ruby -client.tickets.find(1) # the lookup by id -client.tickets.all.detect { ... } # the block form -client.tickets.all.find(1) # ArgumentError -``` - -## Deriving clients - -A client is immutable. `with` returns a new one with some options changed, re-validating -them and carrying over any `on_behalf_of` scope: - -```ruby -bulk = client.with(timeout: 300, retries: 5) -bulk.tickets.all.each { |ticket| archive(ticket) } -``` - -Naming credentials replaces the ones the client has, whichever kind they were, so -`client.with(oauth2_token: '…')` on a client built with an access token authenticates with -the OAuth2 token alone. - -Because nothing is mutated after construction, one client — and any client derived from it — -is safe to use from several threads at once. - ## Acting on behalf of another user -As described in the [Zammad API documentation](https://docs.zammad.org/en/latest/api/intro.html#actions-on-behalf-of-other-users), -actions can be performed on behalf of another user. `on_behalf_of` returns a **new** -client, so the original is unaffected and both are safe to use concurrently. +Zammad can perform +[actions on behalf of another user](https://docs.zammad.org/en/latest/api/intro.html#actions-on-behalf-of-other-users). +`on_behalf_of` returns a new client: ```ruby support = client.on_behalf_of('agent@example.com') @@ -839,16 +456,29 @@ client.on_behalf_of('agent@example.com') do |scoped| end ``` -The identifier can be a login, an email address or a user id. This sends the standard -HTTP `From` header and requires Zammad 5.0 or later. - -An identifier that is `nil` or blank raises `ArgumentError`. Zammad reads an empty `From` -header as none at all, so `client.on_behalf_of(user&.login)` with no user would otherwise -perform every request as the account the client authenticates as. +The identifier can be a login, an email address or a user id. A `nil` or blank identifier +raises `ArgumentError`. This sends the HTTP `From` header and requires Zammad 5.0 or later. ## Error handling -Every error descends from `ZammadAPI::Error`. +```ruby +begin + client.tickets.find(1) +rescue ZammadAPI::NotFoundError + nil +rescue ZammadAPI::RateLimitError => e + # The client already waited and retried, so this limit outlasted that. + reschedule(in: e.retry_after || 60) +rescue ZammadAPI::ResponseError => e + warn "#{e.status}: #{e.server_message}" + warn e.body.inspect +end +``` + +`save` and `update` return `false` on a 422 instead of raising; see +[Saving and validation failures](#saving-and-validation-failures). + +Every error descends from `ZammadAPI::Error`: ```text ZammadAPI::Error @@ -869,41 +499,31 @@ ZammadAPI::Error └── ZammadAPI::ServerError 5xx ``` -```ruby -begin - client.tickets.find(1) -rescue ZammadAPI::NotFoundError - nil -rescue ZammadAPI::RateLimitError => e - # The client already waited and retried, so this limit outlasted that. - reschedule(in: e.retry_after || 60) -rescue ZammadAPI::ResponseError => e - warn "#{e.status}: #{e.server_message}" - warn e.body.inspect -end -``` - -`ResponseError` exposes `status`, `body`, `headers`, `server_message`, `operation` and -`resource_class`. A proxy that returns an HTML error page instead of JSON produces a -`ServerError` describing the status, not a JSON parse failure. +`ResponseError` exposes `response` (a `ZammadAPI::Response`) and, as shortcuts, `status`, +`body`, `headers` and `server_message`, plus `operation` and `resource_class`. A `TransportError` is a request with no answer, which is not the same as one Zammad never saw: a write that timed out may have been applied. ### Timeouts and retries -A `GET` is retried on connection failures, timeouts and the transient statuses 429, 500, -502, 503 and 504, with exponential backoff. +A `GET` is retried on connection failures, timeouts and the statuses 429, 500, 502, 503 +and 504, with exponential backoff. A write is never retried. Both are options: + +```ruby +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'token', + timeout: 10, + retries: 5 +) +``` -A `Retry-After` header on one of those responses is honoured: the client waits as long as -the server asked before the next attempt, up to `timeout` seconds. A longer one is not -waited out. The request fails at once with the error for its status, and -`RateLimitError#retry_after` carries the figure, so a job can reschedule itself. +A `Retry-After` header is honoured up to `timeout` seconds. A longer one is not waited +out: the request fails at once, and `RateLimitError#retry_after` carries the figure. -A write is never retried. `POST` would create a second record, and `PUT` and `DELETE` are -not safe to repeat against Zammad either: a ticket update carrying an `article` adds that -article — and sends its e-mail — once per delivery. So a write that fails raises, and the -code that knows what the request carried decides whether to send it again: +A write that fails raises, because repeating it could create a second record or send an +e-mail twice. The calling code decides whether to send it again: ```ruby begin @@ -914,80 +534,151 @@ rescue ZammadAPI::TransportError, ZammadAPI::ServerError end ``` +## Logging + ```ruby client = ZammadAPI::Client.new( url: 'https://zammad.example.com/', http_token: 'token', - timeout: 10, - retries: 5 + logger: Logger.new($stdout) ) ``` -## Logging +Requests, response statuses and durations are logged at `debug` level. Anything that +responds to `debug` works in place of a `Logger`. Payload keys, query parameters and +headers that look like credentials (`password`, `token`, `secret`, `cookie`, ...) are +redacted, and a path is logged without its query string. + +## Endpoints this gem does not model + +### Declaring a resource + +For an endpoint that serves records like the modelled ones (an index, and a member under +its id), declare a class with a path. `client.resource` then works like `client.tickets`: + +```ruby +class Role < ZammadAPI::Resources::Base + path 'api/v1/roles' +end + +roles = client.resource(Role) + +roles.each { |role| puts role.name } +roles.find(2).update(note: 'Reviewed') +roles.create(name: 'Auditor') +roles.find_by(name: 'Agent') +``` + +Declare where the endpoint differs from the defaults: + +| Declaration | Default | Says | +| ------------------ | ---------- | ------------------------------------------------------------- | +| `path '…'` | *required* | The index endpoint, relative to the instance URL. | +| `searchable true` | `false` | Zammad routes `/search`, so `search` works and `find_by` uses it. | +| `max_per_page 100` | `1000` | The largest page the index endpoint serves. | +| `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. | + +A subclass of a modelled resource works too, and inherits what its parent declares: +`class MyTicket < ZammadAPI::Resources::Ticket`. + +For an endpoint that ignores `page` and returns everything at once, or one that is an +action, a report or a setting, use a raw request. + +### Raw requests + +`get`, `post`, `put` and `delete` reach any endpoint of the Zammad API, with the same +authentication, timeouts, retries and error classes: + +```ruby +client.get('api/v1/roles').body +# => [{id: 1, name: "Admin", ...}, ...] + +client.post('api/v1/tags/add', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) +client.put('api/v1/roles/2', body: {note: 'Updated'}) +client.delete('api/v1/tags/remove', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) + +client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) +``` + +A `body:` is sent as JSON, and a String body is sent as it is. Each call returns a +`ZammadAPI::Response`: + +```ruby +response = client.get('api/v1/tickets') +response.status # => 200 +response.headers['content-type'] +response.body # decoded JSON, or the raw body for anything else +response.raw_body # the body as it arrived +``` + +Paths are relative to the instance URL, and a leading slash is ignored. A path that opens +with a scheme, such as `https://other.example/collect`, raises `ArgumentError`, so the +client's credentials only go to the instance it was configured for. + +### Coverage + +Modelled: tickets, ticket articles and their attachments, ticket states and priorities, +users, organizations and groups, the same set as 1.x. + +Not modelled yet: text modules; ticket tags, links, mentions, time accounting, checklists, +shared drafts, merge and history; the knowledge base; global search; CSV imports. Declare +a resource or use raw requests for those, and +[open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) for the one +you need, so we know what to model first. + +## Adapter and middleware + +The client is built on Faraday. `adapter:` picks the Faraday adapter, and `middleware:` +adds your own middleware, such as instrumentation or a cache: ```ruby client = ZammadAPI::Client.new( url: 'https://zammad.example.com/', http_token: 'token', - logger: Logger.new($stdout) + adapter: :net_http_persistent, + middleware: ->(connection) { connection.use(MyInstrumentation) } ) ``` -Any object that responds to `debug` will do in place of a `Logger`. Each line is handed -over as a block, so that it is only built where it is written. +To pass arguments to an adapter, set it inside the callable: +`->(connection) { connection.adapter :net_http_persistent, pool_size: 5 }`. Do not add +`response :json` or `response :raise_error`; the client decodes JSON and maps errors +itself. -Requests, response statuses and durations are logged at `debug` level. Payload keys, query -parameters and headers that look like credentials (`password`, `token`, `secret`, `cookie`, -...) are redacted, and a path is logged without its query string. A body that is not a -Hash or an Array, such as a JSON String, is not logged, only its size. +Faraday's default adapter opens a connection per request. For anything that reads many +pages, downloads attachments in a loop or runs a worker pool, add +`faraday-net_http_persistent` to your Gemfile and pass `adapter: :net_http_persistent`. ## Type signatures RBS signatures ship in `sig/` and are checked in CI with [Steep](https://github.com/soutaro/steep). -Add the gem to your own RBS collection to type-check calls into this client. - -Records are typed, not only the client. `client.tickets` is a -`ResourceProxy[Resources::Ticket]`, so `find`, `first`, `find_by`, the block of `each` and -a search all hand you a `Ticket`, and each resource declares the attributes every -supported Zammad serves for it: +Add the gem to your own RBS collection to type-check calls into this client. Records are +typed, not only the client: ```ruby ticket = client.tickets.find(1) ticket.title # String ticket.organization_id # Integer? -ticket.titel # a type error, where it used to be untyped +ticket.titel # a type error: no such attribute is declared ``` -Three things are deliberately not declared, and each has a way through: +Attributes an administrator added, columns only newer Zammad versions serve, and expanded +association names that can be absent (such as `organization`) are not declared. Read those +with `ticket[:name]`, or reopen the class in your own signatures: -- **Attributes an administrator added.** Read one with `ticket[:escalation_reason]`, or - declare it in your own signatures by reopening the class: - - ```rbs - class ZammadAPI::Resources::Ticket - attr_accessor escalation_reason: String? - end - ``` - -- **Columns only newer Zammad versions have**, which an older instance does not serve. - `record[:name]` reads those too. -- **The name `expand` adds for an association that may be empty**, such as `organization` - on a ticket or a user. Zammad leaves the key out rather than sending `null`, so a reader - would raise rather than answer `nil`; `ticket[:organization]` is `nil` in that case, and - `ticket.organization_id` is always there. +```rbs +class ZammadAPI::Resources::Ticket + attr_accessor escalation_reason: String? +end +``` -A proxy for [a resource of your own](#resources-this-gem-does-not-model) is untyped until -you say what it holds, because a signature cannot carry a class into its own return type: +A resource of your own needs an annotation: ```ruby roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role] ``` -The types describe a record Zammad served. One built with `new` carries only what it was -given until it is saved, and reading anything else from it raises `NoMethodError`, whatever -the signature says the type would be. - ## Examples Runnable scripts covering pagination, pattern matching, acting on behalf of a user, @@ -996,189 +687,18 @@ attachments, error handling and threaded use live in [`examples/`](examples/READ ## Development ```sh -bin/setup # or: bundle install +bin/setup # bundle install, plus the overcommit git hooks bundle exec rake # unit specs, RuboCop, Steep and the shipped signatures ``` -| Task | What it does | -| ------------------------ | ----------------------------------------------------- | -| `rake spec:unit` | Unit specs; stubbed, no Zammad needed | -| `rake spec:integration` | Integration specs against a live Zammad | -| `rake check_connection` | Drives a live Zammad end to end and prints a transcript | -| `rake rubocop` | Style checks | -| `rake steep` | Type-check `lib/` against `sig/`, and `spec/typed/` the way a caller is checked | -| `rake rbs_published` | Validate the signatures the gem ships, without `sig/vendor/` | - -Set `COVERAGE=true` to produce a coverage report in `coverage/`. +Integration specs need a disposable Zammad named by `TEST_URL`; see +[CONTRIBUTING.md](CONTRIBUTING.md). -### Testing against a live Zammad - -The integration specs and `check_connection` need a reachable Zammad instance and **will -create and delete records**, so they run only where `TEST_URL` names one, and there is no -default: point it at something disposable. Without it, `rspec` runs the unit specs and -says the integration specs were left out, `rspec spec/integration` fails for having -nothing to run, and `rake spec:integration`, `rake spec` and `rake check_connection` stop -before running anything. - -```sh -export TEST_URL=https://zammad.example/ # a disposable Zammad, never one you keep data in -export TEST_USER=admin@example.com -export TEST_PASSWORD=test - -bundle exec rake check_connection # one linear pass, readable transcript -bundle exec rake spec:integration # the full spec suite -``` +## Upgrading from 1.x -`check_connection` walks the documented workflows in order — create, find, update, reload, -pattern match, paginate, search, ticket with articles, attachment download, acting on -behalf of a user, and each error class — printing `ok` or `FAIL` per step and cleaning up -after itself. It stops early if a precondition fails, so a broken instance produces one -clear line rather than a cascade. - -CI runs both against a Zammad booted from source: the `integration` job clones Zammad, -starts it, waits for it to answer, runs `check_connection` as a fast preflight, then runs -the integration specs. Trigger it by hand from the Actions tab (`workflow_dispatch`) to -test against a specific Zammad ref. - -## Migrating from 1.x - -Version 2.0 fixes long-standing behaviour that could not change without breaking -compatibility. Most calling code needs one rename and no more — the resource readers are -plural, so `client.ticket` is `client.tickets` — and almost everything else that needs an -edit raises at the call site. Start with the handful of changes that do not. - -If this is not the time to move, [1.x stays available](#staying-on-1x). - -### Changes that do not announce themselves - -- **`record.attributes = {...}`** was a writer in 1.x. It is now an ordinary attribute - assignment, so it stages a change named `attributes` and `save` sends it to Zammad: - - ```ruby - group.attributes = {name: 'Support'} - group.changes # => {attributes: [nil, {name: "Support"}]} - ``` - - Use `assign_attributes(name: 'Support')`, or `update` to assign and save. - -- **`record.save`** returns `false` when Zammad rejects the attributes, where 1.x raised. - Code that relied on the exception carries on after a rejected save: - - ```ruby - ticket.state = 'closed' - ticket.save # false on a 422 in 2.0; nothing raises, and the ticket is still open - ``` - - Check what `save` returns and read `record.error`, or call `save!`, which raises - `ZammadAPI::ValidationError` as `save` used to. `update` and `update!` are the same pair. - -- **`collection.each`** walks every page, where 1.x read one and stopped: - `client.ticket.all.each { ... }`, as 1.x spelled it, touched the first 100 tickets. That - line raises in 2.0, because the reader is `client.tickets` now, and renaming it is all it - takes to run again — after which it touches every ticket the client can read, at a request - per page. A loop written to handle the first page, or one that writes to each record it is - handed, does that to all of them now. Limit it explicitly with `first(n)` or - `page(1, per_page: n)`. - -- **A Hash inside an Array attribute** has Symbol keys, where 1.x left it the String keys - Zammad sent: only a Hash directly under another Hash was symbolized. Read by String key, - it answers `nil` and nothing raises: - - ```ruby - article.attributes[:attachments].first['filename'] # the name in 1.x, nil in 2.0 - article.attributes[:attachments].first[:filename] # the name in 2.0 - ``` - - Keys are Symbols at every depth now, so one spelling reads a value wherever it sits. - -- **`rescue Faraday::ConnectionFailed`** (and any other Faraday exception) no longer - matches. Transport failures are wrapped, so rescue `ZammadAPI::ConnectionError`, - `ZammadAPI::TimeoutError`, or `ZammadAPI::TransportError` for both. - -### The client - -| 1.x | 2.0 | Why | -| -------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------- | -| `Client.new(config_hash)` | `Client.new(**config_hash)` | Options are keyword arguments now, so a Hash has to be splatted | -| an unknown option was ignored | raises `ArgumentError: unknown keyword` | A typo'd option used to be dropped without a word | -| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object, so you choose the device and level. Anything that responds to `debug` works; `true` raises `NoMethodError` on the first request | -| `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is `Enumerable` over every record now, so `client.ticket.each` read as if it acted on one ticket. The singular names raise `UnknownResourceError`, which lists the plural ones, and so does `client.resource(:ticket)` | -| `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads | -| `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised | -| `ZammadAPI::Resources::Role < Base` reached by `client.role` | `client.resource(Role)`, for a `Role < ZammadAPI::Resources::Base` of your own | The named readers are a fixed list, and a class is handed over rather than looked up by name. [Raw requests](#raw-requests) reach whatever is not a resource | - -### Collections - -| 1.x | 2.0 | Why | -| ---------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------- | -| `collection.each` stopped after one page | `each` walks every page | Iterating truncated silently at the page size: 100 for `all`, 10 for `search` | -| `collection.page(1, 3) { \|r\| ... }` | `collection.page(1, per_page: 3).each { ... }` | `page` now returns a collection instead of mutating and yielding | -| `collection.page_next` / `page_prev` | `collection.page(n)` or `in_batches` | Removed; they mutated shared state | -| `collection[3]` | `collection.page(4, per_page: 1).first` | An index that costs a request, and that ignored `page`, was a trap | -| `collection.find(1)` | `client.x.find(1)`, or `collection.detect { ... }` | On a collection `find` is `Enumerable#find`, whose argument is an ifnone callable — so an id answered with an Enumerator and made no request. It raises now | -| `client.x.all(per_page: 50)` | `client.x.all.page(1, per_page: 50)`, `find_each(batch_size: 50)` | `all` accepted the argument and discarded it; page size belongs to the call that reads | -| `client.x.all(active: true)` | `client.x.search(...)`, or `client.x.all.detect { ... }` | The filter never reached the request in 1.x, and could not have: Zammad's index endpoints do not filter, so 2.0 has no call that pretends to. `find_by(active: true)` answers with the first such record, by walking the index where it has no string to search on | -| `client.x.search(query: 'zammad')` | `client.x.search('zammad')` | The search term is the argument, not a keyword | -| `client.x.search(query: 'z', page: 2, per_page: 50)` | `client.x.search('z').page(2, per_page: 50)` | Search did honour those two; paging is the collection's job now | - -### Records - -| 1.x | 2.0 | Why | -| ----------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------- | -| `record.save` raised on a rejection | `save` → `false` with `record.error`; `save!` raises | Branching on a rejected attribute needed a begin/rescue | -| `record.attributes[:x] = 1` | `record.x = 1`, or `record.to_h` for a copy | Writing through the reader staged no change, so `save` never sent it | -| `record.attributes = {...}` | `record.assign_attributes(...)` / `record.update(...)` | The writer is gone, and the name now stages an attribute of its own | -| `record.id = 5` | `client.x.find(5)` | The id addresses the record, so a staged one deleted or updated a different record than it reported. It raises `ZammadAPI::Error` now | -| `record.new_instance` | `record.new_record?` / `record.persisted?` | Internal flag is no longer public; the old name raises `NoMethodError` | -| `resource.url` (instance) | `Resource.resource_path` (class) | Clashed with an attribute named `url` | -| `record.unknown_attribute` → `nil` | raises `NoMethodError`; use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` | A typo read as `nil` and flowed on into whatever was written with it. Zammad also serves a reduced object where the user may not see the whole record, and that is worth being told about | -| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | A noun that sends a `POST`, one letter away from `ticket.articles`, which only reads. The method is gone: `article` is an attribute reader like any other, and the old call raises `NoMethodError` | - -### Errors - -| 1.x | 2.0 | Why | -| ------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------- | -| `ZammadAPI::Error < RuntimeError` | `ZammadAPI::Error < StandardError` | `RuntimeError` is for `raise "string"` | -| `ZammadAPI::ResourceNotFoundError` | `ZammadAPI::UnknownResourceError` | Renamed so it is not confused with a 404, now `NotFoundError` | -| `ClientError` for every 4xx | `AuthenticationError`, `NotFoundError`, `ValidationError`, … | All still `ClientError`, so existing rescues keep working | -| a Faraday exception for a dead host | `ZammadAPI::ConnectionError` / `TimeoutError` | Every failure this gem can raise descends from `ZammadAPI::Error` | -| `error.response` was a Faraday object | `ZammadAPI::Response` with `status`/`body`/`headers` | Faraday is no longer part of the public surface | -| `error.body` was a raw JSON string | decoded Hash, or the raw body for non-JSON | Saves every caller from parsing it again | - -### Removed constants, and the Ruby version - -| 1.x | 2.0 | Why | -| ------------------------------------------------ | -------------------------- | ------------------------------------------------------------ | -| `ZammadAPI::ListBase` / `ListAll` / `ListSearch` | `ZammadAPI::Collection` | One class instead of three | -| `ZammadAPI::Dispatcher` | `ZammadAPI::ResourceProxy` | Renamed; `client.` hands you one | -| `ZammadAPI::Log`, `ZammadAPI::JsonHelper` | removed | Pass any `Logger` as `logger:`; decoding moved into the transport | -| Ruby >= 3.0 | Ruby >= 3.4 | 3.0 through 3.3 are end-of-life or nearly so | - -### Defaults 1.x did not have - -A collection fetches as many records per request as the endpoint serves — 1000 on the index -endpoints, 100 on tickets, 200 on a search — rather than a fixed 100, so a walk spends -roughly a tenth of the round trips. `page(n)` without `per_page:` is a page of that size, so pin -it with `page(n, per_page: 100)` if a persisted page number has to keep meaning what it did. - -A request now times out after 60 seconds (10 to connect) where 1.x waited as long as the -server took, so a call that used to hang raises `ZammadAPI::TimeoutError` (or -`ZammadAPI::ConnectionError` when the connection is not opened in time). A `GET` is -retried twice with exponential backoff on connection failures, timeouts and the transient -statuses, which means a genuinely broken endpoint takes a little longer to report itself; -a `POST`, `PUT` or `DELETE` is never retried. Both are options — see -[Timeouts and retries](#timeouts-and-retries). The `User-Agent` is now -`zammad_api-ruby/` rather than `Zammad API Ruby`. - -### What did not change - -`find`, `all`, `create` and `new` on a resource, `record.destroy`, attribute readers and -writers, `ticket.articles` and `attachment.download`. The resources themselves are reached -by their plural names — `client.tickets` — and adding an article is `ticket.add_article`; -those two are renames, and the old names raise. - -`record.save`, `record.changes` and `record.attributes` still exist and still mean what -they meant; the tables above only change how they behave at the edges. +Most code needs one rename: `client.ticket` is `client.tickets`. Nearly everything else +that changed raises at the call site. [UPGRADING.md](UPGRADING.md) lists every change, and +says how to stay on 1.x. ## License diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 0000000..139caa5 --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,153 @@ +# Upgrading from 1.x + +Version 2.0 fixes long-standing behaviour that could not change without breaking +compatibility. Most calling code needs one rename: the resource names are plural, so +`client.ticket` is `client.tickets`. Almost everything else that needs an edit raises at +the call site. Start with the few changes that do not. + +If this is not the time to move, [1.x stays available](#staying-on-1x). + +## Silent changes + +- **`record.attributes = {...}`** was a writer in 1.x. It is now an ordinary attribute + assignment, so it stages a change named `attributes` and `save` sends it to Zammad: + + ```ruby + group.attributes = {name: 'Support'} + group.changes # => {attributes: [nil, {name: "Support"}]} + ``` + + Use `assign_attributes(name: 'Support')`, or `update` to assign and save. + +- **`record.save`** returns `false` when Zammad rejects the attributes, where 1.x raised. + Code that relied on the exception carries on after a rejected save: + + ```ruby + ticket.state = 'closed' + ticket.save # false on a 422 in 2.0; nothing raises, and the ticket is still open + ``` + + Check what `save` returns and read `record.error`, or call `save!`, which raises + `ZammadAPI::ValidationError` as `save` used to. `update` and `update!` are the same pair. + +- **`collection.each`** reads every page, where 1.x stopped after the first (100 records + for `all`, 10 for `search`). A loop that used to touch the first 100 tickets now touches + all of them. To keep the old limit, use `first(n)` or `page(1, per_page: n)`. + +- **A Hash inside an Array attribute** has Symbol keys, where 1.x left it the String keys + Zammad sent: only a Hash directly under another Hash was symbolized. Read by String key, + it answers `nil` and nothing raises: + + ```ruby + article.attributes[:attachments].first['filename'] # the name in 1.x, nil in 2.0 + article.attributes[:attachments].first[:filename] # the name in 2.0 + ``` + + Keys are Symbols at every depth now, so one spelling reads a value wherever it sits. + +- **`rescue Faraday::ConnectionFailed`** (and any other Faraday exception) no longer + matches. Transport failures are wrapped, so rescue `ZammadAPI::ConnectionError`, + `ZammadAPI::TimeoutError`, or `ZammadAPI::TransportError` for both. + +## The client + +| 1.x | 2.0 | Why | +| -------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------- | +| `Client.new(config_hash)` | `Client.new(**config_hash)` | Options are keyword arguments now, so a Hash has to be splatted | +| an unknown option was ignored | raises `ArgumentError: unknown keyword` | A typo'd option used to be dropped without a word | +| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object. Anything that responds to `debug` works | +| `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is every record of its kind. The singular names raise `UnknownResourceError` | +| `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads | +| `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised | +| `ZammadAPI::Resources::Role < Base` reached by `client.role` | `client.resource(Role)`, for a `Role < ZammadAPI::Resources::Base` of your own | The named readers are a fixed list. [Raw requests](README.md#raw-requests) reach whatever is not a resource | + +## Collections + +| 1.x | 2.0 | Why | +| ---------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------- | +| `collection.page(1, 3) { \|r\| ... }` | `collection.page(1, per_page: 3).each { ... }` | `page` now returns a collection instead of mutating and yielding | +| `collection.page_next` / `page_prev` | `collection.page(n)` or `in_batches` | Removed; they mutated shared state | +| `collection[3]` | `collection.page(4, per_page: 1).first` | An index that costs a request, and that ignored `page`, was a trap | +| `collection.find(1)` | `client.x.find(1)`, or `collection.detect { ... }` | `find` on a collection is `Enumerable#find`; an id raises `ArgumentError` | +| `client.x.all(per_page: 50)` | `client.x.all.page(1, per_page: 50)`, `find_each(batch_size: 50)` | `all` accepted the argument and discarded it; page size belongs to the call that reads | +| `client.x.all(active: true)` | `client.x.search(...)`, or `client.x.all.detect { ... }` | Zammad's index endpoints do not filter, so 1.x ignored the argument | +| `client.x.search(query: 'zammad')` | `client.x.search('zammad')` | The search term is the argument, not a keyword | +| `client.x.search(query: 'z', page: 2, per_page: 50)` | `client.x.search('z').page(2, per_page: 50)` | Search did honour those two; paging is the collection's job now | + +## Records + +| 1.x | 2.0 | Why | +| ----------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------- | +| `record.attributes[:x] = 1` | `record.x = 1`, or `record.to_h` for a copy | Writing through the reader staged no change, so `save` never sent it | +| `record.id = 5` | `client.x.find(5)` | The id addresses the record, so a staged one deleted or updated a different record than it reported. It raises `ZammadAPI::Error` now | +| `record.new_instance` | `record.new_record?` / `record.persisted?` | Internal flag is no longer public; the old name raises `NoMethodError` | +| `resource.url` (instance) | `Resource.resource_path` (class) | Clashed with an attribute named `url` | +| `record.unknown_attribute` → `nil` | raises `NoMethodError`; use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` | A typo used to read as `nil` | +| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | Renamed; `ticket.article(...)` raises `NoMethodError` | + +## Errors + +| 1.x | 2.0 | Why | +| ------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------- | +| `ZammadAPI::Error < RuntimeError` | `ZammadAPI::Error < StandardError` | `RuntimeError` is for `raise "string"` | +| `ZammadAPI::ResourceNotFoundError` | `ZammadAPI::UnknownResourceError` | Renamed so it is not confused with a 404, now `NotFoundError` | +| `ClientError` for every 4xx | `AuthenticationError`, `NotFoundError`, `ValidationError`, … | All still `ClientError`, so existing rescues keep working | +| `error.response` was a Faraday object | `ZammadAPI::Response` with `status`/`body`/`headers` | Faraday is no longer part of the public surface | +| `error.body` was a raw JSON string | decoded Hash, or the raw body for non-JSON | Saves every caller from parsing it again | + +## Removed constants, and the Ruby version + +| 1.x | 2.0 | Why | +| ------------------------------------------------ | -------------------------- | ------------------------------------------------------------ | +| `ZammadAPI::ListBase` / `ListAll` / `ListSearch` | `ZammadAPI::Collection` | One class instead of three | +| `ZammadAPI::Dispatcher` | `ZammadAPI::ResourceProxy` | Renamed; `client.` hands you one | +| `ZammadAPI::Log`, `ZammadAPI::JsonHelper` | removed | Pass any `Logger` as `logger:`; decoding moved into the transport | +| Ruby >= 3.0 | Ruby >= 3.4 | 3.0 through 3.3 are end-of-life or nearly so | + +## New defaults + +A collection fetches as many records per request as the endpoint serves: 1000 on most +index endpoints (1.x: 100), 100 on tickets (unchanged) and 200 on a search (1.x: 10). +`page(n)` without `per_page:` is a page of that size, so pin it with +`page(n, per_page: 100)` if a persisted page number has to keep meaning what it did. + +A request times out after 60 seconds (10 to connect), where 1.x waited as long as the +server took. A call that used to hang raises `ZammadAPI::TimeoutError`, or +`ZammadAPI::ConnectionError` when the connection is not opened in time. A `GET` is retried +twice with exponential backoff on connection failures, timeouts and the transient +statuses; a `POST`, `PUT` or `DELETE` is never retried. Both are options: see +[Timeouts and retries](README.md#timeouts-and-retries). The `User-Agent` is +`zammad_api-ruby/` rather than `Zammad API Ruby`. + +## What did not change + +`find`, `all`, `create` and `new` on a resource, `record.destroy`, attribute readers and +writers, `ticket.articles` and `attachment.download`. + +`record.save`, `record.changes` and `record.attributes` still exist and still mean what +they meant; the tables above only change how they behave at the edges. + +## Staying on 1.x + +1.x stays available for a project that is not ready for 2.0, or that runs on a Ruby older +than 3.4: 1.x needs Ruby 3.0 or later. + +Its code lives on the +[`1-stable`](https://github.com/zammad/zammad-api-client-ruby/tree/1-stable) branch, and +the [README there](https://github.com/zammad/zammad-api-client-ruby/blob/1-stable/README.md) +documents the 1.x API. To install it, keep the version below 2: + +```ruby +gem 'zammad_api', '~> 1.4' +``` + +Or: + +```sh +gem install zammad_api -v '~> 1.4' +``` + +1.x is in maintenance mode, and will stay there for the foreseeable future: it still gets +fixes, while new features go into 2.0 only. Report a 1.x problem in the same +[issue tracker](https://github.com/zammad/zammad-api-client-ruby/issues), naming the +version, and open a pull request for it against `1-stable`. diff --git a/zammad_api.gemspec b/zammad_api.gemspec index 0938378..e79fd93 100644 --- a/zammad_api.gemspec +++ b/zammad_api.gemspec @@ -17,7 +17,7 @@ Gem::Specification.new do |spec| spec.summary = "Version 2.0 of the Ruby client for the Zammad API#{' (prerelease)' if prerelease}." spec.description = 'Version 2.0 of the Ruby client for the Zammad API v1.0, the one a Zammad serves under ' \ - '/api/v1. It is a breaking release: the README lists every call that changed since 1.x.' + '/api/v1. It is a breaking release: UPGRADING.md lists every call that changed since 1.x.' spec.description += " This is a prerelease, #{ZammadAPI::VERSION}: install it with --pre." if prerelease spec.homepage = 'https://github.com/zammad/zammad-api-client-ruby' spec.licenses = ['AGPL-3.0-only', 'MIT'] @@ -50,9 +50,10 @@ Gem::Specification.new do |spec| LICENSE.MIT.txt LICENSE.md README.md + UPGRADING.md ] spec.require_paths = ['lib'] - spec.extra_rdoc_files = ['README.md', 'CHANGELOG.md'] + spec.extra_rdoc_files = ['README.md', 'UPGRADING.md', 'CHANGELOG.md'] spec.add_dependency 'faraday', '~> 2.9' spec.add_dependency 'faraday-retry', '~> 2.2' From 49460d6ed708b8cff98eac3291ed2797d9846228 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 16:44:28 +0200 Subject: [PATCH 103/121] Docs: add a features roadmap comparing Ruby 1.x, Ruby 2.0 and the PHP client --- README.md | 3 +++ ROADMAP.md | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 ROADMAP.md diff --git a/README.md b/README.md index a98f2a5..4f3ed44 100644 --- a/README.md +++ b/README.md @@ -626,6 +626,9 @@ a resource or use raw requests for those, and [open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) for the one you need, so we know what to model first. +The [features roadmap](ROADMAP.md) shows what is in progress for 2.0, beside 1.x and the +PHP client. + ## Adapter and middleware The client is built on Faraday. `adapter:` picks the Faraday adapter, and `middleware:` diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..f40c126 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,27 @@ +# Features roadmap + +What each Zammad API client models: this gem in its 1.x and 2.0 versions, and the +[PHP client](https://github.com/zammad/zammad-api-client-php). + +✅ available · 🚧 work in progress · ❌ not available + +| Resource | Ruby 1.x | Ruby 2.0 | PHP | +| ------------------------- | :------: | :------: | ---------------------------------------------------- | +| Tickets | ✅ | ✅ | ✅ | +| Ticket articles | ✅ | ✅ | ✅ per ticket only, no index | +| Article attachments | ✅ | ✅ | ✅ no class; `getAttachmentContent()` on the article | +| Ticket states | ✅ | ✅ | ✅ | +| Ticket priorities | ✅ | ✅ | ✅ | +| Users | ✅ | ✅ | ✅ | +| Organizations | ✅ | ✅ | ✅ | +| Groups | ✅ | ✅ | ✅ | +| Tags | ❌ | 🚧 | ✅ list, search, add, remove | +| Links | ❌ | 🚧 | ✅ ticket to ticket | +| Text modules | ❌ | 🚧 | ✅ | +| CSV import: users | ❌ | 🚧 | ✅ | +| CSV import: organizations | ❌ | 🚧 | ✅ | +| CSV import: text modules | ❌ | 🚧 | ✅ | + +Until a 🚧 row lands in Ruby 2.0, reach it by +[declaring a resource](README.md#declaring-a-resource) or with a +[raw request](README.md#raw-requests). From 4c4a0c0b51eadc211d595ceee63fea947b865969 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 16:55:51 +0200 Subject: [PATCH 104/121] Docs: add roles to the features roadmap --- ROADMAP.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ROADMAP.md b/ROADMAP.md index f40c126..2ed3d20 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -15,6 +15,7 @@ What each Zammad API client models: this gem in its 1.x and 2.0 versions, and th | Users | ✅ | ✅ | ✅ | | Organizations | ✅ | ✅ | ✅ | | Groups | ✅ | ✅ | ✅ | +| Roles | ❌ | 🚧 | ✅ | | Tags | ❌ | 🚧 | ✅ list, search, add, remove | | Links | ❌ | 🚧 | ✅ ticket to ticket | | Text modules | ❌ | 🚧 | ✅ | From 4ce4dbf667f07d41d51afe277d765836d543a7e0 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 17:11:11 +0200 Subject: [PATCH 105/121] Docs: fold the example scripts into the README The nine scripts in examples/ restated the README and were run by nothing. The two things only they showed, a resumable page loop and one client shared between threads, are now README recipes. --- Gemfile | 4 -- Gemfile.lock | 1 - README.md | 62 +++++++++++++++++++++++-- examples/README.md | 41 ----------------- examples/concurrent_sync.rb | 57 ----------------------- examples/download_attachments.rb | 45 ------------------ examples/error_handling.rb | 77 ------------------------------- examples/manual_batches.rb | 78 -------------------------------- examples/onboard_customer.rb | 57 ----------------------- examples/pagination.rb | 71 ----------------------------- examples/quickstart.rb | 53 ---------------------- examples/ticket_report.rb | 57 ----------------------- examples/triage_tickets.rb | 58 ------------------------ 13 files changed, 58 insertions(+), 603 deletions(-) delete mode 100644 examples/README.md delete mode 100755 examples/concurrent_sync.rb delete mode 100755 examples/download_attachments.rb delete mode 100755 examples/error_handling.rb delete mode 100755 examples/manual_batches.rb delete mode 100755 examples/onboard_customer.rb delete mode 100755 examples/pagination.rb delete mode 100755 examples/quickstart.rb delete mode 100755 examples/ticket_report.rb delete mode 100755 examples/triage_tickets.rb diff --git a/Gemfile b/Gemfile index 84076c9..a8d8416 100644 --- a/Gemfile +++ b/Gemfile @@ -6,10 +6,6 @@ source 'https://rubygems.org' gemspec group :development, :test do - # For examples/ticket_report.rb. A bundled gem from Ruby 3.4 on, which - # Bundler makes loadable only where the bundle names it. It was in the - # bundle as a dependency of steep alone, and so not without that group. - gem 'csv', require: false gem 'overcommit', require: false gem 'rake', require: false gem 'rspec', '~> 3.13' diff --git a/Gemfile.lock b/Gemfile.lock index fc6b4ca..ba12f34 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -191,7 +191,6 @@ PLATFORMS x86_64-linux-musl DEPENDENCIES - csv irb overcommit rake diff --git a/README.md b/README.md index 4f3ed44..1ebf81d 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ end The sections below cover [creating a client](#creating-a-client), [records](#working-with-records), [collections](#collections) and -[error handling](#error-handling). Runnable scripts live in [`examples/`](examples/README.md). +[error handling](#error-handling). ## Creating a client @@ -682,10 +682,64 @@ A resource of your own needs an annotation: roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role] ``` -## Examples +## Recipes -Runnable scripts covering pagination, pattern matching, acting on behalf of a user, -attachments, error handling and threaded use live in [`examples/`](examples/README.md). +### Resuming a long read + +Keep the page number yourself when a job has to survive being interrupted. Save it once a +page is handled, so a rerun repeats at most one page: + +```ruby +page = File.exist?('cursor') ? Integer(File.read('cursor')) : 1 + +loop do + tickets = client.tickets.page(page, per_page: 50).to_a + break if tickets.empty? + + import(tickets) + + page += 1 + File.write('cursor', page) +end +``` + +A page number is a position, so this suits a list that only grows: tickets are served in +id order, and new ones arrive at the end. + +`in_batches` without a block is an Enumerator, for pulling one page at a time as a +consumer is ready: `pages = client.tickets.in_batches(of: 50)`, then `pages.next`. + +### Sharing one client between threads + +A client is immutable, so one instance serves every thread, and an `on_behalf_of` scope in +one thread cannot leak into another. In Rails, build it once in an initializer: + +```ruby +# config/initializers/zammad.rb +ZAMMAD = ZammadAPI::Client.new( + url: Rails.application.credentials.zammad_url, + http_token: Rails.application.credentials.zammad_token, + logger: Rails.logger +) +``` + +A worker pool shares it the same way: + +```ruby +queue = Queue.new +client.tickets.first(40).each { queue << it.id } +queue.close + +workers = Array.new(4) do + Thread.new do + while (id = queue.pop) + sync(client.tickets.find(id)) + end + end +end + +workers.each(&:join) +``` ## Development diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index 763e7df..0000000 --- a/examples/README.md +++ /dev/null @@ -1,41 +0,0 @@ -# Examples - -Runnable scripts showing how the 2.0 API works in a real project. Each one is -self-contained and builds its client with `ZammadAPI::Client.from_env`, which -reads the credentials from the environment: - -```sh -export ZAMMAD_URL=https://zammad.example.com/ -export ZAMMAD_TOKEN=your-access-token - -bundle exec ruby examples/quickstart.rb -``` - -Run from a checkout of this repository, they go through Bundler, which is what puts -`lib/` on the load path: plain `ruby` would load an installed release of the gem, 1.x -included, or none. Copied into a project that has `zammad_api` 2.0 in its bundle, they -run there the same way. `ticket_report.rb` also needs `gem 'csv'` in that bundle: `csv` is -a bundled gem from Ruby 3.4 on, and `zammad_api` does not depend on it. - -`ZAMMAD_USER` and `ZAMMAD_PASSWORD` work instead of a token, as does -`ZAMMAD_OAUTH2_TOKEN`. - -> These scripts **create, modify and delete records**. Point them at a -> disposable instance. - -None of them set a timeout or a retry policy: requests time out after 60s and -a read that fails transiently is retried with backoff out of the box, so the -examples show what is left for your own code to do. A write is never repeated; -`error_handling.rb` shows what that leaves to you. - -| Script | What it does | API features it shows | -| ------ | ------------ | --------------------- | -| [`quickstart.rb`](quickstart.rb) | Creates a ticket, reads it back, adds an article, updates it | The basics end to end | -| [`pagination.rb`](pagination.rb) | Reads a collection every available way | `each`, `find_each`, `in_batches`, `page(n, per_page: m)`, `search`, `order`, `count`, `empty?`, `lazy`, `first(n)`, `detect`, collection immutability | -| [`manual_batches.rb`](manual_batches.rb) | Drives pagination by hand: pull-based, numbered, resumable | `in_batches` as an Enumerator (`next`, `with_index`), an explicit `page(n, per_page: m)` loop with a persisted cursor | -| [`ticket_report.rb`](ticket_report.rb) | Exports every ticket to CSV | Automatic pagination, `in_batches` batching, `fetch` for required attributes | -| [`triage_tickets.rb`](triage_tickets.rb) | Flags urgent tickets, nudges stale ones | `search`, `case/in` pattern matching on records, staged `changes` so only diffs are sent, `add_article` | -| [`onboard_customer.rb`](onboard_customer.rb) | Creates an organization, a user, and a welcome ticket raised as that user | `find_by`, `create`, `on_behalf_of` as a scoped client and as a block | -| [`download_attachments.rb`](download_attachments.rb) | Saves a ticket's attachments to disk | `articles`, attachment metadata, binary-safe `download` | -| [`error_handling.rb`](error_handling.rb) | Handles the failures that are yours to handle | The error hierarchy, `save` → `false` with `record.error`, rescuing by category, `client.with` for different retry settings | -| [`concurrent_sync.rb`](concurrent_sync.rb) | Syncs tickets with a worker pool sharing one client | Immutable clients are thread-safe; also sketches the Rails initializer pattern | diff --git a/examples/concurrent_sync.rb b/examples/concurrent_sync.rb deleted file mode 100755 index 45073f3..0000000 --- a/examples/concurrent_sync.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Syncs tickets from a worker pool that shares a single client. -# -# A client is immutable once built, so one instance is safe to share between -# threads: no locking, no client per thread, and `on_behalf_of` scoping in one -# thread cannot leak into another. It is the same reason one client works as a -# Rails initializer constant used from every background worker: -# -# # config/initializers/zammad.rb -# ZAMMAD = ZammadAPI::Client.new( -# url: Rails.application.credentials.zammad_url, -# http_token: Rails.application.credentials.zammad_token, -# logger: Rails.logger -# ) -# -# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# bundle exec ruby examples/concurrent_sync.rb - -require 'zammad_api' - -WORKERS = 4 - -client = ZammadAPI::Client.from_env - -# Collect the work first; `first` stops paginating once it has enough. -queue = Queue.new -client.tickets.all.first(40).each { queue << it.id } -queue.close # so a worker draining an empty queue stops instead of blocking - -results = Queue.new - -workers = Array.new(WORKERS) do - Thread.new do - # Every worker shares this one client. Nothing about it is mutated by - # making a request, so there is nothing to synchronise. - while (id = queue.pop) - results << begin - client.tickets.find(id) - :ok - rescue ZammadAPI::Error => e - # Transient failures were already retried, so anything arriving here - # is worth reporting rather than trying again. - warn "ticket #{id}: #{e.class}" - :failed - end - end - end -end - -workers.each(&:join) - -tally = Hash.new(0) -tally[results.pop] += 1 until results.empty? - -puts "synced #{tally[:ok]}, failed #{tally[:failed]}" diff --git a/examples/download_attachments.rb b/examples/download_attachments.rb deleted file mode 100755 index 1b441b8..0000000 --- a/examples/download_attachments.rb +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Saves every attachment of a ticket to a directory. -# -# Shows walking articles, attachment metadata, and binary-safe downloads. -# -# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# bundle exec ruby examples/download_attachments.rb 12345 ./downloads - -require 'zammad_api' -require 'fileutils' - -client = ZammadAPI::Client.from_env - -ticket_id = Integer(ARGV.fetch(0) { abort "usage: #{$PROGRAM_NAME} TICKET_ID [DIRECTORY]" }) -directory = ARGV.fetch(1, "ticket-#{ticket_id}") - -ticket = client.tickets.find(ticket_id) -FileUtils.mkdir_p(directory) - -# The filename comes from the server, so `File.basename` strips any directory -# part that would otherwise let `../` escape the download directory. The ids -# keep two same-named attachments from overwriting each other. -def safe_filename(article_id, attachment) - name = File.basename(attachment.filename.to_s) - name = 'attachment' if name.empty? || name.start_with?('.') - "#{article_id}-#{attachment.id}-#{name}" -end - -saved = 0 - -ticket.articles.each do |article| - article.attachments.each do |attachment| - # `download` returns the bytes as ASCII-8BIT, so images and archives - # survive intact. - contents = attachment.download - File.binwrite(File.join(directory, safe_filename(article.id, attachment)), contents) - saved += 1 - - puts format('%-40s %8d bytes', file: attachment.filename, size: contents.bytesize) - end -end - -puts saved.zero? ? "Ticket ##{ticket.number} has no attachments." : "Saved #{saved} file(s) to #{directory}/" diff --git a/examples/error_handling.rb b/examples/error_handling.rb deleted file mode 100755 index 1854ab4..0000000 --- a/examples/error_handling.rb +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# What to rescue, and what the client has already handled for you. -# -# Timeouts, connection failures and the transient statuses (429, 500, 502, -# 503, 504) are retried with backoff on a GET before any error reaches your -# code. A write is never repeated, because only you know whether sending it -# twice is safe. So what is left to handle is what only you can decide about: -# a missing record, a rejected attribute, bad credentials, a write that may or -# may not have arrived. -# -# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# bundle exec ruby examples/error_handling.rb - -require 'zammad_api' - -# Options are validated up front, before any request is made. -begin - ZammadAPI::Client.new(url: 'not-a-url', http_token: 'x') -rescue ZammadAPI::ConfigurationError => e - puts "rejected early: #{e.message}" -end - -client = ZammadAPI::Client.from_env - -# A missing record is a decision to make, not a failure to retry. -ticket = begin - client.tickets.find(0) -rescue ZammadAPI::NotFoundError - nil -end - -puts "missing ticket: #{ticket.inspect}" - -# A rejected attribute (422) makes `save` return false and leaves the reason -# on the record, so branching needs no begin/rescue. -group = client.groups.new(name: '') - -if group.save - puts "created group: #{group.id}" -else - puts "rejected save: #{group.error.status} #{group.error.server_message}" - puts " body #{group.error.body.inspect}" - puts " operation #{group.error.operation} on #{group.error.resource_class}" -end - -# `create` and `save!` raise instead, which is what a script wants. -begin - client.groups.create(name: '') -rescue ZammadAPI::ValidationError => e - puts "raised instead: #{e.class}" -end - -# Rescue by category where the exact class does not matter. -begin - client.tickets.find(0) -rescue ZammadAPI::ClientError => e # any 4xx - puts "client error: #{e.status}" -rescue ZammadAPI::ServerError => e # any 5xx, including an HTML proxy page - puts "server error: #{e.status}" -rescue ZammadAPI::TransportError => e # no answer arrived, retries spent - puts "transport error: #{e.message}" -end - -# Or catch everything this gem raises in one place. -begin - client.tickets.find(0) -rescue ZammadAPI::Error => e - puts "any gem error: #{e.class}" -end - -# Where the defaults do not suit the job, change them once on a derived -# client instead of writing a retry loop around every call. -patient = client.with(retries: 5, retry_interval: 1) - -puts "derived client: #{patient.config.retries} retries, original still #{client.config.retries}" diff --git a/examples/manual_batches.rb b/examples/manual_batches.rb deleted file mode 100755 index 53bdd67..0000000 --- a/examples/manual_batches.rb +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Driving pagination yourself, for when the loop is not yours to own: a job -# that has to checkpoint and resume, or a producer feeding a queue. -# -# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# bundle exec ruby examples/manual_batches.rb - -require 'zammad_api' -require 'fileutils' -require 'tmpdir' - -PER_PAGE = 50 -CURSOR = File.join(Dir.tmpdir, 'zammad_batch_cursor') - -client = ZammadAPI::Client.from_env -tickets = client.tickets.all - -# 1. Pull a page when you are ready for it ----------------------------------- -# -# `in_batches` without a block is an Enumerator: nothing is fetched until -# `next`, and each `next` costs one request. - -puts '1. pulling two pages, leaving the rest unfetched' - -pages = tickets.in_batches(of: PER_PAGE) - -2.times do - puts " pulled #{pages.next.size} tickets" -rescue StopIteration - break -end - -# 2. Numbered batches -------------------------------------------------------- - -puts '2. every batch, numbered' - -tickets.in_batches(of: PER_PAGE).with_index do |batch, index| - puts " batch #{index}: #{batch.size} tickets" -end - -# 3. A resumable page loop --------------------------------------------------- -# -# Own the page number when the job has to survive being interrupted. The -# checkpoint is written once a page is handled, so a rerun repeats at most -# one page. A page number is a position, so this suits a set that only grows: -# tickets are served in id order, and new ones arrive at the end. - -puts '3. resumable page loop' - -page = File.exist?(CURSOR) ? Integer(File.read(CURSOR)) : 1 -puts " starting at page #{page}" - -loop do - batch = tickets.page(page, per_page: PER_PAGE).to_a - break if batch.empty? - - puts " page #{page}: #{batch.size} tickets" - - page += 1 - File.write(CURSOR, page) -end - -FileUtils.rm_f(CURSOR) - -puts <<~NOTE - - Which to reach for: - - each / find_each the loop is yours and runs to completion - in_batches you want one whole response at a time - in_batches.next you want to pull batches as a consumer is ready - in_batches.with_index you want the batches numbered as they arrive - page(n, per_page: m) the page number must be persisted, retried or skipped - - Pacing is not on this list: the client already backs off and retries a 429. -NOTE diff --git a/examples/onboard_customer.rb b/examples/onboard_customer.rb deleted file mode 100755 index ec54cae..0000000 --- a/examples/onboard_customer.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Onboards a new customer: organization, user, and a welcome ticket raised as -# that user. -# -# Shows `find_by` for a lookup by attribute, `create`, and `on_behalf_of` both -# as a scoped client and as a block. -# -# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# bundle exec ruby examples/onboard_customer.rb "Acme Inc" jane@acme.test Jane Doe - -require 'zammad_api' - -abort "usage: #{$PROGRAM_NAME} COMPANY EMAIL FIRSTNAME LASTNAME" if ARGV.size < 4 - -company, email, firstname, lastname = ARGV -email = email.downcase # Zammad stores addresses in lower case, and find_by matches exactly - -client = ZammadAPI::Client.from_env - -# `find_by` returns the first record carrying exactly these values, or nil. -organization = client.organizations.find_by(name: company) || client.organizations.create(name: company) - -puts "organization: #{organization.name} (id=#{organization.id})" - -user = client.users.find_by(email: email) || client.users.create( - firstname: firstname, - lastname: lastname, - email: email, - organization_id: organization.id, - roles: ['Customer'] -) - -puts "user: #{user.firstname} #{user.lastname} <#{user.email}> (id=#{user.id})" - -# `on_behalf_of` returns a new client rather than changing this one, so the -# admin client stays unscoped. -as_customer = client.on_behalf_of(user.email) - -ticket = as_customer.tickets.create( - title: "Welcome, #{firstname}!", - group: 'Users', - customer: user.email, - article: { - subject: 'Getting started', - body: "Hi #{firstname},\n\nyour account is ready.", - type: 'note' - } -) - -puts "ticket: ##{ticket.number} raised as #{user.email}" - -# The block form scopes a single operation. -own_tickets = client.on_behalf_of(user.email) { |scoped| scoped.tickets.all.count } - -puts "the customer can see #{own_tickets} ticket(s) of their own" diff --git a/examples/pagination.rb b/examples/pagination.rb deleted file mode 100755 index 12992f5..0000000 --- a/examples/pagination.rb +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Every way to read a collection, and what each one costs. -# -# Collections are lazy: nothing is fetched until you iterate, and only the -# pages you actually consume are fetched. A request carries as many records as -# the endpoint serves - 100 for tickets, 200 for a search, 1000 for the other -# index endpoints - unless a call asks for another size. -# -# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# bundle exec ruby examples/pagination.rb - -require 'zammad_api' - -client = ZammadAPI::Client.from_env -tickets = client.tickets.all # no request yet - -# Walk every record. Pages are fetched as the iteration reaches them, so only -# one page is ever held in memory. -seen = 0 -tickets.each { seen += 1 } -puts "each #{seen} tickets, one request per page" - -# The same walk with the page size chosen for the job at hand. -ids = [] -tickets.find_each(batch_size: 50) { ids << it.id } -puts "find_each #{ids.size} tickets, 50 per request" - -# One whole page per block call, for work that batches: an import, a bulk -# insert, a push onto a queue. -sizes = [] -tickets.in_batches(of: 50) { sizes << it.size } -puts "in_batches pages of #{sizes.inspect}" - -# Stop early and the remaining pages are never fetched. -puts "first(3) #{tickets.first(3).map(&:id).inspect}, one request, for three records" -puts "lazy.select #{tickets.lazy.select { it.state == 'open' }.first(2).map(&:id).inspect}" -puts "detect ##{tickets.detect { it.state == 'open' }&.number}, stops at the match" - -# One specific page, when you are driving the paging yourself. -puts "page(2, per_page: 10) #{tickets.page(2, per_page: 10).map(&:id).inspect}" - -# Narrowing by a value is `search`: Zammad's index endpoints sort and page and -# drop every other parameter, so there is no filter to pass them. Searches -# compose with all of the above. -puts "search #{client.tickets.search('state.name:open').first(5).size} open tickets" - -# `order` sorts on the server. A search sorts for every resource; of the index -# endpoints, the ticket and user ones are always served in id order. -newest = client.tickets.search('state.name:open').order(created_at: :desc).first -puts "search.order ##{newest&.number}, the most recently created open ticket" -puts "order #{client.groups.order(:name).first(3).map(&:name).inspect}" - -# Counting a search is one request, because Zammad can answer `only_total_count` -# without serving the records. An index endpoint has no answer for it and no -# total to report, so counting one means walking it. -puts "search.count #{client.tickets.search('state.name:open').count}, one request" -puts "empty? #{client.tickets.search('state.name:merged').empty?}, asks for a single record" - -# `search`, `order` and `page` return a new collection, so scoping one never -# disturbs the original. -puts "page(2) is new #{!tickets.page(2).equal?(tickets)}, tickets still reads every page" - -puts <<~NOTE - - Upgrading from 1.x: `each` used to fetch a single page, so iterating a - collection silently stopped at 100 records. It now walks every page. Ask - for one page explicitly with `page(1, per_page: 100)` where that is what you - wanted. -NOTE diff --git a/examples/quickstart.rb b/examples/quickstart.rb deleted file mode 100755 index 338c9f8..0000000 --- a/examples/quickstart.rb +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# The basics, end to end: create a ticket, read it back, add an article and -# update it. -# -# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# bundle exec ruby examples/quickstart.rb - -require 'zammad_api' - -client = ZammadAPI::Client.from_env - -# `me` answers for any account. `client.version` would name the Zammad -# version as well, but Zammad serves it to administrators only, and an -# agent's token is answered with ZammadAPI::AuthorizationError. -puts "connected to #{client.config.url} as #{client.me.email}" - -# Create a ticket together with its first article. -ticket = client.tickets.create( - title: 'Cannot log in', - group: 'Users', - customer: 'nicole.braun@zammad.org', - article: { - subject: 'Cannot log in', - body: "Hi,\n\nmy password stopped working.", - type: 'note' - } -) - -puts "created ##{ticket.number} - #{ticket.title}" - -# Read it back. Associations come expanded, so these are plain attribute -# reads rather than further requests. -ticket = client.tickets.find(ticket.id) -puts "state #{ticket.state}, priority #{ticket.priority}, group #{ticket.group}" - -# Add another article. -ticket.add_article(subject: 'Update', body: 'Reset link sent.', type: 'note') -puts "#{ticket.articles.size} article(s)" - -# Assignments are staged, and `save` sends only what changed. It answers -# false, with the reason in `error`, where Zammad rejects the change as -# invalid (a 422). Any other failure raises: a 403 as -# ZammadAPI::AuthorizationError, for one. -ticket.priority = '3 high' -puts "sending #{ticket.changes.inspect}" -abort "Zammad rejected the change: #{ticket.error.message}" if !ticket.save - -# Collections paginate themselves, and `first` stops as soon as it has enough. -client.tickets.search('state.name:open').first(5).each do |open_ticket| - puts "open: ##{open_ticket.number} #{open_ticket.title}" -end diff --git a/examples/ticket_report.rb b/examples/ticket_report.rb deleted file mode 100755 index e95f999..0000000 --- a/examples/ticket_report.rb +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Exports every ticket to CSV. -# -# Shows automatic pagination with `in_batches`, and `fetch` for an attribute -# that has to be there. The defaults carry a long export on their own: a -# request times out after 60s, and transient failures are retried with -# backoff before any error reaches this script. -# -# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# bundle exec ruby examples/ticket_report.rb tickets.csv -# -# `csv` is a bundled gem from Ruby 3.4 on, and `zammad_api` does not depend -# on it: a project this is copied into needs `gem 'csv'` in its Gemfile. - -require 'zammad_api' -require 'csv' - -client = ZammadAPI::Client.from_env -destination = ARGV.fetch(0, 'tickets.csv') -exported = 0 - -# A spreadsheet reads a cell starting with =, +, -, @, tab or CR as a formula, -# and a ticket title is whatever the customer typed. An apostrophe keeps every -# exported cell text. -def csv_safe(value) - text = value.to_s - text.match?(/\A[=+\-@\t\r]/) ? "'#{text}" : text -end - -CSV.open(destination, 'w') do |csv| - csv << %w[id number title state priority group customer created_at] - - # Nothing is loaded until the block runs, and each call is one page. - client.tickets.all.in_batches(of: 100) do |tickets| - tickets.each do |ticket| - row = [ - ticket.fetch(:id), # raises KeyError if it is missing - ticket.number, - ticket.title, - ticket.state, # present because associations come expanded - ticket.priority, - ticket.group, - ticket.customer, - ticket.created_at - ] - - csv << row.map { csv_safe(it) } - end - - exported += tickets.size - warn "exported #{exported} tickets..." - end -end - -puts "Wrote #{exported} tickets to #{destination}" diff --git a/examples/triage_tickets.rb b/examples/triage_tickets.rb deleted file mode 100755 index 959865e..0000000 --- a/examples/triage_tickets.rb +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Triages open tickets: flags the urgent ones, nudges the stale ones. -# -# Shows `search`, pattern matching against records, staged changes so only -# what was modified is sent, and adding an article. -# -# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=... \ -# bundle exec ruby examples/triage_tickets.rb - -require 'zammad_api' -require 'time' - -STALE_AFTER = 7 * 24 * 60 * 60 # a week, in seconds - -client = ZammadAPI::Client.from_env -flagged = 0 -nudged = 0 - -# Oldest first: a search is served newest-updated first, so without the -# order the 200 read would be the freshest, and on an instance with more -# open tickets than that the stale ones would never be looked at. `first` -# stops paginating as soon as it has what it asked for. -client.tickets.search('state.name:open').order(updated_at: :asc).first(200).each do |ticket| - # Records implement `deconstruct_keys`, so case/in works on them. - case ticket - in { priority: '3 high', owner_id: 1 } # 1 is Zammad's "-", i.e. unassigned - puts "unassigned and high priority: ##{ticket.number} #{ticket.title}" - flagged += 1 - - in { updated_at: String => updated } if Time.now - Time.parse(updated) > STALE_AFTER - puts "stale: ##{ticket.number} #{ticket.title}" - - ticket.priority = '3 high' - # Sends the one changed attribute, nothing else. A change Zammad rejects - # as invalid (a 422) comes back as false rather than raising, so it is - # checked: an unchecked save carries on as if the priority had been - # raised. Any other failure, such as a 403, raises. - if !ticket.save - warn " could not raise the priority of ##{ticket.number}: #{ticket.error.message}" - next - end - - ticket.add_article( - subject: 'Automated follow-up', - body: "No activity for over #{STALE_AFTER / 86_400} days; priority raised.", - type: 'note', - internal: true - ) - nudged += 1 - - else - next - end -end - -puts "\n#{flagged} ticket(s) flagged, #{nudged} nudged." From 1ca8c2958cb76da0b93263101c2ae38373b163f7 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:34:35 +0200 Subject: [PATCH 106/121] refactor: drop the symbolize_keys switch from DeepCopy.frozen_copy Its one caller always passed true. --- lib/zammad_api/attribute_access.rb | 2 +- lib/zammad_api/deep_copy.rb | 13 ++++++------- sig/zammad_api/deep_copy.rbs | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb index 9b03170..aaa86db 100644 --- a/lib/zammad_api/attribute_access.rb +++ b/lib/zammad_api/attribute_access.rb @@ -116,6 +116,6 @@ def write_attribute(key, _value) raise NoMethodError, "#{self.class.name} attributes are read-only (tried to set #{key})" end - def frozen_attributes(value) = DeepCopy.frozen_copy(value, symbolize_keys: true) + def frozen_attributes(value) = DeepCopy.frozen_copy(value) end end diff --git a/lib/zammad_api/deep_copy.rb b/lib/zammad_api/deep_copy.rb index 3a88b99..05846ae 100644 --- a/lib/zammad_api/deep_copy.rb +++ b/lib/zammad_api/deep_copy.rb @@ -8,17 +8,16 @@ module DeepCopy module_function # A frozen deep copy, so a record's attributes cannot change behind its - # back. Strings are copied before they are frozen, so the caller's own - # values are left alone. + # back. Hash keys become Symbols, so that caller-supplied attributes + # behave the same as decoded responses. Strings are copied before they + # are frozen, so the caller's own values are left alone. # # @param value [Object] - # @param symbolize_keys [Boolean] whether Hash keys become Symbols, so - # that caller-supplied attributes behave the same as decoded responses # @return [Object] a frozen copy - def frozen_copy(value, symbolize_keys: false) + def frozen_copy(value) case value - when Hash then value.to_h { |key, nested| [symbolize_keys ? symbolize(key) : key, frozen_copy(nested, symbolize_keys: symbolize_keys)] }.freeze - when Array then value.map { frozen_copy(it, symbolize_keys: symbolize_keys) }.freeze + when Hash then value.to_h { |key, nested| [symbolize(key), frozen_copy(nested)] }.freeze + when Array then value.map { frozen_copy(it) }.freeze when String then value.dup.freeze else value end diff --git a/sig/zammad_api/deep_copy.rbs b/sig/zammad_api/deep_copy.rbs index 09526b8..6e5d4cd 100644 --- a/sig/zammad_api/deep_copy.rbs +++ b/sig/zammad_api/deep_copy.rbs @@ -1,6 +1,6 @@ module ZammadAPI module DeepCopy - def self?.frozen_copy: (untyped value, ?symbolize_keys: bool) -> untyped + def self?.frozen_copy: (untyped value) -> untyped def self?.writable_copy: (untyped value) -> untyped def self?.symbolize: (untyped key) -> untyped end From 3b35a37e388368e331e0f93df2c50c73341e28cf Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:35:30 +0200 Subject: [PATCH 107/121] refactor: one redaction constant, and no constant for the 2xx range Transport::REDACTED held the same string as Config::REDACTION, and Response::SUCCESS_STATUSES had one reader. --- lib/zammad_api/config.rb | 2 +- lib/zammad_api/response.rb | 4 +--- lib/zammad_api/transport.rb | 5 +---- sig/zammad_api/response.rbs | 1 - sig/zammad_api/transport.rbs | 1 - 5 files changed, 3 insertions(+), 10 deletions(-) diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb index 0a53878..ecbaa2f 100644 --- a/lib/zammad_api/config.rb +++ b/lib/zammad_api/config.rb @@ -78,7 +78,7 @@ class Config # Value of the +User-Agent+ header unless one is configured. DEFAULT_USER_AGENT = "zammad_api-ruby/#{ZammadAPI::VERSION}".freeze - # What {#inspect} prints in place of a credential. + # What {#inspect} and the log show in place of a credential. REDACTION = '[REDACTED]' # The options of each way to authenticate. diff --git a/lib/zammad_api/response.rb b/lib/zammad_api/response.rb index d652894..1ca2816 100644 --- a/lib/zammad_api/response.rb +++ b/lib/zammad_api/response.rb @@ -20,10 +20,8 @@ module ZammadAPI Response = Data.define(:status, :headers, :body, :raw_body) class Response - SUCCESS_STATUSES = (200..299) - # @return [Boolean] whether the status code is in the 2xx range - def success? = SUCCESS_STATUSES.cover?(status) + def success? = status.between?(200, 299) # Decodes a JSON body with symbol keys. Anything else - a proxy error page, # a file download, a body that does not parse - is handed back as it is. diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 468ef88..1e68e89 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -28,9 +28,6 @@ class Transport # name, as Zammad's own log filter does, so +monkey_id+ is hidden too. SENSITIVE_KEY_PATTERN = /passw|pwd|bind_pw|passphrase|secret|token|credential|cookie|authorization|key|otp|salt/i - # What the log shows in place of a sensitive value. - REDACTED = '[REDACTED]' - # A path that opens with a scheme, which Faraday would send to that host. ABSOLUTE_URL = /\A[a-z][a-z0-9+.-]*:/i private_constant :ABSOLUTE_URL @@ -83,7 +80,7 @@ def self.redact_path(path) = path.to_s.sub(/[?#].*/m, '') # @return [Object] def self.redact(value) case value - when Hash then value.to_h { |key, nested| [key, SENSITIVE_KEY_PATTERN.match?(key.to_s) ? REDACTED : redact(nested)] } + when Hash then value.to_h { |key, nested| [key, SENSITIVE_KEY_PATTERN.match?(key.to_s) ? Config::REDACTION : redact(nested)] } when Array then value.map { redact(it) } else value end diff --git a/sig/zammad_api/response.rbs b/sig/zammad_api/response.rbs index 2b47905..2feb30e 100644 --- a/sig/zammad_api/response.rbs +++ b/sig/zammad_api/response.rbs @@ -7,7 +7,6 @@ module ZammadAPI attr_reader raw_body: String def self.new: (status: Integer, headers: Hash[String, String], body: untyped, raw_body: String) -> instance - SUCCESS_STATUSES: Range[Integer] def self.decode_body: (String?, String) -> untyped diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs index bd1f5f5..ab652c3 100644 --- a/sig/zammad_api/transport.rbs +++ b/sig/zammad_api/transport.rbs @@ -12,7 +12,6 @@ module ZammadAPI RETRIABLE_STATUSES: Array[Integer] RETRIABLE_EXCEPTIONS: Array[untyped] SENSITIVE_KEY_PATTERN: Regexp - REDACTED: String # private_constant in the source; RBS has no way to say so. ABSOLUTE_URL: Regexp From 87e1eaa6c46f140eba6f79d8c6e6c755030a60ba Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:36:14 +0200 Subject: [PATCH 108/121] Chore: drop four RuboCop exemptions nothing uses Enabling Style/ClassAndModuleChildren, Style/PerlBackrefs, Style/BlockComments and Performance/Casecmp reports no offense. --- .rubocop.yml | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index feb48e9..fe861e4 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -39,9 +39,6 @@ Layout/HashAlignment: EnforcedColonStyle: table EnforcedLastArgumentHashStyle: always_inspect -Style/ClassAndModuleChildren: - Enabled: false - Naming/MethodParameterName: # `of` is ActiveRecord's name for a batch size, see Collection#in_batches. AllowedNames: [id, to, of] @@ -73,13 +70,6 @@ Style/Documentation: Description: 'Public API documentation is enforced by review, not by this cop.' Enabled: false -Style/PerlBackrefs: - Enabled: false - -Style/BlockComments: - Description: 'Block comments make examples easy to copy and paste.' - Enabled: false - Layout/LineLength: Enabled: false @@ -103,11 +93,6 @@ Metrics/ParameterLists: Max: 16 MaxOptionalParameters: 15 -# Broken: "String".downcase == "strinG".downcase is not the same as -# "String".casecmp("strinG"), only as "String".casecmp("strinG") == 0. -Performance/Casecmp: - Enabled: false - # --- Specs ------------------------------------------------------------------ RSpec/ExampleLength: From 9ff9fd5b5b61cc96834e2ba9164cef555f2cd3c7 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:40:28 +0200 Subject: [PATCH 109/121] Refactor: forward the collection shorthands by hand def_delegators hid order, each, find_each, in_batches, page, pluck, count, empty? and first from YARD, so the API reference for client. listed none of them. Written out, each takes its documentation from the Collection method it forwards to. Forwardable goes with it, and so does sig/vendor/internal.rbs, which existed to tell Steep about it. Four of the forwards carry a Steep ignore: the block or count they hand on may be nil. --- Steepfile | 23 +++++++------------ lib/zammad_api/resource_proxy.rb | 38 +++++++++++++++++++++++++++----- sig/vendor/internal.rbs | 14 ------------ zammad_api.gemspec | 5 ++--- 4 files changed, 42 insertions(+), 38 deletions(-) delete mode 100644 sig/vendor/internal.rbs diff --git a/Steepfile b/Steepfile index 6efc07c..19cf55c 100644 --- a/Steepfile +++ b/Steepfile @@ -4,12 +4,10 @@ target :lib do signature 'sig' check 'lib' - # forwardable is here for the collection shorthands ResourceProxy delegates - # to Collection; uri is here for the parse Config makes of the instance url - # and the escaping of record ids. Neither is named in the signatures the - # gem publishes - see sig/vendor/internal.rbs - so this does not add - # anything a consumer has to load. - library 'json', 'logger', 'timeout', 'forwardable', 'uri' + # uri is here for the parse Config makes of the instance url and the + # escaping of record ids. The signatures the gem publishes do not name it, + # so this does not add anything a consumer has to load. + library 'json', 'logger', 'timeout', 'uri' configure_code_diagnostics do |hash| # Default keyword-argument hashes such as `attributes = {}` cannot be @@ -24,17 +22,12 @@ end # # sig/vendor is in here, although a consumer does not have it, because Steep # hands a signature file to every target of a project whatever the target's -# own pattern says. Listing only the published directories left this target -# with sig/vendor/internal.rbs all the same and without the library it names, -# so its signatures failed to load and Steep then skips the source files of -# such a target without a word: the check passed having checked nothing. That -# the published signatures stand on their own is what `rake rbs_published` -# establishes. +# own pattern says. That the published signatures stand on their own is what +# `rake rbs_published` establishes. target :usage do signature 'sig', 'spec/typed/sig' check 'spec/typed' - # logger is the one library the published signatures name; forwardable is - # here for sig/vendor/internal.rbs. - library 'logger', 'forwardable' + # logger is the one library the published signatures name. + library 'logger' end diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb index 6986a6f..50c99a1 100644 --- a/lib/zammad_api/resource_proxy.rb +++ b/lib/zammad_api/resource_proxy.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require 'forwardable' - module ZammadAPI # Entry point for working with one kind of Zammad record. # @@ -28,7 +26,6 @@ module ZammadAPI # block form. class ResourceProxy include Enumerable - extend Forwardable # @return [Class] the resource class this proxy operates on attr_reader :resource_class @@ -136,9 +133,38 @@ def destroy(id) # @return [Collection] def all = Collection.new(@transport, resource_class) - # @!group Collection shorthands - # These forward to {#all}; see {Collection} for each. - def_delegators :all, :order, :each, :find_each, :in_batches, :page, :pluck, :count, :empty?, :first + # @!group Collection shorthands, each forwarded to {#all} + + # A forward hands on a block or a count that may be nil, which is what picks + # the overload on the collection, and Steep cannot follow that through. + + # (see Collection#order) + def order(*attributes, **directions) = all.order(*attributes, **directions) + + # (see Collection#each) + def each(&block) = all.each(&block) # steep:ignore BlockTypeMismatch + + # (see Collection#find_each) + def find_each(batch_size: nil, &block) = all.find_each(batch_size: batch_size, &block) # steep:ignore BlockTypeMismatch + + # (see Collection#in_batches) + def in_batches(of: nil, &block) = all.in_batches(of: of, &block) # steep:ignore BlockTypeMismatch + + # (see Collection#page) + def page(number, per_page: nil) = all.page(number, per_page: per_page) + + # (see Collection#pluck) + def pluck(*keys) = all.pluck(*keys) + + # (see Collection#count) + def count(...) = all.count(...) + + # (see Collection#empty?) + def empty? = all.empty? + + # (see Collection#first) + def first(count = nil) = all.first(count) # steep:ignore ArgumentTypeMismatch + # @!endgroup # Records matching a Zammad search term, as a lazily paginated collection. diff --git a/sig/vendor/internal.rbs b/sig/vendor/internal.rbs deleted file mode 100644 index 620fdc7..0000000 --- a/sig/vendor/internal.rbs +++ /dev/null @@ -1,14 +0,0 @@ -# Declarations that hold only while this repository is type-checked, and are -# deliberately not part of what the gem publishes. -# -# ResourceProxy forwards the collection shorthands with Forwardable, so the -# type checker has to know the class extends it before it can see -# `def_delegators` on the singleton. Consumers never need that: the published -# signatures declare each forwarded method concretely, which is what a caller -# is checked against, and naming Forwardable there would make `rbs validate` -# fail for anyone who has not loaded the stdlib declarations for it. -module ZammadAPI - class ResourceProxy[R < Resources::Base] - extend Forwardable - end -end diff --git a/zammad_api.gemspec b/zammad_api.gemspec index e79fd93..5ad9f63 100644 --- a/zammad_api.gemspec +++ b/zammad_api.gemspec @@ -41,9 +41,8 @@ Gem::Specification.new do |spec| spec.metadata['documentation_uri'] = "https://rubydoc.info/gems/zammad_api/#{ZammadAPI::VERSION}" spec.metadata['rubygems_mfa_required'] = 'true' - # sig/vendor holds the declarations that exist only for this repository's own - # type checking - stand-ins for dependencies that ship none, and the internal - # ones in sig/vendor/internal.rbs - and must not be published. + # sig/vendor holds stand-ins for dependencies that ship no signatures. They + # exist only for this repository's own type checking and are not published. spec.files = Dir['lib/**/*.rb', 'sig/**/*.rbs'].grep_v(%r{\Asig/vendor/}) + %w[ CHANGELOG.md LICENSE.AGPL.txt From 05c6fabc1a4a1176df8c475bac9224d448b07cf3 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:40:56 +0200 Subject: [PATCH 110/121] Docs: drop three changelog entries that compare to a draft 1.x had no per, where or find_by, so "there is no per", "there is no where" and a breaking change to find_by described earlier drafts of 2.0. The entry that adds find_by now says which value it searches. --- CHANGELOG.md | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd440bf..7a85bcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,9 +35,6 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `Collection#[]` was removed. It cost a request per index and ignored the page a collection was limited to; use `first`, or `page(n, per_page: 1).first` for one record at an offset. -- There is no `per`. The page size belongs to the call that reads: `find_each(batch_size:)` - to walk, `in_batches(of:)` to batch, `page(number, per_page:)` for one page. Everything else - fetches as many records as the endpoint serves. - A collection fetches the endpoint's own page size rather than a fixed 100 — 1000 on the index endpoints, 100 on `/api/v1/tickets`, 200 on a search. `page(n)` without `per_page:` is a page of that size, so pin it with `page(n, per_page: 100)` where a persisted page @@ -93,9 +90,6 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a `Enumerable#find`, whose argument is an ifnone callable, so `client.tickets.all.find(1)` answered with an `Enumerator` and made no request. Use `client.tickets.find(1)`, or `detect { … }` for the block form. -- `find_by` searches one string value, the longest, and compares every value against the - hits. A lookup with no string in it, or on a resource without a search endpoint, walks - the index instead. - `search` raises `ZammadAPI::Error` on a resource Zammad routes no search endpoint for — `ticket_states`, `ticket_priorities` and `ticket_articles` — instead of reaching a 404. - A configuration that names more than one way to authenticate raises `ConfigurationError`. @@ -132,8 +126,6 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `search(term, **filters)` passes its keywords on to the search endpoint, for what it narrows by besides the term: `condition:` and `ids:`, and `role_ids:`, `group_ids:` and `permissions:` on users. A blank term raises `ArgumentError`; `'*'` asks for every record. -- There is no `where`: Zammad's index endpoints sort and page and drop every other - parameter, so filtering is `search` and `find_by`. - A resource proxy is `Enumerable` over `all`, so `client.tickets.each`, `client.tickets.first(5)`, `client.tickets.map`, `#find_each`, `#in_batches`, `#page`, `#pluck` and `#count` all work without naming `all`. `client.x.find(id)` keeps @@ -148,8 +140,8 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - `client..find_by(**params)` and `#find_by!`, which look a record up by attribute value, and `client..exists?(id)`. `find_by` answers with the first record that carries all the values, or `nil`: by its id where `id:` is given, through a - search where the resource has one and a String value is given, and by walking the index - everywhere else. + search for the longest String value where the resource has a search endpoint, and by + walking the index everywhere else. - The page size is clamped to what an endpoint serves (100 for `/api/v1/tickets`, 200 for a search, 1000 for the other index endpoints). Asking for more used to end iteration after the first page, because Zammad capped the response and the short page read as the From 34f7c025768d95b0a4c7806509d809165d552ce1 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:41:05 +0200 Subject: [PATCH 111/121] Docs: say that a raw request takes a String body --- lib/zammad_api/client.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index 4aa4eaf..a38f807 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -182,7 +182,8 @@ def get(path, query: nil, headers: nil) = raw(:get, path, query: query, headers: # # @param path [String] path relative to {Config#url} # @param query [Hash, nil] query string parameters - # @param body [Hash, Array, nil] request payload, encoded as JSON + # @param body [Hash, Array, String, nil] request payload; a Hash or Array is + # encoded as JSON, a String is sent as it is # @param headers [Hash, nil] request headers # @return [Response] # @raise [ResponseError] for any non-2xx response @@ -193,7 +194,8 @@ def post(path, query: nil, body: nil, headers: nil) = raw(:post, path, query: qu # # @param path [String] path relative to {Config#url} # @param query [Hash, nil] query string parameters - # @param body [Hash, Array, nil] request payload, encoded as JSON + # @param body [Hash, Array, String, nil] request payload; a Hash or Array is + # encoded as JSON, a String is sent as it is # @param headers [Hash, nil] request headers # @return [Response] # @raise [ResponseError] for any non-2xx response From 057cfdd06e5f129a33b23ea2b1b65c3e984a18ec Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:41:23 +0200 Subject: [PATCH 112/121] Docs: list roles among what the README says is not modelled ROADMAP.md has them in progress, and the README left them out. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1ebf81d..dddcaf2 100644 --- a/README.md +++ b/README.md @@ -620,9 +620,9 @@ client's credentials only go to the instance it was configured for. Modelled: tickets, ticket articles and their attachments, ticket states and priorities, users, organizations and groups, the same set as 1.x. -Not modelled yet: text modules; ticket tags, links, mentions, time accounting, checklists, -shared drafts, merge and history; the knowledge base; global search; CSV imports. Declare -a resource or use raw requests for those, and +Not modelled yet: roles; text modules; ticket tags, links, mentions, time accounting, +checklists, shared drafts, merge and history; the knowledge base; global search; CSV +imports. Declare a resource or use raw requests for those, and [open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) for the one you need, so we know what to model first. From 4d52699a078dd50928413209b7c7f6481ebce9c7 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:42:02 +0200 Subject: [PATCH 113/121] Chore: describe the gem in the gemspec, not the release The summary and description said "Version 2.0", that the release is breaking and how to install a prerelease. A gem page shows them for as long as the version is listed, and 2.1 would have said 2.0. --- zammad_api.gemspec | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/zammad_api.gemspec b/zammad_api.gemspec index 5ad9f63..010312d 100644 --- a/zammad_api.gemspec +++ b/zammad_api.gemspec @@ -8,17 +8,12 @@ Gem::Specification.new do |spec| spec.authors = ['Martin Edenhofer', 'Martin Gruner', 'Mantas Masalskis'] spec.email = ['support@zammad.org'] - # Two versions meet in these lines, and only one of them is this gem's: 2.0 - # is the client, and v1.0 is the API that Zammad serves under /api/v1. - # - # A prerelease says so where the gem is listed, and stops saying so by itself - # once VERSION no longer carries a prerelease segment. - prerelease = Gem::Version.new(ZammadAPI::VERSION).prerelease? - - spec.summary = "Version 2.0 of the Ruby client for the Zammad API#{' (prerelease)' if prerelease}." - spec.description = 'Version 2.0 of the Ruby client for the Zammad API v1.0, the one a Zammad serves under ' \ - '/api/v1. It is a breaking release: UPGRADING.md lists every call that changed since 1.x.' - spec.description += " This is a prerelease, #{ZammadAPI::VERSION}: install it with --pre." if prerelease + # v1.0 is the version of the API, the one a Zammad serves under /api/v1, and + # not of this gem. + spec.summary = 'Ruby client for the Zammad API v1.0.' + spec.description = 'Tickets, articles, users, organizations and groups of a Zammad instance as records to ' \ + 'find, create, update and destroy, with collections that paginate themselves, timeouts, ' \ + 'retries and an error class per kind of failure.' spec.homepage = 'https://github.com/zammad/zammad-api-client-ruby' spec.licenses = ['AGPL-3.0-only', 'MIT'] From b455cd6b50aeaec042ed4fb831285598bf2df934 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:42:39 +0200 Subject: [PATCH 114/121] Chore: drop homepage_uri from the gemspec metadata spec.homepage already sets it, and gem build warned that it repeated source_code_uri. --- zammad_api.gemspec | 1 - 1 file changed, 1 deletion(-) diff --git a/zammad_api.gemspec b/zammad_api.gemspec index 010312d..99c18c0 100644 --- a/zammad_api.gemspec +++ b/zammad_api.gemspec @@ -29,7 +29,6 @@ Gem::Specification.new do |spec| spec.required_ruby_version = '>= 3.4' spec.metadata['allowed_push_host'] = 'https://rubygems.org' - spec.metadata['homepage_uri'] = spec.homepage spec.metadata['source_code_uri'] = spec.homepage spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md" spec.metadata['bug_tracker_uri'] = "#{spec.homepage}/issues" From ce753deb3a10f903b98843559af7749a1ea98008 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:44:00 +0200 Subject: [PATCH 115/121] Docs: make the generated docs carry UPGRADING and live links .yardopts was not in the gem, so a build from the gem's contents had a README page and nothing else, and it did not list UPGRADING.md. YARD does not rewrite a relative link either: the README's links to UPGRADING.md, CONTRIBUTING.md, ROADMAP.md and the licenses were dead in every build. They are absolute now, as reference links. --- .yardopts | 1 + CHANGELOG.md | 4 +++- LICENSE.md | 4 ++-- README.md | 19 +++++++++++++------ UPGRADING.md | 7 +++++-- zammad_api.gemspec | 1 + 6 files changed, 25 insertions(+), 11 deletions(-) diff --git a/.yardopts b/.yardopts index 04abe42..00fbbfa 100644 --- a/.yardopts +++ b/.yardopts @@ -5,5 +5,6 @@ --protected lib/**/*.rb - +UPGRADING.md CHANGELOG.md LICENSE.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a85bcc..3bb08a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## [2.0.0.alpha1] - 2026-11-17 The first prerelease of 2.0, a breaking release that modernises the whole gem. See -[UPGRADING.md](UPGRADING.md) for the complete before/after guide. +[UPGRADING.md][upgrading] for the complete before/after guide. Everything below is what changed since 1.4.0. It is published as an alpha so that it can still change: names, defaults and behaviour may differ in 2.0.0. A prerelease has to be @@ -259,3 +259,5 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a ## [1.0.7] - 2022-04-14 - Updated package dependencies and tests. + +[upgrading]: https://github.com/zammad/zammad-api-client-ruby/blob/master/UPGRADING.md diff --git a/LICENSE.md b/LICENSE.md index 17882e4..1b3f037 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -2,5 +2,5 @@ This program is free software; you can redistribute it and/or modify it under the terms of either: -1. the [GNU Affero General Public License](LICENSE.AGPL.txt) as published by the Free Software Foundation version 3 -2. the [MIT License](LICENSE.MIT.txt) as published by the Open Source Initiative \ No newline at end of file +1. the [GNU Affero General Public License](https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.AGPL.txt) as published by the Free Software Foundation version 3 +2. the [MIT License](https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.MIT.txt) as published by the Open Source Initiative \ No newline at end of file diff --git a/README.md b/README.md index dddcaf2..ed42d26 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ > `2.0.0.alpha1` is the first prerelease of a breaking 2.0. Names and defaults can still > change: [open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) with > anything that reads wrong, is missing, or makes upgrading hard. Rough notes are welcome. -> On 1.x? See [UPGRADING.md](UPGRADING.md), which also says how to stay on 1.x. +> On 1.x? See [UPGRADING.md][upgrading], which also says how to stay on 1.x. Ruby client for the Zammad API v1.0. @@ -626,7 +626,7 @@ imports. Declare a resource or use raw requests for those, and [open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) for the one you need, so we know what to model first. -The [features roadmap](ROADMAP.md) shows what is in progress for 2.0, beside 1.x and the +The [features roadmap][roadmap] shows what is in progress for 2.0, beside 1.x and the PHP client. ## Adapter and middleware @@ -749,15 +749,22 @@ bundle exec rake # unit specs, RuboCop, Steep and the shipped signatures ``` Integration specs need a disposable Zammad named by `TEST_URL`; see -[CONTRIBUTING.md](CONTRIBUTING.md). +[CONTRIBUTING.md][contributing]. ## Upgrading from 1.x Most code needs one rename: `client.ticket` is `client.tickets`. Nearly everything else -that changed raises at the call site. [UPGRADING.md](UPGRADING.md) lists every change, and +that changed raises at the call site. [UPGRADING.md][upgrading] lists every change, and says how to stay on 1.x. ## License -Dual licensed under the [AGPL-3.0-only](LICENSE.AGPL.txt) or [MIT](LICENSE.MIT.txt) -licenses. See [LICENSE.md](LICENSE.md). +Dual licensed under the [AGPL-3.0-only][agpl] or [MIT][mit] licenses. See +[LICENSE.md][license]. + +[upgrading]: https://github.com/zammad/zammad-api-client-ruby/blob/master/UPGRADING.md +[contributing]: https://github.com/zammad/zammad-api-client-ruby/blob/master/CONTRIBUTING.md +[roadmap]: https://github.com/zammad/zammad-api-client-ruby/blob/master/ROADMAP.md +[agpl]: https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.AGPL.txt +[mit]: https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.MIT.txt +[license]: https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.md diff --git a/UPGRADING.md b/UPGRADING.md index 139caa5..f58ff85 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -59,7 +59,7 @@ If this is not the time to move, [1.x stays available](#staying-on-1x). | `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is every record of its kind. The singular names raise `UnknownResourceError` | | `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads | | `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised | -| `ZammadAPI::Resources::Role < Base` reached by `client.role` | `client.resource(Role)`, for a `Role < ZammadAPI::Resources::Base` of your own | The named readers are a fixed list. [Raw requests](README.md#raw-requests) reach whatever is not a resource | +| `ZammadAPI::Resources::Role < Base` reached by `client.role` | `client.resource(Role)`, for a `Role < ZammadAPI::Resources::Base` of your own | The named readers are a fixed list. [Raw requests][raw-requests] reach whatever is not a resource | ## Collections @@ -116,7 +116,7 @@ server took. A call that used to hang raises `ZammadAPI::TimeoutError`, or `ZammadAPI::ConnectionError` when the connection is not opened in time. A `GET` is retried twice with exponential backoff on connection failures, timeouts and the transient statuses; a `POST`, `PUT` or `DELETE` is never retried. Both are options: see -[Timeouts and retries](README.md#timeouts-and-retries). The `User-Agent` is +[Timeouts and retries][timeouts-and-retries]. The `User-Agent` is `zammad_api-ruby/` rather than `Zammad API Ruby`. ## What did not change @@ -151,3 +151,6 @@ gem install zammad_api -v '~> 1.4' fixes, while new features go into 2.0 only. Report a 1.x problem in the same [issue tracker](https://github.com/zammad/zammad-api-client-ruby/issues), naming the version, and open a pull request for it against `1-stable`. + +[raw-requests]: https://github.com/zammad/zammad-api-client-ruby/blob/master/README.md#raw-requests +[timeouts-and-retries]: https://github.com/zammad/zammad-api-client-ruby/blob/master/README.md#timeouts-and-retries diff --git a/zammad_api.gemspec b/zammad_api.gemspec index 99c18c0..e2481ae 100644 --- a/zammad_api.gemspec +++ b/zammad_api.gemspec @@ -38,6 +38,7 @@ Gem::Specification.new do |spec| # sig/vendor holds stand-ins for dependencies that ship no signatures. They # exist only for this repository's own type checking and are not published. spec.files = Dir['lib/**/*.rb', 'sig/**/*.rbs'].grep_v(%r{\Asig/vendor/}) + %w[ + .yardopts CHANGELOG.md LICENSE.AGPL.txt LICENSE.MIT.txt From d9aab06e5537e3b28ccec5e1bad98c45af6bb9bb Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:45:09 +0200 Subject: [PATCH 116/121] Docs: describe each resource class, and VERSION The pages for Ticket, User and the other five opened with nothing. --- lib/zammad_api/resources/group.rb | 2 ++ lib/zammad_api/resources/organization.rb | 2 ++ lib/zammad_api/resources/ticket.rb | 2 ++ lib/zammad_api/resources/ticket_article.rb | 2 ++ lib/zammad_api/resources/ticket_priority.rb | 2 ++ lib/zammad_api/resources/ticket_state.rb | 1 + lib/zammad_api/resources/user.rb | 2 ++ lib/zammad_api/version.rb | 1 + 8 files changed, 14 insertions(+) diff --git a/lib/zammad_api/resources/group.rb b/lib/zammad_api/resources/group.rb index 7e95657..7c61bcb 100644 --- a/lib/zammad_api/resources/group.rb +++ b/lib/zammad_api/resources/group.rb @@ -2,6 +2,8 @@ module ZammadAPI module Resources + # A group: what a ticket is assigned to, and what agents are given access by. + # Reached through {Client#groups}. class Group < Base path 'api/v1/groups' diff --git a/lib/zammad_api/resources/organization.rb b/lib/zammad_api/resources/organization.rb index 1935985..5bb80db 100644 --- a/lib/zammad_api/resources/organization.rb +++ b/lib/zammad_api/resources/organization.rb @@ -2,6 +2,8 @@ module ZammadAPI module Resources + # An organization that customers belong to. Reached through + # {Client#organizations}. class Organization < Base path 'api/v1/organizations' diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index 31afed2..b40f681 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -2,6 +2,8 @@ module ZammadAPI module Resources + # A ticket. Reached through {Client#tickets}, and its articles through + # {#articles} and {#add_article}. class Ticket < Base path 'api/v1/tickets' diff --git a/lib/zammad_api/resources/ticket_article.rb b/lib/zammad_api/resources/ticket_article.rb index f9620d2..7d5d416 100644 --- a/lib/zammad_api/resources/ticket_article.rb +++ b/lib/zammad_api/resources/ticket_article.rb @@ -2,6 +2,8 @@ module ZammadAPI module Resources + # An article of a ticket: an e-mail, a note, a phone call. Reached through + # {Ticket#articles}, or by id through {Client#ticket_articles}. class TicketArticle < Base path 'api/v1/ticket_articles' diff --git a/lib/zammad_api/resources/ticket_priority.rb b/lib/zammad_api/resources/ticket_priority.rb index cd68656..1d2910e 100644 --- a/lib/zammad_api/resources/ticket_priority.rb +++ b/lib/zammad_api/resources/ticket_priority.rb @@ -2,6 +2,8 @@ module ZammadAPI module Resources + # A ticket priority, such as "2 normal". Reached through + # {Client#ticket_priorities}. class TicketPriority < Base path 'api/v1/ticket_priorities' end diff --git a/lib/zammad_api/resources/ticket_state.rb b/lib/zammad_api/resources/ticket_state.rb index ec9c4fe..67c6e03 100644 --- a/lib/zammad_api/resources/ticket_state.rb +++ b/lib/zammad_api/resources/ticket_state.rb @@ -2,6 +2,7 @@ module ZammadAPI module Resources + # A ticket state, such as "open". Reached through {Client#ticket_states}. class TicketState < Base path 'api/v1/ticket_states' end diff --git a/lib/zammad_api/resources/user.rb b/lib/zammad_api/resources/user.rb index 6442735..4632905 100644 --- a/lib/zammad_api/resources/user.rb +++ b/lib/zammad_api/resources/user.rb @@ -2,6 +2,8 @@ module ZammadAPI module Resources + # A user: a customer, an agent or an administrator. Reached through + # {Client#users}, and the one the client authenticates as through {Client#me}. class User < Base path 'api/v1/users' diff --git a/lib/zammad_api/version.rb b/lib/zammad_api/version.rb index f8df209..2bcc074 100644 --- a/lib/zammad_api/version.rb +++ b/lib/zammad_api/version.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true module ZammadAPI + # The version of this gem. {Client#version} is the Zammad instance's. VERSION = '2.0.0.alpha1' end From 8c406b04edb4e1229c047f27cf7d3fecd7406e5c Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:45:49 +0200 Subject: [PATCH 117/121] Docs: leave the private API out of the generated reference --no-private hides what is tagged @private, and this gem tags @api private: Transport, DeepCopy and the internal constructors were all listed, each under a notice not to use it. --- .yardopts | 1 + 1 file changed, 1 insertion(+) diff --git a/.yardopts b/.yardopts index 00fbbfa..c10e67a 100644 --- a/.yardopts +++ b/.yardopts @@ -2,6 +2,7 @@ --readme README.md --output-dir doc --no-private +--query '@api.text != "private"' --protected lib/**/*.rb - From 76ad7f4ca4027ad82bf405d9e9315d2d89dc9684 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:46:17 +0200 Subject: [PATCH 118/121] Docs: link each changelog version to its comparison The 2.0.0.alpha1 link resolves once that tag exists. --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bb08a1..2c572df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -261,3 +261,11 @@ asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.a - Updated package dependencies and tests. [upgrading]: https://github.com/zammad/zammad-api-client-ruby/blob/master/UPGRADING.md +[2.0.0.alpha1]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.4.0...v2.0.0.alpha1 +[1.4.0]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.3.1...v1.4.0 +[1.3.1]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.3.0...v1.3.1 +[1.3.0]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.2.0...v1.3.0 +[1.2.0]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.1.0...v1.2.0 +[1.1.0]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.0.8...v1.1.0 +[1.0.8]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.0.7...v1.0.8 +[1.0.7]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.0.6...v1.0.7 From 9a226826c913a24488aec351c0ee55dc60b03875 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 26 Nov 2026 18:48:11 +0200 Subject: [PATCH 119/121] Chore: trim the comments that retell past bugs In the gemspec, the CI matrix, the Rakefile, the scripts and the spec helpers. Each keeps what holds now and why; what once went wrong is in the history. --- .github/workflows/ci.yml | 13 +++------- Rakefile | 7 +++-- script/check_connection.rb | 17 ++++--------- script/live_target.rb | 9 ++----- sig/zammad_api/config.rbs | 3 +-- spec/spec_helper.rb | 14 +++++----- spec/support/integration_helper.rb | 41 +++++++++++------------------- zammad_api.gemspec | 11 +++----- 8 files changed, 40 insertions(+), 75 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 219bb00..538a049 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,16 +54,11 @@ jobs: fail-fast: false matrix: # Stable releases only, from required_ruby_version up to the current - # stable line. There is no 3.5: that line was abandoned after - # 3.5.0-preview1 and became 4.0. + # stable line. There is no 3.5: that line became 4.0. # - # 'head' is absent. It could not install while the lockfile said - # `BUNDLED WITH 2.6.9`: bundler self-downgraded from head's 4.1.0.dev - # and died with NameError on the removed Pathname::SEPARATOR_PAT, and - # without the lockfile a fresh resolution pulled steep -> listen -> - # rb-inotify -> ffi, whose native gems require Ruby < 4.1.dev. The - # lockfile now names Bundler 4.0.20, which does not use that constant, - # so the first of those may be gone; head has not been retried since. + # 'head' is absent: it could not install the bundle when it was last + # tried, under a lockfile that named Bundler 2.6.9. The lockfile names + # Bundler 4 now, and head has not been retried since. ruby: ['3.4', '4.0'] env: # The unit specs do not need the type-checking toolchain, and skipping it diff --git a/Rakefile b/Rakefile index 756f246..f3085be 100644 --- a/Rakefile +++ b/Rakefile @@ -43,10 +43,9 @@ task :steep do end # sig/vendor stands in for dependencies that ship no signatures and is kept -# out of the gem, so the published set has to hold up without it. Naming a -# Faraday type in a published signature made `rbs validate` fail for every -# consumer, and nothing in this repo noticed, because sig/vendor is always -# on the load path here. +# out of the gem, so the published set has to hold up without it. Nothing +# else here notices a published signature that names a Faraday type, because +# sig/vendor is always on the load path in this repository. desc 'Check that the signatures the gem ships validate without sig/vendor' task :rbs_published do require 'tmpdir' diff --git a/script/check_connection.rb b/script/check_connection.rb index d5d5011..dfefb86 100755 --- a/script/check_connection.rb +++ b/script/check_connection.rb @@ -136,9 +136,8 @@ def finish found.name end -# Each of these reads back what Zammad holds and compares it. Printing it -# was not a check: with the body of the PUT lost on the way, this said -# `ok ... created by check_connection.rb` and went on. +# Each of these reads back what Zammad holds and compares it: printing a +# value checks nothing. check('update only the changed attribute') do @group.note = 'updated' raise 'change not staged' if !@group.changed? @@ -196,9 +195,6 @@ def finish "#{hits.size} hit(s)" end -# These were never driven against a live Zammad, which is why nobody noticed -# that an attribute filter passed to an index endpoint never reached the query -# at all. check('find_by returns a record that matches') do found = CLIENT.groups.find_by(name: "smoke-#{SUFFIX}") raise 'no record found' if found.nil? @@ -207,12 +203,9 @@ def finish "id=#{found.id}" end -# Two string attributes, because one is the shape that works whatever the -# search term looks like. Joined into a single term - which is what this used -# to send - the query asks every string column to contain the whole of it, and -# on an instance searching through SQL LIKE rather than Elasticsearch no -# column does, so a record that exists comes back as nil. A stubbed unit spec -# cannot see that; it answers whatever term it is handed. +# Two string attributes, of which find_by searches for one. Joined into a +# single term they match no column on an instance that searches through SQL +# LIKE rather than Elasticsearch, and a stubbed unit spec cannot see that. check('find_by matches on two string attributes') do group = CLIENT.groups.find(@group.id) found = CLIENT.groups.find_by(name: group.name, note: group.note) diff --git a/script/live_target.rb b/script/live_target.rb index a237e76..0e9d8ea 100644 --- a/script/live_target.rb +++ b/script/live_target.rb @@ -4,19 +4,14 @@ # `rake check_connection` and script/check_connection.rb. # # Each of them creates and deletes records, so none has a default for where, -# and each asks here whether one was named. They used to ask with a check of -# their own, three copies of one rule that only stayed in step by being -# changed together - and the day one of them read a TEST_URL as set that the -# others read as unset, rake would refuse a run that rspec then made, or the -# other way round. +# and each asks here whether one was named, so that they agree on it. # # Plain Ruby with nothing required, so that the check script, which loads # nothing of the spec suite on purpose, can load it too. module LiveTarget # What to write where TEST_URL is not set. A placeholder that cannot reach # anything if it is pasted as it is: `.example` is reserved and never - # resolves. `http://localhost:3000/`, which this used to suggest, is where - # a Zammad under development listens. + # resolves, where `http://localhost:3000/` is a Zammad under development. EXAMPLE = 'TEST_URL=https://zammad.example/ TEST_USER=admin@example.com TEST_PASSWORD=test' module_function diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs index b523171..5814f17 100644 --- a/sig/zammad_api/config.rbs +++ b/sig/zammad_api/config.rbs @@ -4,8 +4,7 @@ module ZammadAPI # `middleware` is a block handed a Faraday::Connection, but it is declared # untyped here: these signatures ship with the gem, while the Faraday # declarations they would need live in sig/vendor, which does not. Naming - # Faraday here made `rbs validate` fail for every consumer with - # `Could not find Faraday::Connection`. + # Faraday here fails `rbs validate` for every consumer. class Config < ::Data DEFAULT_TIMEOUT: Integer DEFAULT_OPEN_TIMEOUT: Integer diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index bb3ab91..f6cb116 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -34,9 +34,8 @@ # and never touch the network, integration specs need a live Zammad. # # The integration specs also walk a record through its lifecycle across - # ordered examples, so they are pinned to definition order. Without that a - # `--seed` or `--order random` run scrambled the lifecycle and failed on a - # record that had not been built yet. Unit specs stay order-independent. + # ordered examples, so they are pinned to definition order, whatever + # `--seed` or `--order` says. Unit specs stay order-independent. config.define_derived_metadata(file_path: %r{/spec/unit/}) { it[:unit] = true } config.define_derived_metadata(file_path: %r{/spec/integration/}) do |metadata| metadata[:integration] = true @@ -52,11 +51,10 @@ # the suite: RSpec runs no suite hook for a run that selected nothing, # which is what `rspec spec/integration` is without a TEST_URL. # - # A run that selected nothing but them fails, though: `rspec - # spec/integration` without a TEST_URL left every example out and passed - # with `0 examples, 0 failures`, so a CI job that lost its TEST_URL went - # green having run nothing. A bare `rspec` still runs the unit specs, so - # this fires only where everything selected was left out. + # A run that selected nothing but them fails, though, so that a CI job + # that lost its TEST_URL does not pass with `0 examples, 0 failures`. A + # bare `rspec` still runs the unit specs, so this fires only where + # everything selected was left out. config.fail_if_no_examples = true if Helper.target.nil? diff --git a/spec/support/integration_helper.rb b/spec/support/integration_helper.rb index f753d39..e46dead 100644 --- a/spec/support/integration_helper.rb +++ b/spec/support/integration_helper.rb @@ -10,12 +10,9 @@ class SetupError < StandardError; end # The Zammad the integration specs run against, where one was named. # # There is no default. These specs run the auto wizard and then create, - # change and delete groups, organizations, users, tickets, states and - # priorities, and `http://localhost:3000/` used to stand in for a TEST_URL - # that was not set. That is where a Zammad under development listens, and - # a bare `rspec` runs these files along with the unit specs, so the - # commonest way to run the suite wrote test records into whatever was - # there. Where to write is for whoever runs them to say. + # change and delete records, a bare `rspec` loads them along with the unit + # specs, and `http://localhost:3000/` is where a Zammad under development + # listens. Where to write is for whoever runs them to say. # # Asked of {LiveTarget}, which rake and script/check_connection.rb ask # as well, so that the three agree on whether a target was named. @@ -53,11 +50,9 @@ def self.client(**overrides) # # Memoized and idempotent, so it does not matter which spec file happens to # run first, and re-running the suite against an already configured instance - # is not an error. - # The failure is memoized alongside the success, because `||=` memoizes - # neither. A TEST_URL with nothing behind it re-ran the whole probe - two - # requests, each with a ten second open timeout - once per example, so a - # Zammad that never came up took the suite a very long time to say so. + # is not an error. The failure is memoized alongside the success, so that a + # TEST_URL with nothing behind it is probed once rather than once per + # example, each probe waiting out its timeouts. def self.ensure_configured! raise SetupError, 'TEST_URL is not set, so there is no Zammad to run the integration specs against' if target.nil? return true if @ensure_configured @@ -72,12 +67,9 @@ def self.ensure_configured! end end - # The body is asked about only where it is a JSON object. Valid JSON - # that is not one - `null`, a list, a number - raised NoMethodError on - # the lookup, which is neither the SetupError {.ensure_configured!} - # memoizes nor an answer, so every example ran the probe again. Anything - # but an object saying the wizard ran leaves {.verify_setup_done!} to - # decide. + # The body is asked about only where it is a JSON object: valid JSON that + # is not one - `null`, a list, a number - is no answer. Anything but an + # object saying the wizard ran leaves {.verify_setup_done!} to decide. # # @return [Boolean] whether the auto wizard ran now # @raise [SetupError] when the instance cannot be reached at all @@ -86,11 +78,9 @@ def self.auto_wizard? body = parse(response.body) body.is_a?(Hash) && body['auto_wizard_success'] == true rescue Faraday::Error => e - # {.verify_setup_done!} wraps its failure into a SetupError naming the URL - # and the user; this probe runs one line earlier and did not, so the - # commonest failure of all - CI booting against a Zammad that never came - # up - reached every example as a bare Faraday exception from a helper - # that exists to explain exactly that. + # Wrapped the way {.verify_setup_done!} wraps its failure, so that a + # Zammad that never came up reaches every example as a SetupError naming + # the URL rather than as a bare Faraday exception. raise SetupError, "Zammad at #{config[:url]} could not be reached: the setup check failed to connect " \ "(#{e.class}: #{e.message}). Set TEST_URL to a running instance." @@ -133,10 +123,9 @@ def self.random # save, find, destroy - and every step asserts on what the previous one left # behind, so the record is shared across ordered examples. # -# That coupling is fine as long as the whole file runs in definition order, -# and silent nonsense as soon as it does not: `--only-failures`, `-e 'save'` -# or a `--seed` reordering used to fail as `NoMethodError: undefined method -# 'save' for nil`, which says nothing about the actual cause. This says it. +# That coupling holds as long as the whole file runs in definition order. +# Under `--only-failures` or `-e 'save'` it does not, and this names the +# cause where the example would otherwise fail on nil. module LifecycleState def established!(record, example) return record if record diff --git a/zammad_api.gemspec b/zammad_api.gemspec index e2481ae..7d9d251 100644 --- a/zammad_api.gemspec +++ b/zammad_api.gemspec @@ -19,13 +19,10 @@ Gem::Specification.new do |spec| # Keep in sync with TargetRubyVersion in .rubocop.yml and the CI matrix. # - # 3.4 rather than 3.3, the one older line still maintained - for security - # fixes, until March 2027 - and for a single reason: the `it` block - # parameter, which lib/ uses throughout. Nothing else here needs 3.4. On - # Ruby 3.3.13, with every `it` rewritten to `_1`, the unit suite passed but - # for five examples that assert the format Hash#inspect has had since 3.4. - # So the floor is a choice of style over reach rather than a dependency, and - # lowering it is that rewrite, those five expectations and a CI entry. + # 3.4 rather than 3.3, which gets security fixes until March 2027, for the + # `it` block parameter that lib/ uses throughout. Nothing else needs 3.4: + # lowering the floor is rewriting `it` to `_1`, the five spec expectations + # of the format Hash#inspect has had since 3.4, and a CI entry. spec.required_ruby_version = '>= 3.4' spec.metadata['allowed_push_host'] = 'https://rubygems.org' From 9023783b41411031ed01545000e05f9df6dc2d40 Mon Sep 17 00:00:00 2001 From: DerPixler Date: Thu, 26 Nov 2026 21:51:09 +0100 Subject: [PATCH 120/121] Update ROADMAP with requested features section Added a new section for requested features not yet planned, detailing user requests and their sources. --- ROADMAP.md | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 2ed3d20..df9e5cc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -5,6 +5,8 @@ What each Zammad API client models: this gem in its 1.x and 2.0 versions, and th ✅ available · 🚧 work in progress · ❌ not available +## Resources + | Resource | Ruby 1.x | Ruby 2.0 | PHP | | ------------------------- | :------: | :------: | ---------------------------------------------------- | | Tickets | ✅ | ✅ | ✅ | @@ -26,3 +28,66 @@ What each Zammad API client models: this gem in its 1.x and 2.0 versions, and th Until a 🚧 row lands in Ruby 2.0, reach it by [declaring a resource](README.md#declaring-a-resource) or with a [raw request](README.md#raw-requests). + +## Behaviour + +| Behaviour | Ruby 1.x | Ruby 2.0 | PHP | +| ------------------------------------- | :------: | --------------------------- | ------------------------------------------------ | +| Auto-pagination | ❌ | ✅ | ✅ | +| Total count of a search | ❌ | ✅ | ✅ | +| Sorted search | ❌ | ✅ not on tickets and users | ✅ as plain query parameters | +| Search by condition | ❌ | ✅ | ❌ | +| Acting on behalf of a user | ✅ | ✅ | ✅ by wrapping the request handler | +| Custom attributes | ✅ | ✅ | ✅ tickets, users, organizations and groups only | +| Typed errors | ✅ | ✅ | ✅ | +| Timeouts | ❌ | ✅ | ✅ | +| Retry when rate limited | ❌ | ✅ reads only | ✅ | +| Retry on server and connection errors | ❌ | ✅ reads only | ❌ | +| Attachment download as a stream | ❌ | ❌ | ❌ | +| Attachment upload helper | ❌ | ❌ | ❌ Base64 in the article | +| Test doubles for applications | ❌ | ❌ | ❌ | +| Framework integration | ❌ | ❌ | ✅ Laravel, Symfony | + +## Requested, not planned yet + +What users ask for beyond the tables above, most requested first. Neither client +offers these today; all are reachable with a raw request. A row moves into a +table above once work on it starts. + +| Request | Where it was asked | +| ----------------------------------------- | ------------------------------------------------------------- | +| Attachments: upload, stream, delete | [PHP #4][php-4], community [10604][c-10604], [17478][c-17478], [13390][c-13390] | +| Listing beyond the 10,000 search limit | community [10644][c-10644], [16162][c-16162], [zammad #768][z-768] | +| Time accounting | community [10244][c-10244], [7958][c-7958], [17492][c-17492] | +| Knowledge base | [PHP #29][php-29], community [3510][c-3510], [12168][c-12168] | +| Tested Zammad versions per client release | [zammad #6561][z-6561], community [17422][c-17422] | +| Find or create a user by exact email | [PHP #9][php-9], [Ruby #6][ruby-6] | +| Ticket merge | community [4710][c-4710] | +| Ticket history | community [10205][c-10205] | +| Mentions, checklists, shared drafts | community [15937][c-15937], [20651][c-20651] | +| Webhook signature verification | community [9011][c-9011] | + +Missing something? Open an issue so we know what to model first. + +[php-4]: https://github.com/zammad/zammad-api-client-php/issues/4 +[php-9]: https://github.com/zammad/zammad-api-client-php/issues/9 +[php-29]: https://github.com/zammad/zammad-api-client-php/issues/29 +[ruby-6]: https://github.com/zammad/zammad-api-client-ruby/issues/6 +[z-768]: https://github.com/zammad/zammad/issues/768 +[z-6561]: https://github.com/zammad/zammad/issues/6561 +[c-3510]: https://community.zammad.org/t/3510 +[c-4710]: https://community.zammad.org/t/4710 +[c-7958]: https://community.zammad.org/t/7958 +[c-9011]: https://community.zammad.org/t/9011 +[c-10205]: https://community.zammad.org/t/10205 +[c-10244]: https://community.zammad.org/t/10244 +[c-10604]: https://community.zammad.org/t/10604 +[c-10644]: https://community.zammad.org/t/10644 +[c-12168]: https://community.zammad.org/t/12168 +[c-13390]: https://community.zammad.org/t/13390 +[c-15937]: https://community.zammad.org/t/15937 +[c-16162]: https://community.zammad.org/t/16162 +[c-17422]: https://community.zammad.org/t/17422 +[c-17478]: https://community.zammad.org/t/17478 +[c-17492]: https://community.zammad.org/t/17492 +[c-20651]: https://community.zammad.org/t/20651 From ebdd60da1fad5f3197255a7029c198f5fca6d65f Mon Sep 17 00:00:00 2001 From: DerPixler Date: Thu, 26 Nov 2026 21:52:50 +0100 Subject: [PATCH 121/121] Fix formatting for framework integration in roadmap --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index df9e5cc..920325c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -46,7 +46,7 @@ Until a 🚧 row lands in Ruby 2.0, reach it by | Attachment download as a stream | ❌ | ❌ | ❌ | | Attachment upload helper | ❌ | ❌ | ❌ Base64 in the article | | Test doubles for applications | ❌ | ❌ | ❌ | -| Framework integration | ❌ | ❌ | ✅ Laravel, Symfony | +| Framework integration | - | - | ✅ Laravel, Symfony | ## Requested, not planned yet