SailorEval / evaluation /security.py
QingchengChang's picture
Add SailorEval v1.3.4 benchmark data and evaluation suite
e12d99b verified
Raw History Blame Contribute Delete
4.28 kB
"""Keep credentials out of publishable configuration and run artifacts."""
import os
import re
from urllib.parse import quote,quote_plus,urlsplit
_CREDENTIAL_FIELDS={
'apikey','apisecret','accesskey','accesskeyid','accesssecret','accesstoken',
'authtoken','authorization','bearertoken','clientsecret','password',
'privatekey','refreshtoken','secret','secretkey','token','credentials',
}
_TOKEN=re.compile(r'(?i)(?:\bsk-(?:proj-|svcacct-)?[a-z0-9_*.-]{12,}|\bAKIA[A-Z0-9]{16}\b|\bgh[pousr]_[a-z0-9]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')
def _strings(value):
if isinstance(value,str):yield value
elif isinstance(value,dict):
for child in value.values():yield from _strings(child)
elif isinstance(value,list):
for child in value:yield from _strings(child)
def _environment_names(value):
if isinstance(value,dict):
for key,child in value.items():
if key.endswith('_env') and isinstance(child,str):yield child
else:yield from _environment_names(child)
elif isinstance(value,list):
for child in value:yield from _environment_names(child)
def validate_endpoint(url):
"""Blank endpoints are allowed in templates; calls require an explicit URL."""
if url is None or url=='':return
if not isinstance(url,str):raise ValueError('API base_url must be a URL string or empty')
try:
parsed=urlsplit(url)
port=parsed.port
host=parsed.hostname
except ValueError:
raise ValueError('API base_url is invalid; its value is omitted') from None
if not host or parsed.scheme not in ['http','https']:
raise ValueError('API base_url must use HTTP or HTTPS')
if parsed.scheme=='http' and host not in ['localhost','127.0.0.1','::1']:
raise ValueError('Use HTTPS for remote API endpoints')
if parsed.username is not None or parsed.password is not None or parsed.query or parsed.fragment:
raise ValueError('API base_url must not contain credentials, query parameters or fragments')
if _TOKEN.search(url):raise ValueError('API base_url must not contain credential-like tokens')
def validate_public_config(config):
"""Reject inline secrets before fingerprinting, writing metadata or calling APIs."""
if not isinstance(config,dict):raise ValueError('Model configuration must be a JSON object')
def check(value):
if isinstance(value,dict):
for key,child in value.items():
normalized=re.sub(r'[^a-z0-9]','',key.casefold())
sensitive=normalized in _CREDENTIAL_FIELDS or normalized.endswith(('apikey','accesstoken','password','secret','privatekey'))
if sensitive and child not in [None,'',{},[]]:
raise ValueError('Inline credentials are prohibited; configure an environment variable name')
if key.endswith('_env') and child is not None:
if not isinstance(child,str) or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*',child):
raise ValueError('Credential environment references must contain variable names only')
if key=='base_url':validate_endpoint(child)
check(child)
elif isinstance(value,list):
for child in value:check(child)
check(config)
secret_values=[os.environ[name] for name in set(_environment_names(config)) if os.environ.get(name) and len(os.environ[name])>=8]
encoded_secrets={encoded for value in secret_values for encoded in [value,quote(value,safe=''),quote_plus(value)]}
for value in _strings(config):
if value.startswith(('http://','https://')):validate_endpoint(value)
if _TOKEN.search(value) or any(secret in value for secret in encoded_secrets):
raise ValueError('Configuration contains credential material; keep it in the environment only')
def safe_error(exc):
"""Provider errors can echo keys or authenticated URLs; never serialize their text."""
result=dict(error=type(exc).__name__,error_detail='Provider operation failed; raw exception text is omitted to protect credentials.')
status=getattr(exc,'status_code',None)
if isinstance(status,int) and not isinstance(status,bool):result['error_status']=status
return result