Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/witty-spoons-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@unkey/api": minor
---

feat: add permissions
78 changes: 78 additions & 0 deletions apps/api/src/routes/v1_keys_createKey.happy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,45 @@ describe("roles", () => {

expect(res.status, `expected 200, received: ${JSON.stringify(res, null, 2)}`).toBe(200);

const key = await h.db.primary.query.keys.findFirst({
where: (table, { eq }) => eq(table.id, res.body.keyId),
with: {
roles: {
with: {
role: true,
},
},
},
});
expect(key).toBeDefined();
expect(key!.roles.length).toBe(2);
for (const r of key!.roles!) {
expect(roles).include(r.role.name);
}
});
test("upserts the specified roles", async (t) => {
const h = await IntegrationHarness.init(t);
const roles = ["r1", "r2"];

const root = await h.createRootKey([
`api.${h.resources.userApi.id}.create_key`,
"rbac.*.create_role",
]);

const res = await h.post<V1KeysCreateKeyRequest, V1KeysCreateKeyResponse>({
url: "/v1/keys.createKey",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${root.key}`,
},
body: {
apiId: h.resources.userApi.id,
roles,
},
});

expect(res.status, `expected 200, received: ${JSON.stringify(res, null, 2)}`).toBe(200);

const key = await h.db.primary.query.keys.findFirst({
where: (table, { eq }) => eq(table.id, res.body.keyId),
with: {
Expand Down Expand Up @@ -286,6 +325,45 @@ describe("permissions", () => {
});
});

test("upserts the specified permissions", async (t) => {
const h = await IntegrationHarness.init(t);
const permissions = ["p1", "p2"];

const root = await h.createRootKey([
`api.${h.resources.userApi.id}.create_key`,
"rbac.*.create_permission",
]);

const res = await h.post<V1KeysCreateKeyRequest, V1KeysCreateKeyResponse>({
url: "/v1/keys.createKey",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${root.key}`,
},
body: {
apiId: h.resources.userApi.id,
permissions,
},
});

expect(res.status, `expected 200, received: ${JSON.stringify(res, null, 2)}`).toBe(200);

const key = await h.db.primary.query.keys.findFirst({
where: (table, { eq }) => eq(table.id, res.body.keyId),
with: {
permissions: {
with: {
permission: true,
},
},
},
});
expect(key).toBeDefined();
expect(key!.permissions.length).toBe(2);
for (const p of key!.permissions!) {
expect(permissions).include(p.permission.name);
}
});
describe("with encryption", () => {
test("encrypts a key", async (t) => {
const h = await IntegrationHarness.init(t);
Expand Down
56 changes: 56 additions & 0 deletions apps/api/src/routes/v1_keys_createKey.security.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,59 @@ test("cannot encrypt without permissions", async (t) => {
t.expect(res.status, `expected 403, received: ${JSON.stringify(res, null, 2)}`).toBe(403);
t.expect(res.body.error.code).toEqual("INSUFFICIENT_PERMISSIONS");
});

test("cannot create role without permissions", async (t) => {
const h = await IntegrationHarness.init(t);

await h.db.primary
.update(schema.keyAuth)
.set({
storeEncryptedKeys: true,
})
.where(eq(schema.keyAuth.id, h.resources.userKeyAuth.id));

const root = await h.createRootKey([`api.${h.resources.userApi.id}.create_key`]);

const res = await h.post<V1KeysCreateKeyRequest, ErrorResponse>({
url: "/v1/keys.createKey",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${root.key}`,
},
body: {
apiId: h.resources.userApi.id,
roles: ["r1"],
},
});

t.expect(res.status, `expected 403, received: ${JSON.stringify(res, null, 2)}`).toBe(403);
t.expect(res.body.error.code).toEqual("INSUFFICIENT_PERMISSIONS");
});

test("cannot create permission without permissions", async (t) => {
const h = await IntegrationHarness.init(t);

await h.db.primary
.update(schema.keyAuth)
.set({
storeEncryptedKeys: true,
})
.where(eq(schema.keyAuth.id, h.resources.userKeyAuth.id));

const root = await h.createRootKey([`api.${h.resources.userApi.id}.create_key`]);

const res = await h.post<V1KeysCreateKeyRequest, ErrorResponse>({
url: "/v1/keys.createKey",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${root.key}`,
},
body: {
apiId: h.resources.userApi.id,
permissions: ["p1"],
},
});

t.expect(res.status, `expected 403, received: ${JSON.stringify(res, null, 2)}`).toBe(403);
t.expect(res.body.error.code).toEqual("INSUFFICIENT_PERMISSIONS");
});
78 changes: 61 additions & 17 deletions apps/api/src/routes/v1_keys_createKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { schema } from "@unkey/db";
import { sha256 } from "@unkey/hash";
import { newId } from "@unkey/id";
import { KeyV1 } from "@unkey/keys";
import { buildUnkeyQuery } from "@unkey/rbac";
import { type RBAC, buildUnkeyQuery } from "@unkey/rbac";

const route = createRoute({
tags: ["keys"],
Expand Down Expand Up @@ -336,8 +336,8 @@ export const registerV1KeysCreateKey = (app: App) =>
const externalId = req.externalId ?? req.ownerId;

const [permissionIds, roleIds, identity] = await Promise.all([
getPermissionIds(db.readonly, authorizedWorkspaceId, req.permissions ?? []),
getRoleIds(db.readonly, authorizedWorkspaceId, req.roles ?? []),
getPermissionIds(auth, rbac, db.readonly, authorizedWorkspaceId, req.permissions ?? []),
getRoleIds(auth, rbac, db.readonly, authorizedWorkspaceId, req.roles ?? []),
externalId
? upsertIdentity(db.primary, authorizedWorkspaceId, externalId)
: Promise.resolve(null),
Expand Down Expand Up @@ -536,6 +536,8 @@ export const registerV1KeysCreateKey = (app: App) =>
});

async function getPermissionIds(
auth: { permissions: Array<string> },
rbac: RBAC,
db: Database,
workspaceId: string,
permissionNames: Array<string>,
Expand All @@ -551,21 +553,42 @@ async function getPermissionIds(
name: true,
},
});
if (permissions.length < permissionNames.length) {
const missingPermissions = permissionNames.filter(
(name) => !permissions.some((permission) => permission.name === name),
);
if (permissions.length === permissionNames.length) {
return permissions.map((r) => r.id);
}

const { val, err } = rbac.evaluatePermissions(
buildUnkeyQuery(({ or }) => or("*", "rbac.*.create_permission")),
auth.permissions,
);
if (err) {
throw new UnkeyApiError({
code: "PRECONDITION_FAILED",
message: `Permissions ${JSON.stringify(
missingPermissions,
)} are missing, please create them first`,
code: "INTERNAL_SERVER_ERROR",
message: `Failed to evaluate permissions: ${err.message}`,
});
}
return permissions.map((r) => r.id);
if (!val.valid) {
throw new UnkeyApiError({ code: "INSUFFICIENT_PERMISSIONS", message: val.message });
}

const missingPermissions = permissionNames.filter(
(name) => !permissions.some((permission) => permission.name === name),
);

const newPermissions = missingPermissions.map((name) => ({
id: newId("permission"),
workspaceId,
name,
}));

await db.insert(schema.permissions).values(newPermissions);

return [...permissions, ...newPermissions].map((permission) => permission.id);
}

async function getRoleIds(
auth: { permissions: Array<string> },
rbac: RBAC,
db: Database,
workspaceId: string,
roleNames: Array<string>,
Expand All @@ -581,14 +604,35 @@ async function getRoleIds(
name: true,
},
});
if (roles.length < roleNames.length) {
const missingRoles = roleNames.filter((name) => !roles.some((role) => role.name === name));
if (roles.length === roleNames.length) {
return roles.map((r) => r.id);
}

const { val, err } = rbac.evaluatePermissions(
buildUnkeyQuery(({ or }) => or("*", "rbac.*.create_role")),
auth.permissions,
);
if (err) {
throw new UnkeyApiError({
code: "PRECONDITION_FAILED",
message: `Roles ${JSON.stringify(missingRoles)} are missing, please create them first`,
code: "INTERNAL_SERVER_ERROR",
message: `Failed to evaluate permissions: ${err.message}`,
});
}
return roles.map((r) => r.id);
if (!val.valid) {
throw new UnkeyApiError({ code: "INSUFFICIENT_PERMISSIONS", message: val.message });
}

const missingRoles = roleNames.filter((name) => !roles.some((role) => role.name === name));

const newRoles = missingRoles.map((name) => ({
id: newId("role"),
workspaceId,
name,
}));

await db.insert(schema.roles).values(newRoles);

return [...roles, ...newRoles].map((role) => role.id);
}

export async function upsertIdentity(
Expand Down
Loading
Loading