Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

test(callbackauthn): cover the google authn flow end to end (#12486)

Pandeycd8346a91ae1
diff --git a/tests/conftest.py b/tests/conftest.py
index c5f13e3798..0e0c5ccbad 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -24,6 +24,8 @@ pytest_plugins = [
"fixtures.browser",
"fixtures.keycloak",
"fixtures.idp",
+ "fixtures.googleidp",
+ "fixtures.tls",
"fixtures.notification_channel",
"fixtures.maildev",
"fixtures.alerts",
diff --git a/tests/fixtures/googleidp.py b/tests/fixtures/googleidp.py
new file mode 100644
index 0000000000..b7b4c61cd4
--- /dev/null
+++ b/tests/fixtures/googleidp.py
@@ -0,0 +1,231 @@
+import functools
+import time
+from collections.abc import Callable
+from http import HTTPStatus
+from pathlib import Path
+from urllib.parse import urlparse
+
+import docker
+import docker.errors
+import pytest
+import requests
+from jwcrypto import jwk, jwt
+from testcontainers.core.container import Network
+from wiremock.resources.mappings import HttpMethods, Mapping, MappingRequest, MappingResponse
+from wiremock.testing.testcontainer import WireMockContainer
+
+from fixtures import reuse, types
+from fixtures.logger import setup_logger
+from fixtures.tls import CA_ID_LABEL, KEYSTORE_PASSWORD, ca_id, issue_server_keystore
+
+logger = setup_logger(__name__)
+
+# The google callback authn hardcodes Google's issuer, so the mock must be
+# reachable as accounts.google.com over TLS from the signoz container: the
+# wiremock container joins the network under that alias and serves HTTPS on 443
+# with a certificate issued by the integration CA that signoz trusts.
+ISSUER = "https://accounts.google.com"
+ISSUER_HOST = "accounts.google.com"
+
+GOOGLE_DOMAIN = "google.integration.test"
+
+
+# One signing key for the whole session: the token and JWKS stubs are always
+# installed together, so per-call keys would only add RSA keygen latency.
+def signing_key() -> jwk.JWK:
+ return jwk.JWK.generate(kty="RSA", size=2048, kid="googleidp-integration", use="sig", alg="RS256")
+
+
+def perform_google_login(
+ signoz: types.SigNoz,
+ googleidp: types.TestContainerDocker,
+ get_session_context: Callable[[str], dict],
+ email: str,
+) -> str:
+ """Drive the google login flow for email and return the final redirect URL.
+
+ The authorize URL points at https://accounts.google.com (resolvable only
+ inside the docker network), so it is rewritten to the mock's host-mapped
+ port, mirroring how the oidc suite rewrites keycloak URLs.
+ """
+ session_context = get_session_context(email)
+
+ assert len(session_context["orgs"]) == 1
+ assert len(session_context["orgs"][0]["authNSupport"]["callback"]) == 1
+
+ url = session_context["orgs"][0]["authNSupport"]["callback"][0]["url"]
+ assert url.startswith(f"{ISSUER}/")
+
+ parsed_url = urlparse(url)
+ authorize_url = googleidp.host_configs["8080"].get(f"{parsed_url.path}?{parsed_url.query}")
+
+ response = requests.get(authorize_url, allow_redirects=False, timeout=5)
+ assert response.status_code == HTTPStatus.FOUND
+
+ callback_url = response.headers["Location"]
+ assert "/api/v1/complete/google" in callback_url
+
+ response = requests.get(callback_url, allow_redirects=False, timeout=30)
+ assert response.status_code == HTTPStatus.SEE_OTHER
+
+ return response.headers["Location"]
+
+
+def get_google_domain(signoz: types.SigNoz, admin_token: str) -> dict:
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/domains"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=2,
+ )
+ return next(
+ (domain for domain in response.json()["data"] if domain["name"] == GOOGLE_DOMAIN),
+ None,
+ )
+
+
+def google_oidc_mappings(email: str, name: str, hd: str, audience: str, email_verified: bool = True) -> list[Mapping]:
+ """Wiremock mappings for one Google OIDC login: discovery, an auto-approving
+ authorize redirect, a token response with an RS256 id_token for the given
+ identity, and the JWKS the signoz container verifies it against."""
+ now = int(time.time())
+ token = jwt.JWT(
+ header={"alg": "RS256", "kid": signing_key()["kid"], "typ": "JWT"},
+ claims={
+ "iss": ISSUER,
+ "aud": audience,
+ "sub": f"google-oauth2|{email}",
+ "email": email,
+ "email_verified": email_verified,
+ "name": name,
+ "hd": hd,
+ "iat": now,
+ "exp": now + 3600,
+ },
+ )
+ token.make_signed_token(signing_key())
+ id_token = token.serialize()
+
+ return [
+ Mapping(
+ request=MappingRequest(method=HttpMethods.GET, url_path="/.well-known/openid-configuration"),
+ response=MappingResponse(
+ status=200,
+ json_body={
+ "issuer": ISSUER,
+ "authorization_endpoint": f"{ISSUER}/o/oauth2/v2/auth",
+ "token_endpoint": f"{ISSUER}/token",
+ "jwks_uri": f"{ISSUER}/jwks",
+ "response_types_supported": ["code"],
+ "subject_types_supported": ["public"],
+ "id_token_signing_alg_values_supported": ["RS256"],
+ "scopes_supported": ["openid", "email", "profile"],
+ "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"],
+ },
+ ),
+ ),
+ Mapping(
+ request=MappingRequest(method=HttpMethods.GET, url_path="/o/oauth2/v2/auth"),
+ response=MappingResponse(
+ status=302,
+ headers={
+ # Triple-stache: redirect_uri and state are URLs; handlebars
+ # would otherwise HTML-escape their special characters.
+ # request.query values arrive URL-decoded, so the state is
+ # re-encoded into the redirect exactly as google does.
+ "Location": "{{{request.query.redirect_uri}}}?code=integration-test-code&state={{{urlEncode request.query.state}}}",
+ },
+ transformers=["response-template"],
+ ),
+ ),
+ Mapping(
+ request=MappingRequest(method=HttpMethods.POST, url_path="/token"),
+ response=MappingResponse(
+ status=200,
+ json_body={
+ "access_token": "integration-test-access-token",
+ "token_type": "Bearer",
+ "expires_in": 3600,
+ "id_token": id_token,
+ },
+ ),
+ ),
+ Mapping(
+ request=MappingRequest(method=HttpMethods.GET, url_path="/jwks"),
+ response=MappingResponse(
+ status=200,
+ json_body={"keys": [signing_key().export_public(as_dict=True)]},
+ ),
+ ),
+ ]
+
+
[email protected](name="googleidp", scope="package")
+def googleidp( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ network: Network,
+ tls: types.TLS,
+ tmpfs: Callable[[str], Path],
+ request: pytest.FixtureRequest,
+ pytestconfig: pytest.Config,
+) -> types.TestContainerDocker:
+ """Wiremock impersonating Google's OIDC provider. Stubs are installed per
+ test via make_http_mocks with google_oidc_mappings; port 8080 serves the
+ admin API and the authorize redirect to the test process."""
+
+ def create() -> types.TestContainerDocker:
+ keystore_path = issue_server_keystore(tls, tmpfs("googleidp-certs"), ISSUER_HOST)
+
+ container = WireMockContainer(image="wiremock/wiremock:2.35.1-1", secure=False)
+ container.with_volume_mapping(str(keystore_path.parent), "/certs", "ro")
+ container.with_network(network)
+ container.with_network_aliases(ISSUER_HOST)
+ container.with_kwargs(labels={CA_ID_LABEL: ca_id(tls)})
+
+ try:
+ container.start(f"--port 8080 --https-port 443 --https-keystore /certs/keystore.p12 --keystore-type PKCS12 --keystore-password {KEYSTORE_PASSWORD} --local-response-templating")
+ except Exception:
+ # Ryuk is disabled: a started-but-unready container would survive
+ # and keep squatting on the accounts.google.com alias, poisoning
+ # DNS for any replacement on the shared network.
+ container.stop()
+ raise
+
+ return types.TestContainerDocker(
+ id=container.get_wrapped_container().id,
+ host_configs={
+ "8080": types.TestContainerUrlConfig("http", container.get_container_host_ip(), container.get_exposed_port(8080)),
+ },
+ container_configs={
+ "443": types.TestContainerUrlConfig("https", ISSUER_HOST, 443),
+ },
+ )
+
+ def delete(container: types.TestContainerDocker) -> None:
+ client = docker.from_env()
+ try:
+ client.containers.get(container_id=container.id).stop()
+ client.containers.get(container_id=container.id).remove(v=True)
+ except docker.errors.NotFound:
+ logger.info("googleidp container %s already gone", container.id)
+
+ def restore(cache: dict) -> types.TestContainerDocker:
+ return types.TestContainerDocker.from_cache(cache)
+
+ def stale(container: types.TestContainerDocker) -> bool:
+ client = docker.from_env()
+ try:
+ labels = client.containers.get(container_id=container.id).attrs["Config"]["Labels"]
+ except docker.errors.NotFound:
+ return True
+ return labels.get(CA_ID_LABEL) != ca_id(tls)
+
+ return reuse.wrap(
+ request,
+ pytestconfig,
+ "googleidp",
+ lambda: types.TestContainerDocker(id="", host_configs={}, container_configs={}),
+ create,
+ delete,
+ restore,
+ stale=stale,
+ )
diff --git a/tests/fixtures/reuse.py b/tests/fixtures/reuse.py
index 803e9b874d..16fe94b39f 100644
--- a/tests/fixtures/reuse.py
+++ b/tests/fixtures/reuse.py
@@ -39,6 +39,7 @@ def wrap( # pylint: disable=too-many-arguments,too-many-positional-arguments
delete: Callable[[T], None],
restore: Callable[[dict], T],
rebuild: bool = False,
+ stale: Callable[[T], bool] | None = None,
) -> T:
"""
Wraps a resource creation and cleanup process with reuse and teardown options.
@@ -50,6 +51,7 @@ def wrap( # pylint: disable=too-many-arguments,too-many-positional-arguments
- delete: function to delete the resource
- restore: function to restore resource from cache
- rebuild: under --reuse, delete the cached resource and recreate it instead of restoring it
+ - stale: under --reuse, decides whether a restored resource is still usable; a stale resource is deleted and recreated
"""
resource = empty()
@@ -62,8 +64,14 @@ def wrap( # pylint: disable=too-many-arguments,too-many-positional-arguments
delete(restore(existing_resource))
pytestconfig.cache.set(key, None)
else:
- logger.info("Reusing existing %s(%s)", key, existing_resource)
- return restore(existing_resource)
+ restored = restore(existing_resource)
+ if stale is not None and stale(restored):
+ logger.info("Recreating stale %s(%s)", key, existing_resource)
+ delete(restored)
+ pytestconfig.cache.set(key, None)
+ else:
+ logger.info("Reusing existing %s(%s)", key, existing_resource)
+ return restored
if not teardown(request):
resource = create()
@@ -88,15 +96,23 @@ def wrap( # pylint: disable=too-many-arguments,too-many-positional-arguments
return
resource = restore(existing_resource)
+ logger.info(
+ "Removing %s",
+ resource.__log__() if hasattr(resource, "__log__") else resource,
+ )
+ delete(resource)
+ pytestconfig.cache.set(key, None)
+ return
+ # A run without --reuse owns only what it created this session: the
+ # cache key (and whatever a parked --reuse stack has under it) is left
+ # untouched.
logger.info(
"Removing %s",
resource.__log__() if hasattr(resource, "__log__") else resource,
)
delete(resource)
- pytestconfig.cache.set(key, None)
-
request.addfinalizer(finalizer)
if reuse(request):
diff --git a/tests/fixtures/signoz.py b/tests/fixtures/signoz.py
index 86f24b112f..a5abe7e045 100644
--- a/tests/fixtures/signoz.py
+++ b/tests/fixtures/signoz.py
@@ -13,6 +13,7 @@ from testcontainers.core.container import DockerContainer, Network
from fixtures import reuse, types
from fixtures.logger import setup_logger
+from fixtures.tls import CA_CONTAINER_PATH, CA_ID_LABEL, ca_id
logger = setup_logger(__name__)
@@ -27,10 +28,12 @@ def create_signoz(
pytestconfig: pytest.Config,
cache_key: str = "signoz",
env_overrides: dict | None = None,
+ tls: types.TLS | None = None,
) -> types.SigNoz:
"""
Factory function for creating a SigNoz container.
- Accepts optional env_overrides to customize the container environment.
+ Accepts optional env_overrides to customize the container environment, and
+ an optional integration CA (tls) to trust in addition to the system roots.
"""
def create() -> types.SigNoz:
@@ -115,6 +118,13 @@ def create_signoz(
"rw",
)
+ # The CA lands in the directory Go scans for system roots, so tests can
+ # stand in for real TLS hosts (e.g. the fake accounts.google.com) while
+ # the bundled roots keep working for everything else.
+ if tls:
+ container.with_volume_mapping(tls.ca_cert_path, CA_CONTAINER_PATH, "ro")
+ container.with_kwargs(labels={CA_ID_LABEL: ca_id(tls)})
+
container.start()
def ready(container: DockerContainer) -> None:
@@ -193,6 +203,16 @@ def create_signoz(
gateway=gateway,
)
+ def stale(container: types.SigNoz) -> bool:
+ if not tls:
+ return False
+ client = docker.from_env()
+ try:
+ labels = client.containers.get(container_id=container.self.id).attrs["Config"]["Labels"]
+ except docker.errors.NotFound:
+ return True
+ return labels.get(CA_ID_LABEL) != ca_id(tls)
+
return reuse.wrap(
request,
pytestconfig,
@@ -212,6 +232,7 @@ def create_signoz(
delete=delete,
restore=restore,
rebuild=pytestconfig.getoption("--rebuild"),
+ stale=stale,
)
@@ -222,6 +243,7 @@ def signoz( # pylint: disable=too-many-arguments,too-many-positional-arguments
gateway: types.TestContainerDocker,
sqlstore: types.TestContainerSQL,
clickhouse: types.TestContainerClickhouse,
+ tls: types.TLS,
request: pytest.FixtureRequest,
pytestconfig: pytest.Config,
) -> types.SigNoz:
@@ -233,4 +255,5 @@ def signoz( # pylint: disable=too-many-arguments,too-many-positional-arguments
clickhouse=clickhouse,
request=request,
pytestconfig=pytestconfig,
+ tls=tls,
)
diff --git a/tests/fixtures/tls.py b/tests/fixtures/tls.py
new file mode 100644
index 0000000000..bd4d2796ea
--- /dev/null
+++ b/tests/fixtures/tls.py
@@ -0,0 +1,143 @@
+import contextlib
+import datetime
+import hashlib
+import os
+import uuid
+from pathlib import Path
+
+import pytest
+from cryptography import x509
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
+from cryptography.hazmat.primitives.serialization import pkcs12
+from cryptography.x509.oid import NameOID
+
+from fixtures import reuse, types
+from fixtures.logger import setup_logger
+
+logger = setup_logger(__name__)
+
+# The integration CA is mounted into the directory Go scans for system roots,
+# so signoz containers trust it in addition to the bundled Debian roots (not
+# instead of them, which is what SSL_CERT_FILE would do) and mocks that must be
+# reached over TLS under a real hostname (e.g. accounts.google.com) can serve
+# certificates issued by it via issue_server_keystore.
+CA_CONTAINER_PATH = "/etc/ssl/certs/signoz-integration-ca.pem"
+KEYSTORE_PASSWORD = "password" # noqa: S105
+
+# Containers chained to the CA carry its id as this label; comparing it against
+# the current CA spots reused containers built against a rotated CA (or before
+# the CA existed) so they can be recreated instead of failing TLS opaquely.
+CA_ID_LABEL = "signoz.integration.ca"
+
+
+def ca_id(tls: types.TLS) -> str:
+ return hashlib.sha256(Path(tls.ca_cert_path).read_bytes()).hexdigest()[:12]
+
+
[email protected](name="tls", scope="package")
+def tls(
+ request: pytest.FixtureRequest,
+ pytestconfig: pytest.Config,
+) -> types.TLS:
+ """The integration CA. Server certificates for mocks are issued from it
+ with issue_server_keystore.
+
+ The CA cannot live in tmpfs: pytest wipes basetemp at every session start,
+ while reused containers (and the keystores issued for them in later
+ sessions) must keep chaining to the same CA. The pytest cache directory is
+ the cross-session store, like the reuse metadata itself."""
+
+ def create() -> types.TLS:
+ # Each CA gets a fresh directory: a run without --reuse must never
+ # rotate the files that a parked stack's containers bind-mount.
+ ca_dir = pytestconfig.cache.mkdir("tls") / uuid.uuid4().hex
+ ca_dir.mkdir()
+
+ now = datetime.datetime.now(datetime.UTC)
+ ca_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "signoz-integration-ca")])
+ ca_cert = (
+ x509.CertificateBuilder()
+ .subject_name(ca_name)
+ .issuer_name(ca_name)
+ .public_key(ca_key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - datetime.timedelta(days=1))
+ .not_valid_after(now + datetime.timedelta(days=3650))
+ .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
+ .sign(ca_key, hashes.SHA256())
+ )
+
+ (ca_dir / "ca.pem").write_bytes(ca_cert.public_bytes(serialization.Encoding.PEM))
+ (ca_dir / "ca.key").write_bytes(
+ ca_key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ )
+ )
+
+ return types.TLS(ca_cert_path=str(ca_dir / "ca.pem"), ca_key_path=str(ca_dir / "ca.key"))
+
+ def delete(tls: types.TLS) -> None:
+ for path in (tls.ca_cert_path, tls.ca_key_path):
+ try:
+ os.remove(path)
+ except FileNotFoundError:
+ logger.info("CA file %s already gone", path)
+ with contextlib.suppress(OSError):
+ os.rmdir(Path(tls.ca_cert_path).parent)
+
+ def restore(cache: dict) -> types.TLS:
+ return types.TLS.from_cache(cache)
+
+ def stale(tls: types.TLS) -> bool:
+ return not (Path(tls.ca_cert_path).is_file() and Path(tls.ca_key_path).is_file())
+
+ return reuse.wrap(
+ request,
+ pytestconfig,
+ "tls",
+ lambda: types.TLS(ca_cert_path="", ca_key_path=""),
+ create,
+ delete,
+ restore,
+ stale=stale,
+ )
+
+
+def issue_server_keystore(tls: types.TLS, directory: Path, hostname: str) -> Path:
+ """Write a PKCS12 keystore (keystore.p12, password KEYSTORE_PASSWORD) into
+ directory, holding a certificate for hostname issued by the integration CA.
+ Mount it into a mock container that must serve TLS as hostname."""
+ ca_cert = x509.load_pem_x509_certificate(Path(tls.ca_cert_path).read_bytes())
+ ca_key = serialization.load_pem_private_key(Path(tls.ca_key_path).read_bytes(), password=None)
+
+ now = datetime.datetime.now(datetime.UTC)
+ leaf_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ leaf_cert = (
+ x509.CertificateBuilder()
+ .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, hostname)]))
+ .issuer_name(ca_cert.subject)
+ .public_key(leaf_key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - datetime.timedelta(days=1))
+ .not_valid_after(now + datetime.timedelta(days=3650))
+ .add_extension(x509.SubjectAlternativeName([x509.DNSName(hostname)]), critical=False)
+ .add_extension(x509.ExtendedKeyUsage([x509.oid.ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
+ .sign(ca_key, hashes.SHA256())
+ )
+
+ keystore_path = directory / "keystore.p12"
+ keystore_path.write_bytes(
+ pkcs12.serialize_key_and_certificates(
+ name=hostname.encode(),
+ key=leaf_key,
+ cert=leaf_cert,
+ cas=[ca_cert],
+ encryption_algorithm=serialization.BestAvailableEncryption(KEYSTORE_PASSWORD.encode()),
+ )
+ )
+
+ return keystore_path
diff --git a/tests/fixtures/types.py b/tests/fixtures/types.py
index a070b1b659..fd9fda90ba 100644
--- a/tests/fixtures/types.py
+++ b/tests/fixtures/types.py
@@ -158,6 +158,26 @@ class Network:
return f"Network(id={self.id}, name={self.name})"
+@dataclass
+class TLS:
+ __test__ = False
+ ca_cert_path: str
+ ca_key_path: str
+
+ @staticmethod
+ def from_cache(cache: dict) -> "TLS":
+ return TLS(ca_cert_path=cache["ca_cert_path"], ca_key_path=cache["ca_key_path"])
+
+ def __cache__(self) -> dict:
+ return {
+ "ca_cert_path": self.ca_cert_path,
+ "ca_key_path": self.ca_key_path,
+ }
+
+ def __log__(self) -> str:
+ return f"TLS(ca_cert_path={self.ca_cert_path}, ca_key_path={self.ca_key_path})"
+
+
# Alerts related types
diff --git a/tests/integration/bootstrap/setup.py b/tests/integration/bootstrap/setup.py
index 33b34655c3..a9634c0da4 100644
--- a/tests/integration/bootstrap/setup.py
+++ b/tests/integration/bootstrap/setup.py
@@ -37,6 +37,7 @@ def test_telemetry_databases_exist(signoz: types.SigNoz) -> None:
def test_teardown(
signoz: types.SigNoz, # pylint: disable=unused-argument
idp: types.TestContainerIDP, # pylint: disable=unused-argument
+ googleidp: types.TestContainerDocker, # pylint: disable=unused-argument
create_user_admin: types.Operation, # pylint: disable=unused-argument
migrator: types.Operation, # pylint: disable=unused-argument
maildev: types.TestContainerDocker, # pylint: disable=unused-argument
diff --git a/tests/integration/tests/callbackauthn/04_google.py b/tests/integration/tests/callbackauthn/04_google.py
new file mode 100644
index 0000000000..e4f26a2d87
--- /dev/null
+++ b/tests/integration/tests/callbackauthn/04_google.py
@@ -0,0 +1,185 @@
+from collections.abc import Callable
+from http import HTTPStatus
+
+import requests
+from wiremock.resources.mappings import Mapping
+
+from fixtures import types
+from fixtures.auth import (
+ USER_ADMIN_EMAIL,
+ USER_ADMIN_PASSWORD,
+ assert_user_has_role,
+ find_user_with_roles_by_email,
+)
+from fixtures.googleidp import GOOGLE_DOMAIN, get_google_domain, google_oidc_mappings, perform_google_login
+from fixtures.types import Operation, SigNoz
+
+GOOGLE_CLIENT_ID = "google-client-id.apps.googleusercontent.com"
+GOOGLE_CLIENT_SECRET = "google-client-secret"
+
+
+def test_create_auth_domain(
+ signoz: SigNoz,
+ create_user_admin: Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+) -> None:
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ # Reruns against a reused stack find the domain from the previous run;
+ # drop it so creation always starts from a clean slate.
+ domain = get_google_domain(signoz, admin_token)
+ if domain:
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v1/domains/{domain['id']}"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=2,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v1/domains"),
+ json={
+ "name": GOOGLE_DOMAIN,
+ "config": {
+ "ssoEnabled": True,
+ "ssoType": "google_auth",
+ "googleAuthConfig": {
+ "clientId": GOOGLE_CLIENT_ID,
+ "clientSecret": GOOGLE_CLIENT_SECRET,
+ },
+ },
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=2,
+ )
+
+ assert response.status_code == HTTPStatus.CREATED
+
+
+def test_google_authn(
+ signoz: SigNoz,
+ googleidp: types.TestContainerDocker,
+ make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
+ get_token: Callable[[str, str], str],
+ get_session_context: Callable[[str], dict],
+) -> None:
+ email = "[email protected]"
+ make_http_mocks(googleidp, google_oidc_mappings(email=email, name="Google Viewer", hd=GOOGLE_DOMAIN, audience=GOOGLE_CLIENT_ID))
+
+ redirect_url = perform_google_login(signoz, googleidp, get_session_context, email)
+ assert "accessToken=" in redirect_url
+
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ found_user = find_user_with_roles_by_email(signoz, admin_token, email)
+
+ assert found_user["displayName"] == "Google Viewer"
+ assert_user_has_role(found_user, "signoz-viewer")
+
+
+def test_google_authn_hd_mismatch(
+ signoz: SigNoz,
+ googleidp: types.TestContainerDocker,
+ make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
+ get_token: Callable[[str, str], str],
+ get_session_context: Callable[[str], dict],
+) -> None:
+ # The id_token carries a hosted-domain claim for a different workspace than
+ # the auth domain; the callback must reject it and provision no user.
+ email = "[email protected]"
+ make_http_mocks(googleidp, google_oidc_mappings(email=email, name="Intruder", hd="other.workspace.test", audience=GOOGLE_CLIENT_ID))
+
+ redirect_url = perform_google_login(signoz, googleidp, get_session_context, email)
+ assert "callbackauthnerr" in redirect_url
+ assert "accessToken=" not in redirect_url
+
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v2/users"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK
+ assert not any(user["email"] == email for user in response.json()["data"])
+
+
+def test_google_authn_unverified_email(
+ signoz: SigNoz,
+ googleidp: types.TestContainerDocker,
+ make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
+ get_token: Callable[[str, str], str],
+ get_session_context: Callable[[str], dict],
+) -> None:
+ email = "[email protected]"
+ make_http_mocks(googleidp, google_oidc_mappings(email=email, name="Unverified", hd=GOOGLE_DOMAIN, audience=GOOGLE_CLIENT_ID, email_verified=False))
+
+ redirect_url = perform_google_login(signoz, googleidp, get_session_context, email)
+ assert "callbackauthnerr" in redirect_url
+
+ # Opting the domain into insecureSkipEmailVerified must let the same
+ # unverified identity through.
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ domain = get_google_domain(signoz, admin_token)
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v1/domains/{domain['id']}"),
+ json={
+ "config": {
+ "ssoEnabled": True,
+ "ssoType": "google_auth",
+ "googleAuthConfig": {
+ "clientId": GOOGLE_CLIENT_ID,
+ "clientSecret": GOOGLE_CLIENT_SECRET,
+ "insecureSkipEmailVerified": True,
+ },
+ },
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=2,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT
+
+ redirect_url = perform_google_login(signoz, googleidp, get_session_context, email)
+ assert "accessToken=" in redirect_url
+
+ found_user = find_user_with_roles_by_email(signoz, admin_token, email)
+ assert_user_has_role(found_user, "signoz-viewer")
+
+
+def test_google_role_mapping_default_role(
+ signoz: SigNoz,
+ googleidp: types.TestContainerDocker,
+ make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
+ get_token: Callable[[str, str], str],
+ get_session_context: Callable[[str], dict],
+) -> None:
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ domain = get_google_domain(signoz, admin_token)
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v1/domains/{domain['id']}"),
+ json={
+ "config": {
+ "ssoEnabled": True,
+ "ssoType": "google_auth",
+ "googleAuthConfig": {
+ "clientId": GOOGLE_CLIENT_ID,
+ "clientSecret": GOOGLE_CLIENT_SECRET,
+ },
+ "roleMapping": {
+ "defaultRole": "EDITOR",
+ },
+ },
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=2,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT
+
+ email = "[email protected]"
+ make_http_mocks(googleidp, google_oidc_mappings(email=email, name="Google Editor", hd=GOOGLE_DOMAIN, audience=GOOGLE_CLIENT_ID))
+
+ redirect_url = perform_google_login(signoz, googleidp, get_session_context, email)
+ assert "accessToken=" in redirect_url
+
+ found_user = find_user_with_roles_by_email(signoz, admin_token, email)
+ assert_user_has_role(found_user, "signoz-editor")
diff --git a/tests/pyproject.toml b/tests/pyproject.toml
index 0e8449fc9c..0a6deeb8a8 100644
--- a/tests/pyproject.toml
+++ b/tests/pyproject.toml
@@ -19,6 +19,8 @@ dependencies = [
"fastapi>=0.115",
"uvicorn[standard]>=0.34",
"py>=1.11",
+ "cryptography>=50.0.0",
+ "jwcrypto>=1.5.8",
]
[dependency-groups]
diff --git a/tests/uv.lock b/tests/uv.lock
index 7b4f5ecd04..ed550977cd 100644
--- a/tests/uv.lock
+++ b/tests/uv.lock
@@ -1070,8 +1070,10 @@ version = "0.1.0"
source = { virtual = "." }
dependencies = [
{ name = "clickhouse-connect" },
+ { name = "cryptography" },
{ name = "fastapi" },
{ name = "isodate" },
+ { name = "jwcrypto" },
{ name = "numpy" },
{ name = "psycopg2" },
{ name = "py" },
@@ -1093,8 +1095,10 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "clickhouse-connect", specifier = ">=0.8.18" },
+ { name = "cryptography", specifier = ">=50.0.0" },
{ name = "fastapi", specifier = ">=0.115" },
{ name = "isodate", specifier = ">=0.7.2" },
+ { name = "jwcrypto", specifier = ">=1.5.8" },
{ name = "numpy", specifier = ">=2.3.2" },
{ name = "psycopg2", specifier = ">=2.9.10" },
{ name = "py", specifier = ">=1.11" },