interloper-api 0.127.0__tar.gz → 0.128.1__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 (38) hide show
  1. {interloper_api-0.127.0 → interloper_api-0.128.1}/PKG-INFO +1 -1
  2. {interloper_api-0.127.0 → interloper_api-0.128.1}/pyproject.toml +1 -1
  3. {interloper_api-0.127.0 → interloper_api-0.128.1}/pyproject.toml.orig +1 -1
  4. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/authorization.py +28 -12
  5. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/cli.py +9 -10
  6. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/admin.py +134 -2
  7. {interloper_api-0.127.0 → interloper_api-0.128.1}/README.md +0 -0
  8. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/__init__.py +0 -0
  9. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/app.py +0 -0
  10. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/dependencies/__init__.py +0 -0
  11. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/dependencies/auth.py +0 -0
  12. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/dependencies/rbac.py +0 -0
  13. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/dependencies/state.py +0 -0
  14. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/login.py +0 -0
  15. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/notifications/__init__.py +0 -0
  16. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/notifications/base.py +0 -0
  17. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/notifications/invitations.py +0 -0
  18. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/notifications/super_admins.py +0 -0
  19. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/__init__.py +0 -0
  20. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/agent.py +0 -0
  21. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/apps.py +0 -0
  22. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/auth.py +0 -0
  23. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/authorization.py +0 -0
  24. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/backfills.py +0 -0
  25. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/catalog.py +0 -0
  26. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/components.py +0 -0
  27. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/executions.py +0 -0
  28. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/health.py +0 -0
  29. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/oauth.py +0 -0
  30. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/organisations.py +0 -0
  31. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/overview.py +0 -0
  32. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/relations.py +0 -0
  33. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/runs.py +0 -0
  34. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/tokens.py +0 -0
  35. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/routes/websocket.py +0 -0
  36. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/server.py +0 -0
  37. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/utils/__init__.py +0 -0
  38. {interloper_api-0.127.0 → interloper_api-0.128.1}/src/interloper_api/utils/time.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: interloper-api
3
- Version: 0.127.0
3
+ Version: 0.128.1
4
4
  Summary: Interloper FastAPI routes
5
5
  Author: Guillaume Onfroy
6
6
  Author-email: Guillaume Onfroy <guillaume@digitlcloud.com>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "interloper-api"
3
- version = "0.127.0"
3
+ version = "0.128.1"
4
4
  description = "Interloper FastAPI routes"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -3,7 +3,7 @@
3
3
  # ###############
4
4
  [project]
5
5
  name = "interloper-api"
6
- version = "0.127.0"
6
+ version = "0.128.1"
7
7
  description = "Interloper FastAPI routes"
8
8
  readme = "README.md"
9
9
  authors = [{ name = "Guillaume Onfroy", email = "guillaume@digitlcloud.com" }]
@@ -331,6 +331,29 @@ class Client(ClientMixin):
331
331
  return hostname in LOOPBACK_HOSTS
332
332
  return parts.scheme in PRIVATE_USE_SCHEMES
333
333
 
334
+ @staticmethod
335
+ def check_redirect_uris(redirect_uris: list[str]) -> None:
336
+ """Refuse a registration whose redirect URIs could not all safely receive codes.
337
+
338
+ Dynamic registration and every operator registration (the CLI, the
339
+ admin portal) apply this one rule.
340
+
341
+ Args:
342
+ redirect_uris: The URIs the client asks to register.
343
+
344
+ Raises:
345
+ InvalidRedirectURIError: When the list is empty or a URI is not
346
+ :meth:`is_safe_redirect_uri`. The description never quotes the
347
+ URI, which may carry characters an OAuth error must not.
348
+ """
349
+ if not redirect_uris:
350
+ raise InvalidRedirectURIError("At least one redirect URI is required.")
351
+ if not all(Client.is_safe_redirect_uri(uri) for uri in redirect_uris):
352
+ raise InvalidRedirectURIError(
353
+ "A redirect URI must use https, http on a loopback host, or the private-use scheme of a known "
354
+ f"client ({', '.join(sorted(PRIVATE_USE_SCHEMES))})."
355
+ )
356
+
334
357
  @staticmethod
