Merge pull request 'test(lasuite-meet): update stale meeting-flow test for meet v1.22.0+ API auth hardening' (#13) from test/lasuite-meet-stale-test-20260803 into main
This commit was merged in pull request #13.
This commit is contained in:
@@ -0,0 +1,160 @@
|
|||||||
|
"""Recipe-local OIDC *session* login helper (authorization-code flow + session cookie).
|
||||||
|
|
||||||
|
meet v1.22.0 hardened API auth — raw OIDC user access tokens are rejected as Bearer
|
||||||
|
credentials; the app accepts only its own session cookie, established through the standard OIDC
|
||||||
|
authorization-code browser flow (app login URL → keycloak login form → callback → Django
|
||||||
|
session). This helper drives that flow with urllib + a CookieJar so the custom tests can
|
||||||
|
exercise the API the way a real client does.
|
||||||
|
|
||||||
|
Kept recipe-local (cf. tests/ghost/custom/_ghost.py precedent; same helper as
|
||||||
|
tests/lasuite-docs/custom/_oidc_session.py) rather than in runner/harness — promote it there
|
||||||
|
if a third recipe needs it.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
sess = OidcSession(f"https://{live_app}")
|
||||||
|
me = sess.login(kc["user"], kc["password"]) # asserts whoami 200; returns the user dict
|
||||||
|
status, body = sess.post("/api/v1.0/rooms/", {"name": "x"}) # CSRF handled
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import html
|
||||||
|
import http.cookiejar
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import ssl
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
# Per-run *.ci.commoninternet.net domains serve the operator's wildcard cert via the Traefik file
|
||||||
|
# provider; chain verification is done once in the install tier (generic.served_cert).
|
||||||
|
_CTX = ssl.create_default_context()
|
||||||
|
_CTX.check_hostname = False
|
||||||
|
_CTX.verify_mode = ssl.CERT_NONE
|
||||||
|
|
||||||
|
_LOGIN_PATHS = ("/api/v1.0/authenticate/", "/oidc/authenticate/", "/api/v1.0/users/me/")
|
||||||
|
_WHOAMI = "/api/v1.0/users/me/"
|
||||||
|
|
||||||
|
|
||||||
|
class OidcSession:
|
||||||
|
"""A cookie-carrying HTTP session logged in via the app's OIDC authorization-code flow."""
|
||||||
|
|
||||||
|
def __init__(self, base: str):
|
||||||
|
self.base = base.rstrip("/")
|
||||||
|
self.jar = http.cookiejar.CookieJar()
|
||||||
|
self.opener = urllib.request.build_opener(
|
||||||
|
urllib.request.HTTPCookieProcessor(self.jar),
|
||||||
|
urllib.request.HTTPSHandler(context=_CTX),
|
||||||
|
)
|
||||||
|
|
||||||
|
# -- low-level ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _open(
|
||||||
|
self,
|
||||||
|
url: str,
|
||||||
|
data: bytes | None = None,
|
||||||
|
headers: dict[str, str] | None = None,
|
||||||
|
method: str | None = None,
|
||||||
|
timeout: int = 30,
|
||||||
|
) -> tuple[int, str, bytes]:
|
||||||
|
"""Open a URL (following redirects, carrying cookies). Returns (status, final_url, body)."""
|
||||||
|
req = urllib.request.Request(url, data=data, method=method)
|
||||||
|
for k, v in (headers or {}).items():
|
||||||
|
req.add_header(k, v)
|
||||||
|
try:
|
||||||
|
with self.opener.open(req, timeout=timeout) as resp:
|
||||||
|
return resp.getcode(), resp.geturl(), resp.read()
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
body = b""
|
||||||
|
with contextlib.suppress(Exception):
|
||||||
|
body = e.read()
|
||||||
|
return e.code, e.filename or url, body
|
||||||
|
|
||||||
|
def _csrf_token(self) -> str | None:
|
||||||
|
for c in self.jar:
|
||||||
|
if "csrftoken" in c.name.lower():
|
||||||
|
return c.value
|
||||||
|
return None
|
||||||
|
|
||||||
|
# -- login -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def login(
|
||||||
|
self,
|
||||||
|
username: str,
|
||||||
|
password: str,
|
||||||
|
login_paths: tuple[str, ...] = _LOGIN_PATHS,
|
||||||
|
whoami: str = _WHOAMI,
|
||||||
|
) -> dict:
|
||||||
|
"""OIDC authorization-code login: app → keycloak form → callback → session cookie.
|
||||||
|
|
||||||
|
Asserts the resulting session GETs `whoami` with HTTP 200 and returns the parsed user.
|
||||||
|
"""
|
||||||
|
page, page_url, last = None, None, (0, "", b"")
|
||||||
|
for path in login_paths:
|
||||||
|
status, final_url, body = self._open(self.base + path)
|
||||||
|
last = (status, final_url, body)
|
||||||
|
text = body.decode(errors="replace")
|
||||||
|
if "kc-form-login" in text or (
|
||||||
|
"/protocol/openid-connect/" in final_url and "<form" in text
|
||||||
|
):
|
||||||
|
page, page_url = text, final_url
|
||||||
|
break
|
||||||
|
assert page is not None, (
|
||||||
|
f"could not reach the keycloak login form via {login_paths}: last URL "
|
||||||
|
f"{last[1]!r} HTTP {last[0]} body[:200]={last[2][:200]!r}"
|
||||||
|
)
|
||||||
|
|
||||||
|
m = re.search(r'<form[^>]*id="kc-form-login"[^>]*action="([^"]+)"', page) or re.search(
|
||||||
|
r'<form[^>]*action="([^"]+)"[^>]*method=["\']?post', page, re.I
|
||||||
|
)
|
||||||
|
assert m, f"no login form action on keycloak page {page_url!r}: {page[:300]!r}"
|
||||||
|
action = html.unescape(m.group(1))
|
||||||
|
|
||||||
|
form = urllib.parse.urlencode(
|
||||||
|
{"username": username, "password": password, "credentialId": ""}
|
||||||
|
).encode()
|
||||||
|
status, landed, body = self._open(
|
||||||
|
action, data=form, headers={"Content-Type": "application/x-www-form-urlencoded"}
|
||||||
|
)
|
||||||
|
|
||||||
|
status, _, who = self._open(self.base + whoami)
|
||||||
|
assert status == 200, (
|
||||||
|
f"OIDC session login failed: GET {whoami} -> HTTP {status} after submitting the "
|
||||||
|
f"keycloak form (landed at {landed!r}; excerpt: {body[:200]!r})"
|
||||||
|
)
|
||||||
|
parsed = json.loads(who)
|
||||||
|
assert isinstance(parsed, dict), f"unexpected whoami payload: {who[:200]!r}"
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
# -- API calls with the session ----------------------------------------------------------
|
||||||
|
|
||||||
|
def request(self, method: str, path: str, data: dict | None = None) -> tuple[int, object]:
|
||||||
|
"""Issue an API call with the session cookie (+ CSRF header on unsafe methods)."""
|
||||||
|
url = path if path.startswith("http") else self.base + path
|
||||||
|
headers: dict[str, str] = {}
|
||||||
|
body: bytes | None = None
|
||||||
|
if data is not None:
|
||||||
|
body = json.dumps(data).encode()
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
if method.upper() not in ("GET", "HEAD", "OPTIONS"):
|
||||||
|
tok = self._csrf_token()
|
||||||
|
if tok:
|
||||||
|
headers["X-CSRFToken"] = tok
|
||||||
|
headers["Referer"] = self.base + "/"
|
||||||
|
headers["Origin"] = self.base
|
||||||
|
status, _, raw = self._open(url, data=body, headers=headers, method=method.upper())
|
||||||
|
try:
|
||||||
|
return status, json.loads(raw)
|
||||||
|
except (json.JSONDecodeError, ValueError):
|
||||||
|
return status, None
|
||||||
|
|
||||||
|
def get(self, path: str) -> tuple[int, object]:
|
||||||
|
return self.request("GET", path)
|
||||||
|
|
||||||
|
def post(self, path: str, data: dict | None = None) -> tuple[int, object]:
|
||||||
|
return self.request("POST", path, data)
|
||||||
|
|
||||||
|
def delete(self, path: str) -> tuple[int, object]:
|
||||||
|
return self.request("DELETE", path)
|
||||||
@@ -5,8 +5,14 @@ SOURCE: references/recipe-maintainer/recipe-info/lasuite-meet/tests/meeting_flow
|
|||||||
|
|
||||||
Meet's characteristic behavior is real-time meetings: a user creates a room and receives a LiveKit
|
Meet's characteristic behavior is real-time meetings: a user creates a room and receives a LiveKit
|
||||||
(SFU) join token for WebSocket signaling. This is the §4.3 create-an-object + read-it-back, plus the
|
(SFU) join token for WebSocket signaling. This is the §4.3 create-an-object + read-it-back, plus the
|
||||||
distinctive WebRTC-signaling feature (LiveKit token issuance) — not a health/200 stand-in. Flow:
|
distinctive WebRTC-signaling feature (LiveKit token issuance) — not a health/200 stand-in.
|
||||||
1. OIDC password grant (the per-run keycloak user) → a Meet API bearer token.
|
|
||||||
|
Updated for meet v1.22.0+ API auth hardening: the API now REJECTS raw OIDC user access tokens
|
||||||
|
sent as Bearer credentials; authenticated calls run on the app's session cookie from the real
|
||||||
|
OIDC authorization-code login (see _oidc_session.py). Flow:
|
||||||
|
1. OIDC password grant (the per-run keycloak user) → assert the API rejects it as Bearer
|
||||||
|
(the v1.22.0 hardening — a 2xx here would mean the hardening regressed); then log in via
|
||||||
|
the OIDC authorization-code flow → session cookie.
|
||||||
2. POST /api/v1.0/rooms/ {name, access_level:public} → 201 with id/slug AND a LiveKit room+token.
|
2. POST /api/v1.0/rooms/ {name, access_level:public} → 201 with id/slug AND a LiveKit room+token.
|
||||||
3. GET /api/v1.0/rooms/{id}/ (read-it-back) → 200, again with a LiveKit token for the same room.
|
3. GET /api/v1.0/rooms/{id}/ (read-it-back) → 200, again with a LiveKit token for the same room.
|
||||||
4. Assert the LiveKit token is a real JWT carrying a video grant for that room (token issuance —
|
4. Assert the LiveKit token is a real JWT carrying a video grant for that room (token issuance —
|
||||||
@@ -27,9 +33,11 @@ import sys
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(__file__))
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
|
||||||
|
from _oidc_session import OidcSession # noqa: E402 (recipe-local helper, same dir)
|
||||||
from harness import http as harness_http # noqa: E402
|
from harness import http as harness_http # noqa: E402
|
||||||
from harness import sso
|
from harness import sso # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
def _b64url(seg: str) -> bytes:
|
def _b64url(seg: str) -> bytes:
|
||||||
@@ -57,17 +65,28 @@ def _creds(deps: dict) -> dict:
|
|||||||
@pytest.mark.requires_deps
|
@pytest.mark.requires_deps
|
||||||
def test_create_room_get_livekit_token_and_read_back(live_app, deps):
|
def test_create_room_get_livekit_token_and_read_back(live_app, deps):
|
||||||
assert "keycloak" in deps, f"keycloak creds missing; got {list(deps.keys())}"
|
assert "keycloak" in deps, f"keycloak creds missing; got {list(deps.keys())}"
|
||||||
|
kc = deps["keycloak"]
|
||||||
base = f"https://{live_app}"
|
base = f"https://{live_app}"
|
||||||
|
|
||||||
|
# meet v1.22.0+ hardening: a raw OIDC user access token must be REJECTED as Bearer.
|
||||||
token = sso.oidc_password_grant(_creds(deps))
|
token = sso.oidc_password_grant(_creds(deps))
|
||||||
assert isinstance(token, str) and token.count(".") == 2, "OIDC access token is not a JWT"
|
assert isinstance(token, str) and token.count(".") == 2, "OIDC access token is not a JWT"
|
||||||
auth = {"Authorization": f"Bearer {token}"}
|
|
||||||
|
|
||||||
# --- create a room (the object) ---
|
|
||||||
status, body = harness_http.http_post(
|
status, body = harness_http.http_post(
|
||||||
f"{base}/api/v1.0/rooms/",
|
f"{base}/api/v1.0/rooms/",
|
||||||
data={"name": "ccci-meeting", "access_level": "public"},
|
data={"name": "ccci-meeting", "access_level": "public"},
|
||||||
headers=auth,
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
)
|
)
|
||||||
|
assert status in (401, 403), (
|
||||||
|
f"POST /api/v1.0/rooms/ with a raw OIDC Bearer token returned HTTP {status} — meet >= "
|
||||||
|
f"v1.22.0 must reject user access tokens on the API (body {body!r})"
|
||||||
|
)
|
||||||
|
|
||||||
|
# The successor auth path: session cookie via the real OIDC authorization-code login.
|
||||||
|
sess = OidcSession(base)
|
||||||
|
sess.login(kc["user"], kc["password"])
|
||||||
|
|
||||||
|
# --- create a room (the object) ---
|
||||||
|
status, body = sess.post("/api/v1.0/rooms/", {"name": "ccci-meeting", "access_level": "public"})
|
||||||
assert status == 201, f"room create returned HTTP {status} (expected 201); body={body!r}"
|
assert status == 201, f"room create returned HTTP {status} (expected 201); body={body!r}"
|
||||||
assert isinstance(body, dict), f"room create body not JSON: {body!r}"
|
assert isinstance(body, dict), f"room create body not JSON: {body!r}"
|
||||||
room_id = body.get("id")
|
room_id = body.get("id")
|
||||||
@@ -75,36 +94,32 @@ def test_create_room_get_livekit_token_and_read_back(live_app, deps):
|
|||||||
lk_room = livekit.get("room")
|
lk_room = livekit.get("room")
|
||||||
lk_token = livekit.get("token")
|
lk_token = livekit.get("token")
|
||||||
assert room_id, f"room created but no id: {body!r}"
|
assert room_id, f"room created but no id: {body!r}"
|
||||||
assert (
|
assert lk_token and isinstance(lk_token, str) and lk_token.count(".") == 2, (
|
||||||
lk_token and isinstance(lk_token, str) and lk_token.count(".") == 2
|
f"room created but no LiveKit JWT token: {livekit!r}"
|
||||||
), f"room created but no LiveKit JWT token: {livekit!r}"
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# --- read it back (a fresh authenticated GET of the created room) ---
|
# --- read it back (a fresh authenticated GET of the created room) ---
|
||||||
status, got = harness_http.http_request(
|
status, got = sess.get(f"/api/v1.0/rooms/{room_id}/")
|
||||||
"GET", f"{base}/api/v1.0/rooms/{room_id}/", headers=auth
|
|
||||||
)
|
|
||||||
assert status == 200, f"room read-back returned HTTP {status} (expected 200); body={got!r}"
|
assert status == 200, f"room read-back returned HTTP {status} (expected 200); body={got!r}"
|
||||||
assert (
|
assert isinstance(got, dict) and got.get("id") == room_id, (
|
||||||
isinstance(got, dict) and got.get("id") == room_id
|
f"read-back room id mismatch: {got!r}"
|
||||||
), f"read-back room id mismatch: {got!r}"
|
)
|
||||||
got_lk = got.get("livekit") or {}
|
got_lk = got.get("livekit") or {}
|
||||||
assert got_lk.get("token"), f"read-back room missing LiveKit token: {got!r}"
|
assert got_lk.get("token"), f"read-back room missing LiveKit token: {got!r}"
|
||||||
assert (
|
assert got_lk.get("room") == lk_room, (
|
||||||
got_lk.get("room") == lk_room
|
f"read-back LiveKit room {got_lk.get('room')!r} != create-time {lk_room!r}"
|
||||||
), f"read-back LiveKit room {got_lk.get('room')!r} != create-time {lk_room!r}"
|
)
|
||||||
|
|
||||||
# --- the LiveKit token is a real signaling grant for this room (WebRTC subset) ---
|
# --- the LiveKit token is a real signaling grant for this room (WebRTC subset) ---
|
||||||
payload = json.loads(_b64url(lk_token.split(".")[1]))
|
payload = json.loads(_b64url(lk_token.split(".")[1]))
|
||||||
video = payload.get("video") or {}
|
video = payload.get("video") or {}
|
||||||
assert (
|
assert video.get("room") == lk_room or payload.get("room") == lk_room, (
|
||||||
video.get("room") == lk_room or payload.get("room") == lk_room
|
f"LiveKit JWT does not grant the created room {lk_room!r}: {payload!r}"
|
||||||
), f"LiveKit JWT does not grant the created room {lk_room!r}: {payload!r}"
|
)
|
||||||
finally:
|
finally:
|
||||||
# --- delete the room (cleanup + a real DELETE mutation) ---
|
# --- delete the room (cleanup + a real DELETE mutation) ---
|
||||||
del_status, _ = harness_http.http_request(
|
del_status, _ = sess.delete(f"/api/v1.0/rooms/{room_id}/")
|
||||||
"DELETE", f"{base}/api/v1.0/rooms/{room_id}/", headers=auth
|
|
||||||
)
|
|
||||||
assert del_status in (
|
assert del_status in (
|
||||||
204,
|
204,
|
||||||
200,
|
200,
|
||||||
@@ -120,9 +135,7 @@ def test_create_room_get_livekit_token_and_read_back(live_app, deps):
|
|||||||
|
|
||||||
gone = False
|
gone = False
|
||||||
for _ in range(5):
|
for _ in range(5):
|
||||||
status, _ = harness_http.http_request(
|
status, _ = sess.get(f"/api/v1.0/rooms/{room_id}/")
|
||||||
"GET", f"{base}/api/v1.0/rooms/{room_id}/", headers=auth
|
|
||||||
)
|
|
||||||
if status == 404:
|
if status == 404:
|
||||||
gone = True
|
gone = True
|
||||||
break
|
break
|
||||||
|
|||||||
Reference in New Issue
Block a user