infrahub-sdk 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -39,11 +39,25 @@ const usersData = await client.executeGraphQL(listDevices);
39
39
 
40
40
  ## TLS/SSL Configuration
41
41
 
42
- When connecting to Infrahub instances with custom or self-signed certificates, you can configure TLS options:
42
+ When connecting to Infrahub instances with custom, self-signed, or expired certificates, you can configure TLS options:
43
+
44
+ ### Handling Certificate Errors
45
+
46
+ If you encounter certificate errors such as:
47
+ - `certificate has expired`
48
+ - `self-signed certificate`
49
+ - `unable to verify the first certificate`
50
+ - `UNABLE_TO_VERIFY_LEAF_SIGNATURE`
51
+
52
+ You can resolve these by configuring the TLS options as shown below.
43
53
 
44
54
  ### Disable Certificate Verification (for development/testing)
45
55
 
56
+ This is the recommended approach for handling expired certificates in development/testing environments:
57
+
46
58
  ```typescript
59
+ import { InfrahubClient, InfrahubClientOptions } from 'infrahub-sdk';
60
+
47
61
  const options: InfrahubClientOptions = {
48
62
  address: "https://infrahub.example.com",
49
63
  token: "your-api-token",
@@ -55,7 +69,22 @@ const options: InfrahubClientOptions = {
55
69
  const client = new InfrahubClient(options);
56
70
  ```
57
71
 
58
- **Warning**: Disabling certificate verification is not recommended for production environments as it makes your connection vulnerable to man-in-the-middle attacks.
72
+ **Important Notes:**
73
+ - Setting `rejectUnauthorized: false` disables ALL certificate validation
74
+ - This bypasses checks for expired, self-signed, and invalid certificates
75
+ - **Warning**: Never use this in production environments as it makes your connection vulnerable to man-in-the-middle attacks
76
+ - Only use this for development, testing, or when connecting to trusted internal servers
77
+
78
+ **Example:** See [examples/expired-certificate-example.ts](examples/expired-certificate-example.ts) for a complete working example.
79
+
80
+ ### Troubleshooting
81
+
82
+ If you're still experiencing certificate errors after setting `rejectUnauthorized: false`:
83
+
84
+ 1. **Verify the configuration is being applied**: Make sure you're creating the client with the TLS options
85
+ 2. **Check for multiple client instances**: Ensure all instances use the same TLS configuration
86
+ 3. **Network/Proxy Issues**: If you're behind a proxy, you may need additional configuration
87
+ 4. **Node.js Version**: Ensure you're using Node.js 14 or later
59
88
 
60
89
  ### Use Custom CA Certificate
61
90
 
package/dist/index.d.ts CHANGED
@@ -17,10 +17,14 @@ export interface TLSConfig {
17
17
  /**
18
18
  * If true, the server certificate is verified against the list of supplied CAs.
19
19
  * Set to false to disable certificate verification (not recommended for production).
20
+ *
21
+ * Note: Setting this to false will bypass all certificate validation, including
22
+ * expired certificates, self-signed certificates, and hostname mismatches.
20
23
  */
21
24
  rejectUnauthorized?: boolean;
22
25
  /**
23
26
  * Optional CA certificates to trust. Can be a string or Buffer containing the certificate(s).
27
+ * Use this when connecting to servers with custom or self-signed certificates.
24
28
  */
25
29
  ca?: string | Buffer | Array<string | Buffer>;
26
30
  /**
@@ -38,7 +42,15 @@ export interface InfrahubClientOptions {
38
42
  branch?: string;
39
43
  /**
40
44
  * TLS/SSL configuration options for HTTPS connections.
41
- * Use this to handle custom certificates or disable certificate verification.
45
+ * Use this to handle custom certificates, expired certificates, or disable certificate verification.
46
+ *
47
+ * @example
48
+ * // Disable certificate verification (development only)
49
+ * { tls: { rejectUnauthorized: false } }
50
+ *
51
+ * @example
52
+ * // Use custom CA certificate
53
+ * { tls: { ca: fs.readFileSync('/path/to/ca.pem') } }
42
54
  */
43
55
  tls?: TLSConfig;
44
56
  }
