mudauth 0.1.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.
mudauth/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """mudauth — stateless OAuth/OIDC sign-in broker for MUDs.
2
+
3
+ Originally developed as the StickMUD auth service; see README.md for credits.
4
+ """
5
+
6
+ __version__ = "0.1.0"
mudauth/cli.py ADDED
@@ -0,0 +1,218 @@
1
+ """``mudauth`` command line: serve, check, apple-secret."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+ import time
9
+ from urllib.parse import urlsplit
10
+
11
+ from . import __version__, client, server
12
+ from .providers import SUPPORTED_PROVIDERS
13
+
14
+
15
+ def load_env_file(path: str) -> dict[str, str]:
16
+ """Parse a KEY=VALUE file (comments, blank lines, ``export``, quotes)."""
17
+ out: dict[str, str] = {}
18
+ with open(path, encoding="utf-8") as fh:
19
+ for raw in fh:
20
+ line = raw.strip()
21
+ if not line or line.startswith("#") or "=" not in line:
22
+ continue
23
+ if line.startswith("export "):
24
+ line = line[7:].lstrip()
25
+ key, _, value = line.partition("=")
26
+ value = value.strip()
27
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
28
+ value = value[1:-1]
29
+ out[key.strip()] = value
30
+ return out
31
+
32
+
33
+ def _apply_env_file(args: argparse.Namespace) -> None:
34
+ if getattr(args, "env_file", None):
35
+ for k, v in load_env_file(args.env_file).items():
36
+ os.environ.setdefault(k, v)
37
+
38
+
39
+ def _is_local_host(host: str) -> bool:
40
+ """True for a loopback literal or the name that resolves to one."""
41
+ return host == "localhost" or server._is_loopback(host)
42
+
43
+
44
+ def _bind_host_port() -> tuple[str, int]:
45
+ """Host and port the listener binds, from AUTH_BIND.
46
+
47
+ Raises ``ValueError`` on an unparseable port, with a message clear enough
48
+ to print as-is -- the same "configuration error" treatment as a bad hop
49
+ count, rather than an uncaught exception and a raw traceback.
50
+ """
51
+ bind = os.environ.get("AUTH_BIND", "127.0.0.1:7700")
52
+ host, _, port_s = bind.rpartition(":")
53
+ port_s = port_s or "7700"
54
+ try:
55
+ port = int(port_s)
56
+ except ValueError:
57
+ raise ValueError(f"AUTH_BIND port must be a number, not {port_s!r}") from None
58
+ return host or "127.0.0.1", port
59
+
60
+
61
+ def build_server_from_env():
62
+ return server.make_server(*_bind_host_port())
63
+
64
+
65
+ def serve(args: argparse.Namespace) -> int:
66
+ _apply_env_file(args)
67
+ if args.bind:
68
+ os.environ["AUTH_BIND"] = args.bind
69
+ try:
70
+ httpd = build_server_from_env()
71
+ except ValueError as exc:
72
+ # Refuse to come up rather than serve with a degraded origin binding.
73
+ print(f"[auth] configuration error: {exc}", file=sys.stderr)
74
+ return 2
75
+ try:
76
+ httpd.serve_forever()
77
+ except KeyboardInterrupt:
78
+ print("[auth] shutting down")
79
+ httpd.shutdown()
80
+ return 0
81
+
82
+
83
+ def _service_url() -> str:
84
+ """URL to probe: an explicit AUTH_SERVICE_URL wins, else the AUTH_BIND listener."""
85
+ override = os.environ.get("AUTH_SERVICE_URL")
86
+ if override:
87
+ return override.rstrip("/")
88
+ try:
89
+ host, port = _bind_host_port()
90
+ except ValueError:
91
+ # check() has already reported this; fall back to the documented
92
+ # default rather than raising a second time on the same bad value.
93
+ return "http://127.0.0.1:7700"
94
+ return f"http://{host}:{port}"
95
+
96
+
97
+ def check(args: argparse.Namespace) -> int:
98
+ _apply_env_file(args)
99
+ problems = 0
100
+ base = server._public_base()
101
+ print(f"AUTH_PUBLIC_BASE: {base}")
102
+ if base.rstrip("/").endswith("/auth"):
103
+ print(" WARNING: ends in /auth — the service adds /auth/* itself, so URLs would become /auth/auth/*")
104
+ problems += 1
105
+ if not base.startswith("https://"):
106
+ # Everything the player's browser carries over this base is live: the
107
+ # provider redirect, the authorization code, the nonce. The default is
108
+ # http://localhost:7700, so an install nobody configured lands here.
109
+ if _is_local_host(urlsplit(base).hostname or ""):
110
+ print(" WARNING: not https — a loopback base only works for local development; players need an https AUTH_PUBLIC_BASE behind your TLS proxy")
111
+ else:
112
+ print(" WARNING: not https — the login URL and the provider redirect would cross the network in the clear")
113
+ problems += 1
114
+ # `serve` refuses to start on an unparseable AUTH_BIND port, so `check`
115
+ # has to say so too rather than crashing on the same bad value.
116
+ try:
117
+ host, port = _bind_host_port()
118
+ print(f"AUTH_BIND: {host}:{port}")
119
+ if not _is_local_host(host):
120
+ print(" WARNING: not a loopback address — this listener has no authentication of its own and must not be reachable off-box; bind 127.0.0.1 and let your reverse proxy front it")
121
+ problems += 1
122
+ except ValueError as exc:
123
+ print(f"AUTH_BIND: ERROR: {exc}; `mudauth serve` will refuse to start")
124
+ problems += 1
125
+ # `serve` refuses to start on a bad hop count, so `check` has to say so
126
+ # too rather than reporting a configuration that will not come up.
127
+ try:
128
+ print(f"AUTH_TRUSTED_PROXY_HOPS: {server._configure_trusted_proxy_hops()}")
129
+ except ValueError as exc:
130
+ print(f" ERROR: {exc}; `mudauth serve` will refuse to start")
131
+ problems += 1
132
+ # Unset is a deliberately supported, backward-compatible state (not a
133
+ # problem to count), but an operator should still see it at a glance.
134
+ token = server._configure_auth_service_token()
135
+ if token:
136
+ print("AUTH_SERVICE_TOKEN: configured")
137
+ else:
138
+ print("AUTH_SERVICE_TOKEN: not set — the loopback exemption falls back to "
139
+ "peer + absent forwarding headers; see docs/deploy.md")
140
+ configs = server._load_provider_configs()
141
+ enabled = sorted(configs)
142
+ print(f"providers enabled: {', '.join(enabled) or '(none)'}")
143
+ if not enabled:
144
+ print(" WARNING: no provider is configured — nobody can sign in; set a <PROVIDER>_CLIENT_ID and _CLIENT_SECRET (or STEAM_API_KEY)")
145
+ problems += 1
146
+ for p in sorted(SUPPORTED_PROVIDERS):
147
+ if p not in configs and (os.environ.get(f"{p.upper()}_CLIENT_ID") or os.environ.get(f"{p.upper()}_CLIENT_SECRET")):
148
+ print(f" WARNING: {p} has only one of CLIENT_ID / CLIENT_SECRET set; it is disabled")
149
+ problems += 1
150
+ for p in enabled:
151
+ print(f" {p}: callback {configs[p].callback_url}")
152
+ url = _service_url()
153
+ r = client.request("GET", "/auth/healthz", base_url=url, timeout=3)
154
+ if r["status"] == 200:
155
+ print(f"service at {url}: ok")
156
+ else:
157
+ print(f"service at {url}: unreachable ({r['body'] or r['status']}) — is `mudauth serve` running?")
158
+ problems += 1
159
+ return 1 if problems else 0
160
+
161
+
162
+ def apple_secret(args: argparse.Namespace) -> int:
163
+ if not 0 < args.days <= 180:
164
+ print("--days must be 1..180 (Apple rejects JWTs valid > 6 months)", file=sys.stderr)
165
+ return 2
166
+ try:
167
+ import jwt
168
+ except ImportError:
169
+ print("PyJWT is required: pip install 'mudauth[apple]'", file=sys.stderr)
170
+ return 1
171
+ try:
172
+ with open(args.p8) as fh:
173
+ key = fh.read()
174
+ except OSError as exc:
175
+ print(f"cannot read --p8 file {args.p8}: {exc}", file=sys.stderr)
176
+ return 1
177
+ now = int(time.time())
178
+ try:
179
+ token = jwt.encode(
180
+ {"iss": args.team_id, "iat": now, "exp": now + args.days * 86400,
181
+ "aud": "https://appleid.apple.com", "sub": args.client_id},
182
+ key, algorithm="ES256", headers={"kid": args.key_id},
183
+ )
184
+ except Exception as exc: # noqa: BLE001 — PyJWT/cryptography raise various types
185
+ print(f"--p8 file {args.p8} is not a usable Sign in with Apple key: {exc}", file=sys.stderr)
186
+ return 1
187
+ print(token.decode() if isinstance(token, bytes) else token)
188
+ return 0
189
+
190
+
191
+ def main(argv: list[str] | None = None) -> int:
192
+ ap = argparse.ArgumentParser(prog="mudauth", description="Stateless OAuth/OIDC sign-in broker for MUDs")
193
+ ap.add_argument("--version", action="version", version=f"mudauth {__version__}")
194
+ sub = ap.add_subparsers(dest="cmd", required=True)
195
+
196
+ s = sub.add_parser("serve", help="run the loopback listener")
197
+ s.add_argument("--env-file", help="KEY=VALUE file to load (values already in the environment win)")
198
+ s.add_argument("--bind", help="host:port to listen on (default AUTH_BIND or 127.0.0.1:7700)")
199
+ s.set_defaults(func=serve)
200
+
201
+ c = sub.add_parser("check", help="validate configuration and reach the running service")
202
+ c.add_argument("--env-file")
203
+ c.set_defaults(func=check)
204
+
205
+ a = sub.add_parser("apple-secret", help="generate the Sign in with Apple client secret JWT")
206
+ a.add_argument("--team-id", required=True)
207
+ a.add_argument("--key-id", required=True)
208
+ a.add_argument("--client-id", required=True, help="Services ID (the OAuth client_id)")
209
+ a.add_argument("--p8", required=True, help="path to AuthKey_<KID>.p8")
210
+ a.add_argument("--days", type=int, default=180)
211
+ a.set_defaults(func=apple_secret)
212
+
213
+ args = ap.parse_args(argv)
214
+ return args.func(args)
215
+
216
+
217
+ if __name__ == "__main__":
218
+ sys.exit(main())
mudauth/client.py ADDED
@@ -0,0 +1,94 @@
1
+ """Loopback HTTP client for a mudauth service.
2
+
3
+ Games that cannot speak HTTP natively (LPC, for example) call this from
4
+ whatever host-language bridge they have. Anything that *can* speak HTTP can
5
+ ignore this module and follow docs/protocol.md directly.
6
+
7
+ When AUTH_SERVICE_TOKEN is set in the game's own environment, every request
8
+ carries it in X-Auth-Service-Token, which is how the service tells this game
9
+ apart from a browser once that check is enabled -- see server.py's
10
+ _is_trusted_loopback and docs/deploy.md for the required migration order.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ import os
17
+ import re
18
+ import urllib.error
19
+ import urllib.request
20
+
21
+ DEFAULT_BASE_URL = os.environ.get("AUTH_SERVICE_URL", "http://127.0.0.1:7700")
22
+
23
+ # Header carrying the shared secret that identifies this game to the auth
24
+ # service as trusted-loopback, once AUTH_SERVICE_TOKEN is configured (see
25
+ # server.py's _is_trusted_loopback). Must match server.py's
26
+ # AUTH_SERVICE_TOKEN_HEADER.
27
+ AUTH_SERVICE_TOKEN_HEADER = "X-Auth-Service-Token"
28
+
29
+ # secrets.token_urlsafe (the generator the docs recommend) only ever emits
30
+ # this charset. Anything else -- notably a stray \n or \r from a copy-paste
31
+ # into .env -- is not a token this client should send: putheader() would
32
+ # reject it anyway, and its ValueError embeds the whole value.
33
+ _SAFE_TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]+$")
34
+
35
+ _logger = logging.getLogger(__name__)
36
+
37
+
38
+ def request(
39
+ method: str,
40
+ path: str,
41
+ body: str | None = None,
42
+ *,
43
+ base_url: str | None = None,
44
+ timeout: float = 10,
45
+ ) -> dict:
46
+ """Perform one request and return ``{"status": int, "body": str}``.
47
+
48
+ Non-2xx responses are returned with their status (they are normal protocol
49
+ outcomes: 404 unknown provider, 400 bad state). Transport failures — service
50
+ down, timeout — return status 0 with the error text so callers can degrade
51
+ to password login instead of raising.
52
+ """
53
+ if not path.startswith("/"):
54
+ path = "/" + path
55
+ url = (base_url or DEFAULT_BASE_URL).rstrip("/") + path
56
+ method = method.upper()
57
+
58
+ data = None
59
+ headers = {"Accept": "application/json"}
60
+ # Read at call time, not at import, so a test can set/unset it around a
61
+ # single request and so an operator does not need a specific process
62
+ # start order for this module vs. the environment.
63
+ token = (os.environ.get("AUTH_SERVICE_TOKEN") or "").strip()
64
+ if token:
65
+ if _SAFE_TOKEN_RE.match(token):
66
+ headers[AUTH_SERVICE_TOKEN_HEADER] = token
67
+ else:
68
+ _logger.warning(
69
+ "AUTH_SERVICE_TOKEN contains characters outside a token's "
70
+ "expected charset; omitting %s on this request",
71
+ AUTH_SERVICE_TOKEN_HEADER,
72
+ )
73
+ if method == "POST":
74
+ data = (body or "{}").encode("utf-8")
75
+ headers["Content-Type"] = "application/json"
76
+
77
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
78
+ try:
79
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
80
+ return {"status": resp.status, "body": resp.read().decode("utf-8", "replace")}
81
+ except urllib.error.HTTPError as exc:
82
+ text = exc.read().decode("utf-8", "replace") if exc.fp else ""
83
+ return {"status": exc.code, "body": text}
84
+ except ValueError as exc:
85
+ # http.client.putheader raises ValueError("Invalid header value %r" %
86
+ # value) on a header it rejects, embedding the whole value -- which
87
+ # could be the token itself despite the charset check above (e.g.
88
+ # some other header). Log only the exception type, not its text, so a
89
+ # rejected header value never reaches the log.
90
+ _logger.warning("mudauth client %s %s failed: %s", method, path, type(exc).__name__)
91
+ return {"status": 0, "body": type(exc).__name__}
92
+ except Exception as exc: # noqa: BLE001 — transport failure of any kind
93
+ _logger.warning("mudauth client %s %s failed: %s", method, path, exc)
94
+ return {"status": 0, "body": str(exc)}
mudauth/ldmud.py ADDED
@@ -0,0 +1,20 @@
1
+ """LDMud python-efun registration (``pip install "mudauth[ldmud]"``).
2
+
3
+ Registered via the ``ldmud_efun`` entry point as ``auth_service_request``::
4
+
5
+ string auth_service_request(string method, string path, string body)
6
+
7
+ Returns a JSON string ``{"status": int, "body": string}``. Never raises to
8
+ LPC; transport errors return status 0.
9
+ """
10
+
11
+ import json
12
+
13
+ from . import client
14
+
15
+
16
+ def auth_service_request(method: str, path: str, body: str = "") -> str:
17
+ m = (method or "GET").upper()
18
+ if m not in ("GET", "POST"):
19
+ return json.dumps({"status": 0, "body": f"unsupported method {method}"})
20
+ return json.dumps(client.request(m, path or "/", body if isinstance(body, str) else ""))