-
-
Notifications
You must be signed in to change notification settings - Fork 198
feat(audit): optional best-effort webhook for clipboard and file events #256
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
6 commits
Select commit
Hold shift + click to select a range
d16e718
feat(audit): optional best-effort webhook for clipboard and file events
DL6ER fd0de09
docs(audit): scope docstring to clipboard + file upload
DL6ER f572925
refactor(audit): Deliver events in order from one queued sender
ehfd 0ed8592
feat(audit): Record file downloads and refused uploads
ehfd a8cde83
docs(audit): Describe the events and how they are delivered
ehfd 5a8bb08
test(audit): Cover the webhook in the unit and integration tiers
ehfd 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,100 @@ | ||
| # This Source Code Form is subject to the terms of the Mozilla Public | ||
| # License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| # file, You can obtain one at https://mozilla.org/MPL/2.0/. | ||
|
|
||
| """Audit trail of clipboard and file transfers, POSTed to an operator's webhook. | ||
|
|
||
| Every transfer the server carries — clipboard content in either direction, | ||
| a file upload, a file download — is one JSON object on `audit_webhook_url`: | ||
| its `event`, an RFC 3339 `ts`, and metadata (byte size, MIME type or file | ||
| name), never the content. Events queue in order and one task delivers them | ||
| over a single keep-alive connection, so a transfer pays an enqueue and | ||
| nothing else; a collector that is slow or down loses what overflows the | ||
| queue rather than stalling a session, and each outage is logged once. | ||
| Without a URL every call is a no-op. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import logging | ||
| import time | ||
| from datetime import datetime, timezone | ||
| from typing import Any, Optional | ||
|
|
||
| import aiohttp | ||
|
|
||
| from .settings import settings | ||
|
|
||
| logger = logging.getLogger("audit") | ||
|
|
||
| QUEUE_BOUND = 1024 | ||
|
|
||
| _queue: Optional[asyncio.Queue] = None | ||
| _sender: Optional[asyncio.Task] = None | ||
| _overflowing = False | ||
| _closing = False | ||
|
|
||
|
|
||
| def emit(event: str, **fields: Any) -> None: | ||
| """Queue one event and return at once.""" | ||
| global _queue, _sender, _overflowing | ||
| if not settings.audit_webhook_url: | ||
| return | ||
| if _queue is None: | ||
| _queue = asyncio.Queue(QUEUE_BOUND) | ||
| _sender = asyncio.get_running_loop().create_task(_deliver(_queue)) | ||
| try: | ||
| _queue.put_nowait({"event": event, "ts": time.time(), **fields}) | ||
| _overflowing = False | ||
| except asyncio.QueueFull: | ||
| if not _overflowing: | ||
| logger.warning("Audit webhook queue full (%d events); dropping events until it drains", QUEUE_BOUND) | ||
| _overflowing = True | ||
|
|
||
|
|
||
| async def _deliver(queue: asyncio.Queue) -> None: | ||
| """Send queued events one by one; an outage is logged once, its end too.""" | ||
| headers = {} | ||
| if settings.audit_webhook_token: | ||
| headers["Authorization"] = f"Bearer {settings.audit_webhook_token}" | ||
| timeout = aiohttp.ClientTimeout(total=settings.audit_webhook_timeout) | ||
| failing = False | ||
| async with aiohttp.ClientSession(headers=headers, timeout=timeout, | ||
| connector=aiohttp.TCPConnector(limit=1)) as session: | ||
| while not _closing: | ||
| payload = await queue.get() | ||
| payload["ts"] = datetime.fromtimestamp(payload["ts"], timezone.utc).isoformat( | ||
| timespec="milliseconds").replace("+00:00", "Z") | ||
| try: | ||
| async with session.post(settings.audit_webhook_url, json=payload) as response: | ||
| failure = f"HTTP {response.status}" if response.status >= 400 else "" | ||
| except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as exc: | ||
| failure = str(exc) or type(exc).__name__ | ||
| finally: | ||
| queue.task_done() | ||
| if failure and not failing: | ||
| logger.warning("Audit webhook %s failed: %s; events are dropped until it answers", | ||
| settings.audit_webhook_url, failure) | ||
| elif failing and not failure: | ||
| logger.info("Audit webhook delivering again") | ||
| failing = bool(failure) | ||
|
|
||
|
|
||
| async def close() -> None: | ||
| """Deliver what is queued, within one request timeout, and stop the sender.""" | ||
| global _queue, _sender, _closing | ||
| if _sender is None: | ||
| return | ||
| # The flag ends the loop at an event boundary, so shutting down never means | ||
| # interrupting a request in flight; the cancel only breaks the idle wait. | ||
| _closing = True | ||
| try: | ||
| await asyncio.wait_for(_queue.join(), settings.audit_webhook_timeout) | ||
| except asyncio.TimeoutError: | ||
| pass | ||
| _sender.cancel() | ||
| try: | ||
| await _sender | ||
| except asyncio.CancelledError: | ||
| pass | ||
| _queue = _sender = None | ||
| _closing = False |
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
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.