Skip to content

Latest commit

Β 

History

History
407 lines (312 loc) Β· 37.7 KB

authentication.md

File metadata and controls

407 lines (312 loc) Β· 37.7 KB

Authentication

πŸ” Auth0 Integration with Express OpenID Connect

The application uses Auth0 for user authentication via express-openid-connect middleware with selective route protection and session management. The system implements a dual authentication pattern: user authentication for protected routes and machine-to-machine (M2M) authentication for server-side API calls.

πŸ”§ Auth0 Configuration

Environment Variables

# User Authentication (Auth0/Authelia)
PCC_AUTH0_SECRET='your-auth0-secret'
PCC_BASE_URL='http://localhost:4000'
PCC_AUTH0_ISSUER_BASE_URL='https://your-domain.auth0.com/'
PCC_AUTH0_CLIENT_ID='your-client-id'
PCC_AUTH0_CLIENT_SECRET='your-client-secret'
PCC_AUTH0_AUDIENCE='https://your-api-audience'

# Machine-to-Machine (M2M) Token Authentication
M2M_AUTH_CLIENT_ID='your-m2m-client-id'
M2M_AUTH_CLIENT_SECRET='your-m2m-client-secret'
M2M_AUTH_ISSUER_BASE_URL='https://auth.k8s.orb.local/'
M2M_AUTH_AUDIENCE='http://lfx-api.k8s.orb.local/'

Express Server Integration

The authentication configuration uses selective authentication (authRequired: false) with custom route protection middleware. This allows public routes to bypass authentication while maintaining protection for sensitive areas.

Configuration Location: apps/lfx-one/src/server/server.ts

πŸ“‹ User Interface

User Data Structure

// packages/shared/src/interfaces/auth.interface.ts
export interface User {
  sid: string;
  'https://sso.linuxfoundation.org/claims/username': string;
  given_name: string;
  family_name: string;
  nickname: string;
  name: string;
  picture: string;
  updated_at: string;
  email: string;
  email_verified: boolean;
  sub: string;
}

export interface AuthContext {
  authenticated: boolean;
  user: User | null;
  // Persona + project enrichment (populated server-side via persona-detection, hydrated to the
  // browser through Angular TransferState β€” see apps/lfx-one/src/server/services/persona-detection.service.ts)
  persona?: PersonaType | null;
  personas?: PersonaType[];
  organizations?: Account[];
  projects?: EnrichedPersonaProject[];
  personaProjects?: Partial<Record<PersonaType, PersonaProject[]>>;
  // Impersonation capability + active state β€” see docs/architecture/backend/impersonation.md
  canImpersonate?: boolean;
  impersonating?: boolean;
  impersonator?: Impersonator;
}

/**
 * M2M Token Response Interface
 * Used for machine-to-machine authentication responses
 */
export interface M2MTokenResponse {
  access_token: string;
  token_type: string;
  expires_in: number;
  scope?: string;
}

πŸ†” Identity Claims: username vs sub

Two distinct identifiers travel on the OIDC user (req.oidc.user), and choosing the wrong one breaks upstream lookups. They are not interchangeable.

What each one is

