From 2c57cb8828862dbab03e0cb12e19c6804f831fde Mon Sep 17 00:00:00 2001 From: Clarth Date: Tue, 1 Dec 2026 15:16:53 -0500 Subject: [PATCH] Add tinyauth-web: env editor, service control, tinyauth OIDC login --- .gitignore | 5 + README.md | 72 +++++++++++ config.example.php | 29 +++++ public/callback.php | 52 ++++++++ public/index.php | 155 ++++++++++++++++++++++++ public/login.php | 25 ++++ public/logout.php | 9 ++ src/actions.php | 106 ++++++++++++++++ src/lib.php | 229 +++++++++++++++++++++++++++++++++++ sudoers/tinyauth-web.sudoers | 6 + 10 files changed, 688 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 config.example.php create mode 100644 public/callback.php create mode 100644 public/index.php create mode 100644 public/login.php create mode 100644 public/logout.php create mode 100644 src/actions.php create mode 100644 src/lib.php create mode 100644 sudoers/tinyauth-web.sudoers diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9f7ee3a --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# Secrets and local state. Never commit these. +config.php +data/ +tinyauth.env +*.env diff --git a/README.md b/README.md new file mode 100644 index 0000000..a093d5d --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +# tinyauth-web + +A small PHP web UI to edit the tinyauth environment file, and to start, stop, restart and check the tinyauth systemd service. Login goes through tinyauth itself (OIDC). + +## Features + +- Login with tinyauth (OIDC). Only members of one chosen group may use the tool. +- First run: the first person to log in picks the allowed group from their own groups. +- Edit, add and delete variables in the env file. Secret values are never shown; leave blank to keep. +- Every save writes a backup to `data/backups/` first. +- Start, stop, restart and status, through a narrow sudoers rule. +- Permission checks page shows what is missing. + +## Layout + +| Path | Purpose | +| --- | --- | +| `public/` | Web root. Only this directory should be served. | +| `src/` | Shared code (not served). | +| `config.example.php` | Template. Copy to `config.php`. | +| `sudoers/tinyauth-web.sudoers` | Sudo rule for the web user. | +| `data/` | Created at runtime: settings and backups. | + +## Install + +1. **Register an OIDC client in tinyauth.** In the tinyauth env file, add a client, for example: + + ``` + TINYAUTH_OIDC_CLIENTS_TINYAUTHWEB_CLIENTID=tinyauth-web + TINYAUTH_OIDC_CLIENTS_TINYAUTHWEB_CLIENTSECRET= + TINYAUTH_OIDC_CLIENTS_TINYAUTHWEB_NAME=tinyauth-web + TINYAUTH_OIDC_CLIENTS_TINYAUTHWEB_TRUSTEDREDIRECTURIS=https://tinyauth-web.example.com/callback.php + ``` + + Then restart tinyauth. Use the same client secret in `config.php`. + +2. **Copy the app** to the server, then: + + ``` + cp config.example.php config.php + ``` + + Edit `config.php`: `tinyauth_url`, `client_id`, `client_secret`, `redirect_uri`, `env_file`, and `service`. + +3. **Point the web server at `public/`.** Use HTTPS. The app sets secure cookies only over HTTPS. + +4. **Sudo rule** (as root): + + ``` + install -m 0440 sudoers/tinyauth-web.sudoers /etc/sudoers.d/tinyauth-web + visudo -cf /etc/sudoers.d/tinyauth-web + ``` + + Check that the systemctl path matches `command -v systemctl`. + +5. **Let the web user edit the env file** (keep the file owned by root, and only group-writable by the web user): + + ``` + chgrp www-data /etc/tinyauth/tinyauth.env + chmod 660 /etc/tinyauth/tinyauth.env + ``` + + Make sure the `data/` directory is writable by `www-data`, and that it is not inside the web root. + +6. Open the page, log in, and pick the access group. Check the **Permission checks** section. + +## Notes + +- Saved changes take effect only after tinyauth is restarted. The page reminds you of this. +- The group is read from the `groups` claim of the OIDC userinfo response. If your tinyauth uses a different claim, set `groups_claim`. +- To clear the access group, use **Change access group** on the page (only available to members of the current group). +- To clear a secret value, edit the file in a terminal. The web form doesn't clear secrets. diff --git a/config.example.php b/config.example.php new file mode 100644 index 0000000..752465b --- /dev/null +++ b/config.example.php @@ -0,0 +1,29 @@ + 'https://auth.example.com', + + // OIDC client registered in tinyauth (see README). + 'client_id' => 'tinyauth-web', + 'client_secret' => 'CHANGE_ME', + + // Must match the trusted redirect URI of the OIDC client exactly. + 'redirect_uri' => 'https://tinyauth-web.example.com/callback.php', + + // Claim in the userinfo response that lists the user's groups. + 'groups_claim' => 'groups', + + // tinyauth's environment file (the one systemd loads with EnvironmentFile=). + 'env_file' => '/etc/tinyauth/tinyauth.env', + + // systemd unit name, without .service. + 'service' => 'tinyauth', + + // Full path to systemctl. Must match the path in sudoers. + 'systemctl' => '/usr/bin/systemctl', + + // Settings, backups and other writable state. Keep it outside public/. + 'data_dir' => dirname(__DIR__) . '/data', +]; diff --git a/public/callback.php b/public/callback.php new file mode 100644 index 0000000..b626cfc --- /dev/null +++ b/public/callback.php @@ -0,0 +1,52 @@ + 'authorization_code', + 'code' => $code, + 'redirect_uri' => $cfg['redirect_uri'], + 'client_id' => $cfg['client_id'], + 'client_secret' => $cfg['client_secret'], + ]); + if (empty($tokens['access_token'])) { + throw new RuntimeException('tinyauth did not return an access token.'); + } + + $claims = http_request('GET', $discovery['userinfo_endpoint'], [], [ + 'Authorization: Bearer ' . $tokens['access_token'], + ]); + $groups = $claims[$cfg['groups_claim']] ?? []; + $groups = array_values(array_map('strval', (array) $groups)); + $user = (string) ($claims['preferred_username'] ?? $claims['email'] ?? $claims['sub'] ?? 'unknown'); + + session_regenerate_id(true); + $_SESSION['user'] = $user; + $_SESSION['groups'] = $groups; + redirect('index.php'); +} catch (RuntimeException $e) { + page_start('Login error'); + echo '

