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,135 @@
1
+ """Explicit configuration for the public GitCode OAuth broker."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from urllib.parse import urlsplit
10
+
11
+ from cryptography.fernet import Fernet
12
+ from pydantic import AnyHttpUrl, ValidationError
13
+
14
+ from .config import ConfigurationError
15
+
16
+ READ_SCOPE = "gitcode:read"
17
+ WRITE_SCOPE = "gitcode:write"
18
+
19
+
20
+ def _required(env: Mapping[str, str], name: str, *, secret: bool = False) -> str:
21
+ value = env.get(name, "")
22
+ if (
23
+ not value
24
+ or not value.isascii()
25
+ or len(value) > 4096
26
+ or any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in value)
27
+ ):
28
+ raise ConfigurationError(f"{name} must be a nonempty value without whitespace.")
29
+ if secret and len(value) < 32:
30
+ raise ConfigurationError(f"{name} must contain at least 32 characters.")
31
+ return value
32
+
33
+
34
+ def https_url(value: str, name: str, *, origin: bool = False) -> str:
35
+ try:
36
+ parsed = urlsplit(value)
37
+ valid = (
38
+ parsed.scheme == "https"
39
+ and bool(parsed.hostname)
40
+ and parsed.username is None
41
+ and parsed.password is None
42
+ and not parsed.fragment
43
+ and value.isascii()
44
+ and not any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in value)
45
+ and "*" not in value
46
+ and "\\" not in value
47
+ and parsed.port != 0
48
+ )
49
+ except ValueError:
50
+ valid = False
51
+ if not valid or (origin and (parsed.path not in {"", "/"} or parsed.query)):
52
+ suffix = (
53
+ " origin without a path, query or fragment" if origin else " URL without a fragment"
54
+ )
55
+ raise ConfigurationError(f"{name} must be an explicit HTTPS{suffix}.")
56
+ try:
57
+ normalized = str(AnyHttpUrl(value))
58
+ except ValidationError:
59
+ raise ConfigurationError(f"{name} must be a valid HTTPS URL.") from None
60
+ return normalized.rstrip("/") if origin else normalized
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class OAuthSettings:
65
+ public_url: str
66
+ gitcode_client_id: str
67
+ gitcode_client_secret: str = field(repr=False)
68
+ client_id: str
69
+ client_secret: str = field(repr=False)
70
+ redirect_uris: tuple[str, ...]
71
+ encryption_key: str = field(repr=False)
72
+ database: str
73
+ gitcode_scopes: tuple[str, ...] = ()
74
+ allowed_user_ids: tuple[str, ...] = ()
75
+
76
+ @property
77
+ def resource_url(self) -> str:
78
+ return self.public_url + "/mcp"
79
+
80
+ @property
81
+ def callback_url(self) -> str:
82
+ return self.public_url + "/oauth/gitcode/callback"
83
+
84
+ @classmethod
85
+ def from_env(cls, env: Mapping[str, str]) -> OAuthSettings:
86
+ public_url = https_url(
87
+ _required(env, "GITCODE_MCP_PUBLIC_URL"), "GITCODE_MCP_PUBLIC_URL", origin=True
88
+ )
89
+ redirects = tuple(
90
+ https_url(value.strip(), "GITCODE_MCP_OAUTH_REDIRECT_URIS")
91
+ for value in env.get("GITCODE_MCP_OAUTH_REDIRECT_URIS", "").split(",")
92
+ if value.strip()
93
+ )
94
+ key = _required(env, "GITCODE_MCP_OAUTH_ENCRYPTION_KEY")
95
+ try:
96
+ Fernet(key.encode("ascii"))
97
+ except (ValueError, UnicodeError):
98
+ raise ConfigurationError(
99
+ "GITCODE_MCP_OAUTH_ENCRYPTION_KEY must be a persistent Fernet key."
100
+ ) from None
101
+ database = env.get("GITCODE_MCP_OAUTH_DATABASE", "/var/lib/gitcode-mcp/oauth.sqlite3")
102
+ if not Path(database).is_absolute() or "\x00" in database:
103
+ raise ConfigurationError("GITCODE_MCP_OAUTH_DATABASE must be an absolute file path.")
104
+ scopes = tuple(env.get("GITCODE_OAUTH_SCOPES", "").split())
105
+ if any(not re.fullmatch(r"[A-Za-z0-9_:\-.]+", value) for value in scopes):
106
+ raise ConfigurationError(
107
+ "GITCODE_OAUTH_SCOPES must contain space-separated scope names."
108
+ )
109
+ users = tuple(
110
+ value.strip()
111
+ for value in env.get("GITCODE_MCP_OAUTH_ALLOWED_USER_IDS", "").split(",")
112
+ if value.strip()
113
+ )
114
+ if any(not re.fullmatch(r"[A-Za-z0-9_.:-]{1,256}", value) for value in users):
115
+ raise ConfigurationError(
116
+ "GITCODE_MCP_OAUTH_ALLOWED_USER_IDS must list stable user IDs."
117
+ )
118
+ upstream_secret = _required(env, "GITCODE_OAUTH_CLIENT_SECRET")
119
+ client_secret = _required(env, "GITCODE_MCP_OAUTH_CLIENT_SECRET", secret=True)
120
+ if client_secret == upstream_secret or key in {client_secret, upstream_secret}:
121
+ raise ConfigurationError(
122
+ "OAuth client secrets and the storage key must be independent."
123
+ )
124
+ return cls(
125
+ public_url=public_url,
126
+ gitcode_client_id=_required(env, "GITCODE_OAUTH_CLIENT_ID"),
127
+ gitcode_client_secret=upstream_secret,
128
+ client_id=_required(env, "GITCODE_MCP_OAUTH_CLIENT_ID"),
129
+ client_secret=client_secret,
130
+ redirect_uris=redirects,
131
+ encryption_key=key,
132
+ database=database,
133
+ gitcode_scopes=scopes,
134
+ allowed_user_ids=users,
135
+ )
@@ -0,0 +1,163 @@
1
+ """Small HTTP checks around SDK OAuth routes and the MCP transport."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from urllib.parse import parse_qsl
7
+
8
+ from starlette.requests import Request
9
+ from starlette.responses import JSONResponse
10
+ from starlette.types import ASGIApp, Receive, Scope, Send
11
+
12
+ from .config import Settings
13
+ from .oauth import GitCodeOAuthProvider
14
+ from .oauth_store import OAuthStoreError
15
+
16
+
17
+ def _matches(value: str, patterns: tuple[str, ...]) -> bool:
18
+ for pattern in patterns:
19
+ if value == pattern:
20
+ return True
21
+ if pattern.endswith(":*"):
22
+ base = pattern[:-2]
23
+ if value == base or (value.startswith(base + ":") and value[len(base) + 1 :].isdigit()):
24
+ return True
25
+ return False
26
+
27
+
28
+ class OAuthHTTPBoundary:
29
+ """Constrain all public routes, including routes outside SDK transport checks.
30
+
31
+ Canonical OAuth URLs come from configuration, never Host/Forwarded headers.
32
+ OAuth request bodies are buffered once with a small limit and replayed to the
33
+ SDK, which still owns client authentication, PKCE, scopes, and protocol errors.
34
+ """
35
+
36
+ def __init__(self, app: ASGIApp, settings: Settings, provider: GitCodeOAuthProvider):
37
+ self.app, self.settings, self.provider = app, settings, provider
38
+
39
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
40
+ if scope["type"] == "lifespan":
41
+
42
+ async def lifecycle_send(message: dict) -> None:
43
+ if message["type"] in {"lifespan.shutdown.complete", "lifespan.startup.failed"}:
44
+ await self.provider.aclose()
45
+ await send(message)
46
+
47
+ await self.app(scope, receive, lifecycle_send)
48
+ return
49
+ if scope["type"] != "http":
50
+ await self.app(scope, receive, send)
51
+ return
52
+
53
+ async def reject(status: int, error: str = "invalid_request") -> None:
54
+ await JSONResponse(
55
+ {"error": error}, status_code=status, headers={"Cache-Control": "no-store"}
56
+ )(scope, receive, send)
57
+
58
+ headers: dict[bytes, list[bytes]] = {}
59
+ for name, value in scope.get("headers", []):
60
+ headers.setdefault(name.lower(), []).append(value)
61
+ if len(headers.get(b"host", [])) != 1 or not _matches(
62
+ headers[b"host"][0].decode("latin-1"), self.settings.allowed_hosts
63
+ ):
64
+ await reject(421)
65
+ return
66
+ if any(
67
+ len(headers.get(name, [])) > 1
68
+ for name in (b"authorization", b"origin", b"content-type")
69
+ ):
70
+ await reject(400)
71
+ return
72
+ if b"origin" in headers and not _matches(
73
+ headers[b"origin"][0].decode("latin-1"), self.settings.allowed_origins
74
+ ):
75
+ await reject(403)
76
+ return
77
+ path = scope["path"]
78
+ is_oauth = path.startswith("/oauth/") or path in {"/authorize", "/token", "/revoke"}
79
+ raw_query = scope.get("query_string", b"")
80
+ if is_oauth:
81
+ if len(raw_query) > 8192:
82
+ await reject(414)
83
+ return
84
+ try:
85
+ query = parse_qsl(
86
+ raw_query.decode("utf-8"), keep_blank_values=True, max_num_fields=40
87
+ )
88
+ except (UnicodeError, ValueError):
89
+ await reject(400)
90
+ return
91
+ if len({key for key, _ in query}) != len(query):
92
+ await reject(400)
93
+ return
94
+ if any(key in {"client_secret", "access_token", "refresh_token"} for key, _ in query):
95
+ await reject(400)
96
+ return
97
+
98
+ downstream_receive = receive
99
+ if is_oauth and scope["method"] == "POST":
100
+ content_type = headers.get(b"content-type", [b""])[0].split(b";", 1)[0].strip().lower()
101
+ if content_type != b"application/x-www-form-urlencoded":
102
+ await reject(415)
103
+ return
104
+ body = bytearray()
105
+ while True:
106
+ message = await receive()
107
+ if message["type"] == "http.disconnect":
108
+ return
109
+ body.extend(message.get("body", b""))
110
+ if len(body) > 16384:
111
+ await reject(413)
112
+ return
113
+ if not message.get("more_body", False):
114
+ break
115
+ try:
116
+ fields = parse_qsl(body.decode("utf-8"), keep_blank_values=True, max_num_fields=40)
117
+ except (UnicodeError, ValueError):
118
+ await reject(400)
119
+ return
120
+ if len({key for key, _ in fields}) != len(fields):
121
+ await reject(400)
122
+ return
123
+ form = dict(fields)
124
+ if path == "/token":
125
+ # MCP SDK 2.3.0 parses but does not enforce the token request's
126
+ # resource indicator, so explicitly enforce it before delegation.
127
+ if form.get("resource") != self.provider.config.resource_url:
128
+ await reject(400, "invalid_target")
129
+ return
130
+ if form.get("grant_type") == "authorization_code" and not re.fullmatch(
131
+ r"[A-Za-z0-9._~-]{43,128}", form.get("code_verifier", "")
132
+ ):
133
+ await reject(400)
134
+ return
135
+ replayed = False
136
+
137
+ async def replay() -> dict:
138
+ nonlocal replayed
139
+ if not replayed:
140
+ replayed = True
141
+ return {"type": "http.request", "body": bytes(body), "more_body": False}
142
+ return await receive()
143
+
144
+ downstream_receive = replay
145
+
146
+ if path == "/.well-known/oauth-authorization-server" and scope["method"] == "GET":
147
+ response = await self.provider.metadata(Request(scope, downstream_receive))
148
+ await response(scope, downstream_receive, send)
149
+ return
150
+ response_started = False
151
+
152
+ async def tracked_send(message: dict) -> None:
153
+ nonlocal response_started
154
+ if message["type"] == "http.response.start":
155
+ response_started = True
156
+ await send(message)
157
+
158
+ try:
159
+ await self.app(scope, downstream_receive, tracked_send)
160
+ except OAuthStoreError:
161
+ # Storage exceptions intentionally carry no record bodies or keys.
162
+ if not response_started:
163
+ await reject(503, "temporarily_unavailable")