From d391b4cbb89de6cd83c956b9e20a87c76fc2ba78 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 22 Aug 2026 22:31:37 +0200 Subject: [PATCH] test(unit): cover the postmarks, mediawiki and baserow shims Bookwyrm has tests for the same trusted-header SSO bridge and settings patcher; postmarks and baserow ship theirs untested, and the composer require-dev stripper is a pure transformation nobody exercised. Each test was checked by breaking its source: the admin gate failing open, the group matcher loosened to a prefix, require-dev left in place and the SSO gate forced open all turn the new tests red. --- .../files/sso/header_auth.test.js | 180 +++++ .../files/sso/patch_server.test.js | 98 +++ .../install/helpers/StripRequireDevTest.php | 146 ++++ .../web-app-baserow/files/sso/__init__.py | 3 + .../files/sso/test_infinito_sso.py | 649 ++++++++++++++++++ .../files/sso/test_settings_patch.py | 84 +++ 6 files changed, 1160 insertions(+) create mode 100644 tests/unit/javascript/roles/web-app-postmarks/files/sso/header_auth.test.js create mode 100644 tests/unit/javascript/roles/web-app-postmarks/files/sso/patch_server.test.js create mode 100644 tests/unit/php/roles/web-app-mediawiki/files/install/helpers/StripRequireDevTest.php create mode 100644 tests/unit/python/roles/web-app-baserow/files/sso/__init__.py create mode 100644 tests/unit/python/roles/web-app-baserow/files/sso/test_infinito_sso.py create mode 100644 tests/unit/python/roles/web-app-baserow/files/sso/test_settings_patch.py diff --git a/tests/unit/javascript/roles/web-app-postmarks/files/sso/header_auth.test.js b/tests/unit/javascript/roles/web-app-postmarks/files/sso/header_auth.test.js new file mode 100644 index 0000000000..69aae513b3 --- /dev/null +++ b/tests/unit/javascript/roles/web-app-postmarks/files/sso/header_auth.test.js @@ -0,0 +1,180 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const path = require("node:path"); + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../.."); +const SOURCE = path.join( + PROJECT_ROOT, + "roles/web-app-postmarks/files/sso/header_auth.js", +); +const proxyHeaderSso = require(SOURCE).default; + +const SSO_KEYS = ["PROXY_HEADER_SSO", "PROXY_HEADER_SSO_ADMIN_GROUP"]; +const OWNER = "administrator"; + +function run({ env = {}, headers = {}, session = {} } = {}) { + const saved = SSO_KEYS.map((key) => [key, process.env[key]]); + SSO_KEYS.forEach((key) => delete process.env[key]); + Object.assign(process.env, env); + + const lower = Object.fromEntries( + Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]), + ); + const req = { get: (name) => lower[name.toLowerCase()], session }; + let next = 0; + try { + proxyHeaderSso(req, {}, () => { + next += 1; + }); + } finally { + saved.forEach(([key, value]) => { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + }); + } + return { session: req.session, next }; +} + +test("the trusted username header opens the owner session", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true" }, + headers: { "X-Forwarded-Preferred-Username": OWNER }, + }); + assert.deepEqual(call.session, { loggedIn: true, ssoUser: OWNER }); + assert.equal(call.next, 1); +}); + +test("the preferred username wins over the plain forwarded user", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true" }, + headers: { + "X-Forwarded-Preferred-Username": OWNER, + "X-Forwarded-User": "someone-else", + }, + }); + assert.equal(call.session.ssoUser, OWNER); +}); + +test("an email-only identity is still proof enough", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true" }, + headers: { "X-Forwarded-Email": "owner@example.test" }, + }); + assert.deepEqual(call.session, { + loggedIn: true, + ssoUser: "owner@example.test", + }); +}); + +test("a request without an identity is left untouched", () => { + const anonymous = run({ env: { PROXY_HEADER_SSO: "true" } }); + assert.deepEqual(anonymous.session, {}); + assert.equal(anonymous.next, 1); + + const blank = run({ + env: { PROXY_HEADER_SSO: "true" }, + headers: { "X-Forwarded-User": " " }, + }); + assert.deepEqual(blank.session, {}); + assert.equal(blank.next, 1); +}); + +test("headers the proxy does not overwrite cannot inject an identity", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true" }, + headers: { + "X-Auth-Request-User": "attacker", + "X-Auth-Request-Preferred-Username": "attacker", + "Remote-User": "attacker", + }, + }); + assert.deepEqual(call.session, {}); + assert.equal(call.next, 1); +}); + +test("the bridge stays off until PROXY_HEADER_SSO is switched on", () => { + const headers = { "X-Forwarded-Preferred-Username": OWNER }; + ["", "false", "0", "off", "no"].forEach((value) => { + const call = run({ env: { PROXY_HEADER_SSO: value }, headers }); + assert.deepEqual(call.session, {}, `PROXY_HEADER_SSO=${value}`); + assert.equal(call.next, 1); + }); + assert.deepEqual(run({ headers }).session, {}); +}); + +test("every spelling of yes switches the bridge on", () => { + const headers = { "X-Forwarded-Preferred-Username": OWNER }; + ["true", "TRUE", "1", "yes", "On"].forEach((value) => { + const call = run({ env: { PROXY_HEADER_SSO: value }, headers }); + assert.equal(call.session.loggedIn, true, `PROXY_HEADER_SSO=${value}`); + }); +}); + +test("an identity outside the admin group gets no session", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true", PROXY_HEADER_SSO_ADMIN_GROUP: "admins" }, + headers: { + "X-Forwarded-Preferred-Username": OWNER, + "X-Forwarded-Groups": "users,guests", + }, + }); + assert.deepEqual(call.session, {}); + assert.equal(call.next, 1); +}); + +test("a missing group header gets no session rather than a free pass", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true", PROXY_HEADER_SSO_ADMIN_GROUP: "admins" }, + headers: { "X-Forwarded-Preferred-Username": OWNER }, + }); + assert.deepEqual(call.session, {}); + assert.equal(call.next, 1); +}); + +test("a group name that merely starts with the admin group does not match", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true", PROXY_HEADER_SSO_ADMIN_GROUP: "admins" }, + headers: { + "X-Forwarded-Preferred-Username": OWNER, + "X-Forwarded-Groups": "admins-readonly", + }, + }); + assert.deepEqual(call.session, {}); + assert.equal(call.next, 1); +}); + +test("the admin group is matched case-sensitively", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true", PROXY_HEADER_SSO_ADMIN_GROUP: "admins" }, + headers: { + "X-Forwarded-Preferred-Username": OWNER, + "X-Forwarded-Groups": "ADMINS", + }, + }); + assert.deepEqual(call.session, {}); + assert.equal(call.next, 1); +}); + +test("group membership is read through Keycloak's leading slash", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true", PROXY_HEADER_SSO_ADMIN_GROUP: "admins" }, + headers: { + "X-Forwarded-Preferred-Username": OWNER, + "X-Forwarded-Groups": "users, /admins", + }, + }); + assert.deepEqual(call.session, { loggedIn: true, ssoUser: OWNER }); +}); + +test("a request reaching the bridge before the session store passes through", () => { + const call = run({ + env: { PROXY_HEADER_SSO: "true" }, + headers: { "X-Forwarded-Preferred-Username": OWNER }, + session: null, + }); + assert.equal(call.session, null); + assert.equal(call.next, 1); +}); diff --git a/tests/unit/javascript/roles/web-app-postmarks/files/sso/patch_server.test.js b/tests/unit/javascript/roles/web-app-postmarks/files/sso/patch_server.test.js new file mode 100644 index 0000000000..bbbeef60e4 --- /dev/null +++ b/tests/unit/javascript/roles/web-app-postmarks/files/sso/patch_server.test.js @@ -0,0 +1,98 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../.."); +const PATCHER = path.join( + PROJECT_ROOT, + "roles/web-app-postmarks/files/sso/patch_server.js", +); +const IMPORT_ANCHOR = "import routes from './src/routes/index.js';"; +const MOUNT_ANCHOR = "app.use(session());"; +const IMPORT_LINE = "import proxyHeaderSso from './src/sso-header-auth.js';"; +const MOUNT_LINE = "app.use(proxyHeaderSso);"; +const ADMIN_GATE = "app.use('/admin', isAuthenticated, routes.admin);"; + +const UPSTREAM = [ + "import express from 'express';", + "import session from 'express-session';", + IMPORT_ANCHOR, + "", + "const app = express();", + "", + MOUNT_ANCHOR, + "", + "app.use((req, res, next) => {", + " res.locals.loggedIn = req.session.loggedIn;", + " next();", + "});", + "", + ADMIN_GATE, + "", +].join("\n"); + +function patch(source) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "postmarks-patch-")); + const server = path.join(dir, "server.js"); + fs.writeFileSync(server, source); + return () => { + const result = spawnSync(process.execPath, [PATCHER, server], { + encoding: "utf8", + }); + const text = fs.readFileSync(server, "utf8"); + return { ...result, text, rows: text.split("\n") }; + }; +} + +test("the bridge import lands directly under the upstream import block", () => { + const run = patch(UPSTREAM); + const result = run(); + + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /patched for trusted-header SSO/); + assert.equal( + result.rows.indexOf(IMPORT_LINE), + result.rows.indexOf(IMPORT_ANCHOR) + 1, + ); +}); + +test("the middleware mounts between the session and the admin gate", () => { + const { rows } = patch(UPSTREAM)(); + + assert.equal(rows.indexOf(MOUNT_LINE), rows.indexOf(MOUNT_ANCHOR) + 1); + assert.ok( + rows.indexOf(MOUNT_LINE) < rows.indexOf(ADMIN_GATE), + "the gate must see a session the middleware already touched", + ); +}); + +test("a second run changes nothing and says so", () => { + const run = patch(UPSTREAM); + const once = run().text; + const twice = run(); + + assert.equal(twice.status, 0, twice.stderr); + assert.match(twice.stdout, /already patched, skipping/); + assert.equal(twice.text, once); +}); + +test("a moved import anchor aborts instead of shipping an un-bridged server", () => { + const source = UPSTREAM.replace(IMPORT_ANCHOR, "import routes from './r.js';"); + const result = patch(source)(); + + assert.equal(result.status, 1); + assert.match(result.stderr, /import anchor not found/); + assert.equal(result.text, source); +}); + +test("a moved mount anchor aborts instead of shipping an un-bridged server", () => { + const source = UPSTREAM.replace(MOUNT_ANCHOR, "app.use(session(options));"); + const result = patch(source)(); + + assert.equal(result.status, 1); + assert.match(result.stderr, /mount anchor not found/); + assert.equal(result.text, source); +}); diff --git a/tests/unit/php/roles/web-app-mediawiki/files/install/helpers/StripRequireDevTest.php b/tests/unit/php/roles/web-app-mediawiki/files/install/helpers/StripRequireDevTest.php new file mode 100644 index 0000000000..21d4078d55 --- /dev/null +++ b/tests/unit/php/roles/web-app-mediawiki/files/install/helpers/StripRequireDevTest.php @@ -0,0 +1,146 @@ + ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes, + null, + ['PATH' => (string) getenv('PATH')] + ); + $stdout = (string) stream_get_contents($pipes[1]); + $stderr = (string) stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $code = proc_close($process); + + $after = is_file($file) ? (string) file_get_contents($file) : null; + if (is_file($file)) { + unlink($file); + } + + return [$stdout, $stderr, $code, $after]; + } + + private const MANIFEST = <<<'JSON' + { + "name": "acme/ext", + "require": {"php": ">=8.1"}, + "require-dev": {"phpunit/phpunit": "^10"}, + "autoload": {"psr-4": {"Acme\\": "src/"}} + } + JSON; + + public function testRequireDevIsRemovedFromTheManifest(): void + { + [$stdout, , $code, $after] = $this->runScript(self::MANIFEST); + + $this->assertSame(0, $code); + $this->assertSame("STRIP_REQUIRE_DEV_REMOVED\n", $stdout); + $this->assertArrayNotHasKey('require-dev', (array) json_decode((string) $after, true)); + } + + public function testTheRemainingKeysKeepTheirValuesAndOrder(): void + { + [, , , $after] = $this->runScript(self::MANIFEST); + + $decoded = (array) json_decode((string) $after, true); + $this->assertSame(['name', 'require', 'autoload'], array_keys($decoded)); + $this->assertSame('acme/ext', $decoded['name']); + $this->assertSame(['php' => '>=8.1'], $decoded['require']); + $this->assertSame(['psr-4' => ['Acme\\' => 'src/']], $decoded['autoload']); + } + + public function testAnEmptyObjectIsNotRewrittenAsAnArray(): void + { + [, , , $after] = $this->runScript('{"extra":{},"require-dev":{"a/b":"^1"}}'); + + $this->assertStringContainsString('"extra": {}', (string) $after); + $this->assertStringNotContainsString('[]', (string) $after); + } + + public function testSlashesAndUnicodeStayUnescaped(): void + { + [, , , $after] = $this->runScript('{"homepage":"https://acme.test/x","description":"Grüße","require-dev":{}}'); + + $this->assertStringContainsString('https://acme.test/x', (string) $after); + $this->assertStringContainsString('Grüße', (string) $after); + } + + public function testTheRewrittenFileEndsWithANewline(): void + { + [, , , $after] = $this->runScript(self::MANIFEST); + + $this->assertStringEndsWith("}\n", (string) $after); + } + + public function testAManifestWithoutRequireDevIsLeftByteForByte(): void + { + $original = '{"name":"acme/ext", "require":{"php":">=8.1"}}'; + [$stdout, , $code, $after] = $this->runScript($original); + + $this->assertSame(0, $code); + $this->assertSame("STRIP_REQUIRE_DEV_ABSENT\n", $stdout); + $this->assertSame($original, $after); + } + + public function testMalformedJsonFailsWithoutWritingAnything(): void + { + $original = '{"name": "acme/ext", "require-dev"'; + [, $stderr, $code, $after] = $this->runScript($original); + + $this->assertSame(1, $code); + $this->assertStringContainsString('is not a JSON object', $stderr); + $this->assertSame($original, $after); + } + + public function testATopLevelJsonArrayIsRejected(): void + { + $original = '[{"require-dev": {}}]'; + [, $stderr, $code, $after] = $this->runScript($original); + + $this->assertSame(1, $code); + $this->assertStringContainsString('is not a JSON object', $stderr); + $this->assertSame($original, $after); + } + + public function testAMissingManifestFails(): void + { + [, $stderr, $code] = $this->runScript(null); + + $this->assertSame(1, $code); + $this->assertStringContainsString('cannot read', $stderr); + } + + public function testAMissingArgumentIsAUsageError(): void + { + [, $stderr, $code] = $this->runScript(null, false); + + $this->assertSame(2, $code); + $this->assertStringContainsString('usage: strip_require_dev.php', $stderr); + } +} diff --git a/tests/unit/python/roles/web-app-baserow/files/sso/__init__.py b/tests/unit/python/roles/web-app-baserow/files/sso/__init__.py new file mode 100644 index 0000000000..86efabd459 --- /dev/null +++ b/tests/unit/python/roles/web-app-baserow/files/sso/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] diff --git a/tests/unit/python/roles/web-app-baserow/files/sso/test_infinito_sso.py b/tests/unit/python/roles/web-app-baserow/files/sso/test_infinito_sso.py new file mode 100644 index 0000000000..b263fe7d7a --- /dev/null +++ b/tests/unit/python/roles/web-app-baserow/files/sso/test_infinito_sso.py @@ -0,0 +1,649 @@ +from __future__ import annotations + +import importlib.util +import os +import sys +import unittest +from types import ModuleType, SimpleNamespace +from unittest.mock import MagicMock, patch + +from . import PROJECT_ROOT + +MODULE_PATH = PROJECT_ROOT / "roles/web-app-baserow/files/sso/infinito_sso.py" +HOSTNAME = "baserow.infinito.example" +SSO_ON = {"PROXY_HEADER_SSO": "true"} +IDENTITY = { + "username": "alice", + "email": "alice@baserow.infinito.example", + "name": "Alice Smith", + "is_admin": False, +} + + +class _FakeQ: + def __init__(self, **terms): + self.terms = [terms] if terms else [] + + def __or__(self, other): + combined = _FakeQ() + combined.terms = self.terms + other.terms + return combined + + +class _FakeAPIView: + @classmethod + def as_view(cls, **initkwargs): + return cls + + +class _FakeResponse: + def __init__(self, data): + self.data = data + + +class _Http404Error(Exception): + pass + + +class _PermissionDeniedError(Exception): + pass + + +def _normalize_email_address(email): + return str(email).strip().lower() + + +def _modules(spec): + created = {} + for name, attributes in spec.items(): + module = ModuleType(name) + for key, value in attributes.items(): + setattr(module, key, value) + created[name] = module + for name, module in created.items(): + parent, _, leaf = name.rpartition(".") + if parent in created: + setattr(created[parent], leaf, module) + return created + + +def _load_module(hostname=HOSTNAME): + stubs = _modules( + { + "baserow": {}, + "baserow.api": {}, + "baserow.api.user": {}, + "baserow.api.user.serializers": { + "log_in_user": MagicMock(name="log_in_user") + }, + "baserow.core": {}, + "baserow.core.models": { + "WORKSPACE_USER_PERMISSION_ADMIN": "ADMIN", + "UserProfile": MagicMock(name="UserProfile"), + "Workspace": MagicMock(name="Workspace"), + "WorkspaceUser": MagicMock(name="WorkspaceUser"), + }, + "baserow.core.user": {}, + "baserow.core.user.handler": {"UserHandler": MagicMock(name="UserHandler")}, + "baserow.core.user.utils": { + "normalize_email_address": _normalize_email_address + }, + "django": {}, + "django.conf": { + "settings": SimpleNamespace( + PUBLIC_WEB_FRONTEND_HOSTNAME=hostname, LANGUAGE_CODE="en" + ) + }, + "django.contrib": {}, + "django.contrib.auth": { + "get_user_model": MagicMock(return_value=MagicMock(name="User")) + }, + "django.core": {}, + "django.core.exceptions": {"PermissionDenied": _PermissionDeniedError}, + "django.db": {"transaction": SimpleNamespace(atomic=lambda func: func)}, + "django.db.models": {"Q": _FakeQ}, + "django.http": {"Http404": _Http404Error}, + "django.shortcuts": {"redirect": MagicMock(name="redirect")}, + "django.urls": {"path": MagicMock(name="path")}, + "rest_framework": {}, + "rest_framework.permissions": {"AllowAny": object()}, + "rest_framework.response": {"Response": _FakeResponse}, + "rest_framework.views": {"APIView": _FakeAPIView}, + } + ) + saved = {name: sys.modules.get(name) for name in stubs} + sys.modules.update(stubs) + try: + spec = importlib.util.spec_from_file_location( + "baserow_infinito_sso", MODULE_PATH + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + finally: + for name, original in saved.items(): + if original is None: + sys.modules.pop(name, None) + else: + sys.modules[name] = original + return module + + +def _fake_user(**overrides): + attributes = { + "is_active": True, + "email": IDENTITY["email"], + "first_name": IDENTITY["name"], + "is_staff": False, + "is_superuser": False, + "default_workspace": None, + } + attributes.update(overrides) + return SimpleNamespace( + save=MagicMock(name="save"), + set_unusable_password=MagicMock(name="set_unusable_password"), + **attributes, + ) + + +def _wire_orm(mod, *, existing, workspace_user="already-owned"): + lookup = mod.User.objects.select_for_update.return_value.filter.return_value + lookup.order_by.return_value.first.return_value = existing + mod.UserHandler.return_value.force_create_user.return_value = _fake_user() + mod.UserProfile.objects.get_or_create.return_value = ( + SimpleNamespace( + email_verified=True, + completed_onboarding=True, + completed_guided_tours=[], + save=MagicMock(name="profile_save"), + ), + False, + ) + owned = mod.WorkspaceUser.objects.select_related.return_value.filter.return_value + owned.order_by.return_value.first.return_value = ( + None + if workspace_user is None + else SimpleNamespace(workspace=workspace_user, user=existing) + ) + mod.WorkspaceUser.objects.create.return_value = SimpleNamespace( + workspace=mod.Workspace.objects.create.return_value + ) + + +class TestSsoEnabled(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def test_sso_is_disabled_when_the_environment_variable_is_unset(self): + with patch.dict(os.environ, {}, clear=True): + self.assertFalse(self.mod._sso_enabled()) + + def test_sso_is_enabled_for_every_documented_truthy_value(self): + for value in ("true", "TRUE", "1", "yes", "On"): + with patch.dict(os.environ, {"PROXY_HEADER_SSO": value}, clear=True): + self.assertTrue(self.mod._sso_enabled(), value) + + def test_sso_stays_disabled_for_an_unrecognised_value(self): + with patch.dict(os.environ, {"PROXY_HEADER_SSO": "maybe"}, clear=True): + self.assertFalse(self.mod._sso_enabled()) + + +class TestFirstHeader(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def test_returns_the_first_populated_candidate(self): + meta = { + "HTTP_X_FORWARDED_PREFERRED_USERNAME": "alice", + "HTTP_X_FORWARDED_USER": "bob", + } + self.assertEqual( + self.mod._first_header(meta, self.mod.USERNAME_HEADERS), "alice" + ) + + def test_skips_blank_and_whitespace_only_values(self): + meta = { + "HTTP_X_FORWARDED_PREFERRED_USERNAME": " ", + "HTTP_X_FORWARDED_USER": " bob ", + } + self.assertEqual(self.mod._first_header(meta, self.mod.USERNAME_HEADERS), "bob") + + def test_returns_none_when_no_candidate_is_present(self): + self.assertIsNone(self.mod._first_header({}, self.mod.USERNAME_HEADERS)) + + def test_ignores_proxy_uncontrolled_identity_headers(self): + meta = { + "HTTP_X_AUTH_REQUEST_USER": "attacker", + "HTTP_X_AUTH_REQUEST_PREFERRED_USERNAME": "attacker", + "HTTP_X_AUTH_REQUEST_EMAIL": "attacker@example.com", + "HTTP_REMOTE_USER": "attacker", + "HTTP_X_FORWARDED_NAME": "attacker", + } + self.assertIsNone(self.mod._first_header(meta, self.mod.USERNAME_HEADERS)) + self.assertIsNone(self.mod._first_header(meta, self.mod.EMAIL_HEADERS)) + self.assertIsNone(self.mod._first_header(meta, self.mod.NAME_HEADERS)) + + +class TestFallbackDomain(unittest.TestCase): + def test_prefers_the_configured_fallback_domain(self): + mod = _load_module() + with patch.dict( + os.environ, + {"PROXY_HEADER_SSO_FALLBACK_EMAIL_DOMAIN": "mail.example.org"}, + clear=True, + ): + self.assertEqual(mod._fallback_domain(), "mail.example.org") + + def test_falls_back_to_the_public_frontend_hostname(self): + mod = _load_module() + with patch.dict(os.environ, {}, clear=True): + self.assertEqual(mod._fallback_domain(), HOSTNAME) + + def test_strips_scheme_and_path_from_a_url_shaped_hostname(self): + mod = _load_module(hostname="https://baserow.infinito.example/app") + with patch.dict(os.environ, {}, clear=True): + self.assertEqual(mod._fallback_domain(), HOSTNAME) + + def test_defaults_to_localhost_when_nothing_is_configured(self): + mod = _load_module(hostname="") + with patch.dict(os.environ, {}, clear=True): + self.assertEqual(mod._fallback_domain(), "localhost") + + +class TestEmailFromIdentity(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def test_uses_the_forwarded_email_when_present(self): + with patch.dict(os.environ, {}, clear=True): + self.assertEqual( + self.mod._email_from_identity("alice", " Alice@Example.COM "), + "alice@example.com", + ) + + def test_uses_the_username_when_it_is_already_an_address(self): + with patch.dict(os.environ, {}, clear=True): + self.assertEqual( + self.mod._email_from_identity("Alice@Example.COM", None), + "alice@example.com", + ) + + def test_synthesises_an_address_from_the_username_and_fallback_domain(self): + with patch.dict(os.environ, {}, clear=True): + self.assertEqual( + self.mod._email_from_identity("alice.smith", None), + f"alice.smith@{HOSTNAME}", + ) + + def test_replaces_unsafe_characters_in_the_synthesised_local_part(self): + with patch.dict(os.environ, {}, clear=True): + self.assertEqual( + self.mod._email_from_identity("alice smith!", None), + f"alice.smith@{HOSTNAME}", + ) + + def test_falls_back_to_sso_user_without_any_identity(self): + with patch.dict(os.environ, {}, clear=True): + self.assertEqual( + self.mod._email_from_identity(None, None), f"sso-user@{HOSTNAME}" + ) + + def test_falls_back_to_sso_user_when_the_local_part_collapses(self): + with patch.dict(os.environ, {}, clear=True): + self.assertEqual( + self.mod._email_from_identity("!!!", None), f"sso-user@{HOSTNAME}" + ) + + +class TestDisplayName(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def test_prefers_the_forwarded_display_name(self): + self.assertEqual( + self.mod._display_name("alice", "alice@example.com", "Alice Smith"), + "Alice Smith", + ) + + def test_turns_dots_and_underscores_into_spaces(self): + self.assertEqual( + self.mod._display_name("alice_the.great", "alice@example.com", None), + "alice the great", + ) + + def test_derives_the_name_from_the_email_local_part_without_a_username(self): + self.assertEqual( + self.mod._display_name(None, "alice@example.com", None), "alice" + ) + + def test_uses_the_email_when_the_derived_name_is_too_short(self): + self.assertEqual( + self.mod._display_name("a", "alice@example.com", None), "alice@example.com" + ) + + def test_truncates_the_name_to_150_characters(self): + self.assertEqual( + len(self.mod._display_name("x" * 400, "alice@example.com", None)), 150 + ) + + +class TestGroupParsing(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def test_splits_groups_on_commas_and_whitespace(self): + self.assertEqual( + self.mod._split_groups("/admins, users editors"), + ["/admins", "users", "editors"], + ) + + def test_returns_no_groups_for_a_missing_header(self): + self.assertEqual(self.mod._split_groups(None), []) + + def test_matches_the_admin_group_regardless_of_a_leading_slash(self): + self.assertTrue(self.mod._group_matches("admins", "/admins")) + self.assertTrue(self.mod._group_matches("/admins", "admins")) + self.assertFalse(self.mod._group_matches("users", "/admins")) + + def test_is_admin_when_the_configured_group_is_forwarded(self): + with patch.dict( + os.environ, {"PROXY_HEADER_SSO_ADMIN_GROUP": "/admins"}, clear=True + ): + self.assertTrue(self.mod._is_admin(["users", "admins"])) + + def test_is_not_admin_when_no_admin_group_is_configured(self): + with patch.dict(os.environ, {}, clear=True): + self.assertFalse(self.mod._is_admin(["admins"])) + + def test_is_not_admin_when_the_group_is_absent(self): + with patch.dict( + os.environ, {"PROXY_HEADER_SSO_ADMIN_GROUP": "/admins"}, clear=True + ): + self.assertFalse(self.mod._is_admin(["users"])) + + +class TestIdentityFromRequest(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def _identity(self, meta, env=SSO_ON): + with patch.dict(os.environ, env, clear=True): + return self.mod._identity_from_request(SimpleNamespace(META=meta)) + + def test_raises_http404_when_sso_is_disabled(self): + with self.assertRaises(_Http404Error): + self._identity({"HTTP_X_FORWARDED_USER": "alice"}, env={}) + + def test_raises_permission_denied_without_any_identity_header(self): + with self.assertRaises(_PermissionDeniedError): + self._identity({}) + + def test_raises_permission_denied_for_proxy_uncontrolled_headers_only(self): + with self.assertRaises(_PermissionDeniedError): + self._identity( + { + "HTTP_X_AUTH_REQUEST_USER": "attacker", + "HTTP_REMOTE_USER": "attacker", + } + ) + + def test_builds_the_identity_from_the_forwarded_headers(self): + identity = self._identity( + { + "HTTP_X_FORWARDED_PREFERRED_USERNAME": "alice.smith", + "HTTP_X_FORWARDED_EMAIL": "Alice@Example.COM", + "HTTP_X_FORWARDED_GROUPS": "users", + } + ) + self.assertEqual( + identity, + { + "username": "alice.smith", + "email": "alice@example.com", + "name": "alice smith", + "is_admin": False, + }, + ) + + def test_synthesises_the_email_when_only_a_username_is_forwarded(self): + identity = self._identity({"HTTP_X_FORWARDED_USER": "alice"}) + self.assertEqual(identity["email"], f"alice@{HOSTNAME}") + + def test_marks_the_user_as_admin_when_the_admin_group_is_forwarded(self): + identity = self._identity( + { + "HTTP_X_FORWARDED_USER": "alice", + "HTTP_X_FORWARDED_GROUPS": "users,/admins", + }, + env={**SSO_ON, "PROXY_HEADER_SSO_ADMIN_GROUP": "admins"}, + ) + self.assertTrue(identity["is_admin"]) + + +class TestGetOrCreateUser(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def test_creates_a_local_user_when_no_account_matches(self): + _wire_orm(self.mod, existing=None) + user = self.mod._get_or_create_user(dict(IDENTITY)) + self.mod.UserHandler.return_value.force_create_user.assert_called_once_with( + email=IDENTITY["email"], + name=IDENTITY["name"], + password=None, + is_staff=False, + is_superuser=False, + ) + user.set_unusable_password.assert_called_once_with() + user.save.assert_any_call(update_fields=["password"]) + + def test_creates_the_user_as_staff_and_superuser_for_an_admin_identity(self): + _wire_orm(self.mod, existing=None) + self.mod._get_or_create_user({**IDENTITY, "is_admin": True}) + kwargs = self.mod.UserHandler.return_value.force_create_user.call_args.kwargs + self.assertTrue(kwargs["is_staff"]) + self.assertTrue(kwargs["is_superuser"]) + + def test_reuses_the_existing_account_instead_of_creating_one(self): + existing = _fake_user() + _wire_orm(self.mod, existing=existing) + self.assertIs(self.mod._get_or_create_user(dict(IDENTITY)), existing) + self.mod.UserHandler.return_value.force_create_user.assert_not_called() + existing.save.assert_not_called() + + def test_matches_the_account_by_email_and_by_username(self): + _wire_orm(self.mod, existing=_fake_user()) + self.mod._get_or_create_user(dict(IDENTITY)) + query = self.mod.User.objects.select_for_update.return_value.filter.call_args + self.assertEqual( + query.args[0].terms, + [ + {"email__iexact": IDENTITY["email"]}, + {"username__iexact": IDENTITY["email"]}, + {"username__iexact": IDENTITY["username"]}, + ], + ) + + def test_repairs_an_inactive_or_incomplete_existing_account(self): + existing = _fake_user(is_active=False, email="", first_name="A") + _wire_orm(self.mod, existing=existing) + self.mod._get_or_create_user(dict(IDENTITY)) + self.assertTrue(existing.is_active) + self.assertEqual(existing.email, IDENTITY["email"]) + self.assertEqual(existing.first_name, IDENTITY["name"]) + existing.save.assert_called_once_with( + update_fields=["is_active", "email", "first_name"] + ) + + def test_promotes_an_existing_account_for_an_admin_identity(self): + existing = _fake_user() + _wire_orm(self.mod, existing=existing) + self.mod._get_or_create_user({**IDENTITY, "is_admin": True}) + self.assertTrue(existing.is_staff) + self.assertTrue(existing.is_superuser) + existing.save.assert_called_once_with( + update_fields=["is_staff", "is_superuser"] + ) + + def test_never_demotes_an_existing_admin(self): + existing = _fake_user(is_staff=True, is_superuser=True) + _wire_orm(self.mod, existing=existing) + self.mod._get_or_create_user(dict(IDENTITY)) + self.assertTrue(existing.is_staff) + self.assertTrue(existing.is_superuser) + + +class TestEnsureProfile(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def _profile(self, **overrides): + attributes = { + "email_verified": True, + "completed_onboarding": True, + "completed_guided_tours": [], + } + attributes.update(overrides) + profile = SimpleNamespace(save=MagicMock(name="profile_save"), **attributes) + self.mod.UserProfile.objects.get_or_create.return_value = (profile, False) + return profile + + def test_creates_the_profile_with_the_configured_language(self): + self._profile() + user = _fake_user() + self.mod._ensure_profile(user) + self.mod.UserProfile.objects.get_or_create.assert_called_once_with( + user=user, defaults={"language": "en"} + ) + + def test_leaves_a_complete_profile_untouched(self): + profile = self._profile() + self.mod._ensure_profile(_fake_user()) + profile.save.assert_not_called() + + def test_repairs_an_unverified_and_unonboarded_profile(self): + profile = self._profile( + email_verified=False, + completed_onboarding=False, + completed_guided_tours=None, + ) + self.mod._ensure_profile(_fake_user()) + self.assertTrue(profile.email_verified) + self.assertTrue(profile.completed_onboarding) + self.assertEqual(profile.completed_guided_tours, []) + profile.save.assert_called_once_with( + update_fields=[ + "email_verified", + "completed_onboarding", + "completed_guided_tours", + ] + ) + + +class TestEnsureWorkspace(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def test_creates_a_named_admin_workspace_when_the_user_has_none(self): + _wire_orm(self.mod, existing=None, workspace_user=None) + user = _fake_user() + self.mod._ensure_workspace(user, "Alice Smith") + self.mod.Workspace.objects.create.assert_called_once_with( + name="Alice Smith's workspace" + ) + self.assertEqual( + self.mod.WorkspaceUser.objects.create.call_args.kwargs["permissions"], + "ADMIN", + ) + self.assertIs( + user.default_workspace, self.mod.Workspace.objects.create.return_value + ) + + def test_reuses_the_first_workspace_the_user_already_belongs_to(self): + _wire_orm(self.mod, existing=None, workspace_user="already-owned") + user = _fake_user() + self.mod._ensure_workspace(user, "Alice Smith") + self.mod.Workspace.objects.create.assert_not_called() + self.mod.WorkspaceUser.objects.create.assert_not_called() + self.assertEqual(user.default_workspace, "already-owned") + + +class TestSafeNextUrl(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + + def _safe(self, next_url): + query = {} if next_url is None else {"next": next_url} + return self.mod._safe_next_url(SimpleNamespace(GET=query)) + + def test_keeps_a_relative_path_with_its_query(self): + self.assertEqual(self._safe("/database/42?view=grid"), "/database/42?view=grid") + + def test_defaults_to_the_root_when_next_is_missing(self): + self.assertEqual(self._safe(None), "/") + + def test_rejects_an_absolute_url(self): + self.assertEqual(self._safe("https://evil.example/steal"), "/") + + def test_rejects_a_protocol_relative_url(self): + self.assertEqual(self._safe("//evil.example/steal"), "/") + + def test_rejects_a_backslash_disguised_absolute_url(self): + self.assertEqual(self._safe("\\\\evil.example/steal"), "/") + + def test_rejects_a_path_that_does_not_start_at_the_root(self): + self.assertEqual(self._safe("dashboard"), "/") + + def test_rejects_a_protocol_relative_url_smuggled_behind_whitespace(self): + self.assertEqual(self._safe("/\t/evil.example/steal"), "/") + self.assertEqual(self._safe("/\r\n//evil.example/steal"), "/evil.example/steal") + + +class TestViews(unittest.TestCase): + def setUp(self): + self.mod = _load_module() + self.payload = {"refresh_token": "refresh-1", "user_session": "session-1"} + + def _redirect_target(self, next_url): + request = SimpleNamespace(GET={"next": next_url}) + with patch.object(self.mod, "_login_payload", return_value=self.payload): + self.mod.ProxyHeaderLoginView().get(request) + return self.mod.redirect.call_args.args[0] + + def test_the_token_view_returns_the_login_payload(self): + request = SimpleNamespace(GET={}) + with patch.object(self.mod, "_login_payload", return_value=self.payload): + self.assertEqual( + self.mod.ProxyHeaderTokenView().get(request).data, self.payload + ) + self.assertEqual( + self.mod.ProxyHeaderTokenView().post(request).data, self.payload + ) + + def test_the_login_view_appends_the_tokens_to_the_next_url(self): + self.assertEqual( + self._redirect_target("/dashboard"), + "/dashboard?token=refresh-1&user_session=session-1", + ) + + def test_the_login_view_joins_an_existing_query_with_an_ampersand(self): + self.assertEqual( + self._redirect_target("/database/42?view=grid"), + "/database/42?view=grid&token=refresh-1&user_session=session-1", + ) + + def test_the_login_view_redirects_an_unsafe_next_url_to_the_root(self): + self.assertEqual( + self._redirect_target("https://evil.example"), + "/?token=refresh-1&user_session=session-1", + ) + + def test_the_login_payload_provisions_the_user_from_the_request_identity(self): + request = SimpleNamespace(META={"HTTP_X_FORWARDED_USER": "alice"}) + _wire_orm(self.mod, existing=_fake_user()) + with patch.dict(os.environ, SSO_ON, clear=True): + payload = self.mod._login_payload(request) + self.assertIs(payload, self.mod.log_in_user.return_value) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-baserow/files/sso/test_settings_patch.py b/tests/unit/python/roles/web-app-baserow/files/sso/test_settings_patch.py new file mode 100644 index 0000000000..e3c9f31605 --- /dev/null +++ b/tests/unit/python/roles/web-app-baserow/files/sso/test_settings_patch.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +import os +import sys +import unittest +from types import ModuleType +from unittest.mock import patch + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +PATCH_PATH = PROJECT_ROOT / "roles/web-app-baserow/files/sso/settings_patch.py" + +SSO_ROUTE = "api/infinito/sso/" +SSO_MODULE = "baserow.infinito_sso" + +BASE_URLPATTERNS = ["baserow.core.urls", "baserow.api.urls"] + + +def _fake_django_urls() -> ModuleType: + module = ModuleType("django.urls") + module.include = lambda dotted_path: ("include", dotted_path) + module.path = lambda route, view: ("path", route, view) + return module + + +class TestSettingsSsoPatch(unittest.TestCase): + """The patch appended to Baserow settings must mount the SSO endpoints only + when PROXY_HEADER_SSO is truthy, and be completely inert otherwise.""" + + def _apply(self, *, env, urlpatterns=None): + namespace = { + "urlpatterns": list( + BASE_URLPATTERNS if urlpatterns is None else urlpatterns + ) + } + urls = _fake_django_urls() + django = ModuleType("django") + django.urls = urls + code = compile(read_text(str(PATCH_PATH)), str(PATCH_PATH), "exec") + with ( + patch.dict(sys.modules, {"django": django, "django.urls": urls}), + patch.dict(os.environ, env, clear=True), + ): + exec(code, namespace) + return namespace + + def test_enabled_mounts_the_sso_include_first(self): + urlpatterns = self._apply(env={"PROXY_HEADER_SSO": "true"})["urlpatterns"] + self.assertEqual(urlpatterns[0], ("path", SSO_ROUTE, ("include", SSO_MODULE))) + + def test_enabled_keeps_the_existing_routes_behind_it(self): + urlpatterns = self._apply(env={"PROXY_HEADER_SSO": "true"})["urlpatterns"] + self.assertEqual(urlpatterns[1:], BASE_URLPATTERNS) + + def test_disabled_is_inert(self): + namespace = self._apply(env={"PROXY_HEADER_SSO": "false"}) + self.assertEqual(namespace["urlpatterns"], BASE_URLPATTERNS) + self.assertNotIn("_infinito_sso_path", namespace) + self.assertNotIn("_infinito_sso_include", namespace) + + def test_unset_is_inert(self): + namespace = self._apply(env={}) + self.assertEqual(namespace["urlpatterns"], BASE_URLPATTERNS) + self.assertNotIn("_infinito_sso_path", namespace) + self.assertNotIn("_infinito_sso_include", namespace) + + def test_truthy_aliases_activate(self): + for value in ("1", "yes", "on", "TRUE", "Yes"): + urlpatterns = self._apply(env={"PROXY_HEADER_SSO": value})["urlpatterns"] + self.assertEqual( + urlpatterns[0], + ("path", SSO_ROUTE, ("include", SSO_MODULE)), + f"{value!r} should mount the bridge", + ) + + def test_unknown_value_is_inert(self): + namespace = self._apply(env={"PROXY_HEADER_SSO": "maybe"}) + self.assertEqual(namespace["urlpatterns"], BASE_URLPATTERNS) + + +if __name__ == "__main__": + unittest.main()