Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions packages/explainer/src/__tests__/missing-tenant-scope.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { describe, test, expect } from "@jest/globals"
import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol"
import { IR_NODE_TYPES } from "@kidkender/archmind-protocol"
import { detectMissingTenantScope } from "../pattern-detectors/missing-tenant-scope.js"
import { explain } from "../index.js"
import { FINDING_TYPES } from "../findings/types.js"

function makeGraph(
Expand Down Expand Up @@ -131,3 +133,38 @@ describe("detectMissingTenantScope", () => {
expect(detectMissingTenantScope([], graph)).toHaveLength(0)
})
})

describe("detectMissingTenantScope — Gin graphs (ir:tenant_context)", () => {
function ginGraph(): IntermediateExecutionGraph {
return {
entrypoint: "GET /api/v1/orders/:id",
method: "GET",
path: "/api/v1/orders/:id",
annotations: [],
framework: "gin",
nodes: [
{ id: "handler", type: IR_NODE_TYPES.BUSINESS_HANDLER, symbol: "handler.Get" },
{ id: "tenant_ctx", type: IR_NODE_TYPES.TENANT_CONTEXT, symbol: `tenant context: c.GetString("tenant_id")`, role: "runtime" },
{ id: "iso_0", type: IR_NODE_TYPES.UNSCOPED_QUERY, symbol: "Order::First", role: "data_access" },
],
edges: [
{ from: "handler", to: "iso_0", relation: "calls", traceability: "static" },
{ from: "iso_0", to: "tenant_ctx", relation: "missing_tenant_scope", traceability: "semantic" },
],
}
}

test("an unscoped GORM query linked to the tenant context is a finding with Go advice", () => {
const [f] = detectMissingTenantScope([], ginGraph())
expect(f?.type).toBe(FINDING_TYPES.MISSING_TENANT_SCOPE)
expect(f?.provenance.supporting_nodes).toEqual(["iso_0", "tenant_ctx"])
expect(f?.recommendations?.some((r) => r.includes(`Where("tenant_id = ?"`))).toBe(true)
expect(f?.recommendations?.some((r) => r.includes("AppServiceProvider"))).toBe(false)
})

test("the tenant context node does not also raise hidden_runtime_dependency", () => {
const types = explain(ginGraph()).map((x) => x.type)
expect(types).toContain(FINDING_TYPES.MISSING_TENANT_SCOPE)
expect(types).not.toContain(FINDING_TYPES.HIDDEN_RUNTIME_DEPENDENCY)
})
})
62 changes: 47 additions & 15 deletions packages/explainer/src/pattern-detectors/missing-tenant-scope.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { SemanticFact } from "../fact-extraction/types.js"
import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol"
import { IR_NODE_TYPES } from "@kidkender/archmind-protocol"
import { query } from "@kidkender/archmind-graph-query"
import type { Finding, Evidence, ReasoningStep } from "../findings/types.js"
import { FINDING_TYPES } from "../findings/types.js"
Expand All @@ -13,13 +14,15 @@ interface UnscopedQueryGroup {

function findUnscopedGroups(graph: IntermediateExecutionGraph): UnscopedQueryGroup[] {
const q = query(graph)
// missing_tenant_scope edges: unscoped_query → runtime_injection
// missing_tenant_scope edges: unscoped_query → the node that resolves the tenant
// (runtime_injection in Laravel graphs, ir:tenant_context in Gin graphs)
const missingEdges = q.edges().ofRelation("missing_tenant_scope")
const groups: UnscopedQueryGroup[] = []

for (const edge of missingEdges.toArray()) {
const unscopedNode = missingEdges.from(edge.from).fromNodes().ofType("unscoped_query").first()
const injectionNode = missingEdges.to(edge.to).toNodes().ofType("runtime_injection").first()
const injectionNode = missingEdges.to(edge.to).toNodes()
.ofType(IR_NODE_TYPES.RUNTIME_INJECT, IR_NODE_TYPES.TENANT_CONTEXT).first()
if (!unscopedNode || !injectionNode) continue
groups.push({
unscopedNodeId: unscopedNode.id,
Expand Down Expand Up @@ -51,7 +54,9 @@ export function detectMissingTenantScope(
{
type: "tenant_context_present",
node: group.injectionNodeId,
description: "Tenant is resolved and injected into the container — this is a tenant-scoped route",
description: graph.framework === "gin"
? "Tenant is resolved for this request — this is a tenant-scoped route"
: "Tenant is resolved and injected into the container — this is a tenant-scoped route",
},
{
type: "unscoped_query_detected",
Expand All @@ -70,7 +75,9 @@ export function detectMissingTenantScope(
const evidence: Evidence[] = [
{
nodeId: group.injectionNodeId,
description: "Tenant injected into container — confirms this route is tenant-scoped",
description: graph.framework === "gin"
? "Tenant resolved for this request — confirms this route is tenant-scoped"
: "Tenant injected into container — confirms this route is tenant-scoped",
},
{
nodeId: group.unscopedNodeId,
Expand Down Expand Up @@ -99,19 +106,44 @@ export function detectMissingTenantScope(
summary: `${group.unscopedSymbol} fetches by raw ID with no tenant constraint — any authenticated user can access another tenant's ${modelClass ?? "model"} by guessing the ID`,
reasoning,
evidence,
uncertainty: [
{
kind: "unverifiable_condition",
description: `If ${modelClass} has a registered global TenantScope (via booted() or AppServiceProvider), ${operation ?? "find"} is automatically scoped and this finding does not apply — global scopes are not visible at the call site`,
},
],
recommendations: [
`Option A: ${modelClass}::where('tenant_id', app('tenant')->id)->${operation ?? "findOrFail"}($id)`,
`Option B: Add a global TenantScope to ${modelClass}'s booted() method`,
`Option C: Use scoped route model binding in AppServiceProvider`,
],
...(graph.framework === "gin" ? ginAdvice(modelClass, operation) : laravelAdvice(modelClass, operation)),
})
}

return findings
}

type Advice = Pick<Finding, "uncertainty" | "recommendations">

function laravelAdvice(modelClass: string | undefined, operation: string | undefined): Advice {
return {
uncertainty: [
{
kind: "unverifiable_condition",
description: `If ${modelClass} has a registered global TenantScope (via booted() or AppServiceProvider), ${operation ?? "find"} is automatically scoped and this finding does not apply — global scopes are not visible at the call site`,
},
],
recommendations: [
`Option A: ${modelClass}::where('tenant_id', app('tenant')->id)->${operation ?? "findOrFail"}($id)`,
`Option B: Add a global TenantScope to ${modelClass}'s booted() method`,
`Option C: Use scoped route model binding in AppServiceProvider`,
],
}
}

function ginAdvice(modelClass: string | undefined, operation: string | undefined): Advice {
const model = modelClass && modelClass !== "gorm" ? modelClass : "the model"
return {
uncertainty: [
{
kind: "unverifiable_condition",
description: `If ${model} is scoped by a GORM callback, a plugin or a Scopes() function that does not name the tenant, ${operation ?? "the query"} may already be constrained — those are not visible at the call site`,
},
],
recommendations: [
`Option A: add the tenant to the query, e.g. db.Where("tenant_id = ?", tenantID).${operation ?? "First"}(...)`,
`Option B: a reusable scope, e.g. db.Scopes(TenantScope(tenantID)).${operation ?? "First"}(...)`,
`Option C: register a GORM callback that adds the tenant condition to every query on ${model}`,
],
}
}
9 changes: 8 additions & 1 deletion packages/go-parser/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ Most of ArchMind uses it through `@kidkender/archmind-analysis`, the CLI (`archm
- **Authorization checks**: role/policy middleware, and **ownership** checks. A handler that calls one of the functions named in `archmind.json` → `authorization.ownershipSources` (for example `["currentCharacter"]`) is treated as authorizing by ownership.
- **Validation gates**: `ShouldBindJSON`, `ShouldBindQuery` and `ShouldBindUri` resolved to the DTO struct and its `binding` tags.
- **Transaction boundaries**: GORM `.Transaction(func...)` closures, followed one hop into a directly called service method.
- **Tenant isolation**: on a route that resolves a tenant (a middleware whose name carries a tenant key, a `c.Get("tenant_id")`-style read from the Gin context, an accessor such as `GetTenantID(c)` / `tenant.FromContext(ctx)`, a tenant-named function handed the context such as `TenantScope(c)`, or a tenant field read such as `claims.TenantID`), an `ir:tenant_context` node, and every query in the handler and up to two calls below it (handler → service → repository) as `ir:scoped_query` or `ir:unscoped_query` / `ir:unscoped_write`. An unscoped query gets a `missing_tenant_scope` edge, which the explainer reports as a `missing_tenant_scope` finding. Routes that resolve no tenant get none of these nodes.
- Calls are followed through struct fields, typed locals (`db := dal.BoardQuery{}`, `list := models.NewSysRoleList()`), package-level registries and embedded structs (`service.GroupApp.Board.X`); route handlers registered that way (`api.Controllers.BoardApi.X`) are resolved too.
- Besides GORM chains, a read/write-named call on a DAO, repository or model wrapper (a type declared under `dal/`, `dao/`, `repo*/`, `store/`, `query/`, `model*/`, ... or named `*Query` / `*Repo` / `*Dao` / ...) counts as a query. When the wrapper takes its conditions as variadic arguments (`First(ctx, conds ...gen.Condition)`, `Find(c, scopes ...func(*gorm.DB) *gorm.DB)`), it is judged at the call site by those arguments; otherwise it is followed. A `Scopes(funcs...)` fed by a parameter is judged by the arguments of the call that reached it.
- A create, update, delete or query whose GORM callback (`db.Callback().Create()...Register(name, fn)`) mentions the tenant counts as scoped. A query on a model declared in the project without a tenant field (directly or in an embedded struct) is shared data and is not reported. `Preload("Tenant")` does not scope a query.
- A handler wired up as a local variable (`h := handler.NewXxx(...)`) is resolved to its type.

Nodes carry the `file` and `line` where the parser found them.
Expand All @@ -51,14 +55,17 @@ The tree-sitter helpers other packages build on: `parseGo`, `walk`, `receiverTyp
```json
{
"authorization": { "ownershipSources": ["currentCharacter", "UserId"] },
"isolation": { "tenantSignals": ["tenant", "organization_id"], "tenantContextKeys": ["tenant", "organization"] },
"ignoreFindings": ["missing_authorization"]
}
```

`isolation` matches identifier and string tokens, ignoring case and `_`: `tenant` matches `tenant_id`, `TenantID` and `TenantScope`. `tenantSignals` mark a query as constrained (in its `Where` / `Scopes` / `Joins` arguments, or, for a write, in the statements that build the record); `tenantContextKeys` mark where the request's tenant comes from. The values shown are the defaults (`org_id` is in both lists too).

## Limits

- Scoped to the Gin + GORM + `internal/{handler,service,middleware,model,dto}` layout it was built against, and checked on other public Gin repositories. Some architectures still return no routes (an engine held in a struct field and mutated by a method, a custom wrapper type with its own `.GET()`, deeply functional-options setups, Wire-style injection).
- Tenant isolation is not implemented for Go.
- Tenant isolation is syntactic: a GORM plugin, a global scope applied outside a registered callback, or a `Scopes(fn)` whose name and arguments carry no tenant signal is not seen, so a query constrained that way reads as unscoped. Queries that are global by design (login, uniqueness checks, super-admin setup) are reported too. Types are matched by bare name across packages. Queries more than two calls below the handler, or behind an interface whose implementation is not named `T`, `t`, `TImpl` or `tImpl`, are not found. At most 25 query nodes per route.

## License

Expand Down
Loading
Loading