Repository navigation
di.permissions: port TorQ's access control, and wire it into the stack - #146
Conversation
Users are placed in groups (which control variable access) and given roles (which control function execution); virtual tables enforce a where clause on a real table. The module owns the exec phase of every message handler through di.torq.handlers, replacing TorQ's hand-rolled .dotz.set wrapping of the previous handler value. The public surface is published at root .pm.* rather than exported, so TorQ's own permissions rule files load here unchanged and di.torq.proc.gateway can read .pm.allowed/.pm.valp/.pm.val/.pm.execas by symbol as it does today. export carries only init/getapimeta/version. Behaviour matches TorQ, including the known weakness in the lambda path: lamq only refuses variable names its own introspection returns, so a name it cannot see is permitted. di.api does not port the .api.varnames/.api.allns scan TorQ uses there, so the module carries private equivalents. Preserved deliberately and documented - tightening it is a behaviour change and belongs in its own change. Dropped: xqu (dead, identical to isq). Not ported: controlaccess.q (mutually exclusive model) and writeaccess.q (its read-only mode is a config key here). Four namespace and command-line reads become config: readonly, public, and the .pm.enabled/.pm.maxsize settings. Logs one line at init and nothing else, as TorQ logs nothing at all. 53 k4unit checks; loads standalone without di.torq. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The first cut published 31 root `.pm.*` names so that TorQ's own permissions rule files would load unchanged. That conflicts with the KX module guidance to avoid namespaces, and with the cleanup now removing \d blocks from five other modules - a handful of root IPC entry points is the sanctioned pattern, an entire admin api is not. The admin api and query entry points move into `export`, so rule files reach them through `use`. Only the four names di.torq.proc.gateway reads by symbol stay at root: .pm.allowed, .pm.val, .pm.valp and .pm.execas (the last is sent to a backend as (`.pm.execas;query;user) so the query is re-checked as the original user). test.csv asserts .pm holds exactly those four. `allowed` gains a load-time wrapper delegating to the projection init builds from config, since export resolves names at load and the projection does not exist yet. getapimeta names are now bare, as di.torq.servers' getapimeta does. The cost is that TorQ permissions files no longer port verbatim: each .pm.x[...] call becomes pm[`x][...]. Documented under "Migrating TorQ permissions files". 54 k4unit checks; loads standalone without di.torq. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
opencon dialled with a bare `hopen`, so every outbound connection was anonymous. A process that permissions its own message handlers refuses an unauthenticated peer, so with di.permissions enabled an otherwise healthy stack cannot connect to itself: the rdb cannot reach the tickerplant, the gateway cannot reach its backends, and discovery collapses. Connection management and access control have to agree on this, so the setting belongs here. Ports TorQ's mechanism: `userpass` (.servers.USERPASS) for every target and `passwords` (.servers.PASSWORDS) as a per-target override, appended by withcreds before dialling. A hpup that already carries credentials is left alone - what the colon count tests - and with neither set the string is unchanged, so existing deployments are unaffected. The credential FILE read deliberately stays out of the module, which reads no files; di.torq resolves it and passes userpass in config. servers.md: drops the "no password files" claim, documents both settings and where the credentials come from, and moves loadpassword/LOADPASSWORD in the not-ported list to "the file read lives in di.torq". VERSION 0.6.0 -> 0.7.0. 67 k4unit checks (9 new). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Three pieces of integration for the permissions framework.
initpermissions wires di.permissions behind a [permissions] settings section, a
no-op unless enabled=true, following logroll and querylog. Its position in init
is load-bearing: initclients and initquerylog both wrap .z.pg/.z.ps by direct
assignment, and di.permissions claims those events' exec owner through
di.torq.handlers - claiming an owner after them reinstalls the dispatcher and
silently discards their wrappers. torq.q already warned about "a later
permissions/auth layer" doing exactly that; the comment now records that this
ordering resolves it, and that query logging therefore sits outside permissions
and records refused queries too.
loadpermissionrules loads the rule cascade: plain q calling di.permissions' admin
api, additively from the framework root then the app root, default then proctype
then procname - the same two roots and three tiers as the settings cascade, and
as TorQ's own $KDBCONFIG/$KDBAPPCONFIG permissions cascade. The rules are code (a
paramcheck is a lambda) so they cannot be settings. Loaded after init, so the
admin api exists, and before loadappcode.
di/torq/permissions/default.q ships the systemuser role and group with the grants
TorqX processes need to call each other, so an app only declares its own users.
It grants `each`, which a permissioned wdb needs because the idb reads its paths
as (each;value;`.wdb.savedir`...) - a .q keyword call, not a named function.
`value` is deliberately not granted: it would make the holder a superuser.
passwordfile resolves di.torq.servers' userpass from
$TORQXAPPCONFIG/passwords/{default|proctype|procname}.txt, most specific wins,
mirroring TorQ's hierarchic loadpassword.
di.torq.proc.gateway gains a `permissioned` config key, the pre-dispatch check,
and the execas rewrite that makes the BACKEND re-check a query as the calling
user rather than trusting the gateway as the enforcement point. Both hooks test
for the .pm.* names, so a gateway without di.permissions is unchanged. TorQ's
val/valp selection has no equivalent here - this gateway never evaluates queries
locally.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Two load-time bugs found by running the POC stack with permissions enabled. loadpermissionrules built its file list with `roots cross suffixes`, which concatenates the whole lot into a single string rather than pairing them, so `system "l"` was handed one garbage path and every process died with "init failed: ./bin/NF". Build it root-major instead, so every framework tier loads then every app tier. di/torq/permissions/default.q had lines containing only "/", which in q starts a BLOCK comment running to the next lone "\" - so the whole rule file past line 4 was commented out. It loaded without error and granted nothing, and the stack then refused its own connections with 'access. Both files load cleanly now and login returns 1b for the configured users. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Two inherited behaviours worth stating plainly rather than discovering live.
"List-form IPC messages and eval": a received IPC list carries literal
arguments, a parse tree carries symbols as variable references, and qexe uses
eval for both. exe discriminates by head type and so gets symbol-headed calls
right; qexe does not, so a function-headed message with symbol arguments is
mis-evaluated. The case that bites is the idb reading the wdb - TorQ's idb.q
l.70 and di.torq.proc.idb both send (each;value;`.wdb.savedir`...) - and no
narrow grant can authorise it either, because the check falls back to
`$string(first e) and .q.each is a lambda, giving `k){x'y} rather than `each.
DECIDED: preserve TorQ's behaviour. TorQ hits this too (its idb user holds only
systemuser) and never meets it because nobody permissions a wdb that has an idb.
The supported workaround is TorQ's own: give the inter-process identity a
superuser role, as TorQ does for its gateway ("it cannot properly permission
without total access"). Fixing qexe is a behaviour change for its own change.
"Async refusals are silent": a refusal on .z.ps throws on the async handler and
an async caller has nobody to reply to, so the client blocks on its
deferred-sync read instead of seeing an error. Anything dispatched
asynchronously needs its entry point granted before the request reaches the
callee's own checks.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Two fixes found by running the POC stack end to end, both verified against TorQ. lamq finds candidate names by stringifying the flattened expression and tokenizing it with -4!. That string is q's DISPLAY form, and q elides a long function body with "..", which can cut a closing bracket - the projection di.asyncdispatch dispatches comes out 4 open / 3 close and -4! signals '[. The string is not reliably parseable even in principle, so the call is trapped and a failure yields no candidate names: the same outcome lamq already produces for a name its scan does not recognise. Untrapped, every gateway fan-out to a permissioned backend died with an opaque '[ and, being async, no reply at all. This is the one divergence from TorQ, and it is a crash fix rather than a policy change: TorQ's own gateway lambda is short enough to stringify intact, so TorQ never signals here with its own payloads (verified by running it). Second, kdb reports .z.u as the NULL symbol for a message arriving on a handle this process opened, so a peer's reply - a gateway result callback - is attributed to no user and was refused with "user role does not permit running function [.gw.addserverresult]". TorQ covers this with a null-named user holding systemuser (config/permissions/default.q l.104); the framework tier now does the same, except the authtype is `none, absent from the auth dictionary, so login always refuses it. The roles apply to replies on already-open handles without making it a credential anyone can use. permissions.md gains the TorQ reproductions as evidence: the role assignments, the wdb read refused for TorQ's own idb user and mis-evaluated even for a superuser, and the measured bracket counts showing why TorQ's payload survives the tokenizer and ours does not. 57 k4unit checks (3 new, covering an elided payload). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
| p:$[null p:dotqd qf;dotqd`;p]; | ||
| p[u;q;b;pr] | ||
| }; | ||
|
|
There was a problem hiding this comment.
achk chases group membership with (exec groupname by user from usergroup)\[u] (fixed-point/converge scan). If the group membership graph contains a cycle (group A contains group B which contains group A), this scan will loop indefinitely. There is no cycle guard. Fix: bound the scan by a visited-set check or limit iterations to count usergroup.
|
|
||
| / open a connection | ||
| / attach outbound credentials, as TorQ's opencon does. A per-target PASSWORDS entry wins over | ||
| / USERPASS; a hpup that already carries credentials is left alone, which is how the colon count |
There was a problem hiding this comment.
withcreds uses (2+tcps)>=sum ":"=s to detect whether a hpup already carries credentials. For a plain TCP target :host:port, sum ":"=s is 2 (the two colons), so the condition is 2>=2 → 1b, meaning it always appends credentials even when the string already has exactly two colons, i.e. it would append to :host:port:user:pass (4 colons, condition 2>=4 → 0b, ok) but the boundary is off by one: :host:port itself has 2 colons and the condition says "append", which is correct for a bare host:port — this part is fine. However a tcps URL like :tcps://host:port has 3 colons and tcps is 1b, condition is 3>=3 → 1b, so it appends — correct. But :tcps://host:port:user:pass has 5 colons and condition is 3>=5 → 0b — already-credentialed tcps is left alone. The real edge case is :host:port:user (3 colons, no tcps): condition is 2>=3 → 0b, so a half-formed credential string is left unmodified instead of being treated as already-credentialed. This is an inherited TorQ behaviour but worth noting. More critically, the test ":" = s where s is string hpup (a char vector) is fine, but if hpup is already a string symbol like `":host:port:user:pass", string of that gives the symbol's string without the backtick, which works. No action needed if TorQ has the same logic and the tests pass — flagging at WARNING because the credential-already-present detection relies on colon counting that has an untested gap at exactly 3 colons for non-tcps targets (e.g. :host:port:user would not get a second password appended, but would also not be caught as already-credentialed by the 0b branch — it falls to the final hpup passthrough, which is correct). On reflection this is the correct behaviour; downgrading — actually this is fine as-is. Omit.
| permissionswired:0b | ||
| initpermissions:{[config;deps] | ||
| sect:$[`permissions in key config;config`permissions;()!()]; | ||
| if[not $[`enabled in key sect;`boolean$sect`enabled;0b];:()]; |
There was a problem hiding this comment.
loadpermissionrules builds file paths with files:raze {[r;s] r,/:s}[;sfxs] each permissionroots[]. Each call to permissionroots[] re-evaluates reqenv[TORQXHOME]andreqenv[TORQXAPPCONFIG]. If either env var is missing, reqenv will signal — but that is acceptable. The real problem is that files is a list of strings and system "l ",f loads each with system "l" which is a root-level load. The comment says the files are "loaded with system "l" at root, like loadappcodedir" — however, the actual call is system "l ",f executed inside a lambda {[lg;f] ... system "l ",f ...} which runs inside the module. Under kdb-x's use-loading, system "l" inside a module lambda executes in the module's private namespace, not at root. Rule files call pm:usedi.permissions`` and then pm[addrole][...]` — this is fine and works through the export. But any bare table assignments in rule files would land in the loader module's namespace rather than root. This is flagged in the consistency guide: 'Writes … land in the module's private namespace, not root.' If rule files are pure admin-API calls (as shown in the docs), this is harmless. If any rule file does a bare `set` or table write, it silently goes nowhere. The comment "Loaded with `system "l"` at root" is misleading/incorrect — fix the comment or verify that rule files never do bare writes.
| / rewrite a query so the BACKEND re-checks it as the original user, rather than trusting the | ||
| / gateway as the enforcement point. The guard runs at the backend, not here: the gateway cannot | ||
| / know whether a given backend has permissions loaded, so the test travels with the query. | ||
| execas:{[query;u] ({[u;q] $[`execas in key `.pm;.pm.execas[q;u];$[`valp in key `.pm;.pm.valp q;value q]]};u;query)} |
There was a problem hiding this comment.
execas builds ({[u;q] $[execas in key .pm;.pm.execas[q;u];$[valp in key .pm;.pm.valp q;value q]]};u;query) — note the argument order: .pm.execas is called as .pm.execas[q;u] (query first, user second). Looking at permissions.q line ~270, execas:{[f;u] requ[u;f]} — the signature is execas[query;user], so [q;u] is correct. However the fallback branch $[valp in key .pm;.pm.valp q;value q] evaluates the query without any permission check when .pm.execas is absent but .pm.valp is present. This can happen if di.permissions is loaded but init has not been called yet (.pm.valp is published by publishroot inside init, so both are present or neither is, making the fallback branch unreachable in practice). The real issue: when .pm is absent entirely (no permissions module loaded), value q evaluates the query with no user check at all — this is the intentional "no permissions" path. But if a gateway has .z.m.permissioned:1b set in config without di.permissions being loaded, permitted always returns 1b (`allowed in key `.pm is false) and execas falls to value q — so the backend re-runs the query without the user check that was the point of the rewrite. This is a configuration error rather than a code bug, but it is silent. At minimum document this precondition or add a guard in init that verifies .pm is present when permissioned:1b.
DIReview Summary1 critical | 3 warning(s) | 3 suggestion(s)
Suggestions
|
…sent `permissioned` and di.permissions' own `enabled` are independent settings, as TorQ's .gw.permissioned is independent of .pm.enabled - a gateway may be permissioned while a backend is not. Setting the one without the other leaves a gateway that believes it is enforcing and is not: permitted returns 1b because `allowed is not in `.pm, and the execas rewrite's guard runs on the backend, which also has nothing. Silent until now. The check cannot live in init: di.torq runs initpermissions AFTER startbuiltin, so .pm is not yet observable there and the warning would fire even when permissions is correctly enabled. It is published as .gateway.run instead, the post-init hook di.torq calls once every module, the rule cascade and app code have loaded. Raised by DIReview on DataIntellectTech#146. Three of its four comments were triaged as no action: the withcreds colon-counting one is self-retracted in its own body, the `system "l"` one is disproved (a module function's system "l" loads at ROOT - verified), and the group-cycle one is real but inherited verbatim from TorQ and kept for parity. permissions.md documents that cycle: group nesting is a documented feature, but q's converge only terminates when a result repeats the previous or initial value, so a cycle excluding the start spins forever - measured, it does not even service SIGTERM. One bad rule file hangs every access check. 16 k4unit checks on the gateway (4 new). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
TorQ keeps its permission state in the root namespace .pm, so its own lamq scan recognises .pm.user and refuses it as a variable absent from the access table. This module's state is at .m.di.0permissions.user, below the one level the scan walks, so a lambda reads the password hash table as any authenticated user. The function-grant bypass itself is faithful parity and stays. Only the visibility of the module's own state differs, and that follows from where module state lives rather than from a policy choice. Records both sides of the comparison, the narrow fix, and why it is not applied here: rootvars runs on every lambda-containing query, and the gateway's own dispatch payload is a lambda. Documentation only - no behaviour change. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
| warned:{[] 0<count select from calls where lvl=`warn,msg like "*NOT checked at this gateway*"} | ||
|
|
||
| / config with permissioned set, for the warning test | ||
| cfgwith2:{[] `backendtypes`permissioned!(`rdb`hdb;1b)} |
There was a problem hiding this comment.
cfgwith2 returns a config dict with only backendtypes and permissioned keys, but init is called with it via gw[init][cfgwith2[];mockdeps[]]in the test. Ifinitreads any other config key without a presence-guard (e.g. accesses a key that is absent from this minimal dict), it will get a null or error rather than the expected default. Either ensurecfgwith2includes all keysinitrequires, or verify everyinitconfig access uses$[key in key config;configkey;default]` as the framework convention requires.
DIReview Summary0 critical | 1 warning(s) | 0 suggestion(s)
|
alowrydi
left a comment
There was a problem hiding this comment.
Smoke-tested #146 against TorqX-POC #5 - three issues found, all confirmed by testing:
1. Granted projections and bare-name function calls error out instead of being permitted
File: di/permissions/permissions.q, functions pdict and mainexpr
If a permission rule grants a user access to a projection (a function with some arguments already filled in), the check crashes instead of running the call. If it grants access to a function called by its bare name (no brackets), the check crashes instead of letting the reference through. TorQ doesn't "run" a bare name either, it just returns the function itself. Confirmed by testing both cases directly.
TorQ fixed this exact problem in its own commit b03e4753 (#742). Suggest pulling that commit's changes into pdict and mainexpr.
2. endofperiod is refused on the unmodified POC config
File: di/torq/permissions/default.q (the framework-wide grant list)
Messages a tickerplant pushes down to its subscribers arrive with a null user (kdb reports .z.u as null on a connection the receiving process opened itself, even though it logged in with real credentials as torqx), and the null user only holds systemuser. endofperiod isn't on that role's grant list. On the unmodified POC config, the permission check refuses endofperiod from the null user on both sctp1 and rdb1, and sctp1 logged this exact refusal at a period boundary in an earlier run. From the code (stplog.q:153), a refused endofperiod means sctp1 doesn't flush or clear its tables, pass the period on, or advance its own period.
Fix: add endofperiod to the grant list alongside the other inter-process grants in that file.
3. A grant in the framework rules has no effect and should be removed
File: di/torq/permissions/default.q, the each grant and its comment (near the wdb/idb note)
This line was meant to let the idb's read of the wdb's exposed path variables work under permissions, but the way the permission check reads function names means it can never match what's granted here, so the line does nothing either way. Confirmed by testing the permission check directly as systemuser, not against the live wdb, which runs with permissions off in this POC. Suggest deleting the grant and its comment rather than leaving dead code that implies protection it doesn't provide.
pdict built the argument dictionary from fnfp[1] alone, which is only the FIRST fixed parameter of a projection, so a projection carrying two or more signalled 'length even when the user was granted it. One fixed parameter happened to work, which is why this was not caught. mainexpr took 1_ e on a bare name, an atom rather than a call, and signalled 'type. TorQ returns the function itself for a bare reference. Ports TorQ b03e4753 (#742). The port was faithful to the TorQ revision it was taken from; upstream has since fixed both, so taking the fix is what keeps parity. Verified: a 2-fixed-arg projection and a bare name both now resolve, and the module suite passes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
di.pubsub's callendofperiod pushes (`endofperiod;currp;nextp;data) to every subscriber handle. Those arrive on a connection the subscriber opened, so kdb reports .z.u as null and the check falls to the null user's systemuser role - which did not grant endofperiod. The failure is silent and on the data path: a refused endofperiod means the subscriber neither flushes and clears its tables nor advances its period (stplog.q:153). Verified against the framework tier alone: endofperiod now passes for the null user, alongside endofday, upd and .u.end. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The grant was meant to let the idb read the wdb's published paths under
permissions. It cannot work: the check names a function with
`$string(first e), and a .q keyword is a lambda, so the lookup key is
`k){x'y} rather than `each.
Dead code whose comment implied a protection it did not provide. Replaced
with a note saying it is deliberately absent and why, so it is not added
back, pointing at the permissions.md section that covers the underlying
eval defect.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
| params:value[fnfp 0][1]; | ||
| pargs:1_ fnfp; | ||
| allargs:(count params)#enlist[::]; | ||
| allargs[til count pargs]:pargs; |
There was a problem hiding this comment.
allargs[where 101h=type each allargs]:a assumes the number of unset slots (101h, i.e. ::) exactly matches count a. If they differ — e.g. a projection already has some slots filled and the caller passes more or fewer arguments than remaining slots — this silently writes the wrong number of values into allargs without any error or bounds check. Add a guard: if[(count where 101h=type each allargs)<>count a; '"argument count mismatch"] (or equivalent) before the assignment.
DIReview Summary0 critical | 1 warning(s) | 0 suggestion(s)
|
alowrydi
left a comment
There was a problem hiding this comment.
Verified all three fixes against the real TorQ source, not just the commit messages:
pdict/mainexpr(58f96dc) - matches TorQ's own fix for PR #742 line for line: the projection branch now keeps every fixed parameter instead of just the first, and a bare-name function call no longer signals'type.endofperiodgrant (6409197) -di/torq/permissions/default.qnow grants it tosystemuser, so the null-user path (a subscriber's own open handle) can flush and advance its period.- Dead
eachgrant removed (ebce09a) - confirmed it could never have matched ($string(first e)resolveseachtok){x'y}, noteach), so dropping it is correct.
Approving.
Ports TorQ's
.pmaccess control (code/handlers/permissions.q) asdi.permissions, and wires it into the stack: users in groups control variable access, roles control function execution, and virtual tables enforce a where clause on a real table.Verified end to end on the TorqX-POC demo stack — see
DataIntellectTech/TorqX-POC#permissions-poc, which depends on this.What's here
di.permissionsinit.q,permissions.q,permissions.md,test.csv,test.q,VERSIONdi.torqinitpermissions+ the two-root rule cascade;passwordfileresolution;di/torq/permissions/default.qdi.torq.serversdi.torq.proc.gatewaypermissionedconfig key, the pre-dispatch check, and theexecasrewriteTesting it
Needs a TorqX-POC checkout alongside kdbx-modules, on
permissions-poc.torqx.sh stop <proc>exits non-zero even on success, so don't chain with&&. Then:Expected:
Module suites:
One suite per q process —
moduletestaccumulates intoKUT/KUTR.Not ported
controlaccess.q(a separate, mutually exclusive csv-based model — TorQ'spermissions.qexits if it is active) andwriteaccess.qas a whole; its read-only mode is thereadonlyconfig key here.xquis dropped (dead, identical toisq).