Claim Example Shape Source claim(s)
sub (Auth0 subject) auth0|jdoe Provider-prefixed, opaque, globally unique per identity user.sub
username (LFID username) jdoe Bare LF login handle, no provider prefix user['https://sso.linuxfoundation.org/claims/username'] (Authelia local dev only: user.preferred_username)
  • sub identifies the Auth0 identity record. It carries a connection prefix (auth0|, github|, samlp|, …), so the same person can have different sub values across connections. Treat it as an opaque token β€” never parse it, and never display it as if it were a username. Stripping the connection prefix is misleading: the bare value only coincidentally matches the LFID handle today and is not guaranteed to, so a stripped sub is not a substitute for username. getEffectiveSub(req) remains in use at a handful of call sites β€” e.g. cla.service.ts and three of profile.controller.ts's four call sites resolve identity via the auth-service (which also accepts a username or email), mktg-agents.controller.ts binds chat sessions to their creator via internal owner tokens (createSessionOwnerToken/verifySessionOwnerToken), and weekly-brief.service.ts uses it as a stable, non-PII identifier for indefinitely-retained server log records (see "When to use which" below) β€” this list is illustrative, not exhaustive; check getEffectiveSub call sites directly rather than trusting a stale count here.

  • username identifies the LF person by their LFID login handle (bare form, no prefix) and is what most upstream microservices index on going forward. Org role grants (org-identity.controller.ts, org-navigation.service.ts, org-role-grants.service.ts) query b2b_org_settings with tags: ['member:${username}'] where username comes from getEffectiveUsername(req). On surveys, both creator_username and creator_id are set from getEffectiveUsername(req) (the LF username claim, or the impersonation target), and survey creation is refused with a 401 when it resolves to null. Callers that key upstream state on the LFID (profile CDP handlers, surveys, Copilot chat) reject a null LFID with AuthenticationError rather than substituting a shared fallback such as anonymous.

    The role-grants response also reports how well that lookup went β€” lookupOutcome, staffCheck, correlationId (spec 053) β€” so the UI can tell an outage from a denial; see Org Lens empty states.

ID token vs access token β€” where the claims actually live

Auth0 issues two JWTs per session, and they carry identity differently. This split is the central complication of the sub β†’ username migration.

ID token Access token
Lives on req.oidc.user (typed as User) req.oidc.accessToken.access_token, decoded via decodeJwtPayload() into LfxAccessTokenClaims
sub user.sub claims.sub
username claim https://sso.linuxfoundation.org/claims/username (nickname / username are display claims, never the LFID) http://lfx.dev/claims/username β€” different namespace
Consumed by The BFF only (SSR, analytics, persistence, the getEffective* helpers) Forwarded upstream as Authorization: Bearer to the Go microservices

Note: sub is the only identifier present in both tokens under the same key. The username claim is namespaced differently in each (https://sso.linuxfoundation.org/... in the ID token vs http://lfx.dev/... in the access token), so any code bridging the two must map between namespaces β€” they are not the same key.

Worked example β€” impersonation bridges the namespaces by hand. Impersonation discards the target's ID token and rebuilds identity entirely from the exchanged access token, copying its http://lfx.dev/claims/username into every ID-token username slot so both namespaces resolve to the same handle. The claim payload is built by buildImpersonationIdentityOverride() (apps/lfx-one/src/server/utils/auth-helper.ts) and applied via Object.assign(auth.user, ...) in the SSR handler (server.ts):

export function buildImpersonationIdentityOverride(targetClaims: LfxAccessTokenClaims, impersonationUser?: ImpersonationUser | null): Partial<User> {
  const targetUsername = targetClaims['http://lfx.dev/claims/username'] || '';
  return {
    sub: targetClaims.sub,
    username: targetUsername,
    'https://sso.linuxfoundation.org/claims/username': targetUsername,
    preferred_username: targetUsername,
    nickname: targetUsername,
    // ...
  };
}

getUsernameFromAuth() naming. For Authelia tokens it returns preferred_username; for Auth0 tokens it falls back to getEffectiveUsername(req). The name is still easy to misread β€” prefer getEffectiveUsername directly when you need the LFID handle.

When to use which

Use case Use
Calling an upstream microservice / query-service API that keys on the LF login handle username
Persisting an author/owner/creator (creator_id, role grants, changelog viewer) username
Analytics / observability user identity (DataDog RUM, OpenFeature targeting key) username
Per-caller cache keys for user-scoped data username
An indefinitely-retained log line recording who took an action sub

Default to username. sub has been phased out of backend identity references and no upstream currently requires it β€” see the migration note below. The one deliberate exception is structured server log metadata meant to persist indefinitely (distinct from the client-side RUM/OpenFeature identity row above, which stays username): username is a human-readable LFID handle, and putting it in a durably-retained log stream is exactly the PII exposure docs/reviews/knowledge-base/security.md's security/pii-in-logs-and-identifiers warns against (see weekly-brief.service.ts's rating_recorded/share_weekly_brief_slack_sent log calls). This carve-out is scoped to backend log metadata specifically β€” it does not extend to upstream calls, cache keys, persisted records, or client-side analytics identity, all of which still use username.

