9in 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.
- 9in-0.1.0/.gitignore +16 -0
- 9in-0.1.0/CHANGELOG.md +37 -0
- 9in-0.1.0/LICENSE +21 -0
- 9in-0.1.0/PKG-INFO +432 -0
- 9in-0.1.0/README.md +396 -0
- 9in-0.1.0/docs/img/logo.png +0 -0
- 9in-0.1.0/examples/fastapi_api.py +38 -0
- 9in-0.1.0/examples/flask_app.py +106 -0
- 9in-0.1.0/pyproject.toml +103 -0
- 9in-0.1.0/src/nine/__init__.py +98 -0
- 9in-0.1.0/src/nine/_framework.py +69 -0
- 9in-0.1.0/src/nine/_jwt.py +314 -0
- 9in-0.1.0/src/nine/_util.py +238 -0
- 9in-0.1.0/src/nine/_version.py +1 -0
- 9in-0.1.0/src/nine/adapter.py +260 -0
- 9in-0.1.0/src/nine/cache.py +110 -0
- 9in-0.1.0/src/nine/env.py +64 -0
- 9in-0.1.0/src/nine/errors.py +83 -0
- 9in-0.1.0/src/nine/fastapi.py +94 -0
- 9in-0.1.0/src/nine/flask.py +263 -0
- 9in-0.1.0/src/nine/http.py +137 -0
- 9in-0.1.0/src/nine/management.py +271 -0
- 9in-0.1.0/src/nine/py.typed +0 -0
- 9in-0.1.0/src/nine/signature.py +156 -0
- 9in-0.1.0/src/nine/tokens.py +591 -0
- 9in-0.1.0/src/nine/webapp.py +481 -0
- 9in-0.1.0/src/nine/webhooks.py +112 -0
- 9in-0.1.0/tests/conftest.py +32 -0
- 9in-0.1.0/tests/live_support.py +195 -0
- 9in-0.1.0/tests/support.py +376 -0
- 9in-0.1.0/tests/test_adapter_webhooks.py +379 -0
- 9in-0.1.0/tests/test_basics.py +208 -0
- 9in-0.1.0/tests/test_fastapi.py +128 -0
- 9in-0.1.0/tests/test_flask.py +203 -0
- 9in-0.1.0/tests/test_http.py +119 -0
- 9in-0.1.0/tests/test_hybrid.py +365 -0
- 9in-0.1.0/tests/test_live.py +548 -0
- 9in-0.1.0/tests/test_management.py +271 -0
- 9in-0.1.0/tests/test_signature.py +118 -0
- 9in-0.1.0/tests/test_tokens.py +527 -0
- 9in-0.1.0/tests/test_webapp.py +480 -0
9in-0.1.0/.gitignore
ADDED
9in-0.1.0/CHANGELOG.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
First release of the official Python SDK for 9in (`pip install 9in`, `import nine`). Python 3.10+,
|
|
6
|
+
one dependency (`cryptography`).
|
|
7
|
+
|
|
8
|
+
- `WebAppAuth`: sign-in for server-rendered apps. Authorization code flow with PKCE (S256),
|
|
9
|
+
endpoints from OIDC discovery, single-use `state` compared in constant time, `nonce`, the
|
|
10
|
+
RFC 9207 `iss` check, ID tokens verified against the tenant's keys (signature, issuer,
|
|
11
|
+
audience, `azp`, expiry, nonce), refresh token rotation (`refresh`, `ensure_fresh`), `revoke`,
|
|
12
|
+
`userinfo`, `logout_url` (RP-initiated logout), `client_credentials`, `screen="signup"`, and
|
|
13
|
+
`return_to` limited to same-site paths. `TokenSet` serialises to a dict for sessions.
|
|
14
|
+
- `TokenVerifier` / `verify_access_token`: local verification of access tokens with every
|
|
15
|
+
algorithm of the key library (RS256/384/512, PS256/384/512, ES256, ES384, EdDSA from the
|
|
16
|
+
JWKS; HS256/384/512 with the API's secret). Requires `typ: at+jwt` and the key's own `alg` and
|
|
17
|
+
type; checks issuer, expiry, not-before, audience and scopes (`InsufficientScopeError`, 403).
|
|
18
|
+
JWKS cached for 10 minutes, refetched once for an unknown key id, unknown ids throttled for 60 s.
|
|
19
|
+
- `HybridTokenVerifier` / `create_token_verifier`: `local`, `hybrid` and `introspect` modes.
|
|
20
|
+
Opaque `9in_at_` tokens are introspected; answers cached (at most `cache_ttl`, never past
|
|
21
|
+
expiry; refusals until expiry) in memory or a shared cache, and evicted by `handle_event` for
|
|
22
|
+
`token.revoked`, `session.revoked` and `user.*` webhooks.
|
|
23
|
+
- `verify_id_token`.
|
|
24
|
+
- `ManagementClient`: users (list, iterate, get, look up by email / phone number / username,
|
|
25
|
+
create, import, update, delete, block, unblock), single-use login links, and sessions (list,
|
|
26
|
+
revoke all, revoke one), with client-credentials tokens cached per scope.
|
|
27
|
+
- `AdapterHandler`, `Adapter`, `AdapterUser`: adapter protocol v2 (`/authenticate`, `/user`,
|
|
28
|
+
`/event`) with signed requests and responses.
|
|
29
|
+
- `verify_webhook` and `EventDeduplicator` (process each event once: `processed`, `duplicate`,
|
|
30
|
+
`in_progress`).
|
|
31
|
+
- `sign_payload`, `verify_signature`, `check_signature`: the `9in-signature` scheme, with
|
|
32
|
+
several secrets for rotation.
|
|
33
|
+
- `nine.flask` (sign-in blueprint, `login_required`, `require_auth`, `get_access_token`) and
|
|
34
|
+
`nine.fastapi` (`require_auth` and `webhook_event` dependencies), imported only when used.
|
|
35
|
+
- Issuers must use https (`insecure_issuer`), except for localhost; opt out with
|
|
36
|
+
`allow_insecure_issuer` or `NINE_ALLOW_INSECURE_ISSUER=true`.
|
|
37
|
+
- Settings from `NINE_*` environment variables (`nine.env`, `from_env()`).
|
9in-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cubelet Ltd [https://cubelet.co.uk]
|
|
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
|
|
13
|
+
all 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
|
|
21
|
+
THE SOFTWARE.
|
9in-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: 9in
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for 9in: sign-in (OIDC + PKCE), access token verification, Management API, adapters and webhooks.
|
|
5
|
+
Project-URL: Homepage, https://9in.io
|
|
6
|
+
Project-URL: Documentation, https://9in.io/docs/
|
|
7
|
+
Project-URL: Source, https://github.com/9in-io/python-sdk
|
|
8
|
+
Project-URL: Issues, https://github.com/9in-io/python-sdk/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/9in-io/python-sdk/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: Cubelet Ltd <info@cubelet.co.uk>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: 9in,authentication,jwt,oauth2,oidc,openid-connect,pkce,single-sign-on,sso,webhooks
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Framework :: FastAPI
|
|
16
|
+
Classifier: Framework :: Flask
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
26
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Session
|
|
27
|
+
Classifier: Topic :: Security
|
|
28
|
+
Classifier: Typing :: Typed
|
|
29
|
+
Requires-Python: >=3.10
|
|
30
|
+
Requires-Dist: cryptography>=42
|
|
31
|
+
Provides-Extra: fastapi
|
|
32
|
+
Requires-Dist: fastapi>=0.100; extra == 'fastapi'
|
|
33
|
+
Provides-Extra: flask
|
|
34
|
+
Requires-Dist: flask>=2.3.3; extra == 'flask'
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
9in Python SDK
|
|
38
|
+
==============
|
|
39
|
+
|
|
40
|
+
<img src="https://raw.githubusercontent.com/9in-io/python-sdk/main/docs/img/logo.png" width="160" alt="9in"/>
|
|
41
|
+
|
|
42
|
+
Official Python SDK for [9in](https://9in.io): hosted login, OpenID Connect provider and SSO.
|
|
43
|
+
|
|
44
|
+
- **Sign users in** with `WebAppAuth`: authorization code flow with PKCE, endpoints from OIDC
|
|
45
|
+
discovery, ID tokens verified against your tenant's keys, refresh token rotation and logout.
|
|
46
|
+
- **Protect your API**: verify access tokens locally with every algorithm of your tenant's key
|
|
47
|
+
library, and, in hybrid mode, catch revocations at once with cached introspection.
|
|
48
|
+
- **Manage users** through the Management API: users, sessions, single-use sign-in links and
|
|
49
|
+
bulk import.
|
|
50
|
+
- **Keep users in your own database** with the adapter protocol v2 (`/authenticate`, `/user`,
|
|
51
|
+
`/event`) and signed requests and responses.
|
|
52
|
+
- **Receive webhooks**, verify their signature and process each event once.
|
|
53
|
+
- **Flask and FastAPI helpers**: a sign-in blueprint, `@require_auth`, and FastAPI dependencies.
|
|
54
|
+
|
|
55
|
+
Requires Python 3.10+. One dependency, [`cryptography`](https://cryptography.io); HTTP goes
|
|
56
|
+
through the standard library. Fully typed, and safe to share between threads.
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install 9in
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The package is `9in` on PyPI and `nine` in Python (`import nine`). Guides are at
|
|
63
|
+
[9in.io/docs](https://9in.io/docs/).
|
|
64
|
+
|
|
65
|
+
| Building with | Use |
|
|
66
|
+
|---|---|
|
|
67
|
+
| Django | [`9in-django`](https://github.com/9in-io/django) (sign-in, local users, DRF, webhooks, adapter) |
|
|
68
|
+
| JavaScript, Next.js, React | [`@9in-io/sdk`](https://github.com/9in-io/sdk), [`@9in-io/nextjs`](https://github.com/9in-io/nextjs), [`@9in-io/react`](https://github.com/9in-io/react) |
|
|
69
|
+
| PHP or Laravel | [`9in/php-sdk`](https://github.com/9in-io/php-sdk), [`9in/laravel`](https://github.com/9in-io/laravel) |
|
|
70
|
+
|
|
71
|
+
## Configuration
|
|
72
|
+
|
|
73
|
+
Every class takes its settings as arguments, and `from_env()` reads them from the environment:
|
|
74
|
+
|
|
75
|
+
| Variable | Used for |
|
|
76
|
+
|---|---|
|
|
77
|
+
| `NINE_ISSUER` | Your tenant, e.g. `https://acme.9in.io`, or your custom login domain |
|
|
78
|
+
| `NINE_CLIENT_ID` | The application's client ID |
|
|
79
|
+
| `NINE_CLIENT_SECRET` | Confidential applications, the Management API and introspection |
|
|
80
|
+
| `NINE_REDIRECT_URI` | The callback URL registered on the application |
|
|
81
|
+
| `NINE_AUDIENCE` | Your API's identifier: to request access tokens for it, and to verify them |
|
|
82
|
+
| `NINE_ADAPTER_SECRET` | The adapter's signing secret (Connections → User database) |
|
|
83
|
+
| `NINE_WEBHOOK_SECRET` | The webhook endpoint's signing secret (comma-separated while you rotate) |
|
|
84
|
+
|
|
85
|
+
`nine.env.get("ISSUER")` returns `NINE_ISSUER` (or None).
|
|
86
|
+
|
|
87
|
+
## Sign users in
|
|
88
|
+
|
|
89
|
+
Create a **Regular Web App** in the console with your callback URL (for example
|
|
90
|
+
`https://app.acme.com/nine/callback`) and logout URL, and copy its client ID and secret.
|
|
91
|
+
|
|
92
|
+
### Flask
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
import os
|
|
96
|
+
|
|
97
|
+
from flask import Flask
|
|
98
|
+
|
|
99
|
+
from nine.flask import create_blueprint, current_user, get_access_token, login_required
|
|
100
|
+
|
|
101
|
+
app = Flask(__name__)
|
|
102
|
+
app.secret_key = os.environ["SECRET_KEY"]
|
|
103
|
+
app.register_blueprint(create_blueprint()) # /nine/login, /nine/signup, /nine/callback, /nine/logout
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@app.get("/")
|
|
107
|
+
@login_required # signed-out visitors sign in and come back
|
|
108
|
+
def home():
|
|
109
|
+
user = current_user() # sub, email, name, … from the verified ID token
|
|
110
|
+
token = get_access_token() # for your API (set NINE_AUDIENCE); refreshed and rotated
|
|
111
|
+
return f"Hello {user['email']}"
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`create_blueprint()` reads `NINE_ISSUER`, `NINE_CLIENT_ID`, `NINE_CLIENT_SECRET` and
|
|
115
|
+
`NINE_REDIRECT_URI` (or pass a `WebAppAuth`). Link to `/nine/login?return_to=/somewhere` and
|
|
116
|
+
`/nine/logout`. Flask's default session is a signed cookie, which the user can read: use a
|
|
117
|
+
server-side session (Flask-Session) to keep tokens off the browser.
|
|
118
|
+
|
|
119
|
+
### Any framework
|
|
120
|
+
|
|
121
|
+
`WebAppAuth` does the protocol; you keep the pending login and the tokens in your server-side
|
|
122
|
+
session:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
import nine
|
|
126
|
+
|
|
127
|
+
auth = nine.WebAppAuth.from_env()
|
|
128
|
+
|
|
129
|
+
# GET /nine/login
|
|
130
|
+
login = auth.create_login(return_to="/dashboard") # screen="signup" opens the sign-up form
|
|
131
|
+
session["nine_login"] = login.pending # JSON-serialisable; a secret
|
|
132
|
+
redirect_to(login.url)
|
|
133
|
+
|
|
134
|
+
# GET /nine/callback: checks state, iss and PKCE, exchanges the code, verifies the ID token
|
|
135
|
+
tokens = auth.handle_callback(request_url, session.pop("nine_login", None))
|
|
136
|
+
session["nine_tokens"] = tokens.to_dict()
|
|
137
|
+
tokens.claims # sub, email, name, …
|
|
138
|
+
redirect_to(tokens.return_to or "/") # only ever a same-site path
|
|
139
|
+
|
|
140
|
+
# later: refreshed (9in rotates refresh tokens, so save the new set)
|
|
141
|
+
tokens = auth.ensure_fresh(nine.TokenSet.from_dict(session["nine_tokens"]))
|
|
142
|
+
session["nine_tokens"] = tokens.to_dict()
|
|
143
|
+
profile = auth.userinfo(tokens.access_token)
|
|
144
|
+
|
|
145
|
+
# GET /nine/logout
|
|
146
|
+
auth.revoke(tokens.refresh_token)
|
|
147
|
+
redirect_to(auth.logout_url(id_token_hint=tokens.id_token, post_logout_redirect_uri="https://app.acme.com/"))
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
- **The `state` is single-use**, compared in constant time, and expires after 15 minutes. Pass a
|
|
151
|
+
shared `cache=` when several processes handle callbacks.
|
|
152
|
+
- **The callback is checked** for 9in's `iss` parameter (RFC 9207); the ID token's signature,
|
|
153
|
+
issuer, audience, expiry and nonce are verified before you see any claims.
|
|
154
|
+
- **Public applications** (no client secret) work the same way with PKCE; confidential ones
|
|
155
|
+
authenticate with HTTP Basic.
|
|
156
|
+
- `create_login(prompt="login" | "consent" | "none" | "select_account", login_hint=…, locale="de")`.
|
|
157
|
+
- `auth.client_credentials(audience=…, scope=…)` gets a token for the application itself.
|
|
158
|
+
|
|
159
|
+
## Protect your API
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
from nine import InsufficientScopeError, InvalidTokenError, TokenVerifier
|
|
163
|
+
|
|
164
|
+
verifier = TokenVerifier("https://acme.9in.io", audience="https://api.acme.com")
|
|
165
|
+
|
|
166
|
+
try:
|
|
167
|
+
claims = verifier.verify(request.headers.get("Authorization"), scope="orders:read")
|
|
168
|
+
except (InvalidTokenError, InsufficientScopeError) as error:
|
|
169
|
+
abort(error.status) # 401 / 403
|
|
170
|
+
|
|
171
|
+
claims["sub"] # the user (or the client ID for machine tokens)
|
|
172
|
+
claims["client_id"] # the calling application
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`nine.verify_access_token(token, issuer=…, audience=…, scope=…)` does the same in one call.
|
|
176
|
+
|
|
177
|
+
Every algorithm of the console's key library is accepted: RS256/384/512, PS256/384/512, ES256,
|
|
178
|
+
ES384 and EdDSA (Ed25519) from your tenant's JWKS. When a key names its `alg`, the token must use
|
|
179
|
+
exactly it, and the key type must fit. For an API whose tokens are signed with an HMAC key
|
|
180
|
+
(HS256/384/512), pass that key's secret: `TokenVerifier(issuer, secret=os.environ["NINE_API_SECRET"])`.
|
|
181
|
+
Only access tokens (`typ: at+jwt`) pass, never ID tokens. Keys are cached for ten minutes; a token
|
|
182
|
+
with an unknown key id fetches them again once (key rotation), and unknown key ids are then
|
|
183
|
+
ignored for a minute.
|
|
184
|
+
|
|
185
|
+
With Flask or FastAPI:
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
from nine.flask import current_claims, require_auth
|
|
189
|
+
|
|
190
|
+
@app.get("/api/orders")
|
|
191
|
+
@require_auth(scope="orders:read") # 401 / 403 with a WWW-Authenticate header
|
|
192
|
+
def orders():
|
|
193
|
+
return {"user": current_claims()["sub"]}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
```python
|
|
197
|
+
from fastapi import Depends, FastAPI
|
|
198
|
+
|
|
199
|
+
from nine.fastapi import require_auth
|
|
200
|
+
|
|
201
|
+
app = FastAPI()
|
|
202
|
+
|
|
203
|
+
@app.get("/api/orders")
|
|
204
|
+
def orders(claims: dict = Depends(require_auth(scope="orders:read"))):
|
|
205
|
+
return {"user": claims["sub"]}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Both verify with `nine.create_token_verifier()` from `NINE_ISSUER`, `NINE_AUDIENCE` and, for
|
|
209
|
+
hybrid mode, `NINE_CLIENT_ID` / `NINE_CLIENT_SECRET`, unless you pass `verifier=`.
|
|
210
|
+
|
|
211
|
+
### Revocation-aware verification (hybrid)
|
|
212
|
+
|
|
213
|
+
A JWT stays valid until it expires, even after the user signs out or an admin revokes it.
|
|
214
|
+
`HybridTokenVerifier` checks the token locally, asks 9in once (introspection) and caches the
|
|
215
|
+
answer until a revocation webhook arrives:
|
|
216
|
+
|
|
217
|
+
```python
|
|
218
|
+
from nine import HybridTokenVerifier
|
|
219
|
+
|
|
220
|
+
verifier = HybridTokenVerifier(
|
|
221
|
+
"https://acme.9in.io",
|
|
222
|
+
audience="https://api.acme.com",
|
|
223
|
+
client_id=client_id, # a confidential application, for introspection
|
|
224
|
+
client_secret=client_secret,
|
|
225
|
+
# mode="hybrid" # default with credentials; "local" or "introspect"
|
|
226
|
+
# cache=shared_cache # share answers between processes (see Caching)
|
|
227
|
+
# cache_ttl=300 # longest an answer is trusted without hearing from 9in
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
claims = verifier.verify(request.headers.get("Authorization"), scope="orders:read")
|
|
231
|
+
|
|
232
|
+
# In your webhook endpoint (subscribe it to token.revoked, session.revoked, user.*):
|
|
233
|
+
verifier.handle_event(event)
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
- **Opaque access tokens** (`9in_at_…`) are always introspected, and cached in hybrid mode.
|
|
237
|
+
- **Cache lifetime:** an answer never outlives the token. A refusal is remembered until the
|
|
238
|
+
token expires (a minute for an opaque token).
|
|
239
|
+
- **Eviction:** `token.revoked` evicts by `jti`, `session.revoked` by `sid`, and
|
|
240
|
+
`user.sessions_revoked` / `user.deleted` / `user.updated` / `user.password_changed` by user.
|
|
241
|
+
- `nine.create_token_verifier()` builds one from the environment (`NINE_TOKEN_MODE` sets the mode).
|
|
242
|
+
|
|
243
|
+
## Manage users
|
|
244
|
+
|
|
245
|
+
Give a confidential application the `management:*` scopes in the console, then:
|
|
246
|
+
|
|
247
|
+
```python
|
|
248
|
+
from nine import ManagementClient
|
|
249
|
+
|
|
250
|
+
management = ManagementClient.from_env() # NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET
|
|
251
|
+
|
|
252
|
+
user = management.create_user({"email": "jane@acme.com", "password": "correct horse battery", "email_verified": True})
|
|
253
|
+
management.update_user(user["id"], {"name": "Jane Doe", "metadata": {"plan": "pro"}})
|
|
254
|
+
management.find_user_by_email("JANE@acme.com") # the user, or None
|
|
255
|
+
management.find_user("phone_number", "+447700900000")
|
|
256
|
+
page = management.list_users(query="acme.com", limit=50) # {"users": [...], "next_cursor": ...}
|
|
257
|
+
management.get_user(user["id"]) # {"user", "identities", "sessions", "has_password", "mfa"}
|
|
258
|
+
|
|
259
|
+
link = management.create_login_link(user["id"], return_to="https://app.acme.com/nine/callback")
|
|
260
|
+
link["url"] # single use; expires at link["expires_at"]
|
|
261
|
+
|
|
262
|
+
management.list_user_sessions(user["id"])
|
|
263
|
+
management.revoke_user_sessions(user["id"]) # signs the user out everywhere
|
|
264
|
+
management.block_user(user["id"])
|
|
265
|
+
management.unblock_user(user["id"])
|
|
266
|
+
management.delete_user(user["id"])
|
|
267
|
+
|
|
268
|
+
management.import_users([{"id": "legacy-42", "email": "old@acme.com", "password_hash": "$2b$12$…"}], on_conflict="update")
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
Users, sessions and inputs use the API's own snake_case names (`email_verified`,
|
|
272
|
+
`phone_number`, `password_hash`), the same going in and coming out; times are ISO 8601 UTC
|
|
273
|
+
strings. Each call asks for the one scope it needs, so an application granted only some
|
|
274
|
+
management scopes works; tokens are cached until shortly before they expire.
|
|
275
|
+
|
|
276
|
+
## Keep users in your own database
|
|
277
|
+
|
|
278
|
+
9in can check passwords against your database and look users up there (Connections → User
|
|
279
|
+
database → Your server). Implement an `Adapter` and serve it with `AdapterHandler`:
|
|
280
|
+
|
|
281
|
+
```python
|
|
282
|
+
from nine import Adapter, AdapterHandler, AdapterUser, env
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class MyUsers(Adapter):
|
|
286
|
+
def authenticate(self, identifier, password): # {"type": "email" | "username" | "phone", "value": …}
|
|
287
|
+
user = db.find_by_login(identifier["type"], identifier["value"])
|
|
288
|
+
if user is None or not user.check_password(password):
|
|
289
|
+
return self.INVALID
|
|
290
|
+
return self.BLOCKED if user.disabled else to_adapter_user(user)
|
|
291
|
+
|
|
292
|
+
def find_user(self, query): # {"id": …} or {"identifier": {…}}
|
|
293
|
+
user = db.get(query["id"]) if "id" in query else db.find_by_login(**query["identifier"])
|
|
294
|
+
return to_adapter_user(user) if user else None
|
|
295
|
+
|
|
296
|
+
def on_event(self, event): # otp.requested, user.updated, …
|
|
297
|
+
if event["event_type"] == "otp.requested":
|
|
298
|
+
send_code(event["data"]["to"], event["data"]["code"])
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def to_adapter_user(user):
|
|
302
|
+
return AdapterUser(id=str(user.id), email=user.email, email_verified=user.confirmed, name=user.full_name)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
handler = AdapterHandler(env.get("ADAPTER_SECRET"), MyUsers())
|
|
306
|
+
|
|
307
|
+
# Flask: one route for /nine/authenticate, /nine/user and /nine/event
|
|
308
|
+
@app.post("/nine/<any(authenticate, user, event):route>")
|
|
309
|
+
def adapter(route):
|
|
310
|
+
answer = handler.handle(request.method, request.path, request.headers, request.get_data())
|
|
311
|
+
return answer.body, answer.status, answer.headers
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
`AdapterHandler` checks each request's `9in-signature` (HMAC over the timestamp, method, path
|
|
315
|
+
and raw body, 5 minutes of tolerance), routes the three endpoints with 9in's status codes, and
|
|
316
|
+
signs every response over `<path>#<9in-request-id>` so it can't be replayed for another request.
|
|
317
|
+
Pass `[new_secret, old_secret]` while you rotate the secret.
|
|
318
|
+
|
|
319
|
+
## Webhooks
|
|
320
|
+
|
|
321
|
+
```python
|
|
322
|
+
from nine import EventDeduplicator, MemoryCache, NineError, env, verify_webhook
|
|
323
|
+
|
|
324
|
+
dedupe = EventDeduplicator(MemoryCache()) # a shared cache with an atomic add() for several processes
|
|
325
|
+
|
|
326
|
+
@app.post("/nine/webhook")
|
|
327
|
+
def webhook():
|
|
328
|
+
try:
|
|
329
|
+
event = verify_webhook(env.get_list("WEBHOOK_SECRET"), request.get_data(), request.headers.get("9in-signature"), "/nine/webhook")
|
|
330
|
+
except NineError as error:
|
|
331
|
+
return {"error": error.error}, error.status
|
|
332
|
+
|
|
333
|
+
def handle():
|
|
334
|
+
if event["event_type"] == "user.created":
|
|
335
|
+
crm.add_contact(event["data"]["user"])
|
|
336
|
+
verifier.handle_event(event) # if you use HybridTokenVerifier
|
|
337
|
+
|
|
338
|
+
outcome = dedupe.process(event["id"], handle)
|
|
339
|
+
return "", 409 if outcome == EventDeduplicator.IN_PROGRESS else 204
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
`verify_webhook` checks the signature over the **raw** body and the path 9in posted to (pass it
|
|
343
|
+
explicitly when a proxy rewrites paths), with 5 minutes of tolerance, and returns the event:
|
|
344
|
+
`{id, event_type, created_at, tenant, environment, data}`. `EventDeduplicator.process` runs the
|
|
345
|
+
handler once per event id: `processed` or `duplicate` → answer 2xx; `in_progress` (another
|
|
346
|
+
delivery is running) → 409 so 9in retries later; if the handler raises, the id is released and
|
|
347
|
+
the error re-raised, so 9in's retry processes the event. In FastAPI,
|
|
348
|
+
`event: dict = Depends(nine.fastapi.webhook_event())` does the verification.
|
|
349
|
+
|
|
350
|
+
## Caching and threads
|
|
351
|
+
|
|
352
|
+
The SDK caches discovery documents and keys per process, and keeps hybrid answers, used
|
|
353
|
+
sign-in states and processed event ids in a `Cache`. The default `MemoryCache` is thread-safe
|
|
354
|
+
and lives in one process. With several processes, pass one shared cache (`cache=`): any object
|
|
355
|
+
with `get(key)`, `set(key, value, ttl)`, `delete(key)` and an atomic `add(key, value, ttl)`.
|
|
356
|
+
Values are JSON-compatible.
|
|
357
|
+
|
|
358
|
+
```python
|
|
359
|
+
import json
|
|
360
|
+
|
|
361
|
+
import redis
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
class RedisCache:
|
|
365
|
+
def __init__(self, client):
|
|
366
|
+
self.r = client
|
|
367
|
+
|
|
368
|
+
def get(self, key):
|
|
369
|
+
raw = self.r.get(key)
|
|
370
|
+
return None if raw is None else json.loads(raw)
|
|
371
|
+
|
|
372
|
+
def set(self, key, value, ttl=None):
|
|
373
|
+
self.r.set(key, json.dumps(value), ex=ttl)
|
|
374
|
+
|
|
375
|
+
def delete(self, key):
|
|
376
|
+
self.r.delete(key)
|
|
377
|
+
|
|
378
|
+
def add(self, key, value, ttl=None):
|
|
379
|
+
return bool(self.r.set(key, json.dumps(value), ex=ttl, nx=True))
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
cache = RedisCache(redis.Redis())
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
HTTP goes through `nine.UrllibHttpClient` (10 s timeout, TLS verified, redirects never
|
|
386
|
+
followed). Pass `http=` with your own `HttpClient` to change the timeout or use a proxy.
|
|
387
|
+
|
|
388
|
+
## Issuers must use https
|
|
389
|
+
|
|
390
|
+
Every class refuses an issuer that is not `https://` (`insecure_issuer`), so a typo can't send
|
|
391
|
+
codes, tokens or client secrets in clear text. Plain http is accepted for `localhost`,
|
|
392
|
+
`*.localhost` and loopback addresses. For other development hosts (e.g. `http://auth:8897` in
|
|
393
|
+
Docker) pass `allow_insecure_issuer=True` or set `NINE_ALLOW_INSECURE_ISSUER=true`. Issuers with
|
|
394
|
+
a query string, fragment or credentials are refused (`invalid_issuer`).
|
|
395
|
+
|
|
396
|
+
## Errors
|
|
397
|
+
|
|
398
|
+
Every failure is a `nine.NineError` with an `error` code (`invalid_token`, `insufficient_scope`,
|
|
399
|
+
`invalid_state`, `invalid_grant`, `access_denied`, `invalid_signature`, `insecure_issuer`,
|
|
400
|
+
`network_error`, …), a `description` and, for HTTP errors, a `status`:
|
|
401
|
+
|
|
402
|
+
| Class | When | `status` |
|
|
403
|
+
|---|---|---|
|
|
404
|
+
| `InvalidTokenError` | A token is missing, malformed, expired, revoked or for another API | 401 |
|
|
405
|
+
| `InsufficientScopeError` | A valid token lacks a scope (`.missing` lists them) | 403 |
|
|
406
|
+
| `InvalidStateError` | A callback's state doesn't match, was used, or expired | 400 |
|
|
407
|
+
| `SignatureError` | A `9in-signature` is missing, malformed, expired or wrong (`.reason`) | 401 |
|
|
408
|
+
| `NineError` | Anything else, e.g. errors from 9in (`invalid_grant`, `not_found`) or `jwks_unavailable` when 9in can't be reached (answer 503) | varies |
|
|
409
|
+
|
|
410
|
+
Errors from the Management API keep 9in's JSON body in `.body` (`details`, `field`, …).
|
|
411
|
+
|
|
412
|
+
## Development
|
|
413
|
+
|
|
414
|
+
```bash
|
|
415
|
+
uv sync # or: pip install -e . pytest flask fastapi httpx mypy ruff
|
|
416
|
+
uv run pytest # unit tests (a fake 9in tenant; no network)
|
|
417
|
+
uv run mypy && uv run ruff check
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
The live end-to-end tests sign in through 9in's real hosted pages on test tenants, verify real
|
|
421
|
+
tokens, webhooks and adapter calls, and delete the users they create:
|
|
422
|
+
|
|
423
|
+
```bash
|
|
424
|
+
NINE_E2E=1 NINE_E2E_ENV=/path/to/.env.e2e uv run pytest tests/test_live.py
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
`examples/` has a Flask app (sign-in, an API route, webhooks, the adapter) and a FastAPI API.
|
|
428
|
+
Report bugs in [issues](https://github.com/9in-io/python-sdk/issues).
|
|
429
|
+
|
|
430
|
+
## License
|
|
431
|
+
|
|
432
|
+
The MIT License (MIT). See [LICENSE](https://github.com/9in-io/python-sdk/blob/main/LICENSE). 9in is by [Cubelet Ltd](https://cubelet.co.uk).
|