gitcx 0.1.0a3__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.
gitcx/catalog.py ADDED
@@ -0,0 +1,470 @@
1
+ """SQLite platform metadata and transactional, secret-free audit/outbox records."""
2
+
3
+ from contextlib import contextmanager
4
+ from dataclasses import dataclass
5
+ from enum import StrEnum
6
+ import os
7
+ import json
8
+ from pathlib import Path
9
+ import sqlite3
10
+ import stat
11
+ import uuid
12
+
13
+ from .domain import AccessGrant, Action, Membership, OrganizationRole, Owner, OwnerKind, Permission, Principal, RepositoryRecord, Slug, StorageId, Visibility, identifier
14
+ from .permissions import PermissionDenied, require_permission, require_scope, scope_allows
15
+ from .branch_policy import BranchPolicy, BranchRule, MAX_BRANCH_RULES, ref_pattern
16
+
17
+
18
+ APPLICATION_ID = 0x47434154
19
+ SCHEMA_VERSION = 6
20
+ MIGRATIONS = {
21
+ 1: (
22
+ "CREATE TABLE owners (id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK(kind IN ('user','organization')), slug TEXT NOT NULL UNIQUE)",
23
+ "CREATE TABLE memberships (organization_id TEXT NOT NULL REFERENCES owners(id), user_id TEXT NOT NULL REFERENCES owners(id), role TEXT NOT NULL CHECK(role IN ('owner','member')), PRIMARY KEY(organization_id,user_id))",
24
+ "CREATE TABLE repositories (id TEXT PRIMARY KEY, owner_id TEXT NOT NULL REFERENCES owners(id), slug TEXT NOT NULL, storage_id TEXT NOT NULL UNIQUE, visibility TEXT NOT NULL CHECK(visibility IN ('private','public')), object_format TEXT NOT NULL CHECK(object_format IN ('sha1','sha256')), UNIQUE(owner_id,slug))",
25
+ "CREATE TABLE grants (repository_id TEXT NOT NULL REFERENCES repositories(id), user_id TEXT NOT NULL REFERENCES owners(id), permission INTEGER NOT NULL CHECK(permission BETWEEN 1 AND 3), PRIMARY KEY(repository_id,user_id))",
26
+ "CREATE TABLE credentials (id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES owners(id), verifier BLOB NOT NULL CHECK(length(verifier)=32), created_at INTEGER NOT NULL, expires_at INTEGER, revoked_at INTEGER)",
27
+ ),
28
+ 2: (
29
+ "CREATE TABLE audit_events (sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, actor_id TEXT, resource_id TEXT NOT NULL, timestamp INTEGER NOT NULL)",
30
+ "CREATE INDEX audit_resource ON audit_events(resource_id,sequence)",
31
+ "CREATE TABLE outbox (sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, event_id TEXT NOT NULL UNIQUE REFERENCES audit_events(id), kind TEXT NOT NULL CHECK(kind IN ('catalog.changed','repository.index')), resource_id TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0 CHECK(done IN (0,1)))",
32
+ "CREATE INDEX outbox_pending ON outbox(done,sequence)",
33
+ ),
34
+ 3: ("CREATE TABLE provisioning (repository_id TEXT PRIMARY KEY REFERENCES repositories(id), state TEXT NOT NULL CHECK(state IN ('pending','ready')))",),
35
+ 4: ("CREATE TABLE credential_scopes (credential_id TEXT NOT NULL REFERENCES credentials(id), action TEXT NOT NULL CHECK(action IN ('read','write','admin')), PRIMARY KEY(credential_id,action))",),
36
+ 5: (
37
+ "CREATE TABLE ref_policy_versions (repository_id TEXT PRIMARY KEY REFERENCES repositories(id), version INTEGER NOT NULL CHECK(version>=0))",
38
+ "CREATE TABLE branch_rules (repository_id TEXT NOT NULL REFERENCES repositories(id), pattern TEXT NOT NULL, allow_create INTEGER NOT NULL CHECK(allow_create IN (0,1)), allow_delete INTEGER NOT NULL CHECK(allow_delete IN (0,1)), allow_force INTEGER NOT NULL CHECK(allow_force IN (0,1)), require_review INTEGER NOT NULL CHECK(require_review IN (0,1)), minimum_permission INTEGER NOT NULL CHECK(minimum_permission IN (2,3)), PRIMARY KEY(repository_id,pattern))",
39
+ ),
40
+ 6: (
41
+ "CREATE TABLE receive_operations (id TEXT PRIMARY KEY, repository_id TEXT NOT NULL REFERENCES repositories(id), actor_id TEXT NOT NULL REFERENCES owners(id), created_at INTEGER NOT NULL, status TEXT NOT NULL CHECK(status IN ('prepared','completed','rejected','unknown')), commands TEXT NOT NULL, result TEXT)",
42
+ "CREATE INDEX receive_repository ON receive_operations(repository_id,created_at,id)",
43
+ ),
44
+ }
45
+
46
+
47
+ class CatalogError(Exception):
48
+ """A catalog cannot be opened or changed as requested."""
49
+
50
+
51
+ class CatalogConflict(CatalogError):
52
+ """A uniqueness or lifecycle invariant rejected a change."""
53
+
54
+
55
+ class EventKind(StrEnum):
56
+ ACCOUNT_CREATED = "account.created"
57
+ ORGANIZATION_CREATED = "organization.created"
58
+ MEMBERSHIP_CHANGED = "membership.changed"
59
+ REPOSITORY_CREATED = "repository.created"
60
+ REPOSITORY_READY = "repository.ready"
61
+ GRANT_CHANGED = "grant.changed"
62
+ CREDENTIAL_CREATED = "credential.created"
63
+ CREDENTIAL_REVOKED = "credential.revoked"
64
+ REF_POLICY_CHANGED = "ref-policy.changed"
65
+ RECEIVE_PREPARED = "receive.prepared"
66
+ RECEIVE_ACCEPTED = "receive.accepted"
67
+ RECEIVE_REJECTED = "receive.rejected"
68
+ RECEIVE_INTERRUPTED = "receive.interrupted"
69
+ RECEIVE_RECOVERED = "receive.recovered"
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class AuditEvent:
74
+ sequence: int
75
+ id: str
76
+ kind: EventKind
77
+ actor_id: str | None
78
+ resource_id: str
79
+ timestamp: int
80
+
81
+
82
+ @dataclass(frozen=True, slots=True)
83
+ class OutboxJob:
84
+ sequence: int
85
+ id: str
86
+ event_id: str
87
+ kind: str
88
+ resource_id: str
89
+
90
+
91
+ @dataclass(frozen=True, slots=True)
92
+ class CredentialMetadata:
93
+ id: str
94
+ user_id: str
95
+ created_at: int
96
+ expires_at: int | None = None
97
+ revoked_at: int | None = None
98
+
99
+ def __post_init__(self):
100
+ identifier(self.id); identifier(self.user_id)
101
+ for value in (self.created_at, self.expires_at, self.revoked_at):
102
+ if value is not None:
103
+ timestamp(value)
104
+ if self.expires_at is not None and self.expires_at <= self.created_at:
105
+ raise ValueError("credential expiry must follow its creation")
106
+ if self.revoked_at is not None and self.revoked_at < self.created_at:
107
+ raise ValueError("credential revocation cannot precede its creation")
108
+
109
+
110
+ def timestamp(value):
111
+ if type(value) is not int or not 0 <= value <= 0x7fffffffffffffff:
112
+ raise ValueError("timestamps must be nonnegative SQLite integers")
113
+
114
+
115
+ def page(limit, after):
116
+ if type(limit) is not int or not 1 <= limit <= 100 or type(after) is not int or not 0 <= after <= 0x7fffffffffffffff:
117
+ raise ValueError("pages require a limit of 1–100 and a nonnegative cursor")
118
+
119
+
120
+ class Catalog:
121
+ """Trusted local catalog handle, not an authenticated HTTP/service surface.
122
+
123
+ One connection per thread. Repository query/mutation methods enforce the
124
+ shared permission policy; bootstrap and outbox methods are trusted duties.
125
+ """
126
+
127
+ def __init__(self, path, *, timeout: float = 5.0):
128
+ self.path = Path(path).absolute()
129
+ if not 0 <= timeout <= 30:
130
+ raise ValueError("catalog lock timeout must be between 0 and 30 seconds")
131
+ self.path.parent.mkdir(parents=True, exist_ok=True)
132
+ for target in (self.path.parent, self.path, *(Path(str(self.path) + suffix) for suffix in ("-journal", "-wal", "-shm"))):
133
+ if target.is_symlink():
134
+ raise CatalogError("catalog paths must not be symlinks")
135
+ if target != self.path.parent and target.exists() and not stat.S_ISREG(target.stat().st_mode):
136
+ raise CatalogError("catalog files must be regular files")
137
+ try:
138
+ fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
139
+ except FileExistsError:
140
+ pass
141
+ else:
142
+ os.close(fd)
143
+ self._connection = sqlite3.connect(self.path, isolation_level=None, timeout=timeout)
144
+ self._connection.row_factory = sqlite3.Row
145
+ self._savepoint = 0
146
+ try:
147
+ self._connection.execute("PRAGMA foreign_keys=ON")
148
+ self._connection.execute("PRAGMA synchronous=FULL")
149
+ self._migrate()
150
+ except BaseException:
151
+ self.close()
152
+ raise
153
+
154
+ def __enter__(self):return self
155
+
156
+ def __exit__(self, *exc):self.close()
157
+
158
+ def close(self):self._connection.close()
159
+
160
+ @contextmanager
161
+ def transaction(self):
162
+ nested = self._connection.in_transaction
163
+ self._savepoint += 1
164
+ name = f"catalog_{self._savepoint}"
165
+ self._connection.execute(f"SAVEPOINT {name}" if nested else "BEGIN IMMEDIATE")
166
+ try:
167
+ yield self
168
+ self._connection.execute(f"RELEASE {name}" if nested else "COMMIT")
169
+ except BaseException as error:
170
+ if self._connection.in_transaction:
171
+ if nested:
172
+ self._connection.execute(f"ROLLBACK TO {name}")
173
+ self._connection.execute(f"RELEASE {name}")
174
+ else:
175
+ self._connection.execute("ROLLBACK")
176
+ if isinstance(error, sqlite3.IntegrityError):
177
+ raise CatalogConflict("catalog constraint rejected the change") from error
178
+ raise
179
+
180
+ @contextmanager
181
+ def _snapshot(self):
182
+ if self._connection.in_transaction:
183
+ yield
184
+ return
185
+ self._connection.execute("BEGIN")
186
+ try:
187
+ yield
188
+ finally:
189
+ self._connection.execute("ROLLBACK")
190
+
191
+ def _migrate(self):
192
+ with self.transaction():
193
+ app = self._connection.execute("PRAGMA application_id").fetchone()[0]
194
+ version = self._connection.execute("PRAGMA user_version").fetchone()[0]
195
+ tables = self._connection.execute("SELECT 1 FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' LIMIT 1").fetchone()
196
+ if app not in (0, APPLICATION_ID) or (app == 0 and (version or tables)):
197
+ raise CatalogError("database is not an initialized Gitcx catalog")
198
+ if not 0 <= version <= SCHEMA_VERSION:
199
+ raise CatalogError("catalog schema version is newer than this application")
200
+ if version == 0 and tables:
201
+ raise CatalogError("unversioned catalog has existing schema")
202
+ for target in range(version + 1, SCHEMA_VERSION + 1):
203
+ for statement in MIGRATIONS[target]:
204
+ self._connection.execute(statement)
205
+ self._connection.execute(f"PRAGMA user_version={target}")
206
+ self._connection.execute(f"PRAGMA application_id={APPLICATION_ID}")
207
+ if self._connection.execute("PRAGMA foreign_key_check").fetchone() is not None:
208
+ raise CatalogError("catalog foreign-key integrity check failed")
209
+
210
+ def _event(self, kind, actor_id, resource_id, now, *, job_kind="catalog.changed"):
211
+ timestamp(now)
212
+ event_id = uuid.uuid4().hex
213
+ self._connection.execute("INSERT INTO audit_events(id,kind,actor_id,resource_id,timestamp) VALUES(?,?,?,?,?)",
214
+ (event_id, EventKind(kind).value, actor_id, resource_id, now))
215
+ self._connection.execute("INSERT INTO outbox(id,event_id,kind,resource_id) VALUES(?,?,?,?)",
216
+ (uuid.uuid4().hex, event_id, job_kind, resource_id))
217
+
218
+ def _user(self, user_id):
219
+ if user_id is None or self._connection.execute("SELECT 1 FROM owners WHERE id=? AND kind='user'", (user_id,)).fetchone() is None:
220
+ raise PermissionDenied("authenticated account required")
221
+
222
+ def _prepare_receive(self, actor, record, commands, *, now):
223
+ """Trusted outcome bookkeeping; Git refs remain authoritative."""
224
+ with self.transaction():
225
+ self.get_repository(actor, record.id, action=Action.WRITE)
226
+ operation_id = uuid.uuid4().hex
227
+ payload = json.dumps([[c.name.decode('ascii'), c.old.hex if c.old else None, c.new.hex if c.new else None] for c in commands])
228
+ if len(payload) > 512*1024: raise ValueError('receive receipt command limit exceeded')
229
+ self._connection.execute('INSERT INTO receive_operations VALUES(?,?,?,?,?,?,NULL)',
230
+ (operation_id, record.id, actor.user_id, now, 'prepared', payload))
231
+ self._event(EventKind.RECEIVE_PREPARED, actor.user_id, record.id, now)
232
+ return operation_id
233
+
234
+ def _finish_receive(self, operation_id, result, *, now):
235
+ with self.transaction():
236
+ row = self._connection.execute('SELECT * FROM receive_operations WHERE id=?', (operation_id,)).fetchone()
237
+ if row is None: raise CatalogConflict('receive receipt is missing')
238
+ encoded = json.dumps(result, sort_keys=True)
239
+ if len(encoded) > 512*1024: raise ValueError('receive outcome limit exceeded')
240
+ states = [item['state'] for item in result['outcomes']]
241
+ status = 'unknown' if 'unknown' in states else 'completed' if states and all(s == 'accepted' for s in states) else 'rejected'
242
+ self._connection.execute('UPDATE receive_operations SET status=?,result=? WHERE id=?', (status, encoded, operation_id))
243
+ kind = EventKind.RECEIVE_ACCEPTED if status == 'completed' else EventKind.RECEIVE_INTERRUPTED if status == 'unknown' else EventKind.RECEIVE_REJECTED
244
+ self._event(kind, row['actor_id'], row['repository_id'], now,
245
+ job_kind='repository.index' if 'accepted' in states else 'catalog.changed')
246
+
247
+ def receive_operation(self, actor, operation_id):
248
+ identifier(operation_id)
249
+ with self._snapshot():
250
+ row = self._connection.execute('SELECT * FROM receive_operations WHERE id=?', (operation_id,)).fetchone()
251
+ if row is None: raise PermissionDenied('receive operation not found or permission denied')
252
+ self.get_repository(actor, row['repository_id'], action=Action.ADMIN)
253
+ return {'id': row['id'], 'repository_id': row['repository_id'], 'actor_id': row['actor_id'],
254
+ 'created_at': row['created_at'], 'status': row['status'], 'commands': json.loads(row['commands']),
255
+ 'result': json.loads(row['result']) if row['result'] else None}
256
+
257
+ def create_account(self, account_id: str, slug: Slug, *, now: int):
258
+ identifier(account_id)
259
+ if not isinstance(slug, Slug):raise TypeError("account slug must be a Slug")
260
+ with self.transaction():
261
+ self._connection.execute("INSERT INTO owners VALUES(?, 'user', ?)", (account_id, slug.value))
262
+ self._event(EventKind.ACCOUNT_CREATED, None, account_id, now)
263
+
264
+ def create_organization(self, actor: Principal, organization_id: str, slug: Slug, *, now: int):
265
+ require_scope(actor, Action.ADMIN)
266
+ identifier(organization_id)
267
+ if not isinstance(slug, Slug):raise TypeError("organization slug must be a Slug")
268
+ with self.transaction():
269
+ self._user(actor.user_id)
270
+ self._connection.execute("INSERT INTO owners VALUES(?, 'organization', ?)", (organization_id, slug.value))
271
+ self._connection.execute("INSERT INTO memberships VALUES(?,?,'owner')", (organization_id, actor.user_id))
272
+ self._event(EventKind.ORGANIZATION_CREATED, actor.user_id, organization_id, now)
273
+
274
+ def _organization_owner(self, actor, organization_id):
275
+ self._user(actor.user_id)
276
+ row = self._connection.execute("SELECT 1 FROM memberships m JOIN owners o ON o.id=m.organization_id WHERE m.organization_id=? AND m.user_id=? AND m.role='owner' AND o.kind='organization'", (organization_id, actor.user_id)).fetchone()
277
+ if row is None:raise PermissionDenied("organization not found or permission denied")
278
+
279
+ def set_membership(self, actor: Principal, membership: Membership, *, now: int):
280
+ require_scope(actor, Action.ADMIN)
281
+ with self.transaction():
282
+ self._organization_owner(actor, membership.organization_id)
283
+ self._user(membership.user_id)
284
+ if membership.role is OrganizationRole.MEMBER:
285
+ existing = self._connection.execute("SELECT role FROM memberships WHERE organization_id=? AND user_id=?", (membership.organization_id, membership.user_id)).fetchone()
286
+ count = self._connection.execute("SELECT count(*) FROM memberships WHERE organization_id=? AND role='owner'", (membership.organization_id,)).fetchone()[0]
287
+ if existing and existing[0] == 'owner' and count == 1:raise CatalogConflict("organization must retain an owner")
288
+ self._connection.execute("INSERT INTO memberships VALUES(?,?,?) ON CONFLICT(organization_id,user_id) DO UPDATE SET role=excluded.role", (membership.organization_id, membership.user_id, membership.role.value))
289
+ self._event(EventKind.MEMBERSHIP_CHANGED, actor.user_id, membership.organization_id, now)
290
+
291
+ def create_repository(self, actor: Principal, repository: RepositoryRecord, *, now: int):
292
+ require_scope(actor, Action.ADMIN)
293
+ with self.transaction():
294
+ self._user(actor.user_id)
295
+ if repository.owner.kind is OwnerKind.USER:
296
+ if repository.owner.id != actor.user_id:raise PermissionDenied("repository owner permission denied")
297
+ else:
298
+ self._organization_owner(actor, repository.owner.id)
299
+ actual_owner = self._connection.execute("SELECT kind FROM owners WHERE id=?", (repository.owner.id,)).fetchone()
300
+ if actual_owner is None or actual_owner[0] != repository.owner.kind.value:raise CatalogConflict("owner kind mismatch")
301
+ self._connection.execute("INSERT INTO repositories VALUES(?,?,?,?,?,?)", (repository.id, repository.owner.id, repository.slug.value, repository.storage_id.value, repository.visibility.value, repository.object_format))
302
+ self._event(EventKind.REPOSITORY_CREATED, actor.user_id, repository.id, now, job_kind="repository.index")
303
+
304
+ def _record(self, repository_id):
305
+ identifier(repository_id)
306
+ row = self._connection.execute("SELECT r.*,o.kind FROM repositories r JOIN owners o ON o.id=r.owner_id WHERE r.id=?", (repository_id,)).fetchone()
307
+ if row is None:raise PermissionDenied("repository not found or permission denied")
308
+ return RepositoryRecord(row['id'], Owner(row['owner_id'], row['kind']), Slug(row['slug']), StorageId(row['storage_id']), Visibility(row['visibility']), row['object_format'])
309
+
310
+ def _authorize(self, actor, record, action):
311
+ grants = tuple(AccessGrant(row['repository_id'], row['user_id'], Permission(row['permission'])) for row in self._connection.execute("SELECT * FROM grants WHERE repository_id=? AND user_id=?", (record.id, actor.user_id)))
312
+ memberships = tuple(Membership(row['organization_id'], row['user_id'], OrganizationRole(row['role'])) for row in self._connection.execute("SELECT * FROM memberships WHERE organization_id=? AND user_id=?", (record.owner.id, actor.user_id)))
313
+ require_permission(actor, record, action, grants=grants, memberships=memberships)
314
+
315
+ def get_repository(self, actor: Principal, repository_id: str, *, action: Action = Action.READ) -> RepositoryRecord:
316
+ with self._snapshot():
317
+ record = self._record(repository_id)
318
+ self._authorize(actor, record, action)
319
+ if self.provisioning_state(repository_id)=="pending":raise PermissionDenied("repository not found or permission denied")
320
+ return record
321
+
322
+ def list_repositories(self, actor: Principal, *, limit: int = 50, after: str = "", ready_only: bool = False) -> tuple[RepositoryRecord, ...]:
323
+ page(limit, 0)
324
+ if not isinstance(after, str):raise ValueError("repository cursor must be an ID string")
325
+ if after:identifier(after)
326
+ if not scope_allows(actor, Action.READ):return ()
327
+ with self._snapshot():
328
+ rows = self._connection.execute("""SELECT r.id FROM repositories r JOIN owners o ON o.id=r.owner_id LEFT JOIN provisioning p ON p.repository_id=r.id
329
+ WHERE r.id>? AND ((?=0 AND p.repository_id IS NULL) OR p.state='ready') AND (r.visibility='public' OR (o.kind='user' AND o.id=?)
330
+ OR (o.kind='organization' AND EXISTS(SELECT 1 FROM memberships m WHERE m.organization_id=o.id AND m.user_id=? AND m.role='owner'))
331
+ OR EXISTS(SELECT 1 FROM grants g WHERE g.repository_id=r.id AND g.user_id=? AND g.permission>=1))
332
+ ORDER BY r.id LIMIT ?""", (after, int(ready_only), actor.user_id, actor.user_id, actor.user_id, limit)).fetchall()
333
+ result = []
334
+ for row in rows:
335
+ record = self._record(row['id']);self._authorize(actor, record, Action.READ);result.append(record)
336
+ return tuple(result)
337
+
338
+ def grant(self, actor: Principal, grant: AccessGrant, *, now: int):
339
+ with self.transaction():
340
+ self.get_repository(actor, grant.repository_id, action=Action.ADMIN)
341
+ self._user(grant.user_id)
342
+ self._connection.execute("INSERT INTO grants VALUES(?,?,?) ON CONFLICT(repository_id,user_id) DO UPDATE SET permission=excluded.permission", (grant.repository_id, grant.user_id, int(grant.permission)))
343
+ self._event(EventKind.GRANT_CHANGED, actor.user_id, grant.repository_id, now)
344
+
345
+ def revoke_grant(self, actor: Principal, repository_id: str, user_id: str, *, now: int):
346
+ identifier(user_id)
347
+ with self.transaction():
348
+ self.get_repository(actor, repository_id, action=Action.ADMIN)
349
+ deleted = self._connection.execute("DELETE FROM grants WHERE repository_id=? AND user_id=?", (repository_id, user_id)).rowcount
350
+ if deleted:self._event(EventKind.GRANT_CHANGED, actor.user_id, repository_id, now)
351
+
352
+ def branch_policy(self, actor: Principal, repository_id: str) -> BranchPolicy:
353
+ with self._snapshot():
354
+ self.get_repository(actor, repository_id, action=Action.WRITE)
355
+ row = self._connection.execute("SELECT version FROM ref_policy_versions WHERE repository_id=?", (repository_id,)).fetchone()
356
+ rows = self._connection.execute("SELECT * FROM branch_rules WHERE repository_id=? ORDER BY pattern LIMIT ?", (repository_id, MAX_BRANCH_RULES + 1)).fetchall()
357
+ if len(rows) > MAX_BRANCH_RULES:raise CatalogError("repository rule count exceeds the supported bound")
358
+ rules = tuple(BranchRule(r['repository_id'], r['pattern'], *(bool(r[k]) for k in ('allow_create','allow_delete','allow_force','require_review')), Permission(r['minimum_permission'])) for r in rows)
359
+ return BranchPolicy(repository_id, row[0] if row else 0, rules)
360
+
361
+ def _policy_revision(self, actor, repository_id, expected_version):
362
+ self.get_repository(actor, repository_id, action=Action.ADMIN)
363
+ if type(expected_version) is not int or not 0 <= expected_version < 0x7fffffffffffffff:
364
+ raise ValueError("select a nonnegative policy revision below the SQLite maximum")
365
+ current = self.branch_policy(actor, repository_id)
366
+ if current.version != expected_version:raise CatalogConflict("ref policy revision changed")
367
+ return current
368
+
369
+ def _advance_policy(self, actor, repository_id, version, now):
370
+ self._connection.execute("INSERT INTO ref_policy_versions VALUES(?,?) ON CONFLICT(repository_id) DO UPDATE SET version=excluded.version", (repository_id, version + 1))
371
+ self._event(EventKind.REF_POLICY_CHANGED, actor.user_id, repository_id, now)
372
+
373
+ def set_branch_rule(self, actor: Principal, rule: BranchRule, *, expected_version: int, now: int) -> BranchPolicy:
374
+ if not isinstance(rule, BranchRule):raise TypeError("select a BranchRule")
375
+ with self.transaction():
376
+ current = self._policy_revision(actor, rule.repository_id, expected_version)
377
+ if len(current.rules) >= MAX_BRANCH_RULES and all(r.pattern != rule.pattern for r in current.rules):
378
+ raise CatalogConflict("repository rule count exceeded")
379
+ self._connection.execute("INSERT INTO branch_rules VALUES(?,?,?,?,?,?,?) ON CONFLICT(repository_id,pattern) DO UPDATE SET allow_create=excluded.allow_create,allow_delete=excluded.allow_delete,allow_force=excluded.allow_force,require_review=excluded.require_review,minimum_permission=excluded.minimum_permission",
380
+ (rule.repository_id, rule.pattern, int(rule.allow_create), int(rule.allow_delete), int(rule.allow_force), int(rule.require_review), int(rule.minimum_permission)))
381
+ self._advance_policy(actor, rule.repository_id, current.version, now)
382
+ return self.branch_policy(actor, rule.repository_id)
383
+
384
+ def delete_branch_rule(self, actor: Principal, repository_id: str, pattern: str, *, expected_version: int, now: int) -> BranchPolicy:
385
+ ref_pattern(pattern)
386
+ with self.transaction():
387
+ current = self._policy_revision(actor, repository_id, expected_version)
388
+ deleted = self._connection.execute("DELETE FROM branch_rules WHERE repository_id=? AND pattern=?", (repository_id, pattern)).rowcount
389
+ if deleted:self._advance_policy(actor, repository_id, current.version, now)
390
+ return self.branch_policy(actor, repository_id)
391
+
392
+ def store_credential(self, actor: Principal, metadata: CredentialMetadata, verifier_digest: bytes):
393
+ if actor.scopes is not None or actor.credential_id is not None:
394
+ raise PermissionDenied("token issuance requires a trusted local account principal")
395
+ if not isinstance(verifier_digest, bytes) or len(verifier_digest) != 32:
396
+ raise ValueError("credential storage requires a 32-byte verifier digest, never a raw token")
397
+ with self.transaction():
398
+ self._user(actor.user_id)
399
+ if actor.user_id != metadata.user_id:raise PermissionDenied("credential permission denied")
400
+ self._connection.execute("INSERT INTO credentials VALUES(?,?,?,?,?,?)", (metadata.id, metadata.user_id, verifier_digest, metadata.created_at, metadata.expires_at, metadata.revoked_at))
401
+ self._event(EventKind.CREDENTIAL_CREATED, actor.user_id, metadata.id, metadata.created_at)
402
+
403
+ def credential_metadata(self, actor: Principal, credential_id: str) -> CredentialMetadata:
404
+ identifier(credential_id)
405
+ row = self._connection.execute("SELECT id,user_id,created_at,expires_at,revoked_at FROM credentials WHERE id=? AND user_id=?", (credential_id, actor.user_id)).fetchone()
406
+ if row is None:raise PermissionDenied("credential not found or permission denied")
407
+ return CredentialMetadata(*row)
408
+
409
+ def revoke_credential(self, actor: Principal, credential_id: str, *, now: int):
410
+ require_scope(actor, Action.ADMIN)
411
+ timestamp(now)
412
+ with self.transaction():
413
+ metadata = self.credential_metadata(actor, credential_id)
414
+ if now < metadata.created_at:raise ValueError("revocation cannot precede credential creation")
415
+ if metadata.revoked_at is None:
416
+ self._connection.execute("UPDATE credentials SET revoked_at=? WHERE id=?", (now, credential_id))
417
+ self._event(EventKind.CREDENTIAL_REVOKED, actor.user_id, credential_id, now)
418
+
419
+ def _credential_auth_data(self, credential_id):
420
+ """Verifier material is private to the token authentication boundary."""
421
+ row = self._connection.execute("SELECT c.* FROM credentials c JOIN owners o ON o.id=c.user_id AND o.kind='user' WHERE c.id=?", (credential_id,)).fetchone()
422
+ if row is None:return None
423
+ scopes = frozenset(Action(r[0]) for r in self._connection.execute("SELECT action FROM credential_scopes WHERE credential_id=?", (credential_id,)))
424
+ return CredentialMetadata(row['id'], row['user_id'], row['created_at'], row['expires_at'], row['revoked_at']), bytes(row['verifier']), scopes
425
+
426
+ def repository_events(self, actor: Principal, repository_id: str, *, limit=50, after=0) -> tuple[AuditEvent, ...]:
427
+ page(limit, after)
428
+ with self._snapshot():
429
+ self.get_repository(actor, repository_id, action=Action.ADMIN)
430
+ rows = self._connection.execute("SELECT * FROM audit_events WHERE resource_id=? AND sequence>? ORDER BY sequence LIMIT ?", (repository_id, after, limit)).fetchall()
431
+ return tuple(AuditEvent(r['sequence'], r['id'], EventKind(r['kind']), r['actor_id'], r['resource_id'], r['timestamp']) for r in rows)
432
+
433
+ def pending_jobs(self, *, limit=50, after=0) -> tuple[OutboxJob, ...]:
434
+ page(limit, after)
435
+ rows = self._connection.execute("SELECT j.sequence,j.id,j.event_id,j.kind,j.resource_id FROM outbox j LEFT JOIN provisioning p ON p.repository_id=j.resource_id WHERE j.done=0 AND j.sequence>? AND (j.kind!='repository.index' OR p.repository_id IS NULL OR p.state='ready') ORDER BY j.sequence LIMIT ?", (after, limit)).fetchall()
436
+ return tuple(OutboxJob(*r) for r in rows)
437
+
438
+ def acknowledge_job(self, job_id: str) -> bool:
439
+ identifier(job_id)
440
+ with self.transaction():
441
+ return self._connection.execute("UPDATE outbox SET done=1 WHERE id=? AND done=0", (job_id,)).rowcount == 1
442
+
443
+ def provisioning_state(self, repository_id: str):
444
+ identifier(repository_id)
445
+ row=self._connection.execute("SELECT state FROM provisioning WHERE repository_id=?",(repository_id,)).fetchone()
446
+ return row[0] if row else None
447
+
448
+ def reserve_repository(self, actor, record, *, now):
449
+ require_scope(actor, Action.ADMIN)
450
+ with self.transaction():
451
+ existing=self._connection.execute("SELECT id FROM repositories WHERE id=?",(record.id,)).fetchone()
452
+ if existing:
453
+ stored=self._record(record.id);self._authorize(actor,stored,Action.ADMIN)
454
+ state=self.provisioning_state(record.id)
455
+ if stored!=record or state is None:raise CatalogConflict("repository is not the same managed provisioning request")
456
+ return state
457
+ self.create_repository(actor,record,now=now)
458
+ self._connection.execute("INSERT INTO provisioning VALUES(?,'pending')",(record.id,))
459
+ return "pending"
460
+
461
+ def provisioning_record(self, actor, repository_id):
462
+ record=self._record(repository_id);self._authorize(actor,record,Action.ADMIN)
463
+ if self.provisioning_state(repository_id) is None:raise CatalogConflict("repository is not managed by provisioning")
464
+ return record
465
+
466
+ def finish_provisioning(self, actor, repository_id, *, now):
467
+ with self.transaction():
468
+ self.provisioning_record(actor,repository_id)
469
+ if self._connection.execute("UPDATE provisioning SET state='ready' WHERE repository_id=? AND state='pending'",(repository_id,)).rowcount:
470
+ self._event(EventKind.REPOSITORY_READY,actor.user_id,repository_id,now)
gitcx/cli.py ADDED
@@ -0,0 +1,23 @@
1
+ """Package information and an explicitly selected loopback HTTP server."""
2
+
3
+ import argparse
4
+ from importlib.metadata import version
5
+
6
+
7
+ def main(argv: list[str] | None = None) -> int:
8
+ parser = argparse.ArgumentParser(description="Git-compatible hosting and collaboration")
9
+ parser.add_argument("--version", action="version", version=f"gitcx {version('gitcx')}")
10
+ commands = parser.add_subparsers(dest="command")
11
+ serve = commands.add_parser("serve", help="run local management and Git HTTP")
12
+ serve.add_argument("--data-root", required=True)
13
+ serve.add_argument("--port", type=int, default=8000)
14
+ args = parser.parse_args(argv)
15
+ if args.command == "serve":
16
+ if not 0 <= args.port <= 65535:parser.error("port must be between 0 and 65535")
17
+ try:
18
+ from .management import create_app
19
+ except ModuleNotFoundError as error:
20
+ if error.name != "expose_api":raise
21
+ parser.error("install gitcx[http] to run the management API")
22
+ create_app(args.data_root).run(host="127.0.0.1", port=args.port)
23
+ return 0
gitcx/domain.py ADDED
@@ -0,0 +1,145 @@
1
+ """Immutable platform records, separate from Git object and ref authority."""
2
+
3
+ from dataclasses import dataclass
4
+ from enum import IntEnum, StrEnum
5
+ import re
6
+ import uuid
7
+
8
+
9
+ def identifier(value: str) -> str:
10
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{32}", value):
11
+ raise ValueError("identifiers must be canonical lowercase UUID hex strings")
12
+ return value
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class StorageId:
17
+ value: str
18
+
19
+ def __post_init__(self) -> None:
20
+ identifier(self.value)
21
+
22
+ @classmethod
23
+ def new(cls) -> StorageId:
24
+ return cls(uuid.uuid4().hex)
25
+
26
+ def __str__(self) -> str:
27
+ return self.value
28
+
29
+
30
+ RESERVED_SLUGS = frozenset(("api", "admin", "login", "logout", "settings", "new", "git",
31
+ "assets", "static", "health", "info", "git-upload-pack", "git-receive-pack"))
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class Slug:
36
+ value: str
37
+
38
+ def __post_init__(self) -> None:
39
+ if not isinstance(self.value, str) or not re.fullmatch(r"[a-z0-9](?:[a-z0-9_-]{0,61}[a-z0-9])?", self.value):
40
+ raise ValueError("slugs must contain 1–63 lowercase ASCII letters, digits, underscores or dashes and start/end with a letter or digit")
41
+ if self.value in RESERVED_SLUGS:
42
+ raise ValueError("slug is reserved for a platform endpoint")
43
+
44
+ def __str__(self) -> str:
45
+ return self.value
46
+
47
+
48
+ class OwnerKind(StrEnum):
49
+ USER = "user"
50
+ ORGANIZATION = "organization"
51
+
52
+
53
+ class Visibility(StrEnum):
54
+ PRIVATE = "private"
55
+ PUBLIC = "public"
56
+
57
+
58
+ class Permission(IntEnum):
59
+ READ = 1
60
+ WRITE = 2
61
+ ADMIN = 3
62
+
63
+
64
+ class Action(StrEnum):
65
+ READ = "read"
66
+ WRITE = "write"
67
+ ADMIN = "admin"
68
+
69
+
70
+ class OrganizationRole(StrEnum):
71
+ MEMBER = "member"
72
+ OWNER = "owner"
73
+
74
+
75
+ @dataclass(frozen=True, slots=True)
76
+ class Principal:
77
+ user_id: str | None = None
78
+ scopes: frozenset[Action] | None = None
79
+ credential_id: str | None = None
80
+
81
+ def __post_init__(self) -> None:
82
+ if self.user_id is not None:
83
+ identifier(self.user_id)
84
+ if self.scopes is not None:
85
+ if isinstance(self.scopes, str):
86
+ raise ValueError("principal scopes must be a collection of actions")
87
+ object.__setattr__(self, "scopes", frozenset(Action(action) for action in self.scopes))
88
+ if self.credential_id is not None:
89
+ identifier(self.credential_id)
90
+ if self.user_id is None or self.scopes is None:
91
+ raise ValueError("credential principals require an account and explicit scopes")
92
+
93
+
94
+ @dataclass(frozen=True, slots=True)
95
+ class Owner:
96
+ id: str
97
+ kind: OwnerKind
98
+
99
+ def __post_init__(self) -> None:
100
+ identifier(self.id)
101
+ object.__setattr__(self, "kind", OwnerKind(self.kind))
102
+
103
+
104
+ @dataclass(frozen=True, slots=True)
105
+ class RepositoryRecord:
106
+ id: str
107
+ owner: Owner
108
+ slug: Slug
109
+ storage_id: StorageId
110
+ visibility: Visibility = Visibility.PRIVATE
111
+ object_format: str = "sha1"
112
+
113
+ def __post_init__(self) -> None:
114
+ identifier(self.id)
115
+ if not isinstance(self.owner, Owner) or not isinstance(self.slug, Slug) or not isinstance(self.storage_id, StorageId):
116
+ raise TypeError("repository owner, slug and storage ID must be typed records")
117
+ object.__setattr__(self, "visibility", Visibility(self.visibility))
118
+ if self.object_format not in ("sha1", "sha256"):
119
+ raise ValueError("only native sha1/sha256 metadata is supported")
120
+
121
+
122
+ @dataclass(frozen=True, slots=True)
123
+ class AccessGrant:
124
+ repository_id: str
125
+ user_id: str
126
+ permission: Permission
127
+
128
+ def __post_init__(self) -> None:
129
+ identifier(self.repository_id)
130
+ identifier(self.user_id)
131
+ if type(self.permission) is not int and not isinstance(self.permission, Permission):
132
+ raise ValueError("permission must be a declared permission level")
133
+ object.__setattr__(self, "permission", Permission(self.permission))
134
+
135
+
136
+ @dataclass(frozen=True, slots=True)
137
+ class Membership:
138
+ organization_id: str
139
+ user_id: str
140
+ role: OrganizationRole = OrganizationRole.MEMBER
141
+
142
+ def __post_init__(self) -> None:
143
+ identifier(self.organization_id)
144
+ identifier(self.user_id)
145
+ object.__setattr__(self, "role", OrganizationRole(self.role))