This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

API

APIs Overview

Anchore Enterprise is an API-first system. All functions available in the UI and AnchoreCTL are constructed from the same APIs directly available to users. The APIs are a combination of a OpenAPI-specified REST-like API and a reporting-specific GraphQL API.

REST API

The REST API is the primary API for interacting with Anchore and has the most functionality. The Anchore V2 API is viewable in the following ways:

API Browser

API Specification

GraphQL API

The GraphQL API is intended for reporting functions and aggregating data from all resources in an Anchore account and does not provide the same functionality as the REST API. The data that the GraphQL API operates on is updated differently than the data in the REST API and thus may have an update lag between when changes are visible via the REST API and when that data flows into functionality covered by the GraphQL API.

Authentication & Authorization

Authentication

Both the REST and GraphQL APIs are exposed on a network and should be protected at the channel level using TLS. Regardless of the authentication scheme, transport security ensures resistance to replay attacks and other forms of request and credential abuse and should always be used.

See Configuring TLS for setting up TLS in Anchore services directly, or use TLS termination via load balancers or service meshes such as Istio and LinkerD. The right choice for your deployment will depend on your specific environment and requirements.

Anchore APIs support three authentication methods:

  1. HTTP Basic
    • Use HTTP ‘Authorization’ header: Authorization: Basic <base64_encode(<username> + ':' + <password>)> along with your native account credentials
      • curl example: curl -u <username>:<password> http://localhost:8228/v2/images
  2. OAuth2 Bearer Tokens
  3. API Keys
    • Generate API keys following this guide
    • Use HTTP Basic Authorization with a special username _api_key and use the API key value generated as the password
      • curl example: curl -u "_api_key:<api_key_value>" http://localhost:8228/v2/images
    • If you are using SSO, you will need to allow API keys for SAML users

Authorization

Both the REST and GraphQL APIs implement authorization with Role-Based Access Control (RBAC). The APIs also supports Cross-Account access.

  • In this example, we can query for images in an account named ‘product1’ instead of the account that my user resides in.
    • curl -X GET -u {username:password} -H "x-anchore-account: product1" "http://{servername:port}/v2/images"

1 - REST Anchore API

Reference for the Anchore API V2

2 - GraphQL Reports API Access

Anchore Enterprise Reports provides a GraphQL API for direct interaction with the service. GraphQL is a query language for APIs and a runtime for fulfilling those queries.

The main Anchore REST API includes operations for retrieving scheduled report results as static sets to make retrieval of saved results simpler. It is available in V2 API.

Get started

There are different ways of interacting with the Anchore Enterprise Reports GraphQL API. The following sections highlight two different options for exploring the Anchore Enterprise Reports GraphQL schema with a few examples.

THe endpoint you use for interacting with the GraphQL API is the same host and port as the main V2 API. The path is: /v2/reports/.

Interactive GUI

One of the ways of exploring and testing a GraphQL schema is by using GraphiQL. Anchore Enterprise Reports Service has GraphiQL built-in to the service and enabled by default.

To access it in a running Anchore Enterprise deployment, open one of the following urls in a browser:

  • http://<main_api_servername:port>/v2/reports/graphql
  • http://<main_api_servername:port>/v2/reports/global/graphql (Administrator Access Only)

You will be prompted to enter your Anchore Enterprise credentials. Click the Docs tab to view the self-describing schema

Reports GraphQL Schema

In addition to being able to see the API docs, GraphiQL is handy for exploring and constructing queries supported by the backing API. Here is an example of a query for available metrics in the system. Happy querying!

Reports GraphQL Example

Command line using curl

You can also use curl to send HTTP requests to Anchore Enterprise Reports API. To view the schema

$ curl -u <username:password> -X POST "http://<servername:port>/v2/reports/graphql?query=%7B__schema%7BqueryType%7Bname%20description%20fields%7Bname%20description%20args%7Bname%20description%20type%7Bname%20kind%7D%7D%7D%7D%7D%7D%0A"

Generating an API key

If you are interacting directly with the API, either via a command line tool, third party integration or custom scripts/programs; you can generate API keys to avoid exposing your private credentials. See Generating API keys for details on generating API keys.

Using an API key

You can use API keys in the same way as your regular credentials. The username for API keys is static as _api_key and the password is the value of the key itself.

$ curl -u <_api_key:<generated key value> -XGET "http://<servername:port>/v2/images

Pagination

Depending on the size of data set (i.e. number of tags, images etc in the system) results of a query could be very large. Reports service implements pagination for all queries to better handle the volume of the results and respond to the clients within a reasonable amount of time.

Structure of the query contains a metadata object called pageInfo. It is optional, recommended to add to all queries:

{
  imagesByVulnerability {
    pageInfo {
      nextToken
      count
    }
    results {
      ...
    }
  }
}

