Skip to content

tdfs4ds.serve.gateway

tdfs4ds.serve.gateway

The gateway (0.3.8.2): one login page, one worker per person and environment.

The admin app has ONE process-wide teradataml connection and module-level settings, so two people on two Teradata systems cannot share a process. The gateway therefore does not serve the app itself:

  1. the login page lets the person pick an environment (a Teradata system), and gives their credentials; the database decides (raw driver logon, roles read like the login gate);
  2. each successful login gets its own python -m tdfs4ds.serve worker process, bound to 127.0.0.1, with the person's credentials in its environment (never in argv, never in a log), its own Chroma folder and Vector Store prefix, TDFS4DS_SERVE_AUTH=gateway;
  3. every other request is proxied to that worker by session cookie, streaming (SSE works). The worker trusts X-TDFS4DS-User / -Roles / -Profile only with the X-TDFS4DS-Gateway-Key the gateway generated for it.

Start it with python -m tdfs4ds.serve.gateway, python -m tdfs4ds.serve --gateway or TDFS4DS_SERVE_MODE=gateway python -m tdfs4ds.serve. See :mod:tdfs4ds.serve.environments for the environments file and :mod:tdfs4ds.serve.credential_vault for "remember me".

logger module-attribute

logger = logging.getLogger('tdfs4ds.serve')

audit_log module-attribute

audit_log = logging.getLogger('tdfs4ds.serve.audit')
LAST_COOKIE = 'tdfs4ds_last'

NEW_ENV module-attribute

NEW_ENV = '__new__'

DEFAULT_DATA_DIR module-attribute

DEFAULT_DATA_DIR = '/data'

GATEWAY_COOKIES module-attribute

GATEWAY_COOKIES = (auth.COOKIE, LAST_COOKIE)

_HOP module-attribute

_HOP = {'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade'}

_NO_BODY module-attribute

_NO_BODY = {'GET', 'HEAD', 'OPTIONS', 'DELETE'}

_TOKEN_RE module-attribute

_TOKEN_RE = re.compile('(?i)(token=)[^\\s\'\\",;]+')

_PWD_RE module-attribute

_PWD_RE = re.compile('(?i)((?:password|passwd|secret|api[_-]?key)\\s*[=:]\\s*)[^\\s\'\\",;]+')

_GATEWAY_ONLY module-attribute

_GATEWAY_ONLY = ('TDFS4DS_SERVE_SECRET', 'TDFS4DS_SERVE_API_KEY', 'TDFS4DS_SERVE_ENVIRONMENTS', 'TDFS4DS_SERVE_ENVIRONMENTS_STATE', 'TDFS4DS_SERVE_CREDENTIALS_DIR', 'TDFS4DS_SERVE_SESSION_TTL', 'TDFS4DS_SERVE_SESSION_MAX', 'TDFS4DS_SERVE_MAX_WORKERS', 'TDFS4DS_SERVE_ALLOW_NEW_ENVIRONMENT', 'TDFS4DS_SERVE_REMEMBER_ENVIRONMENTS', 'TDFS4DS_SERVE_REMEMBER_CREDENTIALS', 'TDFS4DS_SERVE_REMEMBER_DAYS', 'TDFS4DS_SERVE_WORKER_TIMEOUT', 'TDFS4DS_SERVE_DATA_DIR', 'TDFS4DS_SERVE_TRUST_PROXY', 'TDFS4DS_SERVE_COOKIE_SECURE', 'TDFS4DS_SERVE_MODE', 'TDFS4DS_SERVE_GATEWAY_KEY')

_LOGON_VARS module-attribute

_LOGON_VARS = ('TDFS4DS_TD_HOST', 'TDFS4DS_TD_USERNAME', 'TDFS4DS_TD_PASSWORD', 'TDFS4DS_TD_LOGDATA', 'TDFS4DS_TD_LOGMECH', 'TDFS4DS_TD_ENCRYPT', 'TDFS4DS_TD_DATABASE')

_JOB module-attribute

_JOB = None

_LOGIN_HTML module-attribute

