BlueGit

projects-timfalken-com meteors

feat: write data/config.php from the auth_client_secret CI secret

The group and sibling projects only have FTP credentials, so this is a
project secret. The file is written only when the secret is non-empty,
never appears in the lftp script or logs, and existing data/ is left
in place. Optional auth_client_id defaults to projects.timfalken.com.

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
08b092a40e536166c472d1236995d1c1cdf0268f
Parent
4dac4f2a
4 files changed +236 −10
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())
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});