plugin-workflow-portainer 0.0.0-stage → 0.1.1
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/LICENSE +176 -0
- package/README.md +31 -3
- package/client-v2.js +1 -0
- package/client.js +1 -0
- package/dist/client/127.5012da93825a6e5c.js +10 -0
- package/dist/client/57.ace9538136438718.js +10 -0
- package/dist/client/65.ec4a55173511c06d.js +10 -0
- package/dist/client/660.546c702d1ddf7eff.js +10 -0
- package/dist/client/index.js +10 -0
- package/dist/client-v2/127.0ec4dce7b13750e9.js +10 -0
- package/dist/client-v2/57.e7cfc50fb651ac14.js +10 -0
- package/dist/client-v2/65.9c745ea32ac96e98.js +10 -0
- package/dist/client-v2/660.29ae3c3b4040039d.js +10 -0
- package/dist/client-v2/index.js +10 -0
- package/dist/externalVersion.js +20 -0
- package/dist/index.js +48 -0
- package/dist/locale/en-US.json +151 -0
- package/dist/locale/vi-VN.json +151 -0
- package/dist/locale/zh-CN.json +151 -0
- package/dist/node_modules/joi/dist/joi-browser.min.js +1 -0
- package/dist/node_modules/joi/lib/annotate.js +175 -0
- package/dist/node_modules/joi/lib/base.js +1069 -0
- package/dist/node_modules/joi/lib/cache.js +143 -0
- package/dist/node_modules/joi/lib/common.js +216 -0
- package/dist/node_modules/joi/lib/compile.js +283 -0
- package/dist/node_modules/joi/lib/errors.js +271 -0
- package/dist/node_modules/joi/lib/extend.js +312 -0
- package/dist/node_modules/joi/lib/index.d.ts +2365 -0
- package/dist/node_modules/joi/lib/index.js +1 -0
- package/dist/node_modules/joi/lib/manifest.js +476 -0
- package/dist/node_modules/joi/lib/messages.js +207 -0
- package/dist/node_modules/joi/lib/modify.js +267 -0
- package/dist/node_modules/joi/lib/ref.js +414 -0
- package/dist/node_modules/joi/lib/schemas.js +302 -0
- package/dist/node_modules/joi/lib/state.js +166 -0
- package/dist/node_modules/joi/lib/template.js +463 -0
- package/dist/node_modules/joi/lib/trace.js +346 -0
- package/dist/node_modules/joi/lib/types/alternatives.js +364 -0
- package/dist/node_modules/joi/lib/types/any.js +174 -0
- package/dist/node_modules/joi/lib/types/array.js +809 -0
- package/dist/node_modules/joi/lib/types/binary.js +100 -0
- package/dist/node_modules/joi/lib/types/boolean.js +150 -0
- package/dist/node_modules/joi/lib/types/date.js +233 -0
- package/dist/node_modules/joi/lib/types/function.js +93 -0
- package/dist/node_modules/joi/lib/types/keys.js +1084 -0
- package/dist/node_modules/joi/lib/types/link.js +184 -0
- package/dist/node_modules/joi/lib/types/number.js +363 -0
- package/dist/node_modules/joi/lib/types/object.js +22 -0
- package/dist/node_modules/joi/lib/types/string.js +850 -0
- package/dist/node_modules/joi/lib/types/symbol.js +102 -0
- package/dist/node_modules/joi/lib/validator.js +750 -0
- package/dist/node_modules/joi/lib/values.js +263 -0
- package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.d.ts +60 -0
- package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.js +225 -0
- package/dist/node_modules/joi/node_modules/@hapi/topo/package.json +30 -0
- package/dist/node_modules/joi/package.json +1 -0
- package/dist/server/actions/portainer.js +192 -0
- package/dist/server/collections/portainer-instances.js +54 -0
- package/dist/server/index.js +54 -0
- package/dist/server/instructions/PortainerStackControlInstruction.js +156 -0
- package/dist/server/instructions/PortainerStackRedeployInstruction.js +254 -0
- package/dist/server/instructions/helpers.js +211 -0
- package/dist/server/plugin.js +170 -0
- package/dist/server/services/PortainerClient.js +497 -0
- package/dist/shared/collection.js +57 -0
- package/dist/shared/constants.js +66 -0
- package/dist/shared/env.js +221 -0
- package/dist/shared/types.js +24 -0
- package/package.json +50 -4
- package/server.js +1 -0
- package/src/client/index.tsx +50 -0
- package/src/client/instructions.tsx +76 -0
- package/src/client-v2/__tests__/workflow-registration.test.tsx +132 -0
- package/src/client-v2/components/ControlFieldset.tsx +46 -0
- package/src/client-v2/components/PortainerEnvEditor.tsx +223 -0
- package/src/client-v2/components/PortainerSettingsPage.tsx +671 -0
- package/src/client-v2/components/PortainerTargetFields.tsx +317 -0
- package/src/client-v2/components/RedeployFieldset.tsx +123 -0
- package/src/client-v2/index.tsx +50 -0
- package/src/client-v2/instructions.tsx +162 -0
- package/src/client-v2/locale.ts +24 -0
- package/src/index.ts +11 -0
- package/src/locale/en-US.json +151 -0
- package/src/locale/vi-VN.json +151 -0
- package/src/locale/zh-CN.json +151 -0
- package/src/server/__tests__/portainer-workflow.test.ts +455 -0
- package/src/server/actions/portainer.ts +196 -0
- package/src/server/collections/portainer-instances.ts +34 -0
- package/src/server/index.ts +13 -0
- package/src/server/instructions/PortainerStackControlInstruction.ts +139 -0
- package/src/server/instructions/PortainerStackRedeployInstruction.ts +255 -0
- package/src/server/instructions/helpers.ts +237 -0
- package/src/server/plugin.ts +167 -0
- package/src/server/services/PortainerClient.ts +589 -0
- package/src/shared/collection.ts +32 -0
- package/src/shared/constants.ts +25 -0
- package/src/shared/env.ts +228 -0
- package/src/shared/types.ts +105 -0
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import http from 'node:http';
|
|
11
|
+
import type { AddressInfo } from 'node:net';
|
|
12
|
+
import type Application from '@nocobase/server';
|
|
13
|
+
import { SECRET_MASK } from '../../shared/constants';
|
|
14
|
+
import { buildEffectiveStackEnv, normalizeGitReference, parseDotEnvText } from '../../shared/env';
|
|
15
|
+
import { executePortainerControl } from '../instructions/PortainerStackControlInstruction';
|
|
16
|
+
import { executePortainerRedeploy } from '../instructions/PortainerStackRedeployInstruction';
|
|
17
|
+
import { PluginWorkflowPortainerServer } from '../plugin';
|
|
18
|
+
import { assertValidPortainerUrl, PortainerApiError, PortainerClient } from '../services/PortainerClient';
|
|
19
|
+
|
|
20
|
+
interface RecordedRequest {
|
|
21
|
+
method: string;
|
|
22
|
+
url: string;
|
|
23
|
+
headers: http.IncomingHttpHeaders;
|
|
24
|
+
body: unknown;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function createFakeApp(instanceRow: Record<string, unknown>): Application {
|
|
28
|
+
const model = {
|
|
29
|
+
get: (key: string) => instanceRow[key],
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
aesEncryptor: {
|
|
33
|
+
decrypt: async (v: string) => (v.startsWith('enc:') ? v.slice(4) : v),
|
|
34
|
+
encrypt: async (v: string) => `enc:${v}`,
|
|
35
|
+
},
|
|
36
|
+
db: {
|
|
37
|
+
getRepository: () => ({
|
|
38
|
+
findOne: async () => model,
|
|
39
|
+
}),
|
|
40
|
+
},
|
|
41
|
+
} as unknown as Application;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
describe('plugin-workflow-portainer shared env & server instructions', () => {
|
|
45
|
+
let server: http.Server;
|
|
46
|
+
let baseUrl = '';
|
|
47
|
+
let recorded: RecordedRequest[] = [];
|
|
48
|
+
|
|
49
|
+
beforeAll(async () => {
|
|
50
|
+
server = http.createServer((req, res) => {
|
|
51
|
+
const chunks: Buffer[] = [];
|
|
52
|
+
req.on('data', (c: Buffer) => chunks.push(c));
|
|
53
|
+
req.on('end', () => {
|
|
54
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
55
|
+
let parsedBody: unknown = null;
|
|
56
|
+
if (raw) {
|
|
57
|
+
try {
|
|
58
|
+
parsedBody = JSON.parse(raw);
|
|
59
|
+
} catch {
|
|
60
|
+
parsedBody = raw;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
recorded.push({
|
|
64
|
+
method: req.method || 'GET',
|
|
65
|
+
url: req.url || '/',
|
|
66
|
+
headers: req.headers,
|
|
67
|
+
body: parsedBody,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
71
|
+
|
|
72
|
+
if (req.method === 'GET' && url.pathname === '/api/stacks/10') {
|
|
73
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
74
|
+
res.end(
|
|
75
|
+
JSON.stringify({
|
|
76
|
+
Id: 10,
|
|
77
|
+
Name: 'api-build-stack',
|
|
78
|
+
EndpointId: 2,
|
|
79
|
+
Status: 1,
|
|
80
|
+
Env: [
|
|
81
|
+
{ name: 'EXISTING_FLAG', value: 'keep-me' },
|
|
82
|
+
{ name: 'DB_PASSWORD', value: 'super-secret-db' },
|
|
83
|
+
{ name: 'IMAGE_TAG', value: 'old-tag' },
|
|
84
|
+
],
|
|
85
|
+
GitConfig: {
|
|
86
|
+
URL: 'https://gitlab.example.com/org/service.git',
|
|
87
|
+
ReferenceName: 'refs/heads/develop',
|
|
88
|
+
Authentication: {
|
|
89
|
+
Username: 'gitbot',
|
|
90
|
+
GitCredentialID: 7,
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
}),
|
|
94
|
+
);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (req.method === 'PUT' && url.pathname === '/api/stacks/10/git/redeploy') {
|
|
99
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
100
|
+
res.end(JSON.stringify({ Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 1 }));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (req.method === 'GET' && url.pathname === '/api/stacks/20') {
|
|
105
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
106
|
+
res.end(
|
|
107
|
+
JSON.stringify({
|
|
108
|
+
Id: 20,
|
|
109
|
+
Name: 'api-prod-deploy',
|
|
110
|
+
EndpointId: 3,
|
|
111
|
+
Status: 1,
|
|
112
|
+
Env: [{ name: 'PORT', value: '8080' }],
|
|
113
|
+
GitConfig: null,
|
|
114
|
+
}),
|
|
115
|
+
);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (req.method === 'GET' && url.pathname === '/api/stacks/20/file') {
|
|
120
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
121
|
+
res.end(
|
|
122
|
+
JSON.stringify({
|
|
123
|
+
StackFileContent: 'services:\n app:\n image: registry.local/api:${IMAGE_TAG}\n',
|
|
124
|
+
}),
|
|
125
|
+
);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (req.method === 'PUT' && url.pathname === '/api/stacks/20') {
|
|
130
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
131
|
+
res.end(JSON.stringify({ Id: 20, Name: 'api-prod-deploy', EndpointId: 3, Status: 1 }));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (req.method === 'POST' && url.pathname === '/api/stacks/20/stop') {
|
|
136
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
137
|
+
res.end(JSON.stringify({ Id: 20, Name: 'api-prod-deploy', EndpointId: 3, Status: 2 }));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (req.method === 'POST' && url.pathname.startsWith('/api/stacks/webhooks/')) {
|
|
142
|
+
res.writeHead(204);
|
|
143
|
+
res.end();
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (req.method === 'GET' && url.pathname.endsWith('/docker/containers/json')) {
|
|
148
|
+
const filters = url.searchParams.get('filters') || '';
|
|
149
|
+
if (filters.includes('api-prod-deploy') && recorded.some((r) => r.url.includes('/stop'))) {
|
|
150
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
151
|
+
res.end(JSON.stringify([]));
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
155
|
+
res.end(
|
|
156
|
+
JSON.stringify([
|
|
157
|
+
{
|
|
158
|
+
Id: 'abcdef1234567890',
|
|
159
|
+
Names: ['/api-build-stack-app-1'],
|
|
160
|
+
Image: 'registry.local/api:v1.4.0',
|
|
161
|
+
State: 'running',
|
|
162
|
+
Status: 'Up 12 seconds (healthy)',
|
|
163
|
+
},
|
|
164
|
+
]),
|
|
165
|
+
);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
170
|
+
res.end(JSON.stringify({ message: 'Not found' }));
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
await new Promise<void>((resolve) => {
|
|
175
|
+
server.listen(0, '127.0.0.1', () => resolve());
|
|
176
|
+
});
|
|
177
|
+
const addr = server.address() as AddressInfo;
|
|
178
|
+
baseUrl = `http://127.0.0.1:${addr.port}`;
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
afterAll(async () => {
|
|
182
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
beforeEach(() => {
|
|
186
|
+
recorded = [];
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('merges existing Stack Env, dynamic JSON, .env text, and key-value pairs while masking secrets', () => {
|
|
190
|
+
const parsedDotEnv = parseDotEnvText(
|
|
191
|
+
'# comment\nexport NODE_ENV="production"\nDATABASE_URL="postgres://u:p@db:5432/app?sslmode=disable"\n',
|
|
192
|
+
);
|
|
193
|
+
expect(parsedDotEnv).toEqual([
|
|
194
|
+
{ name: 'NODE_ENV', value: 'production' },
|
|
195
|
+
{ name: 'DATABASE_URL', value: 'postgres://u:p@db:5432/app?sslmode=disable' },
|
|
196
|
+
]);
|
|
197
|
+
|
|
198
|
+
const merged = buildEffectiveStackEnv({
|
|
199
|
+
existingEnv: [
|
|
200
|
+
{ name: 'KEEP_EXISTING', value: '1' },
|
|
201
|
+
{ name: 'IMAGE_TAG', value: 'v0.9.0' },
|
|
202
|
+
{ name: 'JWT_SECRET', value: 'existing-jwt-secret' },
|
|
203
|
+
],
|
|
204
|
+
strategy: 'merge',
|
|
205
|
+
dynamicEnv: '{"IMAGE_TAG":"v1.0.0","EXTRA_JSON":"from-catalog"}',
|
|
206
|
+
envText: 'EXTRA_JSON=from-dotenv\nLOG_LEVEL=info',
|
|
207
|
+
envPairs: [
|
|
208
|
+
{ name: 'IMAGE_TAG', value: 'v1.1.0', secret: false },
|
|
209
|
+
{ name: 'CUSTOM_INTERNAL', value: 'hidden-val', secret: true },
|
|
210
|
+
],
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
expect(merged.env).toEqual([
|
|
214
|
+
{ name: 'KEEP_EXISTING', value: '1' },
|
|
215
|
+
{ name: 'IMAGE_TAG', value: 'v1.1.0' },
|
|
216
|
+
{ name: 'JWT_SECRET', value: 'existing-jwt-secret' },
|
|
217
|
+
{ name: 'EXTRA_JSON', value: 'from-dotenv' },
|
|
218
|
+
{ name: 'LOG_LEVEL', value: 'info' },
|
|
219
|
+
{ name: 'CUSTOM_INTERNAL', value: 'hidden-val' },
|
|
220
|
+
]);
|
|
221
|
+
expect(merged.maskedEnv.JWT_SECRET).toBe(SECRET_MASK);
|
|
222
|
+
expect(merged.maskedEnv.CUSTOM_INTERNAL).toBe(SECRET_MASK);
|
|
223
|
+
expect(merged.maskedEnv.IMAGE_TAG).toBe('v1.1.0');
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('normalizes Git references while preserving existing refs/* values', () => {
|
|
227
|
+
expect(normalizeGitReference('', 'refs/heads/release')).toBe('refs/heads/release');
|
|
228
|
+
expect(normalizeGitReference('feature/ci', 'refs/heads/main')).toBe('refs/heads/feature/ci');
|
|
229
|
+
expect(normalizeGitReference('refs/tags/v2.0.0', 'refs/heads/main')).toBe('refs/tags/v2.0.0');
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
it('redeploys a Git-backed Portainer Stack preserving GitCredentialID and existing Stack Env', async () => {
|
|
233
|
+
const app = createFakeApp({
|
|
234
|
+
id: 1,
|
|
235
|
+
name: 'Portainer Primary',
|
|
236
|
+
baseUrl,
|
|
237
|
+
apiKey: 'enc:ptr_test_key_123',
|
|
238
|
+
enabled: true,
|
|
239
|
+
isDefault: true,
|
|
240
|
+
defaultTimeoutMs: 30_000,
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const result = await executePortainerRedeploy(app, {
|
|
244
|
+
stackId: 10,
|
|
245
|
+
gitReference: 'release/1.4',
|
|
246
|
+
envStrategy: 'merge',
|
|
247
|
+
dynamicEnv: { BUILD_NUMBER: 42 },
|
|
248
|
+
envPairs: [{ name: 'IMAGE_TAG', value: 'v1.4.0', secret: false }],
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
expect(result.ok).toBe(true);
|
|
252
|
+
expect(result.stackType).toBe('git');
|
|
253
|
+
expect(result.endpointId).toBe(2);
|
|
254
|
+
expect(result.gitReference).toBe('refs/heads/release/1.4');
|
|
255
|
+
expect(result.healthy).toBe(true);
|
|
256
|
+
expect(result.runningCount).toBe(1);
|
|
257
|
+
expect(result.appliedEnv.DB_PASSWORD).toBe(SECRET_MASK);
|
|
258
|
+
expect(result.appliedEnv.IMAGE_TAG).toBe('v1.4.0');
|
|
259
|
+
|
|
260
|
+
const redeployCall = recorded.find((r) => r.method === 'PUT' && r.url.startsWith('/api/stacks/10/git/redeploy'));
|
|
261
|
+
expect(redeployCall).toBeDefined();
|
|
262
|
+
expect(redeployCall?.url).toContain('endpointId=2');
|
|
263
|
+
expect(redeployCall?.headers['x-api-key']).toBe('ptr_test_key_123');
|
|
264
|
+
expect(redeployCall?.body).toMatchObject({
|
|
265
|
+
repositoryReferenceName: 'refs/heads/release/1.4',
|
|
266
|
+
repositoryAuthentication: true,
|
|
267
|
+
repositoryGitCredentialID: 7,
|
|
268
|
+
repositoryUsername: 'gitbot',
|
|
269
|
+
env: [
|
|
270
|
+
{ name: 'EXISTING_FLAG', value: 'keep-me' },
|
|
271
|
+
{ name: 'DB_PASSWORD', value: 'super-secret-db' },
|
|
272
|
+
{ name: 'IMAGE_TAG', value: 'v1.4.0' },
|
|
273
|
+
{ name: 'BUILD_NUMBER', value: '42' },
|
|
274
|
+
],
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it('redeploys a separate non-Git Compose Deploy Stack with repullImage and Replace strategy', async () => {
|
|
279
|
+
const app = createFakeApp({
|
|
280
|
+
id: 1,
|
|
281
|
+
name: 'Portainer Primary',
|
|
282
|
+
baseUrl,
|
|
283
|
+
apiKey: 'enc:ptr_test_key_123',
|
|
284
|
+
enabled: true,
|
|
285
|
+
isDefault: true,
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
const result = await executePortainerRedeploy(app, {
|
|
289
|
+
endpointId: 3,
|
|
290
|
+
stackId: 20,
|
|
291
|
+
repullImage: true,
|
|
292
|
+
prune: true,
|
|
293
|
+
envStrategy: 'replace',
|
|
294
|
+
envText: 'IMAGE_TAG=v1.4.0\nPORT=9090',
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
expect(result.ok).toBe(true);
|
|
298
|
+
expect(result.stackType).toBe('compose');
|
|
299
|
+
expect(result.appliedEnv).toEqual({ IMAGE_TAG: 'v1.4.0', PORT: '9090' });
|
|
300
|
+
|
|
301
|
+
const composePut = recorded.find((r) => r.method === 'PUT' && r.url.startsWith('/api/stacks/20?'));
|
|
302
|
+
expect(composePut).toBeDefined();
|
|
303
|
+
expect(composePut?.body).toMatchObject({
|
|
304
|
+
pullImage: true,
|
|
305
|
+
prune: true,
|
|
306
|
+
env: [
|
|
307
|
+
{ name: 'IMAGE_TAG', value: 'v1.4.0' },
|
|
308
|
+
{ name: 'PORT', value: '9090' },
|
|
309
|
+
],
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
it('triggers Stack Webhook without leaking X-API-Key header and supports Control inspect/stop', async () => {
|
|
314
|
+
const app = createFakeApp({
|
|
315
|
+
id: 1,
|
|
316
|
+
name: 'Portainer Primary',
|
|
317
|
+
baseUrl,
|
|
318
|
+
apiKey: 'enc:ptr_test_key_123',
|
|
319
|
+
enabled: true,
|
|
320
|
+
isDefault: true,
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
const webhookRes = await executePortainerRedeploy(app, {
|
|
324
|
+
mode: 'webhook',
|
|
325
|
+
webhookId: '638e6967-ef77-4906-8af8-236800621360',
|
|
326
|
+
webhookTag: 'v1.4.0',
|
|
327
|
+
});
|
|
328
|
+
expect(webhookRes.stackType).toBe('webhook');
|
|
329
|
+
|
|
330
|
+
const hookCall = recorded.find((r) => r.url.startsWith('/api/stacks/webhooks/'));
|
|
331
|
+
expect(hookCall?.url).toBe('/api/stacks/webhooks/638e6967-ef77-4906-8af8-236800621360?tag=v1.4.0');
|
|
332
|
+
expect(hookCall?.headers['x-api-key']).toBeUndefined();
|
|
333
|
+
|
|
334
|
+
const inspectRes = await executePortainerControl(app, {
|
|
335
|
+
stackId: 10,
|
|
336
|
+
action: 'inspect',
|
|
337
|
+
});
|
|
338
|
+
expect(inspectRes.healthy).toBe(true);
|
|
339
|
+
expect(inspectRes.currentEnv.DB_PASSWORD).toBe(SECRET_MASK);
|
|
340
|
+
|
|
341
|
+
const stopRes = await executePortainerControl(app, {
|
|
342
|
+
stackId: 20,
|
|
343
|
+
action: 'stop',
|
|
344
|
+
});
|
|
345
|
+
expect(stopRes.action).toBe('stop');
|
|
346
|
+
expect(stopRes.stackStatus).toBe(2);
|
|
347
|
+
expect(stopRes.healthy).toBe(true);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
it('rejects unsafe URLs with non-HTTP schemes or embedded credentials', () => {
|
|
351
|
+
expect(() => assertValidPortainerUrl('ftp://portainer.local')).toThrow(PortainerApiError);
|
|
352
|
+
expect(() => assertValidPortainerUrl('https://admin:secret@portainer.local:9443')).toThrow(PortainerApiError);
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
it('polls asynchronous Portainer Status=3 (Deploying) until Active or throws on Status=4 (Error)', async () => {
|
|
356
|
+
const client = new PortainerClient({ baseUrl, apiKey: 'ptr_test_key_123', timeoutMs: 5_000 });
|
|
357
|
+
let pollCalls = 0;
|
|
358
|
+
vi.spyOn(client, 'getRawStack').mockImplementation(async () => {
|
|
359
|
+
pollCalls += 1;
|
|
360
|
+
if (pollCalls < 2) {
|
|
361
|
+
return { Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 3 };
|
|
362
|
+
}
|
|
363
|
+
return { Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 1 };
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
const settled = await client.waitForStackSettlement(
|
|
367
|
+
10,
|
|
368
|
+
{ Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 3 },
|
|
369
|
+
{ pollIntervalMs: 50, timeoutMs: 2_000 },
|
|
370
|
+
);
|
|
371
|
+
expect(settled.Status).toBe(1);
|
|
372
|
+
expect(pollCalls).toBe(2);
|
|
373
|
+
|
|
374
|
+
vi.spyOn(client, 'getRawStack').mockResolvedValueOnce({
|
|
375
|
+
Id: 10,
|
|
376
|
+
Name: 'api-build-stack',
|
|
377
|
+
EndpointId: 2,
|
|
378
|
+
Status: 4,
|
|
379
|
+
DeploymentStatus: [{ Status: 4, Time: 123, Message: 'Dockerfile syntax error on line 4' }],
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
await expect(
|
|
383
|
+
client.waitForStackSettlement(
|
|
384
|
+
10,
|
|
385
|
+
{ Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 3 },
|
|
386
|
+
{ pollIntervalMs: 50, timeoutMs: 2_000 },
|
|
387
|
+
),
|
|
388
|
+
).rejects.toThrow('Dockerfile syntax error on line 4');
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
it('enforces ACL on metadata actions and masks stored secrets in API responses', async () => {
|
|
392
|
+
const allowRules = new Map<string, (ctx: Record<string, unknown>) => boolean>();
|
|
393
|
+
let responseMiddleware: ((ctx: Record<string, unknown>, next: () => Promise<void>) => Promise<void>) | null = null;
|
|
394
|
+
const registeredInstructions = new Map<string, unknown>();
|
|
395
|
+
|
|
396
|
+
const fakePlugin = Object.create(PluginWorkflowPortainerServer.prototype) as PluginWorkflowPortainerServer & {
|
|
397
|
+
app: Record<string, unknown>;
|
|
398
|
+
};
|
|
399
|
+
fakePlugin.app = {
|
|
400
|
+
pm: {
|
|
401
|
+
get: () => ({
|
|
402
|
+
registerInstruction: (name: string, inst: unknown) => registeredInstructions.set(name, inst),
|
|
403
|
+
}),
|
|
404
|
+
},
|
|
405
|
+
resourceManager: {
|
|
406
|
+
define: vi.fn(),
|
|
407
|
+
use: (mw: (ctx: Record<string, unknown>, next: () => Promise<void>) => Promise<void>) => {
|
|
408
|
+
responseMiddleware = mw;
|
|
409
|
+
},
|
|
410
|
+
},
|
|
411
|
+
acl: {
|
|
412
|
+
registerSnippet: vi.fn(),
|
|
413
|
+
allow: (_res: string, action: string, fn: (ctx: Record<string, unknown>) => boolean) => {
|
|
414
|
+
allowRules.set(action, fn);
|
|
415
|
+
},
|
|
416
|
+
can: ({ role, resource, action }: { role: string; resource: string; action: string }) => {
|
|
417
|
+
if (role === 'workflow_editor' && resource === 'workflows' && action === 'update') {
|
|
418
|
+
return true;
|
|
419
|
+
}
|
|
420
|
+
return false;
|
|
421
|
+
},
|
|
422
|
+
},
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
await PluginWorkflowPortainerServer.prototype.load.call(fakePlugin);
|
|
426
|
+
|
|
427
|
+
expect(registeredInstructions.has('portainer-stack-redeploy')).toBe(true);
|
|
428
|
+
expect(registeredInstructions.has('portainer-stack-control')).toBe(true);
|
|
429
|
+
|
|
430
|
+
const checkListStacks = allowRules.get('listStacks');
|
|
431
|
+
expect(checkListStacks).toBeDefined();
|
|
432
|
+
expect(checkListStacks?.({ state: {} })).toBe(false);
|
|
433
|
+
expect(checkListStacks?.({ state: { currentUser: { id: 2 }, currentRoles: ['member'] } })).toBe(false);
|
|
434
|
+
expect(checkListStacks?.({ state: { currentUser: { id: 3 }, currentRoles: ['workflow_editor'] } })).toBe(true);
|
|
435
|
+
expect(checkListStacks?.({ state: { currentUser: { id: 1 }, currentRoles: ['root'] } })).toBe(true);
|
|
436
|
+
|
|
437
|
+
const ctx: Record<string, unknown> = {
|
|
438
|
+
action: { resourceName: 'portainerInstances' },
|
|
439
|
+
body: {
|
|
440
|
+
data: [
|
|
441
|
+
{
|
|
442
|
+
id: 1,
|
|
443
|
+
name: 'Prod',
|
|
444
|
+
apiKey: 'enc:secret-key',
|
|
445
|
+
gitAccessToken: 'enc:git-pat',
|
|
446
|
+
},
|
|
447
|
+
],
|
|
448
|
+
},
|
|
449
|
+
};
|
|
450
|
+
await responseMiddleware?.(ctx, async () => {});
|
|
451
|
+
const maskedRow = (ctx.body as { data: Array<Record<string, string>> }).data[0];
|
|
452
|
+
expect(maskedRow.apiKey).toBe(SECRET_MASK);
|
|
453
|
+
expect(maskedRow.gitAccessToken).toBe(SECRET_MASK);
|
|
454
|
+
});
|
|
455
|
+
});
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Context, Next } from '@nocobase/actions';
|
|
11
|
+
import type Application from '@nocobase/server';
|
|
12
|
+
import { PLUGIN_NAMESPACE, PORTAINER_INSTANCES_COLLECTION, SECRET_MASK } from '../../shared/constants';
|
|
13
|
+
import { isLikelySensitiveKey } from '../../shared/env';
|
|
14
|
+
import type { ID, PortainerInstanceSummary } from '../../shared/types';
|
|
15
|
+
import { decryptIfNeeded, resolvePortainerInstance } from '../instructions/helpers';
|
|
16
|
+
import { assertPositiveInt, clampTimeoutMs, PortainerApiError, PortainerClient } from '../services/PortainerClient';
|
|
17
|
+
|
|
18
|
+
function getRequestParam(ctx: Context, key: string): unknown {
|
|
19
|
+
const params = (ctx.action?.params ?? {}) as Record<string, unknown>;
|
|
20
|
+
const values =
|
|
21
|
+
typeof params.values === 'object' && params.values !== null ? (params.values as Record<string, unknown>) : {};
|
|
22
|
+
if (typeof values[key] !== 'undefined') {
|
|
23
|
+
return values[key];
|
|
24
|
+
}
|
|
25
|
+
return params[key];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function sendPortainerError(ctx: Context, error: unknown): never {
|
|
29
|
+
if (error instanceof PortainerApiError) {
|
|
30
|
+
const status =
|
|
31
|
+
error.code === 'INVALID_URL' || error.code === 'INVALID_PARAM' || error.code === 'MISSING_API_KEY'
|
|
32
|
+
? 400
|
|
33
|
+
: error.code === 'INSTANCE_NOT_FOUND'
|
|
34
|
+
? 404
|
|
35
|
+
: error.status && error.status >= 400 && error.status < 500
|
|
36
|
+
? error.status
|
|
37
|
+
: 502;
|
|
38
|
+
ctx.throw(status, error.message);
|
|
39
|
+
}
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createPortainerResourceActions(app: Application) {
|
|
44
|
+
return {
|
|
45
|
+
async listInstances(ctx: Context, next: Next) {
|
|
46
|
+
const repo = app.db.getRepository(PORTAINER_INSTANCES_COLLECTION);
|
|
47
|
+
const rows = await repo.find({
|
|
48
|
+
filter: { enabled: true },
|
|
49
|
+
sort: ['-isDefault', 'id'],
|
|
50
|
+
});
|
|
51
|
+
const items: PortainerInstanceSummary[] = rows.map((row) => ({
|
|
52
|
+
id: Number(row.get('id')),
|
|
53
|
+
name: String(row.get('name') ?? ''),
|
|
54
|
+
baseUrl: String(row.get('baseUrl') ?? ''),
|
|
55
|
+
isDefault: Boolean(row.get('isDefault')),
|
|
56
|
+
enabled: Boolean(row.get('enabled')),
|
|
57
|
+
defaultTimeoutMs: Number(row.get('defaultTimeoutMs') ?? 600_000),
|
|
58
|
+
lastHealthStatus: (row.get('lastHealthStatus') as string | null) ?? null,
|
|
59
|
+
lastVersion: (row.get('lastVersion') as string | null) ?? null,
|
|
60
|
+
}));
|
|
61
|
+
ctx.body = items;
|
|
62
|
+
await next();
|
|
63
|
+
},
|
|
64
|
+
|
|
65
|
+
async testConnection(ctx: Context, next: Next) {
|
|
66
|
+
const filterByTk = (getRequestParam(ctx, 'filterByTk') ?? getRequestParam(ctx, 'instanceId')) as ID | undefined;
|
|
67
|
+
try {
|
|
68
|
+
const instance = await resolvePortainerInstance(app, filterByTk ?? null);
|
|
69
|
+
const status = await instance.client.getStatus();
|
|
70
|
+
const endpoints = await instance.client.listEndpoints();
|
|
71
|
+
const version = String(status?.Version ?? 'unknown');
|
|
72
|
+
|
|
73
|
+
await app.db.getRepository(PORTAINER_INSTANCES_COLLECTION).update({
|
|
74
|
+
filterByTk: instance.id,
|
|
75
|
+
values: {
|
|
76
|
+
lastHealthStatus: 'ok',
|
|
77
|
+
lastVersion: version,
|
|
78
|
+
lastCheckedAt: new Date(),
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
ctx.body = {
|
|
83
|
+
ok: true,
|
|
84
|
+
instanceId: instance.id,
|
|
85
|
+
version,
|
|
86
|
+
endpointCount: endpoints.length,
|
|
87
|
+
endpoints,
|
|
88
|
+
};
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (filterByTk) {
|
|
91
|
+
const numId = Number(filterByTk);
|
|
92
|
+
if (Number.isSafeInteger(numId) && numId > 0) {
|
|
93
|
+
await app.db
|
|
94
|
+
.getRepository(PORTAINER_INSTANCES_COLLECTION)
|
|
95
|
+
.update({
|
|
96
|
+
filterByTk: numId,
|
|
97
|
+
values: {
|
|
98
|
+
lastHealthStatus: 'error',
|
|
99
|
+
lastCheckedAt: new Date(),
|
|
100
|
+
},
|
|
101
|
+
})
|
|
102
|
+
.catch(() => {});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
sendPortainerError(ctx, error);
|
|
106
|
+
}
|
|
107
|
+
await next();
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
async testConnectionDraft(ctx: Context, next: Next) {
|
|
111
|
+
try {
|
|
112
|
+
const baseUrl = String(getRequestParam(ctx, 'baseUrl') ?? '').trim();
|
|
113
|
+
let apiKey = String(getRequestParam(ctx, 'apiKey') ?? '').trim();
|
|
114
|
+
const instanceId = getRequestParam(ctx, 'id') ?? getRequestParam(ctx, 'instanceId');
|
|
115
|
+
const allowInsecureTls = Boolean(getRequestParam(ctx, 'allowInsecureTls'));
|
|
116
|
+
const timeoutMs = clampTimeoutMs(Number(getRequestParam(ctx, 'defaultTimeoutMs') ?? 15_000), 15_000);
|
|
117
|
+
|
|
118
|
+
if ((!apiKey || apiKey === SECRET_MASK) && instanceId) {
|
|
119
|
+
const existing = await app.db
|
|
120
|
+
.getRepository(PORTAINER_INSTANCES_COLLECTION)
|
|
121
|
+
.findOne({ filterByTk: Number(instanceId) });
|
|
122
|
+
if (existing) {
|
|
123
|
+
apiKey = await decryptIfNeeded(app, existing.get('apiKey'));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const client = new PortainerClient({ baseUrl, apiKey, allowInsecureTls, timeoutMs });
|
|
128
|
+
const status = await client.getStatus();
|
|
129
|
+
const endpoints = await client.listEndpoints();
|
|
130
|
+
ctx.body = {
|
|
131
|
+
ok: true,
|
|
132
|
+
version: String(status?.Version ?? 'unknown'),
|
|
133
|
+
endpointCount: endpoints.length,
|
|
134
|
+
endpoints,
|
|
135
|
+
};
|
|
136
|
+
} catch (error) {
|
|
137
|
+
sendPortainerError(ctx, error);
|
|
138
|
+
}
|
|
139
|
+
await next();
|
|
140
|
+
},
|
|
141
|
+
|
|
142
|
+
async listEndpoints(ctx: Context, next: Next) {
|
|
143
|
+
const instanceId = getRequestParam(ctx, 'instanceId') as ID | undefined;
|
|
144
|
+
try {
|
|
145
|
+
const instance = await resolvePortainerInstance(app, instanceId ?? null);
|
|
146
|
+
ctx.body = await instance.client.listEndpoints();
|
|
147
|
+
} catch (error) {
|
|
148
|
+
sendPortainerError(ctx, error);
|
|
149
|
+
}
|
|
150
|
+
await next();
|
|
151
|
+
},
|
|
152
|
+
|
|
153
|
+
async listStacks(ctx: Context, next: Next) {
|
|
154
|
+
const instanceId = getRequestParam(ctx, 'instanceId') as ID | undefined;
|
|
155
|
+
const rawEndpointId = getRequestParam(ctx, 'endpointId');
|
|
156
|
+
try {
|
|
157
|
+
const instance = await resolvePortainerInstance(app, instanceId ?? null);
|
|
158
|
+
const endpointId =
|
|
159
|
+
rawEndpointId !== null && typeof rawEndpointId !== 'undefined' && String(rawEndpointId).trim() !== ''
|
|
160
|
+
? assertPositiveInt(rawEndpointId as ID, 'Environment (Endpoint) ID')
|
|
161
|
+
: null;
|
|
162
|
+
ctx.body = await instance.client.listStacks(endpointId);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
sendPortainerError(ctx, error);
|
|
165
|
+
}
|
|
166
|
+
await next();
|
|
167
|
+
},
|
|
168
|
+
|
|
169
|
+
async getStackDetail(ctx: Context, next: Next) {
|
|
170
|
+
const instanceId = getRequestParam(ctx, 'instanceId') as ID | undefined;
|
|
171
|
+
const rawStackId = getRequestParam(ctx, 'stackId');
|
|
172
|
+
const maskValues =
|
|
173
|
+
getRequestParam(ctx, 'includeValues') !== true && getRequestParam(ctx, 'includeValues') !== 'true';
|
|
174
|
+
try {
|
|
175
|
+
if (rawStackId === null || typeof rawStackId === 'undefined' || String(rawStackId).trim() === '') {
|
|
176
|
+
ctx.throw(400, ctx.t('Stack ID is required', { ns: PLUGIN_NAMESPACE }));
|
|
177
|
+
}
|
|
178
|
+
const instance = await resolvePortainerInstance(app, instanceId ?? null);
|
|
179
|
+
const stackId = assertPositiveInt(rawStackId as ID, 'Stack ID');
|
|
180
|
+
const detail = await instance.client.getStackDetail(stackId);
|
|
181
|
+
ctx.body = {
|
|
182
|
+
...detail,
|
|
183
|
+
env: detail.env.map((pair) => ({
|
|
184
|
+
name: pair.name,
|
|
185
|
+
value: maskValues || isLikelySensitiveKey(pair.name) ? '' : pair.value,
|
|
186
|
+
hasExistingValue: pair.value.length > 0,
|
|
187
|
+
sensitive: isLikelySensitiveKey(pair.name),
|
|
188
|
+
})),
|
|
189
|
+
};
|
|
190
|
+
} catch (error) {
|
|
191
|
+
sendPortainerError(ctx, error);
|
|
192
|
+
}
|
|
193
|
+
await next();
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { CollectionOptions } from '@nocobase/database';
|
|
11
|
+
import { DEFAULT_TIMEOUT_MS, PORTAINER_INSTANCES_COLLECTION } from '../../shared/constants';
|
|
12
|
+
|
|
13
|
+
export default {
|
|
14
|
+
name: PORTAINER_INSTANCES_COLLECTION,
|
|
15
|
+
title: 'Portainer Instances',
|
|
16
|
+
fields: [
|
|
17
|
+
{ name: 'id', type: 'bigInt', autoIncrement: true, primaryKey: true },
|
|
18
|
+
{ name: 'name', type: 'string', length: 200 },
|
|
19
|
+
{ name: 'baseUrl', type: 'string', length: 500 },
|
|
20
|
+
{ name: 'apiKey', type: 'text' },
|
|
21
|
+
{ name: 'gitUsername', type: 'string', length: 200 },
|
|
22
|
+
{ name: 'gitAccessToken', type: 'text' },
|
|
23
|
+
{ name: 'gitCredentialId', type: 'integer' },
|
|
24
|
+
{ name: 'allowInsecureTls', type: 'boolean', defaultValue: false },
|
|
25
|
+
{ name: 'defaultTimeoutMs', type: 'integer', defaultValue: DEFAULT_TIMEOUT_MS },
|
|
26
|
+
{ name: 'isDefault', type: 'boolean', defaultValue: false },
|
|
27
|
+
{ name: 'enabled', type: 'boolean', defaultValue: true },
|
|
28
|
+
{ name: 'lastHealthStatus', type: 'string', length: 32 },
|
|
29
|
+
{ name: 'lastVersion', type: 'string', length: 64 },
|
|
30
|
+
{ name: 'lastCheckedAt', type: 'date' },
|
|
31
|
+
{ name: 'createdAt', type: 'date' },
|
|
32
|
+
{ name: 'updatedAt', type: 'date' },
|
|
33
|
+
],
|
|
34
|
+
} as CollectionOptions;
|