Repository navigation
Expand file tree
/
Copy pathtest_create_subdomain.py
More file actions
557 lines (395 loc) · 20.1 KB
/
Copy pathtest_create_subdomain.py
File metadata and controls
557 lines (395 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
"""Test delle funzioni pure di create_subdomain.py.
Nessuna rete: si testano solo le parti che trasformano dati (validazione,
costruzione parametri, parsing risposte). Sono esattamente i punti in cui
si sono annidati i bug veri di questo script - una docroot presunta, un
campo dimenticato nel round-trip DNS, una risposta interpretata male.
pip install -r requirements-dev.txt
pytest -q
"""
import pytest
import create_subdomain as cs
# --------------------------------------------------------------------------- #
# Validazione del nome
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize("nome", ["lab", "a", "test-2", "x1-y2-z3", "a" * 63])
def test_nomi_validi(nome):
assert cs.valida_subdomain(nome) == nome
@pytest.mark.parametrize(
"nome",
[
"", # vuoto
"-lab", # trattino iniziale
"lab-", # trattino finale
"la b", # spazio
"lab/../etc", # separatore di path
"lab.sub", # punto
'x") ; id ; ("', # il payload di shell injection del workflow
"a" * 64, # troppo lungo
None,
],
)
def test_nomi_rifiutati(nome):
with pytest.raises(ValueError):
cs.valida_subdomain(nome)
# --------------------------------------------------------------------------- #
# Guardia sulla document root (qui si cancellano file veri)
# --------------------------------------------------------------------------- #
HOME = "/home/utente"
def test_docroot_normale_accettata():
assert cs.assert_docroot_sicura(f"{HOME}/lab", HOME) == f"{HOME}/lab"
def test_docroot_con_slash_finale_normalizzata():
assert cs.assert_docroot_sicura(f"{HOME}/lab/", HOME) == f"{HOME}/lab"
def test_docroot_annidata_accettata():
# Sottodomini creati dalle versioni precedenti dello script.
assert cs.assert_docroot_sicura(f"{HOME}/public_html/lab", HOME) == f"{HOME}/public_html/lab"
@pytest.mark.parametrize(
"docroot",
[
HOME, # la home stessa
f"{HOME}/", # idem, con slash
f"{HOME}/public_html", # docroot del dominio principale
"/home/altro/lab", # fuori dalla home
"/etc", # completamente fuori
f"{HOME}/../altro/lab", # traversal
"", # vuoto
],
)
def test_docroot_pericolose_rifiutate(docroot):
with pytest.raises(RuntimeError):
cs.assert_docroot_sicura(docroot, HOME)
def test_home_mancante_rifiutata():
with pytest.raises(RuntimeError):
cs.assert_docroot_sicura(f"{HOME}/lab", "")
# --------------------------------------------------------------------------- #
# Lettura della docroot reale da domains_data
# --------------------------------------------------------------------------- #
RIGHE = [
{"domain": "esempio.com", "documentroot": "/home/u/public_html", "homedir": "/home/u"},
{"domain": "lab.esempio.com", "documentroot": "/home/u/lab", "homedir": "/home/u"},
{"domain": "old.esempio.com", "documentroot": "/home/u/public_html/old", "homedir": "/home/u"},
]
def test_estrae_docroot_del_dominio_giusto():
assert cs.estrai_docroot(RIGHE, "lab.esempio.com") == ("/home/u/lab", "/home/u")
def test_estrae_docroot_annidata():
# Il caso che il path presunto ~/<subdomain> sbagliava.
assert cs.estrai_docroot(RIGHE, "old.esempio.com") == ("/home/u/public_html/old", "/home/u")
def test_dominio_non_trovato():
with pytest.raises(RuntimeError, match="not found"):
cs.estrai_docroot(RIGHE, "inesistente.esempio.com")
def test_campi_mancanti():
righe = [{"domain": "lab.esempio.com", "documentroot": None, "homedir": "/home/u"}]
with pytest.raises(RuntimeError):
cs.estrai_docroot(righe, "lab.esempio.com")
def test_righe_vuote():
with pytest.raises(RuntimeError):
cs.estrai_docroot([], "lab.esempio.com")
# --------------------------------------------------------------------------- #
# Round-trip dei record DNS (setHosts riscrive TUTTO)
# --------------------------------------------------------------------------- #
def _host(nome, tipo="A", **kw):
base = {
"HostName": nome, "RecordType": tipo, "Address": "1.2.3.4", "TTL": "60",
"MXPref": "10", "Flags": None, "Tag": None, "IsDDNSEnabled": False,
}
base.update(kw)
return base
def test_email_type_conservato():
# Se EmailType non viene rimandato indietro, Namecheap puo' resettare
# l'instradamento email del dominio.
extra = cs.costruisci_set_hosts([_host("www")], "esempio", "com", email_type="MX")
assert extra["EmailType"] == "MX"
def test_email_type_assente_non_inventato():
extra = cs.costruisci_set_hosts([_host("www")], "esempio", "com", email_type=None)
assert "EmailType" not in extra
def test_tutti_i_record_rimandati_indietro():
hosts = [_host("www"), _host("blog"), _host("@")]
extra = cs.costruisci_set_hosts(hosts, "esempio", "com")
assert [extra[f"HostName{i}"] for i in (1, 2, 3)] == ["www", "blog", "@"]
def test_mxpref_solo_sugli_mx():
hosts = [_host("www"), _host("@", tipo="MX", MXPref="20")]
extra = cs.costruisci_set_hosts(hosts, "esempio", "com")
assert "MXPref1" not in extra
assert extra["MXPref2"] == "20"
def test_caa_conserva_flags_e_tag():
hosts = [_host("@", tipo="CAA", Flags="0", Tag="issue")]
extra = cs.costruisci_set_hosts(hosts, "esempio", "com")
assert extra["Flags1"] == "0"
assert extra["Tag1"] == "issue"
# --------------------------------------------------------------------------- #
# Interpretazione delle risposte cPanel
# --------------------------------------------------------------------------- #
def test_file_inesistente_riconosciuto():
risposta = {"status": 0, "errors": ['The file "/home/u/lab/.htaccess" does not exist for the account.']}
assert cs.file_inesistente(risposta) is True
def test_errore_di_lettura_non_scambiato_per_file_mancante():
# Questo e' il caso in cui NON si deve sovrascrivere il .htaccess.
risposta = {"status": 0, "errors": ["Permission denied"]}
assert cs.file_inesistente(risposta) is False
def test_risposta_senza_errori():
assert cs.file_inesistente({"status": 0}) is False
def test_api2_successo():
data = {"cpanelresult": {"data": [{"result": 1}]}}
assert cs.parse_api2_result(data, "cPanel")["result"] == 1
def test_api2_successo_come_stringa():
data = {"cpanelresult": {"data": [{"result": "1"}]}}
assert cs.parse_api2_result(data, "cPanel")["result"] == "1"
@pytest.mark.parametrize(
"data",
[
{"cpanelresult": {"data": [{"result": 0, "reason": "non tuo"}]}},
{"cpanelresult": {"data": []}},
{"cpanelresult": {"error": "boom"}},
{},
],
)
def test_api2_fallimento(data):
with pytest.raises(RuntimeError):
cs.parse_api2_result(data, "cPanel -> Domains")
# --------------------------------------------------------------------------- #
# Pagina iniziale con PostHog
# --------------------------------------------------------------------------- #
def test_snippet_canonico_e_cookieless():
s = cs.carica_snippet_posthog()
assert "posthog.init(" in s
assert "cookieless_mode: 'always'" in s
assert "person_profiles: 'never'" in s
assert "api_host: 'https://relay.leandroestrella.com'" in s
assert "ui_host: 'https://eu.posthog.com'" in s
def test_snippet_non_identifica_mai():
s = cs.carica_snippet_posthog()
# Lo stub elenca "identify" e "alias" come nomi di metodo: vietate sono le chiamate.
assert "posthog.identify(" not in s
assert "posthog.alias(" not in s
def test_snippet_tagga_il_progetto():
# Tutti i siti condividono un progetto PostHog: il tag li separa nei report.
s = cs.carica_snippet_posthog(project="lab")
assert "posthog.register({ project: 'lab' })" in s
assert cs.POSTHOG_PROJECT_PLACEHOLDER not in s
def test_snippet_senza_progetto_lascia_il_segnaposto():
s = cs.carica_snippet_posthog()
assert f"posthog.register({{ project: '{cs.POSTHOG_PROJECT_PLACEHOLDER}' }})" in s
def test_snippet_progetto_non_valido_rifiutato():
with pytest.raises(ValueError):
cs.carica_snippet_posthog(project="x' }); alert(1); ({ y: '")
def test_snippet_incompleto_rifiutato(tmp_path):
finto = tmp_path / "snippet.html"
finto.write_text("<script>posthog.init('phc_x', {})</script>")
with pytest.raises(RuntimeError):
cs.carica_snippet_posthog(finto)
def test_starter_page_contiene_snippet_e_titolo():
pagina = cs.costruisci_starter_page("lab.example.com", cs.carica_snippet_posthog())
assert pagina.startswith("<!DOCTYPE html>")
assert "<title>lab.example.com</title>" in pagina
assert pagina.index("posthog.init(") < pagina.index("</head>")
assert '<meta name="robots" content="noindex">' in pagina
assert 'href="https://leandroestrella.com/privacy.html"' in pagina
def test_starter_page_senza_posthog():
# --skip-posthog: stessa pagina, nessuna traccia dello snippet.
pagina = cs.costruisci_starter_page("lab.example.com")
assert "posthog" not in pagina.lower()
assert "<title>lab.example.com</title>" in pagina
assert '<meta name="robots" content="noindex">' in pagina
assert "</head>" in pagina
def test_starter_page_escapa_il_nome():
pagina = cs.costruisci_starter_page("<b>x</b>", "<script>posthog.init(</script>")
assert "<b>x</b>" not in pagina
assert "<b>x</b>" in pagina
# --------------------------------------------------------------------------- #
# Authorized URLs di PostHog
# --------------------------------------------------------------------------- #
LAB = "https://lab.leandroestrella.com"
ESISTENTI = ["https://leandroestrella.com", "https://www.leandroestrella.com"]
def test_app_url_aggiunto_in_fondo_senza_toccare_gli_altri():
assert cs.aggiungi_app_url(ESISTENTI, LAB) == ESISTENTI + [LAB]
assert ESISTENTI == ["https://leandroestrella.com", "https://www.leandroestrella.com"]
def test_app_url_gia_presente_non_duplicato():
assert cs.aggiungi_app_url(ESISTENTI + [LAB], LAB) == ESISTENTI + [LAB]
@pytest.mark.parametrize("variante", [LAB + "/", LAB.upper(), f" {LAB} "])
def test_app_url_varianti_riconosciute_come_duplicati(variante):
# La voce esistente resta com'era: non si riscrive quello che non e' nostro.
assert cs.aggiungi_app_url([variante], LAB) == [variante]
def test_app_urls_duplicati_esistenti_ripuliti():
assert cs.aggiungi_app_url([LAB, ESISTENTI[0], LAB + "/"], LAB) == [LAB, ESISTENTI[0]]
@pytest.mark.parametrize("vuoti", [None, []])
def test_app_urls_vuoti(vuoti):
assert cs.aggiungi_app_url(vuoti, LAB) == [LAB]
assert cs.rimuovi_app_url(vuoti, LAB) == []
def test_app_url_rimosso_in_tutte_le_varianti():
assert cs.rimuovi_app_url([ESISTENTI[0], LAB, LAB + "/", ESISTENTI[1]], LAB) == ESISTENTI
def test_app_url_assente_rimozione_non_cambia_niente():
assert cs.rimuovi_app_url(ESISTENTI, LAB) == ESISTENTI
def test_rimozione_non_tocca_altri_sottodomini():
# "lab" non deve portarsi via "lab2" o "www.lab".
altri = ["https://lab2.leandroestrella.com", "https://www.lab.leandroestrella.com"]
assert cs.rimuovi_app_url(altri + [LAB], LAB) == altri
class _Risposta:
def __init__(self, status_code, data=None):
self.status_code = status_code
self.ok = status_code < 400
self._data = data or {}
self.text = str(self._data)
def json(self):
return self._data
@pytest.fixture
def posthog_finto(monkeypatch):
"""Sostituisce requests con un finto progetto PostHog in memoria."""
stato = {"app_urls": list(ESISTENTI), "patch": [], "get": 0, "get_status": 200}
monkeypatch.setattr(cs, "POSTHOG_PERSONAL_API_KEY", "phx_finta")
monkeypatch.setattr(cs, "ROOT_DOMAIN", "leandroestrella.com")
def get(url, headers, timeout):
assert url == "https://eu.posthog.com/api/environments/139609/"
assert headers == {"Authorization": "Bearer phx_finta"}
stato["get"] += 1
return _Risposta(stato["get_status"], {"app_urls": list(stato["app_urls"])})
def patch(url, headers, json, timeout):
stato["patch"].append(json)
stato["app_urls"] = json["app_urls"]
return _Risposta(200, {"app_urls": list(stato["app_urls"])})
monkeypatch.setattr(cs.requests, "get", get)
monkeypatch.setattr(cs.requests, "patch", patch)
return stato
def test_posthog_aggiunge_il_sottodominio(posthog_finto):
assert cs.aggiorna_app_urls_posthog("lab") is True
assert posthog_finto["patch"] == [{"app_urls": ESISTENTI + [LAB]}]
def test_posthog_gia_presente_niente_patch(posthog_finto):
posthog_finto["app_urls"].append(LAB)
assert cs.aggiorna_app_urls_posthog("lab") is True
assert posthog_finto["patch"] == []
def test_posthog_rimuove_il_sottodominio(posthog_finto):
posthog_finto["app_urls"].append(LAB)
assert cs.aggiorna_app_urls_posthog("lab", rimuovi=True) is True
assert posthog_finto["patch"] == [{"app_urls": ESISTENTI}]
def test_posthog_senza_chiave_saltato(posthog_finto, monkeypatch, capsys):
monkeypatch.setattr(cs, "POSTHOG_PERSONAL_API_KEY", None)
assert cs.aggiorna_app_urls_posthog("lab") is False
assert posthog_finto["get"] == 0
assert "POSTHOG_PERSONAL_API_KEY is not set" in capsys.readouterr().out
def test_posthog_dry_run_nessuna_chiamata(posthog_finto):
assert cs.aggiorna_app_urls_posthog("lab", dry_run=True) is True
assert posthog_finto["get"] == 0
assert posthog_finto["patch"] == []
def test_posthog_chiave_senza_scope_e_un_warning(posthog_finto, capsys):
# Il sottodominio esiste gia': un errore qui non deve far fallire il run.
posthog_finto["get_status"] = 403
assert cs.aggiorna_app_urls_posthog("lab") is False
assert posthog_finto["patch"] == []
out = capsys.readouterr().out
assert "WARNING" in out and "project:write" in out
# --------------------------------------------------------------------------- #
# AutoSSL via UAPI
# --------------------------------------------------------------------------- #
def _problema(dominio):
return {"domain": dominio, "problem": "HTTP DCV: ...", "time": "2026-09-28T16:26:18Z"}
def test_problemi_solo_del_sottodominio():
righe = [_problema("lab.leandroestrella.com"), _problema("altro.leandroestrella.com")]
assert cs.problemi_autossl(righe, "lab.leandroestrella.com") == [righe[0]]
def test_problemi_www_ignorati():
# www.<sub> non risolve con un wildcard di un solo livello: rumore atteso.
righe = [_problema("www.lab.leandroestrella.com")]
assert cs.problemi_autossl(righe, "lab.leandroestrella.com") == []
def test_problemi_confronto_senza_maiuscole():
righe = [_problema("Lab.LeandroEstrella.com")]
assert cs.problemi_autossl(righe, "lab.leandroestrella.com") == righe
@pytest.mark.parametrize("righe", [None, []])
def test_problemi_nessuna_riga(righe):
assert cs.problemi_autossl(righe, "lab.leandroestrella.com") == []
@pytest.fixture
def autossl_finto(monkeypatch):
"""Sostituisce requests con un finto SSL:: di cPanel in memoria."""
stato = {"chiamate": [], "in_corso": [1, 0], "problemi": [], "start_status": 1}
monkeypatch.setattr(cs, "CPANEL_HOST", "server.example.com")
monkeypatch.setattr(cs, "CPANEL_USER", "utente")
monkeypatch.setattr(cs, "CPANEL_API_TOKEN", "token")
monkeypatch.setattr(cs, "ROOT_DOMAIN", "leandroestrella.com")
monkeypatch.setattr(cs.time, "sleep", lambda s: None)
monkeypatch.setattr(cs, "attendi_vhost", lambda fqdn: stato["chiamate"].append("vhost") or True)
def get(url, headers, timeout):
assert url.startswith("https://server.example.com:2083/execute/SSL/")
assert headers == {"Authorization": "cpanel utente:token"}
funzione = url.rsplit("/", 1)[1]
stato["chiamate"].append(funzione)
if funzione == "start_autossl_check":
return _Risposta(200, {"status": stato["start_status"], "data": None,
"errors": None if stato["start_status"] else ["no"]})
if funzione == "is_autossl_check_in_progress":
return _Risposta(200, {"status": 1, "data": stato["in_corso"].pop(0)})
if funzione == "get_autossl_problems":
return _Risposta(200, {"status": 1, "data": stato["problemi"]})
raise AssertionError(funzione)
monkeypatch.setattr(cs.requests, "get", get)
return stato
def test_autossl_dry_run_nessuna_chiamata(autossl_finto):
assert cs.run_autossl("lab", dry_run=True, wait_seconds=60) is True
assert autossl_finto["chiamate"] == []
def test_autossl_senza_attesa_solo_avvio(autossl_finto):
assert cs.run_autossl("lab") is True
assert autossl_finto["chiamate"] == ["vhost", "start_autossl_check"]
def test_autossl_attende_e_legge_i_problemi(autossl_finto):
autossl_finto["problemi"] = [_problema("www.lab.leandroestrella.com")]
assert cs.run_autossl("lab", wait_seconds=60) is True
assert autossl_finto["chiamate"] == [
"vhost",
"start_autossl_check",
"is_autossl_check_in_progress",
"is_autossl_check_in_progress",
"get_autossl_problems",
]
def test_autossl_problema_del_sottodominio_e_un_warning(autossl_finto, capsys):
autossl_finto["problemi"] = [_problema("lab.leandroestrella.com")]
assert cs.run_autossl("lab", wait_seconds=60) is False
assert "WARNING: lab.leandroestrella.com" in capsys.readouterr().out
def test_autossl_avvio_fallito(autossl_finto):
autossl_finto["start_status"] = 0
with pytest.raises(RuntimeError, match="start_autossl_check"):
cs.run_autossl("lab")
def test_autossl_credenziali_mancanti(autossl_finto, monkeypatch):
monkeypatch.setattr(cs, "CPANEL_API_TOKEN", None)
with pytest.raises(SystemExit, match="CPANEL_API_TOKEN"):
cs.run_autossl("lab", dry_run=True)
assert autossl_finto["chiamate"] == []
def test_impronta_uguale_per_lo_stesso_vhost_di_ripiego():
# Il catch-all "*" risponde uguale a qualsiasi nome.
a = cs.impronta_http(302, "https://leandroestrella.com/", "<p>Found</p>", "lab.leandroestrella.com")
b = cs.impronta_http(302, "https://leandroestrella.com/", "<p>Found</p>", "x1.leandroestrella.com")
assert a == b
def test_impronta_neutralizza_il_nome_dell_host():
# Un vhost che rimanda a se stesso resta riconoscibile a prescindere dal nome.
a = cs.impronta_http(301, "https://lab.leandroestrella.com/", "", "lab.leandroestrella.com")
b = cs.impronta_http(301, "https://x1.leandroestrella.com/", "", "x1.leandroestrella.com")
assert a == b
def test_impronta_distingue_il_vhost_proprio():
ripiego = cs.impronta_http(302, "https://leandroestrella.com/", "", "x1.leandroestrella.com")
proprio = cs.impronta_http(301, "https://lab.leandroestrella.com/", "", "lab.leandroestrella.com")
assert ripiego != proprio
def test_impronta_senza_location():
a = cs.impronta_http(200, None, "ciao", "lab.leandroestrella.com")
assert a[:2] == (200, "")
@pytest.fixture
def vhost_finto(monkeypatch):
"""Il sottodominio risponde come il ripiego per le prime `ritardo` richieste."""
stato = {"ritardo": 2, "richieste": []}
monkeypatch.setattr(cs, "ROOT_DOMAIN", "leandroestrella.com")
monkeypatch.setattr(cs.time, "sleep", lambda s: None)
def get(url, allow_redirects, timeout):
assert allow_redirects is False
host = url.split("/")[2]
stato["richieste"].append(host)
risp = _Risposta(302, {})
risp.headers = {"Location": "https://leandroestrella.com/"}
if host == "lab.leandroestrella.com":
if stato["ritardo"] > 0:
stato["ritardo"] -= 1
else:
risp = _Risposta(301, {})
risp.headers = {"Location": "https://lab.leandroestrella.com/"}
risp.text = ""
return risp
monkeypatch.setattr(cs.requests, "get", get)
return stato
def test_attende_il_vhost_proprio(vhost_finto):
assert cs.attendi_vhost("lab.leandroestrella.com") is True
assert vhost_finto["richieste"][0].startswith("hammerspace-probe-")
assert vhost_finto["richieste"][1:] == ["lab.leandroestrella.com"] * 3
def test_vhost_mai_pronto_scade(vhost_finto):
vhost_finto["ritardo"] = 10**6
assert cs.attendi_vhost("lab.leandroestrella.com", attesa_max=0) is False