All files / src/lib/edc client.ts

86.04% Statements 37/43
86.27% Branches 44/51
37.5% Functions 3/8
88.09% Lines 37/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266                                                                  9x                                                         9x                         9x             6x 6x 1x       5x     6x   6x       6x       6x   6x                       5x 1x         4x 4x         4x                                       9x                                     6x 6x   6x           6x 6x 6x 5x   1x               6x 6x 6x       6x               6x 1x 1x           5x       5x               9x             6x                                                                        
/**
 * EDC-V / CFM API Client
 *
 * Type-safe client for all JAD Management, Identity, Issuer, Tenant, and
 * Provision Manager APIs. Uses openapi-typescript generated types with
 * a lightweight fetch wrapper.
 *
 * Usage:
 *   import { edcClient } from '@/lib/edc/client';
 *
 *   // List all assets for a participant
 *   const assets = await edcClient.management(
 *     '/v5alpha/participants/{ctxId}/assets/request', 'POST',
 *     { '@context': [EDC_CONTEXT], '@type': 'QuerySpec' }
 *   );
 *
 *   // List tenants
 *   const tenants = await edcClient.tenant('/v1alpha1/tenants');
 *
 * Types are generated from JAD OpenAPI specs via:
 *   npm run generate:api
 *
 * @see {@link https://github.com/Metaform/jad} JAD repository
 */
 
// ---------------------------------------------------------------------------
// Configuration — base URLs for each API (Docker Compose defaults)
// ---------------------------------------------------------------------------
 
/**
 * Server-side env vars (no NEXT_PUBLIC_ prefix) use Docker-internal hostnames.
 * The NEXT_PUBLIC_ fallbacks use Traefik *.localhost for client-side/dev use.
 */
const API_ENDPOINTS = {
  /** EDC-V Management API (Control Plane — port 8081) */
  management:
    process.env.EDC_MANAGEMENT_URL ||
    process.env.NEXT_PUBLIC_EDC_MANAGEMENT_URL ||
    "http://health-dataspace-controlplane:8081/api/mgmt",
  /** DCP Identity API (IdentityHub — port 7081) */
  identity:
    process.env.EDC_IDENTITY_URL ||
    process.env.NEXT_PUBLIC_EDC_IDENTITY_URL ||
    "http://health-dataspace-identityhub:7081/api/identity",
  /** Issuer Admin API (IssuerService — port 10013) */
  issuer:
    process.env.EDC_ISSUER_URL ||
    process.env.NEXT_PUBLIC_EDC_ISSUER_URL ||
    "http://health-dataspace-issuerservice:10013/api/admin",
  /** CFM Tenant Manager API */
  tenant:
    process.env.EDC_TENANT_URL ||
    process.env.NEXT_PUBLIC_CFM_TENANT_URL ||
    "http://health-dataspace-tenant-manager:8080/api",
  /** CFM Provision Manager API */
  provision:
    process.env.EDC_PROVISION_URL ||
    process.env.NEXT_PUBLIC_CFM_PROVISION_URL ||
    "http://health-dataspace-provision-manager:8080/api",
} as const;
 
/** JSON-LD context required by EDC Management API v5alpha */
export const EDC_CONTEXT = "https://w3id.org/edc/connector/management/v2";
 
type ApiName = keyof typeof API_ENDPOINTS;
 
// ---------------------------------------------------------------------------
// Token management — Keycloak OAuth2 client credentials flow
// ---------------------------------------------------------------------------
interface TokenResponse {
  access_token: string;
  expires_in: number;
  token_type: string;
}
 
let cachedToken: { token: string; expiresAt: number } | null = null;
 
/**
 * Get an OAuth2 access token from Keycloak using client credentials grant.
 * Tokens are cached and refreshed 30s before expiry.
 */
async function getAccessToken(): Promise<string> {
  const now = Date.now();
  if (cachedToken && cachedToken.expiresAt > now + 30_000) {
    return cachedToken.token;
  }
 
  const keycloakUrl =
    process.env.KEYCLOAK_INTERNAL_URL ||
    process.env.NEXT_PUBLIC_KEYCLOAK_URL ||
    "http://keycloak:8080";
  const realm = process.env.NEXT_PUBLIC_KEYCLOAK_REALM || "edcv";
  const clientId =
    process.env.EDC_SERVICE_CLIENT_ID ||
    process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID ||
    "admin";
  const clientSecret =
    process.env.EDC_SERVICE_CLIENT_SECRET ||
    process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_SECRET ||
    "edc-v-admin-secret";
 
  const tokenUrl = `${keycloakUrl}/realms/${realm}/protocol/openid-connect/token`;
 
  const response = await fetch(tokenUrl, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "client_credentials",
      client_id: clientId,
      client_secret: clientSecret,
    }),
    cache: "no-store",
    signal: AbortSignal.timeout(5_000),
  });
 
  if (!response.ok) {
    throw new Error(
      `Keycloak token request failed: ${response.status} ${response.statusText}`,
    );
  }
 
  const data: TokenResponse = await response.json();
  cachedToken = {
    token: data.access_token,
    expiresAt: now + data.expires_in * 1000,
  };
 
  return cachedToken.token;
}
 
