0
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2026-08-07 13:19:19 +08:00
discourse/db/migrate/20260629210246_revoke_invalid_read_only_api_keys.rb
Mark VanLandingham 7c82423416
FIX: Prevent read-only keys being created without scopes (#42280)
## Summary

Prevent read-only API keys from being created without scopes, which
previously granted them unscoped access. This was already enforced for
Api keys created via the UI. The fix enforces a mandatory 'global:read'
scope for read-only keys at the model and API levels, and includes a
migration to revoke existing invalid keys.

## Source

- Patch Triage: https://patch.discourse.org/patch-triage/1192
2026-08-03 15:45:48 -05:00

31 lines
792 B
Ruby
Vendored

# frozen_string_literal: true
class RevokeInvalidReadOnlyApiKeys < ActiveRecord::Migration[8.0]
def up
execute <<~SQL
UPDATE api_keys
SET revoked_at = CURRENT_TIMESTAMP,
updated_at = CURRENT_TIMESTAMP
WHERE scope_mode = 1
AND revoked_at IS NULL
AND NOT (
(
SELECT COUNT(*)
FROM api_key_scopes
WHERE api_key_scopes.api_key_id = api_keys.id
) = 1
AND EXISTS (
SELECT 1
FROM api_key_scopes
WHERE api_key_scopes.api_key_id = api_keys.id
AND api_key_scopes.resource = 'global'
AND api_key_scopes.action = 'read'
)
)
SQL
end
def down
raise ActiveRecord::IrreversibleMigration
end
end