errorgap 0.3.0__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {errorgap-0.3.0 → errorgap-0.4.0}/CHANGELOG.md +9 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/PKG-INFO +29 -1
- {errorgap-0.3.0 → errorgap-0.4.0}/README.md +28 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/pyproject.toml +1 -1
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/__init__.py +28 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/client.py +23 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/configuration.py +5 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/django.py +40 -0
- errorgap-0.4.0/src/errorgap/sign_ins.py +85 -0
- errorgap-0.4.0/src/errorgap/version.py +1 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/test_django.py +26 -0
- errorgap-0.4.0/tests/test_sign_ins.py +50 -0
- errorgap-0.3.0/src/errorgap/version.py +0 -1
- {errorgap-0.3.0 → errorgap-0.4.0}/.github/workflows/ci.yml +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/.github/workflows/release.yml +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/.gitignore +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/LICENSE +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/apm.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/backtrace.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/fastapi.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/filter.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/flask.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/handlers.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/notice.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/transaction_context.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/src/errorgap/wsgi.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/conftest.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/test_apm.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/test_backtrace.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/test_client.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/test_configuration.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/test_fastapi.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/test_filter.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/test_flask.py +0 -0
- {errorgap-0.3.0 → errorgap-0.4.0}/tests/test_notice.py +0 -0
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0 — 2026-10-06
|
|
4
|
+
|
|
5
|
+
- Sign-ins: `init(auth_events=True)` reports sign-ins to errorgap's
|
|
6
|
+
Security › Logins. Django's `user_logged_in` / `user_login_failed` signals
|
|
7
|
+
are reported automatically with the middleware installed;
|
|
8
|
+
`errorgap.sign_in(outcome, user=, request=)` covers Flask, FastAPI and
|
|
9
|
+
other outcomes (`password_reset`, `mfa_failure`, `locked`). `app_name`
|
|
10
|
+
(or `ERRORGAP_APP_NAME`) names the app. Passwords and tokens are never sent.
|
|
11
|
+
|
|
3
12
|
## 0.3.0 — 2026-10-04
|
|
4
13
|
|
|
5
14
|
- Django and FastAPI/Starlette middleware now time each request as an APM
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: errorgap
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Python notifier for Errorgap error tracking.
|
|
5
5
|
Project-URL: Homepage, https://github.com/errorgaphq/errorgap-python
|
|
6
6
|
Project-URL: Source, https://github.com/errorgaphq/errorgap-python
|
|
@@ -181,6 +181,32 @@ transaction id, and the browser SDK's `x-errorgap-trace` header is recorded.
|
|
|
181
181
|
Record spans from an endpoint with `errorgap.fastapi.spans(request).database(sql, ms)`
|
|
182
182
|
(take `request: Request` as a parameter).
|
|
183
183
|
|
|
184
|
+
## Sign-ins
|
|
185
|
+
|
|
186
|
+
Report sign-ins to your app; errorgap shows them beside SSH logins in
|
|
187
|
+
Security › Logins and flags a new IP, country or hour for a user. Off until
|
|
188
|
+
you opt in, since events carry user names and IPs:
|
|
189
|
+
|
|
190
|
+
```python
|
|
191
|
+
errorgap.init(project_slug="ox-coffee", auth_events=True, app_name="oxcoffee-web")
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
**Django** needs nothing else: with `ErrorgapMiddleware` installed, Django's
|
|
195
|
+
`user_logged_in` and `user_login_failed` signals are reported (the user's
|
|
196
|
+
`get_username()`; Django masks the password before the signal). Elsewhere,
|
|
197
|
+
or for other outcomes:
|
|
198
|
+
|
|
199
|
+
```python
|
|
200
|
+
errorgap.sign_in("success" if ok else "failure", user=email, request=request)
|
|
201
|
+
errorgap.sign_in("mfa_failure", user=email, request=request)
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Outcomes: `success`, `failure`, `password_reset`, `mfa_failure`, `locked`.
|
|
205
|
+
A Django, Flask or Starlette `request` supplies the IP, user agent and path
|
|
206
|
+
(without the query string); behind a proxy, pass `ip=` yourself. Never pass
|
|
207
|
+
passwords or tokens; errorgap can also store user names hashed
|
|
208
|
+
(Security › Logins › Web apps › Privacy).
|
|
209
|
+
|
|
184
210
|
## Configuration reference
|
|
185
211
|
|
|
186
212
|
| Argument | Default | Notes |
|
|
@@ -196,6 +222,8 @@ Record spans from an endpoint with `errorgap.fastapi.spans(request).database(sql
|
|
|
196
222
|
| `filter_keys` | `("password", "token", ...)` | Substring match, case-insensitive |
|
|
197
223
|
| `apm_enabled` | `False` | Send APM transactions |
|
|
198
224
|
| `apm_sample_rate` | `1.0` | Fraction of transactions sent (errors are unaffected) |
|
|
225
|
+
| `auth_events` | `False` | Send sign-ins (`sign_in`, Django login signals) |
|
|
226
|
+
| `app_name` | `ERRORGAP_APP_NAME` or the project slug | The app's name in Security › Logins |
|
|
199
227
|
| `capture_globals` | `True` | Install `sys.excepthook` |
|
|
200
228
|
|
|
201
229
|
## Graceful shutdown
|
|
@@ -145,6 +145,32 @@ transaction id, and the browser SDK's `x-errorgap-trace` header is recorded.
|
|
|
145
145
|
Record spans from an endpoint with `errorgap.fastapi.spans(request).database(sql, ms)`
|
|
146
146
|
(take `request: Request` as a parameter).
|
|
147
147
|
|
|
148
|
+
## Sign-ins
|
|
149
|
+
|
|
150
|
+
Report sign-ins to your app; errorgap shows them beside SSH logins in
|
|
151
|
+
Security › Logins and flags a new IP, country or hour for a user. Off until
|
|
152
|
+
you opt in, since events carry user names and IPs:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
errorgap.init(project_slug="ox-coffee", auth_events=True, app_name="oxcoffee-web")
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
**Django** needs nothing else: with `ErrorgapMiddleware` installed, Django's
|
|
159
|
+
`user_logged_in` and `user_login_failed` signals are reported (the user's
|
|
160
|
+
`get_username()`; Django masks the password before the signal). Elsewhere,
|
|
161
|
+
or for other outcomes:
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
errorgap.sign_in("success" if ok else "failure", user=email, request=request)
|
|
165
|
+
errorgap.sign_in("mfa_failure", user=email, request=request)
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Outcomes: `success`, `failure`, `password_reset`, `mfa_failure`, `locked`.
|
|
169
|
+
A Django, Flask or Starlette `request` supplies the IP, user agent and path
|
|
170
|
+
(without the query string); behind a proxy, pass `ip=` yourself. Never pass
|
|
171
|
+
passwords or tokens; errorgap can also store user names hashed
|
|
172
|
+
(Security › Logins › Web apps › Privacy).
|
|
173
|
+
|
|
148
174
|
## Configuration reference
|
|
149
175
|
|
|
150
176
|
| Argument | Default | Notes |
|
|
@@ -160,6 +186,8 @@ Record spans from an endpoint with `errorgap.fastapi.spans(request).database(sql
|
|
|
160
186
|
| `filter_keys` | `("password", "token", ...)` | Substring match, case-insensitive |
|
|
161
187
|
| `apm_enabled` | `False` | Send APM transactions |
|
|
162
188
|
| `apm_sample_rate` | `1.0` | Fraction of transactions sent (errors are unaffected) |
|
|
189
|
+
| `auth_events` | `False` | Send sign-ins (`sign_in`, Django login signals) |
|
|
190
|
+
| `app_name` | `ERRORGAP_APP_NAME` or the project slug | The app's name in Security › Logins |
|
|
163
191
|
| `capture_globals` | `True` | Install `sys.excepthook` |
|
|
164
192
|
|
|
165
193
|
## Graceful shutdown
|
|
@@ -18,6 +18,7 @@ __all__ = [
|
|
|
18
18
|
"notify_transaction",
|
|
19
19
|
"track_transaction",
|
|
20
20
|
"track_job",
|
|
21
|
+
"sign_in",
|
|
21
22
|
"current_transaction_id",
|
|
22
23
|
"transaction_scope",
|
|
23
24
|
"browser_trace_id",
|
|
@@ -53,6 +54,8 @@ def init(
|
|
|
53
54
|
logger: Optional[Any] = None,
|
|
54
55
|
apm_enabled: Optional[bool] = None,
|
|
55
56
|
apm_sample_rate: Optional[float] = None,
|
|
57
|
+
auth_events: Optional[bool] = None,
|
|
58
|
+
app_name: Optional[str] = None,
|
|
56
59
|
capture_globals: bool = True,
|
|
57
60
|
) -> None:
|
|
58
61
|
"""Configure the SDK and install global error hooks.
|
|
@@ -86,6 +89,10 @@ def init(
|
|
|
86
89
|
overrides["apm_enabled"] = apm_enabled
|
|
87
90
|
if apm_sample_rate is not None:
|
|
88
91
|
overrides["apm_sample_rate"] = apm_sample_rate
|
|
92
|
+
if auth_events is not None:
|
|
93
|
+
overrides["auth_events"] = auth_events
|
|
94
|
+
if app_name is not None:
|
|
95
|
+
overrides["app_name"] = app_name
|
|
89
96
|
|
|
90
97
|
_configuration = Configuration(**overrides)
|
|
91
98
|
_client.configure(_configuration)
|
|
@@ -114,6 +121,27 @@ def notify(
|
|
|
114
121
|
)
|
|
115
122
|
|
|
116
123
|
|
|
124
|
+
def sign_in(
|
|
125
|
+
outcome: str,
|
|
126
|
+
user: Any = None,
|
|
127
|
+
request: Any = None,
|
|
128
|
+
ip: Optional[str] = None,
|
|
129
|
+
user_agent: Optional[str] = None,
|
|
130
|
+
path: Optional[str] = None,
|
|
131
|
+
method: Optional[str] = None,
|
|
132
|
+
sync: bool = False,
|
|
133
|
+
) -> DeliveryResult:
|
|
134
|
+
"""Report a sign-in to this app: ``"success"``, ``"failure"``,
|
|
135
|
+
``"password_reset"``, ``"mfa_failure"`` or ``"locked"``. Pass the
|
|
136
|
+
Django, Flask or Starlette ``request`` for its IP, user agent and path.
|
|
137
|
+
Needs ``init(auth_events=True)``; Django's login signals report
|
|
138
|
+
automatically with the middleware installed."""
|
|
139
|
+
return _client.sign_in(
|
|
140
|
+
outcome, sync=sync, user=user, request=request, ip=ip,
|
|
141
|
+
user_agent=user_agent, path=path, method=method,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
117
145
|
def notify_transaction(transaction: Transaction, sync: bool = False) -> DeliveryResult:
|
|
118
146
|
"""Deliver a pre-measured APM transaction."""
|
|
119
147
|
return _client.notify_transaction(transaction, sync=sync)
|
|
@@ -13,6 +13,7 @@ from urllib import request as urlrequest
|
|
|
13
13
|
from .apm import Transaction
|
|
14
14
|
from .configuration import Configuration
|
|
15
15
|
from .notice import build_notice
|
|
16
|
+
from .sign_ins import build_sign_in, sign_in_payload
|
|
16
17
|
from .transaction_context import current_transaction_id
|
|
17
18
|
from .version import VERSION
|
|
18
19
|
|
|
@@ -98,6 +99,28 @@ class Client:
|
|
|
98
99
|
self._queue.put(("transactions", payload))
|
|
99
100
|
return DeliveryResult(queued=True, status=202)
|
|
100
101
|
|
|
102
|
+
def sign_in(self, outcome: str, sync: bool = False, **fields: Any) -> DeliveryResult:
|
|
103
|
+
"""Report a sign-in to this app (Security › Logins). Dropped unless
|
|
104
|
+
``auth_events`` is on, or when the outcome is unknown."""
|
|
105
|
+
try:
|
|
106
|
+
self._configuration.validate()
|
|
107
|
+
if not self._configuration.auth_events:
|
|
108
|
+
return DeliveryResult(status=204)
|
|
109
|
+
event = build_sign_in(outcome, **fields)
|
|
110
|
+
if event is None:
|
|
111
|
+
raise ValueError(f"unknown sign-in outcome {outcome!r}")
|
|
112
|
+
payload = sign_in_payload(event, self._configuration)
|
|
113
|
+
except Exception as caught: # noqa: BLE001 — SDK must not raise
|
|
114
|
+
self._log(caught)
|
|
115
|
+
return DeliveryResult(error=caught)
|
|
116
|
+
|
|
117
|
+
if sync or not self._configuration.async_:
|
|
118
|
+
return self._post("logins/web", payload)
|
|
119
|
+
|
|
120
|
+
self._ensure_worker()
|
|
121
|
+
self._queue.put(("logins/web", payload))
|
|
122
|
+
return DeliveryResult(queued=True, status=202)
|
|
123
|
+
|
|
101
124
|
def deliver(self, notice: Dict[str, Any]) -> DeliveryResult:
|
|
102
125
|
return self._post("notices", notice)
|
|
103
126
|
|
|
@@ -39,6 +39,11 @@ class Configuration:
|
|
|
39
39
|
filter_keys: tuple = DEFAULT_FILTER_KEYS
|
|
40
40
|
apm_enabled: bool = False
|
|
41
41
|
apm_sample_rate: float = 1.0
|
|
42
|
+
# Sign-ins to this app (Security › Logins). Off until you opt in: they
|
|
43
|
+
# carry user names and IPs.
|
|
44
|
+
auth_events: bool = False
|
|
45
|
+
# The app's name in Security › Logins; defaults to the project slug.
|
|
46
|
+
app_name: Optional[str] = field(default_factory=lambda: os.environ.get("ERRORGAP_APP_NAME"))
|
|
42
47
|
|
|
43
48
|
def validate(self) -> None:
|
|
44
49
|
if not self.project_slug or not str(self.project_slug).strip():
|
|
@@ -24,6 +24,7 @@ class ErrorgapMiddleware:
|
|
|
24
24
|
|
|
25
25
|
def __init__(self, get_response: Callable[..., Any]):
|
|
26
26
|
self.get_response = get_response
|
|
27
|
+
install_auth_signals()
|
|
27
28
|
|
|
28
29
|
def __call__(self, request: Any) -> Any:
|
|
29
30
|
meta = getattr(request, "META", {}) or {}
|
|
@@ -136,3 +137,42 @@ def _params(request: Any) -> Dict[str, Any]:
|
|
|
136
137
|
except Exception: # noqa: BLE001
|
|
137
138
|
return out
|
|
138
139
|
return out
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _on_logged_in(sender: Any, request: Any = None, user: Any = None, **_kwargs: Any) -> None:
|
|
143
|
+
from . import configuration, sign_in
|
|
144
|
+
|
|
145
|
+
if request is None or not configuration().auth_events:
|
|
146
|
+
return
|
|
147
|
+
name = user.get_username() if hasattr(user, "get_username") else getattr(user, "pk", None)
|
|
148
|
+
sign_in("success", user=name, request=request)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _on_login_failed(sender: Any, credentials: Any = None, request: Any = None, **_kwargs: Any) -> None:
|
|
152
|
+
from . import configuration, sign_in
|
|
153
|
+
|
|
154
|
+
# No request: a failed check outside a web request (a shell, a test).
|
|
155
|
+
if request is None or not configuration().auth_events:
|
|
156
|
+
return
|
|
157
|
+
creds = credentials or {}
|
|
158
|
+
try:
|
|
159
|
+
from django.contrib.auth import get_user_model
|
|
160
|
+
|
|
161
|
+
field = get_user_model().USERNAME_FIELD
|
|
162
|
+
except Exception: # noqa: BLE001 — auth app not installed
|
|
163
|
+
field = "username"
|
|
164
|
+
# Django masks the password in `credentials`; only the name is read.
|
|
165
|
+
name = next((creds[k] for k in (field, "username", "email") if isinstance(creds.get(k), str)), None)
|
|
166
|
+
sign_in("failure", user=name, request=request)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def install_auth_signals() -> None:
|
|
170
|
+
"""Report Django's login signals (``user_logged_in``,
|
|
171
|
+
``user_login_failed``) as sign-ins. The middleware calls this; it checks
|
|
172
|
+
``auth_events`` per event, so ``init`` may run before or after."""
|
|
173
|
+
try:
|
|
174
|
+
from django.contrib.auth.signals import user_logged_in, user_login_failed
|
|
175
|
+
except Exception: # noqa: BLE001 — django.contrib.auth not available
|
|
176
|
+
return
|
|
177
|
+
user_logged_in.connect(_on_logged_in, dispatch_uid="errorgap.sign_in.success")
|
|
178
|
+
user_login_failed.connect(_on_login_failed, dispatch_uid="errorgap.sign_in.failure")
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Sign-ins to this app, shown beside SSH logins in errorgap's
|
|
2
|
+
Security › Logins. Only who, from where and the result are sent: never
|
|
3
|
+
passwords, tokens or session ids."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from typing import Any, Dict, Optional
|
|
9
|
+
|
|
10
|
+
from .configuration import Configuration
|
|
11
|
+
from .version import VERSION
|
|
12
|
+
|
|
13
|
+
OUTCOMES = ("success", "failure", "password_reset", "mfa_failure", "locked")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _request_fields(request: Any) -> Dict[str, Optional[str]]:
|
|
17
|
+
"""IP, user agent and path from a Django, Flask/Werkzeug or Starlette
|
|
18
|
+
request. Paths never include the query string."""
|
|
19
|
+
meta = getattr(request, "META", None)
|
|
20
|
+
if isinstance(meta, dict): # Django
|
|
21
|
+
return {
|
|
22
|
+
"ip": meta.get("REMOTE_ADDR"),
|
|
23
|
+
"user_agent": meta.get("HTTP_USER_AGENT"),
|
|
24
|
+
"path": f"{request.method} {request.path}",
|
|
25
|
+
}
|
|
26
|
+
client = getattr(request, "client", None)
|
|
27
|
+
url = getattr(request, "url", None)
|
|
28
|
+
if client is not None and hasattr(url, "path"): # Starlette / FastAPI
|
|
29
|
+
return {
|
|
30
|
+
"ip": getattr(client, "host", None),
|
|
31
|
+
"user_agent": request.headers.get("user-agent"),
|
|
32
|
+
"path": f"{request.method} {url.path}",
|
|
33
|
+
}
|
|
34
|
+
headers = getattr(request, "headers", None) or {}
|
|
35
|
+
return { # Flask / Werkzeug
|
|
36
|
+
"ip": getattr(request, "remote_addr", None),
|
|
37
|
+
"user_agent": headers.get("User-Agent") if hasattr(headers, "get") else None,
|
|
38
|
+
"path": f"{getattr(request, 'method', '')} {getattr(request, 'path', '')}".strip() or None,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def build_sign_in(
|
|
43
|
+
outcome: str,
|
|
44
|
+
user: Any = None,
|
|
45
|
+
request: Any = None,
|
|
46
|
+
ip: Optional[str] = None,
|
|
47
|
+
user_agent: Optional[str] = None,
|
|
48
|
+
path: Optional[str] = None,
|
|
49
|
+
method: Optional[str] = None,
|
|
50
|
+
occurred_at: Optional[datetime] = None,
|
|
51
|
+
) -> Optional[Dict[str, Any]]:
|
|
52
|
+
"""The event to send, or ``None`` for an unknown outcome."""
|
|
53
|
+
if outcome not in OUTCOMES:
|
|
54
|
+
return None
|
|
55
|
+
if request is not None:
|
|
56
|
+
found = _request_fields(request)
|
|
57
|
+
ip = ip or found["ip"]
|
|
58
|
+
user_agent = user_agent or found["user_agent"]
|
|
59
|
+
path = path or found["path"]
|
|
60
|
+
at = (occurred_at or datetime.now(timezone.utc)).astimezone(timezone.utc)
|
|
61
|
+
event: Dict[str, Any] = {
|
|
62
|
+
"occurred_at": at.isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
|
63
|
+
"outcome": outcome,
|
|
64
|
+
}
|
|
65
|
+
name = "" if user is None else str(user).strip()
|
|
66
|
+
if name:
|
|
67
|
+
event["user"] = name
|
|
68
|
+
if ip:
|
|
69
|
+
event["ip"] = str(ip)
|
|
70
|
+
if user_agent:
|
|
71
|
+
event["user_agent"] = str(user_agent)[:512]
|
|
72
|
+
if path:
|
|
73
|
+
event["path"] = str(path)[:200]
|
|
74
|
+
if method:
|
|
75
|
+
event["method"] = str(method)
|
|
76
|
+
return event
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def sign_in_payload(event: Dict[str, Any], configuration: Configuration) -> Dict[str, Any]:
|
|
80
|
+
return {
|
|
81
|
+
"app": configuration.app_name or configuration.project_slug,
|
|
82
|
+
"environment": configuration.environment,
|
|
83
|
+
"sdk": f"errorgap-python {VERSION}",
|
|
84
|
+
"events": [event],
|
|
85
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
VERSION = "0.4.0"
|
|
@@ -109,3 +109,29 @@ def test_requests_are_transactions_linked_to_their_errors(ingestor, reset_errorg
|
|
|
109
109
|
by_message = {n["errors"][0]["message"]: n["context"].get("transaction_id") for n in notices}
|
|
110
110
|
assert by_message["card declined"] == ok_txn["id"]
|
|
111
111
|
assert by_message["django-boom"] == boom_txn["id"]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_login_signals_report_sign_ins(ingestor, reset_errorgap):
|
|
115
|
+
from django.contrib.auth.signals import user_logged_in, user_login_failed
|
|
116
|
+
|
|
117
|
+
errorgap.init(endpoint=ingestor.endpoint, project_slug="demo", api_key="k", async_=False,
|
|
118
|
+
capture_globals=False, auth_events=True)
|
|
119
|
+
ErrorgapMiddleware(get_response=lambda req: HttpResponse("")) # connects the signals
|
|
120
|
+
request = RequestFactory().post("/accounts/login/", REMOTE_ADDR="198.51.100.71",
|
|
121
|
+
HTTP_USER_AGENT="Firefox/131")
|
|
122
|
+
|
|
123
|
+
class User:
|
|
124
|
+
def get_username(self):
|
|
125
|
+
return "mara"
|
|
126
|
+
|
|
127
|
+
user_logged_in.send(sender=User, request=request, user=User())
|
|
128
|
+
# Django masks the password before sending the signal.
|
|
129
|
+
user_login_failed.send(sender=None, request=request,
|
|
130
|
+
credentials={"username": "admin", "password": "********************"})
|
|
131
|
+
# A failed check outside a request is not a sign-in attempt.
|
|
132
|
+
user_login_failed.send(sender=None, request=None, credentials={"username": "cli"})
|
|
133
|
+
|
|
134
|
+
events = [r.body["events"][0] for r in ingestor.requests]
|
|
135
|
+
assert [(e["outcome"], e["user"]) for e in events] == [("success", "mara"), ("failure", "admin")]
|
|
136
|
+
assert events[0]["path"] == "POST /accounts/login/"
|
|
137
|
+
assert events[0]["ip"] == "198.51.100.71"
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
|
|
5
|
+
import errorgap
|
|
6
|
+
from errorgap.sign_ins import build_sign_in
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_flask_like_request_fields():
|
|
10
|
+
req = SimpleNamespace(
|
|
11
|
+
remote_addr="198.51.100.71", headers={"User-Agent": "Safari 18"}, method="POST", path="/login"
|
|
12
|
+
)
|
|
13
|
+
e = build_sign_in("success", user="mara@oxcoffee.com", request=req)
|
|
14
|
+
assert e["user"] == "mara@oxcoffee.com"
|
|
15
|
+
assert (e["ip"], e["user_agent"], e["path"]) == ("198.51.100.71", "Safari 18", "POST /login")
|
|
16
|
+
assert e["occurred_at"].endswith("Z")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_starlette_like_request_fields():
|
|
20
|
+
req = SimpleNamespace(
|
|
21
|
+
client=SimpleNamespace(host="203.0.113.9"),
|
|
22
|
+
url=SimpleNamespace(path="/token"),
|
|
23
|
+
headers={"user-agent": "curl/8"},
|
|
24
|
+
method="POST",
|
|
25
|
+
)
|
|
26
|
+
e = build_sign_in("mfa_failure", request=req)
|
|
27
|
+
assert (e["ip"], e["path"], "user" in e) == ("203.0.113.9", "POST /token", False)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_unknown_outcome_is_dropped():
|
|
31
|
+
assert build_sign_in("teleported") is None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_sign_in_posts_once_opted_in(ingestor, reset_errorgap):
|
|
35
|
+
errorgap.init(endpoint=ingestor.endpoint, project_slug="ox-coffee", api_key="k1",
|
|
36
|
+
environment="production", async_=False, capture_globals=False)
|
|
37
|
+
assert errorgap.sign_in("success", user="x").status == 204
|
|
38
|
+
assert ingestor.requests == []
|
|
39
|
+
|
|
40
|
+
errorgap.init(endpoint=ingestor.endpoint, project_slug="ox-coffee", api_key="k1",
|
|
41
|
+
environment="production", async_=False, capture_globals=False,
|
|
42
|
+
auth_events=True, app_name="oxcoffee-web")
|
|
43
|
+
errorgap.sign_in("locked", user="admin", ip="203.0.113.9")
|
|
44
|
+
req = ingestor.requests[0]
|
|
45
|
+
assert req.path == "/api/projects/ox-coffee/logins/web"
|
|
46
|
+
assert req.headers["x-errorgap-project-key"] == "k1"
|
|
47
|
+
assert req.body["app"] == "oxcoffee-web"
|
|
48
|
+
assert req.body["environment"] == "production"
|
|
49
|
+
assert req.body["sdk"].startswith("errorgap-python ")
|
|
50
|
+
assert req.body["events"][0]["outcome"] == "locked"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
VERSION = "0.3.0"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|