Login failed

' . h($e->getMessage()) . '

Try again

'; + page_end(); +} diff --git a/public/index.php b/public/index.php new file mode 100644 index 0000000..1f9e92c --- /dev/null +++ b/public/index.php @@ -0,0 +1,155 @@ +tinyauth-web

Log in with tinyauth

'; + page_end(); + exit; +} + +$groups = $_SESSION['groups'] ?? []; +$allowedGroup = load_settings()['allowed_group'] ?? ''; +$authorized = is_authorized($groups); + +if ($_SERVER['REQUEST_METHOD'] === 'POST') { + require_csrf(); + $action = (string) ($_POST['action'] ?? ''); + + if ($allowedGroup === '' && $action === 'setup') { + handle_setup($groups); + } elseif (!$authorized) { + http_response_code(403); + exit('Forbidden'); + } elseif ($action === 'reset_group') { + handle_reset_group(); + } elseif (in_array($action, SERVICE_ACTIONS, true)) { + handle_service($action); + } elseif ($action === 'save_config') { + handle_save_config(); + } + redirect('index.php'); +} + +$cfg = config(); +$flashes = take_flashes(); +$lastOutput = $_SESSION['last_output'] ?? ''; +unset($_SESSION['last_output']); +$token = csrf_token(); + +page_start('tinyauth-web'); +echo '

tinyauth-web

' . h($_SESSION['user']) . ' · log out
'; +foreach ($flashes as $flash) { + echo '

' . h($flash['message']) . '

'; +} + +if ($allowedGroup === '') { + echo '

First-time setup

'; + echo '

Choose the tinyauth group whose members may use this tool.

'; + if ($groups === []) { + echo '

Your account has no groups in tinyauth. Add yourself to a group first, then reload.

'; + } else { + echo '
'; + echo ''; + foreach ($groups as $group) { + echo '
'; + } + echo '

