qlix 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.
qlix/__init__.py ADDED
File without changes
qlix/artifacts.py ADDED
@@ -0,0 +1,39 @@
1
+ """Private, atomically installed local workflow artifacts."""
2
+
3
+ import json
4
+ import os
5
+ import uuid
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+
10
+ def durable_json(path: Path, value: dict[str, Any], *, replace: bool = False) -> None:
11
+ """Serialize and atomically install a private JSON artifact."""
12
+ payload = json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
13
+ durable_bytes(path, payload.encode("utf-8"), replace=replace)
14
+
15
+
16
+ def durable_bytes(path: Path, payload: bytes, *, replace: bool = False) -> None:
17
+ """Private artifact, fsynced and atomically installed; no clobber by default."""
18
+ if path.exists() and not replace:
19
+ raise FileExistsError(f"Artifact already exists: {path}")
20
+ temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
21
+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
22
+ try:
23
+ with os.fdopen(descriptor, "wb") as stream:
24
+ stream.write(payload)
25
+ stream.flush()
26
+ os.fsync(stream.fileno())
27
+ if replace:
28
+ os.replace(temporary, path)
29
+ else:
30
+ # The destination must not exist at installation time, even if another
31
+ # process creates it after the pre-existence check above.
32
+ os.link(temporary, path)
33
+ directory = os.open(path.parent, os.O_RDONLY)
34
+ try:
35
+ os.fsync(directory)
36
+ finally:
37
+ os.close(directory)
38
+ finally:
39
+ temporary.unlink(missing_ok=True)
qlix/auth/__init__.py ADDED
File without changes
qlix/auth/browser.py ADDED
@@ -0,0 +1,152 @@
1
+ """Shared persistent-browser SSO helper for local Qlik scripts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import sys
8
+ from contextlib import suppress
9
+ from pathlib import Path
10
+ from urllib.parse import urlparse
11
+
12
+ from playwright.async_api import BrowserContext, Page, Playwright
13
+ from playwright.async_api import Error as PlaywrightError
14
+
15
+ DEFAULT_PROFILE = Path.home() / ".local/state/qlix/browser"
16
+
17
+
18
+ def _is_hub_path(path: str, expected_path: str) -> bool:
19
+ """Match the hub path itself or a descendant, not a prefix collision."""
20
+ return path == expected_path or path.startswith(f"{expected_path}/")
21
+
22
+
23
+ def _profile_directory() -> Path:
24
+ configured = os.environ.get("QLIK_BROWSER_PROFILE")
25
+ profile = Path(configured).expanduser() if configured else DEFAULT_PROFILE
26
+ profile.mkdir(parents=True, exist_ok=True, mode=0o700)
27
+ if os.name == "posix" and profile.stat().st_mode & 0o077:
28
+ raise PermissionError(
29
+ f"The Qlik SSO profile {profile} is accessible to group or other users. "
30
+ "Restrict its permissions to the owner before using it."
31
+ )
32
+ return profile
33
+
34
+
35
+ def _sso_timeout_ms() -> int:
36
+ """SSO wait timeout in milliseconds (``QLIK_SSO_TIMEOUT_MS``, default 300000).
37
+
38
+ Slow sign-in flows (MFA, Conditional Access) can exceed the default five
39
+ minutes; operators can widen the wait without editing the module.
40
+ """
41
+ raw = os.environ.get("QLIK_SSO_TIMEOUT_MS", "").strip()
42
+ if not raw:
43
+ return 300_000
44
+ try:
45
+ value = int(raw)
46
+ except ValueError as exc:
47
+ raise ValueError(
48
+ "QLIK_SSO_TIMEOUT_MS must be a positive integer number of milliseconds"
49
+ ) from exc
50
+ if value <= 0:
51
+ raise ValueError("QLIK_SSO_TIMEOUT_MS must be a positive integer number of milliseconds")
52
+ return value
53
+
54
+
55
+ async def _close_context(context: BrowserContext) -> None:
56
+ """Close a browser context without replacing the error that triggered cleanup."""
57
+ with suppress(Exception, asyncio.CancelledError):
58
+ await context.close()
59
+
60
+
61
+ async def open_authenticated_page(
62
+ playwright: Playwright, base_url: str
63
+ ) -> tuple[BrowserContext, Page]:
64
+ """Open the hub using a persistent browser profile and wait for SSO if needed."""
65
+ mode = os.environ.get("QLIK_HEADLESS", "0")
66
+ if mode not in {"0", "1"}:
67
+ raise ValueError("QLIK_HEADLESS must be 0 (interactive) or 1 (reuse existing SSO).")
68
+ headless = mode == "1"
69
+ sso_timeout_ms = _sso_timeout_ms()
70
+ profile = _profile_directory()
71
+ try:
72
+ context = await playwright.chromium.launch_persistent_context(
73
+ user_data_dir=str(profile),
74
+ headless=headless,
75
+ )
76
+ except PlaywrightError as error:
77
+ if "Opening in existing browser session" in str(error):
78
+ raise RuntimeError(
79
+ f"The Qlik SSO profile {profile} is already open in another Chromium process. "
80
+ "Close that browser before running another Qlik script; do not delete profile "
81
+ "lock files while Chromium is active."
82
+ ) from error
83
+ raise
84
+ try:
85
+ page = context.pages[0] if context.pages else await context.new_page()
86
+ parsed = urlparse(base_url)
87
+ hub_url = f"{base_url.rstrip('/')}/hub/"
88
+ expected_path = f"{parsed.path.rstrip('/')}/hub"
89
+ await page.goto(hub_url, wait_until="domcontentloaded")
90
+ current_url = urlparse(page.url)
91
+ if not (
92
+ current_url.netloc == parsed.netloc and _is_hub_path(current_url.path, expected_path)
93
+ ):
94
+ if headless:
95
+ raise RuntimeError(
96
+ "Headless Qlik requires an already authenticated SSO profile. "
97
+ "Run with QLIK_HEADLESS=0 on a graphical desktop to complete sign-in."
98
+ )
99
+ print(
100
+ "Complete SSO sign-in in the Qlik browser window if prompted; "
101
+ "the script will continue automatically.",
102
+ file=sys.stderr,
103
+ flush=True,
104
+ )
105
+ await page.wait_for_function(
106
+ "({host, path}) => location.host === host && "
107
+ "(location.pathname === path || location.pathname.startsWith(path + '/'))",
108
+ arg={"host": parsed.netloc, "path": expected_path},
109
+ timeout=sso_timeout_ms,
110
+ )
111
+ return context, page
112
+ except PlaywrightError as error:
113
+ await _close_context(context)
114
+ if "Target page, context or browser has been closed" in str(error):
115
+ raise RuntimeError(
116
+ "The Qlik SSO browser window closed before authentication returned "
117
+ "to the Hub. Keep the runner's Google Chrome for Testing window open "
118
+ "until the Hub appears, then retry."
119
+ ) from error
120
+ raise
121
+ except Exception:
122
+ await _close_context(context)
123
+ raise
124
+ except BaseException:
125
+ # Preserve interruptions (for example Ctrl-C during SSO) even if the
126
+ # browser driver has already disconnected and context.close() fails.
127
+ await _close_context(context)
128
+ raise
129
+
130
+
131
+ async def open_hub_page(context: BrowserContext, base_url: str, timeout_ms: int = 60_000) -> Page:
132
+ """Open another hub page in an already authenticated context.
133
+
134
+ The page shares the context's cookies, so it reuses the same Qlik proxy session
135
+ instead of signing in again. It never waits for interactive SSO.
136
+ """
137
+ page = await context.new_page()
138
+ parsed = urlparse(base_url)
139
+ expected_path = f"{parsed.path.rstrip('/')}/hub"
140
+ try:
141
+ await page.goto(f"{base_url.rstrip('/')}/hub/", wait_until="domcontentloaded")
142
+ await page.wait_for_function(
143
+ "({host, path}) => location.host === host && "
144
+ "(location.pathname === path || location.pathname.startsWith(path + '/'))",
145
+ arg={"host": parsed.netloc, "path": expected_path},
146
+ timeout=timeout_ms,
147
+ )
148
+ return page
149
+ except BaseException:
150
+ with suppress(Exception):
151
+ await page.close()
152
+ raise