114 lines
6.5 KiB
Python
114 lines
6.5 KiB
Python
"""Authorized read-only MA probe. Never print raw responses, secrets or private IDs."""
|
|||
|
|
import datetime
|
||
|
|
import json
|
||
|
|
import os
|
||
|
|
from pathlib import Path
|
||
|
|
import stat
|
||
|
|
import subprocess
|
||
|
|
import urllib.error
|
||
|
|
import urllib.request
|
||
|
|
from probe_ma import NoRedirect
|
||
|
|
|
||
|
|
ROOT = Path(__file__).resolve().parents[1]
|
||
|
|
|
||
|
|
def credential_check():
|
||
|
|
directory = ROOT / '.local'
|
||
|
|
path = directory / 'ma-token'
|
||
|
|
if directory.is_symlink() or path.is_symlink():
|
||
|
|
raise ValueError('credential symlink refused')
|
||
|
|
if stat.S_IMODE(directory.stat().st_mode) != 0o700 or stat.S_IMODE(path.stat().st_mode) != 0o600:
|
||
|
|
raise ValueError('private permissions required')
|
||
|
|
if path.stat().st_uid != os.getuid() or not path.is_file():
|
||
|
|
raise ValueError('credential owner/type refused')
|
||
|
|
token = path.read_bytes().strip()
|
||
|
|
if not token or b'\n' in token or b'\r' in token:
|
||
|
|
raise ValueError('invalid credential format')
|
||
|
|
ignored = subprocess.run(['git','check-ignore','-q','.local/ma-token'], cwd=ROOT).returncode == 0
|
||
|
|
# Inspect file paths and blob contents across all reachable refs, without logging matches.
|
||
|
|
objects = subprocess.check_output(['git','rev-list','--objects','--all'], cwd=ROOT).splitlines()
|
||
|
|
for entry in objects:
|
||
|
|
oid, _, name = entry.partition(b' ')
|
||
|
|
if name.startswith(b'.local/'):
|
||
|
|
raise ValueError('private path in history')
|
||
|
|
if subprocess.check_output(['git','cat-file','-t',oid], cwd=ROOT).strip() == b'blob':
|
||
|
|
if token in subprocess.check_output(['git','cat-file','blob',oid], cwd=ROOT):
|
||
|
|
raise ValueError('credential in history')
|
||
|
|
for name in subprocess.check_output(['git','ls-files','-z'],cwd=ROOT).split(b'\0'):
|
||
|
|
if name and token in (ROOT / os.fsdecode(name)).read_bytes():
|
||
|
|
raise ValueError('credential in tracked working tree')
|
||
|
|
if not ignored:
|
||
|
|
raise ValueError('credential not ignored')
|
||
|
|
return token.decode(), {'directory_mode':'0700','token_mode':'0600','git_ignored':True,
|
||
|
|
'token_absent_reachable_history':True,'token_absent_tracked_files':True}
|
||
|
|
|
||
|
|
def main():
|
||
|
|
token, safety = credential_check()
|
||
|
|
base = json.loads((ROOT / '.local/environment.json').read_text())['ma_url']
|
||
|
|
from urllib.parse import urlsplit
|
||
|
|
url = urlsplit(base)
|
||
|
|
if url.scheme not in ('http','https') or url.username or url.password or url.query or url.fragment or url.path not in ('','/'):
|
||
|
|
raise ValueError('invalid upstream')
|
||
|
|
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
||
|
|
allowed = {'auth/me','auth/scopes','players/get','player_queues/get','music/playlists/library_items','music/radios/library_items'}
|
||
|
|
def call(command, args=None):
|
||
|
|
if command not in allowed:
|
||
|
|
raise ValueError('command refused')
|
||
|
|
request = urllib.request.Request(base.rstrip('/')+'/api',data=json.dumps({
|
||
|
|
'message_id':'adaptive-music-read','command':command,'args':args or {}}).encode(),
|
||
|
|
headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'},method='POST')
|
||
|
|
try:
|
||
|
|
with opener.open(request,timeout=10) as response:
|
||
|
|
data=response.read(1048577)
|
||
|
|
if len(data)>1048576:
|
||
|
|
raise ValueError('response limit')
|
||
|
|
return json.loads(data)
|
||
|
|
except urllib.error.HTTPError as exc:
|
||
|
|
return {'probe_http_status':exc.code}
|
||
|
|
me=call('auth/me')
|
||
|
|
report={'checked_at':datetime.datetime.now(datetime.timezone.utc).isoformat(), 'credential':safety,
|
||
|
|
'authentication':me.get('username') == 'adaptive-music' and me.get('enabled') is True}
|
||
|
|
raw={'me':me}
|
||
|
|
if report['authentication']:
|
||
|
|
raw['scopes']=call('auth/scopes')
|
||
|
|
filters=me.get('player_filter',[]); providers=me.get('provider_filter',[])
|
||
|
|
report.update(role=me.get('role'), player_filter_count=len(filters),provider_filter_count=len(providers))
|
||
|
|
if len(filters)==1:
|
||
|
|
player=call('players/get',{'player_id':filters[0]}); raw['player']=player
|
||
|
|
report['dedicated_name_matches']=player.get('name')=='Adaptive Music DEV'
|
||
|
|
report['player_available']=player.get('available')
|
||
|
|
report['sendspin_provider']=str(player.get('provider','')).startswith('sendspin')
|
||
|
|
report['standalone_topology']=not any(player.get(k) for k in ('active_group','synced_to','group_members','group_childs','static_group_members'))
|
||
|
|
if report['dedicated_name_matches']:
|
||
|
|
queue=call('player_queues/get',{'queue_id':filters[0]}); raw['queue']=queue
|
||
|
|
report['queue_id_matches_player']=queue.get('queue_id')==filters[0]
|
||
|
|
report['queue_active']=queue.get('active')
|
||
|
|
# Negative read uses a nonexistent synthetic ID, never a household player.
|
||
|
|
negative=call('players/get',{'player_id':'adaptive-music-forbidden-synthetic'})
|
||
|
|
report['synthetic_target_denial_status']=negative.get('probe_http_status')
|
||
|
|
if providers:
|
||
|
|
negative_provider=call('music/playlists/library_items',{'provider':['adaptive-music-forbidden-synthetic'],'limit':1})
|
||
|
|
report['synthetic_provider_denial_status']=negative_provider.get('probe_http_status') if isinstance(negative_provider,dict) else None
|
||
|
|
report['role_scopes']=raw['scopes'].get(me.get('role'),[])
|
||
|
|
for kind in ('playlists','radios'):
|
||
|
|
items=[]
|
||
|
|
for offset in range(0,5000,100):
|
||
|
|
page=call(f'music/{kind}/library_items',{'provider':providers,'limit':100,'offset':offset,'order_by':'name','summary':False})
|
||
|
|
if not isinstance(page,list):
|
||
|
|
report[kind+'_error']=True; break
|
||
|
|
items.extend(page)
|
||
|
|
if len(page)<100: break
|
||
|
|
raw[kind]=items; report[kind+'_count']=len(items)
|
||
|
|
report[kind+'_approved_mappings']=all(any(m.get('provider_instance') in providers and m.get('available') is True for m in i.get('provider_mappings',[])) for i in items)
|
||
|
|
else:
|
||
|
|
report['catalog_blocker']='No explicit approved provider filter; catalog reads skipped'
|
||
|
|
private=ROOT/'.local/ma-readonly-results.json'
|
||
|
|
fd=os.open(private,os.O_WRONLY|os.O_CREAT|os.O_TRUNC|os.O_NOFOLLOW,0o600)
|
||
|
|
with os.fdopen(fd,'w') as output: json.dump(raw,output)
|
||
|
|
(ROOT/'evidence/ma-readonly.json').write_text(json.dumps(report,indent=2)+'\n')
|
||
|
|
print(json.dumps(report,indent=2))
|
||
|
|
|
||
|
|
if __name__=='__main__':
|
||
|
|
try: main()
|
||
|
|
except Exception as exc:
|
||
|
|
print('Read-only probe failed:',type(exc).__name__)
|
||
|
|
raise SystemExit(1)
|