Skip to content

tdfs4ds.serve.auth

tdfs4ds.serve.auth

Login gate of the admin app (0.3.7.10): TDFS4DS_SERVE_AUTH=database.

Each person logs on with their own database credentials. The app checks them with a raw driver logon (the database decides, whatever the logon mechanism of the site), reads the person's roles, and issues a signed session cookie. The password or token is used for that one logon and is never stored, logged or returned.

What the gate is, and is not:

  • A gate and an audit trail. Queries still run on the app's one service connection (TDFS4DS_TD_*), so the database sees the service user, not the person. The person is recorded by the app (one audit line per write) and, for process executions started from the app, in the query band (TDFS4DS_APP_USER).
  • Profiles from database roles: a role named by TDFS4DS_SERVE_ROLE_ADMIN / _ENGINEER / _SCIENTIST (defaults TDFS4DS_ADMIN / TDFS4DS_ENGINEER / TDFS4DS_SCIENTIST) caps the person's profile; nobody holding none of them is a Business analyst. The server refuses (403) a route above the person's profile.

Off (the default) nothing here does anything and the app behaves as before.

logger module-attribute

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

audit_log module-attribute

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

COOKIE module-attribute

COOKIE = 'tdfs4ds_session'

PROFILE_ORDER module-attribute

PROFILE_ORDER = ['analyst', 'scientist', 'engineer', 'admin']

LOGMECHS module-attribute

LOGMECHS = ['TD2', 'LDAP', 'TDNEGO', 'JWT']

_CURRENT module-attribute

_CURRENT = contextvars.ContextVar('tdfs4ds_app_user', default=None)

_SECRET module-attribute

_SECRET: list = []

ROUTE_PROFILE module-attribute

ROUTE_PROFILE = [('/ui/params', 'admin'), ('/ui/skills', 'admin'), ('/ui/eval', 'admin'), ('/ui/removal', 'engineer'), ('/ui/connect', 'admin'), ('/ui/workflow/accept', 'admin'), ('/ui/reconnect', 'engineer'), ('/ui/maintenance', 'engineer'), ('/ui/migration', 'engineer'), ('/ui/attached', 'engineer'), ('/ui/parallel', 'engineer'), ('/ui/qopt', 'engineer'), ('/ui/efs', 'engineer'), ('/ui/relocation', 'engineer'), ('/ui/doc/edit', 'engineer'), ('/ui/doc/run', 'engineer'), ('/ui/doc/assist', 'engineer'), ('/ui/glossary/term', 'engineer'), ('/ui/glossary/remove', 'engineer'), ('/ui/glossary/import', 'engineer'), ('/ui/doc/selection', 'engineer'), ('/ui/catalog/process/capture', 'engineer'), ('/ui/dsbuild/remove', 'engineer'), ('/ui/dsbuild/joinable/create', 'engineer'), ('/ui/datasets', 'engineer'), ('/ui/lineage/add-datasets', 'engineer'), ('/ui/runs/harvest', 'engineer'), ('/ui/sizing', 'admin'), ('/ui/impact', 'scientist'), ('/ui/runs', 'scientist'), ('/ui/runs/evolution', 'scientist'), ('/ui/workflow', 'scientist'), ('/ui/timemgr', 'scientist'), ('/ui/benchmark', 'scientist'), ('/ui/framework', 'scientist'), ('/ui/serverbatch', 'engineer'), ('/ui/doc/coverage', 'scientist'), ('/ui/doc/gaps', 'scientist'), ('/ui/chat', 'analyst'), ('/ui/search', 'analyst'), ('/ui/dsbuild', 'analyst'), ('/ui/glossary', 'analyst'), ('/ui/home', 'analyst'), ('/ui/code', 'analyst'), ('/ui/catalog', 'analyst'), ('/ui/dashboard', 'analyst'), ('/ui/lineage', 'analyst'), ('/ui/doc', 'analyst'), ('/ui/status', 'analyst'), ('/ui/conflicts', 'analyst')]

_ROUTES_BY_LENGTH module-attribute

_ROUTES_BY_LENGTH = sorted(ROUTE_PROFILE, key=lambda x: -len(x[0]))

STORE_CHOICE_ROUTES module-attribute

STORE_CHOICE_ROUTES = ('/ui/params/stores', '/ui/params/database')

