feat(portal-bff): msal confidential client provider in AuthModule (#104)
CI / check (push) Successful in 3m21s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 2m43s
CI / a11y (push) Successful in 1m56s
CI / perf (push) Successful in 3m34s

Second step of ADR-0009 wiring. AuthModule now exposes the
`@azure/msal-node` confidential client alongside the parsed Entra
config — the building block the upcoming OIDC routes inject to issue
the auth-code URL, exchange the callback code for tokens, and
acquire downstream tokens on behalf of the user.

What lands:

- `@azure/msal-node` added as a direct dependency (^5.2.1).
- `apps/portal-bff/src/auth/msal-client.token.ts` — `MSAL_CLIENT`
  string token + `ConfidentialClientApplication` type re-export.
  Mirrors the `ENTRA_CONFIG` token shape from PR #102.
- AuthModule grows a factory provider for `MSAL_CLIENT`:
  - Injects `ENTRA_CONFIG` + nestjs-pino `Logger`.
  - Builds a `ConfidentialClientApplication` with `clientId`,
    `authority`, `clientSecret` from the parsed config.
  - Wires `system.loggerOptions.loggerCallback` to forward MSAL's
    internal log lines into the Pino stream (per ADR-0012) — Error
    → logger.error, Warning → logger.warn, Verbose / Trace →
    logger.debug, Info → logger.log. PII logging is disabled by
    default so tokens / user identifiers never leak into our
    structured log records.
  - Sets MSAL's `logLevel` to Info — Pino's own threshold
    re-filters from there.
  - All MSAL log lines carry the `msal` Pino context for easy
    isolation in log queries.
- `AuthModule.exports` extended to include `MSAL_CLIENT`.

Verification:

- `nx run-many -t lint test build --projects=portal-bff` — green.
- 30/30 specs (was 29; +1 covering MSAL client construction).
- New spec imports `nestjs-pino`'s `LoggerModule.forRoot({ pinoHttp:
  { level: 'silent' } })` to provide the same Logger the production
  app supplies via `ObservabilityModule`, without flooding test
  stdout. Two tests assert the provider tree resolves correctly
  (ENTRA_CONFIG + MSAL_CLIENT) and one re-checks the missing-env
  failure mode still propagates through the new factory.

Construction is cheap — MSAL Node defers authority discovery to the
first auth call — so the client is built eagerly at module init.
The factory is injection-only; no MSAL methods get invoked yet.
Routes land in the next PR.

<!--
PR title format — becomes the squash-merge subject on main, validated by commitlint.

  <type>(<scope>): <short description>

Examples:
  feat(portal-shell): add user-preferences panel skeleton
  fix(portal-bff): correct env var bracket access
  docs(decisions): add ADR-0018 for security baseline
  chore(deps): bump @nx/* to 22.7.2

Imperative mood, lowercase, no trailing period, target ≤ 70 chars.
See docs/development.md §5 for the full convention (types, scopes).
-->

## Summary

## Motivation

## Implementation notes

## Verification

- [ ] `pnpm ci:check` green locally
- [ ] `pnpm ci:audit` green (or pre-existing drift acknowledged)
- [ ] Tested manually:
- [ ] Architecture diagram updated (if `docs/architecture.md` was affected)
- [ ] ADR amended or added (if a decision changed)

## Related

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #104
This commit was merged in pull request #104.
This commit is contained in:
2026-05-12 10:34:23 +02:00
parent abd651b697
commit b7093d61de
5 changed files with 199 additions and 16 deletions
+22 -4
View File
@@ -1,6 +1,9 @@
import { ConfidentialClientApplication } from '@azure/msal-node';
import { Test } from '@nestjs/testing';
import { LoggerModule } from 'nestjs-pino';
import { AuthModule } from './auth.module';
import { ENTRA_CONFIG, type EntraConfig } from './entra-config.token';
import { MSAL_CLIENT } from './msal-client.token';
const VALID = {
ENTRA_INSTANCE_URL: 'https://login.microsoftonline.com/',
@@ -11,6 +14,17 @@ const VALID = {
ENTRA_POST_LOGOUT_REDIRECT_URI: 'http://localhost:4200/',
};
// AuthModule's MSAL_CLIENT factory injects the Pino-backed `Logger`
// (which the production app supplies through `ObservabilityModule`).
// Importing `LoggerModule.forRoot({ pinoHttp: { level: 'silent' } })`
// here registers the same provider for the testing module without
// flooding test stdout.
async function compile() {
return Test.createTestingModule({
imports: [LoggerModule.forRoot({ pinoHttp: { level: 'silent' } }), AuthModule],
}).compile();
}
describe('AuthModule', () => {
const originalEnv: Record<string, string | undefined> = {};
@@ -33,16 +47,20 @@ describe('AuthModule', () => {
});
it('provides EntraConfig via the ENTRA_CONFIG token', async () => {
const ref = await Test.createTestingModule({ imports: [AuthModule] }).compile();
const ref = await compile();
const config = ref.get<EntraConfig>(ENTRA_CONFIG);
expect(config.clientId).toBe(VALID.ENTRA_CLIENT_ID);
expect(config.authority).toBe(`${VALID.ENTRA_INSTANCE_URL}${VALID.ENTRA_TENANT_ID}`);
});
it('provides a ConfidentialClientApplication via the MSAL_CLIENT token', async () => {
const ref = await compile();
const client = ref.get<ConfidentialClientApplication>(MSAL_CLIENT);
expect(client).toBeInstanceOf(ConfidentialClientApplication);
});
it('fails to compile when an env var is missing', async () => {
delete process.env['ENTRA_CLIENT_SECRET'];
await expect(Test.createTestingModule({ imports: [AuthModule] }).compile()).rejects.toThrow(
/ENTRA_CLIENT_SECRET/,
);
await expect(compile()).rejects.toThrow(/ENTRA_CLIENT_SECRET/);
});
});
+61 -12
View File
@@ -1,20 +1,29 @@
import { ConfidentialClientApplication, LogLevel } from '@azure/msal-node';
import { Module } from '@nestjs/common';
import { Logger } from 'nestjs-pino';
import { assertEntraConfig } from '../config/check-entra-config';
import { ENTRA_CONFIG } from './entra-config.token';
import { ENTRA_CONFIG, type EntraConfig } from './entra-config.token';
import { MSAL_CLIENT } from './msal-client.token';
/**
* Auth module — owns the Entra ID configuration and (in subsequent
* PRs) the MSAL Node confidential client, the OIDC routes, the
* Auth module — owns the Entra ID configuration, the MSAL Node
* confidential client, and (in subsequent PRs) the OIDC routes, the
* session integration, and the route guards. Per ADR-0009.
*
* v1 of this module exposes a single provider: the parsed Entra
* config, available via the `ENTRA_CONFIG` injection token. The
* factory delegates to `assertEntraConfig()` — the same validator
* `main.ts` calls at boot — so the typed config object that
* consumers receive is guaranteed to be complete and well-formed.
* The duplicate call is intentional: boot-time fails fast, the
* factory parses again for the DI result. Both reads are
* idempotent and trivially cheap.
* v1 providers:
*
* - `ENTRA_CONFIG` — the parsed, validated Entra app-registration
* config (PR #102).
* - `MSAL_CLIENT` — a `ConfidentialClientApplication` instance
* wired with that config plus a logger callback that forwards
* MSAL's internal log lines into the Pino stream so auth flow
* diagnostics land alongside the rest of the BFF logs (per
* ADR-0012). PII logging is disabled by default — MSAL won't
* include tokens or user identifiers in the messages it emits.
*
* The module stays non-global: modules state "I depend on auth" by
* importing it. Re-exports both tokens so a single
* `imports: [AuthModule]` is enough to consume either.
*/
@Module({
providers: [
@@ -22,7 +31,47 @@ import { ENTRA_CONFIG } from './entra-config.token';
provide: ENTRA_CONFIG,
useFactory: () => assertEntraConfig(),
},
{
provide: MSAL_CLIENT,
inject: [ENTRA_CONFIG, Logger],
useFactory: (config: EntraConfig, logger: Logger) =>
new ConfidentialClientApplication({
auth: {
clientId: config.clientId,
authority: config.authority,
clientSecret: config.clientSecret,
},
system: {
loggerOptions: {
piiLoggingEnabled: false,
logLevel: LogLevel.Info,
loggerCallback: (level, message) => {
// MSAL levels: 0=Error, 1=Warning, 2=Info, 3=Verbose, 4=Trace.
// Forward to Pino with the matching level. The whole
// payload lives under the `msal` context key so a log
// search filtering on `msal` returns every MSAL line
// without false positives from app code.
const ctx = 'msal';
switch (level) {
case LogLevel.Error:
logger.error(message, ctx);
break;
case LogLevel.Warning:
logger.warn(message, ctx);
break;
case LogLevel.Verbose:
case LogLevel.Trace:
logger.debug(message, ctx);
break;
default:
logger.log(message, ctx);
}
},
},
},
}),
},
],
exports: [ENTRA_CONFIG],
exports: [ENTRA_CONFIG, MSAL_CLIENT],
})
export class AuthModule {}
@@ -0,0 +1,16 @@
import type { ConfidentialClientApplication } from '@azure/msal-node';
/**
* DI token used to inject the MSAL Node confidential client.
*
* Usage:
* @Inject(MSAL_CLIENT) private readonly msal: ConfidentialClientApplication
*
* The provider lives in `AuthModule`. Construction is cheap (no
* network call) so the client is built eagerly at module init; the
* lazy authority-discovery round-trip MSAL needs runs on the first
* actual auth method call (e.g. `getAuthCodeUrl`).
*/
export const MSAL_CLIENT = 'MSAL_CLIENT';
export type { ConfidentialClientApplication };