Skip to content

Commit af92bae

Browse files
committed
feat: authorize task listings with JPA ownership scopes
Add optional backend-neutral authorization capabilities and an explicitly selected JPA ownership provider. Apply matching authorization scopes to count and page queries while preserving deny-by-default behavior and bounded fallback checks with opaque-token recovery. Persist exact UTF-8 subject identities as binary ownership keys and isolate first-writer-wins insertion and confirmation transactions. Cover identity equality and repeatable-read ownership races on PostgreSQL and MySQL, and document schema migrations, provider selection, and cloud deployment. Signed-off-by: Kabir Khan <kkhan@redhat.com>
1 parent a87f659 commit af92bae

32 files changed

Lines changed: 1912 additions & 87 deletions

‎.github/workflows/build-and-test.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ jobs:
3434
distribution: 'temurin'
3535
cache: maven
3636
- name: Build with Maven and run tests
37-
run: mvn -B package --file pom.xml -fae ${{ matrix.os == 'windows-latest' && '-DskipDockerTests=true' || '' }}
37+
run: mvn -B package --file pom.xml -fae ${{ matrix.os == 'windows-latest' && '-DskipDockerTests=true' || '-DskipDockerTests=false' }}
3838
- name: Upload Test Reports
3939
if: failure()
4040
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7

