Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/windows-studio/src/packlab_studio/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,8 @@ def translate_widget_tree(root: QWidget) -> None:
"Server address": "Sunucu adresi",
"Company sign-in (issuer)": "Şirket girişi (issuer)",
"Desktop app id": "Masaüstü uygulama kimliği",
"Server audience": "Sunucu hedef kitlesi (audience)",
"only if your company sign-in needs one": "yalnızca şirket girişiniz istiyorsa",
"Released revision": "Yayınlanan revizyon",
"Observations": "Gözlemler",
"Inspection": "Muayene",
Expand Down
42 changes: 33 additions & 9 deletions apps/windows-studio/src/packlab_studio/warehouse_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,14 @@
)

from packlab_core import secure_store
from packlab_core.desktop_signin import TokenSet, TokenSource, discover, refresh, sign_in
from packlab_core.desktop_signin import (
INVALID_GRANT,
TokenSet,
TokenSource,
discover,
refresh,
sign_in,
)
from packlab_core.server_sync import PackLabServerClient, ServerError, SyncAgent
from packlab_core.sync_loop import SyncLoop, SyncStatus

Expand Down Expand Up @@ -80,6 +87,10 @@ def __init__(self, data_root: Path | None = None) -> None:
self.issuer = QLineEdit(settings.get("issuer", ""), self)
self.issuer.setPlaceholderText("https://login.example.com/realms/povu")
self.app_client = QLineEdit(settings.get("app_client", "packlab-desktop"), self)
# the server's configured OIDC audience, for IdPs that take it from the request
# (Auth0); empty: none is sent (Keycloak puts it in the token by client scope)
self.audience = QLineEdit(settings.get("server_audience", ""), self)
self.audience.setPlaceholderText(tr("only if your company sign-in needs one"))
self.sign_in_button = QPushButton(tr("Sign in"), self)
self.sign_in_button.setObjectName("packlab.warehouse.signin")
self.sign_in_button.clicked.connect(self.start_sign_in)
Expand All @@ -97,6 +108,7 @@ def __init__(self, data_root: Path | None = None) -> None:
form.addRow(tr("Server address"), self.server_url)
form.addRow(tr("Company sign-in (issuer)"), self.issuer)
form.addRow(tr("Desktop app id"), self.app_client)
form.addRow(tr("Server audience"), self.audience)
buttons = QHBoxLayout()
buttons.addWidget(self.sign_in_button)
buttons.addWidget(self.sync_button)
Expand Down Expand Up @@ -163,7 +175,10 @@ def start_sign_in(self) -> None:
if not (server and issuer and app):
self._show_failure(tr("Enter the server address, the company sign-in and the app id."))
return
self._save_settings({"server_url": server, "issuer": issuer, "app_client": app})
audience = self.audience.text().strip()
self._save_settings(
{"server_url": server, "issuer": issuer, "app_client": app, "server_audience": audience}
)
# maybe another person: the previous sign-ins are revoked first, in order, so a
# grant-wide revocation can never cancel the new sign-in
previous = [self.erp.forget(revoke=False), self._signed_token]
Expand All @@ -179,7 +194,7 @@ def work() -> None:
revoke_token(old)
try:
endpoints = discover(issuer, allow_loopback_http=loopback)
tokens = sign_in(endpoints, app)
tokens = sign_in(endpoints, app, audience=audience or None)
identity = f"{endpoints.issuer}|{_subject(tokens.access_token)}"
source = me._token_source(server, endpoints, app, identity, tokens)
_emit(bridge.signed_in, (server, source, identity))
Expand All @@ -197,7 +212,9 @@ def resume_sign_in(self) -> None:
self.status_label.setText(tr("Resuming your sign-in..."))

me, bridge, loopback = self._me, self.bridge, self.allow_loopback_http
signin_path = self._signin_path()
signin_path, lock = self._signin_path(), self._session_lock
with lock:
session = self._session # a sign-in started meanwhile is never deleted

