squeeze

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllRules

func AllRules() map[string]Rule

AllRules returns all available rules keyed by name.

func FindAuthTaintedVars

func FindAuthTaintedVars(body *ast.BlockStmt) map[string]bool

FindAuthTaintedVars walks a method body and finds local variables assigned from expressions that contain ctx.Auth(). For example:

authID, err := uuid.Parse(ctx.Auth().UserID)

returns {"authID": true}.

func FindBuiltinCalls

func FindBuiltinCalls(body *ast.BlockStmt, fset *token.FileSet, name string) []int

FindBuiltinCalls finds calls to a Go builtin function (e.g. recover, panic) in a block.

func FindCallsTo

func FindCallsTo(body *ast.BlockStmt, fset *token.FileSet, pkg, funcName string) []int

FindCallsTo walks a method body and finds calls to a specific package.function. e.g. FindCallsTo(body, "fmt", "Sprintf") finds fmt.Sprintf(...) calls.

func FindModelVars

func FindModelVars(body *ast.BlockStmt) map[string]bool

FindModelVars walks a method body and finds local variables assigned from model sources:

  • models.QueryX().First() or .All() (query results)
  • &models.X{} (struct literals)

func ParseControllers

func ParseControllers(controllersDir string) (map[string]*ControllerMethod, error)

ParseControllers parses all Go files in the controllers directory.

func PayloadIsModelWithoutPublic

func PayloadIsModelWithoutPublic(expr ast.Expr, modelVars map[string]bool) bool

PayloadIsModelWithoutPublic checks if a ctx.JSON payload is a model variable that wasn't accessed via .Public(). Uses modelVars to identify which local variables hold model-typed values.

func RouteParams

func RouteParams(path string) []string

RouteParams extracts parameter names from a route path (e.g., "/users/:id" -> ["id"]).

Types

type ActionInfo

type ActionInfo struct {
	Name     string // action name, e.g. "CreateTransfer"
	File     string // path to the action file
	GateFile string // expected gate file path
	HasGate  bool   // whether the gate file exists
}

ActionInfo describes an action file for squeeze analysis.

type AnalysisContext

type AnalysisContext struct {
	Routes         []AnalyzedRoute
	Methods        map[string]*ControllerMethod
	Requests       []generator.RequestDef
	Tables         []*schema.Table
	Config         SqueezeConfig
	FuncRegistry   FuncRegistry
	HasGraphQL     bool // true if the project has a graphql/ directory
	RBACRoles      *RBACRoleSet
	RBACDefaults   []RBACDefault
	Actions        []ActionInfo
	GraphQLExposed map[string]bool // table/model names exposed via GraphQL policies (nil = no policies)
	ProjectDir     string
}

AnalysisContext holds all parsed project data for rules to inspect.

type AnalyzedRoute

type AnalyzedRoute struct {
	Method         string   // GET, POST, PUT, PATCH, DELETE
	Path           string   // full path including group prefixes
	ControllerType string   // e.g. "PostController"
	MethodName     string   // e.g. "Destroy"
	Middleware     []string // accumulated middleware names from groups + per-route
	File           string
	Line           int
}

