[ 
https://issues.apache.org/jira/browse/KNOX-3606?focusedWorklogId=1056623&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-1056623
 ]

ASF GitHub Bot logged work on KNOX-3606:
----------------------------------------

                Author: ASF GitHub Bot
            Created on: 23/Nov/26 12:04
            Start Date: 23/Nov/26 12:04
    Worklog Time Spent: 10m 
      Work Description: smolnar82 opened a new pull request, #1539:
URL: https://github.com/apache/knox/pull/1539

   [KNOX-3606](https://issues.apache.org/jira/browse/KNOX-3606) - Store 
in-flight KnoxIDF authorization flow state in the gateway database
   
   ## What changes were proposed in this pull request?
   
   KnoxIDF kept the state of in-flight interactive authorization flows in 
JVM-local Caffeine caches (`AuthorizeRequestMetadataStore`, 
`FederatedOpConfigurationStore`, `FederatedNonceStore`). Each value is written 
on one browser request and read back on a later one:
   
   - **Consent flow:** `/authorize` stores the pending request, and 
`/authorize/consentAccepted` reads it back.
   - **Federated login flow:** `SSOCookieFederationFilter` stores the request 
and the offered OPs. `WebSSOResource` stores the selected OP and its nonce. 
`/authorize/callback` reads all of them.
   
   With more than one gateway behind a load balancer without affinity, the 
follow-up request often reached another instance. The user then got 
`invalid_request` ("Invalid state" / "Unknown or expired state").
   
   This PR moves that state into the gateway database when an external one is 
configured:
   
   - **New gateway service `KnoxIDFAuthzFlowStateService`** 
(`gateway.service.knoxidfauthzflowstate.impl`):
     - `JdbcAuthzFlowStateService` uses a new `KNOXIDF_AUTHZ_FLOW_STATE` table 
(`id`, `kind`, `payload`, `expires_at`), with DDL for every supported database 
and an Oracle variant. It is selected automatically when 
`gateway.database.type` points at an external database.
     - `InMemoryAuthzFlowStateService` is used otherwise, including embedded 
H2, which is local to one instance.
     - If the JDBC service is explicitly configured and cannot start, the 
gateway fails. If it was only auto-selected and cannot start, the gateway logs 
an error and falls back to memory.
     - `AuthzFlowStateStore` (gateway-spi) gives the KnoxIDF and KnoxSSO 
resources typed, JSON-serialized access to the service. A payload that cannot 
be parsed is treated as absent, so the flow fails closed.
   - **Single-use state is consumed atomically across instances.** This applies 
to the consent state and the federated callback state. Postgres and MariaDB use 
`DELETE ... RETURNING`, H2 uses `SELECT ... FROM OLD TABLE (DELETE ...)`, and 
MySQL and Oracle use SELECT followed by a DELETE whose affected-row count picks 
the winner. A replayed or concurrent consent POST or OP callback, on any 
instance, succeeds at most once. The consent subject-mismatch path still 
invalidates the state.
   - **No secrets are stored.** Only `FederatedOpLoginOption` (OP name plus 
authorization redirect values) and `FederatedOpSelection` (OP name plus nonce) 
are persisted. The callback resolves the full OP configuration, including the 
client secret and token endpoint, from the topology by name.
   - **Federated login state is written only for the `/authorize` endpoint.** 
Unauthenticated requests to other paths of a KnoxIDF topology no longer create 
flow state rows.
   - **TTL and cleanup:** `gateway.knoxidf.authz.flow.state.ttl.secs` (default 
300) and `gateway.knoxidf.authz.flow.state.cleanup.interval.secs` (default 60). 
They replace the store singletons whose TTL depended on which caller 
initialized them first. Reads ignore expired rows, and a periodic sweep deletes 
them. An `expires_at` index keeps the sweep from scanning, and on InnoDB from 
locking, the whole table.
   - **Performance:** each write is one INSERT, falling back to UPDATE on a key 
clash, and every consume runs on a single connection.
   - **Removed:** `KnoxIDFArtifactStore` and its three subclasses, plus the 
Caffeine dependency of gateway-util-common.
   - **Docs (`knoxidf/operations.md`, `configuration.md`):**
     - The HA section now states that, with an external database, no load 
balancer affinity is needed for the authorize flows.
     - New "Database load and connection pool sizing" section: statements per 
flow, the shared Hikari pool, and the `max_connections` rule.
     - Advice to rate-limit `/authorize` at the edge.
     - New checklist item.
   
   ## How was this patch tested?
   
   **Unit tests (all pass):**
   
   - `AuthzFlowStateDatabaseTest` (new, 18 tests). It runs on H2 once with 
`DELETE_FROM_OLD_TABLE` and once with `SELECT_THEN_DELETE` and covers:
     - strategy mapping per DB type, and idempotent `expires_at` index 
creation, including adding the index to an existing table
     - upsert replacing a row and upsert over an expired row
     - consume-once, and ignoring expired rows and rows of another kind
     - concurrent consume: 8 instances x 50 rounds, exactly one winner each 
round
     - `deleteExpired`
   - `JdbcAuthzFlowStateServiceTest` (13), including two service instances on 
one database; `InMemoryAuthzFlowStateServiceTest` (11); 
`AuthzFlowStateStoreTest` (7); `AuthzFlowStateServiceFactoryTest` (7); 
`AuthzFlowStateSchemaTest` (3).
   - `SSOCookieProviderTest`: federated login state is stored for `/authorize` 
and not for other paths. `KnoxIDFUtilsTest`: `isAuthorizeRequest`.
   - Module runs: gateway-util-common 211, gateway-provider-security-jwt 749, 
gateway-service-knoxidf 299, gateway-service-knoxsso 26, and the affected 
gateway-server tests 223.
   
   **Docker Compose E2E:**
   
   - Base suite (`docker compose -f 
.github/workflows/compose/docker-compose.yml up --exit-code-from tests tests`): 
168 passed.
   - HA suite, extended (`-f docker-compose.knoxidf-ha.yml`, two gateways on a 
shared Postgres): 5 passed.
     - New topology `knoxidf-consent.xml` (LDAP auth, auto consent off). The HA 
`gateway-site.xml` selects `JdbcAuthzFlowStateService`.
     - New 
`TestKnoxIdfHaAuthorizeFlowState::test_consent_accepted_on_the_other_node`: 
`/authorize` runs on `knox`, and the consent is accepted on `knox2`. Both 
gateways are called directly, with no load balancer in between.
     - New 
`TestKnoxIdfHaAuthorizeFlowState::test_concurrent_consent_on_both_nodes_succeeds_once`:
 the same consent state is posted to both gateways at the same time, and 
exactly one request succeeds.
   
   **Manual tests (local gateway, `gateway.database.type=postgresql`, so 
`JdbcAuthzFlowStateService` was auto-selected):**
   
   - **Consent flow (LDAP login):** registered a client on `knoxidf-sso` and 
ran Authorization Code + PKCE. The consent page was shown, consent was 
accepted, and the code was issued. The consent record (`consent_<hash>`) was 
stored in `knox_token_metadata`. Redeeming the code at `/token` returned tokens 
(`event=token_grant ... reason=tokens_issued`), and the code was consumed from 
`knox_tokens`.
   - **Federated flow (Auth0):** opened `/authorize` unauthenticated. The 
KnoxSSO login page offered the configured federated OPs (KeyCloak, Auth0). 
After the Auth0 login, `/authorize/callback` found the stored authorize request 
and the selected OP with its nonce, resolved the OP configuration by name, 
validated the id_token and nonce, and redirected to `redirect_uri` with a Knox 
code (`event=federated_callback op=Auth0 reason=federated_identity_resolved`).
   - **Authorize-only gate:** an unauthenticated request to the `homepage` 
topology is sent to the KnoxSSO login page without federated OP options.
   
   **Benchmark (Postgres 16, Hikari pool 10, separate harness calling the JDBC 
store directly):**
   
   The hot paths were tuned during development: insert-first upsert, 
single-connection consume and the `expires_at` index. That raised throughput by 
about 1.5x, and cut the sweep p50 from 32.5 ms to 0.78 ms with 400k rows. The 
numbers below are for the final code.
   
   | Scenario | Result |
   |---|---|
   | 8 threads, consent flow (put + consume) | 8,284 flows/s |
   | 64 threads | 6.9k-9.3k flows/s |
   | 400k preloaded rows + 1 s expiry sweep | 8,556 flows/s, sweep p50 0.78 ms |
   | 64 threads, pool 30 instead of 10 | 13,870 flows/s (vs 9,268), p99 55 ms 
(vs 119 ms) |
   
   The database isn't the bottleneck; the connection pool size is. That's why 
the docs now cover pool sizing and edge rate limiting for `/authorize`. MySQL 
and MariaDB have not been tested end to end. Their SQL paths are covered only 
by the H2 strategy tests.
   
   ## Integration Tests
   
   - New topology: `.github/workflows/build/conf/topologies/knoxidf-consent.xml`
   - Extended suite: `.github/workflows/tests/test_knoxidf_ha.py` (new 
`TestKnoxIdfHaAuthorizeFlowState` class)
   - Updated: `.github/workflows/compose/knoxidf-ha/gateway-site.xml`
   
   The HA suite runs only with the `test-ha` PR label.




Issue Time Tracking
-------------------

            Worklog Id:     (was: 1056623)
    Remaining Estimate: 0h
            Time Spent: 10m

> KnoxIDF: in-flight authorization state is node-local, breaking the 
> authorization-code flow in HA deployments
> ------------------------------------------------------------------------------------------------------------
>
>                 Key: KNOX-3606
>                 URL: https://issues.apache.org/jira/browse/KNOX-3606
>             Project: Apache Knox
>          Issue Type: Improvement
>          Components: KnoxIDF
>            Reporter: Sandor Molnar
>            Assignee: Sandor Molnar
>            Priority: Blocker
>          Time Spent: 10m
>  Remaining Estimate: 0h
>




--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to