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/__init__.py +34 -0
- gitcx/__main__.py +3 -0
- gitcx/authentication.py +128 -0
- gitcx/backend.py +38 -0
- gitcx/branch_policy.py +49 -0
- gitcx/catalog.py +470 -0
- gitcx/cli.py +23 -0
- gitcx/domain.py +145 -0
- gitcx/git_http.py +211 -0
- gitcx/management.py +196 -0
- gitcx/permissions.py +52 -0
- gitcx/provisioning.py +118 -0
- gitcx/py.typed +0 -0
- gitcx/receive.py +151 -0
- gitcx/ref_policy.py +151 -0
- gitcx-0.1.0a3.dist-info/METADATA +76 -0
- gitcx-0.1.0a3.dist-info/RECORD +20 -0
- gitcx-0.1.0a3.dist-info/WHEEL +4 -0
- gitcx-0.1.0a3.dist-info/entry_points.txt +3 -0
- gitcx-0.1.0a3.dist-info/licenses/LICENSE +21 -0
gitcx/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Git hosting domain and explicit permission contracts."""
|
|
2
|
+
|
|
3
|
+
from .backend import BackendMismatch, RepositoryBackend, RepositoryInfo, REQUIRED_CAPABILITIES
|
|
4
|
+
from .domain import AccessGrant, Action, Membership, OrganizationRole, Owner, OwnerKind, Permission, Principal, RepositoryRecord, Slug, StorageId, Visibility
|
|
5
|
+
from .permissions import PermissionDenied, allowed, require_permission, require_scope, scope_allows, visible_repositories
|
|
6
|
+
from .catalog import AuditEvent, Catalog, CatalogConflict, CatalogError, CredentialMetadata, EventKind, OutboxJob
|
|
7
|
+
from .provisioning import GitdxBackend, HostedRepository, ProvisioningError, RepositoryService
|
|
8
|
+
from .authentication import AuthenticationError, IssuedToken, TokenAuth
|
|
9
|
+
from .branch_policy import BranchPolicy, BranchRule
|
|
10
|
+
from .ref_policy import RefDecision, RefPolicyResult, RefPolicyService, RefReason
|
|
11
|
+
from .receive import HostedReceiveResult, ReceiveService
|
|
12
|
+
|
|
13
|
+
__all__ = ["AccessGrant", "Action", "Membership", "OrganizationRole", "Owner", "OwnerKind",
|
|
14
|
+
"Permission", "Principal", "RepositoryRecord", "Slug", "StorageId", "Visibility",
|
|
15
|
+
"RepositoryBackend", "RepositoryInfo", "PermissionDenied", "allowed",
|
|
16
|
+
"require_permission", "visible_repositories"]
|
|
17
|
+
__all__ += ["AuditEvent", "Catalog", "CatalogConflict", "CatalogError", "CredentialMetadata", "EventKind", "OutboxJob"]
|
|
18
|
+
__all__ += ["GitdxBackend", "HostedRepository", "ProvisioningError", "RepositoryService"]
|
|
19
|
+
__all__ += ["AuthenticationError", "IssuedToken", "TokenAuth", "require_scope", "scope_allows"]
|
|
20
|
+
__all__ += ["BackendMismatch", "REQUIRED_CAPABILITIES"]
|
|
21
|
+
__all__ += ["BranchPolicy", "BranchRule", "RefDecision", "RefPolicyResult", "RefPolicyService", "RefReason"]
|
|
22
|
+
__all__ += ['HostedReceiveResult', 'ReceiveService']
|
|
23
|
+
__all__ += ["create_app"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def create_app(*args, **kwargs):
|
|
27
|
+
"""Load the optional HTTP adapter only when explicitly selected."""
|
|
28
|
+
from .management import create_app as factory
|
|
29
|
+
return factory(*args, **kwargs)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def main() -> None:
|
|
33
|
+
from .cli import main as run
|
|
34
|
+
raise SystemExit(run())
|
gitcx/__main__.py
ADDED
gitcx/authentication.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Scoped personal tokens and a fresh authentication boundary per operation."""
|
|
2
|
+
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import re
|
|
7
|
+
import secrets
|
|
8
|
+
import uuid
|
|
9
|
+
|
|
10
|
+
from .catalog import CredentialMetadata, timestamp
|
|
11
|
+
from .domain import Action, Principal
|
|
12
|
+
from .permissions import PermissionDenied
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_TOKEN = re.compile(r"gtc_([0-9a-f]{32})_[A-Za-z0-9_-]{43}")
|
|
16
|
+
_DUMMY_DIGEST = bytes(32)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AuthenticationError(PermissionDenied):
|
|
20
|
+
"""Malformed, unknown, expired and revoked tokens share one safe error."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class IssuedToken:
|
|
24
|
+
"""An explicit, one-time secret delivery; default representations are safe."""
|
|
25
|
+
|
|
26
|
+
__slots__ = ("metadata", "scopes", "_secret")
|
|
27
|
+
|
|
28
|
+
def __init__(self, metadata, scopes, secret):
|
|
29
|
+
self.metadata, self.scopes, self._secret = metadata, scopes, secret
|
|
30
|
+
|
|
31
|
+
def __repr__(self):
|
|
32
|
+
return f"IssuedToken(id={self.metadata.id!r}, secret=<redacted>)"
|
|
33
|
+
|
|
34
|
+
def reveal(self) -> str:
|
|
35
|
+
if self._secret is None:
|
|
36
|
+
raise ValueError("token secret has already been delivered")
|
|
37
|
+
secret, self._secret = self._secret, None
|
|
38
|
+
return secret
|
|
39
|
+
|
|
40
|
+
def __reduce_ex__(self, protocol):
|
|
41
|
+
raise TypeError("issued token secrets cannot be serialized")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TokenAuth:
|
|
45
|
+
"""Use request() for one transaction spanning authentication and access.
|
|
46
|
+
|
|
47
|
+
A returned Principal is a request snapshot, never a reusable session.
|
|
48
|
+
Bootstrap/token issuance requires a trusted local account principal.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, catalog):
|
|
52
|
+
self.catalog = catalog
|
|
53
|
+
|
|
54
|
+
def issue(self, actor: Principal, *, scopes, expires_at: int, now: int) -> IssuedToken:
|
|
55
|
+
timestamp(now)
|
|
56
|
+
timestamp(expires_at)
|
|
57
|
+
if expires_at <= now:
|
|
58
|
+
raise ValueError("token expiry must follow issuance")
|
|
59
|
+
if isinstance(scopes, str):
|
|
60
|
+
raise ValueError("token scopes must be a nonempty collection of actions")
|
|
61
|
+
scopes = frozenset(Action(scope) for scope in scopes)
|
|
62
|
+
if not scopes:
|
|
63
|
+
raise ValueError("tokens require at least one scope")
|
|
64
|
+
if actor.user_id is None or actor.scopes is not None or actor.credential_id is not None:
|
|
65
|
+
raise PermissionDenied("token issuance requires a trusted local account principal")
|
|
66
|
+
metadata = CredentialMetadata(uuid.uuid4().hex, actor.user_id, now, expires_at)
|
|
67
|
+
secret = f"gtc_{metadata.id}_{secrets.token_urlsafe(32)}"
|
|
68
|
+
digest = hashlib.sha256(secret.encode("ascii")).digest()
|
|
69
|
+
with self.catalog.transaction():
|
|
70
|
+
self.catalog.store_credential(actor, metadata, digest)
|
|
71
|
+
self.catalog._connection.executemany("INSERT INTO credential_scopes VALUES(?,?)",
|
|
72
|
+
((metadata.id, scope.value) for scope in sorted(scopes)))
|
|
73
|
+
return IssuedToken(metadata, scopes, secret)
|
|
74
|
+
|
|
75
|
+
def authenticate(self, token: str, *, now: int) -> Principal:
|
|
76
|
+
timestamp(now)
|
|
77
|
+
match = _TOKEN.fullmatch(token) if isinstance(token, str) and len(token) == 80 else None
|
|
78
|
+
candidate = hashlib.sha256(token.encode("ascii") if match else b"").digest()
|
|
79
|
+
with self.catalog._snapshot():
|
|
80
|
+
data = self.catalog._credential_auth_data(match[1]) if match else None
|
|
81
|
+
# Compare fixed-size digests even for unknown/malformed credentials.
|
|
82
|
+
matches = hmac.compare_digest(candidate, data[1] if data else _DUMMY_DIGEST)
|
|
83
|
+
if data is not None:
|
|
84
|
+
metadata, _, scopes = data
|
|
85
|
+
if matches and scopes and metadata.revoked_at is None and metadata.expires_at is not None and metadata.created_at <= now < metadata.expires_at:
|
|
86
|
+
return Principal(metadata.user_id, scopes, metadata.id)
|
|
87
|
+
raise AuthenticationError("invalid or inactive credential")
|
|
88
|
+
|
|
89
|
+
def revalidate(self, actor: Principal, *, now: int) -> Principal:
|
|
90
|
+
"""Refresh a trusted request principal; this does not authenticate input.
|
|
91
|
+
|
|
92
|
+
Callers must obtain credential principals from authenticate()/request().
|
|
93
|
+
Current credential scopes cap the original request scopes as well.
|
|
94
|
+
"""
|
|
95
|
+
timestamp(now)
|
|
96
|
+
if not isinstance(actor, Principal):raise TypeError("select a trusted Principal")
|
|
97
|
+
if actor.credential_id is None:return actor
|
|
98
|
+
with self.catalog._snapshot():
|
|
99
|
+
data = self.catalog._credential_auth_data(actor.credential_id)
|
|
100
|
+
if data is not None:
|
|
101
|
+
metadata, _, scopes = data
|
|
102
|
+
if (metadata.user_id == actor.user_id and scopes and metadata.revoked_at is None
|
|
103
|
+
and metadata.expires_at is not None and metadata.created_at <= now < metadata.expires_at):
|
|
104
|
+
# Keep the original cap even if a trusted administrator later
|
|
105
|
+
# expands the stored scope. Hierarchical caps may differ.
|
|
106
|
+
from .permissions import scope_allows
|
|
107
|
+
current = Principal(actor.user_id, scopes, actor.credential_id)
|
|
108
|
+
capped = frozenset(action for action in Action if scope_allows(actor, action) and scope_allows(current, action))
|
|
109
|
+
return Principal(actor.user_id, capped, actor.credential_id)
|
|
110
|
+
raise AuthenticationError("invalid or inactive credential")
|
|
111
|
+
|
|
112
|
+
@contextmanager
|
|
113
|
+
def request(self, token: str, *, now: int):
|
|
114
|
+
"""Serialize revocation with a single bounded authorized operation."""
|
|
115
|
+
with self.catalog.transaction():
|
|
116
|
+
yield self.authenticate(token, now=now)
|
|
117
|
+
|
|
118
|
+
def repository(self, token: str, repository_id: str, *, action=Action.READ, now: int):
|
|
119
|
+
with self.request(token, now=now) as actor:
|
|
120
|
+
return self.catalog.get_repository(actor, repository_id, action=action)
|
|
121
|
+
|
|
122
|
+
def repositories(self, token: str, *, limit=50, after="", now: int):
|
|
123
|
+
with self.request(token, now=now) as actor:
|
|
124
|
+
return self.catalog.list_repositories(actor, limit=limit, after=after)
|
|
125
|
+
|
|
126
|
+
def revoke(self, token: str, credential_id: str, *, now: int):
|
|
127
|
+
with self.request(token, now=now) as actor:
|
|
128
|
+
self.catalog.revoke_credential(actor, credential_id, now=now)
|
gitcx/backend.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Hosting-facing backend boundary. Gitdx supplies the concrete implementation."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Protocol
|
|
5
|
+
|
|
6
|
+
from .domain import StorageId
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
REQUIRED_CAPABILITIES = frozenset({"objects.read", "objects.write", "refs.read", "refs.update"})
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BackendMismatch(Exception):
|
|
13
|
+
"""A selected provider cannot satisfy the qualified hosting profile."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class RepositoryInfo:
|
|
18
|
+
object_format: str
|
|
19
|
+
bare: bool
|
|
20
|
+
capabilities: frozenset[str]
|
|
21
|
+
|
|
22
|
+
def __post_init__(self) -> None:
|
|
23
|
+
object.__setattr__(self, "capabilities", frozenset(self.capabilities))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RepositoryBackend(Protocol):
|
|
27
|
+
"""No branch/object shadow state; operations delegate to the engine."""
|
|
28
|
+
|
|
29
|
+
def create(self, storage_id: StorageId, *, object_format: str) -> RepositoryInfo: ...
|
|
30
|
+
|
|
31
|
+
def inspect(self, storage_id: StorageId) -> RepositoryInfo: ...
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def require_backend_info(info, object_format):
|
|
35
|
+
if (not isinstance(info, RepositoryInfo) or info.bare is not True
|
|
36
|
+
or info.object_format != object_format or not REQUIRED_CAPABILITIES <= info.capabilities):
|
|
37
|
+
raise BackendMismatch("backend does not satisfy the managed repository profile")
|
|
38
|
+
return info
|
gitcx/branch_policy.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Immutable, bounded protection rules; the catalog never stores branch tips."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from gitdx.names import validate_refname
|
|
6
|
+
|
|
7
|
+
from .domain import Permission, identifier
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
MAX_BRANCH_RULES = 128
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def ref_pattern(value):
|
|
14
|
+
if not isinstance(value, str) or len(value) > 1024:
|
|
15
|
+
raise ValueError("ref patterns must be strings of at most 1024 characters")
|
|
16
|
+
candidate = value[:-1] + "example" if value.endswith("/*") else value
|
|
17
|
+
validate_refname(candidate)
|
|
18
|
+
if not candidate.startswith(("refs/heads/", "refs/tags/")):
|
|
19
|
+
raise ValueError("protection rules select branches or tags")
|
|
20
|
+
return value
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class BranchRule:
|
|
25
|
+
repository_id: str
|
|
26
|
+
pattern: str
|
|
27
|
+
allow_create: bool = True
|
|
28
|
+
allow_delete: bool = False
|
|
29
|
+
allow_force: bool = False
|
|
30
|
+
require_review: bool = False
|
|
31
|
+
minimum_permission: Permission = Permission.WRITE
|
|
32
|
+
|
|
33
|
+
def __post_init__(self):
|
|
34
|
+
identifier(self.repository_id); ref_pattern(self.pattern)
|
|
35
|
+
for value in (self.allow_create, self.allow_delete, self.allow_force, self.require_review):
|
|
36
|
+
if type(value) is not bool:raise TypeError("rule switches must be booleans")
|
|
37
|
+
object.__setattr__(self, "minimum_permission", Permission(self.minimum_permission))
|
|
38
|
+
if self.minimum_permission not in (Permission.WRITE, Permission.ADMIN):
|
|
39
|
+
raise ValueError("rules can require write or administrator permission")
|
|
40
|
+
|
|
41
|
+
def matches(self, name):
|
|
42
|
+
return name.startswith(self.pattern[:-1]) if self.pattern.endswith("/*") else name == self.pattern
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, slots=True)
|
|
46
|
+
class BranchPolicy:
|
|
47
|
+
repository_id: str
|
|
48
|
+
version: int
|
|
49
|
+
rules: tuple[BranchRule, ...]
|