code

package
v1.1303.0 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: Apache-2.0 Imports: 58 Imported by: 0

Documentation

Overview

Package code provides Snyk Code (SAST) scanning functionality.

Index

Constants

View Source
const (
	FixPositiveFeedback string = "FIX_POSITIVE_FEEDBACK"
	FixNegativeFeedback string = "FIX_NEGATIVE_FEEDBACK"
	FixAppliedUserEvent string = "FIX_APPLIED"
)
View Source
const (
	DontUsePrintStackTrace                       string = "DontUsePrintStackTrace"
	CatchingInterruptedExceptionWithoutInterrupt string = "catchingInterruptedExceptionWithoutInterrupt"
)
View Source
const (
	CreateBundleOperation           = "createBundle"
	ExtendBundleWithSourceOperation = "extendBundleWithSource"
	RunAnalysisOperation            = "runAnalysis"
	RunAutofixOperation             = "runAutofix"
	GetFiltersOperation             = "getFilters"
	FakeFileExtension               = ".java"
	// Helper constants to synchronize fake results and tests
	FakeAutofixSuggestionNewText = "FAKE_AUTOFIX_NEW_TEXT"
)
View Source
const (
	ExplainApiVersion string = "2024-10-15"
)
View Source
const FixIssuePrefix = "⚡ Fix this issue: "
View Source
const ShowInDetailPanelIdeCommand = "showInDetailPanel"

Variables

View Source
var (
	FakeSnykCodeApiServiceMutex = &sync.Mutex{}

	FakeCommand = types.CommandData{
		Title:     "Code Flow blah blah fake",
		CommandId: types.NavigateToRangeCommand,
		Arguments: []any{"path", fakeRange},
	}
	FakeFixCommand = types.CommandData{
		Title:     "Code Flow blah blah fake",
		CommandId: types.CodeFixCommand,
		Arguments: []any{"id", "path", fakeRange},
	}

	FakeIssue = &snyk.Issue{
		ID:               "SNYK-123",
		Range:            fakeRange,
		Severity:         types.High,
		Product:          product.ProductCode,
		IssueType:        types.CodeSecurityVulnerability,
		Message:          "This is a dummy error (severity error)",
		CodelensCommands: []types.CommandData{FakeCommand, FakeFixCommand},
		CodeActions:      []types.CodeAction{&FakeCodeAction},
		AdditionalData: snyk.CodeIssueData{
			Key:           uuid.New().String(),
			IsAutofixable: true,
		},
	}

	FakeCodeAction = snyk.CodeAction{
		Title:   "FakeAction",
		Command: &FakeCommand,
	}
)

Functions

func ConvertSARIFJSONToIssues added in v1.1303.0

func ConvertSARIFJSONToIssues(logger *zerolog.Logger, hoverVerbosity int, sarifJSON []byte, basePath string) ([]types.Issue, error)

ConvertSARIFJSONToIssues converts SARIF JSON output to Issues without requiring a full scanner instance This is a simplified version for use by MCP and other tools that need conversion without full scanner basePath is the absolute path where the scan was run (optional - if empty, paths remain relative)

func CreateCodeScanner added in v1.1303.0

func CreateCodeScanner(scanner *Scanner, folderConfig *types.FolderConfig) (codeClient.CodeScanner, error)

CreateCodeScanner creates a real code scanner with Organization populated from folder configuration

func CreateWorkspaceEditFromDiff added in v1.1303.0

func CreateWorkspaceEditFromDiff(absoluteFilePath string, diff string) (*types.WorkspaceEdit, error)

CreateWorkspaceEditFromDiff turns the returned fix (in diff format) into a series of TextEdits in a WorkspaceEdit.

func DecodePath

func DecodePath(encodedRelativePath string) (string, error)

func EncodePath

func EncodePath(relativePath types.FilePath) types.FilePath

func GetAutofixIdeExtensionDetails added in v1.1303.0

func GetAutofixIdeExtensionDetails(c *config.Config) llm.AutofixIdeExtensionDetails

func GetCodeApiUrlForFolder added in v1.1303.0

func GetCodeApiUrlForFolder(c *config.Config, folder types.FilePath) (string, error)

GetCodeApiUrlForFolder returns the Snyk Code API URL for the given folder. The folder parameter can be a subdirectory or file path; this function will find the workspace folder containing it. The URL is determined in the following order:

  • If local code engine (SCLE) is enabled in the folder's SAST settings, we use the local engine endpoint
  • If a custom endpoint from the folder's SAST settings is configured, we use the custom endpoint
  • In non-FedRAMP environments, we return these as is
  • In FedRAMP environments, the folder's organization is included in the URL path

Returns an error if:

  • folder is empty
  • no workspace folder can be found for the given path
  • in FedRAMP, if no organization can be determined for the folder

