-
Notifications
You must be signed in to change notification settings - Fork 25
✨(channels) add encryption, custom scopes and levels, auditing #599
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
22 commits
Select commit
Hold shift + click to select a range
2c94ea6
✨(channels) encrypt channel settings + add new read-only provisioning…
sylvinus 744a5a4
review fixes
sylvinus a5c3214
fix api spec
sylvinus 699bcc5
fix make api
sylvinus 225f799
fix bcc handling
sylvinus da84699
fix
sylvinus 1123e2a
add all users in main mailbox call
sylvinus ec2be08
rebase
sylvinus ce38d0c
add custom attrs
sylvinus 1268955
remove PII log
sylvinus 175e29e
review fixes
sylvinus 968a0ae
Introduce explicit channel scopes and deprecate old API keys
sylvinus e985995
review fixes
sylvinus 0862a2e
regen api
sylvinus 39af647
improve openapi contracts
sylvinus f2f4911
fix test
sylvinus a684617
more review fixes
sylvinus 17a7d6b
review fixes
sylvinus 32d50e3
regen api
sylvinus bb25e51
review fixes
sylvinus b079b47
run backend tests in parallel
sylvinus 332ad9f
review fixes + resilient xdist opensearch
sylvinus 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
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
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,85 @@ | ||
| """Authentication classes for service-to-service API calls. | ||
|
|
||
| Today this module ships a single scheme, ChannelApiKeyAuthentication, which | ||
| authenticates a request as an api_key Channel via the X-Channel-Id + X-API-Key | ||
| headers. New schemes (mTLS, signed JWT, OIDC client credentials, …) should be | ||
| added here as additional BaseAuthentication subclasses that set | ||
| ``request.auth`` to a Channel instance the same way. The downstream permission | ||
| layer (``HasChannelScope``) is scheme-agnostic — it only inspects | ||
| ``request.auth``. | ||
| """ | ||
|
|
||
| import hashlib | ||
| from secrets import compare_digest | ||
|
|
||
| from django.contrib.auth.models import AnonymousUser | ||
| from django.core.exceptions import ValidationError as DjangoValidationError | ||
| from django.utils import timezone | ||
| from django.utils.dateparse import parse_datetime | ||
|
|
||
| from rest_framework.authentication import BaseAuthentication | ||
| from rest_framework.exceptions import AuthenticationFailed | ||
|
|
||
| from core import models | ||
| from core.enums import ChannelTypes | ||
|
|
||
|
|
||
| class ChannelApiKeyAuthentication(BaseAuthentication): | ||
| """Authenticate as an api_key Channel via X-Channel-Id + X-API-Key. | ||
|
|
||
| Client contract: | ||
| X-Channel-Id: <uuid> (public, identifies which channel) | ||
| X-API-Key: <raw secret> (the shared secret, hashed at rest) | ||
|
|
||
| On success ``request.user`` is set to ``AnonymousUser`` (there is no | ||
| associated user) and ``request.auth`` is set to the authenticated | ||
| ``Channel`` instance. Views must read ``request.auth.scope_level``, | ||
| ``request.auth.mailbox_id`` and ``request.auth.maildomain_id`` to | ||
| enforce resource-level bounds on the action they perform. | ||
| """ | ||
|
|
||
| def authenticate(self, request): | ||
| channel_id = request.headers.get("X-Channel-Id") | ||
| api_key = request.headers.get("X-API-Key") | ||
|
|
||
| # Missing either header → this auth scheme does not apply; let DRF | ||
| # try the next class in authentication_classes. Returning None here | ||
| # is the documented way to skip. | ||
| if not channel_id or not api_key: | ||
| return None | ||
|
|
||
| try: | ||
| channel = models.Channel.objects.select_related( | ||
| "mailbox", "maildomain", "user" | ||
| ).get(pk=channel_id, type=ChannelTypes.API_KEY) | ||
| except (models.Channel.DoesNotExist, ValueError, DjangoValidationError) as exc: | ||
| # ValueError / ValidationError handle malformed UUIDs. | ||
| raise AuthenticationFailed("Invalid channel or API key.") from exc | ||
|
|
||
| provided_hash = hashlib.sha256(api_key.encode("utf-8")).hexdigest() | ||
| stored_hashes = (channel.encrypted_settings or {}).get("api_key_hashes") or [] | ||
| # Iterate every stored hash without early exit so the timing is | ||
| # constant with respect to *which* slot matched (the total number | ||
| # of slots is not secret — there is no hard cap on the array). Any | ||
| # match flips the boolean. | ||
| matched = False | ||
| for stored in stored_hashes: | ||
| if isinstance(stored, str) and compare_digest(stored, provided_hash): | ||
| matched = True | ||
| if not matched: | ||
| raise AuthenticationFailed("Invalid channel or API key.") | ||
|
|
||
| expires_at_raw = (channel.settings or {}).get("expires_at") | ||
| if expires_at_raw: | ||
| expires_at = parse_datetime(expires_at_raw) | ||
| if expires_at is not None and expires_at < timezone.now(): | ||
| raise AuthenticationFailed("API key has expired.") | ||
|
|
||
| # Throttled update of last_used_at for monitoring (5 min window). | ||
| channel.mark_used() | ||
|
|
||
| return (AnonymousUser(), channel) | ||
|
|
||
| def authenticate_header(self, request): | ||
| # DRF uses this as the WWW-Authenticate header on 401 responses. | ||
| return "X-API-Key" | ||
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.