SESSIONS module-attribute

SESSIONS = SessionStore()

LIMITER module-attribute

LIMITER = LoginLimiter()

_ERR_NO module-attribute

_ERR_NO = re.compile('\\[Error (\\d+)\\]')

_AUDIT_GET module-attribute

_AUDIT_GET = ('/run', '/dryrun', '/scan', '/storage', '/job')

_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:380px;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)}\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:disabled{opacity:.6;cursor:wait}\n#msg{min-height:1.4em;margin-top:12px;color:var(--bad);font-size:.88rem}\n.note{margin-top:10px;color:var(--slate);font-size:.78rem}\n</style></head><body><main>\n<h1>tdfs4ds<span>.</span></h1><p class="sub">Log on with your database account.</p>\n<form id="f" autocomplete="on">\n<label for="mech">Logon mechanism</label><select id="mech">{mechs}</select>\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<button id="go" type="submit">Log in</button><div id="msg" role="alert"></div>\n</form>\n<p class="note">Your password is checked by the database and is not stored by this application.</p>\n</main>\n<script>\nconst next={next_js};\nconst mech=document.getElementById(\'mech\'),msg=document.getElementById(\'msg\');\nfunction sync(){const j=mech.value===\'JWT\';document.getElementById(\'pw\').hidden=j;document.getElementById(\'tk\').hidden=!j;}\nmech.onchange=sync;sync();\ndocument.getElementById(\'f\').onsubmit=async(ev)=>{\n  ev.preventDefault();const go=document.getElementById(\'go\');go.disabled=true;msg.textContent=\'\';\n  try{\n    const r=await fetch(\'auth/login\',{method:\'POST\',headers:{\'Content-Type\':\'application/json\'},\n      body:JSON.stringify({user:document.getElementById(\'user\').value,password:document.getElementById(\'pass\').value,\n      token:document.getElementById(\'tok\').value,logmech:mech.value,next:next})});\n    const d=await r.json().catch(()=>({}));\n    if(r.ok&&d.ok){location.href=d.redirect||\'./\';return;}\n    msg.textContent=d.error||(\'Login failed (\'+r.status+\').\');\n  }catch(e){msg.textContent=\'The server could not be reached.\';}\n  document.getElementById(\'pass\').value=\'\';document.getElementById(\'tok\').value=\'\';go.disabled=false;\n};\n</script></body></html>'

PUBLIC_EXACT module-attribute

PUBLIC_EXACT = ('/login', '/auth/login', '/auth/logout', '/health', '/favicon.ico')

PUBLIC_PREFIX module-attribute

PUBLIC_PREFIX = ('/ui/static/', '/internal/')

API_PREFIX module-attribute

API_PREFIX = ('/v1', '/consumer', '/query-optimizer')

SessionClock

Started-at / last-activity bookkeeping for ONE session, with an inactivity limit and an absolute limit (seconds, None = no limit). Pure: the clock is time.monotonic.

The Connect-page session below is one instance; a login gate can keep one per cookie session and reuse touch / remaining / due unchanged.

started instance-attribute

started = time.monotonic() if now is None else now

last_activity instance-attribute

last_activity = time.monotonic() if now is None else now

__init__

__init__(ttl_s=None, max_s=None, now=None)

touch

touch(now=None)

remaining

remaining(now=None)

due

due(now=None)

None while valid, else 'max' or 'idle' (the limit that ran out).

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, max_profile, note='', ip='', ttl_s=None, max_s=None)

SessionStore

__init__

__init__()

add

add(session: Session) -> Session

get

get(sid: str, touch: bool = False) -> Optional[Session]

delete

delete(sid: str) -> None

clear

clear() -> None

LoginLimiter

FAIL_LIMIT failures in FAIL_WINDOW_S per key (client address, user name).

__init__

__init__(limit=FAIL_LIMIT, window=FAIL_WINDOW_S)

retry_after

retry_after(keys, now=None) -> int

Seconds to wait (0 = allowed).

fail

fail(keys, now=None) -> None

succeed

succeed(key) -> None

clear

clear() -> None

AuthMiddleware

Pure ASGI (so the Gradio mount and its streams pass through untouched).

Sits INSIDE the prefix-stripping middleware: the path it sees has no reverse-proxy prefix, except the Gradio mount which owns its prefixed path (handled by _relative).

