Compare commits

..

4 Commits

Author SHA1 Message Date
rainyy21 cf62f25ab6 Keep data/ and config/ out of the Docker build context
The self-updater's build failed reading 0600 .env files under data/local,
and they shouldn't end up in the image anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:25:26 -05:00
rainyy21 96e608126b add a login and encrypt the .env so people can't get in and still the api key 2026-11-11 17:01:25 -05:00
rainyy21 f662e647d7 wire up the web UI and fix config editing
- merge the web UI into the watcher: one request queue for the CLI and the
  website (check/deploy/start/stop/remove/add), validated by the watcher
- stop/start pause a repo via `paused` in repos.yml; add `gw stop`/`gw start`
- copy per-repo local files (.env, overrides) into the clone before deploys
- run the website as a second container with no docker socket or tokens
- move repos.yml editing into repos_file.py, shared by cli and watcher
- fix: removing the last repo wrote invalid YAML
- fix: long URLs were wrapped onto their own line
- add .dockerignore so .venv and .env aren't sent to the docker daemon

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 16:33:56 -05:00
rainyy21 a54c625d66 Self-update from a configurable remote (SELF_REMOTE), use gitea
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:30:38 -05:00
13 changed files with 734 additions and 75 deletions
+8
View File
@@ -0,0 +1,8 @@
.git
.venv
.env
stacks/
repos.yml
**/__pycache__
data/
config/
+13
View File
@@ -3,3 +3,16 @@ GITHUB_TOKEN=your-real-token
WEB_SECRET_KEY=change-me
# generate with: openssl rand -hex 32
WEBHOOK_SECRET=change-me
# web UI login (empty or placeholder hash = nobody can log in)
WEB_ADMIN_USER=admin
# generate with:
# python3 -c "from werkzeug.security import generate_password_hash as g; import getpass; print(g(getpass.getpass()))"
# keep the single quotes: the hash contains $ and compose would read those as variables
WEB_ADMIN_PASSWORD_HASH='change-me'
# encrypts the repo .env files saved from the web UI (data/local/) at rest.
# back it up somewhere else: lose it and those files can't be read anymore
# generate with:
# python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
ENV_ENCRYPTION_KEY=
+193
View File
@@ -0,0 +1,193 @@
# gitops-watcher
A small GitOps deployer for a single Docker host. It watches a list of Git
repositories and, when a branch gets a new commit, pulls it and runs
`docker compose up -d --build` for that repo. Removing a repo from the config
stops its stack.
No Kubernetes, no agents, no CI runners: one container with access to the
Docker socket, a YAML file listing your repos, and a CLI to see what's going on.
## How it works
Every `CHECK_INTERVAL` seconds the watcher goes through `repos.yml` and, for each repo:
1. Runs `git ls-remote` to get the latest commit on the branch (cheap, no clone).
2. **New commit:** clones the repo into `STACKS_DIR/<name>` (shallow), or fetches
and hard-resets an existing clone, then runs
`docker compose -p <name> up -d --build --remove-orphans`.
3. **No new commit:** runs `docker compose up -d` anyway, so containers that were
stopped or crashed come back. If `pull_image` is on, it pulls newer images first.
4. **Deploy failed:** retries the same commit with exponential backoff
(`CHECK_INTERVAL`, 2x, 4x … up to `MAX_BACKOFF`). A new commit is tried right away.
Repos that disappear from `repos.yml` get `docker compose down`. Their folder and
volumes are left on disk, since they may hold data. If the config has an invalid
entry, nothing is stopped that round, so a typo can't take a stack down.
State (last commit, last check, errors, backoff) is kept in `STACKS_DIR/.state.json`.
On `docker stop` the watcher finishes the repo it is working on before exiting
(the compose file gives it a 5 minute grace period).
## Quick start
```sh
git clone <this repo> gitops-watcher
cd gitops-watcher
cp .env.example .env # fill in the tokens you need
$EDITOR repos.yml # see below
docker compose up -d --build
docker logs -f gitops-watcher
```
Clones go to `/opt/gitops/<name>` on the host. That path is mounted at the same
location inside the container, so relative bind mounts in your stacks'
compose files (`./data:/data`) resolve to the right place on the host.
## Configuring repos
`repos.yml` sits next to `docker-compose.yml` (it's git-ignored). Example:
```yaml
defaults:
branch: main
compose_file: docker-compose.yml
pull_image: false
repos:
# private repo on Gitea
- name: test-app
url: https://gitea.example.com/me/test-app.git
token_env: GITEA_TOKEN
# public repo, all defaults
- name: public-app
url: https://github.com/me/public-app.git
# private repo on GitHub, different branch and compose file
- name: private-app
url: https://github.com/me/private-app.git
token_env: GITHUB_TOKEN
branch: production
compose_file: compose.yaml
```
| Key | Required | Default | Meaning |
|----------------|----------|--------------------|---------|
| `name` | yes | | Folder name and compose project name. Lowercase letters, digits, `-` and `_`. |
| `url` | yes | | Git URL. Use `https://` if you need a token. |
| `branch` | no | `main` | Branch to deploy. |
| `compose_file` | no | auto-detect | Compose file in the repo root. Unset lets `docker compose` find it. |
| `pull_image` | no | `true` | Run `docker compose pull --ignore-buildable` before each deploy and each check. |
| `token_env` | no | | Name of the env var holding an access token for this repo. |
| `paused` | no | `false` | Leave the stack alone (set by `gw stop` / the web UI's stop button). |
Anything under `defaults` applies to every repo unless the repo sets it itself.
The file is re-read every round, so edits take effect without a restart.
### Private repos
Put the token in `.env` and point the repo at it with `token_env`:
```sh
# .env
GITEA_TOKEN=...
GITHUB_TOKEN=...
```
The token is sent as an HTTP auth header through git's environment config. It
never appears in the command line, in `.git/config` or in logs. Don't put tokens
in the URL itself. After changing `.env`, recreate the container
(`docker compose up -d`) so the watcher picks up the new value.
## CLI
`cli.py` talks to the watcher through its state file and config, so run it inside
the container:
```sh
alias gw='docker exec -it gitops-watcher python cli.py'
```
| Command | What it does |
|---------|--------------|
| `gw status` | Table of every repo: status, commit, last check, last deploy, last error line. Exits `1` if any repo is failing, so it works in cron/monitoring. |
| `gw list-repos` | Repos from `repos.yml` with their settings and whether their token is set. |
| `gw check <name>` | Check a repo now instead of waiting for the next round. Clears any retry backoff. |
| `gw check <name> --force` | Redeploy even if the commit hasn't changed. |
| `gw check <name> --wait` | Wait and print the result. |
| `gw logs <name> [-f] [--tail N]` | Container logs for a stack. |
| `gw add <name> <url> [--branch B] [--token-env T] [--compose-file F]` | Add a repo to `repos.yml`. Only the options you give are written, the rest come from `defaults`. |
| `gw remove <name> [-y]` | Remove a repo from `repos.yml`. The watcher stops the stack on its next round. |
| `gw stop <name>` | Stop a stack and mark it `paused`, so the watcher leaves it down. |
| `gw start <name>` | Unpause a stack and deploy it. |
`add` and `remove` keep the comments and layout of `repos.yml`.
## Settings
Set these in the `environment:` block of `docker-compose.yml`.
| Variable | Default (compose file) | Meaning |
|----------|------------------------|---------|
| `CHECK_INTERVAL` | `30` | Seconds between rounds. |
| `STACKS_DIR` | `/opt/gitops` | Where repos are cloned. |
| `CONFIG_PATH` | `/config/repos.yml` | Path to the repo list. |
| `STATE_PATH` | `$STACKS_DIR/.state.json` | Where state is saved. |
| `REQUEST_DIR` | `$STACKS_DIR/.requests` | Where the CLI and the web UI drop requests for the watcher. |
| `LOCAL_DIR` | `$STACKS_DIR/.local` | Per-repo files that aren't in git (`.env`, overrides), copied into the clone before each deploy. |
| `GIT_TIMEOUT` | `300` | Seconds before a clone/fetch is killed. |
| `DEPLOY_TIMEOUT` | `1800` | Seconds before a pull/build/up is killed. |
| `MAX_BACKOFF` | `3600` | Longest wait between retries of a failing commit. |
## Running without Docker
For development:
```sh
python -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
cd app
CONFIG_PATH=../repos.yml STACKS_DIR=../stacks python watcher.py
```
Needs `git` and `docker compose` on the PATH.
## Web UI
`docker compose up -d` also starts `gitops-web`, a dashboard on port `8088`:
- status of every repo, and buttons to deploy, stop/start (pause) and remove
- an "add repo" form
- a file view per repo: read the repo's files, and edit local files such as
`.env` or `docker-compose.override.yml`. They're kept in `LOCAL_DIR/<name>`
and copied into the clone before every deploy, so they survive updates.
`.env` values are masked until you click to reveal them.
- `POST /webhook/<name>` for GitHub/Gitea push webhooks, so a push is deployed
right away instead of on the next round
The website has no Docker socket and no git tokens. It can only read the state
and write request files, which the watcher checks and acts on. Set these in
`.env` (see `.env.example`):
```sh
WEB_SECRET_KEY=... # openssl rand -hex 32; keeps open pages working across restarts
WEBHOOK_SECRET=... # openssl rand -hex 32; webhooks are off while it's empty
```
To add a webhook, point it at `http://<host>:8088/webhook/<name>` with content
type `application/json`, the `push` event, and `WEBHOOK_SECRET` as the secret.
**The website has no login**, and anyone who can use it can deploy any repo, which
means root on this host. Keep it on your LAN or behind a reverse proxy with access
control.
## Security notes
- The watcher container has the Docker socket, which means root on the host.
Only watch repos you trust: anyone who can push to a watched branch can run
anything on this machine.
- Tokens should be read-only (repo contents only).
+106
View File
@@ -0,0 +1,106 @@
"""Edit repos.yml while keeping its comments and layout (used by cli.py and watcher.py)."""
import os
from pathlib import Path
from ruamel.yaml import YAML
from ruamel.yaml.error import CommentMark
from ruamel.yaml.tokens import CommentToken
CONFIG_PATH = Path(os.environ.get("CONFIG_PATH", "repos.yml"))
rt_yaml = YAML()
rt_yaml.indent(mapping=2, sequence=4, offset=2)
rt_yaml.preserve_quotes = True
rt_yaml.width = 4096 # don't wrap long URLs onto their own line
def load() -> dict:
try:
with CONFIG_PATH.open() as f:
return rt_yaml.load(f) or {}
except FileNotFoundError:
return {}
def save(data) -> None:
# an empty list is written as `[]`, and a comment kept above it would push the
# `[]` onto its own line, which isn't valid YAML. So drop those comments.
repo_list = data.get("repos")
if repo_list is not None and len(repo_list) == 0:
if hasattr(repo_list, "ca"):
repo_list.ca.comment = None
if hasattr(data, "ca") and "repos" in data.ca.items:
data.ca.items["repos"][3] = None
# write in place (no temp file + rename): repos.yml is a single-file bind
# mount in docker, and replacing the file would detach it from the container
with CONFIG_PATH.open("w") as f:
rt_yaml.dump(data, f)
def repos(data) -> list:
"""The `repos:` list of a loaded config, created if missing."""
if data.get("repos") is None:
data["repos"] = []
return data["repos"]
def find(repo_list, name: str) -> int | None:
"""Index of the entry called `name`, or None."""
return next(
(i for i, r in enumerate(repo_list) if isinstance(r, dict) and r.get("name") == name),
None,
)
# ruamel stores the blank lines/comments *after* a list entry on that entry's
# last key, so they have to be moved by hand when entries are added or removed
def _trailing(entry):
tok = entry.ca.items.get(list(entry.keys())[-1])
return tok[2] if tok and len(tok) > 2 else None
def _set_trailing(entry, token) -> None:
tok = entry.ca.items.setdefault(list(entry.keys())[-1], [None, None, None, None])
tok[2] = token
def append_entry(repo_list, entry: dict) -> None:
"""Append with a blank line before it, like the hand-written entries."""
if repo_list and hasattr(repo_list[-1], "ca") and _trailing(repo_list[-1]) is None:
_set_trailing(repo_list[-1], CommentToken("\n\n", CommentMark(0), None))
repo_list.append(entry)
def delete_entry(repo_list, idx: int) -> None:
"""Delete an entry, keeping the comment that sits above the entry after it."""
after = _trailing(repo_list[idx]) if hasattr(repo_list[idx], "ca") else None
if idx > 0 and hasattr(repo_list[idx - 1], "ca"):
_set_trailing(repo_list[idx - 1], after)
elif after is not None:
text = "\n".join(
l.strip().lstrip("#").strip() for l in after.value.splitlines() if l.strip()
)
if text:
repo_list.yaml_set_start_comment(text, indent=2)
del repo_list[idx]
def set_key(name: str, key: str, value) -> bool:
"""Set `key: value` on one entry. Returns False if there's no such repo."""
data = load()
repo_list = repos(data)
idx = find(repo_list, name)
if idx is None:
return False
entry = repo_list[idx]
if key in entry:
entry[key] = value
else:
# the new key becomes the last one, so move the blank line/comment after the entry onto it
trailing = _trailing(entry)
_set_trailing(entry, None)
entry[key] = value
_set_trailing(entry, trailing)
save(data)
return True
+91 -6
View File
@@ -16,6 +16,7 @@ import yaml
from ruamel.yaml import YAML
from ruamel.yaml.error import CommentMark
from ruamel.yaml.tokens import CommentToken
from cryptography.fernet import Fernet, InvalidToken
CONFIG_PATH = Path(os.environ.get("CONFIG_PATH", "repos.yml"))
STACKS_DIR = Path(os.environ.get("STACKS_DIR", "stacks"))
@@ -27,6 +28,11 @@ REQUEST_DIR = Path(os.environ.get("REQUEST_DIR", STACKS_DIR / ".requests"))
# files edited in the website (.env, overrides...), copied into the clone before each deploy
LOCAL_DIR = Path(os.environ.get("LOCAL_DIR", STACKS_DIR / ".local"))
# encrypts the .env files saved from the website (LOCAL_DIR) at rest; empty = plaintext.
# generate with: python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
ENV_ENCRYPTION_KEY = os.environ.get("ENV_ENCRYPTION_KEY", "").strip()
ENC_PREFIX = "gitops-enc:v1:"
# seconds before a command is killed
GIT_TIMEOUT = int(os.environ.get("GIT_TIMEOUT", "300")) # clone / fetch
DEPLOY_TIMEOUT = int(os.environ.get("DEPLOY_TIMEOUT", "1800")) # build / pull
@@ -169,13 +175,87 @@ def compose(
return run(compose_cmd(name, path, compose_file) + list(args), cwd=path, timeout=timeout)
# --- local files (.env encryption) ---
def is_secret(filename: str) -> bool:
return filename == ".env" or filename.endswith(".env")
def _fernet() -> Fernet | None:
if not ENV_ENCRYPTION_KEY:
return None
try:
return Fernet(ENV_ENCRYPTION_KEY)
except ValueError:
raise RuntimeError("ENV_ENCRYPTION_KEY is not a valid Fernet key") from None
def encrypt_text(text: str) -> str:
"""Encrypt if a key is set, else leave as is."""
f = _fernet()
if not f:
return text
return ENC_PREFIX + f.encrypt(text.encode()).decode() + "\n"
def decrypt_text(text: str) -> str:
"""Plaintext passes through, so files saved before the key was set still work."""
if not text.startswith(ENC_PREFIX):
return text
f = _fernet()
if not f:
raise RuntimeError("file is encrypted but ENV_ENCRYPTION_KEY is not set")
try:
return f.decrypt(text[len(ENC_PREFIX) :].strip().encode()).decode()
except InvalidToken:
raise RuntimeError("can't decrypt: wrong ENV_ENCRYPTION_KEY") from None
def read_local(path: Path) -> str:
return decrypt_text(path.read_text(encoding="utf-8"))
def write_private(path: Path, text: str) -> None:
"""Atomic write, readable by the owner only."""
tmp = path.with_name(path.name + ".tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(text)
os.chmod(tmp, 0o600) # in case the .tmp was left over with other permissions
os.replace(tmp, path)
def encrypt_local_files() -> None:
"""On start: encrypt .env files that were saved before the key was set."""
if not _fernet() or not LOCAL_DIR.is_dir():
return
for f in LOCAL_DIR.glob("*/*"):
if not f.is_file() or not is_secret(f.name):
continue
try:
text = f.read_text(encoding="utf-8")
if not text.startswith(ENC_PREFIX):
write_private(f, encrypt_text(text))
log(f.parent.name, f"encrypted {f.name}")
except (OSError, UnicodeDecodeError) as e:
log(f.parent.name, f"can't encrypt {f.name}: {e}")
def sync_local_files(name: str, path: Path) -> None:
"""Copy LOCAL_DIR/<name>/* into the clone, so compose sees .env, overrides, etc."""
"""Copy LOCAL_DIR/<name>/* into the clone, so compose sees .env, overrides, etc.
Encrypted files are written decrypted: compose can only read plain .env files."""
local = LOCAL_DIR / name
if not local.is_dir() or not path.is_dir():
return
for f in local.iterdir():
if f.is_file():
if not f.is_file():
continue
if is_secret(f.name):
try:
text = read_local(f)
except RuntimeError as e: # better to fail the deploy than ship ciphertext as .env
raise RuntimeError(f"{f.name}: {e}") from None
write_private(path / f.name, text)
else:
shutil.copy2(f, path / f.name)
@@ -320,6 +400,7 @@ def remove_stack(name: str, state: dict) -> bool:
# The helper isn't part of the stack, so it survives the restart.
SELF_UPDATE = os.environ.get("SELF_UPDATE", "").lower() in ("1", "true", "yes")
SELF_DIR = Path(os.environ.get("SELF_DIR", "/self")) # the checkout, mounted read-only
SELF_REMOTE = os.environ.get("SELF_REMOTE", "origin") # git remote in the checkout to update from
UPDATER = "gitops-watcher-updater"
# project: compose project we run in (never managed as a repo, see main())
@@ -375,7 +456,7 @@ def check_self() -> None:
try:
branch = git_self("rev-parse", "--abbrev-ref", "HEAD")
remote = remote_hash(git_self("remote", "get-url", "origin"), branch)
remote = remote_hash(git_self("remote", "get-url", SELF_REMOTE), branch)
local = git_self("rev-parse", "HEAD")
dirty = git_self("status", "--porcelain", "--untracked-files=no")
except Exception as e:
@@ -384,12 +465,12 @@ def check_self() -> None:
if remote == SELF["running"] or remote == SELF.get("tried"):
return # up to date, or this commit already failed once
if dirty:
note(f"{branch} has {remote[:7]}, but the checkout has uncommitted changes: not updating")
note(f"{SELF_REMOTE}/{branch} has {remote[:7]}, but the checkout has uncommitted changes: not updating")
return
if local != remote:
try: # remote is behind us = unpushed commits
git_self("merge-base", "--is-ancestor", remote, local)
note(f"the checkout has commits not pushed to {branch}: not updating")
note(f"the checkout has commits not pushed to {SELF_REMOTE}/{branch}: not updating")
return
except Exception:
pass # behind (or diverged: `pull --ff-only` will refuse)
@@ -405,7 +486,7 @@ def check_self() -> None:
owner = SELF_DIR.stat()
docker_gid = os.stat("/var/run/docker.sock").st_gid
host_dir = SELF["host_dir"]
script = (f"git pull --ff-only origin {shlex.quote(branch)} && "
script = (f"git pull --ff-only {shlex.quote(SELF_REMOTE)} {shlex.quote(branch)} && "
f"docker compose -p {shlex.quote(SELF['project'])} up -d --build")
try:
run([
@@ -707,6 +788,10 @@ def main() -> None:
ensure_config()
detect_self()
try:
encrypt_local_files()
except RuntimeError as e: # bad key: deploys will report it per repo
log("watcher", str(e))
signal.signal(signal.SIGTERM, handle_stop)
signal.signal(signal.SIGINT, handle_stop)
+244 -54
View File
@@ -15,36 +15,73 @@ import os
import re
import secrets
import sys
from datetime import datetime
from datetime import datetime, timedelta
import threading
import time
from pathlib import Path
import yaml
from flask import (Flask, abort, flash, jsonify, redirect, render_template,
request, session, url_for)
from flask import (
Flask,
abort,
flash,
jsonify,
redirect,
render_template,
request,
session,
url_for,
)
from werkzeug.security import check_password_hash
# share settings and rules with the watcher (app/watcher.py, one folder up)
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from watcher import (CHECK_INTERVAL, CONFIG_PATH, LOCAL_DIR, # noqa: E402
REQUEST_DIR, STACKS_DIR, STATE_PATH, normalize, queue_request)
from watcher import ( # noqa: E402
CHECK_INTERVAL,
CONFIG_PATH,
LOCAL_DIR,
REQUEST_DIR,
STACKS_DIR,
STATE_PATH,
decrypt_text,
encrypt_text,
is_secret,
normalize,
queue_request,
read_local,
)
# ---------- settings ----------
TOKEN_ENVS = [t for t in os.environ.get("TOKEN_ENVS", "GITEA_TOKEN,GITHUB_TOKEN").split(",") if t]
TOKEN_ENVS = [
t for t in os.environ.get("TOKEN_ENVS", "GITEA_TOKEN,GITHUB_TOKEN").split(",") if t
]
WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "") # empty = webhooks turned off
ADMIN_USER = os.environ.get("ADMIN_USER", "")
ADMIN_PASSWORD_HASH = os.environ.get("ADMIN_PASSWORD_HASH", "") # empty = nobody can log in
MAX_FILE = 256 * 1024 # biggest file the editor will open/save
SAFE_REPO = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$") # compose project names are lowercase
SAFE_FILE = re.compile(r"^[A-Za-z0-9._-]{1,100}$") # no slashes = no ../ tricks
MAX_FILE = 256 * 1024 # biggest file the editor will open/save
SAFE_REPO = re.compile(
r"^[a-z0-9][a-z0-9_-]{0,62}$"
) # compose project names are lowercase
SAFE_FILE = re.compile(r"^[A-Za-z0-9._-]{1,100}$") # no slashes = no ../ tricks
SAFE_BRANCH = re.compile(r"^[A-Za-z0-9._/-]{1,100}$")
SAFE_URL = re.compile(r"^https?://[^\s@]+$") # no "@" = no tokens pasted into URLs
SAFE_URL = re.compile(r"^https?://[^\s@]+$") # no "@" = no tokens pasted into URLs
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY") or secrets.token_hex(32)
app.config["MAX_CONTENT_LENGTH"] = MAX_FILE + 64 * 1024
app.config.update(
SESSION_COOKIE_HTTPONLY=True, # page scripts can't read the cookie
SESSION_COOKIE_SAMESITE="Lax", # other sites' POSTs don't carry it
SESSION_COOKIE_SECURE=os.environ.get("COOKIE_SECURE") == "1", # set to 1 behind https
PERMANENT_SESSION_LIFETIME=timedelta(hours=12),
)
# ---------- reading data ----------
def load_json(path: Path, default):
try:
return json.loads(path.read_text())
@@ -68,7 +105,12 @@ def load_repos() -> list[dict]:
return repos
COMPOSE_NAMES = ("compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml")
COMPOSE_NAMES = (
"compose.yaml",
"compose.yml",
"docker-compose.yaml",
"docker-compose.yml",
)
def compose_file_of(repo: dict) -> str | None:
@@ -99,6 +141,7 @@ def pending_requests() -> dict[str, str]:
# ---------- writing requests ----------
def write_atomic(path: Path, text: str, mode: int | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + ".tmp")
@@ -110,6 +153,7 @@ def write_atomic(path: Path, text: str, mode: int | None = None) -> None:
# ---------- files ----------
def safe_path(base: Path, filename: str) -> Path:
"""Join base + filename, refusing anything that could escape base."""
if not SAFE_FILE.match(filename) or filename in (".", ".."):
@@ -120,10 +164,6 @@ def safe_path(base: Path, filename: str) -> Path:
return path
def is_secret(filename: str) -> bool:
return filename == ".env" or filename.endswith(".env")
def mask(text: str) -> str:
lines = []
for line in text.splitlines():
@@ -141,7 +181,7 @@ def env_keys(text: str) -> set[str]:
if not line or line.startswith("#") or "=" not in line:
continue
if line.startswith("export "):
line = line[len("export "):]
line = line[len("export ") :]
key = line.split("=", 1)[0].strip()
if key:
keys.add(key)
@@ -153,14 +193,20 @@ def missing_env(name: str) -> list[str]:
env = LOCAL_DIR / name / ".env"
if not example.is_file() or not env.is_file():
return []
return sorted(env_keys(example.read_text()) - env_keys(env.read_text()))
try:
have = env_keys(read_local(env))
except (RuntimeError, OSError, UnicodeDecodeError): # can't decrypt: the editor says why
return []
return sorted(env_keys(example.read_text()) - have)
def local_files(name: str) -> list[str]:
folder = LOCAL_DIR / name
if not folder.is_dir():
return []
return sorted(p.name for p in folder.iterdir() if p.is_file() and SAFE_FILE.match(p.name))
return sorted(
p.name for p in folder.iterdir() if p.is_file() and SAFE_FILE.match(p.name)
)
def git_files(repo: dict) -> list[str]:
@@ -171,9 +217,13 @@ def git_files(repo: dict) -> list[str]:
skip = set(local_files(repo["name"]))
names = []
for p in root.iterdir():
if (p.is_file() and p.name not in skip and SAFE_FILE.match(p.name)
and (not p.name.startswith(".") or p.name == ".env.example")
and p.stat().st_size <= MAX_FILE):
if (
p.is_file()
and p.name not in skip
and SAFE_FILE.match(p.name)
and (not p.name.startswith(".") or p.name == ".env.example")
and p.stat().st_size <= MAX_FILE
):
names.append(p.name)
compose = compose_file_of(repo)
return sorted(names, key=lambda n: (n != compose, n.lower()))
@@ -186,8 +236,90 @@ def read_text(path: Path) -> str:
abort(415, "not a text file")
# ---------- login (one admin account from the environment) ----------
PUBLIC = {"login", "static", "webhook"} # webhooks are checked by their signature
MAX_FAILS = 5 # wrong passwords per IP...
FAIL_WINDOW = 15 * 60 # ...within this many seconds = locked out until it passes
_fails: dict[str, list[float]] = {}
_fails_lock = threading.Lock()
def recent_fails(ip: str) -> list[float]:
now = time.monotonic()
with _fails_lock:
_fails[ip] = [t for t in _fails.get(ip, []) if now - t < FAIL_WINDOW]
return _fails[ip]
def note_fail(ip: str) -> None:
with _fails_lock:
_fails.setdefault(ip, []).append(time.monotonic())
def check_login(user: str, password: str) -> bool:
if not ADMIN_USER or not ADMIN_PASSWORD_HASH:
return False
# always hash, so a wrong username takes as long as a wrong password
try:
good_pw = check_password_hash(ADMIN_PASSWORD_HASH, password)
except ValueError: # not a werkzeug hash (e.g. the .env.example placeholder)
return False
return secrets.compare_digest(user, ADMIN_USER) and good_pw
def safe_next(target: str | None) -> str:
"""Only follow redirects back into this site."""
if target and target.startswith("/") and not target.startswith(("//", "/\\")):
return target
return url_for("index")
# registered before check_csrf, so an expired session goes to the login page
# instead of a "bad CSRF token" error
@app.before_request
def require_login():
if request.endpoint in PUBLIC or session.get("user"):
return None
if request.path.startswith("/api/"):
return jsonify(error="not logged in"), 401
nxt = request.full_path.rstrip("?") if request.method == "GET" else None
return redirect(url_for("login", next=nxt))
@app.route("/login", methods=["GET", "POST"])
def login():
if session.get("user"):
return redirect(url_for("index"))
configured = bool(ADMIN_USER and ADMIN_PASSWORD_HASH)
error = None
if request.method == "POST":
ip = request.remote_addr or "?"
if len(recent_fails(ip)) >= MAX_FAILS:
error = "too many attempts, try again in a few minutes"
elif check_login(request.form.get("username", ""), request.form.get("password", "")):
nxt = safe_next(request.args.get("next"))
session.clear() # fresh session (and CSRF token) for the logged-in user
session.permanent = True
session["user"] = ADMIN_USER
return redirect(nxt)
else:
note_fail(ip)
error = "wrong username or password"
status = 429 if error and error.startswith("too many") else 401 if error else 200
return render_template("login.html", error=error, configured=configured), status
@app.post("/logout")
def logout():
session.clear()
return redirect(url_for("login"))
# ---------- CSRF (stops other websites from clicking your buttons) ----------
def csrf_token() -> str:
if "csrf" not in session:
session["csrf"] = secrets.token_hex(16)
@@ -203,7 +335,9 @@ def check_csrf():
if request.method == "POST" and not request.path.startswith("/webhook/"):
sent = request.form.get("csrf") or request.headers.get("X-CSRF-Token") or ""
expected = session.get("csrf", "")
if not expected or not secrets.compare_digest(sent, expected): # no session = no token = reject
if not expected or not secrets.compare_digest(
sent, expected
): # no session = no token = reject
abort(400, "invalid or missing CSRF token: reload the page and try again")
@@ -220,6 +354,7 @@ def api_errors(e):
# ---------- template helpers ----------
@app.template_filter("ago")
def ago(iso: str | None) -> str:
if not iso:
@@ -259,23 +394,35 @@ def index():
status = "paused" if repo["paused"] else info.get("status", "new")
if status not in ORDER:
status = "error"
rows.append({
"name": name,
"status": status,
"commit": (info.get("commit") or "")[:7],
"last_check": info.get("last_check"),
"last_deploy": info.get("last_deploy"),
"error": info.get("error") if status == "error" else None,
"missing_env": missing_env(name),
"busy": pending.get(name),
})
rows.append(
{
"name": name,
"status": status,
"commit": (info.get("commit") or "")[:7],
"last_check": info.get("last_check"),
"last_deploy": info.get("last_deploy"),
"error": info.get("error") if status == "error" else None,
"missing_env": missing_env(name),
"busy": pending.get(name),
}
)
# repos that are queued to be added but not in repos.yml yet
known = {r["name"] for r in rows}
for name, action in pending.items():
if action == "add" and name not in known:
rows.append({"name": name, "status": "new", "commit": "", "last_check": None,
"last_deploy": None, "error": None, "missing_env": [], "busy": "add"})
rows.append(
{
"name": name,
"status": "new",
"commit": "",
"last_check": None,
"last_deploy": None,
"error": None,
"missing_env": [],
"busy": "add",
}
)
rows.sort(key=lambda r: (ORDER[r["status"]], r["name"]))
@@ -288,13 +435,22 @@ def index():
next_in = max(0, int(CHECK_INTERVAL - since))
stale = since > CHECK_INTERVAL * 2 + 60
return render_template("index.html", rows=rows, counts=counts, total=len(rows),
next_in=next_in, stale=stale, last_round=last_round,
interval=CHECK_INTERVAL, token_envs=TOKEN_ENVS)
return render_template(
"index.html",
rows=rows,
counts=counts,
total=len(rows),
next_in=next_in,
stale=stale,
last_round=last_round,
interval=CHECK_INTERVAL,
token_envs=TOKEN_ENVS,
)
# ---------- actions (all become request files) ----------
@app.post("/repos/<name>/<action>")
def repo_action(name: str, action: str):
if action not in ("deploy", "stop", "start"):
@@ -322,14 +478,17 @@ def add_repo():
f = request.form
name = f.get("name", "").strip()
url = f.get("url", "").strip()
branch = f.get("branch", "").strip() # empty = repos.yml default
branch = f.get("branch", "").strip() # empty = repos.yml default
compose_file = f.get("compose_file", "").strip() # empty = let compose find it
token_env = f.get("token_env", "").strip()
problems = []
if not SAFE_REPO.match(name):
problems.append("name: lowercase letters, numbers, - and _ only")
elif any(r["name"] == name for r in load_repos()) or pending_requests().get(name) == "add":
elif (
any(r["name"] == name for r in load_repos())
or pending_requests().get(name) == "add"
):
problems.append(f"a repo named {name} already exists")
if not SAFE_URL.match(url):
problems.append("url: must be http(s) with no username or token in it")
@@ -352,7 +511,7 @@ def add_repo():
if token_env:
entry["token_env"] = token_env
if f.get("pull_image") != "on":
entry["pull_image"] = False # the watcher's default is True
entry["pull_image"] = False # the watcher's default is True
if f.get("deploy_now") != "on":
entry["paused"] = True
@@ -363,26 +522,35 @@ def add_repo():
# ---------- file editor API (used by app.js) ----------
@app.get("/api/version")
def version():
"""A cheap fingerprint of everything the dashboard shows.
The page polls this and reloads only when it changes."""
def mtime(p: Path) -> int:
try:
return p.stat().st_mtime_ns
except OSError:
return 0
pending = pending_requests()
raw = f"{mtime(STATE_PATH)}|{mtime(Path(CONFIG_PATH))}|{sorted(pending.items())}"
return jsonify(version=hashlib.sha1(raw.encode()).hexdigest()[:16], busy=bool(pending))
return jsonify(
version=hashlib.sha1(raw.encode()).hexdigest()[:16], busy=bool(pending)
)
@app.get("/api/repos/<name>/files")
def list_files(name: str):
repo = get_repo(name)
local = local_files(name)
return jsonify(local=local, git=git_files(repo), compose_file=compose_file_of(repo),
missing_env=missing_env(name))
return jsonify(
local=local,
git=git_files(repo),
compose_file=compose_file_of(repo),
missing_env=missing_env(name),
)
@app.get("/api/repos/<name>/files/<kind>/<filename>")
@@ -401,9 +569,17 @@ def read_file(name: str, kind: str, filename: str):
abort(404, "file not found")
text = read_text(path)
secret = is_secret(filename)
if kind == "local" and secret:
try:
text = decrypt_text(text)
except RuntimeError as e:
return jsonify(error=f"{filename}: {e}"), 500
reveal = request.args.get("reveal") == "1"
return jsonify(content=mask(text) if secret and not reveal else text,
secret=secret, masked=secret and not reveal)
return jsonify(
content=mask(text) if secret and not reveal else text,
secret=secret,
masked=secret and not reveal,
)
@app.post("/api/repos/<name>/files/<filename>")
@@ -425,33 +601,47 @@ def save_file(name: str, filename: str):
path = safe_path(LOCAL_DIR / name, filename)
is_new = not path.exists()
shadows = is_new and filename in git_files(repo) # check BEFORE writing: git_files hides local names
write_atomic(path, content, mode=0o600 if is_secret(filename) else 0o644)
shadows = is_new and filename in git_files(
repo
) # check BEFORE writing: git_files hides local names
if is_secret(filename):
try:
content = encrypt_text(content)
except RuntimeError as e: # bad key: refuse rather than save plaintext
return jsonify(error=str(e)), 500
write_atomic(path, content, mode=0o600)
else:
write_atomic(path, content, mode=0o644)
if data.get("redeploy"):
queue_request("deploy", name)
return jsonify(ok=True, missing_env=missing_env(name), shadows_git=shadows)
# ---------- webhooks (GitHub / Gitea call this on every push) ----------
def valid_signature(body: bytes) -> bool:
"""GitHub sends X-Hub-Signature-256: sha256=<hex>, Gitea sends X-Gitea-Signature: <hex>."""
if not WEBHOOK_SECRET:
return False
expected = hmac.new(WEBHOOK_SECRET.encode(), body, hashlib.sha256).hexdigest()
sent = (request.headers.get("X-Hub-Signature-256", "").removeprefix("sha256=")
or request.headers.get("X-Gitea-Signature", ""))
sent = request.headers.get("X-Hub-Signature-256", "").removeprefix(
"sha256="
) or request.headers.get("X-Gitea-Signature", "")
return bool(sent) and hmac.compare_digest(sent, expected)
@app.post("/webhook/<name>")
def webhook(name: str):
if not valid_signature(request.get_data()): # before get_repo, so strangers can't probe repo names
if not valid_signature(
request.get_data()
): # before get_repo, so strangers can't probe repo names
abort(403, "bad or missing signature")
repo = get_repo(name)
event = request.headers.get("X-GitHub-Event") or request.headers.get("X-Gitea-Event")
event = request.headers.get("X-GitHub-Event") or request.headers.get(
"X-Gitea-Event"
)
if event == "ping":
return jsonify(ok=True, msg="pong")
if event != "push":
@@ -461,8 +651,8 @@ def webhook(name: str):
return jsonify(ok=True, ignored=f"push to {ref}")
if repo["paused"]:
return jsonify(ok=True, ignored="paused")
if name not in pending_requests(): # 5 quick pushes = 1 check
queue_request("check", name) # deploys if the branch has a new commit
if name not in pending_requests(): # 5 quick pushes = 1 check
queue_request("check", name) # deploys if the branch has a new commit
return jsonify(ok=True, queued="check"), 202
+2
View File
@@ -76,6 +76,7 @@ const api = (path, opts = {}) => fetch(path, {
...opts,
headers: { "X-CSRF-Token": CSRF, "Content-Type": "application/json", ...(opts.headers || {}) },
}).then(async res => {
if (res.status === 401) { location.reload(); throw new Error("logged out"); } // -> login page
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || `request failed (${res.status})`);
return data;
@@ -332,6 +333,7 @@ document.addEventListener("click", async e => {
if (document.hidden) return;
try {
const res = await fetch("/api/version", { cache: "no-store" });
if (res.status === 401 && !anyOpen()) location.reload(); // session expired -> login page
if (!res.ok) return;
const { version } = await res.json();
if (seen === null) seen = version;
+11 -2
View File
@@ -154,12 +154,12 @@
.field .hint { font-size: 11.5px; color: var(--muted); }
.row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
input[type=text], select {
input[type=text], input[type=password], select {
font: inherit; font-size: 13px; color: var(--text);
background: var(--bg); border: 1px solid var(--border); border-radius: 4px;
padding: 8px 10px; width: 100%;
}
input[type=text]:focus, select:focus { outline: none; border-color: var(--accent); }
input[type=text]:focus, input[type=password]:focus, select:focus { outline: none; border-color: var(--accent); }
input.invalid { border-color: var(--error); }
.check { display: flex; align-items: flex-start; gap: 10px; font-size: 13px; cursor: pointer; }
@@ -331,3 +331,12 @@ span.commit:hover { text-decoration: none; }
@keyframes blink { 50% { opacity: 0; } }
.editor-loading { padding: 16px; color: var(--muted); }
@media (prefers-reduced-motion: reduce) { .cursor { animation: none; } }
/* ---------- login ---------- */
.login { min-height: calc(100vh - 88px); display: flex; align-items: center; justify-content: center; }
.login .modal { max-width: 360px; }
.login .modal-head { color: var(--accent); }
.login .modal-foot .btn { width: 100%; }
.login-error { color: var(--error); font-size: 13px; }
.login-note { color: var(--warn); font-size: 12.5px; }
.logout { display: contents; }
+1 -1
View File
@@ -25,6 +25,6 @@
{% endfor %}
</div>
<script src="{{ url_for('static', filename='app.js') }}"></script>
{% block scripts %}<script src="{{ url_for('static', filename='app.js') }}"></script>{% endblock %}
</body>
</html>
+4
View File
@@ -18,6 +18,10 @@
{% endif %}
</div>
<button class="btn primary" data-open="#add-modal" data-focus="#f-name">+ add repo</button>
<form class="logout" method="post" action="{{ url_for('logout') }}">
<input type="hidden" name="csrf" value="{{ csrf_token() }}">
<button class="btn" title="log out {{ session.user }}">log out</button>
</form>
</div>
</header>
+32
View File
@@ -0,0 +1,32 @@
{% extends "base.html" %}
{% block title %}log in · gitops-watcher{% endblock %}
{% block content %}
<main class="login">
<form class="modal" method="post">
<input type="hidden" name="csrf" value="{{ csrf_token() }}">
<div class="modal-head">☂ gitops-watcher</div>
<div class="modal-body">
{% if not configured %}
<div class="login-note">login isn't set up: set WEB_ADMIN_USER and WEB_ADMIN_PASSWORD_HASH in .env and recreate the container</div>
{% endif %}
{% if error %}<div class="login-error" role="alert">{{ error }}</div>{% endif %}
<div class="field">
<label for="l-user">username</label>
<input type="text" id="l-user" name="username" autocomplete="username" autocapitalize="none" spellcheck="false" required autofocus>
</div>
<div class="field">
<label for="l-pass">password</label>
<input type="password" id="l-pass" name="password" autocomplete="current-password" required>
</div>
</div>
<div class="modal-foot">
<button class="btn primary">log in</button>
</div>
</form>
</main>
{% endblock %}
{# app.js drives the dashboard (and reloads it every minute), so it stays off this page #}
{% block scripts %}{% endblock %}
+28 -12
View File
@@ -19,16 +19,17 @@ services:
image: gitops-watcher
container_name: gitops-watcher
restart: unless-stopped
stop_grace_period: 5m # let a running deploy finish on `docker stop`
stop_grace_period: 5m # let a running deploy finish on `docker stop`
env_file: .env
environment:
<<: *paths
# pull + rebuild this stack when its own branch gets a new commit
# (only when the checkout is clean; see check_self() in app/watcher.py)
SELF_UPDATE: "true"
SELF_REMOTE: gitea # which remote of this checkout to follow (git remote -v)
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- .:/self:ro # this checkout, to compare its commit with the remote
- .:/self:ro # this checkout, to compare its commit with the remote
# a folder, not the single file: Docker would create a *directory* named
# repos.yml if the file didn't exist yet
- ./config:/config
@@ -36,23 +37,38 @@ services:
- /opt/gitops:/opt/gitops
gitops-web:
image: gitops-watcher # same image, built by the service above
image: gitops-watcher # same image, built by the service above
container_name: gitops-web
depends_on: [gitops-watcher]
restart: unless-stopped
command: ["gunicorn", "--workers", "1", "--threads", "4", "--bind", "0.0.0.0:5000",
"--chdir", "/app/web", "app:app"]
command:
[
"gunicorn",
"--workers",
"1",
"--threads",
"4",
"--bind",
"0.0.0.0:5000",
"--chdir",
"/app/web",
"app:app",
]
ports:
- "8088:5000" # LAN only until there's a login in front (e.g. an NPM access list)
- "8088:5000" # LAN only until there's a login in front (e.g. an NPM access list)
environment:
<<: *paths
TOKEN_ENVS: GITEA_TOKEN,GITHUB_TOKEN # names only, for the add-repo dropdown
TOKEN_ENVS: GITEA_TOKEN,GITHUB_TOKEN # names only, for the add-repo dropdown
SECRET_KEY: ${WEB_SECRET_KEY}
WEBHOOK_SECRET: ${WEBHOOK_SECRET} # same value goes in the GitHub/Gitea webhook settings
WEBHOOK_SECRET: ${WEBHOOK_SECRET} # same value goes in the GitHub/Gitea webhook settings
ADMIN_USER: ${WEB_ADMIN_USER}
ADMIN_PASSWORD_HASH: ${WEB_ADMIN_PASSWORD_HASH}
ENV_ENCRYPTION_KEY: ${ENV_ENCRYPTION_KEY} # the watcher gets it through env_file
COOKIE_SECURE: "0"
volumes:
# NO docker socket: the website can't run containers, only ask the watcher
- ./config:/config:ro
- ./data:/data:ro # reads state.json...
- ./data/local:/data/local # ...but only writes local files
- ./data/requests:/data/requests # ...and requests
- /opt/gitops:/opt/gitops:ro # reads the clones to show repo files
- ./data:/data:ro # reads state.json...
- ./data/local:/data/local # ...but only writes local files
- ./data/requests:/data/requests # ...and requests
- /opt/gitops:/opt/gitops:ro # reads the clones to show repo files
+1
View File
@@ -4,3 +4,4 @@ typer
rich
flask
gunicorn
cryptography