stapel-integrations-core 0.1.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.
Files changed (49) hide show
  1. stapel_integrations_core-0.1.0/CONFIG.MD +18 -0
  2. stapel_integrations_core-0.1.0/LICENSE +21 -0
  3. stapel_integrations_core-0.1.0/MODULE.md +31 -0
  4. stapel_integrations_core-0.1.0/PKG-INFO +65 -0
  5. stapel_integrations_core-0.1.0/README.md +30 -0
  6. stapel_integrations_core-0.1.0/__init__.py +40 -0
  7. stapel_integrations_core-0.1.0/actions.py +33 -0
  8. stapel_integrations_core-0.1.0/admin.py +21 -0
  9. stapel_integrations_core-0.1.0/apps.py +18 -0
  10. stapel_integrations_core-0.1.0/checks.py +25 -0
  11. stapel_integrations_core-0.1.0/conf.py +49 -0
  12. stapel_integrations_core-0.1.0/conftest.py +62 -0
  13. stapel_integrations_core-0.1.0/dto.py +57 -0
  14. stapel_integrations_core-0.1.0/errors.py +137 -0
  15. stapel_integrations_core-0.1.0/gdpr.py +38 -0
  16. stapel_integrations_core-0.1.0/llms.txt +17 -0
  17. stapel_integrations_core-0.1.0/management/__init__.py +0 -0
  18. stapel_integrations_core-0.1.0/management/commands/__init__.py +0 -0
  19. stapel_integrations_core-0.1.0/management/commands/integrations_rotate_keys.py +25 -0
  20. stapel_integrations_core-0.1.0/migrations/0001_initial.py +39 -0
  21. stapel_integrations_core-0.1.0/migrations/__init__.py +0 -0
  22. stapel_integrations_core-0.1.0/models.py +61 -0
  23. stapel_integrations_core-0.1.0/presenters.py +46 -0
  24. stapel_integrations_core-0.1.0/py.typed +0 -0
  25. stapel_integrations_core-0.1.0/pyproject.toml +81 -0
  26. stapel_integrations_core-0.1.0/serializers.py +50 -0
  27. stapel_integrations_core-0.1.0/services.py +297 -0
  28. stapel_integrations_core-0.1.0/setup.cfg +4 -0
  29. stapel_integrations_core-0.1.0/stapel_integrations_core.egg-info/PKG-INFO +65 -0
  30. stapel_integrations_core-0.1.0/stapel_integrations_core.egg-info/SOURCES.txt +81 -0
  31. stapel_integrations_core-0.1.0/stapel_integrations_core.egg-info/dependency_links.txt +1 -0
  32. stapel_integrations_core-0.1.0/stapel_integrations_core.egg-info/requires.txt +10 -0
  33. stapel_integrations_core-0.1.0/stapel_integrations_core.egg-info/top_level.txt +1 -0
  34. stapel_integrations_core-0.1.0/stpl_integrations_access.py +99 -0
  35. stapel_integrations_core-0.1.0/stpl_integrations_crypto.py +63 -0
  36. stapel_integrations_core-0.1.0/stpl_integrations_markdown.py +211 -0
  37. stapel_integrations_core-0.1.0/stpl_integrations_net.py +420 -0
  38. stapel_integrations_core-0.1.0/stpl_integrations_providers.py +124 -0
  39. stapel_integrations_core-0.1.0/stpl_integrations_testing.py +39 -0
  40. stapel_integrations_core-0.1.0/tests/test_api.py +261 -0
  41. stapel_integrations_core-0.1.0/tests/test_module_names.py +23 -0
  42. stapel_integrations_core-0.1.0/tests/test_public_api.py +45 -0
  43. stapel_integrations_core-0.1.0/tests/test_stpl_integrations_markdown.py +36 -0
  44. stapel_integrations_core-0.1.0/tests/test_stpl_integrations_net.py +94 -0
  45. stapel_integrations_core-0.1.0/translations/errors.es.json +21 -0
  46. stapel_integrations_core-0.1.0/translations/errors.ru.json +21 -0
  47. stapel_integrations_core-0.1.0/urls.py +6 -0
  48. stapel_integrations_core-0.1.0/urls_v1.py +24 -0
  49. stapel_integrations_core-0.1.0/views.py +161 -0
