1#!/usr/bin/env python3
2import json
3import os
4from pathlib import Path
5import shutil
6import subprocess
7import sys
8import xml.etree.ElementTree as ET
9import zipfile
10
11
12data = json.load(sys.stdin)
13root = Path(data["hostRoot"]) / "config"
14uid = data["uid"]
15service = Path(data["hostRoot"]).name
16variable = json.loads(subprocess.check_output(
17 ["nomad", "var", "get", "-out=json", f"nomad/jobs/{service}/inputs/oidc"],
18 text=True, stderr=subprocess.DEVNULL,
19))["Items"]
20
21plugins = root / "plugins"
22plugins.mkdir(parents=True, exist_ok=True)
23os.chown(plugins, uid, uid)
24files = {"meta.json", "Duende.IdentityModel.dll", "SSO-Auth.dll", "Duende.IdentityModel.OidcClient.dll"}
25archive, = Path(__file__).parent.glob("sso-authentication_*.zip")
26with zipfile.ZipFile(archive) as source:
27 if set(source.namelist()) != files:
28 raise ValueError("unexpected SSO plugin archive contents")
29 metadata = json.loads(source.read("meta.json"))
30 plugin = plugins / f"{metadata['name']}_{metadata['version']}"
31 if not all((plugin / name).is_file() for name in files):
32 plugin.mkdir(exist_ok=True)
33 os.chown(plugin, uid, uid)
34 for name in files:
35 path = plugin / name
36 path.write_bytes(source.read(name))
37 os.chown(path, uid, uid)
38 for previous in plugins.glob(f"{metadata['name']}_*"):
39 if previous.is_dir() and previous != plugin:
40 shutil.rmtree(previous)
41
42configs = plugins / "configurations"
43configs.mkdir(parents=True, exist_ok=True)
44os.chown(configs, uid, uid)
45path = configs / "SSO-Auth.xml"
46ET.register_namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
47tree = ET.parse(path if path.exists() else Path(__file__).with_name("sso.xml"))
48items = tree.getroot().findall("./OidConfigs/item")
49matches = [item for item in items if item.findtext("./key/string") == "snow"]
50if len(matches) != 1:
51 raise ValueError("expected one Jellyfin SSO provider named snow")
52config = matches[0].find("./value/PluginConfiguration")
53for name, value in {
54 "OidEndpoint": variable["issuerUrl"],
55 "OidClientId": variable["clientId"],
56 "OidSecret": variable["clientSecret"],
57 "Enabled": "true",
58 "DefaultUsernameClaim": "preferred_username",
59}.items():
60 element = config.find(name)
61 if element is None:
62 element = ET.SubElement(config, name)
63 element.text = value
64content = ET.tostring(tree.getroot(), encoding="utf-8", xml_declaration=True)
65if not path.exists() or path.read_bytes() != content:
66 pending = path.with_suffix(".xml.pending")
67 pending.write_bytes(content)
68 os.chmod(pending, 0o600)
69 os.chown(pending, uid, uid)
70 os.replace(pending, path)
71
72branding = root / "config"
73branding.mkdir(exist_ok=True)
74os.chown(branding, uid, uid)
75target = branding / "branding.xml"
76if not target.exists():
77 target.touch()
78 os.chown(target, uid, uid)
79
80system = branding / "system.xml"
81if not system.exists() or not system.stat().st_size:
82 system.write_bytes(b"<ServerConfiguration><EnableMetrics>true</EnableMetrics></ServerConfiguration>")
83 os.chown(system, uid, uid)
84settings = ET.parse(system)
85metrics = settings.getroot().find("EnableMetrics")
86if metrics is None:
87 metrics = ET.SubElement(settings.getroot(), "EnableMetrics")
88if metrics.text != "true":
89 metrics.text = "true"
90 pending = system.with_suffix(".xml.pending")
91 settings.write(pending, encoding="utf-8", xml_declaration=True)
92 os.chown(pending, uid, uid)
93 os.replace(pending, system)