func GetIgnoreDetailsFromSuppressions added in v1.1303.0

func GetIgnoreDetailsFromSuppressions(suppressions []codeClientSarif.Suppression) (bool, *types.IgnoreDetails)

func NewAutofixCodeRequestContext added in v1.1303.0

func NewAutofixCodeRequestContext(folderPath types.FilePath) llm.CodeRequestContext

func NewCodeErrorReporter

func NewCodeErrorReporter(errorReporter error_reporting.ErrorReporter) codeClient.ErrorReporter

func NewCodeInstrumentor

func NewCodeInstrumentor() codeClient.Instrumentor

func NewCodeTrackerFactory

func NewCodeTrackerFactory() codeClientScan.TrackerFactory

func NewFakeCodeScannerClient added in v1.1303.0

func NewFakeCodeScannerClient(sc *Scanner, folderConfig *types.FolderConfig) (codeClient.CodeScanner, error)

NewFakeCodeScannerClient creates a fake code scanner for testing

func ResetHTMLRenderer added in v1.1303.0

func ResetHTMLRenderer()

ResetHTMLRenderer resets the singleton HtmlRenderer to nil. This is intended for use in tests to ensure test isolation.

func SnykMagnetUri added in v1.1303.0

func SnykMagnetUri(issue types.Issue, ideAction string) (string, error)

func TempWorkdirWithIssues

func TempWorkdirWithIssues(t *testing.T) (types.FilePath, types.FilePath)

func ToAbsolutePath

func ToAbsolutePath(baseDir types.FilePath, relativePath types.FilePath) string

func ToRelativeUnixPath

func ToRelativeUnixPath(baseDir types.FilePath, absoluteFilePath types.FilePath) (types.FilePath, error)

Types

type AiFixHandler added in v1.1303.0

type AiFixHandler struct {
	// contains filtered or unexported fields
}

func (*AiFixHandler) EnrichWithExplain added in v1.1303.0

func (fixHandler *AiFixHandler) EnrichWithExplain(ctx context.Context, c *config.Config, issue types.Issue, suggestions []llm.AutofixUnifiedDiffSuggestion)

func (*AiFixHandler) GetAiFixDiffError added in v1.1303.0

func (fixHandler *AiFixHandler) GetAiFixDiffError() error

func (*AiFixHandler) GetAiFixDiffResult added in v1.1303.0

func (fixHandler *AiFixHandler) GetAiFixDiffResult() []llm.AutofixUnifiedDiffSuggestion

func (*AiFixHandler) GetAiFixDiffStatus added in v1.1303.0

func (fixHandler *AiFixHandler) GetAiFixDiffStatus() AiStatus

func (*AiFixHandler) GetAutoTriggerAiFix added in v1.1303.0

func (fixHandler *AiFixHandler) GetAutoTriggerAiFix() bool

func (*AiFixHandler) GetCurrentIssueId added in v1.1303.0

func (fixHandler *AiFixHandler) GetCurrentIssueId() string

func (*AiFixHandler) GetResults added in v1.1303.0

func (fixHandler *AiFixHandler) GetResults(fixId string) (filePath string, diff string, err error)

func (*AiFixHandler) SetAiFixDiffState added in v1.1303.0

func (fixHandler *AiFixHandler) SetAiFixDiffState(state AiStatus, suggestions []llm.AutofixUnifiedDiffSuggestion, err error, callback func())

func (*AiFixHandler) SetAutoTriggerAiFix added in v1.1303.0

func (fixHandler *AiFixHandler) SetAutoTriggerAiFix(isEnabled bool)

type AiStatus added in v1.1303.0

type AiStatus string
const (
	AiFixNotStarted AiStatus = "NOT_STARTED"
	AiFixInProgress AiStatus = "IN_PROGRESS"
	AiFixSuccess    AiStatus = "SUCCESS"
	AiFixError      AiStatus = "ERROR"
)

type AnalysisRequest

type AnalysisRequest struct {
	Key             AnalysisRequestKey `json:"key"`
	Severity        int                `json:"severity,omitempty"`
	Prioritized     bool               `json:"prioritized,omitempty"`
	Legacy          bool               `json:"legacy"`
	AnalysisContext codeRequestContext `json:"analysisContext"`
}

type AnalysisRequestKey

type AnalysisRequestKey struct {
	Type         string           `json:"type"`
	Hash         string           `json:"hash"`
	LimitToFiles []types.FilePath `json:"limitToFiles,omitempty"`
	Shard        string           `json:"shard"`
}

type AutofixEventDetails added in v1.1303.0

type AutofixEventDetails struct {
	FixId string `json:"fixId"`
}

type AutofixIdeExtensionDetails added in v1.1303.0

