spyddb 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.
spyddb-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,230 @@
1
+ Metadata-Version: 2.4
2
+ Name: spyddb
3
+ Version: 0.1.0
4
+ Summary: Official Python driver and ORM for SpydDB
5
+ Author: SpydDB Contributors
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/spyddb/spyddb
8
+ Project-URL: Documentation, https://github.com/spyddb/spyddb/blob/main/docs/PROTOCOL.md
9
+ Keywords: spyddb,database,driver,orm,spydwire
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Database
16
+ Classifier: Topic :: Database :: Front-Ends
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+
20
+ # SpydDB Python driver and ORM
21
+
22
+ The official Python client for SpydDB. It has no runtime
23
+ dependencies: the frame layer, CRC-32C, SCRAM-SHA-256, TLS, the value codec,
24
+ the ORM, and migrations use only the standard library.
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ pip install spyddb
30
+ ```
31
+
32
+ ## Connect
33
+
34
+ ```python
35
+ from spyddb import Client
36
+
37
+ with Client.connect(
38
+ "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN"
39
+ ) as client:
40
+ result = client.execute(
41
+ "users | where active == true | pick id, email | sort id | take 10"
42
+ )
43
+ for row in result.dicts:
44
+ print(row)
45
+ ```
46
+
47
+ SCRAM-SHA-256 is selected with `user` and `password` (or `password_env`)
48
+ instead of a token:
49
+
50
+ ```python
51
+ client = Client.connect(
52
+ "spydwire://db.internal:5433?user=alice&password_env=SPYD_PASSWORD"
53
+ "&ca=/etc/spyd/ca.pem&server_name=db.internal"
54
+ )
55
+ ```
56
+
57
+ Connection string parameters: `token`, `token_env`, `user`, `password`,
58
+ `password_env`, `ca`, `server_name`, `client_cert`, `client_key`, `tls`,
59
+ `timeout`, `connect_timeout`. Unknown parameters are refused. Plaintext is
60
+ only accepted by the server on a loopback address; supply `ca` (and the client
61
+ certificate for mTLS) elsewhere.
62
+
63
+ ## Values
64
+
65
+ Parameters are positional (`$1`, `$2`, …) and may be written as Python values:
66
+
67
+ | Python | SpydWire |
68
+ | --- | --- |
69
+ | `None` | `"Null"` |
70
+ | `bool` | `{"Bool": ...}` |
71
+ | `int` | `{"U64": ...}` or `{"I64": ...}` |
72
+ | `float` | `{"F64": ...}` |
73
+ | `str` | `{"String": ...}` |
74
+ | `bytes` | `{"Bytes": [...]}` |
75
+ | `datetime` | `{"Timestamp": microseconds}` |
76
+ | `date` | `{"Date": days}` |
77
+ | `dict`, `list` | `{"Json": ...}` |
78
+ | `spyddb.Vector` | `{"Vector": [...]}` |
79
+ | `spyddb.GeoPoint` | `{"GeoPoint": {...}}` |
80
+ | `spyddb.Text`, `Float32`, `UInt`, `Int`, `EnumName` | forced variants |
81
+
82
+ Results are decoded to `int`, `float`, `str`, `bytes`, `datetime` (UTC),
83
+ `date`, `decimal.Decimal`, `list`, `dict`, `GeoPoint`, and the enum *variant
84
+ name* (resolved from the column type).
85
+
86
+ ### Decimal parameters
87
+
88
+ The current SpydWire request decoder cannot carry `i128`, so a
89
+ `{"Decimal": ...}` parameter is rejected at the frame layer. Send the decimal
90
+ as text and cast it:
91
+
92
+ ```python
93
+ client.execute(
94
+ "orders | insert { id: $1, total: cast($2 as decimal(12, 2)) }",
95
+ [1, "19.99"],
96
+ )
97
+ ```
98
+
99
+ `spyddb.DecimalParam` carries the precision and scale for this purpose. The
100
+ ORM adds the cast automatically.
101
+
102
+ ## Driver features
103
+
104
+ - SpydWire v2 (`SPD2` canonical binary fast path) with transparent `SPD1` JSON
105
+ compatibility, `TCP_NODELAY`, coalesced frame writes, and 64 KiB read buffering.
106
+ - `Client`: serialized requests, `prepare()` / `execute_prepared()` /
107
+ `close_prepared()` (with automatic re-prepare on DDL invalidation),
108
+ `use_database()`, interactive transactions (`begin()`, `commit()`,
109
+ `rollback()`, `transaction()`), query IDs, ping, and cancel.
110
+ - `Pool`: bounded lazy pool, LIFO reuse, optional ping on checkout, discards
111
+ broken connections.
112
+ - `Result`: `rows`, `dicts`, `first()`, `one()`, `scalar()`.
113
+ - Typed errors: `SpydAuthenticationError`, `SpydTypeError`,
114
+ `SpydConstraintError`, `SpydConflictError`, `SpydPermissionError`,
115
+ `SpydResourceError`, `SpydSchemaError`, `SpydCancelledError`, …
116
+ - `ConnectionOptions.parse` for `spydwire://` URLs.
117
+ - TLS 1.2/1.3 with a CA, SNI/server name, and optional client certificate.
118
+
119
+ ## ORM
120
+
121
+ ```python
122
+ from decimal import Decimal
123
+ from spyddb.orm import (
124
+ Database, Model, UInt64, String, Decimal, Bool, Timestamp, Index,
125
+ )
126
+
127
+ class User(Model):
128
+ __collection__ = "users"
129
+ id = UInt64(primary=True, auto_increment=True)
130
+ email = String(160, unique=True, nullable=False)
131
+ name = String(80, nullable=False)
132
+ balance = Decimal(12, 2, default=Decimal("0"))
133
+ active = Bool(default=True)
134
+ joined = Timestamp()
135
+
136
+ database = Database.connect(
137
+ "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN",
138
+ models=[User],
139
+ )
140
+ database.create_all() # create collection + indexes
141
+ database.sync() # additive changes; destructive needs a flag
142
+
143
+ user = User.create(email="ada@example.test", name="Ada")
144
+ user.balance = Decimal("12.50")
145
+ user.save()
146
+
147
+ adults = (
148
+ User.where((User.active == True) & (User.name != ""))
149
+ .order_by(User.name.asc())
150
+ .limit(20)
151
+ .all()
152
+ )
153
+ print(User.get(id=user.id), User.count())
154
+ print(
155
+ User.query()
156
+ .aggregate(sum(User.balance).as_("total"), count().as_("n"))
157
+ .rows()
158
+ )
159
+ ```
160
+
161
+ ### Query builder
162
+
163
+ - Comparisons: `==`, `!=`, `<`, `<=`, `>`, `>=`; `None` becomes
164
+ `is null` / `is not null`.
165
+ - `like`, `between`, `in_`, `not_in`, `is_null`, `is_not_null`.
166
+ - Boolean composition with `&`, `|`, `~`.
167
+ - Functions: `lower`, `upper`, `length`, `abs`, `round`, `coalesce`,
168
+ `concat`, `contains`, `starts_with`, `ends_with`, `now`, and `func(name, …)`.
169
+ - Writes: `create`, `bulk_create`, `save`, `delete`, `upsert`.
170
+ - Query writes: `query.update(...)`, `query.delete()`.
171
+ - Aggregates: `count`, `sum`, `avg`, `min`, `max`, `.group_by(...)`,
172
+ `.aggregate(...)`, `.rows()`.
173
+ - Paging: `.limit()`, `.offset()`, `.iterate(batch_size=...)`.
174
+ - `.explain()` for the plan.
175
+
176
+ SpydQL has no `LIMIT`, `OFFSET`, `SELECT *`, or `HAVING`; the builder emits
177
+ `take`, `skip`, explicit `pick`, and `where` after aggregation.
178
+
179
+ ### Schema and migrations
180
+
181
+ The server has no schema introspection over SpydWire. The ORM records the
182
+ definition it applied in `_spyd_orm_schema` and compares that record with the
183
+ models. `create_all()` is idempotent: because it cannot inspect an existing
184
+ collection, a collection that has no record is adopted as matching the model
185
+ (the `if not exists` creation is a no-op and indexes are added). `sync()` applies additive changes (`add field`, `create index`).
186
+ Destructive changes (drop/change a field, drop an index, change the primary
187
+ key, change the storage layout) are refused unless
188
+ `allow_destructive=True`, and a layout change is always refused because it
189
+ needs a new collection and a copy.
190
+
191
+ ```python
192
+ from spyddb.orm import Migration
193
+
194
+ database.migrate([
195
+ Migration(
196
+ "0001_create_users",
197
+ ["create collection users { id: u64 primary, name: string(80) }"],
198
+ ["drop collection if exists users"],
199
+ ),
200
+ ])
201
+ ```
202
+
203
+ Applied migrations are recorded in `_spyd_orm_migrations` with a SHA-256
204
+ checksum; changing a migration after it ran is refused. Keep each migration small.
205
+
206
+ ## Not supported by the server yet
207
+
208
+ - Schema introspection and `DESCRIBE`.
209
+ - Server-side pagination of one result: a response must fit the 8 MiB frame.
210
+ Use `take`/`skip` and `iterate`.
211
+ - `pick *`.
212
+ - A write with `returning` carries values but **no column metadata**; use the
213
+ row tuples or the ORM (it maps them by model field order).
214
+ - `cancel` is per connection. A synchronous caller cannot cancel its own
215
+ in-flight statement; operator-side `ServerHandle::cancel` is the reliable
216
+ path.
217
+ - Decimal parameters, as described above.
218
+ - Column type changes; drop and re-add creates a new field.
219
+
220
+ ## Tests
221
+
222
+ ```sh
223
+ cd clients/python
224
+ python3 -m unittest discover -s tests -v
225
+ ```
226
+
227
+ The integration tests start `target/debug/spyd-server` on a loopback port
228
+ with a temporary data directory, token credentials, and a generated SCRAM
229
+ verifier. Set `SPYD_SERVER_BIN` to use another binary; the tests skip when no
230
+ binary exists.
spyddb-0.1.0/README.md ADDED
@@ -0,0 +1,211 @@
1
+ # SpydDB Python driver and ORM
2
+
3
+ The official Python client for SpydDB. It has no runtime
4
+ dependencies: the frame layer, CRC-32C, SCRAM-SHA-256, TLS, the value codec,
5
+ the ORM, and migrations use only the standard library.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pip install spyddb
11
+ ```
12
+
13
+ ## Connect
14
+
15
+ ```python
16
+ from spyddb import Client
17
+
18
+ with Client.connect(
19
+ "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN"
20
+ ) as client:
21
+ result = client.execute(
22
+ "users | where active == true | pick id, email | sort id | take 10"
23
+ )
24
+ for row in result.dicts:
25
+ print(row)
26
+ ```
27
+
28
+ SCRAM-SHA-256 is selected with `user` and `password` (or `password_env`)
29
+ instead of a token:
30
+
31
+ ```python
32
+ client = Client.connect(
33
+ "spydwire://db.internal:5433?user=alice&password_env=SPYD_PASSWORD"
34
+ "&ca=/etc/spyd/ca.pem&server_name=db.internal"
35
+ )
36
+ ```
37
+
38
+ Connection string parameters: `token`, `token_env`, `user`, `password`,
39
+ `password_env`, `ca`, `server_name`, `client_cert`, `client_key`, `tls`,
40
+ `timeout`, `connect_timeout`. Unknown parameters are refused. Plaintext is
41
+ only accepted by the server on a loopback address; supply `ca` (and the client
42
+ certificate for mTLS) elsewhere.
43
+
44
+ ## Values
45
+
46
+ Parameters are positional (`$1`, `$2`, …) and may be written as Python values:
47
+
48
+ | Python | SpydWire |
49
+ | --- | --- |
50
+ | `None` | `"Null"` |
51
+ | `bool` | `{"Bool": ...}` |
52
+ | `int` | `{"U64": ...}` or `{"I64": ...}` |
53
+ | `float` | `{"F64": ...}` |
54
+ | `str` | `{"String": ...}` |
55
+ | `bytes` | `{"Bytes": [...]}` |
56
+ | `datetime` | `{"Timestamp": microseconds}` |
57
+ | `date` | `{"Date": days}` |
58
+ | `dict`, `list` | `{"Json": ...}` |
59
+ | `spyddb.Vector` | `{"Vector": [...]}` |
60
+ | `spyddb.GeoPoint` | `{"GeoPoint": {...}}` |
61
+ | `spyddb.Text`, `Float32`, `UInt`, `Int`, `EnumName` | forced variants |
62
+
63
+ Results are decoded to `int`, `float`, `str`, `bytes`, `datetime` (UTC),
64
+ `date`, `decimal.Decimal`, `list`, `dict`, `GeoPoint`, and the enum *variant
65
+ name* (resolved from the column type).
66
+
67
+ ### Decimal parameters
68
+
69
+ The current SpydWire request decoder cannot carry `i128`, so a
70
+ `{"Decimal": ...}` parameter is rejected at the frame layer. Send the decimal
71
+ as text and cast it:
72
+
73
+ ```python
74
+ client.execute(
75
+ "orders | insert { id: $1, total: cast($2 as decimal(12, 2)) }",
76
+ [1, "19.99"],
77
+ )
78
+ ```
79
+
80
+ `spyddb.DecimalParam` carries the precision and scale for this purpose. The
81
+ ORM adds the cast automatically.
82
+
83
+ ## Driver features
84
+
85
+ - SpydWire v2 (`SPD2` canonical binary fast path) with transparent `SPD1` JSON
86
+ compatibility, `TCP_NODELAY`, coalesced frame writes, and 64 KiB read buffering.
87
+ - `Client`: serialized requests, `prepare()` / `execute_prepared()` /
88
+ `close_prepared()` (with automatic re-prepare on DDL invalidation),
89
+ `use_database()`, interactive transactions (`begin()`, `commit()`,
90
+ `rollback()`, `transaction()`), query IDs, ping, and cancel.
91
+ - `Pool`: bounded lazy pool, LIFO reuse, optional ping on checkout, discards
92
+ broken connections.
93
+ - `Result`: `rows`, `dicts`, `first()`, `one()`, `scalar()`.
94
+ - Typed errors: `SpydAuthenticationError`, `SpydTypeError`,
95
+ `SpydConstraintError`, `SpydConflictError`, `SpydPermissionError`,
96
+ `SpydResourceError`, `SpydSchemaError`, `SpydCancelledError`, …
97
+ - `ConnectionOptions.parse` for `spydwire://` URLs.
98
+ - TLS 1.2/1.3 with a CA, SNI/server name, and optional client certificate.
99
+
100
+ ## ORM
101
+
102
+ ```python
103
+ from decimal import Decimal
104
+ from spyddb.orm import (
105
+ Database, Model, UInt64, String, Decimal, Bool, Timestamp, Index,
106
+ )
107
+
108
+ class User(Model):
109
+ __collection__ = "users"
110
+ id = UInt64(primary=True, auto_increment=True)
111
+ email = String(160, unique=True, nullable=False)
112
+ name = String(80, nullable=False)
113
+ balance = Decimal(12, 2, default=Decimal("0"))
114
+ active = Bool(default=True)
115
+ joined = Timestamp()
116
+
117
+ database = Database.connect(
118
+ "spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN",
119
+ models=[User],
120
+ )
121
+ database.create_all() # create collection + indexes
122
+ database.sync() # additive changes; destructive needs a flag
123
+
124
+ user = User.create(email="ada@example.test", name="Ada")
125
+ user.balance = Decimal("12.50")
126
+ user.save()
127
+
128
+ adults = (
129
+ User.where((User.active == True) & (User.name != ""))
130
+ .order_by(User.name.asc())
131
+ .limit(20)
132
+ .all()
133
+ )
134
+ print(User.get(id=user.id), User.count())
135
+ print(
136
+ User.query()
137
+ .aggregate(sum(User.balance).as_("total"), count().as_("n"))
138
+ .rows()
139
+ )
140
+ ```
141
+
142
+ ### Query builder
143
+
144
+ - Comparisons: `==`, `!=`, `<`, `<=`, `>`, `>=`; `None` becomes
145
+ `is null` / `is not null`.
146
+ - `like`, `between`, `in_`, `not_in`, `is_null`, `is_not_null`.
147
+ - Boolean composition with `&`, `|`, `~`.
148
+ - Functions: `lower`, `upper`, `length`, `abs`, `round`, `coalesce`,
149
+ `concat`, `contains`, `starts_with`, `ends_with`, `now`, and `func(name, …)`.
150
+ - Writes: `create`, `bulk_create`, `save`, `delete`, `upsert`.
151
+ - Query writes: `query.update(...)`, `query.delete()`.
152
+ - Aggregates: `count`, `sum`, `avg`, `min`, `max`, `.group_by(...)`,
153
+ `.aggregate(...)`, `.rows()`.
154
+ - Paging: `.limit()`, `.offset()`, `.iterate(batch_size=...)`.
155
+ - `.explain()` for the plan.
156
+
157
+ SpydQL has no `LIMIT`, `OFFSET`, `SELECT *`, or `HAVING`; the builder emits
158
+ `take`, `skip`, explicit `pick`, and `where` after aggregation.
159
+
160
+ ### Schema and migrations
161
+
162
+ The server has no schema introspection over SpydWire. The ORM records the
163
+ definition it applied in `_spyd_orm_schema` and compares that record with the
164
+ models. `create_all()` is idempotent: because it cannot inspect an existing
165
+ collection, a collection that has no record is adopted as matching the model
166
+ (the `if not exists` creation is a no-op and indexes are added). `sync()` applies additive changes (`add field`, `create index`).
167
+ Destructive changes (drop/change a field, drop an index, change the primary
168
+ key, change the storage layout) are refused unless
169
+ `allow_destructive=True`, and a layout change is always refused because it
170
+ needs a new collection and a copy.
171
+
172
+ ```python
173
+ from spyddb.orm import Migration
174
+
175
+ database.migrate([
176
+ Migration(
177
+ "0001_create_users",
178
+ ["create collection users { id: u64 primary, name: string(80) }"],
179
+ ["drop collection if exists users"],
180
+ ),
181
+ ])
182
+ ```
183
+
184
+ Applied migrations are recorded in `_spyd_orm_migrations` with a SHA-256
185
+ checksum; changing a migration after it ran is refused. Keep each migration small.
186
+
187
+ ## Not supported by the server yet
188
+
189
+ - Schema introspection and `DESCRIBE`.
190
+ - Server-side pagination of one result: a response must fit the 8 MiB frame.
191
+ Use `take`/`skip` and `iterate`.
192
+ - `pick *`.
193
+ - A write with `returning` carries values but **no column metadata**; use the
194
+ row tuples or the ORM (it maps them by model field order).
195
+ - `cancel` is per connection. A synchronous caller cannot cancel its own
196
+ in-flight statement; operator-side `ServerHandle::cancel` is the reliable
197
+ path.
198
+ - Decimal parameters, as described above.
199
+ - Column type changes; drop and re-add creates a new field.
200
+
201
+ ## Tests
202
+
203
+ ```sh
204
+ cd clients/python
205
+ python3 -m unittest discover -s tests -v
206
+ ```
207
+
208
+ The integration tests start `target/debug/spyd-server` on a loopback port
209
+ with a temporary data directory, token credentials, and a generated SCRAM
210
+ verifier. Set `SPYD_SERVER_BIN` to use another binary; the tests skip when no
211
+ binary exists.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "spyddb"
7
+ version = "0.1.0"
8
+ description = "Official Python driver and ORM for SpydDB"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "SpydDB Contributors" }]
13
+ keywords = ["spyddb", "database", "driver", "orm", "spydwire"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Topic :: Database",
21
+ "Topic :: Database :: Front-Ends",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/spyddb/spyddb"
26
+ Documentation = "https://github.com/spyddb/spyddb/blob/main/docs/PROTOCOL.md"
27
+
28
+ [tool.setuptools.packages.find]
29
+ include = ["spyddb*"]
30
+
31
+ [tool.pytest.ini_options]
32
+ testpaths = ["tests"]
spyddb-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,98 @@
1
+ """Official Python driver and ORM for SpydDB.
2
+
3
+ The driver speaks SpydWire directly: framed JSON over TCP, token or
4
+ SCRAM-SHA-256 authentication, TLS, and cancellation. The ORM adds declarative
5
+ models, a SpydQL query builder, additive schema sync, and migrations.
6
+
7
+ from spyddb import Client
8
+
9
+ with Client.connect("spydwire://127.0.0.1:5433?token_env=SPYD_TOKEN") as client:
10
+ result = client.execute("users | where active == true | pick email")
11
+ print(result.dicts)
12
+ """
13
+
14
+ from .auth import ScramClient
15
+ from .client import Client, Column, ConnectionOptions, Pool, PreparedStatement, Result
16
+ from .errors import (
17
+ SpydAuthenticationError,
18
+ SpydCancelledError,
19
+ SpydConflictError,
20
+ SpydConnectionError,
21
+ SpydConstraintError,
22
+ SpydError,
23
+ SpydMultipleResultsError,
24
+ SpydNoResultError,
25
+ SpydPermissionError,
26
+ SpydProtocolError,
27
+ SpydQueryError,
28
+ SpydResourceError,
29
+ SpydSchemaError,
30
+ SpydTimeoutError,
31
+ SpydTypeError,
32
+ SpydUnsupportedError,
33
+ SpydValueError,
34
+ )
35
+ from .protocol import DEFAULT_MAX_FRAME_BYTES, crc32c
36
+ from .values import (
37
+ ColumnType,
38
+ DecimalParam,
39
+ EnumName,
40
+ Float32,
41
+ GeoPoint,
42
+ Int,
43
+ Text,
44
+ UInt,
45
+ Vector,
46
+ decode_value,
47
+ encode_parameter,
48
+ parse_type,
49
+ )
50
+ from . import orm
51
+ from .orm import Database, Model
52
+
53
+ connect = Database.connect
54
+
55
+ __all__ = [
56
+ "Client",
57
+ "Column",
58
+ "ColumnType",
59
+ "ConnectionOptions",
60
+ "Database",
61
+ "DecimalParam",
62
+ "DEFAULT_MAX_FRAME_BYTES",
63
+ "EnumName",
64
+ "Float32",
65
+ "GeoPoint",
66
+ "Int",
67
+ "Model",
68
+ "Pool",
69
+ "PreparedStatement",
70
+ "Result",
71
+ "ScramClient",
72
+ "SpydAuthenticationError",
73
+ "SpydCancelledError",
74
+ "SpydConflictError",
75
+ "SpydConnectionError",
76
+ "SpydConstraintError",
77
+ "SpydError",
78
+ "SpydMultipleResultsError",
79
+ "SpydNoResultError",
80
+ "SpydPermissionError",
81
+ "SpydProtocolError",
82
+ "SpydQueryError",
83
+ "SpydResourceError",
84
+ "SpydSchemaError",
85
+ "SpydTimeoutError",
86
+ "SpydTypeError",
87
+ "SpydUnsupportedError",
88
+ "SpydValueError",
89
+ "Text",
90
+ "UInt",
91
+ "Vector",
92
+ "connect",
93
+ "crc32c",
94
+ "decode_value",
95
+ "encode_parameter",
96
+ "orm",
97
+ "parse_type",
98
+ ]
@@ -0,0 +1,109 @@
1
+ """SCRAM-SHA-256 client authentication.
2
+
3
+ This follows the server implementation in ``crates/spyd-server/src/scram.rs``
4
+ exactly: SHA-256, ``biws`` channel binding, the literal strings the client
5
+ transmits are the ones hashed, and the server signature must be verified.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import hashlib
12
+ import hmac
13
+ import os
14
+ from typing import Optional
15
+
16
+ from .errors import SpydAuthenticationError, SpydProtocolError
17
+
18
+
19
+ def _b64(data: bytes) -> str:
20
+ return base64.b64encode(data).decode("ascii")
21
+
22
+
23
+ def _unb64(text: str) -> bytes:
24
+ try:
25
+ return base64.b64decode(text, validate=True)
26
+ except Exception as error: # noqa: BLE001 - surfaced as a protocol error
27
+ raise SpydProtocolError(f"the server sent invalid base64: {error}") from error
28
+
29
+
30
+ def _attribute(message: str, key: str) -> Optional[str]:
31
+ """Find ``key=value`` in a comma-separated SCRAM message."""
32
+ for part in message.split(","):
33
+ if part.startswith(key + "="):
34
+ return part[len(key) + 1:]
35
+ return None
36
+
37
+
38
+ class ScramClient:
39
+ """One SCRAM exchange."""
40
+
41
+ def __init__(self, user: str, password: str) -> None:
42
+ if not user:
43
+ raise SpydAuthenticationError("SCRAM needs a user name")
44
+ self.user = user
45
+ self.password = password
46
+ self.client_first_bare = ""
47
+ self.client_final_without_proof = ""
48
+ self._server_key = b""
49
+ self._auth_message = b""
50
+
51
+ def start(self) -> str:
52
+ """Return the ``client_first`` message."""
53
+ nonce = _b64(os.urandom(18))
54
+ self.client_first_bare = f"n={self.user},r={nonce}"
55
+ return self.client_first_bare
56
+
57
+ def finish(self, server_first: str) -> tuple[str, str]:
58
+ """Compute ``(client_final, proof)`` from the server-first message."""
59
+ combined_nonce = _attribute(server_first, "r")
60
+ salt_text = _attribute(server_first, "s")
61
+ iterations_text = _attribute(server_first, "i")
62
+ if not combined_nonce or salt_text is None or iterations_text is None:
63
+ raise SpydProtocolError("the SCRAM challenge is incomplete")
64
+ if not combined_nonce.startswith(self._nonce()):
65
+ raise SpydProtocolError("the server changed the SCRAM nonce")
66
+ try:
67
+ iterations = int(iterations_text)
68
+ except ValueError as error:
69
+ raise SpydProtocolError("the SCRAM iteration count is not a number") from error
70
+ if iterations < 4096:
71
+ raise SpydProtocolError("the server offered a weak SCRAM iteration count")
72
+
73
+ salt = _unb64(salt_text)
74
+ salted = hashlib.pbkdf2_hmac(
75
+ "sha256", self.password.encode("utf-8"), salt, iterations, dklen=32
76
+ )
77
+ client_key = hmac.new(salted, b"Client Key", hashlib.sha256).digest()
78
+ stored_key = hashlib.sha256(client_key).digest()
79
+ server_key = hmac.new(salted, b"Server Key", hashlib.sha256).digest()
80
+ client_final = f"c=biws,r={combined_nonce}"
81
+ auth_message = (
82
+ f"{self.client_first_bare},{server_first},{client_final}".encode("utf-8")
83
+ )
84
+ signature = hmac.new(stored_key, auth_message, hashlib.sha256).digest()
85
+ proof = bytes(left ^ right for left, right in zip(client_key, signature))
86
+
87
+ self._server_key = server_key
88
+ self._auth_message = auth_message
89
+ self.client_final_without_proof = client_final
90
+ return client_final, _b64(proof)
91
+
92
+ def verify(self, server_final: str) -> None:
93
+ """Verify the server signature and raise on a mismatch."""
94
+ if not server_final.startswith("v="):
95
+ raise SpydProtocolError("the server did not send a SCRAM signature")
96
+ expected = hmac.new(self._server_key, self._auth_message, hashlib.sha256).digest()
97
+ received = _unb64(server_final[2:])
98
+ if len(received) != len(expected) or not hmac.compare_digest(received, expected):
99
+ raise SpydAuthenticationError("the server signature does not match")
100
+
101
+ def _nonce(self) -> str:
102
+ marker = "r="
103
+ index = self.client_first_bare.find(marker)
104
+ if index < 0:
105
+ return ""
106
+ return self.client_first_bare[index + len(marker):]
107
+
108
+
109
+ __all__ = ["ScramClient"]