package/dist/index.js CHANGED
@@ -35,18 +35,52 @@ class InfrahubClient {
35
35
  this.defaultBranch = options.branch || DEFAULT_BRANCH_NAME;
36
36
  this.branch = new branch_1.InfrahubBranchManager(this);
37
37
  // Create custom fetch with TLS options if provided
38
- let customFetch = node_fetch_1.default;
38
+ // Also handle Request objects properly for node-fetch v2 compatibility
39
+ let httpsAgent;
39
40
  if (options.tls) {
40
- const httpsAgent = new https_1.default.Agent({
41
- rejectUnauthorized: options.tls.rejectUnauthorized,
42
- ca: options.tls.ca,
43
- cert: options.tls.cert,
44
- key: options.tls.key
45
- });
46
- customFetch = ((url, opts = {}) => {
47
- return (0, node_fetch_1.default)(url, { ...opts, agent: httpsAgent });
48
- });
41
+ // Build agent options, ensuring rejectUnauthorized is explicitly set if provided
42
+ const agentOptions = {};
43
+ if (options.tls.rejectUnauthorized !== undefined) {
44
+ agentOptions.rejectUnauthorized = options.tls.rejectUnauthorized;
45
+ }
46
+ if (options.tls.ca !== undefined) {
47
+ agentOptions.ca = options.tls.ca;
48
+ }
49
+ if (options.tls.cert !== undefined) {
50
+ agentOptions.cert = options.tls.cert;
51
+ }
52
+ if (options.tls.key !== undefined) {
53
+ agentOptions.key = options.tls.key;
54
+ }
55
+ httpsAgent = new https_1.default.Agent(agentOptions);
49
56
  }
57
+ // Wrap fetch to handle Request objects from openapi-fetch
58
+ // node-fetch v2 doesn't properly extract URL from Request objects
59
+ const customFetch = ((input, init) => {
60
+ let url;
61
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
+ let options = init || {};
63
+ // Handle Request objects by extracting URL and merging options
64
+ if (input && typeof input === 'object' && 'url' in input) {
65
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
66
+ const req = input;
67
+ url = req.url;
68
+ options = {
69
+ method: req.method,
70
+ headers: req.headers,
71
+ body: req.body,
72
+ ...init
73
+ };
74
+ }
75
+ else {
76
+ url = input;
77
+ }
78
+ // Add HTTPS agent if configured
79
+ if (httpsAgent) {
80
+ options = { ...options, agent: httpsAgent };
81
+ }
82
+ return (0, node_fetch_1.default)(url, options);
83
+ });
50
84
  // Initialize the openapi-fetch client with TLS configuration
51
85
  this.rest = (0, openapi_fetch_1.default)({
52
86
  baseUrl: this.baseUrl,
@@ -128,6 +162,45 @@ class InfrahubClient {
128
162
  return await this.graphqlClient.request(query, variables);
129
163
  }
130
164
  catch (error) {
165
+ // Check if this is a certificate error and provide helpful guidance
166
+ if (error instanceof Error) {
167
+ const errorMessage = error.message.toLowerCase();
168
+ const isCertError = errorMessage.includes('certificate') ||
169
+ errorMessage.includes('cert') ||
170
+ errorMessage.includes('ssl') ||
171
+ errorMessage.includes('tls');
172
+ const isExpired = errorMessage.includes('expired');
173
+ const isSelfSigned = errorMessage.includes('self-signed') || errorMessage.includes('self signed');
174
+ const isUnauthorized = errorMessage.includes('unauthorized');
175
+ if (isCertError && (isExpired || isSelfSigned || isUnauthorized)) {
176
+ const helpMessage = [
177
+ '',
178
+ 'Certificate validation failed. To resolve this issue, you can configure TLS options:',
179
+ '',
180
+ '1. Disable certificate verification (for development/testing only):',
181
+ ' const client = new InfrahubClient({',
182
+ ' address: "your-address",',
183
+ ' token: "your-token",',
184
+ ' tls: { rejectUnauthorized: false }',
185
+ ' });',
186
+ '',
187
+ '2. Or provide a custom CA certificate (requires: import fs from "fs"):',
188
+ ' const client = new InfrahubClient({',
189
+ ' address: "your-address",',
190
+ ' token: "your-token",',
191
+ ' tls: { ca: fs.readFileSync("/path/to/ca-cert.pem") }',
192
+ ' });',
193
+ '',
194
+ 'See the README.md for more TLS configuration options.',
195
+ ''
196
+ ].join('\n');
197
+ console.error(helpMessage);
198
+ // Create a new error with helpful message appended
199
+ const enhancedError = new Error(`${error.message}\n${helpMessage}`);
200
+ enhancedError.stack = error.stack;
201
+ throw enhancedError;
202
+ }
203
+ }
131
204
  console.error('Error executing GraphQL query:', error);
132
205
  throw error;
133
206
  }
@@ -38,6 +38,50 @@ const globals_1 = require("@jest/globals");
38
38
  await (0, globals_1.expect)(client.executeGraphQL('{ test }')).rejects.toThrow('GraphQL error');
39
39
  consoleErrorSpy.mockRestore();
40
40
  });
41
+ (0, globals_1.it)('should provide helpful error message for certificate errors', async () => {
42
+ const mockRequest = globals_1.jest
43
+ .fn()
44
+ .mockImplementation(() => Promise.reject(new Error('request failed, reason: certificate has expired')));
45
+ client.graphqlClient.request = mockRequest;
46
+ const consoleErrorSpy = globals_1.jest
47
+ .spyOn(console, 'error')
48
+ .mockImplementation(() => { });
49
+ try {
50
+ await client.executeGraphQL('{ test }');
51
+ (0, globals_1.expect)(true).toBe(false); // Should not reach here
52
+ }
53
+ catch (error) {
54
+ (0, globals_1.expect)(error).toBeInstanceOf(Error);
55
+ if (error instanceof Error) {
56
+ (0, globals_1.expect)(error.message).toContain('certificate has expired');
57
+ (0, globals_1.expect)(error.message).toContain('Certificate validation failed');
58
+ (0, globals_1.expect)(error.message).toContain('rejectUnauthorized: false');
59
+ }
60
+ }
61
+ consoleErrorSpy.mockRestore();
62
+ });
63
+ (0, globals_1.it)('should provide helpful error message for self-signed certificate errors', async () => {
64
+ const mockRequest = globals_1.jest
65
+ .fn()
66
+ .mockImplementation(() => Promise.reject(new Error('request failed, reason: self-signed certificate')));
67
+ client.graphqlClient.request = mockRequest;
68
+ const consoleErrorSpy = globals_1.jest
69
+ .spyOn(console, 'error')
70
+ .mockImplementation(() => { });
71
+ try {
72
+ await client.executeGraphQL('{ test }');
73
+ (0, globals_1.expect)(true).toBe(false); // Should not reach here
74
+ }
75
+ catch (error) {
76
+ (0, globals_1.expect)(error).toBeInstanceOf(Error);
77
+ if (error instanceof Error) {
78
+ (0, globals_1.expect)(error.message).toContain('self-signed certificate');
79
+ (0, globals_1.expect)(error.message).toContain('Certificate validation failed');
80
+ (0, globals_1.expect)(error.message).toContain('tls: { rejectUnauthorized: false }');
81
+ }
82
+ }
83
+ consoleErrorSpy.mockRestore();
84
+ });
41
85
  (0, globals_1.it)('should initialize rest client with baseUrl', () => {
42
86
  (0, globals_1.expect)(client.rest).toBeDefined();
43
87
  });
@@ -72,6 +116,22 @@ const globals_1 = require("@jest/globals");
72
116
  (0, globals_1.expect)(tlsClient).toBeDefined();
73
117
  (0, globals_1.expect)(tlsClient.graphqlClient).toBeInstanceOf(graphql_request_1.GraphQLClient);
74
118
  });
