[+] lab7
Grade 3 secure application acceptance / secure (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Xabenskie
2026-11-30 09:09:57 +03:00
parent 20afc2c790
commit 4eca49fe3d
149 changed files with 68317 additions and 58 deletions
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Generate local role secrets and operator-only provisioning material."""
import hashlib
import json
import os
from pathlib import Path
import secrets
import urllib.parse
ROOT=Path(__file__).resolve().parents[1]
S=ROOT/'secrets';OP=S/'operator'
def secret(name):
path=S/name
if not path.exists(): path.write_text(secrets.token_hex(24));path.chmod(0o444)
return path.read_text().strip()
def main():
os.umask(0o077)
roles={};workloads={}
for role in ('api','worker','relay'):
roles['db_'+role]=secret('db_'+role+'_password')
sid='lab7-'+role
password=secret('s3_'+role+'_secret')
id_path=S/('s3_'+role+'_id')
if id_path.exists(): id_path.chmod(0o600)
id_path.write_text(sid);(S/('s3_'+role+'_id')).chmod(0o444)
broker_user='consumer' if role=='worker' else 'producer'
broker_password=secret('broker_'+broker_user+'_password')
values={'DATABASE_URL':'postgresql://db_'+role+':'+roles['db_'+role]+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/trust/ca.crt',
'S3_ACCESS_KEY_ID':sid,'S3_SECRET_ACCESS_KEY':password,
'BROKER_URL':'rediss://'+broker_user+':'+broker_password+'@broker:'+('6381' if role=='worker' else '6380')+'/0'}
if role=='api': values['CACHE_URL']='rediss://profile:'+secret('cache_password')+'@redis:6380/0'
workloads[role]=values
secret('s3_test_secret')
test_id=S/'s3_test_id'
if test_id.exists():test_id.chmod(0o600)
test_id.write_text('lab7-test');test_id.chmod(0o444)
if (OP/'workloads.json').exists(): (OP/'workloads.json').chmod(0o600)
(OP/'workloads.json').write_text(json.dumps(workloads));(OP/'workloads.json').chmod(0o444)
if (OP/'db-roles.json').exists(): (OP/'db-roles.json').chmod(0o600)
(OP/'db-roles.json').write_text(json.dumps(roles));(OP/'db-roles.json').chmod(0o444)
# Root URL exists only for migrate/operator test containers, with verify-full.
root_url=S/'database_url';root_url.chmod(0o600)
root_url.write_text('postgresql://messenger:'+secret('postgres_password')+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/trust/ca.crt');root_url.chmod(0o444)
# Redis authenticates separately from TLS listener identities. No default data permissions.
def pw(value): return '#'+hashlib.sha256(value.encode()).hexdigest()
broker_acl='user default on nopass -@all +ping\n'
broker_acl+='user producer on '+pw(secret('broker_producer_password'))+' ~attachment-jobs -@all +xadd +ping +client|setinfo\n'
broker_acl+='user consumer on '+pw(secret('broker_consumer_password'))+' ~attachment-jobs -@all +xgroup|create +xreadgroup +xautoclaim +xack +xdel +ping +client|setinfo\n'
cache_acl='user default on nopass -@all +ping\nuser profile on '+pw(secret('cache_password'))+' ~user:* -@all +get +set +ping +client|setinfo\n'
cache_acl+='user tester on '+pw(secret('cache_test_password'))+' ~* -@all +get +set +del +ttl +flushdb +ping +client|setinfo\n'
test_cache=S/'test_cache_url'
if test_cache.exists():test_cache.chmod(0o600)
test_cache.write_text('rediss://tester:'+secret('cache_test_password')+'@redis:6382/0');test_cache.chmod(0o444)
for name,value in [('broker.acl',broker_acl),('cache.acl',cache_acl)]:
p=S/name
if p.exists():p.chmod(0o600)
p.write_text(value);p.chmod(0o444)
# Scoped S3 policies: API writes staging only; worker publishes; relay performs cleanup.
policies=S/'policies';policies.mkdir(exist_ok=True);policies.chmod(0o755)
for role in ('api','worker','relay','test'):
entries=[{'Effect':'Allow','Action':['s3:GetBucketLocation'],'Resource':['arn:aws:s3:::messenger-attachments']},
{'Effect':'Allow','Action':['s3:ListBucket'],'Resource':['arn:aws:s3:::messenger-attachments'],
'Condition':{'StringLike':{'s3:prefix':['originals/*','staging/*','variants/*']}}}]
rights={'api':{'staging':['GetObject','PutObject','DeleteObject'],'originals':['GetObject'],'variants':['GetObject']},
'worker':{'staging':['GetObject','DeleteObject'],'originals':['GetObject','PutObject'],'variants':['GetObject','PutObject']},
'relay':{prefix:['GetObject','DeleteObject'] for prefix in ['staging','originals','variants']},
'test':{prefix:['GetObject','PutObject','DeleteObject'] for prefix in ['staging','originals','variants']}}[role]
for prefix,actions in rights.items(): entries.append({'Effect':'Allow','Action':['s3:'+a for a in actions],'Resource':['arn:aws:s3:::messenger-attachments/'+prefix+'/*']})
p=policies/(role+'.json')
if p.exists():p.chmod(0o600)
p.write_text(json.dumps({'Version':'2012-10-17','Statement':entries}));p.chmod(0o444)
# Provisioning includes Grafana's own private TLS client key, generated outside Git.
template={'apiVersion':1,'datasources':[{'name':name,'uid':name.lower(),'type':name.lower(),'access':'proxy','isDefault':name=='Prometheus'} for name in ['Prometheus','Loki','Tempo']]}
for item in template['datasources']:
hostname={'Prometheus':'prometheus','Loki':'loki','Tempo':'tempo'}[item['name']]
item['url']='https://'+hostname+':9443'
item.setdefault('jsonData',{}).update(tlsAuth=True,tlsAuthWithCACert=True,httpMethod='GET')
item['secureJsonData']={'tlsCACert':(S/'trust/ca.crt').read_text(),'tlsClientCert':(S/'pki/grafana/tls.crt').read_text(),'tlsClientKey':(S/'pki/grafana/tls.key').read_text()}
target=S/'grafana-datasources.yaml'
if target.exists():target.chmod(0o600)
target.write_text(json.dumps(template));target.chmod(0o444)
print('Scoped backend credentials and private provisioning ready; values hidden.')
if __name__=='__main__': main()