_LOGIN_HTML = '<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">\n<title>Log in - tdfs4ds</title><base href="__BASE__/">\n<style>\n:root{--navy:#00233C;--slate:#5C6B7A;--bg:#F4F6F8;--surface:#fff;--border:#D5DCE3;--orange:#FF5F00;--bad:#B3261E}\n@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--navy:#E6EDF5;--slate:#9AA9B8;--bg:#0B1622;--surface:#111F2E;--border:#24384E;--bad:#FF8A80}}\n:root[data-theme="dark"]{--navy:#E6EDF5;--slate:#9AA9B8;--bg:#0B1622;--surface:#111F2E;--border:#24384E;--bad:#FF8A80}\nbody{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:var(--bg);color:var(--navy);font:15px/1.5 system-ui,Segoe UI,sans-serif}\nmain{width:100%;max-width:420px;margin:16px;padding:28px;background:var(--surface);border:1px solid var(--border);border-radius:10px}\nh1{margin:0 0 4px;font-size:1.35rem;letter-spacing:-.5px}h1 span{color:var(--orange)}\np.sub{margin:0 0 18px;color:var(--slate);font-size:.9rem}\nlabel{display:block;margin:12px 0 4px;font-size:.82rem;color:var(--slate)}\nlabel.chk{display:flex;gap:8px;align-items:center;margin-top:14px;color:var(--navy);font-size:.88rem}\nlabel.chk input{width:auto}\ninput,select{box-sizing:border-box;width:100%;padding:9px 10px;border:1px solid var(--border);border-radius:6px;background:var(--bg);color:var(--navy);font:inherit}\nbutton{margin-top:18px;width:100%;padding:10px;border:0;border-radius:6px;background:var(--orange);color:#fff;font:inherit;font-weight:600;cursor:pointer}\nbutton.alt{background:transparent;color:var(--navy);border:1px solid var(--border);margin-top:8px}\nbutton:disabled{opacity:.6;cursor:wait}\na.link{color:var(--slate);font-size:.8rem;cursor:pointer;text-decoration:underline}\n#msg{min-height:1.4em;margin-top:12px;color:var(--bad);font-size:.88rem;white-space:pre-wrap}\npre#log{max-height:160px;overflow:auto;background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:8px;font-size:.74rem;white-space:pre-wrap}\n.note{margin-top:10px;color:var(--slate);font-size:.78rem}\nfieldset{border:1px solid var(--border);border-radius:6px;margin:12px 0 0;padding:0 10px 10px}\nlegend{font-size:.8rem;color:var(--slate)}\n</style></head><body><main>\n<h1>tdfs4ds<span>.</span></h1><p class="sub">Choose a system and log on with your database account.</p>\n<form id="f" autocomplete="on">\n<label for="env">Environment</label><select id="env"></select>\n<fieldset id="newbox" hidden><legend>New environment</legend>\n<label for="nlabel">Name</label><input id="nlabel" autocomplete="off">\n<label for="nhost">Host</label><input id="nhost" autocomplete="off" placeholder="my-system.example.com">\n<label for="ndb">Feature store database (optional)</label><input id="ndb" autocomplete="off">\n<label class="chk"><input id="nenc" type="checkbox" checked>Encrypt the connection</label></fieldset>\n<label for="mech">Logon mechanism</label><select id="mech"></select>\n<div id="rem" hidden><p class="note" id="remtext"></p>\n<button id="goRem" type="button">Log in</button>\n<button id="other" type="button" class="alt">Use other credentials</button>\n<p><a class="link" id="forget">Forget my credentials for this environment</a></p></div>\n<div id="fields">\n<div id="pw"><label for="user">User</label><input id="user" autocomplete="username" autofocus>\n<label for="pass">Password</label><input id="pass" type="password" autocomplete="current-password"></div>\n<div id="tk" hidden><label for="tok">Token (JWT)</label><input id="tok" type="password" autocomplete="off"></div>\n<label class="chk" id="remlab"><input id="remember" type="checkbox">Remember my credentials for this environment</label>\n<button id="go" type="submit">Log in</button></div>\n<div id="msg" role="alert"></div><pre id="log" hidden></pre>\n</form>\n<p class="note">Your password is checked by the database. It is passed to a process started for you\nand is stored only if you ask to remember it (encrypted; the key stays in your browser).</p>\n</main>\n<script>\nconst S=__STATE__;\nconst $=id=>document.getElementById(id);\nconst envSel=$(\'env\'),mech=$(\'mech\'),msg=$(\'msg\');\nlet other=false;\nfor(const e of S.envs){const o=document.createElement(\'option\');o.value=e.id;o.textContent=e.label;envSel.appendChild(o);}\nif(S.allowNew){const o=document.createElement(\'option\');o.value=\'__new__\';o.textContent=\'New environment...\';envSel.appendChild(o);}\nif(S.last&&S.envs.some(e=>e.id===S.last.env))envSel.value=S.last.env;\nfunction cur(){return S.envs.find(e=>e.id===envSel.value)||null;}\nfunction sync(){\n  const isNew=envSel.value===\'__new__\';$(\'newbox\').hidden=!isNew;\n  const mechs=isNew?S.mechs:(cur()?cur().logmechs:S.mechs);const keep=mech.value;\n  mech.textContent=\'\';for(const m of mechs){const o=document.createElement(\'option\');o.value=m;o.textContent=m;mech.appendChild(o);}\n  if(mechs.includes(keep))mech.value=keep;\n  const jwt=mech.value===\'JWT\';\n  $(\'pw\').hidden=jwt;$(\'tk\').hidden=!jwt;\n  $(\'remlab\').hidden=!(S.rememberCreds&&(mech.value===\'TD2\'||mech.value===\'LDAP\'));\n  const rem=(!isNew&&cur()&&cur().remembered)||null;\n  $(\'rem\').hidden=!rem||other;$(\'fields\').hidden=!!rem&&!other;\n  if(rem){$(\'remtext\').textContent=\'Credentials remembered for \'+rem.username+\'.\';}\n  if(S.last&&cur()&&S.last.env===envSel.value&&!$(\'user\').value)$(\'user\').value=S.last.user||\'\';\n}\nenvSel.onchange=()=>{other=false;sync();};mech.onchange=sync;sync();\n$(\'other\').onclick=()=>{other=true;sync();$(\'user\').focus();};\nasync function post(url,body){\n  const r=await fetch(url,{method:\'POST\',headers:{\'Content-Type\':\'application/json\'},body:JSON.stringify(body)});\n  return {r:r,d:await r.json().catch(()=>({}))};\n}\n$(\'forget\').onclick=async()=>{await post(\'auth/credentials/forget\',{environment:envSel.value});\n  const e=cur();if(e)e.remembered=null;other=false;sync();msg.textContent=\'Your remembered credentials were deleted.\';};\nasync function submit(useRemembered){\n  msg.textContent=\'\';$(\'log\').hidden=true;\n  for(const id of [\'go\',\'goRem\'])$(id).disabled=true;\n  const isNew=envSel.value===\'__new__\';\n  const body={environment:envSel.value,logmech:mech.value,next:S.next,use_remembered:useRemembered,\n    user:$(\'user\').value,password:$(\'pass\').value,token:$(\'tok\').value,remember:$(\'remember\').checked};\n  if(isNew)body.new_env={label:$(\'nlabel\').value,host:$(\'nhost\').value,database:$(\'ndb\').value,encrypt:$(\'nenc\').checked};\n  try{\n    const {r,d}=await post(\'auth/login\',body);\n    if(r.ok&&d.ok){location.href=d.redirect||\'./\';return;}\n    msg.textContent=d.error||(\'Login failed (\'+r.status+\').\');\n    if(d.log&&d.log.length){$(\'log\').textContent=d.log.join(\'\\n\');$(\'log\').hidden=false;}\n    if(d.credentials_removed){const e=cur();if(e)e.remembered=null;other=true;sync();}\n  }catch(e){msg.textContent=\'The server could not be reached.\';}\n  $(\'pass\').value=\'\';$(\'tok\').value=\'\';\n  for(const id of [\'go\',\'goRem\'])$(id).disabled=false;\n}\n$(\'f\').onsubmit=ev=>{ev.preventDefault();submit(false);};\n$(\'goRem\').onclick=()=>submit(true);\n</script></body></html>'

