Hanzo
PlatformHanzo KMSPlatformIdentities

AWS Auth

Learn how to authenticate with Hanzo KMS for EC2 instances, Lambda functions, and other IAM principals.

AWS Auth is an AWS-native authentication method for IAM principals like EC2 instances or Lambda functions to access Hanzo KMS.

Diagram

The following sequence diagram illustrates the AWS Auth workflow for authenticating AWS IAM principals with Hanzo KMS.

sequenceDiagram
  participant Client as Client
  participant Infis as Hanzo KMS
  participant AWS as AWS STS

  Note over Client,Client: Step 1: Sign GetCallerIdentityQuery

  Note over Client,Infis: Step 2: Login Operation
  Client->>Infis: Send signed query details /api/v1/auth/aws-auth/login

  Note over Infis,AWS: Step 3: Query verification
  Infis->>AWS: Forward signed GetCallerIdentity query
  AWS-->>Infis: Return IAM user/role details

  Note over Infis: Step 4: Identity Property Validation
  Infis->>Client: Return short-lived access token

  Note over Client,Infis: Step 5: Access Hanzo KMS API with Token
  Client->>Infis: Make authenticated requests using the short-lived access token

Concept

At a high-level, Hanzo KMS authenticates an IAM principal by verifying its identity and checking that it meets specific requirements (e.g. it is an allowed IAM principal ARN) at the /api/v1/auth/aws-auth/login endpoint. If successful, then Hanzo KMS returns a short-lived access token that can be used to make authenticated requests to the Hanzo KMS API.

To be more specific:

  1. The client IAM principal signs a GetCallerIdentity query using the AWS Signature v4 algorithm; this is done using the credentials from the AWS environment where the IAM principal is running.
  2. The client sends the signed query data to Hanzo KMS including the request method, request body, and request headers at the /api/v1/auth/aws-auth/login endpoint.
  3. Hanzo KMS reconstructs the query and sends it to AWS STS API via the sts:GetCallerIdentity method for verification and obtains the identity associated with the IAM principal.
  4. Hanzo KMS checks the identity's properties against set criteria such Allowed Principal ARNs.
  5. If all is well, Hanzo KMS returns a short-lived access token that the IAM principal can use to make authenticated requests to the Hanzo KMS API.

We recommend using one of Hanzo KMS's clients like SDKs or the KMS Agent to authenticate with Hanzo KMS using AWS Auth as they handle the authentication process including the signed GetCallerIdentity query construction for you.

Also, note that Hanzo KMS needs network-level access to send requests to the AWS STS API as part of the AWS Auth workflow.

Guide

In the following steps, we explore how to create and use identities for your workloads and applications on AWS to access the Hanzo KMS API using the AWS Auth authentication method.

To create an identity, head to your Organization Settings > Access Control > Identities and press Create identity.

identities organization

When creating an identity, you specify an organization level role for it to assume; you can configure roles in Organization Settings > Access Control > Organization Roles.

identities organization create

Now input a few details for your new identity. Here's some guidance for each field:

  • Name (required): A friendly name for the identity.
  • Role (required): A role from the Organization Roles tab for the identity to assume. The organization role assigned will determine what organization level resources this identity can have access to.

Once you've created an identity, you'll be redirected to a page where you can manage the identity.

identities page

Since the identity has been configured with Universal Auth by default, you should re-configure it to use AWS Auth instead. To do this, press to edit the Authentication section, remove the existing Universal Auth configuration, and add a new AWS Auth configuration onto the identity.

identities page remove default auth

identities create aws auth method

