Compare commits

...
Author SHA1 Message Date
Canina Automation 69dd6922f6 fix(stage): accept persisted ADMIN human role in maintenance
Stage author bootstrap (dedicated repair) / bootstrap (push) Successful in 1m5s
Deploy Canina / deploy (push) Successful in 2m41s
2026-10-28 21:08:40 +00:00
Canina Automation a0d588ba12 fix(stage): retain allowlisted bootstrap API failure status
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 48s
2026-10-28 21:02:09 +00:00
Canina Automation 5c93517b9e fix(stage): stream Redis snapshot with native stdout support
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 49s
2026-10-28 20:57:03 +00:00
Canina Automation 2408bafc49 fix(stage): verify existing database alias for bootstrap runtime
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 38s
2026-10-28 20:48:21 +00:00
7 changed files with 102 additions and 10 deletions

No files matched your search

+8
View File
@@ -94,6 +94,14 @@ describe('Public authors are attribution only, never principals', () => {
const ctx = { getHandler: () => null, getClass: () => null, switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
expect(() => guard.canActivate(ctx)).toThrow(ForbiddenException);
});
it.each(['Admin', 'ADMIN', 'SUPER_ADMIN'])('human admin guard accepts actual human role %s', role => {
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: { role } }) }) } as any;
expect(new HumanAdminGuard().canActivate(ctx)).toBe(true);
});
it.each(['User_PetOwner', 'adminsuper', '', undefined])('human admin guard denies nonallowlisted role %s', role => {
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: { role } }) }) } as any;
expect(() => new HumanAdminGuard().canActivate(ctx)).toThrow(ForbiddenException);
});
it('human admin guard rejects author with admin role', () => {
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
expect(() => new HumanAdminGuard().canActivate(ctx)).toThrow(ForbiddenException);
@@ -10,7 +10,7 @@ import {
export class HumanAdminGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const user = context.switchToHttp().getRequest().user;
if (!user || user.isPublicAuthor || user.isApiKey || !['Admin', 'SUPER_ADMIN'].includes(user.role))
if (!user || user.isPublicAuthor || user.isApiKey || !['Admin', 'ADMIN', 'SUPER_ADMIN'].includes(user.role))
throw new ForbiddenException('Human administrator required');
return true;
}
+20 -3
View File
@@ -16,6 +16,18 @@ op = importlib.util.module_from_spec(spec)
spec.loader.exec_module(op)
def validate_runtime_url(value, database_info):
from urllib.parse import urlparse
url = urlparse(value)
aliases = {a for n in database_info.get('NetworkSettings', {}).get('Networks', {}).values()
for a in (n.get('Aliases') or [])}
if (url.scheme not in ('postgres', 'postgresql')
or url.hostname not in ({op.STAGE, 'db_stage'} & (aliases | {op.STAGE}))
or url.port not in (None, 5432) or url.path != '/caninodb_stage'
or url.fragment or url.query not in ('', 'schema=public')):
raise ValueError('Existing Stage runtime DB identity mismatch')
def run(env=os.environ, call=subprocess.run):
sha = env.get('GITHUB_SHA', '')
refs = {'refs/heads/ops/author-bootstrap-stage-rehearse': 'rehearse',
@@ -47,10 +59,15 @@ def run(env=os.environ, call=subprocess.run):
if info.get('Name') != '/' + op.BACKEND or not info.get('State', {}).get('Running'):
raise ValueError('Existing Stage runtime unavailable')
values = dict(x.split('=', 1) for x in info['Config']['Env'])
database_info = json.loads(command(['docker', 'inspect', op.STAGE], capture_output=True).stdout)[0]
op.check_identity(database_info)
validate_runtime_url(values.get('DATABASE_URL', ''), database_info)
# Dedicated maintenance scope uses the independently verified canonical name.
# Preserve credentials, remove only the already validated default schema hint.
from urllib.parse import urlparse
url = urlparse(values.get('DATABASE_URL', ''))
if url.hostname != op.STAGE or url.path != '/caninodb_stage' or url.query or url.fragment:
raise ValueError('Existing Stage runtime DB identity mismatch')
runtime_url = urlparse(values['DATABASE_URL'])
credentials = runtime_url.netloc.rsplit('@', 1)[0] + '@' if '@' in runtime_url.netloc else ''
values['DATABASE_URL'] = runtime_url._replace(netloc=credentials + op.STAGE + ':5432', query='').geturl()
if any('\n' in v or '\r' in v for v in values.values()): raise ValueError('Multiline env refused')
live_env = evidence / 'stage.env'
op.private_write(live_env, '\n'.join(k + '=' + v for k, v in values.items()).encode())
+10 -5
View File
@@ -26,7 +26,12 @@ def check_image(d, image, sha):
def api(d, backend, token):
# No retry: a lost response can follow a committed transaction.
result = json.loads(d.run(['exec', '-i', backend, 'node', '-e', API_JS], token, timeout=40))
try:
result = json.loads(d.run(['exec', '-i', backend, 'node', '-e', API_JS], token, timeout=40))
except subprocess.CalledProcessError as error:
diagnostic = (error.stderr or b'').decode(errors='replace')
match = re.search(r'BOOTSTRAP_API_(?:STATUS_[0-9]{3}|CONTRACT|TRANSPORT)', diagnostic)
raise ValueError(match.group(0) if match else 'Bootstrap API process failed') from None
if {a.get('id') for a in result.get('authors', [])} != AUTHOR_IDS:
raise ValueError('API returned unexpected author identities')
return result
@@ -127,9 +132,9 @@ def readiness(d, cid):
API_JS = r'''const fs=require('fs'); const token=fs.readFileSync(0,'utf8').trim();
(async()=>{let r=await fetch('http://127.0.0.1:39071/api/admin/users/stage-author-restoration',{
method:'POST',headers:{Authorization:'Bearer '+token},signal:AbortSignal.timeout(30000)});
if(!r.ok)throw Error('API status '+r.status);let x=await r.json();
if(x.success!==true||x.totalConfigured!==5||x.restoredCount+x.existingCount!==5)throw Error('API contract');
process.stdout.write(JSON.stringify(x));})().catch(()=>{process.exit(1)});'''
if(!r.ok){console.error('BOOTSTRAP_API_STATUS_'+r.status);process.exit(1)}let x=await r.json();
if(x.success!==true||x.totalConfigured!==5||x.restoredCount+x.existingCount!==5){console.error('BOOTSTRAP_API_CONTRACT');process.exit(1)}
process.stdout.write(JSON.stringify(x));})().catch(()=>{console.error('BOOTSTRAP_API_TRANSPORT');process.exit(1)});'''
def rehearse(d, backup, sql, backend_image, env_file, token, owned, evidence):
def clone():
@@ -161,7 +166,7 @@ def rehearse(d, backup, sql, backend_image, env_file, token, owned, evidence):
if redis_info.get('Name') != '/canino_redis_stage' or not redis_info.get('State', {}).get('Running'):
raise ValueError('Stage session validator unavailable')
rdb = d.run(['exec', 'canino_redis_stage', 'sh', '-c',
'export REDISCLI_AUTH="$REDIS_PASSWORD"; exec redis-cli --rdb /dev/stdout'], timeout=120)
'if [ -n "$REDIS_PASSWORD" ]; then export REDISCLI_AUTH="$REDIS_PASSWORD"; else unset REDISCLI_AUTH; fi; exec redis-cli --rdb -'], timeout=120)
if not rdb.startswith(b'REDIS'): raise ValueError('Invalid Stage blacklist snapshot')
redis = d.run(['create', '--pull=never', '--network=container:' + cid,
redis_info['Image'], 'redis-server', '--bind', '127.0.0.1',
+47
View File
@@ -30,6 +30,13 @@ class WorkflowTests(unittest.TestCase):
if args[:2] == ['docker','build']:
if build_fail: raise subprocess.CalledProcessError(1,args)
Path(args[args.index('--iidfile')+1]).write_text('sha256:'+'b'*64)
if args[:3] == ['docker','inspect', ci.op.STAGE]:
return subprocess.CompletedProcess(args,0,stdout=json.dumps([{
'Name':'/'+ci.op.STAGE, 'Image':ci.op.POSTGRES_IMAGE, 'Id':'c'*64,
'State':{'Running':True}, 'Config':{'Env':['POSTGRES_DB=caninodb_stage']},
'Mounts':[{'Destination':'/var/lib/postgresql/data','RW':True,'Type':'volume'}],
'NetworkSettings':{'Networks':{'stage':{'Aliases':['canino_db_stage','db_stage']}}}
}]).encode())
if args[:2] == ['docker','inspect']:
return subprocess.CompletedProcess(args,0,stdout=json.dumps([{
'Name':'/canino_backend_stage','State':{'Running':True},
@@ -51,6 +58,23 @@ class WorkflowTests(unittest.TestCase):
self.assertEqual((root/'evidence/clone.env').stat().st_mode & 0o777,0o600)
return calls
def test_stage_runtime_url_identity(self):
network = {'NetworkSettings': {'Networks': {'stage': {'Aliases': ['canino_db_stage', 'db_stage']}}}}
ci.validate_runtime_url('postgresql://u:p@db_stage:5432/caninodb_stage?schema=public', network)
ci.validate_runtime_url('postgresql://u:p@canino_db_stage:5432/caninodb_stage', network)
for url in ['postgresql://u:p@db_stage/caninodb_stage?'+q for q in
('&&','schema=public&','%73chema=public','schema=%70ublic')] + [
'postgresql://u:p@db_prod/caninodb_stage?schema=public',
'postgresql://u:p@db_stage/caninodb_prod?schema=public',
'postgresql://u:p@db_stage/caninodb_stage?schema=private',
'postgresql://u:p@db_stage/caninodb_stage?schema=public&schema=public',
'postgresql://u:p@db_stage/caninodb_stage?sslmode=disable',
'postgresql://u:p@db_stage:5433/caninodb_stage',
'postgresql://u:p@db_stage/caninodb_stage#fragment']:
with self.assertRaises(ValueError): ci.validate_runtime_url(url, network)
with self.assertRaises(ValueError):
ci.validate_runtime_url('postgresql://u:p@db_stage/caninodb_stage', {})
def test_real_ci_driver_rehearse(self): self.exercise('refs/heads/ops/author-bootstrap-stage-rehearse')
def test_real_ci_driver_apply(self): self.exercise('refs/heads/ops/author-bootstrap-stage-apply')
def test_missing_token_still_builds(self):
@@ -72,6 +96,29 @@ class WorkflowTests(unittest.TestCase):
class MaintenanceTests(unittest.TestCase):
def test_api_failure_diagnostic_never_leaks_stderr(self):
class D:
def run(self, *args, **kwargs):
raise subprocess.CalledProcessError(1, ['fixture'], stderr=b'private fixture BOOTSTRAP_API_STATUS_403 private fixture')
with self.assertRaisesRegex(ValueError, '^BOOTSTRAP_API_STATUS_403$'):
ci.op.api(D(), 'fixture', b'fixture')
def test_snapshot_stream_auth_matches_existing_configuration(self):
import os
text = (HERE / 'operation.py').read_text()
command = next(line.strip().split("'", 2)[1] for line in text.splitlines()
if 'if [ -n "$REDIS_PASSWORD" ]' in line)
self.assertIn('exec redis-cli --rdb -', command)
with tempfile.TemporaryDirectory(dir='/opt/data/cache/scratch') as tmp:
cli = Path(tmp) / 'redis-cli'
cli.write_text('#!/bin/sh\nprintf "%s:%s:%s" "${REDISCLI_AUTH-unset}" "$1" "$2"\n')
cli.chmod(0o700)
for password, expected in [('', 'unset:--rdb:-'), ('fixture', 'fixture:--rdb:-')]:
env = dict(os.environ, PATH=tmp+':'+os.environ['PATH'],
REDIS_PASSWORD=password, REDISCLI_AUTH='stale-fixture')
result = subprocess.run(['sh','-c',command], env=env, capture_output=True, text=True, check=True)
self.assertEqual(result.stdout, expected)
def test_no_published_port_real_validator_and_single_post(self):
op=ci.op
calls=[]
@@ -33,7 +33,7 @@ class RecoveryTests(unittest.TestCase):
return b'[{"Name":"/canino_redis_stage","State":{"Running":true},"Image":"redis"}]'
if args[:2] == ['inspect', '-f']: return b'true'
if args[0] == 'create': return ('b'*64).encode()
if '--rdb /dev/stdout' in ' '.join(args): return b'REDISsnapshot'
if '--rdb -' in ' '.join(args): return b'REDISsnapshot'
if 'PING' in args: return b'PONG'
if args[0] == 'run': return ('a'*64).encode()
if 'pg_restore' in args:
@@ -0,0 +1,15 @@
# Stage bootstrap runtime URL compatibility
## Scope and evidence
Run 1346 at reviewed source 46da1c5339a9bd4dc2585c9f1912d8a034d927ce built the backend image, then failed before operation evidence or credential copies. Read-only inspection found the existing Stage DATABASE_URL host `db_stage` and literal query `schema=public`. Fixed `canino_db_stage` advertises aliases `canino_db_stage` and `db_stage` on its actual Docker network. No live DDL or business data operation occurred.
## Acceptance and plan
Keep source/ref/review bindings, original archive recovery and apply gates unchanged. Independently inspect and validate the exact fixed Stage DB container using the existing image/database/durable-mount check before URL acceptance. Accept only fixed canonical hostname or observed `db_stage` alias, database `caninodb_stage`, default/5432 port and no fragment. Query is empty or exactly literal `schema=public`; reject duplicates, alternate schema, malformed/encoded alternatives and any other key. Preserve runtime values privately, without changing Stage configuration.
## Tests and tasks
- RED: new runtime URL contract test failed because validator was absent.
- GREEN: 16 bootstrap tests and 17 unchanged schema-operation tests passed.
- Independent review flagged parse_qsl normalization; replaced with literal query allowlist and regressions covering all four review probes. Bootstrap 16 tests pass again; diff check clean.
- Review integrated patch, bind repository reviewed-SHA secret to new commit, then repeat dedicated rehearsal and apply only after real full clone recovery passes.
No frontend/backend files changed, so no new graph build was needed. Existing graph dirty stamp, .specify and unrelated evidence remain untouched. Original source/release evidence is not represented as green live acceptance.