app instance-attribute

app = app

root instance-attribute

root = root_path or ''

__init__

__init__(app, root_path: str = '')

__call__ async

__call__(scope, receive, send)

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).

auth_mode

auth_mode() -> str

'database', 'gateway' or 'off'. An unrecognised value is read as 'database': a typo must not silently switch a security setting off.

'gateway' (0.3.8.2) is the mode of a worker started by the gateway: the person was authenticated by the gateway, which says who it is in X-TDFS4DS-* headers accompanied by a key only the gateway and its worker know.

enabled

enabled() -> bool

gateway_key

gateway_key() -> str

gateway_identity

gateway_identity(headers: dict)

(user, roles, profile) from the gateway's headers, or None when the key is missing, empty or wrong (constant-time comparison). headers: lower-case names.

_minutes

_minutes(name: str, default: float) -> float

ttl_seconds

ttl_seconds() -> float

max_seconds

max_seconds() -> float

role_names

role_names() -> dict

profile -> database role name (upper case).

default_logmech

default_logmech() -> str

api_key

api_key() -> str

trust_proxy

trust_proxy() -> bool

cookie_secure_forced

cookie_secure_forced() -> bool

_secret

_secret() -> bytes

rank

rank(profile: str) -> int

at_least

at_least(profile: str, minimum) -> str

The higher of two profiles; minimum None or unknown changes nothing.

min_profile_setting

min_profile_setting() -> str

TDFS4DS_SERVE_MIN_PROFILE: the profile everybody logging on gets at least ('' = none). An unknown value is ignored (no elevation).

profile_for_roles

profile_for_roles(roles) -> str

The highest profile the roles grant; 'analyst' when none.

store_choice_open

store_choice_open() -> bool

May every profile choose the feature store? The ONE rule (0.3.8.10).

'gateway': each person has a worker of their own, so a switch moves only their store. 'off': no login gate. 'database': one process shared by everybody logged in, a switch would move the store for all of them: admin only.

required_profile

required_profile(method: str, path: str) -> str

sign

sign(sid: str) -> str

unsign

unsign(value: str) -> Optional[str]
session_from_cookie(cookie_value: Optional[str], touch: bool = False) -> Optional[Session]

parse_cookies

parse_cookies(header: str) -> dict

_logon_kwargs

_logon_kwargs(user, password, token, logmech, *, host=None, encrypt=None) -> Optional[dict]

host / encrypt (keyword-only, 0.3.8.2): the gateway logs a person on to the environment they chose. Default: TDFS4DS_TD_HOST / TDFS4DS_TD_ENCRYPT.

_quote_in

_quote_in(values) -> str

read_roles

read_roles(run) -> list

Roles of the logged-on person, direct and through roles granted to roles, plus the user's default role. run(sql) returns rows; anything that fails raises.

check_credentials

check_credentials(user, password, token, logmech, *, host=None, encrypt=None)

The database decides. Returns a dict: {'ok': True|False|None, 'detail': str, 'roles': list|None, 'role_note': str}. ok None = could not be established (unreachable, no driver): not a refusal.

_clean_user

_clean_user(user) -> str

login

login(user, password, token, logmech, ip) -> dict

The whole POST /auth/login decision. Returns {'status': int, 'body': dict, 'session': Session|None}. Never keeps or echoes the password / token.

current_user

current_user() -> Optional[str]

set_current_user

set_current_user(user)

reset_current_user

reset_current_user(token) -> None

spawn

spawn(fn, *args, name=None)

Start a daemon thread that sees the same current user as the caller (a worker of a streamed job would otherwise run with no person attached).

app_user_pairs

app_user_pairs() -> dict

Query-band pairs naming the person, for a process execution started from the app.

audit_write

audit_write(user, method, path, query, status) -> None

is_write

is_write(method: str, path: str) -> bool

safe_next

safe_next(value) -> str

A path inside the app: starts with one '/', no scheme, no host.

login_page

login_page(base: str, next_path: str) -> str

_is_api

_is_api(rel: str) -> bool

_json_body

_json_body(status: int, payload: dict, extra=None)

client_ip

client_ip(request) -> str

add_routes

add_routes(app, root_path: str = '') -> None

/login, /auth/login, /auth/logout, /auth/me (404 while the gate is off).