igni-client 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.
@@ -0,0 +1,131 @@
1
+ """igni-client: drive an igni from your own code.
2
+
3
+ Connect headlessly to a person's, an app's or a space's igni — in Fleet,
4
+ through its gateway, or on this machine — and run work there:
5
+
6
+ from igni_client import Fleet, IgniClient, Person
7
+
8
+ async with IgniClient(Fleet("https://gw.acme.internal", auth=Person.from_cli())) as igni:
9
+ session = await igni.sessions.create()
10
+ reply = await session.ask("Summarise the open pull requests", approve=False)
11
+ print(reply)
12
+
13
+ `Session.send()` follows a run event by event, approvals included;
14
+ `igni.commands.run()` runs a shell command in the VM; `igni.rpc()` reaches
15
+ any of igni's methods.
16
+ """
17
+
18
+ from igni_client.auth import ApiKey, App, Person, Space, SpaceRecord, Spaces, TokenSource
19
+ from igni_client.client import IgniClient
20
+ from igni_client.commands import CommandFinished, CommandOutput, CommandRun, Commands, Me
21
+ from igni_client.errors import (
22
+ ApprovalRequired,
23
+ AuthError,
24
+ IgniClientError,
25
+ NotAllowed,
26
+ NotSupported,
27
+ RpcError,
28
+ RunFailed,
29
+ RunInterrupted,
30
+ Unavailable,
31
+ )
32
+ from igni_client.events import (
33
+ CommandResult,
34
+ ContentDelta,
35
+ ErrorMessage,
36
+ Event,
37
+ InfoMessage,
38
+ ModelCompleted,
39
+ PushNotification,
40
+ ReasoningStarted,
41
+ Requirement,
42
+ RequirementDetails,
43
+ RequirementResolved,
44
+ RunCompleted,
45
+ RunError,
46
+ RunEvent,
47
+ RunPaused,
48
+ RunStarted,
49
+ SessionListEntry,
50
+ StatusUpdate,
51
+ StreamingDone,
52
+ TaskCreated,
53
+ TaskStateUpdated,
54
+ TaskUpdated,
55
+ ToolCompleted,
56
+ ToolError,
57
+ ToolStarted,
58
+ Unknown,
59
+ UserMessageReceived,
60
+ )
61
+ from igni_client.runs import ApprovalRequested, Decision, Reply
62
+ from igni_client.sessions import ModelCatalogue, Models, Session, Sessions
63
+ from igni_client.targets import Fleet, Local, Target
64
+
65
+ __all__ = [
66
+ # Connecting
67
+ "IgniClient",
68
+ "Fleet",
69
+ "Local",
70
+ "Target",
71
+ # Who
72
+ "Person",
73
+ "ApiKey",
74
+ "App",
75
+ "Space",
76
+ "Spaces",
77
+ "SpaceRecord",
78
+ "TokenSource",
79
+ # Sessions and runs
80
+ "Session",
81
+ "Sessions",
82
+ "Models",
83
+ "ModelCatalogue",
84
+ "ApprovalRequested",
85
+ "Decision",
86
+ "Reply",
87
+ # Commands
88
+ "Commands",
89
+ "CommandRun",
90
+ "CommandOutput",
91
+ "CommandFinished",
92
+ "Me",
93
+ # Events
94
+ "Event",
95
+ "RunEvent",
96
+ "ContentDelta",
97
+ "RunStarted",
98
+ "ReasoningStarted",
99
+ "ToolStarted",
100
+ "ToolCompleted",
101
+ "ToolError",
102
+ "ModelCompleted",
103
+ "StreamingDone",
104
+ "RunCompleted",
105
+ "RunError",
106
+ "RunPaused",
107
+ "Requirement",
108
+ "RequirementDetails",
109
+ "RequirementResolved",
110
+ "TaskCreated",
111
+ "TaskUpdated",
112
+ "TaskStateUpdated",
113
+ "SessionListEntry",
114
+ "StatusUpdate",
115
+ "CommandResult",
116
+ "InfoMessage",
117
+ "ErrorMessage",
118
+ "UserMessageReceived",
119
+ "PushNotification",
120
+ "Unknown",
121
+ # Errors
122
+ "IgniClientError",
123
+ "Unavailable",
124
+ "AuthError",
125
+ "NotAllowed",
126
+ "NotSupported",
127
+ "RpcError",
128
+ "RunFailed",
129
+ "RunInterrupted",
130
+ "ApprovalRequired",
131
+ ]
igni_client/auth.py ADDED
@@ -0,0 +1,539 @@
1
+ """Who the client connects as: a person, an app, or one of an app's spaces.
2
+
3
+ Each is a token source — `await auth.token()` — that a target asks for a
4
+ bearer token every time it opens a connection. Fleet's gateway checks the
5
+ token only when the socket opens, so a short-lived token is fetched again
6
+ for each connection, never refreshed under one that is open.
7
+
8
+ * **A person** brings a session pinned to their organisation: the one
9
+ `igni login` keeps, or one handed over explicitly. It lasts 30 days.
10
+ There is no headless sign-in for a person.
11
+ * **An app** signs in as itself — `client_credentials` with a
12
+ `private_key_jwt` assertion signed with its own key, whose public half
13
+ an org admin registered on igni server. Its tokens last ten minutes and
14
+ are renewed a minute before they run out.
15
+ * **A space** is one end user of an app. The app declares it, then
16
+ exchanges its own token for the space's.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ import base64
23
+ import hashlib
24
+ import json
25
+ import os
26
+ import time
27
+ import uuid
28
+ from collections.abc import Callable
29
+ from datetime import UTC, datetime
30
+ from pathlib import Path
31
+ from typing import Any, Protocol
32
+ from urllib.parse import quote
33
+
34
+ import httpx
35
+ import jwt
36
+ from cryptography.hazmat.primitives import serialization
37
+ from cryptography.hazmat.primitives.asymmetric import rsa
38
+ from pydantic import BaseModel, ConfigDict, ValidationError
39
+
40
+ from igni_client.errors import AuthError, NotAllowed, Unavailable
41
+
42
+ ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
43
+ TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange" # noqa: S105 — an RFC 8693 grant type, not a token
44
+ ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" # noqa: S105 — an RFC 8693 URN, not a token
45
+
46
+ #: The only signing algorithm on this wire.
47
+ ALGORITHM = "RS256"
48
+
49
+
50
+ class TokenSource(Protocol):
51
+ """Anything a target can ask for a bearer token."""
52
+
53
+ async def token(self) -> str: ...
54
+
55
+
56
+ # ── A person ─────────────────────────────────────────────────────────
57
+
58
+
59
+ class Person:
60
+ """A person, by their igni session.
61
+
62
+ The token must be pinned to an organisation — the session `igni login`
63
+ stores is. A plain sign-in session without one is refused by Fleet.
64
+ """
65
+
66
+ def __init__(self, token: str) -> None:
67
+ token = token.strip()
68
+ if not token:
69
+ raise AuthError("a person needs a session token")
70
+ self._token = token
71
+
72
+ @classmethod
73
+ def from_api_key(
74
+ cls,
75
+ key: str | None = None,
76
+ *,
77
+ server: str | None = None,
78
+ http: httpx.AsyncClient | None = None,
79
+ ) -> ApiKey:
80
+ """A person by their API key — the way to give a program their access.
81
+
82
+ Make the key on the portal (*API keys*). `key` defaults to
83
+ `IGNI_API_KEY` and `server` — igni server's address — to
84
+ `IGNI_SERVER_URL`. Each connection gets a fresh 15-minute session as
85
+ the person; see `ApiKey`.
86
+ """
87
+ key = key or os.environ.get("IGNI_API_KEY", "")
88
+ server = server or os.environ.get("IGNI_SERVER_URL", "")
89
+ if not key:
90
+ raise AuthError("no API key: pass one, or set IGNI_API_KEY")
91
+ if not server:
92
+ raise AuthError("where is igni server? pass server=, or set IGNI_SERVER_URL")
93
+ return ApiKey(key, server=server, http=http)
94
+
95
+ @classmethod
96
+ def from_cli(cls, path: str | Path | None = None) -> Person:
97
+ """The session `igni login` stored: `~/.igni/credentials.json`, or the file at `path`.
98
+
99
+ Raises `AuthError` when there is none or it has expired — run
100
+ `igni login` again. For a program, prefer an API key
101
+ (`from_api_key`): it needs no browser.
102
+ """
103
+ candidates = [
104
+ Path(path).expanduser()
105
+ if path is not None
106
+ else Path("~/.igni/credentials.json").expanduser()
107
+ ]
108
+ for candidate in candidates:
109
+ if not candidate.is_file():
110
+ continue
111
+ try:
112
+ stored = _StoredCredentials.model_validate_json(candidate.read_text())
113
+ except (OSError, ValidationError) as exc:
114
+ raise AuthError(f"{candidate} is not an igni credentials file") from exc
115
+ if stored.expired():
116
+ raise AuthError(f"the session in {candidate} has expired; run `igni login`")
117
+ return cls(stored.access_token)
118
+ raise AuthError("no igni session on this machine; run `igni login`")
119
+
120
+ async def token(self) -> str:
121
+ return self._token
122
+
123
+
124
+ class ApiKey:
125
+ """A person's API key, exchanged for short sessions as them.
126
+
127
+ The key comes from the portal (*API keys*). igni server exchanges it for
128
+ a 15-minute session as the person, pinned to the key's organisation —
129
+ every igni server route and Fleet's gateway take it. The session is
130
+ renewed a minute before it runs out. It can do what the person can,
131
+ except make more credentials. A revoked or expired key raises
132
+ `AuthError`.
133
+ """
134
+
135
+ API_KEY_GRANT = "urn:igni:params:oauth:grant-type:api-key"
136
+ RENEW_BEFORE = 60
137
+
138
+ def __init__(
139
+ self,
140
+ key: str,
141
+ *,
142
+ server: str,
143
+ http: httpx.AsyncClient | None = None,
144
+ clock: Callable[[], float] = time.time,
145
+ ) -> None:
146
+ if not key.strip().startswith("igpak1."):
147
+ raise AuthError("not an igni API key (they start with 'igpak1.')")
148
+ self._key = key.strip()
149
+ self.server = server.rstrip("/")
150
+ self._http = http or httpx.AsyncClient(timeout=10.0)
151
+ self._owns_http = http is None
152
+ self._clock = clock
153
+ self._token: str | None = None
154
+ self._expires_at = 0.0
155
+ self._lock = asyncio.Lock()
156
+
157
+ async def token(self) -> str:
158
+ async with self._lock:
159
+ if self._token is not None and self._clock() < self._expires_at:
160
+ return self._token
161
+ try:
162
+ response = await self._http.post(
163
+ f"{self.server}/v1/oauth/token",
164
+ data={"grant_type": self.API_KEY_GRANT, "api_key": self._key},
165
+ )
166
+ except httpx.HTTPError as exc:
167
+ raise Unavailable(
168
+ f"could not reach igni server for the key's session: {exc}"
169
+ ) from exc
170
+ if response.status_code in (400, 401, 403):
171
+ try:
172
+ reason = str(response.json().get("error_description") or response.text)
173
+ except ValueError:
174
+ reason = response.text
175
+ raise AuthError(f"igni server refused the API key: {reason}")
176
+ if response.status_code != 200:
177
+ raise Unavailable(
178
+ f"igni server answered the key's exchange with {response.status_code}"
179
+ )
180
+ try:
181
+ issued = _IssuedToken.model_validate(response.json())
182
+ except (ValidationError, ValueError) as exc:
183
+ raise Unavailable(
184
+ "igni server answered the key's exchange with something else"
185
+ ) from exc
186
+ self._token = issued.access_token
187
+ self._expires_at = self._clock() + max(0, issued.expires_in - self.RENEW_BEFORE)
188
+ return self._token
189
+
190
+ async def aclose(self) -> None:
191
+ if self._owns_http:
192
+ await self._http.aclose()
193
+
194
+ def __repr__(self) -> str:
195
+ return f"ApiKey(server={self.server!r})" # never the key
196
+
197
+
198
+ class _StoredCredentials(BaseModel):
199
+ """`~/.igni/credentials.json`, as igni's CLI writes it."""
200
+
201
+ model_config = ConfigDict(extra="ignore")
202
+
203
+ access_token: str
204
+ expires_at: str = ""
205
+
206
+ def expired(self) -> bool:
207
+ if not self.expires_at:
208
+ return False
209
+ try:
210
+ expires = datetime.fromisoformat(self.expires_at)
211
+ except ValueError:
212
+ return False
213
+ if expires.tzinfo is None:
214
+ expires = expires.replace(tzinfo=UTC)
215
+ return datetime.now(UTC) >= expires
216
+
217
+
218
+ # ── An app ───────────────────────────────────────────────────────────
219
+
220
+
221
+ class _IssuedToken(BaseModel):
222
+ model_config = ConfigDict(extra="ignore")
223
+
224
+ access_token: str
225
+ expires_in: int = 600
226
+
227
+
228
+ class SpaceRecord(BaseModel):
229
+ """One space of an app, as igni server keeps it."""
230
+
231
+ model_config = ConfigDict(extra="allow")
232
+
233
+ space_id: str
234
+ app_id: str = ""
235
+ org_id: str = ""
236
+ external_id: str = ""
237
+ created_at: str = ""
238
+
239
+
240
+ def _b64url_uint(value: int) -> str:
241
+ raw = value.to_bytes((value.bit_length() + 7) // 8 or 1, "big")
242
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
243
+
244
+
245
+ class App:
246
+ """An app of an organisation, signing in as itself.
247
+
248
+ `server` is igni server's address (not the gateway's). The key is the
249
+ app's RSA private key; its public half — `public_jwks()` — is what an
250
+ org admin registers for the app on igni server. Until they have, a
251
+ token request is refused with `AuthError`.
252
+ """
253
+
254
+ #: Renew a token this many seconds before it runs out.
255
+ RENEW_BEFORE = 60
256
+ #: How long a client assertion lives; one is made per token request.
257
+ ASSERTION_LIFETIME = 60
258
+
259
+ def __init__(
260
+ self,
261
+ app_id: str,
262
+ *,
263
+ server: str,
264
+ key_file: str | Path | None = None,
265
+ key_pem: str | None = None,
266
+ http: httpx.AsyncClient | None = None,
267
+ clock: Callable[[], float] = time.time,
268
+ ) -> None:
269
+ if not app_id:
270
+ raise ValueError("an app needs its app id")
271
+ if (key_file is None) == (key_pem is None):
272
+ raise ValueError("give the app's key as exactly one of key_file= or key_pem=")
273
+ pem = Path(key_file).expanduser().read_text() if key_file is not None else key_pem
274
+ assert pem is not None
275
+ loaded = serialization.load_pem_private_key(pem.encode(), password=None)
276
+ if not isinstance(loaded, rsa.RSAPrivateKey):
277
+ raise ValueError("an app's key must be an RSA private key")
278
+ self.app_id = app_id
279
+ self.server = server.rstrip("/")
280
+ self._key = loaded
281
+ self._http = http or httpx.AsyncClient(timeout=10.0)
282
+ self._owns_http = http is None
283
+ self._clock = clock
284
+ self._issuer: str | None = None
285
+ self._token: str | None = None
286
+ self._expires_at = 0.0
287
+ self._lock = asyncio.Lock()
288
+
289
+ @staticmethod
290
+ def generate_key(path: str | Path) -> Path:
291
+ """Make a new RSA key for an app and write it to `path`, readable by its owner only."""
292
+ target = Path(path).expanduser()
293
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
294
+ pem = key.private_bytes(
295
+ encoding=serialization.Encoding.PEM,
296
+ format=serialization.PrivateFormat.PKCS8,
297
+ encryption_algorithm=serialization.NoEncryption(),
298
+ )
299
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
300
+ with os.fdopen(fd, "wb") as handle:
301
+ handle.write(pem)
302
+ return target
303
+
304
+ def thumbprint(self) -> str:
305
+ """The key's RFC 7638 thumbprint: its `kid`, and what an admin compares."""
306
+ numbers = self._key.public_key().public_numbers()
307
+ members = {"e": _b64url_uint(numbers.e), "kty": "RSA", "n": _b64url_uint(numbers.n)}
308
+ canonical = json.dumps(members, separators=(",", ":"), sort_keys=True).encode()
309
+ return base64.urlsafe_b64encode(hashlib.sha256(canonical).digest()).rstrip(b"=").decode()
310
+
311
+ def public_jwks(self) -> dict[str, Any]:
312
+ """The public key as a JWK set: what an org admin registers for this app."""
313
+ numbers = self._key.public_key().public_numbers()
314
+ return {
315
+ "keys": [
316
+ {
317
+ "kty": "RSA",
318
+ "use": "sig",
319
+ "alg": ALGORITHM,
320
+ "kid": self.thumbprint(),
321
+ "n": _b64url_uint(numbers.n),
322
+ "e": _b64url_uint(numbers.e),
323
+ }
324
+ ]
325
+ }
326
+
327
+ async def token(self) -> str:
328
+ """The app's own token (`token_use=app`), renewed shortly before it runs out."""
329
+ async with self._lock:
330
+ if self._token is not None and self._clock() < self._expires_at:
331
+ return self._token
332
+ issued = await self._grant(
333
+ {
334
+ "grant_type": "client_credentials",
335
+ "client_assertion_type": ASSERTION_TYPE,
336
+ "client_assertion": await self._assertion(),
337
+ },
338
+ what="the app's token",
339
+ )
340
+ self._token = issued.access_token
341
+ self._expires_at = self._clock() + max(0, issued.expires_in - self.RENEW_BEFORE)
342
+ return self._token
343
+
344
+ @property
345
+ def spaces(self) -> Spaces:
346
+ """This app's spaces: its end users, each a producer with an igni of its own."""
347
+ return Spaces(self)
348
+
349
+ async def aclose(self) -> None:
350
+ if self._owns_http:
351
+ await self._http.aclose()
352
+
353
+ async def __aenter__(self) -> App:
354
+ return self
355
+
356
+ async def __aexit__(self, *exc: object) -> None:
357
+ await self.aclose()
358
+
359
+ # ── igni server ──
360
+
361
+ async def _assertion(self) -> str:
362
+ now = int(self._clock())
363
+ return jwt.encode(
364
+ {
365
+ "iss": self.app_id,
366
+ "sub": self.app_id,
367
+ "aud": await self._issuer_url(),
368
+ "iat": now,
369
+ "exp": now + self.ASSERTION_LIFETIME,
370
+ "jti": uuid.uuid4().hex,
371
+ },
372
+ self._key,
373
+ algorithm=ALGORITHM,
374
+ headers={"kid": self.thumbprint()},
375
+ )
376
+
377
+ async def _issuer_url(self) -> str:
378
+ if self._issuer is None:
379
+ response = await self._call(
380
+ "GET", "/.well-known/openid-configuration", what="discovery"
381
+ )
382
+ issuer = response.json().get("issuer") if response.status_code == 200 else None
383
+ if not isinstance(issuer, str) or not issuer:
384
+ raise Unavailable("igni server published no issuer")
385
+ self._issuer = issuer
386
+ return self._issuer
387
+
388
+ async def _grant(self, form: dict[str, str], *, what: str) -> _IssuedToken:
389
+ response = await self._call("POST", "/v1/oauth/token", what=what, data=form)
390
+ if response.status_code in (400, 401, 403):
391
+ raise AuthError(f"igni server refused {what}: {response.text}")
392
+ if response.status_code != 200:
393
+ raise Unavailable(f"igni server answered {what} with {response.status_code}")
394
+ try:
395
+ return _IssuedToken.model_validate(response.json())
396
+ except (ValidationError, ValueError) as exc:
397
+ raise Unavailable(f"igni server answered {what} with something else") from exc
398
+
399
+ async def _call(self, method: str, path: str, *, what: str, **kwargs: Any) -> httpx.Response:
400
+ try:
401
+ return await self._http.request(method, f"{self.server}{path}", **kwargs)
402
+ except httpx.HTTPError as exc:
403
+ raise Unavailable(f"could not reach igni server for {what}: {exc}") from exc
404
+
405
+ async def _authorized(
406
+ self, method: str, path: str, *, what: str, **kwargs: Any
407
+ ) -> httpx.Response:
408
+ """A call to igni server as this app, retried once with a fresh token on a 401."""
409
+ for attempt in range(2):
410
+ headers = {"Authorization": f"Bearer {await self.token()}"}
411
+ response = await self._call(method, path, what=what, headers=headers, **kwargs)
412
+ if response.status_code != 401 or attempt:
413
+ return response
414
+ async with self._lock:
415
+ self._token = None
416
+ return response
417
+
418
+
419
+ # ── An app's spaces ──────────────────────────────────────────────────
420
+
421
+
422
+ class Spaces:
423
+ """The spaces of one app: declare, look up, list and delete them, and act as one."""
424
+
425
+ def __init__(self, app: App) -> None:
426
+ self._app = app
427
+
428
+ def _path(self, external_id: str = "") -> str:
429
+ base = f"/v1/apps/{quote(self._app.app_id, safe='')}/spaces"
430
+ return f"{base}/{quote(external_id, safe='')}" if external_id else base
431
+
432
+ async def declare(self, external_id: str) -> Space:
433
+ """The space for `external_id` (your own id for the user), made if it is new.
434
+
435
+ Idempotent: declaring the same id again returns the same space.
436
+ igni provisions its VM in the background.
437
+ """
438
+ if not external_id or "/" in external_id or len(external_id) > 200:
439
+ raise ValueError("a space's external id is 1 to 200 characters, without '/'")
440
+ response = await self._app._authorized(
441
+ "PUT", self._path(external_id), what="declaring a space"
442
+ )
443
+ return self._space(self._record(response, what="declaring a space"))
444
+
445
+ async def get(self, external_id: str) -> Space | None:
446
+ """The space for `external_id`, or `None` when the app has none."""
447
+ response = await self._app._authorized(
448
+ "GET", self._path(external_id), what="reading a space"
449
+ )
450
+ if response.status_code == 404:
451
+ return None
452
+ return self._space(self._record(response, what="reading a space"))
453
+
454
+ async def list(self, *, limit: int = 100) -> list[SpaceRecord]:
455
+ """Every space of this app."""
456
+ found: list[SpaceRecord] = []
457
+ after: str | None = None
458
+ while True:
459
+ params: dict[str, str | int] = {"limit": limit}
460
+ if after:
461
+ params["after"] = after
462
+ response = await self._app._authorized(
463
+ "GET", self._path(), what="listing spaces", params=params
464
+ )
465
+ body = self._body(response, what="listing spaces")
466
+ found.extend(SpaceRecord.model_validate(s) for s in body.get("spaces") or [])
467
+ after = body.get("next")
468
+ if not after:
469
+ return found
470
+
471
+ async def delete(self, external_id: str) -> None:
472
+ """Delete a space: its credential stops working and its VM is erased."""
473
+ response = await self._app._authorized(
474
+ "DELETE", self._path(external_id), what="deleting a space"
475
+ )
476
+ if response.status_code not in (204, 404):
477
+ self._body(response, what="deleting a space")
478
+
479
+ def space(self, space_id: str) -> Space:
480
+ """Act as a space you already know the id of."""
481
+ return Space(self._app, space_id)
482
+
483
+ def _space(self, record: SpaceRecord) -> Space:
484
+ return Space(self._app, record.space_id, record=record)
485
+
486
+ def _record(self, response: httpx.Response, *, what: str) -> SpaceRecord:
487
+ return SpaceRecord.model_validate(self._body(response, what=what))
488
+
489
+ @staticmethod
490
+ def _body(response: httpx.Response, *, what: str) -> dict[str, Any]:
491
+ if response.status_code == 403:
492
+ raise NotAllowed(f"igni server refused {what}: {response.text}")
493
+ if response.status_code in (400, 409):
494
+ raise NotAllowed(f"igni server refused {what}: {response.text}")
495
+ if response.status_code >= 300:
496
+ raise Unavailable(f"igni server answered {what} with {response.status_code}")
497
+ try:
498
+ body = response.json()
499
+ except ValueError as exc:
500
+ raise Unavailable(f"igni server answered {what} with something else") from exc
501
+ if not isinstance(body, dict):
502
+ raise Unavailable(f"igni server answered {what} with something else")
503
+ return body
504
+
505
+
506
+ class Space:
507
+ """One space of an app, as a token source: the app's token exchanged for the space's."""
508
+
509
+ def __init__(self, app: App, space_id: str, *, record: SpaceRecord | None = None) -> None:
510
+ if not space_id:
511
+ raise ValueError("a space needs its space id")
512
+ self.app = app
513
+ self.space_id = space_id
514
+ self.record = record
515
+ self._token: str | None = None
516
+ self._expires_at = 0.0
517
+ self._lock = asyncio.Lock()
518
+
519
+ @property
520
+ def external_id(self) -> str:
521
+ return self.record.external_id if self.record else ""
522
+
523
+ async def token(self) -> str:
524
+ """The space's token (`token_use=space`), renewed shortly before it runs out."""
525
+ async with self._lock:
526
+ if self._token is not None and self.app._clock() < self._expires_at:
527
+ return self._token
528
+ issued = await self.app._grant(
529
+ {
530
+ "grant_type": TOKEN_EXCHANGE,
531
+ "subject_token": await self.app.token(),
532
+ "subject_token_type": ACCESS_TOKEN_TYPE,
533
+ "space": self.space_id,
534
+ },
535
+ what="the space's token",
536
+ )
537
+ self._token = issued.access_token
538
+ self._expires_at = self.app._clock() + max(0, issued.expires_in - App.RENEW_BEFORE)
539
+ return self._token