mirror of
https://github.com/bitechdev/ResolveSpec.git
synced 2026-08-28 20:12:35 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dab4940ace | ||
|
|
c7178e0a2b | ||
|
|
0261f121e8 | ||
|
|
93dc1008ee | ||
|
|
c60565e4e0 |
@@ -1040,3 +1040,21 @@ func BuildInCondition(column string, v interface{}) (query string, args []interf
|
||||
}
|
||||
return fmt.Sprintf("%s IN (%s)", column, strings.Join(placeholders, ",")), values
|
||||
}
|
||||
|
||||
// BuildArrayOverlapCondition builds a parameterized condition testing whether an
|
||||
// array column has at least one element in common with the given value(s), using
|
||||
// PostgreSQL's array overlap operator (&&). Unlike a text-cast ILIKE, this performs
|
||||
// real element-wise containment (no substring false positives) and can use a GIN
|
||||
// index on the column. A single value is treated as a one-element array.
|
||||
// Returns ("", nil) if the value is empty.
|
||||
func BuildArrayOverlapCondition(column string, v interface{}) (query string, args []interface{}) {
|
||||
values := FilterValueToSlice(v)
|
||||
if len(values) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
placeholders := make([]string, len(values))
|
||||
for i := range values {
|
||||
placeholders[i] = "?"
|
||||
}
|
||||
return fmt.Sprintf("%s && ARRAY[%s]", column, strings.Join(placeholders, ",")), values
|
||||
}
|
||||
|
||||
+147
-89
@@ -542,8 +542,8 @@ func TestSplitByAND(t *testing.T) {
|
||||
expected: []string{"col1 between 1 and 5", "col2 between 10 and 20"},
|
||||
},
|
||||
{
|
||||
name: "complex OR block with multiple BETWEENs (real-world case)",
|
||||
input: "tbl.applicationdate between '2025-08-31' and '1970-01-01'\n or tbl.capturedate between '2025-08-31' and '1970-01-01'\n or tbl.startdate between '2025-08-31' AND '1970-01-01'",
|
||||
name: "complex OR block with multiple BETWEENs (real-world case)",
|
||||
input: "tbl.applicationdate between '2025-08-31' and '1970-01-01'\n or tbl.capturedate between '2025-08-31' and '1970-01-01'\n or tbl.startdate between '2025-08-31' AND '1970-01-01'",
|
||||
expected: []string{"tbl.applicationdate between '2025-08-31' and '1970-01-01'\n or tbl.capturedate between '2025-08-31' and '1970-01-01'\n or tbl.startdate between '2025-08-31' AND '1970-01-01'"},
|
||||
},
|
||||
// Quote-aware cases: AND inside a string literal must not split.
|
||||
@@ -889,93 +889,151 @@ func TestSanitizeWhereClause_PreservesParenthesesWithOR(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAddTablePrefixToColumns_ComplexConditions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
where string
|
||||
tableName string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "Parentheses with true AND condition - should not prefix true",
|
||||
where: "(true AND status = 'active')",
|
||||
tableName: "mastertask",
|
||||
expected: "(true AND mastertask.status = 'active')",
|
||||
},
|
||||
{
|
||||
name: "Parentheses with multiple conditions including true",
|
||||
where: "(true AND status = 'active' AND id > 5)",
|
||||
tableName: "mastertask",
|
||||
expected: "(true AND mastertask.status = 'active' AND mastertask.id > 5)",
|
||||
},
|
||||
{
|
||||
name: "Nested parentheses with true",
|
||||
where: "((true AND status = 'active'))",
|
||||
tableName: "mastertask",
|
||||
expected: "((true AND mastertask.status = 'active'))",
|
||||
},
|
||||
{
|
||||
name: "Mixed: false AND valid conditions",
|
||||
where: "(false AND name = 'test')",
|
||||
tableName: "mastertask",
|
||||
expected: "(false AND mastertask.name = 'test')",
|
||||
},
|
||||
{
|
||||
name: "Mixed: null AND valid conditions",
|
||||
where: "(null AND status = 'active')",
|
||||
tableName: "mastertask",
|
||||
expected: "(null AND mastertask.status = 'active')",
|
||||
},
|
||||
{
|
||||
name: "Multiple true conditions in parentheses",
|
||||
where: "(true AND true AND status = 'active')",
|
||||
tableName: "mastertask",
|
||||
expected: "(true AND true AND mastertask.status = 'active')",
|
||||
},
|
||||
{
|
||||
name: "Simple true without parens - should not prefix",
|
||||
where: "true",
|
||||
tableName: "mastertask",
|
||||
expected: "true",
|
||||
},
|
||||
{
|
||||
name: "Simple condition without parens - should prefix",
|
||||
where: "status = 'active'",
|
||||
tableName: "mastertask",
|
||||
expected: "mastertask.status = 'active'",
|
||||
},
|
||||
{
|
||||
name: "Unregistered table with true - should not prefix true",
|
||||
where: "(true AND status = 'active')",
|
||||
tableName: "unregistered_table",
|
||||
expected: "(true AND unregistered_table.status = 'active')",
|
||||
},
|
||||
// BETWEEN regression: date literals inside BETWEEN must not be prefixed as columns.
|
||||
{
|
||||
name: "BETWEEN date range - second date must not be prefixed",
|
||||
where: "applicationdate between '2025-08-31' and '1970-01-01'",
|
||||
tableName: "unregistered_table",
|
||||
expected: "unregistered_table.applicationdate between '2025-08-31' and '1970-01-01'",
|
||||
},
|
||||
{
|
||||
name: "Already-prefixed BETWEEN column - unchanged",
|
||||
where: `"v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01'`,
|
||||
tableName: "v_webui_clients",
|
||||
expected: `"v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01'`,
|
||||
},
|
||||
{
|
||||
name: "Complex OR block with multiple BETWEENs - date values must not be prefixed",
|
||||
where: `("v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01' or "v_webui_clients".clientcapturedate between '2025-08-31' and '1970-01-01' or "v_webui_clients".startdate between '2025-08-31' AND '1970-01-01')`,
|
||||
tableName: "v_webui_clients",
|
||||
expected: `("v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01' or "v_webui_clients".clientcapturedate between '2025-08-31' and '1970-01-01' or "v_webui_clients".startdate between '2025-08-31' AND '1970-01-01')`,
|
||||
},
|
||||
tests := []struct {
|
||||
name string
|
||||
where string
|
||||
tableName string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "Parentheses with true AND condition - should not prefix true",
|
||||
where: "(true AND status = 'active')",
|
||||
tableName: "mastertask",
|
||||
expected: "(true AND mastertask.status = 'active')",
|
||||
},
|
||||
{
|
||||
name: "Parentheses with multiple conditions including true",
|
||||
where: "(true AND status = 'active' AND id > 5)",
|
||||
tableName: "mastertask",
|
||||
expected: "(true AND mastertask.status = 'active' AND mastertask.id > 5)",
|
||||
},
|
||||
{
|
||||
name: "Nested parentheses with true",
|
||||
where: "((true AND status = 'active'))",
|
||||
tableName: "mastertask",
|
||||
expected: "((true AND mastertask.status = 'active'))",
|
||||
},
|
||||
{
|
||||
name: "Mixed: false AND valid conditions",
|
||||
where: "(false AND name = 'test')",
|
||||
tableName: "mastertask",
|
||||
expected: "(false AND mastertask.name = 'test')",
|
||||
},
|
||||
{
|
||||
name: "Mixed: null AND valid conditions",
|
||||
where: "(null AND status = 'active')",
|
||||
tableName: "mastertask",
|
||||
expected: "(null AND mastertask.status = 'active')",
|
||||
},
|
||||
{
|
||||
name: "Multiple true conditions in parentheses",
|
||||
where: "(true AND true AND status = 'active')",
|
||||
tableName: "mastertask",
|
||||
expected: "(true AND true AND mastertask.status = 'active')",
|
||||
},
|
||||
{
|
||||
name: "Simple true without parens - should not prefix",
|
||||
where: "true",
|
||||
tableName: "mastertask",
|
||||
expected: "true",
|
||||
},
|
||||
{
|
||||
name: "Simple condition without parens - should prefix",
|
||||
where: "status = 'active'",
|
||||
tableName: "mastertask",
|
||||
expected: "mastertask.status = 'active'",
|
||||
},
|
||||
{
|
||||
name: "Unregistered table with true - should not prefix true",
|
||||
where: "(true AND status = 'active')",
|
||||
tableName: "unregistered_table",
|
||||
expected: "(true AND unregistered_table.status = 'active')",
|
||||
},
|
||||
// BETWEEN regression: date literals inside BETWEEN must not be prefixed as columns.
|
||||
{
|
||||
name: "BETWEEN date range - second date must not be prefixed",
|
||||
where: "applicationdate between '2025-08-31' and '1970-01-01'",
|
||||
tableName: "unregistered_table",
|
||||
expected: "unregistered_table.applicationdate between '2025-08-31' and '1970-01-01'",
|
||||
},
|
||||
{
|
||||
name: "Already-prefixed BETWEEN column - unchanged",
|
||||
where: `"v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01'`,
|
||||
tableName: "v_webui_clients",
|
||||
expected: `"v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01'`,
|
||||
},
|
||||
{
|
||||
name: "Complex OR block with multiple BETWEENs - date values must not be prefixed",
|
||||
where: `("v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01' or "v_webui_clients".clientcapturedate between '2025-08-31' and '1970-01-01' or "v_webui_clients".startdate between '2025-08-31' AND '1970-01-01')`,
|
||||
tableName: "v_webui_clients",
|
||||
expected: `("v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01' or "v_webui_clients".clientcapturedate between '2025-08-31' and '1970-01-01' or "v_webui_clients".startdate between '2025-08-31' AND '1970-01-01')`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := AddTablePrefixToColumns(tt.where, tt.tableName)
|
||||
if result != tt.expected {
|
||||
t.Errorf("AddTablePrefixToColumns(%q, %q) = %q; want %q", tt.where, tt.tableName, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := AddTablePrefixToColumns(tt.where, tt.tableName)
|
||||
if result != tt.expected {
|
||||
t.Errorf("AddTablePrefixToColumns(%q, %q) = %q; want %q", tt.where, tt.tableName, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
func TestBuildArrayOverlapCondition(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
column string
|
||||
value interface{}
|
||||
expectedCond string
|
||||
expectedArgs int
|
||||
}{
|
||||
{
|
||||
name: "single scalar value",
|
||||
column: "tags",
|
||||
value: "urgent",
|
||||
expectedCond: "tags && ARRAY[?]",
|
||||
expectedArgs: 1,
|
||||
},
|
||||
{
|
||||
name: "multiple values",
|
||||
column: "tags",
|
||||
value: []string{"urgent", "billing", "vip"},
|
||||
expectedCond: "tags && ARRAY[?,?,?]",
|
||||
expectedArgs: 3,
|
||||
},
|
||||
{
|
||||
name: "JSON-decoded []interface{} value",
|
||||
column: "tags",
|
||||
value: []interface{}{"urgent", "billing"},
|
||||
expectedCond: "tags && ARRAY[?,?]",
|
||||
expectedArgs: 2,
|
||||
},
|
||||
{
|
||||
name: "nil value",
|
||||
column: "tags",
|
||||
value: nil,
|
||||
expectedCond: "",
|
||||
expectedArgs: 0,
|
||||
},
|
||||
{
|
||||
name: "empty slice value",
|
||||
column: "tags",
|
||||
value: []string{},
|
||||
expectedCond: "",
|
||||
expectedArgs: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cond, args := BuildArrayOverlapCondition(tt.column, tt.value)
|
||||
if cond != tt.expectedCond {
|
||||
t.Errorf("BuildArrayOverlapCondition(%q, %v) condition = %q; want %q", tt.column, tt.value, cond, tt.expectedCond)
|
||||
}
|
||||
if len(args) != tt.expectedArgs {
|
||||
t.Errorf("BuildArrayOverlapCondition(%q, %v) args = %d; want %d", tt.column, tt.value, len(args), tt.expectedArgs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ func (h *Handler) ParseParameters(r *http.Request) *RequestParameters {
|
||||
FieldFilters: make(map[string]string),
|
||||
SearchFilters: make(map[string]string),
|
||||
SearchOps: make(map[string]FilterOperator),
|
||||
Limit: 20, // Default limit
|
||||
Limit: 100000, // Default limit
|
||||
Offset: 0, // Default offset
|
||||
ResponseFormat: "simple", // Default format
|
||||
ComplexAPI: false, // Default to simple API
|
||||
|
||||
@@ -57,6 +57,36 @@ func TestBuildFilterCondition(t *testing.T) {
|
||||
expectedCondition: "CAST(email AS TEXT) LIKE ?",
|
||||
expectedArgsCount: 1,
|
||||
},
|
||||
{
|
||||
name: "CONTAINS operator with single value",
|
||||
filter: common.FilterOption{
|
||||
Column: "tags",
|
||||
Operator: "contains",
|
||||
Value: "urgent",
|
||||
},
|
||||
expectedCondition: "tags && ARRAY[?]",
|
||||
expectedArgsCount: 1,
|
||||
},
|
||||
{
|
||||
name: "CONTAINS operator with multiple values",
|
||||
filter: common.FilterOption{
|
||||
Column: "tags",
|
||||
Operator: "contains",
|
||||
Value: []string{"urgent", "billing"},
|
||||
},
|
||||
expectedCondition: "tags && ARRAY[?,?]",
|
||||
expectedArgsCount: 2,
|
||||
},
|
||||
{
|
||||
name: "CONTAINS operator with empty value",
|
||||
filter: common.FilterOption{
|
||||
Column: "tags",
|
||||
Operator: "contains",
|
||||
Value: nil,
|
||||
},
|
||||
expectedCondition: "",
|
||||
expectedArgsCount: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -1895,6 +1895,11 @@ func (h *Handler) buildFilterCondition(filter common.FilterOption) (conditionStr
|
||||
if condition == "" {
|
||||
return "", nil
|
||||
}
|
||||
case "contains":
|
||||
condition, args = common.BuildArrayOverlapCondition(filter.Column, filter.Value)
|
||||
if condition == "" {
|
||||
return "", nil
|
||||
}
|
||||
default:
|
||||
return "", nil
|
||||
}
|
||||
@@ -1939,6 +1944,11 @@ func (h *Handler) applyFilter(query common.SelectQuery, filter common.FilterOpti
|
||||
if condition == "" {
|
||||
return query
|
||||
}
|
||||
case "contains":
|
||||
condition, args = common.BuildArrayOverlapCondition(filter.Column, filter.Value)
|
||||
if condition == "" {
|
||||
return query
|
||||
}
|
||||
default:
|
||||
return query
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ This will match any records where the column contains the search term (case-inse
|
||||
Search with specific operators (AND logic).
|
||||
|
||||
**Supported Operators:**
|
||||
- `contains` - Contains substring (case-insensitive)
|
||||
- `contains` - Contains substring (case-insensitive). Implemented as `CAST(col AS TEXT) ILIKE '%value%'` for every column type, including arrays (stringifies the array, then substring-matches). **Not** array containment — no GIN index use, and can false-positive on partial matches within array elements. resolvespec (a different spec package in this repo) defines `contains` differently: real PostgreSQL array-overlap (`&&`). Don't assume the two behave the same.
|
||||
- `beginswith` / `startswith` - Starts with (case-insensitive)
|
||||
- `endswith` - Ends with (case-insensitive)
|
||||
- `equals` / `eq` - Exact match
|
||||
|
||||
@@ -96,6 +96,8 @@ X-Limit: 50
|
||||
|
||||
**Available Operators**: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `contains`, `startswith`, `endswith`, `between`, `betweeninclusive`, `in`, `empty`, `notempty`
|
||||
|
||||
> Note: `contains` here is a text-cast ILIKE substring match (works on any column type, including arrays, by stringifying first) — not array containment. resolvespec's `contains` operator has different semantics (real array overlap). See [HEADERS.md](HEADERS.md) for details.
|
||||
|
||||
For complete header documentation, see [HEADERS.md](HEADERS.md).
|
||||
|
||||
## Lifecycle Hooks
|
||||
|
||||
@@ -551,11 +551,27 @@ func (a *DatabaseAuthenticator) RefreshToken(ctx context.Context, refreshToken s
|
||||
return nil, fmt.Errorf("failed to parse user context: %w", err)
|
||||
}
|
||||
|
||||
return &LoginResponse{
|
||||
// A resolvespec_refresh_token implementation that issues its own rotating
|
||||
// refresh token (independent of the access/session token) returns it
|
||||
// under claims.refresh_token, since UserContext has no dedicated field
|
||||
// for it. Surface that into LoginResponse.RefreshToken so callers don't
|
||||
// need to reach into User.Claims themselves. claims.expires_in
|
||||
// (seconds) similarly overrides the default access-token ExpiresIn when
|
||||
// the procedure provides a real value. Implementations that don't set
|
||||
// these claims keep today's behavior unchanged (empty RefreshToken,
|
||||
// 24h ExpiresIn default).
|
||||
resp := &LoginResponse{
|
||||
Token: userCtx.SessionID, // New session token from stored procedure
|
||||
User: &userCtx,
|
||||
ExpiresIn: int64(24 * time.Hour.Seconds()),
|
||||
}, nil
|
||||
}
|
||||
if refreshToken, ok := userCtx.Claims["refresh_token"].(string); ok && refreshToken != "" {
|
||||
resp.RefreshToken = refreshToken
|
||||
}
|
||||
if expiresIn, ok := userCtx.Claims["expires_in"].(float64); ok && expiresIn > 0 {
|
||||
resp.ExpiresIn = int64(expiresIn)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// JWTAuthenticator provides JWT token-based authentication
|
||||
@@ -912,8 +928,20 @@ func (p *DatabaseRowSecurityProvider) GetRowSecurity(ctx context.Context, userRe
|
||||
return RowSecurity{}, ErrDirectModeUnsupported
|
||||
}
|
||||
|
||||
var template string
|
||||
var hasBlock bool
|
||||
// resolvespec_row_security's p_user_id is a scalar integer. GetUserRef() may
|
||||
// hand back the full *UserContext so non-DB providers can inspect claims;
|
||||
// unwrap it here before it reaches the SQL args.
|
||||
switch v := userRef.(type) {
|
||||
case *UserContext:
|
||||
if v != nil {
|
||||
userRef = v.UserID
|
||||
}
|
||||
case UserContext:
|
||||
userRef = v.UserID
|
||||
}
|
||||
|
||||
var template sql.NullString
|
||||
var hasBlock sql.NullBool
|
||||
|
||||
runQuery := func() error {
|
||||
query := fmt.Sprintf(`SELECT p_template, p_block FROM %s($1, $2, $3)`, p.sqlNames.RowSecurity)
|
||||
@@ -933,8 +961,8 @@ func (p *DatabaseRowSecurityProvider) GetRowSecurity(ctx context.Context, userRe
|
||||
Schema: schema,
|
||||
Tablename: table,
|
||||
UserID: userRef,
|
||||
Template: template,
|
||||
HasBlock: hasBlock,
|
||||
Template: template.String,
|
||||
HasBlock: hasBlock.Bool,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -793,6 +793,49 @@ func TestDatabaseAuthenticatorRefreshToken(t *testing.T) {
|
||||
t.Errorf("unfulfilled expectations: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
// A resolvespec_refresh_token implementation that rotates its own
|
||||
// independent refresh token (not just reusing the session/access token)
|
||||
// has nowhere else to put the new refresh token and real access-token
|
||||
// expiry than under UserContext.Claims, since UserContext has no
|
||||
// dedicated fields for either. RefreshToken must surface those claims
|
||||
// keys into LoginResponse.RefreshToken/ExpiresIn rather than silently
|
||||
// dropping them (see the "successful token refresh" case above, which
|
||||
// covers an implementation that has no independent refresh token at all
|
||||
// and gets the 24h default instead).
|
||||
t.Run("surfaces rotated refresh token and expiry from claims", func(t *testing.T) {
|
||||
refreshToken := "refresh-token-abc"
|
||||
|
||||
sessionRows := sqlmock.NewRows([]string{"p_success", "p_error", "p_user"}).
|
||||
AddRow(true, nil, `{"user_id":1,"user_name":"testuser"}`)
|
||||
mock.ExpectQuery(`SELECT p_success, p_error, p_user::text FROM resolvespec_session`).
|
||||
WithArgs(refreshToken, "refresh").
|
||||
WillReturnRows(sessionRows)
|
||||
|
||||
refreshRows := sqlmock.NewRows([]string{"p_success", "p_error", "p_user"}).
|
||||
AddRow(true, nil, `{"user_id":1,"user_name":"testuser","session_id":"new-access-789","claims":{"refresh_token":"new-refresh-def","expires_in":900}}`)
|
||||
mock.ExpectQuery(`SELECT p_success, p_error, p_user::text FROM resolvespec_refresh_token`).
|
||||
WithArgs(refreshToken, sqlmock.AnyArg()).
|
||||
WillReturnRows(refreshRows)
|
||||
|
||||
resp, err := auth.RefreshToken(ctx, refreshToken)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if resp.Token != "new-access-789" {
|
||||
t.Errorf("expected token new-access-789, got %s", resp.Token)
|
||||
}
|
||||
if resp.RefreshToken != "new-refresh-def" {
|
||||
t.Errorf("expected rotated refresh token new-refresh-def, got %q", resp.RefreshToken)
|
||||
}
|
||||
if resp.ExpiresIn != 900 {
|
||||
t.Errorf("expected ExpiresIn 900 from claims, got %d", resp.ExpiresIn)
|
||||
}
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unfulfilled expectations: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDatabaseAuthenticatorReconnectsClosedDBPaths(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user