code

package
v0.0.0-...-28ae1cc Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2024 License: Apache-2.0 Imports: 56 Imported by: 0

Documentation

Overview

* © 2023 Snyk Limited All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.

Index

Constants

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"
)

Variables

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

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

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

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

	FakeFilters = []string{".cjs", ".ejs", ".es", ".es6", ".htm", ".html", ".js", ".jsx", ".mjs", ".ts", ".tsx", ".vue", ".java", ".erb", ".haml", ".rb", ".rhtml", ".slim", ".kt", ".swift", ".cls", ".config", ".pom", ".wxs", ".xml", ".xsd", ".aspx", ".cs", ".py", ".go", ".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".hxx", ".php", ".phtml"}
)

Functions

func DecodePath

func DecodePath(encodedRelativePath string) (string, error)

func EncodePath

func EncodePath(relativePath string) string

func NewCodeErrorReporter

func NewCodeErrorReporter(errorReporter error_reporting.ErrorReporter) codeClient.ErrorReporter

func NewCodeInstrumentor

func NewCodeInstrumentor() codeClient.Instrumentor

func NewCodeTrackerFactory

func NewCodeTrackerFactory() codeClientScan.TrackerFactory

func TempWorkdirWithVulnerabilities

func TempWorkdirWithVulnerabilities(t *testing.T) (filePath string, folderPath string)

func ToAbsolutePath

func ToAbsolutePath(baseDir string, relativePath string) string

func ToEncodedNormalizedPath

func ToEncodedNormalizedPath(rootPath string, filePath string) (string, error)

func ToRelativeUnixPath

func ToRelativeUnixPath(baseDir string, absoluteFilePath string) (string, error)

Types

type AnalysisOptions

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

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 []string `json:"limitToFiles,omitempty"`
	Shard        string   `json:"shard"`
}

type AnalysisStatus

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

type AutofixFeedback

type AutofixFeedback struct {
	FixId           string             `json:"fixId"`
	Feedback        string             `json:"feedback"`
	AnalysisContext codeRequestContext `json:"analysisContext"`
}

type AutofixOptions

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

type AutofixRequest

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

type AutofixRequestKey

