mirror of
https://github.com/discourse/discourse.git
synced 2025-05-21 18:12:32 +08:00
FEATURE: Overhaul of admin API key system (#8284)
- Allow revoking keys without deleting them - Auto-revoke keys after a period of no use (default 6 months) - Allow multiple keys per user - Allow attaching a description to each key, for easier auditing - Log changes to keys in the staff action log - Move all key management to one place, and improve the UI
This commit is contained in:
@ -10,12 +10,59 @@ describe ApiKey do
|
||||
it { is_expected.to belong_to :created_by }
|
||||
it { is_expected.to validate_presence_of :key }
|
||||
|
||||
it 'validates uniqueness of user_id' do
|
||||
Fabricate(:api_key, user: user)
|
||||
api_key = Fabricate.build(:api_key, user: user)
|
||||
it 'generates a key when saving' do
|
||||
key = ApiKey.new
|
||||
key.save!
|
||||
initial_key = key.key
|
||||
expect(initial_key.length).to eq(64)
|
||||
|
||||
expect(api_key.save).to eq(false)
|
||||
expect(api_key.errors).to include(:user_id)
|
||||
# Does not overwrite key when saving again
|
||||
key.description = "My description here"
|
||||
key.save!
|
||||
expect(key.reload.key).to eq(initial_key)
|
||||
end
|
||||
|
||||
it "can calculate the epoch correctly" do
|
||||
expect(ApiKey.last_used_epoch.to_datetime).to be_a(DateTime)
|
||||
|
||||
SiteSetting.api_key_last_used_epoch = ""
|
||||
expect(ApiKey.last_used_epoch).to eq(nil)
|
||||
end
|
||||
|
||||
it "can automatically revoke keys" do
|
||||
now = Time.now
|
||||
|
||||
SiteSetting.api_key_last_used_epoch = now - 2.years
|
||||
SiteSetting.revoke_api_keys_days = 180 # 6 months
|
||||
|
||||
freeze_time now - 1.year
|
||||
never_used = Fabricate(:api_key)
|
||||
used_previously = Fabricate(:api_key)
|
||||
used_previously.update(last_used_at: Time.zone.now)
|
||||
used_recently = Fabricate(:api_key)
|
||||
|
||||
freeze_time now - 3.months
|
||||
used_recently.update(last_used_at: Time.zone.now)
|
||||
|
||||
freeze_time now
|
||||
ApiKey.revoke_unused_keys!
|
||||
|
||||
[never_used, used_previously, used_recently].each(&:reload)
|
||||
expect(never_used.revoked_at).to_not eq(nil)
|
||||
expect(used_previously.revoked_at).to_not eq(nil)
|
||||
expect(used_recently.revoked_at).to eq(nil)
|
||||
|
||||
# Restore them
|
||||
[never_used, used_previously, used_recently].each { |a| a.update(revoked_at: nil) }
|
||||
|
||||
# Move the epoch to 1 month ago
|
||||
SiteSetting.api_key_last_used_epoch = now - 1.month
|
||||
ApiKey.revoke_unused_keys!
|
||||
|
||||
[never_used, used_previously, used_recently].each(&:reload)
|
||||
expect(never_used.revoked_at).to eq(nil)
|
||||
expect(used_previously.revoked_at).to eq(nil)
|
||||
expect(used_recently.revoked_at).to eq(nil)
|
||||
end
|
||||
|
||||
end
|
||||
|
Reference in New Issue
Block a user