Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: validate operation body #5537

Merged
merged 3 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { initSeed } from 'testkit/seed';
import { TargetAccessScope } from '../../testkit/gql/graphql';
import { getServiceHost } from '../../testkit/utils';

test('valid operation is accepted', async () => {
const { createOrg } = await initSeed().createOwner();
const { createProject } = await createOrg();
const { createToken } = await createProject();
const { secret: accessToken } = await createToken({
targetScopes: [TargetAccessScope.RegistryWrite, TargetAccessScope.RegistryRead],
});

const usageAddress = await getServiceHost('usage', 8081);

const response = await fetch(`http://${usageAddress}`, {
method: 'POST',
headers: {
'X-Usage-API-Version': '2',
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
size: 3,
map: {
c3b6d9b0: {
operationName: 'me',
operation: 'query me { me { id name } }',
fields: ['Query', 'Query.me', 'User', 'User.id', 'User.name'],
},
},
operations: [
{
operationMapKey: 'c3b6d9b0',
timestamp: 1663158676535,
execution: {
ok: true,
duration: 150000000,
errorsTotal: 0,
},
metadata: {
client: {
name: 'demo',
version: '0.0.1',
},
},
},
],
}),
});
expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({
id: expect.any(String),
operations: {
accepted: 1,
rejected: 0,
},
});
});

test('invalid operation is rejected', async () => {
const { createOrg } = await initSeed().createOwner();
const { createProject } = await createOrg();
const { createToken } = await createProject();
const { secret: accessToken } = await createToken({
targetScopes: [TargetAccessScope.RegistryWrite, TargetAccessScope.RegistryRead],
});

const usageAddress = await getServiceHost('usage', 8081);
// GraphQL operation is invalid at Query.me(id:)
const faultyOperation = 'query me { me(id: ) { id name } }';

const response = await fetch(`http://${usageAddress}`, {
method: 'POST',
headers: {
'X-Usage-API-Version': '2',
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
size: 3,
map: {
c3b6d9b0: {
operationName: 'me',
operation: faultyOperation,
fields: ['Query', 'Query.me', 'User', 'User.id', 'User.name'],
},
},
operations: [
{
operationMapKey: 'c3b6d9b0',
timestamp: 1663158676535,
execution: {
ok: true,
duration: 150000000,
errorsTotal: 0,
},
metadata: {
client: {
name: 'demo',
version: '0.0.1',
},
},
},
],
}),
});
expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({
id: expect.any(String),
operations: {
accepted: 0,
rejected: 1,
},
});
});
12 changes: 6 additions & 6 deletions packages/services/usage/src/usage-processor-1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,21 +269,21 @@ export function validateOperationMapRecord(record: OperationMapRecord) {
};
}

function isValidOperationBody(op: OperationMapRecord) {
const cached = validOperationBodyCache.get(op.operation);
export function isValidOperationBody(operation: string) {
const cached = validOperationBodyCache.get(operation);

if (typeof cached === 'boolean') {
return cached;
}

try {
parse(op.operation, {
parse(operation, {
noLocation: true,
});
validOperationBodyCache.set(op.operation, true);
validOperationBodyCache.set(operation, true);
return true;
} catch (error) {
validOperationBodyCache.set(op.operation, false);
validOperationBodyCache.set(operation, false);
return false;
}
}
Expand All @@ -304,7 +304,7 @@ export function validateOperation(operation: IncomingOperation, operationMap: Op
}

if (validate(operation)) {
if (!isValidOperationBody(operationMap[operation.operationMapKey])) {
if (!isValidOperationBody(operationMap[operation.operationMapKey].operation)) {
return {
valid: false,
errors: [
Expand Down
47 changes: 24 additions & 23 deletions packages/services/usage/src/usage-processor-2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as tb from '@sinclair/typebox';
import * as tc from '@sinclair/typebox/compiler';
import { invalidRawOperations, rawOperationsSize, totalOperations, totalReports } from './metrics';
import { TokensResponse } from './tokens';
import { isValidOperationBody } from './usage-processor-1';

export function usageProcessorV2(
logger: Logger,
Expand Down Expand Up @@ -74,15 +75,35 @@ export function usageProcessorV2(

const newKeyMappings = new Map<OperationMapRecord, string>();

function getOperationMapRecord(operationMapKey: string): string | null {
function getOperationMapRecordKey(operationMapKey: string): string | null {
const operationMapRecord = incoming.map[operationMapKey] as OperationMapRecord | undefined;

if (!operationMapRecord) {
logger.warn(
`Detected invalid operation. Operation map key could not be found. (target=%s): %s`,
token.target,
operationMapKey,
);
invalidRawOperations
.labels({
reason: 'operation_map_key_not_found',
})
.inc(1);
return null;
}

let newOperationMapKey = newKeyMappings.get(operationMapRecord);

if (!isValidOperationBody(operationMapRecord.operation)) {
logger.warn(`Detected invalid operation (target=%s): %s`, operationMapKey);
invalidRawOperations
.labels({
reason: 'invalid_operation_body',
})
.inc(1);
return null;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we could do what we do in usage-1, return to the sender that N operations were accepted and M operations rejected?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kamilkisiela we already do, see tests: 7b01304 (#5537)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed the incorrect information in d9a3e56 (#5537)

}

if (newOperationMapKey === undefined) {
const sortedFields = operationMapRecord.fields.sort();
newOperationMapKey = createHash('md5')
Expand All @@ -106,20 +127,10 @@ export function usageProcessorV2(
}

for (const operation of incomingOperations) {
const operationMapKey = getOperationMapRecord(operation.operationMapKey);
const operationMapKey = getOperationMapRecordKey(operation.operationMapKey);

// if the record does not exist -> skip the operation
if (operationMapKey === null) {
logger.warn(
`Detected invalid operation. Operation map key could not be found. (target=%s): %s`,
token.target,
operation.operationMapKey,
);
invalidRawOperations
.labels({
reason: 'operation_map_key_not_found',
})
.inc(1);
continue;
}

Expand Down Expand Up @@ -154,20 +165,10 @@ export function usageProcessorV2(
}

for (const operation of incomingSubscriptionOperations) {
const operationMapKey = getOperationMapRecord(operation.operationMapKey);
const operationMapKey = getOperationMapRecordKey(operation.operationMapKey);

// if the record does not exist -> skip the operation
if (operationMapKey === null) {
logger.warn(
`Detected invalid operation. Operation map key could not be found. (target=%s): %s`,
token.target,
operation.operationMapKey,
);
invalidRawOperations
.labels({
reason: 'operation_map_key_not_found',
})
.inc(1);
continue;
}

Expand Down
Loading