type AutofixIdeExtensionDetails struct {
	IdeName          string `json:"ideName"`
	IdeVersion       string `json:"ideVersion"`
	ExtensionName    string `json:"extensionName"`
	ExtensionVersion string `json:"extensionVersion"`
}

type AutofixRequest

type AutofixRequest struct {
	Key                 AutofixRequestKey          `json:"key"`
	AnalysisContext     codeRequestContext         `json:"analysisContext"`
	IdeExtensionDetails AutofixIdeExtensionDetails `json:"ideExtensionDetails"`
}

type AutofixRequestKey

type AutofixRequestKey struct {
	Type     string         `json:"type"`
	Hash     string         `json:"hash"`
	Shard    string         `json:"shard"`
	FilePath types.FilePath `json:"filePath"`
	RuleId   string         `json:"ruleId"`
	// 1-based to comply with Sarif and Code API, see
	// https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html#_Ref493492556
	LineNum int `json:"lineNum"`
}

type AutofixResponse

type AutofixResponse struct {
	Status             string                     `json:"status"`
	AutofixSuggestions []autofixResponseSingleFix `json:"fixes"`
}

AutofixResponse is the json-based structure to which we can translate the results of the HTTP request to Autofix upstream.

type AutofixSuggestion

type AutofixSuggestion struct {
	FixId       string
	AutofixEdit types.WorkspaceEdit
}

AutofixSuggestion models a fix returned by autofix service

type AutofixUnifiedDiffSuggestion

type AutofixUnifiedDiffSuggestion struct {
	FixId               string            `json:"fixId"`
	UnifiedDiffsPerFile map[string]string `json:"unifiedDiffsPerFile"`
	FullTextPerFile     map[string]string `json:"fullTextPerFile"`
	Explanation         string            `json:"explanation"`
}

AutofixUnifiedDiffSuggestion represents the diff between the original and the fixed source code.

func (AutofixUnifiedDiffSuggestion) GetUnifiedDiffForFile

func (a AutofixUnifiedDiffSuggestion) GetUnifiedDiffForFile(filePath string) string

func (AutofixUnifiedDiffSuggestion) String

type AutofixUserEvent added in v1.1303.0

type AutofixUserEvent struct {
	AnalysisContext     codeRequestContext         `json:"analysisContext"`
	Channel             string                     `json:"channel"`
	EventType           string                     `json:"eventType"`
	EventDetails        AutofixEventDetails        `json:"eventDetails"`
	IdeExtensionDetails AutofixIdeExtensionDetails `json:"ideExtensionDetails"`
}

type CodeConfig added in v1.1303.0

type CodeConfig struct {
	// contains filtered or unexported fields
}

CodeConfig provides a concrete implementation of the codeClientConfig.Config interface It's lazy and delegates most calls to the language server config, only storing Organization for the folder

func (*CodeConfig) IsFedramp added in v1.1303.0

func (c *CodeConfig) IsFedramp() bool

func (*CodeConfig) Organization added in v1.1303.0

func (c *CodeConfig) Organization() string

func (*CodeConfig) SnykApi added in v1.1303.0

func (c *CodeConfig) SnykApi() string

func (*CodeConfig) SnykCodeAnalysisTimeout added in v1.1303.0

func (c *CodeConfig) SnykCodeAnalysisTimeout() time.Duration

func (*CodeConfig) SnykCodeApi added in v1.1303.0

func (c *CodeConfig) SnykCodeApi() string

type DataFlowItem

type DataFlowItem struct {
	Number         int
	FilePath       string
	StartLine      int
	EndLine        int
	StartCharacter int
	EndCharacter   int
	FileName       string
	Content        string
	StartLineValue int
}

type ExampleCommit

type ExampleCommit struct {
	CommitURL    string
	RepoName     string
	RepoLink     string
	ExampleLines []ExampleLines
}

type ExampleLines

type ExampleLines struct {
	LineNumber int
	Line       string
	LineChange string
}

type FakeCodeScannerClient

type FakeCodeScannerClient struct {
	UploadAndAnalyzeWasCalled bool
	Organization              string // Captures the org the scanner was created with
}

func (*FakeCodeScannerClient) Upload added in v1.1303.0

func (*FakeCodeScannerClient) UploadAndAnalyze

func (f *FakeCodeScannerClient) UploadAndAnalyze(
	_ context.Context,
	_ string,
	_ scan.Target,
	files <-chan string,
	_ map[string]bool,
) (*codeClientSarif.SarifResponse, string, error)

func (*FakeCodeScannerClient) UploadAndAnalyzeLegacy added in v1.1303.0

