Skip to content

Commit bf93f0b

Browse files
authored
Merge pull request DeusData#2471 from DeusData/fix/laravel-slashless-route-paths
fix(routes): mint Laravel routes written without a leading slash
2 parents d19cab8 + b95d628 commit bf93f0b

2 files changed

Lines changed: 309 additions & 2 deletions

File tree

‎internal/cbm/extract_calls.c‎

Lines changed: 150 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1763,6 +1763,59 @@ static const char *php_chain_prefix_arg(CBMArena *a, TSNode call_node, const cha
17631763
return NULL;
17641764
}
17651765

1766+
/* The value of a plain PHP string literal ('...' or "..." with no
1767+
* interpolation or escapes), "" for an empty one; NULL for anything else. */
1768+
static const char *php_plain_string_value(CBMArena *a, TSNode node, const char *source) {
1769+
const char *kind = ts_node_type(node);
1770+
if (strcmp(kind, "string") != 0 && strcmp(kind, "encapsed_string") != 0) {
1771+
return NULL;
1772+
}
1773+
uint32_t nc = ts_node_named_child_count(node);
1774+
for (uint32_t i = 0; i < nc; i++) {
1775+
if (strcmp(ts_node_type(ts_node_named_child(node, i)), "string_content") != 0) {
1776+
return NULL;
1777+
}
1778+
}
1779+
return nc == 0 ? "" : cbm_node_text(a, ts_node_named_child(node, 0), source);
1780+
}
1781+
1782+
/* The first argument's value node of a PHP call (unwrapping `argument`). */
1783+
static TSNode php_first_arg_value(TSNode call_node) {
1784+
TSNode none = {0};
1785+
TSNode args = ts_node_child_by_field_name(call_node, TS_FIELD("arguments"));
1786+
if (ts_node_is_null(args) || ts_node_named_child_count(args) == 0) {
1787+
return none;
1788+
}
1789+
TSNode arg = ts_node_named_child(args, 0);
1790+
if (strcmp(ts_node_type(arg), "argument") == 0) {
1791+
return ts_node_named_child_count(arg) == SKIP_ONE ? ts_node_named_child(arg, 0) : none;
1792+
}
1793+
return arg;
1794+
}
1795+
1796+
/* The literal 'prefix' of an attribute-array group (#1146):
1797+
* Route::group(['prefix' => 'v1/autocomplete', 'as' => ...], function () {...}),
1798+
* the form Firefly III's whole API is written in. */
1799+
static const char *php_group_array_prefix(CBMArena *a, TSNode group_call, const char *source) {
1800+
TSNode attrs = php_first_arg_value(group_call);
1801+
if (ts_node_is_null(attrs) || strcmp(ts_node_type(attrs), "array_creation_expression") != 0) {
1802+
return NULL;
1803+
}
1804+
uint32_t nc = ts_node_named_child_count(attrs);
1805+
for (uint32_t i = 0; i < nc; i++) {
1806+
TSNode el = ts_node_named_child(attrs, i);
1807+
if (strcmp(ts_node_type(el), "array_element_initializer") != 0 ||
1808+
ts_node_named_child_count(el) != PAIR_LEN) {
1809+
continue;
1810+
}
1811+
const char *key = php_plain_string_value(a, ts_node_named_child(el, 0), source);
1812+
if (key && strcmp(key, "prefix") == 0) {
1813+
return php_plain_string_value(a, ts_node_named_child(el, SKIP_ONE), source);
1814+
}
1815+
}
1816+
return NULL;
1817+
}
1818+
17661819
static const char *php_group_prefix_for_call(CBMArena *a, TSNode node, const char *source) {
17671820
const char *parts[PHP_PREFIX_PARTS_MAX];
17681821
int part_count = 0;
@@ -1785,7 +1838,14 @@ static const char *php_group_prefix_for_call(CBMArena *a, TSNode node, const cha
17851838
strcmp(ts_node_type(p), "scoped_call_expression") == 0)) {
17861839
TSNode gname = ts_node_child_by_field_name(p, TS_FIELD("name"));
17871840
char *gtxt = ts_node_is_null(gname) ? NULL : cbm_node_text(a, gname, source);
1788-
if (gtxt && strcmp(gtxt, "group") == 0) {
1841+
const char *array_prefix = gtxt && strcmp(gtxt, "group") == 0
1842+
? php_group_array_prefix(a, p, source)
1843+
: NULL;
1844+
if (array_prefix) {
1845+
if (part_count < PHP_PREFIX_PARTS_MAX) {
1846+
parts[part_count++] = array_prefix; /* inner-first */
1847+
}
1848+
} else if (gtxt && strcmp(gtxt, "group") == 0) {
17891849
/* Scan the receiver chain for prefix('...'). */
17901850
TSNode recv = ts_node_child_by_field_name(p, TS_FIELD("object"));
17911851
for (int hops = 0; hops < PHP_GROUP_WALK_MAX && !ts_node_is_null(recv);
@@ -1843,6 +1903,81 @@ static const char *php_group_prefix_for_call(CBMArena *a, TSNode node, const cha
18431903
return pos ? cbm_arena_strndup(a, buf, pos) : NULL;
18441904
}
18451905

1906+
/* A Laravel route registrar receiver (#1146): the Route facade — also at the
1907+
* root of a registrar chain, Route::middleware('auth')->get(...) — or the
1908+
* $router instance route files are loaded with (RouteServiceProvider, Lumen).
1909+
* The same literal `Route` scope the #952 callee qualification accepts. */
1910+
static bool php_is_laravel_registrar(CBMArena *a, TSNode call_node, const char *source) {
1911+
TSNode cur = call_node;
1912+
for (int hops = 0; hops < PHP_GROUP_WALK_MAX && !ts_node_is_null(cur); hops++) {
1913+
const char *kind = ts_node_type(cur);
1914+
if (strcmp(kind, "scoped_call_expression") == 0) {
1915+
TSNode scope = ts_node_child_by_field_name(cur, TS_FIELD("scope"));
1916+
const char *st = ts_node_is_null(scope) ? NULL : cbm_node_text(a, scope, source);
1917+
return st && strcmp(st, "Route") == 0;
1918+
}
1919+
if (strcmp(kind, "variable_name") == 0) {
1920+
const char *vt = cbm_node_text(a, cur, source);
1921+
return vt && strcmp(vt, "$router") == 0;
1922+
}
1923+
if (strcmp(kind, "member_call_expression") != 0) {
1924+
return false;
1925+
}
1926+
cur = ts_node_child_by_field_name(cur, TS_FIELD("object"));
1927+
}
1928+
return false;
1929+
}
1930+
1931+
/* Laravel accepts a route URI with or without its leading slash and trims
1932+
* '/' from both ends: Route::get('users', ...) serves /users, and '' is the
1933+
* group root. The route passes only mint a Route for a path that starts with
1934+
* '/', so give a recognised registration's literal URI its slash here, where
1935+
* the first argument is still at hand (#1146). Returns NULL — leave the call
1936+
* alone — for any other call, any non-literal URI, or one already slashed:
1937+
* `$request->get('name')`, `Cache::get('key')` and a collection's get('k')
1938+
* keep their argument. */
1939+
static const char *php_laravel_route_uri(CBMArena *a, TSNode call_node, const char *source) {
1940+
static const char *const verbs[] = {"get", "post", "put", "patch", "delete", NULL};
1941+
TSNode mname = ts_node_child_by_field_name(call_node, TS_FIELD("name"));
1942+
const char *verb = ts_node_is_null(mname) ? NULL : cbm_node_text(a, mname, source);
1943+
bool is_verb = false;
1944+
for (int i = 0; verb && verbs[i] && !is_verb; i++) {
1945+
is_verb = strcmp(verb, verbs[i]) == 0;
1946+
}
1947+
if (!is_verb || !php_is_laravel_registrar(a, call_node, source)) {
1948+
return NULL;
1949+
}
1950+
TSNode arg0 = php_first_arg_value(call_node);
1951+
const char *uri = ts_node_is_null(arg0) ? NULL : php_plain_string_value(a, arg0, source);
1952+
if (!uri || uri[0] == '/') {
1953+
return NULL;
1954+
}
1955+
size_t len = strlen(uri);
1956+
while (len > 0 && uri[len - SKIP_ONE] == '/') {
1957+
len--;
1958+
}
1959+
return cbm_arena_sprintf(a, "/%.*s", (int)len, uri);
1960+
}
1961+
1962+
/* Is a Laravel registration's action (its last argument) a string — 'index'
1963+
* inside a Route::controller() group, 'UserController@show'? Such an action
1964+
* does not say which class owns the method, so resolving it could only guess a
1965+
* same-named function anywhere in the repo. */
1966+
static bool php_route_action_is_string(TSNode call_node) {
1967+
TSNode args = ts_node_child_by_field_name(call_node, TS_FIELD("arguments"));
1968+
uint32_t nc = ts_node_is_null(args) ? 0 : ts_node_named_child_count(args);
1969+
if (nc < PAIR_LEN) {
1970+
return false;
1971+
}
1972+
TSNode action = ts_node_named_child(args, nc - SKIP_ONE);
1973+
if (strcmp(ts_node_type(action), "argument") == 0 &&
1974+
ts_node_named_child_count(action) == SKIP_ONE) {
1975+
action = ts_node_named_child(action, 0);
1976+
}
1977+
const char *kind = ts_node_type(action);
1978+
return strcmp(kind, "string") == 0 || strcmp(kind, "encapsed_string") == 0;
1979+
}
1980+
18461981
static bool is_nested_verilog_call_wrapper(CBMLanguage lang, TSNode node) {
18471982
if (lang != CBM_LANG_VERILOG || strcmp(ts_node_type(node), "subroutine_call") != 0) {
18481983
return false;
@@ -3941,6 +4076,16 @@ CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBML
39414076
}
39424077
if (!ts_node_is_null(args)) {
39434078
call.first_string_arg = extract_url_or_topic_arg(ctx, args, call.callee_name);
4079+
/* #1146: a Laravel registration's slashless URI ('users', '')
4080+
* becomes '/users' / '/' so it mints and composes below. */
4081+
const char *laravel_uri = NULL;
4082+
if (ctx->language == CBM_LANG_PHP && call.callee_name &&
4083+
cbm_service_pattern_route_method(call.callee_name) != NULL) {
4084+
laravel_uri = php_laravel_route_uri(ctx->arena, node, ctx->source);
4085+
if (laravel_uri) {
4086+
call.first_string_arg = laravel_uri;
4087+
}
4088+
}
39444089
/* #952: routes registered inside Laravel `prefix()->group()`
39454090
* closures must carry the composed path — the resolve passes
39464091
* only see the flat CBMCall, so the enclosing chain can only
@@ -3959,7 +4104,10 @@ CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBML
39594104
: cbm_arena_strndup(ctx->arena, gp, strlen(gp));
39604105
}
39614106
}
3962-
if (call.first_string_arg && call.first_string_arg[0] == '/') {
4107+
/* A slashless registration's string action would only be
4108+
* guessed at (#1146): mint its Route without a handler. */
4109+
if (call.first_string_arg && call.first_string_arg[0] == '/' &&
4110+
!(laravel_uri && php_route_action_is_string(node))) {
39634111
call.second_arg_name = extract_handler_arg(ctx, args);
39644112
}
39654113
if (ctx->language == CBM_LANG_OBJECTSCRIPT_UDL ||

‎tests/test_edge_types_probe.c‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -922,6 +922,161 @@ TEST(routes_laravel_withrouting_parallel_subdir_issue1146) {
922922
PASS();
923923
}
924924

925+
/* Assert the exact Route set as "METHOD /path" strings: the method comes from
926+
* the Route QN ("__route__PUT__/articles/{}"), the path from the node name
927+
* (the raw composed path). The count must match too, so a junk Route fails. */
928+
static int et_route_set_exact(const EtFile *files, int nfiles, const char **want, int parallel) {
929+
EtProj lp;
930+
cbm_store_t *store =
931+
parallel ? et_index_parallel(&lp, files, nfiles) : et_index_files(&lp, files, nfiles);
932+
cbm_node_t *nodes = NULL;
933+
int node_count = 0;
934+
int wanted = 0;
935+
int found[ET_ROUTE_ASSERT_MAX] = {0};
936+
while (want[wanted] && wanted < ET_ROUTE_ASSERT_MAX) {
937+
wanted++;
938+
}
939+
int ok = store != NULL &&
940+
cbm_store_find_nodes_by_label(store, lp.project, "Route", &nodes, &node_count) ==
941+
CBM_STORE_OK &&
942+
node_count == wanted;
943+
for (int ni = 0; store && ni < node_count; ni++) {
944+
char got[512];
945+
const char *qn = nodes[ni].qualified_name ? nodes[ni].qualified_name : "";
946+
const char *m = strncmp(qn, "__route__", 9) == 0 ? qn + 9 : qn;
947+
const char *end = strstr(m, "__");
948+
snprintf(got, sizeof(got), "%.*s %s", end ? (int)(end - m) : 0, m,
949+
nodes[ni].name ? nodes[ni].name : "");
950+
int matched = 0;
951+
for (int wi = 0; wi < wanted; wi++) {
952+
if (!found[wi] && strcmp(got, want[wi]) == 0) {
953+
found[wi] = matched = 1;
954+
break;
955+
}
956+
}
957+
if (!matched) {
958+
ok = 0;
959+
fprintf(stderr, " [ET-ROUTESET] unexpected %s\n", got);
960+
}
961+
}
962+
for (int wi = 0; wi < wanted; wi++) {
963+
if (!found[wi]) {
964+
ok = 0;
965+
fprintf(stderr, " [ET-ROUTESET] missing %s\n", want[wi]);
966+
}
967+
}
968+
if (!ok) {
969+
fprintf(stderr, " [ET-ROUTESET] FAIL (%s path) expected=%d actual=%d\n",
970+
parallel ? "parallel" : "sequential", wanted, node_count);
971+
}
972+
cbm_store_free_nodes(nodes, node_count);
973+
et_cleanup(&lp, store);
974+
return ok;
975+
}
976+
977+
/* #1146: Laravel writes most route URIs without the leading slash —
978+
* Route::get('users', ...) serves /users, Route::put('{article}', ...) inside
979+
* prefix('articles') serves /articles/{article}, and '' is the group root.
980+
* Both route passes only minted a Route for a first argument starting with
981+
* '/', so Firefly III's API (258 registrations) and laravel.io's PUT/DELETE
982+
* API routes had no Route at all. Covers the facade, a facade chain
983+
* (Route::middleware()->get), the $router instance, the chain-form and the
984+
* array-form prefix group (Route::group(['prefix' => ...], fn)), and a
985+
* trailing slash. */
986+
static const EtFile et_laravel_slashless[] = {
987+
{"routes/api.php",
988+
"<?php\nuse Illuminate\\Support\\Facades\\Route;\n\n"
989+
"Route::get('users', 'UserController@index');\n"
990+
"Route::post('users/', 'UserController@store');\n"
991+
"Route::prefix('articles')->group(function () {\n"
992+
" Route::get('', 'ArticlesController@index');\n"
993+
" Route::put('{article}', 'ArticlesController@update');\n"
994+
" Route::delete('{article}', 'ArticlesController@delete');\n"
995+
"});\n"
996+
"Route::group(['prefix' => 'v1/autocomplete', 'as' => 'api.v1.'], static function (): void {\n"
997+
" Route::get('accounts', ['uses' => 'AccountController@accounts', 'as' => 'accounts']);\n"
998+
"});\n"
999+
"Route::middleware('auth')->get('dashboard', 'DashboardController@show');\n"
1000+
"$router->get('lumen/users', 'UserController@index');\n"}};
1001+
1002+
static const char *et_laravel_slashless_routes[] = {"GET /users",
1003+
"POST /users",
1004+
"GET /articles",
1005+
"PUT /articles/{article}",
1006+
"DELETE /articles/{article}",
1007+
"GET /v1/autocomplete/accounts",
1008+
"GET /dashboard",
1009+
"GET /lumen/users",
1010+
NULL};
1011+
1012+
TEST(routes_laravel_slashless_issue1146) {
1013+
ASSERT_TRUE(et_route_set_exact(et_laravel_slashless, 1, et_laravel_slashless_routes, 0));
1014+
PASS();
1015+
}
1016+
1017+
TEST(routes_laravel_slashless_parallel_issue1146) {
1018+
ASSERT_TRUE(et_route_set_exact(et_laravel_slashless, 1, et_laravel_slashless_routes, 1));
1019+
PASS();
1020+
}
1021+
1022+
/* The string action of a slashless registration — 'index' inside a
1023+
* Route::controller() group, 'UserController@store' — does not say which
1024+
* class owns the method, so resolving it could only guess a same-named
1025+
* function anywhere in the repo (on krayin/laravel-crm 'update' and 'destroy'
1026+
* bound a chart.js function). Such routes are minted without a guessed
1027+
* HANDLES edge. Decoys: a JS function and a PHP method per action name. */
1028+
TEST(routes_laravel_slashless_no_guessed_handlers_issue1146) {
1029+
static const char *want[] = {"GET /leads", "PUT /leads/edit/{id}", "POST /users", NULL};
1030+
static const EtFile f[] = {
1031+
{"routes/web.php",
1032+
"<?php\nuse Illuminate\\Support\\Facades\\Route;\n\n"
1033+
"Route::controller(LeadController::class)->prefix('leads')->group(function () {\n"
1034+
" Route::get('', 'index');\n"
1035+
" Route::put('edit/{id}', 'update');\n"
1036+
"});\n"
1037+
"Route::post('users', 'UserController@store');\n"},
1038+
{"resources/js/chart.js",
1039+
"function index() { return 1; }\nfunction update() { return 2; }\n"},
1040+
{"app/Http/Controllers/ActivityController.php",
1041+
"<?php\nnamespace App\\Http\\Controllers;\n\n"
1042+
"class ActivityController {\n public function store() { return 1; }\n}\n"}};
1043+
ASSERT_TRUE(et_route_set_exact(f, 3, want, 0));
1044+
EtProj lp;
1045+
cbm_store_t *store = et_index_files(&lp, f, 3);
1046+
int handles = store ? cbm_store_count_edges_by_type(store, lp.project, "HANDLES") : -1;
1047+
et_cleanup(&lp, store);
1048+
ASSERT_EQ(handles, 0);
1049+
PASS();
1050+
}
1051+
1052+
/* Precision guard for the slashless form: only a Laravel route registration
1053+
* (the Route facade, or $router) has its URI normalised. A string first
1054+
* argument of any other get/post call — a request input, a cache key, config,
1055+
* a collection or session lookup, a property that merely holds a router, a
1056+
* test client call — stays what it is and mints no Route. */
1057+
TEST(routes_laravel_slashless_no_junk_issue1146) {
1058+
static const char *want[] = {"GET /real", NULL};
1059+
static const EtFile f[] = {
1060+
{"routes/web.php",
1061+
"<?php\nuse Illuminate\\Support\\Facades\\Route;\n"
1062+
"use Illuminate\\Support\\Facades\\Cache;\n\n"
1063+
"Route::get('real', 'RealController@show');\n\n"
1064+
"class UsersController {\n"
1065+
" public function index($request) {\n"
1066+
" $name = $request->get('name');\n"
1067+
" $q = $request->query->get('q');\n"
1068+
" $v = Cache::get('users.count');\n"
1069+
" $c = config('app.name');\n"
1070+
" $k = collect(['a' => 1])->get('a');\n"
1071+
" $s = session()->get('key');\n"
1072+
" $r = $this->router->get('status');\n"
1073+
" $p = $this->post('login', []);\n"
1074+
" return $this->get('users');\n"
1075+
" }\n}\n"}};
1076+
ASSERT_TRUE(et_route_set_exact(f, 1, want, 0));
1077+
PASS();
1078+
}
1079+
9251080
/* Rails (Ruby) — ActionDispatch router. The handler MUST be passed as a bare
9261081
* identifier (not the idiomatic `to: 'list_items'` string, which extract_handler_arg
9271082
* cannot capture). mapper.get resolves by name to the Mapper#get method whose QN
@@ -2138,6 +2293,10 @@ SUITE(edge_types_probe) {
21382293
RUN_TEST(routes_laravel_routeserviceprovider_control_issue1146);
21392294
RUN_TEST(routes_laravel_withrouting_nonliteral_prefix_issue1146);
21402295
RUN_TEST(routes_laravel_withrouting_parallel_subdir_issue1146);
2296+
RUN_TEST(routes_laravel_slashless_issue1146);
2297+
RUN_TEST(routes_laravel_slashless_parallel_issue1146);
2298+
RUN_TEST(routes_laravel_slashless_no_guessed_handlers_issue1146);
2299+
RUN_TEST(routes_laravel_slashless_no_junk_issue1146);
21412300
RUN_TEST(handles_rails_ruby);
21422301
RUN_TEST(handles_actix_rust);
21432302

0 commit comments

Comments
 (0)