liudong
2023-05-29 340f156319b863525e50e900c58e59b86ecb3d5e
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
    // init: init,
    // register: register,
    // registerSubflow: registerSubflow,
    // checkFlowDependencies: checkFlowDependencies,
    // require: requireModule
    //
 
const should = require("should");
const sinon = require("sinon");
const fs = require("fs-extra");
const path = require("path");
const os = require("os");
 
const NR_TEST_UTILS = require("nr-test-utils");
const externalModules = NR_TEST_UTILS.require("@node-red/registry/lib/externalModules");
const exec = NR_TEST_UTILS.require("@node-red/util/lib/exec");
const hooks = NR_TEST_UTILS.require("@node-red/util/lib/hooks");
 
let homeDir;
 
async function createUserDir() {
    if (!homeDir) {
        homeDir = path.join(os.tmpdir(),"nr-test-"+Math.floor(Math.random()*100000));
    }
    await fs.ensureDir(homeDir);
}
 
async function setupExternalModulesPackage(dependencies) {
    await fs.writeFile(path.join(homeDir,"package.json"),`{
"name": "Node-RED-External-Modules",
"description": "These modules are automatically installed by Node-RED to use in Function nodes.",
"version": "1.0.0",
"private": true,
"dependencies": ${JSON.stringify(dependencies)}
}`)
}
 