// ---------------------------------------------------------------------------
// Core fetch wrapper
// ---------------------------------------------------------------------------
interface RequestOptions {
  /** Skip OAuth2 token (for public endpoints) */
  noAuth?: boolean;
  /** Additional headers */
  headers?: Record<string, string>;
  /** AbortSignal for cancellation */
  signal?: AbortSignal;
  /** Request timeout in ms (default 8_000). Prevents hung fetches when the
   *  upstream ACA replica is unavailable (e.g. mvhd-tenant-mgr scaled to 0). */
  timeoutMs?: number;
}
 
/** Default fetch timeout — short enough that a dead upstream doesn't stall
 *  operator dashboards, long enough for normal JAD startup latency. */
const DEFAULT_TIMEOUT_MS = 8_000;
 
/**
 * Make a typed API request to a JAD service.
 *
 * @param api - Which API to call (management, identity, issuer, tenant, provision)
 * @param path - API path (e.g., '/v3/assets/request')
 * @param method - HTTP method
 * @param body - Request body (will be JSON-serialized)
 * @param options - Additional request options
 * @returns Parsed JSON response
 */
async function apiRequest<T = unknown>(
  api: ApiName,
  path: string,
  method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" = "GET",
  body?: unknown,
  options: RequestOptions = {},
): Promise<T> {
  const baseUrl = API_ENDPOINTS[api];
  const url = `${baseUrl}${path}`;
 
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    Accept: "application/json",
    ...options.headers,
  };
 
  Eif (!options.noAuth) {
    try {
      const token = await getAccessToken();
      headers["Authorization"] = `Bearer ${token}`;
    } catch (err) {
      console.warn("Failed to get access token, proceeding without auth:", err);
    }
  }
 
  // Compose caller-supplied AbortSignal (if any) with a default timeout.
  // Without this, a dead ACA replica causes fetches to hang indefinitely,
  // which blocks the /api/admin/components route until the HTTP client
  // times out (and times out the test harness with it).
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  const timeoutSignal = AbortSignal.timeout(timeoutMs);
  const signal = options.signal
    ? AbortSignal.any([options.signal, timeoutSignal])
    : timeoutSignal;
 
  const response = await fetch(url, {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined,
    signal,
    cache: "no-store",
  });
 
  if (!response.ok) {
    const errorBody = await response.text().catch(() => "No error body");
    throw new Error(
      `EDC API error [${api}] ${method} ${path}: ${response.status} ${response.statusText}\n${errorBody}`,
    );
  }
 
  // Handle 204 No Content
  Iif (response.status === 204) {
    return undefined as T;
  }
 
  return response.json() as Promise<T>;
}
 
// ---------------------------------------------------------------------------
// Typed API client facade
// ---------------------------------------------------------------------------
 
/** Type-safe EDC-V / CFM API client */
export const edcClient = {
  /** EDC-V Management API — assets, policies, contracts, catalogs, transfers */
  management: <T = unknown>(
    path: string,
    method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" = "GET",
    body?: unknown,
    options?: RequestOptions,
  ) => apiRequest<T>("management", path, method, body, options),
 
  /** DCP Identity API — participants, key pairs, credentials */
  identity: <T = unknown>(
    path: string,
    method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" = "GET",
    body?: unknown,
    options?: RequestOptions,
  ) => apiRequest<T>("identity", path, method, body, options),
 
  /** Issuer Admin API — credential definitions, issuance */
  issuer: <T = unknown>(
    path: string,
    method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" = "GET",
    body?: unknown,
    options?: RequestOptions,
  ) => apiRequest<T>("issuer", path, method, body, options),
 
  /** CFM Tenant Manager API — tenants, participant profiles, dataspaces */
  tenant: <T = unknown>(
    path: string,
    method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" = "GET",
    body?: unknown,
    options?: RequestOptions,
  ) => apiRequest<T>("tenant", path, method, body, options),
 
  /** CFM Provision Manager API — provision requests, workflows */
  provision: <T = unknown>(
    path: string,
    method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" = "GET",
    body?: unknown,
    options?: RequestOptions,
  ) => apiRequest<T>("provision", path, method, body, options),
} as const;
 
export type { ApiName, RequestOptions };