codeasier-gitcode-mcp 0.3.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,431 @@
1
+ """Small, encrypted OAuth store for a single-worker HTTP deployment.
2
+
3
+ Only ciphertext and hashes of caller-supplied keys reach SQLite. Transactions are
4
+ synchronous and must not span an ``await``. Keeping the database and its Fernet
5
+ key together in a backup is necessary to restore existing authorizations.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import math
13
+ import os
14
+ import sqlite3
15
+ import stat
16
+ import threading
17
+ import time
18
+ from collections.abc import Iterator
19
+ from contextlib import contextmanager
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from cryptography.fernet import Fernet, InvalidToken
24
+
25
+ _MARKER = b"codeasier-gitcode-mcp.oauth-store.v1"
26
+ _CLEANUP_BATCH_SIZE = 100
27
+ _SIDECAR_SUFFIXES = ("-journal", "-wal", "-shm")
28
+ _PENDING_KINDS = frozenset({"flow", "state", "consent"})
29
+
30
+
31
+ class OAuthStoreError(RuntimeError):
32
+ """Storage failed; messages never include keys, payloads, paths or SQL."""
33
+
34
+
35
+ def _record_key(kind: str, key: str) -> tuple[str, str]:
36
+ if not isinstance(kind, str) or not kind or len(kind) > 128 or "\x00" in kind:
37
+ raise OAuthStoreError("OAuth storage record kind is invalid.")
38
+ if not isinstance(key, str) or not key:
39
+ raise OAuthStoreError("OAuth storage record key is invalid.")
40
+ try:
41
+ kind.encode("utf-8")
42
+ return kind, hashlib.sha256(key.encode("utf-8")).hexdigest()
43
+ except UnicodeError:
44
+ raise OAuthStoreError("OAuth storage record key is invalid.") from None
45
+
46
+
47
+ def _expiry(value: float) -> float:
48
+ if isinstance(value, bool):
49
+ raise OAuthStoreError("OAuth storage expiration is invalid.")
50
+ try:
51
+ result = float(value)
52
+ except (TypeError, ValueError, OverflowError):
53
+ raise OAuthStoreError("OAuth storage expiration is invalid.") from None
54
+ if not math.isfinite(result):
55
+ raise OAuthStoreError("OAuth storage expiration is invalid.")
56
+ return result
57
+
58
+
59
+ def _prepare_parent(path: Path) -> None:
60
+ """Create only missing directories; never chmod an existing ancestor."""
61
+ for directory in reversed(path.parent.parents):
62
+ _ensure_directory(directory)
63
+ _ensure_directory(path.parent)
64
+
65
+
66
+ def _ensure_directory(path: Path) -> None:
67
+ try:
68
+ info = path.lstat()
69
+ except FileNotFoundError:
70
+ try:
71
+ path.mkdir(mode=0o700)
72
+ except FileExistsError:
73
+ # A concurrent creator still has to pass the checks below.
74
+ pass
75
+ info = path.lstat()
76
+ if not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode):
77
+ raise OAuthStoreError("OAuth storage requires real directories, not symlinks.")
78
+
79
+
80
+ def _open_private_file(path: Path, *, create: bool) -> int:
81
+ """Open without following a final symlink, including broken symlinks."""
82
+ try:
83
+ before = path.lstat()
84
+ except FileNotFoundError:
85
+ before = None
86
+ if before is not None and (not stat.S_ISREG(before.st_mode) or before.st_nlink != 1):
87
+ raise OAuthStoreError(
88
+ "OAuth storage requires a regular file without symlinks or hard links."
89
+ )
90
+ flags = os.O_RDWR | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
91
+ if create and before is None:
92
+ flags |= os.O_CREAT | os.O_EXCL
93
+ descriptor = os.open(path, flags, 0o600)
94
+ try:
95
+ info = os.fstat(descriptor)
96
+ after = path.lstat()
97
+ if (
98
+ not stat.S_ISREG(info.st_mode)
99
+ or info.st_nlink != 1
100
+ or not stat.S_ISREG(after.st_mode)
101
+ or (info.st_dev, info.st_ino) != (after.st_dev, after.st_ino)
102
+ or (before is not None and (before.st_dev, before.st_ino) != (info.st_dev, info.st_ino))
103
+ ):
104
+ raise OAuthStoreError("OAuth storage file changed while opening it.")
105
+ os.fchmod(descriptor, 0o600)
106
+ return descriptor
107
+ except BaseException:
108
+ os.close(descriptor)
109
+ raise
110
+
111
+
112
+ class OAuthTransaction:
113
+ """Operations valid only inside the transaction which created this object."""
114
+
115
+ def __init__(self, store: OAuthStore) -> None:
116
+ self._store = store
117
+ self._thread = threading.get_ident()
118
+ self._active = True
119
+
120
+ def _connection(self) -> sqlite3.Connection:
121
+ if not self._active or self._thread != threading.get_ident():
122
+ raise OAuthStoreError("OAuth storage transaction is no longer active in this thread.")
123
+ return self._store._connection()
124
+
125
+ def get(self, kind: str, key: str) -> dict[str, Any] | None:
126
+ connection = self._connection()
127
+ kind, digest = _record_key(kind, key)
128
+ row = connection.execute(
129
+ "SELECT value, expires FROM oauth_records WHERE kind = ? AND key = ?",
130
+ (kind, digest),
131
+ ).fetchone()
132
+ if row is None:
133
+ return None
134
+ encrypted, expires = row
135
+ expires = _expiry(expires)
136
+ if expires <= time.time():
137
+ connection.execute(
138
+ "DELETE FROM oauth_records WHERE kind = ? AND key = ?", (kind, digest)
139
+ )
140
+ return None
141
+ return self._store._decrypt_record(kind, digest, encrypted, expires)
142
+
143
+ def put(self, kind: str, key: str, payload: dict[str, Any], expires_at: float) -> None:
144
+ connection = self._connection()
145
+ kind, digest = _record_key(kind, key)
146
+ expires = _expiry(expires_at)
147
+ encrypted = self._store._encrypt_record(kind, digest, payload, expires)
148
+ exists = connection.execute(
149
+ "SELECT 1 FROM oauth_records WHERE kind = ? AND key = ?", (kind, digest)
150
+ ).fetchone()
151
+ if exists is None:
152
+ count = connection.execute("SELECT COUNT(*) FROM oauth_records").fetchone()[0]
153
+ if count >= self._store.max_records:
154
+ raise OAuthStoreError("OAuth storage capacity has been reached.")
155
+ if kind in _PENDING_KINDS:
156
+ pending = connection.execute(
157
+ "SELECT COUNT(*) FROM oauth_records WHERE kind IN ('flow', 'state', 'consent')"
158
+ ).fetchone()[0]
159
+ if pending >= self._store.max_pending_records:
160
+ raise OAuthStoreError("OAuth pending authorization capacity has been reached.")
161
+ connection.execute(
162
+ "INSERT INTO oauth_records(kind, key, value, expires) VALUES (?, ?, ?, ?) "
163
+ "ON CONFLICT(kind, key) DO UPDATE SET value = excluded.value, expires = excluded.expires",
164
+ (kind, digest, encrypted, expires),
165
+ )
166
+
167
+ def pop(self, kind: str, key: str) -> dict[str, Any] | None:
168
+ payload = self.get(kind, key)
169
+ if payload is not None:
170
+ self.delete(kind, key)
171
+ return payload
172
+
173
+ def delete(self, kind: str, key: str) -> None:
174
+ connection = self._connection()
175
+ kind, digest = _record_key(kind, key)
176
+ connection.execute("DELETE FROM oauth_records WHERE kind = ? AND key = ?", (kind, digest))
177
+
178
+
179
+ class OAuthStore:
180
+ """SQLite + Fernet persistence, with atomic, serialized transactions.
181
+
182
+ ``path`` must be absolute. New directories have mode 0700 and the database
183
+ has mode 0600. Existing parent permissions are not changed. SQLite's DELETE
184
+ journal inherits the private database permissions and is removed on commit.
185
+ Existing symlinks or hard links at the database or sidecar paths are refused.
186
+ Pending login records have a separate, smaller quota so unauthenticated
187
+ authorization attempts cannot fill the space reserved for existing grants.
188
+ """
189
+
190
+ def __init__(
191
+ self,
192
+ path: str | Path,
193
+ encryption_key: str,
194
+ *,
195
+ max_records: int = 10000,
196
+ max_pending_records: int = 256,
197
+ ) -> None:
198
+ self._lock = threading.RLock()
199
+ self._db: sqlite3.Connection | None = None
200
+ self._in_transaction = False
201
+ if isinstance(max_records, bool) or not isinstance(max_records, int) or max_records < 1:
202
+ raise OAuthStoreError("OAuth storage capacity must be a positive integer.")
203
+ if (
204
+ isinstance(max_pending_records, bool)
205
+ or not isinstance(max_pending_records, int)
206
+ or max_pending_records < 1
207
+ ):
208
+ raise OAuthStoreError(
209
+ "OAuth pending authorization capacity must be a positive integer."
210
+ )
211
+ self.max_records = max_records
212
+ self.max_pending_records = min(max_pending_records, max_records)
213
+ try:
214
+ if not isinstance(encryption_key, str):
215
+ raise ValueError
216
+ self._fernet = Fernet(encryption_key.encode("ascii"))
217
+ except (TypeError, ValueError, UnicodeError):
218
+ raise OAuthStoreError("OAuth storage encryption key is invalid.") from None
219
+ try:
220
+ self.path = Path(path)
221
+ if not self.path.is_absolute() or ".." in self.path.parts or "\x00" in str(self.path):
222
+ raise OAuthStoreError("OAuth storage requires a fixed absolute database path.")
223
+ _prepare_parent(self.path)
224
+ descriptor = _open_private_file(self.path, create=True)
225
+ try:
226
+ info = os.fstat(descriptor)
227
+ self._identity = (info.st_dev, info.st_ino)
228
+ was_empty = info.st_size == 0
229
+ self._check_files()
230
+ # mode=rw prevents SQLite from silently creating a replacement path.
231
+ self._db = sqlite3.connect(
232
+ self.path.as_uri() + "?mode=rw",
233
+ uri=True,
234
+ isolation_level=None,
235
+ check_same_thread=False,
236
+ timeout=5,
237
+ )
238
+ self._check_files()
239
+ finally:
240
+ os.close(descriptor)
241
+ connection = self._connection()
242
+ connection.execute("PRAGMA trusted_schema = OFF")
243
+ connection.execute("PRAGMA temp_store = MEMORY")
244
+ connection.execute("PRAGMA secure_delete = ON")
245
+ connection.execute("PRAGMA synchronous = FULL")
246
+ mode = connection.execute("PRAGMA journal_mode = DELETE").fetchone()[0]
247
+ if mode.lower() != "delete":
248
+ raise OAuthStoreError("OAuth storage could not enable private rollback journaling.")
249
+ self._initialize(was_empty)
250
+ except OAuthStoreError:
251
+ self.close()
252
+ raise
253
+ except (OSError, sqlite3.Error, TypeError, ValueError):
254
+ self.close()
255
+ raise OAuthStoreError("OAuth storage could not be opened securely.") from None
256
+
257
+ def _connection(self) -> sqlite3.Connection:
258
+ if self._db is None:
259
+ raise OAuthStoreError("OAuth storage is closed.")
260
+ return self._db
261
+
262
+ def _check_files(self) -> None:
263
+ info = self.path.lstat()
264
+ if (
265
+ not stat.S_ISREG(info.st_mode)
266
+ or info.st_nlink != 1
267
+ or (info.st_dev, info.st_ino) != self._identity
268
+ ):
269
+ raise OAuthStoreError("OAuth storage database path changed.")
270
+ for suffix in _SIDECAR_SUFFIXES:
271
+ sidecar = Path(str(self.path) + suffix)
272
+ try:
273
+ sidecar.lstat()
274
+ except FileNotFoundError:
275
+ continue
276
+ descriptor = _open_private_file(sidecar, create=False)
277
+ os.close(descriptor)
278
+
279
+ def _initialize(self, was_empty: bool) -> None:
280
+ connection = self._connection()
281
+ try:
282
+ connection.execute("BEGIN IMMEDIATE")
283
+ tables = {
284
+ row[0]
285
+ for row in connection.execute(
286
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
287
+ )
288
+ }
289
+ if not tables and was_empty:
290
+ connection.execute(
291
+ "CREATE TABLE oauth_metadata(id INTEGER PRIMARY KEY CHECK(id = 1), value BLOB NOT NULL)"
292
+ )
293
+ connection.execute(
294
+ "CREATE TABLE oauth_records("
295
+ "kind TEXT NOT NULL, key TEXT NOT NULL, value BLOB NOT NULL, expires REAL NOT NULL, "
296
+ "PRIMARY KEY(kind, key))"
297
+ )
298
+ connection.execute(
299
+ "CREATE INDEX oauth_records_expiration ON oauth_records(expires)"
300
+ )
301
+ connection.execute(
302
+ "INSERT INTO oauth_metadata(id, value) VALUES (1, ?)",
303
+ (self._fernet.encrypt(_MARKER),),
304
+ )
305
+ elif tables != {"oauth_metadata", "oauth_records"}:
306
+ raise OAuthStoreError("OAuth storage format is not recognized.")
307
+ marker = connection.execute("SELECT value FROM oauth_metadata WHERE id = 1").fetchone()
308
+ try:
309
+ if marker is None or self._fernet.decrypt(marker[0]) != _MARKER:
310
+ raise InvalidToken
311
+ except (InvalidToken, TypeError, ValueError):
312
+ raise OAuthStoreError(
313
+ "OAuth storage encryption key does not match or metadata is damaged."
314
+ ) from None
315
+ self._cleanup_expired(connection)
316
+ connection.commit()
317
+ except BaseException:
318
+ self._rollback()
319
+ raise
320
+
321
+ def _cleanup_expired(self, connection: sqlite3.Connection) -> None:
322
+ connection.execute(
323
+ "DELETE FROM oauth_records WHERE rowid IN ("
324
+ "SELECT rowid FROM oauth_records WHERE expires <= ? ORDER BY expires LIMIT ?)",
325
+ (time.time(), _CLEANUP_BATCH_SIZE),
326
+ )
327
+
328
+ def _encrypt_record(
329
+ self, kind: str, digest: str, payload: dict[str, Any], expires: float
330
+ ) -> bytes:
331
+ if not isinstance(payload, dict):
332
+ raise OAuthStoreError("OAuth storage payload must be a JSON object.")
333
+ try:
334
+ encoded = json.dumps(
335
+ {"kind": kind, "key": digest, "expires": expires, "payload": payload},
336
+ ensure_ascii=True,
337
+ allow_nan=False,
338
+ separators=(",", ":"),
339
+ ).encode("utf-8")
340
+ except (TypeError, ValueError, OverflowError, RecursionError):
341
+ raise OAuthStoreError("OAuth storage payload must be a JSON object.") from None
342
+ return self._fernet.encrypt(encoded)
343
+
344
+ def _decrypt_record(
345
+ self, kind: str, digest: str, encrypted: bytes, expires: float
346
+ ) -> dict[str, Any]:
347
+ try:
348
+ envelope = json.loads(self._fernet.decrypt(encrypted))
349
+ if (
350
+ not isinstance(envelope, dict)
351
+ or set(envelope) != {"kind", "key", "expires", "payload"}
352
+ or envelope["kind"] != kind
353
+ or envelope["key"] != digest
354
+ or envelope["expires"] != expires
355
+ or not isinstance(envelope["payload"], dict)
356
+ ):
357
+ raise ValueError
358
+ return envelope["payload"]
359
+ except (InvalidToken, TypeError, ValueError, UnicodeError, RecursionError):
360
+ raise OAuthStoreError(
361
+ "OAuth storage ciphertext is damaged or belongs to another record."
362
+ ) from None
363
+
364
+ def _rollback(self) -> None:
365
+ connection = self._connection()
366
+ try:
367
+ if connection.in_transaction:
368
+ connection.rollback()
369
+ except sqlite3.Error:
370
+ try:
371
+ connection.close()
372
+ finally:
373
+ self._db = None
374
+ raise OAuthStoreError(
375
+ "OAuth storage rollback failed; reopen the store before use."
376
+ ) from None
377
+
378
+ @contextmanager
379
+ def transaction(self) -> Iterator[OAuthTransaction]:
380
+ """Hold the lock and a write transaction; never await within this block."""
381
+ with self._lock:
382
+ connection = self._connection()
383
+ if self._in_transaction:
384
+ raise OAuthStoreError("Nested OAuth storage transactions are not supported.")
385
+ transaction: OAuthTransaction | None = None
386
+ try:
387
+ self._check_files()
388
+ connection.execute("BEGIN IMMEDIATE")
389
+ self._in_transaction = True
390
+ transaction = OAuthTransaction(self)
391
+ self._cleanup_expired(connection)
392
+ yield transaction
393
+ connection.commit()
394
+ except (OSError, sqlite3.Error):
395
+ self._rollback()
396
+ raise OAuthStoreError("OAuth storage transaction failed.") from None
397
+ except BaseException:
398
+ self._rollback()
399
+ raise
400
+ finally:
401
+ if transaction is not None:
402
+ transaction._active = False
403
+ self._in_transaction = False
404
+
405
+ def get(self, kind: str, key: str) -> dict[str, Any] | None:
406
+ with self.transaction() as transaction:
407
+ return transaction.get(kind, key)
408
+
409
+ def put(self, kind: str, key: str, payload: dict[str, Any], expires_at: float) -> None:
410
+ with self.transaction() as transaction:
411
+ transaction.put(kind, key, payload, expires_at)
412
+
413
+ def pop(self, kind: str, key: str) -> dict[str, Any] | None:
414
+ with self.transaction() as transaction:
415
+ return transaction.pop(kind, key)
416
+
417
+ def delete(self, kind: str, key: str) -> None:
418
+ with self.transaction() as transaction:
419
+ transaction.delete(kind, key)
420
+
421
+ def close(self) -> None:
422
+ with self._lock:
423
+ if self._in_transaction:
424
+ raise OAuthStoreError("Cannot close OAuth storage during a transaction.")
425
+ if self._db is not None:
426
+ try:
427
+ self._db.close()
428
+ except sqlite3.Error:
429
+ raise OAuthStoreError("OAuth storage could not close cleanly.") from None
430
+ finally:
431
+ self._db = None