'; + } + echo '
'; + page_end(); + exit; +} + +if (!$authorized) { + echo '

You are not in the required tinyauth group ' . h($allowedGroup) . '.

'; + page_end(); + exit; +} + +$perms = []; +foreach (SERVICE_ACTIONS as $action) { + $perms[$action] = service_allowed($action); +} +$status = $perms['status'] ? service_run('status') : null; +$state = 'unknown'; +if ($status !== null && preg_match('/Active:\s+(\S+)/', $status['output'], $m)) { + $state = $m[1]; +} +$service = $cfg['service']; + +echo '

Service: ' . h($service) . '

'; +echo '

State: ' . h($state) . '

'; +echo '
'; +echo ''; +foreach (SERVICE_ACTIONS as $action) { + $disabled = $perms[$action] ? '' : ' disabled'; + echo ''; +} +echo '
'; +if ($status !== null) { + echo '
' . h($status['output']) . '
'; +} +if ($lastOutput !== '') { + echo '
' . h($lastOutput) . '
'; +} +echo '
'; + +$envPath = $cfg['env_file']; +$envReadable = is_file($envPath) && is_readable($envPath); +$envWritable = $envReadable && is_writable($envPath); +$dataWritable = is_writable(data_dir()); + +echo '

Permission checks

'; +foreach (SERVICE_ACTIONS as $action) { + echo ''; +} +echo ''; +echo ''; +echo ''; +echo '
sudo: systemctl ' . h($action) . ' ' . h($service) . '' . permission_mark($perms[$action]) . '
Env file readable (' . h($envPath) . ')' . permission_mark($envReadable) . '
Env file writable' . permission_mark($envWritable) . '
Data directory writable' . permission_mark($dataWritable) . '
'; +if (in_array(false, $perms, true)) { + echo '

Missing sudo rules: install sudoers/tinyauth-web.sudoers from this repo (check with visudo -cf).

'; +} +echo '
'; +echo '
'; +echo '
'; + +echo '

Config: ' . h($envPath) . '

'; +if (!$envReadable) { + echo '

The env file cannot be read by this user.

'; +} else { + $vars = env_parse((string) file_get_contents($envPath)); + echo '
'; + echo ''; + echo ''; + foreach ($vars as $key => $value) { + $name = h($key); + echo ''; + } + echo ''; + echo ''; + echo '
VariableValueDelete
' . $name . ''; + if (preg_match(SECRET_PATTERN, $key)) { + $hint = $value === '' ? '(not set)' : '(set, leave blank to keep)'; + echo ''; + } else { + echo ''; + } + echo '
add
'; + echo '

'; + echo 'Saving writes a backup first. Restart tinyauth to apply changes.

'; + echo '
'; +} +echo '
'; +page_end(); + +function permission_mark(bool $ok): string +{ + return $ok ? '✔ ok' : '✘ missing'; +} diff --git a/public/login.php b/public/login.php new file mode 100644 index 0000000..d18f645 --- /dev/null +++ b/public/login.php @@ -0,0 +1,25 @@ + 'code', + 'client_id' => $cfg['client_id'], + 'redirect_uri' => $cfg['redirect_uri'], + 'scope' => 'openid profile email groups', + 'state' => $state, + ])); +} catch (RuntimeException $e) { + page_start('Login error'); + echo '

Cannot reach tinyauth

' . h($e->getMessage()) . '

