Add tinyauth-web: env editor, service control, tinyauth OIDC login
This commit is contained in:
commit
2c57cb8828
10 changed files with 688 additions and 0 deletions
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
# Secrets and local state. Never commit these.
|
||||||
|
config.php
|
||||||
|
data/
|
||||||
|
tinyauth.env
|
||||||
|
*.env
|
||||||
72
README.md
Normal file
72
README.md
Normal file
|
|
@ -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=<generate a long random secret>
|
||||||
|
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.
|
||||||
29
config.example.php
Normal file
29
config.example.php
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
<?php
|
||||||
|
// Copy to config.php and edit. config.php is gitignored because it holds the client secret.
|
||||||
|
|
||||||
|
return [
|
||||||
|
// Base URL of tinyauth, as the browser sees it.
|
||||||
|
'tinyauth_url' => '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',
|
||||||
|
];
|
||||||
52
public/callback.php
Normal file
52
public/callback.php
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/src/lib.php';
|
||||||
|
|
||||||
|
start_session();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isset($_GET['error'])) {
|
||||||
|
throw new RuntimeException('tinyauth returned: ' . (string) $_GET['error']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$expected = $_SESSION['oidc_state'] ?? '';
|
||||||
|
unset($_SESSION['oidc_state']);
|
||||||
|
if ($expected === '' || !hash_equals($expected, (string) ($_GET['state'] ?? ''))) {
|
||||||
|
throw new RuntimeException('Login state did not match. Try logging in again.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$code = (string) ($_GET['code'] ?? '');
|
||||||
|
if ($code === '') {
|
||||||
|
throw new RuntimeException('No authorization code received.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$cfg = config();
|
||||||
|
$discovery = oidc_discovery();
|
||||||
|
$tokens = http_request('POST', $discovery['token_endpoint'], [
|
||||||
|
'grant_type' => '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 '<h1>Login failed</h1><p>' . h($e->getMessage()) . '</p><p><a href="login.php">Try again</a></p>';
|
||||||
|
page_end();
|
||||||
|
}
|
||||||
155
public/index.php
Normal file
155
public/index.php
Normal file
|
|
@ -0,0 +1,155 @@
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/src/lib.php';
|
||||||
|
require dirname(__DIR__) . '/src/actions.php';
|
||||||
|
|
||||||
|
start_session();
|
||||||
|
|
||||||
|
if (empty($_SESSION['user'])) {
|
||||||
|
page_start('tinyauth-web');
|
||||||
|
echo '<h1>tinyauth-web</h1><p><a class="button" href="login.php">Log in with tinyauth</a></p>';
|
||||||
|
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 '<header><h1>tinyauth-web</h1><span>' . h($_SESSION['user']) . ' · <a href="logout.php">log out</a></span></header>';
|
||||||
|
foreach ($flashes as $flash) {
|
||||||
|
echo '<p class="flash ' . h($flash['type']) . '">' . h($flash['message']) . '</p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($allowedGroup === '') {
|
||||||
|
echo '<section><h2>First-time setup</h2>';
|
||||||
|
echo '<p>Choose the tinyauth group whose members may use this tool.</p>';
|
||||||
|
if ($groups === []) {
|
||||||
|
echo '<p class="flash error">Your account has no groups in tinyauth. Add yourself to a group first, then reload.</p>';
|
||||||
|
} else {
|
||||||
|
echo '<form method="post"><input type="hidden" name="csrf" value="' . h($token) . '">';
|
||||||
|
echo '<input type="hidden" name="action" value="setup">';
|
||||||
|
foreach ($groups as $group) {
|
||||||
|
echo '<label><input type="radio" name="group" value="' . h($group) . '" required> ' . h($group) . '</label><br>';
|
||||||
|
}
|
||||||
|
echo '<p><button type="submit">Save access group</button></p></form>';
|
||||||
|
}
|
||||||
|
echo '</section>';
|
||||||
|
page_end();
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$authorized) {
|
||||||
|
echo '<p class="flash error">You are not in the required tinyauth group <b>' . h($allowedGroup) . '</b>.</p>';
|
||||||
|
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 '<section><h2>Service: <code>' . h($service) . '</code></h2>';
|
||||||
|
echo '<p>State: <span class="badge">' . h($state) . '</span></p>';
|
||||||
|
echo '<form method="post" style="display:inline-flex;gap:.5rem">';
|
||||||
|
echo '<input type="hidden" name="csrf" value="' . h($token) . '">';
|
||||||
|
foreach (SERVICE_ACTIONS as $action) {
|
||||||
|
$disabled = $perms[$action] ? '' : ' disabled';
|
||||||
|
echo '<button type="submit" name="action" value="' . h($action) . '"' . $disabled . '>' . h(ucfirst($action)) . '</button>';
|
||||||
|
}
|
||||||
|
echo '</form>';
|
||||||
|
if ($status !== null) {
|
||||||
|
echo '<pre>' . h($status['output']) . '</pre>';
|
||||||
|
}
|
||||||
|
if ($lastOutput !== '') {
|
||||||
|
echo '<pre>' . h($lastOutput) . '</pre>';
|
||||||
|
}
|
||||||
|
echo '</section>';
|
||||||
|
|
||||||
|
$envPath = $cfg['env_file'];
|
||||||
|
$envReadable = is_file($envPath) && is_readable($envPath);
|
||||||
|
$envWritable = $envReadable && is_writable($envPath);
|
||||||
|
$dataWritable = is_writable(data_dir());
|
||||||
|
|
||||||
|
echo '<section><h2>Permission checks</h2><table>';
|
||||||
|
foreach (SERVICE_ACTIONS as $action) {
|
||||||
|
echo '<tr><td>sudo: systemctl ' . h($action) . ' ' . h($service) . '</td><td>' . permission_mark($perms[$action]) . '</td></tr>';
|
||||||
|
}
|
||||||
|
echo '<tr><td>Env file readable (' . h($envPath) . ')</td><td>' . permission_mark($envReadable) . '</td></tr>';
|
||||||
|
echo '<tr><td>Env file writable</td><td>' . permission_mark($envWritable) . '</td></tr>';
|
||||||
|
echo '<tr><td>Data directory writable</td><td>' . permission_mark($dataWritable) . '</td></tr>';
|
||||||
|
echo '</table>';
|
||||||
|
if (in_array(false, $perms, true)) {
|
||||||
|
echo '<p>Missing sudo rules: install <code>sudoers/tinyauth-web.sudoers</code> from this repo (check with <code>visudo -cf</code>).</p>';
|
||||||
|
}
|
||||||
|
echo '<form method="post" style="margin-top:.8rem"><input type="hidden" name="csrf" value="' . h($token) . '">';
|
||||||
|
echo '<button type="submit" name="action" value="reset_group">Change access group</button></form>';
|
||||||
|
echo '</section>';
|
||||||
|
|
||||||
|
echo '<section><h2>Config: <code>' . h($envPath) . '</code></h2>';
|
||||||
|
if (!$envReadable) {
|
||||||
|
echo '<p class="flash error">The env file cannot be read by this user.</p>';
|
||||||
|
} else {
|
||||||
|
$vars = env_parse((string) file_get_contents($envPath));
|
||||||
|
echo '<form method="post"><input type="hidden" name="csrf" value="' . h($token) . '">';
|
||||||
|
echo '<input type="hidden" name="action" value="save_config">';
|
||||||
|
echo '<table><tr><th>Variable</th><th>Value</th><th>Delete</th></tr>';
|
||||||
|
foreach ($vars as $key => $value) {
|
||||||
|
$name = h($key);
|
||||||
|
echo '<tr><td><code>' . $name . '</code></td><td>';
|
||||||
|
if (preg_match(SECRET_PATTERN, $key)) {
|
||||||
|
$hint = $value === '' ? '(not set)' : '(set, leave blank to keep)';
|
||||||
|
echo '<input type="password" name="value[' . $name . ']" placeholder="' . h($hint) . '" autocomplete="off">';
|
||||||
|
} else {
|
||||||
|
echo '<input type="text" name="value[' . $name . ']" value="' . h($value) . '">';
|
||||||
|
}
|
||||||
|
echo '</td><td><input type="checkbox" name="delete[]" value="' . $name . '"></td></tr>';
|
||||||
|
}
|
||||||
|
echo '<tr><td><input type="text" name="new_key" placeholder="NEW_VARIABLE"></td>';
|
||||||
|
echo '<td><input type="text" name="new_value" placeholder="value"></td><td>add</td></tr>';
|
||||||
|
echo '</table>';
|
||||||
|
echo '<p><button type="submit"' . ($envWritable ? '' : ' disabled') . '>Save config</button> ';
|
||||||
|
echo 'Saving writes a backup first. Restart tinyauth to apply changes.</p>';
|
||||||
|
echo '</form>';
|
||||||
|
}
|
||||||
|
echo '</section>';
|
||||||
|
page_end();
|
||||||
|
|
||||||
|
function permission_mark(bool $ok): string
|
||||||
|
{
|
||||||
|
return $ok ? '<span class="yes">✔ ok</span>' : '<span class="no">✘ missing</span>';
|
||||||
|
}
|
||||||
25
public/login.php
Normal file
25
public/login.php
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/src/lib.php';
|
||||||
|
|
||||||
|
start_session();
|
||||||
|
|
||||||
|
try {
|
||||||
|
$cfg = config();
|
||||||
|
$state = bin2hex(random_bytes(16));
|
||||||
|
$_SESSION['oidc_state'] = $state;
|
||||||
|
|
||||||
|
$discovery = oidc_discovery();
|
||||||
|
redirect($discovery['authorization_endpoint'] . '?' . http_build_query([
|
||||||
|
'response_type' => '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 '<h1>Cannot reach tinyauth</h1><p>' . h($e->getMessage()) . '</p>';
|
||||||
|
page_end();
|
||||||
|
}
|
||||||
9
public/logout.php
Normal file
9
public/logout.php
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/src/lib.php';
|
||||||
|
|
||||||
|
start_session();
|
||||||
|
$_SESSION = [];
|
||||||
|
session_destroy();
|
||||||
|
redirect('index.php');
|
||||||
106
src/actions.php
Normal file
106
src/actions.php
Normal file
|
|
@ -0,0 +1,106 @@
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
function handle_setup(array $groups): void
|
||||||
|
{
|
||||||
|
$group = (string) ($_POST['group'] ?? '');
|
||||||
|
if (!in_array($group, $groups, true)) {
|
||||||
|
flash('error', 'Pick one of your own groups.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
save_settings(['allowed_group' => $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.');
|
||||||
|
}
|
||||||
229
src/lib.php
Normal file
229
src/lib.php
Normal file
|
|
@ -0,0 +1,229 @@
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
const SECRET_PATTERN = '/SECRET|PASSWORD|TOKEN/i';
|
||||||
|
const KEY_PATTERN = '/^[A-Za-z_][A-Za-z0-9_]*$/';
|
||||||
|
const SERVICE_ACTIONS = ['status', 'start', 'stop', 'restart'];
|
||||||
|
|
||||||
|
function config(): array
|
||||||
|
{
|
||||||
|
static $config = null;
|
||||||
|
if ($config === null) {
|
||||||
|
$file = dirname(__DIR__) . '/config.php';
|
||||||
|
if (!is_file($file)) {
|
||||||
|
http_response_code(500);
|
||||||
|
exit('Missing config.php. Copy config.example.php to config.php and edit it.');
|
||||||
|
}
|
||||||
|
$config = require $file;
|
||||||
|
}
|
||||||
|
return $config;
|
||||||
|
}
|
||||||
|
|
||||||
|
function h(?string $value): string
|
||||||
|
{
|
||||||
|
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
function redirect(string $to): never
|
||||||
|
{
|
||||||
|
header('Location: ' . $to);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
function start_session(): void
|
||||||
|
{
|
||||||
|
session_name('tinyauthweb');
|
||||||
|
session_set_cookie_params([
|
||||||
|
'lifetime' => 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 '<!doctype html><html lang="en"><head><meta charset="utf-8">'
|
||||||
|
. '<meta name="viewport" content="width=device-width,initial-scale=1">'
|
||||||
|
. '<title>' . h($title) . '</title><style>'
|
||||||
|
. 'body{font-family:system-ui,sans-serif;background:#f4f5f7;color:#222;margin:0}'
|
||||||
|
. 'main{max-width:960px;margin:0 auto;padding:1rem}'
|
||||||
|
. 'header{display:flex;justify-content:space-between;align-items:baseline;flex-wrap:wrap}'
|
||||||
|
. 'section{background:#fff;border:1px solid #ddd;border-radius:6px;padding:1rem;margin:1rem 0}'
|
||||||
|
. 'table{width:100%;border-collapse:collapse}'
|
||||||
|
. 'th,td{text-align:left;padding:.3rem;border-bottom:1px solid #eee;vertical-align:top}'
|
||||||
|
. 'input[type=text],input[type=password]{width:100%;box-sizing:border-box;padding:.3rem;font-family:monospace}'
|
||||||
|
. 'button,.button{padding:.4rem .9rem;border:1px solid #888;border-radius:4px;background:#eee;cursor:pointer;text-decoration:none;color:#222;display:inline-block}'
|
||||||
|
. 'button:disabled{opacity:.4;cursor:not-allowed}'
|
||||||
|
. '.flash{padding:.5rem;border-radius:4px}.flash.ok{background:#e3f6e5}.flash.error{background:#fbe3e3}.flash.info{background:#e6eefb}'
|
||||||
|
. '.badge{padding:.1rem .5rem;border-radius:4px;background:#eee}'
|
||||||
|
. '.yes{color:#1a7f37;font-weight:bold}.no{color:#b42318;font-weight:bold}'
|
||||||
|
. 'pre{background:#111;color:#ddd;padding:.6rem;overflow:auto;border-radius:4px;white-space:pre-wrap}'
|
||||||
|
. '</style></head><body><main>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function page_end(): void
|
||||||
|
{
|
||||||
|
echo '</main></body></html>';
|
||||||
|
}
|
||||||
6
sudoers/tinyauth-web.sudoers
Normal file
6
sudoers/tinyauth-web.sudoers
Normal file
|
|
@ -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
|
||||||
Loading…
Add table
Reference in a new issue