Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
204 lines
11 KiB
Python
204 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Exercise real native HTTP auth on CPU only; destroy temporary test keys."""
|
|
import http.client
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
|
|
|
|
def init_key(binary, root):
|
|
key = root / 'api.key'
|
|
def init(path, **kwargs):
|
|
return subprocess.run([binary, 'api-key', 'init', '--file', str(path)],
|
|
env={'PATH': os.defpath}, capture_output=True, timeout=8, **kwargs)
|
|
# Simultaneous cold initialization must converge on one complete key.
|
|
with ThreadPoolExecutor(max_workers=12) as pool:
|
|
results = list(pool.map(lambda _: init(key), range(12)))
|
|
assert all(r.returncode == 0 for r in results)
|
|
statuses = [json.loads(r.stdout) for r in results]
|
|
assert statuses.count({'created': True, 'reused': False}) == 1
|
|
assert statuses.count({'created': False, 'reused': True}) == 11
|
|
token = key.read_text().rstrip('\n')
|
|
assert len(token) == 64 and all(c in '0123456789abcdef' for c in token)
|
|
assert key.stat().st_mode & 0o777 == 0o600
|
|
before = key.stat()
|
|
reused = init(key)
|
|
assert reused.returncode == 0 and json.loads(reused.stdout) == {'created': False, 'reused': True}
|
|
assert key.stat().st_ino == before.st_ino and key.stat().st_mtime_ns == before.st_mtime_ns
|
|
assert key.read_text() == token + '\n'
|
|
assert all(token.encode() not in r.stdout + r.stderr for r in results + [reused])
|
|
assert sorted(p.name for p in root.iterdir()) == ['api.key']
|
|
other = root / 'other.key'
|
|
result = init(other, umask=0o777)
|
|
assert result.returncode == 0 and other.stat().st_mode & 0o777 == 0o600
|
|
assert other.read_bytes() != key.read_bytes()
|
|
other.unlink()
|
|
# Refuse unsafe or invalid targets without changing them or the good key.
|
|
bad = root / 'bad.key'
|
|
for data, mode in [(b'short', 0o600), (b'A'*515, 0o600), (token.encode(), 0o644)]:
|
|
bad.write_bytes(data); bad.chmod(mode)
|
|
result = init(bad)
|
|
assert result.returncode != 0 and bad.read_bytes() == data and bad.stat().st_mode & 0o777 == mode
|
|
assert token.encode() not in result.stdout + result.stderr
|
|
bad.unlink()
|
|
bad.symlink_to(key)
|
|
assert init(bad).returncode != 0 and key.read_text() == token + '\n'
|
|
bad.unlink(); bad.symlink_to(root/'absent')
|
|
assert init(bad).returncode != 0 and not (root/'absent').exists()
|
|
bad.unlink(); os.mkfifo(bad, 0o600)
|
|
assert init(bad).returncode != 0
|
|
bad.unlink(); bad.mkdir(mode=0o700)
|
|
assert init(bad).returncode != 0
|
|
bad.rmdir()
|
|
parent = root / 'public'; parent.mkdir(mode=0o755)
|
|
assert init(parent/'key').returncode != 0 and not list(parent.iterdir())
|
|
parent.chmod(0o700)
|
|
alias = root/'alias'; alias.symlink_to(parent, target_is_directory=True)
|
|
assert init(alias/'key').returncode != 0 and not list(parent.iterdir())
|
|
alias.unlink(); parent.rmdir()
|
|
assert init(root/'missing'/'key').returncode != 0 and not (root/'missing').exists()
|
|
assert sorted(p.name for p in root.iterdir()) == ['api.key']
|
|
return key, token
|
|
|
|
|
|
def main():
|
|
binary = Path(sys.argv[1]).resolve()
|
|
with tempfile.TemporaryDirectory(prefix='strata-auth-smoke-') as directory:
|
|
root = Path(directory)
|
|
key, token = init_key(binary, root)
|
|
with socket.socket() as probe:
|
|
probe.bind(('127.0.0.1', 0))
|
|
port = probe.getsockname()[1]
|
|
config = root / 'config.json'
|
|
config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'api_key_file': str(key), 'model': 'auth-cpu-smoke'}))
|
|
env = {'PATH': os.defpath}
|
|
|
|
def request(path, headers=(), body=None, method=None):
|
|
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=2)
|
|
conn.putrequest(method or ('POST' if body is not None else 'GET'), path)
|
|
for name, value in headers:
|
|
conn.putheader(name, value)
|
|
if body is not None:
|
|
conn.putheader('Content-Type', 'application/json')
|
|
conn.putheader('Content-Length', str(len(body)))
|
|
conn.endheaders(body)
|
|
response = conn.getresponse()
|
|
result = response.status, dict(response.getheaders()), response.read().decode()
|
|
conn.close()
|
|
assert token not in result[2]
|
|
return result
|
|
|
|
with tempfile.TemporaryFile() as logs:
|
|
process = subprocess.Popen([binary, 'serve', '--config', config], env=env, stdout=logs, stderr=logs)
|
|
try:
|
|
deadline = time.monotonic() + 8
|
|
while True:
|
|
try:
|
|
assert request('/health')[0] == 200
|
|
break
|
|
except OSError:
|
|
assert process.poll() is None and time.monotonic() < deadline
|
|
time.sleep(0.02)
|
|
for headers in [(), (('Authorization', 'Bearer wrong'),),
|
|
(('Authorization', 'Bearer ' + token), ('Authorization', 'Bearer ' + token))]:
|
|
code, response_headers, _ = request('/v1/responses', headers, b'not-json')
|
|
assert code == 401
|
|
assert response_headers.get('www-authenticate') == 'Bearer'
|
|
auth = (('Authorization', 'Bearer ' + token),)
|
|
model_record = {'id': 'auth-cpu-smoke', 'object': 'model', 'created': 0, 'owned_by': 'local'}
|
|
for path in ['/v1/models', '/v1/models/auth-cpu-smoke', '/v1/models/missing?x=1']:
|
|
assert request(path)[0] == 401
|
|
assert request(path, (('Authorization', 'Bearer wrong'),))[0] == 401
|
|
assert json.loads(request('/v1/models', auth)[2]) == {'object': 'list', 'data': [model_record]}
|
|
assert json.loads(request('/v1/models/auth-cpu-smoke', auth)[2]) == model_record
|
|
missing = request('/v1/models/missing', auth)
|
|
assert missing[0] == 404 and json.loads(missing[2])['error']['code'] == 'model_not_found'
|
|
for path in ['/v1/models?limit=1', '/v1/models/auth-cpu-smoke?x=1']:
|
|
assert request(path, auth)[0] == 400
|
|
for method, path in [('POST', '/v1/models'), ('DELETE', '/v1/models/auth-cpu-smoke')]:
|
|
assert request(path, auth, method=method)[0] == 405
|
|
assert request('/status')[0] == 401
|
|
assert request('/ready')[0] == 401
|
|
assert request('/metrics')[0] == 401
|
|
for path in ['/admin/drain', '/admin/resume', '/admin/lifecycle']:
|
|
assert request(path, body=b'{}')[0] == 401
|
|
status = request('/status', auth)
|
|
assert status[0] == 200 and json.loads(status[2])['model'] == 'auth-cpu-smoke'
|
|
assert request('/ready', auth)[0] == 503
|
|
metrics = request('/metrics', auth)
|
|
assert metrics[0] == 200
|
|
observed = json.loads(metrics[2])
|
|
assert observed['schema_version'] == 1
|
|
assert observed['active'] is False and observed['active_elapsed_ms'] is None
|
|
assert observed['queue_capacity'] is None and observed['queue_used'] is None
|
|
assert observed['generation']['started'] == 0
|
|
assert observed['generation']['last_done'] is None
|
|
assert observed['done_decode_tokens_per_second'] is None
|
|
assert request('/v1/responses', auth, b'not-json')[0] == 400
|
|
assert json.loads(request('/admin/lifecycle', auth)[2])['draining'] is False
|
|
assert json.loads(request('/admin/drain', auth, b'{}')[2])['drained'] is True
|
|
assert json.loads(request('/v1/models', auth)[2]) == {'object': 'list', 'data': [model_record]}
|
|
assert json.loads(request('/metrics', auth)[2])['generation']['started'] == 0
|
|
assert request('/v1/responses', auth, b'not-json')[0] == 503
|
|
assert json.loads(request('/admin/resume', auth, b'{}')[2])['draining'] is False
|
|
finally:
|
|
process.terminate()
|
|
try:
|
|
process.wait(timeout=8)
|
|
except subprocess.TimeoutExpired:
|
|
process.kill()
|
|
process.wait()
|
|
logs.seek(0)
|
|
assert token.encode() not in logs.read()
|
|
|
|
# Each invalid source must fail before binding, with no secret echo.
|
|
for content, mode in [(b'short', 0o600), (b'A' * 32 + b'\ninside', 0o600),
|
|
(b'A' * 515, 0o600), (token.encode(), 0o644)]:
|
|
key.write_bytes(content)
|
|
key.chmod(mode)
|
|
result = subprocess.run([binary, 'serve', '--config', config], env=env,
|
|
capture_output=True, timeout=8)
|
|
assert result.returncode != 0
|
|
assert token.encode() not in result.stdout + result.stderr
|
|
fifo = root / 'not-a-file'
|
|
os.mkfifo(fifo, 0o600)
|
|
result = subprocess.run([binary, 'serve', '--config', config],
|
|
env={**env, 'STRATA_API_KEY_FILE': str(fifo)}, capture_output=True, timeout=8)
|
|
assert result.returncode != 0 and b'regular file' in result.stderr
|
|
# An environment override is authoritative, including invalid paths.
|
|
result = subprocess.run([binary, 'serve', '--config', config],
|
|
env={**env, 'STRATA_API_KEY_FILE': str(root/'missing')}, capture_output=True, timeout=8)
|
|
assert result.returncode != 0
|
|
config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'model': 'auth-off-fixture'}))
|
|
with tempfile.TemporaryFile() as logs:
|
|
process = subprocess.Popen([binary, 'serve', '--config', config], env=env, stdout=logs, stderr=logs)
|
|
try:
|
|
deadline = time.monotonic() + 8
|
|
while True:
|
|
try:
|
|
assert request('/status')[0] == 200
|
|
break
|
|
except OSError:
|
|
assert process.poll() is None and time.monotonic() < deadline
|
|
time.sleep(0.02)
|
|
assert request('/v1/responses', body=b'not-json')[0] == 400
|
|
assert request('/metrics')[0] == 200
|
|
finally:
|
|
process.terminate()
|
|
try:
|
|
process.wait(timeout=8)
|
|
except subprocess.TimeoutExpired:
|
|
process.kill()
|
|
process.wait()
|
|
print('Native auth passed: native key init/concurrent reuse/no replacement/private modes, protected routes, duplicate rejection, public health, invalid sources and no key echo')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|