@cocreate/api 1.31.0 → 1.34.0

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.
@@ -0,0 +1,198 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const vm = require('node:vm');
5
+ const { spawnSync } = require('node:child_process');
6
+ const { URL } = require('node:url');
7
+
8
+ const source = fs.readFileSync(require.resolve('../src/server.js'), 'utf8')
9
+ .replace(/^import \{ URL \} from 'node:url';$/m, '')
10
+ .replace(/import \{[\s\S]*?\} from '@cocreate\/utils';/, '')
11
+ .replace(/export async function/g, 'async function')
12
+ .replace(/export default \{[\s\S]*?\};/, '');
13
+ const dependencies = Promise.all([
14
+ import('../../CoCreate-utils/src/modules/ast/index.js'),
15
+ import('../../CoCreate-utils/src/modules/objectToSearchParams.js'),
16
+ import('../../CoCreate-utils/src/modules/searchParamsToObject.js'),
17
+ import('../../../CoCreate-app/src/apps/endpoints/config/data.js'),
18
+ import('../../../CoCreate-app/src/apps/servers/configs/config/autoscaler.js')
19
+ ]);
20
+
21
+ async function setup({ index = 0, storage, storageError } = {}) {
22
+ const [{ astAsync }, { objectToSearchParams }, { searchParamsToObject }, endpoints, startup] = await dependencies;
23
+ const definitions = endpoints.default.object.filter(record => record.name === 'create-instance');
24
+ const endpoint = definitions[index];
25
+ let currentStorage = storage;
26
+ let returnedStorage;
27
+ const lookups = [];
28
+ const requests = [];
29
+ const context = vm.createContext({
30
+ Buffer, URL, AbortController, setTimeout, clearTimeout,
31
+ console: { log() {}, warn() {}, error() {} },
32
+ objectToSearchParams, searchParamsToObject, astAsync, security: {},
33
+ fetch: async (url, options) => {
34
+ const body = options.body?.startsWith('{')
35
+ ? JSON.parse(options.body)
36
+ : Object.fromEntries(new URLSearchParams(options.body || ''));
37
+ requests.push({ url, body });
38
+ let result;
39
+ if (body.Action === 'DescribeVpcs') result = '<vpcId>vpc-example</vpcId>';
40
+ else if (body.Action === 'DescribeSecurityGroups') result = '<groupId>sg-example</groupId>';
41
+ else if (body.Action === 'RunInstances') result = '<instanceId>i-example</instanceId><imageId>ami-example</imageId><instanceType>small</instanceType><instanceState><name>pending</name></instanceState><availabilityZone>example</availabilityZone><privateIpAddress>127.0.0.1</privateIpAddress>';
42
+ else result = JSON.stringify({ id: 'existing-resource' });
43
+ return new Response(result, { status: 200 });
44
+ }
45
+ });
46
+ vm.runInContext(source, context);
47
+ await context.init({
48
+ organization_id: 'platform',
49
+ crud: { send: async query => {
50
+ lookups.push(query);
51
+ if (query.array === 'endpoints') {
52
+ if (query.filter.query.name === 'create-instance') return { object: [endpoint] };
53
+ if (query.filter.query.name === 'resolve-image') return { object: [{
54
+ resolved: true, method: 'post', endpoint: '/', data: { Parameter: { Value: 'ami-example' } }
55
+ }] };
56
+ return { object: [] };
57
+ }
58
+ assert.equal(query.array, 'apis');
59
+ if (query.filter.query._id) {
60
+ assert.equal(query.organization_id, 'platform');
61
+ assert.equal(query.filter.query.type, 'storage');
62
+ assert.equal(query.filter.query.enabled, true);
63
+ assert.equal(query.filter.limit, 1);
64
+ if (storageError) return { error: [storageError] };
65
+ const found = currentStorage?._id === query.filter.query._id &&
66
+ currentStorage.enabled === true && currentStorage.organization_id === query.organization_id;
67
+ // Model a projected CRUD record that retains its internal ID.
68
+ // The endpoint must pass it through without further reshaping.
69
+ returnedStorage = found ? Object.fromEntries(Object.entries(currentStorage)
70
+ .filter(([key]) => key === '_id' || query.filter.key?.[key] !== 0)) : undefined;
71
+ return { object: found ? [returnedStorage] : [] };
72
+ }
73
+ return { object: [{ _id: endpoint.api_id, name: 'test-cloud', url: 'https://cloud.invalid' }] };
74
+ } }
75
+ });
76
+ return {
77
+ requests, lookups,
78
+ get returnedStorage() { return returnedStorage; },
79
+ setStorage(value) { currentStorage = value; },
80
+ async run(data = {}) {
81
+ const original = {
82
+ storage: 'storage-id', region: 'example', vmType: 'small', vmId: 'server-example',
83
+ cluster_id: 'cluster-id', host: 'example.com', binaryUrl: 'https://example.com/runtime.tar.gz',
84
+ environment: 'server_id=server-id\ncluster_id=cluster-id',
85
+ startupScript: startup.default.object[0].config.startupScript,
86
+ ...data
87
+ };
88
+ const result = await context.send({
89
+ api: 'test-cloud', endpoint: 'create-instance', method: endpoint.method,
90
+ organization_id: 'platform', host: 'platform.example.com', region: 'example', data: original
91
+ });
92
+ assert.equal(original.storage, data.storage ?? 'storage-id');
93
+ return result;
94
+ }
95
+ };
96
+ }
97
+
98
+ function readBootstrap(requests) {
99
+ let script;
100
+ for (const { body } of requests) {
101
+ const encoded = body.UserData || body.properties?.osProfile?.customData || body.metadata?.user_data;
102
+ if (encoded) script = Buffer.from(encoded, 'base64').toString('utf8');
103
+ else if (body.user_data) {
104
+ script = body.user_data.startsWith('#!') ? body.user_data : Buffer.from(body.user_data, 'base64').toString('utf8');
105
+ } else if (body.userdata) script = body.userdata;
106
+ else if (body.metadata?.items) script = body.metadata.items.find(item => item.key === 'startup-script')?.value;
107
+ }
108
+ assert.ok(script?.startsWith('#!/usr/bin/env bash'), 'Cloud request must contain the rendered startup script');
109
+ const syntax = spawnSync('bash', ['-n'], { input: script, encoding: 'utf8' });
110
+ assert.equal(syntax.status, 0, syntax.stderr);
111
+ assert.ok(script.includes('https://example.com/runtime.tar.gz'));
112
+ const match = script.match(/printf '%s' '([^']+)' \| base64 --decode > \/etc\/cocreatews\/storage.json/);
113
+ assert.ok(match, 'Startup script must contain encoded bootstrap storage');
114
+ return JSON.parse(Buffer.from(match[1], 'base64').toString('utf8'));
115
+ }
116
+
117
+ const record = {
118
+ _id: 'storage-id', organization_id: 'platform', name: 'primary', provider: 'mongodb',
119
+ type: 'storage', enabled: true, connectionString: 'mongodb://example/platform'
120
+ };
121
+
122
+ for (let index = 0; index < 8; index++) {
123
+ test(`create-instance endpoint ${index + 1} resolves the storage ID before rendering cloud user data`, async () => {
124
+ const fixture = await setup({ index, storage: record });
125
+ await fixture.run();
126
+ assert.deepEqual(readBootstrap(fixture.requests), fixture.returnedStorage);
127
+ assert.equal(fixture.returnedStorage.connectionString, record.connectionString);
128
+ assert.equal(fixture.returnedStorage.organization_id, undefined);
129
+ assert.equal(fixture.returnedStorage.enabled, undefined);
130
+ assert.equal(fixture.lookups.filter(query => query.filter?.query?.type === 'storage').length, 1);
131
+ });
132
+ }
133
+
134
+ test('subsequent provisioning reads rotated credentials while keeping the storage ID', async () => {
135
+ const fixture = await setup({ storage: record });
136
+ await fixture.run();
137
+ assert.deepEqual(readBootstrap(fixture.requests), fixture.returnedStorage);
138
+ fixture.requests.length = 0;
139
+ const rotated = { ...record, connectionString: 'mongodb://rotated/平台' };
140
+ fixture.setStorage(rotated);
141
+ await fixture.run();
142
+ assert.deepEqual(readBootstrap(fixture.requests), fixture.returnedStorage);
143
+ assert.equal(fixture.returnedStorage.connectionString, rotated.connectionString);
144
+ });
145
+
146
+ test('endpoint bootstrap keeps arbitrary provider credential fields unchanged', async () => {
147
+ const storage = {
148
+ ...record, provider: 'custom-provider', connectionString: undefined,
149
+ apiKey: 'example-key', credentials: { uri: 'custom://example', options: { region: 'example' } }
150
+ };
151
+ delete storage.connectionString;
152
+ const fixture = await setup({ storage });
153
+ await fixture.run();
154
+ assert.deepEqual(readBootstrap(fixture.requests), fixture.returnedStorage);
155
+ assert.equal(fixture.returnedStorage.apiKey, storage.apiKey);
156
+ assert.deepEqual(fixture.returnedStorage.credentials, storage.credentials);
157
+ });
158
+
159
+ for (const id of [undefined, '', ' ', { name: 'embedded-credentials' }]) {
160
+ test(`invalid storage ID ${JSON.stringify(id)} stops before database lookup or cloud calls`, async () => {
161
+ const fixture = await setup({ storage: record });
162
+ await assert.rejects(fixture.run({ storage: id }), /requires a storage API record ID/);
163
+ assert.equal(fixture.requests.length, 0);
164
+ assert.equal(fixture.lookups.filter(query => query.filter?.query?.type === 'storage').length, 0);
165
+ });
166
+ }
167
+
168
+ for (const unavailable of [null, { ...record, enabled: false }, { ...record, organization_id: 'another-org' }]) {
169
+ test(`unavailable storage ${unavailable?.organization_id || 'missing'} stops before any cloud call`, async () => {
170
+ const fixture = await setup({ storage: unavailable });
171
+ await assert.rejects(fixture.run(), /storage API record is unavailable/);
172
+ assert.equal(fixture.requests.length, 0);
173
+ });
174
+ }
175
+
176
+ test('storage read errors and malformed records stop the endpoint pipeline', async () => {
177
+ const readError = await setup({ storage: record, storageError: 'read failed' });
178
+ await assert.rejects(readError.run(), /Unable to read/);
179
+ assert.equal(readError.requests.length, 0);
180
+ const invalid = await setup({ storage: { ...record, provider: '' } });
181
+ await assert.rejects(invalid.run(), /requires a provider/);
182
+ assert.equal(invalid.requests.length, 0);
183
+ });
184
+
185
+
186
+ test('storage lookup requests MongoDB-compatible provider template exclusions', async () => {
187
+ const template = fs.readFileSync(new URL('../../../CoCreate-app/src/apps/apis/components/fields.html', 'file://' + __filename), 'utf8');
188
+ const excluded = template.match(/render-exclude="([^"]+)"/)[1].split(',').map(key => key.trim())
189
+ .filter(key => !['name', 'provider', '_id'].includes(key) && !key.startsWith('$'));
190
+ const fixture = await setup({ storage: record });
191
+ await fixture.run();
192
+ const query = fixture.lookups.find(query => query.filter?.query?.type === 'storage');
193
+ assert.deepEqual(Object.keys(query.filter.key).sort(), excluded.sort());
194
+ assert.ok(Object.values(query.filter.key).every(value => value === 0));
195
+ assert.equal(fixture.returnedStorage.name, record.name);
196
+ assert.equal(fixture.returnedStorage.provider, record.provider);
197
+ assert.equal(readBootstrap(fixture.requests)._id, record._id);
198
+ });