Compare commits

..

4 Commits

Author SHA1 Message Date
Roberto Treviño Cervantes 234c45c10a ISSSTELEON pointer: fold repeated catalog-matching captions 2026-11-11 09:16:05 -06:00
Roberto Treviño Cervantes a3b848ef6f Submodule pointer: ISSSTELEON at its merged staging 2026-11-11 07:40:53 -06:00
Roberto Treviño Cervantes f84f497cf9 import files in columns 2026-11-11 07:40:37 -06:00
Roberto Treviño Cervantes 8e30ac5aea Merge dev into staging 2026-11-11 07:40:37 -06:00
30 changed files with 102 additions and 3027 deletions
-202
View File
@@ -1,202 +0,0 @@
# Native release deployment
This manual-dispatch workflow prepares and deploys a published Release to
`10.0.10.41` using native Ubuntu processes. A successful run means it has
resolved the tag, transferred the pinned application source, prepared the
instance, started three supervised user services, verified local health and
confirmed that the runner can reach WebApp and the proxied API at
`http://10.0.10.41:<puerto>/`. It then checks the service states once more.
The intermediate bundle remains in the job workspace; no manual download,
transfer, installation or activation is required per deployment.
The installer revision comes from the selected workflow branch, normally
`dev`; the application revision comes exclusively from the tag. It is not
restricted to `dev`, `staging` or `main`. The first intended test is a
published Release for the operator-selected `staging` commit on port `18090`.
No Release, tag, deployment or infrastructure change is created by this work.
## Architecture and prerequisites
An isolated non-root deployment account connects to the host over SSH with a
dedicated key and a verified host key. It owns an isolated installation parent
and runs its own `systemd --user` manager, with lingering enabled once by the
operator. The account must not have Docker, sudo, wheel or root group
membership; it must have no other administrative grants or capabilities. It
can execute commands and write within its own permissions, so the private key
is sensitive even though it does not confer root access. SSH key `restrict`
options can disable forwarding and interactive PTY access; they do not prevent
the account from executing arbitrary commands as itself.
The workflow uses no `sudo` and never changes the existing runner or Docker
configuration. The operator confirmed that `ubuntu-latest`, `ubuntu-24.04` and
`ubuntu-22.04` jobs use `docker://docker.gitea.com/runner-images` as configured
in `/etc/act_runner/config.yaml`. The application itself runs as native user
services on the host. The job must be able to reach Gitea, SSH on labserver, and the
application's public port; these are required for the final checks. The host
must provide Python >=3.12, uv, compatible Node/npm, nginx with
`/etc/nginx/mime.types`, Tesseract and `spa`/`eng` language data. The inspected
application container uses Node 22. The account must be able to reach any
required package registries, and uv, npm, nginx and Tesseract must be on its
noninteractive SSH PATH. `systemd --user`, its D-Bus runtime and the
sandbox options in the units must work on the target Ubuntu configuration.
User services explicitly use `PrivateUsers=true` with filesystem sandboxing;
this requires unprivileged user namespaces to be available. Depending on the
host, sandbox settings may fail or be ineffective; validate their effective
behavior before relying on them. Availability and compatibility have not been
demonstrated by local tests.
The operator reports that `admon` has interactive sudo and that the runner is
an `act-runner` host process. `admon` is a member of Docker and sudo groups and
must not be the deployment/service account. No assumption is made about runner
sudo access. Use `admon` for the one-time authorized setup, not as the runtime
identity or as an Action credential.
## One-time operator setup
Only after authorization for physical changes, an administrator should:
1. Provision a dedicated non-root account with a real home and a shell capable
of the SSH commands and SFTP used here. Verify it has no Docker,
administrative, custom sudoers or capability grants. The installer rejects
the standard privileged groups but cannot detect every possible grant.
2. Create an isolated parent directory outside `/srv/workingnarrative-dev`
and all existing installation/data paths; give only that account the needed
access. For a new directory an administrator may use, for example,
`sudo mkdir /srv/workingnarrative-native`, followed by a reviewed `chown`
and `chmod 0750` for the chosen account. Do not overwrite or reassign an
existing directory without a separate review.
3. Provision an SSH deployment key for that account through the authorized
channel. Restrict its `authorized_keys` entry appropriately and verify the
server host-key fingerprint independently. Do not store the `admon` password
or enable passwordless sudo. Confirm SSH and SFTP work for this account.
4. Enable lingering once with `sudo loginctl enable-linger <account>`. Confirm
the account's user manager and `/run/user/<uid>/bus` are available. This is
needed so services survive the SSH session and start after reboot. Confirm
that the required systemd user-service sandbox options work; the deployment
fails closed if its manager or services cannot start.
5. Configure the following Gitea Actions variables and secrets through the
authorized administrative process. No credentials are provisioned here.
| Kind | Name | Value |
|---|---|---|
| Variable | `NATIVE_ACCOUNT` | Dedicated deployment/service account |
| Variable | `NATIVE_SSH_PORT` | SSH port for the host |
| Variable | `NATIVE_HOSTNAME` | Exact hostname returned by the host |
| Variable | `NATIVE_PARENT` | Existing dedicated absolute parent directory |
| Secret | `NATIVE_SSH_KEY` | Dedicated account's private key, in full |
| Secret | `NATIVE_KNOWN_HOSTS` | Independently verified SSH known-hosts entry |
The job writes the key and known-hosts data to temporary files with a private
umask and removes them on normal shell exit. Use a trusted runner and its
secret controls; abrupt termination may prevent cleanup. The Gitea job token must have read access to the published Release and all
private application submodules. Configure only the required cross-repository
read access through the authorized Gitea administration process. The resolver
passes the job token to Git as an HTTP header scoped to the institutional
repository namespace; it does not embed credentials in repository URLs.
## Running a deployment
After review, integration and one-time setup, the operator may publish the
Release pointing to the selected application commit. In Gitea, dispatch
`deploy-terminal-release` from the reviewed installer branch and supply the
exactly three inputs: published `tag`, public `puerto` (default `18090`) and
loopback `puerto_api` (default `28090`). Both ports must be integers in
`1024..65535`, distinct and available on the host. This is a new-install-only
workflow. It rejects an existing instance, unit path or occupied port rather
than updating or overwriting it. Choose a different free API port when another
native instance already uses the requested value.
The Action performs these steps:
1. Validate the institutional event, origin and published Release, fetch the
exact tag, peel it to a commit and check that neither tag nor Release changed.
2. Check out only recognized institutional application gitlinks at their
committed SHAs, independently of branch heads. Archive committed application
components and record tag, release ID, tag object, application and installer
commits, gitlinks, installer file hashes and bundle digest.
3. Connect to the configured host with strict SSH host-key checking. Check the
hostname, account, groups, user manager and lingering, create a unique
account-owned staging directory, and transfer the bundle and reviewed
installer. The requested API port is included in the release record and
checked against the value passed to the remote installer. The job does not copy any files into system-wide systemd paths.
4. Exclusively create `NATIVE_PARENT/isssteleon-native-<puerto>`, check both
ports, install Python and Node dependencies using the release's lockfiles,
and compile Angular. Create four new SQLite files and validate the effective
Persistance URLs and empty isolated files before running Alembic.
5. Generate three units in the instance, link them exclusively into the
account's user-unit directory, reload its user manager, and enable/start the
API, indicator worker and nginx. There is no privileged operation per run.
6. Verify the three units, direct and proxied `/health`, Angular root and SPA
fallback on the host. From the runner check the public root and proxied API
on `10.0.10.41:<puerto>`, then recheck the host services. Any failure makes
the Action fail; a successful external check is recorded on the host.
Preparation uses the selected release's equivalents of these commands:
```sh
# application/WebApi
uv sync --locked --no-dev --extra sql-drivers
uv run --no-sync alembic -c ../Persistance/persistance/cacu/alembic.ini upgrade head
uv run --no-sync alembic -c ../Persistance/persistance/cama/alembic.ini upgrade head
uv run --no-sync alembic -c ../Persistance/persistance/tea/alembic.ini upgrade head
uv run --no-sync alembic -c ../Persistance/persistance/governance/alembic.ini upgrade head
# application/WebApp
npm ci
npm run build -- --configuration production
```
The service commands use `.venv/bin/gunicorn` on `127.0.0.1:<API port>`,
`.venv/bin/python -m webapi.indicadores_vivos`, and a dedicated nginx process
for the Angular production files and proxy. The nginx process listens on the
requested public port. The four domain databases, MLflow database and
artifacts, reports, indicator queue and nginx temporary files are under the new
instance's `data/`. No Docker volume, database, compose project or existing
Docker installer is used or modified.
`installation.json` records identity, paths, service names, both requested ports, phases,
status and health checks. User services use `default.target`, restart on
failure and write to the user journal. For example, under the service account:
```sh
systemctl --user status isssteleon-native-18090-{api,worker,web}.service
journalctl --user -u isssteleon-native-18090-api.service -u isssteleon-native-18090-worker.service -u isssteleon-native-18090-web.service
```
The helper explicitly sets `XDG_RUNTIME_DIR` and `DBUS_SESSION_BUS_ADDRESS`
for noninteractive SSH. An operator's interactive session may also need these
set for `systemctl --user` and `journalctl --user`. The host-local checks do
not prove that the indicator worker completed a calculation or exercise
clinical workflows; perform an authorized functional smoke test separately.
## Failure handling and validation
A failed build, migration, activation or health check makes the job fail.
Instance files and databases are retained for inspection; no retry automatically
reuses or migrates them. Failed activation attempts to disable/stop only the
newly linked user units and records failure; any links left by systemd remain
for inspection. If that stop
itself fails, the operator must inspect the user manager; no global cleanup is
performed. A public HTTP failure is reported back into the instance record when
SSH remains available. If SSH fails while reporting, the job log is authoritative
about that failure. Recovery, deletion or updates require a separate review.
Automated local tests use temporary Git repositories and bundles, mock SSH and
systemd subprocesses, and exercise a real local port conflict. The observed
staging application trees were exported and extracted from cached objects.
These tests do not prove that user systemd, nginx, package downloads, real
migrations, SSH, or the Gitea Actions context work on Ubuntu. Validate the full
path in a disposable Ubuntu environment and complete the authorized one-time
setup before requesting a physical test. The operator must check the actual
public and loopback port availability and dedicated paths before that test.
The inspected local `dev` base was `e8d19e88e1022953f5714cf891129adfe992d3f7`;
the older `91f3b9942a9df390da3435267c7131fe7464240c` was a historical local
reference. The observed `staging` commit was
`234c45c10ad901e75907d56b5443ecbc619af342` with application gitlink
`f6d00f51f30cc5482c1711082f8656f2b3d9cd30`. A later selected commit must be
reviewed against its own commands, migrations and gitlinks before publication.
A future `release: { types: [published] }` trigger is intentionally absent.
After the manual workflow is validated, design and test event-specific tag
handling and a trusted installer revision before enabling automatic publication
triggers.
-126
View File
@@ -1,126 +0,0 @@
#!/usr/bin/env python3
"""Activate only this prepared instance through the account's user systemd manager."""
import argparse
import json
import os
import stat
from pathlib import Path
import subprocess
import sys
import time
import install
def manager_environment(account):
import pwd
install.validate_service_account(account)
entry = pwd.getpwuid(os.geteuid())
home = Path(entry.pw_dir)
if (not home.is_absolute() or home.resolve() != home or not home.is_dir()
or home.stat().st_uid != os.geteuid() or home.stat().st_mode & 0o022):
raise ValueError('service account home must be owned by the account and not group/world writable')
runtime = Path('/run/user') / str(os.geteuid())
bus = runtime / 'bus'
if (runtime.is_symlink() or not runtime.is_dir() or runtime.stat().st_uid != os.geteuid()
or bus.is_symlink() or not bus.exists() or not stat.S_ISSOCK(bus.stat().st_mode)):
raise ValueError('user systemd runtime or D-Bus socket is unavailable')
return {'PATH': os.environ.get('PATH', '/usr/local/bin:/usr/bin:/bin'), 'HOME': str(home),
'XDG_RUNTIME_DIR': str(runtime), 'DBUS_SESSION_BUS_ADDRESS': 'unix:path=' + str(runtime / 'bus')}
def command(args, env, *, check=True):
return subprocess.run(args, env=env, capture_output=True, text=True, check=check)
def units_directory(home):
"""Create account-owned systemd configuration without traversing symlinks."""
current = Path(home)
for part in ('.config', 'systemd', 'user'):
current = current / part
try:
current.mkdir(mode=0o700)
except FileExistsError:
pass
if current.is_symlink() or not current.is_dir() or current.stat().st_uid != os.geteuid() or current.stat().st_mode & 0o022:
raise ValueError('unsafe user systemd unit directory: ' + str(current))
return current
def activate(instance, record, env):
"""Link and start only fresh instance units; retain data and failure evidence."""
base = Path(instance)
install.validate_record(record)
if (record.get('status') != 'prepared' or Path(record.get('base', '')) != base
or base.is_symlink() or base.resolve() != base):
raise ValueError('instance is not a freshly prepared installation')
port = record['public_port']
names = [f'isssteleon-native-{port}-{part}.service' for part in ('api', 'worker', 'web')]
if record.get('services') != names or base.name != f'isssteleon-native-{port}':
raise ValueError('invalid service identity')
linger = command(['loginctl', 'show-user', record['account'], '--property=Linger', '--value'], env)
if linger.stdout.strip().lower() != 'yes':
raise ValueError('user lingering is not enabled; one-time operator setup is required')
command(['systemctl', '--user', 'show-environment'], env)
unit_dir = units_directory(env['HOME'])
for name in names:
source = base / 'units' / name
dest = unit_dir / name
if source.is_symlink() or not source.is_file() or dest.exists() or dest.is_symlink():
raise ValueError('missing source or existing unit path: ' + name)
state = command(['systemctl', '--user', 'show', name, '--property=LoadState', '--value'], env)
if state.stdout.strip() != 'not-found':
raise ValueError('systemd unit already exists: ' + name)
record.update(status='activating', phase='linking_user_units', unit_directory=str(unit_dir))
install.atomic_record(base / 'installation.json', record)
linked = []
try:
for name in names:
os.symlink(base / 'units' / name, unit_dir / name)
linked.append(name)
command(['systemctl', '--user', 'daemon-reload'], env)
record.update(phase='starting_user_units')
install.atomic_record(base / 'installation.json', record)
for name in names:
command(['systemctl', '--user', 'enable', '--now', name], env)
record.update(status='started', phase='awaiting_health', started_at=int(time.time()))
install.atomic_record(base / 'installation.json', record)
return record
except BaseException as exc:
if linked:
try:
command(['systemctl', '--user', 'disable', '--now', *linked], env, check=False)
except OSError:
pass
record.update(status='activation_failed', phase='activation_failed', error=type(exc).__name__)
try:
install.atomic_record(base / 'installation.json', record)
except OSError:
pass
raise
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('instance', type=Path)
args = parser.parse_args()
try:
base = args.instance
if not base.is_absolute() or base.is_symlink() or base.resolve() != base:
raise ValueError('instance path must be absolute and not symlinked')
path = base / 'installation.json'
if path.is_symlink():
raise ValueError('symlinked installation record')
record = json.loads(path.read_text(encoding='utf-8'))
install.validate_record(record)
install.check_installer_files(Path(__file__).resolve().parent, record)
result = activate(base, record, manager_environment(record['account']))
print(json.dumps(result, sort_keys=True))
return 0
except (OSError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
print('Activation failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
-63
View File
@@ -1,63 +0,0 @@
#!/usr/bin/env python3
"""Export exact committed application trees as a guarded release bundle."""
import hashlib
import gzip
import json
from pathlib import Path, PurePosixPath
import subprocess
import tarfile
import tempfile
import source
APPLICATION_COMPONENTS = {'Core', 'Persistance', 'Extraction', 'WebApi', 'WebApp', 'models', 'indicadores_kit'}
def safe_member(member):
path = PurePosixPath(member.name)
return (not path.is_absolute() and member.name not in ('', '.')
and all(part not in ('', '.', '..') for part in path.parts)
and '\\' not in member.name and (member.isdir() or member.isfile()))
def export(checkout, manifest, output):
"""Export each verified commit, excluding Git metadata and untracked files."""
checkout, output = Path(checkout), Path(output)
seen = set()
with output.open('xb') as raw, gzip.GzipFile(fileobj=raw, mode='wb', filename='', mtime=0) as zipped, tarfile.open(fileobj=zipped, mode='w:', format=tarfile.PAX_FORMAT) as bundle:
for full, sha in sorted(manifest.items(), key=lambda item: (item[0].count('/'), item[0])):
repo = checkout / full
if source.git(repo, 'rev-parse', 'HEAD') != sha:
raise ValueError('source checkout changed: ' + full)
prefix = PurePosixPath('application') / PurePosixPath(full).relative_to('ISSSTELEON')
with tempfile.TemporaryFile() as stream:
subprocess.run(['git', '-C', str(repo), 'archive', '--format=tar', sha], stdout=stream, check=True)
stream.seek(0)
with tarfile.open(fileobj=stream, mode='r:') as archive:
for member in archive:
if full == 'ISSSTELEON' and PurePosixPath(member.name).parts[0] not in APPLICATION_COMPONENTS:
continue
if not safe_member(member):
raise ValueError('unsafe Git archive member: ' + member.name)
name = str(prefix / member.name)
if name in seen:
if member.isdir():
continue
raise ValueError('overlapping archive member: ' + name)
seen.add(name)
member.name = name
member.uid = member.gid = 0
member.uname = member.gname = ''
member.mode = (0o755 if member.isdir() or member.mode & 0o111 else 0o644)
bundle.addfile(member, archive.extractfile(member) if member.isfile() else None)
digest = hashlib.sha256()
with output.open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(block)
return digest.hexdigest()
def write_record(path, record):
with Path(path).open('x', encoding='utf-8') as stream:
json.dump(record, stream, indent=2, sort_keys=True)
stream.write('\n')
-350
View File
@@ -1,350 +0,0 @@
#!/usr/bin/env python3
"""Prepare a new isolated native instance; never activate privileged services."""
import argparse
import errno
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import socket
import subprocess
import sys
import tarfile
import time
import urllib.request
import bundle
NAME = re.compile(r'^[a-z_][a-z0-9_-]{0,30}$')
SHA = re.compile(r'^[0-9a-f]{40}$')
DIGEST = re.compile(r'^[0-9a-f]{64}$')
SAFE_PATH = re.compile(r'^/[A-Za-z0-9_./-]+$')
DOCKER_ROOT = Path('/srv/workingnarrative-dev')
DOMAINS = ('cacu', 'cama', 'tea', 'governance')
INSTALLER_FILES = {'install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'}
REQUIRED_LINKS = {'ISSSTELEON', 'ISSSTELEON/WebApi', 'ISSSTELEON/WebApp',
'ISSSTELEON/models', 'ISSSTELEON/indicadores_kit'}
def validate_record(record):
if not isinstance(record, dict):
raise ValueError('invalid release record')
if (not isinstance(record.get('tag'), str) or not record['tag'] or len(record['tag']) > 255
or any(ord(c) < 32 for c in record['tag']) or type(record.get('release_id')) is not int
or record['release_id'] <= 0 or type(record.get('public_port')) is not int
or not 1024 <= record['public_port'] <= 65535
or type(record.get('api_port')) is not int or not 1024 <= record['api_port'] <= 65535
or record['api_port'] == record['public_port']):
raise ValueError('invalid release identity or port')
if any(not isinstance(record.get(k), str) or not SHA.fullmatch(record[k])
for k in ('application_sha', 'installer_sha', 'tag_object')):
raise ValueError('invalid commit identity')
if not isinstance(record.get('bundle_sha256'), str) or not DIGEST.fullmatch(record['bundle_sha256']):
raise ValueError('invalid bundle digest')
files = record.get('installer_files')
if (not isinstance(files, dict) or set(files) != INSTALLER_FILES
or any(not isinstance(value, str) or not DIGEST.fullmatch(value) for value in files.values())):
raise ValueError('invalid installer file manifest')
links = record.get('gitlinks')
if (not isinstance(links, dict) or set(links) != REQUIRED_LINKS
or any(not isinstance(value, str) or not SHA.fullmatch(value) for value in links.values())):
raise ValueError('unsupported or incomplete gitlinks')
if not isinstance(record.get('installer_ref'), str) or not record['installer_ref'].startswith('refs/heads/'):
raise ValueError('invalid installer reference')
def digest(path):
value = hashlib.sha256()
with open(path, 'rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
value.update(block)
return value.hexdigest()
def check_installer_files(directory, record):
for name, expected in record['installer_files'].items():
file = Path(directory) / name
if file.is_symlink() or not file.is_file() or digest(file) != expected:
raise ValueError('installer file differs from release record: ' + name)
def validate_service_account(account):
"""Reject root and accounts with common administrative or Docker groups."""
import grp
import pwd
if not NAME.fullmatch(account) or os.geteuid() == 0:
raise ValueError('a non-root service account is required')
entry = pwd.getpwuid(os.geteuid())
if entry.pw_name != account:
raise ValueError('preparation must run as the selected service account')
groups = set(os.getgroups()) | set(os.getgrouplist(account, entry.pw_gid))
groups.update((entry.pw_gid, os.getegid()))
privileged = {0}
for name in ('docker', 'sudo', 'wheel'):
try:
privileged.add(grp.getgrnam(name).gr_gid)
except KeyError:
pass
if groups & privileged:
raise ValueError('service account belongs to a privileged administrative or Docker group')
def require_private_parent(parent):
"""Reject installation parents that other accounts can replace or modify."""
metadata = parent.stat()
if metadata.st_uid != os.geteuid() or metadata.st_mode & 0o022:
raise ValueError('installation parent must be owned by the service account and not group/world writable')
def validate_parent(parent):
parent = Path(parent)
if not parent.is_absolute() or not SAFE_PATH.fullmatch(str(parent)) or not parent.is_dir():
raise ValueError('parent must be an existing absolute path without whitespace or shell metacharacters')
if parent.resolve() != parent:
raise ValueError('parent and its ancestors must not be symlinks or contain dot components')
destination = parent / 'instance'
if destination == DOCKER_ROOT or DOCKER_ROOT in destination.parents or destination in DOCKER_ROOT.parents:
raise ValueError('native installation must be separate from the Docker deployment')
require_private_parent(parent)
return parent
def check_port(port, public):
if type(port) is not int or not 1024 <= port <= 65535:
raise ValueError('ports must be between 1024 and 65535')
families = [(socket.AF_INET, '0.0.0.0' if public else '127.0.0.1')]
if socket.has_ipv6:
families.append((socket.AF_INET6, '::' if public else '::1'))
for family, address in families:
try:
with socket.socket(family, socket.SOCK_STREAM) as sock:
if family == socket.AF_INET6:
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
sock.bind((address, port))
except OSError as exc:
if exc.errno in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL) and family == socket.AF_INET6:
continue
raise ValueError(f'port {port} is unavailable: {exc}') from exc
def extract_bundle(archive_path, target):
"""Extract regular files only into a new directory; reject links and duplicates."""
target = Path(target)
seen = set()
total = 0
with tarfile.open(archive_path, 'r:gz') as archive:
for member in archive:
if not bundle.safe_member(member):
raise ValueError('unsafe archive member')
path = PurePosixPath(member.name)
if not path.parts or path.parts[0] != 'application' or member.name in seen:
raise ValueError('invalid or duplicate archive member')
seen.add(member.name)
total += member.size
if total > 4 * 1024 ** 3 or len(seen) > 250000:
raise ValueError('archive exceeds extraction limits')
dest = target.joinpath(*path.parts)
if member.isdir():
dest.mkdir(parents=True, exist_ok=True, mode=0o755)
else:
dest.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
with archive.extractfile(member) as source_stream, dest.open('xb') as out:
shutil.copyfileobj(source_stream, out, 1024 * 1024)
os.chmod(dest, 0o755 if member.mode & 0o111 else 0o644)
app = target / 'application'
required = ['WebApi/pyproject.toml', 'WebApi/uv.lock', 'WebApi/webapi/indicadores_vivos.py',
'WebApp/package.json', 'WebApp/package-lock.json']
required += [f'Persistance/persistance/{domain}/alembic.ini' for domain in DOMAINS]
if any(not (app / path).is_file() for path in required):
raise ValueError('bundle lacks required locked application components')
def atomic_record(path, record):
temporary = path.with_suffix('.tmp')
with temporary.open('x', encoding='utf-8') as stream:
json.dump(record, stream, indent=2, sort_keys=True)
stream.write('\n')
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
def environment(base):
data = base / 'data'
result = {'PATH': os.environ.get('PATH', '/usr/local/bin:/usr/bin:/bin'),
'HOME': str(data), 'LANG': 'C.UTF-8', 'UV_CACHE_DIR': str(data / 'uv-cache'),
'npm_config_cache': str(data / 'npm-cache'),
'MLFLOW_TRACKING_URI': 'sqlite:///' + str(data / 'mlflow.db'),
'MLFLOW_ARTIFACT_ROOT': str(data / 'mlflow-artifacts'),
'MLFLOW_DISABLE_TELEMETRY': 'true', 'DO_NOT_TRACK': 'true',
'MLFLOW_DISABLE_AGENT_HINT': '1', 'WEBAPI_REPORT_DIR': str(data / 'reportes'),
'INDICADORES_DIR': str(data / 'indicadores')}
for domain in DOMAINS:
result[domain.upper() + '_DATABASE_URL'] = 'sqlite:///' + str(data / (domain + '.db'))
return result
def run(args, cwd, env):
subprocess.run([str(arg) for arg in args], cwd=cwd, env=env, check=True)
def verify_database_targets(uv, app, env, data):
"""Check the selected application's effective settings before any migration."""
code = """import os, sys
from pathlib import Path
from sqlalchemy.engine import make_url
from persistance.settings import settings
base = Path(sys.argv[1]).resolve()
for domain in ('cacu', 'cama', 'tea', 'governance'):
expected = base / (domain + '.db')
url = getattr(settings, domain + '_database_url')
parsed = make_url(url)
if (url != os.environ[domain.upper() + '_DATABASE_URL'] or parsed.drivername != 'sqlite'
or not parsed.database or Path(parsed.database) != expected or expected.is_symlink()
or expected.resolve().parent != base or not expected.is_file() or expected.stat().st_size != 0):
raise SystemExit('effective migration destination rejected: ' + domain)
print('Verified four new isolated SQLite migration targets')
"""
run([uv, 'run', '--no-sync', 'python', '-c', code, data], app / 'WebApi', env)
def systemd_unit(base, account, service, api_port, nginx):
work = base / 'application' / 'WebApi'
binary = work / '.venv' / 'bin'
name = base.name
common = f'''[Unit]\nDescription=ISSSTELEON native {service} {name}\nAfter=network.target\n'''
if service == 'worker':
common += f'After={name}-api.service\nRequires={name}-api.service\n'
if service == 'web':
common += f'After={name}-api.service\nRequires={name}-api.service\n'
command = {
'api': f'{binary}/gunicorn --bind 127.0.0.1:{api_port} --workers 2 --timeout 600 --access-logfile - webapi:create_app()',
'worker': f'{binary}/python -m webapi.indicadores_vivos',
'web': f'{nginx} -c {base}/nginx.conf -p {base}/',
}[service]
directory = base if service == 'web' else work
return common + f'''\n[Service]\nType=simple\nWorkingDirectory={directory}\nEnvironmentFile={base}/service.env\nExecStart={command}\nRestart=on-failure\nRestartSec=5\nNoNewPrivileges=true\nPrivateUsers=true\nPrivateTmp=true\nProtectSystem=strict\nReadWritePaths={base}/data\n\n[Install]\nWantedBy=default.target\n'''
def nginx_conf(base, port, api_port):
data = base / 'data'
return f'''worker_processes 1;\ndaemon off;\npid {data}/nginx.pid;\nerror_log stderr;\nevents {{ worker_connections 1024; }}\nhttp {{\n include /etc/nginx/mime.types;\n default_type application/octet-stream;\n access_log /dev/stdout;\n client_body_temp_path {data}/nginx-client;\n proxy_temp_path {data}/nginx-proxy;\n fastcgi_temp_path {data}/nginx-fastcgi;\n uwsgi_temp_path {data}/nginx-uwsgi;\n scgi_temp_path {data}/nginx-scgi;\n server {{\n listen {port};\n server_name _;\n root {base}/application/WebApp/dist/WebApp/browser;\n client_max_body_size 270m;\n location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) {{\n proxy_pass http://127.0.0.1:{api_port};\n proxy_set_header Host $host;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 600s;\n }}\n location ~* \\.(js|css)$ {{ add_header Cache-Control "public, max-age=31536000, immutable"; try_files $uri =404; }}\n location / {{ add_header Cache-Control "no-cache"; try_files $uri $uri/ /index.html; }}\n }}\n}}\n'''
def prepare(parent, record, archive_path, expected_digest, api_port, account, expected_hostname, tools):
"""Create a fresh instance; failure retains its data and prevents retries over it."""
validate_record(record)
if (not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,252}', expected_hostname)
or socket.gethostname().lower() != expected_hostname.lower()):
raise ValueError('host identity does not match the explicitly expected hostname')
parent = validate_parent(parent)
validate_service_account(account)
if expected_digest != record['bundle_sha256'] or digest(archive_path) != expected_digest:
raise ValueError('bundle digest does not match the independently supplied digest and record')
port = record['public_port']
if type(api_port) is not int or api_port != record['api_port']:
raise ValueError('API port does not match the validated release request')
check_port(port, True)
check_port(api_port, False)
base = parent / f'isssteleon-native-{port}'
base.mkdir(mode=0o750) # exclusive; no update or reuse
state = dict(record, status='preparing', phase='reserved', base=str(base), api_port=api_port,
account=account, hostname=expected_hostname, services=[f'{base.name}-{part}.service' for part in ('api', 'worker', 'web')])
metadata = base / 'installation.json'
try:
atomic_record(metadata, state)
(base / 'data').mkdir(mode=0o700)
extract_bundle(archive_path, base)
app = base / 'application'
env = environment(base)
for domain in DOMAINS:
path = base / 'data' / (domain + '.db')
with path.open('xb'):
pass
os.chmod(path, 0o600)
state.update(phase='dependencies')
atomic_record(metadata, state)
run([tools['uv'], 'sync', '--locked', '--no-dev', '--extra', 'sql-drivers'], app / 'WebApi', env)
run([tools['npm'], 'ci'], app / 'WebApp', env)
run([tools['npm'], 'run', 'build', '--', '--configuration', 'production'], app / 'WebApp', env)
if not (app / 'WebApp' / 'dist' / 'WebApp' / 'browser' / 'index.html').is_file():
raise ValueError('Angular distribution index is missing')
state.update(phase='verifying_migration_targets')
atomic_record(metadata, state)
verify_database_targets(tools['uv'], app, env, base / 'data')
state.update(phase='migrations')
atomic_record(metadata, state)
for domain in DOMAINS:
target = base / 'data' / (domain + '.db')
if target.is_symlink() or target.resolve().parent != (base / 'data').resolve() or target.stat().st_size != 0:
raise ValueError('migration target is not a new isolated database: ' + domain)
run([tools['uv'], 'run', '--no-sync', 'alembic', '-c', app / 'Persistance' / 'persistance' / domain / 'alembic.ini', 'upgrade', 'head'], app / 'WebApi', env)
service_env = {k: v for k, v in env.items() if k not in ('PATH', 'LANG', 'npm_config_cache', 'UV_CACHE_DIR')}
(base / 'service.env').write_text(''.join(f'{key}={value}\n' for key, value in sorted(service_env.items())), encoding='utf-8')
(base / 'nginx.conf').write_text(nginx_conf(base, port, api_port), encoding='utf-8')
units = base / 'units'
units.mkdir(mode=0o750)
for service in ('api', 'worker', 'web'):
(units / f'{base.name}-{service}.service').write_text(systemd_unit(base, account, service, api_port, tools['nginx']), encoding='utf-8')
run([tools['nginx'], '-t', '-c', base / 'nginx.conf', '-p', str(base) + '/'], base, env)
state.update(status='prepared', phase='awaiting_systemd_activation', prepared_at=int(time.time()))
atomic_record(metadata, state)
return state
except BaseException as exc:
state.update(status='failed', error=type(exc).__name__)
try:
atomic_record(metadata, state)
except OSError:
pass
raise
def available_tools():
result = {}
for name in ('uv', 'npm', 'nginx', 'tesseract'):
path = shutil.which(name)
if not path or not SAFE_PATH.fullmatch(path):
raise ValueError('missing or unsafe executable path: ' + name)
result[name] = path
languages = subprocess.run([result['tesseract'], '--list-langs'], capture_output=True, text=True, check=True).stdout.splitlines()
if not {'spa', 'eng'} <= set(languages):
raise ValueError('Tesseract requires spa and eng language data')
if not Path('/etc/nginx/mime.types').is_file():
raise ValueError('nginx mime.types is missing')
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--record', required=True, type=Path)
parser.add_argument('--bundle', required=True, type=Path)
parser.add_argument('--bundle-sha256', required=True)
parser.add_argument('--parent', required=True, type=Path)
parser.add_argument('--api-port', required=True, type=int)
parser.add_argument('--account', required=True)
parser.add_argument('--expected-hostname', required=True)
args = parser.parse_args()
if sys.platform != 'linux':
parser.error('native installation requires Linux')
try:
if Path('/.dockerenv').exists() or Path('/run/.containerenv').exists():
raise ValueError('run preparation on the selected host, not inside a container')
record = json.loads(args.record.read_text(encoding='utf-8'))
validate_record(record)
check_installer_files(Path(__file__).resolve().parent, record)
result = prepare(args.parent, record, args.bundle, args.bundle_sha256, args.api_port, args.account, args.expected_hostname, available_tools())
print(json.dumps(result, indent=2, sort_keys=True))
return 0
except (OSError, ValueError, subprocess.CalledProcessError, tarfile.TarError, json.JSONDecodeError) as exc:
print('Native preparation failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
-152
View File
@@ -1,152 +0,0 @@
#!/usr/bin/env python3
"""Deploy and verify a release through an explicitly configured non-root SSH account."""
import argparse
import json
from pathlib import Path
import re
import shlex
import shutil
import subprocess
import sys
import uuid
import time
import urllib.error
import verify
import install
FILES = ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py', 'release-record.json', 'release-source.tar.gz')
HOST = re.compile(r'^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$')
def ssh_options(identity, known_hosts):
return ['-i', str(identity), '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes',
'-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=' + str(known_hosts)]
def remote_command(arguments):
return shlex.join([str(part) for part in arguments])
def check_public(host, port, timeout=90):
"""Require the runner to reach both the application and proxied API."""
deadline = time.monotonic() + timeout
while True:
try:
status, body = verify.request(f'http://{host}:{port}/health')
health = json.loads(body)
index_status, index = verify.request(f'http://{host}:{port}/')
if status != 200 or not isinstance(health, dict) or health.get('status') != 'ok' or index_status != 200 or not index:
raise ValueError('public HTTP or proxied API health check failed')
return
except (OSError, ValueError, urllib.error.URLError, json.JSONDecodeError) as exc:
if time.monotonic() >= deadline:
raise ValueError('public endpoint is unavailable: ' + str(exc)) from exc
time.sleep(2)
def prepare(bundle_dir, digest, host, port, account, expected_hostname, parent, api_port, identity, known_hosts):
"""Use pinned host keys and create a unique staging directory without elevated privileges."""
bundle_dir = Path(bundle_dir).resolve()
identity, known_hosts = Path(identity).resolve(), Path(known_hosts).resolve()
if (not HOST.fullmatch(host) or not HOST.fullmatch(expected_hostname) or not install.NAME.fullmatch(account)
or account == 'root' or not 1 <= port <= 65535 or not identity.is_file() or not known_hosts.is_file()
or not install.SAFE_PATH.fullmatch(parent) or parent == '/' or '..' in Path(parent).parts):
raise ValueError('invalid explicit SSH endpoint, host key, account or parent')
files = [bundle_dir / name for name in FILES]
if any(not item.is_file() or item.is_symlink() for item in files):
raise ValueError('bundle or installer file is missing or symlinked')
record = json.loads((bundle_dir / 'release-record.json').read_text(encoding='utf-8'))
install.validate_record(record)
install.check_installer_files(bundle_dir, record)
if digest != record['bundle_sha256'] or install.digest(bundle_dir / 'release-source.tar.gz') != digest:
raise ValueError('bundle checksum mismatch')
if type(api_port) is not int or api_port != record['api_port']:
raise ValueError('API port does not match the validated release request')
ssh, scp = shutil.which('ssh'), shutil.which('scp')
if not ssh or not scp:
raise ValueError('ssh and scp are required')
endpoint = account + '@' + host
stage = parent.rstrip('/') + '/.release-' + uuid.uuid4().hex
options = ssh_options(identity, known_hosts)
# Check identity and containment remotely before making any files.
guard = '''import grp,os,pathlib,pwd,socket,subprocess,sys
parent,stage,account,host=sys.argv[1:]
p=pathlib.Path(parent)
resolved=p.resolve(strict=True)
docker=pathlib.Path('/srv/workingnarrative-dev')
entry=pwd.getpwuid(os.geteuid())
if str(resolved)!=parent or not p.is_dir() or p.stat().st_uid!=os.geteuid() or p.stat().st_mode & 0o022 or docker==resolved or docker in resolved.parents or socket.gethostname().lower()!=host.lower() or os.geteuid()==0 or entry.pw_name!=account:
raise SystemExit('remote identity or parent rejected')
groups=set(os.getgroups()) | set(os.getgrouplist(account,entry.pw_gid)) | {entry.pw_gid,os.getegid()}
privileged={0}
for name in ('docker','sudo','wheel'):
try:
privileged.add(grp.getgrnam(name).gr_gid)
except KeyError:
pass
if groups & privileged:
raise SystemExit('remote service account has privileged group membership')
runtime=pathlib.Path('/run/user') / str(os.geteuid())
if not runtime.is_dir() or not (runtime / 'bus').exists():
raise SystemExit('user manager runtime is unavailable')
env=dict(os.environ, HOME=entry.pw_dir, XDG_RUNTIME_DIR=str(runtime), DBUS_SESSION_BUS_ADDRESS='unix:path=' + str(runtime / 'bus'))
linger=subprocess.run(['loginctl','show-user',account,'--property=Linger','--value'],env=env,text=True,capture_output=True,check=True)
if linger.stdout.strip().lower() != 'yes':
raise SystemExit('user lingering is not enabled')
subprocess.run(['systemctl','--user','show-environment'],env=env,capture_output=True,check=True)
os.mkdir(stage,0o700)
'''
subprocess.run([ssh, *options, '-p', str(port), endpoint,
remote_command(['python3', '-c', guard, parent, stage, account, expected_hostname])], check=True)
print('Remote staging directory:', stage, flush=True)
subprocess.run([scp, *options, '-P', str(port), *map(str, files), endpoint + ':' + stage + '/'], check=True)
command = ['python3', stage + '/install.py', '--record', stage + '/release-record.json',
'--bundle', stage + '/release-source.tar.gz', '--bundle-sha256', digest,
'--parent', parent, '--account', account, '--expected-hostname', expected_hostname,
'--api-port', str(api_port)]
subprocess.run([ssh, *options, '-p', str(port), endpoint, remote_command(command)], check=True)
instance = parent.rstrip('/') + '/isssteleon-native-' + str(record['public_port'])
def remote_run(args, check=True):
return subprocess.run([ssh, *options, '-p', str(port), endpoint, remote_command(args)], check=check)
remote_run(['python3', stage + '/activate.py', instance])
remote_run(['python3', stage + '/verify.py', instance, '--wait-seconds', '180'])
try:
check_public(host, record['public_port'])
except (OSError, ValueError) as exc:
try:
remote_run(['python3', stage + '/verify.py', instance, '--public-result', 'failed', '--wait-seconds', '0'], check=False)
except OSError:
pass
raise exc
remote_run(['python3', stage + '/verify.py', instance, '--public-result', 'ok', '--wait-seconds', '0'])
return stage
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--bundle-dir', required=True, type=Path)
parser.add_argument('--bundle-sha256', required=True)
parser.add_argument('--host', required=True)
parser.add_argument('--ssh-port', required=True, type=int)
parser.add_argument('--account', required=True)
parser.add_argument('--expected-hostname', required=True)
parser.add_argument('--parent', required=True)
parser.add_argument('--api-port', required=True, type=int)
parser.add_argument('--identity', required=True, type=Path)
parser.add_argument('--known-hosts', required=True, type=Path)
args = parser.parse_args()
try:
prepare(args.bundle_dir, args.bundle_sha256, args.host, args.ssh_port, args.account,
args.expected_hostname, args.parent, args.api_port, args.identity, args.known_hosts)
print('Native deployment is active and public HTTP checks passed.')
return 0
except (OSError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
print('Remote preparation failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
-168
View File
@@ -1,168 +0,0 @@
#!/usr/bin/env python3
"""Resolve a published institutional release without deploying it."""
import json
import hashlib
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import source
import bundle
import urllib.error
import urllib.parse
import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[2]
SERVER = 'http://10.0.10.41:3000'
REPOSITORY = 'ISSSTELEON/WorkingNarrative'
ORIGIN = SERVER + '/' + REPOSITORY + '.git'
SHA = re.compile(r'^[0-9a-f]{40}$')
def git(root, *args):
return subprocess.run(['git', '-C', str(root), *args], check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
def validate_tag(tag):
if not tag or tag.startswith(('-', 'refs/')) or re.fullmatch(r'[0-9a-fA-F]{40}', tag):
raise ValueError('tag must be an unambiguous tag name')
subprocess.run(['git', 'check-ref-format', 'refs/tags/' + tag], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return tag
def validate_port(port):
if not re.fullmatch(r'[0-9]{1,5}', port) or not 1024 <= int(port) <= 65535:
raise ValueError('port must be an integer from 1024 to 65535')
return int(port)
def dispatch(root, env):
ref, name, sha = (env.get('DISPATCH_REF', ''), env.get('DISPATCH_REF_NAME', ''), env.get('DISPATCH_SHA', ''))
if (env.get('DISPATCH_REPOSITORY') != REPOSITORY or env.get('DISPATCH_SERVER', '').rstrip('/') != SERVER
or env.get('DISPATCH_REF_TYPE') != 'branch' or not name or ref != 'refs/heads/' + name
or not SHA.fullmatch(sha)):
raise ValueError('invalid workflow dispatch identity')
subprocess.run(['git', 'check-ref-format', ref], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if git(root, 'rev-parse', 'HEAD') != sha or git(root, 'remote', 'get-url', 'origin') not in (ORIGIN, ORIGIN.removesuffix('.git')):
raise ValueError('workflow checkout identity mismatch')
return {'installer_ref': ref, 'installer_sha': sha}
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def release(tag, token):
if not token:
raise ValueError('Gitea token is required')
url = SERVER + '/api/v1/repos/' + REPOSITORY + '/releases/tags/' + urllib.parse.quote(tag, safe='')
req = urllib.request.Request(url, headers={'Authorization': 'token ' + token, 'Accept': 'application/json'})
with urllib.request.build_opener(NoRedirect).open(req, timeout=15) as response:
data = json.load(response)
if (not isinstance(data, dict) or type(data.get('id')) is not int or data['id'] <= 0
or data.get('tag_name') != tag or data.get('draft') is not False
or not data.get('published_at')):
raise ValueError('tag does not identify a published release')
return {'release_id': data['id'], 'tag': tag}
def resolve(root, tag, port, api_port, env):
validate_tag(tag)
port = validate_port(port)
api_port = validate_port(api_port)
if port == api_port:
raise ValueError('public and API ports must differ')
installer = dispatch(root, env)
first = release(tag, env.get('RELEASE_TOKEN', ''))
ref = 'refs/deploy-terminal/' + uuid.uuid4().hex
try:
git(root, 'fetch', '--no-tags', 'origin', '+refs/tags/' + tag + ':' + ref)
object_sha = git(root, 'rev-parse', '--verify', ref)
commit = git(root, 'rev-parse', '--verify', ref + '^{commit}')
if not SHA.fullmatch(object_sha) or not SHA.fullmatch(commit):
raise ValueError('invalid fetched tag object or commit')
# A remote tag changed during resolution must not be silently accepted.
lines = git(root, 'ls-remote', '--refs', 'origin', 'refs/tags/' + tag).splitlines()
if lines != [object_sha + '\trefs/tags/' + tag]:
raise ValueError('remote tag changed during resolution')
if release(tag, env.get('RELEASE_TOKEN', '')) != first:
raise ValueError('release changed during resolution')
return dict(first, **installer, tag_object=object_sha, application_sha=commit, public_port=port, api_port=api_port)
finally:
git(root, 'update-ref', '-d', ref)
def prepare_source(root, record, output=None):
"""Fetch the same tag again into a disposable checkout and verify gitlinks."""
ref = 'refs/deploy-terminal/' + uuid.uuid4().hex
try:
git(root, 'fetch', '--no-tags', 'origin', '+refs/tags/' + record['tag'] + ':' + ref)
if (git(root, 'rev-parse', '--verify', ref) != record['tag_object']
or git(root, 'rev-parse', '--verify', ref + '^{commit}') != record['application_sha']):
raise ValueError('tag changed before source preparation')
with tempfile.TemporaryDirectory(prefix='isssteleon-release-') as temporary:
checkout = Path(temporary)
subprocess.run(['git', 'init', '--quiet', str(checkout)], check=True)
git(checkout, 'fetch', '--no-tags', str(root), ref)
git(checkout, 'checkout', '--quiet', '--detach', record['application_sha'])
if git(checkout, 'rev-parse', 'HEAD') != record['application_sha']:
raise ValueError('application checkout mismatch')
manifest = source.checkout_pinned(checkout)
if output is not None:
record['bundle_sha256'] = bundle.export(checkout, manifest, output)
return manifest
finally:
git(root, 'update-ref', '-d', ref)
def installer_manifest(root, sha):
"""Bind exported installer scripts to the dispatched committed revision."""
manifest = {}
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
relative = '.gitea/deploy-terminal/' + name
committed = subprocess.run(['git', '-C', str(root), 'show', sha + ':' + relative],
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout
if (Path(root) / relative).read_bytes() != committed:
raise ValueError('installer file differs from dispatched revision: ' + name)
manifest[name] = hashlib.sha256(committed).hexdigest()
return manifest
def revalidate(root, record, token):
"""Fail if the tag or publication changed while the bundle was being built."""
tag = validate_tag(record['tag'])
lines = git(root, 'ls-remote', '--refs', 'origin', 'refs/tags/' + tag).splitlines()
if lines != [record['tag_object'] + '\trefs/tags/' + tag]:
raise ValueError('remote tag changed before bundle publication')
if release(tag, token) != {'tag': tag, 'release_id': record['release_id']}:
raise ValueError('release changed before bundle publication')
def main():
try:
record = resolve(ROOT, os.environ.get('REQUESTED_TAG', ''), os.environ.get('REQUESTED_PORT', ''),
os.environ.get('REQUESTED_API_PORT', ''), os.environ)
output = Path(os.environ.get('RELEASE_OUTPUT', 'release-source.tar.gz'))
record['installer_files'] = installer_manifest(ROOT, record['installer_sha'])
record['gitlinks'] = prepare_source(ROOT, record, output)
revalidate(ROOT, record, os.environ.get('RELEASE_TOKEN', ''))
bundle.write_record(output.with_name('release-record.json'), record)
print(json.dumps(record, sort_keys=True), flush=True)
print('Release bundle prepared for automated native deployment.', flush=True)
return 0
except (ValueError, subprocess.CalledProcessError, OSError, urllib.error.URLError, json.JSONDecodeError) as exc:
print('Release resolution failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
-91
View File
@@ -1,91 +0,0 @@
#!/usr/bin/env python3
"""Check out only institutional application gitlinks at their committed SHAs."""
import os
import base64
from pathlib import Path
import re
import subprocess
ORIGINS = {
'ISSSTELEON': 'ISSSTELEON',
'ISSSTELEON/WebApi': 'WebApi',
'ISSSTELEON/WebApp': 'WebApp',
'ISSSTELEON/models': 'models',
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
}
SHA = re.compile(r'^[0-9a-f]{40}$')
def git(repo, *args, binary=False):
env = os.environ.copy()
token = env.get('RELEASE_TOKEN')
if token:
try:
count = int(env.get('GIT_CONFIG_COUNT', '0'))
except ValueError as exc:
raise ValueError('invalid inherited Git configuration count') from exc
if not 0 <= count < 32:
raise ValueError('invalid inherited Git configuration count')
encoded = base64.b64encode(('x-access-token:' + token).encode()).decode('ascii')
env['GIT_CONFIG_KEY_' + str(count)] = 'http.http://10.0.10.41:3000/ISSSTELEON/.extraheader'
env['GIT_CONFIG_VALUE_' + str(count)] = 'AUTHORIZATION: basic ' + encoded
env['GIT_CONFIG_COUNT'] = str(count + 1)
env['GIT_TERMINAL_PROMPT'] = '0'
result = subprocess.run(['git', '-C', str(repo), *args], check=True, env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=not binary)
return result.stdout if binary else result.stdout.strip()
def gitlinks(repo):
entries = git(repo, 'ls-tree', '-rz', '--full-tree', 'HEAD', binary=True)
links = {}
for entry in entries.split(b'\0'):
if not entry:
continue
meta, name = entry.split(b'\t', 1)
mode, kind, sha = meta.decode('ascii').split()
if mode != '160000':
continue
path = os.fsdecode(name)
if (kind != 'commit' or not SHA.fullmatch(sha) or path.startswith('/')
or any(part in ('', '.', '..') for part in path.split('/')) or '\\' in path):
raise ValueError('unsafe gitlink entry')
links[path] = sha
return links
def checkout_pinned(root):
"""Ignore unrelated top-level submodules; reject unknown application origins."""
root = Path(root)
outer = gitlinks(root)
if 'ISSSTELEON' not in outer:
raise ValueError('application gitlink is missing')
manifest = {}
def visit(repo, path, prefix, sha):
full = prefix + '/' + path if prefix else path
if full not in ORIGINS:
raise ValueError('unrecognized application gitlink: ' + full)
config = git(repo, 'config', '-f', '.gitmodules', '--get-regexp', r'^submodule\..*\.path$')
matches = []
for line in config.splitlines():
parts = line.split(None, 1)
if len(parts) == 2 and parts[1] == path:
matches.append(parts[0][len('submodule.'):-len('.path')])
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
raise ValueError('ambiguous submodule mapping: ' + full)
name = matches[0]
origin = 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + ORIGINS[full] + '.git'
if git(repo, 'config', '-f', '.gitmodules', '--get', f'submodule.{name}.url') != origin:
raise ValueError('untrusted submodule origin: ' + full)
git(repo, '-c', 'protocol.file.allow=never', '-c', f'submodule.{name}.url={origin}',
'submodule', 'update', '--init', '--checkout', '--', path)
child = repo / path
if git(child, 'rev-parse', 'HEAD') != sha:
raise ValueError('gitlink checkout mismatch: ' + full)
manifest[full] = sha
for nested, child_sha in gitlinks(child).items():
visit(child, nested, full, child_sha)
visit(root, 'ISSSTELEON', '', outer['ISSSTELEON'])
return manifest
-94
View File
@@ -1,94 +0,0 @@
"""Test user-service activation and failure handling with isolated unit directories."""
import json
from pathlib import Path
import subprocess
import tempfile
import types
import unittest
from unittest.mock import patch
import activate
import install
class ActivationTests(unittest.TestCase):
"""Temporary files and a mocked user manager stand in for systemd and the host."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name).resolve()
self.base = self.root / 'isssteleon-native-18090'
self.base.mkdir()
(self.base / 'data').mkdir()
(self.base / 'data' / 'cacu.db').write_bytes(b'existing')
(self.base / 'units').mkdir()
self.names = [f'isssteleon-native-18090-{part}.service' for part in ('api', 'worker', 'web')]
for name in self.names:
(self.base / 'units' / name).write_text('[Service]\n', encoding='utf-8')
self.unit_dir = self.root / 'user-units'
self.unit_dir.mkdir()
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090,
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
'bundle_sha256': 'd' * 64, 'installer_files': {name: 'e' * 64 for name in install.INSTALLER_FILES},
'gitlinks': {name: 'f' * 40 for name in install.REQUIRED_LINKS},
'status': 'prepared', 'base': str(self.base), 'api_port': 28090,
'account': 'wnnative', 'services': self.names}
(self.base / 'installation.json').write_text(json.dumps(self.record), encoding='utf-8')
self.commands = []
self.env = {'HOME': str(self.root)}
def fake_command(self, args, env, check=True):
self.commands.append(args)
if args[0] == 'loginctl': return types.SimpleNamespace(stdout='yes\n', returncode=0)
if '--property=LoadState' in args: return types.SimpleNamespace(stdout='not-found\n', returncode=0)
return types.SimpleNamespace(stdout='', returncode=0)
def fake_symlink(self, source, dest):
Path(dest).write_text(str(source), encoding='utf-8')
def run_activate(self):
with patch.object(activate, 'units_directory', return_value=self.unit_dir), patch.object(activate, 'command', side_effect=self.fake_command), patch.object(activate.os, 'symlink', side_effect=self.fake_symlink):
return activate.activate(self.base, self.record, self.env)
def test_starts_only_new_user_units(self):
"""Activation enables the three instance units in the user manager without root operations."""
result = self.run_activate()
self.assertEqual(result['status'], 'started')
enabled = [cmd for cmd in self.commands if 'enable' in cmd]
self.assertEqual(len(enabled), 3)
self.assertTrue(all(cmd[:2] == ['systemctl', '--user'] for cmd in enabled))
self.assertEqual((self.base / 'data' / 'cacu.db').read_bytes(), b'existing')
def test_existing_unit_is_never_replaced(self):
"""An existing user unit must stop activation without modifying the existing unit or data."""
existing = self.unit_dir / self.names[0]
existing.write_text('keep', encoding='utf-8')
with self.assertRaises(ValueError): self.run_activate()
self.assertEqual(existing.read_text(), 'keep')
self.assertFalse(any('enable' in cmd for cmd in self.commands))
def test_linger_is_required(self):
"""A user manager without lingering must fail before creating or starting a unit."""
def no_linger(args, env, check=True):
return types.SimpleNamespace(stdout='no\n', returncode=0)
with patch.object(activate, 'command', side_effect=no_linger), patch.object(activate, 'units_directory') as units:
with self.assertRaises(ValueError): activate.activate(self.base, self.record, self.env)
units.assert_not_called()
def test_start_failure_stops_only_new_units_and_keeps_data(self):
"""A failed startup must mark failure and stop the newly linked units while retaining data."""
def fail_start(args, env, check=True):
if 'enable' in args and args[-1].endswith('-worker.service'):
raise subprocess.CalledProcessError(1, args)
return self.fake_command(args, env, check)
with patch.object(activate, 'units_directory', return_value=self.unit_dir), patch.object(activate, 'command', side_effect=fail_start), patch.object(activate.os, 'symlink', side_effect=self.fake_symlink):
with self.assertRaises(subprocess.CalledProcessError): activate.activate(self.base, self.record, self.env)
state = json.loads((self.base / 'installation.json').read_text())
self.assertEqual(state['status'], 'activation_failed')
self.assertTrue(any(cmd[:4] == ['systemctl', '--user', 'disable', '--now'] for cmd in self.commands))
self.assertEqual((self.base / 'data' / 'cacu.db').read_bytes(), b'existing')
if __name__ == '__main__':
unittest.main()
-65
View File
@@ -1,65 +0,0 @@
"""Verify bundles export committed trees, excluding working files and Git metadata."""
import hashlib
from pathlib import Path
import subprocess
import tarfile
import tempfile
import unittest
import bundle
def git(repo, *args):
return subprocess.run(['git', '-C', str(repo), *args], check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
class BundleTests(unittest.TestCase):
"""Two small temporary Git repositories model the application and a pinned child."""
def test_export_uses_git_objects_and_pinned_nested_checkout(self):
"""Uncommitted changes and untracked files cannot enter a release archive."""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
app = root / 'ISSSTELEON'
child = app / 'WebApi'
for repo in (app, child):
repo.mkdir(parents=True, exist_ok=True)
git(repo, 'init', '--quiet')
git(repo, 'config', 'user.name', 'Fixture')
git(repo, 'config', 'user.email', 'fixture@example.invalid')
tracked = repo / ('Core/tracked.txt' if repo == app else 'tracked.txt')
tracked.parent.mkdir(parents=True, exist_ok=True)
tracked.write_text('committed', encoding='utf-8')
git(repo, 'add', str(tracked.relative_to(repo)))
git(repo, 'commit', '-m', 'fixture')
manifest = {'ISSSTELEON': git(app, 'rev-parse', 'HEAD'), 'ISSSTELEON/WebApi': git(child, 'rev-parse', 'HEAD')}
(child / 'tracked.txt').write_text('modified', encoding='utf-8')
(child / 'private.txt').write_text('untracked', encoding='utf-8')
output = root / 'bundle.tar.gz'
sha = bundle.export(root, manifest, output)
self.assertEqual(sha, hashlib.sha256(output.read_bytes()).hexdigest())
duplicate = root / 'duplicate.tar.gz'
self.assertEqual(bundle.export(root, manifest, duplicate), sha)
self.assertEqual(output.read_bytes(), duplicate.read_bytes())
with tarfile.open(output) as archive:
self.assertEqual(archive.extractfile('application/WebApi/tracked.txt').read(), b'committed')
self.assertNotIn('application/WebApi/private.txt', archive.getnames())
self.assertFalse(any('.git/' in name for name in archive.getnames()))
def test_unknown_checkout_is_rejected(self):
"""A child checkout at a different SHA cannot be archived under a recorded gitlink."""
with tempfile.TemporaryDirectory() as tmp:
repo = Path(tmp) / 'ISSSTELEON'
repo.mkdir()
git(repo, 'init', '--quiet')
git(repo, 'config', 'user.name', 'Fixture')
git(repo, 'config', 'user.email', 'fixture@example.invalid')
(repo / 'file').write_text('data', encoding='utf-8')
git(repo, 'add', 'file')
git(repo, 'commit', '-m', 'fixture')
with self.assertRaises(ValueError):
bundle.export(Path(tmp), {'ISSSTELEON': '0' * 40}, Path(tmp) / 'out.tar.gz')
if __name__ == '__main__':
unittest.main()
-297
View File
@@ -1,297 +0,0 @@
"""Test isolated preparation and health verification with temporary release bundles and fake commands."""
import hashlib
import io
import json
import os
import subprocess
from pathlib import Path
import socket
import sys
import tarfile
import tempfile
import types
import unittest
from unittest.mock import patch
import install
import verify
class InstallerTests(unittest.TestCase):
"""A temporary directory represents an empty dedicated installation parent."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.bundle = self.root / 'release.tar.gz'
with tarfile.open(self.bundle, 'w:gz') as archive:
files = [('application/WebApi/pyproject.toml', b'[project]'),
('application/WebApi/uv.lock', b''),
('application/WebApi/webapi/indicadores_vivos.py', b''),
('application/WebApp/package.json', b'{}'),
('application/WebApp/package-lock.json', b'{}')]
files += [(f'application/Persistance/persistance/{domain}/alembic.ini', b'')
for domain in install.DOMAINS]
for name, content in files:
info = tarfile.TarInfo(name)
info.size = len(content)
archive.addfile(info, io.BytesIO(content))
self.digest = hashlib.sha256(self.bundle.read_bytes()).hexdigest()
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090, 'api_port': 28090,
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
'bundle_sha256': self.digest,
'installer_files': {name: 'e' * 64 for name in install.INSTALLER_FILES},
'gitlinks': {name: 'd' * 40 for name in install.REQUIRED_LINKS}}
self.account = 'wnnative'
self.hostname = socket.gethostname()
self.tools = {'uv': '/usr/bin/uv', 'npm': '/usr/bin/npm', 'nginx': '/usr/sbin/nginx'}
self.calls = []
self.real_check_port = install.check_port
self.real_validate_parent = install.validate_parent
self.real_validate_service_account = install.validate_service_account
self.patches = [patch.object(install, 'validate_parent', return_value=self.root),
patch.object(install, 'validate_service_account'),
patch.object(install.os, 'geteuid', return_value=1234, create=True),
patch.dict(sys.modules, {'pwd': types.SimpleNamespace(getpwuid=lambda uid: types.SimpleNamespace(pw_name=self.account))}),
patch.object(install, 'check_port'), patch.object(install, 'run', side_effect=self.fake_run)]
for item in self.patches:
item.start()
self.addCleanup(item.stop)
def fake_run(self, args, cwd, env):
self.calls.append((list(map(str, args)), Path(cwd), dict(env)))
if args[1:3] == ['run', 'build']:
index = Path(cwd) / 'dist' / 'WebApp' / 'browser' / 'index.html'
index.parent.mkdir(parents=True)
index.write_text('app', encoding='utf-8')
if 'alembic' in args:
domain = next(part for part in install.DOMAINS if part in str(args[-3]))
self.assertTrue(env[domain.upper() + '_DATABASE_URL'].replace('\\', '/').endswith('/data/' + domain + '.db'))
(self.root / 'isssteleon-native-18090' / 'data' / (domain + '.db')).write_bytes(b'migrated')
def prepare(self, api_port=28090):
return install.prepare(self.root, self.record, self.bundle, self.digest, api_port, self.account, self.hostname, self.tools)
def test_new_installation_prepares_locked_build_migrations_and_units(self):
"""A new instance must use locked builds, four isolated databases and three inactive unit files."""
result = self.prepare()
base = self.root / 'isssteleon-native-18090'
self.assertEqual(result['status'], 'prepared')
self.assertEqual([item[0][1:3] for item in self.calls[:3]], [['sync', '--locked'], ['ci'], ['run', 'build']])
self.assertEqual(sum('alembic' in args for args, _, _ in self.calls), 4)
guard_index = next(i for i, (args, _, _) in enumerate(self.calls) if args[1:4] == ['run', '--no-sync', 'python'])
first_migration = next(i for i, (args, _, _) in enumerate(self.calls) if 'alembic' in args)
self.assertLess(guard_index, first_migration)
for domain in install.DOMAINS:
self.assertEqual((base / 'data' / (domain + '.db')).read_bytes(), b'migrated')
self.assertEqual(len(list((base / 'units').glob('*.service'))), 3)
api = (base / 'units' / 'isssteleon-native-18090-api.service').read_text()
worker = (base / 'units' / 'isssteleon-native-18090-worker.service').read_text()
self.assertIn('127.0.0.1:28090', api)
self.assertNotIn('User=', api)
self.assertIn('WantedBy=default.target', api)
self.assertIn('PrivateUsers=true', api)
self.assertIn('webapi.indicadores_vivos', worker)
self.assertIn('proxy_pass http://127.0.0.1:28090', (base / 'nginx.conf').read_text())
self.assertFalse(any('systemctl' in args for args, _, _ in self.calls))
def test_custom_api_port_reaches_configuration_record_and_health_checks(self):
"""The selected API port must drive loopback Gunicorn, nginx, metadata and verification."""
self.record['api_port'] = 31001
result = self.prepare(31001)
base = self.root / 'isssteleon-native-18090'
self.assertEqual(result['api_port'], 31001)
self.assertEqual(json.loads((base / 'installation.json').read_text())['api_port'], 31001)
self.assertIn('127.0.0.1:31001', (base / 'units' / 'isssteleon-native-18090-api.service').read_text())
self.assertIn('proxy_pass http://127.0.0.1:31001', (base / 'nginx.conf').read_text())
urls = []
def request(url):
urls.append(url)
return 200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>'
verify.check(dict(result, status='started'), command=lambda *a, **k: types.SimpleNamespace(returncode=0), get=request)
self.assertIn('http://127.0.0.1:31001/health', urls)
self.assertIn('http://127.0.0.1:18090/health', urls)
def test_api_port_mismatch_stops_before_creating_instance(self):
"""A changed API port must not override the port recorded in the validated release request."""
with self.assertRaises(ValueError): self.prepare(31001)
self.assertFalse((self.root / 'isssteleon-native-18090').exists())
self.assertEqual(self.calls, [])
def test_existing_instance_is_never_overwritten_or_migrated(self):
"""A repeated installation must reject the existing directory and preserve data."""
self.prepare()
marker = self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db'
before = marker.read_bytes()
call_count = len(self.calls)
with self.assertRaises(FileExistsError):
self.prepare()
self.assertEqual(marker.read_bytes(), before)
self.assertEqual(len(self.calls), call_count)
def test_digest_mismatch_and_port_conflict_stop_before_reservation(self):
"""Wrong source integrity or occupied ports must not create an installation directory."""
with self.assertRaises(ValueError):
install.prepare(self.root, self.record, self.bundle, '0' * 64, 28090, self.account, self.hostname, self.tools)
with patch.object(install, 'check_port', side_effect=ValueError('occupied')):
with self.assertRaises(ValueError): self.prepare()
self.assertFalse((self.root / 'isssteleon-native-18090').exists())
def test_partial_failure_preserves_data_and_rejects_retry(self):
"""A build error must leave a failed record and data rather than erase or reuse it."""
with patch.object(install, 'run', side_effect=RuntimeError('build failed')):
with self.assertRaises(RuntimeError): self.prepare()
base = self.root / 'isssteleon-native-18090'
state = json.loads((base / 'installation.json').read_text())
self.assertEqual(state['status'], 'failed')
self.assertTrue((base / 'data' / 'cacu.db').exists())
with self.assertRaises(FileExistsError): self.prepare()
def test_effective_target_guard_executes_and_rejects_mismatch(self):
"""The guard must inspect effective settings in a separate Python process without migrating files."""
data = self.root / 'guard-data'
data.mkdir()
for domain in install.DOMAINS:
(data / (domain + '.db')).touch()
env = dict(os.environ)
env.update(install.environment(self.root))
for domain in install.DOMAINS:
env[domain.upper() + '_DATABASE_URL'] = 'sqlite:///' + str(data / (domain + '.db'))
captured = []
with patch.object(install, 'run', side_effect=lambda args, cwd, env: captured.append(args)):
install.verify_database_targets('/usr/bin/uv', self.root, env, data)
code = captured[0][-2]
bootstrap = """import os, sys, types
root = types.ModuleType('persistance')
settings_module = types.ModuleType('persistance.settings')
settings_module.settings = types.SimpleNamespace(**{d + '_database_url': os.environ[d.upper() + '_DATABASE_URL'] for d in ('cacu','cama','tea','governance')})
if os.environ.get('FIXTURE_MISMATCH'):
settings_module.settings.cacu_database_url = 'sqlite:////outside/data.db'
sys.modules['persistance'] = root
sys.modules['persistance.settings'] = settings_module
sqlalchemy = types.ModuleType('sqlalchemy')
engine = types.ModuleType('sqlalchemy.engine')
engine.make_url = lambda url: types.SimpleNamespace(drivername='sqlite', database=url[len('sqlite:///'):])
sys.modules['sqlalchemy'] = sqlalchemy
sys.modules['sqlalchemy.engine'] = engine
"""
ok = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=env, capture_output=True)
self.assertEqual(ok.returncode, 0, ok.stderr)
mismatch = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=dict(env, FIXTURE_MISMATCH='1'), capture_output=True)
self.assertNotEqual(mismatch.returncode, 0)
(data / 'tea.db').write_bytes(b'existing')
occupied = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=env, capture_output=True)
self.assertNotEqual(occupied.returncode, 0)
self.assertEqual((data / 'tea.db').read_bytes(), b'existing')
def test_effective_target_guard_failure_blocks_all_migrations(self):
"""An application settings mismatch must stop the installer before any Alembic command."""
def reject_guard(args, cwd, env):
self.fake_run(args, cwd, env)
if args[1:4] == ['run', '--no-sync', 'python']:
raise RuntimeError('effective database URL mismatch')
with patch.object(install, 'run', side_effect=reject_guard), self.assertRaises(RuntimeError):
self.prepare()
self.assertFalse(any('alembic' in args for args, _, _ in self.calls))
record = json.loads((self.root / 'isssteleon-native-18090' / 'installation.json').read_text())
self.assertEqual(record['phase'], 'verifying_migration_targets')
self.assertEqual(record['status'], 'failed')
def test_migration_rejects_nonempty_target(self):
"""Unexpected existing database contents must stop migrations rather than touch the data."""
def inject(args, cwd, env):
self.fake_run(args, cwd, env)
if args[1:3] == ['run', 'build']:
(self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db').write_bytes(b'existing')
with patch.object(install, 'run', side_effect=inject), self.assertRaises(ValueError): self.prepare()
self.assertEqual((self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db').read_bytes(), b'existing')
self.assertFalse(any('alembic' in args for args, _, _ in self.calls))
def test_install_parent_must_be_private_and_account_owned(self):
"""A parent writable by another account cannot hold a trusted fresh installation."""
for owner, mode in [(9999, 0o750), (1234, 0o770), (1234, 0o757)]:
parent = types.SimpleNamespace(stat=lambda: types.SimpleNamespace(st_uid=owner, st_mode=mode))
with self.subTest(owner=owner, mode=mode), self.assertRaises(ValueError):
install.require_private_parent(parent)
parent = types.SimpleNamespace(stat=lambda: types.SimpleNamespace(st_uid=1234, st_mode=0o750))
install.require_private_parent(parent)
def test_privileged_service_group_memberships_are_rejected(self):
"""Reject Docker, sudo and root group membership even for non-root accounts."""
user = types.SimpleNamespace(pw_name=self.account, pw_gid=1001)
fake_pwd = types.SimpleNamespace(getpwuid=lambda uid: user)
fake_grp = types.SimpleNamespace(getgrnam=lambda name: types.SimpleNamespace(gr_gid={'docker': 998, 'sudo': 27, 'wheel': 10}[name]))
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[1001], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001, 998], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
with self.assertRaises(ValueError): install.validate_service_account(self.account)
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[27], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
with self.assertRaises(ValueError): install.validate_service_account(self.account)
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[1001], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
install.validate_service_account(self.account)
def test_host_mismatch_and_docker_root_are_rejected(self):
"""An unexpected host or Docker data parent cannot receive an installation."""
with self.assertRaises(ValueError):
install.prepare(self.root, self.record, self.bundle, self.digest, 28090, self.account, 'different-host', self.tools)
parent = self.root / 'docker'
parent.mkdir()
import re
real_validate_parent = self.real_validate_parent
with patch.object(install, 'SAFE_PATH', re.compile(r'^.+$')), patch.object(install, 'DOCKER_ROOT', parent), patch.object(install, 'validate_parent', wraps=real_validate_parent):
with self.assertRaises(ValueError): install.validate_parent(parent)
self.assertFalse((parent / 'isssteleon-native-18090').exists())
def test_archive_rejects_traversal_and_links(self):
"""Archive extraction must reject paths and links that escape the fresh instance."""
for name, member_type in [('../escape', tarfile.REGTYPE), ('application/link', tarfile.SYMTYPE)]:
path = self.root / ('bad-' + str(member_type[0]) + '.tar.gz')
with tarfile.open(path, 'w:gz') as archive:
info = tarfile.TarInfo(name)
info.type = member_type
if member_type == tarfile.SYMTYPE: info.linkname = '/tmp'
archive.addfile(info)
with self.subTest(name=name), self.assertRaises(ValueError):
install.extract_bundle(path, self.root / 'extract')
self.assertFalse((self.root / 'escape').exists())
def test_socket_conflict_detection(self):
"""A real loopback listener must prevent the installer from using the same API port."""
with socket.socket() as listener:
listener.bind(('127.0.0.1', 0))
listener.listen()
with patch.object(install, 'check_port', wraps=self.real_check_port):
with self.assertRaises(ValueError): install.check_port(listener.getsockname()[1], False)
with socket.socket() as listener:
listener.bind(('0.0.0.0', 0))
listener.listen()
with patch.object(install, 'check_port', wraps=self.real_check_port):
with self.assertRaises(ValueError): install.check_port(listener.getsockname()[1], True)
def test_failed_verification_is_recorded_and_can_be_retried(self):
"""A startup failure remains visible in the record and permits another health check."""
record = dict(self.prepare(), status='started')
base = self.root / 'isssteleon-native-18090'
(base / 'installation.json').write_text(json.dumps(record), encoding='utf-8')
with patch.object(sys, 'argv', ['verify.py', str(base), '--wait-seconds', '0']), patch.object(verify.activate, 'manager_environment', return_value={}), patch.object(verify, 'check', side_effect=ValueError('service failed')):
self.assertEqual(verify.main(), 1)
record = json.loads((base / 'installation.json').read_text())
self.assertEqual(record['status'], 'verification_failed')
self.assertIn('service failed', record['health']['error'])
ok = lambda *args, **kwargs: types.SimpleNamespace(returncode=0)
get = lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>')
self.assertEqual(verify.check(record, command=ok, get=get)['proxy_health'], 'ok')
def test_health_requires_all_services_and_spa_fallback(self):
"""Health fails if a unit is inactive or proxy and SPA checks do not match."""
record = dict(self.prepare(), status='started')
ok = lambda *args, **kwargs: types.SimpleNamespace(returncode=0)
get = lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>')
self.assertEqual(verify.check(record, command=ok, get=get)['proxy_health'], 'ok')
with self.assertRaises(ValueError):
verify.check(record, command=lambda *a, **k: types.SimpleNamespace(returncode=3), get=get)
with self.assertRaises(ValueError):
verify.check(record, command=ok, get=lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else url.encode()))
if __name__ == '__main__':
unittest.main()
-108
View File
@@ -1,108 +0,0 @@
"""Test explicit, pinned-key SSH preparation with synthetic artifacts and no network."""
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import install
import remote
class RemoteTests(unittest.TestCase):
"""Local fake files and mocked processes represent an authorized operator channel."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.dir = self.root / 'bundle'
self.dir.mkdir()
for name in install.INSTALLER_FILES:
(self.dir / name).write_bytes(('content:' + name).encode())
(self.dir / 'release-source.tar.gz').write_bytes(b'archive')
self.sha = hashlib.sha256(b'archive').hexdigest()
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090, 'api_port': 28090,
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
'bundle_sha256': self.sha,
'gitlinks': {name: 'd' * 40 for name in install.REQUIRED_LINKS},
'installer_files': {name: install.digest(self.dir / name) for name in install.INSTALLER_FILES}}
(self.dir / 'release-record.json').write_text(json.dumps(self.record), encoding='utf-8')
self.key = self.root / 'identity'
self.known = self.root / 'known_hosts'
self.key.write_text('fixture')
self.known.write_text('fixture')
def call(self, host='10.0.10.41', account='wnnative', api_port=28090):
return remote.prepare(self.dir, self.sha, host, 22, account, 'labserver',
'/srv/workingnarrative-native', api_port, self.key, self.known)
def test_only_explicit_nonprivileged_ssh_and_pinned_host_keys(self):
"""Preparation uses strict host-key checks and never invokes sudo or systemctl."""
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public') as public:
stage = self.call()
self.assertTrue(stage.startswith('/srv/workingnarrative-native/.release-'))
self.assertEqual(run.call_count, 6)
public.assert_called_once_with('10.0.10.41', 18090)
for call in run.call_args_list:
args = call.args[0]
self.assertIn('StrictHostKeyChecking=yes', args)
self.assertIn('BatchMode=yes', args)
self.assertNotIn('sudo', args)
self.assertNotIn('systemctl', args)
self.assertIn('install.py', str(run.call_args_list[2]))
self.assertIn('activate.py', str(run.call_args_list[3]))
self.assertIn('--public-result ok', str(run.call_args_list[-1]))
def test_requested_api_port_is_transferred_and_mismatch_rejected(self):
"""SSH must pass the exact recorded API port and reject any altered value before connection."""
with patch.object(remote.subprocess, 'run') as run:
with self.assertRaises(ValueError): self.call(api_port=31001)
run.assert_not_called()
self.record['api_port'] = 31001
(self.dir / 'release-record.json').write_text(json.dumps(self.record), encoding='utf-8')
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public'):
self.call(api_port=31001)
self.assertIn('--api-port 31001', str(run.call_args_list[2]))
def test_bad_endpoint_or_tampered_installer_never_connects(self):
"""Unsafe endpoint syntax or altered installer scripts must fail before SSH."""
with patch.object(remote.subprocess, 'run') as run:
with self.assertRaises(ValueError): self.call(host='host;evil')
with self.assertRaises(ValueError): self.call(account='root')
(self.dir / 'install.py').write_text('tampered', encoding='utf-8')
with self.assertRaises(ValueError): self.call()
run.assert_not_called()
def test_public_failure_fails_action_and_records_failure(self):
"""An unreachable public endpoint must report failure instead of a successful deployment."""
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public', side_effect=ValueError('unreachable')):
with self.assertRaises(ValueError): self.call()
self.assertIn('--public-result failed', str(run.call_args_list[-1]))
self.assertFalse(run.call_args_list[-1].kwargs['check'])
def test_activation_failure_prevents_public_success(self):
"""A failed service activation must stop before any public health check."""
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run', side_effect=[None, None, None, subprocess.CalledProcessError(1, 'ssh')]), patch.object(remote, 'check_public') as public:
with self.assertRaises(subprocess.CalledProcessError): self.call()
public.assert_not_called()
def test_public_probe_rejects_bad_health(self):
"""The public endpoint must serve both the WebApp and a healthy proxied API."""
responses = [(200, b'{"status":"ok"}'), (200, b'<html>app</html>')]
with patch.object(remote.verify, 'request', side_effect=responses):
remote.check_public('10.0.10.41', 18090, timeout=0)
with patch.object(remote.verify, 'request', side_effect=[(200, b'{"status":"bad"}'), (200, b'app')]):
with self.assertRaises(ValueError): remote.check_public('10.0.10.41', 18090, timeout=0)
def test_failed_remote_identity_check_never_uploads(self):
"""A failed remote guard must prevent copying or executing the installer."""
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'ssh')) as run:
with self.assertRaises(subprocess.CalledProcessError): self.call()
self.assertEqual(run.call_count, 1)
if __name__ == '__main__':
unittest.main()
-218
View File
@@ -1,218 +0,0 @@
"""Exercise release identity and fail-closed behavior using temporary Git repositories and fake API responses."""
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('resolve', Path(__file__).with_name('resolve.py'))
resolver = importlib.util.module_from_spec(spec)
spec.loader.exec_module(resolver)
def command(*args, cwd):
return subprocess.run(args, cwd=cwd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
class ResolutionTests(unittest.TestCase):
"""A bare local origin stands in for the institutional repository."""
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name)
self.origin = root / 'origin.git'
self.repo = root / 'repo'
command('git', 'init', '--bare', str(self.origin), cwd=root)
command('git', 'init', str(self.repo), cwd=root)
command('git', 'config', 'user.name', 'Test', cwd=self.repo)
command('git', 'config', 'user.email', 'test@example.invalid', cwd=self.repo)
(self.repo / 'file').write_text('test', encoding='utf-8')
command('git', 'add', 'file', cwd=self.repo)
command('git', 'commit', '-m', 'initial', cwd=self.repo)
self.sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
command('git', 'remote', 'add', 'origin', str(self.origin), cwd=self.repo)
command('git', 'tag', '-a', 'v1', '-m', 'release', cwd=self.repo)
command('git', 'push', 'origin', 'refs/tags/v1', cwd=self.repo)
self.env = {'DISPATCH_REF': 'refs/heads/dev', 'DISPATCH_REF_NAME': 'dev',
'DISPATCH_REF_TYPE': 'branch', 'DISPATCH_SHA': self.sha,
'DISPATCH_REPOSITORY': resolver.REPOSITORY, 'DISPATCH_SERVER': resolver.SERVER,
'RELEASE_TOKEN': 'test'}
def test_annotated_tag_resolves_to_commit_and_preserves_installer_identity(self):
"""Peeling must return the commit while retaining the distinct tag object and installer revision."""
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
record = resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
self.assertEqual(record['application_sha'], self.sha)
self.assertEqual(record['installer_sha'], self.sha)
self.assertNotEqual(record['tag_object'], self.sha)
self.assertEqual(record['release_id'], 7)
self.assertEqual(record['public_port'], 18090)
self.assertEqual(record['api_port'], 28090)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_invalid_or_missing_tags_and_ports_fail(self):
"""Invalid inputs and absent remote refs must fail before they can identify a deployment."""
for tag in ('', '-x', 'refs/tags/v1', 'bad..tag', 'a' * 40):
with self.subTest(tag=tag), self.assertRaises((ValueError, subprocess.CalledProcessError)):
resolver.validate_tag(tag)
for port in ('0', '65536', 'abc'):
with self.subTest(port=port), self.assertRaises(ValueError):
resolver.validate_port(port)
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'missing'}):
with self.assertRaises(subprocess.CalledProcessError):
resolver.resolve(self.repo, 'missing', '18090', '28090', self.env)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_custom_public_and_api_ports_are_recorded(self):
"""The release record must retain both operator-selected ports without replacing either default."""
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
record = resolver.resolve(self.repo, 'v1', '18123', '31001', self.env)
self.assertEqual(record['public_port'], 18123)
self.assertEqual(record['api_port'], 31001)
def test_both_requested_ports_are_validated_before_release_lookup(self):
"""Invalid, privileged, oversized or equal ports must fail before any network access."""
requests = [('0', '28090'), ('65536', '28090'), ('18090', '0'),
('18090', '65536'), ('18090', 'abc'), ('18090', '18090')]
with patch.object(resolver, 'dispatch') as dispatch, patch.object(resolver, 'release') as release:
for public, api in requests:
with self.subTest(public=public, api=api), self.assertRaises(ValueError):
resolver.resolve(self.repo, 'v1', public, api, self.env)
dispatch.assert_not_called()
release.assert_not_called()
def test_wrong_identity_is_rejected(self):
"""External repository, server and checkout identities cannot authorize resolution."""
with patch.object(resolver, 'ORIGIN', str(self.origin)):
for key, value in [('DISPATCH_REPOSITORY', 'other/repo'), ('DISPATCH_SERVER', 'http://evil'), ('DISPATCH_SHA', '0' * 40)]:
with self.subTest(key=key), self.assertRaises(ValueError):
resolver.dispatch(self.repo, dict(self.env, **{key: value}))
with self.assertRaises(ValueError):
resolver.dispatch(self.repo, self.env)
def test_release_change_fails_and_cleans_temporary_ref(self):
"""A changed release cannot pass the second check and failure removes its temporary ref."""
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', side_effect=[{'release_id': 7, 'tag': 'v1'}, {'release_id': 8, 'tag': 'v1'}]):
with self.assertRaises(ValueError):
resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_source_preparation_uses_selected_commit_in_a_disposable_tree(self):
"""Source preparation must retain the installer checkout and discard temporary application files."""
tag_object = command('git', 'rev-parse', 'refs/tags/v1', cwd=self.repo)
record = {'tag': 'v1', 'tag_object': tag_object, 'application_sha': self.sha}
captured = []
def inspect(checkout):
captured.append(checkout)
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=checkout), self.sha)
return {'ISSSTELEON': 'a' * 40}
with patch.object(resolver.source, 'checkout_pinned', side_effect=inspect):
self.assertEqual(resolver.prepare_source(self.repo, record), {'ISSSTELEON': 'a' * 40})
self.assertFalse(captured[0].exists())
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=self.repo), self.sha)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_source_preparation_rejects_changed_tag(self):
"""A tag that changes between resolution and source checkout cannot reach submodule preparation."""
record = {'tag': 'v1', 'tag_object': '0' * 40, 'application_sha': self.sha}
with patch.object(resolver.source, 'checkout_pinned') as checkout:
with self.assertRaises(ValueError):
resolver.prepare_source(self.repo, record)
checkout.assert_not_called()
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_remote_tag_change_fails_closed(self):
"""A tag moved after fetch must not be used even if the release remains published."""
original_git = resolver.git
def changed_git(root, *args):
if args[0] == 'ls-remote':
return '0' * 40 + '\trefs/tags/v1'
return original_git(root, *args)
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}), patch.object(resolver, 'git', side_effect=changed_git):
with self.assertRaises(ValueError):
resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
def test_application_and_installer_commits_are_independent(self):
"""A release can point to an older commit without changing the installer checkout."""
(self.repo / 'file').write_text('installer', encoding='utf-8')
command('git', 'commit', '-am', 'installer', cwd=self.repo)
installer_sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
env = dict(self.env, DISPATCH_SHA=installer_sha)
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
record = resolver.resolve(self.repo, 'v1', '18090', '28090', env)
self.assertEqual(record['application_sha'], self.sha)
self.assertEqual(record['installer_sha'], installer_sha)
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=self.repo), installer_sha)
def test_installer_files_match_dispatched_commit(self):
"""Every transferred installer script must be the committed installer revision."""
directory = self.repo / '.gitea' / 'deploy-terminal'
directory.mkdir(parents=True)
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
(directory / name).write_bytes(('fixture ' + name).encode())
command('git', 'add', '.gitea', cwd=self.repo)
command('git', 'commit', '-m', 'installer', cwd=self.repo)
sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
self.assertEqual(len(resolver.installer_manifest(self.repo, sha)), 6)
(directory / 'install.py').write_text('modified', encoding='utf-8')
with self.assertRaises(ValueError): resolver.installer_manifest(self.repo, sha)
def test_manual_workflow_prepares_bundle_and_release_record(self):
"""A manual dispatch must publish the resolved identity and source digest together."""
directory = self.repo / '.gitea' / 'deploy-terminal'
directory.mkdir(parents=True)
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
(directory / name).write_bytes(('fixture ' + name).encode())
command('git', 'add', '.gitea', cwd=self.repo)
command('git', 'commit', '-m', 'installer', cwd=self.repo)
installer_sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
output = self.repo.parent / 'artifact' / 'release-source.tar.gz'
output.parent.mkdir()
env = dict(self.env, DISPATCH_SHA=installer_sha, REQUESTED_TAG='v1', REQUESTED_PORT='18090', REQUESTED_API_PORT='28090', RELEASE_OUTPUT=str(output))
links = {'ISSSTELEON': 'a' * 40}
def export(checkout, manifest, path):
Path(path).write_bytes(b'fixture bundle')
return 'd' * 64
with patch.object(resolver, 'ROOT', self.repo), patch.object(resolver, 'ORIGIN', str(self.origin)), patch.dict(os.environ, env), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}), patch.object(resolver.source, 'checkout_pinned', return_value=links), patch.object(resolver.bundle, 'export', side_effect=export):
self.assertEqual(resolver.main(), 0)
record = json.loads((output.parent / 'release-record.json').read_text())
self.assertEqual(record['installer_sha'], installer_sha)
self.assertEqual(record['application_sha'], self.sha)
self.assertEqual(record['api_port'], 28090)
self.assertEqual(record['gitlinks'], links)
self.assertEqual(record['bundle_sha256'], 'd' * 64)
self.assertEqual(len(record['installer_files']), 6)
def test_publication_is_rechecked_after_packaging(self):
"""A release or tag changed during archive creation must not produce an artifact record."""
record = {'tag': 'v1', 'tag_object': 'a' * 40, 'release_id': 7}
with patch.object(resolver, 'git', return_value='b' * 40 + '\trefs/tags/v1'), patch.object(resolver, 'release') as release:
with self.assertRaises(ValueError): resolver.revalidate(self.repo, record, 'token')
release.assert_not_called()
with patch.object(resolver, 'git', return_value='a' * 40 + '\trefs/tags/v1'), patch.object(resolver, 'release', return_value={'tag': 'v1', 'release_id': 8}):
with self.assertRaises(ValueError): resolver.revalidate(self.repo, record, 'token')
def test_release_metadata_must_be_published_and_match_tag(self):
"""Drafts, missing publication times and mismatched tags must not qualify as published releases."""
class Response:
def __init__(self, data): self.data = json.dumps(data).encode()
def __enter__(self): return self
def __exit__(self, *args): pass
def read(self, *args): return self.data
class Opener:
def __init__(self, data): self.data = data
def open(self, req, timeout): return Response(self.data)
good = {'id': 1, 'tag_name': 'v1', 'draft': False, 'published_at': '2026-01-01T00:00:00Z'}
for change in ({'draft': True}, {'published_at': None}, {'tag_name': 'v2'}, {'id': True}):
with self.subTest(change=change), patch.object(resolver.urllib.request, 'build_opener', return_value=Opener(dict(good, **change))):
with self.assertRaises(ValueError): resolver.release('v1', 'token')
with patch.object(resolver.urllib.request, 'build_opener', return_value=Opener(good)):
self.assertEqual(resolver.release('v1', 'token')['release_id'], 1)
if __name__ == '__main__':
unittest.main()
-88
View File
@@ -1,88 +0,0 @@
"""Check pinned application traversal with synthetic Git-tree and configuration fixtures."""
from pathlib import Path
import unittest
import os
import types
from unittest.mock import patch
import source
class SourceTests(unittest.TestCase):
"""A mocked Git interface models one outer and one nested application repository."""
def setUp(self):
self.a, self.b = 'a' * 40, 'b' * 40
self.outer = Path('/fixture')
self.application = self.outer / 'ISSSTELEON'
self.api = self.application / 'WebApi'
self.calls = []
def fake_git(self, repo, *args, binary=False):
repo = Path(repo)
self.calls.append((repo, args))
if args[:1] == ('ls-tree',):
if repo == self.outer:
return (f'160000 commit {self.a}\tISSSTELEON\0' + f'160000 commit {self.b}\tdev-data\0').encode()
if repo == self.application:
return f'160000 commit {self.b}\tWebApi\0'.encode()
return b''
if args[:4] == ('config', '-f', '.gitmodules', '--get-regexp'):
return 'submodule.ISSSTELEON.path ISSSTELEON' if repo == self.outer else 'submodule.WebApi.path WebApi'
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
name = 'ISSSTELEON' if repo == self.outer else 'WebApi'
return 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + name + '.git'
if args[:2] == ('rev-parse', 'HEAD'):
return self.a if repo == self.application else self.b
return ''
def test_institutional_git_auth_is_scoped_and_not_in_command(self):
"""Private nested Git fetches use a host-scoped job token without exposing it in arguments."""
env = {'RELEASE_TOKEN': 'fixture-token', 'GIT_CONFIG_COUNT': '1',
'GIT_CONFIG_KEY_0': 'url.http://10.0.10.41:3000/ISSSTELEON/.insteadOf',
'GIT_CONFIG_VALUE_0': 'ssh://git@10.0.10.41:2222/ISSSTELEON/'}
with patch.dict(os.environ, env, clear=True), patch.object(source.subprocess, 'run', return_value=types.SimpleNamespace(stdout='result')) as run:
self.assertEqual(source.git(self.outer, 'status'), 'result')
args, kwargs = run.call_args
self.assertNotIn('fixture-token', str(args))
self.assertEqual(kwargs['env']['GIT_CONFIG_COUNT'], '2')
self.assertEqual(kwargs['env']['GIT_CONFIG_KEY_1'], 'http.http://10.0.10.41:3000/ISSSTELEON/.extraheader')
self.assertEqual(kwargs['env']['GIT_TERMINAL_PROMPT'], '0')
def test_nested_links_are_pinned_and_unrelated_tree_is_ignored(self):
"""Traverse the application link and its nested link without touching dev-data."""
with patch.object(source, 'git', side_effect=self.fake_git):
result = source.checkout_pinned(self.outer)
self.assertEqual(result, {'ISSSTELEON': self.a, 'ISSSTELEON/WebApi': self.b})
self.assertFalse(any('dev-data' in str(args) for _, args in self.calls if '--checkout' in args))
self.assertTrue(all('--checkout' in args for _, args in self.calls if 'update' in args))
def test_external_origin_is_rejected(self):
"""An external submodule URL must fail before Git can initialize it."""
def fake(repo, *args, **kwargs):
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
return 'https://outside.invalid/repo.git'
return self.fake_git(repo, *args, **kwargs)
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
source.checkout_pinned(self.outer)
self.assertFalse(any('--checkout' in args for _, args in self.calls))
def test_wrong_nested_checkout_is_rejected(self):
"""A nested checkout that differs from its gitlink must stop preparation."""
def fake(repo, *args, **kwargs):
if Path(repo) == self.api and args[:2] == ('rev-parse', 'HEAD'):
return 'c' * 40
return self.fake_git(repo, *args, **kwargs)
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
source.checkout_pinned(self.outer)
def test_unknown_nested_gitlink_is_rejected(self):
"""Unrecognized nested repositories must never be initialized implicitly."""
def fake(repo, *args, **kwargs):
if Path(repo) == self.application and args[:1] == ('ls-tree',):
return f'160000 commit {self.b}\tUnknown\0'.encode()
return self.fake_git(repo, *args, **kwargs)
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
source.checkout_pinned(self.outer)
if __name__ == '__main__':
unittest.main()
-41
View File
@@ -1,41 +0,0 @@
"""Protect the manual workflow's deployment chain and Docker independence."""
from pathlib import Path
import subprocess
import re
import unittest
ROOT = Path(__file__).resolve().parents[2]
WORKFLOW = ROOT / '.gitea' / 'workflows' / 'deploy-terminal-release.yml'
class WorkflowTests(unittest.TestCase):
"""The current checkout provides the uncommitted workflow and the Docker baseline."""
def test_workflow_dispatch_builds_and_executes_host_deployment(self):
"""A manual dispatch must resolve first and invoke the automated host helper."""
text = WORKFLOW.read_text(encoding='utf-8')
self.assertIn('workflow_dispatch:', text)
inputs = text.split(' inputs:', 1)[1].split('\njobs:', 1)[0]
self.assertEqual(set(re.findall(r'^ ([a-z_]+):$', inputs, re.MULTILINE)), {'tag', 'puerto', 'puerto_api'})
self.assertRegex(inputs, r"puerto_api:\s+description:[^\n]+\s+required: true\s+default: '28090'")
self.assertNotIn('release:', text)
self.assertIn('tag:', text)
self.assertIn('puerto:', text)
self.assertIn('puerto_api:', text)
self.assertIn('inputs.puerto_api', text)
self.assertIn('--api-port "$REQUESTED_API_PORT"', text)
self.assertNotIn('NATIVE_API_PORT', text)
self.assertLess(text.index('resolve.py'), text.index('remote.py \\'))
self.assertIn('--host 10.0.10.41', text)
self.assertIn('secrets.NATIVE_SSH_KEY', text)
self.assertIn('secrets.NATIVE_KNOWN_HOSTS', text)
self.assertNotIn('sudo ', text)
def test_existing_docker_workflow_is_not_modified(self):
"""The independent deployment must not alter the Docker workflow or its installers."""
result = subprocess.run(['git', '-C', str(ROOT), 'diff', '--quiet', 'HEAD', '--',
'.gitea/workflows/deploy-dev.yml', '.gitea/deploy'], check=False)
self.assertEqual(result.returncode, 0)
if __name__ == '__main__':
unittest.main()
-102
View File
@@ -1,102 +0,0 @@
#!/usr/bin/env python3
"""Verify native unit state, API health and Angular routing after activation."""
import argparse
import json
from pathlib import Path
import subprocess
import sys
import time
import urllib.error
import urllib.request
import install
import activate
def request(url):
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(url, timeout=5) as response:
return response.status, response.read(1024 * 1024)
def check(record, command=subprocess.run, get=request, manager_env=None):
install.validate_record(record)
if record.get('status') not in ('started', 'local_healthy', 'healthy', 'verification_failed'):
raise ValueError('installation is not prepared')
port = record['public_port']
api = record.get('api_port')
expected = [f'isssteleon-native-{port}-{part}.service' for part in ('api', 'worker', 'web')]
if record.get('services') != expected or type(api) is not int or api == port or not 1024 <= api <= 65535:
raise ValueError('invalid installed service metadata')
for unit in expected:
result = command(['systemctl', '--user', 'is-active', '--quiet', unit], check=False, capture_output=True, env=manager_env)
if result.returncode:
raise ValueError('service is not active: ' + unit)
for url in (f'http://127.0.0.1:{api}/health', f'http://127.0.0.1:{port}/health'):
status, body = get(url)
health = json.loads(body)
if status != 200 or not isinstance(health, dict) or health.get('status') != 'ok':
raise ValueError('API health check failed: ' + url)
status, index = get(f'http://127.0.0.1:{port}/')
route_status, route = get(f'http://127.0.0.1:{port}/native-health-route')
if status != 200 or route_status != 200 or not index or index != route:
raise ValueError('Angular distribution or SPA fallback failed')
return {'services': expected, 'api_health': 'ok', 'proxy_health': 'ok', 'spa_fallback': 'ok'}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('instance', type=Path)
parser.add_argument('--wait-seconds', type=int, default=90)
parser.add_argument('--public-result', choices=('ok', 'failed'))
args = parser.parse_args()
if not 0 <= args.wait_seconds <= 300:
parser.error('wait-seconds must be between 0 and 300')
record = None
path = None
tracked = False
try:
path = args.instance.resolve() / 'installation.json'
if args.instance.is_symlink() or path.is_symlink():
raise ValueError('symlinked installation or metadata')
record = json.loads(path.read_text(encoding='utf-8'))
if Path(record.get('base', '')) != args.instance.resolve():
raise ValueError('installation path does not match record')
install.validate_record(record)
if record.get('status') not in ('started', 'local_healthy', 'healthy', 'verification_failed'):
raise ValueError('installation is not prepared')
tracked = True
if args.public_result == 'failed':
raise ValueError('external HTTP check failed from the Actions runner')
manager_env = activate.manager_environment(record['account'])
deadline = time.monotonic() + args.wait_seconds
while True:
try:
checks = check(record, manager_env=manager_env)
break
except (OSError, ValueError, urllib.error.URLError, json.JSONDecodeError) as exc:
if time.monotonic() >= deadline:
raise ValueError('health verification failed: ' + str(exc)) from exc
time.sleep(2)
if args.public_result == 'ok':
checks['public_http'] = 'ok'
record.update(status='healthy' if args.public_result == 'ok' else 'local_healthy',
phase='running' if args.public_result == 'ok' else 'awaiting_external_health',
health=checks, verified_at=int(time.time()))
install.atomic_record(path, record)
print(json.dumps(checks, indent=2, sort_keys=True))
return 0
except (OSError, ValueError, json.JSONDecodeError) as exc:
if tracked:
record.update(status='verification_failed', phase='verification_failed',
health={'result': 'failed', 'error': str(exc)}, verified_at=int(time.time()))
try:
install.atomic_record(path, record)
except OSError:
pass
print('Verification failed: ' + str(exc), file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
+2 -3
View File
@@ -1,8 +1,7 @@
# General DEV workflow integration
`.gitea/workflows/deploy-dev.yml` accepts `puerto` and `rama`. The workflow
branch supplies the installer; `rama` resolves independently to an application
commit and its recognized recursive gitlinks, then routes an unregistered
`.gitea/workflows/deploy-dev.yml` accepts only `puerto` on `dev`. It checks out
the dispatched SHA and recursive application gitlinks, then routes an unregistered
free port to installation and a registered installation to conservative update.
The same revision takes a verified no-op path. Existing storage is never reset as
a fallback. Pending migrations are rejected for updates; post-activation failures
+54 -36
View File
@@ -1,6 +1,6 @@
# DEV installation and conservative updates
The manual `deploy-dev` workflow accepts `puerto` and the application branch `rama` (default `dev`). An unregistered,
The manual `deploy-dev` workflow accepts `puerto` on `dev`. An unregistered,
available port installs a new instance. A registered port updates its existing
managed instance, retaining the original `data/`, project, port and connections.
Repeating the same outer revision verifies recursive gitlinks, recorded image
@@ -11,10 +11,9 @@ to resetting or recreating storage.
## Operator quick start
After the reviewed change reaches `dev`, open **Actions → deploy-dev → Run workflow**.
Select `dev` under **Use workflow from** for the central installer, enter the public
`puerto` and application `rama` (for example `18083` and `staging`), then inspect
the workflow and application revisions and final log. The same action installs a free port or updates its registered
After the reviewed change reaches `dev`, open repository **Actions → deploy-dev →
Run workflow**, select **dev**, enter only **puerto**, then inspect the run's SHA
and final log. The same action installs a free port or updates its registered
installation. Existing projects are discovered from their records; their names
do not have to contain the port.
@@ -32,7 +31,7 @@ outer commit with unchanged application pins still takes the checked update path
Updates do not execute pending migrations: they retain the existing migration
compatibility gate. New installations continue to run their initial migrations.
Successful records contain `status=installed`, `branch`, `workflow_ref`, `workflow_sha`, `revision`, `gitlinks`, `images`
Successful records contain `status=installed`, `revision`, `gitlinks`, `images`
and `result=installed|updated|unchanged`. Updates also retain operation, target,
backup and archive references. `unchanged` preserves previous recovery evidence
and records `verification=complete`; it does not claim a new recalculation.
@@ -51,46 +50,65 @@ for path in pathlib.Path('/srv/workingnarrative-dev').glob('*/installation.json'
if len(matches) != 1:
raise SystemExit('Expected exactly one registered installation; inspect the registry')
record = matches[0]
keys = ('project', 'port', 'status', 'phase', 'result', 'branch', 'workflow_ref', 'workflow_sha', 'revision', 'gitlinks', 'images',
keys = ('project', 'port', 'status', 'phase', 'result', 'revision', 'gitlinks', 'images',
'verification', 'recalculation', 'operation_id', 'target_revision', 'target_images',
'backup', 'archive', 'recovery')
print(json.dumps({key: record[key] for key in keys if key in record}, indent=2))
PY
```
### Central workflow and application branch
### Dispatch when the UI does not offer dev
Gitea 1.26.2 loads the workflow from the selected **Use workflow from** branch,
as shown by its [dispatch implementation](https://github.com/go-gitea/gitea/blob/v1.26.2/services/actions/workflow.go).
Choose a trusted stable branch that contains this reviewed workflow and installer.
At the time of review, remote `main` does not contain `deploy-dev.yml`; use `dev`
after this change is integrated there, or another reviewed branch containing it.
A different or old workflow can omit these controls, so protect the stable branch
and restrict workflow dispatch to trusted operators.
Read-only API checks on 2026-11-10 confirmed Gitea **1.26.2**, repository default
branch **main**, and Actions enabled. Anonymous workflow metadata returned 401;
authenticated UI visibility and dispatch were not tested. Do not dispatch `main`
or the old resetting workflow to work around the UI. Keep the general workflow's
`refs/heads/dev` guard.
`rama` is independent of the workflow ref. The central installer validates the
branch name, fetches its exact `refs/heads/...` from the official repository,
and freezes the resulting commit in a separate temporary checkout. It does not
execute the target branch's workflow or deployment scripts. The target branch
may lack the workflow or contain an older version. A missing branch fails; a tag,
SHA or arbitrary ref is not substituted. A branch move after fetch does not alter
the selected commit. Builds still execute code from the application branch;
choose trusted code and retain existing Actions authorization.
An authorized operator can use the official
[workflow dispatch endpoint](https://docs.gitea.com/api/operations/actions-dispatch-workflow/)
with filename `deploy-dev.yml`, `ref=dev` and only the `puerto` input. Gitea's
[v1.26.2 implementation](https://github.com/go-gitea/gitea/blob/v1.26.2/services/actions/workflow.go)
resolves that branch's commit and reads the workflow from it. This supports using
the API independently of default-branch UI discovery; it is source-based evidence,
not a dispatch performed against this server.
The installer verifies the workflow event and checkout, then uses the exact
recursive application gitlinks. Supported paths are ISSSTELEON, WebApp, WebApi,
models and indicadores_kit at their institutional origins; unknown paths and
origins are rejected. `branch` and `revision` describe the application, while
`workflow_ref` and `workflow_sha` describe the installer. Older records remain
eligible; a verified same-SHA no-op records the new selection without rebuilding.
**This submits a real deployment. Use only after review/merge and explicit
authorization for the intended environment and port.** Set `PORT` and provide
`GITEA_TOKEN` through the operator's private environment, then run:
An authorized operator can also use the [workflow dispatch API](https://docs.gitea.com/api/operations/actions-dispatch-workflow/)
with `ref` naming the stable workflow branch and both inputs, for example
`{"ref":"dev","inputs":{"puerto":"18083","rama":"staging"}}`.
This submits a real deployment. Review the selected workflow, target branch and
environment first. Local validation did not exercise the Gitea UI or runner.
See [INTEGRATION.md](INTEGRATION.md) for the controlled trial; do not use existing
installations for fault injection.
```sh
python3 -B - "$PORT" <<'PY'
import json, os, sys, urllib.request
port = sys.argv[1]
if not port.isascii() or not port.isdigit() or not 1024 <= int(port) <= 65535:
raise SystemExit('Invalid public port')
request = urllib.request.Request(
'http://10.0.10.41:3000/api/v1/repos/ISSSTELEON/WorkingNarrative/actions/workflows/deploy-dev.yml/dispatches',
data=json.dumps({'ref': 'dev', 'inputs': {'puerto': port}}).encode(),
headers={'Authorization': 'token ' + os.environ['GITEA_TOKEN'], 'Content-Type': 'application/json'},
method='POST')
with urllib.request.urlopen(request, timeout=30) as response:
print('Dispatch HTTP status:', response.status)
PY
```
Use an account/token with the repository's required Actions write access. An HTTP
success only confirms dispatch acceptance: open the resulting run in Actions,
verify `ref=dev`, the captured SHA and the intended port, then read its final
result and installation record. A 401/403 requires access correction; a 404 may
mean the workflow/ref is unavailable. Do not remove the branch guard or retry
against another branch. The Action checks out its captured SHA, verifies HEAD,
and initializes only recursive `ISSSTELEON` gitlinks; unrelated `dev-data` is not
required to deploy.
Local validation, review scope and a proposed disposable-environment trial are in
[INTEGRATION.md](INTEGRATION.md). Do not use existing installations for fault injection.
The checkout follows the dispatched WorkingNarrative commit and every recursive
gitlink. Source export rejects mismatching submodule checkouts. Builds include
WebApp, WebApi, Core, Persistance, Extraction, indicadores_kit, models and other
application trees at those pins. No `submodule update --remote` is used.
## Four distinct operations
+2 -6
View File
@@ -354,10 +354,8 @@ def update(api, record, helper, root, base, *, verify_restore=False):
for sha in record['gitlinks'].values())):
raise RuntimeError('installation status or Git provenance is invalid; manual inspection required')
project, port = record['project'], record['port']
metadata = getattr(api, 'request_metadata', lambda root: {})(root)
revision = api.git(root, 'rev-parse', 'HEAD').strip()
getattr(api, 'verify_target_revision', lambda revision: None)(revision)
expected = api.git(root, 'ls-tree', revision, 'ISSSTELEON').split()[2]
expected = api.git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]
old_ids = api.verify_existing_containers(record, base, helper)
phase = 'preparing'
current = None
@@ -389,7 +387,7 @@ def update(api, record, helper, root, base, *, verify_restore=False):
raise RuntimeError('installation containers changed during verification')
operation_step = 'record verified no-op'
api.host_action(helper, 'save', project, json.dumps(dict(
record, **metadata, result='unchanged', verification='complete')))
record, result='unchanged', verification='complete')))
print(f'Unchanged {project} on port {port} at {revision}; verification complete')
return
manifest = {}
@@ -420,7 +418,6 @@ def update(api, record, helper, root, base, *, verify_restore=False):
operation = uuid.uuid4().hex
current = dict(record, status='updating', operation_id=operation, phase='quiescing',
target_revision=revision, target_images=images, target_gitlinks=manifest,
target_branch=metadata.get('branch'),
migrations='none-pending', recalculation='not-started')
def save():
@@ -488,7 +485,6 @@ def update(api, record, helper, root, base, *, verify_restore=False):
{'data': '/data', 'contract': contract, 'before': backup['state'], 'derived': True}, data)
current.update(status='installed', revision=revision, gitlinks=manifest, images=images,
phase='complete', result='updated', recalculation='complete', verification='complete')
current.update(metadata)
current.pop('error', None)
save()
print(f'Updated {project} on port {port} at {revision}')
+4 -136
View File
@@ -56,127 +56,6 @@ def git(repo, *args, binary=False):
return run(['git', '-C', repo, *args], binary=binary)
def dispatch_metadata(root=ROOT):
"""Validate the event identity and its immutable checked-out commit."""
ref = os.environ.get('DISPATCH_REF', '')
name = os.environ.get('DISPATCH_REF_NAME', '')
sha = os.environ.get('DISPATCH_SHA', '')
if (os.environ.get('DISPATCH_REPOSITORY') != 'ISSSTELEON/WorkingNarrative'
or os.environ.get('DISPATCH_SERVER', '').rstrip('/') != 'http://10.0.10.41:3000'
or os.environ.get('DISPATCH_REF_TYPE') != 'branch'
or not name or ref != 'refs/heads/' + name
or not re.fullmatch(r'[0-9a-f]{40}', sha)):
raise ValueError('invalid deployment event identity or branch reference')
run(['git', 'check-ref-format', ref])
if git(root, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError('checkout does not match the dispatched SHA')
return {'workflow_ref': ref, 'workflow_sha': sha}
_target_request = None
def validate_branch(branch):
if (not branch or branch.startswith(('refs/', '-')) or branch == '@'
or re.fullmatch(r'[0-9a-fA-F]{40}', branch)):
raise ValueError('target must be a branch name')
run(['git', 'check-ref-format', 'refs/heads/' + branch])
return branch
def verify_target_revision(revision):
if _target_request is not None and revision != _target_request[1]:
raise RuntimeError('application checkout changed during deployment preparation')
def request_metadata(root=ROOT):
if _target_request is None:
return {}
branch, sha = _target_request
metadata = dispatch_metadata(ROOT)
if git(root, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError('application checkout does not match resolved branch commit')
return dict(metadata, branch=branch)
def deploy_branch(port, branch, workflow_root=ROOT, base=BASE):
"""Fetch one official branch and deploy its fixed commit using this installer."""
global _target_request
validate_port(port)
validate_branch(branch)
dispatch_metadata(workflow_root)
official = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
if git(workflow_root, 'remote', 'get-url', 'origin').strip() not in (official, official.removesuffix('.git')):
raise RuntimeError('workflow checkout origin is not the official repository')
target_ref = 'refs/deploy/' + uuid.uuid4().hex
try:
git(workflow_root, 'fetch', '--no-tags', 'origin',
'+refs/heads/' + branch + ':' + target_ref)
sha = git(workflow_root, 'rev-parse', '--verify', target_ref + '^{commit}').strip()
if not re.fullmatch(r'[0-9a-f]{40}', sha):
raise RuntimeError('remote branch did not resolve to a full commit SHA')
with tempfile.TemporaryDirectory(prefix='isssteleon-source-') as tmp:
source = Path(tmp)
run(['git', 'init', '--quiet', source])
git(source, 'fetch', '--no-tags', str(workflow_root), target_ref)
git(source, 'checkout', '--quiet', '--detach', sha)
_target_request = (branch, sha)
request_metadata(source)
print('Deployment source:', json.dumps({'branch': branch, 'revision': sha}, sort_keys=True))
checkout_pinned(source)
install_auto(port, source, base)
finally:
_target_request = None
git(workflow_root, 'update-ref', '-d', target_ref)
SUBMODULE_ORIGINS = {
'ISSSTELEON': 'ISSSTELEON',
'ISSSTELEON/WebApp': 'WebApp',
'ISSSTELEON/WebApi': 'WebApi',
'ISSSTELEON/models': 'models',
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
}
def checkout_pinned(root=ROOT):
"""Initialize only recognized institutional gitlinks at the captured revision."""
request_metadata(root)
def visit(repo, prefix, selected=None):
entries = git(repo, 'ls-tree', '-rz', '--full-tree', 'HEAD', binary=True)
for entry in entries.split(b'\0'):
if not entry:
continue
meta, raw_path = entry.split(b'\t', 1)
mode, _, sha = meta.decode().split()
if mode != '160000':
continue
path = os.fsdecode(raw_path)
if selected is not None and path != selected:
continue
full = f'{prefix}/{path}' if prefix else path
if full not in SUBMODULE_ORIGINS or path in ('', '.', '..') or '..' in Path(path).parts:
raise RuntimeError(f'unsupported application gitlink: {full}')
config = git(repo, 'config', '-f', '.gitmodules', '--get-regexp', r'^submodule\..*\.path$')
matches = [line.split(None, 1)[0][len('submodule.'):-len('.path')]
for line in config.splitlines() if len(line.split(None, 1)) == 2
and line.split(None, 1)[1] == path]
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
raise RuntimeError(f'invalid submodule mapping: {full}')
name = matches[0]
origin = 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + SUBMODULE_ORIGINS[full] + '.git'
if git(repo, 'config', '-f', '.gitmodules', '--get', f'submodule.{name}.url').strip() != origin:
raise RuntimeError(f'untrusted submodule origin: {full}')
git(repo, '-c', f'submodule.{name}.url={origin}', 'submodule', 'update', '--init', '--checkout', '--', path)
child = repo / path
if git(child, 'rev-parse', 'HEAD').strip() != sha:
raise RuntimeError(f'gitlink checkout mismatch: {full}')
visit(child, full)
visit(root, '', 'ISSSTELEON')
print('Pinned application gitlinks:', json.dumps(pinned_manifest(root / 'ISSSTELEON',
git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]), sort_keys=True))
def committed_trees(repo, revision, prefix=''):
"""Walk exact recursive gitlinks and reject mismatching checked-out commits."""
actual = git(repo, 'rev-parse', 'HEAD').strip()
@@ -341,9 +220,7 @@ def verify_services(cmd, port, timeout=300):
def install(instance, port_text, operation, root=ROOT, base=BASE, helper=None):
project, port = validate(instance, port_text, operation)
revision = git(root, 'rev-parse', 'HEAD').strip()
metadata = request_metadata(root)
verify_target_revision(revision)
expected = git(root, 'ls-tree', revision, 'ISSSTELEON').split()[2]
expected = git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]
owns_helper = helper is None
if owns_helper:
helper = start_helper(base)
@@ -352,8 +229,7 @@ def install(instance, port_text, operation, root=ROOT, base=BASE, helper=None):
with tempfile.TemporaryDirectory(prefix='isssteleon-deploy-') as tmp:
directory = Path(tmp)
source, deploy, data = directory / 'codigo', directory / 'deploy', base / project / 'data'
record = {'project': project, 'port': port, 'revision': revision, 'status': 'preparing',
**metadata}
record = {'project': project, 'port': port, 'revision': revision, 'status': 'preparing'}
def save():
host_action(helper, 'save', project, json.dumps(record))
cmd = None
@@ -514,19 +390,11 @@ def install_auto(port, root=ROOT, base=BASE, *, check_record=None):
def main():
parser = argparse.ArgumentParser()
parser.add_argument('command', choices=['validate', 'install', 'validate-auto', 'install-auto', 'validate-dispatch', 'deploy-branch'])
parser.add_argument('command', choices=['validate', 'install', 'validate-auto', 'install-auto'])
parser.add_argument('arguments', nargs='*')
args = parser.parse_args()
try:
if args.command == 'validate-dispatch':
if args.arguments:
raise ValueError('validate-dispatch takes no arguments')
print('Workflow event:', json.dumps(dispatch_metadata(), sort_keys=True))
elif args.command == 'deploy-branch':
if len(args.arguments) != 2:
raise ValueError('deploy-branch requires port and branch')
deploy_branch(*args.arguments)
elif args.command in ('validate-auto', 'install-auto'):
if args.command in ('validate-auto', 'install-auto'):
if len(args.arguments) != 1:
raise ValueError('automatic commands require exactly one port')
port_text = args.arguments[0]
-56
View File
@@ -1,56 +0,0 @@
#!/usr/bin/env python3
"""Report sanitized checkout URL comparisons without contacting a remote."""
import json
import os
import subprocess
from urllib.parse import urlsplit
OFFICIAL = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
SSH = 'ssh://git@10.0.10.41:2222/ISSSTELEON/WorkingNarrative.git'
SERVER = 'http://10.0.10.41:3000'
REPOSITORY = 'ISSSTELEON/WorkingNarrative'
def describe(value):
"""Return fixed labels and comparisons, never any part of the input."""
try:
parsed = urlsplit(value)
scheme = parsed.scheme if parsed.scheme in ('http', 'https', 'ssh') else 'other'
return {'exact_http': value == OFFICIAL,
'exact_http_without_git': value == OFFICIAL.removesuffix('.git'), 'exact_ssh': value == SSH,
'scheme': scheme, 'official_host': parsed.hostname == '10.0.10.41',
'official_http_port': parsed.port == 3000,
'official_ssh_port': parsed.port == 2222,
'repository_path': parsed.path == '/ISSSTELEON/WorkingNarrative.git',
'repository_path_without_git': parsed.path == '/ISSSTELEON/WorkingNarrative',
'userinfo_present': parsed.username is not None or parsed.password is not None,
'query_or_fragment': bool(parsed.query or parsed.fragment)}
except ValueError:
return {'invalid_url': True}
def git_values(*args):
result = subprocess.run(['git', *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
text=True, encoding='utf-8', errors='replace', check=False)
return result.stdout.splitlines() if result.returncode == 0 else []
def main():
literal = git_values('config', '--get-all', 'remote.origin.url')
effective = git_values('remote', 'get-url', '--all', 'origin')
github = os.environ.get('GITHUB_SERVER_URL', '')
gitea = os.environ.get('GITEA_SERVER_URL', '')
result = {'literal_origin': [describe(url) for url in literal],
'effective_origin': [describe(url) for url in effective],
'origin_rewritten': literal != effective,
'github_server_is_official': github.rstrip('/') == SERVER,
'gitea_server_is_official': gitea.rstrip('/') == SERVER,
'server_variables_equal': bool(github and gitea) and github.rstrip('/') == gitea.rstrip('/'),
'event_server_is_official': os.environ.get('DISPATCH_SERVER', '').rstrip('/') == SERVER,
'event_repository_is_official': os.environ.get('DISPATCH_REPOSITORY') == REPOSITORY}
print('Checkout origin diagnostic:', json.dumps(result, sort_keys=True))
if __name__ == '__main__':
main()
-24
View File
@@ -88,28 +88,6 @@ class AutomaticDeploymentTests(unittest.TestCase):
self.assertEqual(before, {str(p.relative_to(self.root)): p.read_bytes() for p in self.root.rglob('*')
if p.is_file() and p.name != 'installation.json'})
def test_selected_branch_updates_legacy_record(self):
"""Fail if updating an older record loses the selected branch or retained data."""
before = data_guard.storage_state(self.root / 'data', self.contract)
with patch.object(dev, 'request_metadata', return_value={'branch': 'staging',
'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'f' * 40}):
self.execute()
record = host.read_record(self.root)
self.assertEqual(record['branch'], 'staging')
self.assertEqual(record['revision'], self.runtime.revision)
self.assertEqual((record['workflow_ref'], record['workflow_sha']), ('refs/heads/dev', 'f' * 40))
data_guard.verify_state(self.root / 'data', self.contract, before, derived=True)
def test_different_branch_same_commit_records_verified_noop(self):
"""Fail if selecting another branch at the same SHA rebuilds or leaves stale provenance."""
self.select_same_revision()
with patch.object(dev, 'request_metadata', return_value={'branch': 'feature/demo',
'workflow_ref': 'refs/heads/feature/demo', 'workflow_sha': self.runtime.revision}):
self.execute()
record = host.read_record(self.root)
self.assertEqual((record['result'], record['branch']), ('unchanged', 'feature/demo'))
self.assertFalse(any('build' in args or 'stop' in args for args in self.runtime.calls))
def test_same_revision_rejects_mismatching_gitlinks(self):
"""Fail if the outer SHA alone can hide inconsistent installed recursive gitlinks."""
self.select_same_revision()
@@ -258,7 +236,6 @@ class AutomaticDeploymentTests(unittest.TestCase):
patch.object(dev, 'git', side_effect=lambda repo, *args: revision if args[0] == 'rev-parse' else
'160000 commit ' + pin + '\tISSSTELEON'), \
patch.object(dev, 'export_tree', side_effect=export), \
patch.object(dev, 'request_metadata', return_value={'branch': 'main', 'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'f' * 40}), \
patch.object(dev, 'copy_to_host', side_effect=copy_to_host), \
patch.object(dev, 'reserve', side_effect=lambda helper, project, port: host.reserve(base, project, port)), \
patch.object(conservative, 'guard'), patch.object(conservative, 'verify_api'), \
@@ -270,7 +247,6 @@ class AutomaticDeploymentTests(unittest.TestCase):
self.assertEqual((record['status'], record['result'], record['phase'], record['revision']),
('installed', 'installed', 'complete', revision))
self.assertEqual(record['gitlinks'], {'ISSSTELEON': pin})
self.assertEqual((record['branch'], record['workflow_sha']), ('main', 'f' * 40))
self.assertEqual(record['images'], [c[c.index('-t') + 1] for c in calls if c[:2] == ['docker', 'build']])
self.assertEqual(finish.call_count, 1)
self.assertEqual(verify.call_count, 1)
+11 -9
View File
@@ -10,18 +10,20 @@ import unittest
class GeneralWorkflowTests(unittest.TestCase):
def test_dispatch_separates_workflow_and_target_branch(self):
"""Fail if the central workflow omits the independent target branch or event validation."""
def test_dispatch_uses_only_port_and_exact_dev_checkout(self):
"""Fail if deployment accepts unpinned source or bypasses the dev-only dispatch guard."""
text = (Path(__file__).resolve().parents[1] / 'workflows' / 'deploy-dev.yml').read_text()
inputs = text.split(' inputs:\n', 1)[1].split('\njobs:', 1)[0]
self.assertEqual(re.findall(r'^ (\w+):', inputs, re.M), ['puerto', 'rama'])
for boundary in ('${{ gitea.ref }}', '${{ gitea.ref_name }}', '${{ gitea.ref_type }}',
'ref: ${{ gitea.sha }}', 'dev.py validate-dispatch',
'dev.py validate-auto "$PORT"', 'dev.py deploy-branch "$PORT" "$TARGET_BRANCH"',
'default: dev'):
self.assertEqual(re.findall(r'^ (\w+):', inputs, re.M), ['puerto'])
for boundary in ('test "$DISPATCH_REF" = refs/heads/dev', 'ref: ${{ github.sha }}',
'test "$(git rev-parse HEAD)" = "$DISPATCH_SHA"',
'dev.py validate-auto "$PORT"',
'git submodule update --init --recursive ISSSTELEON',
'dev.py install-auto "$PORT"'):
self.assertIn(boundary, text)
self.assertLess(text.index('validate-dispatch'), text.index('deploy-branch'))
self.assertNotIn('refs/heads/dev', text)
self.assertLess(text.index('refs/heads/dev'), text.index('actions/checkout'))
self.assertLess(text.index('git rev-parse HEAD'), text.index('validate-auto'))
self.assertLess(text.index('validate-auto'), text.index('git submodule update'))
self.assertNotIn('--remote', text)
def test_general_path_has_no_laboratory_identity_or_reset_fallback(self):
-201
View File
@@ -1,201 +0,0 @@
"""Validate branch events with synthetic contexts and no deployment or network."""
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import dev
class DispatchTests(unittest.TestCase):
def event(self, name='dev'):
"""Create a synthetic institutional workflow event for a full commit."""
return {'DISPATCH_REF': 'refs/heads/' + name, 'DISPATCH_REF_NAME': name,
'DISPATCH_REF_TYPE': 'branch', 'DISPATCH_SHA': 'a' * 40,
'DISPATCH_REPOSITORY': 'ISSSTELEON/WorkingNarrative',
'DISPATCH_SERVER': 'http://10.0.10.41:3000'}
def test_branch_names_and_immutable_sha(self):
"""Fail if valid selected branches do not retain the event SHA and full name."""
for name in ('dev', 'main', 'staging', 'feature/dashboard-unificado'):
with self.subTest(name=name), patch.dict(os.environ, self.event(name)), \
patch.object(dev, 'git', return_value='a' * 40):
self.assertEqual(dev.dispatch_metadata(Path('.'))['workflow_ref'], 'refs/heads/' + name)
self.assertEqual(dev.dispatch_metadata(Path('.'))['workflow_sha'], 'a' * 40)
def test_invalid_context_and_changed_checkout(self):
"""Fail if tags, invalid refs, another repository or mismatched SHAs can deploy."""
changes = ({'DISPATCH_REF_TYPE': 'tag'}, {'DISPATCH_REF': 'refs/tags/dev'},
{'DISPATCH_REPOSITORY': 'other/repo'}, {'DISPATCH_SERVER': 'http://example.com'},
{'DISPATCH_SHA': 'abc'}, {'DISPATCH_REF_NAME': 'other'})
for change in changes:
with self.subTest(change=change), patch.dict(os.environ, self.event() | change), \
patch.object(dev, 'git', return_value='a' * 40):
with self.assertRaises(ValueError):
dev.dispatch_metadata(Path('.'))
with patch.dict(os.environ, self.event('bad..name')), patch.object(dev, 'git', return_value='a' * 40):
with self.assertRaises(subprocess.CalledProcessError):
dev.dispatch_metadata(Path('.'))
with patch.dict(os.environ, self.event()), patch.object(dev, 'git', return_value='b' * 40):
with self.assertRaises(RuntimeError):
dev.dispatch_metadata(Path('.'))
def test_submodule_origin_checked_before_fetch(self):
"""Fail if a selected commit can fetch its application from an external origin."""
calls = []
def fake_git(repo, *args, **kwargs):
calls.append(args)
if args[0] == 'ls-tree':
return b'160000 commit ' + b'b' * 40 + b'\tISSSTELEON\0'
if '--get-regexp' in args:
return 'submodule.ISSSTELEON.path ISSSTELEON\n'
if '--get' in args:
return 'https://example.com/other.git\n'
raise AssertionError(args)
with patch.object(dev, 'request_metadata'), patch.object(dev, 'git', side_effect=fake_git):
with self.assertRaisesRegex(RuntimeError, 'untrusted submodule origin'):
dev.checkout_pinned(Path('.'))
self.assertFalse(any('update' in args for args in calls))
def test_target_branch_validation(self):
"""Fail if refs, hashes or invalid names can replace a branch selection."""
for branch in ('dev', 'staging', 'feature/dashboard-unificado'):
self.assertEqual(dev.validate_branch(branch), branch)
for branch in ('', 'refs/tags/release', '-bad', '@', 'a' * 40, 'bad..name'):
with self.subTest(branch=branch):
with self.assertRaises((ValueError, subprocess.CalledProcessError)):
dev.validate_branch(branch)
def test_effective_origin_accepts_only_exact_institutional_http_urls(self):
"""Reject deceptive or rewritten origins before fetch while accepting checkout's HTTP URL."""
official = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative'
for url, accepted in ((official, True), (official + '.git', True),
(official + '.git.evil', False),
(official.replace('10.0.10.41', '10.0.10.41.evil'), False),
(official.replace('http://', 'http://user:secret@'), False),
(official.replace('http://', 'https://'), False),
('http://example.com/ISSSTELEON/WorkingNarrative', False)):
with self.subTest(url=url):
def fake_git(repo, *args, **kwargs):
if args[:2] == ('remote', 'get-url'):
return url
if args[0] == 'fetch':
raise subprocess.CalledProcessError(1, args)
return ''
with patch.object(dev, 'dispatch_metadata'), patch.object(dev, 'git', side_effect=fake_git) as git, \
patch.object(dev, 'install_auto') as install:
with self.assertRaises(subprocess.CalledProcessError if accepted else RuntimeError):
dev.deploy_branch('18083', 'staging', Path('/central'))
self.assertEqual(any(call.args[1:2] == ('fetch',) for call in git.call_args_list), accepted)
install.assert_not_called()
def test_external_git_rewrite_is_rejected_before_fetch(self):
"""Fail if an official literal origin rewritten to another host reaches fetch."""
with tempfile.TemporaryDirectory() as tmp:
subprocess.run(['git', 'init', '-q', tmp], check=True)
subprocess.run(['git', '-C', tmp, 'remote', 'add', 'origin',
'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative'], check=True)
env = {'GIT_CONFIG_COUNT': '1', 'GIT_CONFIG_KEY_0': 'url.http://example.com/.insteadOf',
'GIT_CONFIG_VALUE_0': 'http://10.0.10.41:3000/'}
with patch.dict(os.environ, env), patch.object(dev, 'dispatch_metadata'), \
patch.object(dev, 'install_auto') as install:
with self.assertRaisesRegex(RuntimeError, 'origin is not the official repository'):
dev.deploy_branch('18083', 'staging', Path(tmp))
install.assert_not_called()
def test_central_installer_uses_resolved_application_tree(self):
"""Fail if a target without a workflow or with an old installer controls execution."""
for branch in ('dev', 'staging', 'feature/demo'):
with self.subTest(branch=branch):
calls = []
workflow_root = Path('/central')
target_sha = 'b' * 40
def fake_git(repo, *args, **kwargs):
calls.append((repo, args))
if args[:2] == ('remote', 'get-url'):
return 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
if args[:2] == ('rev-parse', '--verify'):
return target_sha
if args[:2] == ('rev-parse', 'HEAD'):
return target_sha
return ''
observed = []
def install(port, source, base):
observed.append((port, source, dev.request_metadata(source)))
self.assertNotEqual(source, workflow_root)
with patch.object(dev, 'dispatch_metadata', return_value={
'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'a' * 40}), \
patch.object(dev, 'git', side_effect=fake_git), \
patch.object(dev, 'run'), patch.object(dev, 'checkout_pinned') as checkout, \
patch.object(dev, 'install_auto', side_effect=install):
dev.deploy_branch('18083', branch, workflow_root, Path('/base'))
self.assertEqual(observed[0][2], {'branch': branch, 'workflow_ref': 'refs/heads/dev',
'workflow_sha': 'a' * 40})
self.assertTrue(any(args[0] == 'fetch' and '+refs/heads/' + branch + ':' in args[-1]
for _, args in calls))
checkout.assert_called_once_with(observed[0][1])
def test_real_git_snapshot_is_separate_from_workflow(self):
"""Fail if a moving branch or target deployment script replaces the central installer."""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
remote, central = root / 'remote', root / 'central'
remote.mkdir()
central.mkdir()
def command(repo, *args, input=None):
return subprocess.run(['git', '-C', str(repo), *args], input=input,
text=True, capture_output=True, check=True).stdout.strip()
command(remote, 'init', '-q')
command(remote, 'config', 'user.email', 'fixture@example.invalid')
command(remote, 'config', 'user.name', 'Fixture')
(remote / '.gitea/deploy').mkdir(parents=True)
(remote / '.gitea/deploy/dev.py').write_text('untrusted target installer')
command(remote, 'add', '.gitea/deploy/dev.py')
command(remote, 'commit', '-qm', 'target with old installer and no workflow')
original = command(remote, 'rev-parse', 'HEAD')
command(remote, 'branch', 'staging')
(remote / '.gitea/deploy/dev.py').write_text('later branch tip')
command(remote, 'commit', '-qam', 'later commit')
newer = command(remote, 'rev-parse', 'HEAD')
command(central, 'init', '-q')
command(central, 'remote', 'add', 'origin', 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git')
actual_git = dev.git
def routed_git(repo, *args, **kwargs):
if repo == central and args[:3] == ('fetch', '--no-tags', 'origin'):
result = actual_git(repo, 'fetch', '--no-tags', str(remote), *args[3:], **kwargs)
command(remote, 'update-ref', 'refs/heads/staging', newer)
return result
return actual_git(repo, *args, **kwargs)
def inspect(port, source, base):
self.assertEqual(command(source, 'rev-parse', 'HEAD'), original)
self.assertEqual((source / '.gitea/deploy/dev.py').read_text(), 'untrusted target installer')
self.assertFalse((source / '.gitea/workflows/deploy-dev.yml').exists())
self.assertEqual(dev.request_metadata(source)['branch'], 'staging')
with patch.object(dev, 'dispatch_metadata', return_value={
'workflow_ref': 'refs/heads/dev', 'workflow_sha': 'a' * 40}), \
patch.object(dev, 'git', side_effect=routed_git), \
patch.object(dev, 'checkout_pinned'), patch.object(dev, 'install_auto', side_effect=inspect) as install:
dev.deploy_branch('18083', 'staging', central, root / 'base')
install.assert_called_once()
self.assertEqual(command(remote, 'rev-parse', 'refs/heads/staging'), newer)
def test_nonexistent_branch_does_not_start_deployment(self):
"""Fail if an absent remote branch falls back to another commit or starts deployment."""
def fake_git(repo, *args, **kwargs):
if args[:2] == ('remote', 'get-url'):
return 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
if args[0] == 'fetch':
raise subprocess.CalledProcessError(1, args)
return ''
with patch.object(dev, 'dispatch_metadata'), patch.object(dev, 'git', side_effect=fake_git), \
patch.object(dev, 'install_auto') as install:
with self.assertRaises(subprocess.CalledProcessError):
dev.deploy_branch('18083', 'missing', Path('/central'))
install.assert_not_called()
if __name__ == '__main__':
unittest.main()
-50
View File
@@ -1,50 +0,0 @@
"""Exercise sanitized origin diagnostics using temporary Git repositories."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
import origin_diagnostic as diagnostic
class OriginDiagnosticTests(unittest.TestCase):
def test_url_classification_never_returns_input(self):
"""Fail if credentials or deceptive URLs appear in the diagnostic output."""
for url in ('http://secret:password@10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git',
'http://10.0.10.41.evil:3000/ISSSTELEON/WorkingNarrative.git',
'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git.evil'):
with self.subTest(url=url):
result = diagnostic.describe(url)
self.assertFalse(result['exact_http'])
self.assertNotIn(url, json.dumps(result))
self.assertNotIn('password', json.dumps(result))
self.assertTrue(diagnostic.describe(diagnostic.OFFICIAL)['exact_http'])
self.assertTrue(diagnostic.describe(diagnostic.SSH)['exact_ssh'])
def test_real_git_rewrite_is_detected_without_disclosing_credentials(self):
"""Fail if Git URL rewriting is missed or a configured credential is logged."""
with tempfile.TemporaryDirectory() as tmp:
subprocess.run(['git', 'init', '-q', tmp], check=True)
subprocess.run(['git', '-C', tmp, 'remote', 'add', 'origin', diagnostic.SSH], check=True)
env = os.environ.copy()
env.update({'GIT_CONFIG_COUNT': '1',
'GIT_CONFIG_KEY_0': 'url.http://secret:password@10.0.10.41:3000/ISSSTELEON/.insteadOf',
'GIT_CONFIG_VALUE_0': 'ssh://git@10.0.10.41:2222/ISSSTELEON/',
'DISPATCH_SERVER': diagnostic.SERVER, 'DISPATCH_REPOSITORY': diagnostic.REPOSITORY})
result = subprocess.run([sys.executable, '-B', str(Path(diagnostic.__file__).resolve())],
cwd=tmp, env=env, text=True, capture_output=True, check=True)
self.assertNotIn('secret', result.stdout + result.stderr)
self.assertNotIn('password', result.stdout + result.stderr)
data = json.loads(result.stdout.split(': ', 1)[1])
self.assertTrue(data['literal_origin'][0]['exact_ssh'])
self.assertTrue(data['effective_origin'][0]['userinfo_present'])
self.assertTrue(data['origin_rewritten'])
self.assertTrue(data['event_repository_is_official'])
if __name__ == '__main__':
unittest.main()
+10 -18
View File
@@ -7,37 +7,29 @@ on:
description: Public WebApp port; create a new instance or conservatively update its existing data
required: true
type: string
rama:
description: WorkingNarrative branch to deploy
required: true
default: dev
type: string
jobs:
deploy:
runs-on: ubuntu-latest
env:
PORT: ${{ inputs.puerto }}
TARGET_BRANCH: ${{ inputs.rama }}
DISPATCH_REF: ${{ gitea.ref }}
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
DISPATCH_SHA: ${{ gitea.sha }}
DISPATCH_REPOSITORY: ${{ gitea.repository }}
DISPATCH_SERVER: ${{ gitea.server_url }}
DISPATCH_REF: ${{ github.ref }}
DISPATCH_SHA: ${{ github.sha }}
GIT_CONFIG_COUNT: 1
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
steps:
- name: Require dev branch
run: test "$DISPATCH_REF" = refs/heads/dev
- uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ gitea.sha }}
ref: ${{ github.sha }}
- name: Verify dispatched revision
run: python3 -B .gitea/deploy/dev.py validate-dispatch
- name: Diagnose checkout origin
run: python3 -B .gitea/deploy/origin_diagnostic.py
run: test "$(git rev-parse HEAD)" = "$DISPATCH_SHA"
- name: Validate request
run: python3 -B .gitea/deploy/dev.py validate-auto "$PORT"
- name: Resolve branch and install or conservatively update instance
run: python3 -B .gitea/deploy/dev.py deploy-branch "$PORT" "$TARGET_BRANCH"
- name: Checkout pinned submodules
run: git submodule update --init --recursive ISSSTELEON
- name: Install or conservatively update instance
run: python3 -B .gitea/deploy/dev.py install-auto "$PORT"
@@ -1,77 +0,0 @@
name: deploy-terminal-release
on:
workflow_dispatch:
inputs:
tag:
description: Published release tag
required: true
type: string
puerto:
description: Public WebApp port
required: true
default: '18090'
type: string
puerto_api:
description: Internal loopback WebApi port
required: true
default: '28090'
type: string
jobs:
resolve:
runs-on: ubuntu-latest
env:
RELEASE_OUTPUT: release-output/release-source.tar.gz
REQUESTED_TAG: ${{ inputs.tag }}
REQUESTED_PORT: ${{ inputs.puerto }}
REQUESTED_API_PORT: ${{ inputs.puerto_api }}
RELEASE_TOKEN: ${{ gitea.token }}
GIT_CONFIG_COUNT: 1
GIT_CONFIG_KEY_0: url.${{ gitea.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
DISPATCH_REF: ${{ gitea.ref }}
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
DISPATCH_SHA: ${{ gitea.sha }}
DISPATCH_REPOSITORY: ${{ gitea.repository }}
DISPATCH_SERVER: ${{ gitea.server_url }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ gitea.sha }}
- name: Prepare release bundle
run: |
mkdir release-output
python3 -B .gitea/deploy-terminal/resolve.py
cp .gitea/deploy-terminal/{install.py,activate.py,verify.py,remote.py,bundle.py,source.py,README.md} release-output/
- name: Install, activate and verify native services
env:
NATIVE_ACCOUNT: ${{ vars.NATIVE_ACCOUNT }}
NATIVE_SSH_PORT: ${{ vars.NATIVE_SSH_PORT }}
NATIVE_HOSTNAME: ${{ vars.NATIVE_HOSTNAME }}
NATIVE_PARENT: ${{ vars.NATIVE_PARENT }}
NATIVE_SSH_KEY: ${{ secrets.NATIVE_SSH_KEY }}
NATIVE_KNOWN_HOSTS: ${{ secrets.NATIVE_KNOWN_HOSTS }}
run: |
set -eu
: "${NATIVE_ACCOUNT:?Missing NATIVE_ACCOUNT}"
: "${NATIVE_SSH_PORT:?Missing NATIVE_SSH_PORT}"
: "${NATIVE_HOSTNAME:?Missing NATIVE_HOSTNAME}"
: "${NATIVE_PARENT:?Missing NATIVE_PARENT}"
: "${REQUESTED_API_PORT:?Missing puerto_api}"
: "${NATIVE_SSH_KEY:?Missing NATIVE_SSH_KEY}"
: "${NATIVE_KNOWN_HOSTS:?Missing NATIVE_KNOWN_HOSTS}"
umask 077
scratch=$(mktemp -d)
trap 'rm -f "$scratch/key" "$scratch/known_hosts"; rmdir "$scratch"' EXIT
printf '%s\n' "$NATIVE_SSH_KEY" > "$scratch/key"
printf '%s\n' "$NATIVE_KNOWN_HOSTS" > "$scratch/known_hosts"
checksum=$(python3 -c 'import json; print(json.load(open("release-output/release-record.json"))["bundle_sha256"])')
python3 -B release-output/remote.py \
--bundle-dir release-output --bundle-sha256 "$checksum" \
--host 10.0.10.41 --ssh-port "$NATIVE_SSH_PORT" \
--account "$NATIVE_ACCOUNT" --expected-hostname "$NATIVE_HOSTNAME" \
--parent "$NATIVE_PARENT" --api-port "$REQUESTED_API_PORT" \
--identity "$scratch/key" --known-hosts "$scratch/known_hosts"
+18 -1
View File
@@ -20,11 +20,28 @@ Package `Extraction/extraction/`:
terms in `nlp/vocabulary.py` (extend there, no code changes).
- `records.py` — `DocumentExtractor` and `RecordMerger` (same patient across
pages/files, most confident value wins, confident disagreements become
`FieldConflict`).
`FieldConflict`). `ExtractedRecord.discovered` also carries every caption
no known `FieldSpec` claimed (`nlp/discovery.py::discover_captions`).
- `readers/text.py` — `TextReader`, the fallback in `FALLBACK_READERS`:
content that's neither a PDF nor an image, read as plain text (one page,
one line per newline) as long as it decodes as one, instead of being
rejected as an unsupported format.
- WebApi side: `connectors/document.py` + `schemas/field_specs.py` (field
specs derived from the target schema). Each row carries `documento` (the
record's pages as one PDF), mappable to a file column. Corrections from
the UI travel as `overrides`. Results cached per worker for repeated calls.
A `document` source's `payload` may carry `sql` (a connection, `table` or
`query`, `column`, `key_column`) instead of `files`: one document per
row, the named column read as its bytes (a `varbinary(max)` PDF) or, via
`TextReader`, as plain text — the same connector and extraction either way.
- `schemas/catalog_matching.py` + `services/catalog_commit_service.py`:
a discovered caption is fuzzy-matched (`rapidfuzz`) against the project's
catalog (`core/catalogos/<proyecto>.toml`); a close enough etiqueta reuses
that `resultado_id`, otherwise one is minted
(`indicadores_kit.registry.catalogos.add_resultado`) and synced. Written
straight into `procedimiento`/`observacion` (no staging row for these),
tagged with the sentinel `fuente_tabla` `catalogo_abierto` so it reads
apart from every staging-derived row.
- WebApp: `DocumentReviewDialog` (records, value, confidence, method,
source line and page, conflicts, image thumbnails, editable values).
- Limits: NLP is rule-based (no trained model); images are located and
@@ -1,198 +0,0 @@
# CaMa dashboard integration coordination
## Patient identity follow-up — 2026-11-13 (proposal for Claude)
Remote tips were checked: WorkingNarrative `92d3a65797b1a07c0bd3bd737f9af967acc876ee`, ISSSTELEON `ec6d3e6cd7b8126423664b694ff40c479ceb1613`, WebApi `8b47f1522de0efd29f6c66c4b13df48f51bf8381`, WebApp `2e0938628c85fae76fc41384edfd887c808cf53b`, kit `f4be01b3127588e98c02ff96822098138bd5b1f5`. The `feature/seguimiento-pac-id` tips are kit `23957cc8d2ee9176e5800bc0ab3cd7ea31408a41`, WebApi `854720066fb4e14f171f0c4a0034be5fd96a5623`, WebApp `bfbd11beae578beb483c46ee5052f1efbc6b3ba1`; no such branch exists in the two parent repositories. The kit branch returns `str(pac_id)` under the legacy name `id_seudonimo`, WebApi removes the salt argument, and WebApp uses that value for CaCu risk. These are not ancestors of the dashboard tips. Their intent needs integration without reverting CaMa work.
`pac_id` is the staging patient primary key, copied to each domain's indicator `persona` and used by cohort/risk records. It is stable within the retained domain database; it is not proven globally unique across CaCu, CaMa and TEA databases or installations. `pac_id_hospital` is a separate source identifier; do not expose it or equate independently assigned domain IDs. TEA redesign has its own `pacientes.pac_id` and patient-linked records; an episode or order is not a patient identity. Preserve domain context and any episode identifier separately.
TEA redesign WebApi `461d651` currently emits a salted pseudonym as both FHIR `Patient.id` and `EpisodeOfCare.id`; the episode references that patient and the summary endpoint resolves the pseudonym against the cohort. That shared value reflects the current one-row-per-child projection, not proof that patient and episode are the same entity. A future migration must update references and lookup together, retain compatibility for existing FHIR clients, and avoid assuming one episode per patient forever.
The CaMa token is currently checked by `patient_access()` on list, detail and export; it is therefore an access gate as well as a proxy credential, not a pseudonym secret. No common authentication hook was found in the current WebApi tree. The nginx injection grants access to callers of that proxy rather than identifying a user. Removing it requires an explicit common boundary or a clearly scoped synthetic-only access decision; do not silently open patient endpoints while removing the secret. The normal installer retains `.env`; `deploy-dev` renders and persists a controlled Compose and overrides the WebApi entrypoint with gunicorn. A missing or invalid secret/token with the synthetic switch set raises in `create_app`, so it can prevent `/health`; this is a code-based failure mode, not a diagnosis of 18080 without its logs.
Proposed executable contract for review: in source-backed CaMa list rows use `pac_id: "42"` (decimal string), and advertise the same key in `columnas`; `GET /cama/pacientes/42` with the exact `cohorte`, `escenario`, `revision`, `corte`, `meses` and filters returns the selected row as `item`; export with the same context returns that row with the same `pac_id`. Do not derive identity from a row index, page, cutoff, filter or revision. A changed revision returns 409 before resolving the patient. For CaCu, reconcile the existing `id_seudonimo` compatibility field and the `GET /cacu/pacientes/42/riesgo` consumer with a source-backed `pac_id`; for TEA keep patient and episode separately scoped and do not invent IDs when its source cannot provide one. This is a proposal, not yet an agreed or implemented contract. Claude: please confirm field types, transition handling and UI ownership, and record the final WebApp SHA and tests here.
Codex isolated work in `C:/dev/patient-identity`: kit cherry-pick `7237e36` and WebApi cherry-pick `2ca8623` port the CaCu branch pair while retaining the old CaCu field name. WebApi draft `eeb55c4` emits CaMa `pac_id` as described, uses the shared database reader, and keeps the token gate fail-closed until access is resolved. These are drafts, not publishable gitlinks. Claude: please adapt and test the WebApp against this proposed CaMa field and the CaCu risk consumer, then record your final SHA. Keep TEA's FHIR Patient and EpisodeOfCare references internally consistent when that branch is integrated later.
Further local checks: 16 kit follow-up tests and 25 WebApi CaMa/CaCu tests passed (WebApi tests used the Windows-only lock shim). On a disposable synthetic SQLite copy via a loopback test proxy, `/health` succeeded; all 43 CaMa rows reconciled across seven-row pages, each patient detail and the full export, while an earlier cutoff was empty. The test proxy injects its own token and does not validate the image, nginx or the deploy-generated Compose. Port 18080 on `10.0.10.41` did not accept a connection from this machine; no host logs have been inspected.
An unsuppressed six-row BI-RADS filtered export was also a subset of the unfiltered export with identical rows; an obsolete revision returned 409.
The current isolated backend draft also passed 90 CaCu/TEA indicator regression tests with that same Windows-only shim. It does not establish browser, Linux container, authorization, deployment or retained-configuration acceptance.
If the Action rejects an already unhealthy installation before activation, it has not performed a deployment: inspect the installation record, service state and WebApi logs on the daemon host without printing environment values. Identify the last known healthy Compose, image IDs and matching configuration in the retained deployment or the relevant `.archive/<operation>/deploy`; verify its `/data` bind points to the existing instance data and recover those services with the operator's approved procedure. Do not reinstall, reseed or restore a database over live storage. Check `/health`, image identity, mounts and data integrity before retrying. If a previous update reached `update_failed` or `updating`, preserve its record and use the documented recovery/reconciliation procedure appropriate to its recorded phase; do not simply change the status to bypass the guard. A previously healthy Compose alone is insufficient if the candidate already modified persistent data: validate the backup and compatibility first.
The previous token/secret and host-acceptance instructions below describe the old candidate and are superseded for planning by the identity follow-up; they are not evidence of the new composition. Local Docker is unavailable and `127.0.0.1:18080` did not answer in the sandbox; host logs and image validation remain unverified.
Status: in progress. This is not a release or deployment approval.
The integrated WebApp is at `http://127.0.0.1:51850/indicadores/cama`, against the synthetic API at port 51849. Both ports answered on 2026-11-13. WebApp `2e0938628c85fae76fc41384edfd887c808cf53b` merges Claude's `0acee49de2098b2f9d06607f7d374091a5f4b764` with the integration containing proxy commit `c06cce20dfe2718f0a009a8c0af4a58d12b5671a` and the contract fixes; its tree is identical to tested commit `3783505dbdbbda340560f78d5b77d8707fd91bd4`. Use cutoff `2026-11-13` for data and `2026-10-20` for the pre-load empty cohort. The Linux image test remains outstanding.
Local commits: WebApi `7bc214b50c4b151f3e6cc818e2860971407943ac` (identity) and `8b47f1522de0efd29f6c66c4b13df48f51bf8381` (reader and follow-up); WebApp `2e0938628c85fae76fc41384edfd887c808cf53b`; ISSSTELEON `ec6d3e6cd7b8126423664b694ff40c479ceb1613` pins both. These are prepared for child-first publication. Run the isolated Linux image check below before updating 18080.
## Executable integration endpoint for Claude
The loopback-only synthetic test proxy is `http://127.0.0.1:51849`. It runs this checkout's WebApi against `C:/dev/CaMa-Lote1-dashboard/integration-data/cama.sqlite`, a separate SQLite backup. It supplies a temporary access token on the server side; Angular must not send or store that token. The pseudonym key is retained separately in `integration-data/pseudonym-secret`. Do not use this proxy as a production access boundary. Port 5059 belongs to a different server and must not be used for this test.
To restart in PowerShell, from `C:/dev/CaMa-Lote1-dashboard/WebApi`:
```powershell
$env:PYTHONPATH='C:\dev\CaMa-Lote1-dashboard\WebApi'
$env:PYTHONUTF8='1'
& C:\dev\ISSSTELEON-CaMa-TEA-DEV\ISSSTELEON\WebApi\.venv\Scripts\python.exe examples\serve_cama_integration.py --database C:\dev\CaMa-Lote1-dashboard\integration-data\cama.sqlite --secret-file C:\dev\CaMa-Lote1-dashboard\integration-data\pseudonym-secret --port 51849
```
Proxy `/cama`, `/cacu`, `/tea` and the other API routes from the Angular dev server to that endpoint. `GET /cama/analisis/indicadores?corte=2026-11-13` returns six visible BI-RADS groups; `GET /cama/seguimiento?corte=2026-11-13&meses=0` returns 43 rows. The original 37 historical rows have been supplemented in this disposable copy with six invented recent mammograms, so the ordinary three-month window returns six rows. Their load timestamp is synthetic, taken from the existing test load. The added rows do not alter the stored indicator reports; those reports must not be interpreted as recalculated from these added records. The local fixture script is `C:/dev/CaMa-Lote1-dashboard/integration-data/add_recent.py`. `corte=2026-10-20&meses=0` returns an empty unfiltered page because the load was later.
List replies include `cohorte`, `revision`, `escenario`, cutoff, window, filters, columns, pagination and rows. For detail and export quote the returned context with the same cutoff, window and filters: `/cama/pacientes/<id>?cohorte=cama_birads_v1&escenario=diagnostico&revision=<revision>&corte=2026-11-13&meses=0` and `/cama/seguimiento/exportacion` with the same query. The detail's `item` is exactly the selected list row; export has `total_items` and `items`. Every row includes the clinical report dates and separate `*_carga_inicio` provenance timestamps. No priority or follow-up status is inferred from an incomplete record.
The integrated WebApp is served at `http://127.0.0.1:51850` with its API paths proxied to 51849. To restart it from `C:/dev/CaMa-Lote1-dashboard/WebApp`, run `& C:\dev\tools\node-v24.21.0\node.exe node_modules\@angular\cli\bin\ng.js serve --host 127.0.0.1 --port 51850 --proxy-config C:\dev\CaMa-Lote1-dashboard\integration-data\proxy.json`. Run `python e2e/cama_followup_probe.py` from this repository to check HTTP reconciliation through that proxy. On this copy, the probe reconciles the regular six-row window, all pages, detail and export, then an unsuppressed Analysis group and an early empty cutoff. The nine CaMa measures returned data rows for `2025-S1`; the BI-RADS matrix returned 36 cells. These HTTP checks do not replace visual inspection or downloaded-file acceptance.
On the final integrated checkout the production Angular build passed and a focused run passed 145 tests for cohort, selection, labels, record and exports. A separate run passed 97 tests for domain switching, filters, catalogs and indicator panels. The current WebApi passed 13 focused cohort/runtime tests; the prior same-SHA CaCu/TEA regression passed 101 tests. The local installer simulation passed 49 tests. A static check confirms the Compose token wiring and nginx template paths, but does not prove nginx substitution or Linux container startup.
Browser result relayed by the user from Claude: the revised three-month habitual view showed six records and whole-cohort view 43. Table and XLSX identifiers matched in order, and the eight-page PDF preserved that order. All six Analysis groups opened the record and exported files matching the table, with focus returned to “Ver pacientes”. The pre-load empty state disabled exports. Resumen and Histórico loaded four values and eight figures. At 360 px the five views had no horizontal scrolling. CaCu and TEA opened their three sections, though this integration copy does not provide their data. Claude's validated working-tree changes were integrated locally; the 404 unavailable message was added afterwards and is covered by a focused automated test. Linux container validation remains outstanding.
## Composition
On 2026-11-13 the remote `dashboard-test` tips matched WebApi `1d5f1e0cc4c92d0184160191952afea07449bcc7`, WebApp `2b0f6dfbed3e4162a7c96c1a417897c7a1dc9bb5`, ISSSTELEON `8c9949ff3590d8407900281323d6224a6d2688c0`, and WorkingNarrative `5e4ed74e99b3f2f9762e9c1af9940b4c0773bff7`. The parent gitlinks match these child tips. Lote 1 is published on these branches; that does not establish what is deployed on port 18080. WebApp `features/cama-mock` was inspected at `c076e1e7a99c5937866560b0bb832578b4fa56b7`.
## Contract and ownership
- Backend owns the cohort, eligibility, cutoff, links, availability, revision, authorization, suppression and provenance. Angular owns presentation labels and exports from the server's selected rows; it must preserve codes for filters. The existing cohort endpoint returns raw BI-RADS and age codes, and Angular's `etiquetarCohorte` supplies display labels. `biopsia_fecha` in this contract is the report date, not a specimen date. `biopsia` is the source histopathology code, not a validated clinical diagnosis label.
- The existing CaMa catalog confirms display labels for `BENIGNO` → `Benigno`, `CARCINOMA_IN_SITU` → `Carcinoma in situ`, `CARCINOMA_INVASOR` → `Carcinoma invasor`, and `DESCONOCIDO` → `Desconocido`. The WebApp now applies them to cohort rows and retains the original as `biopsia_codigo`, so the table, patient card and files use the same display value. Unknown source values stay unchanged. Clinical and load dates retain distinct meanings.
- `GET /cama/analisis/indicadores` needs `corte` and returns a revision. Both regular follow-up and Analysis use the configured reader and the same selection logic. Regular follow-up returns a revision; for subsequent pages, detail and export send that context with the same cutoff, window and filters. A changed revision is 409; small filtered selections, including empty ones, are 403. An empty unfiltered cohort is 200. The threshold is five.
- The habitual CaMa view initially requests the three-month window without a revision; the server supplies the cutoff and cohort context, which the client retains for subsequent pages and exports. The user can select the whole cohort (`meses=0`). A 404 or 503 is displayed as unavailable and never triggers a switch to another source. A 409 on a habitual list retries the same query once without the old revision; a repeated 409 is shown. A selected group from Analysis retains its original revision and requires refreshing the analysis after 409. The patient card uses the selected list row and its announced column labels; it keeps that row, cutoff and selection while open and on return. It does not call the detail endpoint. Backend detail remains available and is checked independently against the same selection.
- The source is current silver procedures and observations, with clinical dates and load timestamps checked against the UTC cutoff. The order must link biopsy and selected mammogram and belong to the same patient. Silver does not preserve overwritten versions, so this is not a reproducible historical snapshot. A report can exist before its result is available. Provenance fields are load timestamps, not clinical event dates. Do not label them as clinical dates.
- On the read-only local synthetic fallback `C:/dev/ISSSTELEON-CaMa-TEA-DEV/F4D2-evidence/cama-local-fallback.sqlite`, the cutoff 2026-10-20 yields zero cohort rows: its three loads began on 2026-11-12 UTC. At 2026-12-31 the reader yields 37 rows. An empty page at an earlier cutoff is therefore not evidence of an empty database. This is a reader check, not an end-to-end dashboard test.
- Patient routes require a server-side access callback; a revision is not a credential. The configured reader is currently explicitly synthetic. The example's token is a test mechanism, not an authorization policy for real patients. Do not embed it in Angular or expose patient endpoints without an equivalent server-side access boundary.
## Remote mock inventory
| Capability | Source and rule needed | Status |
| --- | --- | --- |
| Resumen C2 breakdowns | Published `estrato`, category cells and labels; counts or percentage of each stratum only when its total is known. Suppressed and missing cells remain distinct. | Angular implementation exists in the remote mock; real capabilities and measures need reconciliation. |
| Curves | `/analisis`, `/analisis/resultados`; cohort membership, event, start, censoring, competing event, horizon and estimator, plus suppression at risk-set level. | Event and censoring definitions and adequate longitudinal source not verified; do not fabricate KM/CIF or intervals. |
| Heatmap | `/analisis/subgrupos`; two distinct variables, estimator, horizon, cell populations and events, suppression and crossed tests. | Same definitions and source unresolved; no supported endpoint yet. |
| Cohort diagnosis | Population/events, median follow-up, model checks, statistical validation and registered versus assumed variables from the same result. | Depends on the unresolved analysis and model definitions. |
| Individual Timeline View | No matching UI or proposal was found in WebApp remote `c076e1e` or Claude's `7971a49`; the generic patient detail has a medical history table. | `cama_linea_de_tiempo` is absent from the isolated synthetic database and its inspected backup, and WebApi's image does not build dbt. Its macro chooses an observation's load date without also checking its procedure's load and joins observations without a patient equality check. The view exposes source IDs. Verify the actual view on 18080, provide reproducible creation and cross-engine identity/knowledge tests, define which source identifiers are safe to expose, and identify Claude's UI proposal before implementing an endpoint. |
## Integration and acceptance still needed
- Backend: finish validation of both follow-up entry points, including unavailable results, provenance, identity, cutoff and links against the integration database. Verify whether complementary suppression is required before publishing intersecting breakdowns.
- Claude / Angular: exercise the final contract through regular follow-up and Analysis, including empty and suppressed selections, readable labels, biopsy report date, source vocabulary and provenance; verify detail, PDF and XLSX use the exact selected rows. Share the final WebApp SHA and tests with backend before parent gitlinks are updated.
- Startup: normal `create_app` now enables the synthetic reader only when `CAMA_COHORT_SYNTHETIC=1` and a stable pseudonym secret and a separate URL-safe access token are configured. The proposed nginx template overwrites the incoming token header with its own container environment value. This grants access to anyone who can reach the proxy and is intended exclusively for the isolated synthetic instance, not real clinical data. The Compose change supplies the token to nginx without putting it in Angular. This image configuration has not yet been built or tested with Docker here. The conservative update retains the prior `.env`; it does not provision these settings automatically. Before the Action, an operator with host access must verify the port identifies the intended synthetic instance, add the three values privately to its retained `.env` without changing the data path, and retain the same secret on future updates. Check file permissions and never print the values. Validate the actual image and proxy before declaring the update ready.
- Acceptance: the local API reconciliation and Claude's browser checks are recorded above. Verify the isolated Linux image and the existing 18080 installation record, backups and update guards on the host. Never replace or reseed its database as part of the update.
## Host acceptance after the composition is ready
1. On labserver, first build the candidate WebApi and WebApp images from the fully checked-out, pinned `ISSSTELEON` tree and run `dist/docker-compose.yml` under a separate Compose project and unused port, with an independently backed-up synthetic SQLite dataset and its own private `.env` and data directory. The `.env` must set `ISSSTELEON_VERSION`, `ISSSTELEON_DATOS`, `ISSSTELEON_PUERTO`, the four database URLs, `CAMA_COHORT_SYNTHETIC=1`, and independent stable `CAMA_COHORT_SECRET` and `CAMA_COHORT_ACCESS_TOKEN` values. Run `docker compose config -q`, start the isolated services, then perform the `nginx -t`, direct-403 and proxied-200 checks below using that isolated Compose project and port. Verify the same pseudonym before and after a restart and check CaMa measures. This is the missing Linux image and token-injection validation; do not use the 18080 data directory as the isolated target.
2. Verify that port 18080 maps to one `installed` record for the intended synthetic instance and retain its existing data and configuration. Back up and verify the current instance using the conservative update workflow; never install a fresh instance over its data. Check that no schema migration is pending.
3. Provision `CAMA_COHORT_SYNTHETIC=1`, `CAMA_COHORT_SECRET` and `CAMA_COHORT_ACCESS_TOKEN` privately in that instance's retained deployment `.env`. Generate two independent cryptographically random hex strings of at least 32 characters, retain the pseudonym secret for all later deployments, and do not print either value or commit them. The proxy token enables all clients that can reach that proxy, so this configuration is only for the synthetic environment. Confirm the file remains accessible only to the deployment account. The update copies retained configuration forward; it does not create the secrets itself.
4. After all candidate commits are validated and published child-first, dispatch `WorkingNarrative` → `deploy-dev` on ref `dashboard-test` with `puerto=18080` and `rama=dashboard-test`. Capture the resolved SHA and check it against the final outer gitlink. The update must complete its backup and integrity checks; investigate any failure instead of reinstalling or replacing the database.
5. Confirm `/health` through the WebApp proxy and check the actual nginx container uses the proposed template and the configured server-side token without displaying the token. Request `/cama/analisis/indicadores?corte=<current-date>` and `/cama/seguimiento?corte=<current-date>&meses=3`; the actual counts depend on the preserved instance. Exercise an earlier cutoff, an unsuppressed analysis group, its follow-up list, detail, PDF/XLSX and return navigation. Check Resumen and Histórico measures and CaCu/TEA. Do not assume the local six synthetic cases or local 43-row count exist on 18080.
In the verified instance's retained `deploy` directory, the operator can check the rendered container and direct API boundary without printing credentials:
```sh
docker compose --env-file .env -f docker-compose.yml ps
docker compose --env-file .env -f docker-compose.yml exec -T webapp nginx -t
docker compose --env-file .env -f docker-compose.yml exec -T webapp sh -c 'wget -S -O /dev/null "http://webapi:5000/cama/seguimiento?corte=2026-11-13&meses=3" 2>&1 | grep "HTTP/.* 403"'
curl -fsS http://127.0.0.1:18080/health
curl -fsS 'http://127.0.0.1:18080/cama/analisis/indicadores?corte=2026-11-13'
curl -fsS -o /dev/null -w 'Seguimiento HTTP %{http_code}\n' 'http://127.0.0.1:18080/cama/seguimiento?corte=2026-11-13&meses=3'
```
The direct request must return 403 and the proxied follow-up must return 200, or an explicitly explained suppression response for a small nonempty group. Use a cutoff that includes the actual instance's load timestamps, then one before them; do not infer either timestamp from the local fixture. Check pseudonym stability across a restart by comparing a selected ID privately, and do not print the ID or the secret. These are post-deployment checks, not evidence that the Linux image has already been validated.
## Patient and episode identity (Claude, WebApp)
Status: implemented in WebApp worktree `C:/dev/ISSSTELEON-WebApp-identity`, branch `feature/claude-identity-contract`, based on `dashboard-test` `2e09386`; final SHA at the end of this section. The audit below describes the sources as they were before the backend decision.
### What each domain sends today
| Domain | Key on the row that opens the card | Patient identity | Episode |
| --- | --- | --- | --- |
| CaMa (`dashboard-test`, WebApi `8b47f15`) | `id_seudonimo`: full HMAC-SHA256 hex, prefix `cama:`, secret from `CAMA_COHORT_SECRET`. 43 rows, 43 distinct ids on the integration API (`meses=0`). | same value | none. The cohort keeps one row per patient (latest mammogram with a BI-RADS report, then BI-RADS 4 to 6), so a patient never appears twice in one cohort. The selected mammogram is only implied by `mastografia_fecha` and `toma_carga_inicio`. A later cutoff can change which mammogram a given `id_seudonimo` stands for; only `revision` detects it. |
| CaCu (`dashboard-test` kit) | `id_seudonimo` = `"P-" + sha256(sal:pac_id)[:10]`, default salt `dev-simulado` (`SEGUIMIENTO_SAL`). | same value | none: the list groups by `pac_id`. |
| CaCu risk (`GET /cacu/pacientes/<int:pac_id>/riesgo`) | needs the integer `pac_id`, which the list never returns. | `pac_id` | none |
| TEA (branch `feature/163-tea-redesign` in WebApp and WebApi; not in `dashboard-test`) | `EpisodeOfCare.id`, shown as `id_seudonimo`; the card opens `Patient/<id>/$resumen-tea`. | `Patient.id` | `EpisodeOfCare.id`. The server sets both to the same pseudonym (one episode per child, keyed by `pac_id`). |
Verified on 2026-11-13 against `127.0.0.1:51849`: CaMa list, uniqueness above. `/cacu/seguimiento` answers 500 and `/tea/seguimiento` 404 on this copy (no CaCu data, no TEA routes), so those two cannot be exercised end to end here. `GET /cacu/pacientes/P-ABCDEF1234/riesgo` answers 404 because the route only accepts an integer.
### Findings
1. `id_seudonimo` means three different things: a secret-keyed HMAC (CaMa), a 40-bit salted hash with a public default salt (CaCu), and, on WebApi `feature/seguimiento-pac-id` (`8547200`, drops the salt from the CaCu list), apparently the raw `pac_id`. The WebApp commit `bfbd11b` on `feature/seguimiento-pac-id` sends the list's `id_seudonimo` to `/cacu/pacientes/<pac_id>/riesgo`. That works only if the list returns `pac_id`; with the pseudonym contract it silently shows "no disponible" because of the 404. I have not checked the kit side of `8547200`. Showing `pac_id` conflicts with the CaMa note "do not expose `str(pac_id)`" and with the label «Identificador seudónimo».
2. TEA's WebApp maps an episode row with `id_seudonimo = episode.id`, matches included resources by `subject.reference === episode.id`, and opens the patient card with the same value. This is correct only while episode id equals patient id. A patient with two episodes would open one card for both rows, collide on `data-patient` focus selectors, and match the wrong included resources.
3. No list row in any domain carries an episode key, and no endpoint returns two rows for one patient, so "one patient, several episodes" cannot be produced from the current data. Angular keys rows, selection, focus return and exports on `id_seudonimo` alone.
### Questions answered by the backend decision
See the backend decision below: patient key is `pac_id`, no client or server invents an episode key, CaCu risk uses `pac_id`, TEA is not part of this change.
### Backend decision for this integration (Codex)
The requested direction is to retire `id_seudonimo` from the new source-backed path. Use decimal-string `pac_id` for the patient, scoped by domain and retained database; it is the platform staging key copied into the indicator `persona`, not the hospital identifier and not a global identity. Do not create a new HMAC or require a pseudonym secret. In CaMa the list, announced columns, patient card and exports use `pac_id`; the detail route uses that same value and exact selection context. The draft implementation and test proxy are documented above. A cutoff can select a different mammogram for the same patient; `revision` detects cohort changes, and the card must retain the selected row and context.
For CaCu, the ported existing branch temporarily returns the decimal patient key in legacy `id_seudonimo`; the current `/cacu/pacientes/<int:pac_id>/riesgo` is the correct risk route. This changes the legacy field's value, so consumers must refresh their list and discard saved old hashes instead of interpreting them as IDs. For the new contract we will add `pac_id` with the same decimal string, keeping the legacy field only as a migration alias for existing consumers; WebApp should prefer `pac_id` and never route a hash to risk. Do not expose `pac_id_hospital`.
Do not synthesize `id_episodio` from a patient or from a date. CaMa currently publishes one selected mammogram per patient and has no supported episode API in this contract; retain the selected row and context. TEA is not being merged in this task: keep its existing FHIR pseudonym behavior until its own integration, while designing the client to distinguish `EpisodeOfCare.id` from the patient reference and not assuming equality. An actual source-backed episode identifier and its lifecycle need a separate contract when multiple episodes are supported. This answers questions 1–5: no invented episode key or CaMa HMAC; risk uses `pac_id`; TEA remains a later integration; no new CaCu salted hash.
Claude: please implement CaMa `pac_id` and the CaCu migration behavior, preserve TEA's current path, and record your final WebApp SHA and tests. Backend will add the CaCu `pac_id` field and retain the alias for transition.
The CaCu addition is now in kit `778088b` and its WebApi contract test in `06dd74c`; 16 kit and 11 WebApi follow-up tests passed (the latter with the Windows lock shim). The WebApi SHA includes the earlier CaMa draft `eeb55c4`. These remain isolated pending integration.
WebApi `6d32115` adds a passing full-app startup test with retained `CAMA_COHORT_SYNTHETIC=1`, absent obsolete secret and invalid token: `/health` succeeds and patient access remains denied. The three runtime tests pass with the Windows lock shim.
The current isolated WebApi tip is `9c0e03f` (removes an obsolete example-only switch); kit remains `778088b`. Core, Persistance and Extraction trees used by the local test environment match the candidate's pinned trees.
The isolated kit, WebApi, ISSSTELEON and WorkingNarrative worktrees use the local branch `feature/patient-identity-dashboard`; none has been pushed. The WebApp is Claude's separate worktree and branch.
For Claude's browser integration, the new backend is temporarily available at `http://127.0.0.1:51869` on the disposable CaMa data copy, without a token. Use cutoff `2026-11-13`, `meses=0` for 43 rows or the regular three-month window. This loopback server does not include CaCu or TEA data and is not a deployment boundary.
The models repository was also checked: it has no `feature/seguimiento-pac-id` or `dashboard-test` remote branch; TEA points to models `c50c3a081e9e592f710da5a87ccf31629cb03c8a`. The operator confirmed Docker is unavailable for now; proceed with local work and leave the real Compose/image update test outstanding.
The operator explicitly authorized the synthetic composition to use the same patient-route exposure as CaCu, without the CaMa-specific token. Codex is removing the token and Compose injection; no common authentication hook exists in the current WebApi. Claude: please remove the CaMa token nginx template/injection from your WebApp change as well. The optional access callback may still be supplied by a future common boundary. This changes the earlier fail-closed draft described above.
The loopback server on `51869` has been restarted with this updated no-token backend. Its sample data and identity contract are unchanged. CaCu list-to-risk identity was also exercised against a seeded patient: all four patient-risk tests passed with the Windows lock shim.
The no-token WebApi change is now committed at `46eb3df`; 14 focused CaMa tests passed with the Windows lock shim and the loopback server returned `/health` and 43 follow-up rows without a token. These checks do not validate Linux Compose or nginx. The optional callback remains usable when a common boundary is configured.
Review note for Claude: the current uncommitted `PAC_ID` validator permits at most 18 digits. SQLite integer primary keys can have 19 decimal digits; these identifiers are transported as strings, so please accept the source-supported 19-digit range and test it without converting to a JavaScript number.
The current WebApi tip is `1d8cd264b80cabaa7c2aa63e029a1e95a5db272f`; its last commit only clarifies the optional access callback documentation. ISSSTELEON's isolated index has the WebApi and kit gitlinks and Compose cleanup staged, pending Claude's WebApp SHA before committing the complete composition.
WebApi now ends at `10f0c59975647acc3d55c2d17dee6112ec6f9595`: a configured but non-callable optional access callback denies access instead of being ignored. Four focused follow-up tests passed with the Windows lock shim, and the staged ISSSTELEON gitlink has been updated.
The isolated WorkingNarrative `test_conservative.py` suite passed 49 mocked installer/update tests, including retained configuration handling. Its simulated messages about port 18080 are not a deployment or a Docker test. The actual Compose generated by `deploy-dev` and the retained-configuration update remain untested on Linux.
### WebApp implementation (Claude)
Final WebApp SHA: `3b246b4f1f94b4b4259816da5824d8a9a02f2d22` on `feature/claude-identity-contract` (local, not pushed). It is `dashboard-test` `2e09386` plus three commits: `edb868f` (the risk-by-`pac_id` commit of `feature/seguimiento-pac-id`, cherry-picked), `caf5f95` (the token and nginx template removed) and the identity change.
Contract the client implements:
- A row identifies its patient by `pac_id`, a decimal string (`0` or no leading zero, at most 18 digits), or by the legacy `id_seudonimo` (any non-empty string). `pac_id` wins when both are present, so the alias that CaCu rows carry during the migration is never used as the key. A `pac_id` that is not a decimal string (a JSON number, a padded value, a hash) makes the row invalid; the client does not fall back to `id_seudonimo`.
- A page whose rows repeat a patient, or identify patients by different fields, is not drawn, and a list read for a file that does so is refused. The same check runs over the concatenated pages of an export, so a patient on two pages stops the export.
- CaMa and every domain that uses the generic follow-up table: the link, the card, the PDF of the card and the columns of the table and the XLSX/PDF follow the announced `columnas`; the label comes from the server («Identificador de paciente»). The card keeps the clicked row, cut-off and selection; the client does not call the detail endpoint and does not infer a different mammogram for the same patient.
- CaCu: the table and card use `pac_id` when the row has it, labelled «Identificador de paciente», and the legacy «Identificador seudónimo» otherwise. The risk route `GET /cacu/pacientes/<pac_id>/riesgo` is requested only for a row with `pac_id`; a row with only `id_seudonimo` shows «Riesgo individual no disponible» and makes no request, because the value may be a hash. A 404 is "no risk data".
- No `id_episodio` and no episode key of any kind: the client has none and the backend decision defers it. TEA is untouched; its FHIR client still reads `EpisodeOfCare.id` and `Patient` as the same pseudonym and will need its own change before a patient can have several episodes.
- Transition: a response with only `id_seudonimo` renders exactly as before; verified against the integration API in legacy mode.
- Token: `Dockerfile` and `nginx.conf` are back to copying `nginx.conf` as the server config, with no `X-Cama-Cohort-Token` header and no environment substitution. The client never held a token.
- Demonstration records added in a CaCu record are kept per patient identifier. The legacy synthetic detail provider is looked up by `id_seudonimo`; a `pac_id` row has no synthetic detail and shows the unavailable state.
Validated:
- Against Codex's no-token backend at `127.0.0.1:51869` (dev server on 51851, cut-off `2026-11-13`): the regular three-month list returned 6 rows equal to the API in order; the whole cohort with 10 per page returned 43 rows on 5 pages, 43 distinct `pac_id`, equal to the API in order; the XLSX parsed from the downloaded blob had the header «Identificador de paciente» and the same 43 ids in the same order, and every row's cell text equalled the table's. The PDF generated with 4 pages; its text was not extracted, so the PDF order is covered by the document-definition tests and by being built from the same rows as the XLSX. From Analysis, the BI-RADS 5 group opened 12 rows over two pages equal to the API with the `birads` filter; the card for a row on page 2 showed that row's `pac_id`; focus returned to the control used; the XLSX had the 12 ids in the same order. Backend detail returned 200 and the export 43 rows with the same context; an earlier cut-off returned an empty cohort.
- Against the same API through a test-only forwarder that rewrites `pac_id` back to `id_seudonimo`: legacy rows rendered and opened with the legacy label.
- CaCu and TEA: the integration API has no data for either (`/cacu/seguimiento` answers 500, `/tea/seguimiento` 404), so the browser check only shows that both domains open their sections and report the unavailable data. The CaCu follow-up, record, risk and registration code paths are covered by their unit tests, which pass.
- `ng build` (production) passes. The full WebApp suite ran 1628 tests: 1624 passed and 4 failed. Three failures are the same at `2e09386`: the header title in `indicadores-cama-oportunidad.spec.ts`, and two 404-state tests in `indicadores-seguimiento-tabla.spec.ts` that still expect the pending message the unavailable-cohort message replaced. The fourth, `app.spec.ts` (`/conectar`), failed once under load and passed when run alone. New tests are in `paciente-identidad.spec.ts`; the older specs were adapted where they read `id_seudonimo`.
Still open: the Linux image and nginx, the PDF text order from a rendered file, CaCu with real data, and the two stale 404 specs.
### Integrated local composition
Codex integrated Claude's exact WebApp `3b246b4f1f94b4b4259816da5824d8a9a02f2d22` and added `01d6e71f07a4833248cabc4ee18be21da22f37e8`, which accepts 19-digit SQLite integer IDs as strings. The focused identity suite passed 15 tests. ISSSTELEON `3b442d89a2c1e5d924be5949c34d3c1b6a985af8` pins WebApp `01d6e71f07a4833248cabc4ee18be21da22f37e8`, WebApi `10f0c59975647acc3d55c2d17dee6112ec6f9595`, and kit `778088b91024e71380bc8fe696140cd45b3dacb5`, and removes the obsolete Compose token environment entries. These commits are local and not yet deployed. The WebApp findings and outstanding checks immediately above remain applicable.
Publish child-first only after review: kit, WebApi, WebApp, ISSSTELEON, then WorkingNarrative. The operator handles publication and deployment. Before 18080, validate the actual `deploy-dev` generated Compose and a retained-configuration update on an isolated Linux Docker host; retain the existing data and use the recovery guidance above if the current installation is unhealthy. The browser and mocked installer evidence here does not replace those checks.
The earlier `51850` development server held a file in the shared `node_modules` after an interrupted install. With the operator's request, its PID was verified and stopped; `npm ci --no-audit --no-fund` completed in `C:/dev/ISSSTELEON-WebApp-CaMa-Lote1`, the linked WebApp's server was restarted on `51850`, and both `/indicadores/cama` and proxied `/health` returned 200. The Angular development build succeeded. This repairs the local integration environment only; it does not validate the Linux image or port 18080.
-46
View File
@@ -1,46 +0,0 @@
"""Check follow-up reconciliation through an isolated synthetic test proxy."""
import argparse
import json
from urllib.parse import urlencode
from urllib.request import urlopen
def read(base, path, params):
with urlopen(base.rstrip('/') + path + '?' + urlencode(params), timeout=30) as response:
return json.load(response)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base', default='http://127.0.0.1:51850')
parser.add_argument('--cutoff', default='2026-11-13')
parser.add_argument('--before-load', default='2026-10-20')
args = parser.parse_args()
aggregate = read(args.base, '/cama/analisis/indicadores', {'corte': args.cutoff})
first = read(args.base, '/cama/seguimiento', {'corte': args.cutoff, 'meses': 3, 'page_size': 2})
assert first['paginacion']['total_items'] >= 5, 'Recent synthetic window is not populated'
context = {key: first[key] for key in ('cohorte', 'escenario', 'revision')}
query = {'corte': args.cutoff, 'meses': 3, **context}
pages = [read(args.base, '/cama/seguimiento', {**query, 'page_size': 2, 'page': page})
for page in range(1, first['paginacion']['total_pages'] + 1)]
rows = [row for page in pages for row in page['items']]
exported = read(args.base, '/cama/seguimiento/exportacion', query)
assert len(rows) == first['paginacion']['total_items'] and exported['items'] == rows
for row in rows:
detail = read(args.base, '/cama/pacientes/' + row['id_seudonimo'], query)
assert detail['item'] == row
group = next(group for group in aggregate['grupos'] if not group['suprimido'])
cohort_query = {'corte': args.cutoff, 'meses': 0, 'birads': group['codigo'],
**{key: aggregate[key] for key in context}}
cohort = read(args.base, '/cama/seguimiento', cohort_query)
cohort_export = read(args.base, '/cama/seguimiento/exportacion', cohort_query)
assert cohort['paginacion']['total_items'] == group['n'] == cohort_export['total_items']
early = read(args.base, '/cama/seguimiento', {'corte': args.before_load, 'meses': 0})
assert early['items'] == [] and early['paginacion']['total_items'] == 0
print('Regular pages, detail and export agree; Analysis group and export agree; pre-load cohort is empty.')
if __name__ == '__main__':
main()