Organize device inventory by customer and restrict token access to its audience
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish selected signed agent packages for first enrollment in empty customer catalogs."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
from dev_stage import ssh_prefix
|
||||
|
||||
|
||||
def publish(tenant, platform, release):
|
||||
root = Path('/opt/rust-discovery/devstate/mvp-releases')
|
||||
labels = {'x86_64-pc-windows-gnu': 'windows-gnu', 'x86_64-unknown-linux-gnu': 'linux'}
|
||||
label = labels[platform]
|
||||
source = root / 'objects' / tenant
|
||||
config = root / 'config'
|
||||
dest = config / 'customer-starters'
|
||||
sql = """SELECT json_build_object('envelope',convert_from(envelope,'UTF8')::json,
|
||||
'agent',agent_sha256,'agent_size',agent_bytes,'helper',helper_sha256,'helper_size',helper_bytes)
|
||||
FROM agent_update_releases WHERE tenant_id=:'customer' AND platform=:'platform' AND release_id=:'release';"""
|
||||
row = json.loads(subprocess.check_output(['docker','exec','-i','rust-discovery-server-postgres-1',
|
||||
'psql','-XqtA','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm','-v','customer='+tenant,
|
||||
'-v','platform='+platform,'-v','release='+release],input=sql.encode()))
|
||||
local_pin = config / (label+'-bootstrap.'+tenant+'.json')
|
||||
if local_pin.exists():
|
||||
worker = json.loads(local_pin.read_bytes())['current']
|
||||
else:
|
||||
default = json.loads((config / (label+'-bootstrap.json')).read_bytes())
|
||||
worker = {'sha256': default['updater_sha256'], 'bytes': default['updater_bytes']}
|
||||
desc = {'envelope': row['envelope'], 'worker': worker}
|
||||
dest.mkdir(mode=0o700,exist_ok=True)
|
||||
assert dest.is_dir() and not dest.is_symlink()
|
||||
os.chown(dest,10001,10001)
|
||||
os.chmod(dest,0o700)
|
||||
def write(name, blocks):
|
||||
with tempfile.NamedTemporaryFile(dir=dest,delete=False) as out:
|
||||
temp = Path(out.name)
|
||||
try:
|
||||
digest = hashlib.sha256()
|
||||
for data in blocks:
|
||||
out.write(data)
|
||||
digest.update(data)
|
||||
if len(name)==64 and digest.hexdigest()!=name:
|
||||
raise ValueError('Package object digest mismatch')
|
||||
out.flush()
|
||||
os.fchown(out.fileno(),10001,10001)
|
||||
os.fsync(out.fileno())
|
||||
os.replace(temp,dest/name)
|
||||
finally:
|
||||
temp.unlink(missing_ok=True)
|
||||
for digest,size in [(row['agent'],row['agent_size']),(row['helper'],row['helper_size']),(worker['sha256'],worker['bytes'])]:
|
||||
if not re.fullmatch('[a-f0-9]{64}',digest) or not 0<size<=268435456:
|
||||
raise ValueError('Invalid package descriptor')
|
||||
with os.fdopen(os.open(source/digest,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:
|
||||
info=os.fstat(f.fileno())
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size!=size:
|
||||
raise ValueError('Missing regular package file')
|
||||
write(digest,iter(lambda:f.read(1024*1024),b''))
|
||||
write(platform+'.json',[json.dumps(desc,separators=(',',':')).encode()])
|
||||
print(json.dumps({'starter_platform':platform,'release_id':release}))
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--tenant',required=True,type=uuid.UUID)
|
||||
parser.add_argument('--platform',required=True,choices=['x86_64-unknown-linux-gnu','x86_64-pc-windows-gnu'])
|
||||
parser.add_argument('--release',required=True,type=uuid.UUID)
|
||||
args=parser.parse_args()
|
||||
imports='import hashlib,json,os,re,stat,subprocess,tempfile\nfrom pathlib import Path\n'
|
||||
script=imports+inspect.getsource(publish)+'\npublish'+repr((str(args.tenant),args.platform,str(args.release)))
|
||||
subprocess.run([*ssh_prefix('server'),'python3 -I -'],input=script,text=True,check=True)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -38,6 +38,21 @@ def on_server(payload):
|
||||
work.mkdir(mode=0o700,exist_ok=True)
|
||||
with (work/'deployment.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
if payload['action']=='grant-customer-admin':
|
||||
principal = payload['principal']
|
||||
if 'local:' + str(uuid.UUID(principal.removeprefix('local:'))) != principal:
|
||||
raise ValueError('Invalid bootstrap principal')
|
||||
config_path = root / 'devstate/public-auth/users.json'
|
||||
configured = json.loads(config_path.read_bytes())['users']
|
||||
if not any(u['principal'] == principal and u['tenant_id'] == TENANT
|
||||
and u['username'] == 'kevin' and not u['disabled'] for u in configured):
|
||||
raise ValueError('Active public bootstrap account differs')
|
||||
query = f"SELECT provision_customer_admin('{TENANT}','{principal}');"
|
||||
subprocess.run(['docker','exec','-i','rust-discovery-server-postgres-1','psql','-XqAt',
|
||||
'-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm'],
|
||||
input=query,text=True,check=True,stdout=subprocess.DEVNULL)
|
||||
print(json.dumps({'customer_admin':principal}))
|
||||
return
|
||||
if payload['action']=='prepare':
|
||||
config=payload['accounts']
|
||||
user,=config['users']
|
||||
@@ -142,11 +157,11 @@ def on_server(payload):
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action',choices=('prepare','activate','publish'))
|
||||
parser.add_argument('action',choices=('prepare','activate','publish','grant-customer-admin'))
|
||||
args=parser.parse_args()
|
||||
os.umask(0o077)
|
||||
payload={'action':args.action}
|
||||
if args.action=='prepare':
|
||||
if args.action in ('prepare','grant-customer-admin'):
|
||||
path=ROOT/'credentials/public-webui-login.json'
|
||||
if path.exists():
|
||||
info=path.lstat()
|
||||
@@ -154,6 +169,8 @@ def main():
|
||||
raise ValueError('Unsafe bootstrap credential file')
|
||||
credentials=json.loads(path.read_bytes())
|
||||
else:
|
||||
if args.action=='grant-customer-admin':
|
||||
raise ValueError('Provision the local login before granting customer administration')
|
||||
secret=base64.b32encode(secrets.token_bytes(20)).decode().rstrip('=')
|
||||
password=secrets.token_urlsafe(32);salt=secrets.token_bytes(32)
|
||||
derived=hashlib.scrypt(password.encode(),salt=salt,n=1<<17,r=8,p=1,dklen=64,maxmem=256*1024*1024)
|
||||
@@ -164,7 +181,11 @@ def main():
|
||||
'accounts':{'schema_version':1,'users':[account]}}
|
||||
with path.open('x') as stream:json.dump(credentials,stream,indent=2)
|
||||
path.chmod(0o600)
|
||||
payload['accounts']=credentials['accounts']
|
||||
if args.action=='grant-customer-admin':
|
||||
account,=credentials['accounts']['users']
|
||||
payload['principal']=account['principal']
|
||||
else:
|
||||
payload['accounts']=credentials['accounts']
|
||||
else:
|
||||
names=['server.public-access.compose.yaml'] if args.action=='activate' else ['server-bootstrap-ingress.conf','server-bootstrap-ingress.service']
|
||||
payload['files']={name:base64.b64encode((ROOT/'deploy'/name).read_bytes()).decode() for name in names}
|
||||
|
||||
Reference in New Issue
Block a user