hecks 2.9.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/exe/hecks +51 -6
- data/lib/hecks/adapters/driven/heki/journal.rb +1 -1
- data/lib/hecks/adapters/driven/lambda/client.rb +1 -1
- data/lib/hecks/adapters/driven/lambda.rb +1 -1
- data/lib/hecks/adapters/driven/memory.rb +16 -3
- data/lib/hecks/adapters/driven/postgres/reconnect.rb +6 -2
- data/lib/hecks/adapters/driven/postgres/shared_connection.rb +180 -0
- data/lib/hecks/adapters/driven/postgres.rb +4 -2
- data/lib/hecks/adapters/driven/prism.rb +41 -8
- data/lib/hecks/adapters/driven/tenant_provisioner.rb +73 -16
- data/lib/hecks/behaviors/expectations.rb +1 -1
- data/lib/hecks/behaviors.rb +1 -1
- data/lib/hecks/bench/cli.rb +62 -0
- data/lib/hecks/bench/environment.rb +71 -0
- data/lib/hecks/bench/postgres_probe.rb +30 -0
- data/lib/hecks/bench/report.rb +76 -0
- data/lib/hecks/bench/ruby_runner.rb +93 -0
- data/lib/hecks/bench/run.rb +55 -0
- data/lib/hecks/bench/rust_runner.rb +101 -0
- data/lib/hecks/bench/stats.rb +46 -0
- data/lib/hecks/bench/suite.rb +98 -0
- data/lib/hecks/bench/workload.rb +89 -0
- data/lib/hecks/bench.rb +17 -0
- data/lib/hecks/bluebook/assembly/contracts.rb +2 -0
- data/lib/hecks/bluebook/attribute.rb +1 -1
- data/lib/hecks/bluebook/behaviour/aggregate.rb +30 -1
- data/lib/hecks/bluebook/behaviour/domain_port.rb +7 -0
- data/lib/hecks/bluebook/chapter.rb +6 -2
- data/lib/hecks/bluebook/domain_port.rb +36 -5
- data/lib/hecks/bluebook/dsl/bluebook_builder/validation.rb +10 -0
- data/lib/hecks/bluebook/dsl/bluebook_builder.rb +8 -0
- data/lib/hecks/bluebook/dsl/bootstrap_table.rb +2 -1
- data/lib/hecks/bluebook/dsl/domain_port_builder.rb +31 -3
- data/lib/hecks/bluebook/dsl/hecksagon_builder.rb +122 -3
- data/lib/hecks/bluebook/dsl/lifecycle_builder.rb +1 -1
- data/lib/hecks/bluebook/dsl/query_builder.rb +27 -1
- data/lib/hecks/bluebook/dsl/rule_reference.rb +1 -1
- data/lib/hecks/bluebook/dsl/world_builder.rb +29 -2
- data/lib/hecks/bluebook/expression/canonical_form.rb +1 -1
- data/lib/hecks/bluebook/expression/resolver.rb +3 -2
- data/lib/hecks/bluebook/hexagon.rb +13 -5
- data/lib/hecks/bluebook/meta_validator/reconstruction.rb +1 -0
- data/lib/hecks/bluebook/meta_validator/syntax_boot.rb +4 -1
- data/lib/hecks/bluebook/meta_validator/verdict_cache.rb +246 -0
- data/lib/hecks/bluebook/meta_validator.rb +9 -4
- data/lib/hecks/bluebook/model_check.rb +23 -0
- data/lib/hecks/bluebook/pattern_subset.rb +38 -0
- data/lib/hecks/bluebook/query.rb +20 -5
- data/lib/hecks/bluebook/smoke_test.rb +1 -1
- data/lib/hecks/canonical_json.rb +30 -0
- data/lib/hecks/chapters.rb +102 -0
- data/lib/hecks/cli/behaviors.rb +61 -0
- data/lib/hecks/cli/canonicalise.rb +25 -0
- data/lib/hecks/cli/check_engine_agreement.rb +32 -0
- data/lib/hecks/cli/check_era.rb +88 -0
- data/lib/hecks/cli/console.rb +66 -0
- data/lib/hecks/cli/deploy_template_diff.rb +40 -0
- data/lib/hecks/cli/doc_coverage.rb +32 -0
- data/lib/hecks/cli/document.rb +2 -2
- data/lib/hecks/cli/expression_projection.rb +41 -0
- data/lib/hecks/cli/follow.rb +88 -0
- data/lib/hecks/cli/history.rb +44 -0
- data/lib/hecks/cli/ir.rb +1 -1
- data/lib/hecks/cli/mcp.rb +3 -3
- data/lib/hecks/cli/model_check.rb +7 -4
- data/lib/hecks/cli/pattern_cases.rb +47 -0
- data/lib/hecks/cli/present.rb +39 -0
- data/lib/hecks/cli/project_cli.rb +224 -32
- data/lib/hecks/cli/project_diagrams.rb +4 -3
- data/lib/hecks/cli/project_glossary.rb +44 -0
- data/lib/hecks/cli/reference.rb +46 -0
- data/lib/hecks/cli/refresh_projections.rb +44 -0
- data/lib/hecks/cli/refresh_rspec_runtime_baseline.rb +150 -0
- data/lib/hecks/cli/release.rb +70 -0
- data/lib/hecks/cli/release_gem.rb +59 -0
- data/lib/hecks/cli/rspec_io_parallel_files.rb +137 -0
- data/lib/hecks/cli/rspec_shard_files.rb +66 -0
- data/lib/hecks/cli/run.rb +3 -3
- data/lib/hecks/cli/seed_semantics_corpus.rb +71 -0
- data/lib/hecks/cli/serve_query_ir_mcp.rb +30 -0
- data/lib/hecks/cli/shape.rb +70 -0
- data/lib/hecks/cli/smoke_http.rb +230 -0
- data/lib/hecks/cli/smoke_test.rb +5 -3
- data/lib/hecks/cli/spec_example.rb +27 -0
- data/lib/hecks/cli/statements.rb +32 -0
- data/lib/hecks/cli/stores.rb +4 -5
- data/lib/hecks/cli/stress_concurrency_specs.rb +177 -0
- data/lib/hecks/cli.rb +201 -52
- data/lib/hecks/codemod.rb +324 -0
- data/lib/hecks/corpus.rb +423 -0
- data/lib/hecks/deploy/bluebook/deploy.bluebook +591 -23
- data/lib/hecks/deploy/bluebook/deploy.hecksagon +41 -4
- data/lib/hecks/deploy/oidc.json +82 -2
- data/lib/hecks/doc/reference.rb +351 -0
- data/lib/hecks/doors/cli_door.rb +196 -0
- data/lib/hecks/doors/cli_runner.rb +297 -0
- data/lib/hecks/{facade → doors}/command_request.rb +1 -1
- data/lib/hecks/{facade → doors}/handle.rb +2 -2
- data/lib/hecks/{facade → doors}/json_door.rb +4 -4
- data/lib/hecks/doors/launcher_options.rb +129 -0
- data/lib/hecks/{cli → doors}/mcp_door.rb +7 -7
- data/lib/hecks/doors/mcp_door_scope.rb +97 -0
- data/lib/hecks/{facade/surface → doors/ruby_door}/aggregate_door.rb +8 -3
- data/lib/hecks/{facade/surface → doors/ruby_door}/chapter.rb +3 -3
- data/lib/hecks/{facade/surface.rb → doors/ruby_door.rb} +36 -5
- data/lib/hecks/doors.rb +61 -0
- data/lib/hecks/embryonaut_bluebook/vendor_cli.rb +1 -1
- data/lib/hecks/embryonaut_bluebook.rb +1 -1
- data/lib/hecks/engine_agreement.rb +156 -0
- data/lib/hecks/facade.rb +24 -37
- data/lib/hecks/forms/app.rb +6 -6
- data/lib/hecks/forms/banking_presentation.rb +50 -0
- data/lib/hecks/forms/field_shape.rb +2 -1
- data/lib/hecks/forms/port_argument.rb +1 -1
- data/lib/hecks/fuzzing/bounded_exhaustive_expressions.rb +393 -0
- data/lib/hecks/fuzzing/combination_miner.rb +86 -0
- data/lib/hecks/fuzzing/concurrent_dispatch.rb +214 -0
- data/lib/hecks/fuzzing/coverage_campaign.rb +143 -0
- data/lib/hecks/fuzzing/differential.rb +156 -0
- data/lib/hecks/fuzzing/domain_generator.rb +615 -0
- data/lib/hecks/fuzzing/era_boundary.rb +71 -0
- data/lib/hecks/fuzzing/form_census.rb +136 -0
- data/lib/hecks/fuzzing/generated_domain_check.rb +93 -0
- data/lib/hecks/fuzzing/invalid_value_generator.rb +64 -0
- data/lib/hecks/fuzzing/isolated_boot.rb +301 -0
- data/lib/hecks/fuzzing/nondeterministic.rb +51 -0
- data/lib/hecks/fuzzing/outside_world.rb +45 -0
- data/lib/hecks/fuzzing/persistence_parity.rb +102 -0
- data/lib/hecks/fuzzing/properties/corrections.rb +88 -0
- data/lib/hecks/fuzzing/properties/dispatch_and_mutations.rb +314 -0
- data/lib/hecks/fuzzing/properties/guards.rb +190 -0
- data/lib/hecks/fuzzing/properties/invariants_and_aggregation.rb +300 -0
- data/lib/hecks/fuzzing/properties/lifecycle_and_replay.rb +93 -0
- data/lib/hecks/fuzzing/properties/outbox.rb +89 -0
- data/lib/hecks/fuzzing/properties/querying.rb +175 -0
- data/lib/hecks/fuzzing/properties.rb +162 -0
- data/lib/hecks/fuzzing/qa_settings.rb +123 -0
- data/lib/hecks/fuzzing/replay.rb +505 -0
- data/lib/hecks/fuzzing/rotation_priority.rb +48 -0
- data/lib/hecks/fuzzing/rust_gap_manifest.rb +108 -0
- data/lib/hecks/fuzzing/self_consistency.rb +339 -0
- data/lib/hecks/fuzzing/sequence_generator/adversary.rb +385 -0
- data/lib/hecks/fuzzing/sequence_generator/catalog.rb +132 -0
- data/lib/hecks/fuzzing/sequence_generator/outcome_tracker.rb +95 -0
- data/lib/hecks/fuzzing/sequence_generator/picker.rb +77 -0
- data/lib/hecks/fuzzing/sequence_generator/query_binding.rb +109 -0
- data/lib/hecks/fuzzing/sequence_generator/step_builder.rb +237 -0
- data/lib/hecks/fuzzing/sequence_generator.rb +189 -0
- data/lib/hecks/fuzzing/shrinker.rb +166 -0
- data/lib/hecks/fuzzing/structural_skips.rb +33 -0
- data/lib/hecks/fuzzing/sweep_depth.rb +43 -0
- data/lib/hecks/fuzzing/target_capabilities.rb +163 -0
- data/lib/hecks/fuzzing/value_generator.rb +216 -0
- data/lib/hecks/fuzzing.rb +23 -0
- data/lib/hecks/grammar/evolve.rb +336 -0
- data/lib/hecks/hecks/adapters/codebase/codemods.rb +45 -0
- data/lib/hecks/hecks/adapters/codebase/conformance.rb +71 -0
- data/lib/hecks/hecks/adapters/codebase/corpus_tasks.rb +202 -0
- data/lib/hecks/hecks/adapters/codebase/gem_registry.rb +80 -0
- data/lib/hecks/hecks/adapters/codebase/kernel_tables.rb +54 -0
- data/lib/hecks/hecks/adapters/codebase/language.rb +240 -0
- data/lib/hecks/hecks/adapters/codebase/npm_registry.rb +102 -0
- data/lib/hecks/hecks/adapters/codebase/publishing.rb +142 -0
- data/lib/hecks/hecks/adapters/codebase/regeneration.rb +67 -0
- data/lib/hecks/hecks/adapters/codebase/release_facts.rb +90 -0
- data/lib/hecks/hecks/adapters/codebase/ruby_child.rb +83 -0
- data/lib/hecks/hecks/adapters/codebase/secret_vault.rb +36 -0
- data/lib/hecks/hecks/adapters/codebase/source_tree.adapter +7 -0
- data/lib/hecks/hecks/adapters/codebase/source_tree.rb +189 -0
- data/lib/hecks/hecks/adapters/codebase/sqlite_fixture.rb +71 -0
- data/lib/hecks/hecks/adapters/codebase/style.rb +171 -0
- data/lib/hecks/hecks/adapters/codebase/test_runner.rb +55 -0
- data/lib/hecks/hecks/adapters/codebase/test_suite.rb +165 -0
- data/lib/hecks/hecks/adapters/codebase/tree.rb +111 -0
- data/lib/hecks/hecks/adapters/console_capture.rb +79 -0
- data/lib/hecks/hecks/adapters/deploy_toolchain.adapter +7 -0
- data/lib/hecks/hecks/adapters/deploy_toolchain.rb +108 -0
- data/lib/hecks/hecks/adapters/git.adapter +7 -0
- data/lib/hecks/hecks/adapters/git.rb +102 -0
- data/lib/hecks/hecks/adapters/host_http.adapter +7 -0
- data/lib/hecks/hecks/adapters/host_http.rb +65 -0
- data/lib/hecks/hecks/adapters/in_process_boot.adapter +7 -0
- data/lib/hecks/hecks/adapters/in_process_boot.rb +197 -0
- data/lib/hecks/hecks/adapters/in_process_operations.rb +202 -0
- data/lib/hecks/hecks/adapters/journal_store/changes.rb +143 -0
- data/lib/hecks/hecks/adapters/journal_store/compaction.rb +145 -0
- data/lib/hecks/hecks/adapters/journal_store/edge_audit.rb +132 -0
- data/lib/hecks/hecks/adapters/journal_store/examination.rb +135 -0
- data/lib/hecks/hecks/adapters/journal_store/held_domain.rb +163 -0
- data/lib/hecks/hecks/adapters/journal_store/readings.rb +187 -0
- data/lib/hecks/hecks/adapters/journal_store.adapter +7 -0
- data/lib/hecks/hecks/adapters/journal_store.rb +64 -0
- data/lib/hecks/hecks/adapters/local_files.adapter +7 -0
- data/lib/hecks/hecks/adapters/local_files.rb +46 -0
- data/lib/hecks/hecks/adapters/pg_admin.adapter +7 -0
- data/lib/hecks/hecks/adapters/pg_admin.rb +245 -0
- data/lib/hecks/hecks/adapters/process_pool.adapter +7 -0
- data/lib/hecks/hecks/adapters/process_pool.rb +119 -0
- data/lib/hecks/hecks/adapters/rust_toolchain.adapter +7 -0
- data/lib/hecks/hecks/adapters/rust_toolchain.rb +179 -0
- data/lib/hecks/hecks/adapters/rust_workspace.rb +150 -0
- data/lib/hecks/hecks/adapters/shell.adapter +7 -0
- data/lib/hecks/hecks/adapters/shell.rb +49 -0
- data/lib/hecks/hecks/adapters/terminal.adapter +7 -0
- data/lib/hecks/hecks/adapters/terminal.rb +74 -0
- data/lib/hecks/hecks/codebase.behaviors +172 -0
- data/lib/hecks/hecks/codebase.bluebook +2453 -0
- data/lib/hecks/hecks/context_map.hecksagon +13 -0
- data/lib/hecks/hecks/custodian.behaviors +179 -0
- data/lib/hecks/hecks/custodian.bluebook +1847 -0
- data/lib/hecks/hecks/deploy.behaviors +74 -0
- data/lib/hecks/hecks/deploy.world +12 -0
- data/lib/hecks/hecks/environments/memory.world +10 -0
- data/lib/hecks/hecks/governance.world +7 -0
- data/lib/hecks/hecks/hecks.behaviors +62 -0
- data/lib/hecks/hecks/hecks.bluebook +124 -0
- data/lib/hecks/hecks/hecks.hecksagon +390 -0
- data/lib/hecks/hecks/hecks.world +42 -0
- data/lib/hecks/kernel_capabilities.rb +194 -0
- data/lib/hecks/language/bluebook/bluebook.bluebook +11 -0
- data/lib/hecks/language/bluebook/query.bluebook +7 -0
- data/lib/hecks/language/bluebook/vocabulary.bluebook +4 -4
- data/lib/hecks/language/hecksagon/domain_port.bluebook +10 -0
- data/lib/hecks/language/hecksagon/hecksagon.bluebook +20 -0
- data/lib/hecks/mcp_stdio_guard.rb +2 -2
- data/lib/hecks/persistence_legacy_fixture/regenerate.rb +161 -0
- data/lib/hecks/persistence_legacy_fixture.rb +113 -0
- data/lib/hecks/ports/persistence/plugins/era/era_check.rb +8 -5
- data/lib/hecks/ports/persistence/plugins/era/era_guard.rb +4 -1
- data/lib/hecks/ports/persistence/plugins/era/expected_era.rb +15 -2
- data/lib/hecks/ports/persistence/plugins/era/postgres_era/lineage/era_store.rb +1 -1
- data/lib/hecks/ports/persistence/plugins/era/postgres_era/lineage/tail_merge.rb +1 -1
- data/lib/hecks/ports/persistence/plugins/era/postgres_era/lineage_manager/merge_coordinator.rb +1 -1
- data/lib/hecks/ports/persistence/plugins/era/postgres_era/lineage_manager/minter.rb +32 -15
- data/lib/hecks/ports/persistence/plugins/era/postgres_era.rb +6 -3
- data/lib/hecks/ports/persistence/plugins/era/translation/approval_file.rb +227 -0
- data/lib/hecks/ports/persistence/plugins/era/translation/audit/approval_digest.rb +1 -1
- data/lib/hecks/ports/persistence/plugins/era/translation/reattest.rb +43 -24
- data/lib/hecks/ports/persistence/plugins/era/translation.rb +1 -0
- data/lib/hecks/ports/persistence/state_codec.rb +24 -5
- data/lib/hecks/projection_files.rb +285 -0
- data/lib/hecks/projections/bootstrap_table.rb +1 -1
- data/lib/hecks/projections/deploy/fargate.rb +5 -5
- data/lib/hecks/projections/deploy/lambda.rb +43 -32
- data/lib/hecks/projections/deploy/preview/preview.sh.erb +1 -1
- data/lib/hecks/projections/deploy/preview/template.rb +1 -1
- data/lib/hecks/projections/deploy/scripts/deploy-service.sh.tmpl +1 -1
- data/lib/hecks/projections/deploy/scripts/expected-era.header +1 -1
- data/lib/hecks/projections/deploy/scripts/hosting.mk.tmpl +3 -3
- data/lib/hecks/projections/deploy/scripts/smoke-after-deploy.sh.tmpl +1 -1
- data/lib/hecks/projections/deploy/shared.rb +1 -1
- data/lib/hecks/projections/diagrams.rb +3 -3
- data/lib/hecks/projections/model/deviations.rb +1 -1
- data/lib/hecks/projections/parser_table.rb +4 -4
- data/lib/hecks/projections/reference.rb +2 -3
- data/lib/hecks/projections/rust_vocabulary.rb +1 -1
- data/lib/hecks/projector/cli_projector.rb +106 -37
- data/lib/hecks/projector.rb +1 -1
- data/lib/hecks/quality_control/adapters/agent.adapter +7 -0
- data/lib/hecks/quality_control/adapters/agent.rb +58 -0
- data/lib/hecks/quality_control/adapters/angle_tools.adapter +7 -0
- data/lib/hecks/quality_control/adapters/angle_tools.rb +15 -0
- data/lib/hecks/quality_control/adapters/clearance_recorder.rb +36 -0
- data/lib/hecks/quality_control/adapters/clearance_tools.adapter +7 -0
- data/lib/hecks/quality_control/adapters/clearance_tools.rb +17 -0
- data/lib/hecks/quality_control/adapters/git_pr.adapter +7 -0
- data/lib/hecks/quality_control/adapters/git_pr.rb +226 -0
- data/lib/hecks/quality_control/adapters/github_checks.adapter +9 -0
- data/lib/hecks/quality_control/adapters/github_checks.rb +83 -0
- data/lib/hecks/quality_control/adapters/github_ci_webhook.rb +56 -0
- data/lib/hecks/quality_control/adapters/github_issues.adapter +7 -0
- data/lib/hecks/quality_control/adapters/github_issues.rb +49 -0
- data/lib/hecks/quality_control/adapters/qa_tool.rb +59 -0
- data/lib/hecks/quality_control/adapters/sweep_tools.adapter +7 -0
- data/lib/hecks/quality_control/adapters/sweep_tools.rb +51 -0
- data/lib/hecks/quality_control/adapters/target_tools.adapter +7 -0
- data/lib/hecks/quality_control/adapters/target_tools.rb +43 -0
- data/lib/hecks/quality_control/cli/child.rb +45 -0
- data/lib/hecks/quality_control/cli/qa_concurrency_racer.rb +45 -0
- data/lib/hecks/quality_control/cli/qa_discover_external_domains.rb +248 -0
- data/lib/hecks/quality_control/cli/qa_domain_novelty.rb +163 -0
- data/lib/hecks/quality_control/cli/qa_generated_domains.rb +450 -0
- data/lib/hecks/quality_control/cli/qa_log_bug.rb +195 -0
- data/lib/hecks/quality_control/cli/qa_mine_combinations.rb +220 -0
- data/lib/hecks/quality_control/cli/qa_open_pr.rb +305 -0
- data/lib/hecks/quality_control/cli/qa_postgres_migrate.rb +154 -0
- data/lib/hecks/quality_control/cli/qa_postgres_role.rb +159 -0
- data/lib/hecks/quality_control/cli/qa_pr_check.rb +232 -0
- data/lib/hecks/quality_control/cli/qa_seed_angles.rb +142 -0
- data/lib/hecks/quality_control/cli/qa_seed_targets.rb +69 -0
- data/lib/hecks/quality_control/cli/qa_sweep/all_mode.rb +280 -0
- data/lib/hecks/quality_control/cli/qa_sweep/checks.rb +329 -0
- data/lib/hecks/quality_control/cli/qa_sweep/dials.rb +92 -0
- data/lib/hecks/quality_control/cli/qa_sweep/finding_report.rb +117 -0
- data/lib/hecks/quality_control/cli/qa_sweep/parsing.rb +175 -0
- data/lib/hecks/quality_control/cli/qa_sweep/release_mode.rb +60 -0
- data/lib/hecks/quality_control/cli/qa_sweep.rb +611 -0
- data/lib/hecks/quality_control/cli/qa_tick.rb +274 -0
- data/lib/hecks/quality_control/quality_control.bluebook +2224 -0
- data/lib/hecks/quality_control/quality_control.hecksagon +13 -0
- data/lib/hecks/quality_control/quality_control.ports.hecksagon +54 -0
- data/lib/hecks/query_ir.rb +346 -0
- data/lib/hecks/query_ir_mcp.rb +198 -0
- data/lib/hecks/release/runner/ci_publisher.rb +2 -2
- data/lib/hecks/release/runner/clean_tree.rb +42 -0
- data/lib/hecks/release/runner/console.rb +6 -0
- data/lib/hecks/release/runner/gem_publisher.rb +14 -7
- data/lib/hecks/release/runner/npm_publisher.rb +6 -36
- data/lib/hecks/release/runner/preflight.rb +26 -2
- data/lib/hecks/release/runner/published.rb +8 -26
- data/lib/hecks/release/runner/tagger.rb +30 -15
- data/lib/hecks/release/runner.rb +57 -6
- data/lib/hecks/router/namespace_installer.rb +3 -3
- data/lib/hecks/runtime/adapter_lookup.rb +124 -0
- data/lib/hecks/runtime/command_interpreter/mutation_applier.rb +4 -0
- data/lib/hecks/runtime/dependency_planning.rb +20 -2
- data/lib/hecks/runtime/dispatcher.rb +53 -3
- data/lib/hecks/runtime/interpreting.rb +3 -0
- data/lib/hecks/runtime/loader.rb +65 -12
- data/lib/hecks/runtime/outbox.rb +1 -1
- data/lib/hecks/runtime/policy_interpreter.rb +5 -2
- data/lib/hecks/runtime/port_operation_interpreter.rb +2 -10
- data/lib/hecks/runtime/query_interpreter.rb +77 -0
- data/lib/hecks/runtime/reaction_outcome.rb +89 -0
- data/lib/hecks/runtime/refusal_wording.rb +23 -1
- data/lib/hecks/runtime/registry/verification.rb +163 -4
- data/lib/hecks/runtime/registry.rb +57 -3
- data/lib/hecks/runtime/remote_dispatcher.rb +31 -2
- data/lib/hecks/runtime/value/coercion.rb +23 -135
- data/lib/hecks/runtime/value/field_checks.rb +172 -0
- data/lib/hecks/runtime/value.rb +4 -1
- data/lib/hecks/runtime.rb +20 -6
- data/lib/hecks/rust_build/conformance.rb +158 -0
- data/lib/hecks/rust_build/conformance_fuzz.rb +71 -0
- data/lib/hecks/rust_build/coverage.rb +218 -0
- data/lib/hecks/rust_build/native_build.rb +124 -0
- data/lib/hecks/rust_build/project_rust/root_mod.rb +120 -0
- data/lib/hecks/rust_build/project_rust.rb +332 -0
- data/lib/hecks/rust_build/wasm.rb +105 -0
- data/lib/hecks/rust_build/wasm_browser.rb +113 -0
- data/lib/hecks/rust_build.rb +144 -0
- data/lib/hecks/storehouse.rb +16 -16
- data/lib/hecks/tenancy/bluebook/tenancy.bluebook +2 -2
- data/lib/hecks/tenancy/bluebook/tenancy.hecksagon +1 -1
- data/lib/hecks/three_zero/forms.yml +127 -0
- data/lib/hecks/three_zero.rb +12 -0
- data/lib/hecks/tools/argument_gate_matrix.rb +316 -0
- data/lib/hecks/tools/comment_style.rb +1070 -0
- data/lib/hecks/tools/corpus_report.rb +87 -0
- data/lib/hecks/tools/deploy_recipe.rb +255 -0
- data/lib/hecks/tools/deploy_recipe_lint.rb +282 -0
- data/lib/hecks/tools/drop_implicit_append_fields.rb +95 -0
- data/lib/hecks/tools/era_projection_backfill.rb +94 -0
- data/lib/hecks/tools/era_reattest.rb +146 -0
- data/lib/hecks/tools/evolve_run.rb +189 -0
- data/lib/hecks/tools/fuzz_sweep.rb +373 -0
- data/lib/hecks/tools/heki_compaction.rb +100 -0
- data/lib/hecks/tools/hoist_local_givens.rb +246 -0
- data/lib/hecks/tools/journal_compaction.rb +89 -0
- data/lib/hecks/tools/oidc_manifests.rb +70 -0
- data/lib/hecks/tools/query_ir_run.rb +81 -0
- data/lib/hecks/tools/regeneration_run.rb +166 -0
- data/lib/hecks/tools/rust_comment_style.rb +642 -0
- data/lib/hecks/tools/sequence_script.rb +62 -0
- data/lib/hecks/tools/tail_merge.rb +117 -0
- data/lib/hecks/tools/tenant_provisioning.rb +142 -0
- data/lib/hecks/tools/translation_audit.rb +208 -0
- data/lib/hecks/tools/translation_scaffold.rb +131 -0
- data/lib/hecks/tools.rb +86 -0
- data/lib/hecks/version.rb +1 -1
- data/lib/hecks.rb +32 -15
- data/qa/settings.yml +66 -0
- data/rust/.cargo/config.toml +6 -0
- data/rust/.gitignore +2 -0
- data/rust/Cargo.lock +54 -0
- data/rust/Cargo.toml +61 -0
- data/rust/build/.cargo/config.toml +3 -0
- data/rust/build/.gitignore +1 -0
- data/rust/build/Cargo.lock +7 -0
- data/rust/build/Cargo.toml +19 -0
- data/rust/build/src/build_artifact.rs +47 -0
- data/rust/build/src/cargo_sync.rs +248 -0
- data/rust/build/src/json.rs +421 -0
- data/rust/build/src/lineage_pass.rs +285 -0
- data/rust/build/src/main.rs +51 -0
- data/rust/build/src/optional_pass.rs +150 -0
- data/rust/build/src/pipeline.rs +264 -0
- data/rust/build/src/reserved_names.rs +76 -0
- data/rust/build/src/resolve.rs +124 -0
- data/rust/build/src/root.rs +25 -0
- data/rust/build/src/sidecars.rs +73 -0
- data/rust/build/src/subprocess.rs +51 -0
- data/rust/build/src/tmp.rs +31 -0
- data/rust/codegen/.cargo/config.toml +3 -0
- data/rust/codegen/.gitignore +1 -0
- data/rust/codegen/Cargo.lock +7 -0
- data/rust/codegen/Cargo.toml +20 -0
- data/rust/codegen/src/attr.rs +32 -0
- data/rust/codegen/src/bridging.rs +481 -0
- data/rust/codegen/src/commands.rs +1226 -0
- data/rust/codegen/src/constraints.rs +109 -0
- data/rust/codegen/src/dependency_planning.rs +209 -0
- data/rust/codegen/src/domain_generator.rs +1288 -0
- data/rust/codegen/src/exemplar.rs +230 -0
- data/rust/codegen/src/expr_emitter.rs +87 -0
- data/rust/codegen/src/fielded.rs +192 -0
- data/rust/codegen/src/hecks_naming.rs +33 -0
- data/rust/codegen/src/json.rs +335 -0
- data/rust/codegen/src/json_codec.rs +697 -0
- data/rust/codegen/src/literal.rs +207 -0
- data/rust/codegen/src/main.rs +290 -0
- data/rust/codegen/src/manifest.rs +227 -0
- data/rust/codegen/src/mutations.rs +784 -0
- data/rust/codegen/src/naming.rs +286 -0
- data/rust/codegen/src/ports.rs +208 -0
- data/rust/codegen/src/prelude.rs +116 -0
- data/rust/codegen/src/queries.rs +786 -0
- data/rust/codegen/src/reactions.rs +532 -0
- data/rust/codegen/src/read_models.rs +697 -0
- data/rust/codegen/src/reference_specs.rs +40 -0
- data/rust/codegen/src/registry.rs +966 -0
- data/rust/codegen/src/reserved_names.rs +76 -0
- data/rust/codegen/src/shared.rs +93 -0
- data/rust/codegen/src/skip_reason.rs +25 -0
- data/rust/codegen/src/types.rs +362 -0
- data/rust/host/.cargo/config.toml +3 -0
- data/rust/host/.gitignore +1 -0
- data/rust/host/Cargo.lock +4297 -0
- data/rust/host/Cargo.toml +61 -0
- data/rust/host/HECKS_RELEASE +1 -0
- data/rust/host/rds-ca-bundle.pem +2736 -0
- data/rust/host/src/api.rs +1596 -0
- data/rust/host/src/approval.rs +652 -0
- data/rust/host/src/auth.rs +1287 -0
- data/rust/host/src/bin/expr_harness.rs +46 -0
- data/rust/host/src/bin/lineage_harness.rs +119 -0
- data/rust/host/src/bin/mint_harness.rs +135 -0
- data/rust/host/src/checkout.rs +265 -0
- data/rust/host/src/dispatch.rs +1443 -0
- data/rust/host/src/expr_json.rs +1117 -0
- data/rust/host/src/field_hints.rs +52 -0
- data/rust/host/src/ir.rs +733 -0
- data/rust/host/src/journal.rs +874 -0
- data/rust/host/src/lambda_client.rs +378 -0
- data/rust/host/src/log.rs +147 -0
- data/rust/host/src/main.rs +474 -0
- data/rust/host/src/mint.rs +1865 -0
- data/rust/host/src/payments/keystore.rs +330 -0
- data/rust/host/src/payments/tests.rs +1400 -0
- data/rust/host/src/payments.rs +767 -0
- data/rust/host/src/presentation.rs +698 -0
- data/rust/host/src/presentation_write.rs +1431 -0
- data/rust/host/src/query_step.rs +149 -0
- data/rust/host/src/rate_limit.rs +904 -0
- data/rust/host/src/reference_transform.rs +241 -0
- data/rust/host/src/reference_validate.rs +338 -0
- data/rust/host/src/resend.rs +296 -0
- data/rust/host/src/secrets.rs +106 -0
- data/rust/host/src/server.rs +663 -0
- data/rust/host/src/storage_shape.rs +175 -0
- data/rust/host/src/test_pg.rs +40 -0
- data/rust/host/src/ui_schema.rs +1351 -0
- data/rust/host/src/wasm_runner.rs +191 -0
- data/rust/host/src/web/newsletter/cooldown.rs +126 -0
- data/rust/host/src/web/newsletter/tests.rs +104 -0
- data/rust/host/src/web/newsletter.rs +310 -0
- data/rust/host/src/web/newsletter_send.rs +357 -0
- data/rust/host/src/web/registrations.rs +1505 -0
- data/rust/host/src/web.rs +2937 -0
- data/rust/lsp/.gitignore +1 -0
- data/rust/lsp/Cargo.lock +7 -0
- data/rust/lsp/Cargo.toml +16 -0
- data/rust/lsp/README.md +133 -0
- data/rust/lsp/src/diagnostics.rs +165 -0
- data/rust/lsp/src/json.rs +385 -0
- data/rust/lsp/src/main.rs +399 -0
- data/rust/lsp/src/outline.rs +177 -0
- data/rust/lsp/src/rpc.rs +67 -0
- data/rust/parser/.cargo/config.toml +5 -0
- data/rust/parser/.gitignore +1 -0
- data/rust/parser/Cargo.lock +7 -0
- data/rust/parser/Cargo.toml +21 -0
- data/rust/parser/src/build/closed_sets.rs +27 -0
- data/rust/parser/src/build/identity.rs +276 -0
- data/rust/parser/src/build/mod.rs +12 -0
- data/rust/parser/src/build/naming.rs +141 -0
- data/rust/parser/src/build/pattern_subset.rs +161 -0
- data/rust/parser/src/build/query_derive.rs +72 -0
- data/rust/parser/src/build/query_inference.rs +269 -0
- data/rust/parser/src/build/query_options.rs +100 -0
- data/rust/parser/src/build/read_model.rs +94 -0
- data/rust/parser/src/build/references.rs +32 -0
- data/rust/parser/src/canonical.rs +114 -0
- data/rust/parser/src/diag.rs +55 -0
- data/rust/parser/src/emit.rs +953 -0
- data/rust/parser/src/expr/ast_json.rs +147 -0
- data/rust/parser/src/expr/evaluator.rs +81 -0
- data/rust/parser/src/expr/mod.rs +84 -0
- data/rust/parser/src/expr/resolver.rs +497 -0
- data/rust/parser/src/ir.rs +387 -0
- data/rust/parser/src/keywords.rs +585 -0
- data/rust/parser/src/lex.rs +662 -0
- data/rust/parser/src/main.rs +252 -0
- data/rust/parser/src/parse/aggregate.rs +612 -0
- data/rust/parser/src/parse/chapter.rs +517 -0
- data/rust/parser/src/parse/command.rs +637 -0
- data/rust/parser/src/parse/domain_port.rs +127 -0
- data/rust/parser/src/parse/entity.rs +527 -0
- data/rust/parser/src/parse/file.rs +67 -0
- data/rust/parser/src/parse/hecksagon.rs +231 -0
- data/rust/parser/src/parse/lifecycle.rs +162 -0
- data/rust/parser/src/parse/mod.rs +1262 -0
- data/rust/parser/src/parse/policy.rs +87 -0
- data/rust/parser/src/parse/process_manager.rs +305 -0
- data/rust/parser/src/parse/query.rs +100 -0
- data/rust/parser/src/parse/read_model.rs +214 -0
- data/rust/parser/src/parse/value_object.rs +250 -0
- data/rust/parser/src/ruby_value.rs +422 -0
- data/rust/project/bridging.rb +257 -0
- data/rust/project/commands.rb +877 -0
- data/rust/project/constraints.rb +86 -0
- data/rust/project/dependency_planning.rb +178 -0
- data/rust/project/domain_generator.rb +980 -0
- data/rust/project/exemplar.rb +148 -0
- data/rust/project/expr_emitter.rb +72 -0
- data/rust/project/fielded.rb +141 -0
- data/rust/project/json_codec.rb +641 -0
- data/rust/project/mutations.rb +721 -0
- data/rust/project/naming.rb +205 -0
- data/rust/project/ports.rb +65 -0
- data/rust/project/queries.rb +493 -0
- data/rust/project/reactions.rb +317 -0
- data/rust/project/read_models.rb +690 -0
- data/rust/project/reference_specs.rb +27 -0
- data/rust/project/registry.rb +396 -0
- data/rust/project/skip_reason.rb +29 -0
- data/rust/project/types.rb +225 -0
- data/rust/project/write_if_changed.rb +83 -0
- data/rust/project.rb +30 -0
- data/rust/project_rust_pipeline.rb +383 -0
- data/rust/src/exemplar/commands.rs +279 -0
- data/rust/src/exemplar/constraints.rs +18 -0
- data/rust/src/exemplar/fielded.rs +280 -0
- data/rust/src/exemplar/json.rs +277 -0
- data/rust/src/exemplar/mod.rs +17 -0
- data/rust/src/exemplar/mutations.rs +80 -0
- data/rust/src/exemplar/queries.rs +33 -0
- data/rust/src/exemplar/reactions.rs +88 -0
- data/rust/src/exemplar/read_models.rs +48 -0
- data/rust/src/exemplar/registry.rs +166 -0
- data/rust/src/exemplar/types.rs +44 -0
- data/rust/src/kernel/attribute_shapes/composite.rs +88 -0
- data/rust/src/kernel/attribute_shapes/list.rs +18 -0
- data/rust/src/kernel/attribute_shapes/mod.rs +44 -0
- data/rust/src/kernel/attribute_shapes/optional.rs +9 -0
- data/rust/src/kernel/attribute_shapes/scalar.rs +39 -0
- data/rust/src/kernel/cli.rs +585 -0
- data/rust/src/kernel/dispatch.rs +1090 -0
- data/rust/src/kernel/expr.rs +458 -0
- data/rust/src/kernel/expression_operators/arithmetic.rs +128 -0
- data/rust/src/kernel/expression_operators/comparison.rs +48 -0
- data/rust/src/kernel/expression_operators/enumeration.rs +232 -0
- data/rust/src/kernel/expression_operators/logical.rs +13 -0
- data/rust/src/kernel/expression_operators/membership.rs +18 -0
- data/rust/src/kernel/expression_operators/mod.rs +68 -0
- data/rust/src/kernel/expression_operators/pattern_match.rs +73 -0
- data/rust/src/kernel/expression_operators/positional.rs +126 -0
- data/rust/src/kernel/expression_operators/presence.rs +101 -0
- data/rust/src/kernel/expression_operators/sign_test.rs +16 -0
- data/rust/src/kernel/expression_operators/sized.rs +35 -0
- data/rust/src/kernel/expression_operators/text.rs +79 -0
- data/rust/src/kernel/expression_operators/to_string.rs +18 -0
- data/rust/src/kernel/json.rs +779 -0
- data/rust/src/kernel/mod.rs +133 -0
- data/rust/src/kernel/named_query.rs +219 -0
- data/rust/src/kernel/orchestrate.rs +1810 -0
- data/rust/src/kernel/pattern.rs +307 -0
- data/rust/src/kernel/query_comparators.rs +206 -0
- data/rust/src/kernel/query_ordering.rs +103 -0
- data/rust/src/kernel/read_model.rs +914 -0
- data/rust/src/kernel/reference_lookup.rs +149 -0
- data/rust/src/kernel/repository.rs +468 -0
- data/rust/src/kernel/routing.rs +612 -0
- data/rust/src/kernel/vocab/aggregate_dispatch_order.rs +118 -0
- data/rust/src/kernel/vocab/entity_dispatch_order.rs +114 -0
- data/rust/src/kernel/vocab/field_hint.rs +70 -0
- data/rust/src/kernel/vocab/mod.rs +20 -0
- data/rust/src/kernel/vocab/query_comparator.rs +65 -0
- data/rust/src/kernel/vocab/refusal_template.rs +1592 -0
- data/rust/src/lib.rs +8 -0
- data/rust/src/main.rs +16 -0
- data/rust/web/.gitignore +1 -0
- data/rust/web/Cargo.lock +119 -0
- data/rust/web/Cargo.toml +18 -0
- data/rust/web/src/lib.rs +8 -0
- metadata +477 -12
- data/lib/hecks/facade/cli_door.rb +0 -96
- data/lib/hecks/facade/cli_runner.rb +0 -127
- data/lib/hecks/mcp_door_scope.rb +0 -95
|
@@ -0,0 +1,904 @@
|
|
|
1
|
+
//! Per-address sliding-window rate limits for the public write routes a stranger can abuse,
|
|
2
|
+
//! enforced in `server.rs` before dispatch so a refused request costs no Postgres lock or run.
|
|
3
|
+
|
|
4
|
+
use axum::http::header::{HeaderValue, CONTENT_TYPE, RETRY_AFTER};
|
|
5
|
+
use axum::http::{HeaderMap, HeaderName, StatusCode};
|
|
6
|
+
use axum::response::{IntoResponse, Response};
|
|
7
|
+
use serde_json::json;
|
|
8
|
+
use std::collections::{BTreeMap, HashMap, VecDeque};
|
|
9
|
+
use std::net::{IpAddr, Ipv6Addr};
|
|
10
|
+
use std::sync::atomic::{AtomicBool, Ordering};
|
|
11
|
+
use std::sync::Mutex;
|
|
12
|
+
use std::time::{Duration, Instant};
|
|
13
|
+
|
|
14
|
+
const UNKNOWN_CLIENT: &str = "unknown";
|
|
15
|
+
|
|
16
|
+
const DEFAULT_WINDOW_SECONDS: u64 = 3600;
|
|
17
|
+
const DEFAULT_SUBSCRIBE: usize = 10;
|
|
18
|
+
const DEFAULT_REGISTER: usize = 15;
|
|
19
|
+
const DEFAULT_MAX_KEYS: usize = 10_000;
|
|
20
|
+
|
|
21
|
+
/// The outcome of counting one request against a window.
|
|
22
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
23
|
+
pub struct Decision {
|
|
24
|
+
/// Whether the request may proceed; when true it has been recorded.
|
|
25
|
+
pub allowed: bool,
|
|
26
|
+
/// Requests still allowed in the current window after this one.
|
|
27
|
+
pub remaining: usize,
|
|
28
|
+
/// Whole seconds until a refused caller may try again; 0 when allowed.
|
|
29
|
+
pub retry_after_secs: u64,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
struct Entry {
|
|
33
|
+
stamps: VecDeque<Instant>,
|
|
34
|
+
seq: u64,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// `check` takes the current instant so tests move time by hand instead of sleeping.
|
|
38
|
+
pub struct SlidingWindow {
|
|
39
|
+
limit: usize,
|
|
40
|
+
window: Duration,
|
|
41
|
+
max_keys: usize,
|
|
42
|
+
entries: HashMap<String, Entry>,
|
|
43
|
+
// Keys ordered by the sequence of their last allowed request, oldest first. An active key is
|
|
44
|
+
// re-inserted at the end on every allowed request, so the first entry is always the least
|
|
45
|
+
// recently active key and expired keys form a prefix.
|
|
46
|
+
recency: BTreeMap<u64, String>,
|
|
47
|
+
next_seq: u64,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
impl SlidingWindow {
|
|
51
|
+
// A zero `limit` or `max_keys` is raised to 1.
|
|
52
|
+
pub fn new(limit: usize, window: Duration, max_keys: usize) -> Self {
|
|
53
|
+
Self {
|
|
54
|
+
limit: limit.max(1),
|
|
55
|
+
window,
|
|
56
|
+
max_keys: max_keys.max(1),
|
|
57
|
+
entries: HashMap::new(),
|
|
58
|
+
recency: BTreeMap::new(),
|
|
59
|
+
next_seq: 0,
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
pub fn check(&mut self, key: &str, now: Instant) -> Decision {
|
|
64
|
+
let window = self.window;
|
|
65
|
+
match self.entries.get_mut(key) {
|
|
66
|
+
Some(entry) => {
|
|
67
|
+
while entry.stamps.front().is_some_and(|s| now.saturating_duration_since(*s) >= window) {
|
|
68
|
+
entry.stamps.pop_front();
|
|
69
|
+
}
|
|
70
|
+
if entry.stamps.len() >= self.limit {
|
|
71
|
+
let oldest = entry.stamps.front().copied().unwrap_or(now);
|
|
72
|
+
let wait = window.saturating_sub(now.saturating_duration_since(oldest));
|
|
73
|
+
let retry_after_secs = u64::try_from(wait.as_millis().div_ceil(1000)).unwrap_or(u64::MAX).max(1);
|
|
74
|
+
return Decision { allowed: false, remaining: 0, retry_after_secs };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
None => self.make_room(now),
|
|
78
|
+
}
|
|
79
|
+
self.record(key, now)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
#[cfg(test)]
|
|
83
|
+
fn len(&self) -> usize {
|
|
84
|
+
self.entries.len()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
fn record(&mut self, key: &str, now: Instant) -> Decision {
|
|
88
|
+
let seq = self.next_seq;
|
|
89
|
+
self.next_seq += 1;
|
|
90
|
+
let remaining = match self.entries.get_mut(key) {
|
|
91
|
+
Some(entry) => {
|
|
92
|
+
self.recency.remove(&entry.seq);
|
|
93
|
+
entry.seq = seq;
|
|
94
|
+
entry.stamps.push_back(now);
|
|
95
|
+
self.limit - entry.stamps.len()
|
|
96
|
+
}
|
|
97
|
+
None => {
|
|
98
|
+
self.entries.insert(key.to_string(), Entry { stamps: VecDeque::from([now]), seq });
|
|
99
|
+
self.limit - 1
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
self.recency.insert(seq, key.to_string());
|
|
103
|
+
Decision { allowed: true, remaining, retry_after_secs: 0 }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Called before adding a new key: sweeps keys whose last request left the window, and only
|
|
107
|
+
// then drops the least recently active ones, so a live caller is never evicted while an idle
|
|
108
|
+
// one is still held.
|
|
109
|
+
fn make_room(&mut self, now: Instant) {
|
|
110
|
+
if self.entries.len() < self.max_keys {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
while let Some((&seq, key)) = self.recency.first_key_value() {
|
|
114
|
+
let expired = self
|
|
115
|
+
.entries
|
|
116
|
+
.get(key)
|
|
117
|
+
.and_then(|e| e.stamps.back())
|
|
118
|
+
.is_none_or(|last| now.saturating_duration_since(*last) >= self.window);
|
|
119
|
+
if !expired {
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
let key = key.clone();
|
|
123
|
+
self.recency.remove(&seq);
|
|
124
|
+
self.entries.remove(&key);
|
|
125
|
+
}
|
|
126
|
+
while self.entries.len() >= self.max_keys {
|
|
127
|
+
let Some((_, key)) = self.recency.pop_first() else { break };
|
|
128
|
+
self.entries.remove(&key);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
134
|
+
pub struct IpNet {
|
|
135
|
+
addr: IpAddr,
|
|
136
|
+
prefix: u8,
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
impl IpNet {
|
|
140
|
+
pub fn parse(text: &str) -> Option<Self> {
|
|
141
|
+
let text = text.trim();
|
|
142
|
+
let (addr_text, prefix_text) = match text.split_once('/') {
|
|
143
|
+
Some((addr, prefix)) => (addr, Some(prefix)),
|
|
144
|
+
None => (text, None),
|
|
145
|
+
};
|
|
146
|
+
let addr: IpAddr = addr_text.trim().parse().ok()?;
|
|
147
|
+
let width = if addr.is_ipv4() { 32 } else { 128 };
|
|
148
|
+
let prefix = match prefix_text {
|
|
149
|
+
Some(p) => p.trim().parse::<u8>().ok().filter(|p| *p <= width)?,
|
|
150
|
+
None => width,
|
|
151
|
+
};
|
|
152
|
+
Some(Self { addr, prefix })
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// An IPv4-mapped IPv6 address counts as its IPv4 form.
|
|
156
|
+
pub fn contains(&self, ip: IpAddr) -> bool {
|
|
157
|
+
match (self.addr, ip.to_canonical()) {
|
|
158
|
+
(IpAddr::V4(net), IpAddr::V4(ip)) => {
|
|
159
|
+
let mask = if self.prefix == 0 { 0 } else { u32::MAX << (32 - u32::from(self.prefix)) };
|
|
160
|
+
u32::from(net) & mask == u32::from(ip) & mask
|
|
161
|
+
}
|
|
162
|
+
(IpAddr::V6(net), IpAddr::V6(ip)) => {
|
|
163
|
+
let mask = if self.prefix == 0 { 0 } else { u128::MAX << (128 - u32::from(self.prefix)) };
|
|
164
|
+
u128::from(net) & mask == u128::from(ip) & mask
|
|
165
|
+
}
|
|
166
|
+
_ => false,
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
172
|
+
pub struct ProxyAuth {
|
|
173
|
+
header: HeaderName,
|
|
174
|
+
secret: String,
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
|
178
|
+
pub struct ProxyTrust {
|
|
179
|
+
networks: Vec<IpNet>,
|
|
180
|
+
hops: usize,
|
|
181
|
+
auth: Option<ProxyAuth>,
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
impl ProxyTrust {
|
|
185
|
+
// `None` means the client address could not be determined safely, rather than guessed;
|
|
186
|
+
// callers then share one bucket. The forwarded header is read only from a trusted source.
|
|
187
|
+
pub fn client_ip(&self, peer: Option<IpAddr>, forwarded_for: Option<&str>, presented_secret: Option<&str>) -> Option<IpAddr> {
|
|
188
|
+
let peer = peer.map(|p| p.to_canonical());
|
|
189
|
+
if !self.trusts(peer, presented_secret) {
|
|
190
|
+
return peer;
|
|
191
|
+
}
|
|
192
|
+
let entries: Vec<&str> = forwarded_for.unwrap_or("").split(',').map(str::trim).filter(|e| !e.is_empty()).collect();
|
|
193
|
+
if entries.is_empty() {
|
|
194
|
+
return peer;
|
|
195
|
+
}
|
|
196
|
+
for entry in entries.iter().rev().skip(self.hops) {
|
|
197
|
+
let ip = entry.parse::<IpAddr>().ok()?.to_canonical();
|
|
198
|
+
if !self.networks.iter().any(|net| net.contains(ip)) {
|
|
199
|
+
return Some(ip);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
None
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
fn trusts(&self, peer: Option<IpAddr>, presented_secret: Option<&str>) -> bool {
|
|
206
|
+
let secret_matches = match (&self.auth, presented_secret) {
|
|
207
|
+
(Some(auth), Some(presented)) => constant_time_eq(auth.secret.as_bytes(), presented.as_bytes()),
|
|
208
|
+
_ => false,
|
|
209
|
+
};
|
|
210
|
+
secret_matches || peer.is_some_and(|p| self.networks.iter().any(|net| net.contains(p)))
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
|
215
|
+
a.len() == b.len() && a.iter().zip(b).fold(0u8, |diff, (x, y)| diff | (x ^ y)) == 0
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
219
|
+
pub enum Form {
|
|
220
|
+
Subscribe,
|
|
221
|
+
Register,
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
impl Form {
|
|
225
|
+
pub fn for_request(method: &str, path: &str) -> Option<Self> {
|
|
226
|
+
match (method, path) {
|
|
227
|
+
("POST", "/newsletter/subscribers") => Some(Self::Subscribe),
|
|
228
|
+
("POST", "/registrations") => Some(Self::Register),
|
|
229
|
+
_ => None,
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
235
|
+
pub struct Config {
|
|
236
|
+
enabled: bool,
|
|
237
|
+
window: Duration,
|
|
238
|
+
subscribe: usize,
|
|
239
|
+
register: usize,
|
|
240
|
+
max_keys: usize,
|
|
241
|
+
trust: ProxyTrust,
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
impl Config {
|
|
245
|
+
// Returns one warning per setting that was unusable and fell back to its default or was
|
|
246
|
+
// dropped, rather than failing boot.
|
|
247
|
+
pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> (Self, Vec<String>) {
|
|
248
|
+
let mut warnings = Vec::new();
|
|
249
|
+
let mut number = |name: &str, default: u64| -> u64 {
|
|
250
|
+
match get(name).map(|v| v.trim().to_string()).filter(|v| !v.is_empty()) {
|
|
251
|
+
None => default,
|
|
252
|
+
Some(raw) => raw.parse::<u64>().ok().filter(|n| *n >= 1).unwrap_or_else(|| {
|
|
253
|
+
warnings.push(format!("{name}={raw:?} is not a positive whole number; using {default}"));
|
|
254
|
+
default
|
|
255
|
+
}),
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
let window = number("HECKS_RATE_LIMIT_WINDOW_SECONDS", DEFAULT_WINDOW_SECONDS);
|
|
259
|
+
let subscribe = number("HECKS_RATE_LIMIT_SUBSCRIBE", DEFAULT_SUBSCRIBE as u64);
|
|
260
|
+
let register = number("HECKS_RATE_LIMIT_REGISTER", DEFAULT_REGISTER as u64);
|
|
261
|
+
let max_keys = number("HECKS_RATE_LIMIT_MAX_KEYS", DEFAULT_MAX_KEYS as u64);
|
|
262
|
+
let hops = get("HECKS_TRUSTED_PROXY_HOPS").map(|v| v.trim().to_string()).filter(|v| !v.is_empty()).map_or(0, |raw| {
|
|
263
|
+
raw.parse::<usize>().unwrap_or_else(|_| {
|
|
264
|
+
warnings.push(format!("HECKS_TRUSTED_PROXY_HOPS={raw:?} is not a whole number; using 0"));
|
|
265
|
+
0
|
|
266
|
+
})
|
|
267
|
+
});
|
|
268
|
+
let networks = parse_networks(get("HECKS_TRUSTED_PROXIES").as_deref().unwrap_or(""), &mut warnings);
|
|
269
|
+
let auth = parse_proxy_auth(get("HECKS_PROXY_AUTH_HEADER"), get("HECKS_PROXY_AUTH_SECRET"), &mut warnings);
|
|
270
|
+
let enabled = !get("HECKS_RATE_LIMIT").is_some_and(|v| is_off(&v));
|
|
271
|
+
|
|
272
|
+
let config = Self {
|
|
273
|
+
enabled,
|
|
274
|
+
window: Duration::from_secs(window),
|
|
275
|
+
subscribe: usize::try_from(subscribe).unwrap_or(usize::MAX),
|
|
276
|
+
register: usize::try_from(register).unwrap_or(usize::MAX),
|
|
277
|
+
max_keys: usize::try_from(max_keys).unwrap_or(usize::MAX),
|
|
278
|
+
trust: ProxyTrust { networks, hops, auth },
|
|
279
|
+
};
|
|
280
|
+
(config, warnings)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
fn limit_for(&self, form: Form) -> usize {
|
|
284
|
+
match form {
|
|
285
|
+
Form::Subscribe => self.subscribe,
|
|
286
|
+
Form::Register => self.register,
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
fn is_off(value: &str) -> bool {
|
|
292
|
+
matches!(value.trim().to_ascii_lowercase().as_str(), "off" | "false" | "0" | "no" | "disabled")
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
fn parse_networks(list: &str, warnings: &mut Vec<String>) -> Vec<IpNet> {
|
|
296
|
+
list.split(',')
|
|
297
|
+
.map(str::trim)
|
|
298
|
+
.filter(|e| !e.is_empty())
|
|
299
|
+
.filter_map(|entry| {
|
|
300
|
+
let net = IpNet::parse(entry);
|
|
301
|
+
if net.is_none() {
|
|
302
|
+
warnings.push(format!("HECKS_TRUSTED_PROXIES entry {entry:?} is not an address or CIDR range; ignored"));
|
|
303
|
+
}
|
|
304
|
+
net
|
|
305
|
+
})
|
|
306
|
+
.collect()
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
fn parse_proxy_auth(header: Option<String>, secret: Option<String>, warnings: &mut Vec<String>) -> Option<ProxyAuth> {
|
|
310
|
+
let header = header.map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
|
|
311
|
+
let secret = secret.filter(|v| !v.is_empty());
|
|
312
|
+
match (header, secret) {
|
|
313
|
+
(None, None) => None,
|
|
314
|
+
(Some(header), Some(secret)) => match HeaderName::from_bytes(header.to_ascii_lowercase().as_bytes()) {
|
|
315
|
+
Ok(header) => Some(ProxyAuth { header, secret }),
|
|
316
|
+
Err(_) => {
|
|
317
|
+
warnings.push(format!("HECKS_PROXY_AUTH_HEADER {header:?} is not a valid header name; proxy authentication is off"));
|
|
318
|
+
None
|
|
319
|
+
}
|
|
320
|
+
},
|
|
321
|
+
_ => {
|
|
322
|
+
warnings.push("HECKS_PROXY_AUTH_HEADER and HECKS_PROXY_AUTH_SECRET must both be set; proxy authentication is off".to_string());
|
|
323
|
+
None
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
329
|
+
pub enum Verdict {
|
|
330
|
+
Allowed,
|
|
331
|
+
Limited {
|
|
332
|
+
// Whole seconds until the oldest counted request leaves the window.
|
|
333
|
+
retry_after_secs: u64,
|
|
334
|
+
},
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
pub struct RateLimits {
|
|
338
|
+
config: Config,
|
|
339
|
+
windows: Mutex<HashMap<Form, SlidingWindow>>,
|
|
340
|
+
warned_untrusted_proxy: AtomicBool,
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
impl RateLimits {
|
|
344
|
+
pub fn new(config: Config) -> Self {
|
|
345
|
+
Self { config, windows: Mutex::new(HashMap::new()), warned_untrusted_proxy: AtomicBool::new(false) }
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
pub fn from_env() -> Self {
|
|
349
|
+
let (config, warnings) = Config::from_lookup(|name| std::env::var(name).ok());
|
|
350
|
+
for warning in &warnings {
|
|
351
|
+
crate::log::info("rate_limit_config_warning", json!({ "warning": warning }));
|
|
352
|
+
}
|
|
353
|
+
crate::log::info(
|
|
354
|
+
"rate_limit_config",
|
|
355
|
+
json!({
|
|
356
|
+
"enabled": config.enabled,
|
|
357
|
+
"window_seconds": config.window.as_secs(),
|
|
358
|
+
"subscribe": config.subscribe,
|
|
359
|
+
"register": config.register,
|
|
360
|
+
"trusted_networks": config.trust.networks.len(),
|
|
361
|
+
"trusted_proxy_hops": config.trust.hops,
|
|
362
|
+
"proxy_auth": config.trust.auth.is_some(),
|
|
363
|
+
}),
|
|
364
|
+
);
|
|
365
|
+
Self::new(config)
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// A route that is not limited is always `Allowed`.
|
|
369
|
+
pub fn check(&self, method: &str, path: &str, headers: &HeaderMap, peer: Option<IpAddr>) -> Verdict {
|
|
370
|
+
self.check_at(method, path, headers, peer, Instant::now())
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// `check` with the clock supplied, so tests need not sleep.
|
|
374
|
+
pub fn check_at(&self, method: &str, path: &str, headers: &HeaderMap, peer: Option<IpAddr>, now: Instant) -> Verdict {
|
|
375
|
+
let Some(form) = Form::for_request(method, path).filter(|_| self.config.enabled) else {
|
|
376
|
+
return Verdict::Allowed;
|
|
377
|
+
};
|
|
378
|
+
let key = self.client_key(headers, peer);
|
|
379
|
+
let decision = {
|
|
380
|
+
let mut windows = self.windows.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
381
|
+
let config = &self.config;
|
|
382
|
+
windows
|
|
383
|
+
.entry(form)
|
|
384
|
+
.or_insert_with(|| SlidingWindow::new(config.limit_for(form), config.window, config.max_keys))
|
|
385
|
+
.check(&key, now)
|
|
386
|
+
};
|
|
387
|
+
if decision.allowed {
|
|
388
|
+
Verdict::Allowed
|
|
389
|
+
} else {
|
|
390
|
+
Verdict::Limited { retry_after_secs: decision.retry_after_secs }
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
fn client_key(&self, headers: &HeaderMap, peer: Option<IpAddr>) -> String {
|
|
395
|
+
let forwarded_for = joined_header(headers, "x-forwarded-for");
|
|
396
|
+
let presented = self.config.trust.auth.as_ref().and_then(|auth| headers.get(&auth.header)).and_then(|v| v.to_str().ok());
|
|
397
|
+
self.warn_if_proxy_untrusted(forwarded_for.as_deref(), peer, presented);
|
|
398
|
+
match self.config.trust.client_ip(peer, forwarded_for.as_deref(), presented) {
|
|
399
|
+
Some(ip) => bucket_key(ip),
|
|
400
|
+
None => UNKNOWN_CLIENT.to_string(),
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// A forwarded header from a private peer that nothing trusts means a proxy sits in front of
|
|
405
|
+
// the host and every visitor is being counted as that proxy. Said once, since it repeats on
|
|
406
|
+
// every request.
|
|
407
|
+
fn warn_if_proxy_untrusted(&self, forwarded_for: Option<&str>, peer: Option<IpAddr>, presented: Option<&str>) {
|
|
408
|
+
let Some(peer) = peer.map(|p| p.to_canonical()) else { return };
|
|
409
|
+
if forwarded_for.is_none() || !is_private(peer) || self.config.trust.trusts(Some(peer), presented) {
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if !self.warned_untrusted_proxy.swap(true, Ordering::Relaxed) {
|
|
413
|
+
crate::log::info(
|
|
414
|
+
"rate_limit_untrusted_proxy",
|
|
415
|
+
json!({
|
|
416
|
+
"peer": peer.to_string(),
|
|
417
|
+
"hint": "requests arrive from a private address with X-Forwarded-For but no trusted proxy is configured; \
|
|
418
|
+
set HECKS_TRUSTED_PROXIES or HECKS_PROXY_AUTH_HEADER and HECKS_PROXY_AUTH_SECRET",
|
|
419
|
+
}),
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Several X-Forwarded-For header lines mean the same as one comma-joined line.
|
|
426
|
+
fn joined_header(headers: &HeaderMap, name: &str) -> Option<String> {
|
|
427
|
+
let values: Vec<String> = headers.get_all(name).iter().map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned()).collect();
|
|
428
|
+
if values.is_empty() {
|
|
429
|
+
None
|
|
430
|
+
} else {
|
|
431
|
+
Some(values.join(", "))
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// IPv6 callers are counted per /64: one subscriber controls the whole prefix and could otherwise
|
|
436
|
+
// rotate through it for a fresh allowance on every request.
|
|
437
|
+
fn bucket_key(ip: IpAddr) -> String {
|
|
438
|
+
match ip {
|
|
439
|
+
IpAddr::V4(v4) => v4.to_string(),
|
|
440
|
+
IpAddr::V6(v6) => {
|
|
441
|
+
let prefix = u128::from(v6) & (u128::MAX << 64);
|
|
442
|
+
format!("{}/64", Ipv6Addr::from(prefix))
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
fn is_private(ip: IpAddr) -> bool {
|
|
448
|
+
match ip {
|
|
449
|
+
IpAddr::V4(v4) => v4.is_private() || v4.is_loopback() || v4.is_link_local(),
|
|
450
|
+
IpAddr::V6(v6) => v6.is_loopback() || (v6.segments()[0] & 0xfe00) == 0xfc00,
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
pub fn too_many_requests(retry_after_secs: u64) -> Response {
|
|
455
|
+
let body = json!({ "error": "too many requests, please try again later" }).to_string();
|
|
456
|
+
let mut response = (StatusCode::TOO_MANY_REQUESTS, body).into_response();
|
|
457
|
+
let headers = response.headers_mut();
|
|
458
|
+
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
|
459
|
+
headers.insert(RETRY_AFTER, HeaderValue::from(retry_after_secs));
|
|
460
|
+
response
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
#[cfg(test)]
|
|
464
|
+
mod tests {
|
|
465
|
+
use super::*;
|
|
466
|
+
|
|
467
|
+
const HOUR: Duration = Duration::from_secs(3600);
|
|
468
|
+
const VISITOR: &str = "203.0.113.7";
|
|
469
|
+
const EDGE: &str = "130.176.1.9";
|
|
470
|
+
|
|
471
|
+
fn ip(text: &str) -> IpAddr {
|
|
472
|
+
text.parse().unwrap()
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
fn trust(networks: &[&str], hops: usize, auth: Option<(&str, &str)>) -> ProxyTrust {
|
|
476
|
+
ProxyTrust {
|
|
477
|
+
networks: networks.iter().map(|n| IpNet::parse(n).unwrap()).collect(),
|
|
478
|
+
hops,
|
|
479
|
+
auth: auth.map(|(header, secret)| ProxyAuth { header: HeaderName::from_bytes(header.as_bytes()).unwrap(), secret: secret.to_string() }),
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
fn config_from(pairs: &[(&str, &str)]) -> (Config, Vec<String>) {
|
|
484
|
+
let map: HashMap<String, String> = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
|
|
485
|
+
Config::from_lookup(|name| map.get(name).cloned())
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
fn limits(pairs: &[(&str, &str)]) -> RateLimits {
|
|
489
|
+
RateLimits::new(config_from(pairs).0)
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
|
|
493
|
+
let mut map = HeaderMap::new();
|
|
494
|
+
for (name, value) in pairs {
|
|
495
|
+
map.append(HeaderName::from_bytes(name.as_bytes()).unwrap(), HeaderValue::from_str(value).unwrap());
|
|
496
|
+
}
|
|
497
|
+
map
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
#[test]
|
|
501
|
+
fn allows_up_to_the_limit_then_refuses_with_the_seconds_until_the_oldest_hit_expires() {
|
|
502
|
+
let start = Instant::now();
|
|
503
|
+
let mut window = SlidingWindow::new(3, HOUR, 100);
|
|
504
|
+
assert_eq!(window.check("a", start), Decision { allowed: true, remaining: 2, retry_after_secs: 0 });
|
|
505
|
+
assert_eq!(window.check("a", start + Duration::from_secs(10)).remaining, 1);
|
|
506
|
+
assert_eq!(window.check("a", start + Duration::from_secs(20)).remaining, 0);
|
|
507
|
+
|
|
508
|
+
let refused = window.check("a", start + Duration::from_secs(30));
|
|
509
|
+
assert!(!refused.allowed);
|
|
510
|
+
assert_eq!(refused.retry_after_secs, 3600 - 30);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
#[test]
|
|
514
|
+
fn the_window_slides_so_a_hit_ages_out_individually() {
|
|
515
|
+
let start = Instant::now();
|
|
516
|
+
let mut window = SlidingWindow::new(2, HOUR, 100);
|
|
517
|
+
window.check("a", start);
|
|
518
|
+
window.check("a", start + Duration::from_secs(1800));
|
|
519
|
+
assert!(!window.check("a", start + Duration::from_secs(1801)).allowed);
|
|
520
|
+
|
|
521
|
+
let later = start + Duration::from_secs(3601);
|
|
522
|
+
assert!(window.check("a", later).allowed, "the first hit is past the window");
|
|
523
|
+
assert!(!window.check("a", later).allowed, "the second is still inside it");
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
#[test]
|
|
527
|
+
fn keys_are_independent() {
|
|
528
|
+
let now = Instant::now();
|
|
529
|
+
let mut window = SlidingWindow::new(1, HOUR, 100);
|
|
530
|
+
assert!(window.check("a", now).allowed);
|
|
531
|
+
assert!(!window.check("a", now).allowed);
|
|
532
|
+
assert!(window.check("b", now).allowed);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
#[test]
|
|
536
|
+
fn refused_requests_are_not_recorded_so_hammering_does_not_extend_the_lockout() {
|
|
537
|
+
let start = Instant::now();
|
|
538
|
+
let mut window = SlidingWindow::new(1, HOUR, 100);
|
|
539
|
+
window.check("a", start);
|
|
540
|
+
for second in 1..=50 {
|
|
541
|
+
assert!(!window.check("a", start + Duration::from_secs(second)).allowed);
|
|
542
|
+
}
|
|
543
|
+
assert!(window.check("a", start + HOUR).allowed, "the one recorded hit expired on schedule");
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
#[test]
|
|
547
|
+
fn retry_after_is_at_least_one_second_and_rounds_up() {
|
|
548
|
+
let start = Instant::now();
|
|
549
|
+
let mut window = SlidingWindow::new(1, Duration::from_millis(1500), 100);
|
|
550
|
+
window.check("a", start);
|
|
551
|
+
assert_eq!(window.check("a", start + Duration::from_millis(1)).retry_after_secs, 2);
|
|
552
|
+
assert_eq!(window.check("a", start + Duration::from_millis(1499)).retry_after_secs, 1);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
#[test]
|
|
556
|
+
fn expired_keys_are_swept_before_live_ones_are_evicted() {
|
|
557
|
+
let start = Instant::now();
|
|
558
|
+
let mut window = SlidingWindow::new(1, HOUR, 3);
|
|
559
|
+
window.check("old1", start);
|
|
560
|
+
window.check("old2", start);
|
|
561
|
+
let later = start + HOUR + Duration::from_secs(1);
|
|
562
|
+
window.check("live", later);
|
|
563
|
+
window.check("new1", later);
|
|
564
|
+
assert_eq!(window.len(), 2, "sweeping dropped old1 and old2, not live");
|
|
565
|
+
assert!(!window.check("live", later).allowed, "live was kept");
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
#[test]
|
|
569
|
+
fn at_the_size_cap_the_least_recently_active_key_is_evicted() {
|
|
570
|
+
let start = Instant::now();
|
|
571
|
+
let mut window = SlidingWindow::new(1, HOUR, 3);
|
|
572
|
+
for (i, key) in ["a", "b", "c", "d", "e"].iter().enumerate() {
|
|
573
|
+
window.check(key, start + Duration::from_millis(i as u64));
|
|
574
|
+
assert!(window.len() <= 3);
|
|
575
|
+
}
|
|
576
|
+
assert_eq!(window.len(), 3);
|
|
577
|
+
let now = start + Duration::from_millis(10);
|
|
578
|
+
assert!(window.check("a", now).allowed, "a was evicted, so it starts fresh");
|
|
579
|
+
assert!(!window.check("e", now).allowed, "e is still tracked");
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
#[test]
|
|
583
|
+
fn a_zero_limit_or_key_cap_is_raised_to_one() {
|
|
584
|
+
let mut window = SlidingWindow::new(0, HOUR, 0);
|
|
585
|
+
let now = Instant::now();
|
|
586
|
+
assert!(window.check("a", now).allowed);
|
|
587
|
+
assert!(!window.check("a", now).allowed);
|
|
588
|
+
assert!(window.check("b", now).allowed);
|
|
589
|
+
assert_eq!(window.len(), 1);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
#[test]
|
|
593
|
+
fn parses_and_matches_addresses_and_cidr_ranges() {
|
|
594
|
+
let single = IpNet::parse("10.0.0.5").unwrap();
|
|
595
|
+
assert!(single.contains(ip("10.0.0.5")));
|
|
596
|
+
assert!(!single.contains(ip("10.0.0.6")));
|
|
597
|
+
|
|
598
|
+
let range = IpNet::parse("10.0.0.0/8").unwrap();
|
|
599
|
+
assert!(range.contains(ip("10.255.1.2")));
|
|
600
|
+
assert!(!range.contains(ip("11.0.0.1")));
|
|
601
|
+
|
|
602
|
+
let v6 = IpNet::parse("fd00::/8").unwrap();
|
|
603
|
+
assert!(v6.contains(ip("fd12::1")));
|
|
604
|
+
assert!(!v6.contains(ip("2001:db8::1")));
|
|
605
|
+
assert!(!v6.contains(ip("10.0.0.1")), "families never match each other");
|
|
606
|
+
|
|
607
|
+
assert!(IpNet::parse("0.0.0.0/0").unwrap().contains(ip("8.8.8.8")));
|
|
608
|
+
assert!(IpNet::parse("10.0.0.0/8").unwrap().contains(ip("::ffff:10.1.1.1")), "a mapped address is its IPv4 form");
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
#[test]
|
|
612
|
+
fn rejects_malformed_ranges() {
|
|
613
|
+
for bad in ["", "banana", "10.0.0.0/33", "::1/129", "10.0.0.0/", "10.0.0/8", "/8"] {
|
|
614
|
+
assert!(IpNet::parse(bad).is_none(), "{bad:?}");
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
#[test]
|
|
619
|
+
fn with_nothing_trusted_the_peer_is_the_client_and_the_header_is_ignored() {
|
|
620
|
+
let none = trust(&[], 0, None);
|
|
621
|
+
assert_eq!(none.client_ip(Some(ip("198.51.100.4")), Some("6.6.6.6"), None), Some(ip("198.51.100.4")));
|
|
622
|
+
assert_eq!(none.client_ip(None, Some("6.6.6.6"), None), None);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
#[test]
|
|
626
|
+
fn an_untrusted_peer_cannot_choose_its_own_key_by_sending_a_header() {
|
|
627
|
+
let proxies = trust(&["10.0.0.0/8"], 0, None);
|
|
628
|
+
let from_stranger = |spoof: &str| proxies.client_ip(Some(ip("198.51.100.4")), Some(spoof), None);
|
|
629
|
+
assert_eq!(from_stranger("1.1.1.1"), from_stranger("2.2.2.2"));
|
|
630
|
+
assert_eq!(from_stranger("1.1.1.1"), Some(ip("198.51.100.4")));
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
#[test]
|
|
634
|
+
fn a_trusted_peer_is_believed_and_the_rightmost_entry_is_the_client() {
|
|
635
|
+
let proxies = trust(&["10.0.0.0/8"], 0, None);
|
|
636
|
+
assert_eq!(proxies.client_ip(Some(ip("10.0.0.5")), Some(&format!("6.6.6.6, {VISITOR}")), None), Some(ip(VISITOR)));
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
#[test]
|
|
640
|
+
fn a_spoofed_leading_entry_is_never_reached() {
|
|
641
|
+
let proxies = trust(&["10.0.0.0/8"], 0, None);
|
|
642
|
+
let forwarded = format!("6.6.6.6, 7.7.7.7, {VISITOR}, 10.0.0.9");
|
|
643
|
+
assert_eq!(proxies.client_ip(Some(ip("10.0.0.5")), Some(&forwarded), None), Some(ip(VISITOR)));
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
#[test]
|
|
647
|
+
fn a_visitor_cannot_pick_their_key_by_varying_the_spoofed_part() {
|
|
648
|
+
let proxies = trust(&["10.0.0.0/8"], 0, None);
|
|
649
|
+
let key = |spoof: &str| proxies.client_ip(Some(ip("10.0.0.5")), Some(&format!("{spoof}, {VISITOR}")), None);
|
|
650
|
+
assert_eq!(key("1.1.1.1"), key("2.2.2.2"));
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
#[test]
|
|
654
|
+
fn trusted_proxies_inside_the_header_are_skipped_from_the_right() {
|
|
655
|
+
let proxies = trust(&["10.0.0.0/8", "172.16.0.0/12"], 0, None);
|
|
656
|
+
let forwarded = format!("6.6.6.6, {VISITOR}, 172.16.0.3, 10.0.0.9");
|
|
657
|
+
assert_eq!(proxies.client_ip(Some(ip("10.0.0.5")), Some(&forwarded), None), Some(ip(VISITOR)));
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
#[test]
|
|
661
|
+
fn the_shared_secret_authenticates_a_request_from_an_unlisted_peer() {
|
|
662
|
+
let cdn = trust(&[], 1, Some(("x-origin-secret", "s3cret")));
|
|
663
|
+
let forwarded = format!("6.6.6.6, {VISITOR}, {EDGE}");
|
|
664
|
+
assert_eq!(cdn.client_ip(Some(ip("10.0.0.5")), Some(&forwarded), Some("s3cret")), Some(ip(VISITOR)));
|
|
665
|
+
assert_eq!(cdn.client_ip(Some(ip("10.0.0.5")), Some(&forwarded), Some("wrong")), Some(ip("10.0.0.5")));
|
|
666
|
+
assert_eq!(cdn.client_ip(Some(ip("10.0.0.5")), Some(&forwarded), None), Some(ip("10.0.0.5")));
|
|
667
|
+
assert_eq!(cdn.client_ip(Some(ip("10.0.0.5")), Some(&forwarded), Some("s3cret-and-more")), Some(ip("10.0.0.5")));
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
#[test]
|
|
671
|
+
fn hops_skip_the_rightmost_entries_added_by_unlisted_proxies() {
|
|
672
|
+
let cdn = trust(&[], 1, Some(("x-origin-secret", "s")));
|
|
673
|
+
let one = format!("6.6.6.6, 7.7.7.7, {VISITOR}, {EDGE}");
|
|
674
|
+
assert_eq!(cdn.client_ip(None, Some(&one), Some("s")), Some(ip(VISITOR)));
|
|
675
|
+
|
|
676
|
+
let two = trust(&[], 2, Some(("x-origin-secret", "s")));
|
|
677
|
+
let forwarded = format!("6.6.6.6, {VISITOR}, {EDGE}, 130.176.2.2");
|
|
678
|
+
assert_eq!(two.client_ip(None, Some(&forwarded), Some("s")), Some(ip(VISITOR)));
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
#[test]
|
|
682
|
+
fn a_header_shorter_than_the_walk_implies_yields_no_client() {
|
|
683
|
+
let cdn = trust(&[], 1, Some(("x-origin-secret", "s")));
|
|
684
|
+
assert_eq!(cdn.client_ip(Some(ip("127.0.0.1")), Some("6.6.6.6"), Some("s")), None);
|
|
685
|
+
let listed = trust(&["10.0.0.0/8"], 0, None);
|
|
686
|
+
assert_eq!(listed.client_ip(Some(ip("10.0.0.5")), Some("10.0.0.9, 10.0.0.8"), None), None, "every entry is one of ours");
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
#[test]
|
|
690
|
+
fn a_client_entry_that_is_not_an_address_yields_no_client() {
|
|
691
|
+
let proxies = trust(&["10.0.0.0/8"], 0, None);
|
|
692
|
+
assert_eq!(proxies.client_ip(Some(ip("10.0.0.5")), Some("6.6.6.6, not-an-ip"), None), None);
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
#[test]
|
|
696
|
+
fn a_trusted_peer_with_no_header_is_its_own_client() {
|
|
697
|
+
let proxies = trust(&["127.0.0.1"], 0, None);
|
|
698
|
+
assert_eq!(proxies.client_ip(Some(ip("127.0.0.1")), None, None), Some(ip("127.0.0.1")));
|
|
699
|
+
assert_eq!(proxies.client_ip(Some(ip("127.0.0.1")), Some(" , "), None), Some(ip("127.0.0.1")));
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
#[test]
|
|
703
|
+
fn tolerates_spaces_empty_entries_and_ipv6() {
|
|
704
|
+
let proxies = trust(&["10.0.0.0/8"], 0, None);
|
|
705
|
+
let forwarded = " 9.9.9.9 ,, 2001:db8::1 , 10.0.0.9 ";
|
|
706
|
+
assert_eq!(proxies.client_ip(Some(ip("10.0.0.5")), Some(forwarded), None), Some(ip("2001:db8::1")));
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
#[test]
|
|
710
|
+
fn a_mapped_peer_is_matched_as_its_ipv4_form() {
|
|
711
|
+
let proxies = trust(&["10.0.0.0/8"], 0, None);
|
|
712
|
+
assert_eq!(proxies.client_ip(Some(ip("::ffff:10.0.0.5")), Some(VISITOR), None), Some(ip(VISITOR)));
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
#[test]
|
|
716
|
+
fn ipv6_callers_are_bucketed_by_their_64() {
|
|
717
|
+
assert_eq!(bucket_key(ip("2001:db8:1:2:aaaa:bbbb:cccc:dddd")), bucket_key(ip("2001:db8:1:2::1")));
|
|
718
|
+
assert_ne!(bucket_key(ip("2001:db8:1:2::1")), bucket_key(ip("2001:db8:1:3::1")));
|
|
719
|
+
assert_eq!(bucket_key(ip("203.0.113.7")), "203.0.113.7");
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
#[test]
|
|
723
|
+
fn defaults_are_on_with_no_trust() {
|
|
724
|
+
let (config, warnings) = config_from(&[]);
|
|
725
|
+
assert!(warnings.is_empty());
|
|
726
|
+
assert!(config.enabled);
|
|
727
|
+
assert_eq!(config.window, HOUR);
|
|
728
|
+
assert_eq!((config.subscribe, config.register, config.max_keys), (10, 15, 10_000));
|
|
729
|
+
assert_eq!(config.trust, ProxyTrust::default());
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
#[test]
|
|
733
|
+
fn every_setting_can_be_tuned() {
|
|
734
|
+
let (config, warnings) = config_from(&[
|
|
735
|
+
("HECKS_RATE_LIMIT_WINDOW_SECONDS", " 60 "),
|
|
736
|
+
("HECKS_RATE_LIMIT_SUBSCRIBE", "3"),
|
|
737
|
+
("HECKS_RATE_LIMIT_REGISTER", "4"),
|
|
738
|
+
("HECKS_RATE_LIMIT_MAX_KEYS", "50"),
|
|
739
|
+
("HECKS_TRUSTED_PROXIES", "10.0.0.0/8, 127.0.0.1"),
|
|
740
|
+
("HECKS_TRUSTED_PROXY_HOPS", "1"),
|
|
741
|
+
("HECKS_PROXY_AUTH_HEADER", "X-Origin-Secret"),
|
|
742
|
+
("HECKS_PROXY_AUTH_SECRET", "s3cret"),
|
|
743
|
+
]);
|
|
744
|
+
assert!(warnings.is_empty(), "{warnings:?}");
|
|
745
|
+
assert_eq!(config.window, Duration::from_secs(60));
|
|
746
|
+
assert_eq!((config.subscribe, config.register, config.max_keys), (3, 4, 50));
|
|
747
|
+
assert_eq!(config.trust, trust(&["10.0.0.0/8", "127.0.0.1"], 1, Some(("x-origin-secret", "s3cret"))));
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
#[test]
|
|
751
|
+
fn off_values_turn_the_limits_off_and_anything_else_leaves_them_on() {
|
|
752
|
+
for off in ["off", "OFF", " false ", "0", "no", "disabled"] {
|
|
753
|
+
assert!(!config_from(&[("HECKS_RATE_LIMIT", off)]).0.enabled, "{off:?}");
|
|
754
|
+
}
|
|
755
|
+
for on in ["on", "true", "1", ""] {
|
|
756
|
+
assert!(config_from(&[("HECKS_RATE_LIMIT", on)]).0.enabled, "{on:?}");
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
#[test]
|
|
761
|
+
fn unusable_values_fall_back_and_are_reported() {
|
|
762
|
+
let (config, warnings) = config_from(&[
|
|
763
|
+
("HECKS_RATE_LIMIT_SUBSCRIBE", "0"),
|
|
764
|
+
("HECKS_RATE_LIMIT_REGISTER", "lots"),
|
|
765
|
+
("HECKS_RATE_LIMIT_WINDOW_SECONDS", "-5"),
|
|
766
|
+
("HECKS_TRUSTED_PROXY_HOPS", "two"),
|
|
767
|
+
("HECKS_TRUSTED_PROXIES", "10.0.0.0/8, banana"),
|
|
768
|
+
]);
|
|
769
|
+
assert_eq!((config.subscribe, config.register, config.window), (10, 15, HOUR));
|
|
770
|
+
assert_eq!(config.trust.hops, 0);
|
|
771
|
+
assert_eq!(config.trust.networks.len(), 1);
|
|
772
|
+
assert_eq!(warnings.len(), 5, "{warnings:?}");
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
#[test]
|
|
776
|
+
fn proxy_authentication_needs_both_a_header_and_a_secret() {
|
|
777
|
+
for pairs in [&[("HECKS_PROXY_AUTH_HEADER", "x-secret")][..], &[("HECKS_PROXY_AUTH_SECRET", "s")][..]] {
|
|
778
|
+
let (config, warnings) = config_from(pairs);
|
|
779
|
+
assert!(config.trust.auth.is_none());
|
|
780
|
+
assert_eq!(warnings.len(), 1);
|
|
781
|
+
}
|
|
782
|
+
let (config, warnings) = config_from(&[("HECKS_PROXY_AUTH_HEADER", "not a header"), ("HECKS_PROXY_AUTH_SECRET", "s")]);
|
|
783
|
+
assert!(config.trust.auth.is_none());
|
|
784
|
+
assert_eq!(warnings.len(), 1);
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
#[test]
|
|
788
|
+
fn only_the_public_write_routes_are_limited() {
|
|
789
|
+
assert_eq!(Form::for_request("POST", "/newsletter/subscribers"), Some(Form::Subscribe));
|
|
790
|
+
assert_eq!(Form::for_request("POST", "/registrations"), Some(Form::Register));
|
|
791
|
+
for (method, path) in [
|
|
792
|
+
("GET", "/newsletter/subscribers"),
|
|
793
|
+
("GET", "/newsletter/subscribers/confirm"),
|
|
794
|
+
("GET", "/newsletter/subscribers/unsubscribe"),
|
|
795
|
+
("GET", "/registrations"),
|
|
796
|
+
("GET", "/registrations/REG-1"),
|
|
797
|
+
("POST", "/registrations/REG-1/complete"),
|
|
798
|
+
("POST", "/webhooks/stripe"),
|
|
799
|
+
("POST", "/events"),
|
|
800
|
+
("POST", "/members"),
|
|
801
|
+
("POST", "/newsletter/subscribers/"),
|
|
802
|
+
] {
|
|
803
|
+
assert_eq!(Form::for_request(method, path), None, "{method} {path}");
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
#[test]
|
|
808
|
+
fn each_route_has_its_own_budget_per_client() {
|
|
809
|
+
let limits = limits(&[("HECKS_RATE_LIMIT_SUBSCRIBE", "2"), ("HECKS_RATE_LIMIT_REGISTER", "1")]);
|
|
810
|
+
let (none, peer, now) = (HeaderMap::new(), Some(ip("198.51.100.4")), Instant::now());
|
|
811
|
+
let hit = |path: &str| limits.check_at("POST", path, &none, peer, now);
|
|
812
|
+
|
|
813
|
+
assert_eq!(hit("/newsletter/subscribers"), Verdict::Allowed);
|
|
814
|
+
assert_eq!(hit("/newsletter/subscribers"), Verdict::Allowed);
|
|
815
|
+
assert_eq!(hit("/newsletter/subscribers"), Verdict::Limited { retry_after_secs: 3600 });
|
|
816
|
+
assert_eq!(hit("/registrations"), Verdict::Allowed, "subscribe being spent does not touch register");
|
|
817
|
+
assert_eq!(hit("/registrations"), Verdict::Limited { retry_after_secs: 3600 });
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
#[test]
|
|
821
|
+
fn the_window_rolls_over() {
|
|
822
|
+
let limits = limits(&[("HECKS_RATE_LIMIT_REGISTER", "1"), ("HECKS_RATE_LIMIT_WINDOW_SECONDS", "60")]);
|
|
823
|
+
let (none, peer, start) = (HeaderMap::new(), Some(ip("198.51.100.4")), Instant::now());
|
|
824
|
+
let at = |secs: u64| limits.check_at("POST", "/registrations", &none, peer, start + Duration::from_secs(secs));
|
|
825
|
+
|
|
826
|
+
assert_eq!(at(0), Verdict::Allowed);
|
|
827
|
+
assert_eq!(at(10), Verdict::Limited { retry_after_secs: 50 });
|
|
828
|
+
assert_eq!(at(60), Verdict::Allowed);
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
#[test]
|
|
832
|
+
fn unlimited_routes_and_disabled_limits_always_allow() {
|
|
833
|
+
let on = limits(&[("HECKS_RATE_LIMIT_SUBSCRIBE", "1")]);
|
|
834
|
+
let (none, peer, now) = (HeaderMap::new(), Some(ip("198.51.100.4")), Instant::now());
|
|
835
|
+
for _ in 0..5 {
|
|
836
|
+
assert_eq!(on.check_at("GET", "/newsletter/subscribers", &none, peer, now), Verdict::Allowed);
|
|
837
|
+
assert_eq!(on.check_at("POST", "/webhooks/stripe", &none, peer, now), Verdict::Allowed);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
let off = limits(&[("HECKS_RATE_LIMIT", "off"), ("HECKS_RATE_LIMIT_SUBSCRIBE", "1")]);
|
|
841
|
+
for _ in 0..5 {
|
|
842
|
+
assert_eq!(off.check_at("POST", "/newsletter/subscribers", &none, peer, now), Verdict::Allowed);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
#[test]
|
|
847
|
+
fn a_spoofed_header_from_an_untrusted_peer_does_not_reset_the_count() {
|
|
848
|
+
let limits = limits(&[("HECKS_RATE_LIMIT_SUBSCRIBE", "1"), ("HECKS_TRUSTED_PROXIES", "10.0.0.0/8")]);
|
|
849
|
+
let (peer, now) = (Some(ip("198.51.100.4")), Instant::now());
|
|
850
|
+
let send = |spoof: &str| limits.check_at("POST", "/newsletter/subscribers", &headers(&[("x-forwarded-for", spoof)]), peer, now);
|
|
851
|
+
|
|
852
|
+
assert_eq!(send("1.1.1.1"), Verdict::Allowed);
|
|
853
|
+
assert!(matches!(send("2.2.2.2"), Verdict::Limited { .. }));
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
#[test]
|
|
857
|
+
fn behind_the_shared_secret_each_visitor_has_their_own_budget() {
|
|
858
|
+
let limits = limits(&[
|
|
859
|
+
("HECKS_RATE_LIMIT_REGISTER", "1"),
|
|
860
|
+
("HECKS_PROXY_AUTH_HEADER", "x-origin-secret"),
|
|
861
|
+
("HECKS_PROXY_AUTH_SECRET", "s3cret"),
|
|
862
|
+
("HECKS_TRUSTED_PROXY_HOPS", "1"),
|
|
863
|
+
]);
|
|
864
|
+
let (alb, now) = (Some(ip("10.0.0.5")), Instant::now());
|
|
865
|
+
let from = |spoof: &str, visitor: &str| {
|
|
866
|
+
let forwarded = format!("{spoof}, {visitor}, {EDGE}");
|
|
867
|
+
limits.check_at("POST", "/registrations", &headers(&[("x-origin-secret", "s3cret"), ("x-forwarded-for", &forwarded)]), alb, now)
|
|
868
|
+
};
|
|
869
|
+
|
|
870
|
+
assert_eq!(from("1.1.1.1", VISITOR), Verdict::Allowed);
|
|
871
|
+
assert!(matches!(from("2.2.2.2", VISITOR), Verdict::Limited { .. }), "a new spoofed entry is not a new visitor");
|
|
872
|
+
assert_eq!(from("2.2.2.2", "198.51.100.4"), Verdict::Allowed, "another visitor has their own count");
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
#[test]
|
|
876
|
+
fn requests_whose_client_cannot_be_determined_share_one_bucket() {
|
|
877
|
+
let limits = limits(&[("HECKS_RATE_LIMIT_REGISTER", "1"), ("HECKS_TRUSTED_PROXIES", "10.0.0.0/8")]);
|
|
878
|
+
let now = Instant::now();
|
|
879
|
+
let short = headers(&[("x-forwarded-for", "10.0.0.9")]);
|
|
880
|
+
assert_eq!(limits.check_at("POST", "/registrations", &short, Some(ip("10.0.0.5")), now), Verdict::Allowed);
|
|
881
|
+
assert!(matches!(limits.check_at("POST", "/registrations", &short, Some(ip("10.0.0.6")), now), Verdict::Limited { .. }));
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
#[test]
|
|
885
|
+
fn repeated_forwarded_header_lines_read_as_one_list() {
|
|
886
|
+
let limits = limits(&[("HECKS_RATE_LIMIT_REGISTER", "1"), ("HECKS_TRUSTED_PROXIES", "10.0.0.0/8")]);
|
|
887
|
+
let (peer, now) = (Some(ip("10.0.0.5")), Instant::now());
|
|
888
|
+
let split = headers(&[("x-forwarded-for", "6.6.6.6"), ("x-forwarded-for", VISITOR)]);
|
|
889
|
+
let joined = headers(&[("x-forwarded-for", &format!("9.9.9.9, {VISITOR}"))]);
|
|
890
|
+
assert_eq!(limits.check_at("POST", "/registrations", &split, peer, now), Verdict::Allowed);
|
|
891
|
+
assert!(matches!(limits.check_at("POST", "/registrations", &joined, peer, now), Verdict::Limited { .. }));
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
#[tokio::test]
|
|
895
|
+
async fn the_refusal_is_a_429_with_retry_after_and_the_json_error_shape() {
|
|
896
|
+
let response = too_many_requests(120);
|
|
897
|
+
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
|
898
|
+
assert_eq!(response.headers()[RETRY_AFTER], "120");
|
|
899
|
+
assert_eq!(response.headers()[CONTENT_TYPE], "application/json");
|
|
900
|
+
let bytes = axum::body::to_bytes(response.into_body(), 4096).await.unwrap();
|
|
901
|
+
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
|
902
|
+
assert_eq!(body, json!({ "error": "too many requests, please try again later" }));
|
|
903
|
+
}
|
|
904
|
+
}
|