@fabrika/auth-core 0.3.2 → 0.4.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/auth-core",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The IAM application id of one environment of an application: `<app>@<env>`, for example `notes@prod`
3
+ * ([ADR-0022](../../../docs/decisions/0022-the-proxy-is-the-only-enforcement-point.md) rule 6). Schemas,
4
+ * roles, grants, keys and return origins are registered under it, so a staging key is refused at production.
5
+ * The installation's own services keep a plain id without `@` — the platform audiences IAM registers.
6
+ */
7
+
8
+ /**
9
+ * The one name the IAM application id travels under, from the control plane to the application that
10
+ * verifies a token's `aud` against it. Platform-owned like `FABRIKA_IAM_ISSUER`: every deploy writes it,
11
+ * and an application that declares it for itself is refused.
12
+ */
13
+ export const FABRIKA_IAM_APP_ID = 'FABRIKA_IAM_APP_ID'
14
+
15
+ /** Separates the application from the environment. Reserved: neither part may contain it. */
16
+ export const APP_ENVIRONMENT_SEPARATOR = '@'
17
+
18
+ export interface AppEnvironment {
19
+ readonly app: string
20
+ readonly env: string
21
+ }
22
+
23
+ /** True when `value` can be one part of an application id: non-empty and without the separator. */
24
+ export function isAppEnvironmentPart(value: string): boolean {
25
+ return value !== '' && !value.includes(APP_ENVIRONMENT_SEPARATOR)
26
+ }
27
+
28
+ /** Build `<app>@<env>`. Throws when either part is empty or contains `@`, because the id would not parse back. */
29
+ export function appEnvironmentId(app: string, env: string): string {
30
+ if (!isAppEnvironmentPart(app) || !isAppEnvironmentPart(env)) {
31
+ throw new Error(`an application id and an environment name must be non-empty and must not contain '${APP_ENVIRONMENT_SEPARATOR}'`)
32
+ }
33
+ return `${app}${APP_ENVIRONMENT_SEPARATOR}${env}`
34
+ }
35
+
36
+ /** The parts of `<app>@<env>`, or null for any other string — a platform audience or a malformed id. */
37
+ export function parseAppEnvironmentId(id: string): AppEnvironment | null {
38
+ const parts = id.split(APP_ENVIRONMENT_SEPARATOR)
39
+ if (parts.length !== 2) {
40
+ return null
41
+ }
42
+ const [app = '', env = ''] = parts
43
+ return isAppEnvironmentPart(app) && isAppEnvironmentPart(env) ? { app, env } : null
44
+ }
@@ -0,0 +1,66 @@
1
+ /** A request target split into its raw pathname and its query (with the leading `?`, or empty). */
2
+ export interface RequestTarget {
3
+ readonly pathname: string
4
+ readonly search: string
5
+ }
6
+
7
+ const ENCODED_SEPARATOR = /%2f|%5c/i
8
+ const ENCODED_DOT = /%2e/gi
9
+
10
+ /**
11
+ * A raw pathname is canonical when it starts with `/` and has no empty segment, no `.` or `..` (also
12
+ * encoded), no encoded `/` or `\`, no literal `\` and no malformed percent escape. Each refused form is one
13
+ * some hop rewrites or rejects, so the gate matcher and the application would otherwise read different
14
+ * paths. A trailing `/` is allowed and significant: every matcher compares it literally, so `/a/` and `/a`
15
+ * are different paths.
16
+ */
17
+ export function isCanonicalPath(pathname: string): boolean {
18
+ if (pathname === '/') {
19
+ return true
20
+ }
21
+ if (!pathname.startsWith('/') || pathname.includes('\\') || ENCODED_SEPARATOR.test(pathname)) {
22
+ return false
23
+ }
24
+ const segments = pathname.slice(1).split('/')
25
+ const last = segments.length - 1
26
+ return segments.every((segment, index) => (segment !== '' || index === last) && !isDotSegment(segment) && isDecodable(segment))
27
+ }
28
+
29
+ /** Split an origin-form request target (`/path?query`) at its first `?`. */
30
+ export function splitRequestTarget(target: string): RequestTarget {
31
+ const query = target.indexOf('?')
32
+ return query === -1 ? { pathname: target, search: '' } : { pathname: target.slice(0, query), search: target.slice(query) }
33
+ }
34
+
35
+ /**
36
+ * The path and query of an absolute URL string exactly as written, without the fragment. Read it from
37
+ * the string because `new URL()` resolves dot segments and so hides the very paths that must be refused.
38
+ */
39
+ export function rawRequestTarget(url: string): RequestTarget {
40
+ const schemeEnd = url.indexOf('://')
41
+ const afterScheme = schemeEnd === -1 ? url : url.slice(schemeEnd + 3)
42
+ const fragment = afterScheme.indexOf('#')
43
+ const withoutFragment = fragment === -1 ? afterScheme : afterScheme.slice(0, fragment)
44
+ // A backslash ends the authority too: a URL parser reads it as `/`.
45
+ const authorityEnd = withoutFragment.search(/[/\\?]/)
46
+ if (authorityEnd === -1) {
47
+ return { pathname: '/', search: '' }
48
+ }
49
+ const target = splitRequestTarget(withoutFragment.slice(authorityEnd))
50
+ return target.pathname === '' ? { pathname: '/', search: target.search } : target
51
+ }
52
+
53
+ /** A segment one reader decodes and another refuses would route differently, so a malformed escape is refused. */
54
+ function isDecodable(segment: string): boolean {
55
+ try {
56
+ decodeURIComponent(segment)
57
+ return true
58
+ } catch {
59
+ return false
60
+ }
61
+ }
62
+
63
+ function isDotSegment(segment: string): boolean {
64
+ const decoded = segment.replace(ENCODED_DOT, '.')
65
+ return decoded === '.' || decoded === '..'
66
+ }
@@ -0,0 +1,189 @@
1
+ // The canonical form of a contract artifact. Two producers (`compileContract`, the static reader) and every digest
2
+ // over an artifact must agree byte for byte, so declaration order may not leak into it.
3
+
4
+ import type {
5
+ BodyAdmission,
6
+ Caller,
7
+ ContractArtifact,
8
+ CspSource,
9
+ EndpointRow,
10
+ MountArtifact,
11
+ OutputShape,
12
+ RoleArtifact,
13
+ SchemaShape,
14
+ TablePolicyArtifact,
15
+ } from './contract'
16
+
17
+ /**
18
+ * The artifact with every array whose order carries no meaning sorted: endpoints by id, and every list of names.
19
+ * Tuple items and union options keep their order, because it changes what a schema admits. Object keys are left
20
+ * as they are; `canonicalArtifactJson` sorts them.
21
+ */
22
+ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifact {
23
+ return {
24
+ app: artifact.app,
25
+ dimensions: artifact.dimensions,
26
+ actions: artifact.actions,
27
+ roles: mapValues(artifact.roles, canonicalRole),
28
+ mounts: mapValues(artifact.mounts, canonicalMount),
29
+ files: mapValues(artifact.files, (collection) => ({
30
+ ...collection,
31
+ types: sorted(collection.types),
32
+ link: typeof collection.link === 'boolean' ? collection.link : sorted(collection.link),
33
+ })),
34
+ jobs: mapValues(artifact.jobs, (job) => ({ ...job, actions: sorted(job.actions) })),
35
+ exports: mapValues(artifact.exports, (declaration) => ({ ...declaration, consumers: sorted(declaration.consumers) })),
36
+ imports: mapValues(artifact.imports, (declaration) => ({
37
+ ...declaration,
38
+ procedures: sorted(declaration.procedures),
39
+ usedBy: sorted(declaration.usedBy),
40
+ })),
41
+ csp: {
42
+ connectSrc: sortedSources(artifact.csp.connectSrc),
43
+ imgSrc: sortedSources(artifact.csp.imgSrc),
44
+ frameAncestors: sortedSources(artifact.csp.frameAncestors),
45
+ ...(artifact.csp.scriptSrc === undefined ? {} : { scriptSrc: sortedSources(artifact.csp.scriptSrc) }),
46
+ ...(artifact.csp.frameSrc === undefined ? {} : { frameSrc: sortedSources(artifact.csp.frameSrc) }),
47
+ ...(artifact.csp.styleSrc === undefined ? {} : { styleSrc: sortedSources(artifact.csp.styleSrc) }),
48
+ ...(artifact.csp.fontSrc === undefined ? {} : { fontSrc: sortedSources(artifact.csp.fontSrc) }),
49
+ },
50
+ tables: mapValues(artifact.tables, canonicalTable),
51
+ endpoints: artifact.endpoints.map(canonicalizeEndpoint).sort((a, b) => compare(a.id, b.id)),
52
+ reservedPrefixes: sorted(artifact.reservedPrefixes),
53
+ ...(artifact.declared === undefined
54
+ ? {}
55
+ : { declared: mapValues(artifact.declared, (reach) => ({ ...reach, connect: sorted(reach.connect) })) }),
56
+ ...(artifact.directories === undefined ? {} : { directories: artifact.directories }),
57
+ ...(artifact.locale === undefined ? {} : { locale: artifact.locale }),
58
+ ...(artifact.displayName === undefined ? {} : { displayName: artifact.displayName }),
59
+ ...(artifact.mail === undefined ? {} : { mail: artifact.mail }),
60
+ ...(artifact.members === undefined ? {} : { members: artifact.members }),
61
+ ...(artifact.directory === undefined ? {} : { directory: artifact.directory }),
62
+ }
63
+ }
64
+
65
+ /** The canonical artifact as JSON with every object's keys sorted: the bytes a digest of the artifact is taken over. */
66
+ export function canonicalArtifactJson(artifact: ContractArtifact): string {
67
+ return canonicalJson(canonicalizeArtifact(artifact))
68
+ }
69
+
70
+ /** JSON with every object's keys sorted. Arrays keep their order; canonicalize them first. */
71
+ export function canonicalJson(value: unknown): string {
72
+ return JSON.stringify(value, sortKeys)
73
+ }
74
+
75
+ function canonicalRole(role: RoleArtifact): RoleArtifact {
76
+ return {
77
+ grants: sorted(role.grants),
78
+ member: role.member === null ? null : { scope: role.member.scope, assignableBy: sorted(role.member.assignableBy) },
79
+ ...(role.external === true ? { external: true } : {}),
80
+ }
81
+ }
82
+
83
+ function canonicalMount(mount: MountArtifact): MountArtifact {
84
+ switch (mount.kind) {
85
+ case 'rpc':
86
+ return { ...mount, callers: sortedTuple(mount.callers) }
87
+ case 'link':
88
+ return { ...mount, grants: sorted(mount.grants) }
89
+ case 'webhook':
90
+ return { ...mount, actions: sorted(mount.actions) }
91
+ case 'spa':
92
+ return mount.public === undefined ? mount : { ...mount, public: sorted(mount.public) }
93
+ default:
94
+ return mount
95
+ }
96
+ }
97
+
98
+ function canonicalTable(table: TablePolicyArtifact): TablePolicyArtifact {
99
+ const { appRead, appCount } = table.actions
100
+ return {
101
+ ...table,
102
+ actions: {
103
+ ...table.actions,
104
+ ...(appRead === undefined ? {} : { appRead: sorted(appRead) }),
105
+ ...(appCount === undefined ? {} : { appCount: sorted(appCount) }),
106
+ },
107
+ scope: table.scope.mode === 'child' ? { ...table.scope, inherit: sorted(table.scope.inherit) } : table.scope,
108
+ insert: sorted(table.insert),
109
+ update: sorted(table.update),
110
+ }
111
+ }
112
+
113
+ function canonicalizeEndpoint(row: EndpointRow): EndpointRow {
114
+ const shared = {
115
+ admission: row.admission === null ? null : canonicalAdmission(row.admission),
116
+ input: row.input === null ? null : canonicalShape(row.input),
117
+ output: row.output === null ? null : canonicalOutput(row.output),
118
+ }
119
+ if (row.requirement === null) {
120
+ return { ...row, ...shared }
121
+ }
122
+ return { ...row, ...shared, callers: sortedTuple<Caller>(row.callers) }
123
+ }
124
+
125
+ /** A body admission with its content types sorted. */
126
+ export function canonicalAdmission(admission: BodyAdmission): BodyAdmission {
127
+ return { contentTypes: sortedTuple(admission.contentTypes), maxBytes: admission.maxBytes }
128
+ }
129
+
130
+ /** An output shape: an attachment keeps its column order, which is the file's; each column's shape is canonical. */
131
+ export function canonicalOutput(shape: OutputShape): OutputShape {
132
+ if (shape.type !== 'attachment') {
133
+ return canonicalShape(shape)
134
+ }
135
+ return { ...shape, columns: shape.columns.map((column) => ({ name: column.name, shape: canonicalShape(column.shape) })) }
136
+ }
137
+
138
+ /** A schema shape with its enum values sorted; tuple items and union options keep their order. */
139
+ export function canonicalShape(shape: SchemaShape): SchemaShape {
140
+ switch (shape.type) {
141
+ case 'enum':
142
+ return { type: 'enum', values: sorted(shape.values) }
143
+ case 'array':
144
+ return { ...shape, items: canonicalShape(shape.items) }
145
+ case 'tuple':
146
+ return { type: 'tuple', items: shape.items.map(canonicalShape), rest: shape.rest === null ? null : canonicalShape(shape.rest) }
147
+ case 'record':
148
+ return { type: 'record', key: canonicalShape(shape.key), value: canonicalShape(shape.value) }
149
+ case 'object':
150
+ return { type: 'object', fields: mapValues(shape.fields, canonicalShape) }
151
+ case 'optional':
152
+ case 'nullable':
153
+ return { type: shape.type, inner: canonicalShape(shape.inner) }
154
+ case 'union':
155
+ return { type: 'union', options: shape.options.map(canonicalShape) }
156
+ default:
157
+ return shape
158
+ }
159
+ }
160
+
161
+ /** Code-unit order: unlike `localeCompare`, it is the same on every machine. */
162
+ function compare(a: string, b: string): number {
163
+ return a < b ? -1 : a > b ? 1 : 0
164
+ }
165
+
166
+ function sorted<T extends string>(values: readonly T[]): T[] {
167
+ return [...values].sort(compare)
168
+ }
169
+
170
+ function sortedTuple<T extends string>(values: readonly [T, ...T[]]): [T, ...T[]] {
171
+ const [head] = values
172
+ const [first = head, ...rest] = sorted(values)
173
+ return [first, ...rest]
174
+ }
175
+
176
+ function sortedSources(sources: readonly CspSource[]): CspSource[] {
177
+ return [...sources].sort((a, b) => compare(a.origin, b.origin))
178
+ }
179
+
180
+ function mapValues<T, U>(record: Readonly<Record<string, T>>, map: (value: T) => U): Record<string, U> {
181
+ return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(value)]))
182
+ }
183
+
184
+ function sortKeys(_key: string, value: unknown): unknown {
185
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
186
+ return value
187
+ }
188
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
189
+ }