type AutofixRequestKey struct {
	Type     string `json:"type"`
	Hash     string `json:"hash"`
	Shard    string `json:"shard"`
	FilePath string `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 AutofixStatus

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

type AutofixSuggestion

type AutofixSuggestion struct {
	FixId       string
	AutofixEdit snyk.WorkspaceEdit
}

AutofixSuggestion models a fix returned by autofix service

type AutofixUnifiedDiffSuggestion

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

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 Bundle

type Bundle struct {
	SnykCode      SnykCodeClient
	BundleHash    string
	UploadBatches []*UploadBatch
	Files         map[string]BundleFile
	// contains filtered or unexported fields
}

func (*Bundle) FetchDiagnosticsData

func (b *Bundle) FetchDiagnosticsData(
	ctx context.Context,
) ([]snyk.Issue, error)

func (*Bundle) Upload

func (b *Bundle) Upload(ctx context.Context, uploadBatch *UploadBatch) error

type BundleFile

type BundleFile struct {
	Hash    string `json:"hash"`
	Content string `json:"content"`
}

type BundleUploader

type BundleUploader struct {
	SnykCode SnykCodeClient
	// contains filtered or unexported fields
}

func NewBundler

func NewBundler(c *config.Config, SnykCode SnykCodeClient, instrumentor codeClientObservability.Instrumentor) *BundleUploader

func (*BundleUploader) Upload

func (b *BundleUploader) Upload(ctx context.Context, bundle Bundle, files map[string]BundleFile) (Bundle, error)

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
	// contains filtered or unexported fields
}

func (*FakeCodeScannerClient) UploadAndAnalyze

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

type FakeSnykCodeClient

type FakeSnykCodeClient struct {
	Calls               map[string][][]any
	HasCreatedNewBundle bool
	HasExtendedBundle   bool
	ExtendBundleFiles   map[string]BundleFile
	TotalBundleCount    int
	ExtendedBundleCount int
	AnalysisDuration    time.Duration
	FailOnCreateBundle  bool
	ConfigFiles         []string

	NoFixSuggestions       bool
	UnifiedDiffSuggestions []AutofixUnifiedDiffSuggestion
	Options                AnalysisOptions
	C                      *config.Config
	// contains filtered or unexported fields
}

func (*FakeSnykCodeClient) Clear

func (f *FakeSnykCodeClient) Clear()

func (*FakeSnykCodeClient) CreateBundle

func (f *FakeSnykCodeClient) CreateBundle(_ context.Context,
	files map[string]string,
) (bundleHash string, missingFiles []string, err error)

func (*FakeSnykCodeClient) ExtendBundle

func (f *FakeSnykCodeClient) ExtendBundle(
	_ context.Context,
	bundleHash string,
	files map[string]BundleFile,
	removedFiles []string,
) (string, []string, error)

func (*FakeSnykCodeClient) GetAllCalls

func (f *FakeSnykCodeClient) GetAllCalls(op string) [][]any

func (*FakeSnykCodeClient) GetAutoFixDiffs

func (f *FakeSnykCodeClient) GetAutoFixDiffs(ctx context.Context, baseDir string, options AutofixOptions) (unifiedDiffSuggestions []AutofixUnifiedDiffSuggestion, err error)

func (*FakeSnykCodeClient) GetAutofixSuggestions

func (f *FakeSnykCodeClient) GetAutofixSuggestions(
	_ context.Context,
	options AutofixOptions,
	baseDir string,
) ([]AutofixSuggestion, AutofixStatus, error)

func (*FakeSnykCodeClient) GetCallParams

func (f *FakeSnykCodeClient) GetCallParams(callNo int, op string) []any

func (*FakeSnykCodeClient) GetFilters

func (f *FakeSnykCodeClient) GetFilters(_ context.Context) (
	filters FiltersResponse,
	err error,
)

func (*FakeSnykCodeClient) RunAnalysis

func (f *FakeSnykCodeClient) RunAnalysis(
	_ context.Context,
	options AnalysisOptions,
	_ string,
) ([]snyk.Issue, AnalysisStatus, error)

func (*FakeSnykCodeClient) SubmitAutofixFeedback

func (f *FakeSnykCodeClient) SubmitAutofixFeedback(ctx context.Context, fixId string, positive bool) error

type FiltersResponse

type FiltersResponse struct {
	ConfigFiles []string `json:"configFiles" pact:"min=1"`
	Extensions  []string `json:"extensions" pact:"min=1"`
}

type IgnoreDetail

type IgnoreDetail struct {
	Label string
	Value string
}

type IssueEnhancer

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

type SarifConverter

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

type ScanMetrics

type ScanMetrics 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 {
	BundleUploader *BundleUploader
	SnykApiClient  snyk_api.SnykApiClient

	// global map to store last used bundle hashes for each workspace folder
	// these are needed when we want to retrieve auto-fixes for a previously
	// analyzed folder
	BundleHashes map[string]string
	// contains filtered or unexported fields
}

func New

func New(bundleUploader *BundleUploader,
	apiClient snyk_api.SnykApiClient,
	reporter codeClientObservability.ErrorReporter,
	analytics ux2.Analytics,
	learnService learn.Service,
	notifier notification.Notifier,
	codeScanner codeClient.CodeScanner,
) *Scanner

func (*Scanner) Clear

func (sc *Scanner) Clear()

func (*Scanner) ClearIssues

func (sc *Scanner) ClearIssues(path string)

func (*Scanner) GetAutoFixDiffs

func (sc *Scanner) GetAutoFixDiffs(
	ctx context.Context,
	baseDir string,
	filePath string,
	issue snyk.Issue,
) (unifiedDiffSuggestions []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) snyk.Issue

func (*Scanner) Issues

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

func (*Scanner) IssuesForFile

func (sc *Scanner) IssuesForFile(path string) []snyk.Issue

func (*Scanner) IssuesForRange

func (sc *Scanner) IssuesForRange(path string, r snyk.Range) []snyk.Issue

func (*Scanner) Product

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

func (*Scanner) RegisterCacheRemovalHandler

func (sc *Scanner) RegisterCacheRemovalHandler(handler func(path string))

func (*Scanner) Scan

func (sc *Scanner) Scan(ctx context.Context, path string, folderPath string) (issues []snyk.Issue, err error)

func (*Scanner) SupportedCommands

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

func (*Scanner) UploadAndAnalyze

func (sc *Scanner) UploadAndAnalyze(ctx context.Context,
	files <-chan string,
	path string,
	scanMetrics *ScanMetrics,
	changedFiles map[string]bool,
) (issues []snyk.Issue, err error)

func (*Scanner) UploadAndAnalyzeWithIgnores

func (sc *Scanner) UploadAndAnalyzeWithIgnores(ctx context.Context,
	path string,
	files <-chan string,
	changedFiles map[string]bool,
) (issues []snyk.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 SnykCodeClient

type SnykCodeClient interface {
	GetFilters(ctx context.Context) (
		filters FiltersResponse,
		err error)

	CreateBundle(
		ctx context.Context,
		files map[string]string,
	) (newBundleHash string, missingFiles []string, err error)

	ExtendBundle(
		ctx context.Context,
		bundleHash string,
		files map[string]BundleFile,
		removedFiles []string,
	) (newBundleHash string, missingFiles []string, err error)

	RunAnalysis(
		ctx context.Context,
		options AnalysisOptions,
		baseDir string,
	) (
		[]snyk.Issue,
		AnalysisStatus,
		error,
	)

	GetAutofixSuggestions(
		ctx context.Context,
		options AutofixOptions,
		baseDir string,
	) ([]AutofixSuggestion,
		AutofixStatus,
		error,
	)

	SubmitAutofixFeedback(ctx context.Context, fixId string, positive bool) error

	GetAutoFixDiffs(ctx context.Context, baseDir string, options AutofixOptions) (unifiedDiffSuggestions []AutofixUnifiedDiffSuggestion, err error)
}

type SnykCodeHTTPClient

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

func NewSnykCodeHTTPClient

func NewSnykCodeHTTPClient(
	c *config.Config,
	instrumentor codeClientObservability.Instrumentor,
	errorReporter codeClientObservability.ErrorReporter,
	client func() *http.Client,
) *SnykCodeHTTPClient

func (*SnykCodeHTTPClient) CreateBundle

func (s *SnykCodeHTTPClient) CreateBundle(
	ctx context.Context,
	filesToFilehashes map[string]string,
) (string, []string, error)

func (*SnykCodeHTTPClient) ExtendBundle

func (s *SnykCodeHTTPClient) ExtendBundle(
	ctx context.Context,
	bundleHash string,
	files map[string]BundleFile,
	removedFiles []string,
) (string, []string, error)

func (*SnykCodeHTTPClient) GetAutoFixDiffs

func (s *SnykCodeHTTPClient) GetAutoFixDiffs(ctx context.Context, baseDir string, options AutofixOptions) (unifiedDiffSuggestions []AutofixUnifiedDiffSuggestion, err error)

func (*SnykCodeHTTPClient) GetAutofixSuggestions

func (s *SnykCodeHTTPClient) GetAutofixSuggestions(
	ctx context.Context,
	options AutofixOptions,
	baseDir string,
) (autofixSuggestions []AutofixSuggestion,
	status AutofixStatus,
	err error,
)

func (*SnykCodeHTTPClient) GetFilters

func (s *SnykCodeHTTPClient) GetFilters(ctx context.Context) (
	filters FiltersResponse,
	err error,
)

func (*SnykCodeHTTPClient) RunAnalysis

func (s *SnykCodeHTTPClient) RunAnalysis(
	ctx context.Context,
	options AnalysisOptions,
	baseDir string,
) ([]snyk.Issue, AnalysisStatus, error)

func (*SnykCodeHTTPClient) RunAutofix

func (s *SnykCodeHTTPClient) RunAutofix(ctx context.Context, options AutofixOptions) (AutofixResponse, error)

func (*SnykCodeHTTPClient) SubmitAutofixFeedback

func (s *SnykCodeHTTPClient) SubmitAutofixFeedback(ctx context.Context, fixId string, positive bool) error

type SpanRecorderCode

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

type UploadBatch

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

func NewUploadBatch

func NewUploadBatch() *UploadBatch

type UploadStatus

type UploadStatus struct {
	UploadedFiles int
	TotalFiles    int
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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