"""Unit tests for the SuccessFactors auth layer.""" from __future__ import annotations import base64 from xml.etree import ElementTree import httpx import pytest import respx from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from app.identity.successfactors_auth import ( BasicAuth, OAuth2ClientCredentialsAuth, OAuth2SamlBearerAuth, build_auth_from_config, build_signed_saml_assertion, ) def _make_private_key_pem() -> str: key = rsa.generate_private_key(public_exponent=65537, key_size=2048) return key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), ).decode() def test_basic_auth_sets_authorization_header(): auth = BasicAuth(username="apiuser@MYCO", password="pw") request = httpx.Request("GET", "https://x.example.com/") import asyncio asyncio.run(auth.apply(request)) header = request.headers["Authorization"] assert header.startswith("Basic ") decoded = base64.b64decode(header.removeprefix("Basic ").encode()).decode() assert decoded == "apiuser@MYCO:pw" def test_basic_auth_rejects_empty_credentials(): with pytest.raises(ValueError): BasicAuth(username="", password="p") with pytest.raises(ValueError): BasicAuth(username="u", password="") def test_build_signed_saml_assertion_structure(): pem = _make_private_key_pem() b64 = build_signed_saml_assertion( client_id="API_KEY_X", technical_user_id="sfadmin", token_url="https://api15.sapsf.cn/oauth/token", private_key_pem=pem, ) xml = base64.b64decode(b64).decode() # Core bits a SAP token endpoint will verify assert "