Skip to content

Commit

Permalink
feat: implement openapi security inferrence and override (zenstackhq#341
Browse files Browse the repository at this point in the history
)
  • Loading branch information
ymc9 authored Apr 11, 2023
1 parent d996d09 commit 2860f00
Show file tree
Hide file tree
Showing 11 changed files with 185 additions and 108 deletions.
31 changes: 28 additions & 3 deletions packages/plugins/openapi/src/generator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
// Inspired by: https://github.com/omar-dulaimi/prisma-trpc-generator

import { DMMF } from '@prisma/generator-helper';
import { AUXILIARY_FIELDS, getDataModels, hasAttribute, PluginError, PluginOptions } from '@zenstackhq/sdk';
import {
analyzePolicies,
AUXILIARY_FIELDS,
getDataModels,
hasAttribute,
PluginError,
PluginOptions,
} from '@zenstackhq/sdk';
import { DataModel, isDataModel, type Model } from '@zenstackhq/sdk/ast';
import {
addMissingInputObjectTypesForAggregate,
Expand Down Expand Up @@ -201,11 +208,15 @@ export class OpenAPIGenerator {
inputType?: object;
outputType: object;
successCode?: number;
security?: Array<Record<string, string[]>>;
};

const definitions: OperationDefinition[] = [];
const hasRelation = zmodel.fields.some((f) => isDataModel(f.type.reference?.ref));

// analyze access policies to determine default security
const { create, read, update, delete: del } = analyzePolicies(zmodel);

if (ops['createOne']) {
definitions.push({
method: 'post',
Expand All @@ -225,6 +236,7 @@ export class OpenAPIGenerator {
outputType: this.ref(model.name),
description: `Create a new ${model.name}`,
successCode: 201,
security: create === true ? [] : undefined,
});
}

Expand All @@ -245,6 +257,7 @@ export class OpenAPIGenerator {
outputType: this.ref('BatchPayload'),
description: `Create several ${model.name}`,
successCode: 201,
security: create === true ? [] : undefined,
});
}

Expand All @@ -266,6 +279,7 @@ export class OpenAPIGenerator {
),
outputType: this.ref(model.name),
description: `Find one unique ${model.name}`,
security: read === true ? [] : undefined,
});
}

Expand All @@ -287,6 +301,7 @@ export class OpenAPIGenerator {
),
outputType: this.ref(model.name),
description: `Find the first ${model.name} matching the given condition`,
security: read === true ? [] : undefined,
});
}

Expand All @@ -308,6 +323,7 @@ export class OpenAPIGenerator {
),
outputType: this.array(this.ref(model.name)),
description: `Find a list of ${model.name}`,
security: read === true ? [] : undefined,
});
}

Expand All @@ -330,6 +346,7 @@ export class OpenAPIGenerator {
),
outputType: this.ref(model.name),
description: `Update a ${model.name}`,
security: update === true ? [] : undefined,
});
}

Expand All @@ -350,6 +367,7 @@ export class OpenAPIGenerator {
),
outputType: this.ref('BatchPayload'),
description: `Update ${model.name}s matching the given condition`,
security: update === true ? [] : undefined,
});
}

Expand All @@ -373,6 +391,7 @@ export class OpenAPIGenerator {
),
outputType: this.ref(model.name),
description: `Upsert a ${model.name}`,
security: create === true && update == true ? [] : undefined,
});
}

Expand All @@ -394,6 +413,7 @@ export class OpenAPIGenerator {
),
outputType: this.ref(model.name),
description: `Delete one unique ${model.name}`,
security: del === true ? [] : undefined,
});
}

Expand All @@ -413,6 +433,7 @@ export class OpenAPIGenerator {
),
outputType: this.ref('BatchPayload'),
description: `Delete ${model.name}s matching the given condition`,
security: del === true ? [] : undefined,
});
}

Expand All @@ -433,6 +454,7 @@ export class OpenAPIGenerator {
),
outputType: this.oneOf({ type: 'integer' }, this.ref(`${model.name}CountAggregateOutputType`)),
description: `Find a list of ${model.name}`,
security: read === true ? [] : undefined,
});

if (ops['aggregate']) {
Expand All @@ -456,6 +478,7 @@ export class OpenAPIGenerator {
),
outputType: this.ref(`Aggregate${model.name}`),
description: `Aggregate ${model.name}s`,
security: read === true ? [] : undefined,
});
}

Expand All @@ -481,13 +504,14 @@ export class OpenAPIGenerator {
),
outputType: this.array(this.ref(`${model.name}GroupByOutputType`)),
description: `Group ${model.name}s by fields`,
security: read === true ? [] : undefined,
});
}

// get meta specified with @@openapi.meta
const resourceMeta = getModelResourceMeta(zmodel);

