plugin-workflow-portainer 0.0.0-stage → 0.2.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.
- package/LICENSE +176 -0
- package/README.md +31 -3
- package/client-v2.js +1 -0
- package/client.js +1 -0
- package/dist/client/127.09e6675863ac8138.js +10 -0
- package/dist/client/57.67f04a547ead06b8.js +10 -0
- package/dist/client/660.546c702d1ddf7eff.js +10 -0
- package/dist/client/981.e38099c59bf992f0.js +10 -0
- package/dist/client/index.js +10 -0
- package/dist/client-v2/127.9f65dc2e3d0df10a.js +10 -0
- package/dist/client-v2/57.a60e16e4b4e4fa28.js +10 -0
- package/dist/client-v2/660.29ae3c3b4040039d.js +10 -0
- package/dist/client-v2/981.8627062881ad83d1.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 +193 -0
- package/dist/locale/vi-VN.json +193 -0
- package/dist/locale/zh-CN.json +193 -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 +317 -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 +177 -0
- package/dist/server/services/PortainerClient.js +669 -0
- package/dist/shared/collection.js +57 -0
- package/dist/shared/constants.js +66 -0
- package/dist/shared/env.js +238 -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 +242 -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 +707 -0
- package/src/client-v2/components/PortainerTargetFields.tsx +309 -0
- package/src/client-v2/components/RedeployFieldset.tsx +124 -0
- package/src/client-v2/components/StackDetailDrawer.tsx +790 -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 +193 -0
- package/src/locale/vi-VN.json +193 -0
- package/src/locale/zh-CN.json +193 -0
- package/src/server/__tests__/portainer-workflow.test.ts +559 -0
- package/src/server/actions/portainer.ts +361 -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 +174 -0
- package/src/server/services/PortainerClient.ts +846 -0
- package/src/shared/collection.ts +32 -0
- package/src/shared/constants.ts +25 -0
- package/src/shared/env.ts +243 -0
- package/src/shared/types.ts +164 -0
|
@@ -0,0 +1,559 @@
|
|
|
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 { Context } from '@nocobase/actions';
|
|
13
|
+
import type Application from '@nocobase/server';
|
|
14
|
+
import { SECRET_MASK } from '../../shared/constants';
|
|
15
|
+
import { buildEffectiveStackEnv, normalizeGitReference, parseDotEnvText } from '../../shared/env';
|
|
16
|
+
import { createPortainerResourceActions } from '../actions/portainer';
|
|
17
|
+
import { executePortainerControl } from '../instructions/PortainerStackControlInstruction';
|
|
18
|
+
import { executePortainerRedeploy } from '../instructions/PortainerStackRedeployInstruction';
|
|
19
|
+
import { PluginWorkflowPortainerServer } from '../plugin';
|
|
20
|
+
import {
|
|
21
|
+
assertValidContainerId,
|
|
22
|
+
assertValidPortainerUrl,
|
|
23
|
+
computeDockerContainerStats,
|
|
24
|
+
demuxDockerLogBuffer,
|
|
25
|
+
PortainerApiError,
|
|
26
|
+
PortainerClient,
|
|
27
|
+
} from '../services/PortainerClient';
|
|
28
|
+
|
|
29
|
+
interface RecordedRequest {
|
|
30
|
+
method: string;
|
|
31
|
+
url: string;
|
|
32
|
+
headers: http.IncomingHttpHeaders;
|
|
33
|
+
body: unknown;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function createFakeApp(instanceRow: Record<string, unknown>): Application {
|
|
37
|
+
const model = {
|
|
38
|
+
get: (key: string) => instanceRow[key],
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
aesEncryptor: {
|
|
42
|
+
decrypt: async (v: string) => (v.startsWith('enc:') ? v.slice(4) : v),
|
|
43
|
+
encrypt: async (v: string) => `enc:${v}`,
|
|
44
|
+
},
|
|
45
|
+
db: {
|
|
46
|
+
getRepository: () => ({
|
|
47
|
+
findOne: async () => model,
|
|
48
|
+
}),
|
|
49
|
+
},
|
|
50
|
+
} as unknown as Application;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
describe('plugin-workflow-portainer shared env & server instructions', () => {
|
|
54
|
+
let server: http.Server;
|
|
55
|
+
let baseUrl = '';
|
|
56
|
+
let recorded: RecordedRequest[] = [];
|
|
57
|
+
|
|
58
|
+
beforeAll(async () => {
|
|
59
|
+
server = http.createServer((req, res) => {
|
|
60
|
+
const chunks: Buffer[] = [];
|
|
61
|
+
req.on('data', (c: Buffer) => chunks.push(c));
|
|
62
|
+
req.on('end', () => {
|
|
63
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
64
|
+
let parsedBody: unknown = null;
|
|
65
|
+
if (raw) {
|
|
66
|
+
try {
|
|
67
|
+
parsedBody = JSON.parse(raw);
|
|
68
|
+
} catch {
|
|
69
|
+
parsedBody = raw;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
recorded.push({
|
|
73
|
+
method: req.method || 'GET',
|
|
74
|
+
url: req.url || '/',
|
|
75
|
+
headers: req.headers,
|
|
76
|
+
body: parsedBody,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
80
|
+
|
|
81
|
+
if (req.method === 'GET' && url.pathname === '/api/stacks/10') {
|
|
82
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
83
|
+
res.end(
|
|
84
|
+
JSON.stringify({
|
|
85
|
+
Id: 10,
|
|
86
|
+
Name: 'api-build-stack',
|
|
87
|
+
EndpointId: 2,
|
|
88
|
+
Status: 1,
|
|
89
|
+
Env: [
|
|
90
|
+
{ name: 'EXISTING_FLAG', value: 'keep-me' },
|
|
91
|
+
{ name: 'DB_PASSWORD', value: 'super-secret-db' },
|
|
92
|
+
{ name: 'IMAGE_TAG', value: 'old-tag' },
|
|
93
|
+
],
|
|
94
|
+
GitConfig: {
|
|
95
|
+
URL: 'https://gitlab.example.com/org/service.git',
|
|
96
|
+
ReferenceName: 'refs/heads/develop',
|
|
97
|
+
Authentication: {
|
|
98
|
+
Username: 'gitbot',
|
|
99
|
+
GitCredentialID: 7,
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
}),
|
|
103
|
+
);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (req.method === 'PUT' && url.pathname === '/api/stacks/10/git/redeploy') {
|
|
108
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
109
|
+
res.end(JSON.stringify({ Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 1 }));
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (req.method === 'GET' && url.pathname === '/api/stacks/20') {
|
|
114
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
115
|
+
res.end(
|
|
116
|
+
JSON.stringify({
|
|
117
|
+
Id: 20,
|
|
118
|
+
Name: 'api-prod-deploy',
|
|
119
|
+
EndpointId: 3,
|
|
120
|
+
Status: 1,
|
|
121
|
+
Env: [{ name: 'PORT', value: '8080' }],
|
|
122
|
+
GitConfig: null,
|
|
123
|
+
}),
|
|
124
|
+
);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (req.method === 'GET' && url.pathname === '/api/stacks/20/file') {
|
|
129
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
130
|
+
res.end(
|
|
131
|
+
JSON.stringify({
|
|
132
|
+
StackFileContent: 'services:\n app:\n image: registry.local/api:${IMAGE_TAG}\n',
|
|
133
|
+
}),
|
|
134
|
+
);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (req.method === 'PUT' && url.pathname === '/api/stacks/20') {
|
|
139
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
140
|
+
res.end(JSON.stringify({ Id: 20, Name: 'api-prod-deploy', EndpointId: 3, Status: 1 }));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (req.method === 'POST' && url.pathname === '/api/stacks/20/stop') {
|
|
145
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
146
|
+
res.end(JSON.stringify({ Id: 20, Name: 'api-prod-deploy', EndpointId: 3, Status: 2 }));
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (req.method === 'POST' && url.pathname.startsWith('/api/stacks/webhooks/')) {
|
|
151
|
+
res.writeHead(204);
|
|
152
|
+
res.end();
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (req.method === 'GET' && url.pathname.endsWith('/docker/containers/json')) {
|
|
157
|
+
const filters = url.searchParams.get('filters') || '';
|
|
158
|
+
if (filters.includes('api-prod-deploy') && recorded.some((r) => r.url.includes('/stop'))) {
|
|
159
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
160
|
+
res.end(JSON.stringify([]));
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
164
|
+
res.end(
|
|
165
|
+
JSON.stringify([
|
|
166
|
+
{
|
|
167
|
+
Id: 'abcdef1234567890',
|
|
168
|
+
Names: ['/api-build-stack-app-1'],
|
|
169
|
+
Image: 'registry.local/api:v1.4.0',
|
|
170
|
+
State: 'running',
|
|
171
|
+
Status: 'Up 12 seconds (healthy)',
|
|
172
|
+
},
|
|
173
|
+
]),
|
|
174
|
+
);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
179
|
+
res.end(JSON.stringify({ message: 'Not found' }));
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
await new Promise<void>((resolve) => {
|
|
184
|
+
server.listen(0, '127.0.0.1', () => resolve());
|
|
185
|
+
});
|
|
186
|
+
const addr = server.address() as AddressInfo;
|
|
187
|
+
baseUrl = `http://127.0.0.1:${addr.port}`;
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
afterAll(async () => {
|
|
191
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
beforeEach(() => {
|
|
195
|
+
recorded = [];
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it('merges existing Stack Env, dynamic JSON, .env text, and key-value pairs while masking secrets', () => {
|
|
199
|
+
const parsedDotEnv = parseDotEnvText(
|
|
200
|
+
'# comment\nexport NODE_ENV="production"\nDATABASE_URL="postgres://u:p@db:5432/app?sslmode=disable"\n',
|
|
201
|
+
);
|
|
202
|
+
expect(parsedDotEnv).toEqual([
|
|
203
|
+
{ name: 'NODE_ENV', value: 'production' },
|
|
204
|
+
{ name: 'DATABASE_URL', value: 'postgres://u:p@db:5432/app?sslmode=disable' },
|
|
205
|
+
]);
|
|
206
|
+
|
|
207
|
+
const merged = buildEffectiveStackEnv({
|
|
208
|
+
existingEnv: [
|
|
209
|
+
{ name: 'KEEP_EXISTING', value: '1' },
|
|
210
|
+
{ name: 'IMAGE_TAG', value: 'v0.9.0' },
|
|
211
|
+
{ name: 'JWT_SECRET', value: 'existing-jwt-secret' },
|
|
212
|
+
],
|
|
213
|
+
strategy: 'merge',
|
|
214
|
+
dynamicEnv: '{"IMAGE_TAG":"v1.0.0","EXTRA_JSON":"from-catalog"}',
|
|
215
|
+
envText: 'EXTRA_JSON=from-dotenv\nLOG_LEVEL=info',
|
|
216
|
+
envPairs: [
|
|
217
|
+
{ name: 'IMAGE_TAG', value: 'v1.1.0', secret: false },
|
|
218
|
+
{ name: 'CUSTOM_INTERNAL', value: 'hidden-val', secret: true },
|
|
219
|
+
],
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
expect(merged.env).toEqual([
|
|
223
|
+
{ name: 'KEEP_EXISTING', value: '1' },
|
|
224
|
+
{ name: 'IMAGE_TAG', value: 'v1.1.0' },
|
|
225
|
+
{ name: 'JWT_SECRET', value: 'existing-jwt-secret' },
|
|
226
|
+
{ name: 'EXTRA_JSON', value: 'from-dotenv' },
|
|
227
|
+
{ name: 'LOG_LEVEL', value: 'info' },
|
|
228
|
+
{ name: 'CUSTOM_INTERNAL', value: 'hidden-val' },
|
|
229
|
+
]);
|
|
230
|
+
expect(merged.maskedEnv.JWT_SECRET).toBe(SECRET_MASK);
|
|
231
|
+
expect(merged.maskedEnv.CUSTOM_INTERNAL).toBe(SECRET_MASK);
|
|
232
|
+
expect(merged.maskedEnv.IMAGE_TAG).toBe('v1.1.0');
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it('normalizes Git references while preserving existing refs/* values', () => {
|
|
236
|
+
expect(normalizeGitReference('', 'refs/heads/release')).toBe('refs/heads/release');
|
|
237
|
+
expect(normalizeGitReference('feature/ci', 'refs/heads/main')).toBe('refs/heads/feature/ci');
|
|
238
|
+
expect(normalizeGitReference('refs/tags/v2.0.0', 'refs/heads/main')).toBe('refs/tags/v2.0.0');
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it('redeploys a Git-backed Portainer Stack preserving GitCredentialID and existing Stack Env', async () => {
|
|
242
|
+
const app = createFakeApp({
|
|
243
|
+
id: 1,
|
|
244
|
+
name: 'Portainer Primary',
|
|
245
|
+
baseUrl,
|
|
246
|
+
apiKey: 'enc:ptr_test_key_123',
|
|
247
|
+
enabled: true,
|
|
248
|
+
isDefault: true,
|
|
249
|
+
defaultTimeoutMs: 30_000,
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
const result = await executePortainerRedeploy(app, {
|
|
253
|
+
stackId: 10,
|
|
254
|
+
gitReference: 'release/1.4',
|
|
255
|
+
envStrategy: 'merge',
|
|
256
|
+
dynamicEnv: { BUILD_NUMBER: 42 },
|
|
257
|
+
envPairs: [{ name: 'IMAGE_TAG', value: 'v1.4.0', secret: false }],
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
expect(result.ok).toBe(true);
|
|
261
|
+
expect(result.stackType).toBe('git');
|
|
262
|
+
expect(result.endpointId).toBe(2);
|
|
263
|
+
expect(result.gitReference).toBe('refs/heads/release/1.4');
|
|
264
|
+
expect(result.healthy).toBe(true);
|
|
265
|
+
expect(result.runningCount).toBe(1);
|
|
266
|
+
expect(result.appliedEnv.DB_PASSWORD).toBe(SECRET_MASK);
|
|
267
|
+
expect(result.appliedEnv.IMAGE_TAG).toBe('v1.4.0');
|
|
268
|
+
|
|
269
|
+
const redeployCall = recorded.find((r) => r.method === 'PUT' && r.url.startsWith('/api/stacks/10/git/redeploy'));
|
|
270
|
+
expect(redeployCall).toBeDefined();
|
|
271
|
+
expect(redeployCall?.url).toContain('endpointId=2');
|
|
272
|
+
expect(redeployCall?.headers['x-api-key']).toBe('ptr_test_key_123');
|
|
273
|
+
expect(redeployCall?.body).toMatchObject({
|
|
274
|
+
repositoryReferenceName: 'refs/heads/release/1.4',
|
|
275
|
+
repositoryAuthentication: true,
|
|
276
|
+
repositoryGitCredentialID: 7,
|
|
277
|
+
repositoryUsername: 'gitbot',
|
|
278
|
+
env: [
|
|
279
|
+
{ name: 'EXISTING_FLAG', value: 'keep-me' },
|
|
280
|
+
{ name: 'DB_PASSWORD', value: 'super-secret-db' },
|
|
281
|
+
{ name: 'IMAGE_TAG', value: 'v1.4.0' },
|
|
282
|
+
{ name: 'BUILD_NUMBER', value: '42' },
|
|
283
|
+
],
|
|
284
|
+
});
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it('redeploys a separate non-Git Compose Deploy Stack with repullImage and Replace strategy', async () => {
|
|
288
|
+
const app = createFakeApp({
|
|
289
|
+
id: 1,
|
|
290
|
+
name: 'Portainer Primary',
|
|
291
|
+
baseUrl,
|
|
292
|
+
apiKey: 'enc:ptr_test_key_123',
|
|
293
|
+
enabled: true,
|
|
294
|
+
isDefault: true,
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
const result = await executePortainerRedeploy(app, {
|
|
298
|
+
endpointId: 3,
|
|
299
|
+
stackId: 20,
|
|
300
|
+
repullImage: true,
|
|
301
|
+
prune: true,
|
|
302
|
+
envStrategy: 'replace',
|
|
303
|
+
envText: 'IMAGE_TAG=v1.4.0\nPORT=9090',
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
expect(result.ok).toBe(true);
|
|
307
|
+
expect(result.stackType).toBe('compose');
|
|
308
|
+
expect(result.appliedEnv).toEqual({ IMAGE_TAG: 'v1.4.0', PORT: '9090' });
|
|
309
|
+
|
|
310
|
+
const composePut = recorded.find((r) => r.method === 'PUT' && r.url.startsWith('/api/stacks/20?'));
|
|
311
|
+
expect(composePut).toBeDefined();
|
|
312
|
+
expect(composePut?.body).toMatchObject({
|
|
313
|
+
pullImage: true,
|
|
314
|
+
prune: true,
|
|
315
|
+
env: [
|
|
316
|
+
{ name: 'IMAGE_TAG', value: 'v1.4.0' },
|
|
317
|
+
{ name: 'PORT', value: '9090' },
|
|
318
|
+
],
|
|
319
|
+
});
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
it('triggers Stack Webhook without leaking X-API-Key header and supports Control inspect/stop', async () => {
|
|
323
|
+
const app = createFakeApp({
|
|
324
|
+
id: 1,
|
|
325
|
+
name: 'Portainer Primary',
|
|
326
|
+
baseUrl,
|
|
327
|
+
apiKey: 'enc:ptr_test_key_123',
|
|
328
|
+
enabled: true,
|
|
329
|
+
isDefault: true,
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
const webhookRes = await executePortainerRedeploy(app, {
|
|
333
|
+
mode: 'webhook',
|
|
334
|
+
webhookId: '638e6967-ef77-4906-8af8-236800621360',
|
|
335
|
+
webhookTag: 'v1.4.0',
|
|
336
|
+
});
|
|
337
|
+
expect(webhookRes.stackType).toBe('webhook');
|
|
338
|
+
|
|
339
|
+
const hookCall = recorded.find((r) => r.url.startsWith('/api/stacks/webhooks/'));
|
|
340
|
+
expect(hookCall?.url).toBe('/api/stacks/webhooks/638e6967-ef77-4906-8af8-236800621360?tag=v1.4.0');
|
|
341
|
+
expect(hookCall?.headers['x-api-key']).toBeUndefined();
|
|
342
|
+
|
|
343
|
+
const inspectRes = await executePortainerControl(app, {
|
|
344
|
+
stackId: 10,
|
|
345
|
+
action: 'inspect',
|
|
346
|
+
});
|
|
347
|
+
expect(inspectRes.healthy).toBe(true);
|
|
348
|
+
expect(inspectRes.currentEnv.DB_PASSWORD).toBe(SECRET_MASK);
|
|
349
|
+
|
|
350
|
+
const stopRes = await executePortainerControl(app, {
|
|
351
|
+
stackId: 20,
|
|
352
|
+
action: 'stop',
|
|
353
|
+
});
|
|
354
|
+
expect(stopRes.action).toBe('stop');
|
|
355
|
+
expect(stopRes.stackStatus).toBe(2);
|
|
356
|
+
expect(stopRes.healthy).toBe(true);
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
it('rejects unsafe URLs with non-HTTP schemes or embedded credentials', () => {
|
|
360
|
+
expect(() => assertValidPortainerUrl('ftp://portainer.local')).toThrow(PortainerApiError);
|
|
361
|
+
expect(() => assertValidPortainerUrl('https://admin:secret@portainer.local:9443')).toThrow(PortainerApiError);
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
it('polls asynchronous Portainer Status=3 (Deploying) until Active or throws on Status=4 (Error)', async () => {
|
|
365
|
+
const client = new PortainerClient({ baseUrl, apiKey: 'ptr_test_key_123', timeoutMs: 5_000 });
|
|
366
|
+
let pollCalls = 0;
|
|
367
|
+
vi.spyOn(client, 'getRawStack').mockImplementation(async () => {
|
|
368
|
+
pollCalls += 1;
|
|
369
|
+
if (pollCalls < 2) {
|
|
370
|
+
return { Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 3 };
|
|
371
|
+
}
|
|
372
|
+
return { Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 1 };
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
const settled = await client.waitForStackSettlement(
|
|
376
|
+
10,
|
|
377
|
+
{ Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 3 },
|
|
378
|
+
{ pollIntervalMs: 50, timeoutMs: 2_000 },
|
|
379
|
+
);
|
|
380
|
+
expect(settled.Status).toBe(1);
|
|
381
|
+
expect(pollCalls).toBe(2);
|
|
382
|
+
|
|
383
|
+
vi.spyOn(client, 'getRawStack').mockResolvedValueOnce({
|
|
384
|
+
Id: 10,
|
|
385
|
+
Name: 'api-build-stack',
|
|
386
|
+
EndpointId: 2,
|
|
387
|
+
Status: 4,
|
|
388
|
+
DeploymentStatus: [{ Status: 4, Time: 123, Message: 'Dockerfile syntax error on line 4' }],
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
await expect(
|
|
392
|
+
client.waitForStackSettlement(
|
|
393
|
+
10,
|
|
394
|
+
{ Id: 10, Name: 'api-build-stack', EndpointId: 2, Status: 3 },
|
|
395
|
+
{ pollIntervalMs: 50, timeoutMs: 2_000 },
|
|
396
|
+
),
|
|
397
|
+
).rejects.toThrow('Dockerfile syntax error on line 4');
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
it('enforces ACL on metadata actions and masks stored secrets in API responses', async () => {
|
|
401
|
+
const allowRules = new Map<string, (ctx: Record<string, unknown>) => boolean>();
|
|
402
|
+
let responseMiddleware: ((ctx: Record<string, unknown>, next: () => Promise<void>) => Promise<void>) | null = null;
|
|
403
|
+
const registeredInstructions = new Map<string, unknown>();
|
|
404
|
+
|
|
405
|
+
const fakePlugin = Object.create(PluginWorkflowPortainerServer.prototype) as PluginWorkflowPortainerServer & {
|
|
406
|
+
app: Record<string, unknown>;
|
|
407
|
+
};
|
|
408
|
+
fakePlugin.app = {
|
|
409
|
+
pm: {
|
|
410
|
+
get: () => ({
|
|
411
|
+
registerInstruction: (name: string, inst: unknown) => registeredInstructions.set(name, inst),
|
|
412
|
+
}),
|
|
413
|
+
},
|
|
414
|
+
resourceManager: {
|
|
415
|
+
define: vi.fn(),
|
|
416
|
+
use: (mw: (ctx: Record<string, unknown>, next: () => Promise<void>) => Promise<void>) => {
|
|
417
|
+
responseMiddleware = mw;
|
|
418
|
+
},
|
|
419
|
+
},
|
|
420
|
+
acl: {
|
|
421
|
+
registerSnippet: vi.fn(),
|
|
422
|
+
allow: (_res: string, action: string, fn: (ctx: Record<string, unknown>) => boolean) => {
|
|
423
|
+
allowRules.set(action, fn);
|
|
424
|
+
},
|
|
425
|
+
can: ({ role, resource, action }: { role: string; resource: string; action: string }) => {
|
|
426
|
+
if (role === 'workflow_editor' && resource === 'workflows' && action === 'update') {
|
|
427
|
+
return true;
|
|
428
|
+
}
|
|
429
|
+
return false;
|
|
430
|
+
},
|
|
431
|
+
},
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
await PluginWorkflowPortainerServer.prototype.load.call(fakePlugin);
|
|
435
|
+
|
|
436
|
+
expect(registeredInstructions.has('portainer-stack-redeploy')).toBe(true);
|
|
437
|
+
expect(registeredInstructions.has('portainer-stack-control')).toBe(true);
|
|
438
|
+
|
|
439
|
+
const checkListStacks = allowRules.get('listStacks');
|
|
440
|
+
expect(checkListStacks).toBeDefined();
|
|
441
|
+
expect(checkListStacks?.({ state: {} })).toBe(false);
|
|
442
|
+
expect(checkListStacks?.({ state: { currentUser: { id: 2 }, currentRoles: ['member'] } })).toBe(false);
|
|
443
|
+
expect(checkListStacks?.({ state: { currentUser: { id: 3 }, currentRoles: ['workflow_editor'] } })).toBe(true);
|
|
444
|
+
expect(checkListStacks?.({ state: { currentUser: { id: 1 }, currentRoles: ['root'] } })).toBe(true);
|
|
445
|
+
|
|
446
|
+
const ctx: Record<string, unknown> = {
|
|
447
|
+
action: { resourceName: 'portainerInstances' },
|
|
448
|
+
body: {
|
|
449
|
+
data: [
|
|
450
|
+
{
|
|
451
|
+
id: 1,
|
|
452
|
+
name: 'Prod',
|
|
453
|
+
apiKey: 'enc:secret-key',
|
|
454
|
+
gitAccessToken: 'enc:git-pat',
|
|
455
|
+
},
|
|
456
|
+
],
|
|
457
|
+
},
|
|
458
|
+
};
|
|
459
|
+
await responseMiddleware?.(ctx, async () => {});
|
|
460
|
+
const maskedRow = (ctx.body as { data: Array<Record<string, string>> }).data[0];
|
|
461
|
+
expect(maskedRow.apiKey).toBe(SECRET_MASK);
|
|
462
|
+
expect(maskedRow.gitAccessToken).toBe(SECRET_MASK);
|
|
463
|
+
expect(allowRules.has('getStackOverview')).toBe(true);
|
|
464
|
+
expect(allowRules.has('getContainerLogs')).toBe(true);
|
|
465
|
+
expect(allowRules.has('controlStack')).toBe(false);
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
it('computes live Docker container stats, demuxes binary log frames, and builds getStackOverview', async () => {
|
|
469
|
+
const stats = computeDockerContainerStats({
|
|
470
|
+
cpu_stats: {
|
|
471
|
+
cpu_usage: { total_usage: 250_000_000 },
|
|
472
|
+
system_cpu_usage: 2_000_000_000,
|
|
473
|
+
online_cpus: 2,
|
|
474
|
+
},
|
|
475
|
+
precpu_stats: {
|
|
476
|
+
cpu_usage: { total_usage: 150_000_000 },
|
|
477
|
+
system_cpu_usage: 1_000_000_000,
|
|
478
|
+
},
|
|
479
|
+
memory_stats: {
|
|
480
|
+
usage: 120 * 1024 * 1024,
|
|
481
|
+
limit: 1024 * 1024 * 1024,
|
|
482
|
+
stats: { inactive_file: 20 * 1024 * 1024 },
|
|
483
|
+
},
|
|
484
|
+
networks: {
|
|
485
|
+
eth0: { rx_bytes: 4096, tx_bytes: 2048 },
|
|
486
|
+
eth1: { rx_bytes: 1024, tx_bytes: 512 },
|
|
487
|
+
},
|
|
488
|
+
blkio_stats: {
|
|
489
|
+
io_service_bytes_recursive: [
|
|
490
|
+
{ op: 'Read', value: 8192 },
|
|
491
|
+
{ op: 'Write', value: 4096 },
|
|
492
|
+
],
|
|
493
|
+
},
|
|
494
|
+
pids_stats: { current: 7 },
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
expect(stats.cpuPercent).toBe(20);
|
|
498
|
+
expect(stats.memUsageBytes).toBe(100 * 1024 * 1024);
|
|
499
|
+
expect(stats.memLimitBytes).toBe(1024 * 1024 * 1024);
|
|
500
|
+
expect(stats.memPercent).toBe(9.77);
|
|
501
|
+
expect(stats.netRxBytes).toBe(5120);
|
|
502
|
+
expect(stats.netTxBytes).toBe(2560);
|
|
503
|
+
expect(stats.blockReadBytes).toBe(8192);
|
|
504
|
+
expect(stats.blockWriteBytes).toBe(4096);
|
|
505
|
+
expect(stats.pids).toBe(7);
|
|
506
|
+
|
|
507
|
+
const line1 = Buffer.from('2026-11-26T16:25:00Z nginx ready\n', 'utf8');
|
|
508
|
+
const hdr1 = Buffer.alloc(8);
|
|
509
|
+
hdr1[0] = 1;
|
|
510
|
+
hdr1.writeUInt32BE(line1.length, 4);
|
|
511
|
+
const line2 = Buffer.from('2026-11-26T16:25:01Z worker started\n', 'utf8');
|
|
512
|
+
const hdr2 = Buffer.alloc(8);
|
|
513
|
+
hdr2[0] = 2;
|
|
514
|
+
hdr2.writeUInt32BE(line2.length, 4);
|
|
515
|
+
const muxBuf = Buffer.concat([hdr1, line1, hdr2, line2]);
|
|
516
|
+
|
|
517
|
+
expect(demuxDockerLogBuffer(muxBuf)).toBe(
|
|
518
|
+
'2026-11-26T16:25:00Z nginx ready\n2026-11-26T16:25:01Z worker started\n',
|
|
519
|
+
);
|
|
520
|
+
expect(demuxDockerLogBuffer(Buffer.from('plain tty log\n', 'utf8'))).toBe('plain tty log\n');
|
|
521
|
+
expect(() => assertValidContainerId('../bad-path')).toThrow(PortainerApiError);
|
|
522
|
+
expect(assertValidContainerId('afb6265776d5')).toBe('afb6265776d5');
|
|
523
|
+
|
|
524
|
+
const app = createFakeApp({
|
|
525
|
+
id: 1,
|
|
526
|
+
name: 'Primary Portainer',
|
|
527
|
+
baseUrl,
|
|
528
|
+
apiKey: 'enc:ptr_test_key_123',
|
|
529
|
+
enabled: true,
|
|
530
|
+
defaultTimeoutMs: 10_000,
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
vi.spyOn(PortainerClient.prototype, 'getContainerLiveStats').mockResolvedValueOnce(stats);
|
|
534
|
+
|
|
535
|
+
const actions = createPortainerResourceActions(app);
|
|
536
|
+
const ctx = {
|
|
537
|
+
action: { params: { instanceId: 1, stackId: 10 } },
|
|
538
|
+
t: (k: string) => k,
|
|
539
|
+
throw: (code: number, msg: string) => {
|
|
540
|
+
throw new Error(`${code}:${msg}`);
|
|
541
|
+
},
|
|
542
|
+
body: undefined as unknown,
|
|
543
|
+
} as unknown as Context;
|
|
544
|
+
|
|
545
|
+
await actions.getStackOverview(ctx, async () => {});
|
|
546
|
+
const overview = ctx.body as {
|
|
547
|
+
detail: { env: Array<{ name: string; value: string; sensitive: boolean }> };
|
|
548
|
+
summary: { totalCpuPercent: number; runningCount: number };
|
|
549
|
+
};
|
|
550
|
+
expect(overview.summary.totalCpuPercent).toBe(20);
|
|
551
|
+
expect(overview.summary.runningCount).toBe(1);
|
|
552
|
+
const dbSecret = overview.detail.env.find((item) => item.name === 'DB_PASSWORD');
|
|
553
|
+
const existingFlag = overview.detail.env.find((item) => item.name === 'EXISTING_FLAG');
|
|
554
|
+
expect(dbSecret?.sensitive).toBe(true);
|
|
555
|
+
expect(dbSecret?.value).toBe(SECRET_MASK);
|
|
556
|
+
expect(existingFlag?.sensitive).toBe(false);
|
|
557
|
+
expect(existingFlag?.value).toBe('keep-me');
|
|
558
|
+
});
|
|
559
|
+
});
|