@@ -0,0 +1,18 @@
1
+ # CONFIG.MD — stapel-integrations-core
2
+
3
+ Keys live in `STAPEL_INTEGRATIONS_CORE`. Resolution: dict → flat Django setting of the same name → environment → default; hence the prefix on every key.
4
+
5
+ | Key | Default | Meaning |
6
+ |---|---|---|
7
+ | `INTEGRATIONS_ENCRYPTION_KEYS` | `[]` | Fernet keys, newest first. Empty: the secret `STAPEL_INTEGRATIONS_ENCRYPTION_KEY`. Without either nothing is stored. |
8
+ | `INTEGRATIONS_ACCESS_POLICY` | `…DefaultAccessPolicy` | Who may do what. Not read from the environment. |
9
+ | `INTEGRATIONS_MANAGE_ROLES` | `["owner"]` | Roles that manage connections. |
10
+ | `INTEGRATIONS_ACCESS_ADMIN_ROLES` | `["owner","admin"]` | Roles that choose who may use one. |
11
+ | `INTEGRATIONS_USE_LEVELS` | members / admins / owner | Choices and their roles. |
12
+ | `INTEGRATIONS_DEFAULT_USE_LEVEL` | `"members"` | Level of a new connection. |
13
+ | `INTEGRATIONS_MAX_PER_SCOPE` | `50` | Cap per scope. |
14
+ | `INTEGRATIONS_TIMEOUT_SECONDS` | `20.0` | Per request. |
15
+ | `INTEGRATIONS_MAX_RETRIES` | `2` | Reads only. |
16
+ | `INTEGRATIONS_MAX_RETRY_AFTER_SECONDS` | `30` | Longest honoured wait. |
17
+ | `INTEGRATIONS_MAX_RESPONSE_BYTES` | `10485760` | Response cap. |
18
+ | `INTEGRATIONS_TRANSPORT` | `…SafeHttpsTransport` | For an egress proxy or tests. Not read from the environment. |
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stapel contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,31 @@
1
+ # MODULE.md — stapel-integrations-core
2
+
3
+ ## Model
4
+ `IntegrationConnection` (app label `integrations`): provider, scope_type, scope_id, name, config (JSON, non-secret), secrets_encrypted, use_level, check results.
5
+
6
+ ## HTTP (`/integrations/api/v1/`)
7
+ | Route | Who |
8
+ |---|---|
9
+ | `GET providers` | any signed-in user: installed integrations and their form fields |
10
+ | `GET, POST connections?scope_type&scope_id` | managers |
11
+ | `GET connections/available` | what the caller may use or set access on; no account details |
12
+ | `GET, PATCH, DELETE connections/<id>` | managers |
13
+ | `PUT connections/<id>/access` `{use_level}` | access administrators |
14
+ | `POST connections/<id>/check` | managers |
15
+
16
+ A caller with no rights on a connection gets 404.
17
+
18
+ ## Default access (workspace scope)
19
+ Manage: owner. Choose who may use: owner, admin. Use: the connection's `use_level` — `members` (owner, admin, member; default), `admins`, `owner`. Viewers never use. A `user` scope belongs to that user. Unknown scope types are refused. A failing role lookup answers 503.
20
+
21
+ ## Security
22
+ - Outbound: https:443, public addresses only, validated IP is the one dialled, no redirects, capped responses, reads retried, writes never.
23
+ - Secrets: Fernet, key rotation with `manage.py integrations_rotate_keys`.
24
+ - Changing a field marked `rebinds` requires every secret again.
25
+ - GDPR: erasing a user deletes the connections whose secrets they entered. `user.merged` re-parents.
26
+
27
+ ## Seams
28
+ `INTEGRATIONS_ACCESS_POLICY`, `INTEGRATIONS_TRANSPORT`, the provider registry, `STAPEL_INTEGRATIONS_CORE_CONNECTION_PRESENTER`.
29
+
30
+ ## Not here
31
+ Delivery queues and export history: the host decides what it sends and records it.
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: stapel-integrations-core
3
+ Version: 0.1.0
4
+ Summary: Shared base of Stapel integrations: stored connections, access, safe HTTP, provider registry
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/usestapel/stapel-integrations-core
7
+ Project-URL: Repository, https://github.com/usestapel/stapel-integrations-core
8
+ Project-URL: Documentation, https://github.com/usestapel/stapel-integrations-core#readme
9
+ Project-URL: Changelog, https://github.com/usestapel/stapel-integrations-core/blob/main/CHANGELOG.md
10
+ Project-URL: Issues, https://github.com/usestapel/stapel-integrations-core/issues
11
+ Keywords: django,stapel,integrations-core
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: Django
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: stapel-core<1.0,>=0.99.5
27
+ Requires-Dist: cryptography>=41.0
28
+ Requires-Dist: drf-spectacular>=0.27
29
+ Provides-Extra: all
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest; extra == "test"
32
+ Requires-Dist: pytest-django; extra == "test"
33
+ Requires-Dist: pytest-cov; extra == "test"
34
+ Dynamic: license-file
35
+
36
+ # stapel-integrations-core
37
+
38
+ Shared base of Stapel integrations: stored connections with encrypted secrets, per-workspace access, guarded outbound HTTP and a provider registry.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install stapel-integrations-core stapel-atlassian # plus the integrations you need
44
+ ```
45
+
46
+ ```python
47
+ INSTALLED_APPS += ["stapel_integrations_core", "stapel_atlassian"]
48
+ urlpatterns += [path("integrations/", include("stapel_integrations_core.urls"))]
49
+ STAPEL_INTEGRATIONS_CORE = {"INTEGRATIONS_ENCRYPTION_KEYS": [FERNET_KEY]} # or the secret STAPEL_INTEGRATIONS_ENCRYPTION_KEY
50
+ ```
51
+
52
+ Run `migrate`. The default workspace policy asks the comm function `workspaces.check_membership`.
53
+
54
+ ## Use
55
+
56
+ ```python
57
+ from stapel_integrations_core import services
58
+
59
+ row = services.get_connection(request.user, connection_id, services.USE, provider="atlassian")
60
+ site = services.open_integration(row)
61
+ ```
62
+
63
+ See `MODULE.md` for the contract, `CONFIG.MD` for settings, `llms.txt` for agents.
64
+
65
+ MIT licensed.
@@ -0,0 +1,30 @@
1
+ # stapel-integrations-core
2
+
3
+ Shared base of Stapel integrations: stored connections with encrypted secrets, per-workspace access, guarded outbound HTTP and a provider registry.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install stapel-integrations-core stapel-atlassian # plus the integrations you need
9
+ ```
10
+
11
+ ```python
12
+ INSTALLED_APPS += ["stapel_integrations_core", "stapel_atlassian"]
13
+ urlpatterns += [path("integrations/", include("stapel_integrations_core.urls"))]
14
+ STAPEL_INTEGRATIONS_CORE = {"INTEGRATIONS_ENCRYPTION_KEYS": [FERNET_KEY]} # or the secret STAPEL_INTEGRATIONS_ENCRYPTION_KEY
15
+ ```
16
+
17
+ Run `migrate`. The default workspace policy asks the comm function `workspaces.check_membership`.
18
+
19
+ ## Use
20
+
21
+ ```python
22
+ from stapel_integrations_core import services
23
+
24
+ row = services.get_connection(request.user, connection_id, services.USE, provider="atlassian")
25
+ site = services.open_integration(row)
26
+ ```
27
+
28
+ See `MODULE.md` for the contract, `CONFIG.MD` for settings, `llms.txt` for agents.
29
+
30
+ MIT licensed.
@@ -0,0 +1,40 @@
1
+ """stapel-integrations-core — what every Stapel integration shares.
2
+
3
+ Public names are exported lazily (PEP 562): importing the package never
4
+ imports Django.
5
+ """
6
+
7
+ _LAZY_EXPORTS = {
8
+ "ApiClient": ".stpl_integrations_net",
9
+ "IntegrationError": ".stpl_integrations_net",
10
+ "AuthError": ".stpl_integrations_net",
11
+ "ConfigError": ".stpl_integrations_net",
12
+ "NotFoundError": ".stpl_integrations_net",
13
+ "PermissionDeniedError": ".stpl_integrations_net",
14
+ "RateLimited": ".stpl_integrations_net",
15
+ "RejectedError": ".stpl_integrations_net",
16
+ "Unavailable": ".stpl_integrations_net",
17
+ "UnknownOutcome": ".stpl_integrations_net",
18
+ "IntegrationProvider": ".stpl_integrations_providers",
19
+ "Field": ".stpl_integrations_providers",
20
+ "InvalidField": ".stpl_integrations_providers",
21
+ "CheckResult": ".stpl_integrations_providers",
22
+ "register_provider": ".stpl_integrations_providers",
23
+ "integrations_settings": ".conf",
24
+ }
25
+
26
+ __all__ = sorted(_LAZY_EXPORTS)
27
+
28
+
29
+ def __getattr__(name):
30
+ if name in _LAZY_EXPORTS:
31
+ from importlib import import_module
32
+
33
+ value = getattr(import_module(_LAZY_EXPORTS[name], __name__), name)
34
+ globals()[name] = value
35
+ return value
36
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
37
+
38
+
39
+ def __dir__():
40
+ return sorted(set(globals()) | set(__all__))
@@ -0,0 +1,33 @@
1
+ """comm Actions this module reacts to. Both handlers are idempotent."""
2
+ from django.db import IntegrityError, transaction
3
+ from stapel_core.comm import on_action
4
+
5
+
6
+ @on_action("user.deleted")
7
+ def handle_user_deleted(event):
8
+ """Delete the erased person's credentials (GDPR Art. 17)."""
9
+ from .gdpr import IntegrationsGDPRProvider
10
+
11
+ user_id = (event.payload or {}).get("user_id")
12
+ if user_id:
13
+ IntegrationsGDPRProvider().delete(user_id)
14
+
15
+
16
+ @on_action("user.merged")
17
+ def handle_user_merged(event):
18
+ """Move a merged-away account's connections to the surviving one."""
19
+ from .models import SCOPE_USER, IntegrationConnection
20
+
21
+ payload = event.payload or {}
22
+ old, new = payload.get("from_user_id"), payload.get("into_user_id")
23
+ if not old or not new:
24
+ return
25
+ IntegrationConnection.objects.filter(created_by=old).update(created_by=new)
26
+ for row in IntegrationConnection.objects.filter(scope_type=SCOPE_USER, scope_id=str(old)):
27
+ row.scope_id = str(new)
28
+ try:
29
+ with transaction.atomic():
30
+ row.save(update_fields=["scope_id"])
31
+ except IntegrityError:
32
+ row.name = f"{row.name[:100]} ({str(old)[:8]})"
33
+ row.save(update_fields=["scope_id", "name"])
@@ -0,0 +1,21 @@
1
+ """Read-only admin without the secrets column."""
2
+ from django.contrib import admin
3
+
4
+ from .models import IntegrationConnection
5
+
6
+
7
+ @admin.register(IntegrationConnection)
8
+ class IntegrationConnectionAdmin(admin.ModelAdmin):
9
+ list_display = ("name", "provider", "scope_type", "scope_id", "use_level", "last_check_ok")
10
+ list_filter = ("provider", "scope_type", "last_check_ok")
11
+ search_fields = ("name", "scope_id")
12
+ exclude = ("secrets_encrypted",)
13
+
14
+ def get_readonly_fields(self, request, obj=None):
15
+ return [f.name for f in self.model._meta.fields if f.name != "secrets_encrypted"]
16
+
17
+ def has_add_permission(self, request):
18
+ return False
19
+
20
+ def has_change_permission(self, request, obj=None):
21
+ return False
@@ -0,0 +1,18 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class IntegrationsCoreConfig(AppConfig):
5
+ name = "stapel_integrations_core"
6
+ label = "integrations"
7
+ verbose_name = "Integrations"
8
+ default_auto_field = "django.db.models.BigAutoField"
9
+
10
+ def ready(self):
11
+ # Import-time registration: comm actions, checks, error keys.
12
+ from stapel_core.gdpr import gdpr_registry
13
+
14
+ from . import actions, checks, errors # noqa: F401
15
+ from .gdpr import IntegrationsGDPRProvider
16
+
17
+ if IntegrationsGDPRProvider.section not in gdpr_registry.sections:
18
+ gdpr_registry.register(IntegrationsGDPRProvider())
@@ -0,0 +1,25 @@
1
+ """System checks: configurations that boot cleanly and cannot work."""
2
+ from django.core import checks
3
+
4
+ from .conf import integrations_settings
5
+
6
+
7
+ @checks.register(checks.Tags.security)
8
+ def check_integrations_settings(app_configs, **kwargs):
9
+ from . import stpl_integrations_crypto as crypto
10
+
11
+ problems = []
12
+ if not crypto.is_configured():
13
+ problems.append(checks.Warning(
14
+ "No usable encryption key: integration connections cannot be stored.",
15
+ hint="Set STAPEL_INTEGRATIONS_CORE['INTEGRATIONS_ENCRYPTION_KEYS'] or the secret "
16
+ f"{crypto.SECRET_NAME} (cryptography.fernet.Fernet.generate_key()).",
17
+ id="stapel_integrations_core.W001",
18
+ ))
19
+ levels = integrations_settings.INTEGRATIONS_USE_LEVELS or {}
20
+ if integrations_settings.INTEGRATIONS_DEFAULT_USE_LEVEL not in levels:
21
+ problems.append(checks.Error(
22
+ "INTEGRATIONS_DEFAULT_USE_LEVEL is not one of INTEGRATIONS_USE_LEVELS.",
23
+ id="stapel_integrations_core.E001",
24
+ ))
25
+ return problems
@@ -0,0 +1,49 @@
1
+ """Settings namespace ``STAPEL_INTEGRATIONS_CORE``.
2
+
3
+ Resolution per key: the namespace dict -> a flat Django setting of the same
4
+ name -> environment variable -> the default. Because of the flat fallback
5
+ every key is prefixed: an unprefixed ``ALLOWED_HOSTS`` would silently read
6
+ Django's own.
7
+ """
8
+ from stapel_core.conf import AppSettings
9
+
10
+ DEFAULTS = {
11
+ # ── Secrets at rest ──────────────────────────────────────────────
12
+ # Fernet keys, newest first (a list or a comma-separated string). Empty:
13
+ # the secret STAPEL_INTEGRATIONS_ENCRYPTION_KEY is read through
14
+ # stapel_core.secrets. With neither, no connection can be stored.
15
+ "INTEGRATIONS_ENCRYPTION_KEYS": [],
16
+
17
+ # ── Access ───────────────────────────────────────────────────────
18
+ "INTEGRATIONS_ACCESS_POLICY": "stapel_integrations_core.stpl_integrations_access.DefaultAccessPolicy",
19
+ # Workspace roles that see a connection and its settings, and create,
20
+ # change, delete and check it.
21
+ "INTEGRATIONS_MANAGE_ROLES": ["owner"],
22
+ # Workspace roles that choose who may use a connection.
23
+ "INTEGRATIONS_ACCESS_ADMIN_ROLES": ["owner", "admin"],
24
+ # The choices of "who may use it", each a list of workspace roles.
25
+ "INTEGRATIONS_USE_LEVELS": {
26
+ "members": ["owner", "admin", "member"],
27
+ "admins": ["owner", "admin"],
28
+ "owner": ["owner"],
29
+ },
30
+ "INTEGRATIONS_DEFAULT_USE_LEVEL": "members",
31
+ "INTEGRATIONS_MAX_PER_SCOPE": 50,
32
+
33
+ # ── Outbound HTTP ────────────────────────────────────────────────
34
+ "INTEGRATIONS_TIMEOUT_SECONDS": 20.0,
35
+ # Retries of reads only. A write is never repeated.
36
+ "INTEGRATIONS_MAX_RETRIES": 2,
37
+ "INTEGRATIONS_MAX_RETRY_AFTER_SECONDS": 30,
38
+ "INTEGRATIONS_MAX_RESPONSE_BYTES": 10 * 1024 * 1024,
39
+ "INTEGRATIONS_TRANSPORT": "stapel_integrations_core.stpl_integrations_net.SafeHttpsTransport",
40
+ }
41
+
42
+ integrations_settings = AppSettings(
43
+ "STAPEL_INTEGRATIONS_CORE",
44
+ defaults=DEFAULTS,
45
+ # Names that select code are never read from the environment.
46
+ import_strings=("INTEGRATIONS_ACCESS_POLICY", "INTEGRATIONS_TRANSPORT"),
47
+ )
48
+
49
+ __all__ = ["DEFAULTS", "integrations_settings"]
@@ -0,0 +1,62 @@
1
+ def pytest_configure(config):
2
+ from cryptography.fernet import Fernet
3
+ from django.conf import settings
4
+ if not settings.configured:
5
+ settings.configure(
6
+ SECRET_KEY="test-secret-key-not-for-production",
7
+ INSTALLED_APPS=[
8
+ "django.contrib.contenttypes",
9
+ "django.contrib.auth",
10
+ "django.contrib.sessions",
11
+ "django.contrib.admin",
12
+ "django.contrib.messages",
13
+ "stapel_core.django.users",
14
+ "rest_framework",
15
+ "stapel_integrations_core",
16
+ ],
17
+ AUTH_USER_MODEL="users.User",
18
+ DATABASES={
19
+ "default": {
20
+ "ENGINE": "django.db.backends.sqlite3",
21
+ "NAME": ":memory:",
22
+ }
23
+ },
24
+ DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
25
+ USE_TZ=True,
26
+ ROOT_URLCONF="stapel_integrations_core.tests.urls",
27
+ STAPEL_INTEGRATIONS_CORE={
28
+ # A throwaway key generated per run.
29
+ "INTEGRATIONS_ENCRYPTION_KEYS": [Fernet.generate_key().decode()],
30
+ },
31
+ CACHES={
32
+ "default": {
33
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
34
+ }
35
+ },
36
+ # Synchronous in-process comm with schema validation ON, so the
37
+ # committed contracts in schemas/ are enforced by the tests.
38
+ STAPEL_BUS_BACKEND="stapel_core.bus.backends.memory.MemoryBus",
39
+ STAPEL_COMM={
40
+ "OUTBOX_ENABLED": False,
41
+ "ACTION_TRANSPORT": "inprocess",
42
+ "VALIDATE_SCHEMAS": True,
43
+ },
44
+ MIGRATION_MODULES={
45
+ "users": None,
46
+ "integrations": None,
47
+ },
48
+ )
49
+ import django
50
+ django.setup()
51
+
52
+ from stapel_core.comm.schemas import autoload_schemas
53
+ autoload_schemas()
54
+
55
+
56
+ import pytest # noqa: E402
57
+
58
+
59
+ @pytest.fixture
60
+ def api_client():
61
+ from rest_framework.test import APIClient
62
+ return APIClient()
@@ -0,0 +1,57 @@
1
+ """Response DTOs. None of them can carry a secret."""
2
+ from dataclasses import dataclass, field
3
+ from typing import Optional
4
+
5
+
6
+ @dataclass
7
+ class FieldDTO:
8
+ """One input of an integration's connection form."""
9
+
10
+ name: str
11
+ kind: str
12
+ required: bool
13
+ rebinds: bool
14
+ read_only: bool
15
+ label: str
16
+ help: str
17
+ max_length: int
18
+
19
+
20
+ @dataclass
21
+ class ProviderDTO:
22
+ """An installed integration and its form fields."""
23
+
24
+ slug: str
25
+ title: str
26
+ fields: list[FieldDTO] = field(default_factory=list)
27
+
28
+
29
+ @dataclass
30
+ class ConnectionDTO:
31
+ """A stored connection as its manager sees it. Never carries a secret."""
32
+
33
+ id: str
34
+ provider: str
35
+ scope_type: str
36
+ scope_id: str
37
+ name: str
38
+ config: dict
39
+ use_level: str
40
+ created_at: str
41
+ updated_at: str
42
+ last_checked_at: Optional[str]
43
+ last_check_ok: Optional[bool]
44
+ last_check_errors: dict
45
+
46
+
47
+ @dataclass
48
+ class AvailableConnectionDTO:
49
+ """What a non-manager sees: enough to choose it, nothing about the account."""
50
+
51
+ id: str
52
+ provider: str
53
+ name: str
54
+ use_level: str
55
+ can_use: bool
56
+ can_set_access: bool
57
+ can_manage: bool
@@ -0,0 +1,137 @@
1
+ """Error keys of stapel-integrations-core.
2
+
3
+ Every integration answers with these: the ``service`` parameter names the
4
+ third party. A refusal from a third party is never answered with 401: that
5
+ would read as the caller's own session dying.
6
+ """
7
+ from stapel_core.django.api.errors import ErrorKeysView, StapelErrorResponse, register_service_errors
8
+
9
+ from . import stpl_integrations_crypto as crypto
10
+ from .stpl_integrations_access import AccessUnavailable
11
+ from .stpl_integrations_net import IntegrationError
12
+ from .services import ServiceError
13
+
14
+ ERR_400_INVALID = "error.400.integrations_invalid"
15
+ ERR_400_INVALID_FIELD = "error.400.integrations_invalid_field"
16
+ ERR_400_SECRET_REQUIRED = "error.400.integrations_secret_required"
17
+ ERR_400_UNKNOWN_PROVIDER = "error.400.integrations_unknown_provider"
18
+ ERR_403_FORBIDDEN = "error.403.integrations_forbidden"
19
+ ERR_404_CONNECTION = "error.404.integrations_connection_not_found"
20
+ ERR_409_NAME_TAKEN = "error.409.integrations_name_taken"
21
+ ERR_409_CONNECTION_LIMIT = "error.409.integrations_connection_limit"
22
+ ERR_409_SECRET_UNREADABLE = "error.409.integrations_secret_unreadable"
23
+ ERR_503_ACCESS_UNAVAILABLE = "error.503.integrations_access_unavailable"
24
+ ERR_503_NOT_CONFIGURED = "error.503.integrations_not_configured"
25
+ # Refusals of the third party.
26
+ ERR_400_AUTH_FAILED = "error.400.integrations_auth_failed"
27
+ ERR_400_REMOTE_FORBIDDEN = "error.400.integrations_remote_forbidden"
28
+ ERR_400_REMOTE_CONFIG = "error.400.integrations_remote_config"
29
+ ERR_400_REJECTED = "error.400.integrations_rejected"
30
+ ERR_404_REMOTE = "error.404.integrations_remote_not_found"
31
+ ERR_429_REMOTE = "error.429.integrations_rate_limited"
32
+ ERR_502_UNAVAILABLE = "error.502.integrations_unavailable"
33
+ ERR_502_UNKNOWN_OUTCOME = "error.502.integrations_unknown_outcome"
34
+
35
+ STAPEL_INTEGRATIONS_ERRORS = {
36
+ ERR_400_INVALID: "The request is not valid",
37
+ ERR_400_INVALID_FIELD: "Check the value of the field {field}",
38
+ ERR_400_SECRET_REQUIRED: "Enter {field} again. It is required for a new connection and when the account or address changes",
39
+ ERR_400_UNKNOWN_PROVIDER: "This integration is not installed",
40
+ ERR_403_FORBIDDEN: "You do not have permission to do this with the connection",
41
+ ERR_404_CONNECTION: "Connection not found",
42
+ ERR_409_NAME_TAKEN: "A connection with this name already exists",
43
+ ERR_409_CONNECTION_LIMIT: "The maximum number of connections is reached",
44
+ ERR_409_SECRET_UNREADABLE: "The saved credentials can no longer be read. Enter them again",
45
+ ERR_503_ACCESS_UNAVAILABLE: "We could not check your permissions. Try again in a moment",
46
+ ERR_503_NOT_CONFIGURED: "Integrations are not set up on this server",
47
+ ERR_400_AUTH_FAILED: "{service} did not accept the saved credentials. Check them, or create new ones",
48
+ ERR_400_REMOTE_FORBIDDEN: "The {service} account does not have permission for this action",
49
+ ERR_400_REMOTE_CONFIG: "{service} cannot be reached with these settings",
50
+ ERR_400_REJECTED: "{service} refused the request: {detail}",
51
+ ERR_404_REMOTE: "{service} did not find this item, or the account cannot see it",
52
+ ERR_429_REMOTE: "{service} is limiting requests. Try again later",
53
+ ERR_502_UNAVAILABLE: "{service} is not responding. Try again later",
54
+ ERR_502_UNKNOWN_OUTCOME: "{service} did not confirm the result. Check there before you try again",
55
+ }
56
+
57
+ STAPEL_INTEGRATIONS_REMEDIATION = {
58
+ ERR_400_INVALID: "fix_input",
59
+ ERR_400_INVALID_FIELD: "fix_input",
60
+ ERR_400_SECRET_REQUIRED: "fix_input",
61
+ ERR_400_UNKNOWN_PROVIDER: "verify",
62
+ ERR_403_FORBIDDEN: "contact_support",
63
+ ERR_404_CONNECTION: "verify",
64
+ ERR_409_NAME_TAKEN: "fix_input",
65
+ ERR_409_CONNECTION_LIMIT: "verify",
66
+ ERR_409_SECRET_UNREADABLE: "fix_input",
67
+ ERR_503_ACCESS_UNAVAILABLE: "retry",
68
+ ERR_503_NOT_CONFIGURED: "contact_support",
69
+ ERR_400_AUTH_FAILED: "fix_input",
70
+ ERR_400_REMOTE_FORBIDDEN: "verify",
71
+ ERR_400_REMOTE_CONFIG: "fix_input",
72
+ ERR_400_REJECTED: "fix_input",
73
+ ERR_404_REMOTE: "verify",
74
+ ERR_429_REMOTE: "retry",
75
+ ERR_502_UNAVAILABLE: "retry",
76
+ ERR_502_UNKNOWN_OUTCOME: "verify",
77
+ }
78
+
79
+ register_service_errors(STAPEL_INTEGRATIONS_ERRORS, remediation=STAPEL_INTEGRATIONS_REMEDIATION)
80
+
81
+ _SERVICE_KEYS = {
82
+ "invalid": ERR_400_INVALID,
83
+ "invalid_field": ERR_400_INVALID_FIELD,
84
+ "secret_required": ERR_400_SECRET_REQUIRED,
85
+ "unknown_provider": ERR_400_UNKNOWN_PROVIDER,
86
+ "forbidden": ERR_403_FORBIDDEN,
87
+ "connection_not_found": ERR_404_CONNECTION,
88
+ "name_taken": ERR_409_NAME_TAKEN,
89
+ "connection_limit": ERR_409_CONNECTION_LIMIT,
90
+ }
91
+
92
+ _REMOTE_KEYS = {
93
+ "auth_failed": ERR_400_AUTH_FAILED,
94
+ "forbidden": ERR_400_REMOTE_FORBIDDEN,
95
+ "invalid_config": ERR_400_REMOTE_CONFIG,
96
+ "rejected": ERR_400_REJECTED,
97
+ "not_found": ERR_404_REMOTE,
98
+ "rate_limited": ERR_429_REMOTE,
99
+ "unavailable": ERR_502_UNAVAILABLE,
100
+ "unknown_outcome": ERR_502_UNKNOWN_OUTCOME,
101
+ }
102
+
103
+ #: Everything :func:`error_response` translates — catch exactly this.
104
+ HANDLED_ERRORS = (
105
+ IntegrationError, ServiceError, AccessUnavailable,
106
+ crypto.EncryptionNotConfigured, crypto.SecretUnreadable,
107
+ )
108
+
109
+
110
+ def error_response(exc: Exception, *, service: str = "The service"):
111
+ """The unified error envelope for any of :data:`HANDLED_ERRORS`.
112
+
113
+ Public so an integration's and a host's own endpoints answer the same way.
114
+ """
115
+ if isinstance(exc, ServiceError):
116
+ key = _SERVICE_KEYS.get(exc.code, ERR_400_INVALID)
117
+ return StapelErrorResponse(exc.status, key, {"field": exc.field} if exc.field else {})
118
+ if isinstance(exc, IntegrationError):
119
+ key = _REMOTE_KEYS.get(exc.code, ERR_502_UNAVAILABLE)
120
+ params = {"service": service}
121
+ if key == ERR_400_REJECTED:
122
+ params["detail"] = exc.detail
123
+ return StapelErrorResponse(int(key.split(".")[1]), key, params)
124
+ if isinstance(exc, AccessUnavailable):
125
+ return StapelErrorResponse(503, ERR_503_ACCESS_UNAVAILABLE, {})
126
+ if isinstance(exc, crypto.EncryptionNotConfigured):
127
+ return StapelErrorResponse(503, ERR_503_NOT_CONFIGURED, {})
128
+ if isinstance(exc, crypto.SecretUnreadable):
129
+ return StapelErrorResponse(409, ERR_409_SECRET_UNREADABLE, {})
130
+ raise exc
131
+
132
+
133
+ class IntegrationsErrorKeysView(ErrorKeysView):
134
+ """The listing the stapel-translate error collector reads."""
135
+
136
+ def get_service_errors(self):
137
+ return STAPEL_INTEGRATIONS_ERRORS
@@ -0,0 +1,38 @@
1
+ """GDPR handler: the secrets of a connection are one person's credential.
2
+
3
+ Erasing a user deletes every connection whose secrets they entered, workspace
4
+ ones included: it acts in the third-party service under their name.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from django.db.models import Q
9
+ from stapel_core.gdpr import GDPRProvider
10
+
11
+
12
+ def _rows(user_id):
13
+ from .models import SCOPE_USER, IntegrationConnection
14
+
15
+ return IntegrationConnection.objects.filter(
16
+ Q(created_by=user_id) | Q(scope_type=SCOPE_USER, scope_id=str(user_id))
17
+ )
18
+
19
+
20
+ class IntegrationsGDPRProvider(GDPRProvider):
21
+ section = "integrations"
22
+
23
+ def export(self, user_id) -> dict:
24
+ return {
25
+ "connections": [
26
+ {
27
+ "id": str(row.id), "provider": row.provider, "name": row.name,
28
+ "config": row.config, "created_at": row.created_at.isoformat(),
29
+ }
30
+ for row in _rows(user_id)
31
+ ]
32
+ }
33
+
34
+ def delete(self, user_id) -> None:
35
+ _rows(user_id).delete()
36
+
37
+ def anonymize(self, user_id) -> None:
38
+ self.delete(user_id)