11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ci// Test that fs.copyFile() respects file permissions.
41cb0ef41Sopenharmony_ci// Ref: https://github.com/nodejs/node/issues/26936
51cb0ef41Sopenharmony_ci
61cb0ef41Sopenharmony_ciconst common = require('../common');
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_ciif (!common.isWindows && process.getuid() === 0)
91cb0ef41Sopenharmony_ci  common.skip('as this test should not be run as `root`');
101cb0ef41Sopenharmony_ci
111cb0ef41Sopenharmony_ciif (common.isIBMi)
121cb0ef41Sopenharmony_ci  common.skip('IBMi has a different access permission mechanism');
131cb0ef41Sopenharmony_ci
141cb0ef41Sopenharmony_ciconst tmpdir = require('../common/tmpdir');
151cb0ef41Sopenharmony_citmpdir.refresh();
161cb0ef41Sopenharmony_ci
171cb0ef41Sopenharmony_ciconst assert = require('assert');
181cb0ef41Sopenharmony_ciconst fs = require('fs');
191cb0ef41Sopenharmony_ciconst path = require('path');
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_cilet n = 0;
221cb0ef41Sopenharmony_ci
231cb0ef41Sopenharmony_cifunction beforeEach() {
241cb0ef41Sopenharmony_ci  n++;
251cb0ef41Sopenharmony_ci  const source = path.join(tmpdir.path, `source${n}`);
261cb0ef41Sopenharmony_ci  const dest = path.join(tmpdir.path, `dest${n}`);
271cb0ef41Sopenharmony_ci  fs.writeFileSync(source, 'source');
281cb0ef41Sopenharmony_ci  fs.writeFileSync(dest, 'dest');
291cb0ef41Sopenharmony_ci  fs.chmodSync(dest, '444');
301cb0ef41Sopenharmony_ci
311cb0ef41Sopenharmony_ci  const check = (err) => {
321cb0ef41Sopenharmony_ci    const expected = ['EACCES', 'EPERM'];
331cb0ef41Sopenharmony_ci    assert(expected.includes(err.code), `${err.code} not in ${expected}`);
341cb0ef41Sopenharmony_ci    assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'dest');
351cb0ef41Sopenharmony_ci    return true;
361cb0ef41Sopenharmony_ci  };
371cb0ef41Sopenharmony_ci
381cb0ef41Sopenharmony_ci  return { source, dest, check };
391cb0ef41Sopenharmony_ci}
401cb0ef41Sopenharmony_ci
411cb0ef41Sopenharmony_ci// Test synchronous API.
421cb0ef41Sopenharmony_ci{
431cb0ef41Sopenharmony_ci  const { source, dest, check } = beforeEach();
441cb0ef41Sopenharmony_ci  assert.throws(() => { fs.copyFileSync(source, dest); }, check);
451cb0ef41Sopenharmony_ci}
461cb0ef41Sopenharmony_ci
471cb0ef41Sopenharmony_ci// Test promises API.
481cb0ef41Sopenharmony_ci{
491cb0ef41Sopenharmony_ci  const { source, dest, check } = beforeEach();
501cb0ef41Sopenharmony_ci  (async () => {
511cb0ef41Sopenharmony_ci    await assert.rejects(fs.promises.copyFile(source, dest), check);
521cb0ef41Sopenharmony_ci  })().then(common.mustCall());
531cb0ef41Sopenharmony_ci}
541cb0ef41Sopenharmony_ci
551cb0ef41Sopenharmony_ci// Test callback API.
561cb0ef41Sopenharmony_ci{
571cb0ef41Sopenharmony_ci  const { source, dest, check } = beforeEach();
581cb0ef41Sopenharmony_ci  fs.copyFile(source, dest, common.mustCall(check));
591cb0ef41Sopenharmony_ci}
60