feat(cfold): canonicalize custom test layout
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
This commit is contained in:
@ -1,35 +0,0 @@
|
||||
"""lasuite-docs — recipe-specific functional test (Phase 2 P3, ≥2 beyond parity).
|
||||
|
||||
The defining property of lasuite-docs as configured by the recipe is that its **backend API is
|
||||
auth-protected** — OIDC tokens authorize access; anonymous requests are rejected. This test
|
||||
proves the auth middleware is wired correctly: a sample backend endpoint (`/api/v1.0/users/me/`)
|
||||
returns 401 Unauthorized without a token. Non-vacuous: a misconfigured backend serving anonymous
|
||||
access would return 200; a broken auth middleware would return 500; a wrong route would return
|
||||
404 — only a correctly-wired OIDC gate returns 401.
|
||||
|
||||
Distinct from the OIDC password-grant test against the keycloak dep (`test_oidc_with_keycloak`):
|
||||
this proves **lasuite-docs's** own auth posture; that test proves the **SSO provider** can issue
|
||||
tokens. Together they exercise both sides of the OIDC flow's plumbing.
|
||||
|
||||
Runs in the custom tier against the shared post-install deployment.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
|
||||
from harness import http as harness_http # noqa: E402
|
||||
|
||||
|
||||
def test_users_me_requires_auth(live_app):
|
||||
"""GET /api/v1.0/users/me/ without a Bearer token must return 401, not 200/404/500."""
|
||||
url = f"https://{live_app}/api/v1.0/users/me/"
|
||||
# Retry with broad acceptance: any 4xx (or specific 401) indicates the route exists + auth is
|
||||
# required. Reject 200 (anonymous access) and 5xx (broken backend).
|
||||
status, _ = harness_http.retry_http_get(url, expect_status=(401, 403), max_wait=60, interval=3)
|
||||
assert status in (401, 403), (
|
||||
f"GET {url} returned {status}, expected 401 (auth required). "
|
||||
f"200 = anonymous access leaked; 404 = route missing; 5xx = backend broken."
|
||||
)
|
||||
@ -1,78 +0,0 @@
|
||||
"""lasuite-docs — Phase-2 P3 §4.3 prescribed create-a-doc + read-back test.
|
||||
|
||||
Plan §4.3 explicitly names this test for lasuite-docs: "create a doc, edit via the API, confirm
|
||||
persistence". This is the canonical create-an-object + read-it-back for lasuite-docs.
|
||||
|
||||
Flow (uses an OIDC token from the dep keycloak):
|
||||
1. Obtain a JWT via OIDC password grant against the dep keycloak (the test user is provisioned
|
||||
by the orchestrator's dep-provisioning step).
|
||||
2. POST `/api/v1.0/documents/` with `Authorization: Bearer <jwt>` to create a new doc with a
|
||||
unique title; capture the returned `id`.
|
||||
3. GET `/api/v1.0/documents/<id>/` with the same Bearer token; assert the returned title and
|
||||
id match.
|
||||
|
||||
Non-vacuous: a misconfigured OIDC, broken backend, or missing endpoint fails at the layer it's
|
||||
broken. The marker-in-the-title + id round-trip proves the doc actually persisted in lasuite-
|
||||
docs's database after going through the recipe's nginx → backend → postgres path.
|
||||
|
||||
Marked @pytest.mark.requires_deps — skips with `deps-not-ready` if dep provisioning failed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
|
||||
from harness import http as harness_http # noqa: E402
|
||||
from harness import sso
|
||||
|
||||
|
||||
@pytest.mark.requires_deps
|
||||
def test_create_doc_and_read_back(live_app, deps):
|
||||
"""Create a doc via the authenticated API; fetch it back; assert round-trip."""
|
||||
kc = deps["keycloak"]
|
||||
|
||||
# Obtain a JWT via OIDC password grant
|
||||
access_token = sso.oidc_password_grant(
|
||||
{
|
||||
"client_id": kc["client_id"],
|
||||
"client_secret": kc["client_secret"],
|
||||
"user": kc["user"],
|
||||
"password": kc["password"],
|
||||
"token_url": kc["token_url"],
|
||||
}
|
||||
)
|
||||
auth = {"Authorization": f"Bearer {access_token}"}
|
||||
|
||||
# Create a doc with a unique title
|
||||
title = f"ccci-doc-{uuid.uuid4().hex[:8]}"
|
||||
s, body = harness_http.http_post(
|
||||
f"https://{live_app}/api/v1.0/documents/",
|
||||
data={"title": title},
|
||||
headers=auth,
|
||||
)
|
||||
assert s in (200, 201), f"POST /api/v1.0/documents/ HTTP {s}: {body!r}"
|
||||
assert isinstance(body, dict), f"unexpected response shape: {body!r}"
|
||||
doc_id = body.get("id")
|
||||
assert doc_id, f"created doc has no id: {body!r}"
|
||||
assert (
|
||||
body.get("title") == title
|
||||
), f"created doc title mismatch: created={title!r}, response={body.get('title')!r}"
|
||||
|
||||
# Fetch it back via the dedicated GET endpoint
|
||||
s, fetched = harness_http.http_get(
|
||||
f"https://{live_app}/api/v1.0/documents/{doc_id}/", headers=auth
|
||||
)
|
||||
assert s == 200, f"GET /api/v1.0/documents/{doc_id}/ HTTP {s}: {fetched!r}"
|
||||
assert isinstance(fetched, dict), f"unexpected GET response: {fetched!r}"
|
||||
assert fetched.get("id") in (
|
||||
doc_id,
|
||||
str(doc_id),
|
||||
), f"fetched id mismatch: created={doc_id!r}, fetched={fetched.get('id')!r}"
|
||||
assert (
|
||||
fetched.get("title") == title
|
||||
), f"fetched title mismatch: created={title!r}, fetched={fetched.get('title')!r}"
|
||||
@ -1,32 +0,0 @@
|
||||
"""lasuite-docs — parity port of recipe-maintainer's health_check.py (Phase 2 P2).
|
||||
|
||||
SOURCE: references/recipe-maintainer/recipe-info/lasuite-docs/tests/health_check.py
|
||||
|
||||
The original asserted HTTP 200 from `https://lasuite-docs.<DOMAIN_SUFFIX>`. The cc-ci port
|
||||
preserves the assertion shape — non-error HTTP from the served root — adapted to the ephemeral
|
||||
per-run domain via the `live_app` fixture. Runs in the custom tier against the shared post-install
|
||||
live deployment.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
|
||||
from harness import http as harness_http # noqa: E402
|
||||
|
||||
|
||||
def test_lasuite_docs_returns_200(live_app):
|
||||
"""Parity with recipe-info/lasuite-docs/tests/health_check.py: HTTP 200 from `/`."""
|
||||
url = f"https://{live_app}/"
|
||||
# accept 200 (frontend SPA shell) — lasuite-docs serves the SPA at root unauthenticated;
|
||||
# the SPA itself bootstraps via /api/v1.0/users/me/ which requires OIDC (separate test).
|
||||
status, _ = harness_http.retry_http_get(
|
||||
url, expect_status=(200, 301, 302), max_wait=60, interval=3
|
||||
)
|
||||
assert status in (
|
||||
200,
|
||||
301,
|
||||
302,
|
||||
), f"lasuite-docs at {url} returned HTTP {status} (expected 200/301/302)"
|
||||
@ -1,94 +0,0 @@
|
||||
"""lasuite-docs — parity port of recipe-maintainer's oidc_login.py (Phase 2 P2).
|
||||
|
||||
SOURCE: references/recipe-maintainer/recipe-info/lasuite-docs/tests/oidc_login.py
|
||||
|
||||
End-to-end flow:
|
||||
1. GET `/api/v1.0/users/me/` without auth → asserts the response REDIRECTS to the dep
|
||||
keycloak's realm auth endpoint (the recipe is correctly configured to challenge
|
||||
unauthenticated callers — wired via install_steps.sh).
|
||||
2. Obtain an OIDC token from the dep keycloak via password grant
|
||||
(the test user provisioned by the orchestrator's realm setup).
|
||||
3. Call `/api/v1.0/users/me/` with `Authorization: Bearer <jwt>` → asserts 200 and the
|
||||
returned user's email matches the provisioned test user.
|
||||
|
||||
Marked @pytest.mark.requires_deps — skips with `deps-not-ready` if dep provisioning failed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
|
||||
from harness import http as harness_http # noqa: E402
|
||||
from harness import sso
|
||||
|
||||
_CTX = ssl.create_default_context()
|
||||
_CTX.check_hostname = False
|
||||
_CTX.verify_mode = ssl.CERT_NONE
|
||||
|
||||
|
||||
class _NoFollow(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise urllib.error.HTTPError(newurl, code, msg, headers, fp)
|
||||
|
||||
|
||||
def _get_no_redirect(url: str) -> tuple[int, str]:
|
||||
"""GET without auto-following redirects. Returns (status, redirect_url-or-body)."""
|
||||
opener = urllib.request.build_opener(_NoFollow, urllib.request.HTTPSHandler(context=_CTX))
|
||||
try:
|
||||
with opener.open(url, timeout=15) as resp:
|
||||
return resp.status, resp.read().decode(errors="replace")
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code in (301, 302, 303, 307, 308):
|
||||
return e.code, e.headers.get("Location", "")
|
||||
return e.code, ""
|
||||
|
||||
|
||||
@pytest.mark.requires_deps
|
||||
def test_oidc_login_via_keycloak(live_app, deps):
|
||||
"""Anonymous → redirect to keycloak; password-grant token → 200 from /api/v1.0/users/me/."""
|
||||
kc = deps["keycloak"]
|
||||
|
||||
# Step 1: unauthenticated GET → 302 to keycloak realm's auth endpoint
|
||||
status, redirect = _get_no_redirect(f"https://{live_app}/api/v1.0/users/me/")
|
||||
expected_prefix = f"https://{kc['domain']}/realms/{kc['realm']}/protocol/openid-connect/auth"
|
||||
# Some configurations return 401 with WWW-Authenticate (an OIDC challenge) rather than a
|
||||
# 302 redirect. Both are valid "auth-required" indicators — accept either, but if a
|
||||
# redirect is returned it must point at the dep keycloak realm.
|
||||
if status in (301, 302, 303, 307, 308):
|
||||
assert expected_prefix in (
|
||||
redirect or ""
|
||||
), f"Docs redirected to {redirect!r}, expected to start with {expected_prefix!r}"
|
||||
else:
|
||||
assert status in (401, 403), (
|
||||
f"GET /api/v1.0/users/me/ unauth: HTTP {status}; expected redirect to keycloak "
|
||||
f"OR 401/403. (200 would be an auth leak.)"
|
||||
)
|
||||
|
||||
# Step 2: obtain an OIDC token via password grant against the dep keycloak
|
||||
creds = {
|
||||
"client_id": kc["client_id"],
|
||||
"client_secret": kc["client_secret"],
|
||||
"user": kc["user"],
|
||||
"password": kc["password"],
|
||||
"token_url": kc["token_url"],
|
||||
}
|
||||
access_token = sso.oidc_password_grant(creds)
|
||||
assert isinstance(access_token, str) and access_token.count(".") == 2, "expected JWT"
|
||||
|
||||
# Step 3: call the protected API with the Bearer token; assert 200 + user email
|
||||
status, body = harness_http.http_get(
|
||||
f"https://{live_app}/api/v1.0/users/me/",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert status == 200, f"GET /api/v1.0/users/me/ with token HTTP {status}: {body!r}"
|
||||
assert isinstance(body, dict), f"unexpected response: {body!r}"
|
||||
assert (
|
||||
body.get("email") == kc["email"]
|
||||
), f"unexpected user email: got {body.get('email')!r}, expected {kc['email']!r}"
|
||||
@ -1,87 +0,0 @@
|
||||
"""lasuite-docs — Q2 SSO-flow acceptance test (operator-2026-05-28 SSO-dep plan).
|
||||
|
||||
Refactored to the refined SSO-dep model:
|
||||
- The orchestrator deploys a per-run keycloak dep AFTER generic tiers and provisions a fresh
|
||||
realm/client/user via `harness.sso.setup_keycloak_realm`. The creds are written to
|
||||
`$CCCI_DEPS_FILE` (read here via the `deps` fixture).
|
||||
- This test no longer calls `setup_keycloak_realm` itself — that's the orchestrator's job in
|
||||
the dep-provisioning step. We just consume the credentials and exercise the OIDC flow.
|
||||
- Marked `@pytest.mark.requires_deps` so if dep provisioning failed, this test SKIPs with a
|
||||
clear `deps-not-ready` reason rather than red-flagging a non-recipe failure.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
|
||||
from harness import sso # noqa: E402
|
||||
|
||||
|
||||
def _b64url_decode(seg: str) -> bytes:
|
||||
pad = "=" * ((4 - len(seg) % 4) % 4)
|
||||
return base64.urlsafe_b64decode(seg + pad)
|
||||
|
||||
|
||||
@pytest.mark.requires_deps
|
||||
def test_oidc_password_grant_against_dep_keycloak(live_app, deps):
|
||||
"""The dep keycloak issues a JWT for the pre-provisioned test user via OIDC password grant."""
|
||||
assert "keycloak" in deps, (
|
||||
f"keycloak creds not in deps; got {list(deps.keys())}. "
|
||||
"dep provisioning should have populated this."
|
||||
)
|
||||
kc = deps["keycloak"]
|
||||
|
||||
# Sanity-check the creds shape — orchestrator-written
|
||||
assert kc["domain"]
|
||||
# WC1: realm is per-run namespaced "<parent>-<6hex>" so concurrent dependents never collide.
|
||||
assert re.fullmatch(
|
||||
r"lasuite-docs-[0-9a-f]{6}", kc["realm"]
|
||||
), f"realm {kc['realm']!r} not the per-run namespaced form lasuite-docs-<6hex>"
|
||||
assert kc["client_id"] == "lasuite-docs"
|
||||
assert isinstance(kc["client_secret"], str) and len(kc["client_secret"]) >= 16
|
||||
assert isinstance(kc["password"], str) and len(kc["password"]) >= 16
|
||||
|
||||
# Build a creds dict in the shape sso.* primitives expect
|
||||
creds = {
|
||||
"provider": "keycloak",
|
||||
"provider_domain": kc["domain"],
|
||||
"realm": kc["realm"],
|
||||
"client_id": kc["client_id"],
|
||||
"client_secret": kc["client_secret"],
|
||||
"user": kc["user"],
|
||||
"password": kc["password"],
|
||||
"email": kc["email"],
|
||||
"discovery_url": kc["discovery_url"],
|
||||
"token_url": kc["token_url"],
|
||||
"auth_url": kc["auth_url"],
|
||||
"userinfo_url": kc["userinfo_url"],
|
||||
}
|
||||
|
||||
# OIDC discovery endpoint advertises the realm
|
||||
discovery = sso.assert_discovery_endpoint(creds)
|
||||
expected_iss = f"https://{kc['domain']}/realms/{kc['realm']}"
|
||||
assert discovery.get("issuer") == expected_iss
|
||||
assert discovery.get("token_endpoint", "").startswith(expected_iss + "/")
|
||||
assert discovery.get("authorization_endpoint", "").startswith(expected_iss + "/")
|
||||
|
||||
# Password grant → real JWT
|
||||
token = sso.oidc_password_grant(creds)
|
||||
assert isinstance(token, str) and token.count(".") == 2, f"access_token is not a JWT: {token!r}"
|
||||
payload = json.loads(_b64url_decode(token.split(".")[1]))
|
||||
assert payload.get("iss") == expected_iss, f"JWT iss={payload.get('iss')!r} != {expected_iss!r}"
|
||||
assert (
|
||||
payload.get("azp") == kc["client_id"]
|
||||
), f"JWT azp={payload.get('azp')!r} != {kc['client_id']!r}"
|
||||
assert payload.get("typ") == "Bearer", f"JWT typ={payload.get('typ')!r} != 'Bearer'"
|
||||
exp = payload.get("exp")
|
||||
assert (
|
||||
isinstance(exp, int) and exp > time.time()
|
||||
), f"JWT exp={exp!r} not a future timestamp (now={time.time():.0f})"
|
||||
Reference in New Issue
Block a user