hsheinblatt opened a new pull request, #1524:
URL: https://github.com/apache/knox/pull/1524
KNOX-3587 - Read delegation policies in a single query on the token-exchange
evaluation path
## What changes were proposed in this pull request?
Previously, reading one delegation policy issued a query per child row.
selectByActor() and
selectById() ran the core SELECT and then one query for users, one for
groups, one for resources,
and one per resource for that resource's scopes, so a single read cost 4 + R
statements for a
policy holding R resources. selectAll() called the same assembler once per
row, costing
1 + N * (3 + R) statements to list N policies. A policy can hold an
unbounded number of users,
groups, resources and scopes, so both paths scaled with the data rather than
with the request.
selectByActor() is on the token-exchange path and runs once per delegation
exchange.
Policies are now read in one statement, and listed in a fixed number of
statements:
selectByActor() 4 + R -> 1
selectById() 4 + R -> 1
selectAll() 1 + N * (3 + R) -> 1 + 4 * ceil(N / 1000)
DelegationPolicyDatabase:
* buildSelectPolicySql(String predicate) assembles the whole-policy read as
five UNION ALL
branches -- the core row plus one per child table -- each tagged with a
row_kind literal
('C', 'U', 'G', 'R', 'S') and carrying its child values in two shared
columns, child_a and
child_b. The branches are summed, not joined to each other, so a read
returns
1 + users + groups + resources + scopes rows; joining the child tables
would have returned
their cartesian product. The predicate is restated per branch, and each
branch reaches its
rows through the core table's primary key or actor unique constraint and
the leading
registration_id column of the child table's primary key. SELECT_BY_ID_SQL
and
SELECT_BY_ACTOR_SQL are both built from it, so the two reads share one
statement shape.
* countPlaceholders(String) derives each statement's bind count from the
statement itself, and
bindRepeating() cycles the predicate values to fill them. Adding a branch
therefore cannot
desynchronize the binding from the SQL.
* assemblePolicy(ResultSet) folds the tagged rows into one DelegationPolicy.
Core values are
taken from the first row of any kind, because UNION ALL does not promise
branch order;
resources and scopes both go through computeIfAbsent, so a resource with
no scopes round-trips
as an empty set and a scope row is tolerated ahead of its resource row. An
unrecognized
row_kind throws rather than silently dropping child data.
* readCoreRow(ResultSet) and a new private record CoreRow hold a core row
while its children are
still being read. tokenTtlSec is boxed so a NULL token_ttl_sec stays null
instead of becoming
zero, with wasNull() consulted immediately after getInt(); the timestamps
are converted to
Instant on read.
* selectAll() now runs in two phases. Phase one reads the core rows and
applies the row cap
through PreparedStatement.setMaxRows(limit + 1), replacing the FETCH FIRST
n ROWS ONLY clause
that was previously concatenated into two instance fields; the limit+1 row
still detects
truncation without a COUNT query, and hasMore is unchanged. Phase two
reads the children of
exactly that page with four IN-list queries per batch of at most 1000
registration ids, folds
them by id, and rebuilds the policies in the order phase one returned. A
policy with no child
rows keeps empty collections.
* A package-private constructor overload takes the id batch size, validated
as at least one, so
the batching loop is reachable in tests without registering a batch's
worth of policies. The
existing four-argument constructor delegates to it.
* Removed, now unreachable: assemblePolicyFromRow(), selectStrings(),
selectResourcePolicy(),
selectScopesForResource(), the four single-id child SELECT constants, and
the two derived
selectAll SQL fields.
* Javadoc records the read strategy on the class, and records on selectAll()
that it is not a
snapshot: its phases are separate statements, so a policy deleted after
its core row was read
is returned with empty children, and one registered mid-read is absent.
The single-statement
reads have no such gap.
JdbcDelegationPolicyService: a comment on evaluate() marking the policy read
and the
single-query requirement. No behavioral change.
No public signature, SPI, DDL, index, dependency or configuration change.
findByActor(), get()
and list() return the same data as before; all six evaluate() deny reasons
are still
distinguishable, because the core branch is keyed on the actor alone and is
never filtered by
resource. Usernames and resource URIs are still matched in Java rather than
in SQL, so database
collation cannot widen an authorization decision.
## How was this patch tested?
Eleven tests added to JdbcDelegationPolicyServiceTest, covering the paths
whose assembly
changed:
testFindByActorReturnsEveryFieldAndAllChildCollections
testFindByActorKeepsNullableFieldsNull
testFindByActorPolicyWithNoChildRowsAtAllIsStillFound
testFindByActorResourceWithNoScopesRoundTripsAsEmptySet
testFindByActorMixedResourcesWithAndWithoutScopes
testFindByActorUnknownActorReturnsEmpty
testFindByActorAndGetReturnIdenticalPolicies
testListAssignsEachPolicyOnlyItsOwnChildRows
testListMixesPolicyWithNoChildRowsAndPolicyWithChildRows
testListReadsChildRowsAcrossIdBatchBoundaries
testListTruncatedPageStillCarriesItsOwnChildRows
The three that matter most: a policy with no users, groups or resources at
all must still be
found, since it contributes only its core row and would vanish if the core
branch were dropped;
three policies with pairwise disjoint children must each receive only their
own child rows,
since misfolding rows onto the wrong registration id is the failure mode the
batched list read
introduces; and the batch-boundary test drives the batching loop with a
batch size of two across
five policies. The fetch size is now clamped to the cap in the list path
since H2 rejects it..
All 60 pre-existing tests in that class are unchanged and pass, which is the
evidence that the
rewritten reads are behaviorally equivalent for every existing caller.
The whole gateway-server suite passes: 1083 tests, no failures or errors,
two pre-existing skips
unrelated to this change. checkstyle, PMD, SpotBugs with findsecbugs, and
forbiddenapis are
clean. Statement counts were confirmed against an instrumented DataSource
during development:
a policy with 20 resources and 60 scopes reads in one statement on one
connection, and listing
five policies takes five statements.
Database notes:
Supported backends are PostgreSQL, MySQL, MariaDB, Oracle and H2, and only
H2 runs in the test
suite. The read shape was exercised by hand on PostgreSQL 16, returning the
expected rows and
row kinds on each. On PostgreSQL at a seeded volume of 2003 policies, 10503
resources and 51503
scopes, the planner reached every child table by an index-only scan with no
heap fetches and
executed the 2009-row read in 0.9 ms server-side, which excludes connection
setup and client-side
row materialization.
The child_a and child_b placeholders in the branches that have
nothing to put there are plain NULLs. Every value those positions carry is a
character column,
so the union resolves them to a character type whichever branch supplies it.
Older Oracle
releases, however, took a union column's type from the first branch alone,
which would type
these two from the NULL rather than from the child values. That behavior is
documented only
indirectly and could not be reproduced, and no Oracle instance runs in this
project's tests, so
it is called out here rather than proven absent. Should Oracle reject the
statement with
ORA-01790, the fix is to select a real character column such as
p.registration_id in the first
branch and leave the later branches NULL; the code comment says so. Do not
switch to
CAST(NULL AS VARCHAR(n)), which MySQL has no cast target for.
Portability also narrowed the available designs, and the following are
deliberate rather than
incidental:
* No row-limiting clause is accepted by every supported backend. FETCH FIRST
n ROWS ONLY is
absent from MySQL and arrived only in recent MariaDB, while LIMIT is
unavailable on Oracle,
and no minimum server version is declared anywhere in the build. The cap
therefore moved out
of the SQL and into JDBC's setMaxRows. This also fixes a latent defect:
the FETCH FIRST clause
this change removes would not have parsed on MySQL, so listing policies
could not have worked
there.
* An explicit fetch size cannot exceed the row cap -- H2 rejects it -- so
the list path clamps
the two together while the uncapped reads use the full fetch size.
* Oracle rejects an IN list of more than 1000 expressions, which is why the
list path batches
registration ids at 1000 rather than binding a whole page at once. JDBC
offers no batched
READ, since addBatch applies to writes, so an IN list is the portable
mechanism.
* The list read is not wrapped in one transaction because a transaction
alone would not make it
a snapshot: PostgreSQL and Oracle default to READ COMMITTED, where each
statement takes a
fresh snapshot. A real snapshot needs REPEATABLE READ, which Oracle does
not offer, or
SERIALIZABLE, which on MySQL makes plain SELECTs take shared locks and
could block writers for
the length of a large listing.
* An explicit fetch size is set on the reads because a driver that defaults
to a small prefetch
would otherwise split a single statement over many round trips.
## Integration Tests
None added. Existing tests are sufficient to validate the functional change,
this is an
implementation change only. Load and performance tests are necessary to
detect improvement.
## UI changes
N/A
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]