feat: bind operator sessions to upstream identity (Closes #1372)
CI / lint (pull_request) Successful in 3m24s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m49s
CI / release-candidate (pull_request) Has been skipped

This commit is contained in:
timmy committed 2026-08-25 01:12:42 +00:00
1 parent 53706f18ab
commit d6e6cf2e67
9 files changed
+256 -15

No files matched your search

+8
View File
@@ -32,6 +32,8 @@ class Session:
csrf: str
expires_at: int
idle_expires_at: int | None = None
principal_id: int | None = None
principal_login: str | None = None
@dataclass(frozen=True)
@@ -145,6 +147,8 @@ def issue_session(
*,
device_label: str = "This device",
management_id: str | None = None,
principal_id: int | None = None,
principal_login: str | None = None,
) -> tuple[str, Session]:
issued_at = int(time.time() if now is None else now)
ttl = int(os.getenv("STACKCHAIN_DASHBOARD_SESSION_TTL_SECONDS", str(DEFAULT_TTL_SECONDS)))
@@ -165,6 +169,8 @@ def issue_session(
session.expires_at,
device_label=device_label,
management_id=management_id,
principal_id=principal_id,
principal_login=principal_login,
)
return f"{encoded}.{signature}", session
@@ -211,6 +217,8 @@ def verify_session_with_reason(
csrf=session.csrf,
expires_at=session.expires_at,
idle_expires_at=getattr(status, "idle_expires_at", None),
principal_id=getattr(status, "principal_id", None),
principal_login=getattr(status, "principal_login", None),
)
)
+58 -1
View File
@@ -429,6 +429,21 @@ class ReadinessPayloadError(ValueError):
"""Raised when Gitea returns a structurally invalid readiness payload."""
async def _upstream_identity() -> tuple[int, str]:
upstream = await current_user()
principal_id = upstream.get("id") if isinstance(upstream, dict) else None
principal_login = upstream.get("login") if isinstance(upstream, dict) else None
if (
not isinstance(principal_id, int)
or isinstance(principal_id, bool)
or principal_id <= 0
or not isinstance(principal_login, str)
or not principal_login
):
raise ValueError("Gitea identity response is incomplete")
return principal_id, principal_login
class DashboardSignIn(BaseModel):
access_token: str = Field(min_length=1, max_length=1_024)
device_label: str = Field(default="This device", min_length=1, max_length=64)
@@ -1563,6 +1578,27 @@ async def require_operator_session(request: Request, call_next):
status_code=503,
headers={"Cache-Control": "no-store"},
)
if session is not None:
try:
current_principal_id, current_login = await _upstream_identity()
except Exception:
return JSONResponse(
{"detail": "Gitea identity is temporarily unavailable"},
status_code=503,
headers={"Cache-Control": "no-store", "Retry-After": "5"},
)
if session.principal_id != current_principal_id:
return JSONResponse(
{
"detail": "Connected Gitea account changed; sign in again",
"code": "session_idle",
"reason": "upstream_identity_changed",
"previous_login": session.principal_login,
"current_login": current_login,
},
status_code=401,
headers={"Cache-Control": "no-store"},
)
if not public and session is None:
if path.startswith("/api/"):
payload = {"detail": "Authentication required"}
@@ -1736,9 +1772,20 @@ async def sign_in(payload: DashboardSignIn, request: Request, response: Response
status_code=503,
headers={"Cache-Control": "no-store"},
)
try:
principal_id, principal_login = await _upstream_identity()
except Exception:
return JSONResponse(
{"detail": "Gitea identity is temporarily unavailable"},
status_code=503,
headers={"Cache-Control": "no-store", "Retry-After": "5"},
)
try:
signed, session = await asyncio.to_thread(
dashboard_auth.issue_session, device_label=payload.device_label
dashboard_auth.issue_session,
device_label=payload.device_label,
principal_id=principal_id,
principal_login=principal_login,
)
except dashboard_auth.SessionStoreError:
return JSONResponse(
@@ -2326,11 +2373,21 @@ async def verify_passkey_authentication(
target="sign_in:dashboard",
)
raise ValueError("stale passkey counter")
try:
principal_id, principal_login = await _upstream_identity()
except Exception:
return JSONResponse(
{"detail": "Gitea identity is temporarily unavailable"},
status_code=503,
headers={"Cache-Control": "no-store", "Retry-After": "5"},
)
await dashboard_auth.revoke_managed_session(stored.management_id)
signed, session = await asyncio.to_thread(
dashboard_auth.issue_session,
device_label=stored.device_label,
management_id=stored.management_id,
principal_id=principal_id,
principal_login=principal_login,
)
except dashboard_auth.SessionStoreError:
raise HTTPException(status_code=503, detail="Passkey registry is temporarily unavailable")
+31 -7
View File
@@ -18,10 +18,20 @@ class SessionStatus(str):
"""String-compatible status carrying the server-confirmed idle deadline."""
idle_expires_at: int | None
principal_id: int | None
principal_login: str | None
def __new__(cls, value: str, idle_expires_at: int | None = None):
def __new__(
cls,
value: str,
idle_expires_at: int | None = None,
principal_id: int | None = None,
principal_login: str | None = None,
):
instance = super().__new__(cls, value)
instance.idle_expires_at = idle_expires_at
instance.principal_id = principal_id
instance.principal_login = principal_login
return instance
@@ -71,7 +81,9 @@ class SessionStore:
management_id TEXT,
device_label TEXT,
created_at INTEGER,
last_active_at INTEGER
last_active_at INTEGER,
principal_id INTEGER,
principal_login TEXT
)
"""
)
@@ -98,6 +110,8 @@ class SessionStore:
"device_label": "TEXT",
"created_at": "INTEGER",
"last_active_at": "INTEGER",
"principal_id": "INTEGER",
"principal_login": "TEXT",
}
for name, column_type in additions.items():
if name not in columns:
@@ -135,6 +149,8 @@ class SessionStore:
*,
device_label: str = "This device",
management_id: str | None = None,
principal_id: int | None = None,
principal_login: str | None = None,
) -> None:
label = " ".join(str(device_label).split())[:64] or "This device"
now = int(self.clock())
@@ -145,8 +161,9 @@ class SessionStore:
)
connection.execute(
"INSERT INTO active_sessions("
"session_hash, expires_at, management_id, device_label, created_at, last_active_at"
") VALUES (?, ?, ?, ?, ?, ?)",
"session_hash, expires_at, management_id, device_label, created_at, last_active_at, "
"principal_id, principal_login"
") VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(
self._digest(session_id),
expires_at,
@@ -154,6 +171,8 @@ class SessionStore:
label,
now,
now,
principal_id,
principal_login,
),
)
except (OSError, sqlite3.Error) as exc:
@@ -176,7 +195,8 @@ class SessionStore:
) -> str:
now = int(self.clock())
query = (
"SELECT expires_at, last_active_at FROM active_sessions "
"SELECT expires_at, last_active_at, principal_id, principal_login "
"FROM active_sessions "
"WHERE session_hash = ?"
)
parameters = (self._digest(session_id),)
@@ -185,7 +205,11 @@ class SessionStore:
with self._connect() as connection:
row = connection.execute(query, parameters).fetchone()
except sqlite3.OperationalError as exc:
if "no such column: last_active_at" not in str(exc):
missing_migrated_column = any(
f"no such column: {name}" in str(exc)
for name in ("last_active_at", "principal_id", "principal_login")
)
if not missing_migrated_column:
raise
with self._connect(initialize=True) as connection:
row = connection.execute(query, parameters).fetchone()
@@ -196,7 +220,7 @@ class SessionStore:
idle_expires_at = min(row[0], row[1] + max(1, idle_timeout_seconds))
if idle_expires_at <= now:
return SessionStatus("idle", idle_expires_at)
return SessionStatus("active", idle_expires_at)
return SessionStatus("active", idle_expires_at, row[2], row[3])
def touch(
self, session_id: str, expires_at: int, *, idle_timeout_seconds: int