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

Return to the regular view of this page.

API

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 complete API is a combination of OpenAPI-specified REST-like APIs and a reporting-specific GraphQL API.

For a more detailed information regarding access and authentication, see V2 API

Access to the API Specification itself is available in the following ways:

  • Documentation API Browser
  • Enterprise API
    • The API specification is also available directly from your Enterprise deployment:
      curl -X GET -u {username:password} "http://{servername:port}/v2/openapi.json
      
  • Enterprise UI

1 - Anchore V2 API

V2 API 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. The REST API is the primary API for interacting with Anchore and has the most functionality. The GraphQL API is for querying aggregated information within an account and does not provide the same functionality as the REST API.

The API specifications for this release of Anchore Enterprise are available here in the documentation. The specifications are also available directly from your Enterprise deployment at GET /v2/openapi.json

REST API Version 2

The Anchore V2 API is now available with the Enterprise v4.9.0 release. V2 will be the only supported API beginning in the future Enterprise v5.0.0 release.

GraphQL API

The GraphQL API is intended for reporting functions and aggregating data from all resources in an Anchore account. 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

Any API exposed on a network should be protected at the channels level using TLS. Regardless of the authentication scheme, transport security ensure 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 service 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.

The API supports two authentication methods:

  1. HTTP Basic
    1. Use HTTP ‘Authorization’ header: Authorization: Basic <base64_encode(<username> + ':' + <password>)>
      1. curl example: curl -u <username>:<password> http://localhost:8228/v2/images
  2. OAuth2 Bearer Tokens
    1. SAML Bearer Flow
    2. PasswordGrant flow
  3. API Keys
    1. Generate API keys following this guide
    2. Use HTTP Basic Authorization with a special username _api_key and use the API key value generated as the password
      1. curl example: curl -u "_api_key:<api_key_value>" http://localhost:8228/v2/images

Authorization

Anchore implements authorization with Role-Based Access Control (RBAC)

Enterprise Service V2 API Specifications

Browse Online

The V2 API is available to browse hosted in this site: V2 API browser

Downloadable YAML Documents

Anchore API Swagger Specification YAML

Feed Service API Swagger Specfication YAML

Retrieving the Swagger JSON from your Anchore Deployment Directly

The APIs provide their own specifications available from the deployment itself using: GET /v2/openapi.json.

This provides a useful mechanism for integrations and other automation tasks to retrieve the specification for the correct Anchore version since it is provided by the deployment itself.

1.1 - Anchore API V2 Reference

Reference for the Anchore API V2

1.2 - Anchore Enterprise 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
        }
      }
    }
    

1.3 - Migrating from API V1 to V2

Overview

The changes from V1 to V2, while breaking, primarily resolve inconsistencies and confusion in the V1 API rather than establishing any new API patterns or interaction styles. Clients using the V1 API should be able to migrate to V2 without changing their workflows at all.

API Consolidation

Endpoint Consolidation

In the V2 API, all REST-like APIs are available from the main API service in the deployment. This means simpler integrations, ingress setups, and client configurations. Specifically, the RBAC Manager API, Notifications API, and Reports API are now served through the same endpoint. Those services will become internal-only services for processing requests in the 5.0 release.

A single swagger/openapi specification now covers all Anchore APIs except the GraphQL API.

Enterprise & Non-Enterprise Route Consolidation

There are no longer any enterprise prefixed routes, and all routes that had a version with and without the enterprise prefix are now consolidated with no prefix but implement the full enterprise functionality.

Authentication

There are no changes to authentication mechanisms.

HTTP Basic and Oauth2 Tokens using JWT continue to be the authentication mechanisms for using the API. See Authentication

Authorization

There are no changes to the RBAC authorization scheme, actions, and management workflows.

All roles, accounts, and role memberships directly transfer to V2, subject to some field and URL path element renaming for consistency as indicated in the table below.

All the RBAC-related APIs are now served from the main API endpoint per the consolidation section above. There is no longer a need to expose a public port from the RBAC Manager Service (NOTE: The RBAC Manger Service has been removed altogether in the v5.4.0 release).

Specification

The V2 API is specified using OpenAPI v2/Swagger v2. We anticipate a future migration to specifying the API using OpenAPI v3 to support more modern client generation tooling. However, in the 4.9 release of the V2 API the specification continues to be in Swagger V2.

Required Version in Path

In the V1 API, Anchore services would automatically re-write a version-less request path to use a “v1” prefix. This behavior will no longer be present in the V2 API and in the 5.0 release all clients must specify the requested API version in the path explicitly.

For example, in V1: GET /images –> routed internally to –> GET /v1/images

In V2: GET /images –> HTTP 404. Must use GET /v2/images explicitly.

This is being strictly enforced to allow better future migration between APIs and consistent request handling for clients as the APIs evolve.

Field Renames and Consolidations Overview

This covers the most impactful and significant updates, but is not exhaustive.

Account Name

The “userId” field was a legacy element of a very old version of Anchore. It is now removed and replaced with account_name in the operations where the return is in fact the account name rather than the ID of the specific user. Since resources in Anchore are owned by accounts, which may contain multiple users, this is the correct and clear field.

Example: userId ==> account_name

Snake Casing

There is no longer a mix between Camel Casing and Snake Casing for fields in the API. All fields are snake-case for consistency.

Example: imageDigest is now image_digest

Arrays Removed Where Not Appropriate

All APIs that returned an array where the actual response was always a single element have been re-typed to return objects.

Example: POST /v2/images, returns a single object instead of an array.

APIs that may return large arrays have been wrapped in an object and the array set to the “items” property of the object. This change will allow better non-breaking evolution of the API in the future.

Detailed Changes from V1 to V2

API Comparison