-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
234 lines (208 loc) · 6.32 KB
/
Copy pathindex.js
File metadata and controls
234 lines (208 loc) · 6.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import "dotenv/config";
import Fastify from "fastify";
import { Permit } from "permitio";
const fastify = Fastify({});
const permit = new Permit({
pdp: process.env.PERMIT_PDP_URL,
token: process.env.PERMIT_API_KEY,
});
const permitIdp = new Permit({
pdp: process.env.PERMIT_IDP_PDP_URL,
token: process.env.PERMIT_IDP_API_KEY,
});
// Cache for scope to avoid fetching on every request
let idpScopeCache = null;
// Helper function to get scope (project/env) from API key
async function getScope(apiKey) {
// Return cached scope if available
if (idpScopeCache) {
return idpScopeCache;
}
const response = await fetch("https://api.permit.io/v2/api-key/scope", {
method: "GET",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error(`Failed to get scope: ${response.status} ${response.statusText}`);
}
const scope = await response.json();
// Cache the scope
idpScopeCache = scope;
return scope;
}
fastify.get("/", async () => {
return { status: "ok" };
});
fastify.post(
"/access/v1/evaluation",
async function handler({
body: {
subject: { id },
action: { name: action },
resource: { type, id: resourceId, properties },
},
reply,
}) {
const { key, email } = await permit.api.users.get(id);
console.log("Checking access for", {
key,
email,
action,
type,
properties,
});
const decision = await permit.check(
{ key, email, attributes: { email } },
action,
{
type,
attributes: { ...properties },
id: resourceId,
tenant: "default",
}
);
console.log("Decision", JSON.stringify({ decision }));
return { decision };
}
);
fastify.post(
"/access/v1/evaluations",
async function handler({
body: {
subject: { id },
action: { name: action },
evaluations,
},
reply,
}) {
const { key, email } = await permit.api.users.get(id);
console.log(
"Checking access for",
evaluations.map(({ resource: { type, id: resourceId, properties } }) => ({
user: { key, email, attributes: { email } },
action,
resource: {
type,
attributes: { ...properties },
id: resourceId,
tenant: "default",
},
}))
);
const decisions = await permit.bulkCheck(
evaluations.map(({ resource: { type, id: resourceId, properties } }) => ({
user: { key, email, attributes: { email } },
action,
resource: {
type,
attributes: { ...properties },
id: resourceId,
tenant: "default",
},
}))
);
console.log(
"Decisions",
JSON.stringify(decisions.map((decision) => ({ decision })))
);
return { evaluations: decisions.map((decision) => ({ decision })) };
}
);
fastify.post(
"/access/v1/search/resource",
async function handler({
body: {
subject: { id },
action: { name: action },
resource: { type: resourceType },
},
reply,
}) {
console.log("Searching resources for", {
userId: id,
action,
resourceType,
});
try {
// Get user details first (API expects a User object, not just a string)
const userData = await permitIdp.api.users.get(id);
// Get scope (project/env) from API key
const scope = await getScope(process.env.PERMIT_IDP_API_KEY);
const projectId = scope.project_id;
const environmentId = scope.environment_id;
console.log("Getting user permissions for", {
userId: id,
userKey: userData.key,
projectId,
environmentId,
action,
resourceType,
});
console.log("Permit IDP PDP URL", process.env.PERMIT_IDP_PDP_URL);
console.log("Permit IDP API Key", process.env.PERMIT_IDP_API_KEY);
// Call the raw user-permissions API endpoint
// The API expects a User object with at least a 'key' field
const response = await fetch(`${process.env.PERMIT_IDP_PDP_URL}/user-permissions`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.PERMIT_IDP_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
user: {
key: userData.key,
email: userData.email,
attributes: userData.attributes || {},
},
tenants: ["default"],
resource_types: [resourceType],
action: action,
context: {
enable_abac_user_permissions: true,
project_id: projectId,
environment_id: environmentId,
},
}),
});
console.log("Permissions", JSON.stringify(response));
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to get user permissions: ${response.status} ${response.statusText} - ${errorText}`);
}
const permissions = await response.json();
// Map action name to permission format (e.g., "delete" -> "record:delete")
const permissionKey = `${resourceType}:${action}`;
// Filter permissions to find resources where user has the specific action
const results = [];
// The API returns IUserPermissions: an object where keys are resource IDs
// and values are ResourcePermissions objects with a 'permissions' array
// Format: { "resourceId": { permissions: ["record:delete", ...], resource?: {...} } }
for (const [resourceId, permissionData] of Object.entries(permissions || {})) {
// Check if this resource has the specific action permission
if (permissionData?.permissions?.includes(permissionKey)) {
results.push({
type: resourceType,
id: resourceId,
});
}
}
console.log("Search results", JSON.stringify({ results }));
return { results };
} catch (error) {
console.error("Error searching resources:", error);
// Return empty results on error (as per AuthZEN spec)
return { results: [] };
}
}
);
// Run the server!
try {
await fastify.listen({ port: process.env.PORT || 3000, host: "0.0.0.0" });
console.log(`Server listening on ${fastify.server.address().port}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}