BlueGit

projects-timfalken-com meteors

Merge branch 'feature/oauth-config-from-ci'

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
47ef73d71fc6d4d87b490655e2f8d675feb73d6f
Pipeline
Passed
6 files changed +264 −35
README.md +17 −20
@@ -73,7 +73,7 @@ Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToC
73 73
74 74 BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.
75 75
76 Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project).
76 Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project), en `auth_client_secret` (dit project, zie hieronder). De groep en de andere projecten (verhalenboek, microchess) hebben geen auth-geheim; alleen FTP-gegevens.
77 77
78 78 ## Online spelen (stage 2)
79 79
@@ -93,10 +93,12 @@ op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschou
93 93 en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
94 94 op het podium en daarna ga je terug naar de lobby.
95 95
96 ### Wat Tim op de server moet instellen
96 ### Wat Tim moet instellen
97 97
98 98 Online werkt pas als OAuth is ingesteld. Zolang dat niet zo is, blijft solo
99 beschikbaar en toont **Online spelen** een duidelijke boodschap.
99 beschikbaar en toont **Online spelen** een duidelijke boodschap. Je hoeft
100 `data/config.php` **niet** via FTP te zetten: de deploy schrijft dat bestand
101 zelf vanuit een CI-geheim.
100 102
101 103 1. Ga naar https://auth.timfalken.com/admin, bij de **bestaande** client
102 104 `projects.timfalken.com` (dezelfde als de andere sites op dit domein).
@@ -104,23 +106,18 @@ beschikbaar en toont **Online spelen** een duidelijke boodschap.
104 106 `https://projects.timfalken.com/meteors/callback.php`.
105 107 3. Kopieer het **bestaande** client-geheim. **Genereer het niet opnieuw** —
106 108 dat breekt de andere sites die dit geheim al gebruiken.
107 4. Zet op de FTP-server, in de map `data/` naast het spel (niet in git, wordt
108 nooit gedeployed), een bestand `config.php`:
109
110 ```php
111 <?php
112 return [
113 'auth_url' => 'https://auth.timfalken.com',
114 'base_url' => 'https://projects.timfalken.com/meteors',
115 'client_id' => 'projects.timfalken.com',
116 'client_secret' => 'HIER_HET_BESTAANDE_GEHEIM',
117 ];
118 ```
119
120 De eerste keer dat de PHP-API draait, maakt ze een sjabloon van dit bestand
121 als het nog niet bestaat. `data/.htaccess` weigert alle toegang tot die map.
122 De deploy raakt `data/config.php` en de SQLite-database nooit aan, en
123 overschrijft `favicon.ico` niet.
109 4. Zet in BlueGit, bij dit project (`projects-timfalken-com/meteors`), een
110 **protected** (alleen `master`) geheim met de naam **`auth_client_secret`**
111 en als waarde dat bestaande geheim. Er is geen groepsgeheim voor dit:
112 de groep en verhalenboek hebben alleen FTP-credentials. Optioneel is
113 `auth_client_id` (standaard `projects.timfalken.com`); dat hoeft Tim
114 niet te zetten.
115 5. De volgende deploy naar `master` schrijft `data/config.php` op de server
116 (alleen als het geheim niet leeg is; de waarde komt nooit in de logs).
117 Zonder geheim blijft een bestaand `data/config.php` ongemoeid. De
118 SQLite-database en sessies worden nooit gewist. `data/.htaccess`
119 weigert alle HTTP-toegang tot die map. `favicon.ico` wordt niet
120 overschreven.
124 121
125 122 Lokaal (alleen op loopback, host én remote-adres) kun je zonder geheim
126 123 inloggen als `auth.php?test=1` of `auth.php?test=2`.
@@ -73,7 +73,7 @@ Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToC
73
73
74BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.
74BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.
75
75
76Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project).
76Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project), en `auth_client_secret` (dit project, zie hieronder). De groep en de andere projecten (verhalenboek, microchess) hebben geen auth-geheim; alleen FTP-gegevens.
77
77
78## Online spelen (stage 2)
78## Online spelen (stage 2)
79
79
@@ -93,10 +93,12 @@ op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschou
93en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
93en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
94op het podium en daarna ga je terug naar de lobby.
94op het podium en daarna ga je terug naar de lobby.
95
95
96### Wat Tim op de server moet instellen
96### Wat Tim moet instellen
97
97
98Online werkt pas als OAuth is ingesteld. Zolang dat niet zo is, blijft solo
98Online werkt pas als OAuth is ingesteld. Zolang dat niet zo is, blijft solo
99beschikbaar en toont **Online spelen** een duidelijke boodschap.
99beschikbaar en toont **Online spelen** een duidelijke boodschap. Je hoeft
100`data/config.php` **niet** via FTP te zetten: de deploy schrijft dat bestand
101zelf vanuit een CI-geheim.
100
102
1011. Ga naar https://auth.timfalken.com/admin, bij de **bestaande** client
1031. Ga naar https://auth.timfalken.com/admin, bij de **bestaande** client
102 `projects.timfalken.com` (dezelfde als de andere sites op dit domein).
104 `projects.timfalken.com` (dezelfde als de andere sites op dit domein).
@@ -104,23 +106,18 @@ beschikbaar en toont **Online spelen** een duidelijke boodschap.
104 `https://projects.timfalken.com/meteors/callback.php`.
106 `https://projects.timfalken.com/meteors/callback.php`.
1053. Kopieer het **bestaande** client-geheim. **Genereer het niet opnieuw** —
1073. Kopieer het **bestaande** client-geheim. **Genereer het niet opnieuw** —
106 dat breekt de andere sites die dit geheim al gebruiken.
108 dat breekt de andere sites die dit geheim al gebruiken.
1074. Zet op de FTP-server, in de map `data/` naast het spel (niet in git, wordt
1094. Zet in BlueGit, bij dit project (`projects-timfalken-com/meteors`), een
108 nooit gedeployed), een bestand `config.php`:
110 **protected** (alleen `master`) geheim met de naam **`auth_client_secret`**
109
111 en als waarde dat bestaande geheim. Er is geen groepsgeheim voor dit:
110```php
112 de groep en verhalenboek hebben alleen FTP-credentials. Optioneel is
111<?php
113 `auth_client_id` (standaard `projects.timfalken.com`); dat hoeft Tim
112return [
114 niet te zetten.
113 'auth_url' => 'https://auth.timfalken.com',
1155. De volgende deploy naar `master` schrijft `data/config.php` op de server
114 'base_url' => 'https://projects.timfalken.com/meteors',
116 (alleen als het geheim niet leeg is; de waarde komt nooit in de logs).
115 'client_id' => 'projects.timfalken.com',
117 Zonder geheim blijft een bestaand `data/config.php` ongemoeid. De
116 'client_secret' => 'HIER_HET_BESTAANDE_GEHEIM',
118 SQLite-database en sessies worden nooit gewist. `data/.htaccess`
117];
119 weigert alle HTTP-toegang tot die map. `favicon.ico` wordt niet
118```
120 overschreven.
119
120De eerste keer dat de PHP-API draait, maakt ze een sjabloon van dit bestand
121als het nog niet bestaat. `data/.htaccess` weigert alle toegang tot die map.
122De deploy raakt `data/config.php` en de SQLite-database nooit aan, en
123overschrijft `favicon.ico` niet.
124
121
125Lokaal (alleen op loopback, host én remote-adres) kun je zonder geheim
122Lokaal (alleen op loopback, host én remote-adres) kun je zonder geheim
126inloggen als `auth.php?test=1` of `auth.php?test=2`.
123inloggen als `auth.php?test=1` of `auth.php?test=2`.
blue-ci-cd.yml +11 −3
@@ -1,9 +1,16 @@
1 1 # BlueGit CI for Meteors: unit tests, build of build/, FTP deploy of build/.
2 2 # Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).
3 # Repo secret: projectftp (protected; Tim set this to $timftproot/meteors).
3 # The group (and verhalenboek / microchess) has no auth.timfalken.com secret.
4 # Repo secrets (protected, master only):
5 # projectftp — Tim set this to $timftproot/meteors.
6 # auth_client_secret — existing auth.timfalken.com client secret for
7 # client_id projects.timfalken.com. If non-empty, deploy writes
8 # data/config.php (never logged). If empty/unset, an existing file
9 # is left alone. Optional: auth_client_id (defaults to that client_id).
4 10 # GEEN mirror --delete: live files mogen niet verdwijnen.
5 # Deployt map build/ (NIET de repo-root). data/ (config, sqlite) wordt
6 # niet geüpload; alleen data/.htaccess wordt naderhand gezet.
11 # Deployt map build/ (NIET de repo-root). data/ (sqlite, sessies) wordt
12 # niet gespiegeld; data/.htaccess wordt naderhand gezet, en config.php
13 # alleen vanuit het CI-geheim.
7 14 # favicon.ico wordt nooit geüpload.
8 15 stages: [test, build, deploy]
9 16
@@ -21,6 +28,7 @@ unit_tests:
21 28 script:
22 29 - apt-get update -qq && apt-get install -y -qq php-cli php-sqlite3 php-curl php-mbstring >/dev/null
23 30 - node --test test/*.test.js
31 - python3 ci/test_deploy_auth.py
24 32 - php server/tests/run.php
25 33
26 34 build_game:
@@ -1,9 +1,16 @@
1# BlueGit CI for Meteors: unit tests, build of build/, FTP deploy of build/.
1# BlueGit CI for Meteors: unit tests, build of build/, FTP deploy of build/.
2# Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).
2# Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).
3# Repo secret: projectftp (protected; Tim set this to $timftproot/meteors).
3# The group (and verhalenboek / microchess) has no auth.timfalken.com secret.
4# Repo secrets (protected, master only):
5# projectftp — Tim set this to $timftproot/meteors.
6# auth_client_secret — existing auth.timfalken.com client secret for
7# client_id projects.timfalken.com. If non-empty, deploy writes
8# data/config.php (never logged). If empty/unset, an existing file
9# is left alone. Optional: auth_client_id (defaults to that client_id).
4# GEEN mirror --delete: live files mogen niet verdwijnen.
10# GEEN mirror --delete: live files mogen niet verdwijnen.
5# Deployt map build/ (NIET de repo-root). data/ (config, sqlite) wordt
11# Deployt map build/ (NIET de repo-root). data/ (sqlite, sessies) wordt
6# niet geüpload; alleen data/.htaccess wordt naderhand gezet.
12# niet gespiegeld; data/.htaccess wordt naderhand gezet, en config.php
13# alleen vanuit het CI-geheim.
7# favicon.ico wordt nooit geüpload.
14# favicon.ico wordt nooit geüpload.
8stages: [test, build, deploy]
15stages: [test, build, deploy]
9
16
@@ -21,6 +28,7 @@ unit_tests:
21 script:
28 script:
22 - apt-get update -qq && apt-get install -y -qq php-cli php-sqlite3 php-curl php-mbstring >/dev/null
29 - apt-get update -qq && apt-get install -y -qq php-cli php-sqlite3 php-curl php-mbstring >/dev/null
23 - node --test test/*.test.js
30 - node --test test/*.test.js
31 - python3 ci/test_deploy_auth.py
24 - php server/tests/run.php
32 - php server/tests/run.php
25
33
26build_game:
34build_game:
ci/deploy.py +91 −7
@@ -9,6 +9,7 @@ Tim-provided icon is not overwritten.
9 9 import os
10 10 import subprocess
11 11 import sys
12 import tempfile
12 13 from pathlib import Path
13 14 from urllib.parse import urlsplit
14 15
@@ -29,6 +30,16 @@ OURS = {
29 30 # Never upload this name: the remote icon may belong to Tim or the host.
30 31 LEAVE_ON_REMOTE = ('favicon.ico',)
31 32
33 # OAuth file written from CI secrets. Names match BlueGit project secrets.
34 # The group and sibling repos (verhalenboek, microchess, …) have no
35 # auth.timfalken.com client secret — only FTP credentials — so this is a
36 # meteors project secret. client_id is public and optional to override.
37 AUTH_SECRET_ENV = 'auth_client_secret'
38 AUTH_CLIENT_ID_ENV = 'auth_client_id'
39 DEFAULT_AUTH_URL = 'https://auth.timfalken.com'
40 DEFAULT_BASE_URL = 'https://projects.timfalken.com/meteors'
41 DEFAULT_CLIENT_ID = 'projects.timfalken.com'
42
32 43
33 44 def quoted(value):
34 45 if any(c in value for c in '\r\n\x00'):
@@ -36,6 +47,46 @@ def quoted(value):
36 47 return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
37 48
38 49
50 def php_single_quoted(value):
51 """A PHP single-quoted string. Raises if the value has a NUL or newline."""
52 if any(c in value for c in '\r\n\x00'):
53 raise ValueError('auth config values must not contain line breaks or NUL bytes.')
54 return "'" + value.replace('\\', '\\\\').replace("'", "\\'") + "'"
55
56
57 def auth_secret(environ):
58 """Return the stripped secret, or '' if unset/empty. Never print this."""
59 raw = environ.get(AUTH_SECRET_ENV)
60 if raw is None:
61 return ''
62 return str(raw).strip()
63
64
65 def auth_config_php(environ):
66 """PHP source for data/config.php, or None if the secret is empty.
67
68 The secret itself is only placed inside a single-quoted PHP string.
69 Callers must not log the return value.
70 """
71 secret = auth_secret(environ)
72 if not secret:
73 return None
74 client_id = (environ.get(AUTH_CLIENT_ID_ENV) or '').strip() or DEFAULT_CLIENT_ID
75 auth_url = DEFAULT_AUTH_URL
76 base_url = DEFAULT_BASE_URL
77 # Built as a list so the secret is only interpolated via php_single_quoted.
78 return (
79 '<?php\n'
80 '// Written by CI from the auth_client_secret project secret. Not in git.\n'
81 'return [\n'
82 f" 'auth_url' => {php_single_quoted(auth_url)},\n"
83 f" 'base_url' => {php_single_quoted(base_url)},\n"
84 f" 'client_id' => {php_single_quoted(client_id)},\n"
85 f" 'client_secret' => {php_single_quoted(secret)},\n"
86 '];\n'
87 )
88
89
39 90 def host_url(environ):
40 91 for key in ['timftphost', 'timftpuser', 'timftppassword']:
41 92 if not environ.get(key):
@@ -144,14 +195,16 @@ def assert_safe_target(exists, names):
144 195 print('Remote meteors folder is empty; deploying.')
145 196
146 197
147 def deploy_commands(environ, target, webroot):
198 def deploy_commands(environ, target, webroot, auth_config_path=None):
148 199 host = host_url(environ)
149 return lftp_preamble(environ, host) + [
200 commands = lftp_preamble(environ, host) + [
150 201 f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
151 202 f'cd {quoted(target)}',
152 203 # GEEN --delete. Never upload favicon.ico (leave Tim's / the host's).
153 # Never mirror data/: that folder holds Tim's config.php and the
154 # sqlite database. We only ensure data/.htaccess afterwards.
204 # Never mirror data/: that folder holds the sqlite database and
205 # sessions. We only ensure data/.htaccess afterwards, and optionally
206 # write data/config.php from auth_client_secret (never from the
207 # build tree, which must not contain a secret).
155 208 'mirror --reverse --no-perms --no-symlinks --max-errors=1 '
156 209 '--exclude-glob ".git/" --exclude-glob ".git/**" '
157 210 '--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '
@@ -160,11 +213,17 @@ def deploy_commands(environ, target, webroot):
160 213 '--exclude-glob "data/" --exclude-glob "data/**" '
161 214 '--exclude-glob "**/config.php" --exclude-glob "**/*.sqlite" '
162 215 f'{quoted(str(webroot))} .',
163 # Ensure the deny-all htaccess exists; do not touch any other data file.
216 # Ensure the deny-all htaccess exists; do not delete any data file.
164 217 'mkdir -p data || echo "data exists"',
165 218 f'put {quoted(str(webroot / "data" / ".htaccess"))} -o data/.htaccess',
166 'bye',
167 219 ]
220 if auth_config_path:
221 # The lftp script only has the local path, never the secret.
222 commands.append(
223 f'put {quoted(str(auth_config_path))} -o data/config.php'
224 )
225 commands.append('bye')
226 return commands
168 227
169 228
170 229 def main():
@@ -178,7 +237,32 @@ def main():
178 237 raise ValueError('build/ is incomplete (need framework.js and images/).')
179 238 exists, names = list_remote(environ, target)
180 239 assert_safe_target(exists, names)
181 run_lftp(deploy_commands(environ, target, webroot), environ)
240 php = auth_config_php(environ)
241 auth_path = None
242 tmpdir = None
243 try:
244 if php is not None:
245 tmpdir = tempfile.TemporaryDirectory(prefix='meteors-auth-')
246 auth_path = Path(tmpdir.name) / 'config.php'
247 # 0o600: the secret lives in this file only until lftp puts it.
248 fd = os.open(auth_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
249 try:
250 os.write(fd, php.encode('utf-8'))
251 finally:
252 os.close(fd)
253 print('Writing data/config.php from CI secret auth_client_secret.')
254 else:
255 print(
256 'CI secret auth_client_secret is empty or unset; '
257 'leaving data/config.php alone.'
258 )
259 run_lftp(
260 deploy_commands(environ, target, webroot, auth_config_path=auth_path),
261 environ,
262 )
263 finally:
264 if tmpdir is not None:
265 tmpdir.cleanup()
182 266 print('Deploy complete (no --delete).')
183 267 return 0
184 268 except (ValueError, DeployGuardError, subprocess.CalledProcessError) as error:
@@ -9,6 +9,7 @@ Tim-provided icon is not overwritten.
9import os
9import os
10import subprocess
10import subprocess
11import sys
11import sys
12import tempfile
12from pathlib import Path
13from pathlib import Path
13from urllib.parse import urlsplit
14from urllib.parse import urlsplit
14
15
@@ -29,6 +30,16 @@ OURS = {
29# Never upload this name: the remote icon may belong to Tim or the host.
30# Never upload this name: the remote icon may belong to Tim or the host.
30LEAVE_ON_REMOTE = ('favicon.ico',)
31LEAVE_ON_REMOTE = ('favicon.ico',)
31
32
33# OAuth file written from CI secrets. Names match BlueGit project secrets.
34# The group and sibling repos (verhalenboek, microchess, …) have no
35# auth.timfalken.com client secret — only FTP credentials — so this is a
36# meteors project secret. client_id is public and optional to override.
37AUTH_SECRET_ENV = 'auth_client_secret'
38AUTH_CLIENT_ID_ENV = 'auth_client_id'
39DEFAULT_AUTH_URL = 'https://auth.timfalken.com'
40DEFAULT_BASE_URL = 'https://projects.timfalken.com/meteors'
41DEFAULT_CLIENT_ID = 'projects.timfalken.com'
42
32
43
33def quoted(value):
44def quoted(value):
34 if any(c in value for c in '\r\n\x00'):
45 if any(c in value for c in '\r\n\x00'):
@@ -36,6 +47,46 @@ def quoted(value):
36 return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
47 return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
37
48
38
49
50def php_single_quoted(value):
51 """A PHP single-quoted string. Raises if the value has a NUL or newline."""
52 if any(c in value for c in '\r\n\x00'):
53 raise ValueError('auth config values must not contain line breaks or NUL bytes.')
54 return "'" + value.replace('\\', '\\\\').replace("'", "\\'") + "'"
55
56
57def auth_secret(environ):
58 """Return the stripped secret, or '' if unset/empty. Never print this."""
59 raw = environ.get(AUTH_SECRET_ENV)
60 if raw is None:
61 return ''
62 return str(raw).strip()
63
64
65def auth_config_php(environ):
66 """PHP source for data/config.php, or None if the secret is empty.
67
68 The secret itself is only placed inside a single-quoted PHP string.
69 Callers must not log the return value.
70 """
71 secret = auth_secret(environ)
72 if not secret:
73 return None
74 client_id = (environ.get(AUTH_CLIENT_ID_ENV) or '').strip() or DEFAULT_CLIENT_ID
75 auth_url = DEFAULT_AUTH_URL
76 base_url = DEFAULT_BASE_URL
77 # Built as a list so the secret is only interpolated via php_single_quoted.
78 return (
79 '<?php\n'
80 '// Written by CI from the auth_client_secret project secret. Not in git.\n'
81 'return [\n'
82 f" 'auth_url' => {php_single_quoted(auth_url)},\n"
83 f" 'base_url' => {php_single_quoted(base_url)},\n"
84 f" 'client_id' => {php_single_quoted(client_id)},\n"
85 f" 'client_secret' => {php_single_quoted(secret)},\n"
86 '];\n'
87 )
88
89
39def host_url(environ):
90def host_url(environ):
40 for key in ['timftphost', 'timftpuser', 'timftppassword']:
91 for key in ['timftphost', 'timftpuser', 'timftppassword']:
41 if not environ.get(key):
92 if not environ.get(key):
@@ -144,14 +195,16 @@ def assert_safe_target(exists, names):
144 print('Remote meteors folder is empty; deploying.')
195 print('Remote meteors folder is empty; deploying.')
145
196
146
197
147def deploy_commands(environ, target, webroot):
198def deploy_commands(environ, target, webroot, auth_config_path=None):
148 host = host_url(environ)
199 host = host_url(environ)
149 return lftp_preamble(environ, host) + [
200 commands = lftp_preamble(environ, host) + [
150 f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
201 f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
151 f'cd {quoted(target)}',
202 f'cd {quoted(target)}',
152 # GEEN --delete. Never upload favicon.ico (leave Tim's / the host's).
203 # GEEN --delete. Never upload favicon.ico (leave Tim's / the host's).
153 # Never mirror data/: that folder holds Tim's config.php and the
204 # Never mirror data/: that folder holds the sqlite database and
154 # sqlite database. We only ensure data/.htaccess afterwards.
205 # sessions. We only ensure data/.htaccess afterwards, and optionally
206 # write data/config.php from auth_client_secret (never from the
207 # build tree, which must not contain a secret).
155 'mirror --reverse --no-perms --no-symlinks --max-errors=1 '
208 'mirror --reverse --no-perms --no-symlinks --max-errors=1 '
156 '--exclude-glob ".git/" --exclude-glob ".git/**" '
209 '--exclude-glob ".git/" --exclude-glob ".git/**" '
157 '--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '
210 '--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '
@@ -160,11 +213,17 @@ def deploy_commands(environ, target, webroot):
160 '--exclude-glob "data/" --exclude-glob "data/**" '
213 '--exclude-glob "data/" --exclude-glob "data/**" '
161 '--exclude-glob "**/config.php" --exclude-glob "**/*.sqlite" '
214 '--exclude-glob "**/config.php" --exclude-glob "**/*.sqlite" '
162 f'{quoted(str(webroot))} .',
215 f'{quoted(str(webroot))} .',
163 # Ensure the deny-all htaccess exists; do not touch any other data file.
216 # Ensure the deny-all htaccess exists; do not delete any data file.
164 'mkdir -p data || echo "data exists"',
217 'mkdir -p data || echo "data exists"',
165 f'put {quoted(str(webroot / "data" / ".htaccess"))} -o data/.htaccess',
218 f'put {quoted(str(webroot / "data" / ".htaccess"))} -o data/.htaccess',
166 'bye',
167 ]
219 ]
220 if auth_config_path:
221 # The lftp script only has the local path, never the secret.
222 commands.append(
223 f'put {quoted(str(auth_config_path))} -o data/config.php'
224 )
225 commands.append('bye')
226 return commands
168
227
169
228
170def main():
229def main():
@@ -178,7 +237,32 @@ def main():
178 raise ValueError('build/ is incomplete (need framework.js and images/).')
237 raise ValueError('build/ is incomplete (need framework.js and images/).')
179 exists, names = list_remote(environ, target)
238 exists, names = list_remote(environ, target)
180 assert_safe_target(exists, names)
239 assert_safe_target(exists, names)
181 run_lftp(deploy_commands(environ, target, webroot), environ)
240 php = auth_config_php(environ)
241 auth_path = None
242 tmpdir = None
243 try:
244 if php is not None:
245 tmpdir = tempfile.TemporaryDirectory(prefix='meteors-auth-')
246 auth_path = Path(tmpdir.name) / 'config.php'
247 # 0o600: the secret lives in this file only until lftp puts it.
248 fd = os.open(auth_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
249 try:
250 os.write(fd, php.encode('utf-8'))
251 finally:
252 os.close(fd)
253 print('Writing data/config.php from CI secret auth_client_secret.')
254 else:
255 print(
256 'CI secret auth_client_secret is empty or unset; '
257 'leaving data/config.php alone.'
258 )
259 run_lftp(
260 deploy_commands(environ, target, webroot, auth_config_path=auth_path),
261 environ,
262 )
263 finally:
264 if tmpdir is not None:
265 tmpdir.cleanup()
182 print('Deploy complete (no --delete).')
266 print('Deploy complete (no --delete).')
183 return 0
267 return 0
184 except (ValueError, DeployGuardError, subprocess.CalledProcessError) as error:
268 except (ValueError, DeployGuardError, subprocess.CalledProcessError) as error:
ci/test_deploy_auth.py added +120 −0
@@ -0,0 +1,120 @@
1 #!/usr/bin/env python3
2 """Tests for writing data/config.php from the auth_client_secret CI secret.
3
4 Fake secrets below are test fixtures only. The real secret is never used here.
5 This file prints only pass/fail text, never a generated config or a secret.
6 """
7 from __future__ import annotations
8
9 import os
10 import subprocess
11 import sys
12 import tempfile
13 from pathlib import Path
14
15 sys.path.insert(0, str(Path(__file__).resolve().parent))
16 from deploy import ( # noqa: E402
17 auth_config_php,
18 deploy_commands,
19 php_single_quoted,
20 )
21
22 FAKE = 'test-secret-value-NOT-FOR-PRODUCTION'
23 FAKE_QUOTED = "it's a \\secret with 'quotes'"
24 ENV = {
25 'timftphost': 'ftp://example.test',
26 'timftpuser': 'u',
27 'timftppassword': 'p',
28 }
29
30
31 def check(cond, msg):
32 if not cond:
33 raise SystemExit('FAIL: ' + msg)
34
35
36 def test_empty_secret():
37 check(auth_config_php({}) is None, 'unset → None')
38 check(auth_config_php({'auth_client_secret': ''}) is None, 'empty → None')
39 check(auth_config_php({'auth_client_secret': ' '}) is None, 'whitespace → None')
40
41
42 def test_php_quoting():
43 check(php_single_quoted('hello') == "'hello'", 'plain')
44 check(php_single_quoted("it's") == r"'it\'s'", 'quote')
45 check(php_single_quoted('a\\b') == r"'a\\b'", 'backslash')
46
47
48 def test_generated_php_evaluates():
49 php = auth_config_php({'auth_client_secret': FAKE_QUOTED, 'auth_client_id': ''})
50 check(php is not None, 'php generated')
51 check('projects.timfalken.com' in php, 'default client_id')
52 check('https://projects.timfalken.com/meteors' in php, 'base_url')
53 php2 = auth_config_php({
54 'auth_client_secret': FAKE,
55 'auth_client_id': 'other.example',
56 })
57 check('other.example' in php2, 'optional auth_client_id')
58
59 cfg = Path(tempfile.mkstemp(suffix='.php')[1])
60 wrp = Path(tempfile.mkstemp(suffix='.php')[1])
61 cfg.write_text(php)
62 # Wrapper prints only safe fields and a MATCH flag; never the secret.
63 wrp.write_text(
64 "<?php\n"
65 "$c = require $argv[1];\n"
66 "echo $c['client_id'], chr(10), $c['base_url'], chr(10), "
67 "strlen($c['client_secret']), chr(10), "
68 "($c['client_secret'] === $argv[2] ? 'MATCH' : 'MISMATCH'), chr(10);\n"
69 )
70 try:
71 result = subprocess.run(
72 ['php', str(wrp), str(cfg), FAKE_QUOTED],
73 capture_output=True,
74 text=True,
75 check=False,
76 )
77 finally:
78 cfg.unlink(missing_ok=True)
79 wrp.unlink(missing_ok=True)
80 if result.returncode != 0:
81 # Redact any accidental secret material before printing.
82 blob = (result.stdout + '\n' + result.stderr).replace(FAKE_QUOTED, '[FAKE]').replace(FAKE, '[FAKE]')
83 raise SystemExit('FAIL: php exit %s: %s' % (result.returncode, blob[:300]))
84 lines = result.stdout.strip().splitlines()
85 check(len(lines) >= 4, 'php output lines')
86 check(lines[0] == 'projects.timfalken.com', 'client_id eval')
87 check(lines[1] == 'https://projects.timfalken.com/meteors', 'base_url eval')
88 check(lines[3] == 'MATCH', 'secret round-trip')
89 check(FAKE_QUOTED not in result.stdout, 'php test stdout leaked secret')
90
91
92 def test_lftp_script_has_no_secret():
93 cmds = '\n'.join(deploy_commands(ENV, '/var/www/meteors', Path('build')))
94 check('--delete' not in cmds, 'no --delete')
95 check('--exclude-glob "**/config.php"' in cmds, 'mirror excludes config')
96 check('--exclude-glob "data/**"' in cmds, 'mirror excludes data')
97 check(' -o data/config.php' not in cmds, 'no put without secret path')
98 check('data/.htaccess' in cmds, 'htaccess still put')
99
100 path = '/tmp/meteors-auth-XXXX/config.php'
101 cmds2 = '\n'.join(
102 deploy_commands(ENV, '/var/www/meteors', Path('build'), auth_config_path=path)
103 )
104 check(' -o data/config.php' in cmds2, 'put when path given')
105 check(path in cmds2, 'local path in put')
106 check(FAKE not in cmds2 and FAKE_QUOTED not in cmds2, 'secret not in lftp script')
107 check('--delete' not in cmds2, 'no --delete with config put')
108
109
110 def main():
111 test_empty_secret()
112 test_php_quoting()
113 test_generated_php_evaluates()
114 test_lftp_script_has_no_secret()
115 print('auth-config ok')
116 return 0
117
118
119 if __name__ == '__main__':
120 sys.exit(main())
@@ -0,0 +1,120 @@
1#!/usr/bin/env python3
2"""Tests for writing data/config.php from the auth_client_secret CI secret.
3
4Fake secrets below are test fixtures only. The real secret is never used here.
5This file prints only pass/fail text, never a generated config or a secret.
6"""
7from __future__ import annotations
8
9import os
10import subprocess
11import sys
12import tempfile
13from pathlib import Path
14
15sys.path.insert(0, str(Path(__file__).resolve().parent))
16from deploy import ( # noqa: E402
17 auth_config_php,
18 deploy_commands,
19 php_single_quoted,
20)
21
22FAKE = 'test-secret-value-NOT-FOR-PRODUCTION'
23FAKE_QUOTED = "it's a \\secret with 'quotes'"
24ENV = {
25 'timftphost': 'ftp://example.test',
26 'timftpuser': 'u',
27 'timftppassword': 'p',
28}
29
30
31def check(cond, msg):
32 if not cond:
33 raise SystemExit('FAIL: ' + msg)
34
35
36def test_empty_secret():
37 check(auth_config_php({}) is None, 'unset → None')
38 check(auth_config_php({'auth_client_secret': ''}) is None, 'empty → None')
39 check(auth_config_php({'auth_client_secret': ' '}) is None, 'whitespace → None')
40
41
42def test_php_quoting():
43 check(php_single_quoted('hello') == "'hello'", 'plain')
44 check(php_single_quoted("it's") == r"'it\'s'", 'quote')
45 check(php_single_quoted('a\\b') == r"'a\\b'", 'backslash')
46
47
48def test_generated_php_evaluates():
49 php = auth_config_php({'auth_client_secret': FAKE_QUOTED, 'auth_client_id': ''})
50 check(php is not None, 'php generated')
51 check('projects.timfalken.com' in php, 'default client_id')
52 check('https://projects.timfalken.com/meteors' in php, 'base_url')
53 php2 = auth_config_php({
54 'auth_client_secret': FAKE,
55 'auth_client_id': 'other.example',
56 })
57 check('other.example' in php2, 'optional auth_client_id')
58
59 cfg = Path(tempfile.mkstemp(suffix='.php')[1])
60 wrp = Path(tempfile.mkstemp(suffix='.php')[1])
61 cfg.write_text(php)
62 # Wrapper prints only safe fields and a MATCH flag; never the secret.
63 wrp.write_text(
64 "<?php\n"
65 "$c = require $argv[1];\n"
66 "echo $c['client_id'], chr(10), $c['base_url'], chr(10), "
67 "strlen($c['client_secret']), chr(10), "
68 "($c['client_secret'] === $argv[2] ? 'MATCH' : 'MISMATCH'), chr(10);\n"
69 )
70 try:
71 result = subprocess.run(
72 ['php', str(wrp), str(cfg), FAKE_QUOTED],
73 capture_output=True,
74 text=True,
75 check=False,
76 )
77 finally:
78 cfg.unlink(missing_ok=True)
79 wrp.unlink(missing_ok=True)
80 if result.returncode != 0:
81 # Redact any accidental secret material before printing.
82 blob = (result.stdout + '\n' + result.stderr).replace(FAKE_QUOTED, '[FAKE]').replace(FAKE, '[FAKE]')
83 raise SystemExit('FAIL: php exit %s: %s' % (result.returncode, blob[:300]))
84 lines = result.stdout.strip().splitlines()
85 check(len(lines) >= 4, 'php output lines')
86 check(lines[0] == 'projects.timfalken.com', 'client_id eval')
87 check(lines[1] == 'https://projects.timfalken.com/meteors', 'base_url eval')
88 check(lines[3] == 'MATCH', 'secret round-trip')
89 check(FAKE_QUOTED not in result.stdout, 'php test stdout leaked secret')
90
91
92def test_lftp_script_has_no_secret():
93 cmds = '\n'.join(deploy_commands(ENV, '/var/www/meteors', Path('build')))
94 check('--delete' not in cmds, 'no --delete')
95 check('--exclude-glob "**/config.php"' in cmds, 'mirror excludes config')
96 check('--exclude-glob "data/**"' in cmds, 'mirror excludes data')
97 check(' -o data/config.php' not in cmds, 'no put without secret path')
98 check('data/.htaccess' in cmds, 'htaccess still put')
99
100 path = '/tmp/meteors-auth-XXXX/config.php'
101 cmds2 = '\n'.join(
102 deploy_commands(ENV, '/var/www/meteors', Path('build'), auth_config_path=path)
103 )
104 check(' -o data/config.php' in cmds2, 'put when path given')
105 check(path in cmds2, 'local path in put')
106 check(FAKE not in cmds2 and FAKE_QUOTED not in cmds2, 'secret not in lftp script')
107 check('--delete' not in cmds2, 'no --delete with config put')
108
109
110def main():
111 test_empty_secret()
112 test_php_quoting()
113 test_generated_php_evaluates()
114 test_lftp_script_has_no_secret()
115 print('auth-config ok')
116 return 0
117
118
119if __name__ == '__main__':
120 sys.exit(main())
docs/ASSUMPTIONS.md +11 −5
@@ -208,8 +208,9 @@ Aanname:
208 208 - Login via auth.timfalken.com (`/oauth/authorize`, `/oauth/token`, `/api/me`),
209 209 client_id `projects.timfalken.com`. Callback
210 210 `https://projects.timfalken.com/meteors/callback.php`. Het geheim zet Tim
211 zelf in `data/config.php`; wij genereren het nooit opnieuw. Zonder geheim
212 blijft solo werken, met een duidelijke online-melding.
211 als protected projectgeheim `auth_client_secret` (niet opnieuw genereren);
212 de deploy schrijft dan `data/config.php`. Zonder geheim blijft solo
213 werken, met een duidelijke online-melding.
213 214 - Testers `auth.php?test=1` / `?test=2` alleen als `localDev()` waar is:
214 215 loopback-host **én** loopback-remote-adres (zelfde regel als verhalenboek).
215 216 - Sessies staan in `data/sessions`, cookie-pad is de map van het script
@@ -238,7 +239,12 @@ Aanname:
238 239 laatste die overblijft is 1e; de eerder uitgeschakelden 2e, 3e, … Het
239 240 podium blijft **5 seconden** (`METEORS_PODIUM_SECONDS`) en daarna gaat de
240 241 lobby terug naar `waiting` (ready-vlaggen gereset).
241 - `data/` (config, sqlite, sessies) wordt nooit gedeployed of gewist. Alleen
242 - `data/` (sqlite, sessies) wordt nooit gespiegeld of gewist. Alleen
242 243 `data/.htaccess` (Require all denied) wordt na de mirror gezet.
243 `favicon.ico` blijft ongemoeid. `router.php` is alleen voor lokale `php -S`
244 en gaat niet mee naar live.
244 Als het projectgeheim `auth_client_secret` niet leeg is, schrijft de
245 deploy `data/config.php` vanuit dat geheim (waarde nooit in de logs).
246 Is het leeg of afwezig, dan blijft een bestaand bestand staan. De groep
247 `projects-timfalken-com` en verhalenboek hebben dit geheim niet (alleen
248 FTP); Tim zet het op het meteors-project. Optioneel: `auth_client_id`
249 (standaard `projects.timfalken.com`). `favicon.ico` blijft ongemoeid.
250 `router.php` is alleen voor lokale `php -S` en gaat niet mee naar live.
@@ -208,8 +208,9 @@ Aanname:
208- Login via auth.timfalken.com (`/oauth/authorize`, `/oauth/token`, `/api/me`),
208- Login via auth.timfalken.com (`/oauth/authorize`, `/oauth/token`, `/api/me`),
209 client_id `projects.timfalken.com`. Callback
209 client_id `projects.timfalken.com`. Callback
210 `https://projects.timfalken.com/meteors/callback.php`. Het geheim zet Tim
210 `https://projects.timfalken.com/meteors/callback.php`. Het geheim zet Tim
211 zelf in `data/config.php`; wij genereren het nooit opnieuw. Zonder geheim
211 als protected projectgeheim `auth_client_secret` (niet opnieuw genereren);
212 blijft solo werken, met een duidelijke online-melding.
212 de deploy schrijft dan `data/config.php`. Zonder geheim blijft solo
213 werken, met een duidelijke online-melding.
213- Testers `auth.php?test=1` / `?test=2` alleen als `localDev()` waar is:
214- Testers `auth.php?test=1` / `?test=2` alleen als `localDev()` waar is:
214 loopback-host **én** loopback-remote-adres (zelfde regel als verhalenboek).
215 loopback-host **én** loopback-remote-adres (zelfde regel als verhalenboek).
215- Sessies staan in `data/sessions`, cookie-pad is de map van het script
216- Sessies staan in `data/sessions`, cookie-pad is de map van het script
@@ -238,7 +239,12 @@ Aanname:
238 laatste die overblijft is 1e; de eerder uitgeschakelden 2e, 3e, … Het
239 laatste die overblijft is 1e; de eerder uitgeschakelden 2e, 3e, … Het
239 podium blijft **5 seconden** (`METEORS_PODIUM_SECONDS`) en daarna gaat de
240 podium blijft **5 seconden** (`METEORS_PODIUM_SECONDS`) en daarna gaat de
240 lobby terug naar `waiting` (ready-vlaggen gereset).
241 lobby terug naar `waiting` (ready-vlaggen gereset).
241- `data/` (config, sqlite, sessies) wordt nooit gedeployed of gewist. Alleen
242- `data/` (sqlite, sessies) wordt nooit gespiegeld of gewist. Alleen
242 `data/.htaccess` (Require all denied) wordt na de mirror gezet.
243 `data/.htaccess` (Require all denied) wordt na de mirror gezet.
243 `favicon.ico` blijft ongemoeid. `router.php` is alleen voor lokale `php -S`
244 Als het projectgeheim `auth_client_secret` niet leeg is, schrijft de
244 en gaat niet mee naar live.
245 deploy `data/config.php` vanuit dat geheim (waarde nooit in de logs).
246 Is het leeg of afwezig, dan blijft een bestaand bestand staan. De groep
247 `projects-timfalken-com` en verhalenboek hebben dit geheim niet (alleen
248 FTP); Tim zet het op het meteors-project. Optioneel: `auth_client_id`
249 (standaard `projects.timfalken.com`). `favicon.ico` blijft ongemoeid.
250 `router.php` is alleen voor lokale `php -S` en gaat niet mee naar live.
test/deploy_guard.test.js +14 −0
@@ -121,3 +121,17 @@ describe('assert_safe_target', () =>
121 121 assert.match(r.stdout, /mirror ok/);
122 122 });
123 123 });
124
125
126 describe('auth_config_php', () =>
127 {
128 it('is covered by ci/test_deploy_auth.py (PHP escaping, empty secret, no leak in lftp)', () =>
129 {
130 const r = spawnSync('python3', ['ci/test_deploy_auth.py'], {
131 cwd: path.join(__dirname, '..'),
132 encoding: 'utf8'
133 });
134 assert.equal(r.status, 0, r.stdout + r.stderr);
135 assert.match(r.stdout, /ok/);
136 });
137 });
@@ -121,3 +121,17 @@ describe('assert_safe_target', () =>
121 assert.match(r.stdout, /mirror ok/);
121 assert.match(r.stdout, /mirror ok/);
122 });
122 });
123});
123});
124
125
126describe('auth_config_php', () =>
127{
128 it('is covered by ci/test_deploy_auth.py (PHP escaping, empty secret, no leak in lftp)', () =>
129 {
130 const r = spawnSync('python3', ['ci/test_deploy_auth.py'], {
131 cwd: path.join(__dirname, '..'),
132 encoding: 'utf8'
133 });
134 assert.equal(r.status, 0, r.stdout + r.stderr);
135 assert.match(r.stdout, /ok/);
136 });
137});