The response may return an opaque token or a null value for nextToken:

{
  "data": {
    "imagesByVulnerability": {
      "pageInfo": {
        "nextToken": "Q1ZFLTIwMTYtMTAyNjY=",
        "count": 1000
      },
      "results": [
        ...
      ]
    }
  }
}      

A non-null nextToken indicates that results are paginated. To get the next page of results, fire the same query along with the nextToken from the last response as a query parameter:

{
  imagesByVulnerability(nextToken: "Q1ZFLTIwMTYtMTAyNjY=") {
    pageInfo {
      nextToken
      count
    }
    results {
      ...
    }
  }
}

Some useful queries

Vulnerability centric queries

  • List vulnerabilities of a specific severity. And include all the images, currently or historically mapped to a tag, affected by each vulnerability

    Use the query’s filter argument for specifying the conditionality. Reports service defaults to the “current” image-tag mapping for computing results. To compute results across all image-tag mappings - current and historic,
    set the tag filter’s currentOnly attribute to false. Query for vulnerabilities of Critical severity:
    { imagesByVulnerability(filter: {vulnerability: {severity: Critical}, tag: {currentOnly: false}}) { pageInfo { nextToken } results { vulnerabilityId links imagesCount images { digest } } } } To get more details such as tag mappings for the image, add the relevant attributes from the schema to the body of the query.

  • List vulnerabilities detected in the last x hours. And include all the images, currently or historically mapped to a tag, affected by each vulnerability

    Use vulnerability filter’s after and before attributes for specifying a time window using UTC timestamps. Query for vulnerabilities detected after/since August 1st 2019:

    {
      imagesByVulnerability(filter: {vulnerability: {after: "2019-08-01T00:00:00"}, tag: {currentOnly: false}}) {
        pageInfo {
          nextToken
        }
        results {
          vulnerabilityId
          images {
            digest
          }
        }
      }
    }
    
  • Given a vulnerability ID, list all the artifacts affected by that vulnerability. And include all the images, currently or historically mapped to a tag, containing the said artifact

    Use vulnerability filter’s id attribute for specifying a vulnerability identifier. Query for vulnerability ID CVE-2019-15213:

    {
      artifactsByVulnerability(filter: {vulnerability: {id: "CVE-2019-15213"}, tag: {currentOnly: false}}) {
        pageInfo {
          nextToken
        }
        results {
          vulnerabilityId
          links
          artifactsCount
          artifacts {
            artifactName
            artifactVersion
            artifactType
            severity
            images {
              digest
            }
          }
        }
      }
    }
    

Policy evaluation centric queries

  • Given a repository, get the policy evaluation results for all the tags currently mapped to an image using the active policy

    Use registry and repository filters for narrowing the results down. Query for docker.io registry and library/node repository:

    {
      policyEvaluationsByTag(filter: {registry: {name: "docker.io"}, repository: {name: "library/node"}}) {
        pageInfo {
          nextToken
        }
        results {
          repositories {
            tagsCount
            tags {
              tagName
              imageDigest
              evaluations {
                result
                reason
              }
            }
          }
        }
      }
    }
    
  • Given a tag, get the policy evaluation history. Include policy evaluations encompassing updates to the tag and the active policy

    Reports service defaults to the “current” state for computing results. To compute results across historic state, a few filter knobs have to be turned

    • tag -> currentOnly set to false instructs the service to include all, current and historic, image tag mappings
    • policyEvaluation -> latestOnly set to false instructs the service to include all, current and historic, policy evaluations
    • policyBundle -> active set to false instructs service to include all, current and historic, active policies
    {
      policyEvaluationsByTag(filter: {registry: {name: "docker.io"}, repository: {name: "library/node"}, tag: {name: "latest", currentOnly: false}, policyEvaluation: {latestOnly: false}, policyBundle: {active: false}}) {
        pageInfo {
          nextToken
        }
        results {
          repositories {
            tags {
              imageDigest
              detectedAt
              current
              evaluations {
                result
                reason
                lastEvaluatedAt
                policyBundle {
                  bundleId
                  bundleDigest
                }
                latest
              }
            }
          }
        }
      }
    }
    

Metric centric queries

  • List all the available metrics

    {
      metrics {
        pageInfo {
          nextToken
        }
        results {
          id
          name
          description
          metricType
        }
      }
    }
    
  • Given a metric ID, list values for that metric within a period of time. Useful for plotting changes over a timescale

    Query for vulnerabilities.tags.all.critical metric between 1st August and 1st September 2019:

    {
      metricData(filter: {metricId: "vulnerabilities.tags.all.critical", start: "2019-08-01T00:00:00", end: "2019-09-01T00:00:00"}) {
        pageInfo {
          nextToken
        }
        results {
          collectedAt
          value
        }
      }
    }