Menu

Lesson 18 · Node.js on IBM i — From RPG Developer to Modern IBM i Developer

Configure and Secure the Application

Separate environment settings from source, use least authority, protect the API, and make logs useful without exposing sensitive data.

IBM iNode.jsSecurityConfigurationLogging

A working development server is not yet a production service. Production needs controlled configuration, an appropriately limited IBM i profile, authenticated users, protected network traffic, and supportable logs.

Keep environment values outside the source

Create .env.example and commit it:

HOST=127.0.0.1
PORT=3000
APP_ENV=development

Create the real .env from it. The .gitignore from Lesson 8 already keeps that file out of Git:

cp .env.example .env

Node.js can load the file itself. Change the two scripts in package.json:

"scripts": {
  "start": "node --env-file=.env src/server.js",
  "dev": "node --env-file=.env --watch src/server.js",
  "test": "node --test"
}

Environment variables are strings. Validate them at startup rather than allowing an invalid port or environment name to fail later. Add this function to src/server.js, above start:

function readConfig() {
  const port = Number(process.env.PORT ?? 3000);
  const environment = process.env.APP_ENV ?? 'development';

  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    throw new Error('PORT must be a valid TCP port');
  }

  if (!['development', 'test', 'production'].includes(environment)) {
    throw new Error('APP_ENV must be development, test, or production');
  }

  return {
    environment,
    host: process.env.HOST ?? '127.0.0.1',
    port
  };
}

Then replace start so that it uses the validated values:

async function start() {
  const config = readConfig();
  const server = buildServer();

  try {
    await server.listen({ port: config.port, host: config.host });
    server.log.info({ environment: config.environment }, 'Tools Rental started');
  } catch (error) {
    server.log.error(error);
    process.exitCode = 1;
  }
}

Try it. Set PORT=abc in .env and run npm start. The application should stop immediately with PORT must be a valid TCP port, which is far easier to diagnose than a server listening somewhere unexpected. Restore PORT=3000 afterward.

Development, test, and production can use the same source while supplying different settings.

Use a dedicated IBM i profile

Do not run the service under a developer’s profile or a highly privileged administrator profile.

The application profile should receive only what it needs:

An administrator creates the profile. TOOLAPP is the name used in this course:

CRTUSRPRF USRPRF(TOOLAPP) PASSWORD(*NONE) USRCLS(*USER) TEXT('Tools Rental service')

PASSWORD(*NONE) prevents password-based sign-on; authorized batch submission can still run work under this profile. Then grant the database authority from Run SQL Scripts:

GRANT USAGE ON SCHEMA TOOLRENT TO TOOLAPP;

GRANT SELECT ON TOOLRENT.TOOLS TO TOOLAPP;
GRANT SELECT ON TOOLRENT.CUSTOMERS TO TOOLAPP;
GRANT SELECT ON TOOLRENT.RENTALS TO TOOLAPP;

GRANT EXECUTE ON PROCEDURE TOOLRENT.RENT_TOOL TO TOOLAPP;
GRANT EXECUTE ON PROCEDURE TOOLRENT.RETURN_TOOL TO TOOLAPP;

Notice what is missing: the profile has no INSERT or UPDATE authority on any table. It can change data only by calling the two procedures. That works because an SQL procedure created with SQL naming runs, by default, under the authority of its owner rather than its caller. It is the same idea as an RPG program that adopts its owner’s authority.

Confirm it on your system instead of assuming it. Run the application as TOOLAPP and check both sides:

If the rental fails with an authority error, the procedures were created to run under the caller’s authority. Decide with your security team whether to recreate them or to grant the table authority explicitly.

The profile should not receive *ALLOBJ as a shortcut. Review adopted authority, group profiles, public authority, and the ownership of deployed files with the IBM i security team.

Put authentication in the design

The course application has no login. Do not expose it to an untrusted network in that state.

A production design should normally place the service behind the organization’s approved reverse proxy or web server, terminate TLS there, and integrate with its established identity provider. The API should receive a verified user identity and enforce which users may rent, return, or administer tools.

Avoid inventing a password table for a tutorial. Authentication, session handling, password recovery, multifactor authentication, and account lifecycle are security systems of their own.

Improve the health check

The current /health route proves only that Node.js can answer. That is a liveness check. A readiness check asks a second question: can the application reach what it depends on?

/health        Liveness: the Node.js process is responding
/health/ready  Readiness: Db2 can be reached

Add a small read-only query to src/db.js and export it:

async function checkDatabase() {
  await pool.runSql('VALUES 1');
}

Add the route in buildServer, below /health:

server.get('/health/ready', async (request, reply) => {
  try {
    await db.checkDatabase();
    return { status: 'ready' };
  } catch (error) {
    request.log.error({ err: error }, 'Readiness check failed');
    return reply.code(503).send({ status: 'unavailable' });
  }
});

HTTP 503 means “service unavailable”. A monitor can treat that differently from a process that does not answer at all.

Because the server accepts a replaceable database, the failure case can be tested without breaking Db2. Add async checkDatabase() {} to createFakeDb in test/server.test.js, then add this test:

test('GET /health/ready returns 503 when Db2 is unavailable', async () => {
  const db = createFakeDb();
  db.checkDatabase = async () => {
    throw new Error('Db2 is not reachable');
  };

  const server = buildServer({ db, logger: false });
  const response = await server.inject({
    method: 'GET',
    url: '/health/ready'
  });

  assert.equal(response.statusCode, 503);
  await server.close();
});

Check the working case by hand:

curl -i http://127.0.0.1:3000/health/ready

Log for operations

Useful events include:

Do not log passwords, tokens, cookies, authorization headers, or complete customer records. Configure retention and access rather than allowing logs to grow forever.

Run the release checks

Before calling the application deployable:

npm test
npm audit
git status

Review audit results instead of applying breaking upgrades blindly.

Commit the configuration and health-check work:

git add .env.example package.json src test
git commit -m "Add configuration and readiness check"
git status

A clean Git status confirms that the release can be traced to committed source. Confirm too that .env is not listed as a tracked file.

The next lesson takes this exact source, lock file, SQL, configuration definition, and operating instructions into an IBM i production deployment.

References

Documentation and references used for this lesson.

← Return to Node.js on IBM i

Comments

Share your thoughts, questions, or real-world IBM i experiences related to this article.