Vault

Server half of the remembered credentials. sign / unsign come from the login gate (auth.sign / auth.unsign): the cookie value is signed with the server's secret, so a forged or edited cookie is refused before any file is read.

dir instance-attribute

dir = directory or os.environ.get('TDFS4DS_SERVE_CREDENTIALS_DIR') or DEFAULT_DIR

__init__

__init__(directory: Optional[str] = None, sign=None, unsign=None, now=time.time)

store

store(env_id: str, host: str, logmech: str, username: str, password: str, previous_cookie: Optional[str] = None) -> Optional[str]

Seal the credentials; returns the signed cookie value. None when not storable (switch off, mechanism other than TD2/LDAP, empty fields).

peek

peek(env_id: str, host: str, cookie_value: Optional[str]) -> Optional[dict]

{'username', 'logmech'} when the cookie names a live entry of this environment (nothing decrypted); None otherwise. For the login page.

load

load(env_id: str, host: str, cookie_value: Optional[str]) -> Optional[dict]

The decrypted credentials, or None (no cookie, forged cookie, wrong key, other environment, expired, tampered file). An expired entry is deleted.

touch

touch(cookie_value: Optional[str]) -> None

A successful use moves the expiry: 30 days from now.

forget_entry

forget_entry(entry_id: str) -> None
forget_cookie(cookie_value: Optional[str]) -> bool