119
+ (0, globals_1.it)('should create agent with rejectUnauthorized: false when explicitly set', () => {
120
+ const https = require('https');
121
+ const createAgentSpy = globals_1.jest.spyOn(https, 'Agent');
122
+ const options = {
123
+ address: baseURL,
124
+ token: token,
125
+ tls: {
126
+ rejectUnauthorized: false
127
+ }
128
+ };
129
+ const tlsClient = new index_1.InfrahubClient(options);
130
+ (0, globals_1.expect)(createAgentSpy).toHaveBeenCalled();
131
+ const agentOptions = createAgentSpy.mock.calls[createAgentSpy.mock.calls.length - 1][0];
132
+ (0, globals_1.expect)(agentOptions.rejectUnauthorized).toBe(false);
133
+ createAgentSpy.mockRestore();
134
+ });
75
135
  (0, globals_1.it)('should accept TLS configuration with custom CA certificate', () => {
76
136
  const options = {
77
137
  address: baseURL,
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Integration tests for the Infrahub SDK
3
+ *
4
+ * These tests require a running Infrahub server at http://localhost:8000
5
+ *
6
+ * Run with: npx jest --testPathPattern=integration --resetModules
7
+ * Or run directly: npx ts-node src/integration.test.ts
8
+ */
9
+ export {};
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ /**
3
+ * Integration tests for the Infrahub SDK
4
+ *
5
+ * These tests require a running Infrahub server at http://localhost:8000
6
+ *
7
+ * Run with: npx jest --testPathPattern=integration --resetModules
8
+ * Or run directly: npx ts-node src/integration.test.ts
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ const index_1 = require("./index");
12
+ const globals_1 = require("@jest/globals");
13
+ const INFRAHUB_URL = process.env.INFRAHUB_URL || 'http://localhost:8000';
14
+ const INFRAHUB_TOKEN = process.env.INFRAHUB_TOKEN || '';
15
+ (0, globals_1.describe)('Integration Tests - Schema Loading', () => {
16
+ let client;
17
+ (0, globals_1.beforeAll)(() => {
18
+ const options = {
19
+ address: INFRAHUB_URL,
20
+ token: INFRAHUB_TOKEN
21
+ };
22
+ client = new index_1.InfrahubClient(options);
23
+ });
24
+ (0, globals_1.it)('should load schema from the server', async () => {
25
+ const result = await client.rest.GET('/api/schema');
26
+ (0, globals_1.expect)(result.error).toBeUndefined();
27
+ (0, globals_1.expect)(result.response?.status).toBe(200);
28
+ (0, globals_1.expect)(result.data).toBeDefined();
29
+ // Schema should have nodes and/or generics arrays
30
+ if (result.data) {
31
+ (0, globals_1.expect)(typeof result.data).toBe('object');
32
+ }
33
+ });
34
+ (0, globals_1.it)('should load schema summary from the server', async () => {
35
+ const result = await client.rest.GET('/api/schema/summary');
36
+ (0, globals_1.expect)(result.error).toBeUndefined();
37
+ (0, globals_1.expect)(result.response?.status).toBe(200);
38
+ (0, globals_1.expect)(result.data).toBeDefined();
39
+ });
40
+ (0, globals_1.it)('should get server info', async () => {
41
+ const result = await client.rest.GET('/api/info');
42
+ (0, globals_1.expect)(result.error).toBeUndefined();
43
+ (0, globals_1.expect)(result.response?.status).toBe(200);
44
+ (0, globals_1.expect)(result.data).toBeDefined();
45
+ });
46
+ (0, globals_1.it)('should get server config', async () => {
47
+ const result = await client.rest.GET('/api/config');
48
+ (0, globals_1.expect)(result.error).toBeUndefined();
49
+ (0, globals_1.expect)(result.response?.status).toBe(200);
50
+ (0, globals_1.expect)(result.data).toBeDefined();
51
+ });
52
+ });
@@ -0,0 +1 @@
1
+ export {};