nkx-runtime 2.2.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.

Potentially problematic release.


This version of nkx-runtime might be problematic. Click here for more details.

@@ -0,0 +1,39 @@
1
+ """Structured trace logging, emitted to stderr as JSON lines.
2
+
3
+ Separate from the human-readable print() output used throughout the CLI:
4
+ trace() is for machine consumption — entrypoint.sh picks these lines out of
5
+ stderr and forwards them to the backend's job-log endpoint, where they're
6
+ persisted with stage/action tags intact instead of being bucketed as generic
7
+ "stdout"/"stderr" text. Deliberately kept off stdout: analyze/status --json
8
+ write a single JSON document to stdout for the backend to parse, and
9
+ interleaved trace lines would corrupt it.
10
+
11
+ Enabled by NKX_TRACE (the core/.env flag, baked into the image at build
12
+ time) or NKX_VERBOSE (a per-job override the backend can still inject).
13
+ Checked at call time, not import time, since embedded use (nkx.install())
14
+ doesn't go through entrypoint.sh and may set the env var after import.
15
+ """
16
+ from __future__ import annotations
17
+ import json
18
+ import os
19
+ import sys
20
+
21
+
22
+ def _enabled() -> bool:
23
+ return (
24
+ os.environ.get("NKX_TRACE", "").lower() in ("1", "true")
25
+ or os.environ.get("NKX_VERBOSE", "").lower() in ("1", "true")
26
+ )
27
+
28
+
29
+ def trace(stage: str, action: str, message: str, level: str = "info", **data) -> None:
30
+ """Emit one structured trace line to stdout. No-op unless tracing is enabled."""
31
+ if not _enabled():
32
+ return
33
+ print(json.dumps({
34
+ "stage": stage,
35
+ "action": action,
36
+ "level": level,
37
+ "message": message,
38
+ "data": data,
39
+ }), file=sys.stderr, flush=True)
nkx_runtime/bridge.py ADDED
@@ -0,0 +1,49 @@
1
+ """Env-mutation bridge into core loader (internal implementation detail)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ from .credentials.chain import ResolvedCredentials
8
+
9
+
10
+ def apply_resolved_credentials(resolved: ResolvedCredentials) -> None:
11
+ """Set process env once so core's env-first readers pick up SDK values."""
12
+ if resolved.endpoint:
13
+ os.environ["NKX_KEK_URL"] = resolved.endpoint
14
+
15
+ if resolved.license_jwt:
16
+ os.environ["NKX_LICENSE_KEY"] = resolved.license_jwt.expose()
17
+
18
+ if resolved.register_token:
19
+ os.environ["NKX_REGISTER_TOKEN"] = resolved.register_token.expose()
20
+
21
+ if resolved.project_id:
22
+ os.environ["NKX_PROJECT_ID"] = resolved.project_id
23
+
24
+ if resolved.runtime_env_token:
25
+ os.environ["NKX_RUNTIME_TOKEN"] = resolved.runtime_env_token.expose()
26
+
27
+ if resolved.credentials_dir:
28
+ os.environ["NKX_CREDENTIALS_DIR"] = str(resolved.credentials_dir)
29
+
30
+ if resolved.repo_root:
31
+ os.environ["NKX_REPO_ROOT"] = str(resolved.repo_root)
32
+
33
+ # config.json-resolved slots (see credentials/chain.py) — set here so
34
+ # core's existing env-only readers (context._get_public_key(),
35
+ # _require_https_origin) keep working unchanged whether the value came
36
+ # from an env var or from `nkx register`'s config.json. Only set when
37
+ # present/true: never clobber an operator's own NKX_ALLOW_INSECURE_BACKEND_URL
38
+ # with a false default.
39
+ if resolved.license_public_key:
40
+ os.environ["NKX_LICENSE_PUBLIC_KEY"] = resolved.license_public_key
41
+
42
+ if resolved.allow_insecure_backend_url:
43
+ os.environ["NKX_ALLOW_INSECURE_BACKEND_URL"] = "1"
44
+
45
+
46
+ def zeroize_register_token(resolved: ResolvedCredentials) -> None:
47
+ if resolved.register_token:
48
+ resolved.register_token.zeroize()
49
+ os.environ.pop("NKX_REGISTER_TOKEN", None)
nkx_runtime/cli.py ADDED
@@ -0,0 +1,121 @@
1
+ """``nkx-run`` — zero-source-touch CLI wrapper for protected Python apps.
2
+
3
+ Mirrors packages/sdk-js/bin/nkx-run.js: install the runtime hook, then run
4
+ the entrypoint in-process as if it had been invoked directly (``python
5
+ entrypoint.py args...``). Unlike the Node wrapper this never needs to be
6
+ async — the Python KEK derive call is a plain blocking ``urllib.request``
7
+ call, so there's no ``--require``-style synchronicity problem to work around.
8
+
9
+ Also supports ``-m <module>`` (module mode) for the common production
10
+ invocation style — gunicorn/celery workers, etc. — that exec via
11
+ ``python -m``. See discover_repo_root() in config.py for the upward
12
+ ``.nkx/`` search used when NKX_REPO_ROOT is unset.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import runpy
19
+ import sys
20
+
21
+ from .client import RuntimeClient
22
+ from .config import discover_repo_root
23
+
24
+
25
+ def _usage() -> str:
26
+ return (
27
+ "Usage: nkx-run <entrypoint.py> [args...]\n"
28
+ " nkx-run -m <module> [args...]\n"
29
+ " nkx-run --version\n"
30
+ " nkx-run --help"
31
+ )
32
+
33
+
34
+ def _version() -> str:
35
+ """The installed nkx-runtime version, however it was installed.
36
+
37
+ importlib.metadata reads the *installed distribution*, so a repacked
38
+ wheel and a published one report honestly rather than echoing a constant
39
+ baked into the source. Falls back rather than raising: a version command
40
+ that crashes is worse than one that says it does not know, and this is
41
+ the first thing anyone runs when a deployment is misbehaving.
42
+ """
43
+ try:
44
+ from importlib.metadata import version
45
+ return version("nkx-runtime")
46
+ except Exception:
47
+ return "unknown (nkx-runtime distribution metadata not found)"
48
+
49
+
50
+ def main(argv: list[str] | None = None) -> None:
51
+ args = list(sys.argv[1:] if argv is None else argv)
52
+ if not args:
53
+ print(_usage(), file=sys.stderr)
54
+ sys.exit(1)
55
+
56
+ # Handled before entrypoint parsing, because args[0] is otherwise taken as
57
+ # a path: `nkx-run --version` used to try to *run* a file called
58
+ # "--version" and die with a FileNotFoundError with the cwd interpolated
59
+ # into it. Asking a runtime which version it is, is the first diagnostic
60
+ # step when a protected app misbehaves — and the .enc/.nkxc release skew
61
+ # was exactly that kind of failure, where this command would have answered
62
+ # the question immediately had it existed.
63
+ #
64
+ # Deliberately not argparse: bare `nkx-run` must keep printing usage to
65
+ # stderr and exiting 1 (publish-runtime-sdk.yml asserts that exact
66
+ # behaviour), and everything after the entrypoint belongs to the customer's
67
+ # program, not to us.
68
+ if args[0] in ("--version", "-V"):
69
+ print(_version())
70
+ sys.exit(0)
71
+ if args[0] in ("--help", "-h"):
72
+ print(_usage())
73
+ sys.exit(0)
74
+
75
+ module_name: str | None = None
76
+ entrypoint: str | None = None
77
+ if args[0] == "-m":
78
+ if len(args) < 2:
79
+ print(_usage(), file=sys.stderr)
80
+ sys.exit(1)
81
+ module_name, rest = args[1], args[2:]
82
+ else:
83
+ entrypoint, rest = args[0], args[1:]
84
+
85
+ # Precedence, strict: explicit NKX_REPO_ROOT env var > upward
86
+ # discovery of .nkx/manifest.json > cwd. Discovery never overrides an
87
+ # explicit root — it only fills in when the operator hasn't set one.
88
+ repo_root = os.environ.get("NKX_REPO_ROOT") or discover_repo_root() or os.getcwd()
89
+ repo_root = os.path.abspath(repo_root)
90
+
91
+ # runpy.run_path()/run_module() below don't put repo_root on sys.path by
92
+ # themselves (run_path only adds the entrypoint's own directory; run_module
93
+ # resolves purely via the existing import system) — for a nested
94
+ # entrypoint/module (e.g. services/api/main.py or riskops_processor.cli)
95
+ # with repo-root-relative absolute imports, that's not enough. Protected
96
+ # modules resolve fine either way (ProtectedFinder is a meta_path hook,
97
+ # not sys.path-based), but unprotected sibling modules under repo_root
98
+ # need it explicitly on sys.path. If the importable package lives in a
99
+ # subdirectory of repo_root rather than at repo_root itself, set
100
+ # PYTHONPATH to that subdirectory too — this insertion alone won't reach
101
+ # it (see packages/sdk-spec/customer-deploy.md).
102
+ if repo_root not in sys.path:
103
+ sys.path.insert(0, repo_root)
104
+
105
+ try:
106
+ RuntimeClient.from_env(repo_root=repo_root).install(repo_root=repo_root)
107
+ except Exception as exc:
108
+ print(str(exc), file=sys.stderr)
109
+ sys.exit(1)
110
+
111
+ if module_name is not None:
112
+ sys.argv = [module_name, *rest]
113
+ runpy.run_module(module_name, run_name="__main__", alter_sys=True)
114
+ else:
115
+ entry_path = os.path.abspath(entrypoint)
116
+ sys.argv = [entry_path, *rest]
117
+ runpy.run_path(entry_path, run_name="__main__")
118
+
119
+
120
+ if __name__ == "__main__":
121
+ main()
nkx_runtime/client.py ADDED
@@ -0,0 +1,179 @@
1
+ """Runtime client — orchestrates credential resolution and loader install."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from .bridge import apply_resolved_credentials, zeroize_register_token
11
+ from .config import RuntimeConfig
12
+ from .credentials import resolve_credentials
13
+ from .errors import (
14
+ ConfigurationError,
15
+ KekDeniedError,
16
+ KekUnreachableError,
17
+ RegistrationDeniedError,
18
+ )
19
+
20
+
21
+ def _has_manifest(repo_root: str) -> bool:
22
+ return (Path(repo_root) / ".nkx" / "manifest.json").is_file()
23
+
24
+
25
+ class RuntimeClient:
26
+ """AWS-style runtime client for customer deployed apps."""
27
+
28
+ def __init__(self, config: RuntimeConfig | None = None) -> None:
29
+ self._config = config or RuntimeConfig()
30
+
31
+ @classmethod
32
+ def from_env(cls, repo_root: str = ".") -> RuntimeClient:
33
+ return cls(RuntimeConfig.from_env(repo_root=repo_root))
34
+
35
+ def install(self, repo_root: str | None = None) -> None:
36
+ if repo_root is not None:
37
+ self._config.repo_root = repo_root
38
+
39
+ resolved = resolve_credentials(self._config)
40
+ root = str(resolved.repo_root or self._config.resolve_repo_root())
41
+
42
+ # Only the public key, not the full apply_resolved_credentials() —
43
+ # that call also sets NKX_KEK_URL/NKX_REGISTER_TOKEN/NKX_RUNTIME_TOKEN
44
+ # etc., which deliberately must NOT happen on the devmode path (the
45
+ # comment below explains why devmode has to see a genuinely bare
46
+ # environment). But _is_developer_license() below verifies the
47
+ # license JWT's signature, which needs NKX_LICENSE_PUBLIC_KEY in the
48
+ # environment; when that key only resolved from `nkx register`'s
49
+ # config.json (not an env var already set by the caller), it wasn't
50
+ # in os.environ yet at the point this check used to run, so an
51
+ # offline developer whose public key came only from config.json was
52
+ # never detected as a developer licence and fell through to the
53
+ # "NKX_KEK_URL is not set" error instead of devmode. Setting only
54
+ # this one value early is side-effect-free for the devmode path.
55
+ if resolved.license_public_key:
56
+ os.environ["NKX_LICENSE_PUBLIC_KEY"] = resolved.license_public_key
57
+
58
+ if not _has_manifest(root):
59
+ return
60
+
61
+ if self._should_use_devmode(resolved):
62
+ self._install_devmode(root=root, resolved=resolved)
63
+ return
64
+
65
+ # No endpoint, so there is no server to make the routing decision and
66
+ # no way to derive anything. Offline, a developer key has exactly two
67
+ # possible outcomes — legacy plaintext stubs, or a loud failure on the
68
+ # first import of a file that needs a KEK — and _install_devmode()
69
+ # produces both correctly. Choosing between them here is not the
70
+ # client granting itself anything: real content is unreachable either
71
+ # way, and this path can only ever serve *less*. A runtime key falls
72
+ # through to the "endpoint required" error below, which is the right
73
+ # answer for a deployment.
74
+ #
75
+ # Mirrors core/loader.py's own offline branch and client.js's
76
+ # (packages/sdk-js/src/client.js). Python had neither, so an offline
77
+ # developer hit ConfigurationError here and never reached
78
+ # DevModeFinder at all, while their JS colleagues kept working.
79
+ if resolved.endpoint_is_default and self._is_developer_license(resolved):
80
+ self._install_devmode(root=root, resolved=resolved)
81
+ return
82
+
83
+ if resolved.endpoint_is_default:
84
+ raise ConfigurationError(
85
+ "NKX_KEK_URL is not set — cannot start runtime SDK."
86
+ )
87
+
88
+ apply_resolved_credentials(resolved)
89
+
90
+ if self._config.kek_refresh_seconds is not None:
91
+ os.environ["NKX_KEK_REFRESH_SECONDS"] = str(
92
+ self._config.kek_refresh_seconds
93
+ )
94
+ os.environ["NKX_RUNTIME_TIMEOUT_SECONDS"] = str(self._config.timeout_seconds)
95
+ os.environ["NKX_RUNTIME_MAX_RETRIES"] = str(self._config.max_retries)
96
+
97
+ from nkx_runtime._core.loader import _install_core
98
+
99
+ try:
100
+ _install_core(root)
101
+ except ImportError as exc:
102
+ from .http.middleware import redact_message
103
+ from ._core.instanceauth import RegistrationDeniedError as _CoreRegDenied
104
+ from ._core.remotekek import KekDeniedError as _CoreKekDenied
105
+ from ._core.remotekek import KekUnreachableError as _CoreKekUnreachable
106
+
107
+ message = redact_message(str(exc))
108
+ # __cause__ is the original typed engine exception, preserved by
109
+ # loader.py's `raise ImportError(...) from exc` — map it back to
110
+ # the SDK's public typed error classes so `except KekDeniedError:`
111
+ # etc. (the documented pattern) actually fires (audit finding
112
+ # B21). Falls back to plain ImportError for cases with no typed
113
+ # cause (e.g. legacy-manifest/no-license-key checks above).
114
+ cause = exc.__cause__
115
+ if isinstance(cause, _CoreKekDenied):
116
+ raise KekDeniedError(message) from None
117
+ if isinstance(cause, _CoreKekUnreachable):
118
+ raise KekUnreachableError(message) from None
119
+ if isinstance(cause, _CoreRegDenied):
120
+ raise RegistrationDeniedError(message) from None
121
+ raise ImportError(message) from None
122
+ finally:
123
+ # Always zeroize, including on failure — a denied/unreachable
124
+ # install must not leave a scoped runtime:register credential
125
+ # live in-process for callers that catch and continue past this
126
+ # (audit finding B22).
127
+ zeroize_register_token(resolved)
128
+
129
+ def _should_use_devmode(self, resolved) -> bool:
130
+ dev_mode = self._config.dev_mode or os.environ.get("NKX_DEVMODE") == "1"
131
+ return dev_mode and not resolved.endpoint
132
+
133
+ @staticmethod
134
+ def _is_developer_license(resolved) -> bool:
135
+ """Whether the resolved licence is a developer key.
136
+
137
+ `kind` is the spec 16 phase 2 spelling, `purpose` the older one; the
138
+ backend signs both. Fails open to False on any verification error,
139
+ matching context.is_developer_license() and client.js — an invalid
140
+ JWT here just means this is not treated as a developer licence rather
141
+ than crashing before the real error is reached.
142
+ """
143
+ if not resolved.license_jwt:
144
+ return False
145
+ try:
146
+ from nkx_runtime._core.context import _verify_license_jwt
147
+
148
+ payload = _verify_license_jwt(resolved.license_jwt.expose())
149
+ except Exception:
150
+ return False
151
+ return (payload.get("kind") or payload.get("purpose")) == "developer"
152
+
153
+ def _install_devmode(self, root: str, resolved=None) -> None:
154
+ from nkx_runtime._core.devmode import DevModeFinder
155
+
156
+ manifest_path = Path(root) / ".nkx" / "manifest.json"
157
+ if not manifest_path.exists():
158
+ return
159
+ manifest = json.loads(manifest_path.read_text())
160
+ # build_id lives under manifest["context"] while kdf/key_version are
161
+ # top-level, the same wiring _install_core() does. Passing them does
162
+ # NOT make encrypted mocks work offline: DevModeFinder's lazy derive
163
+ # calls /internal/keys/derive-mock, and this branch is reached only
164
+ # when there is no endpoint to call. It changes nothing observable
165
+ # today — both routes raise the same ImportError — and is passed so
166
+ # the constructor is not left half-filled from fields sitting in this
167
+ # same function. Offline encrypted mocks are an open product question;
168
+ # see core/CONTEXT.md.
169
+ ctx = manifest.get("context") or {}
170
+ license_jwt = ""
171
+ if resolved is not None and resolved.license_jwt:
172
+ license_jwt = resolved.license_jwt.expose()
173
+ sys.meta_path.insert(0, DevModeFinder(
174
+ root, manifest,
175
+ build_id=ctx.get("build_id", ""),
176
+ kdf=manifest.get("kdf"),
177
+ key_version=manifest.get("key_version"),
178
+ license_jwt=license_jwt,
179
+ ))
nkx_runtime/config.py ADDED
@@ -0,0 +1,122 @@
1
+ """Runtime SDK configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from .secrets import SecretStr
10
+
11
+ # The built-in fallback backend origin for `endpoint`, the last resort in
12
+ # the credential chain's precedence for that slot (ctor -> NKX_KEK_URL env
13
+ # -> config.json's "endpoint" -> this). Canonical value documented in
14
+ # packages/sdk-spec/credentials.md — this literal must stay identical to
15
+ # the JS SDK's own copy and to web/lib/connectSnippets.ts's, and a guard
16
+ # test/script fails the build if any of the three drift apart.
17
+ DEFAULT_KEK_URL = "https://gateway.nakodax.com"
18
+
19
+
20
+ @dataclass
21
+ class RuntimeConfig:
22
+ """AWS-style config object for the runtime client."""
23
+
24
+ repo_root: str = "."
25
+ endpoint: str | None = None
26
+ license_jwt: SecretStr | None = None
27
+ register_token: SecretStr | None = None
28
+ project_id: str | None = None
29
+ runtime_env_token: SecretStr | None = None
30
+ credentials_dir: str | None = None
31
+ kek_refresh_seconds: int | None = None
32
+ dev_mode: bool = False
33
+ timeout_seconds: float = 10.0
34
+ max_retries: int = 3
35
+
36
+ def resolve_repo_root(self) -> Path:
37
+ return Path(self.repo_root).resolve()
38
+
39
+ def resolve_credentials_dir(self) -> Path:
40
+ if self.credentials_dir:
41
+ return Path(self.credentials_dir).resolve()
42
+ env_dir = os.environ.get("NKX_CREDENTIALS_DIR", "").strip()
43
+ if env_dir:
44
+ return Path(env_dir).resolve()
45
+ return self.resolve_repo_root() / ".nkx"
46
+
47
+ @classmethod
48
+ def from_env(cls, repo_root: str = ".") -> RuntimeConfig:
49
+ # Read before the constructor call because both fields are plain
50
+ # non-optional numbers: an unset variable means "keep the dataclass
51
+ # default", not "set this to None".
52
+ #
53
+ # Without these two reads, from_env() (and so nkx-run) always built a
54
+ # config holding the defaults 10s/3, and client.install() then wrote
55
+ # those defaults back into NKX_RUNTIME_TIMEOUT_SECONDS and
56
+ # NKX_RUNTIME_MAX_RETRIES — silently overwriting whatever an operator
57
+ # had set, which is what the engine (_core/remotekek.py,
58
+ # _core/instanceauth.py) actually reads. sdk-js/src/config.js has read
59
+ # both since the same bug was found there; this is the half that was
60
+ # never brought back (PKG-04).
61
+ timeout_seconds = _float_from_env("NKX_RUNTIME_TIMEOUT_SECONDS")
62
+ max_retries = _int_from_env("NKX_RUNTIME_MAX_RETRIES")
63
+ defaults = cls()
64
+ return cls(
65
+ repo_root=repo_root,
66
+ endpoint=os.environ.get("NKX_KEK_URL", "").strip() or None,
67
+ license_jwt=_secret_from_env("NKX_LICENSE_KEY"),
68
+ register_token=_secret_from_env("NKX_REGISTER_TOKEN"),
69
+ project_id=os.environ.get("NKX_PROJECT_ID", "").strip() or None,
70
+ runtime_env_token=_secret_from_env("NKX_RUNTIME_TOKEN"),
71
+ credentials_dir=os.environ.get("NKX_CREDENTIALS_DIR", "").strip() or None,
72
+ dev_mode=os.environ.get("NKX_DEVMODE") == "1",
73
+ kek_refresh_seconds=_int_from_env("NKX_KEK_REFRESH_SECONDS"),
74
+ timeout_seconds=timeout_seconds if timeout_seconds is not None else defaults.timeout_seconds,
75
+ max_retries=max_retries if max_retries is not None else defaults.max_retries,
76
+ )
77
+
78
+
79
+ def discover_repo_root(start: str | None = None, max_depth: int = 64) -> str | None:
80
+ """Walk upward from `start` (default cwd) looking for `.nkx/manifest.json`,
81
+ like git discovers `.git`. Returns the first matching directory, or None.
82
+
83
+ First match wins — this never searches past a hit for other candidates
84
+ further up, so a process started inside a deployment root (e.g.
85
+ services/processor/) finds that app's own manifest, not a parent
86
+ monorepo's, even if both exist. Only used as a fallback when
87
+ NKX_REPO_ROOT is unset — an explicit root always wins over discovery.
88
+ """
89
+ current = Path(start or os.getcwd()).resolve()
90
+ for _ in range(max_depth):
91
+ if (current / ".nkx" / "manifest.json").is_file():
92
+ return str(current)
93
+ parent = current.parent
94
+ if parent == current:
95
+ return None
96
+ current = parent
97
+ return None
98
+
99
+
100
+ def _secret_from_env(name: str) -> SecretStr | None:
101
+ raw = os.environ.get(name, "").strip()
102
+ return SecretStr(raw) if raw else None
103
+
104
+
105
+ def _float_from_env(name: str) -> float | None:
106
+ raw = os.environ.get(name, "").strip()
107
+ if not raw:
108
+ return None
109
+ try:
110
+ return float(raw)
111
+ except ValueError:
112
+ return None
113
+
114
+
115
+ def _int_from_env(name: str) -> int | None:
116
+ raw = os.environ.get(name, "").strip()
117
+ if not raw:
118
+ return None
119
+ try:
120
+ return int(raw)
121
+ except ValueError:
122
+ return None
@@ -0,0 +1,5 @@
1
+ """Credential chain package."""
2
+
3
+ from .chain import ResolvedCredentials, resolve_credentials
4
+
5
+ __all__ = ["ResolvedCredentials", "resolve_credentials"]