describe("externalModules api", function() {
    beforeEach(async function() {
        await createUserDir()
    })
    afterEach(async function() {
        hooks.clear();
        await fs.remove(homeDir);
    })
    describe("checkFlowDependencies", function() {
        beforeEach(function() {
            sinon.stub(exec,"run").callsFake(async function(cmd, args, options) {
                let error;
                let moduleName = args[args.length-1];
                if (moduleName === "moduleNotFound") {
                    error = new Error();
                    error.stderr = "E404";
                } else if (moduleName === "moduleVersionNotFound") {
                    error = new Error();
                    error.stderr = "ETARGET";
                } else if (moduleName === "moduleFail") {
                    error = new Error();
                    error.stderr = "Some unexpected install error";
                }
                if (error) {
                    throw error;
                }
            })
        })
        afterEach(function() {
            exec.run.restore();
        })
        it("does nothing when no types are registered",async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            await externalModules.checkFlowDependencies([
                {type: "function", libs:[{module: "foo"}]}
            ])
            exec.run.called.should.be.false();
        });
 
        it("skips install for modules already installed", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            await setupExternalModulesPackage({"foo": "1.2.3", "bar":"2.3.4"});
            await externalModules.checkFlowDependencies([
                {type: "function", libs:[{module: "foo"}]}
            ])
            exec.run.called.should.be.false();
        })
 
        it("skips install for built-in modules", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            await externalModules.checkFlowDependencies([
                {type: "function", libs:[{module: "fs"}]}
            ])
            exec.run.called.should.be.false();
        })
 
        it("installs missing modules", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            await externalModules.checkFlowDependencies([
                {type: "function", libs:[{module: "foo"}]}
            ])
            exec.run.called.should.be.true();
        })
 
 
        it("calls pre/postInstall hooks", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            let receivedPreEvent,receivedPostEvent;
            hooks.add("preInstall", function(event) { event.args = ["a"]; receivedPreEvent = event; })
            hooks.add("postInstall", function(event) { receivedPostEvent = event; })
 
            await externalModules.checkFlowDependencies([
                {type: "function", libs:[{module: "foo"}]}
            ])
            exec.run.called.should.be.true();
            // exec.run.lastCall.args[1].should.eql([ 'install', 'a', 'foo' ]);
            receivedPreEvent.should.have.property("module","foo")
            receivedPreEvent.should.have.property("version")
            receivedPreEvent.should.have.property("dir")
            receivedPreEvent.should.eql(receivedPostEvent)
        })
 
        it("skips npm install if preInstall returns false", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            let receivedPreEvent,receivedPostEvent;
            hooks.add("preInstall", function(event) { receivedPreEvent = event; return false })
            hooks.add("postInstall", function(event) { receivedPostEvent = event; })
 
            await externalModules.checkFlowDependencies([
                {type: "function", libs:[{module: "foo"}]}
            ])
            exec.run.called.should.be.false();
            receivedPreEvent.should.have.property("module","foo")
            receivedPreEvent.should.have.property("version")
            receivedPreEvent.should.have.property("dir")
            receivedPreEvent.should.eql(receivedPostEvent)
        })
 
 
        it("installs missing modules from inside subflow module", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            externalModules.registerSubflow("sf", {"flow":[{type: "function", libs:[{module: "foo"}]}]});
            await externalModules.checkFlowDependencies([
                {type: "sf"}
            ])
            exec.run.called.should.be.true();
        })
 
        it("reports install fail - 404", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            try {
                await externalModules.checkFlowDependencies([
                    {type: "function", libs:[{module: "moduleNotFound"}]}
                ])
                throw new Error("checkFlowDependencies did not reject after install fail")
            } catch(err) {
                exec.run.called.should.be.true();
                Array.isArray(err).should.be.true();
                err.should.have.length(1);
                err[0].should.have.property("module");
                err[0].module.should.have.property("module","moduleNotFound");
                err[0].should.have.property("error");
                err[0].error.should.have.property("code",404);
 
            }
        })
        it("reports install fail - target", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            try {
                await externalModules.checkFlowDependencies([
                    {type: "function", libs:[{module: "moduleVersionNotFound"}]}
                ])
                throw new Error("checkFlowDependencies did not reject after install fail")
            } catch(err) {
                exec.run.called.should.be.true();
                Array.isArray(err).should.be.true();
                err.should.have.length(1);
                err[0].should.have.property("module");
                err[0].module.should.have.property("module","moduleVersionNotFound");
                err[0].should.have.property("error");
                err[0].error.should.have.property("code",404);
            }
        })
 
        it("reports install fail - unexpected", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            try {
                await externalModules.checkFlowDependencies([
                    {type: "function", libs:[{module: "moduleFail"}]}
                ])
                throw new Error("checkFlowDependencies did not reject after install fail")
            } catch(err) {
                exec.run.called.should.be.true();
                Array.isArray(err).should.be.true();
                err.should.have.length(1);
                err[0].should.have.property("module");
                err[0].module.should.have.property("module","moduleFail");
                err[0].should.have.property("error");
                err[0].error.should.have.property("code","unexpected_error");
            }
        })
        it("reports install fail - multiple", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            externalModules.register("function", "libs");
            try {
                await externalModules.checkFlowDependencies([
                    {type: "function", libs:[{module: "moduleNotFound"},{module: "moduleFail"}]}
                ])
                throw new Error("checkFlowDependencies did not reject after install fail")
            } catch(err) {
                exec.run.called.should.be.true();
                Array.isArray(err).should.be.true();
                err.should.have.length(2);
                // Sort the array so we know the order to test for
                err.sort(function(A,B) {
                    return A.module.module.localeCompare(B.module.module);
                })
                err[1].should.have.property("module");
                err[1].module.should.have.property("module","moduleNotFound");
                err[1].should.have.property("error");
                err[1].error.should.have.property("code",404);
                err[0].should.have.property("module");
                err[0].module.should.have.property("module","moduleFail");
                err[0].should.have.property("error");
                err[0].error.should.have.property("code","unexpected_error");
 
            }
        })
        it("reports install fail - install disabled", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}, externalModules: {
                modules: {
                    allowInstall: false
                }
            }});
            externalModules.register("function", "libs");
            try {
                await externalModules.checkFlowDependencies([
                    {type: "function", libs:[{module: "foo"}]}
                ])
                throw new Error("checkFlowDependencies did not reject after install fail")
            } catch(err) {
                // Should not try to install
                exec.run.called.should.be.false();
                Array.isArray(err).should.be.true();
                err.should.have.length(1);
                err[0].should.have.property("module");
                err[0].module.should.have.property("module","foo");
                err[0].should.have.property("error");
                err[0].error.should.have.property("code","install_not_allowed");
            }
        })
 
        it("reports install fail - module disallowed", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}, externalModules: {
                modules: {
                    denyList: ['foo']
                }
            }});
            externalModules.register("function", "libs");
            try {
                await externalModules.checkFlowDependencies([
                    // foo disallowed
                    // bar allowed
                    {type: "function", libs:[{module: "foo"},{module: "bar"}]}
                ])
                throw new Error("checkFlowDependencies did not reject after install fail")
            } catch(err) {
                exec.run.calledOnce.should.be.true();
                Array.isArray(err).should.be.true();
                err.should.have.length(1);
                err[0].should.have.property("module");
                err[0].module.should.have.property("module","foo");
                err[0].should.have.property("error");
                err[0].error.should.have.property("code","install_not_allowed");
            }
        })
 
        it("reports install fail - built-in module disallowed", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}, externalModules: {
                modules: {
                    denyList: ['fs']
                }
            }});
            externalModules.register("function", "libs");
            try {
                await externalModules.checkFlowDependencies([
                    // foo disallowed
                    // bar allowed
                    {type: "function", libs:[{module: "fs"},{module: "bar"}]}
                ])
                throw new Error("checkFlowDependencies did not reject after install fail")
            } catch(err) {
                exec.run.calledOnce.should.be.true();
                Array.isArray(err).should.be.true();
                err.should.have.length(1);
                err[0].should.have.property("module");
                err[0].module.should.have.property("module","fs");
                err[0].should.have.property("error");
                err[0].error.should.have.property("code","module_not_allowed");
            }
        })
    })
    describe("require", async function() {
        it("requires built-in modules", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            const result = externalModules.require("fs")
            result.should.eql(require("fs"));
        })
        it("rejects unknown modules", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            try {
                externalModules.require("foo")
                throw new Error("require did not reject after fail")
            } catch(err) {
                err.should.have.property("code","module_not_allowed");
            }
        })
 
        it("rejects disallowed modules", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}, externalModules: {
                modules: {
                    denyList: ['fs']
                }
            }});
            try {
                externalModules.require("fs")
                throw new Error("require did not reject after fail")
            } catch(err) {
                err.should.have.property("code","module_not_allowed");
            }
        })
    })
    describe("import", async function() {
        it("import built-in modules", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            const result = await externalModules.import("fs")
            // `result` won't have the `should` property
            should.exist(result);
            should.exist(result.existsSync);
        })
        it("rejects unknown modules", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}});
            try {
                await externalModules.import("foo")
                throw new Error("import did not reject after fail")
            } catch(err) {
                err.should.have.property("code","module_not_allowed");
            }
        })
 
        it("rejects disallowed modules", async function() {
            externalModules.init({userDir: homeDir, get:()=>{}, set:()=>{}, externalModules: {
                modules: {
                    denyList: ['fs']
                }
            }});
            try {
                await externalModules.import("fs")
                throw new Error("import did not reject after fail")
            } catch(err) {
                err.should.have.property("code","module_not_allowed");
            }
        })
    })
});