'; + page_end(); +} diff --git a/public/logout.php b/public/logout.php new file mode 100644 index 0000000..511d6fe --- /dev/null +++ b/public/logout.php @@ -0,0 +1,9 @@ + $group]); + flash('ok', "Access group set to \"$group\"."); +} + +function handle_reset_group(): void +{ + save_settings([]); + flash('info', 'Access group cleared. Pick a new one below.'); +} + +function handle_service(string $action): void +{ + $service = config()['service']; + if (!service_allowed($action)) { + flash('error', "sudo does not allow 'systemctl $action $service' for this user. See the permission checks."); + return; + } + $result = service_run($action); + $ok = $result['code'] === 0 || ($action === 'status' && $result['code'] === 3); + flash($ok ? 'ok' : 'error', ucfirst($action) . ' ' . ($ok ? 'done' : 'failed') . " (exit {$result['code']})."); + if ($result['output'] !== '') { + $_SESSION['last_output'] = $result['output']; + } +} + +function handle_save_config(): void +{ + $envFile = config()['env_file']; + if (!is_file($envFile) || !is_readable($envFile) || !is_writable($envFile)) { + flash('error', "Env file $envFile is missing or not readable/writable by this user."); + return; + } + + $content = (string) file_get_contents($envFile); + $original = env_parse($content); + $deletes = array_values(array_intersect(array_map('strval', (array) ($_POST['delete'] ?? [])), array_keys($original))); + $posted = (array) ($_POST['value'] ?? []); + $changes = []; + + foreach ($original as $key => $current) { + if (in_array($key, $deletes, true) || !array_key_exists($key, $posted)) { + continue; + } + $new = (string) $posted[$key]; + if (preg_match('/[\r\n]/', $new)) { + flash('error', "Value for $key contains a line break."); + return; + } + if (preg_match(SECRET_PATTERN, $key) && $new === '') { + continue; + } + if ($new !== $current) { + $changes[$key] = $new; + } + } + + $newKey = trim((string) ($_POST['new_key'] ?? '')); + $newValue = (string) ($_POST['new_value'] ?? ''); + if ($newKey !== '') { + if (!preg_match(KEY_PATTERN, $newKey)) { + flash('error', "\"$newKey\" is not a valid variable name (letters, digits and underscores)."); + return; + } + if (isset($original[$newKey]) && !in_array($newKey, $deletes, true)) { + flash('error', "$newKey already exists. Edit it in the table instead."); + return; + } + if (preg_match('/[\r\n]/', $newValue)) { + flash('error', "Value for $newKey contains a line break."); + return; + } + $changes[$newKey] = $newValue; + } + + if ($changes === [] && $deletes === []) { + flash('info', 'No changes to save.'); + return; + } + + $backupDir = data_dir() . '/backups'; + if (!is_dir($backupDir)) { + mkdir($backupDir, 0750, true); + } + $backup = $backupDir . '/tinyauth.env.' . date('Ymd-His'); + if (!copy($envFile, $backup)) { + flash('error', "Could not write backup to $backup. Nothing was changed."); + return; + } + + $updated = env_apply($content, $changes, $deletes); + if (file_put_contents($envFile, $updated, LOCK_EX) === false) { + flash('error', "Could not write $envFile."); + return; + } + flash('ok', 'Saved ' . (count($changes) + count($deletes)) . ' change(s). Backup: ' . basename($backup) . '. Restart tinyauth to apply.'); +} diff --git a/src/lib.php b/src/lib.php new file mode 100644 index 0000000..f4a0796 --- /dev/null +++ b/src/lib.php @@ -0,0 +1,229 @@ + 0, + 'path' => '/', + 'secure' => !empty($_SERVER['HTTPS']), + 'httponly' => true, + 'samesite' => 'Lax', + ]); + session_start(); +} + +function csrf_token(): string +{ + return $_SESSION['csrf'] ??= bin2hex(random_bytes(32)); +} + +function require_csrf(): void +{ + if (!hash_equals($_SESSION['csrf'] ?? '', (string) ($_POST['csrf'] ?? ''))) { + http_response_code(400); + exit('Invalid form token. Reload the page and try again.'); + } +} + +function flash(string $type, string $message): void +{ + $_SESSION['flash'][] = ['type' => $type, 'message' => $message]; +} + +function take_flashes(): array +{ + $flashes = $_SESSION['flash'] ?? []; + unset($_SESSION['flash']); + return $flashes; +} + +function data_dir(): string +{ + $dir = config()['data_dir']; + if (!is_dir($dir) && !mkdir($dir, 0750, true) && !is_dir($dir)) { + throw new RuntimeException("Cannot create data directory $dir"); + } + return $dir; +} + +function load_settings(): array +{ + $file = data_dir() . '/settings.json'; + if (!is_file($file)) { + return []; + } + $data = json_decode((string) file_get_contents($file), true); + return is_array($data) ? $data : []; +} + +function save_settings(array $settings): void +{ + $file = data_dir() . '/settings.json'; + if (file_put_contents($file, json_encode($settings, JSON_PRETTY_PRINT), LOCK_EX) === false) { + throw new RuntimeException("Cannot write $file"); + } +} + +function is_authorized(array $groups): bool +{ + $allowed = load_settings()['allowed_group'] ?? ''; + return $allowed !== '' && in_array($allowed, $groups, true); +} + +function http_request(string $method, string $url, array $fields = [], array $headers = []): array +{ + $ch = curl_init($url); + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 15, + CURLOPT_HTTPHEADER => $headers, + ]); + if ($method === 'POST') { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields)); + } + $body = curl_exec($ch); + $code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + $error = curl_error($ch); + curl_close($ch); + + if ($body === false) { + throw new RuntimeException("Request to $url failed: $error"); + } + if ($code >= 400) { + throw new RuntimeException("Request to $url returned HTTP $code"); + } + $json = json_decode((string) $body, true); + return is_array($json) ? $json : []; +} + +function oidc_discovery(): array +{ + static $discovery = null; + if ($discovery === null) { + $base = rtrim(config()['tinyauth_url'], '/'); + $discovery = http_request('GET', $base . '/.well-known/openid-configuration'); + } + return $discovery; +} + +function run_command(array $command): array +{ + $proc = proc_open($command, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + if (!is_resource($proc)) { + return ['code' => -1, 'output' => 'Could not start ' . $command[0]]; + } + fclose($pipes[0]); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $code = proc_close($proc); + return ['code' => $code, 'output' => trim($stdout . "\n" . $stderr)]; +} + +function service_allowed(string $action): bool +{ + $cfg = config(); + return run_command(['sudo', '-n', '-l', $cfg['systemctl'], $action, $cfg['service']])['code'] === 0; +} + +function service_run(string $action): array +{ + $cfg = config(); + return run_command(['sudo', '-n', $cfg['systemctl'], $action, $cfg['service']]); +} + +function env_parse(string $content): array +{ + $vars = []; + foreach (preg_split('/\r?\n/', $content) as $line) { + if (preg_match('/^\s*([A-Za-z_][A-Za-z0-9_]*)=(.*)$/', $line, $m)) { + $vars[$m[1]] = $m[2]; + } + } + return $vars; +} + +function env_apply(string $content, array $changes, array $deletes): string +{ + $out = []; + $written = []; + foreach (preg_split('/\r?\n/', $content) as $line) { + if (preg_match('/^\s*([A-Za-z_][A-Za-z0-9_]*)=/', $line, $m)) { + $key = $m[1]; + if (in_array($key, $deletes, true) || isset($written[$key])) { + continue; + } + if (array_key_exists($key, $changes)) { + $out[] = $key . '=' . $changes[$key]; + $written[$key] = true; + continue; + } + } + $out[] = $line; + } + foreach ($changes as $key => $value) { + if (!isset($written[$key])) { + $out[] = $key . '=' . $value; + } + } + return rtrim(implode("\n", $out), "\n") . "\n"; +} + +function page_start(string $title): void +{ + echo '' + . '' + . '' . h($title) . '
'; +} + +function page_end(): void +{ + echo '
'; +} diff --git a/sudoers/tinyauth-web.sudoers b/sudoers/tinyauth-web.sudoers new file mode 100644 index 0000000..dc69fa7 --- /dev/null +++ b/sudoers/tinyauth-web.sudoers @@ -0,0 +1,6 @@ +# Allows the web server user to manage only the tinyauth service. +# Install: sudo install -m 0440 tinyauth-web.sudoers /etc/sudoers.d/tinyauth-web +# sudo visudo -cf /etc/sudoers.d/tinyauth-web +# Adjust the systemctl path if `command -v systemctl` differs. + +www-data ALL=(root) NOPASSWD: /usr/bin/systemctl status tinyauth, /usr/bin/systemctl start tinyauth, /usr/bin/systemctl stop tinyauth, /usr/bin/systemctl restart tinyauth