Branch | Status |
---|---|
master | |
dev |
- JFrog Go Client
- Table of Contents
- General
- Pull Requests
- Tests
- General APIs
- Artifactory APIs
- Creating Artifactory Service Manager
- Using Artifactory Services
- Uploading Files to Artifactory
- Downloading Files from Artifactory
- Downloading Release Bundles from Artifactory
- Uploading and Downloading Files with Summary
- Copying Files in Artifactory
- Moving Files in Artifactory
- Deleting Files from Artifactory
- Searching Files in Artifactory
- Setting Properties on Files in Artifactory
- Deleting Properties from Files in Artifactory
- Getting Properties from Files in Artifactory
- Publishing Build Info to Artifactory
- Fetching Build Info from Artifactory
- Promoting Published Builds in Artifactory
- Promoting a Docker Image in Artifactory
- Triggering Build Scanning with JFrog Xray
- Discarding Old Builds
- Cleaning Unreferenced Git LFS Files from Artifactory
- Executing AQLs
- Reading Files in Artifactory
- Creating an Artifactory Access Token
- Fetching Artifactory Access Tokens
- Fetching Artifactory Access Tokens of a User
- Refreshing an Artifactory Access Token
- Revoking an Artifactory Access Token
- Create API Key
- Regenerate API Key
- Get API Key
- Creating and Updating Local Repository
- Creating and Updating Remote Repository
- Creating and Updating Virtual Repository
- Creating and Updating Federated Repository
- Removing a Repository
- Getting Repository Details
- Getting All Repositories
- Check if Repository Exists
- Creating and Updating Repository Replications
- Getting a Repository Replication
- Removing a Repository Replication
- Converting a Local Repository to a Federated Repository
- Triggering a Full Federated Repository Synchronisation
- Creating and Updating Permission Targets
- Removing a Permission Target
- Fetching a Permission Target
- Fetching Artifactory's Version
- Fetching Running Artifactory Nodes in a Cluster
- Fetching Artifactory's Service ID
- Fetching Artifactory's Config Descriptor
- Activating Artifactory's Key Encryption
- Deactivating Artifactory's Key Encryption
- Fetching Users Details
- Fetching All Users Details
- Creating Inviting and Updating a User
- Deleting a User
- Fetching Locked Out Users
- Unlock Locked Out User
- Fetching All Groups
- Fetching Group Details
- Creating and Updating a Group
- Deleting a Group
- Generating Full System Export
- Getting Info of a Folder in Artifactory
- Getting Info of a File in Artifactory
- Getting a listing of files and folders within a folder in Artifactory
- Getting Storage Summary Info of Artifactory
- Getting package artifact Lead File
- Triggering Storage Info Recalculation in Artifactory
- Access APIs
- Creating Access Service Manager
- Using Access Services
- Creating a New Project
- Updating a Project
- Deleting a Project
- Getting a Project
- Getting all Projects
- Assigning Repository to Project
- Un-assigning Repository from Project
- Get all groups assigned to a project
- Get a specific group assigned to a project
- Add or update a group assigned to a project
- Remove a group from a project
- Send Web Login Authentication Request
- Get Web Login Authentication Token
- Creating an Access Token
- Refreshing an Access Token
- Distribution APIs
- Using ContentReader
- Xray APIs
- Creating Xray Service Manager
- Using Xray Services
- Fetching Xray's Version
- Creating an Xray Watch
- Get an Xray Watch
- Update an Xray Watch
- Delete an Xray Watch
- Creating a Security Xray Policy
- Creating a License Xray Policy
- Get an Xray Policy
- Update an Xray Policy
- Delete an Xray Policy
- Create an Xray Ignore Rule
- Get an Xray Ignore Rule
- Delete an Xray Ignore Rule
- Add Builds to Indexing Configuration
- Request Graph Scan
- Retrieve the Graph Scan Results
- Request Graph Enrich
- Retrieve the Graph Enrich Results
- Get Token Validation Status
- Generate Vulnerabilities Report
- Get Vulnerabilities Report Details
- Get Vulnerabilities Report Content
- Delete Vulnerabilities Report
- Generate Licences Report
- Get Licences Report Details
- Get Licences Report Content
- Delete Licences Report
- Generate Violations Report
- Get Violations Report Details
- Get Violations Report Content
- Delete Violations Report
- Get Artifact Summary
- Get Entitlement info
- XSC APIs
- Pipelines APIs
- Creating Pipelines Service Manager
- Using Pipelines Services
- Fetching Pipelines' System Info
- Creating GitHub Integration
- Creating GitHub Enterprise Integration
- Creating Bitbucket Integration
- Creating Bitbucket Server Integration
- Creating Gitlab Integration
- Creating Artifactory Integration
- Get Integration by Id
- Get Integration by Name
- Get All Integrations
- Get All Raw Integrations
- Delete Integration
- Add Pipeline Source
- Get Recent Pipeline Run Status
- Trigger Pipeline Run
- Trigger Pipeline Sync
- Get Pipeline Sync Status
- Cancel Run
- Lifecycle APIs
- Creating Lifecycle Service Manager
- Using Lifecycle Services
- Creating a Release Bundle From AQL
- Creating a Release Bundle From Artifacts
- Creating a Release Bundle From Published Builds
- Creating a Release Bundle From Release Bundles
- Promoting a Release Bundle
- Get Release Bundle Creation Status
- Get Release Bundle Promotion Status
- Get Release Bundle Promotions
- Distribute Release Bundle
- Delete Release Bundle Version
- Delete Release Bundle Version Promotion
- Export Release Bundle Archive
- Import Release Bundle Archive
- Remote Delete Release Bundle
- Lifecycle APIs
- Evidence APIs
- Metadata APIs
jfrog-client-go is a library which provides Go APIs to performs actions on JFrog Artifactory, Xray and Distribution from your Go application. The project is still relatively new, and its APIs may therefore change frequently between releases. The library can be used as a go-module, which should be added to your project's go.mod file. As a reference you may look at JFrog CLI' s go.mod file, which uses this library as a dependency.
We welcome pull requests from the community.
- If the existing tests do not already cover your changes, please add tests.
- Pull requests should be created on the dev branch.
- Please use gofmt for formatting the code before submitting the pull request.
To run the tests on the source code, you'll need a running JFrog instance. See the Prerequisites column in the Test Types section below for more information.
Use the following command with the below options to run the tests.
go test -v github.com/jfrog/jfrog-client-go/tests -timeout 0 [test-types] [flags]
If you'd like to run a specific test, add the test function name using the -run
flag. For example:
go test -v github.com/jfrog/jfrog-client-go/tests -timeout 0 -run TestGetArtifactoryVersionWithCustomHttpClient -test.artifactory -rt.url=http://127.0.0.1:8081/artifactory -rt.user=admin -rt.password=password
Note: The tests create an Artifactory repository named jfrog-client-tests-repo1. Once the tests are completed, the content of this repository is deleted.
Type | Description | Prerequisites |
---|---|---|
-test.artifactory |
Artifactory tests | Artifactory Pro |
-test.distribution |
Distribution tests | Artifactory with Distribution |
-test.xray |
Xray tests | Artifactory with Xray |
-test.xsc |
Xsc tests | Xray with Xsc |
-test.pipelines |
Pipelines tests | JFrog Pipelines |
-test.access |
Access tests | Artifactory Pro |
-test.repositories |
Repositories tests | Artifactory Pro |
-test.mpu |
Multipart upload tests | Artifactory Pro with S3 storage |
Flag | Description |
---|---|
-rt.url |
[Default: http://localhost:8081/artifactory] Artifactory URL. |
-ds.url |
[Optional] JFrog Distribution URL. |
-xr.url |
[Optional] JFrog Xray URL. |
-xsc.url |
[Optional] JFrog Xsc URL. |
-pipe.url |
[Optional] JFrog Pipelines URL. |
-access.url |
[Optional] JFrog Access URL. |
-rt.user |
[Default: admin] Artifactory username. |
-rt.password |
[Default: password] Artifactory password. |
-rt.apikey |
[Optional] Artifactory API key. |
-rt.sshKeyPath |
[Optional] Ssh key file path. Should be used only if the Artifactory URL format is ssh://[domain]:port |
-rt.sshPassphrase |
[Optional] Ssh key passphrase. |
-pipe.accessToken |
[Optional] Pipelines access token. |
-pipe.vcsToken |
[Optional] Vcs token for Pipelines tests (should have admin permissions). |
-pipe.vcsRepo |
[Optional] Vcs full repo path for Pipelines tests (ex: "domain/myrepo"). |
-pipe.vcsBranch |
[Optional] Vcs branch for Pipelines tests (ex: "main"). |
-access.token |
[Optional] Access access token. |
-ci.runId |
[Optional] A unique identifier used as a suffix to create repositories in the tests. |
Default logger:
log.SetLogger(log.NewLogger(log.INFO, nil))
You may also log to a file, and/or add log prefixes as shown below:
var file *os.File
// Log flags as described in https://pkg.go.dev/log#pkg-constants.
logFlags := Ldate | Ltime
...
log.SetLogger(log.NewLoggerWithFlags(log.DEBUG, file, logFlags))
The default temp dir used is 'os.TempDir()'. Use the following API to set a new temp dir:
fileutils.SetTempDirBase(filepath.Join("my", "temp", "path"))
rtDetails := auth.NewArtifactoryDetails()
rtDetails.SetUrl("http://localhost:8081/artifactory")
rtDetails.SetSshKeyPath("path/to/.ssh/")
rtDetails.SetApiKey("apikey")
rtDetails.SetUser("user")
rtDetails.SetPassword("password")
rtDetails.SetAccessToken("accesstoken")
// if client certificates are required
rtDetails.SetClientCertPath("path/to/.cer")
rtDetails.SetClientCertKeyPath("path/to/.key")
proxyUrl, err := url.Parse("http://proxyIp:proxyPort")
myCustomClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}
rtDetails := auth.NewArtifactoryDetails()
rtDetails.SetUrl("http://localhost:8081/artifactory")
rtDetails.SetSshKeysPath("path/to/.ssh/")
rtDetails.SetApiKey("apikey")
rtDetails.SetUser("user")
rtDetails.SetPassword("password")
rtDetails.SetAccessToken("accesstoken")
serviceConfig, err := config.NewConfigBuilder().
SetServiceDetails(rtDetails).
SetDryRun(false).
SetHttpClient(myCustomClient).
Build()
serviceConfig, err := config.NewConfigBuilder().
SetServiceDetails(rtDetails).
SetCertificatesPath(certPath).
SetThreads(threads).
SetDryRun(false).
// Add [Context](https://golang.org/pkg/context/)
SetContext(ctx).
// Optionally overwrite the default dial timeout, which is set to 30 seconds.
SetDialTimeout(180 * time.Second).
// Optionally set the total HTTP request timeout.
SetOverallRequestTimeout(10 * time.Minute).
// Optionally overwrite the default HTTP retries, which is set to 3.
SetHttpRetries(8).
Build()
rtManager, err := artifactory.New(serviceConfig)
Using the UploadFiles()
function, we can upload files and get the general statistics of the action (The actual number
of successful and failed uploads), and the error value if it occurred.
params := services.NewUploadParams()
params.Pattern = "repo/*/*.zip"
params.Target = "repo/path/"
params.AddVcsProps = false
params.BuildProps = "build.name=buildName;build.number=17;build.timestamp=1600856623553"
params.Recursive = true
params.Regexp = false
params.IncludeDirs = false
params.Flat = true
params.ExplodeArchive = false
params.Archive = "zip"
params.Deb = ""
params.Symlink = false
params.Exclusions = "(.*)a.zip"
// Retries default value: 3
params.Retries = 5
// The maximum number of parts that can be concurrently uploaded per file during a multi-part upload. Set to 0 to disable multi-part upload.
// SplitCount default value: 5
params.SplitCount = 10
// The minimum file size in MiB required to attempt a multi-part upload.
// MinSplitSize default value: 200
params.MinSplitSize = 100
// The upload chunk size in MiB that can be concurrently uploaded during a multi-part upload.
params.ChunkSize = 5
// The min file size in bytes for "checksum deploy".
// "Checksum deploy" is the action of calculating the file checksum locally, before
// the upload, and skipping the actual file transfer if the file already
// exists in Artifactory.
// MinChecksumDeploy default value: 10400
params.MinChecksumDeploy = 15360
// Set to false to disable all checksum calculation, including "checksum deploy".
// ChecksumsCalcEnabled default value: true
params.ChecksumsCalcEnabled = false
// Attach properties to the uploaded files
targetProps := utils.NewProperties()
targetProps.AddProperty("key1", "val1")
params.TargetProps = targetProps
// When using the 'archive' option for upload, we can control the target path inside the uploaded archive using placeholders. This operation determines the TargetPathInArchive value.
TargetPathInArchive := "archive/path/"
// Size limit for files to be uploaded.
SizeLimit= &fspatterns.SizeThreshold{SizeInBytes: 10000, Condition: fspatterns.LessThan}
uploadServiceOptions := &UploadServiceOptions{
// Set to true to fail the upload operation if any of the files fail to upload
FailFast: false,
}
totalUploaded, totalFailed, err := rtManager.UploadFiles(uploadServiceOptions, params)
Using the DownloadFiles()
function, we can download files and get the general statistics of the action (The actual
number of files downloaded, and the number of files we expected to download). In addition, we get the error value if it
occurred.
params := services.NewDownloadParams()
params.Pattern = "repo/*/*.zip"
params.Target = "target/path/"
// Filter the downloaded files by properties.
params.Props = "key1=val1;key2=val2"
params.Recursive = true
params.IncludeDirs = false
params.Flat = false
params.Explode = false
params.Symlink = true
params.ValidateSymlink = false
params.Exclusions = "(.*)a.zip"
// Retries default value: 3
params.Retries = 5
// SplitCount default value: 3
params.SplitCount = 2
// MinSplitSize default value: 5120
params.MinSplitSize = 7168
// Optional fields to avoid AQL request
Sha256 = "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9"
Size = 1000
totalDownloaded, totalFailed, err := rtManager.DownloadFiles(params)
Using the DownloadFiles()
function, we can download release bundles v1 and get the general statistics of the action (The
actual number of files downloaded, and the number of files we expected to download). In addition, we get the error value
if it occurred.
It is possible to validate the downloaded release bundle's files by providing a local path to a GPG public key file (the public GPG key should of course correspond to the private GPG key which was used to sign the release bundle).
params := services.NewDownloadParams()
// Path on the local file system to which the files should be downloaded.
params.Target = "target/path/"
// Bundle's name and version should be separated with "/".
params.Bundle = "bundleName/10"
// Optional GPG validation
params.PublicGpgKey = "public/key/file/path"
totalDownloaded, totalFailed, err := rtManager.DownloadFiles(params)
Read more about GPG signing release bundles v1 here.
The methods UploadFilesWithSummary()
and DownloadFilesWithSummary()
are similar to UploadFlies()
and DownloadFlies()
, but return an OperationSummary struct, which allows iterating over the details of the
uploaded/downloaded files.
The OperationSummary struct contains:
- TotalSucceeded - the number of successful uploads/downloads
- TotalFailed - the number of failed uploads/downloads
- TransferDetailsReader - a ContentReader of FileTransferDetails structs, with a struct for each successful transfer of file
- ArtifactsDetailsReader - a ContentReader of ArtifactDetails structs, with a struct for each artifact in Artifactory that was uploaded/downloaded successfully
The ContentReaders can be closed separately by calling Close()
on each of them, or they both can be closed at once by
calling Close()
on the OperationSummary struct.
params := services.NewUploadParams()
params.Pattern = "repo/*/*.zip"
params.Target = "repo/path/"
uploadServiceOptions := &UploadServiceOptions{
// Set to true to fail the upload operation if any of the files fail to upload
FailFast: false,
}
summary, err := rtManager.UploadFilesWithSummary(uploadServiceOptions, params)
defer summary.Close()
reader, totalDownloaded, totalExpected, err := rtManager.DownloadFilesWithResultReader(params)
// Iterate over each file
for currentFileInfo := new(utils.FileInfo); reader.NextRecord(currentFileInfo) == nil; currentFileInfo = new(utils.FileInfo) {
fmt.Printf("File path: %s\n", currentFileInfo.LocalPath)
}
if err := reader.GetError(); err != nil {
return err
}
Read more about ContentReader.
params := services.NewMoveCopyParams()
params.Pattern = "repo/*/*.zip"
params.Target = "target/path/"
// Filter the files by properties.
params.Props = "key1=val1;key2=val2"
params.Recursive = true
params.Flat = false
rtManager.Copy(params)
params := services.NewMoveCopyParams()
params.Pattern = "repo/*/*.zip"
params.Target = "target/path/"
// Filter the files by properties.
params.Props = "key1=val1;key2=val2"
params.Recursive = true
params.Flat = false
rtManager.Move(params)
params := services.NewDeleteParams()
params.Pattern = "repo/*/*.zip"
// Filter the files by properties.
params.Props = "key1=val1;key2=val2"
params.Recursive = true
pathsToDelete, err := rtManager.GetPathsToDelete(params)
if err != nil {
return err
}
defer pathsToDelete.Close()
rtManager.DeleteFiles(pathsToDelete)
Read more about ContentReader.
params := services.NewSearchParams()
params.Pattern = "repo/*/*.zip"
// Filter the files by properties.
params.Props = "key1=val1;key2=val2"
params.Recursive = true
reader, err := rtManager.SearchFiles(params)
if err != nil {
return err
}
defer reader.Close()
Read more about ContentReader.
searchParams = services.NewSearchParams()
searchParams.Recursive = true
searchParams.IncludeDirs = false
reader, err = rtManager.SearchFiles(searchParams)
if err != nil {
return err
}
defer reader.Close()
propsParams = services.NewPropsParams()
propsParams.Pattern = "repo/*/*.zip"
propsParams.Reader = reader
// Filter the files by properties.
propsParams.Props = "key=value"
rtManager.SetProps(propsParams)
Read more about ContentReader.
searchParams = services.NewSearchParams()
searchParams.Recursive = true
searchParams.IncludeDirs = false
resultItems, err = rtManager.SearchFiles(searchParams)
if err != nil {
return err
}
defer reader.Close()
propsParams = services.NewPropsParams()
propsParams.Pattern = "repo/*/*.zip"
propsParams.Reader = reader
// Filter the files by properties.
propsParams.Props = "key=value"
rtManager.DeleteProps(propsParams)
rtManager.GetItemProperties("repo/path/file")
Read more about ContentReader.
buildInfo := &buildinfo.BuildInfo{}
// Optional Artifactory project key
projectKey := "my-project-key"
...
rtManager.PublishBuildInfo(buildInfo, projectKey)
buildInfoParams := services.NewBuildInfoParams{}
buildInfoParams.BuildName = "buildName"
buildInfoParams.BuildNumber = "LATEST"
// Optional Artifactory project key
buildInfoParams.ProjectKey = "my-project-key"
rtManager.GetBuildInfo(buildInfoParams)
params := services.NewPromotionParams()
params.BuildName = "buildName"
params.BuildNumber = "10"
params.TargetRepo = "target-repo"
params.Status = "status"
params.Comment = "comment"
params.Copy = &trueValue
params.FailFast = true
params.IncludeDependencies = &falseValue
params.SourceRepo = "source-repo"
// Optional Artifactory project key
params.ProjectKey = "my-project-key"
rtManager.PromoteBuild(params)
sourceDockerImage := "hello-world"
sourceRepo := "docker-local-1"
targetRepo := "docker-local-2"
params := services.NewDockerPromoteParams(sourceDockerImage, sourceRepo, targetRepo)
// Optional parameters:
params.TargetDockerImage = "target-docker-image"
params.SourceTag = "42"
params.TargetTag = "43"
params.Copy = true
rtManager.PromoteDocker(params)
params := services.NewXrayScanParams()
params.BuildName = buildName
params.BuildNumber = buildNumber
rtManager.XrayScanBuild(params)
params := services.NewDiscardBuildsParams()
params.BuildName = "buildName"
params.MaxDays = "max-days"
params.MaxBuilds = "max-builds"
params.ExcludeBuilds = "1,2"
params.DeleteArtifacts = false
params.Async = false
// Optional Artifactory project key
projectKey := "my-project-key"
rtManager.DiscardBuilds(params)
params := services.NewGitLfsCleanParams()
params.Refs = "refs/remotes/*"
params.Repo = "my-project-lfs"
params.GitPath = "path/to/git"
reader,err := rtManager.GetUnreferencedGitLfsFiles(params)
defer reader.Close()
rtManager.DeleteFiles(reader)
rtManager.Aql(aql string)
rtManager.ReadRemoteFile(FilePath string)
params := services.NewCreateTokenParams()
params.Scope = "api:* member-of-groups:readers"
params.Username = "user"
params.ExpiresIn = 3600 // default -1 (use server default)
params.GrantType = "client_credentials"
params.Refreshable = true
params.Audience = "jfrt@<serviceID1> jfrt@<serviceID2>"
results, err := rtManager.CreateToken(params)
results, err := rtManager.GetTokens()
results, err := rtManager.GetUserTokens(username)
params := services.NewRefreshTokenParams()
params.AccessToken = "<access token>"
params.RefreshToken = "<refresh token>"
params.Token.Scope = "api:*"
params.Token.ExpiresIn = 3600
results, err := rtManager.RefreshToken(params)
params := services.NewRevokeTokenParams()
// Provide either TokenId or Token
params.TokenId = "<token id>"
// params.Token = "access token"
err := rtManager.RevokeToken(params)
// Returns an error if API key already exists - use RegenerateAPIKey instead.
apiKey, err := rtManager.CreateAPIKey()
apiKey, err := rtManager.RegenerateAPIKey()
apiKey, err := rtManager.GetAPIKey()
You can create and update a local repository for the following package types:
Alpine, Bower, Cran, Cargo, Chef, Cocoapods, Composer, Conan, Conda, Debian, Docker, Gems, Generic, Gitlfs, Go, Gradle, Helm, Ivy, Maven, Npm, Nuget, Opkg, Puppet, Pypi, Rpm, Sbt, Swift, Terraform, Vagrant, and Yum.
Each package type has its own parameters struct, can be created using the method
New<packageType>LocalRepositoryParams()
.
Example for creating local Generic repository:
params := services.NewGenericLocalRepositoryParams()
params.Key = "generic-repo"
params.Description = "This is a public description for generic-repo"
params.Notes = "These are internal notes for generic-repo"
params.RepoLayoutRef = "simple-default"
params.ArchiveBrowsingEnabled = true
params.XrayIndex = true
params.IncludesPattern = "**/*"
params.ExcludesPattern = "excludedDir/*"
params.DownloadRedirect = true
err = servicesManager.CreateLocalRepository().Generic(params)
You can also create a local repository with basic local params:
params := services.NewLocalRepositoryBaseParams()
params.Key = "generic-repo"
params.PackageType = "generic"
params.Description = "This is a public description for generic-repo"
err := servicesManager.CreateLocalRepository(params)
Updating local Generic repository:
err = servicesManager.UpdateLocalRepository().Generic(params)
You can create and update a remote repository for the following package types:
Alpine, Bower, Cran, Cargo, Chef, Cocoapods, Composer, Conan, Conda, Debian, Docker, Gems, Generic, Gitlfs, Go, Gradle, Helm, Ivy, Maven, Npm, Nuget, Opkg, P2, Puppet, Pypi, Rpm, Sbt, Swift, Terraform, Vcs, and Yum.
Each package type has its own parameters struct, can be created using the method
New<packageType>RemoteRepositoryParams()
.
Example for creating remote Maven repository:
params := services.NewMavenRemoteRepositoryParams()
params.Key = "maven-central-remote"
params.Url = "https://repo.maven.apache.org"
params.RepoLayoutRef = "maven-2-default"
params.Description = "A caching proxy repository for Maven central"
params.HandleSnapshot = false
params.HandleReleases = true
params.FetchJarsEagerly = true
params.XrayIndex = true
params.AssumedOfflinePeriodSecs = 600
params.SuppressPomConsistencyChecks = true
params.RemoteRepoChecksumPolicyType = "pass-thru"
err = servicesManager.CreateRemoteRepository().Maven(params)
Updating remote Maven repository:
err = servicesManager.UpdateRemoteRepository().Maven(params)
You can also create a remote repository with basic remote params:
params := services.NewRemoteRepositoryBaseParams()
params.Key = "remote-repo"
params.Url = "https://repo.maven.apache.org"
err := servicesManager.CreateRemoteRepository(params)
You can create and update a virtual repository for the following package types:
Alpine, Bower, Cran, Chef, Conan, Conda, Debian, Docker, Gems, Generic, Gitlfs, Go, Gradle, Helm, Ivy, Maven, Npm, Nuget, P2, Puppet, Pypi, Rpm, Sbt, Swift, Terraform and Yum.
Each package type has its own parameters struct, can be created using the method
New<packageType>VirtualRepositoryParams()
.
Example for creating virtual Go repository:
params := services.NewGoVirtualRepositoryParams()
params.Description = "This is an aggregated repository for several go repositories"
params.RepoLayoutRef = "go-default"
params.Repositories = {"gocenter-remote", "go-local"}
params.DefaultDeploymentRepo = "go-local"
params.ExternalDependenciesEnabled = true
params.ExternalDependenciesPatterns = {"**/github.com/**", "**/golang.org/**", "**/gopkg.in/**"}
params.ArtifactoryRequestsCanRetrieveRemoteArtifacts = true
err = servicesManager.CreateVirtualRepository().Go(params)
You can also create a virtual repository with basic virtual params:
params := services.NewVirtualRepositoryBaseParams()
params.Key = "generic-repo"
params.PackageType = "generic"
params.Description = "This is a public description for generic-repo"
params.Repositories = string[]{"remote-repo","local-repo"}
err := servicesManager.CreateVirtualRepository(params)
Updating virtual Go repository:
err = servicesManager.UpdateVirtualRepository().Go(params)
You can create and update a federated repository for the following package types:
Alpine, Bower, Cran, Cargo, Chef, Cocoapods, Composer, Conan, Conda, Debian, Docker, Gems, Generic, Gitlfs, Go, Gradle, Helm, Ivy, Maven, Npm, Nuget, Opkg, Puppet, Pypi, Rpm, Sbt, Swift, Terraform, Vagrant and Yum
Each package type has its own parameters struct, can be created using the method
New<packageType>FederatedRepositoryParams()
.
Example for creating federated Generic repository:
params := services.NewGenericFederatedRepositoryParams()
params.Key = "generic-repo"
params.Description = "This is a public description for generic-repo"
params.Notes = "These are internal notes for generic-repo"
params.RepoLayoutRef = "simple-default"
params.ArchiveBrowsingEnabled = true
params.XrayIndex = true
params.IncludesPattern = "**/*"
params.ExcludesPattern = "excludedDir/*"
params.DownloadRedirect = true
params.Members = []services.FederatedRepositoryMemberParams{
{Url: "http://targetartifactory/artifactory/federatedRepositoryName", Enabled: true},
}
err = servicesManager.CreateFederatedRepository().Generic(params)
You can also create a federated repository with basic federated params:
params := services.NewFederatedRepositoryBaseParams()
params.Key = "generic-repo"
params.PackageType = "generic"
params.Description = "This is a public description for generic-repo"
params.Members = []services.FederatedRepositoryMemberParams{
{Url: "http://targetartifactory/artifactory/federatedRepositoryName", Enabled: true},
}
err := servicesManager.CreateFederatedRepository(params)
Updating federated Generic repository:
err = servicesManager.UpdateFederatedRepository().Generic(params)
You can remove a repository from Artifactory using its key:
servicesManager.DeleteRepository("generic-repo")
You can get repository details from Artifactory using its key, and the desired params struct. The function expects to get the repo key (name) and a pointer to a param struct that will be filled up. The param struct should contain the desired params fields corresponded to the Artifactory REST API:
repoDetails = services.RepositoryDetails{}
err := servicesManager.GetRepository("maven-repo", &repoDetails)
repoDetails = services.LocalRepositoryBaseParams{}
err := servicesManager.GetRepository("maven-repo", &repoDetails)
repoDetails = services.MavenLocalRepositoryParams{}
err := servicesManager.GetRepository("maven-repo", &repoDetails)
services.RepositoryDetails
You can get all repositories from Artifactory:
servicesManager.GetAllRepositories()
You can get all repositories from Artifactory filtered according to theirs type and/or theirs package type:
params := services.NewRepositoriesFilterParams()
params.RepoType = "remote"
params.PackageType = "maven"
params.ProjectKey = "project-key"
err := servicesManager.GetAllRepositoriesFiltered(params)
You can check whether a repository exists in Artifactory:
exists, err := servicesManager.IsRepoExists()
Example of creating a repository replication:
params := services.NewCreateReplicationParams()
// Source replication repository.
params.RepoKey = "my-repository"
params.CronExp = "0 0 12 * * ?"
params.Username = "admin"
params.Password = "password"
params.Url = "http://localhost:8081/artifactory/remote-repo"
params.Enabled = true
params.SocketTimeoutMillis = 15000
params.EnableEventReplication = true
params.SyncDeletes = true
params.SyncProperties = true
params.SyncStatistics = true
params.PathPrefix = "/path/to/repo"
err = servicesManager.CreateReplication(params)
Example of updating a local repository replication:
params := services.NewUpdateReplicationParams()
// Source replication repository.
params.RepoKey = "my-repository"
params.CronExp = "0 0 12 * * ?"
params.Enabled = true
params.SocketTimeoutMillis = 15000
params.EnableEventReplication = true
params.SyncDeletes = true
params.SyncProperties = true
params.SyncStatistics = true
params.PathPrefix = "/path/to/repo"
err = servicesManager.UpdateReplication(params)
You can get a repository replication configuration from Artifactory using its key:
replicationConfiguration, err := servicesManager.GetReplication("my-repository")
You can remove a repository replication configuration from Artifactory using its key:
err := servicesManager.DeleteReplication("my-repository")
You can convert a local repository to a federated repository using its key:
err := servicesManager.ConvertLocalToFederatedRepository("my-repository")
You can trigger a full federated repository synchronisation for all members using its key:
err := servicesManager.TriggerFederatedRepositoryFullSyncAll("my-repository")
You can also trigger a full federated repository synchronisation for a specific member using its key and the members URL
err := servicesManager.TriggerFederatedRepositoryFullSyncMirror("my-repository", "http://localhost:8081/artifactory/my-repository")
You can create or update a permission target in Artifactory.
Permissions are set according to the following conventions:
read, write, annotate, delete, manage, managedXrayMeta, distribute
For repositories You can specify the name "ANY"
in order to apply to all repositories, "ANY REMOTE"
for all remote
repositories or "ANY LOCAL"
for all local repositories.
Creating a new permission target :
params := services.NewPermissionTargetParams()
params.Name = "java-developers"
params.Repo = &services.PermissionTargetSection{}
params.Repo.Repositories = []string{"ANY REMOTE", "local-repo1", "local-repo2"}
params.Repo.ExcludePatterns = []string{"dir/*"}
params.Repo.Actions = &services.Actions{}
params.Repo.Actions.Users = map[string][]string{
"user1": {"read", "write"},
"user2": {"write", "annotate", "read"},
}
params.Repo.Actions.Groups = map[string][]string{
"group1": {"manage", "read", "annotate"},
}
// This is the default value that cannot be changed
params.Build = &services.PermissionTargetSection{}
params.Build.Repositories = []string{"artifactory-build-info"}
params.Build.Actions = &services.Actions{}
params.Build.Actions.Groups = map[string][]string{
"group1": {"manage", "read", "write", "annotate", "delete"},
"group2": {"read"},
}
err := testsPermissionTargetService.Create(params)
Updating an existing permission target :
err = servicesManager.UpdatePermissionTarget(params)
You can remove a permission target from Artifactory using its name:
err = servicesManager.DeletePermissionTarget("java-developers")
You can fetch a permission target from Artifactory using its name:
permissionTargetParams, err = servicesManager.GetPermissionTarget("java-developers")
If the requested permission target does not exist, a nil value is returned for the permissionTargetParams param, with a nil error value
version, err := servicesManager.GetVersion()
runningNodes, err := servicesManager.GetRunningNodes()
serviceId, err := servicesManager.GetServiceId()
Notice: This API is enabled only on self-hosted Artifactory servers
serviceId, err := servicesManager.GetConfigDescriptor()
Notice: This API is enabled only on self-hosted Artifactory servers
err := servicesManager.ActivateKeyEncryption()
Notice: This API is enabled only on self-hosted Artifactory servers
wasEncrypted, err := servicesManager.DeactivateKeyEncryption()
params := services.NewUserParams()
params.UserDetails.Name = "myUserName"
user, err := serviceManager.GetUser(params)
If the requested user does not exist, a nil value is returned for the User param, with a nil error value
You can get all users from Artifactory:
users, err := servicesManager.GetAllUsers()
params := services.NewUserParams()
params.UserDetails.Name = "myUserName"
params.UserDetails.Email = "[email protected]"
params.UserDetails.Password = "Password1"
params.UserDetails.Admin = &falseValue
params.UserDetails.Realm = "internal"
params.UserDetails.ProfileUpdatable = &trueValue
params.UserDetails.DisableUIAccess = &falseValue
params.UserDetails.InternalPasswordDisabled = &falseValue
params.UserDetails.groups = []string{"GroupA", "GroupB"}
// Set to true to replace existing user with the same name.
params.ReplaceIfExists = false
err := serviceManager.CreateUser(params)
// Inviting user to the platform.
param.UserDetails.ShouldInvite = &trueValue
param.UserDetails.Source = "cli"
err := serviceManager.CreateUser(params)
params.UserDetails.groups = []string{"GroupA", "GroupB", "GroupC"}
err := serviceManager.UpdateUser(params)
// Set to true to remove a user from every group.
params.UserDetails.ClearGroups = true
err := serviceManager.UpdateUser(params)
err := serviceManager.DeleteUser("myUserName")
lockedUsers, err := serviceManager.GetLockedUsers()
Unlocks a locked out user. This function succeeds even if the user doesn't exist or not locked.
err := serviceManager.UnlockUser("userToUnlock")
You can get all groups from Artifactory
groups, err := serviceManager.GetAllGroups()
params := services.NewGroupParams()
params.GroupDetails.Name = "myGroupName"
// Set this param to true to receive the usernames associated with this group
params.IncludeUsers = true
group, err := serviceManager.GetGroup(params)
If the requested group does not exist, a nil value is returned for the Group param, with a nil error value
params := services.NewGroupParams()
params.GroupDetails.Name = "myGroupName"
params.GroupDetails.Description = "Description"
params.GroupDetails.AutoJoin = &falseValue
params.GroupDetails.AdminPrivileges = &trueValue
params.GroupDetails.Realm = "internal"
params.GroupDetails.UsersNames = [2]string{"UserA", "UserB"}
// Set to true in order to replace exist group with the same name
params.ReplaceIfExists = false
err := serviceManager.CreateGroup(params)
params.GroupDetails.Description = "Newer Description"
// Will add UserC to the group (in addition to existing UserA and UserB)
params.GroupDetails.UsersNames = [1]string{"UserC"}
err := serviceManager.UpdateGroup(params)
err := serviceManager.DeleteGroup("myGroupName")
params := services.NewExportParams("/tmp/")
err := serviceManager.Export(params)
serviceManager.FolderInfo("repo/path/")
serviceManager.FileInfo("repo/path/file")
optionalParams := servicesutils.NewFileListParams()
optionalParams.Deep= true
optionalParams.Depth= 2
optionalParams.ListFolders= true
optionalParams.MetadataTimestamps= true
optionalParams.IncludeRootPath= true
serviceManager.FileList("repo/path/", optionalParams)
storageInfo, err := serviceManager.GetStorageInfo()
leadArtifact, err := serviceManager.GetPackageLeadFile()
err := serviceManager.CalculateStorageInfo()
accessDetails := accessAuth.NewAccessDetails()
accessDetails.SetUrl("http://localhost:8081/access/")
accessDetails.SetSshKeyPath("path/to/.ssh/")
accessDetails.SetApiKey("apikey")
accessDetails.SetUser("user")
accessDetails.SetPassword("password")
accessDetails.SetAccessToken("accesstoken")
// if client certificates are required
accessDetails.SetClientCertPath("path/to/.cer")
accessDetails.SetClientCertKeyPath("path/to/.key")
serviceConfig, err := clientConfig.NewConfigBuilder().
SetServiceDetails(accessAuth).
SetCertificatesPath(certsPath).
SetInsecureTls(accessDetails.InsecureTls).
SetDryRun(isDryRun).
Build()
accessManager, err := access.New(serviceConfig)
adminPriviligies := accessServices.AdminPrivileges{
ManageMembers: &trueValue,
ManageResources: &trueValue,
IndexResources: &trueValue,
}
projectDetails := accessServices.Project{
DisplayName: "testProject",
Description: "My Test Project",
AdminPrivileges: &adminPriviligies,
SoftLimit: &falseValue,
StorageQuotaBytes: 1073741825, // needs to be higher than 1073741824
ProjectKey: "tstprj",
}
projectParams = accessServices.NewProjectParams()
projectParams.ProjectDetails = projectDetails
err = accessManager.CreateProject(projectParams)
adminPriviligies := accessServices.AdminPrivileges{
ManageMembers: true,
ManageResources: true,
IndexResources: true,
}
projectDetails := accessServices.Project{
DisplayName: "testProject",
Description: "My Test Project",
AdminPrivileges: &adminPriviligies,
SoftLimit: &falseValue,
StorageQuotaBytes: 1073741825, // needs to be higher than 1073741824
ProjectKey: "tstprj",
}
projectParams = accessServices.NewProjectParams()
projectParams.ProjectDetails = projectDetails
err = accessManager.UpdateProject(projectParams)
err = accessManager.DeleteProject("tstprj")
err = accessManager.GetProject("tstprj")
err = accessManager.GetAllProjects()
// Params: (repositoryName, projectKey string, isForce bool)
err = accessManager.AssignRepoToProject("repoName", "tstprj", true)
err = accessManager.AssignRepoToProject("repoName")
err = accessManager.GetProjectsGroups("tstprj")
err = accessManager.GetProjectsGroup("tstprj", "tstgroup")
projectGroup := accessServices.ProjectGroup{
Name: "tstgroup",
Roles: []string{"Contributor","Release Manager"},
}
err = accessManager.UpdateGroupInProject("tstprj", "tstgroup", projectGroup)
err = accessManager.DeleteExistingProjectGroup("tstprj", "tstgroup")
uuid := "09b34617-b48a-455d-8b05-25a6989fb76a"
err = accessManager.SendLoginAuthenticationRequest(uuid)
uuid := "09b34617-b48a-455d-8b05-25a6989fb76a"
err = accessManager.GetLoginAuthenticationToken(uuid)
params := CreateTokenParams{}
params.Scope = "applied-permissions/user"
params.Username = "my-user"
params.ExpiresIn = 12345 // nil = system default, 0 = no expiry.
params.Refreshable = true
params.Audience = "jfrt@<serviceID1>"
reference := true
params.IncludeReferenceToken = &reference
params.ProjectKey = "my-project"
params.Description = "my-token"
results, err := accessManager.CreateToken(params)
params := accessServices.CreateTokenParams{}
params.RefreshToken = "<refresh token>"
results, err := accessManager.RefreshToken(params)
distDetails := auth.NewDistributionDetails()
distDetails.SetUrl("http://localhost:8081/distribution")
distDetails.SetSshKeyPath("path/to/.ssh/")
distDetails.SetApiKey("apikey")
distDetails.SetUser("user")
distDetails.SetPassword("password")
distDetails.SetAccessToken("accesstoken")
// if client certificates are required
distDetails.SetClientCertPath("path/to/.cer")
distDetails.SetClientCertKeyPath("path/to/.key")
serviceConfig, err := config.NewConfigBuilder().
SetServiceDetails(rtDetails).
SetCertificatesPath(certPath).
SetThreads(threads).
SetDryRun(false).
// Add [Context](https://golang.org/pkg/context/)
SetContext(ctx).
// Optionally overwrite the default HTTP retries, which is set to 3.
SetHttpRetries(8).
Build()
distManager, err := distribution.New(serviceConfig)
params := services.NewSetSigningKeyParams("private-gpg-key", "public-gpg-key")
err := distManager.SetSigningKey(params)
params := services.NewCreateReleaseBundleParams("bundle-name", "1")
params.Description = "Description"
params.ReleaseNotes = "Release notes"
params.ReleaseNotesSyntax = "plain_text"
targetProps := utils.NewProperties()
targetProps.AddProperty("key1", "val1")
params.SpecFiles = []*utils.CommonParams{{Pattern: "repo/*/*.zip", TargetProps: targetProps}}
// Be default, artifacts that are distributed as part of a release bundle v1, have the same path in their destination server
// (the edge node) as the path they had on the distributing Artifactory server.
// You have however the option for modifying the target path on edge node. You do this by defining the Target property as shown below.
// The Pattern property is a wildcard based pattern. Any wildcards enclosed in parentheses in the pattern (source)
// path can be matched with a corresponding placeholder in the target path, to determine the path and name
// of the artifact, once distributed to the edge node.
// In the following example, the path in the edge node is similar to the path in the source Artifactory server, except for the additional "dir" level at the root of the repository.
// Pattern: my-repo/(*)/a.zip
// Target: my-repo/dir/{1}/a.zip
pathMappingSpec := &utils.CommonParams{Pattern: "source-repo/(a)/(*.zip)", Target: "target-repo/{1}-{2}"}
params.SpecFiles = append(params.SpecFiles, pathMappingSpec)
// In case: params.SignImmediately == true, the summary contain the release bundle v1 details. Otherwise, summary is nil.
summary, err := distManager.CreateReleaseBundle(params)
params := services.NewUpdateReleaseBundleParams("bundle-name", "1")
params.Description = "New Description"
params.ReleaseNotes = "New Release notes"
params.ReleaseNotesSyntax = "plain_text"
targetProps := utils.NewProperties()
targetProps.AddProperty("key1", "val1")
params.SpecFiles = []*utils.CommonParams{{Pattern: "repo/*/*.zip", TargetProps: targetProps}}
// The Target property defines the target path in the edge node, and can include replaceable in the form of {1}, {2}, ...
// Read more about it in the above "Creating a Release Bundle v1" section.
pathMappingSpec := &utils.CommonParams{Pattern: "source-repo/(a)/(*.zip)", Target: "target-repo/{1}-{2}"}
params.SpecFiles = append(params.SpecFiles, pathMappingSpec)
// In case: params.SignImmediately == true, the summary contain the release bundle v1 details. Otherwise, summary is nil.
summary, err := distManager.UpdateReleaseBundle(params)
params := services.NewSignBundleParams("bundle-name", "1")
params.GpgPassphrase = "123456"
summary, err := distManager.SignReleaseBundle(params)
params := distribution.NewDistributeReleaseBundleParams("bundle-name", "1")
distributionRules := distribution.DistributionCommonParams{SiteName: "Swamp-1", "CityName": "Tel-Aviv", "CountryCodes": []string{"123"}}}
params.DistributionRules = []*distribution.DistributionCommonParams{distributionRules}
// Auto-creating repository if it does not exist
autoCreateRepo := true
err := distManager.DistributeReleaseBundle(params, autoCreateRepo)
params := distribution.NewDistributeReleaseBundleParams("bundle-name", "1")
distributionRules := distribution.DistributionCommonParams{SiteName: "Swamp-1", "CityName": "Tel-Aviv", "CountryCodes": []string{"123"}}}
params.DistributionRules = []*distribution.DistributionCommonParams{distributionRules}
// Auto-creating repository if it does not exist
autoCreateRepo := true
// Wait up to 120 minutes for the release bundle v1 distribution
err := distManager.DistributeReleaseBundleSync(params, 120, autoCreateRepo)
params := services.NewDistributionStatusParams()
// Optional parameters:
// If missing, get status for all distributions
params.Name = "bundle-name"
// If missing, get status for all versions of "bundle-name"
params.Version = "1"
// If missing, get status for all "bundle-name" with version "1"
params.TrackerId = "123456789"
status, err := distributeBundleService.GetStatus(params)
params := services.NewDeleteReleaseBundleParams("bundle-name", "1")
params.DeleteFromDistribution = true
distributionRules := distribution.DistributionCommonParams{SiteName: "Swamp-1", "CityName": "Tel-Aviv", "CountryCodes": []string{"123"}}}
params.DistributionRules = []*distribution.DistributionCommonParams{distributionRules}
// Set to true to enable sync deletion (the command execution will end when the deletion process ends).
param.Sync = true
// Max minutes to wait for sync deletion.
param.MaxWaitMinutes = 10
err := distManager.DeleteReleaseBundle(params)
params := services.NewDeleteReleaseBundleParams("bundle-name", "1")
err := distManager.DeleteLocalReleaseBundle(params)
Some APIs return a content.ContentReader
struct, which allows reading the API's output. content.ContentReader
provides access to large amounts of data safely, without loading all of it into the memory.
Here's an example for how content.ContentReader
should be used:
reader, err := servicesManager.SearchFiles(searchParams)
if err != nil {
return err
}
// Remove the data file used by the reader.
defer func() {
if reader != nil {
err = reader.Close()
}
}()
// Iterate over the results.
for currentResult := new(utils.ResultItem); reader.NextRecord(currentResult) == nil; currentResult = new(utils.ResultItem) {
fmt.Printf("Found artifact: %s of type: %s\n", currentResult.Name, currentResult.Type)
}
if err := resultReader.GetError(); err != nil {
return err
}
// Resets the reader pointer back to the beginning of the output. Make sure not to call this method after the reader had been closed using ```reader.Close()```
reader.Reset()
-
reader.NextRecord(currentResult)
reads the next record from the reader intocurrentResult
of typeutils.ResultItem
. -
reader.Close()
removes the file used by the reader after it is used (preferably usingdefer
). -
reader.GetError()
returns any error that might have occurred duringNextRecord()
. -
reader.Reset()
resets the reader back to the beginning of the output.
xrayDetails := auth.NewXrayDetails()
xrayDetails.SetUrl("http://localhost:8081/xray")
xrayDetails.SetSshKeyPath("path/to/.ssh/")
xrayDetails.SetApiKey("apikey")
xrayDetails.SetUser("user")
xrayDetails.SetPassword("password")
xrayDetails.SetAccessToken("accesstoken")
// if client certificates are required
xrayDetails.SetClientCertPath("path/to/.cer")
xrayDetails.SetClientCertKeyPath("path/to/.key")
serviceConfig, err := config.NewConfigBuilder().
SetServiceDetails(xrayDetails).
SetCertificatesPath(certPath).
// Optionally overwrite the default HTTP retries, which is set to 3.
SetHttpRetries(8).
Build()
xrayManager, err := xray.New(serviceConfig)
version, err := xrayManager.GetVersion()
This uses API version 2.
You are able to configure repositories and builds on a watch. However, bundles are not supported.
params := utils.NewWatchParams()
params.Name = "example-watch-all"
params.Description = "All Repos"
params.Active = true
params.Repositories.Type = utils.WatchRepositoriesAll
params.Repositories.All.Filters.PackageTypes = []string{"Npm", "maven"}
params.Repositories.ExcludePatterns = []string{"excludePath1", "excludePath2"}
params.Repositories.IncludePatterns = []string{"includePath1", "includePath2"}
params.Builds.Type = utils.WatchBuildAll
params.Builds.All.Bin_Mgr_ID = "default"
params.Policies = []utils.AssignedPolicy{
{
Name: policy1Name,
Type: "security",
},
{
Name: policy2Name,
Type: "security",
},
}
err := xrayManager.CreateWatch(*params)
watch, err := xrayManager.GetWatch("example-watch-all")
watch, err := xrayManager.GetWatch("example-watch-all")
watch.Description = "Updated description"
err := xrayManager.UpdateWatch(*watch)
err := xrayManager.DeleteWatch("example-watch-all")
params := utils.NewPolicyParams()
params.Name = "example-security-policy"
params.Type = utils.Security
params.Description = "Security policy with 2 rules"
params.Rules = []utils.PolicyRule{
params.Rules = []utils.PolicyRule{
{
Name: "min-severity-rule",
Criteria: *utils.CreateSeverityPolicyCriteria(utils.Low),
Priority: 1,
},
{
Name: "cvss-range-rule",
Criteria: *utils.CreateCvssRangePolicyCriteria(5.7, 8.9),
Priority: 2,
Actions: &utils.PolicyAction{
Webhooks: []string{"sec_webhook"},
BlockDownload: utils.PolicyBlockDownload{
Active: &trueValue,
Unscanned: &falseValue,
},
BlockReleaseBundleDistribution: &falseValue,
FailBuild: &trueValue,
NotifyDeployer: &falseValue,
NotifyWatchRecipients: &trueValue,
CustomSeverity: utils.Medium,
},
},
}
err := xrayManager.CreatePolicy(params)
params := utils.NewPolicyParams()
params.Name = "example-licence-policy"
params.Type = utils.License
params.Description = "License policy with 2 rules"
params.Rules = []utils.PolicyRule{
{
Name: "allowed-licenses",
Criteria: *utils.CreateLicensePolicyCriteria(true, true, false, "MIT", "Apache-2.0"),
Priority: 1,
},
{
Name: "baned-licenses",
Criteria: *utils.CreateLicensePolicyCriteria(false, true, false, "GPL"),
Priority: 2,
},
}
err := xrayManager.CreatePolicy(params)
policy, err := xrayManager.GetPolicy("example-policy")
policy, err := xrayManager.GetPolicy("example-policy")
policy.Description = "Updated description"
err := xrayManager.UpdatePolicy(*policy)
err := xrayManager.DeletePolicy("example-policy")
params := utils.NewIgnoreRuleParams()
params.Notes := "random-notes-for-ignore-rules"
params.ExpiredAt := time.Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location)
params.IgnoreFilters := IgnoreFilters{
Vulnerabilities: []string{"XRAY-12345", "XRAY-67891"},
Licenses: []string{"MIT", "BSD"},
CVEs: []string{"CVE-2021-1234", "CVE-2022-5678"},
Policies: []string{"policy-name-1", "policy-name-2"},
Watches: []string{"watch-name-1", "watch-name-2"},
DockerLayers: []string{"0503825856099e6adb39c8297af09547f69684b7016b7f3680ed801aa310baaa"},
OperationalRisks: []string{"any"},
Exposures: []ExposuresFilterName{
{
FilePath: []string{"/path/to/file1", "/path/to/file2"},
Scanners: []string{"EXP-12345"},
Catagories: []ExposuresCatagories{
{
Secrets: true,
Services: true,
Applications: true,
Iac: true,
},
},
},
},
ReleaseBundles: []IgnoreFilterNameVersion{
{
Name: "RB-name",
Version: "0.0.0",
},
{
Name: "RB-name-2",
Version: "1.2.3",
},
},
Builds: []IgnoreFilterNameVersion{
{
Name: "build-name",
Version: "0.0.0",
},
{
Name: "build-name-2",
Version: "1.2.3",
},
},
Components: []IgnoreFilterNameVersion{
{
Name: "component-name",
Version: "0.0.0",
},
{
Name: "component-name-2",
Version: "1.2.3",
},
},
Arti: []IgnoreFilterNameVersion{
{
Name: "artifact-name",
Version: "0.0.0",
},
{
Name: "artifact-name-2",
Version: "1.2.3",
},
},
}
ignoreRuleIgnoreId, err := xrayManager.CreateIgnoreRule(params)
ignoreRule, err := xrayManager.GetIgnoreRule("ignore-rule-id")
err := xrayManager.DeleteIgnoreRule("ignore-rule-id")
buildsToIndex := []string{"buildName1", "buildName2"}
err := xrayManager.AddBuildsToIndexing(buildsToIndex)
graphScanParams := &XrayGraphScanParams{}
// Dependency tree. Each node must have a component identifier, see https://www.jfrog.com/confluence/display/JFROG/Xray+REST+API#XrayRESTAPI-ComponentIdentifiers.
graphScanParams.Graph = &GraphNode{
Id: "gav://org.jfrog.buildinfo:build-info-extractor-gradle:4.24.5",
Nodes: []*GraphNode{{Id: "gav://junit:junit:4.13.2"}, {Id: "gav://commons-lang:commons-lang:2.6"}}}
scanId, err := xrayManager.ScanGraph(graphScanParams)
// scanId should be received from xrayManager.ScanGraph(graphScanParams) request.
scanResults, err := xrayManager.GetScanGraphResults(scanId)
graphImportParams := &XrayGraphImportParams{}
// Dependency tree. Each node must have a component identifier, see https://www.jfrog.com/confluence/display/JFROG/Xray+REST+API#XrayRESTAPI-ComponentIdentifiers.
graphScanParams.SBOMInput = "{
"bomFormat": "CycloneDX",
"specVersion": "1.4",
"serialNumber": "urn:uuid:3c94db59-0dbf-41cd-49e8-c4518ac2ef3c",
"version": 1,
"metadata": {
"timestamp": "2024-05-22T14:52:40Z",
"tools": [
{
"vendor": "JFrog Inc.",
"name": "Xray",
"version": "3.95.7"
}
],
"component": {
"type": "container",
"name": "jfrog/artifactory-pro:sha256",
"version": "2e774ffb112bcaef62804d97e6db3dc67b9169b440838b12ba12584cba2c5251"
}
},
"components": [
{
"bom-ref": "pkg:Oci/jfrog%2Fartifactory-pro:sha256@2e774ffb112bcaef62804d97e6db3dc67b9169b440838b12ba12584cba2c5251",
"type": "application",
"name": "jfrog/artifactory-pro:sha256",
"version": "2e774ffb112bcaef62804d97e6db3dc67b9169b440838b12ba12584cba2c5251",
"hashes": [
{
"alg": "SHA-256",
"content": "2e774ffb112bcaef62804d97e6db3dc67b9169b440838b12ba12584cba2c5251"
}
],
"licenses": [],
"purl": "pkg:Oci/jfrog%2Fartifactory-pro:sha256@2e774ffb112bcaef62804d97e6db3dc67b9169b440838b12ba12584cba2c5251"
}
],
"dependencies": []
}
"
scanId, err := xrayManager.ImportGraph(graphImportParams)
// scanId should be received from xrayManager.ImportGraph(graphImportParams) request.
enrichResults, err := xrayManager.GetImportGraphResults(scanId)
isEnabled, err := xrayManager.IsTokenValidationEnabled()
vulnerabilitiesReportRequest := services.VulnerabilitiesReportRequestParams{
Name: "example-report",
Filters: services.VulnerabilitiesFilter{
VulnerableComponent: "*vulnerable:component*",
ImpactedArtifact: "some://impacted*artifact",
HasRemediation: &falseValue,
Cve: "CVE-1234-1234",
IssueId: "XRAY-1234",
Severity: []string{
"High",
"Medium"
},
CvssScore: services.CvssScore {
MinScore: float64(6.3),
MaxScore: float64(9)
},
Published: services.DateTimeRange {
Start: "2020-06-29T12:22:16Z",
End: "2020-06-29T12:22:16Z"
},
ScanDate: services.DateTimeRange {
Start: "2020-06-29T12:22:16Z",
End: "2020-06-29T12:22:16Z"
}
},
Resources: services.Resource{
IncludePathPatterns: []string{ "/example-sub-dir/**" },
Repositories: []services.Repository{
{
Name: "example-repository",
},
},
},
}
// The reportRequestResponse will contain the report ID to use in subsequent requests
reportRequestResponse, err := xrayManager.GenerateVulnerabilitiesReport(vulnerabilitiesReportRequest)
// The reportId argument value is returned as part of the xrayManager.GenerateVulnerabilitiesReport API response.
reportDetails, err := xrayManager.ReportDetails(reportId)
// The ReportId value is returned as part of the xrayManager.GenerateVulnerabilitiesReport API response.
reportContentRequest := services.ReportContentRequestParams{
ReportId: "example-report-id",
Direction: "asc",
PageNum: 0,
NumRows: 0,
OrderBy: "severity",
}
reportContent, err := xrayManager.ReportContent(reportContentRequest)
// The reportId argument value is returned as part of the xrayManager.GenerateVulnerabilitiesReport API response.
err := xrayManager.DeleteReport(reportId)
licensesReportRequest := services.LicensesReportRequestParams{
Name: "example-report",
Filters: services.LicensesFilter{
Component: "*gav:component*",
Artifact: "some://impacted*artifact",
Unknown: &falseValue,
Unrecognized: &trueValue,
LicenseNames: []string{
"Apache",
"MIT",
"AFL"
},
LicensePatterns: []string{
"*Apache*",
"The Apache*",
"AFL*"
},
ScanDate: services.DateTimeRange {
Start: "2020-06-29T12:22:16Z",
End: "2020-06-29T12:22:16Z"
}
},
Resources: services.Resource{
IncludePathPatterns: []string{ "/example-sub-dir/**" },
Repositories: []services.Repository{
{
Name: "example-repository",
},
},
},
}
// The reportRequestResponse will contain the report ID to use in subsequent requests
reportRequestResponse, err := xrayManager.GenerateLicencesReport(licensesReportRequest)
// The reportId argument value is returned as part of the xrayManager.GenerateLicencesReport API response.
reportDetails, err := xrayManager.ReportDetails(reportId)
// The ReportId value is returned as part of the xrayManager.GenerateLicencesReport API response.
reportContentRequest := services.ReportContentRequestParams{
ReportId: "example-report-id",
Direction: "asc",
PageNum: 0,
NumRows: 0,
OrderBy: "severity",
}
reportContent, err := xrayManager.ReportContent(reportContentRequest)
// The reportId argument value is returned as part of the xrayManager.GenerateLicencesReport API response.
err := xrayManager.DeleteReport(reportId)
violationsReportRequest := services.ViolationsReportRequestParams{
Name: "example-report",
Filters: Type: "security|license|operational_risk",
WatchNames: []string{
"NameOfWatch1",
"NameOfWatch2"
},
WatchPatterns: []string{
"WildcardWatch*"
},
Component: "*vulnerable:component*",
Artifact: "some://impacted*artifact",
PolicyNames: []string{
"NameOfPolicy"
},
Severities: []string{
"High",
"Medium"
},
Updated: services.DateTimeRange {
Start: "2020-01-02T15:00:00Z",
End: "2020-12-15T00:00:00Z"
},
SecurityFilters: services.VulnerabilitiesFilter{
Cve: "CVE-2020-10693",
IssueId: "XRAY-87343",
Severity: []string{
"High",
"Medium"
},
CvssScore: services.CvssScore {
MinScore: float64(6.3),
MaxScore: float64(9)
},
Published: services.DateTimeRange {
Start: "2020-06-29T12:22:16Z",
End: "2020-06-29T12:22:16Z"
},
ScanDate: services.DateTimeRange {
Start: "2020-06-29T12:22:16Z",
End: "2020-06-29T12:22:16Z"
},
SummaryContains: "kernel",
HasRemediation: &falseValue,
},
LicenseFilters: services.LicensesFilter {
Unknown: &falseValue,
Unrecognized: &trueValue,
LicenseNames: []string{
"Apache",
"MIT",
"AFL"
},
LicensePatterns: []string{
"*Apache*",
"AFL*"
},
}
Resources: services.Resource{
IncludePathPatterns: []string{ "/example-sub-dir/**" },
Repositories: []services.Repository{
{
Name: "example-repository",
},
},
},
}
// The reportRequestResponse will contain the report ID to use in subsequent requests
reportRequestResponse, err := xrayManager.GenerateViolationsReport(violationsReportRequest)
// The reportId argument value is returned as part of the xrayManager.GenerateViolationsReport API response.
reportDetails, err := xrayManager.ReportDetails(reportId)
// The ReportId value is returned as part of the xrayManager.GenerateViolationsReport API response.
reportContentRequest := services.ReportContentRequestParams{
ReportId: "example-report-id",
Direction: "asc",
PageNum: 0,
NumRows: 0,
OrderBy: "severity",
}
reportContent, err := xrayManager.ReportContent(reportContentRequest)
// The reportId argument value is returned as part of the xrayManager.GenerateViolationsReport API response.
err := xrayManager.DeleteReport(reportId)
artifactSummaryRequest := services.ArtifactSummaryParams{
Checksums: []string{"a96370b18b3d7e70b7b34d49dcb621a805c15cf71217ee8c77be5a98cc793fd3"},
Paths: []string{"default/example-repository/example-folder/example-artifact"},
}
artifactSummary, err := xrayManager.ArtifactSummary(artifactSummaryRequest)
// The featureId is the requested feature ID to check, for instance: "contextual_analysis"
isEntitled, err := xrayManager.IsEntitled(featureId)
xscDetails := auth.NewXscDetails()
xscDetails.SetUrl("http://localhost:8081/xsc")
xscDetails.SetSshKeyPath("path/to/.ssh/")
xscDetails.SetApiKey("apikey")
xscDetails.SetUser("user")
xscDetails.SetPassword("password")
xscDetails.SetAccessToken("accesstoken")
// if client certificates are required
xscDetails.SetClientCertPath("path/to/.cer")
xscDetails.SetClientCertKeyPath("path/to/.key")
serviceConfig, err := config.NewConfigBuilder().
SetServiceDetails(xscDetails).
SetCertificatesPath(certPath).
// Optionally overwrite the default HTTP retries, which is set to 3.
SetHttpRetries(8).
Build()
xscManager, err := xsc.New(serviceConfig)
version, err := xscManager.GetVersion()
Sent XSC a new event which contains analytics data, and get multi-scan id back from XSC.
event := services.XscAnalyticsGeneralEvent{
XscAnalyticsBasicGeneralEvent: services.XscAnalyticsBasicGeneralEvent{
EventType: services.CliEventType,
Product: services.CliProduct,
ProductVersion: "2.53.1",
IsDefaultConfig: false,
JfrogUser: "gail",
OsPlatform: "mac",
OsArchitecture: "arm64",
AnalyzerManagerVersion: "1.1.1",
EventStatus: services.Started,
}}
msi, err := xscManager.AddAnalyticsGeneralEvent(event)
Sent XSC a finalized analytics metrics event with information matching an existing event's msi.
finalizeEvent := services.XscAnalyticsGeneralEventFinalize{
MultiScanId: msi,
XscAnalyticsBasicGeneralEvent: services.XscAnalyticsBasicGeneralEvent{
EventStatus: services.Completed,
TotalFindings: 10,
TotalIgnoredFindings: 5,
TotalScanDuration: "15s",
},
}
err := xscManager.UpdateAnalyticsGeneralEvent(finalizeEvent)
Get a general event from XSC matching the provided msi.
event, err := xscManager.GetAnalyticsGeneralEvent(msi)
pipelinesDetails := auth.NewPipelinesDetails()
pipelinesDetails.SetUrl("http://localhost:8081/pipelines")
pipelinesDetails.SetAccessToken("accesstoken")
// if client certificates are required
pipelinesDetails.SetClientCertPath("path/to/.cer")
pipelinesDetails.SetClientCertKeyPath("path/to/.key")
serviceConfig, err := config.NewConfigBuilder().
SetServiceDetails(pipelinesDetails).
SetCertificatesPath(pipelinesDetails.GetClientCertPath()).
// Optionally overwrite the default HTTP retries, which is set to 3.
SetHttpRetries(8).
Build()
pipelinesManager, err := pipelines.New(serviceConfig)
systemInfo, err := pipelinesManager.GetSystemInfo()
id, err := pipelinesManager.CreateGithubIntegration("integrationName", "token")
id, err := pipelinesManager.CreateGithubEnterpriseIntegration("integrationName", "url", "token")
id, err := pipelinesManager.CreateBitbucketIntegration("integrationName", "username", "token")
id, err := pipelinesManager.CreateBitbucketServerIntegration("integrationName", "url", "username", "passwordOrToken")
id, err := pipelinesManager.CreateGitlabIntegration("integrationName", "url", "token")
id, err := pipelinesManager.CreateArtifactoryIntegration("integrationName", "url", "username", "apikey")
integrationId := 1234
integration, err := pipelinesManager.GetIntegrationById(integrationId)
integration, err := pipelinesManager.GetIntegrationByName("integrationName")
integrations, err := pipelinesManager.GetAllIntegrations()
integrations, err := pipelinesManager.GetAllRawIntegrations()
integrationId := 1234
err := pipelinesManager.DeleteIntegration(integrationId)
projectIntegrationId := 1234
err := pipelinesManager.AddSource(projectIntegrationId, "domain/repo", "master", "pipelines.yml", "pipelineSourceName")
branch := "master"
pipeline := "pipeline_name"
response, err := pipelinesManager.GetPipelineRunStatusByBranch(branch, pipeline)
branch := "master"
pipeline := "pipeline_name"
status, err := pipelinesManager.TriggerPipelineRun(branch, pipeline)
branch := "master"
repoName := "jfrog/pipelines" // repository full path
err := pipelinesManager.SyncPipelineResource(branch, repoFullName)
branch := "master"
repoName := "jfrog/pipelines" // repository full path
err := pipelinesManager.GetSyncStatusForPipelineResource(branch, repoFullName)
runID := 234 // run id of pipeline
err := pipelinesManager.CancelRun(runID)
lcDetails := auth.NewLifecycleDetails()
lcDetails.SetUrl("http://localhost:8081/lifecycle")
lcDetails.SetAccessToken("access-token")
// if client certificates are required
lcDetails.SetClientCertPath("path/to/.cer")
lcDetails.SetClientCertKeyPath("path/to/.key")
serviceConfig, err := config.NewConfigBuilder().
SetServiceDetails(lcDetails).
SetCertificatesPath(lcDetails.GetClientCertPath()).
// Optionally overwrite the default HTTP retries, which is set to 3.
SetHttpRetries(8).
Build()
lifecycleManager, err := lifecycle.New(serviceConfig)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
queryParams := CommonOptionalQueryParams{}
queryParams.ProjectKey = "project"
queryParams.Async = true
// The GPG/RSA key-pair name given in Artifactory.
signingKeyName = "key-pair"
aqlQuery := `items.find({"repo": "my-repo","path": ".","name": "a2.in"})`
serviceManager.CreateReleaseBundleFromAql(rbDetails, queryParams, signingKeyName, aqlQuery)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
queryParams := CommonOptionalQueryParams{}
queryParams.ProjectKey = "project"
queryParams.Async = true
// The GPG/RSA key-pair name given in Artifactory.
signingKeyName = "key-pair"
artifacts := CreateFromArtifacts{Artifacts: []ArtifactSource{
{
Path: "repo/path/file",
Sha256: "3e3deb6628658a48cf0d280a2210211f9d977ec2e10a4619b95d5fb85cb10450",
},
}}
serviceManager.CreateReleaseBundleFromArtifacts(rbDetails, queryParams, signingKeyName, artifacts)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
queryParams := CommonOptionalQueryParams{}
queryParams.ProjectKey = "project"
queryParams.Async = true
// The GPG/RSA key-pair name given in Artifactory.
signingKeyName = "key-pair"
source := CreateFromBuildsSource{Builds: []BuildSource{
{
BuildName: "name",
BuildNumber: "number",
// Optional:
BuildRepository: "artifactory-build-info",
},
}}
serviceManager.CreateReleaseBundleFromBuilds(rbDetails, queryParams, signingKeyName, source)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
queryParams := CommonOptionalQueryParams{}
queryParams.ProjectKey = "project"
queryParams.Async = true
// The GPG/RSA key-pair name given in Artifactory.
signingKeyName = "key-pair"
source := CreateFromReleaseBundlesSource{ReleaseBundles: []ReleaseBundleSource{
{
ReleaseBundleName: "name",
ReleaseBundleVersion: "version",
ProjectKey: "default",
},
}}
serviceManager.CreateReleaseBundleFromBundles(rbDetails, params, signingKeyName, source)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
queryParams := CommonOptionalQueryParams{}
queryParams.ProjectKey = "project"
queryParams.Async = true
// The GPG/RSA key-pair name given in Artifactory.
signingKeyName = "key-pair"
promotionParams := RbPromotionParams{}
promotionParams.Environment := "target-env"
promotionParams.IncludedRepositoryKeys := []string{"generic-local"}
resp, err := serviceManager.PromoteReleaseBundle(rbDetails, queryParams, signingKeyName, promotionParams)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
sync := true
// Optional:
projectKey := "default"
resp, err := serviceManager.GetReleaseBundleCreationStatus(rbDetails, projectKey, sync)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
createdMillis := "1668073165322"
sync := true
// Optional:
projectKey := "default"
resp, err := serviceManager.GetReleaseBundlePromotionStatus(rbDetails, projectKey, createdMillis, sync)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
optionalQueryParams := lifecycle.GetPromotionsOptionalQueryParams{
Include: "MSG",
Offset: 1,
Limit: 10,
FilterBy: "DEV",
OrderBy: "created",
OrderAsc: true,
ProjectKey: "default",
}
resp, err := serviceManager.GetReleaseBundleVersionPromotions(rbDetails, optionalQueryParams)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
resp, err := serviceManager.GetReleaseBundleSpecification(rbDetails)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
pathMappings := []services.PathMapping{
{
Pattern: "(*)/(*)",
Target: "{1}/target/{2}",
},
}
rules := &distribution.DistributionCommonParams{
SiteName: "*",
CityName: "*",
CountryCodes: []string{"*"},
}
dsParams := DistributeReleaseBundleParams{
Sync: true,
AutoCreateRepo: true,
MaxWaitMinutes: 60,
PathMappings: pathMappings,
DistributionRules: []*dmUtils.DistributionCommonParams{
rules,
},
}
resp, err := serviceManager.DistributeReleaseBundle(rbDetails, dsParams)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
queryParams := CommonOptionalQueryParams{}
queryParams.ProjectKey = "project"
// Specifies the path mapping for the artifacts
// in the form of input and output regular expressions.
// These expressions define where the artifacts are located
// and where they should be exported.
modifictions:= []utils.PathMapping{{
Input: "(.*)/(.*)",
Output: "$1/mapping/$2",
}}
// Export & Download
res,err:= serviceManager.ExportReleaseBundle(rbDetails, modifications, queryParams)
// Imports an exported release bundle archive
res,err:= serviceManager.releaseService.ImportReleaseBundle(filePath)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
queryParams := CommonOptionalQueryParams{}
queryParams.ProjectKey = "project"
queryParams.Async = true
resp, err := serviceManager.DeleteReleaseBundleVersion(rbDetails, queryParams)
rbDetails := ReleaseBundleDetails{"rbName", "rbVersion"}
queryParams := CommonOptionalQueryParams{}
queryParams.ProjectKey = "project"
queryParams.Async = true
created := "1708612052952"
resp, err := serviceManager.DeleteReleaseBundleVersionPromotion(rbDetails, queryParams, created)
rules := &distribution.DistributionCommonParams{
SiteName: "*",
CityName: "*",
CountryCodes: []string{"*"},
}
params := distribution.NewDistributeReleaseBundleParams("rbName", "rbVersion")
params.DistributionRules = append(params.DistributionRules, rules)
dryRun := true
resp, err := serviceManager.RemoteDeleteReleaseBundle(params, dryRun)
evdDetails := auth.NewEvidenceDetails()
evdDetails.SetUrl("http://localhost:8081/evidence")
evdDetails.SetAccessToken("access-token")
// if client certificates are required
evdDetails.SetClientCertPath("path/to/.cer")
evdDetails.SetClientCertKeyPath("path/to/.key")
serviceConfig, err := config.NewConfigBuilder().
SetServiceDetails(evdDetails).
SetCertificatesPath(evdDetails.GetClientCertPath()).
// Optionally overwrite the default HTTP retries, which is set to 3.
SetHttpRetries(3).
Build()
evidenceManager, err := evidence.New(serviceConfig)
envelopeBytes := []byte("envelope")
evidenceDetails := evidenceService.EvidenceDetails{
SubjectUri: "subjectUri",
DSSEFileRaw: &envelopeBytes,
}
body, err = evideceManager.UploadEvidence(evidenceDetails)
mdDetails := auth.NewMetadataDetails()
mdDetails.SetUrl("http://localhost:8081/metadata")
mdDetails.SetAccessToken("access-token")
// if client certificates are required
mdDetails.SetClientCertPath("path/to/.cer")
mdDetails.SetClientCertKeyPath("path/to/.key")
serviceConfig, err := config.NewConfigBuilder().
SetServiceDetails(mdDetails).
SetCertificatesPath(mdDetails.GetClientCertPath()).
// Optionally overwrite the default HTTP retries, which is set to 3.
SetHttpRetries(3).
Build()
metadataManager, err := metadata.NewManager(serviceConfig)
queryBytes := []byte(`{"query":"someGraphqlQuery"}`)
queryDetails := metadataService.QueryDetails{
Body: queryBytes,
}
body, err = metadataManager.GraphqlQuery(queryDetails)