Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
10 changes: 9 additions & 1 deletion packages/runtime/src/client/client-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,14 @@ export class ClientImpl<Schema extends SchemaDef> {
return this.auth;
}

$setInputValidation(enable: boolean) {
const newOptions: ClientOptions<Schema> = {
...this.options,
validateInput: enable,
};
return new ClientImpl<Schema>(this.schema, newOptions, this);
}

$executeRaw(query: TemplateStringsArray, ...values: any[]) {
return createZenStackPromise(async () => {
const result = await sql(query, ...values).execute(this.kysely);
Expand Down Expand Up @@ -325,7 +333,7 @@ export class ClientImpl<Schema extends SchemaDef> {
}

function createClientProxy<Schema extends SchemaDef>(client: ClientImpl<Schema>): ClientImpl<Schema> {
const inputValidator = new InputValidator(client.$schema);
const inputValidator = new InputValidator(client as unknown as ClientContract<Schema>);
const resultProcessor = new ResultProcessor(client.$schema, client.$options);

return new Proxy(client, {
Expand Down
6 changes: 6 additions & 0 deletions packages/runtime/src/client/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ export type ClientContract<Schema extends SchemaDef> = {
*/
$setAuth(auth: AuthType<Schema> | undefined): ClientContract<Schema>;

/**
* Returns a new client enabling/disabling input validations expressed with attributes like
* `@email`, `@regex`, `@@validate`, etc.
*/
$setInputValidation(enable: boolean): ClientContract<Schema>;

/**
* The Kysely query builder instance.
*/
Expand Down
65 changes: 48 additions & 17 deletions packages/runtime/src/client/crud/validator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { enumerate } from '../../../utils/enumerate';
import { extractFields } from '../../../utils/object-utils';
import { formatError } from '../../../utils/zod-utils';
import { AGGREGATE_OPERATORS, LOGICAL_COMBINATORS, NUMERIC_FIELD_TYPES } from '../../constants';
import type { ClientContract } from '../../contract';
import {
type AggregateArgs,
type CountArgs,
Expand Down Expand Up @@ -53,7 +54,15 @@ type GetSchemaFunc<Schema extends SchemaDef, Options> = (model: GetModels<Schema
export class InputValidator<Schema extends SchemaDef> {
private schemaCache = new Map<string, ZodType>();

constructor(private readonly schema: Schema) {}
constructor(private readonly client: ClientContract<Schema>) {}

private get schema() {
return this.client.$schema;
}

private get extraValidationsEnabled() {
return this.client.$options.validateInput !== false;
}

validateFindArgs(model: GetModels<Schema>, args: unknown, options: { unique: boolean; findOne: boolean }) {
return this.validate<
Expand Down Expand Up @@ -251,23 +260,37 @@ export class InputValidator<Schema extends SchemaDef> {
return this.makeTypeDefSchema(type);
} else {
return match(type)
.with('String', () => addStringValidation(z.string(), attributes))
.with('Int', () => addNumberValidation(z.number().int(), attributes))
.with('Float', () => addNumberValidation(z.number(), attributes))
.with('String', () =>
this.extraValidationsEnabled ? addStringValidation(z.string(), attributes) : z.string(),
)
.with('Int', () =>
this.extraValidationsEnabled ? addNumberValidation(z.number().int(), attributes) : z.number().int(),
)
.with('Float', () =>
this.extraValidationsEnabled ? addNumberValidation(z.number(), attributes) : z.number(),
)
.with('Boolean', () => z.boolean())
.with('BigInt', () =>
z.union([
addNumberValidation(z.number().int(), attributes),
addBigIntValidation(z.bigint(), attributes),
]),
)
.with('Decimal', () =>
z.union([
addNumberValidation(z.number(), attributes),
addDecimalValidation(z.instanceof(Decimal), attributes),
addDecimalValidation(z.string(), attributes),
this.extraValidationsEnabled
? addNumberValidation(z.number().int(), attributes)
: z.number().int(),
this.extraValidationsEnabled ? addBigIntValidation(z.bigint(), attributes) : z.bigint(),
]),
)
.with('Decimal', () => {
const options: [z.ZodSchema, z.ZodSchema, ...z.ZodSchema[]] = [
z.number(),
z.instanceof(Decimal),
z.string(),
];
if (this.extraValidationsEnabled) {
for (let i = 0; i < options.length; i++) {
options[i] = addDecimalValidation(options[i]!, attributes);
}
}
return z.union(options);
})
.with('DateTime', () => z.union([z.date(), z.string().datetime()]))
.with('Bytes', () => z.instanceof(Uint8Array))
.otherwise(() => z.unknown());
Expand Down Expand Up @@ -913,8 +936,12 @@ export class InputValidator<Schema extends SchemaDef> {
}
});

const uncheckedCreateSchema = addCustomValidation(z.strictObject(uncheckedVariantFields), modelDef.attributes);
const checkedCreateSchema = addCustomValidation(z.strictObject(checkedVariantFields), modelDef.attributes);
const uncheckedCreateSchema = this.extraValidationsEnabled
? addCustomValidation(z.strictObject(uncheckedVariantFields), modelDef.attributes)
: z.strictObject(uncheckedVariantFields);
const checkedCreateSchema = this.extraValidationsEnabled
? addCustomValidation(z.strictObject(checkedVariantFields), modelDef.attributes)
: z.strictObject(checkedVariantFields);

if (!hasRelation) {
return this.orArray(uncheckedCreateSchema, canBeArray);
Expand Down Expand Up @@ -1193,8 +1220,12 @@ export class InputValidator<Schema extends SchemaDef> {
}
});

const uncheckedUpdateSchema = addCustomValidation(z.strictObject(uncheckedVariantFields), modelDef.attributes);
const checkedUpdateSchema = addCustomValidation(z.strictObject(checkedVariantFields), modelDef.attributes);
const uncheckedUpdateSchema = this.extraValidationsEnabled
? addCustomValidation(z.strictObject(uncheckedVariantFields), modelDef.attributes)
: z.strictObject(uncheckedVariantFields);
const checkedUpdateSchema = this.extraValidationsEnabled
? addCustomValidation(z.strictObject(checkedVariantFields), modelDef.attributes)
: z.strictObject(checkedVariantFields);
if (!hasRelation) {
return uncheckedUpdateSchema;
} else {
Expand Down
6 changes: 6 additions & 0 deletions packages/runtime/src/client/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ export type ClientOptions<Schema extends SchemaDef> = {
* @see https://github.com/brianc/node-postgres/issues/429
*/
fixPostgresTimezone?: boolean;

/**
* Whether to enable input validations expressed with attributes like `@email`, `@regex`,
* `@@validate`, etc. Defaults to `true`.
*/
validateInput?: boolean;
} & (HasComputedFields<Schema> extends true
? {
/**
Expand Down
62 changes: 62 additions & 0 deletions tests/e2e/orm/validation/custom-validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,66 @@ describe('Custom validation tests', () => {
).toResolveTruthy();
}
});

it('allows disabling validation', async () => {
const db = await createTestClient(
`
model User {
id Int @id @default(autoincrement())
email String @unique @email
@@validate(length(email, 8))
@@allow('all', true)
}
`,
);

await expect(
db.user.create({
data: {
email: 'xyz',
},
}),
).toBeRejectedByValidation();
await expect(
db.user.create({
data: {
email: '[email protected]',
},
}),
).toBeRejectedByValidation();

await expect(
db.$setInputValidation(false).user.create({
data: {
id: 1,
email: 'xyz',
},
}),
).toResolveTruthy();

await expect(
db.$setInputValidation(false).user.update({
where: { id: 1 },
data: {
email: '[email protected]',
},
}),
).toResolveTruthy();

// original client not affected
await expect(
db.user.create({
data: {
email: 'xyz',
},
}),
).toBeRejectedByValidation();
await expect(
db.user.create({
data: {
email: '[email protected]',
},
}),
).toBeRejectedByValidation();
});
});
66 changes: 66 additions & 0 deletions tests/regression/test/v2-migrated/issue-2000.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { createPolicyTestClient } from '@zenstackhq/testtools';
import { expect, it } from 'vitest';

// TODO: field-level policy support
it.skip('verifies issue 2000', async () => {
const db = await createPolicyTestClient(
`
type Base {
id String @id @default(uuid()) @deny('update', true)
createdAt DateTime @default(now()) @deny('update', true)
updatedAt DateTime @updatedAt @deny('update', true)
active Boolean @default(false)
published Boolean @default(true)
deleted Boolean @default(false)
startDate DateTime?
endDate DateTime?

@@allow('create', true)
@@allow('read', true)
@@allow('update', true)
}

enum EntityType {
User
Alias
Group
Service
Device
Organization
Guest
}

model Entity with Base {
entityType EntityType
name String? @unique
members Entity[] @relation("members")
memberOf Entity[] @relation("members")
@@delegate(entityType)


@@allow('create', true)
@@allow('read', true)
@@allow('update', true)
@@validate(!active || (active && name != null), "Active Entities Must Have A Name")
}

model User extends Entity {
profile Json?
username String @unique
password String @password

@@allow('create', true)
@@allow('read', true)
@@allow('update', true)
}
`,
);

await expect(db.user.create({ data: { username: 'admin', password: 'abc12345' } })).toResolveTruthy();
await expect(
db.user.update({ where: { username: 'admin' }, data: { password: 'abc123456789123' } }),
).toResolveTruthy();

// violating validation rules
await expect(db.user.update({ where: { username: 'admin' }, data: { active: true } })).toBeRejectedByPolicy();
});
91 changes: 91 additions & 0 deletions tests/regression/test/v2-migrated/issue-2007.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { createPolicyTestClient } from '@zenstackhq/testtools';
import { describe, expect, it } from 'vitest';

// TODO: field-level policy support
describe.skip('Regression for issue 2007', () => {
it('regression1', async () => {
const db = await createPolicyTestClient(
`
model Page {
id String @id @default(cuid())
title String

images Image[]

@@allow('all', true)
}

model Image {
id String @id @default(cuid()) @deny('update', true)
url String
pageId String?
page Page? @relation(fields: [pageId], references: [id])

@@allow('all', true)
}
`,
);

const image = await db.image.create({
data: {
url: 'https://example.com/image.png',
},
});

await expect(
db.image.update({
where: { id: image.id },
data: {
page: {
create: {
title: 'Page 1',
},
},
},
}),
).toResolveTruthy();
});

it('regression2', async () => {
const db = await createPolicyTestClient(
`
model Page {
id String @id @default(cuid())
title String

images Image[]

@@allow('all', true)
}

model Image {
id String @id @default(cuid())
url String
pageId String? @deny('update', true)
page Page? @relation(fields: [pageId], references: [id])

@@allow('all', true)
}
`,
);

const image = await db.image.create({
data: {
url: 'https://example.com/image.png',
},
});

await expect(
db.image.update({
where: { id: image.id },
data: {
page: {
create: {
title: 'Page 1',
},
},
},
}),
).toBeRejectedByPolicy();
});
});
Loading
Loading