Skip to content

Commit df4258d

Browse files
Validate undeclared path params in HttpApiEndpoint (#11114)
Co-authored-by: Effect Bot <tech-ops@effectful.co>
1 parent 85d964f commit df4258d

6 files changed

Lines changed: 366 additions & 5 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
Validate explicit closed `params` schemas in `HttpApiEndpoint` against encoded wire keys for segment-leading `:param` placeholders at compile time and runtime (including `.prefix()`), while preserving literal action suffixes and omitted `params` for raw `HttpRouter.RouteContext` handlers.

‎packages/effect/src/http-api/HttpApiEndpoint.ts‎

Lines changed: 90 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ import type * as HttpApiError from "./HttpApiError.ts"
9292
import type * as HttpApiGroup from "./HttpApiGroup.ts"
9393
import type * as HttpApiMiddleware from "./HttpApiMiddleware.ts"
9494
import * as HttpApiSchema from "./HttpApiSchema.ts"
95+
import * as HttpApiPath from "./internal/path.ts"
9596
import { toCodecHttpProperties } from "./internal/toCodecHttpProperties.ts"
9697

9798
const TypeId = "~effect/http-api/HttpApiEndpoint"
@@ -989,9 +990,11 @@ const Proto = {
989990
return pipeArguments(this, arguments)
990991
},
991992
prefix(this: Top, prefix: HttpRouter.PathInput) {
993+
const path = HttpRouter.prefixPath(this.path, prefix)
994+
HttpApiPath.assertPathParams(this.identifier, this.method, path, this.params)
992995
return makeProto({
993996
...optionsFromEndpoint(this),
994-
path: HttpRouter.prefixPath(this.path, prefix)
997+
path
995998
})
996999
},
9971000
middleware(this: Top, middleware: HttpApiMiddleware.AnyService) {
@@ -1164,6 +1167,87 @@ export type SuccessConstraint = Schema.Top | ReadonlyArray<Schema.Top>
11641167
*/
11651168
export type ErrorConstraint = Schema.Top | ReadonlyArray<Schema.Top>
11661169

1170+
type Chars<S extends string, Acc extends string = never> = S extends `${infer C}${infer Rest}` ? Chars<Rest, Acc | C>
1171+
: Acc
1172+
1173+
type WordChar = Chars<"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_">
1174+
1175+
type SplitParamName<S extends string, Name extends string = ""> = S extends `${infer C}${infer Rest}` ?
1176+
C extends WordChar ? SplitParamName<Rest, `${Name}${C}`> : [Name, S]
1177+
: [Name, S]
1178+
1179+
type SkipParens<S extends string, Depth extends ReadonlyArray<unknown> = [unknown]> = Depth extends [] ? S
1180+
: S extends `\\${infer _}${infer Rest}` ? SkipParens<Rest, Depth>
1181+
: S extends `(${infer Rest}` ? SkipParens<Rest, [...Depth, unknown]>
1182+
: S extends `)${infer Rest}` ? SkipParens<Rest, Depth extends [unknown, ...infer Outer] ? Outer : []>
1183+
: S extends `${infer _}${infer Rest}` ? SkipParens<Rest, Depth>
1184+
: ""
1185+
1186+
type IsRouterParam<
1187+
Before extends string,
1188+
Leading extends boolean,
1189+
Name extends string,
1190+
After extends string,
1191+
Declared
1192+
> = Name extends "" ? false
1193+
: Name extends Declared ? true
1194+
: (Before extends "" ? Leading : Before extends `${string}/` ? true : false) extends false ? false
1195+
: After extends "" | `${"/" | "?" | "(" | "." | ":" | "-"}${string}` ? true
1196+
: false
1197+
1198+
// Mirrors `assertPathParams`: collects `:name` params the router would see.
1199+
type PathParamNames<
1200+
Path extends string,
1201+
Declared extends string,
1202+
Leading extends boolean = true,
1203+
Acc extends string = never
1204+
> = Path extends `${infer Before}:${infer Rest}` ?
1205+
Rest extends `:${infer Tail}` ? PathParamNames<Tail, Declared, false, Acc>
1206+
: SplitParamName<Rest> extends [infer Name extends string, infer After extends string] ?
1207+
IsRouterParam<Before, Leading, Name, After, Declared> extends true ? PathParamNames<
1208+
After extends `(${infer Regex}` ? SkipParens<Regex> : After,
1209+
Declared,
1210+
false,
1211+
Acc | Name
1212+
>
1213+
: PathParamNames<Rest, Declared, false, Acc>
1214+
: Acc
1215+
: Acc
1216+
1217+
type KeyToString<K> = K extends string | number ? `${K}` : never
1218+
1219+
type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never
1220+
1221+
type HasIndexSignature<K extends PropertyKey> = K extends unknown ? ({} extends Record<K, never> ? true : false) : never
1222+
1223+
type ClosedKeys<T> = 0 extends 1 & T ? string
1224+
: [unknown] extends [T] ? string
1225+
: true extends IsUnion<T> ? string
1226+
: [T] extends [ReadonlyArray<any> | ((...args: ReadonlyArray<any>) => any)] ? string
1227+
: [T] extends [object] ? true extends HasIndexSignature<keyof T> ? string : KeyToString<keyof T>
1228+
: string
1229+
1230+
type DeclaredParamKeys<Params> = true extends IsUnion<Params> ? string
1231+
: [Params] extends [Schema.toCodecStringTree<infer Inner>] ? DeclaredParamKeys<Inner>
1232+
: ClosedKeys<[Params] extends [Schema.Constraint] ? Params["Encoded"] : Params>
1233+
1234+
type MissingPathParams<Path extends string, Params, Declared extends string = DeclaredParamKeys<Params>> = Exclude<
1235+
PathParamNames<Path, Declared>,
1236+
Declared
1237+
>
1238+
1239+
// Distributes over `Path` so a generic `Path` resolves to its constraint's
1240+
// `"ok"`, while any member of a literal union can select `"err"`.
1241+
type PathParamsStatus<Path extends string, Params> = Path extends unknown ?
1242+
[MissingPathParams<Path, Params>] extends [never] ? "ok" : "err"
1243+
: never
1244+
1245+
type ValidatePathParams<Path extends string, Params> = [Params] extends [never] ? unknown
1246+
: {
1247+
readonly ok: unknown
1248+
readonly err: { readonly "~missing path params": MissingPathParams<Path, Params> }
1249+
}["err" extends PathParamsStatus<Path, Params> ? "err" : "ok"]
1250+
11671251
type ErrorSchema<S> = S extends HttpApiSchema.WithHeaders<infer Inner, Schema.Top> ? Inner : S
11681252

11691253
type ErrorNoStream<S extends ErrorConstraint> = [
@@ -1208,7 +1292,7 @@ export const make = <Method extends HttpMethod>(method: Method): {
12081292
path: Path,
12091293
options?: {
12101294
readonly disableCodecs?: false | undefined
1211-
readonly params?: Params | undefined
1295+
readonly params?: (Params & ValidatePathParams<Types.NoInfer<Path>, Types.NoInfer<Params>>) | undefined
12121296
readonly query?: Query | undefined
12131297
readonly headers?: Headers | undefined
12141298
readonly payload?: Payload | undefined
@@ -1241,7 +1325,7 @@ export const make = <Method extends HttpMethod>(method: Method): {
12411325
path: Path,
12421326
options?: {
12431327
readonly disableCodecs: true
1244-
readonly params?: Params | undefined
1328+
readonly params?: (Params & ValidatePathParams<Types.NoInfer<Path>, Types.NoInfer<Params>>) | undefined
12451329
readonly query?: Query | undefined
12461330
readonly headers?: Headers | undefined
12471331
readonly payload?: Payload | undefined
@@ -1296,12 +1380,14 @@ export const make = <Method extends HttpMethod>(method: Method): {
12961380
> => {
12971381
const disableCodecs = options?.disableCodecs ?? false
12981382
const transformProperties = disableCodecs ? identity : toCodecHttpProperties
1383+
const params = ensureStruct(options?.params, transformProperties)
1384+
HttpApiPath.assertPathParams(identifier, method, path, params)
12991385
const payload = getPayload(options?.payload, method, disableCodecs)
13001386
return makeProto({
13011387
identifier,
13021388
path,
13031389
method,
1304-
params: ensureStruct(options?.params, transformProperties),
1390+
params,
13051391
query: ensureStruct(options?.query, transformProperties),
13061392
headers: ensureStruct(options?.headers, transformProperties),
13071393
payload,

‎packages/effect/src/http-api/internal/path.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,43 @@ import type * as Schema from "../../Schema.ts"
33
import * as SchemaAST from "../../SchemaAST.ts"
44

55
const emptyParamNames: ReadonlySet<string> = new Set()
6+
/**
7+
* Throws when a closed `params` schema omits a segment-leading `:name`, which
8+
* `toRouterPath` would otherwise turn into literal text.
9+
*
10+
* @internal
11+
*/
12+
export function assertPathParams(
13+
identifier: string,
14+
method: string,
15+
path: string,
16+
schema: Schema.Constraint | undefined
17+
): void {
18+
if (schema === undefined || !path.includes(":")) return
19+
const paramNames = getParamNames(schema)
20+
if (paramNames === undefined) return
21+
22+
const missing = new Set<string>()
23+
const params = /::|:(\w+)/g
24+
for (let param = params.exec(path); param !== null; param = params.exec(path)) {
25+
const name = param[1]
26+
if (name === undefined) continue
27+
const next = path[params.lastIndex]
28+
if (!paramNames.has(name)) {
29+
const leading = param.index === 0 || path[param.index - 1] === "/"
30+
if (!leading || (next !== undefined && !"/?(.:-".includes(next))) continue
31+
missing.add(name)
32+
}
33+
if (next === "(") params.lastIndex = getClosingParenthensePosition(path, params.lastIndex) + 1
34+
}
35+
if (missing.size > 0) {
36+
const label = missing.size === 1 ? "parameter" : "parameters"
37+
const names = Array.from(missing, (name) => `":${name}"`).join(", ")
38+
throw new Error(
39+
`HttpApiEndpoint "${identifier}" (${method} ${path}): missing path ${label} ${names} in params schema`
40+
)
41+
}
42+
}
643

744
/**
845
* @internal

‎packages/effect/test/httpapi/HttpApiBuilder.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,30 @@ it.layer(TestServices)("HttpApiBuilder.handler", (it) => {
392392
assert.deepStrictEqual(yield* client.test.get({ params: { "a$b": "value" } }), {})
393393
}))
394394

395+
it.effect("preserves omitted params for raw HttpRouter.RouteContext handlers", () =>
396+
Effect.gen(function*() {
397+
const Api = HttpApi.make("Api").add(
398+
HttpApiGroup.make("users").add(
399+
HttpApiEndpoint.get("get", "/users/:id", {
400+
success: Schema.String
401+
})
402+
)
403+
)
404+
const GroupLayer = HttpApiBuilder.group(Api, "users", (handlers) =>
405+
handlers.handle("get", () =>
406+
Effect.map(HttpRouter.RouteContext, (ctx) => ctx.params.id ?? "")))
407+
const { handler } = HttpRouter.toWebHandler(
408+
HttpApiBuilder.layer(Api).pipe(
409+
Layer.provide(GroupLayer),
410+
Layer.provideMerge(TestServices)
411+
)
412+
)
413+
const response = yield* Effect.promise(() =>
414+
handler(new Request("http://localhost/users/42"))
415+
)
416+
assert.strictEqual(yield* Effect.promise(() => response.text()), "\"42\"")
417+
}))
418+
395419
it.effect("returns the callback unchanged and supports registration in a group", () =>
396420
Effect.gen(function*() {
397421
const Api = HttpApi.make("Api").add(

‎packages/effect/test/httpapi/HttpApiEndpoint.test.ts‎

Lines changed: 116 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { assert, describe, it } from "@effect/vitest"
22
import { Schema } from "effect"
3-
import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api"
3+
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/http-api"
44

55
const Events = Schema.Struct({
66
event: Schema.Literal("user.created"),
@@ -45,6 +45,121 @@ describe("HttpApiEndpoint", () => {
4545
})
4646
})
4747

48+
describe("HttpApiEndpoint path parameter validation", () => {
49+
it("rejects undeclared segment-leading parameters on explicit closed params", () => {
50+
assert.throws(
51+
() =>
52+
HttpApiEndpoint.get("getPost", "/users/:userId/posts/:postId", {
53+
params: { userId: Schema.NumberFromString } as any
54+
}),
55+
/HttpApiEndpoint "getPost" \(GET \/users\/:userId\/posts\/:postId\): missing path parameter ":postId" in params schema/
56+
)
57+
assert.throws(
58+
() => HttpApiEndpoint.get("getPost", "/users/:userId/posts/:postId", { params: {} as any }),
59+
/missing path parameters ":userId", ":postId" in params schema/
60+
)
61+
assert.throws(
62+
() =>
63+
HttpApiEndpoint.get("getPost", "/users/:userId/posts/:postId", {
64+
disableCodecs: true,
65+
params: Schema.Struct({ userId: Schema.String }) as any
66+
}),
67+
/missing path parameter ":postId"/
68+
)
69+
70+
for (
71+
const [path, expected] of [
72+
["/:postId/", "\":postId\""],
73+
["/users/:id?", "\":id\""],
74+
["/upload/:0?", "\":0\""],
75+
["/users/:id(\\d+)", "\":id\""],
76+
["/previews/:id(^(?:\\d)+)preview", "\":id\""],
77+
["/operations/:id:wait", "\":id\""],
78+
["/items/:id-bar", "\":id\""],
79+
["/files/:id.json", "\":id\""]
80+
] as const
81+
) {
82+
assert.throws(
83+
() => HttpApiEndpoint.get("ep", path as any, { params: {} as any }),
84+
new RegExp(`missing path parameter ${expected}`)
85+
)
86+
}
87+
88+
assert.throws(
89+
() => HttpApiEndpoint.get("regexSlash", "/:id([^/:x.]+)/:postId", { params: { id: Schema.String } as any }),
90+
/missing path parameter ":postId"/
91+
)
92+
assert.throws(
93+
() => HttpApiEndpoint.get("literalParen", "/offers:resolve(/:id/detail)", { params: {} as any }),
94+
/missing path parameter ":id"/
95+
)
96+
assert.throws(
97+
() => HttpApiEndpoint.get("escapedParen", "/items/::literal(/:id", { params: {} as any }),
98+
/missing path parameter ":id"/
99+
)
100+
})
101+
102+
it("validates against encoded wire keys in both codec modes", () => {
103+
const EncodedParams = Schema.Struct({ userId: Schema.String }).pipe(
104+
Schema.encodeKeys({ userId: "user_id" })
105+
)
106+
107+
HttpApiEndpoint.get("ok", "/users/:user_id", { params: EncodedParams })
108+
HttpApiEndpoint.get("okDisabled", "/users/:user_id", { disableCodecs: true, params: EncodedParams })
109+
assert.throws(
110+
() => HttpApiEndpoint.get("bad", "/users/:userId", { params: EncodedParams as any }),
111+
/missing path parameter ":userId"/
112+
)
113+
assert.throws(
114+
() =>
115+
HttpApiEndpoint.get("badDisabled", "/users/:userId", {
116+
disableCodecs: true,
117+
params: EncodedParams as any
118+
}),
119+
/missing path parameter ":userId"/
120+
)
121+
})
122+
123+
it("validates prefixed paths across endpoint, group, and api prefixing", () => {
124+
const post = HttpApiEndpoint.get("getPost", "/posts/:postId", {
125+
params: { postId: Schema.String }
126+
})
127+
128+
assert.throws(() => post.prefix("/users/:userId"), /missing path parameter ":userId"/)
129+
assert.throws(
130+
() => HttpApiGroup.make("posts").add(post).prefix("/users/:userId"),
131+
/missing path parameter ":userId"/
132+
)
133+
assert.throws(
134+
() => HttpApi.make("api").add(HttpApiGroup.make("posts").add(post)).prefix("/users/:userId"),
135+
/missing path parameter ":userId"/
136+
)
137+
138+
HttpApiEndpoint.get("getPost", "/posts/:postId", {
139+
params: { userId: Schema.String, postId: Schema.String }
140+
}).prefix("/users/:userId")
141+
})
142+
143+
it("allows omitted params, regex slashes, literal suffixes, mid-segment placeholders, and open schemas", () => {
144+
HttpApiEndpoint.get("raw", "/users/:id").prefix("/tenants/:tenantId")
145+
HttpApiEndpoint.get("regexSlash", "/:id([^/:x.]+)", { params: { id: Schema.String } })
146+
HttpApiEndpoint.post("resolve", "/offers:resolve", { params: {} })
147+
HttpApiEndpoint.post("wait", "/operations/:id:wait", { params: { id: Schema.String } })
148+
HttpApiEndpoint.get("ext", "/file.:ext", { params: {} })
149+
HttpApiEndpoint.get("compound", "/:a-:b", { params: { a: Schema.String } })
150+
HttpApiEndpoint.get("escaped", "/users/::literal", { params: {} })
151+
HttpApiEndpoint.get("nonWord", "/x/:a$b", { params: {} })
152+
HttpApiEndpoint.get("wildcard", "/*", { params: {} })
153+
HttpApiEndpoint.get("record", "/users/:id", { params: Schema.Record(Schema.String, Schema.String) })
154+
HttpApiEndpoint.get("patternedRecord", "/users/:id", {
155+
params: Schema.Record(Schema.TemplateLiteral(["x", Schema.String]), Schema.String)
156+
})
157+
HttpApiEndpoint.get("union", "/users/:a", {
158+
params: Schema.Union([Schema.Struct({ a: Schema.String }), Schema.Struct({ b: Schema.String })])
159+
})
160+
})
161+
})
162+
48163
describe("HttpApiEndpoint payload schemas", () => {
49164
it("normalizes payload map keys while preserving the declared content type", () => {
50165
const contentType = "Application/Vnd.Effect+JSON; Charset=UTF-8"

0 commit comments

Comments
 (0)