‎docs/content/dev/authorization.md‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,17 @@ public class MyTaskAuthorizationProvider implements TaskAuthorizationProvider {
2828

2929
@Override
3030
public boolean checkRead(ServerCallContext context, String taskId, TaskOperation op) {
31+
if (op == TaskOperation.LIST_TASKS && taskId.isEmpty()) {
32+
return context.getUser() != null && context.getUser().isAuthenticated();
33+
}
3134
return isOwner(context, taskId);
3235
}
3336

3437
private boolean isOwner(ServerCallContext context, String taskId) {
3538
String owner = ownershipStore.get(taskId);
3639
return owner != null
3740
&& context.getUser() != null
41+
&& context.getUser().isAuthenticated()
3842
&& owner.equals(context.getUser().getUsername());
3943
}
4044

@@ -55,7 +59,7 @@ public class MyTaskAuthorizationProvider implements TaskAuthorizationProvider {
5559

5660
@Override
5761
public void recordOwnership(ServerCallContext context, String taskId, TaskOperation op) {
58-
if (context.getUser() != null) {
62+
if (context.getUser() != null && context.getUser().isAuthenticated()) {
5963
ownershipStore.putIfAbsent(taskId, context.getUser().getUsername());
6064
}
6165
}
@@ -79,12 +83,40 @@ Authorization decisions rely on `context.getUser()` returning the authenticated
7983
| `cancelTask`, `createTaskPushNotificationConfig`, `deleteTaskPushNotificationConfig` | `checkWrite` |
8084
| `messageSend` / `messageSendStream` (existing task) | `checkWrite` |
8185
| `messageSend` / `messageSendStream` (new task) | `checkCreate`, then `recordOwnership` |
82-
| `listTasks` | `checkRead` per task |
86+
| `listTasks` | Unconditional `checkRead(context, "", LIST_TASKS)` gate, authorized count/page selection, final returned-task checks |
87+
88+
## Persisted JPA ownership
89+
90+
The optional JPA module provides `JpaTaskAuthorizationProvider`. Adding the module does not select it. Explicitly enable the CDI alternative (in Quarkus, `quarkus.arc.selected-alternatives=org.a2aproject.sdk.extras.taskstore.database.jpa.JpaTaskAuthorizationProvider`), register `JpaTaskOwner` with `JpaTask` in the same `a2a-java` unit, and migrate the ownership table and complete index. See [Storage & Persistence](extra/storage.md) for PostgreSQL `BYTEA` and MySQL `VARBINARY(1024)` setup.
91+
92+
The provider requires authenticated subjects, denies unknown ownership, and records a persistent first owner without transfer. Strict UTF-8 subject identities have a 1,024-byte limit; malformed surrogates and oversized values are rejected. Case, accents, Unicode-normalization forms and trailing spaces remain distinct. There is no normalization, trimming, truncation or lossy hashing. Usernames must be unique across the deployment; multiple issuers or tenant-local names require namespaced keys or a custom policy. Backfill only from a trusted source preserving original identities.
93+
94+
Outside CDI, use `JpaTaskOwnershipRepository.create(entityManagerFactory, transactionManager)`, then `new JpaTaskAuthorizationProvider(repository)`, and pass it to the handler builder. The JTA factory and manager must govern the task database. Insertion and duplicate confirmation each run in a separate new transaction with a fresh persistence context; insertion rolls back before confirmation. Never instantiate the transaction helper directly, as this bypasses CDI interception.
95+
96+
## Optional backend capabilities
97+
98+
Core authorization stays independent of storage technology:
99+
100+
```java
101+
default <T> Optional<T> getCapability(Class<T> capabilityType) {
102+
return Optional.empty();
103+
}
104+
```
105+
106+
Existing providers inherit empty discovery. Stores define backend-specific capability interfaces and request them from the **same configured provider** used by the handler. Empty means bounded fallback; present means supported policy, including explicit all/none scopes. Exceptions fail the request and never mean unsupported or allow-all.
107+
108+
JPA requests `JpaTaskAuthorizationCapability.readScope(context, operation)`. Its closed scopes are `JpaTaskReadScope.OwnedBy(subject)`, `All`, and `None`. A capability represents the provider's **complete per-task policy for that operation**. Wrappers adding restrictions must not forward a broader delegate capability. Custom allow-all providers may expose `All` only when individual checks agree; it includes unowned tasks.
109+
110+
Both database `COUNT` and paginated `SELECT` apply the same scope and ordinary filters. The cursor never narrows the exact authorized total. Only returned page data is deserialized and transformed. The handler still applies its unconditional list gate and final task checks; these cannot repair an overbroad count or replace exact query equality.
111+
112+
Unsupported providers retain iterative checks. JPA exact counts can fail at the configured candidate ceiling, without returning partial totals. See [Configuration](configuration.md) for JPA fallback settings. Capability queries do not use these Java scan limits.
83113

84114
## Default authorized listing fallback
85115

86116
Stores that do not override `TaskStore.listAuthorized` use a bounded fallback over `list`. Each call scans all matching candidates to count authorized tasks, then separately traverses the requested page and looks ahead for more authorized tasks. This can scan the full candidate set twice, even for a small requested page.
87117

88-
The count scan fetches batches of 100 candidates. Counting and page traversal/lookahead each have separate limits of 300 queries or 20,000 returned candidate tasks, including denied tasks. Exceeding either limit throws `TaskStoreException` rather than returning a partial total; JPA configuration properties do not change these generic limits. Stores with larger candidate sets or more efficient query support should override `listAuthorized`, applying the supplied provider's authorization before pagination and counting authorized matches across all pages independently of the cursor.
118+
The fallback fetches batches of up to 100 candidates and separately limits count queries (300), normal page/lookahead queries (300), and distinct candidate tasks per phase (20,000, including denied tasks). Up to 100 extra queries may recover an opaque continuation token within the final fetched batch. Exceeding any limit throws `TaskStoreException` rather than returning a partial total; JPA configuration properties do not change these generic limits. Stores with larger candidate sets or more efficient query support should override `listAuthorized`, applying the supplied provider's authorization before pagination and counting authorized matches across all pages independently of the cursor.
119+
120+
The exact `totalSize` assumes stable task data and authorization decisions. The default fallback does not share a snapshot between counting and page selection, so concurrent task additions, deletions, or updates can make the count, returned page, and continuation token disagree. Overrides follow their store's consistency and isolation guarantees; JPA count and page queries use the configured database isolation without an implied stronger snapshot guarantee.
89121

90-
The exact `totalSize` assumes stable task data and authorization decisions. The default fallback does not share a snapshot between counting and page selection, so concurrent task additions, deletions, or updates can make the count, returned page, and continuation token disagree. Overrides follow their store's consistency and isolation guarantees.
122+
Without a provider, access is denied unless explicitly disabled. `a2a.authorization.required=false` only opts out when no provider is present; configured providers remain authoritative.

‎docs/content/dev/configuration.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,21 +74,23 @@ When enabled, task IDs referenced in incoming messages are looked up in the `Tas
7474
a2a.authorization.required=true
7575
```
7676

77+
A configured provider remains authoritative even when `a2a.authorization.required=false`; that flag only permits providerless access.
78+
7779
See [Task Authorization](authorization.md) for details on implementing a `TaskAuthorizationProvider`.
7880

7981
### JPA Task Store Authorized Listings
8082

8183
These settings apply when using the JPA Task Store together with a `TaskAuthorizationProvider`:
8284

8385
```properties
84-
# Maximum candidate rows inspected while counting an authorized task listing (default: 10000)
86+
# Fallback only: maximum candidates inspected for an exact authorized count (default: 10000)
8587
a2a.max-scanned-tasks=10000
8688

87-
# Candidate rows fetched in each database query during that scan (default: 100)
89+
# Fallback only: candidates fetched per query (default: 100)
8890
a2a.authorization-scan-batch-size=100
8991
```
9092

91-
`a2a.max-scanned-tasks` bounds the work performed while counting authorized tasks. The count must be exact, so a listing fails if the scan limit is reached before all matching candidates have been inspected. `a2a.authorization-scan-batch-size` controls the database fetch size within that budget. Both values must be greater than zero. Increase the batch size to reduce round trips when many candidates are denied; lower it to reduce memory used per query.
93+
`a2a.max-scanned-tasks` bounds the work performed while counting authorized tasks. The count must be exact, so a listing fails if the scan limit is reached before all matching candidates have been inspected. `a2a.authorization-scan-batch-size` controls the database fetch size within that budget. Both values must be greater than zero when fallback is used. These settings apply only to providers without `JpaTaskAuthorizationCapability`; the explicitly selected `JpaTaskAuthorizationProvider` enables database-side count/page filtering without Java candidate-scan ceilings. Increase the batch size to reduce round trips when many candidates are denied; lower it to reduce memory used per query.
9294

9395
### Push Notification Config Store
9496

‎docs/content/dev/extra/storage.md‎

Lines changed: 73 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ quarkus.datasource.db-kind=postgresql
3636
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/a2a_db
3737
quarkus.datasource.username=your_username
3838
quarkus.datasource.password=your_password
39-
quarkus.hibernate-orm.database.generation=update
39+
quarkus.hibernate-orm."a2a-java".datasource=<default>
40+
quarkus.hibernate-orm."a2a-java".packages=org.a2aproject.sdk.extras.taskstore.database.jpa
41+
# Application-managed production migrations; update is only for development
42+
quarkus.hibernate-orm."a2a-java".database.generation=none
4043
```
4144

4245
#### For WildFly/Jakarta EE Servers
@@ -52,10 +55,11 @@ Create or update your `persistence.xml`:
5255
<jta-data-source>java:jboss/datasources/A2ADataSource</jta-data-source>
5356

5457
<class>org.a2aproject.sdk.extras.taskstore.database.jpa.JpaTask</class>
58+
<class>org.a2aproject.sdk.extras.taskstore.database.jpa.JpaTaskOwner</class>
5559
<exclude-unlisted-classes>true</exclude-unlisted-classes>
5660

5761
<properties>
58-
<property name="jakarta.persistence.schema-generation.database.action" value="create"/>
62+
<property name="jakarta.persistence.schema-generation.database.action" value="none"/>
5963
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
6064
</properties>
6165
</persistence-unit>
@@ -64,7 +68,7 @@ Create or update your `persistence.xml`:
6468

6569
### 3. Database Schema
6670

67-
The module automatically creates the required table:
71+
Schema creation is controlled by the application. Production upgrades require an application-managed migration for both task and ownership tables before using the updated store. Register both entities in the same `a2a-java` unit; package scanning discovers them in Quarkus. The task schema includes:
6872

6973
```sql
7074
CREATE TABLE a2a_tasks (
@@ -77,6 +81,61 @@ CREATE TABLE a2a_tasks (
7781
);
7882
```
7983

84+
### 4. Ownership schema and authorization selection
85+
86+
PostgreSQL 16 ownership DDL:
87+
88+
```sql
89+
CREATE TABLE a2a_task_owners (
90+
task_id VARCHAR(255) PRIMARY KEY,
91+
subject_key BYTEA NOT NULL
92+
);
93+
CREATE INDEX a2a_task_owner_subject ON a2a_task_owners (subject_key, task_id);
94+
```
95+
96+
MySQL 8 ownership DDL:
97+
98+
```sql
99+
CREATE TABLE a2a_task_owners (
100+
task_id VARCHAR(255) PRIMARY KEY,
101+
subject_key VARBINARY(1024) NOT NULL
102+
);
103+
CREATE INDEX a2a_task_owner_subject ON a2a_task_owners (subject_key, task_id);
104+
```
105+
106+
Verify the actual binary type and complete index. PostgreSQL must use `BYTEA`, not a large-object OID. MySQL requires variable-length `VARBINARY(1024)`, not padded `BINARY`, text with a binary collation, or a prefix index. Other databases need an equivalent exact variable-length binary mapping.
107+
108+
The SDK uses strict UTF-8 and rejects malformed surrogates or subjects exceeding 1,024 encoded bytes before ownership access. Case, accents, Unicode-normalization and trailing-space distinctions remain significant; there is no normalization, trimming, truncation, padding or lossy hashing. Backfill only from a trusted source preserving original subject keys. Audit legacy text-collation associations and lossless conversion; a migration cannot recover distinctions already discarded.
109+
110+
Adding the module selects the task store but does not enable an authorization provider. Explicitly select the supplied owner-only provider in Quarkus:
111+
112+
```properties
113+
quarkus.arc.selected-alternatives=org.a2aproject.sdk.extras.taskstore.database.jpa.JpaTaskAuthorizationProvider
114+
```
115+
116+
For portable CDI, expose an ordinary application producer instead of relying on archive-scoped `beans.xml` alternative selection:
117+
118+
```java
119+
@ApplicationScoped
120+
public class TaskAuthorizationConfiguration {
121+
@Produces
122+
@Dependent
123+
TaskAuthorizationProvider taskAuthorization(JpaTaskOwnershipRepository ownership) {
124+
return new JpaTaskAuthorizationProvider(ownership);
125+
}
126+
}
127+
```
128+
129+
Use the Jakarta CDI annotations and the JPA module's provider/repository types. Choose the producer or Quarkus alternative selection, avoiding ambiguous providers. The repository uses an intercepted JTA helper: insertion and duplicate confirmation each run in a separate `REQUIRES_NEW` transaction with a fresh persistence context. Confirmation starts after insertion rollback, so a stale repeatable-read caller cannot hide committed ownership or become rollback-only. Outside CDI, use `JpaTaskOwnershipRepository.create(entityManagerFactory, transactionManager)` and pass `new JpaTaskAuthorizationProvider(repository)` to `DefaultRequestHandler.builder().authorizationProvider(provider)`. The factory must be JTA-enabled for the same database/transaction manager. Do not directly instantiate the transaction helper.
130+
131+
Authenticate `ServerCallContext.getUser()` and supply a username unique across your identity domain. Multiple issuers or tenant-local names require stable namespaced keys or a custom policy. Anonymous users and unknown ownership are denied; recording is first-writer-wins across replicas. An owner row may precede its task, so there is no immediate task foreign key. A persisted task remains inaccessible until ownership is recorded. Store deletion removes ownership in the same transaction; direct database maintenance must clean up both tables. Replicas must share ownership storage.
132+
133+
With no provider, authorization is required by default. Only deliberate providerless deployments should set `a2a.authorization.required=false`. Configured providers remain authoritative with that setting. An explicitly configured allow-all provider may expose `JpaTaskReadScope.All`, including unowned tasks, if its individual checks agree.
134+
135+
A supported `JpaTaskAuthorizationCapability` restricts both database count and page queries. The exact authorized total excludes the cursor and is repeated on every page; the page query alone uses the cursor. The handler's list gate and final checks remain. Counts and pages follow configured database isolation, without an implied stronger snapshot guarantee.
136+
137+
Unsupported providers retain iterative checks in Java. Their exact count may fail at `a2a.max-scanned-tasks`; `a2a.authorization-scan-batch-size` controls fetch size. These limits do not apply to capability-based queries. Lookup or capability exceptions fail the request rather than switching policy. See [Task Authorization](../authorization.md) for capability contracts and [Configuration](../configuration.md) for fallback limits.
138+
80139
### Persistence Unit Name
81140

82141
The module uses the persistence unit name `"a2a-java"`. Ensure your `persistence.xml` defines a persistence unit with this name.
@@ -116,7 +175,7 @@ Create or update your `persistence.xml`:
116175
<exclude-unlisted-classes>true</exclude-unlisted-classes>
117176

118177
<properties>
119-
<property name="jakarta.persistence.schema-generation.database.action" value="create"/>
178+
<property name="jakarta.persistence.schema-generation.database.action" value="none"/>
120179
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
121180
</properties>
122181
</persistence-unit>
@@ -125,7 +184,7 @@ Create or update your `persistence.xml`:
125184

126185
### 3. Database Schema
127186

128-
The module automatically creates the required table with a composite primary key:
187+
When application schema generation is enabled, it creates a table with a composite primary key. Otherwise apply the corresponding migration:
129188

130189
```sql
131190
CREATE TABLE a2a_push_notification_configs (
@@ -149,15 +208,22 @@ When using both JPA stores, combine their entity classes in a single `persistenc
149208
<jta-data-source>java:jboss/datasources/A2ADataSource</jta-data-source>
150209

151210
<class>org.a2aproject.sdk.extras.taskstore.database.jpa.JpaTask</class>
211+
<class>org.a2aproject.sdk.extras.taskstore.database.jpa.JpaTaskOwner</class>
152212
<class>org.a2aproject.sdk.extras.pushnotificationconfigstore.database.jpa.JpaPushNotificationConfig</class>
153213
<exclude-unlisted-classes>true</exclude-unlisted-classes>
154214

155215
<properties>
156-
<property name="jakarta.persistence.schema-generation.database.action" value="create"/>
216+
<property name="jakarta.persistence.schema-generation.database.action" value="none"/>
157217
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
158218
</properties>
159219
</persistence-unit>
160220
</persistence>
161221
```
162222

163-
For Quarkus, no additional configuration is needed — both entities are discovered automatically.
223+
For Quarkus, include both store packages in the named persistence unit:
224+
225+
```properties
226+
quarkus.hibernate-orm."a2a-java".packages=org.a2aproject.sdk.extras.taskstore.database.jpa,org.a2aproject.sdk.extras.pushnotificationconfigstore.database.jpa
227+
```
228+
229+
This discovers `JpaTask`, `JpaTaskOwner` and `JpaPushNotificationConfig`. Schema generation remains an application choice; production upgrades require migrations.

0 commit comments

Comments
 (0)