Files
sure/test/controllers/api/v1/usage_controller_test.rb
ghost 95f6451b39 feat(sync): add Brex provider connections (#1752)
* feat(sync): add Brex provider schema

Adds Brex item and account tables with per-family credentials, scoped upstream account uniqueness, encrypted token storage, and sanitized provider payload columns.

* feat(sync): add Brex provider core

Adds Brex item/account models, provider client and adapter support, family connection helpers, and provider enum registration for read-only Brex cash and card data.

* feat(sync): add Brex import pipeline

Adds Brex account discovery, linked-account sync, cash/card balance processors, transaction import, sanitized metadata handling, and idempotent provider entry processing.

* feat(sync): add Brex connection flows

Adds Mercury-style Brex connection management, explicit item-scoped account selection and linking, settings provider UI, account index visibility, localized copy, and per-item cache handling.

* test(sync): cover Brex provider workflows

Adds targeted coverage for Brex provider requests, adapter config, item/account guards, importer behavior, entry processing, and Mercury-style controller flows.

* fix(sync): align Brex API edge cases

Tightens Brex account fetching against the official card-account response shape, sends transaction start filters as RFC3339 date-times, and keeps provider error bodies out of user-facing messages while expanding provider client guard coverage.

* fix(sync): harden Brex provider integration

Restrict Brex API base URLs to official hosts, tighten account-selection UI behavior, and add tests for invalid credentials, cache scoping, and provider setup edge cases.

* test(sync): avoid Brex secret-shaped fixtures

* refactor(sync): extract Brex account flows

* fix(sync): address Brex provider review feedback

* fix(sync): address Brex review follow-ups

Move remaining Brex review cleanup into focused model behavior, tighten link/setup edge cases, localize summaries, and add regression coverage from CodeRabbit feedback.

Also records the security-review pass as no-findings after diff-scoped inspection and Brakeman validation.

* refactor(sync): split Brex account flow controllers

Route Brex account selection and setup actions through small namespaced controllers while keeping existing URLs and helpers stable.

Business flow remains in BrexItem::AccountFlow; the main Brex item controller now only handles connection CRUD, provider-panel rendering, destroy, and sync.

* fix(sync): address Brex CodeRabbit review

* fix(sync): address Brex follow-up review

* fix(sync): address Brex review follow-ups

* fix(sync): address Brex sync review findings

* fix(sync): polish Brex review copy and errors

* fix(sync): register Brex provider health

* fix(sync): polish Brex bank sync presentation

* fix(sync): address Brex review follow-ups

* fix(sync): tighten Brex setup params

* test(api): stabilize usage rate-limit window

* fix(sync): polish Brex setup flow nits

* fix(sync): harden Brex setup params

* fix(sync): finalize Brex review cleanup

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-05-13 18:13:48 +02:00

139 lines
4.8 KiB
Ruby

require "test_helper"
class Api::V1::UsageControllerTest < ActionDispatch::IntegrationTest
setup do
@user = users(:family_admin)
# Destroy any existing active API keys for this user
@user.api_keys.active.destroy_all
@api_key = ApiKey.create!(
user: @user,
name: "Test API Key",
scopes: [ "read" ],
display_key: "usage_test_#{SecureRandom.hex(8)}"
)
# Clear any existing rate limit data
Redis.new.del("api_rate_limit:#{@api_key.id}")
end
teardown do
# Clean up Redis data after each test
Redis.new.del("api_rate_limit:#{@api_key.id}")
end
test "should return usage information for API key authentication" do
# Make a few requests to generate some usage
3.times do
get "/api/v1/test", headers: { "X-Api-Key" => @api_key.display_key }
assert_response :success
end
# Now check usage
get "/api/v1/usage", headers: { "X-Api-Key" => @api_key.display_key }
assert_response :success
response_body = JSON.parse(response.body)
# Check API key information
assert_equal "Test API Key", response_body["api_key"]["name"]
assert_equal [ "read" ], response_body["api_key"]["scopes"]
assert_not_nil response_body["api_key"]["last_used_at"]
assert_not_nil response_body["api_key"]["created_at"]
# Check rate limit information
assert_equal "standard", response_body["rate_limit"]["tier"]
assert_equal 100, response_body["rate_limit"]["limit"]
assert_equal 4, response_body["rate_limit"]["current_count"] # 3 test requests + 1 usage request
assert_equal 96, response_body["rate_limit"]["remaining"]
assert response_body["rate_limit"]["reset_in_seconds"] > 0
assert_not_nil response_body["rate_limit"]["reset_at"]
end
test "should require read scope for usage endpoint" do
# Create an API key without read scope (this shouldn't be possible with current validations, but let's test)
api_key_no_read = ApiKey.new(
user: @user,
name: "No Read Key",
scopes: [],
display_key: "no_read_key_#{SecureRandom.hex(8)}"
)
# Skip validations to create invalid key for testing
api_key_no_read.save(validate: false)
begin
get "/api/v1/usage", headers: { "X-Api-Key" => api_key_no_read.display_key }
assert_response :forbidden
response_body = JSON.parse(response.body)
assert_equal "insufficient_scope", response_body["error"]
ensure
Redis.new.del("api_rate_limit:#{api_key_no_read.id}")
api_key_no_read.destroy
end
end
test "should return correct message for OAuth authentication" do
# This test would need OAuth setup, but for now we can mock it
# For the current implementation, we'll test what happens with no authentication
get "/api/v1/usage"
assert_response :unauthorized
end
test "should update usage count when accessing usage endpoint" do
# Check initial state
get "/api/v1/usage", headers: { "X-Api-Key" => @api_key.display_key }
assert_response :success
response_body = JSON.parse(response.body)
first_count = response_body["rate_limit"]["current_count"]
# Make another usage request
get "/api/v1/usage", headers: { "X-Api-Key" => @api_key.display_key }
assert_response :success
response_body = JSON.parse(response.body)
second_count = response_body["rate_limit"]["current_count"]
assert_equal first_count + 1, second_count
end
test "should include rate limit headers in usage response" do
get "/api/v1/usage", headers: { "X-Api-Key" => @api_key.display_key }
assert_response :success
assert_not_nil response.headers["X-RateLimit-Limit"]
assert_not_nil response.headers["X-RateLimit-Remaining"]
assert_not_nil response.headers["X-RateLimit-Reset"]
assert_equal "100", response.headers["X-RateLimit-Limit"]
assert_equal "99", response.headers["X-RateLimit-Remaining"]
end
test "should work correctly when approaching rate limit" do
travel_to Time.zone.local(2026, 1, 1, 12, 15, 0) do
# Make 98 requests to get close to the limit
98.times do
get "/api/v1/test", headers: { "X-Api-Key" => @api_key.display_key }
assert_response :success
end
# Check usage - this should be request 99
get "/api/v1/usage", headers: { "X-Api-Key" => @api_key.display_key }
assert_response :success
response_body = JSON.parse(response.body)
assert_equal 99, response_body["rate_limit"]["current_count"]
assert_equal 1, response_body["rate_limit"]["remaining"]
# One more request should hit the limit
get "/api/v1/test", headers: { "X-Api-Key" => @api_key.display_key }
assert_response :success
# Now we should be rate limited
get "/api/v1/usage", headers: { "X-Api-Key" => @api_key.display_key }
assert_response :too_many_requests
end
end
end