1#!/usr/bin/env python3
2import json
3import os
4import re
5from pathlib import Path
6import subprocess
7import tempfile
8import unittest
9from unittest.mock import patch
10
11import snowglobe
12import router
13
14
15class SsoConnectivity(unittest.TestCase):
16 client = '''new sso.Client {
17 clientId = module.id
18 name = module.name
19 redirectUris { "https://fixture.example/api/callback" }
20}'''
21
22 def load(self, requirements=client, extra_hosts=(), http=""):
23 with tempfile.TemporaryDirectory(prefix="snowglobe-sso-") as temporary:
24 fixture = Path(temporary) / "fixture.pkl"
25 fixture.write_text(f'''amends {json.dumps((snowglobe.REPO / "config/Service.pkl").as_uri())}
26import {json.dumps((snowglobe.REPO / "config/OpenID.pkl").as_uri())} as sso
27name = "Fixture"
28requirements {{ {requirements} }}
29containers {{
30 ["app"] {{
31 image = "localhost/fixture:pinned"
32 {http}
33 extraHosts {{ {"; ".join(json.dumps(host) for host in extra_hosts)} }}
34 }}
35 ["worker"] {{ image = "localhost/fixture:pinned" }}
36}}
37''')
38 def pkl(*args, capture=False):
39 return subprocess.run([os.environ.get("PKL", "pkl"), *args[1:]], check=True, capture_output=capture, text=True)
40 with patch.object(snowglobe, "service_files", return_value={"fixture": fixture}), patch.object(snowglobe, "identity", return_value=3132), patch.object(snowglobe, "command", side_effect=pkl):
41 return snowglobe.load("fixture", {"domain": "fixture.example"})
42
43 def render(self, data):
44 return snowglobe.render(data, {"fixture": data})
45
46 def test_client_declaration_routes_every_task_without_changing_provider_inputs(self):
47 data = self.load()
48 self.assertEqual(data["inputs"]["oidc"], {
49 "alias": "oidc", "provider": "snowglobe", "kind": "client", "clientId": "fixture",
50 "name": "Fixture", "redirectUris": ["https://fixture.example/api/callback"],
51 "usernameAliases": {}, "allowGuests": False, "usernameRequired": False,
52 })
53 rendered = self.render(data)
54 self.assertEqual(rendered.count('extra_hosts = ["snowglobe.fixture.example:host-gateway"]'), 2)
55 self.assertNotIn("snowglobe.paperclover.net", rendered)
56
57 def test_explicit_hosts_take_precedence_and_duplicates_are_removed(self):
58 data = self.load(extra_hosts=[
59 "Snowglobe.Fixture.Example:192.0.2.10",
60 "other.example:2001:db8::10",
61 "other.example:2001:db8::10",
62 ])
63 rendered = self.render(data)
64 self.assertIn('extra_hosts = ["Snowglobe.Fixture.Example:192.0.2.10", "other.example:2001:db8::10"]', rendered)
65 self.assertEqual(rendered.count("snowglobe.fixture.example:host-gateway"), 1)
66
67 def test_multiple_clients_share_one_host_binding_per_task(self):
68 other = self.client.replace('clientId = module.id', 'alias = "other"; clientId = "other"')
69 data = self.load(requirements=self.client + "\n" + other)
70 self.assertEqual(self.render(data).count("snowglobe.fixture.example:host-gateway"), 2)
71
72 def test_plain_alias_omits_sso_role_and_identity_header(self):
73 data = self.load(requirements="", http='http { containerPort = 8080; subdomain = "fixture"; authRole = "infra-admin"; userHeader = "X-User"; plainHostnames { "api.fixture.example" } }')
74 tags = json.loads(re.search(r'tags = (\[.*\])', self.render(data))[1])
75 def nomad(path, _):
76 if path == '/v1/services':
77 return [{'Namespace': 'default', 'Services': [{'ServiceName': name} for name in ('fixture', 'forward-auth')]}]
78 if path.startswith('/v1/service/'):
79 name = path.rsplit('/', 1)[1]
80 return [{'ServiceName': name, 'JobID': name, 'AllocID': name, 'Address': '127.0.0.1', 'Port': 28000,
81 'Tags': tags if name == 'fixture' else []}]
82 return {'http': {'Status': 'success'}}
83 with tempfile.TemporaryDirectory() as temporary:
84 root = Path(temporary)
85 proof = root / 'proof'; proof.write_text('a' * 64)
86 environment = {'SNOWGLOBE_DOMAIN': 'fixture.example', 'SNOWGLOBE_DASHBOARD_PORT': '28001',
87 'SNOWGLOBE_PROXY_TOKEN_FILE': str(proof), 'SNOWGLOBE_STATE': temporary}
88 with patch.dict(os.environ, environment, clear=True), patch.object(router, 'nomad', nomad), patch.object(router, 'ROUTE_DIR', str(root / 'routes')):
89 rendered = router.render('fixture')
90 protected = rendered.split('fixture.fixture.example {', 1)[1].split('\n}\n', 1)[0]
91 public = rendered.split('api.fixture.example {', 1)[1].split('\n}\n', 1)[0]
92 self.assertIn('/snow.oauth2/auth', protected)
93 self.assertIn('role:infra-admin', protected)
94 self.assertIn('X-User', protected)
95 self.assertNotIn('/snow.oauth2/', public)
96 self.assertNotIn('X-User', public)
97 self.assertIn('reverse_proxy 127.0.0.1:28000', public)
98
99 def test_services_without_sso_preserve_their_explicit_hosts(self):
100 data = self.load(requirements="", extra_hosts=["other.example:host-gateway"])
101 rendered = self.render(data)
102 self.assertIn('extra_hosts = ["other.example:host-gateway"]', rendered)
103 self.assertNotIn("snowglobe.fixture.example", rendered)
104
105
106if __name__ == "__main__":
107 unittest.main()