335
358
  def without_loopback_port(uri: str) -> str:
336
359
  """Drop the port of a loopback ``http`` URI, which a native app picks per request.
@@ -800,6 +823,9 @@ class Registration(ClientRegistrationEndpoint):
800
823
  def create_registration_response(self, request: RegistrationRequest) -> tuple[int, dict[str, Any], list]:
801
824
  """Register a client from validated metadata.
802
825
 
826
+ Its redirect URIs pass :meth:`Client.check_redirect_uris` first, which
827
+ refuses the registration when none is given or one is unsafe.
828
+
803
829
  Args:
804
830
  request: The registration request.
805
831
 
@@ -807,20 +833,10 @@ class Registration(ClientRegistrationEndpoint):
807
833
  ``(201, body, headers)``; the body carries the client's secret
808
834
  once, for a confidential client only, and its name as stored, cut
809
835
  to :data:`CLIENT_NAME_MAX_LENGTH`.
810
-
811
- Raises:
812
- InvalidRedirectURIError: When no redirect URI is registered, or
813
- one is unsafe.
814
836
  """
815
837
  metadata = self.extract_client_metadata(request)
816
- redirect_uris = metadata.get("redirect_uris")
817
- if not redirect_uris:
818
- raise InvalidRedirectURIError("'redirect_uris' is required.")
819
- if not all(Client.is_safe_redirect_uri(uri) for uri in redirect_uris):
820
- raise InvalidRedirectURIError(
821
- "A redirect URI must use https, http on a loopback host, or the private-use scheme of a known "
822
- f"client ({', '.join(sorted(PRIVATE_USE_SCHEMES))})."
823
- )
838
+ redirect_uris = metadata.get("redirect_uris") or []
839
+ Client.check_redirect_uris(redirect_uris)
824
840
  auth_method = metadata.get("token_endpoint_auth_method", "client_secret_basic")
825
841
  client, secret = self.server.store.oauth.register_client(
826
842
  (metadata.get("client_name") or "Unnamed application")[:CLIENT_NAME_MAX_LENGTH],
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import argparse
6
6
  import logging
7
7
 
8
+ from authlib.oauth2.rfc7591 import InvalidRedirectURIError
8
9
  from interloper.catalog import Catalog
9
10
  from interloper.cli.console import configure_console_logging
10
11
  from interloper.settings import AppSettings
@@ -76,7 +77,8 @@ def register_oauth(subparsers: argparse._SubParsersAction) -> None:
76
77
  "oauth",
77
78
  help="Manage operator-registered OAuth clients",
78
79
  description="Manage the OAuth clients an operator registers for apps that cannot register themselves "
79
- "(a Slack app, a shared connector). Clients that register dynamically are not listed or deleted here.",
80
+ "(a Slack app, a shared connector), as the admin portal's OAuth clients page does. Clients that register "
81
+ "dynamically are not listed or deleted here.",
80
82
  )
81
83
  commands = parser.add_subparsers(dest="oauth_command")
82
84
 
@@ -116,11 +118,10 @@ def _cmd_oauth_create(args: argparse.Namespace) -> None:
116
118
  Raises:
117
119
  SystemExit: When a redirect URI is one dynamic registration would refuse.
118
120
  """
119
- for uri in args.redirect_uri:
120
- if not Client.is_safe_redirect_uri(uri):
121
- raise SystemExit(
122
- f"Refusing redirect URI {uri!r}: it must use https, http on a loopback host, or a private-use scheme."
123
- )
121
+ try:
122
+ Client.check_redirect_uris(args.redirect_uri)
123
+ except InvalidRedirectURIError as error:
124
+ raise SystemExit(error.description) from error
124
125
  client, secret = Store.from_settings(catalog=Catalog()).oauth.register_client(
125
126
  args.name, args.redirect_uri, registered_by="operator", confidential=True
126
127
  )
@@ -149,9 +150,7 @@ def _cmd_oauth_delete(args: argparse.Namespace) -> None:
149
150
  Raises:
150
151
  SystemExit: When no operator client has that id.
151
152
  """
152
- oauth = Store.from_settings(catalog=Catalog()).oauth
153
- client = oauth.get_client(args.client_id)
154
- if client is None or client.registered_by != "operator":
153
+ client = Store.from_settings(catalog=Catalog()).oauth.delete_client(args.client_id, registered_by="operator")
154
+ if client is None:
155
155
  raise SystemExit(f"No operator client {args.client_id}.")
156
- oauth.delete_client(client.client_id)
157
156
  print(f"Deleted {client.name} ({client.client_id}) and revoked its tokens.")
@@ -2,7 +2,8 @@
2
2
 
3
3
  These endpoints are gated by :func:`require_super_admin` and are NOT bound to
4
4
  the session's active organisation: every organisation (soft-deleted ones
5
- included), every user, quotas and the instance configuration. Managing one
5
+ included), every user, quotas, the operator OAuth clients and the instance
6
+ configuration. Managing one
6
7
  organisation's members and invitations goes through the organisation routes,
7
8
  which admit super-admins (:mod:`interloper_api.routes.organisations`). They
8
9
  deliberately grant no access to org-scoped *data* (sources, jobs, runs, …).
@@ -17,14 +18,18 @@ from importlib import metadata
17
18
  from typing import Annotated, Any
18
19
  from uuid import UUID
19
20
 
21
+ from authlib.oauth2.rfc7591 import InvalidRedirectURIError
20
22
  from fastapi import APIRouter, HTTPException, Query, Request, Response
21
23
  from interloper_db import Organisation, OrganisationQuery, Page, PageQuery, Profile, ProfileQuery, UsageQuery
24
+ from interloper_db.models import OAuthClient
22
25
  from interloper_db.store.insights import ActivityEntry
23
26
  from interloper_db.store.quotas import METRIC_SUCCESSFUL_RUNS, QUOTAS
24
- from pydantic import BaseModel, RootModel, field_validator
27
+ from pydantic import BaseModel, Field, RootModel, field_validator
25
28
 
29
+ from interloper_api.authorization import CLIENT_NAME_MAX_LENGTH, Client
26
30
  from interloper_api.dependencies import SettingsDep, StateDep, StoreDep, SuperAdminDep
27
31
  from interloper_api.notifications import SuperAdminPromotionEmail
32
+ from interloper_api.routes.apps import AppResponse
28
33
  from interloper_api.routes.organisations import CreateOrganisationRequest
29
34
 
30
35
  router = APIRouter(prefix="/admin", tags=["admin"])
@@ -113,6 +118,57 @@ class AdminUserUpdateRequest(BaseModel):
113
118
  is_super_admin: bool
114
119
 
115
120
 
121
+ class AdminOAuthClientCreateRequest(BaseModel):
122
+ """An operator client to register: its name and the URIs its codes may be sent to."""
123
+
124
+ name: str = Field(min_length=1, max_length=CLIENT_NAME_MAX_LENGTH)
125
+ redirect_uris: list[str]
126
+
127
+ @field_validator("name")
128
+ @classmethod
129
+ def _strip_name(cls, name: str) -> str:
130
+ """Refuse a name of whitespace only, which the consent page would show blank.
131
+
132
+ Args:
133
+ name: The name as sent.
134
+
135
+ Returns:
136
+ The name without surrounding whitespace.
137
+
138
+ Raises:
139
+ ValueError: When nothing is left once stripped.
140
+ """
141
+ stripped = name.strip()
142
+ if not stripped:
143
+ raise ValueError("A client needs a name")
144
+ return stripped
145
+
146
+
147
+ class AdminOAuthClientCreatedResponse(AppResponse):
148
+ """A client just registered, carrying its secret: the only response that ever does."""
149
+
150
+ client_secret: str
151
+
152
+ @classmethod
153
+ def from_registration(cls, client: OAuthClient, secret: str | None) -> AdminOAuthClientCreatedResponse:
154
+ """Describe a client just registered, with the secret the store returned once.
155
+
156
+ Args:
157
+ client: The stored client.
158
+ secret: The raw secret; an operator client is confidential, so it
159
+ always has one.
160
+
161
+ Returns:
162
+ The response model.
163
+
164
+ Raises:
165
+ ValueError: When the client came back without a secret.
166
+ """
167
+ if secret is None:
168
+ raise ValueError(f"Client {client.client_id} was registered without a secret")
169
+ return cls(**AppResponse.from_client(client).model_dump(), client_secret=secret)
170
+
171
+
116
172
  class AdminLauncherConfig(BaseModel):
117
173
  """Launcher type plus the key-allowlisted, non-secret part of its config.