func (f *FakeCodeScannerClient) UploadAndAnalyzeLegacy(
	ctx context.Context,
	requestId string,
	target scan.Target,
	_ string,
	files <-chan string,
	changedFiles map[string]bool,
	statusChannel chan<- scan.LegacyScanStatus,
) (*codeClientSarif.SarifResponse, string, error)

type HtmlRenderer

type HtmlRenderer struct {
	AiFixHandler *AiFixHandler
	// contains filtered or unexported fields
}

func GetHTMLRenderer added in v1.1303.0

func GetHTMLRenderer(c *config.Config, featureFlagService featureflag.Service) (*HtmlRenderer, error)

func (*HtmlRenderer) GetDetailsHtml

func (renderer *HtmlRenderer) GetDetailsHtml(issue types.Issue) string

type IgnoreDetail

type IgnoreDetail struct {
	Label string
	Value string
}

type IssueEnhancer

type IssueEnhancer struct {
	// contains filtered or unexported fields
}

type SarifConverter

type SarifConverter struct {
	// contains filtered or unexported fields
}

type ScanStatus

type ScanStatus struct {
	// contains filtered or unexported fields
}

func NewScanStatus

func NewScanStatus() *ScanStatus

type Scanner

type Scanner struct {
	SnykApiClient snyk_api.SnykApiClient

	Instrumentor performance.Instrumentor
	C            *config.Config
	// contains filtered or unexported fields
}

func New

func New(c *config.Config, instrumentor performance.Instrumentor, apiClient snyk_api.SnykApiClient, reporter codeClientObservability.ErrorReporter, learnService learn.Service, featureFlagService featureflag.Service, notifier notification.Notifier, codeInstrumentor codeClientObservability.Instrumentor, codeErrorReporter codeClientObservability.ErrorReporter, codeScanner func(sc *Scanner, folderConfig *types.FolderConfig) (codeClient.CodeScanner, error)) *Scanner

func (*Scanner) AddBundleHash

func (sc *Scanner) AddBundleHash(key types.FilePath, value string)

func (*Scanner) BundleHashes

func (sc *Scanner) BundleHashes() map[types.FilePath]string

func (*Scanner) Clear

func (sc *Scanner) Clear()

func (*Scanner) ClearIssues

func (sc *Scanner) ClearIssues(path types.FilePath)

func (*Scanner) GetAutofixDiffs

func (sc *Scanner) GetAutofixDiffs(ctx context.Context, baseDir types.FilePath, filePath types.FilePath, issue types.Issue) (unifiedDiffSuggestions []llm.AutofixUnifiedDiffSuggestion, err error)

func (*Scanner) IsEnabled

func (sc *Scanner) IsEnabled() bool

func (*Scanner) IsProviderFor

func (sc *Scanner) IsProviderFor(issueType product.FilterableIssueType) bool

func (*Scanner) Issue

func (sc *Scanner) Issue(key string) types.Issue

func (*Scanner) Issues

func (sc *Scanner) Issues() snyk.IssuesByFile

func (*Scanner) IssuesForFile

func (sc *Scanner) IssuesForFile(path types.FilePath) []types.Issue

func (*Scanner) IssuesForRange

func (sc *Scanner) IssuesForRange(path types.FilePath, r types.Range) []types.Issue

func (*Scanner) Product

func (sc *Scanner) Product() product.Product

func (*Scanner) RegisterCacheRemovalHandler

func (sc *Scanner) RegisterCacheRemovalHandler(handler func(path types.FilePath))

func (*Scanner) Scan

func (sc *Scanner) Scan(ctx context.Context, path types.FilePath, folderPath types.FilePath, folderConfig *types.FolderConfig) (issues []types.Issue, err error)

func (*Scanner) SupportedCommands

func (sc *Scanner) SupportedCommands() []types.CommandName

func (*Scanner) UploadAndAnalyze

func (sc *Scanner) UploadAndAnalyze(ctx context.Context, path types.FilePath, folderConfig *types.FolderConfig, files <-chan string, changedFiles map[types.FilePath]bool, codeConsistentIgnores bool, t *progress.Tracker) (issues []types.Issue, err error)

type SnykAnalysisFailedError

type SnykAnalysisFailedError struct {
	Msg string
}

func (SnykAnalysisFailedError) Error

func (e SnykAnalysisFailedError) Error() string

type SnykAutofixFailedError

type SnykAutofixFailedError struct {
	Msg string
}

Should implement `error` interface

func (SnykAutofixFailedError) Error

func (e SnykAutofixFailedError) Error() string

type SpanRecorderCode

type SpanRecorderCode interface {
	Record(span codeClient.Span)
	Spans() []codeClient.Span
	ClearSpans()
	Finish(span codeClient.Span)
}

Directories

Path Synopsis
Package encoding implements encoding functionality
Package encoding implements encoding functionality

Jump to

Keyboard shortcuts

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