Documentation
¶
Overview ¶
Package code provides Snyk Code (SAST) scanning functionality.
Index ¶
- Constants
- Variables
- func ConvertSARIFJSONToIssues(logger *zerolog.Logger, hoverVerbosity int, sarifJSON []byte, basePath string) ([]types.Issue, error)
- func CreateCodeScanner(scanner *Scanner, folderConfig *types.FolderConfig) (codeClient.CodeScanner, error)
- func CreateWorkspaceEditFromDiff(absoluteFilePath string, diff string) (*types.WorkspaceEdit, error)
- func DecodePath(encodedRelativePath string) (string, error)
- func EncodePath(relativePath types.FilePath) types.FilePath
- func GetAutofixIdeExtensionDetails(c *config.Config) llm.AutofixIdeExtensionDetails
- func GetCodeApiUrlForFolder(c *config.Config, folder types.FilePath) (string, error)
- func GetIgnoreDetailsFromSuppressions(suppressions []codeClientSarif.Suppression) (bool, *types.IgnoreDetails)
- func NewAutofixCodeRequestContext(folderPath types.FilePath) llm.CodeRequestContext
- func NewCodeErrorReporter(errorReporter error_reporting.ErrorReporter) codeClient.ErrorReporter
- func NewCodeInstrumentor() codeClient.Instrumentor
- func NewCodeTrackerFactory() codeClientScan.TrackerFactory
- func NewFakeCodeScannerClient(sc *Scanner, folderConfig *types.FolderConfig) (codeClient.CodeScanner, error)
- func ResetHTMLRenderer()
- func SnykMagnetUri(issue types.Issue, ideAction string) (string, error)
- func TempWorkdirWithIssues(t *testing.T) (types.FilePath, types.FilePath)
- func ToAbsolutePath(baseDir types.FilePath, relativePath types.FilePath) string
- func ToRelativeUnixPath(baseDir types.FilePath, absoluteFilePath types.FilePath) (types.FilePath, error)
- type AiFixHandler
- func (fixHandler *AiFixHandler) EnrichWithExplain(ctx context.Context, c *config.Config, issue types.Issue, ...)
- func (fixHandler *AiFixHandler) GetAiFixDiffError() error
- func (fixHandler *AiFixHandler) GetAiFixDiffResult() []llm.AutofixUnifiedDiffSuggestion
- func (fixHandler *AiFixHandler) GetAiFixDiffStatus() AiStatus
- func (fixHandler *AiFixHandler) GetAutoTriggerAiFix() bool
- func (fixHandler *AiFixHandler) GetCurrentIssueId() string
- func (fixHandler *AiFixHandler) GetResults(fixId string) (filePath string, diff string, err error)
- func (fixHandler *AiFixHandler) SetAiFixDiffState(state AiStatus, suggestions []llm.AutofixUnifiedDiffSuggestion, err error, ...)
- func (fixHandler *AiFixHandler) SetAutoTriggerAiFix(isEnabled bool)
- type AiStatus
- type AnalysisRequest
- type AnalysisRequestKey
- type AutofixEventDetails
- type AutofixIdeExtensionDetails
- type AutofixRequest
- type AutofixRequestKey
- type AutofixResponse
- type AutofixSuggestion
- type AutofixUnifiedDiffSuggestion
- type AutofixUserEvent
- type CodeConfig
- type DataFlowItem
- type ExampleCommit
- type ExampleLines
- type FakeCodeScannerClient
- func (f *FakeCodeScannerClient) Upload(context.Context, string, scan.Target, <-chan string, map[string]bool) (bundle.Bundle, error)
- func (f *FakeCodeScannerClient) UploadAndAnalyze(_ context.Context, _ string, _ scan.Target, files <-chan string, ...) (*codeClientSarif.SarifResponse, string, error)
- func (f *FakeCodeScannerClient) UploadAndAnalyzeLegacy(ctx context.Context, requestId string, target scan.Target, _ string, ...) (*codeClientSarif.SarifResponse, string, error)
- type HtmlRenderer
- type IgnoreDetail
- type IssueEnhancer
- type SarifConverter
- type ScanStatus
- type Scanner
- func (sc *Scanner) AddBundleHash(key types.FilePath, value string)
- func (sc *Scanner) BundleHashes() map[types.FilePath]string
- func (sc *Scanner) Clear()
- func (sc *Scanner) ClearIssues(path types.FilePath)
- func (sc *Scanner) GetAutofixDiffs(ctx context.Context, baseDir types.FilePath, filePath types.FilePath, ...) (unifiedDiffSuggestions []llm.AutofixUnifiedDiffSuggestion, err error)
- func (sc *Scanner) IsEnabled() bool
- func (sc *Scanner) IsProviderFor(issueType product.FilterableIssueType) bool
- func (sc *Scanner) Issue(key string) types.Issue
- func (sc *Scanner) Issues() snyk.IssuesByFile
- func (sc *Scanner) IssuesForFile(path types.FilePath) []types.Issue
- func (sc *Scanner) IssuesForRange(path types.FilePath, r types.Range) []types.Issue
- func (sc *Scanner) Product() product.Product
- func (sc *Scanner) RegisterCacheRemovalHandler(handler func(path types.FilePath))
- func (sc *Scanner) Scan(ctx context.Context, path types.FilePath, folderPath types.FilePath, ...) (issues []types.Issue, err error)
- func (sc *Scanner) SupportedCommands() []types.CommandName
- func (sc *Scanner) UploadAndAnalyze(ctx context.Context, path types.FilePath, folderConfig *types.FolderConfig, ...) (issues []types.Issue, err error)
- type SnykAnalysisFailedError
- type SnykAutofixFailedError
- type SpanRecorderCode
Constants ¶
const ( FixPositiveFeedback string = "FIX_POSITIVE_FEEDBACK" FixNegativeFeedback string = "FIX_NEGATIVE_FEEDBACK" FixAppliedUserEvent string = "FIX_APPLIED" )
const ( DontUsePrintStackTrace string = "DontUsePrintStackTrace" CatchingInterruptedExceptionWithoutInterrupt string = "catchingInterruptedExceptionWithoutInterrupt" )
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" )
const (
ExplainApiVersion string = "2024-10-15"
)
const FixIssuePrefix = "⚡ Fix this issue: "
const ShowInDetailPanelIdeCommand = "showInDetailPanel"
Variables ¶
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 GetAutofixIdeExtensionDetails ¶ added in v1.1303.0
func GetAutofixIdeExtensionDetails(c *config.Config) llm.AutofixIdeExtensionDetails
func GetCodeApiUrlForFolder ¶ added in v1.1303.0
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 TempWorkdirWithIssues ¶
func ToAbsolutePath ¶
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 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 AutofixEventDetails ¶ added in v1.1303.0
type AutofixEventDetails struct {
FixId string `json:"fixId"`
}
type AutofixIdeExtensionDetails ¶ added in v1.1303.0
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 ¶
func (a AutofixUnifiedDiffSuggestion) String() 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 ExampleCommit ¶
type ExampleCommit struct {
CommitURL string
RepoName string
RepoLink string
ExampleLines []ExampleLines
}
type ExampleLines ¶
type FakeCodeScannerClient ¶
type FakeCodeScannerClient struct {
UploadAndAnalyzeWasCalled bool
Organization string // Captures the org the scanner was created with
}
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 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) ClearIssues ¶
func (*Scanner) GetAutofixDiffs ¶
func (*Scanner) IsProviderFor ¶
func (sc *Scanner) IsProviderFor(issueType product.FilterableIssueType) bool
func (*Scanner) Issues ¶
func (sc *Scanner) Issues() snyk.IssuesByFile
func (*Scanner) IssuesForRange ¶
func (*Scanner) RegisterCacheRemovalHandler ¶
func (*Scanner) SupportedCommands ¶
func (sc *Scanner) SupportedCommands() []types.CommandName
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)
}
Source Files
¶
- ai_fix_handler.go
- autofix.go
- cache.go
- code.go
- code_error_reporter.go
- code_html.go
- code_instrumentor.go
- code_tracker.go
- codeconfig.go
- constants.go
- conversion.go
- convert.go
- example_commit_fixes.go
- fake_code_client_scanner.go
- fake_snyk_code_api_service.go
- issue_enhancer.go
- path.go
- sarif_utils.go
- sast_local_engine.go
- snyk_code_http_client.go
- types.go