Skip to content

Commit bc4e979

Browse files
Fix protected-field leaks in SQL pagination cursors (#3898)
## Why make this change? SQL pagination cursors can expose excluded primary-key values as Base64 JSON, bypassing field-level read permissions across REST, GraphQL, and MCP. ## What is this change? - Check read permissions for every cursor field, including implicit/composite keys and sort fields. - Reject unauthorized cursor generation; MCP returns `PermissionDenied`. - Preserve reads without cursors and pagination using readable fields omitted only from the projection. - Add regression tests and document the behavior change. Cursor encoding is unchanged. ## How was this tested? - [ ] Integration Tests - [x] Unit Tests **Passed:** 105 focused tests and affected-project builds on the new main-based branch: ```powershell dotnet test src\Service.Tests\Azure.DataApiBuilder.Service.Tests.csproj --no-restore -p:BaseOutputPath=C:\Users\sogh\.copilot\session-state\8f3619d8-cd04-4773-ab2d-a3a849d89683\files\cursor-validation\ --filter "FullyQualifiedName~SqlPaginationUtilUnitTests|FullyQualifiedName~SqlResponseHelpersUnitTests|FullyQualifiedName~SqlQueryStructureHelperTests|FullyQualifiedName~RestServiceUnitTests|FullyQualifiedName~MultiSourceQueryExecutionUnitTests" --verbosity minimal ``` **Passed:** Formatting verification for modified C# files before committing: ```powershell $changedCs = @(git --no-pager diff --name-only -- '*.cs') dotnet format whitespace src\Azure.DataApiBuilder.sln --no-restore --include $changedCs --verify-no-changes --verbosity quiet ``` **Not run:** Database integration tests, the full suite, or hosted-service reproduction. ## Sample Request(s) ```http GET /api/PublicRecords?$first=1&$select=PublicLabel ``` If pagination requires an excluded `OwnerToken` key, return an authorization error instead of a cursor exposing its value. Equivalent checks apply to MCP `read_records` and GraphQL `endCursor`. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent e92b02e commit bc4e979

12 files changed

Lines changed: 349 additions & 20 deletions

File tree

‎docs/readme.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,19 @@
33
All documentation has now been moved [here](https://learn.microsoft.com/azure/data-api-builder/)
44

55
The process for updating Data API builder documentation on Learn is available [here](https://learn.microsoft.com/contribute/)
6+
7+
## SQL pagination and field permissions
8+
9+
SQL-backed REST, GraphQL, and MCP pagination cursors contain sort-field and primary-key
10+
values, including composite-key tie breakers. Base64 encoding is not encryption.
11+
Every field included in a cursor must be readable by the caller's effective role,
12+
even when it was not selected in the request.
13+
14+
If a response would emit a cursor containing a field the role cannot read, the
15+
request fails with an authorization error instead of returning that cursor.
16+
Reads that do not emit a cursor are unaffected. Omitting a permitted field from
17+
the requested projection does not prevent pagination.
18+
19+
To retain pagination without exposing confidential keys, use an entity or database
20+
view with a non-sensitive unique key that the role is allowed to read. Do not grant
21+
read access to a confidential key solely to enable pagination.

‎src/Azure.DataApiBuilder.Mcp/BuiltInTools/ReadRecordsTool.cs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -263,8 +263,8 @@ public async Task<CallToolResult> ExecuteAsync(
263263
JsonDocument? queryResult = await queryEngine.ExecuteAsync(context);
264264
IMetadataProviderFactory metadataProviderFactory = serviceProvider.GetRequiredService<IMetadataProviderFactory>();
265265
IActionResult actionResult = queryResult is null
266-
? SqlResponseHelpers.FormatFindResult(JsonDocument.Parse("[]").RootElement.Clone(), context, sqlMetadataProvider, runtimeConfig, httpContext, true)
267-
: SqlResponseHelpers.FormatFindResult(queryResult.RootElement.Clone(), context, sqlMetadataProvider, runtimeConfig, httpContext, true);
266+
? SqlResponseHelpers.FormatFindResult(JsonDocument.Parse("[]").RootElement.Clone(), context, sqlMetadataProvider, runtimeConfig, httpContext, authResolver, true)
267+
: SqlResponseHelpers.FormatFindResult(queryResult.RootElement.Clone(), context, sqlMetadataProvider, runtimeConfig, httpContext, authResolver, true);
268268

269269
// Normalize response
270270
string rawPayloadJson = McpResponseBuilder.ExtractResultJson(actionResult);
@@ -293,6 +293,10 @@ public async Task<CallToolResult> ExecuteAsync(
293293
{
294294
return McpResponseBuilder.BuildErrorResult(toolName, "InvalidArguments", argEx.Message, logger);
295295
}
296+
catch (DataApiBuilderException argEx) when (argEx.SubStatusCode == DataApiBuilderException.SubStatusCodes.AuthorizationCheckFailed)
297+
{
298+
return McpResponseBuilder.BuildErrorResult(toolName, "PermissionDenied", argEx.Message, logger);
299+
}
296300
catch (DataApiBuilderException argEx)
297301
{
298302
return McpResponseBuilder.BuildErrorResult(toolName, argEx.StatusCode.ToString(), argEx.Message, logger);

‎src/Config/DataApiBuilderException.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ public class DataApiBuilderException : Exception
1919
public const string AUTHORIZATION_FAILURE = "Authorization Failure: Access Not Allowed.";
2020
public const string GRAPHQL_MUTATION_FIELD_AUTHZ_FAILURE = "Unauthorized due to one or more fields in this mutation.";
2121
public const string GRAPHQL_ORDERBY_FIELD_AUTHZ_FAILURE = "Access forbidden to a field referenced in the orderBy argument.";
22+
public const string PAGINATION_FIELD_AUTHZ_FAILURE = "Access forbidden to a field required for pagination.";
2223
public const string GRAPHQL_GROUPBY_FIELD_AUTHZ_FAILURE = "Access forbidden to field '{0}' referenced in the groupBy argument.";
2324
public const string GRAPHQL_AGGREGATION_FIELD_AUTHZ_FAILURE = "Access forbidden to field '{0}' referenced in the aggregation function '{1}'.";
2425
public const string OBO_IDENTITY_CLAIMS_MISSING = "User-delegated authentication failed: Neither 'oid' nor 'sub' claim found in the access token.";

‎src/Core/Resolvers/Sql Query Structures/SqlQueryStructure.cs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System.Data;
55
using System.Net;
6+
using System.Text.Json;
67
using Azure.DataApiBuilder.Auth;
78
using Azure.DataApiBuilder.Config.ObjectModel;
89
using Azure.DataApiBuilder.Core.Configurations;
@@ -1120,6 +1121,26 @@ private void ProcessAggregations(FieldNode aggregationsField, IMiddlewareContext
11201121
}
11211122
}
11221123

1124+
internal string CreatePaginationCursor(JsonElement element, bool isGroupByQuery)
1125+
{
1126+
if (_ctx is null)
1127+
{
1128+
throw new InvalidOperationException("GraphQL context is required to authorize a pagination cursor.");
1129+
}
1130+
1131+
return SqlPaginationUtil.MakeCursorFromJsonElement(
1132+
element,
1133+
PrimaryKey(),
1134+
OrderByColumns,
1135+
AuthorizationResolver,
1136+
Authorization.AuthorizationResolver.GetRoleOfGraphQLRequest(_ctx),
1137+
EntityName,
1138+
DatabaseObject.SchemaName,
1139+
DatabaseObject.Name,
1140+
MetadataProvider,
1141+
isGroupByQuery);
1142+
}
1143+
11231144
/// <summary>
11241145
/// Create a list of orderBy columns from the orderBy argument
11251146
/// passed to the gql query. The orderBy argument could contain mapped field names

‎src/Core/Resolvers/SqlPaginationUtil.cs‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
using System.Text.Json;
77
using System.Text.Json.Nodes;
88
using System.Text.Json.Serialization;
9+
using Azure.DataApiBuilder.Auth;
10+
using Azure.DataApiBuilder.Config.ObjectModel;
911
using Azure.DataApiBuilder.Core.Configurations;
1012
using Azure.DataApiBuilder.Core.Models;
1113
using Azure.DataApiBuilder.Core.Parsers;
@@ -155,15 +157,7 @@ private static JsonObject CreatePaginationConnection(JsonElement root, Paginatio
155157
{
156158
JsonElement lastElemInRoot = rootEnumerated.ElementAtOrDefault(returnedElementCount - 1);
157159
connection.Add(QueryBuilder.PAGINATION_TOKEN_FIELD_NAME,
158-
MakeCursorFromJsonElement(
159-
lastElemInRoot,
160-
paginationMetadata.Structure!.PrimaryKey(),
161-
paginationMetadata.Structure!.OrderByColumns,
162-
paginationMetadata.Structure!.EntityName,
163-
paginationMetadata.Structure!.DatabaseObject.SchemaName,
164-
paginationMetadata.Structure!.DatabaseObject.Name,
165-
paginationMetadata.Structure!.MetadataProvider,
166-
paginationMetadata.RequestedGroupBy));
160+
paginationMetadata.Structure!.CreatePaginationCursor(lastElemInRoot, paginationMetadata.RequestedGroupBy));
167161
}
168162
}
169163

@@ -203,19 +197,36 @@ public NextLinkField(
203197

204198
/// <summary>
205199
/// Extracts the columns from the JsonElement needed for pagination, represents them as a string in json format and base64 encodes.
206-
/// The JSON is encoded in base64 for opaqueness. The cursor should function as a token that the user copies and pastes
207-
/// without needing to understand how it works.
200+
/// Base64 encoding does not provide confidentiality, so every cursor field must be readable by the caller.
208201
/// </summary>
209202
public static string MakeCursorFromJsonElement(
210203
JsonElement element,
211204
List<string> primaryKey,
212205
List<OrderByColumn>? orderByColumns,
206+
IAuthorizationResolver authorizationResolver,
207+
string roleName,
213208
string entityName = "",
214209
string schemaName = "",
215210
string tableName = "",
216211
ISqlMetadataProvider? sqlMetadataProvider = null,
217212
bool isGroupByQuery = false)
218213
{
214+
IEnumerable<string> cursorColumns = orderByColumns?.Select(column => column.ColumnName) ?? Enumerable.Empty<string>();
215+
if (!isGroupByQuery)
216+
{
217+
cursorColumns = cursorColumns.Concat(primaryKey);
218+
}
219+
220+
IEnumerable<string> exposedCursorColumns = cursorColumns.Distinct()
221+
.Select(column => GetExposedColumnName(entityName, column, sqlMetadataProvider));
222+
if (!authorizationResolver.AreColumnsAllowedForOperation(entityName, roleName, EntityActionOperation.Read, exposedCursorColumns))
223+
{
224+
throw new DataApiBuilderException(
225+
message: DataApiBuilderException.PAGINATION_FIELD_AUTHZ_FAILURE,
226+
statusCode: HttpStatusCode.Forbidden,
227+
subStatusCode: DataApiBuilderException.SubStatusCodes.AuthorizationCheckFailed);
228+
}
229+
219230
List<NextLinkField> cursorJson = new();
220231
JsonSerializerOptions options = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull };
221232
// Hash set is used here to maintain linear runtime

‎src/Core/Resolvers/SqlResponseHelpers.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
using System.Text;
55
using System.Text.Json;
66
using System.Text.Json.Nodes;
7+
using Azure.DataApiBuilder.Auth;
78
using Azure.DataApiBuilder.Config.DatabasePrimitives;
89
using Azure.DataApiBuilder.Config.ObjectModel;
10+
using Azure.DataApiBuilder.Core.Authorization;
911
using Azure.DataApiBuilder.Core.Models;
1012
using Azure.DataApiBuilder.Core.Services;
1113
using Azure.DataApiBuilder.Service.Exceptions;
@@ -31,6 +33,7 @@ public class SqlResponseHelpers
3133
/// <param name="sqlMetadataProvider">The metadataprovider.</param>
3234
/// <param name="runtimeConfig">Runtimeconfig object</param>
3335
/// <param name="httpContext">HTTP context associated with the API request</param>
36+
/// <param name="authorizationResolver">Resolver used to authorize all fields included in pagination cursors.</param>
3437
/// <param name="isMcpRequest"><c>true</c> if invoked from the MCP endpoint (emit <c>after</c>); <c>false</c> or <c>null</c> for REST (emit <c>nextLink</c>).</param>
3538
/// <returns>An OkObjectResult from a Find operation that has been correctly formatted.</returns>
3639
public static OkObjectResult FormatFindResult(
@@ -39,6 +42,7 @@ public static OkObjectResult FormatFindResult(
3942
ISqlMetadataProvider sqlMetadataProvider,
4043
RuntimeConfig runtimeConfig,
4144
HttpContext httpContext,
45+
IAuthorizationResolver authorizationResolver,
4246
bool? isMcpRequest = null)
4347
{
4448
// Empty result set: return the standard envelope { "value": [] } and skip extra-field/cursor work.
@@ -85,6 +89,8 @@ public static OkObjectResult FormatFindResult(
8589
element: rows[rows.Count - 1],
8690
orderByColumns: context.OrderByClauseOfBackingColumns,
8791
primaryKey: sqlMetadataProvider.GetSourceDefinition(context.EntityName).PrimaryKey,
92+
authorizationResolver: authorizationResolver,
93+
roleName: httpContext.Request.Headers[AuthorizationResolver.CLIENT_ROLE_HEADER].ToString(),
8894
entityName: context.EntityName,
8995
schemaName: context.DatabaseObject.SchemaName,
9096
tableName: context.DatabaseObject.Name,

‎src/Core/Services/RestService.cs‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Net;
66
using System.Text.Json;
77
using System.Web;
8+
using Azure.DataApiBuilder.Auth;
89
using Azure.DataApiBuilder.Config.DatabasePrimitives;
910
using Azure.DataApiBuilder.Config.ObjectModel;
1011
using Azure.DataApiBuilder.Core.Authorization;
@@ -30,6 +31,7 @@ public class RestService
3031
private readonly IMutationEngineFactory _mutationEngineFactory;
3132
private readonly IHttpContextAccessor _httpContextAccessor;
3233
private readonly IAuthorizationService _authorizationService;
34+
private readonly IAuthorizationResolver _authorizationResolver;
3335
private readonly IMetadataProviderFactory _sqlMetadataProviderFactory;
3436
private readonly RuntimeConfigProvider _runtimeConfigProvider;
3537
private readonly RequestValidator _requestValidator;
@@ -41,13 +43,15 @@ public RestService(
4143
IHttpContextAccessor httpContextAccessor,
4244
IAuthorizationService authorizationService,
4345
RuntimeConfigProvider runtimeConfigProvider,
44-
RequestValidator requestValidator
46+
RequestValidator requestValidator,
47+
IAuthorizationResolver authorizationResolver
4548
)
4649
{
4750
_queryEngineFactory = queryEngineFactory;
4851
_mutationEngineFactory = mutationEngineFactory;
4952
_httpContextAccessor = httpContextAccessor;
5053
_authorizationService = authorizationService;
54+
_authorizationResolver = authorizationResolver;
5155
_sqlMetadataProviderFactory = sqlMetadataProviderFactory;
5256
_runtimeConfigProvider = runtimeConfigProvider;
5357
_requestValidator = requestValidator;
@@ -236,8 +240,8 @@ private async Task<IActionResult> DispatchQuery(RestRequestContext context, Data
236240
if (context is FindRequestContext findRequestContext)
237241
{
238242
using JsonDocument? restApiResponse = await queryEngine.ExecuteAsync(findRequestContext);
239-
return restApiResponse is null ? SqlResponseHelpers.FormatFindResult(JsonDocument.Parse("[]").RootElement.Clone(), findRequestContext, _sqlMetadataProviderFactory.GetMetadataProvider(dataSourceName), _runtimeConfigProvider.GetConfig(), GetHttpContext())
240-
: SqlResponseHelpers.FormatFindResult(restApiResponse.RootElement.Clone(), findRequestContext, _sqlMetadataProviderFactory.GetMetadataProvider(dataSourceName), _runtimeConfigProvider.GetConfig(), GetHttpContext());
243+
return restApiResponse is null ? SqlResponseHelpers.FormatFindResult(JsonDocument.Parse("[]").RootElement.Clone(), findRequestContext, _sqlMetadataProviderFactory.GetMetadataProvider(dataSourceName), _runtimeConfigProvider.GetConfig(), GetHttpContext(), _authorizationResolver)
244+
: SqlResponseHelpers.FormatFindResult(restApiResponse.RootElement.Clone(), findRequestContext, _sqlMetadataProviderFactory.GetMetadataProvider(dataSourceName), _runtimeConfigProvider.GetConfig(), GetHttpContext(), _authorizationResolver);
241245
}
242246
else if (context is StoredProcedureRequestContext storedProcedureRequestContext)
243247
{

‎src/Service.Tests/UnitTests/MultiSourceQueryExecutionUnitTests.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,8 @@ public async Task TestMultiSourceQueryRest()
210210
httpContextAccessor.Object,
211211
authorizationService.Object,
212212
provider,
213-
requestValidator);
213+
requestValidator,
214+
authorizationResolver);
214215

215216
// client is mapped as belonging to the sql data source.
216217
// customer is mapped as belonging to the cosmos data source.

‎src/Service.Tests/UnitTests/RestServiceUnitTests.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Collections.Generic;
55
using System.IO.Abstractions.TestingHelpers;
66
using System.Net;
7+
using Azure.DataApiBuilder.Auth;
78
using Azure.DataApiBuilder.Config;
89
using Azure.DataApiBuilder.Config.ObjectModel;
910
using Azure.DataApiBuilder.Core.Authorization;
@@ -344,7 +345,8 @@ private static void InitializeTestWithEntityPaths(string restRoutePrefix, Dictio
344345
httpContextAccessor.Object,
345346
authorizationService.Object,
346347
provider,
347-
requestValidator);
348+
requestValidator,
349+
Mock.Of<IAuthorizationResolver>());
348350
}
349351

350352
/// <summary>

0 commit comments

Comments
 (0)