for (const { method, operation, description, inputType, outputType, successCode } of definitions) {
for (const { method, operation, description, inputType, outputType, successCode, security } of definitions) {
const meta = resourceMeta?.[operation];

if (meta?.ignore === true) {
Expand All @@ -511,7 +535,8 @@ export class OpenAPIGenerator {
description: meta?.description ?? description,
tags: meta?.tags || [camelCase(model.name)],
summary: meta?.summary,
security: meta?.security,
// security priority: operation-level > model-level > inferred
security: meta?.security ?? resourceMeta?.security ?? security,
deprecated: meta?.deprecated,
responses: {
[successCode !== undefined ? successCode : '200']: {
Expand Down
1 change: 1 addition & 0 deletions packages/plugins/openapi/src/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { DataModel } from '@zenstackhq/sdk/ast';
*/
export type ModelMeta = {
tagDescription?: string;
security?: Array<Record<string, string[]>>;
};

/**
Expand Down
66 changes: 63 additions & 3 deletions packages/plugins/openapi/tests/openapi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,18 +196,52 @@ model User {
);
});

it('security override', async () => {
it('security model level override', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${process.cwd()}/dist'
securitySchemes = {
myBasic: { type: 'http', scheme: 'basic' }
}
}
model User {
id String @id
@@openapi.meta({
security: []
})
}
`);

const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);

console.log('OpenAPI specification generated:', output);

const api = await OpenAPIParser.validate(output);
expect(api.paths?.['/user/findMany']?.['get']?.security).toHaveLength(0);
});

it('security operation level override', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${process.cwd()}/dist'
securitySchemes = {
myBasic: { type: 'http', scheme: 'basic' }
}
}
model User {
id String @id
@@allow('read', true)
@@openapi.meta({
security: [],
findMany: {
security: []
security: [{ myBasic: [] }]
}
})
}
Expand All @@ -220,7 +254,33 @@ model User {
console.log('OpenAPI specification generated:', output);

const api = await OpenAPIParser.validate(output);
expect(api.paths?.['/user/findMany']?.['get']?.security).toHaveLength(0);
expect(api.paths?.['/user/findMany']?.['get']?.security).toHaveLength(1);
});

it('security inferred', async () => {
const { model, dmmf, modelFile } = await loadZModelAndDmmf(`
plugin openapi {
provider = '${process.cwd()}/dist'
securitySchemes = {
myBasic: { type: 'http', scheme: 'basic' }
}
}
model User {
id String @id
@@allow('create', true)
}
`);

const { name: output } = tmp.fileSync({ postfix: '.yaml' });
const options = buildOptions(model, modelFile, output);
await generate(model, options, dmmf);

console.log('OpenAPI specification generated:', output);

const api = await OpenAPIParser.validate(output);
expect(api.paths?.['/user/create']?.['post']?.security).toHaveLength(0);
expect(api.paths?.['/user/findMany']?.['get']?.security).toBeUndefined();
});

it('v3.1.0 fields', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import {
isLiteralExpr,
ReferenceExpr,
} from '@zenstackhq/language/ast';
import { analyzePolicies, getLiteral } from '@zenstackhq/sdk';
import { ValidationAcceptor } from 'langium';
import { analyzePolicies } from '../../utils/ast-utils';
import { IssueCodes, SCALAR_TYPES } from '../constants';
import { AstValidator } from '../types';
import { getIdFields, getUniqueFields } from '../utils';
import { validateAttributeApplication, validateDuplicatedDeclarations } from './utils';
import { getLiteral } from '@zenstackhq/sdk';

/**
* Validates data model declarations.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from '@zenstackhq/language/ast';
import type { PolicyKind, PolicyOperationKind } from '@zenstackhq/runtime';
import {
analyzePolicies,
getDataModels,
getLiteral,
GUARD_FIELD_NAME,
Expand All @@ -29,7 +30,7 @@ import path from 'path';
import { FunctionDeclaration, Project, SourceFile, VariableDeclarationKind } from 'ts-morph';
import { name } from '.';
import { isFromStdlib } from '../../language-server/utils';
import { analyzePolicies, getIdFields } from '../../utils/ast-utils';
import { getIdFields } from '../../utils/ast-utils';
import { ALL_OPERATION_KINDS, getDefaultOutputFolder } from '../plugin-utils';
import { ExpressionWriter } from './expression-writer';
import { isFutureExpr } from './utils';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { DataModel, DataModelField, DataModelFieldAttribute, isDataModelField } from '@zenstackhq/language/ast';
import { AUXILIARY_FIELDS, getLiteral } from '@zenstackhq/sdk';
import { AUXILIARY_FIELDS, VALIDATION_ATTRIBUTES, getLiteral } from '@zenstackhq/sdk';
import { camelCase } from 'change-case';
import { CodeBlockWriter } from 'ts-morph';
import { VALIDATION_ATTRIBUTES } from '../../utils/ast-utils';

/**
* Writes Zod schema for data models.
Expand Down
10 changes: 5 additions & 5 deletions packages/schema/src/plugins/prisma/schema-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
Model,
} from '@zenstackhq/language/ast';
import {
analyzePolicies,
getLiteral,
getLiteralArray,
GUARD_FIELD_NAME,
Expand All @@ -31,24 +32,23 @@ import {
import fs from 'fs';
import { writeFile } from 'fs/promises';
import path from 'path';
import { analyzePolicies } from '../../utils/ast-utils';
import { execSync } from '../../utils/exec-utils';
import {
ModelFieldType,
AttributeArg as PrismaAttributeArg,
AttributeArgValue as PrismaAttributeArgValue,
ContainerAttribute as PrismaModelAttribute,
ContainerDeclaration as PrismaContainerDeclaration,
Model as PrismaDataModel,
DataSourceUrl as PrismaDataSourceUrl,
Enum as PrismaEnum,
FieldAttribute as PrismaFieldAttribute,
FieldReference as PrismaFieldReference,
FieldReferenceArg as PrismaFieldReferenceArg,
FunctionCall as PrismaFunctionCall,
FunctionCallArg as PrismaFunctionCallArg,
Model as PrismaDataModel,
ModelFieldType,
PassThroughAttribute as PrismaPassThroughAttribute,
PrismaModel,
ContainerAttribute as PrismaModelAttribute,
PassThroughAttribute as PrismaPassThroughAttribute,
SimpleField,
} from './prisma-builder';
import ZModelCodeGenerator from './zmodel-code-generator';
Expand Down
Loading

0 comments on commit 2860f00

Please sign in to comment.