118
174
 
@@ -878,3 +934,79 @@ def delete_user(
878
934
  raise HTTPException(status_code=400, detail="You cannot delete your own account")
879
935
  store.profiles.delete(user_id)
880
936
  return Response(status_code=204)
937
+
938
+
939
+ # -- OAuth clients -------------------------------------------------------------
940
+
941
+
942
+ @router.get("/oauth-clients")
943
+ def list_oauth_clients(user: SuperAdminDep, store: StoreDep) -> list[AppResponse]:
944
+ """List the operator-registered OAuth clients, the ones ``interloper oauth list`` shows.
945
+
946
+ Clients that registered themselves are left out: anyone may register one,
947
+ and each belongs to the users who approve it, who revoke it from their own
948
+ settings.
949
+
950
+ Args:
951
+ user: The calling super-admin, resolved from the session.
952
+ store: The database store backing the request.
953
+
954
+ Returns:
955
+ The operator clients by name, without secret material.
956
+ """
957
+ return [AppResponse.from_client(client) for client in store.oauth.list_clients(registered_by="operator")]
958
+
959
+
960
+ @router.post("/oauth-clients", status_code=201)
961
+ def create_oauth_client(
962
+ body: AdminOAuthClientCreateRequest,
963
+ user: SuperAdminDep,
964
+ store: StoreDep,
965
+ ) -> AdminOAuthClientCreatedResponse:
966
+ """Register a confidential operator client, as ``interloper oauth create`` does.
967
+
968
+ Args:
969
+ body: The client's name and redirect URIs.
970
+ user: The calling super-admin, resolved from the session.
971
+ store: The database store backing the request.
972
+
973
+ Returns:
974
+ The client with its secret, which only its hash is stored of: this
975
+ response is the one chance to read it.
976
+
977
+ Raises:
978
+ HTTPException: 422 when no redirect URI is given or one could not
979
+ safely receive codes.
980
+ """
981
+ try:
982
+ Client.check_redirect_uris(body.redirect_uris)
983
+ except InvalidRedirectURIError as error:
984
+ raise HTTPException(status_code=422, detail=error.description) from error
985
+ client, secret = store.oauth.register_client(
986
+ body.name, body.redirect_uris, registered_by="operator", confidential=True
987
+ )
988
+ return AdminOAuthClientCreatedResponse.from_registration(client, secret)
989
+
990
+
991
+ @router.delete("/oauth-clients/{client_id}", status_code=204)
992
+ def delete_oauth_client(client_id: str, user: SuperAdminDep, store: StoreDep) -> Response:
993
+ """Delete an operator client and every grant it holds, as ``interloper oauth delete`` does.
994
+
995
+ Its codes and refresh tokens are removed and its access tokens revoked for
996
+ every user, and the conversations it started are deleted.
997
+
998
+ Args:
999
+ client_id: The client to delete.
1000
+ user: The calling super-admin, resolved from the session.
1001
+ store: The database store backing the request.
1002
+
1003
+ Returns:
1004
+ An empty 204 response.
1005
+
1006
+ Raises:
1007
+ HTTPException: 404 when no operator client has that id; a client that
1008
+ registered itself is never deleted here.
1009
+ """
1010
+ if store.oauth.delete_client(client_id, registered_by="operator") is None:
1011
+ raise HTTPException(status_code=404, detail=f"No operator client {client_id}")
1012
+ return Response(status_code=204)