forget_environment

forget_environment(env_id: str) -> int

Delete every entry of an environment (the environment is forgotten).

purge_expired

purge_expired() -> int

Delete expired entries (and half entries). Called at start and daily.

purge_if_due

purge_if_due() -> int

Masker

Replaces every known secret value, and anything shaped like one, by ***.

values instance-attribute

values = sorted({str(v) for v in values if v and len(str(v)) >= 3}, key=len, reverse=True)

__init__

__init__(values=())

mask

mask(text: str) -> str

WorkerError

Bases: RuntimeError

log instance-attribute

log = list(log or [])

__init__

__init__(message, log=None)

WorkerCapReached

Bases: RuntimeError

WorkerSpec dataclass

env instance-attribute

env: dict

cwd instance-attribute

cwd: str

masker instance-attribute

masker: Masker

label class-attribute instance-attribute

label: str = ''

user class-attribute instance-attribute

user: str = ''

env_id class-attribute instance-attribute

env_id: str = ''

service class-attribute instance-attribute

service: bool = False

__init__

__init__(env: dict, cwd: str, masker: Masker, label: str = '', user: str = '', env_id: str = '', service: bool = False) -> None

Worker

gateway_key instance-attribute

gateway_key = spec.env['TDFS4DS_SERVE_GATEWAY_KEY']

port instance-attribute

port = int(spec.env['TDFS4DS_SERVE_PORT'])

proc instance-attribute

proc: Optional[Popen] = None

log instance-attribute

log: deque = deque(maxlen=200)

restarts instance-attribute

restarts = 0

started instance-attribute

started = time.time()

last_used instance-attribute

last_used = time.time()

lock instance-attribute

lock = threading.RLock()

service property

service: bool

url property

url: str

__init__

__init__(key: str, spec: WorkerSpec, command, host='127.0.0.1')

alive

alive() -> bool

tail

tail(n: int = 15) -> list

launch

launch() -> None

wait_ready

wait_ready(timeout: float) -> None

Returns when the worker answers /health connected; raises :class:WorkerError.

stop

stop() -> None

WorkerPool

command instance-attribute

command = list(command or [sys.executable, '-m', 'tdfs4ds.serve'])

workers instance-attribute

workers: Dict[str, Worker] = {}

cap property

cap: int

timeout property

timeout: float

__init__

__init__(command=None, cap: Optional[int] = None, timeout: Optional[float] = None)

get

get(key: str) -> Optional[Worker]

count

count() -> int

get_or_start

get_or_start(key: str, make_spec: Callable[[], WorkerSpec]) -> Worker

The live worker of key, or a new one (blocking until it is ready).

restart

restart(worker: Worker) -> Worker

One restart of a dead worker (same environment, so the same credentials).

stop

stop(key: str) -> bool

stop_all

stop_all() -> None

GatewaySession

