-
Notifications
You must be signed in to change notification settings - Fork 309
Improved API key handling #3094
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
1ac583f
Allow users to reset their API key
tillprochaska a2a94ae
Only return API key once after it has been generated
tillprochaska 399e85f
Add new UI to reset and display API key
tillprochaska 5d96021
Refactor existing settings screen
tillprochaska b13425c
Ensure that toasts are always visible, even when scrolling
tillprochaska 8065afa
Do not display password setting when password auth is disabled
tillprochaska 688bb96
Use session tokens for authentication in API tests
tillprochaska b3eac7f
Do not generate API tokens for new roles
tillprochaska d7420be
Handle users without an API key properly in the settings UI
tillprochaska 0622c84
Update wording to clarify that API keys are secrets
tillprochaska 6f03791
Rename "reset_api_key" to "generate_api_key"
tillprochaska be5f029
Send email notification when API key is (re-)generated
tillprochaska f30757f
Extract logic to regenerate API keys into separate module
tillprochaska e1ed9b6
Let API keys expire after 90 days
tillprochaska a506ebe
Extract `generate_api_key` method from role model
tillprochaska 6cc615b
Send notification when API keys are about to expire/have expired
tillprochaska 6d2d89b
Display API key expiration date in UI
tillprochaska 87ce636
Add CLI command to reset API key expiration of non-expiring API keys
tillprochaska 5e52e2d
Replace use of deprecated `utcnow` method
tillprochaska c091223
Remove unnecessary keys from API JSON response
tillprochaska 9a42b22
Add note to remind us to remove/update logic handling legacy API keys
tillprochaska b9ad42e
Send API key expiration notifications on a daily basis
tillprochaska c0ad86d
Fix Alembic migration order
tillprochaska 1e74da4
Reauthenticate user in test to update session cache
tillprochaska f95572a
Update wording of API key notification emails based on feedback
tillprochaska de6eeff
Use strict equality check
tillprochaska 9b9efa9
Clarify that API keys expire when generating a new key
tillprochaska 50b689e
Display different UI messages in case the API key has expired
tillprochaska 987b907
Fix Alembic migration order
tillprochaska File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
import datetime | ||
|
||
import structlog | ||
from flask import render_template | ||
from sqlalchemy import and_, or_, func | ||
|
||
from aleph.core import db | ||
from aleph.model import Role | ||
from aleph.model.common import make_token | ||
from aleph.logic.mail import email_role | ||
from aleph.logic.roles import update_role | ||
from aleph.logic.util import ui_url | ||
|
||
# Number of days after which API keys expire | ||
API_KEY_EXPIRATION_DAYS = 90 | ||
|
||
# Number of days before an API key expires | ||
API_KEY_EXPIRES_SOON_DAYS = 7 | ||
|
||
log = structlog.get_logger(__name__) | ||
|
||
|
||
def generate_user_api_key(role): | ||
event = "regenerated" if role.has_api_key else "generated" | ||
params = {"role": role, "event": event} | ||
plain = render_template("email/api_key_generated.txt", **params) | ||
html = render_template("email/api_key_generated.html", **params) | ||
subject = f"API key {event}" | ||
email_role(role, subject, html=html, plain=plain) | ||
|
||
now = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0) | ||
role.api_key = make_token() | ||
role.api_key_expires_at = now + datetime.timedelta(days=API_KEY_EXPIRATION_DAYS) | ||
role.api_key_expiration_notification_sent = None | ||
|
||
db.session.add(role) | ||
db.session.commit() | ||
update_role(role) | ||
|
||
return role.api_key | ||
|
||
|
||
def send_api_key_expiration_notifications(): | ||
_send_api_key_expiration_notification( | ||
days=7, | ||
subject="Your API key will expire in 7 days", | ||
plain_template="email/api_key_expires_soon.txt", | ||
html_template="email/api_key_expires_soon.html", | ||
) | ||
|
||
_send_api_key_expiration_notification( | ||
days=0, | ||
subject="Your API key has expired", | ||
plain_template="email/api_key_expired.txt", | ||
html_template="email/api_key_expired.html", | ||
) | ||
|
||
|
||
def _send_api_key_expiration_notification( | ||
days, | ||
subject, | ||
plain_template, | ||
html_template, | ||
): | ||
now = datetime.date.today() | ||
threshold = now + datetime.timedelta(days=days) | ||
|
||
query = Role.all_users() | ||
query = query.yield_per(1000) | ||
query = query.where( | ||
and_( | ||
and_( | ||
Role.api_key != None, # noqa: E711 | ||
func.date(Role.api_key_expires_at) <= threshold, | ||
), | ||
or_( | ||
Role.api_key_expiration_notification_sent == None, # noqa: E711 | ||
Role.api_key_expiration_notification_sent > days, | ||
), | ||
) | ||
) | ||
|
||
for role in query: | ||
expires_at = role.api_key_expires_at | ||
params = { | ||
"role": role, | ||
"expires_at": expires_at, | ||
"settings_url": ui_url("settings"), | ||
} | ||
plain = render_template(plain_template, **params) | ||
html = render_template(html_template, **params) | ||
log.info(f"Sending API key expiration notification: {role} at {expires_at}") | ||
email_role(role, subject, html=html, plain=plain) | ||
|
||
query.update({Role.api_key_expiration_notification_sent: days}) | ||
db.session.commit() | ||
|
||
|
||
def reset_api_key_expiration(): | ||
tillprochaska marked this conversation as resolved.
Show resolved
Hide resolved
|
||
now = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0) | ||
expires_at = now + datetime.timedelta(days=API_KEY_EXPIRATION_DAYS) | ||
|
||
query = Role.all_users() | ||
query = query.yield_per(500) | ||
query = query.where( | ||
and_( | ||
Role.api_key != None, # noqa: E711 | ||
Role.api_key_expires_at == None, # noqa: E711 | ||
) | ||
) | ||
|
||
query.update({Role.api_key_expires_at: expires_at}) | ||
db.session.commit() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 2 additions & 2 deletions
4
aleph/migrate/versions/131674bde902_add_primary_key_constraint_to_role_membership.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
stchris marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
"""API key expiration | ||
|
||
Revision ID: d46fc882ec6b | ||
Revises: 131674bde902 | ||
Create Date: 2024-05-02 11:43:50.993948 | ||
|
||
""" | ||
from alembic import op | ||
import sqlalchemy as sa | ||
|
||
# revision identifiers, used by Alembic. | ||
tillprochaska marked this conversation as resolved.
Show resolved
Hide resolved
|
||
revision = "d46fc882ec6b" | ||
down_revision = "131674bde902" | ||
|
||
|
||
def upgrade(): | ||
op.add_column("role", sa.Column("api_key_expires_at", sa.DateTime())) | ||
op.add_column( | ||
"role", sa.Column("api_key_expiration_notification_sent", sa.Integer()) | ||
) | ||
op.create_index( | ||
index_name="ix_role_api_key_expires_at", | ||
table_name="role", | ||
columns=["api_key_expires_at"], | ||
) | ||
|
||
|
||
def downgrade(): | ||
op.drop_column("role", "api_key_expires_at") | ||
op.drop_column("role", "api_key_expiration_notification_sent") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
{% extends "email/layout.html" %} | ||
|
||
{% block content -%} | ||
<p> | ||
{% trans expires_at=(expires_at | datetimeformat) -%} | ||
Your Aleph API key has expired on {{expires_at}} UTC. | ||
{%- endtrans %} | ||
</p> | ||
|
||
<p> | ||
{% trans settings_url=settings_url -%} | ||
If you do not use the Aleph API, or only use the API to access public data you can ignore this email. If you use the Aleph API to access data that is not publicly accessible then you’ll need to <a href="{{settings_url}}">regenerate your API key</a> to maintain access. | ||
{%- endtrans %} | ||
</p> | ||
{%- endblock %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
{% extends "email/layout.txt" %} | ||
|
||
{% block content -%} | ||
{% trans expires_at=(expires_at | datetimeformat) -%} | ||
Your Aleph API key has expired on {{expires_at}} UTC. | ||
{%- endtrans %} | ||
|
||
{% trans settings_url=settings_url -%} | ||
If you do not use the Aleph API, or only use the API to access public data you can ignore this email. If you use the Aleph API to access data that is not publicly accessible then you’ll need to regenerate your API key ({{settings_url}}) to maintain access. | ||
{%- endtrans %} | ||
{%- endblock %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
{% extends "email/layout.html" %} | ||
|
||
{% block content -%} | ||
<p> | ||
{% trans expires_at=(expires_at | datetimeformat) -%} | ||
Your Aleph API key will expire in 7 days, on {{expires_at}} UTC. | ||
{%- endtrans %} | ||
</p> | ||
|
||
<p> | ||
{% trans settings_url=settings_url -%} | ||
If you do not use the Aleph API, or only use the API to access public data you can ignore this email. If you use the Aleph API to access data that is not publicly accessible then you’ll need to <a href="{{settings_url}}">regenerate your API key</a> to maintain access. | ||
{%- endtrans %} | ||
</p> | ||
{%- endblock %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
{% extends "email/layout.txt" %} | ||
|
||
{% block content -%} | ||
{% trans expires_at=(expires_at | datetimeformat) -%} | ||
Your Aleph API key will expire in 7 days, on {{expires_at}} UTC. | ||
{%- endtrans %} | ||
|
||
{% trans -%} | ||
If you do not use the Aleph API, or only use the API to access public data you can ignore this email. If you use the Aleph API to access data that is not publicly accessible then you’ll need to regenerate your API key ({{settings_url}}) to maintain access. | ||
{%- endtrans %} | ||
{%- endblock %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
{% extends "email/layout.html" %} | ||
|
||
{% block content -%} | ||
{% if event == "regenerated" -%} | ||
{% trans -%} | ||
Your Aleph API key has been regenerated. If that wasn’t you, please contact an administrator. | ||
{%- endtrans %} | ||
{% else -%} | ||
{% trans -%} | ||
An Aleph API key has been generated for your account. If that wasn’t you, please contact an administrator. | ||
{%- endtrans %} | ||
{%- endif %} | ||
{%- endblock %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
{% extends "email/layout.txt" %} | ||
|
||
{% block content -%} | ||
{% if event == "regenerated" -%} | ||
{% trans -%} | ||
Your Aleph API key has been regenerated. If that wasn’t you, please contact an administrator. | ||
{%- endtrans %} | ||
{% else -%} | ||
{% trans -%} | ||
An Aleph API key has been generated for your account. If that wasn’t you, please contact an administrator. | ||
{%- endtrans %} | ||
{%- endif %} | ||
{%- endblock %} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.