Skip to content

merge dev to main #630

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

Merged
merged 2 commits into from
Aug 14, 2023
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "zenstack-monorepo",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"description": "",
"scripts": {
"build": "pnpm -r build",
Expand Down
2 changes: 1 addition & 1 deletion packages/language/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/language",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"displayName": "ZenStack modeling language compiler",
"description": "ZenStack modeling language compiler",
"homepage": "https://zenstack.dev",
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/openapi/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/openapi",
"displayName": "ZenStack Plugin and Runtime for OpenAPI",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"description": "ZenStack plugin and runtime supporting OpenAPI",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/swr/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/swr",
"displayName": "ZenStack plugin for generating SWR hooks",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"description": "ZenStack plugin for generating SWR hooks",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/tanstack-query/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/tanstack-query",
"displayName": "ZenStack plugin for generating tanstack-query hooks",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"description": "ZenStack plugin for generating tanstack-query hooks",
"main": "index.js",
"exports": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/trpc/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/trpc",
"displayName": "ZenStack plugin for tRPC",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"description": "ZenStack plugin for tRPC",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/runtime",
"displayName": "ZenStack Runtime Library",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"description": "Runtime of ZenStack for both client-side and server-side environments.",
"repository": {
"type": "git",
Expand Down
17 changes: 17 additions & 0 deletions packages/runtime/src/enhancements/policy/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import path from 'path';
import semver from 'semver';
import { PRISMA_MINIMUM_VERSION } from '../../constants';
import { AuthUser, DbClientContract } from '../../types';
import { hasAllFields } from '../../validation';
import { getDefaultModelMeta } from '../model-meta';
import { makeProxy } from '../proxy';
import type { ModelMeta, PolicyDef, ZodSchemas } from '../types';
import { getIdFields } from '../utils';
import { PolicyProxyHandler } from './handler';

/**
Expand Down Expand Up @@ -70,6 +72,21 @@ export function withPolicy<DbClient extends object>(
const _modelMeta = options?.modelMeta ?? getDefaultModelMeta();
const _zodSchemas = options?.zodSchemas ?? getDefaultZodSchemas();

// validate user context
if (context?.user) {
const idFields = getIdFields(_modelMeta, 'User');
if (
!hasAllFields(
context.user,
idFields.map((f) => f.name)
)
) {
throw new Error(
`Invalid user context: must have valid ID field ${idFields.map((f) => `"${f.name}"`).join(', ')}`
);
}
}

return makeProxy(
prisma,
_modelMeta,
Expand Down
8 changes: 6 additions & 2 deletions packages/runtime/src/enhancements/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ export function getModelFields(data: object) {
* Gets id fields for the given model.
*/
export function getIdFields(modelMeta: ModelMeta, model: string, throwIfNotFound = false) {
const fields = modelMeta.fields[lowerCaseFirst(model)];
let fields = modelMeta.fields[lowerCaseFirst(model)];
if (!fields) {
throw new Error(`Unable to load fields for ${model}`);
if (throwIfNotFound) {
throw new Error(`Unable to load fields for ${model}`);
} else {
fields = {};
}
}
const result = Object.values(fields).filter((f) => f.isId);
if (result.length === 0 && throwIfNotFound) {
Expand Down
2 changes: 1 addition & 1 deletion packages/schema/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"publisher": "zenstack",
"displayName": "ZenStack Language Tools",
"description": "A toolkit for building secure CRUD apps with Next.js + Typescript",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"author": {
"name": "ZenStack Team"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
getPrismaClientImportSpec,
hasAttribute,
hasValidationAttributes,
isForeignKeyField,
PluginError,
PluginOptions,
resolved,
Expand Down Expand Up @@ -274,6 +275,7 @@ export default class PolicyGenerator {
// we can't check based on create input
return false;
}

if (
isDataModelField(expr.target.ref) &&
expr.target.ref.$container === model &&
Expand All @@ -284,6 +286,12 @@ export default class PolicyGenerator {
// based on create input
return false;
}

if (isDataModelField(expr.target.ref) && isForeignKeyField(expr.target.ref)) {
// reference to foreign key field
// we can't check based on create input
return false;
}
}

return true;
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/sdk",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"description": "ZenStack plugin development SDK",
"main": "index.js",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/server",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"displayName": "ZenStack Server-side Adapters",
"description": "ZenStack server-side adapters",
"homepage": "https://zenstack.dev",
Expand Down
2 changes: 1 addition & 1 deletion packages/testtools/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/testtools",
"version": "1.0.0-beta.17",
"version": "1.0.0-beta.18",
"description": "ZenStack Test Tools",
"main": "index.js",
"publishConfig": {
Expand Down
45 changes: 41 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,7 @@ describe('With Policy: auth() test', () => {
const authDb = withPolicy();
await expect(authDb.post.update({ where: { id: '1' }, data: { title: 'bcd' } })).toBeRejectedByPolicy();

const authDb1 = withPolicy({ id: null });
await expect(authDb1.post.update({ where: { id: '1' }, data: { title: 'bcd' } })).rejects.toThrow();
expect(() => withPolicy({ id: null })).toThrow(/Invalid user context/);

const authDb2 = withPolicy({ id: 'user1' });
await expect(authDb2.post.update({ where: { id: '1' }, data: { title: 'bcd' } })).toResolveTruthy();
Expand Down Expand Up @@ -148,9 +147,6 @@ describe('With Policy: auth() test', () => {

await expect(db.post.update({ where: { id: '1' }, data: { title: 'bcd' } })).toBeRejectedByPolicy();

const authDb1 = withPolicy({ id: null });
await expect(authDb1.post.update({ where: { id: '1' }, data: { title: 'bcd' } })).rejects.toThrow();

const authDb2 = withPolicy({ id: 'user1' });
await expect(authDb2.post.update({ where: { id: '1' }, data: { title: 'bcd' } })).toResolveTruthy();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ describe('With Policy: multiple id fields', () => {
await prisma.user.create({ data: { x: '1', y: '1' } });
await prisma.user.create({ data: { x: '1', y: '2' } });

const anonDb = withPolicy({});
const anonDb = withPolicy();

await expect(
anonDb.m.create({ data: { owner: { connect: { x_y: { x: '1', y: '2' } } } } })
Expand Down
51 changes: 51 additions & 0 deletions tests/integration/tests/regression/issues.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,4 +548,55 @@ model Group {
})
).resolves.toHaveLength(2);
});

it('issue 627', async () => {
const { prisma, withPolicy } = await loadSchema(
`
model User {
id String @id @default(uuid())
}

abstract model BaseEntityWithTenant {
id String @id @default(uuid())

name String
tenant_id String
tenant tenant? @relation(fields: [tenant_id], references: [id])

@@allow('all', auth().id == tenant_id)
}

model tenant {
id String @id @default(uuid())
equipments Equipment[]
}

model Equipment extends BaseEntityWithTenant {
a String
}
`,
{ logPrismaQuery: true }
);

await prisma.tenant.create({
data: {
id: 'tenant-1',
},
});

const db = withPolicy({ id: 'tenant-1' });
const r = await db.equipment.create({
data: {
name: 'equipment-1',
tenant: {
connect: {
id: 'tenant-1',
},
},
a: 'a',
},
});

console.log(r);
});
});