cinchdb 0.1.12__py3-none-any.whl → 0.1.13__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.
cinchdb/cli/main.py CHANGED
@@ -18,7 +18,7 @@ from cinchdb.cli.commands import (
18
18
 
19
19
  app = typer.Typer(
20
20
  name="cinch",
21
- help="CinchDB - A Git-like SQLite database management system",
21
+ help="CinchDB - A Git-like SQLite database management system\n\nENCRYPTION: Set CINCH_ENCRYPT_DATA=true to enable tenant database encryption.",
22
22
  add_completion=False,
23
23
  invoke_without_command=True,
24
24
  )
@@ -28,6 +28,11 @@ app = typer.Typer(
28
28
  def main(ctx: typer.Context):
29
29
  """
30
30
  CinchDB - A Git-like SQLite database management system
31
+
32
+ ENCRYPTION:
33
+ Set CINCH_ENCRYPT_DATA=true to enable tenant database encryption.
34
+ Set CINCH_ENCRYPTION_KEY=your-key to provide encryption key.
35
+ Requires SQLite3MultipleCiphers for encryption support.
31
36
  """
32
37
  if ctx.invoked_subcommand is None:
33
38
  # No subcommand was invoked, show help
@@ -6,6 +6,8 @@ from typing import Optional, Dict, List
6
6
  from contextlib import contextmanager
7
7
  from datetime import datetime
8
8
 
9
+ from cinchdb.security.encryption import encryption
10
+
9
11
 
10
12
  # Custom datetime adapter and converter for SQLite
11
13
  def adapt_datetime(dt):
@@ -42,18 +44,24 @@ class DatabaseConnection:
42
44
  # Ensure directory exists
43
45
  self.path.parent.mkdir(parents=True, exist_ok=True)
44
46
 
45
- # Connect with row factory for dict-like access
46
- # detect_types=PARSE_DECLTYPES tells SQLite to use our registered converters
47
- self._conn = sqlite3.connect(
48
- str(self.path),
49
- detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES,
50
- )
47
+ # Use encryption if enabled, otherwise standard connection
48
+ if encryption.enabled:
49
+ self._conn = encryption.get_connection(self.path)
50
+ else:
51
+ # Connect with row factory for dict-like access
52
+ # detect_types=PARSE_DECLTYPES tells SQLite to use our registered converters
53
+ self._conn = sqlite3.connect(
54
+ str(self.path),
55
+ detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES,
56
+ )
57
+
58
+ # Configure WAL mode and settings (encryption module handles this if enabled)
59
+ self._conn.execute("PRAGMA journal_mode = WAL")
60
+ self._conn.execute("PRAGMA synchronous = NORMAL")
61
+ self._conn.execute("PRAGMA wal_autocheckpoint = 0")
62
+
63
+ # Always set row factory and foreign keys
51
64
  self._conn.row_factory = sqlite3.Row
52
-
53
- # Configure WAL mode and settings
54
- self._conn.execute("PRAGMA journal_mode = WAL")
55
- self._conn.execute("PRAGMA synchronous = NORMAL")
56
- self._conn.execute("PRAGMA wal_autocheckpoint = 0")
57
65
  self._conn.execute("PRAGMA foreign_keys = ON")
58
66
  self._conn.commit()
59
67
 
@@ -0,0 +1 @@
1
+ """Security module for CinchDB encryption."""
@@ -0,0 +1,108 @@
1
+ """Simple SQLite encryption using environment variables with KMS upgrade path."""
2
+
3
+ import os
4
+ import sqlite3
5
+ import logging
6
+ from pathlib import Path
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class SQLiteEncryption:
12
+ """Simple SQLite encryption with static keys and KMS upgrade path."""
13
+
14
+ def __init__(self):
15
+ # Encryption is optional for open source users
16
+ self.enabled = os.getenv("CINCH_ENCRYPT_DATA", "false").lower() == "true"
17
+ self._encryption_key = None
18
+
19
+ if self.enabled:
20
+ self._encryption_key = self._get_encryption_key()
21
+
22
+ def _get_encryption_key(self) -> str:
23
+ """Get encryption key with future KMS support."""
24
+
25
+ # Future KMS support - check for KMS configuration first
26
+ kms_provider = os.getenv("CINCH_KMS_PROVIDER")
27
+ if kms_provider:
28
+ # TODO: Implement KMS key retrieval
29
+ # return self._get_key_from_kms(kms_provider)
30
+ logger.warning("KMS provider configured but not implemented yet")
31
+
32
+ # Require explicit key
33
+ static_key = os.getenv("CINCH_ENCRYPTION_KEY")
34
+ if static_key:
35
+ return static_key
36
+
37
+ # Fail fast if no key provided
38
+ raise ValueError(
39
+ "CINCH_ENCRYPTION_KEY environment variable is required when CINCH_ENCRYPT_DATA=true. "
40
+ "Generate a key with: python -c \"import secrets; print(secrets.token_urlsafe(32))\""
41
+ )
42
+
43
+ def get_connection(self, db_path: Path) -> sqlite3.Connection:
44
+ """Get SQLite connection with optional encryption."""
45
+ # Connect with datetime parsing support
46
+ conn = sqlite3.connect(
47
+ str(db_path),
48
+ detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES,
49
+ )
50
+
51
+ if self.enabled and self._encryption_key:
52
+ try:
53
+ # Apply encryption key
54
+ conn.execute(f"PRAGMA key = '{self._encryption_key}'")
55
+
56
+ # Configure recommended cipher (ChaCha20-Poly1305) if supported
57
+ try:
58
+ conn.execute("PRAGMA cipher = 'chacha20'")
59
+ except sqlite3.OperationalError:
60
+ # Fallback to default cipher if ChaCha20 not available
61
+ logger.debug("ChaCha20 cipher not available, using default")
62
+
63
+ # Security hardening
64
+ conn.execute("PRAGMA temp_store = MEMORY") # Encrypt temp data
65
+ conn.execute("PRAGMA secure_delete = ON") # Overwrite deleted data
66
+
67
+ except sqlite3.OperationalError as e:
68
+ logger.error(f"Failed to apply encryption to {db_path}: {e}")
69
+ # Close connection and re-raise with helpful message
70
+ conn.close()
71
+ raise sqlite3.OperationalError(
72
+ f"Failed to apply encryption. Make sure SQLite3MultipleCiphers is installed. Error: {e}"
73
+ ) from e
74
+
75
+ # Standard SQLite optimizations
76
+ conn.execute("PRAGMA journal_mode = WAL")
77
+ conn.execute("PRAGMA synchronous = NORMAL")
78
+ conn.execute("PRAGMA cache_size = -2000")
79
+
80
+ return conn
81
+
82
+ def is_encrypted(self, db_path: Path) -> bool:
83
+ """Check if database file is encrypted."""
84
+ if not db_path.exists():
85
+ return False
86
+
87
+ try:
88
+ # Try to open without key
89
+ test_conn = sqlite3.connect(str(db_path))
90
+ test_conn.execute("SELECT name FROM sqlite_master LIMIT 1")
91
+ test_conn.close()
92
+ return False # Successfully opened = not encrypted
93
+ except sqlite3.DatabaseError:
94
+ return True # Failed to open = likely encrypted
95
+
96
+ def test_encryption_support(self) -> bool:
97
+ """Test if SQLite encryption is available."""
98
+ try:
99
+ conn = sqlite3.connect(':memory:')
100
+ conn.execute("PRAGMA key = 'test'")
101
+ conn.close()
102
+ return True
103
+ except sqlite3.OperationalError:
104
+ return False
105
+
106
+
107
+ # Global instance for easy access
108
+ encryption = SQLiteEncryption()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cinchdb
3
- Version: 0.1.12
3
+ Version: 0.1.13
4
4
  Summary: A Git-like SQLite database management system with branching and multi-tenancy
5
5
  Project-URL: Homepage, https://github.com/russellromney/cinchdb
6
6
  Project-URL: Documentation, https://russellromney.github.io/cinchdb
@@ -23,6 +23,8 @@ Requires-Dist: requests>=2.28.0
23
23
  Requires-Dist: rich>=13.0.0
24
24
  Requires-Dist: toml>=0.10.0
25
25
  Requires-Dist: typer>=0.9.0
26
+ Provides-Extra: encryption
27
+ Requires-Dist: pysqlcipher3>=1.2.0; extra == 'encryption'
26
28
  Description-Content-Type: text/markdown
27
29
 
28
30
  # CinchDB
@@ -154,6 +156,25 @@ db.update("posts", post_id, {"content": "Updated content"})
154
156
  - **Python SDK**: Core functionality for local development
155
157
  - **CLI**: Full-featured command-line interface
156
158
 
159
+ ## Security & Encryption
160
+
161
+ Optional transparent encryption for tenant databases:
162
+
163
+ ```bash
164
+ # Enable encryption
165
+ export CINCH_ENCRYPT_DATA=true
166
+ export CINCH_ENCRYPTION_KEY="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')"
167
+
168
+ # Install encryption library
169
+ pip install pysqlcipher3
170
+ ```
171
+
172
+ - **Tenant databases**: Encrypted with ChaCha20-Poly1305 (~2-5% overhead)
173
+ - **Metadata**: Unencrypted for operational simplicity
174
+ - **Integration**: Transparent - no code changes needed
175
+
176
+ Works without encryption libraries - gracefully falls back to standard SQLite.
177
+
157
178
  ## Development
158
179
 
159
180
  ```bash
@@ -2,7 +2,7 @@ cinchdb/__init__.py,sha256=NZdSzfhRguSBTjJ2dcESOQYy53OZEuBndlB7U08GMY0,179
2
2
  cinchdb/__main__.py,sha256=OpkDqn9zkTZhhYgvv_grswWLAHKbmxs4M-8C6Z5HfWY,85
3
3
  cinchdb/config.py,sha256=gocjMnYKLWhgvnteo6zprgwtK6Oevoxq547J_v-C9Ns,5265
4
4
  cinchdb/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
- cinchdb/cli/main.py,sha256=iAh19hD4uiWmQmvGS6gZD7WodLxoYUXK8lsZsf7BJdA,4461
5
+ cinchdb/cli/main.py,sha256=G26O3EqOaKwOfwkOXOfp2XgyS5fslMgKidOAgW5k6qU,4764
6
6
  cinchdb/cli/utils.py,sha256=InAGuo7uENvsfBQu6EKIbbiNXqmvg-BecLmhLvOz5qg,6485
7
7
  cinchdb/cli/commands/__init__.py,sha256=IRUIPHgdpF4hBDbDy0SgaWn39o5GNUjH54_C42sjlQg,273
8
8
  cinchdb/cli/commands/branch.py,sha256=Nz8YQYJ7lizSXEAv0usTx85TDOC-N5Ul9KIxN8JQtKc,17973
@@ -18,7 +18,7 @@ cinchdb/cli/commands/view.py,sha256=ZmS1IW7idzzHAXmgVyY3C4IQRo7toHb6fHNFY_tQJjI,
18
18
  cinchdb/cli/handlers/__init__.py,sha256=f2f-Cc96rSBLbVsiIbf-b4pZCKZoHfmhNEvnZ0OurRs,131
19
19
  cinchdb/cli/handlers/codegen_handler.py,sha256=i5we_AbiUW3zfO6pIKWxvtO8OvOqz3H__4xPmTLEuQM,6524
20
20
  cinchdb/core/__init__.py,sha256=iNlT0iO9cM0HLoYwzBavUBoXRh1Tcnz1l_vfbwVxK_Q,246
21
- cinchdb/core/connection.py,sha256=SlKyEfIpeaDws8M6SfEbvCEVnt26zBY1RYwHtTXj0kY,5110
21
+ cinchdb/core/connection.py,sha256=x_xMJv1DiZtWjBoSa2rJSGHs_m6pbtk2JYIYTdeWMtE,5491
22
22
  cinchdb/core/database.py,sha256=vzVr6Y6iydf9kOU0OO7yVYoHQJ3zlfwAWF2LylJUV0I,27162
23
23
  cinchdb/core/initializer.py,sha256=CAzq947plgEF-KXV-PD-ycJ8Zy4zXCQqCrmQ0-pV0i4,14474
24
24
  cinchdb/core/maintenance.py,sha256=PAgrSL7Cj9p3rKHV0h_L7gupN6nLD0-5eQpJZNiqyEs,2097
@@ -48,11 +48,13 @@ cinchdb/models/project.py,sha256=6GMXUZUsEIebqQJgRXIthWzpWKuNNmJ3drgI1vFDrMo,644
48
48
  cinchdb/models/table.py,sha256=nxf__C_YvDOW-6-vdOQ4xKmwWPZwgEdYw1I4mO_C44o,2955
49
49
  cinchdb/models/tenant.py,sha256=wTvGoO_tQdtueVB0faZFVIhSjh_DNJzywflrUpngWTM,1072
50
50
  cinchdb/models/view.py,sha256=q6j-jYzFJuhRJO87rKt6Uv8hOizHQx8xwoPKoH6XnNY,530
51
+ cinchdb/security/__init__.py,sha256=GWV6OIczkPhJazLvMFcT54aDUI6_mU9MTZu09TEGrJ0,45
52
+ cinchdb/security/encryption.py,sha256=nEmjNot2NyJZivrsf4jYB9Ei-LJdb2_O6BfXsO9-pww,4168
51
53
  cinchdb/utils/__init__.py,sha256=yQQhEjndDiB2SUJybUmp9dvEOQKiR-GySe-WiCius5E,490
52
54
  cinchdb/utils/name_validator.py,sha256=dyGX5bjlTFRA9EGrWRQKp6kR__HSV04hLV5VueJs4IQ,4027
53
55
  cinchdb/utils/sql_validator.py,sha256=aWOGlPX0gBkuR6R1EBP2stbP4PHZuI6FUBi2Ljx7JUI,5815
54
- cinchdb-0.1.12.dist-info/METADATA,sha256=iXOb9UnRYHZJ4gG4j9c_Z8Oxk-hvVdsgXWdFNk49IBo,5471
55
- cinchdb-0.1.12.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
56
- cinchdb-0.1.12.dist-info/entry_points.txt,sha256=VBOIzvnGbkKudMCCmNORS3885QSyjZUVKJQ-Syqa62w,47
57
- cinchdb-0.1.12.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
58
- cinchdb-0.1.12.dist-info/RECORD,,
56
+ cinchdb-0.1.13.dist-info/METADATA,sha256=hhBYsukXvnx0Kh8GnQ4943zFJ7AFkiVX_Sm7vDQYg98,6116
57
+ cinchdb-0.1.13.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
58
+ cinchdb-0.1.13.dist-info/entry_points.txt,sha256=VBOIzvnGbkKudMCCmNORS3885QSyjZUVKJQ-Syqa62w,47
59
+ cinchdb-0.1.13.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
60
+ cinchdb-0.1.13.dist-info/RECORD,,