Repository navigation
feat(integrations): add Discord audit log integration #9150
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
Open
afreenorbit
wants to merge
2
commits into
Flagsmith:main
Choose a base branch
from
afreenorbit:feat/discord-integration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+582
−0
Open
Changes from all commits
Commits
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
Empty file.
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,5 @@ | ||
| from django.apps import AppConfig | ||
|
|
||
|
|
||
| class DiscordConfigurationConfig(AppConfig): | ||
| name = "integrations.discord" |
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,71 @@ | ||
| import logging | ||
| from typing import Any | ||
|
|
||
| import requests | ||
| import structlog | ||
|
|
||
| from audit.models import AuditLog | ||
| from integrations.common.wrapper import AbstractBaseEventIntegrationWrapper | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
| structlog_logger = structlog.get_logger("discord") | ||
|
|
||
| # Discord limits: embed title 256 characters, description 4096. | ||
| EMBED_TITLE_LIMIT = 256 | ||
| EMBED_DESCRIPTION_LIMIT = 4096 | ||
| FLAGSMITH_PURPLE = 0x6837FC | ||
|
|
||
|
|
||
| def _clip(text: str, limit: int) -> str: | ||
| return text if len(text) <= limit else text[: limit - 1] + "…" | ||
|
|
||
|
|
||
| class DiscordWrapper(AbstractBaseEventIntegrationWrapper): | ||
| def __init__(self, webhook_url: str) -> None: | ||
| self.webhook_url = webhook_url | ||
|
|
||
| @staticmethod | ||
| def generate_event_data(audit_log_record: AuditLog) -> dict[str, Any]: | ||
| details = ( | ||
| [f"**Project:** {audit_log_record.project.name}"] | ||
| if audit_log_record.project | ||
| else [] | ||
| ) | ||
| if audit_log_record.environment: # environment_name falls back to "unknown" | ||
| details.append(f"**Environment:** {audit_log_record.environment.name}") | ||
| details.append(f"**By:** {audit_log_record.author_identifier}") | ||
| return { | ||
| "username": "Flagsmith", | ||
| "embeds": [ | ||
| { | ||
| "title": _clip(audit_log_record.log, EMBED_TITLE_LIMIT), | ||
| "description": _clip("\n".join(details), EMBED_DESCRIPTION_LIMIT), | ||
| "color": FLAGSMITH_PURPLE, | ||
| "timestamp": audit_log_record.created_date.isoformat(), | ||
| } | ||
| ], | ||
| # Never ping anyone, even if a flag or segment name contains @everyone. | ||
| "allowed_mentions": {"parse": []}, | ||
| } | ||
|
|
||
| def _track_event(self, event: dict[str, Any]) -> None: | ||
| try: | ||
| response = requests.post(self.webhook_url, json=event, timeout=10) | ||
| except requests.RequestException as exc: | ||
| # Never let Discord being unreachable fail the change that was audited | ||
| # (the post runs inline when the postpone decorator is disabled). | ||
| structlog_logger.warning( | ||
| "webhook.failed", | ||
| error__type=type(exc).__name__, | ||
| ) | ||
| return | ||
| if not response.ok: | ||
| # 404: the webhook was deleted in Discord; 429: rate limited. | ||
| structlog_logger.warning( | ||
| "webhook.failed", | ||
| response__status_code=response.status_code, | ||
| ) | ||
| return | ||
| logger.debug( | ||
| "Sent event to Discord. Response code was %s", response.status_code | ||
| ) |
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,33 @@ | ||
| import uuid | ||
|
|
||
| import django.db.models.deletion | ||
| import django_lifecycle.mixins # type: ignore[import-untyped] | ||
| from django.db import migrations, models | ||
|
|
||
| import core.fields | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
| initial = True | ||
|
|
||
| dependencies = [ | ||
| ("projects", "0029_bump_default_project_limits"), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.CreateModel( | ||
| name="DiscordConfiguration", | ||
| fields=[ | ||
| ("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), | ||
| ("deleted_at", models.DateTimeField(blank=True, db_index=True, default=None, editable=False, null=True)), | ||
| ("uuid", models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), | ||
| ("base_url", core.fields.NoSSRFURLField(null=True)), | ||
| ("api_key", models.CharField(blank=True, default="", max_length=100)), | ||
| ("project", models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name="discord_config", to="projects.project")), | ||
| ], | ||
| options={ | ||
| "abstract": False, | ||
| }, | ||
| bases=(django_lifecycle.mixins.LifecycleModelMixin, models.Model), | ||
| ), | ||
| ] |
Empty file.
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,17 @@ | ||
| from django.db import models | ||
|
|
||
| from integrations.common.models import IntegrationsModel | ||
| from projects.models import Project | ||
|
|
||
|
|
||
| class DiscordConfiguration(IntegrationsModel): | ||
| """Posts a project's audit log events to a Discord channel. | ||
|
|
||
| `base_url` holds the channel's Discord webhook URL (Server Settings > Integrations > | ||
| Webhooks). No API key is needed: the webhook URL carries its own token. | ||
| """ | ||
|
|
||
| project = models.OneToOneField( | ||
| Project, on_delete=models.CASCADE, related_name="discord_config" | ||
| ) | ||
| api_key = models.CharField(max_length=100, blank=True, default="") |
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,32 @@ | ||
| import re | ||
|
|
||
| from rest_framework import serializers | ||
|
|
||
| from integrations.common.serializers import ( | ||
| BaseProjectIntegrationModelSerializer, | ||
| ) | ||
|
|
||
| from .models import DiscordConfiguration | ||
|
|
||
| DISCORD_WEBHOOK_URL = re.compile( | ||
| r"^https://(?:(?:canary|ptb)\.)?discord(?:app)?\.com/api/(?:v\d+/)?webhooks/\d+/[\w-]+/?$" | ||
| ) | ||
|
|
||
|
|
||
| class DiscordConfigurationSerializer(BaseProjectIntegrationModelSerializer): | ||
| base_url = serializers.CharField( | ||
| # The model's URLField holds at most 200 characters. | ||
| max_length=200, | ||
| help_text="The Discord channel webhook URL (Server Settings > Integrations > Webhooks).", | ||
| ) | ||
|
|
||
| class Meta: | ||
| model = DiscordConfiguration | ||
| fields = ("id", "base_url") | ||
|
|
||
| def validate_base_url(self, value: str) -> str: | ||
| if not DISCORD_WEBHOOK_URL.match(value): | ||
| raise serializers.ValidationError( | ||
| "Enter a Discord webhook URL, e.g. https://discord.com/api/webhooks/<id>/<token>." | ||
| ) | ||
| return value | ||
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,9 @@ | ||
| from integrations.common.views import ProjectIntegrationBaseViewSet | ||
| from integrations.discord.models import DiscordConfiguration | ||
| from integrations.discord.serializers import DiscordConfigurationSerializer | ||
|
|
||
|
|
||
| class DiscordConfigurationViewSet(ProjectIntegrationBaseViewSet): | ||
| # The base class declares both attributes as `None` placeholders. | ||
| serializer_class = DiscordConfigurationSerializer # type: ignore[assignment] | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||
| model_class = DiscordConfiguration # type: ignore[assignment] | ||
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
Empty file.
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.