stapel-integrations-core 0.1.0__py3-none-any.whl
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.
- stapel_integrations_core/CONFIG.MD +18 -0
- stapel_integrations_core/MODULE.md +31 -0
- stapel_integrations_core/__init__.py +40 -0
- stapel_integrations_core/actions.py +33 -0
- stapel_integrations_core/admin.py +21 -0
- stapel_integrations_core/apps.py +18 -0
- stapel_integrations_core/checks.py +25 -0
- stapel_integrations_core/conf.py +49 -0
- stapel_integrations_core/conftest.py +62 -0
- stapel_integrations_core/dto.py +57 -0
- stapel_integrations_core/errors.py +137 -0
- stapel_integrations_core/gdpr.py +38 -0
- stapel_integrations_core/llms.txt +17 -0
- stapel_integrations_core/management/__init__.py +0 -0
- stapel_integrations_core/management/commands/__init__.py +0 -0
- stapel_integrations_core/management/commands/integrations_rotate_keys.py +25 -0
- stapel_integrations_core/migrations/0001_initial.py +39 -0
- stapel_integrations_core/migrations/__init__.py +0 -0
- stapel_integrations_core/models.py +61 -0
- stapel_integrations_core/presenters.py +46 -0
- stapel_integrations_core/py.typed +0 -0
- stapel_integrations_core/serializers.py +50 -0
- stapel_integrations_core/services.py +297 -0
- stapel_integrations_core/stpl_integrations_access.py +99 -0
- stapel_integrations_core/stpl_integrations_crypto.py +63 -0
- stapel_integrations_core/stpl_integrations_markdown.py +211 -0
- stapel_integrations_core/stpl_integrations_net.py +420 -0
- stapel_integrations_core/stpl_integrations_providers.py +124 -0
- stapel_integrations_core/stpl_integrations_testing.py +39 -0
- stapel_integrations_core/translations/errors.es.json +21 -0
- stapel_integrations_core/translations/errors.ru.json +21 -0
- stapel_integrations_core/urls.py +6 -0
- stapel_integrations_core/urls_v1.py +24 -0
- stapel_integrations_core/views.py +161 -0
- stapel_integrations_core-0.1.0.dist-info/METADATA +65 -0
- stapel_integrations_core-0.1.0.dist-info/RECORD +39 -0
- stapel_integrations_core-0.1.0.dist-info/WHEEL +5 -0
- stapel_integrations_core-0.1.0.dist-info/licenses/LICENSE +21 -0
- stapel_integrations_core-0.1.0.dist-info/top_level.txt +1 -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,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,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)
|
|
@@ -0,0 +1,17 @@
|
|
|
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
|
+
## Rules
|
|
6
|
+
- Get a connection only through `services.get_connection(user, id, action, provider=...)`; never query the model in a view.
|
|
7
|
+
- Actions: MANAGE (see settings, change), SET_ACCESS (choose who may use), USE (act through it).
|
|
8
|
+
- Secrets are write-only: no API, log or error text may carry them.
|
|
9
|
+
- A write that raises `UnknownOutcome` must not be retried blindly.
|
|
10
|
+
- In views use `IntegrationAPIView`, `@maps_errors`, `provider_slug`.
|
|
11
|
+
|
|
12
|
+
## Add an integration
|
|
13
|
+
1. New package `stapel-<name>`; modules named `stpl_<name>_*.py`.
|
|
14
|
+
2. A client subclassing `stpl_integrations_net.ApiClient` (pass secrets in `secrets=` so they are redacted).
|
|
15
|
+
3. An `IntegrationProvider` with `fields`, `clean`, `build`, `check`; `register_provider()` in `AppConfig.ready()`.
|
|
16
|
+
4. Test with `stpl_integrations_testing.FakeTransport`.
|
|
17
|
+
Text goes in as Markdown: parse it with `stpl_integrations_markdown.parse` and escape for the target.
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Re-encrypt every stored secret with the newest key."""
|
|
2
|
+
from django.core.management.base import BaseCommand, CommandError
|
|
3
|
+
|
|
4
|
+
from stapel_integrations_core import stpl_integrations_crypto as crypto
|
|
5
|
+
from stapel_integrations_core.models import IntegrationConnection
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Command(BaseCommand):
|
|
9
|
+
help = "Re-encrypt stored integration secrets with the first encryption key."
|
|
10
|
+
|
|
11
|
+
def handle(self, *args, **options):
|
|
12
|
+
rotated, unreadable = 0, []
|
|
13
|
+
for row in IntegrationConnection.objects.all().iterator():
|
|
14
|
+
try:
|
|
15
|
+
fresh = crypto.rotate(row.secrets_encrypted)
|
|
16
|
+
except crypto.SecretUnreadable:
|
|
17
|
+
unreadable.append(str(row.id))
|
|
18
|
+
continue
|
|
19
|
+
# Compare-and-set: secrets replaced meanwhile are left alone.
|
|
20
|
+
rotated += IntegrationConnection.objects.filter(
|
|
21
|
+
pk=row.pk, secrets_encrypted=row.secrets_encrypted
|
|
22
|
+
).update(secrets_encrypted=fresh)
|
|
23
|
+
self.stdout.write(f"rotated {rotated}")
|
|
24
|
+
if unreadable:
|
|
25
|
+
raise CommandError(f"unreadable with the listed keys: {', '.join(unreadable)}")
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Generated by Django 6.1.3 on 2026-11-27 22:06
|
|
2
|
+
|
|
3
|
+
import uuid
|
|
4
|
+
from django.db import migrations, models
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Migration(migrations.Migration):
|
|
8
|
+
|
|
9
|
+
initial = True
|
|
10
|
+
|
|
11
|
+
dependencies = [
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
operations = [
|
|
15
|
+
migrations.CreateModel(
|
|
16
|
+
name='IntegrationConnection',
|
|
17
|
+
fields=[
|
|
18
|
+
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
|
19
|
+
('provider', models.CharField(max_length=40)),
|
|
20
|
+
('scope_type', models.CharField(max_length=32)),
|
|
21
|
+
('scope_id', models.CharField(max_length=64)),
|
|
22
|
+
('name', models.CharField(max_length=120)),
|
|
23
|
+
('config', models.JSONField(blank=True, default=dict)),
|
|
24
|
+
('secrets_encrypted', models.TextField()),
|
|
25
|
+
('use_level', models.CharField(default='members', max_length=32)),
|
|
26
|
+
('created_by', models.UUIDField(blank=True, db_index=True, null=True)),
|
|
27
|
+
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
28
|
+
('updated_at', models.DateTimeField(auto_now=True)),
|
|
29
|
+
('last_checked_at', models.DateTimeField(blank=True, null=True)),
|
|
30
|
+
('last_check_ok', models.BooleanField(blank=True, null=True)),
|
|
31
|
+
('last_check_errors', models.JSONField(blank=True, default=dict)),
|
|
32
|
+
],
|
|
33
|
+
options={
|
|
34
|
+
'ordering': ('created_at', 'id'),
|
|
35
|
+
'indexes': [models.Index(fields=['scope_type', 'scope_id'], name='integ_conn_scope_idx')],
|
|
36
|
+
'constraints': [models.UniqueConstraint(fields=('scope_type', 'scope_id', 'provider', 'name'), name='integ_conn_name_uniq')],
|
|
37
|
+
},
|
|
38
|
+
),
|
|
39
|
+
]
|
|
File without changes
|