@insaeng/auth 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/app/cli/types-command.d.ts +11 -0
  2. package/dist/app/cli/types-command.d.ts.map +1 -0
  3. package/dist/app/cli/types-command.js +45 -0
  4. package/dist/app/http/auth-error-handler.d.ts +3 -0
  5. package/dist/app/http/auth-error-handler.d.ts.map +1 -0
  6. package/dist/app/http/auth-error-handler.js +29 -0
  7. package/dist/app/http/auth-middleware.d.ts +16 -0
  8. package/dist/app/http/auth-middleware.d.ts.map +1 -0
  9. package/dist/app/http/auth-middleware.js +73 -0
  10. package/dist/data/auth/auth-repo.d.ts +8 -1
  11. package/dist/data/auth/auth-repo.d.ts.map +1 -1
  12. package/dist/data/auth/auth-repo.js +23 -1
  13. package/dist/data/sources/cedar/cedar-schema-source.d.ts +3 -0
  14. package/dist/data/sources/cedar/cedar-schema-source.d.ts.map +1 -0
  15. package/dist/data/sources/cedar/cedar-schema-source.js +67 -0
  16. package/dist/data/sources/cedar/cedar-source.d.ts +17 -0
  17. package/dist/data/sources/cedar/cedar-source.d.ts.map +1 -0
  18. package/dist/data/sources/cedar/cedar-source.js +75 -0
  19. package/dist/data/sources/oauth/oauth-source.d.ts +18 -0
  20. package/dist/data/sources/oauth/oauth-source.d.ts.map +1 -0
  21. package/dist/data/sources/oauth/oauth-source.js +104 -0
  22. package/dist/dependencies.d.ts +10 -5
  23. package/dist/dependencies.d.ts.map +1 -1
  24. package/dist/dependencies.js +7 -4
  25. package/dist/domain/authz-types/authz-types-entity.d.ts +37 -0
  26. package/dist/domain/authz-types/authz-types-entity.d.ts.map +1 -0
  27. package/dist/domain/authz-types/authz-types-entity.js +1 -0
  28. package/dist/domain/authz-types/use-cases/generate-authz-types-use-case.d.ts +4 -0
  29. package/dist/domain/authz-types/use-cases/generate-authz-types-use-case.d.ts.map +1 -0
  30. package/dist/domain/authz-types/use-cases/generate-authz-types-use-case.js +64 -0
  31. package/dist/main.d.ts +3 -0
  32. package/dist/main.d.ts.map +1 -0
  33. package/dist/main.js +11 -0
  34. package/package.json +29 -2
  35. package/src/app/cli/types-command.ts +62 -0
  36. package/src/app/http/auth-error-handler.ts +39 -0
  37. package/src/app/http/auth-middleware.ts +104 -0
  38. package/src/data/auth/auth-repo.ts +43 -1
  39. package/src/data/sources/cedar/cedar-schema-source.ts +92 -0
  40. package/src/data/sources/cedar/cedar-source.ts +116 -0
  41. package/src/data/sources/oauth/oauth-source.ts +140 -0
  42. package/src/dependencies.ts +16 -7
  43. package/src/domain/authz-types/authz-types-entity.ts +29 -0
  44. package/src/domain/authz-types/use-cases/generate-authz-types-use-case.ts +85 -0
  45. package/src/main.ts +12 -0
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { AuthzSchema } from "../authz-types-entity.js";
2
+ export type GenerateAuthzTypes = (schema: AuthzSchema) => string;
3
+ export declare function generateAuthzTypesUseCase(schema: AuthzSchema): string;
4
+ //# sourceMappingURL=generate-authz-types-use-case.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-authz-types-use-case.d.ts","sourceRoot":"","sources":["../../../../src/domain/authz-types/use-cases/generate-authz-types-use-case.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,WAAW,EAEZ,MAAM,0BAA0B,CAAC;AAElC,MAAM,MAAM,kBAAkB,GAAG,CAAC,MAAM,EAAE,WAAW,KAAK,MAAM,CAAC;AAwDjE,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAsBrE"}
@@ -0,0 +1,64 @@
1
+ const maxLineLength = 80;
2
+ function byName(a, b) {
3
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
4
+ }
5
+ function propertyName(name) {
6
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
7
+ }
8
+ function renderAttributes(attributes, indent) {
9
+ return [...attributes]
10
+ .sort(byName)
11
+ .map(({ name, type, required }) => `${indent} ${propertyName(name)}${required ? "" : "?"}: ${renderType(type, `${indent} `)};\n`)
12
+ .join("");
13
+ }
14
+ function renderType(type, indent) {
15
+ switch (type.kind) {
16
+ case "string":
17
+ case "extension":
18
+ return "string";
19
+ case "long":
20
+ return "number";
21
+ case "boolean":
22
+ return "boolean";
23
+ case "set":
24
+ return `${renderType(type.element, indent)}[]`;
25
+ case "entity":
26
+ return `EntityUid<${JSON.stringify(type.name)}>`;
27
+ case "record":
28
+ return type.attributes.length === 0
29
+ ? "Record<string, never>"
30
+ : `{\n${renderAttributes(type.attributes, indent)}${indent}}`;
31
+ }
32
+ }
33
+ function renderAction(actions) {
34
+ if (actions.length === 0) {
35
+ return "export type Action = never;\n";
36
+ }
37
+ const union = `${actions.map((action) => JSON.stringify(action)).join(" | ")};`;
38
+ if (`export type Action = ${union}`.length <= maxLineLength) {
39
+ return `export type Action = ${union}\n`;
40
+ }
41
+ if (` ${union}`.length <= maxLineLength) {
42
+ return `export type Action =\n ${union}\n`;
43
+ }
44
+ return `export type Action =\n${actions.map((action) => ` | ${JSON.stringify(action)}`).join("\n")};\n`;
45
+ }
46
+ export function generateAuthzTypesUseCase(schema) {
47
+ const actions = [
48
+ ...new Set(schema.namespaces.flatMap(({ actions }) => actions)),
49
+ ].sort();
50
+ const entities = schema.namespaces
51
+ .flatMap(({ name: namespace, entityTypes }) => entityTypes.map(({ name, attributes }) => ({
52
+ name: [...namespace.split("::"), name].join(""),
53
+ attributes,
54
+ })))
55
+ .sort(byName)
56
+ .map(({ name, attributes }) => attributes.length === 0
57
+ ? `export type ${name} = Record<string, never>;\n`
58
+ : `export interface ${name} {\n${renderAttributes(attributes, "")}}\n`);
59
+ return [
60
+ renderAction(actions),
61
+ "export interface EntityUid<Type extends string> {\n type: Type;\n id: string;\n}\n",
62
+ ...entities,
63
+ ].join("\n");
64
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":""}
package/dist/main.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { typesCommand } from "./app/cli/types-command.js";
3
+ import { readCedarSchemaSource } from "./data/sources/cedar/cedar-schema-source.js";
4
+ import { generateAuthzTypesUseCase } from "./domain/authz-types/use-cases/generate-authz-types-use-case.js";
5
+ process.exitCode = typesCommand(process.argv.slice(2), {
6
+ readAuthzSchema: readCedarSchemaSource,
7
+ generateAuthzTypes: generateAuthzTypesUseCase,
8
+ cwd: process.cwd(),
9
+ log: console.log,
10
+ error: console.error,
11
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insaeng/auth",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Access-token verification for insaeng services",
5
5
  "repository": {
6
6
  "type": "git",
@@ -8,11 +8,18 @@
8
8
  "directory": "packages/auth"
9
9
  },
10
10
  "type": "module",
11
+ "bin": {
12
+ "insaeng-auth": "./dist/main.js"
13
+ },
11
14
  "exports": {
12
15
  ".": {
13
16
  "types": "./dist/dependencies.d.ts",
14
17
  "default": "./dist/dependencies.js"
15
18
  },
19
+ "./client": {
20
+ "types": "./dist/data/sources/oauth/oauth-source.d.ts",
21
+ "default": "./dist/data/sources/oauth/oauth-source.js"
22
+ },
16
23
  "./testing": {
17
24
  "types": "./dist/data/sources/jwks/test-issuer-source.d.ts",
18
25
  "default": "./dist/data/sources/jwks/test-issuer-source.js"
@@ -20,6 +27,10 @@
20
27
  "./domain": {
21
28
  "types": "./dist/domain/auth/auth-entity.d.ts",
22
29
  "default": "./dist/domain/auth/auth-entity.js"
30
+ },
31
+ "./hono": {
32
+ "types": "./dist/app/http/auth-middleware.d.ts",
33
+ "default": "./dist/app/http/auth-middleware.js"
23
34
  }
24
35
  },
25
36
  "publishConfig": {
@@ -31,16 +42,32 @@
31
42
  "src"
32
43
  ],
33
44
  "dependencies": {
45
+ "@cedar-policy/cedar-wasm": "4.15.0",
34
46
  "jose": "6.2.19"
35
47
  },
48
+ "peerDependencies": {
49
+ "@hono/zod-openapi": "^1.6.3",
50
+ "hono": "^4.13.23"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "@hono/zod-openapi": {
54
+ "optional": true
55
+ },
56
+ "hono": {
57
+ "optional": true
58
+ }
59
+ },
36
60
  "devDependencies": {
61
+ "@hono/zod-openapi": "1.6.3",
37
62
  "@insaeng/tsconfig": "0.1.0",
38
63
  "@types/node": "24.19.4",
64
+ "hono": "4.13.23",
65
+ "prettier": "3.10.1",
39
66
  "typescript": "6.0.3",
40
67
  "vitest": "5.1.2"
41
68
  },
42
69
  "scripts": {
43
- "build": "tsc -p tsconfig.build.json",
70
+ "build": "tsc -p tsconfig.build.json && chmod +x dist/main.js",
44
71
  "typecheck": "tsc"
45
72
  }
46
73
  }
@@ -0,0 +1,62 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import type { AuthzSchema } from "../../domain/authz-types/authz-types-entity.js";
5
+ import type { GenerateAuthzTypes } from "../../domain/authz-types/use-cases/generate-authz-types-use-case.js";
6
+
7
+ export interface TypesCommandDeps {
8
+ readAuthzSchema(dir: string): AuthzSchema;
9
+ generateAuthzTypes: GenerateAuthzTypes;
10
+ cwd: string;
11
+ log(message: string): void;
12
+ error(message: string): void;
13
+ }
14
+
15
+ const usage =
16
+ "Usage: insaeng-auth types [--dir authz] [--out src/domain/authz/authz-entity.ts] [--check]";
17
+
18
+ function parse(argv: string[]) {
19
+ try {
20
+ const { positionals, values } = parseArgs({
21
+ args: argv,
22
+ allowPositionals: true,
23
+ options: {
24
+ dir: { type: "string", default: "authz" },
25
+ out: { type: "string", default: "src/domain/authz/authz-entity.ts" },
26
+ check: { type: "boolean", default: false },
27
+ },
28
+ });
29
+ return positionals.length === 1 && positionals[0] === "types"
30
+ ? values
31
+ : undefined;
32
+ } catch {
33
+ return undefined;
34
+ }
35
+ }
36
+
37
+ export function typesCommand(argv: string[], deps: TypesCommandDeps): number {
38
+ const options = parse(argv);
39
+ if (options === undefined) {
40
+ deps.error(usage);
41
+ return 2;
42
+ }
43
+ const { dir, out, check } = options;
44
+ const path = resolve(deps.cwd, out);
45
+ const text = deps.generateAuthzTypes(
46
+ deps.readAuthzSchema(resolve(deps.cwd, dir)),
47
+ );
48
+ if (check) {
49
+ if (!existsSync(path) || readFileSync(path, "utf8") !== text) {
50
+ deps.error(
51
+ `${out} is stale; run insaeng-auth types to regenerate it from ${dir}/schema.cedarschema.`,
52
+ );
53
+ return 1;
54
+ }
55
+ deps.log(`${out} is up to date.`);
56
+ return 0;
57
+ }
58
+ mkdirSync(dirname(path), { recursive: true });
59
+ writeFileSync(path, text);
60
+ deps.log(`Wrote ${out}.`);
61
+ return 0;
62
+ }
@@ -0,0 +1,39 @@
1
+ import { STATUS_CODES } from "node:http";
2
+ import type { Context, ErrorHandler } from "hono";
3
+ import type { ContentfulStatusCode } from "hono/utils/http-status";
4
+ import { Forbidden, Unauthenticated } from "../../domain/auth/auth-entity.js";
5
+
6
+ interface ProblemInput {
7
+ status: ContentfulStatusCode;
8
+ detail: string;
9
+ headers?: Record<string, string>;
10
+ }
11
+
12
+ function problem(c: Context, input: ProblemInput): Response {
13
+ const body = {
14
+ type: "about:blank",
15
+ title: STATUS_CODES[input.status] ?? "Error",
16
+ status: input.status,
17
+ detail: input.detail,
18
+ instance: c.req.path,
19
+ };
20
+ return c.body(JSON.stringify(body), input.status, {
21
+ ...input.headers,
22
+ "Content-Type": "application/problem+json",
23
+ });
24
+ }
25
+
26
+ export const authErrorHandler: ErrorHandler = (error, c) => {
27
+ if (error instanceof Forbidden) {
28
+ const action = String(error.action);
29
+ return problem(c, { status: 403, detail: `The caller may not ${action}` });
30
+ }
31
+ if (error instanceof Unauthenticated) {
32
+ return problem(c, {
33
+ status: 401,
34
+ detail: "A valid bearer access token is required",
35
+ headers: { "WWW-Authenticate": "Bearer" },
36
+ });
37
+ }
38
+ throw error;
39
+ };
@@ -0,0 +1,104 @@
1
+ import type { OpenAPIHono } from "@hono/zod-openapi";
2
+ import type { Context, MiddlewareHandler } from "hono";
3
+ import { createMiddleware } from "hono/factory";
4
+ import { matchedRoutes } from "hono/route";
5
+ import {
6
+ Unauthenticated,
7
+ type Principal,
8
+ type VerifyAccessToken,
9
+ } from "../../domain/auth/auth-entity.js";
10
+ import { authErrorHandler } from "./auth-error-handler.js";
11
+
12
+ export { authErrorHandler } from "./auth-error-handler.js";
13
+
14
+ export interface AuthEnv {
15
+ Variables: { principal: Principal };
16
+ }
17
+
18
+ export type OpenAPIApp = Pick<OpenAPIHono, "getOpenAPI31Document">;
19
+
20
+ export interface AuthMiddlewareOptions {
21
+ app: OpenAPIApp;
22
+ verifyAccessToken: VerifyAccessToken;
23
+ }
24
+
25
+ const methods = [
26
+ "get",
27
+ "put",
28
+ "post",
29
+ "delete",
30
+ "options",
31
+ "head",
32
+ "patch",
33
+ "trace",
34
+ ] as const;
35
+
36
+ const bearerToken = /^Bearer +(\S+)$/i;
37
+
38
+ function routeKey(method: string, path: string): string {
39
+ return `${method.toUpperCase()} ${path}`;
40
+ }
41
+
42
+ function readPublicRoutes(app: OpenAPIApp): ReadonlySet<string> {
43
+ const document = app.getOpenAPI31Document({
44
+ openapi: "3.1.0",
45
+ info: { title: "routes", version: "0.0.0" },
46
+ });
47
+ const publicRoutes = new Set<string>();
48
+ const undeclaredRoutes: string[] = [];
49
+ for (const [path, item] of Object.entries(document.paths ?? {})) {
50
+ for (const method of methods) {
51
+ const operation = item[method];
52
+ if (operation === undefined) {
53
+ continue;
54
+ }
55
+ if (operation.security === undefined) {
56
+ undeclaredRoutes.push(routeKey(method, path));
57
+ } else if (operation.security.length === 0) {
58
+ publicRoutes.add(
59
+ routeKey(method, path.replaceAll(/\{([^}]+)\}/g, ":$1")),
60
+ );
61
+ }
62
+ }
63
+ }
64
+ if (undeclaredRoutes.length > 0) {
65
+ throw new Error(
66
+ `Every route must declare security; missing on ${undeclaredRoutes.join(", ")}`,
67
+ );
68
+ }
69
+ return publicRoutes;
70
+ }
71
+
72
+ function isPublic(c: Context, publicRoutes: ReadonlySet<string>): boolean {
73
+ const route = matchedRoutes(c).find(({ method }) => method !== "ALL");
74
+ return (
75
+ route !== undefined && publicRoutes.has(routeKey(route.method, route.path))
76
+ );
77
+ }
78
+
79
+ export function createAuthMiddleware({
80
+ app,
81
+ verifyAccessToken,
82
+ }: AuthMiddlewareOptions): MiddlewareHandler<AuthEnv> {
83
+ const publicRoutes = readPublicRoutes(app);
84
+ return createMiddleware<AuthEnv>(async (c, next) => {
85
+ if (isPublic(c, publicRoutes)) {
86
+ await next();
87
+ return undefined;
88
+ }
89
+ const token = bearerToken.exec(c.req.header("Authorization") ?? "")?.[1];
90
+ if (token === undefined) {
91
+ return authErrorHandler(new Unauthenticated(), c);
92
+ }
93
+ try {
94
+ c.set("principal", await verifyAccessToken(token));
95
+ } catch (error) {
96
+ if (error instanceof Unauthenticated) {
97
+ return authErrorHandler(error, c);
98
+ }
99
+ throw error;
100
+ }
101
+ await next();
102
+ return undefined;
103
+ });
104
+ }
@@ -1,6 +1,12 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { errors } from "jose";
2
3
  import type { Principal } from "../../domain/auth/auth-entity.js";
3
4
  import type { AuthRepo } from "../../domain/auth/auth-repo.js";
5
+ import type {
6
+ CedarEntity,
7
+ CedarEntityUid,
8
+ CedarSource,
9
+ } from "../sources/cedar/cedar-source.js";
4
10
  import type {
5
11
  AccessTokenClaims,
6
12
  JwksSource,
@@ -8,6 +14,13 @@ import type {
8
14
 
9
15
  export interface AuthRepoDeps {
10
16
  jwks: JwksSource;
17
+ cedar: CedarSource;
18
+ }
19
+
20
+ export interface AuthResource {
21
+ type: string;
22
+ id?: string;
23
+ [attribute: string]: unknown;
11
24
  }
12
25
 
13
26
  const rejectedTokenErrors = [
@@ -40,9 +53,18 @@ function toPrincipal(claims: AccessTokenClaims): Principal {
40
53
  return principal;
41
54
  }
42
55
 
56
+ function toEntity(
57
+ uid: CedarEntityUid,
58
+ attrs: Record<string, unknown> = {},
59
+ parents: CedarEntityUid[] = [],
60
+ ): CedarEntity {
61
+ return { uid, attrs: attrs as CedarEntity["attrs"], parents };
62
+ }
63
+
43
64
  export function createAuthRepo({
44
65
  jwks,
45
- }: AuthRepoDeps): Pick<AuthRepo, "findPrincipal"> {
66
+ cedar,
67
+ }: AuthRepoDeps): AuthRepo<string, AuthResource> {
46
68
  return {
47
69
  async findPrincipal(accessToken) {
48
70
  try {
@@ -54,5 +76,25 @@ export function createAuthRepo({
54
76
  throw error;
55
77
  }
56
78
  },
79
+ can(principal, action, { type, id = randomUUID(), ...attributes }) {
80
+ const principalUid = {
81
+ type: principal.kind === "client" ? "Client" : "User",
82
+ id: principal.id,
83
+ };
84
+ const roles = principal.roles.map((role) => ({ type: "Role", id: role }));
85
+ const resourceUid = { type, id };
86
+ return Promise.resolve(
87
+ cedar.isAuthorized({
88
+ principal: principalUid,
89
+ action: { type: "Action", id: action },
90
+ resource: resourceUid,
91
+ entities: [
92
+ toEntity(principalUid, {}, roles),
93
+ ...roles.map((role) => toEntity(role)),
94
+ toEntity(resourceUid, attributes),
95
+ ],
96
+ }),
97
+ );
98
+ },
57
99
  };
58
100
  }
@@ -0,0 +1,92 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import {
4
+ schemaToJsonWithResolvedTypes,
5
+ type SchemaJson,
6
+ type Type,
7
+ type TypeOfAttribute,
8
+ } from "@cedar-policy/cedar-wasm/nodejs";
9
+ import type {
10
+ AuthzAttribute,
11
+ AuthzSchema,
12
+ AuthzType,
13
+ } from "../../../domain/authz-types/authz-types-entity.js";
14
+
15
+ const primitives: Partial<Record<string, AuthzType>> = {
16
+ String: { kind: "string" },
17
+ Long: { kind: "long" },
18
+ Boolean: { kind: "boolean" },
19
+ Bool: { kind: "boolean" },
20
+ };
21
+
22
+ function commonType(json: SchemaJson<string>, name: string) {
23
+ const separator = name.lastIndexOf("::");
24
+ const namespace = separator === -1 ? "" : name.slice(0, separator);
25
+ const id = separator === -1 ? name : name.slice(separator + 2);
26
+ return json[namespace]?.commonTypes?.[id];
27
+ }
28
+
29
+ function toType(json: SchemaJson<string>, type: Type<string>): AuthzType {
30
+ if ("element" in type) {
31
+ return { kind: "set", element: toType(json, type.element) };
32
+ }
33
+ if ("attributes" in type) {
34
+ return { kind: "record", attributes: toAttributes(json, type.attributes) };
35
+ }
36
+ if ("name" in type) {
37
+ if (type.type === "Extension") {
38
+ return { kind: "extension", name: type.name };
39
+ }
40
+ const common = commonType(json, type.name);
41
+ return common === undefined
42
+ ? { kind: "entity", name: type.name }
43
+ : toType(json, common);
44
+ }
45
+ const primitive = primitives[type.type.replace(/^__cedar::/, "")];
46
+ if (primitive !== undefined) {
47
+ return primitive;
48
+ }
49
+ const common = commonType(json, type.type);
50
+ return common === undefined
51
+ ? { kind: "extension", name: type.type }
52
+ : toType(json, common);
53
+ }
54
+
55
+ function toAttributes(
56
+ json: SchemaJson<string>,
57
+ attributes: Record<string, TypeOfAttribute<string>>,
58
+ ): AuthzAttribute[] {
59
+ return Object.entries(attributes).map(([name, type]) => ({
60
+ name,
61
+ type: toType(json, type),
62
+ required: type.required !== false,
63
+ }));
64
+ }
65
+
66
+ export function readCedarSchemaSource(dir: string): AuthzSchema {
67
+ const answer = schemaToJsonWithResolvedTypes(
68
+ readFileSync(join(dir, "schema.cedarschema"), "utf8"),
69
+ );
70
+ if (answer.type === "failure") {
71
+ throw new Error(
72
+ `Invalid Cedar schema in ${dir}:\n${answer.errors.map((error) => `- ${error.message}`).join("\n")}`,
73
+ );
74
+ }
75
+ const { json } = answer;
76
+ return {
77
+ namespaces: Object.entries(json).map(([name, namespace]) => ({
78
+ name,
79
+ actions: Object.keys(namespace.actions),
80
+ entityTypes: Object.entries(namespace.entityTypes).map(
81
+ ([entityName, entityType]) => {
82
+ const shape =
83
+ "shape" in entityType ? toType(json, entityType.shape) : undefined;
84
+ return {
85
+ name: entityName,
86
+ attributes: shape?.kind === "record" ? shape.attributes : [],
87
+ };
88
+ },
89
+ ),
90
+ })),
91
+ };
92
+ }
@@ -0,0 +1,116 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readdirSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import {
5
+ policySetTextToParts,
6
+ preparsePolicySet,
7
+ preparseSchema,
8
+ statefulIsAuthorized,
9
+ validate,
10
+ type DetailedError,
11
+ type EntityJson,
12
+ type TypeAndId,
13
+ } from "@cedar-policy/cedar-wasm/nodejs";
14
+
15
+ export type CedarEntityUid = TypeAndId;
16
+ export type CedarEntity = EntityJson;
17
+
18
+ export interface CedarSourceOptions {
19
+ dir: string;
20
+ }
21
+
22
+ export interface CedarRequest {
23
+ principal: CedarEntityUid;
24
+ action: CedarEntityUid;
25
+ resource: CedarEntityUid;
26
+ entities: CedarEntity[];
27
+ }
28
+
29
+ export interface CedarSource {
30
+ isAuthorized(request: CedarRequest): boolean;
31
+ }
32
+
33
+ function messages(errors: DetailedError[], prefix = ""): string[] {
34
+ return errors.map((error) => `${prefix}${error.message}`);
35
+ }
36
+
37
+ function fail(dir: string, errors: string[]): never {
38
+ throw new Error(
39
+ `Invalid Cedar schema or policies in ${dir}:\n${errors.map((error) => `- ${error}`).join("\n")}`,
40
+ );
41
+ }
42
+
43
+ function readPolicies(policiesDir: string) {
44
+ const policies: Record<string, string> = {};
45
+ const errors: string[] = [];
46
+ const files = readdirSync(policiesDir)
47
+ .filter((file) => file.endsWith(".cedar"))
48
+ .sort();
49
+ for (const file of files) {
50
+ const parts = policySetTextToParts(
51
+ readFileSync(join(policiesDir, file), "utf8"),
52
+ );
53
+ if (parts.type === "failure") {
54
+ errors.push(...messages(parts.errors, `${file}: `));
55
+ continue;
56
+ }
57
+ if (parts.policy_templates.length > 0) {
58
+ errors.push(`${file}: policy templates are not supported`);
59
+ }
60
+ parts.policies.forEach((policy, index) => {
61
+ policies[`${file}#${String(index)}`] = policy;
62
+ });
63
+ }
64
+ return { policies, errors };
65
+ }
66
+
67
+ export function createCedarSource({ dir }: CedarSourceOptions): CedarSource {
68
+ const schema = readFileSync(join(dir, "schema.cedarschema"), "utf8");
69
+ const { policies, errors } = readPolicies(join(dir, "policies"));
70
+ if (errors.length > 0) {
71
+ fail(dir, errors);
72
+ }
73
+
74
+ const validation = validate({
75
+ schema,
76
+ policies: { staticPolicies: policies },
77
+ });
78
+ const validationErrors =
79
+ validation.type === "failure"
80
+ ? validation.errors
81
+ : validation.validationErrors.map(({ error }) => error);
82
+ if (validationErrors.length > 0) {
83
+ fail(dir, messages(validationErrors));
84
+ }
85
+
86
+ const id = randomUUID();
87
+ for (const parsed of [
88
+ preparseSchema(id, schema),
89
+ preparsePolicySet(id, { staticPolicies: policies }),
90
+ ]) {
91
+ if (parsed.type === "failure") {
92
+ fail(dir, messages(parsed.errors));
93
+ }
94
+ }
95
+
96
+ return {
97
+ isAuthorized({ principal, action, resource, entities }) {
98
+ const answer = statefulIsAuthorized({
99
+ principal,
100
+ action,
101
+ resource,
102
+ context: {},
103
+ entities,
104
+ preparsedSchemaName: id,
105
+ preparsedPolicySetId: id,
106
+ validateRequest: true,
107
+ });
108
+ if (answer.type === "failure") {
109
+ throw new Error(
110
+ `Cedar authorization failed:\n${messages(answer.errors, "- ").join("\n")}`,
111
+ );
112
+ }
113
+ return answer.response.decision === "allow";
114
+ },
115
+ };
116
+ }