Server-side helpers (impersonation-aware)

Prefer the impersonation-aware helpers in apps/lfx-one/src/server/utils/auth-helper.ts when resolving effective caller identity (author/owner, cache keys, upstream params) instead of reading directly off req.oidc.user. They transparently return the target user's identity during impersonation and the session user's otherwise. Session-scoped enrichment that does not need impersonation swap (e.g. survey creator_id from the OIDC session) may still read req.oidc.user directly.

Helper Returns Status
getEffectiveUsername(req) Impersonated username, else the OIDC LF username claim (Authelia: preferred_username); null when absent Preferred for all new identity references, including upstream calls, cache keys, and persisted records
getEffectiveLfUsername(req) Impersonated username while impersonating, else the OIDC LF username claim; '' when that value is missing Only for comparisons against an EasyCLA CCLA's CLA Manager list, which EasyCLA matches on this claim exactly. It has no nickname / username / preferred_username fallback, so a session without the claim (for example a local Authelia session) matches no list
getEffectiveSub(req) Impersonated sub or OIDC sub @deprecated for identity references generally β€” no upstream requires the prefixed sub β€” but still the right choice for indefinitely-retained server log metadata, where username would put readable PII in the log stream
getEffectiveEmail(req) Impersonated email, else the OIDC email (lowercased) only when the ID token asserts email_verified: true; null otherwise For email-keyed lookups

Session email is an identity only when verified. getEffectiveEmail, getRawEffectiveEmail, getRealEmail and resolveUserIdentity return the session's email claim only when the same ID token carries email_verified: true; anything else (false, missing, non-boolean) resolves to null. Those emails select meeting registrants under the M2M token, vote_response/survey_response rows without filter_grants, groups.io members and Snowflake event registrations β€” lookups built to match email-only invitees who have no LFID. An unverified address does not prove ownership, so the BFF enforces the check itself rather than relying on every Auth0 connection blocking unverified logins. Never read req.oidc.user.email directly for a lookup; go through these helpers. The auth-service primary_email (user_emails.read) is the same root address and has no verified flag of its own, so callers that union it with verified alternates (badges and the newsletter reader via resolveVerifiedUserEmails, CLA) include it only when getEffectiveEmail returned non-null. The impersonation target's email is exempt: it comes from the LFX-issued impersonation token, not a user-asserted claim.

For the deliberate opposite case β€” resolving the REAL impersonator's identity/token for a write that must be attributed to the actual actor rather than the impersonation target β€” see getRealEmail/resolveRealAccessToken in impersonation.md (LFXV2-3093).

Migration: sub β†’ username

