Files
stack/packages/mosaic/framework/tools/git/resolve-legacy-token.py
T

50 lines
1.5 KiB
Python

#!/usr/bin/env python3
"""Fail-closed reader for one legacy per-seat token file."""
import os
import stat
import sys
MAX_BYTES = 16 * 1024
def refuse(message: str) -> None:
print(f"legacy credential refused: {message}", file=sys.stderr)
raise SystemExit(1)
if len(sys.argv) != 2:
refuse("expected token path")
path = sys.argv[1]
parent = os.path.dirname(path)
try:
parent_stat = os.stat(parent, follow_symlinks=False)
except OSError:
refuse("credential directory unavailable")
if not stat.S_ISDIR(parent_stat.st_mode) or stat.S_ISLNK(parent_stat.st_mode):
refuse("credential directory is not a real directory")
if parent_stat.st_uid != os.getuid() or parent_stat.st_mode & 0o022:
refuse("credential directory owner or mode is unsafe")
try:
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC)
except OSError:
refuse("credential file unavailable or symbolic")
try:
file_stat = os.fstat(fd)
if not stat.S_ISREG(file_stat.st_mode):
refuse("credential is not a regular file")
if file_stat.st_uid != os.getuid() or file_stat.st_mode & 0o077:
refuse("credential owner or mode is unsafe")
content = os.read(fd, MAX_BYTES + 1)
if len(content) > MAX_BYTES:
refuse("credential exceeds size limit")
finally:
os.close(fd)
try:
token = content.decode("utf-8").strip()
except UnicodeDecodeError:
refuse("credential is not UTF-8")
if not token or any(ch.isspace() for ch in token):
refuse("credential token is invalid")
sys.stdout.write(token + "\n")