Here's some more guidance on each field:

  • Allowed Principal ARNs: A comma-separated list of trusted IAM principal ARNs that are allowed to authenticate with Hanzo KMS. The values should take one of three forms: arn:aws:iam::123456789012:user/MyUserName, arn:aws:iam::123456789012:role/MyRoleName, or arn:aws:iam::123456789012:*. Using a wildcard in this case allows any IAM principal in the account 123456789012 to authenticate with Hanzo KMS under the identity.
  • Allowed Account IDs: A comma-separated list of trusted AWS account IDs that are allowed to authenticate with Hanzo KMS.
  • STS Endpoint (default is https://sts.amazonaws.com/): The endpoint URL for the AWS STS API. This value should be adjusted based on the AWS region you are operating in (e.g. https://sts.us-east-1.amazonaws.com/); refer to the list of regional STS endpoints here.
  • Access Token TTL (default is 2592000 equivalent to 30 days): The lifetime for an acccess token in seconds. This value will be referenced at renewal time.
  • Access Token Max TTL (default is 2592000 equivalent to 30 days): The maximum lifetime for an acccess token in seconds. This value will be referenced at renewal time.
  • Access Token Max Number of Uses (default is 0): The maximum number of times that an access token can be used; a value of 0 implies infinite number of uses.
  • Access Token Trusted IPs: The IPs or CIDR ranges that access tokens can be used from. By default, each token is given the 0.0.0.0/0, allowing usage from any network address.

To enable the identity to access project-level resources such as secrets within a specific project, you should add it to that project.

To do this, head over to the project you want to add the identity to and go to Project Settings > Access Control > Machine Identities and press Add identity.

Next, select the identity you want to add to the project and the project level role you want to allow it to assume. The project role assigned will determine what project level resources this identity can have access to.

identities project

identities project create

To access the Hanzo KMS API as the identity, you need to construct a signed GetCallerIdentity query using the AWS Signature v4 algorithm and make a request to the /api/v1/auth/aws-auth/login endpoint containing the query data in exchange for an access token.

We provide a few code examples below of how you can authenticate with Hanzo KMS from inside a Lambda function, EC2 instance, etc. and obtain an access token to access the Hanzo KMS API.

The following query construction is an example of how you can authenticate with Hanzo KMS from inside a Lambda function.

The shown example uses Node.js but you can use other languages supported by AWS Lambda.

import AWS from "aws-sdk";
import axios from "axios";

export const handler = async (event, context) => {
    try {
        const region = process.env.AWS_REGION;
        AWS.config.update({ region });

        const iamRequestURL = `https://sts.${region}.amazonaws.com/`;
        const iamRequestBody = "Action=GetCallerIdentity&Version=2011-06-15";
        const iamRequestHeaders = {
            "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
            Host: `sts.${region}.amazonaws.com`,
        };

        // Create the request
        const request = new AWS.HttpRequest(iamRequestURL, region);
        request.method = "POST";
        request.headers = iamRequestHeaders;
        request.headers["X-Amz-Date"] = AWS.util.date
            .iso8601(new Date())
            .replace(/[:-]|\.\d{3}/g, "");
        request.body = iamRequestBody;
        request.headers["Content-Length"] =
        Buffer.byteLength(iamRequestBody).toString();

        // Sign the request
        const signer = new AWS.Signers.V4(request, "sts");
        signer.addAuthorization(AWS.config.credentials, new Date());

        const kmsUrl = "https://app.kms.hanzo.ai"; // or your self-hosted Hanzo KMS URL
        const identityId = "<your-identity-id>";

        const { data } = await axios.post(
            `${kmsUrl}/api/v1/auth/aws-auth/login`,
            {
                identityId,
                iamHttpRequestMethod: "POST",
                iamRequestUrl: Buffer.from(iamRequestURL).toString("base64"),
                iamRequestBody: Buffer.from(iamRequestBody).toString("base64"),
                iamRequestHeaders: Buffer.from(
                JSON.stringify(iamRequestHeaders)
                ).toString("base64"),
            }
        );

        console.log("result data: ", data); // access token here
    } catch (err) {
        console.error(err);
    }
};

The following query construction is an example of how you can authenticate with Hanzo KMS from inside a EC2 instance.

The shown example uses Node.js but you can use other language you wish.

import AWS from "aws-sdk";
import axios from "axios";

const main = async () => {
    try {
        // obtain region from EC2 instance metadata
        const tokenResponse = await axios.put("http://169.254.169.254/latest/api/token", null, {
            headers: {
            "X-aws-ec2-metadata-token-ttl-seconds": "21600"
            }
        });

        const url = "http://169.254.169.254/latest/dynamic/instance-identity/document";
        const response = await axios.get(url, {
            headers: {
                "X-aws-ec2-metadata-token": tokenResponse.data
            }
        });

        const region = response.data.region;

        AWS.config.update({
            region
        });

        const iamRequestURL = `https://sts.${region}.amazonaws.com/`;
        const iamRequestBody = "Action=GetCallerIdentity&Version=2011-06-15";
        const iamRequestHeaders = {
            "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
            Host: `sts.${region}.amazonaws.com`
        };

        const request = new AWS.HttpRequest(new AWS.Endpoint(iamRequestURL), AWS.config.region);
        request.method = "POST";
        request.headers = iamRequestHeaders;
        request.headers["X-Amz-Date"] = AWS.util.date.iso8601(new Date()).replace(/[:-]|\.\d{3}/g, "");
        request.body = iamRequestBody;
        request.headers["Content-Length"] = Buffer.byteLength(iamRequestBody);

        const signer = new AWS.Signers.V4(request, "sts");
        signer.addAuthorization(AWS.config.credentials, new Date());

        const kmsUrl = "https://app.kms.hanzo.ai"; // or your self-hosted Hanzo KMS URL
        const identityId = "<your-identity-id>";

        const { data } = await axios.post(`${kmsUrl}/api/v1/auth/aws-auth/login`, {
            identityId,
            iamHttpRequestMethod: "POST",
            iamRequestUrl: Buffer.from(iamRequestURL).toString("base64"),
            iamRequestBody: Buffer.from(iamRequestBody).toString("base64"),
            iamRequestHeaders: Buffer.from(JSON.stringify(iamRequestHeaders)).toString("base64")
        });

        console.log("result data: ", data); // access token here
    } catch (err) {
        console.error(err);
    }
}

main();

The following query construction provides a generic example of how you can construct a signed GetCallerIdentity query and obtain the required payload components.

The shown example uses Node.js but you can use any language you wish.

const AWS = require("aws-sdk");

const region = "<your-aws-region>";
const kmsUrl = "https://app.kms.hanzo.ai"; // or your self-hosted Hanzo KMS URL

const iamRequestURL = `https://sts.${region}.amazonaws.com/`;
const iamRequestBody = "Action=GetCallerIdentity&Version=2011-06-15";
const iamRequestHeaders = {
    "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
    Host: `sts.${region}.amazonaws.com`
};

const request = new AWS.HttpRequest(new AWS.Endpoint(iamRequestURL), region);
request.method = "POST";
request.headers = iamRequestHeaders;
request.headers["X-Amz-Date"] = AWS.util.date.iso8601(new Date()).replace(/[:-]|\.\d{3}/g, "");
request.body = iamRequestBody;
request.headers["Content-Length"] = Buffer.byteLength(iamRequestBody);

const signer = new AWS.Signers.V4(request, "sts");
signer.addAuthorization(AWS.config.credentials, new Date());

Sample request

curl --location --request POST 'https://app.kms.hanzo.ai/api/v1/auth/aws-auth/login' \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode 'identityId=...' \
    --data-urlencode 'iamHttpRequestMethod=...' \
    --data-urlencode 'iamRequestBody=...' \
    --data-urlencode 'iamRequestHeaders=...'

Note that you should replace <identityId> with the ID of the identity you created in step 1.

Sample response

{
    "accessToken": "...",
    "expiresIn": 7200,
    "accessTokenMaxTTL": 43244
    "tokenType": "Bearer"
}

Next, you can use the access token to access the Hanzo KMS API

The following query construction is an example of how you can authenticate with Hanzo KMS from inside an EKS pod.

The shown example uses Node.js Typescript but you can use any language you wish.

import axios from "axios";
import { Sha256 } from "@aws-crypto/sha256-js";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import { HttpRequest } from "@aws-sdk/protocol-http";
import { SignatureV4 } from "@aws-sdk/signature-v4";

const main = async () => {
  try {
    const tokenRes = await axios.put<string>("http://169.254.169.254/latest/api/token", undefined, {
      headers: {
        "X-aws-ec2-metadata-token-ttl-seconds": "21600"
      }
    });

    const {
      data: { region }
    } = await axios.get<{ region: string }>("http://169.254.169.254/latest/dynamic/instance-identity/document", {
      headers: {
        "X-aws-ec2-metadata-token": tokenRes.data,
        Accept: "application/json"
      }
    });

    const credentials = await fromNodeProviderChain()();

    if (!credentials.accessKeyId || !credentials.secretAccessKey) {
      throw new Error("Credentials not found");
    }

    const iamRequestURL = `https://sts.${region}.amazonaws.com/`;
    const iamRequestBody = "Action=GetCallerIdentity&Version=2011-06-15";
    const iamRequestHeaders = {
      "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
      Host: `sts.${region}.amazonaws.com`
    };

    const request = new HttpRequest({
      protocol: "https:",
      hostname: `sts.${region}.amazonaws.com`,
      path: "/",
      method: "POST",
      headers: {
        ...iamRequestHeaders,
        "Content-Length": String(Buffer.byteLength(iamRequestBody))
      },
      body: iamRequestBody
    });

    const signer = new SignatureV4({
      credentials,
      region,
      service: "sts",
      sha256: Sha256
    });

    const signedRequest = await signer.sign(request);

    const headers: Record<string, string> = {};
    Object.entries(signedRequest.headers).forEach(([key, value]) => {
      if (typeof value === "string") headers[key] = value;
    });

    const iamRequest = {
      iamHttpRequestMethod: "POST",
      iamRequestUrl: iamRequestURL,
      iamRequestBody: iamRequestBody,
      iamRequestHeaders: headers
    };

    const {
      data: { accessToken }
    } = await axios.post<{ accessToken: string }>("https://app.kms.hanzo.ai/api/v1/auth/aws-auth/login", {
      ...iamRequest,
      identityId: "<replace-with-your-identity-id>"
    });

    console.log(`Hanzo KMS Access Token: ${accessToken}`);
  } catch (e) {
    console.error("Failed to do AWS auth", e);
  }
};

We recommend using one of Hanzo KMS's clients like SDKs or the KMS Agent to authenticate with Hanzo KMS using AWS Auth as they handle the authentication process including the signed GetCallerIdentity query construction for you.

Each identity access token has a time-to-live (TTL) which you can infer from the response of the login operation; the default TTL is 7200 seconds which can be adjusted.

If an identity access token expires, it can no longer authenticate with the Hanzo KMS API. In this case, a new access token should be obtained by performing another login operation.

How is this guide?

Last updated on

On this page