AnalyzedRoute represents a single route extracted from routes/*.go via AST.

func ParseRoutes

func ParseRoutes(routesDir string) ([]AnalyzedRoute, error)

ParseRoutes parses all Go files in the routes directory and extracts route definitions.

func (AnalyzedRoute) HasAdminMiddleware

func (r AnalyzedRoute) HasAdminMiddleware(mc MiddlewareConfig) bool

HasAdminMiddleware returns true if any middleware on this route is classified as admin.

func (AnalyzedRoute) HasAuthMiddleware

func (r AnalyzedRoute) HasAuthMiddleware(mc MiddlewareConfig) bool

HasAuthMiddleware returns true if any middleware on this route is classified as auth.

func (AnalyzedRoute) HasCSRFMiddleware

func (r AnalyzedRoute) HasCSRFMiddleware(mc MiddlewareConfig) bool

HasCSRFMiddleware returns true if any middleware on this route is classified as CSRF protection.

func (AnalyzedRoute) HasRateLimitMiddleware

func (r AnalyzedRoute) HasRateLimitMiddleware(mc MiddlewareConfig) bool

HasRateLimitMiddleware returns true if any middleware on this route is classified as rate limiting.

type AppConfig

type AppConfig struct {
	Path       string   `yaml:"path"`                 // directory containing go.mod, relative to pickle.yaml
	Migrations []string `yaml:"migrations,omitempty"` // migration dirs relative to app path; default: ["database/migrations"]
	Config     string   `yaml:"config,omitempty"`     // config dir relative to app path; default: "config"
}

AppConfig describes a single app in a monorepo layout.

type CallChain

type CallChain struct {
	Segments []ChainSegment
	Line     int
	AuthVars map[string]bool // auth-tainted variable names in scope for this chain
}

CallChain represents an unwound method call chain like models.QueryPost().WhereID(id).First()

func ExtractCallChains

func ExtractCallChains(body *ast.BlockStmt, fset *token.FileSet) []CallChain

ExtractCallChains walks a method body and extracts all call chains.

func ExtractCallChainsRecursive

func ExtractCallChainsRecursive(body *ast.BlockStmt, fset *token.FileSet, registry FuncRegistry, authVars map[string]bool) []CallChain

ExtractCallChainsRecursive extracts call chains from a method body, recursively inlining project-local function calls to discover chains inside service functions.

func (CallChain) HasSegment

func (cc CallChain) HasSegment(name string) bool

HasSegment returns true if any segment in the chain has the given name.

func (CallChain) HasSegmentWithAuthArg

func (cc CallChain) HasSegmentWithAuthArg(prefix string) bool

HasSegmentWithAuthArg returns true if any segment has an argument containing ctx.Auth() either directly or via a local variable that was assigned from a ctx.Auth() expression.

func (CallChain) HasSegmentWithAuthArgTainted

func (cc CallChain) HasSegmentWithAuthArgTainted(prefix string, authVars map[string]bool) bool

HasSegmentWithAuthArgTainted is like HasSegmentWithAuthArg but also accepts a set of local variable names known to carry auth-derived values (e.g. authID from uuid.Parse(ctx.Auth().UserID)).

func (CallChain) Names

func (cc CallChain) Names() []string

Names returns just the segment names (e.g. ["models", "QueryPost", "WhereID", "First"]).

type ChainSegment

type ChainSegment struct {
	Name string
	Args []ast.Expr
}

ChainSegment is one link in a call chain.

type CompositeLitInfo

type CompositeLitInfo struct {
	PackageName string   // e.g. "models"
	TypeName    string   // e.g. "Post"
	FieldNames  []string // fields set in the literal
	Line        int
}

CompositeLitInfo describes a model struct literal found in a controller method.

func FindCompositeLiterals

func FindCompositeLiterals(body *ast.BlockStmt, fset *token.FileSet) []CompositeLitInfo

FindCompositeLiterals finds &models.Type{...} composite literals in a method body.

func FindCompositeLiteralsRecursive

func FindCompositeLiteralsRecursive(body *ast.BlockStmt, fset *token.FileSet, registry FuncRegistry) []CompositeLitInfo

FindCompositeLiteralsRecursive finds composite literals in a method body and recursively in any project-local functions called from it.

type Config

type Config struct {
	Squeeze  SqueezeConfig            `yaml:"squeeze"`
	Apps     map[string]AppConfig     `yaml:"apps,omitempty"`
	Services map[string]ServiceConfig `yaml:"services,omitempty"`
}

Config represents the top-level pickle.yaml file.

func LoadConfig

func LoadConfig(projectDir string) (*Config, error)

LoadConfig reads pickle.yaml from the project root. Returns a default config if the file doesn't exist.

func (*Config) IsMonorepo

func (c *Config) IsMonorepo() bool

IsMonorepo returns true if the config defines multiple apps (separate go.mod files).

func (*Config) IsMultiService

func (c *Config) IsMultiService() bool

IsMultiService returns true if the config defines multiple services.

type ControllerMethod

type ControllerMethod struct {
	ControllerType string
	MethodName     string
	File           string
	Line           int
	Body           *ast.BlockStmt
	Fset           *token.FileSet
}

ControllerMethod represents a parsed controller method with its AST body.

type CtxJSONCall

type CtxJSONCall struct {
	Line        int
	PayloadExpr ast.Expr
}

FindCtxJSONCalls finds ctx.JSON(status, payload) calls and returns info about the payload.

func FindCtxJSONCalls

func FindCtxJSONCalls(body *ast.BlockStmt, fset *token.FileSet) []CtxJSONCall

type Finding

type Finding struct {
	Rule     string
	Severity Severity
	File     string
	Line     int
	Message  string
}

Finding represents a single issue detected by squeeze.

func Run

func Run(projectDir string) ([]Finding, error)

Run executes all enabled squeeze rules against the project and returns findings.

func (Finding) String

func (f Finding) String() string

type FuncRegistry

type FuncRegistry map[string]*ParsedFunc

FuncRegistry maps "pkg.FuncName" to parsed function info.

func ParseProjectFunctions

func ParseProjectFunctions(projectDir string) FuncRegistry

ParseProjectFunctions walks the app/ directory and indexes all top-level functions (excluding _gen.go and _test.go files) by "packageName.FuncName".

type MiddlewareConfig

type MiddlewareConfig struct {
	Auth      []string `yaml:"auth"`       // middleware that provides authentication
	Admin     []string `yaml:"admin"`      // middleware that provides admin access (implies auth)
	RateLimit []string `yaml:"rate_limit"` // middleware that provides rate limiting
	CSRF      []string `yaml:"csrf"`       // middleware that provides CSRF protection
}

MiddlewareConfig classifies middleware by role.

func (MiddlewareConfig) IsAdminMiddleware

func (mc MiddlewareConfig) IsAdminMiddleware(name string) bool

IsAdminMiddleware returns true if the given middleware name is classified as admin. Defaults to matching "RequireAdmin" if no admin middleware is configured.

func (MiddlewareConfig) IsAuthMiddleware

func (mc MiddlewareConfig) IsAuthMiddleware(name string) bool

IsAuthMiddleware returns true if the given middleware name is classified as auth. Defaults to matching "Auth" if no auth middleware is configured.

func (MiddlewareConfig) IsCSRFMiddleware

func (mc MiddlewareConfig) IsCSRFMiddleware(name string) bool

IsCSRFMiddleware returns true if the given middleware name is classified as CSRF protection. Defaults to matching "CSRF" if no CSRF middleware is configured.

func (MiddlewareConfig) IsRateLimitMiddleware

func (mc MiddlewareConfig) IsRateLimitMiddleware(name string) bool

IsRateLimitMiddleware returns true if the given middleware name is classified as rate limiting. Defaults to matching "RateLimit" if no rate limit middleware is configured.

type MustParseCall

type MustParseCall struct {
	Line        int
	HasCtxParam bool // argument contains ctx.Param(...)
	HasCtxAuth  bool // argument contains ctx.Auth()
}

FindMustParseCalls finds uuid.MustParse calls and categorizes them by argument type.

func FindMustParseCalls

func FindMustParseCalls(body *ast.BlockStmt, fset *token.FileSet) []MustParseCall

type ParamCall

type ParamCall struct {
	Name string
	Line int
}

ParamCall represents a ctx.Param("name") call found in a controller.

func FindParamNames

func FindParamNames(body *ast.BlockStmt, fset *token.FileSet) []ParamCall

FindParamNames returns all string literal arguments to ctx.Param() and ctx.ParamUUID() calls in a method body.

type ParsedFunc

type ParsedFunc struct {
	Body   *ast.BlockStmt
	Fset   *token.FileSet
	Params []*ast.Field
}

ParsedFunc represents a parsed project-local function for inlining.

type RBACDefault

type RBACDefault struct {
	Role string
	File string
	Line int
}

RBACDefault represents a role marked as Default().

type RBACRoleSet

type RBACRoleSet struct {
	Defined map[string]bool // all roles that have been defined
	Removed map[string]bool // roles that were defined then removed
}

RBACRoleSet represents roles defined in a project for RBAC analysis.

type RoleHit

type RoleHit struct {
	Role string
	Line int
}

RoleHit represents a found role annotation in source code.

type Rule

type Rule func(ctx *AnalysisContext) []Finding

Rule is a function that inspects the analysis context and returns findings.

type ServiceConfig

type ServiceConfig struct {
	Dir string `yaml:"dir"` // relative to project root, e.g. "services/api"
}

ServiceConfig describes a service in a multi-service project (one go.mod, shared models).

type Severity

type Severity int

Severity indicates the importance of a finding.

const (
	SeverityWarning Severity = iota
	SeverityError
)

func (Severity) String

func (s Severity) String() string

type SqueezeConfig

type SqueezeConfig struct {
	Middleware MiddlewareConfig `yaml:"middleware"`
	Rules      map[string]bool  `yaml:"rules"`
}

SqueezeConfig holds all squeeze-related configuration.

func (SqueezeConfig) RuleEnabled

func (sc SqueezeConfig) RuleEnabled(name string) bool

RuleEnabled returns true if the named rule is enabled. All rules default to true when not specified.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL