# How kcmd Handles Authentication: Inside the ApiContext Class

> Discover how kcmd handles authentication by exploring the ApiContext class. Learn how it uses gcloud CLI and OAuth 2.0 tokens for secure Google Cloud API calls.

- Repository: [Google Cloud Platform/knowledge-catalog](https://github.com/GoogleCloudPlatform/knowledge-catalog)
- Tags: internals
- Published: 2026-07-15

---

**kcmd authenticates all Google Cloud API calls through the `ApiContext` class, which executes `gcloud` CLI commands to obtain Application Default Credentials and automatically attaches OAuth 2.0 tokens to every request.**

The `kcmd` CLI tool in the GoogleCloudPlatform/knowledge-catalog repository simplifies interactions with Google Cloud services by abstracting complex authentication flows. Understanding how kcmd handles authentication is essential for developers integrating Dataplex, BigQuery, and other GCP APIs into their workflows. The library delegates credential management to the `ApiContext` class, which bridges local gcloud configurations with secure API requests.

## The ApiContext Authentication Architecture

### Constructing Credentials from gcloud Configuration

In [`toolbox/mdcode/src/libts/gcp/context.ts`](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/toolbox/mdcode/src/libts/gcp/context.ts), the `ApiContext` class serves as the central authentication hub. When a command initializes, it calls `gcp.ApiContext.default()`, which executes three synchronous shell commands to gather the local gcloud configuration:

1. `gcloud -q config get-value project` – Retrieves the active GCP project ID
2. `gcloud -q config get-value compute/region` – Captures the default region or zone  
3. `gcloud auth application-default print-access-token` – Generates a fresh OAuth 2.0 access token

The `default()` method trims these values and instantiates a new `ApiContext(project, location, token)`. This approach ensures that kcmd handles authentication seamlessly across local development machines, Cloud Shell, and CI/CD pipelines where gcloud is configured.

### Token Lifecycle and Automatic Refresh

The `ApiContext` instance stores the access token in a private `_token` property and exposes it through a public `token` getter. For long-running operations, the class provides a `refresh()` method that re-executes the `gcloud auth application-default print-access-token` command to obtain a new token without reconstructing the entire context.

## Token Propagation to GCP Services

Every GCP client wrapper in the kcmd library receives the `ApiContext` instance and injects the token into HTTP headers. In [`toolbox/mdcode/src/libts/gcp/bigquery.ts`](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/toolbox/mdcode/src/libts/gcp/bigquery.ts) and [`toolbox/mdcode/src/libts/gcp/dataplex.ts`](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/toolbox/mdcode/src/libts/gcp/dataplex.ts), the library constructs REST requests with the `Authorization: Bearer <token>` header using the token provided by `ApiContext`. This pattern is consistently implemented across [`toolbox/mdcode/src/libts/gcp/crm.ts`](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/toolbox/mdcode/src/libts/gcp/crm.ts) and other service-specific modules, ensuring uniform authentication handling regardless of the target API.

The CLI entry point in [`toolbox/mdcode/src/tool/main.ts`](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/toolbox/mdcode/src/tool/main.ts) routes commands through [`toolbox/mdcode/src/tool/commands.ts`](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/toolbox/mdcode/src/tool/commands.ts), which retrieves the default context at execution time and passes it to the underlying service wrappers.

## Implementation Examples

### Basic Authentication Context

To use kcmd in a TypeScript application, obtain the default context and pass it to library methods:

```typescript
import * as kcmd from 'kcmd';

// Create the default GCP auth context (reads gcloud config)
const ctx = kcmd.gcp.ApiContext.default();

// Use the context with a kcmd library call
const snapshot = await kcmd.CatalogSnapshot.fromPath('.', ctx);

// Example: fetch entries from a BigQuery dataset
for await (const entry of snapshot.entries(ctx)) {
  console.log(entry.name);
}

```

### Manual Token Refresh

For scripts that run longer than the token expiration period, explicitly refresh the credentials:

```typescript
const ctx = kcmd.gcp.ApiContext.default();

// After some time the token may expire
ctx.refresh();  // Re-issues `gcloud auth application-default print-access-token`

```

### CLI Usage

When using the kcmd command-line interface, authentication is handled automatically without manual context creation:

```bash

# The CLI internally calls ApiContext.default()

kcmd init --bigquery-dataset my-project.my_dataset

```

## Summary

- **kcmd** delegates all GCP authentication to the `ApiContext` class located in [`toolbox/mdcode/src/libts/gcp/context.ts`](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/toolbox/mdcode/src/libts/gcp/context.ts).
- The `ApiContext.default()` method executes gcloud CLI commands to retrieve the project, region, and Application Default Credentials access token.
- Service wrappers in `toolbox/mdcode/src/libts/gcp/` attach the token as a Bearer header to all REST API requests.
- The `refresh()` method allows long-running scripts to renew tokens without restarting the authentication flow.
- This design works automatically in any environment with a configured Google Cloud SDK, including local workstations and Cloud Shell.

## Frequently Asked Questions

### What authentication method does kcmd use under the hood?

kcmd relies on Application Default Credentials (ADC) sourced through the gcloud CLI. Specifically, it executes `gcloud auth application-default print-access-token` to obtain OAuth 2.0 access tokens, which are then attached to HTTP requests via the `Authorization: Bearer` header scheme.

### Do I need to manually configure service account keys to use kcmd?

No. As long as you have gcloud installed and initialized (run `gcloud init` or `gcloud auth application-default login`), kcmd automatically discovers your credentials. The tool reads your active project and default region from the gcloud configuration without requiring explicit service account key files.

### How does kcmd handle token expiration during long-running operations?

The `ApiContext` class provides a `refresh()` method that re-runs the gcloud token generation command to obtain a new access token. You can call this method on an existing context instance to update the internal token without reconstructing the authentication object or re-reading the project configuration.

### Where does kcmd initialize the authentication context in the CLI?

The CLI entry point in [`toolbox/mdcode/src/tool/main.ts`](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/toolbox/mdcode/src/tool/main.ts) routes commands to handlers in [`toolbox/mdcode/src/tool/commands.ts`](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/toolbox/mdcode/src/tool/commands.ts), which invoke `gcp.ApiContext.default()` at execution time. This ensures every sub-command receives a fresh authentication context with valid credentials before making any GCP API calls.