Bases: Session

sid instance-attribute

sid = secrets.token_urlsafe(24)

created instance-attribute

created = time.time()

clock instance-attribute

clock = SessionClock(ttl_s if ttl_s is not None else ttl_seconds(), max_s if max_s is not None else max_seconds())

__init__

__init__(user, roles, profile, *, env_id, env_label, worker_key, note='', ip='')

Gateway

client instance-attribute

client: Optional[AsyncClient] = None

model_keys instance-attribute

model_keys = ModelKeyStore(vault.dir)

__init__

__init__(registry: 'envmod.EnvironmentRegistry', pool: WorkerPool, vault: Vault, prefix: str = '')

all_envs

all_envs()

match_api_key

match_api_key(bearer: str, hint: Optional[str])

push_model_keys

push_model_keys(sender, changes: dict) -> int

Give the new keys to every other running worker (the sender applied them itself).

user_spec

user_spec(env, *, user, password, token, logmech) -> WorkerSpec

service_spec

service_spec(env) -> WorkerSpec

live_worker_keys

live_worker_keys() -> set

reap

reap() -> None

end_session

end_session(sess) -> None

base

base(request) -> str

cookie_path

cookie_path() -> str

secure

secure(request) -> bool

session_of

session_of(request, touch=False)

_PrefixMiddleware

Pure ASGI. Strips the external path prefix when the proxy in front did not, and records it so every URL the gateway emits is relative to it.

state instance-attribute

state = app.state

__init__

__init__(app, prefix: str)

__call__ async

__call__(scope, receive, send)

cookie_name

cookie_name(env_id: str) -> str

vault_enabled

vault_enabled() -> bool

is_activity_path

is_activity_path(path: str) -> bool

A request that shows someone is using the app. The status poll, static files, /health and the documentation do not (they would keep a forgotten tab alive).

_int_env

_int_env(name: str, default: int) -> int

data_dir

data_dir() -> str

max_workers

max_workers() -> int

worker_timeout

worker_timeout() -> float

normalise_prefix

normalise_prefix(raw) -> str

slug_user

slug_user(user: str) -> str

_env_value

_env_value(value) -> str

worker_env

worker_env(base: dict, env: 'envmod.Environment', *, user: str, password: Optional[str], token: Optional[str], logmech: str, key: str, port: int, data: str, user_slug: str, all_envs=(), prefix: str = '', model_keys: Optional[dict] = None) -> dict

The environment of one worker (pure). Secrets live here and nowhere else.

secret_values

secret_values(env: dict, user: str, password, token) -> list

Every secret a worker's log could echo: the person's, and any secret setting.

free_port

free_port() -> int

_kill_on_close_job

_kill_on_close_job()

A Windows job object that kills its processes when the gateway ends, however it ends (Ctrl+C, the console window closed, a crash). None elsewhere or when it cannot be made.

_assign_to_job

_assign_to_job(proc) -> None

_package_parent

_package_parent() -> Optional[str]

The folder holding the running tdfs4ds when it is a source checkout (a worker started from another folder must import the same code); None for an installed package.

_worker_environment

_worker_environment(env: dict) -> dict

_b64json

_b64json(obj) -> str

_unb64json

_unb64json(text)

_is_api

_is_api(rel: str) -> bool

login_page

login_page(gw: Gateway, request: Request, next_path: str) -> str

_json

_json(status, payload, headers=None)

create_gateway_app

create_gateway_app(*, registry=None, pool=None, vault=None, root_path=None) -> FastAPI

Build the gateway. Raises :class:environments.EnvironmentsError when the environments file is unusable (the gateway then refuses to start).

_first_existing

_first_existing(candidates) -> Optional[str]

local_defaults

local_defaults(environ=None, home: Optional[str] = None, cwd: Optional[str] = None) -> dict

The settings of a gateway started on one's own computer, each applied ONLY when unset.

Returns what was set (name -> value; the secret itself is not repeated). environ, home and cwd exist for the tests.

_install_exit_handlers

_install_exit_handlers(pool) -> None

Stop every worker on SIGTERM / SIGBREAK (console close on Windows) as well as Ctrl+C.

main

main(force: bool = False) -> None