BlueGit

projects-timfalken-com verhalenboek

Merge branch 'cursor/bluegit-deploy-guard' into 'master'

timfa

Authored 2026-10-25 · 3 weeks ago

Hash
e5eec9fa2bbd6cccf0af5cea7437442eb781274e
Pipeline
Passed
7 files changed +244 −19
.gitlab-ci.yml +1 −14
@@ -1,6 +1,5 @@
1 1 stages:
2 2 - test
3 - deploy
4 3
5 4 php_tests:
6 5 stage: test
@@ -35,16 +34,4 @@ deploy_tests:
35 34 script:
36 35 - python3 ci/test_deploy.py
37 36
38 ftp_upload:
39 stage: deploy
40 image: debian:bookworm-slim
41 resource_group: production
42 environment:
43 name: production
44 rules:
45 - if: '$CI_COMMIT_BRANCH == "master"'
46 before_script:
47 - apt-get update -qq
48 - apt-get install -y --no-install-recommends python3 lftp ca-certificates openssh-client
49 script:
50 - python3 ci/deploy.py
37 # Deploy runs on BlueGit (blue-ci-cd.yml). GitLab is only a backup mirror and never deploys.
@@ -1,6 +1,5 @@
1stages:
1stages:
2 - test
2 - test
3 - deploy
4
3
5php_tests:
4php_tests:
6 stage: test
5 stage: test
@@ -35,16 +34,4 @@ deploy_tests:
35 script:
34 script:
36 - python3 ci/test_deploy.py
35 - python3 ci/test_deploy.py
37
36
38ftp_upload:
37# Deploy runs on BlueGit (blue-ci-cd.yml). GitLab is only a backup mirror and never deploys.
39 stage: deploy
40 image: debian:bookworm-slim
41 resource_group: production
42 environment:
43 name: production
44 rules:
45 - if: '$CI_COMMIT_BRANCH == "master"'
46 before_script:
47 - apt-get update -qq
48 - apt-get install -y --no-install-recommends python3 lftp ca-certificates openssh-client
49 script:
50 - python3 ci/deploy.py
README.md +15 −2
@@ -123,9 +123,22 @@ curl -sS -D - -o - \
123 123
124 124 ## Deploy
125 125
126 `.gitlab-ci.yml` is die van microchess: PHP-syntax, domeintests, API-tests, een JavaScript-syntaxcheck, en een echte FTP-fixture. Alleen `master` uploadt, en nooit tegelijk met een andere productie-deploy. [`ci/deploy.py`](ci/deploy.py) spiegelt `web/` met lftp en slaat `data/` (database, WAL, `config.php`, sessies) over, zowel bij upload als bij verwijderen. `data/.htaccess` wordt apart gezet. `tests/`, `router.php` en `README.md` gaan niet mee.
126 De code staat op BlueGit: https://git.timfalken.com/projects-timfalken-com/verhalenboek (publiek). GitLab (`Timfa/Verhalenboek`) is alleen nog een backup en deployt niet meer.
127 127
128 Benodigde CI-variabelen, al aanwezig in dit project: `timftphost`, `timftpuser`, `timftppassword`, `timftproot`, `projectftp` (`$timftproot/verhaaltjesboek`).
128 [`blue-ci-cd.yml`](blue-ci-cd.yml) draait PHP-syntax, domeintests, API-tests, een JavaScript-syntaxcheck en een echte FTP-fixture. `ftp_upload` wacht via `needs` op alle drie testjobs: faalt er één, dan is er geen deploy. Alleen een push naar `master` uploadt (geen MR-pipelines), en nooit tegelijk met een andere productie-deploy. [`ci/deploy.py`](ci/deploy.py) spiegelt `web/` met lftp en slaat `data/` (database, WAL, `config.php`, sessies, API-sleutels) over, zowel bij upload als bij verwijderen. `data/.htaccess` wordt apart gezet. `tests/`, `router.php` en `README.md` gaan niet mee.
129
130 ### Geheimen
131
132 | Naam | Waar | Beschermd |
133 |---|---|---|
134 | `timftphost`, `timftpuser`, `timftppassword`, `timftproot` | groep `projects.timfalken.com` (gedeeld door alle projecten op die site) | ja |
135 | `projectftp` | deze repository (`$timftproot/verhaaltjesboek`) | ja |
136
137 Beschermde geheimen komen alleen mee op de beschermde branch `master`. MR-pipelines krijgen ze niet. Waarden van acht tekens of meer worden in joblogs vervangen door `[MASKED]`.
138
139 ### Deploy-guard
140
141 [`ci/deploy_guard.py`](ci/deploy_guard.py) laat de deploy hard falen (`DEPLOY GEBLOKKEERD: …`) als `projectftp` niet gezet of leeg is, naar `/` of `.` wijst, gelijk is aan `timftproot`, `..` bevat of buiten `timftproot` ligt. Zo kan een `mirror --delete` nooit de hele website overschrijven. `$timftproot` in `projectftp` wordt door de guard zelf ingevuld, want BlueGit-geheimen verwijzen niet naar elkaar. Zie [docs/deploy-guard.md](docs/deploy-guard.md) om de guard in een ander project te gebruiken.
129 142
130 143 ## Tests
131 144
@@ -123,9 +123,22 @@ curl -sS -D - -o - \
123
123
124## Deploy
124## Deploy
125
125
126`.gitlab-ci.yml` is die van microchess: PHP-syntax, domeintests, API-tests, een JavaScript-syntaxcheck, en een echte FTP-fixture. Alleen `master` uploadt, en nooit tegelijk met een andere productie-deploy. [`ci/deploy.py`](ci/deploy.py) spiegelt `web/` met lftp en slaat `data/` (database, WAL, `config.php`, sessies) over, zowel bij upload als bij verwijderen. `data/.htaccess` wordt apart gezet. `tests/`, `router.php` en `README.md` gaan niet mee.
126De code staat op BlueGit: https://git.timfalken.com/projects-timfalken-com/verhalenboek (publiek). GitLab (`Timfa/Verhalenboek`) is alleen nog een backup en deployt niet meer.
127
127
128Benodigde CI-variabelen, al aanwezig in dit project: `timftphost`, `timftpuser`, `timftppassword`, `timftproot`, `projectftp` (`$timftproot/verhaaltjesboek`).
128[`blue-ci-cd.yml`](blue-ci-cd.yml) draait PHP-syntax, domeintests, API-tests, een JavaScript-syntaxcheck en een echte FTP-fixture. `ftp_upload` wacht via `needs` op alle drie testjobs: faalt er één, dan is er geen deploy. Alleen een push naar `master` uploadt (geen MR-pipelines), en nooit tegelijk met een andere productie-deploy. [`ci/deploy.py`](ci/deploy.py) spiegelt `web/` met lftp en slaat `data/` (database, WAL, `config.php`, sessies, API-sleutels) over, zowel bij upload als bij verwijderen. `data/.htaccess` wordt apart gezet. `tests/`, `router.php` en `README.md` gaan niet mee.
129
130### Geheimen
131
132| Naam | Waar | Beschermd |
133|---|---|---|
134| `timftphost`, `timftpuser`, `timftppassword`, `timftproot` | groep `projects.timfalken.com` (gedeeld door alle projecten op die site) | ja |
135| `projectftp` | deze repository (`$timftproot/verhaaltjesboek`) | ja |
136
137Beschermde geheimen komen alleen mee op de beschermde branch `master`. MR-pipelines krijgen ze niet. Waarden van acht tekens of meer worden in joblogs vervangen door `[MASKED]`.
138
139### Deploy-guard
140
141[`ci/deploy_guard.py`](ci/deploy_guard.py) laat de deploy hard falen (`DEPLOY GEBLOKKEERD: …`) als `projectftp` niet gezet of leeg is, naar `/` of `.` wijst, gelijk is aan `timftproot`, `..` bevat of buiten `timftproot` ligt. Zo kan een `mirror --delete` nooit de hele website overschrijven. `$timftproot` in `projectftp` wordt door de guard zelf ingevuld, want BlueGit-geheimen verwijzen niet naar elkaar. Zie [docs/deploy-guard.md](docs/deploy-guard.md) om de guard in een ander project te gebruiken.
129
142
130## Tests
143## Tests
131
144
blue-ci-cd.yml added +54 −0
@@ -0,0 +1,54 @@
1 # BlueGit CI (git.timfalken.com). Secrets: timftp* from group projects.timfalken.com, projectftp from this repo (all protected: master only).
2 stages:
3 - test
4 - deploy
5
6 php_tests:
7 stage: test
8 image: php:8.3-cli-bookworm
9 before_script:
10 - apt-get update -qq
11 - apt-get install -y --no-install-recommends python3 libonig-dev
12 - docker-php-ext-install mbstring
13 script:
14 - find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
15 - php -r 'foreach (["pdo_sqlite", "curl", "mbstring", "openssl"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing extension " . $extension); exit(1); } }'
16 - php web/tests/storybook.php
17 - python3 web/tests/startup.py
18 - python3 web/tests/integration.py
19 - python3 web/tests/pwa.py
20
21 frontend_checks:
22 stage: test
23 image: node:22-bookworm-slim
24 script:
25 - node --check web/assets/app.js
26 - node --check web/assets/pwa.js
27 - node --check web/sw.js
28
29 # A real FTP fixture verifies that mirroring preserves production data and secrets.
30 deploy_tests:
31 stage: test
32 image: debian:bookworm-slim
33 before_script:
34 - apt-get update -qq
35 - apt-get install -y --no-install-recommends python3 python3-pyftpdlib lftp ca-certificates openssh-client
36 script:
37 - python3 ci/test_deploy.py
38
39 ftp_upload:
40 stage: deploy
41 image: debian:bookworm-slim
42 resource_group: production
43 environment:
44 name: production
45 # Deploy only after every test job passed; a failed test means no deploy.
46 needs: [php_tests, frontend_checks, deploy_tests]
47 rules:
48 - if: '$CI_COMMIT_BRANCH == "master" && $CI_PIPELINE_SOURCE != "merge_request_event"'
49 before_script:
50 - apt-get update -qq
51 - apt-get install -y --no-install-recommends python3 lftp ca-certificates openssh-client
52 script:
53 - python3 ci/deploy_guard.py
54 - python3 ci/deploy.py
@@ -0,0 +1,54 @@
1# BlueGit CI (git.timfalken.com). Secrets: timftp* from group projects.timfalken.com, projectftp from this repo (all protected: master only).
2stages:
3 - test
4 - deploy
5
6php_tests:
7 stage: test
8 image: php:8.3-cli-bookworm
9 before_script:
10 - apt-get update -qq
11 - apt-get install -y --no-install-recommends python3 libonig-dev
12 - docker-php-ext-install mbstring
13 script:
14 - find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
15 - php -r 'foreach (["pdo_sqlite", "curl", "mbstring", "openssl"] as $extension) { if (!extension_loaded($extension)) { fwrite(STDERR, "Missing extension " . $extension); exit(1); } }'
16 - php web/tests/storybook.php
17 - python3 web/tests/startup.py
18 - python3 web/tests/integration.py
19 - python3 web/tests/pwa.py
20
21frontend_checks:
22 stage: test
23 image: node:22-bookworm-slim
24 script:
25 - node --check web/assets/app.js
26 - node --check web/assets/pwa.js
27 - node --check web/sw.js
28
29# A real FTP fixture verifies that mirroring preserves production data and secrets.
30deploy_tests:
31 stage: test
32 image: debian:bookworm-slim
33 before_script:
34 - apt-get update -qq
35 - apt-get install -y --no-install-recommends python3 python3-pyftpdlib lftp ca-certificates openssh-client
36 script:
37 - python3 ci/test_deploy.py
38
39ftp_upload:
40 stage: deploy
41 image: debian:bookworm-slim
42 resource_group: production
43 environment:
44 name: production
45 # Deploy only after every test job passed; a failed test means no deploy.
46 needs: [php_tests, frontend_checks, deploy_tests]
47 rules:
48 - if: '$CI_COMMIT_BRANCH == "master" && $CI_PIPELINE_SOURCE != "merge_request_event"'
49 before_script:
50 - apt-get update -qq
51 - apt-get install -y --no-install-recommends python3 lftp ca-certificates openssh-client
52 script:
53 - python3 ci/deploy_guard.py
54 - python3 ci/deploy.py
ci/deploy.py +8 −3
@@ -6,6 +6,9 @@ import subprocess
6 6 import sys
7 7 from urllib.parse import urlsplit
8 8
9 sys.path.insert(0, str(Path(__file__).resolve().parent))
10 from deploy_guard import project_dir # noqa: E402
11
9 12 ROOT = Path(__file__).resolve().parents[1]
10 13
11 14 def quoted(value):
@@ -14,7 +17,9 @@ def quoted(value):
14 17 return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
15 18
16 19 def deployment_commands(environ, webroot):
17 for key in ['timftphost', 'timftpuser', 'timftppassword', 'projectftp']:
20 # Hard guard first: never mirror --delete into the site root.
21 target = project_dir(environ)
22 for key in ['timftphost', 'timftpuser', 'timftppassword']:
18 23 if not environ.get(key):
19 24 raise ValueError(f'CI variable {key} is not set.')
20 25 host = environ['timftphost']
@@ -37,8 +42,8 @@ def deployment_commands(environ, webroot):
37 42 'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',
38 43 f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}',
39 44 # First deploy: the project folder may not exist yet on the server.
40 f'mkdir -p {quoted(environ["projectftp"])} || echo "Using existing project directory"',
41 f'cd {quoted(environ["projectftp"])}',
45 f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
46 f'cd {quoted(target)}',
42 47 'mkdir -p data || echo "Using existing data directory"',
43 48 f'put {quoted(str(webroot / "data/.htaccess"))} -o data/.htaccess',
44 49 # No --delete-excluded: these paths belong to the running server.
@@ -6,6 +6,9 @@ import subprocess
6import sys
6import sys
7from urllib.parse import urlsplit
7from urllib.parse import urlsplit
8
8
9sys.path.insert(0, str(Path(__file__).resolve().parent))
10from deploy_guard import project_dir # noqa: E402
11
9ROOT = Path(__file__).resolve().parents[1]
12ROOT = Path(__file__).resolve().parents[1]
10
13
11def quoted(value):
14def quoted(value):
@@ -14,7 +17,9 @@ def quoted(value):
14 return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
17 return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
15
18
16def deployment_commands(environ, webroot):
19def deployment_commands(environ, webroot):
17 for key in ['timftphost', 'timftpuser', 'timftppassword', 'projectftp']:
20 # Hard guard first: never mirror --delete into the site root.
21 target = project_dir(environ)
22 for key in ['timftphost', 'timftpuser', 'timftppassword']:
18 if not environ.get(key):
23 if not environ.get(key):
19 raise ValueError(f'CI variable {key} is not set.')
24 raise ValueError(f'CI variable {key} is not set.')
20 host = environ['timftphost']
25 host = environ['timftphost']
@@ -37,8 +42,8 @@ def deployment_commands(environ, webroot):
37 'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',
42 'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',
38 f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}',
43 f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}',
39 # First deploy: the project folder may not exist yet on the server.
44 # First deploy: the project folder may not exist yet on the server.
40 f'mkdir -p {quoted(environ["projectftp"])} || echo "Using existing project directory"',
45 f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
41 f'cd {quoted(environ["projectftp"])}',
46 f'cd {quoted(target)}',
42 'mkdir -p data || echo "Using existing data directory"',
47 'mkdir -p data || echo "Using existing data directory"',
43 f'put {quoted(str(webroot / "data/.htaccess"))} -o data/.htaccess',
48 f'put {quoted(str(webroot / "data/.htaccess"))} -o data/.htaccess',
44 # No --delete-excluded: these paths belong to the running server.
49 # No --delete-excluded: these paths belong to the running server.
ci/deploy_guard.py added +83 −0
@@ -0,0 +1,83 @@
1 #!/usr/bin/env python3
2 """Deploy guard for projects.timfalken.com repositories.
3
4 Shared snippet: copy this file unchanged into ci/ of every repository that
5 deploys to projects.timfalken.com. It refuses any project directory that would
6 make a mirror --delete overwrite the whole site (or another project).
7
8 Usage in Python: from deploy_guard import project_dir; path = project_dir(os.environ)
9 Usage in a shell: python3 ci/deploy_guard.py (exit 1 with a clear message on failure)
10
11 Values are never printed; only variable names appear in messages.
12 """
13 import posixpath
14 import re
15 import sys
16
17 ROOT_VAR = 'timftproot'
18 PROJECT_VAR = 'projectftp'
19
20
21 class DeployGuardError(ValueError):
22 pass
23
24
25 def _expand(value, environ):
26 """Expand $timftproot / ${timftproot} (GitLab expanded these; BlueGit secrets do not)."""
27 root = environ.get(ROOT_VAR) or ''
28 return re.sub(r'\$\{?' + ROOT_VAR + r'\}?', lambda _m: root, value)
29
30
31 def _norm(path):
32 path = path.strip()
33 if not path:
34 return ''
35 norm = posixpath.normpath(path)
36 return '/' if norm in ('/', '//') else norm.rstrip('/') or '/'
37
38
39 def project_dir(environ):
40 raw = environ.get(PROJECT_VAR)
41 if raw is None:
42 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is niet gezet. '
43 f'Zet de projectmap als project-secret, bijvoorbeeld $timftproot/<project>.')
44 if any(c in raw for c in '\r\n\x00'):
45 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een regeleinde of NUL-byte.')
46 if '$' in raw.replace('$' + ROOT_VAR, '').replace('${' + ROOT_VAR + '}', ''):
47 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een onbekende $-verwijzing.')
48 if (('$' + ROOT_VAR) in raw or ('${' + ROOT_VAR + '}') in raw) and not (environ.get(ROOT_VAR) or '').strip():
49 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} verwijst naar {ROOT_VAR}, maar die is niet gezet.')
50 value = _expand(raw, environ).strip()
51 if not value:
52 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is leeg.')
53 parts = [p for p in value.replace('\\', '/').split('/') if p]
54 if '..' in parts:
55 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag geen ".." bevatten.')
56 if value.startswith('~'):
57 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag niet de thuismap (~) zijn.')
58 norm = _norm(value)
59 if norm in ('/', '.', ''):
60 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} wijst naar de root ("/" of "."); '
61 f'dat zou de hele website overschrijven.')
62 root = _norm(environ.get(ROOT_VAR) or '')
63 if root and norm == root:
64 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} is gelijk aan {ROOT_VAR} (de FTP-root van de site); '
65 f'dat zou de hele website overschrijven.')
66 if root and root not in ('/', '.') and norm.startswith('/') and not norm.startswith(root + '/'):
67 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} ligt niet onder {ROOT_VAR}.')
68 return norm
69
70
71 def main(environ=None):
72 import os
73 try:
74 project_dir(os.environ if environ is None else environ)
75 except DeployGuardError as error:
76 print(str(error), file=sys.stderr)
77 return 1
78 print('Deploy guard: projectmap ok.')
79 return 0
80
81
82 if __name__ == '__main__':
83 sys.exit(main())
@@ -0,0 +1,83 @@
1#!/usr/bin/env python3
2"""Deploy guard for projects.timfalken.com repositories.
3
4Shared snippet: copy this file unchanged into ci/ of every repository that
5deploys to projects.timfalken.com. It refuses any project directory that would
6make a mirror --delete overwrite the whole site (or another project).
7
8Usage in Python: from deploy_guard import project_dir; path = project_dir(os.environ)
9Usage in a shell: python3 ci/deploy_guard.py (exit 1 with a clear message on failure)
10
11Values are never printed; only variable names appear in messages.
12"""
13import posixpath
14import re
15import sys
16
17ROOT_VAR = 'timftproot'
18PROJECT_VAR = 'projectftp'
19
20
21class DeployGuardError(ValueError):
22 pass
23
24
25def _expand(value, environ):
26 """Expand $timftproot / ${timftproot} (GitLab expanded these; BlueGit secrets do not)."""
27 root = environ.get(ROOT_VAR) or ''
28 return re.sub(r'\$\{?' + ROOT_VAR + r'\}?', lambda _m: root, value)
29
30
31def _norm(path):
32 path = path.strip()
33 if not path:
34 return ''
35 norm = posixpath.normpath(path)
36 return '/' if norm in ('/', '//') else norm.rstrip('/') or '/'
37
38
39def project_dir(environ):
40 raw = environ.get(PROJECT_VAR)
41 if raw is None:
42 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is niet gezet. '
43 f'Zet de projectmap als project-secret, bijvoorbeeld $timftproot/<project>.')
44 if any(c in raw for c in '\r\n\x00'):
45 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een regeleinde of NUL-byte.')
46 if '$' in raw.replace('$' + ROOT_VAR, '').replace('${' + ROOT_VAR + '}', ''):
47 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een onbekende $-verwijzing.')
48 if (('$' + ROOT_VAR) in raw or ('${' + ROOT_VAR + '}') in raw) and not (environ.get(ROOT_VAR) or '').strip():
49 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} verwijst naar {ROOT_VAR}, maar die is niet gezet.')
50 value = _expand(raw, environ).strip()
51 if not value:
52 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is leeg.')
53 parts = [p for p in value.replace('\\', '/').split('/') if p]
54 if '..' in parts:
55 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag geen ".." bevatten.')
56 if value.startswith('~'):
57 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag niet de thuismap (~) zijn.')
58 norm = _norm(value)
59 if norm in ('/', '.', ''):
60 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} wijst naar de root ("/" of "."); '
61 f'dat zou de hele website overschrijven.')
62 root = _norm(environ.get(ROOT_VAR) or '')
63 if root and norm == root:
64 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} is gelijk aan {ROOT_VAR} (de FTP-root van de site); '
65 f'dat zou de hele website overschrijven.')
66 if root and root not in ('/', '.') and norm.startswith('/') and not norm.startswith(root + '/'):
67 raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} ligt niet onder {ROOT_VAR}.')
68 return norm
69
70
71def main(environ=None):
72 import os
73 try:
74 project_dir(os.environ if environ is None else environ)
75 except DeployGuardError as error:
76 print(str(error), file=sys.stderr)
77 return 1
78 print('Deploy guard: projectmap ok.')
79 return 0
80
81
82if __name__ == '__main__':
83 sys.exit(main())
ci/test_deploy.py +38 −0
@@ -15,6 +15,7 @@ from pyftpdlib.authorizers import DummyAuthorizer
15 15 from pyftpdlib.handlers import FTPHandler
16 16 from pyftpdlib.servers import FTPServer
17 17 from deploy import ROOT, deployment_commands, write_asset_version
18 from deploy_guard import DeployGuardError, project_dir, main as guard_main
18 19
19 20 class DeployTests(unittest.TestCase):
20 21 def test_mirror_preserves_data(self):
@@ -76,5 +77,42 @@ class DeployTests(unittest.TestCase):
76 77 env={'timftphost':'ftp://example.test','timftpuser':'user','timftppassword':'secret','projectftp':'x\nrm -r data'}
77 78 with self.assertRaises(ValueError):deployment_commands(env,ROOT/'web')
78 79
80 class DeployGuardTests(unittest.TestCase):
81 BASE={'timftphost':'ftp://example.test','timftpuser':'user','timftppassword':'secret','timftproot':'/domains/projects.timfalken.com/public_html'}
82
83 def blocked(self, **extra):
84 env=dict(self.BASE); env.update(extra)
85 env={k:v for k,v in env.items() if v is not None}
86 with self.assertRaises(DeployGuardError):project_dir(env)
87 with self.assertRaises(ValueError):deployment_commands(env,ROOT/'web')
88
89 def test_not_set(self):self.blocked(projectftp=None)
90 def test_empty(self):self.blocked(projectftp='')
91 def test_whitespace(self):self.blocked(projectftp=' ')
92 def test_slash(self):self.blocked(projectftp='/')
93 def test_dot(self):self.blocked(projectftp='.')
94 def test_dot_slash(self):self.blocked(projectftp='./')
95 def test_root_literal(self):self.blocked(projectftp='/domains/projects.timfalken.com/public_html/')
96 def test_root_reference(self):self.blocked(projectftp='$timftproot')
97 def test_root_reference_slash(self):self.blocked(projectftp='${timftproot}/')
98 def test_root_reference_without_root(self):self.blocked(projectftp='$timftproot/verhaaltjesboek',timftproot=None)
99 def test_parent(self):self.blocked(projectftp='$timftproot/verhaaltjesboek/..')
100 def test_outside_root(self):self.blocked(projectftp='/domains/other.site/public_html/x')
101 def test_unknown_reference(self):self.blocked(projectftp='$HOME/x')
102
103 def test_valid(self):
104 env=dict(self.BASE,projectftp='$timftproot/verhaaltjesboek')
105 self.assertEqual(project_dir(env),'/domains/projects.timfalken.com/public_html/verhaaltjesboek')
106 self.assertIn('cd "/domains/projects.timfalken.com/public_html/verhaaltjesboek"',deployment_commands(env,ROOT/'web'))
107 self.assertEqual(project_dir(dict(self.BASE,projectftp='verhaaltjesboek')),'verhaaltjesboek')
108 self.assertEqual(project_dir(dict(self.BASE,timftproot='/r/',projectftp='$timftproot/vb/')),'/r/vb')
109
110 def test_cli_exit_code_and_no_values(self):
111 import io,contextlib
112 err=io.StringIO()
113 with contextlib.redirect_stderr(err):self.assertEqual(guard_main(dict(self.BASE,projectftp='/')),1)
114 self.assertIn('DEPLOY GEBLOKKEERD',err.getvalue())
115 self.assertNotIn(self.BASE['timftproot'],err.getvalue())
116
79 117 if __name__=='__main__':
80 118 unittest.main()
@@ -15,6 +15,7 @@ from pyftpdlib.authorizers import DummyAuthorizer
15from pyftpdlib.handlers import FTPHandler
15from pyftpdlib.handlers import FTPHandler
16from pyftpdlib.servers import FTPServer
16from pyftpdlib.servers import FTPServer
17from deploy import ROOT, deployment_commands, write_asset_version
17from deploy import ROOT, deployment_commands, write_asset_version
18from deploy_guard import DeployGuardError, project_dir, main as guard_main
18
19
19class DeployTests(unittest.TestCase):
20class DeployTests(unittest.TestCase):
20 def test_mirror_preserves_data(self):
21 def test_mirror_preserves_data(self):
@@ -76,5 +77,42 @@ class DeployTests(unittest.TestCase):
76 env={'timftphost':'ftp://example.test','timftpuser':'user','timftppassword':'secret','projectftp':'x\nrm -r data'}
77 env={'timftphost':'ftp://example.test','timftpuser':'user','timftppassword':'secret','projectftp':'x\nrm -r data'}
77 with self.assertRaises(ValueError):deployment_commands(env,ROOT/'web')
78 with self.assertRaises(ValueError):deployment_commands(env,ROOT/'web')
78
79
80class DeployGuardTests(unittest.TestCase):
81 BASE={'timftphost':'ftp://example.test','timftpuser':'user','timftppassword':'secret','timftproot':'/domains/projects.timfalken.com/public_html'}
82
83 def blocked(self, **extra):
84 env=dict(self.BASE); env.update(extra)
85 env={k:v for k,v in env.items() if v is not None}
86 with self.assertRaises(DeployGuardError):project_dir(env)
87 with self.assertRaises(ValueError):deployment_commands(env,ROOT/'web')
88
89 def test_not_set(self):self.blocked(projectftp=None)
90 def test_empty(self):self.blocked(projectftp='')
91 def test_whitespace(self):self.blocked(projectftp=' ')
92 def test_slash(self):self.blocked(projectftp='/')
93 def test_dot(self):self.blocked(projectftp='.')
94 def test_dot_slash(self):self.blocked(projectftp='./')
95 def test_root_literal(self):self.blocked(projectftp='/domains/projects.timfalken.com/public_html/')
96 def test_root_reference(self):self.blocked(projectftp='$timftproot')
97 def test_root_reference_slash(self):self.blocked(projectftp='${timftproot}/')
98 def test_root_reference_without_root(self):self.blocked(projectftp='$timftproot/verhaaltjesboek',timftproot=None)
99 def test_parent(self):self.blocked(projectftp='$timftproot/verhaaltjesboek/..')
100 def test_outside_root(self):self.blocked(projectftp='/domains/other.site/public_html/x')
101 def test_unknown_reference(self):self.blocked(projectftp='$HOME/x')
102
103 def test_valid(self):
104 env=dict(self.BASE,projectftp='$timftproot/verhaaltjesboek')
105 self.assertEqual(project_dir(env),'/domains/projects.timfalken.com/public_html/verhaaltjesboek')
106 self.assertIn('cd "/domains/projects.timfalken.com/public_html/verhaaltjesboek"',deployment_commands(env,ROOT/'web'))
107 self.assertEqual(project_dir(dict(self.BASE,projectftp='verhaaltjesboek')),'verhaaltjesboek')
108 self.assertEqual(project_dir(dict(self.BASE,timftproot='/r/',projectftp='$timftproot/vb/')),'/r/vb')
109
110 def test_cli_exit_code_and_no_values(self):
111 import io,contextlib
112 err=io.StringIO()
113 with contextlib.redirect_stderr(err):self.assertEqual(guard_main(dict(self.BASE,projectftp='/')),1)
114 self.assertIn('DEPLOY GEBLOKKEERD',err.getvalue())
115 self.assertNotIn(self.BASE['timftproot'],err.getvalue())
116
79if __name__=='__main__':
117if __name__=='__main__':
80 unittest.main()
118 unittest.main()
docs/deploy-guard.md added +45 −0
@@ -0,0 +1,45 @@
1 # Deploy-guard voor projects.timfalken.com
2
3 Elke repository die naar `projects.timfalken.com` deployt staat in de BlueGit-groep `projects.timfalken.com` (pad `projects-timfalken-com`). De groep levert de gedeelde, beschermde geheimen `timftphost`, `timftpuser`, `timftppassword` en `timftproot`. Elk project zet zelf alleen `projectftp`, bijvoorbeeld `$timftproot/<project>`, ook beschermd.
4
5 Een deploy met een ontbrekende of verkeerde `projectftp` zou met `mirror --delete` de hele site kunnen wissen. Daarom draait elk project de guard vóór de upload.
6
7 ## Gebruik
8
9 1. Kopieer [`ci/deploy_guard.py`](../ci/deploy_guard.py) ongewijzigd naar `ci/` van het project (alleen de Python-standaardbibliotheek).
10 2. Zet in de deploy-job een eigen stap vóór de upload:
11
12 ```yaml
13 ftp_upload:
14 stage: deploy
15 needs: [<alle testjobs>]
16 rules:
17 - if: '$CI_COMMIT_BRANCH == "master" && $CI_PIPELINE_SOURCE != "merge_request_event"'
18 script:
19 - python3 ci/deploy_guard.py
20 - python3 ci/deploy.py
21 ```
22
23 3. Gebruik in een Python-deployscript de gecontroleerde map in plaats van `projectftp` zelf:
24
25 ```python
26 from deploy_guard import project_dir
27 target = project_dir(os.environ) # gooit DeployGuardError (ValueError)
28 ```
29
30 Een shellscript doet `python3 ci/deploy_guard.py || exit 1` en gebruikt daarna de map.
31
32 ## Wat de guard weigert
33
34 | `projectftp` | Uitkomst |
35 |---|---|
36 | niet gezet | geblokkeerd |
37 | leeg of alleen spaties | geblokkeerd |
38 | `/`, `.`, `./` | geblokkeerd |
39 | gelijk aan `timftproot` (ook `$timftproot`, met of zonder `/`) | geblokkeerd |
40 | bevat `..`, begint met `~`, of een andere `$`-verwijzing | geblokkeerd |
41 | absoluut pad buiten `timftproot` | geblokkeerd |
42 | `$timftproot` zonder dat `timftproot` gezet is | geblokkeerd |
43 | `$timftproot/<project>` of een relatieve submap | toegestaan |
44
45 Meldingen noemen alleen namen van variabelen, nooit waarden. De tests staan in `ci/test_deploy.py` (`DeployGuardTests`).
@@ -0,0 +1,45 @@
1# Deploy-guard voor projects.timfalken.com
2
3Elke repository die naar `projects.timfalken.com` deployt staat in de BlueGit-groep `projects.timfalken.com` (pad `projects-timfalken-com`). De groep levert de gedeelde, beschermde geheimen `timftphost`, `timftpuser`, `timftppassword` en `timftproot`. Elk project zet zelf alleen `projectftp`, bijvoorbeeld `$timftproot/<project>`, ook beschermd.
4
5Een deploy met een ontbrekende of verkeerde `projectftp` zou met `mirror --delete` de hele site kunnen wissen. Daarom draait elk project de guard vóór de upload.
6
7## Gebruik
8
91. Kopieer [`ci/deploy_guard.py`](../ci/deploy_guard.py) ongewijzigd naar `ci/` van het project (alleen de Python-standaardbibliotheek).
102. Zet in de deploy-job een eigen stap vóór de upload:
11
12 ```yaml
13 ftp_upload:
14 stage: deploy
15 needs: [<alle testjobs>]
16 rules:
17 - if: '$CI_COMMIT_BRANCH == "master" && $CI_PIPELINE_SOURCE != "merge_request_event"'
18 script:
19 - python3 ci/deploy_guard.py
20 - python3 ci/deploy.py
21 ```
22
233. Gebruik in een Python-deployscript de gecontroleerde map in plaats van `projectftp` zelf:
24
25 ```python
26 from deploy_guard import project_dir
27 target = project_dir(os.environ) # gooit DeployGuardError (ValueError)
28 ```
29
30 Een shellscript doet `python3 ci/deploy_guard.py || exit 1` en gebruikt daarna de map.
31
32## Wat de guard weigert
33
34| `projectftp` | Uitkomst |
35|---|---|
36| niet gezet | geblokkeerd |
37| leeg of alleen spaties | geblokkeerd |
38| `/`, `.`, `./` | geblokkeerd |
39| gelijk aan `timftproot` (ook `$timftproot`, met of zonder `/`) | geblokkeerd |
40| bevat `..`, begint met `~`, of een andere `$`-verwijzing | geblokkeerd |
41| absoluut pad buiten `timftproot` | geblokkeerd |
42| `$timftproot` zonder dat `timftproot` gezet is | geblokkeerd |
43| `$timftproot/<project>` of een relatieve submap | toegestaan |
44
45Meldingen noemen alleen namen van variabelen, nooit waarden. De tests staan in `ci/test_deploy.py` (`DeployGuardTests`).