def work() -> None:
try:
Expand All @@ -209,9 +226,15 @@ def work() -> None:
source = me._token_source(server, endpoints, app, identity, tokens)
_emit(bridge.signed_in, (server, source, identity))
except Exception as error: # noqa: BLE001 - any failure: sign in again
if str(error).startswith(("token_refused", "idp_discovery_failed")):
secure_store.delete(signin_path) # refused: never retried
# unreachable IdP (offline start): the saved sign-in stays for next time
if str(error) == INVALID_GRANT: # refused for good: never retried
with lock:
try:
current = me._session
except ReferenceError: # the page is gone
current = None
if current == session:
secure_store.delete(signin_path)
# unreachable or failing IdP (offline start): the saved sign-in stays
_emit(
bridge.failed,
tr("saved sign-in expired: sign in again ({e})").format(
Expand Down Expand Up @@ -257,15 +280,16 @@ def _token_source(
def keep(fresh: TokenSet) -> None:
# a late refresh of an older sign-in (after Sign out, or another person signed in)
# must never write the saved sign-in again
if not fresh.refresh_token:
return
with lock:
try:
current = me._session
except ReferenceError: # the page is gone
return
if session != current:
return
if not fresh.refresh_token: # none, or the IdP refused it (invalid_grant)
secure_store.delete(signin_path)
return
secure_store.save(
signin_path,
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# CLAUDE_PEER_REVIEW PL-0506 hardening V01 (PR #114)
Reviewer: independent Claude subagent (did not author). Date: 2026-12-04.
Source: feat/pl-0506-signin-hardening head 5892e5768f931f815c7136c7b231e6f894cf81a6, base 89ccec8a.
Verdict: PASS_WITH_FIXES

Evidence: pytest (test_desktop_signin, test_secure_store, test_warehouse_view, test_warehouse_erp, server/test_oidc): 62 passed, 1 warning (existing tamper_state fake-browser thread HTTPError 400). mypy clean (352 files). ruff check core apps server tools tests clean. Mutations (11): 9 killed; SURVIVED M4 (error handled before iss) and M7 (keep() deletes before session check).

Findings:
- F1 Medium (test gap): iss-before-error ordering (desktop_signin.py:172-178) correct but untested.
- F2 Medium (test gap): old-session on_refresh(None) must not delete a newer sign-in (warehouse_view.py:275-284); code correct, untested.
- F3 Low/Info: resume failure delete (warehouse_view.py:227-228) not under _session_lock/session snapshot; mitigated by disabled Sign in during resume.
- F4 Info: HTTP 200 + error=invalid_grant without access_token treated as INVALID_GRANT (fail-closed).

Security conclusions: RFC 9207 exact match vs discovered issuer, missing iss refused when advertised, empty iss refused; no refused/forged path yields tokens; invalid_grant stops refresh without IdP contact and deletes the DPAPI file only for the current session; transient failures keep the DPAPI-only token without retry storm; audience url-encoded, non-secret, interactive-only; no tokens logged or stored in plain text; no new dependencies/secrets.
Limits: no real IdP run; F1/F2 tests required before [x].

## Fix verification (V01-R1)
Reviewer: independent Claude subagent (did not author). Date: 2026-12-04.
Source: PR #114 head f3fbb034a787e9cbc2d0dec40191c829146ca714 (fix commit ab056529 on top of 5892e576).
Verdict: PASS

- F1 fixed: test_rfc9207_the_authorization_answer_must_come_from_this_issuer gains deny=True cases (wrong iss; advertised support + missing iss) expecting idp_issuer_mismatch and no token POST. Mutation M4 (error handled before iss) now KILLED.
- F2 fixed: test_an_old_sign_ins_refusal_never_deletes_a_newer_saved_sign_in - an old session's on_refresh(None) after _end_session + new sign-in leaves the newer DPAPI sign-in. Mutation M7 (keep() deletes before session check) now KILLED.
- F3 fixed: resume_sign_in snapshots _session under _session_lock before starting the thread (warehouse_view.py:216-217) and deletes on INVALID_GRANT only under the lock while still current, ReferenceError-safe (230-235). Lock scope holds only an attribute read + unlink; no Qt call or IdP request under the lock; no nested acquisition; no deadlock found. Mutations M12 (no current==session check) and M13 (snapshot taken at failure time) KILLED by the same test (blocked refresh, newer sign-in saved meanwhile, rt-c survives).
- Validation: pytest (test_desktop_signin, test_secure_store, test_warehouse_view, test_warehouse_erp, server/test_oidc) 65 passed, 1 warning (existing tamper_state fake-browser HTTP 400); ruff check core apps server tools tests clean; ruff format --check on committed blobs clean; mypy --no-incremental core apps server tools clean (352 files).
- Limits: F3 race test uses monkeypatched discover/refresh (real-IdP invalid_grant path covered by V01 tests); no live Keycloak/Auth0 run.
33 changes: 30 additions & 3 deletions core/src/packlab_core/desktop_signin.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
from .erp_contract import ErpContractError

REFRESH_MARGIN_S = 60.0
# the IdP refused the refresh token for good (expired, revoked, reused): sign in again.
# Anything else (IdP unreachable, 5xx) is temporary and the refresh token is kept.
INVALID_GRANT = "token_refused: invalid_grant"


class SignInError(Exception):
Expand All @@ -48,6 +51,8 @@ class IdpEndpoints:
authorization_endpoint: str
token_endpoint: str
revocation_endpoint: str | None = None # RFC 7009, when the IdP announces one
# RFC 9207: the IdP promises ``iss`` in every authorization response
authorization_response_iss_parameter_supported: bool = False


def discover(
Expand All @@ -66,6 +71,9 @@ def discover(
),
token_endpoint=_safe_url(str(document.get("token_endpoint", "")), allow_loopback_http),
revocation_endpoint=_optional_url(document.get("revocation_endpoint"), allow_loopback_http),
authorization_response_iss_parameter_supported=(
document.get("authorization_response_iss_parameter_supported") is True
),
)


Expand Down Expand Up @@ -97,7 +105,9 @@ def do_GET(self) -> None: # noqa: N802
if url.path != "/callback" or self.server.answer is not None:
self.send_error(404)
return
query = {k: v[0] for k, v in urllib.parse.parse_qs(url.query).items() if v}
query = {
k: v[0] for k, v in urllib.parse.parse_qs(url.query, keep_blank_values=True).items()
}
state = query.get("state", "").encode("utf-8", "replace")
if not secrets.compare_digest(state, self.server.expected_state):
# not this sign-in's answer (another local process, a stale tab): keep waiting
Expand Down Expand Up @@ -159,6 +169,11 @@ def sign_in(
answer = receiver.answer
if answer is None:
raise SignInError("signin_timed_out")
# RFC 9207 (mix-up defence): an ``iss`` must be exactly this IdP's; an IdP that
# promises ``iss`` must send it. Checked before anything else in the answer is used.
if "iss" in answer or endpoints.authorization_response_iss_parameter_supported:
if answer.get("iss") != endpoints.issuer:
raise SignInError("idp_issuer_mismatch")
if "error" in answer:
raise SignInError("idp_refused: " + answer["error"][:60])
code = answer.get("code", "")
Expand Down Expand Up @@ -239,7 +254,8 @@ def __init__(
tokens,
clock,
)
self.on_refresh = on_refresh # e.g. keep a rotated refresh token in the secure store
# e.g. keep a rotated refresh token in the secure store; refresh_token None: forget it
self.on_refresh = on_refresh
self._lock = threading.Lock()

def revoke(self) -> bool:
Expand All @@ -252,7 +268,17 @@ def revoke(self) -> bool:
def __call__(self) -> str:
with self._lock:
if self.clock() > self.tokens.expires_at - REFRESH_MARGIN_S:
self.tokens = refresh(self.endpoints, self.app_client_id, self.tokens, self.clock)
try:
fresh = refresh(self.endpoints, self.app_client_id, self.tokens, self.clock)
except SignInError as error:
if str(error) == INVALID_GRANT:
# refused for good: never asked again (next call: signin_required),
# and ``on_refresh`` sees no refresh token, so the saved one goes too
self.tokens = TokenSet(self.tokens.access_token, self.tokens.expires_at)
if self.on_refresh is not None:
self.on_refresh(self.tokens)
raise # any other error keeps the refresh token for the next try
self.tokens = fresh
if self.on_refresh is not None:
self.on_refresh(self.tokens)
return self.tokens.access_token
Expand Down Expand Up @@ -315,6 +341,7 @@ def _safe_url(url: str, allow_loopback_http: bool) -> str:


__all__ = [
"INVALID_GRANT",
"IdpEndpoints",
"SignInError",
"TokenSet",
Expand Down
76 changes: 76 additions & 0 deletions tests/core/test_desktop_signin.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ def __init__(self) -> None:
self.seen_queries: list[dict[str, str]] = []
self.revocation_endpoint: str | None = "/revoke" # None: the IdP announces none
self.revocations: list[dict[str, str]] = []
self.send_iss: str | None = None # RFC 9207 ``iss`` in the authorization answer
self.iss_supported = False # discovery: authorization_response_iss_parameter_supported
self.refresh_status = 0 # e.g. 503: the token endpoint fails without an error code
self.token_posts = 0

@property
def issuer(self) -> str:
Expand Down Expand Up @@ -66,6 +70,7 @@ def do_GET(self) -> None: # noqa: N802
"issuer": self.server.issuer,
"authorization_endpoint": base + "/authorize",
"token_endpoint": base + "/token",
"authorization_response_iss_parameter_supported": self.server.iss_supported,
**(
{
"revocation_endpoint": (
Expand All @@ -90,6 +95,8 @@ def do_GET(self) -> None: # noqa: N802
self.server.seen_queries.append(query)
answer = {"state": "forged" if self.server.tamper_state else query["state"]}
answer.update({"error": "access_denied"} if self.server.deny else {"code": code})
if self.server.send_iss is not None:
answer["iss"] = self.server.send_iss
self.send_response(302)
self.send_header("Location", query["redirect_uri"] + "?" + urllib.parse.urlencode(answer))
self.send_header("Content-Length", "0")
Expand All @@ -104,6 +111,10 @@ def do_POST(self) -> None: # noqa: N802
self.send_header("Content-Length", "0")
self.end_headers()
return
self.server.token_posts += 1
if form["grant_type"] == "refresh_token" and self.server.refresh_status:
self._json(self.server.refresh_status, {"detail": "down for maintenance"})
return
if form["grant_type"] == "authorization_code":
sent = self.server.codes.pop(form["code"], None)
digest = hashlib.sha256(form.get("code_verifier", "").encode()).digest()
Expand Down Expand Up @@ -258,3 +269,68 @@ def test_revoke_signs_out_at_the_idp_and_never_fails_the_sign_out(idp: MockIdp)
gone = IdpEndpoints(idp.issuer, "x", "y", "http://127.0.0.1:9/revoke")
assert revoke(gone, "packlab-desktop", "rt-1", timeout_s=2) is False
assert len(idp.revocations) == 1


@pytest.mark.parametrize(
("supported", "sent", "accepted", "deny"),
[
(False, None, True, False), # an IdP without RFC 9207: no iss, nothing to check
(False, "same", True, False),
(False, "http://evil.example", False, False), # mix-up: another IdP's answer
(False, "", False, False),
(True, "same", True, False),
(True, None, False, False), # the IdP promised iss and the answer has none
# review V01 F1: iss is checked before an error answer is trusted
(False, "http://evil.example", False, True),
(True, None, False, True),
],
)
def test_rfc9207_the_authorization_answer_must_come_from_this_issuer(
idp: MockIdp, supported: bool, sent: str | None, accepted: bool, deny: bool
) -> None:
idp.iss_supported = supported
idp.deny = deny
idp.send_iss = idp.issuer if sent == "same" else sent
endpoints = discover(idp.issuer, allow_loopback_http=True)
assert endpoints.authorization_response_iss_parameter_supported is supported
if accepted:
assert sign_in(endpoints, "packlab-desktop", open_browser=_browser, timeout_s=10)
return
with pytest.raises(SignInError, match="idp_issuer_mismatch"):
sign_in(endpoints, "packlab-desktop", open_browser=_browser, timeout_s=10)
assert idp.token_posts == 0 # the code was never exchanged


def test_invalid_grant_drops_the_refresh_token_once_and_other_failures_keep_it(
idp: MockIdp,
) -> None:
"""A refresh token the IdP refuses for good is forgotten (on_refresh sees None) and never
sent again; an IdP that is down (503, no error code) keeps it for the next try."""
from packlab_core.desktop_signin import INVALID_GRANT, TokenSet

endpoints = discover(idp.issuer, allow_loopback_http=True)
seen: list[str | None] = []
idp.refresh_status = 503
source = TokenSource(
endpoints, "packlab-desktop", TokenSet("old", 0.0, "rt-1"), on_refresh=lambda t: None
)
with pytest.raises(SignInError, match="token_refused") as down:
source()
assert str(down.value) != INVALID_GRANT and source.tokens.refresh_token == "rt-1"
idp.refresh_status = 0
assert source() == "at-r1" # the IdP is back: the kept token works

source = TokenSource(
endpoints,
"packlab-desktop",
TokenSet("old", 0.0, "revoked"),
on_refresh=lambda t: seen.append(t.refresh_token),
)
posts = idp.token_posts
with pytest.raises(SignInError) as refused:
source()
assert str(refused.value) == INVALID_GRANT
assert seen == [None] and source.tokens.refresh_token is None
with pytest.raises(SignInError, match="signin_required"):
source() # no silent loop: the IdP is not asked again
assert idp.token_posts == posts + 1
Loading