Backend identity references have migrated from the Auth0 sub to the LFID username. In this repo:

  • Front-end (ID token): DataDog RUM id, OpenFeature targetingKey, and survey creator_id now read https://sso.linuxfoundation.org/claims/username (OpenFeature no longer falls back to sub β€” existing LaunchDarkly rules keyed on sub values need updating before deploy).
  • BFF call sites: getEffectiveSub β†’ getEffectiveUsername in changelog, copilot, org-identity, org-navigation, org-lens-access, and org-membership cache keys; project.service.ts uses resolveEmailToUsername (not resolveEmailToSub) for permission and user-info lookups against the plain-LFID b2b_org_settings index.
  • Upstream matching: the platform authorization proxy (Heimdall) derives the FGA principal from the access token's username attribute (falling back to client_id@clients for M2M), not sub β€” so the Go microservices authorize on the LFID handle.
  • getEffectiveSub is annotated @deprecated in auth-helper.ts for identity references generally. Its remaining call sites fall into three kinds, not exhaustively listed: incidental auth-service/lookup holdovers that are cleanup candidates (e.g. CLA's identity/email lookups, three of profile.controller.ts's four call sites, mktg-agents' internal session-token binding β€” none require the prefixed sub upstream); one response-payload field that's a genuine getEffectiveUsername migration candidate rather than a holdover (profile.controller.ts's UserProfile.id, which the carve-out below explicitly does not cover); and a deliberate use in indefinitely-retained server log metadata (weekly-brief.service.ts), which is not a cleanup candidate β€” see the log-line carve-out in "When to use which" above.

When adding new code, use username β€” unless the value is going into an indefinitely-retained log line, in which case use sub and note why inline (mirror the existing rating_recorded/share_weekly_brief_slack_sent comments in weekly-brief.service.ts). No upstream currently requires the prefixed sub outside that log-metadata case.

πŸ— Server-Side Implementation

Auth Context Injection

The server creates an authentication context for each request and injects it into Angular's SSR:

// apps/lfx-one/src/server/server.ts
app.use('/**', (req: Request, res: Response, next: NextFunction) => {
  const auth: AuthContext = {
    authenticated: false,
    user: null,
  };

  if (req.oidc?.isAuthenticated()) {
    auth.authenticated = true;
    auth.user = req.oidc?.user as User;
  }

  angularApp
    .handle(req, {
      auth,
      providers: [
        { provide: APP_BASE_HREF, useValue: process.env['PCC_BASE_URL'] },
        { provide: REQUEST, useValue: req },
        { provide: 'RESPONSE', useValue: res },
      ],
    })
    .then((response) => {
      if (response) {
        return writeResponseToNodeResponse(response, res);
      }
      return next();
    })
    .catch((error) => {
      req.log.error({ error }, 'Error rendering Angular application');
      if (error.code === 'NOT_FOUND') {
        res.status(404).send('Not Found');
      } else if (error.code === 'UNAUTHORIZED') {
        res.status(401).send('Unauthorized');
      } else {
        res.status(500).send('Internal Server Error');
      }
    });
});

🎯 Frontend User Service

Simple Signal-Based State

// apps/lfx-one/src/app/shared/services/user.service.ts
import { Injectable, signal, WritableSignal } from '@angular/core';
import { User } from '@lfx-one/shared/interfaces';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  public authenticated: WritableSignal<boolean> = signal<boolean>(false);
  public user: WritableSignal<User | null> = signal<User | null>(null);
}

πŸ”’ Authentication Architecture

Selective Authentication Pattern

The application implements a sophisticated authentication system with multiple layers:

  1. Public Routes: Routes like /meeting and /public/api bypass authentication entirely
  2. Protected Routes: All other routes require user authentication
  3. Custom Login Flow: Enhanced login handling with URL validation and secure redirects
  4. M2M Authentication: Server-side API calls use machine-to-machine tokens
  5. Session Management: Express OpenID Connect handles user sessions automatically
  6. Auth Context Injection: Server provides authentication state to Angular SSR
  7. Client State Management: Frontend maintains authentication state using Angular signals

Auth Middleware

The unified auth middleware (apps/lfx-one/src/server/middleware/auth.middleware.ts) implements selective authentication logic using a DEFAULT_ROUTE_CONFIG array for fine-grained route-based authentication decisions:

  • Route Analysis: Examines incoming requests against route config to determine authentication requirements
  • Public Route Bypass: Allows specific routes (e.g., /meetings/, /public/api) to use optional authentication
  • Conditional Redirects: GET requests redirect to login, API requests return 401
  • Token Refresh: Automatically handles expired tokens
  • Error Handling: Provides structured authentication errors

Custom Login Handler

The system includes a custom login route (/login) that provides:

  • URL Validation: Ensures secure redirect destinations
  • State Management: Handles authentication state transitions
  • Return-to Functionality: Redirects users to their intended destination after login

Flow C CSRF State Storage (#1938)

express-openid-connect's session middleware reads the whole session once per request and blind-overwrites it on every response β€” no dirty check, no CAS. A concurrent request that loaded the session before Flow C's /auth/start wrote profileAuthState and finishes after it silently drops that write, producing invalid_state on the Auth0 callback.

AuthStateService (apps/lfx-one/src/server/services/auth-state.service.ts) sidesteps this by keying the CSRF nonce in its own short-TTL Valkey record (auth-state:v1:<nonce>, 600s TTL) instead of req.appSession, independent of SESSION_STORE_ENABLED. The callback consumes (looks up and deletes) the record by nonce and requires it belong to the authenticated user, rather than comparing against the session. When VALKEY_URL is unset, AuthStateService falls back to session-based storage so Flow C keeps working β€” that fallback retains the original race, and it also persists the issuing sub as profileAuthSub so the callback controller's same-sub check can compare against it even without Valkey (the comparison itself lives in the callback controller, not in AuthStateService).

Rollout note: this nonce cutover has two rolling-deploy/rollback incompatibilities. First, the Valkey-vs-session storage switch itself: a pod running the old code cannot read a nonce written to Valkey by a new pod, and a new pod treats an old pod's session-only nonce as an authoritative Valkey miss. Second, when Valkey is unavailable, an old pod's session-stored nonce carries no profileAuthSub β€” a new pod reading it during a mixed-version window resolves an empty sub and rejects the callback with invalid_state. Either case forces the affected login to restart. Deploying this change requires a no-overlap rollout (and rollback plan) for Flow C traffic; it does not have cross-version compatibility built in.

Flow C Email Verification, Already-Connected and Already-Linked Addresses (#4253, #5459)

ProfileController.verifyAndLinkEmail (POST /api/profile/identities/email/verify) and the pending-email replay in handleProfileAuthCallback both verify the OTP through EmailVerificationService.verifyOtp before linking. Changes to this orchestration need the authentication code owner's review.

  • Token provenance. On the configured Auth0 Flow C path, the caller's own Flow C management token (the same one later used for user_identity.link) is also sent with the OTP as user.auth_token. It is tracked separately from the link credential, so the Authelia/unconfigured fallback β€” which links with an M2M token β€” still sends the legacy tokenless { email, otp }. An M2M token is never sent to email_linking.verify: it does not resolve to the user and can fail verification. The token is resolved before the OTP request, so a missing or expired authorization returns 403 management_token_required (direct) without consuming the code.
  • Own-account no-op. With the user token, auth-service (lfx-v2-auth-service#114) replies to an address already connected to the caller with a token-free { success: true, data: { status: 'already_connected' } }. The BFF checks success === true plus that exact status before requiring id_token, and returns { success: true, status: 'already_connected', message } to the browser. That branch makes no writes: no link, gateway-token population, v1 sync, or CDP lookup/verify/reject. Any other tokenless success stays a malformed token_missing failure, including on the fallback path.
  • Callback outcome. The pending attempt is copied and deleted from the session exactly once, before any upstream call, and the code is never replayed again. The callback resolves the freshly stored token first; if it is missing, the code is not sent. The authorization-success redirect then carries a presentation-only marker: email_status=already_connected for the own-account outcome, email_status=already_linked (EMAIL_CALLBACK_ALREADY_LINKED_STATUS) when OTP verification or the identity link reports the proven address is already linked to an LFX account, or email_status=retry_required for a missing token, OTP/provider failure, malformed success, non-conflict link failure, or thrown error. An already-linked outcome stops before any follow-up write β€” no link (for a verify-time conflict), gateway-token population, v1 sync, or CDP lookup/verify β€” and is logged without resolving the owning account. A newly linked address and an authorization with no pending email add no marker. ProfileLayoutComponent reads the marker only alongside success=profile_token_obtained, ignores unknown values, shows a single notice (refreshing identities for already-connected only; Email already linked with EMAIL_ALREADY_LINKED_MESSAGE for already-linked), and strips the query while keeping the tab and fragment. A pending social connect that chains after the callback carries no email marker.
  • Linked-email support context (#5511). Only on an already-linked callback returning to /profile or its child paths, LinkedEmailSupportService stores only the caller's proven address and an expiry in Valkey for five minutes. Consumption allows up to 30 seconds of inter-pod clock skew in the upper expiry sanity check, without extending the Valkey TTL or accepting an already-expired timestamp. Its key is a digest of the authenticated subject plus a random per-return handle, under the deployment-aware email-linked-support:v1 namespace. The URL adds only email_support_context=<opaque handle> alongside the existing status; no address, OTP, token or other-account details enter it. POST /api/profile/auth/email-support-context consumes the authenticated user's matching record using atomic GETDEL and responds with { email } or {} and Cache-Control: no-store; it is blocked during impersonation. Wrong-user/attempt handles cannot read or consume another record. Missing/expired/malformed context or disabled/faulted Valkey falls back to the generic editable draft, without a replayable session fallback. Abandoned returns expire; invalid OTPs, ordinary authorization returns, chained social redirects and non-profile returns (including the allowlisted /mentorship/mentor) issue no support context. Those non-profile pages do not render the profile layout's notice or consume a handle; no mentor notice is added by this handoff. The layout captures the handle before query cleanup, waits for its keyed toast to render, then consumes the context once; it cancels on destruction and suppresses late replies after a user change. Authentication code-owner review is required for changes to this handoff.
  • Proof before disclosure. Send-code stays enumeration-safe. auth-service validates the code before any ownership lookup (lfx-v2-auth-service#113), so a linked-address conflict from verifyOtp means the caller proved the inbox. The direct endpoint returns it as a fixed 409 { success: false, error: 'email already linked', message: EMAIL_ALREADY_LINKED_MESSAGE }, held to the same EMAIL_VERIFICATION_MIN_RESPONSE_MS floor as generic 400 verification_failed responses (verification outages return 503 without that hold), and logs it without the owning account. Wrong, expired, and other unsuccessful codes stay floor-held and generic (400 verification_failed), whether or not the address is linked. A link-time conflict after a successful OTP still returns 409 with the same neutral copy and now uses the same fixed conflict log without resolving the holder. Direct verify-time conflicts bypass raw upstream debug metadata. Both 409 responses use fixed, non-identifying message copy rather than the upstream message. The verify-time error is also canonicalized to 'email already linked'; the existing link-time branch still forwards linkResponse.error unchanged.
  • Deployment prerequisite. Exposing a verify-time conflict is safe only against an auth-service that includes #113. Before releasing this BFF behavior, confirm every deployed auth-service environment runs a revision containing it; an older service could report a conflict before validating the code.
  • Local fallback limitation. Authelia and unconfigured environments stay tokenless, so they cannot report already_connected; re-adding an owned address there keeps the earlier behavior. The auth-service mock provider refuses a verify carrying user.auth_token, so local mock verification relies on the tokenless request.

Social Reconnect of an Already-Connected Identity (#4327)

ProfileController.handleSocialCallback (GET /social/callback) reports a reconnect of a social identity that already resolves to the signed-in account as a successful no-op instead of a link attempt. Changes to this orchestration need the authentication code owner's review.

  • Evidence. After every existing guard β€” return-path consumption, impersonation block, Auth0 error, CSRF state, code, management token β€” and a successful server-side code exchange that returned an id_token, the callback reads the token's sub. Only a three-segment token whose payload is an object with a nonempty string sub, exactly equal (full string) to a nonempty string req.oidc.user.sub, qualifies. Missing, empty, non-string, or malformed subjects on either side, and suffix, prefix, or case variants, fall through to the normal link path. The decode is plain JSON, not JWT signature verification; it is trusted only because the token came straight from the callback's own state-checked exchange, and it selects a presentation outcome, never authorizes a write.
  • Reconnect no-op. The match redirects to the normalized initiating page with success=identity_already_connected (IDENTITY_ALREADY_CONNECTED_STATUS) before user_identity.link. Every other subject keeps the existing outcomes: success=identity_linked, error=already_linked (non-identifying conflict), or error=link_failed. The callback performs no CDP reads or writes on any path. No subject, email, or token is added to the redirect.
  • UI ownership. The marker is a notice only, never proof of verification or ownership. ProfileIdentitiesComponent (Identities tab) and the mentorship ProfileCardComponent each show one Already connected notice in the browser, refresh identities, and strip the query; neither shows the conflict banner, and the card sends no mentorship field sync. ProfileLayoutComponent ignores the marker β€” it owns only Flow C authorization and email outcomes.
  • Ownership-matched reconciliation. The refresh is the ordinary GET /api/profile/identities. CDP verification and synthetic-identity creation happen there, based on a platform/type/value ownership match against linked auth-service identities, never on a successful callback alone. The reconnect no-op guarantee is callback-local; an identity may display as verified or remain unverified after the refresh.
  • Runtime limitation. The branch assumes the tenant returns the account's primary sub when an already-linked social identity signs in again, as Auth0 account linking documents. If a tenant returns the secondary social subject instead, the branch never fires and the reconnect keeps the earlier link-and-classify behavior.

πŸ€– Machine-to-Machine (M2M) Authentication

Architecture Overview

The M2M system enables server-side components to authenticate with external APIs:

  • Token Generation: Automatic M2M token creation for server-side requests
  • Provider Support: Compatible with both Auth0 and Authelia
  • Error Handling: Comprehensive error management for token failures
  • Logging: Structured logging for token operations

Implementation: apps/lfx-one/src/server/utils/m2m-token.util.ts

Public Endpoint Integration

Public endpoints use M2M tokens for backend API calls:

  • Token Injection: M2M tokens are automatically generated and injected into requests
  • API Authentication: Backend services receive authenticated requests
  • Transparent Operation: Public endpoints remain unauthenticated for users while maintaining security for API calls

Example: Public Meeting Controller (apps/lfx-one/src/server/controllers/public-meeting.controller.ts)

Authentication Flow Diagram

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   User Request  │───▢│  Route Analysis  │───▢│  Auth Decision  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                β”‚                        β”‚
                                β–Ό                        β–Ό
                       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                       β”‚  Public Routes   β”‚    β”‚ Protected Routesβ”‚
                       β”‚  (/meeting,      β”‚    β”‚ (all others)    β”‚
                       β”‚   /public/api)   β”‚    β”‚                 β”‚
                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                β”‚                        β”‚
                                β–Ό                        β–Ό
                       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                       β”‚   Bypass Auth    β”‚    β”‚  Check Auth     β”‚
                       β”‚   Continue to    β”‚    β”‚  Status         β”‚
                       β”‚   Handler        β”‚    β”‚                 β”‚
                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                         β”‚
                                                         β–Ό
                                                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                                β”‚  Authenticated? β”‚
                                                β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                    β”‚         β”‚
                                                   Yes       No
                                                    β”‚         β”‚
                                                    β–Ό         β–Ό
                                           β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                           β”‚   Continue  β”‚ β”‚ Redirect β”‚
                                           β”‚   to Route  β”‚ β”‚ to Login β”‚
                                           β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Logout Process

1. User accesses /logout (provided by express-openid-connect)
2. Middleware clears session and redirects to Auth0 logout
3. Auth0 clears authentication and redirects back to application

express-openid-connect's /logout route never calls next(), so any cleanup that must run on logout is registered on /logout before auth(authConfig) in server.ts:

  • clearIntercomCookies expires the Intercom messenger cookies.
  • endGatewazeSessionOnLogout revokes and deletes the user's Gatewaze host session, found from the appSession cookie alone. It waits at most 3 seconds and always calls next(), so a Gatewaze or Valkey fault can delay the LFX logout by at most 3 seconds and never fails it. See Gatewaze Host Session.

With the session store on, the legacy appSession.N chunk-cookie cleanup also runs before auth() for the same reason.

πŸ›‘ Security Features

Built-in Security

  • CSRF Protection: Handled by express-openid-connect
  • Session Security: Secure session management
  • Token Validation: Automatic JWT validation
  • Secure Redirects: Safe redirect handling

Configuration Security

  • Environment Variables: All sensitive config in environment variables
  • Fallback Values: Safe fallback values for development
  • Signing Algorithm: HS256 token signing specified
  • Scope Configuration: Minimal required scopes defined

πŸ”„ Error Handling

Server Error Handling

// Error handling in the main request handler
.catch((error) => {
  req.log.error({ error }, 'Error rendering Angular application');
  if (error.code === 'NOT_FOUND') {
    res.status(404).send('Not Found');
  } else if (error.code === 'UNAUTHORIZED') {
    res.status(401).send('Unauthorized');
  } else {
    res.status(500).send('Internal Server Error');
  }
});

πŸ“Š What's Implemented

  • Dual authentication: user auth (Auth0/Authelia) + M2M tokens for server-side API calls
  • Selective route protection with public route bypass (/meeting, /public/api)
  • Custom login flow with URL validation and secure redirects
  • Server-side auth context injection into Angular SSR
  • Bearer token middleware for API routes
  • Public meeting access with optional passcode