66 lines
2.8 KiB
Python
66 lines
2.8 KiB
Python
"""Generate isolated test credentials into new, private local files only."""
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
from urllib.parse import quote
|
|
|
|
from .environment import validate_config
|
|
|
|
|
|
def _write_private(path, text):
|
|
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
|
stream.write(text)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
|
|
|
|
def generate_credentials(config, outdir):
|
|
"""Return file paths, never credential contents; refuse replacing any output."""
|
|
normalized = validate_config(config)
|
|
output = Path(os.path.abspath(outdir))
|
|
for path in (output, *output.parents):
|
|
if path.is_symlink():
|
|
raise ValueError("credential output must not traverse a symbolic link")
|
|
if output.exists():
|
|
raise FileExistsError("credential output must be a new directory")
|
|
output.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
output.mkdir(mode=0o700)
|
|
|
|
root_password = secrets.token_urlsafe(36)
|
|
app_password = secrets.token_urlsafe(36)
|
|
namespace = normalized["namespace"]
|
|
database = normalized["databaseName"]
|
|
host = f"{normalized['mongoServiceName']}.{namespace}.svc.cluster.local"
|
|
values = {
|
|
"MONGO_ROOT_USERNAME": "test_root",
|
|
"MONGO_ROOT_PASSWORD": root_password,
|
|
"MONGO_APP_USERNAME": "test_app",
|
|
"MONGO_APP_PASSWORD": app_password,
|
|
"MONGO_URI": f"mongodb://test_app:{quote(app_password, safe='')}@{host}:27017/{database}?authSource={database}",
|
|
"DROBOTICFLOW_API_TOKEN": secrets.token_urlsafe(48),
|
|
}
|
|
secret = {
|
|
"apiVersion": "v1", "kind": "Secret", "type": "Opaque",
|
|
"metadata": {"name": normalized["credentialsSecretName"], "namespace": namespace,
|
|
"labels": {"app.kubernetes.io/part-of": "internal-test-lane"}},
|
|
"stringData": values,
|
|
}
|
|
roles = [("admin", "平台管理员"), ("supplier_manager", "供应商管理员"),
|
|
("annotator", "标注员"), ("quality_reviewer", "质检员"),
|
|
("acceptance_reviewer", "最终验收员")]
|
|
accounts = {"accounts": [
|
|
{"role": role, "name": f"内部测试·{name}", "phone": f"1999999000{number}",
|
|
"password": secrets.token_urlsafe(36)}
|
|
for number, (role, name) in enumerate(roles, start=1)
|
|
]}
|
|
secret_file, accounts_file = output / "secret.json", output / "accounts.json"
|
|
_write_private(secret_file, json.dumps(secret, ensure_ascii=False, indent=2) + "\n")
|
|
_write_private(accounts_file, json.dumps(accounts, ensure_ascii=False, indent=2) + "\n")
|
|
uri_file = output / "mongo-uri.txt"
|
|
_write_private(uri_file, values["MONGO_URI"] + "\n")
|
|
return {"secretManifest": str(secret_file), "accountsFile": str(accounts_file),
|
|
"mongoUriFile": str(uri_file)}
|