Skip to content

Commit

Permalink
fix: Root table validation should return 400 (#1975)
Browse files Browse the repository at this point in the history
When root table is missing it should return 400 with the correct
message. Currently it is returning 500 which would lead to clients
retrying even through the request is malformed.
  • Loading branch information
msfstef authored Nov 14, 2024
1 parent 31414f6 commit d98d9ed
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/dirty-wolves-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@core/sync-service": patch
---

Fix root table parameter validation to return 400 when missing
2 changes: 2 additions & 0 deletions packages/sync-service/lib/electric/plug/serve_shape_plug.ex
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ defmodule Electric.Plug.ServeShapePlug do
end
end

def cast_root_table(%Ecto.Changeset{valid?: false} = changeset, _), do: changeset

def cast_root_table(%Ecto.Changeset{} = changeset, opts) do
table = fetch_change!(changeset, :table)
where = fetch_field!(changeset, :where)
Expand Down
27 changes: 24 additions & 3 deletions packages/sync-service/test/electric/plug/serve_shape_plug_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -152,22 +152,43 @@ defmodule Electric.Plug.ServeShapePlugTest do
:with_tenant_id
]

test "returns 400 for invalid params", ctx do
test "returns 400 for invalid table", ctx do
conn =
ctx
|> conn(:get, %{"table" => ".invalid_shape"}, "?offset=invalid")
|> conn(:get, %{"table" => ".invalid_shape"}, "?offset=-1")
|> ServeShapePlug.call([])

assert conn.status == 400

assert Jason.decode!(conn.resp_body) == %{
"offset" => ["has invalid format"],
"table" => [
"Invalid zero-length delimited identifier"
]
}
end

test "returns 400 for invalid offset", ctx do
conn =
ctx
|> conn(:get, %{"table" => "foo"}, "?offset=invalid")
|> ServeShapePlug.call([])

assert conn.status == 400

assert Jason.decode!(conn.resp_body) == %{"offset" => ["has invalid format"]}
end

test "returns 400 when table param is missing", ctx do
conn =
ctx
|> conn(:get, %{}, "?offset=-1")
|> ServeShapePlug.call([])

assert conn.status == 400

assert %{"table" => ["can't be blank"]} = Jason.decode!(conn.resp_body)
end

test "returns 400 when table does not exist", ctx do
# this will pass table name validation
# but will fail to find the table
Expand Down

0 comments on commit d98d9ed

Please sign in to comment.