Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

22.4 KB
Raw Blame
#!/usr/bin/env node

// Consolidated auth + connectivity pre-flight. Runs every check a skill needs before it touches an
// environment, so the agent gets one structured result instead of stringing together shell commands.
//
// This file ships byte for byte in model-apps and in pcf (scripts/validate-plugin-copies.js keeps the two
// equal), and the steps that run `pac` differ between them. Nothing it prints is therefore worded for one
// plugin's flows: the text states the rule that holds in both — only a step that runs `pac` needs the pac
// login — and the skill that ran the check knows which of its steps those are.
//
// Usage:
//   node check-auth.js [--env <envUrl>] [<envUrl>] [--require-pac]
//
// The env URL may be passed as `--env <url>` (the flag build/verify/teardown use) or positionally;
// if omitted, the script tries to read it from `pac org who`. Pass `--require-pac` when the next steps run
// `pac` (model-apps' genpage and pcf's push and package paths do) to make a missing pac login a hard blocker;
// without it (model-apps' app-builder, pcf's verification and inventory), pac is only a warning.
//
// Output (stdout JSON, exit 0 even on auth failure — failures are in the fields):
//   {
//     "ok": true|false,
//     "blocker": null | "az_missing" | "az_not_logged_in" | "az_timeout" | "pac_not_logged_in" | "pac_timeout"
//                     | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error" | "no_customization_role",
//     "message": "human-readable next step",
//     "warnings": ["..."],
//     "azUser": "...",
//     "pacUser": "...",
//     "envUrl": "...",
//     "identitiesMatch": true|false,
//     "whoAmI": { "ok": true, "userId": "...", "organizationId": "..." }
//   }
//
// PAC login is NOT required to pass unless the caller asks for it (--require-pac): a flow that
// authenticates to Dataverse with the `az` token alone (model-apps builds, verifies and tears down through
// the SDK's az-token HttpClient; pcf verifies and inventories the same way) needs no pac login, and WhoAmI
// below is the authoritative test. PAC is only used by the steps that run it and, when --env is omitted, to
// read the environment; a missing/for-different-identity pac login is surfaced as a WARNING, not a hard
// blocker.
//
// After a passing WhoAmI one more GET (`solutions?$select=solutionid&$top=1`, the first read a build makes)
// checks the identity can read customizations: an HTTP 403 `0x80042f09` ("has not been assigned any roles")
// is `ok: false` with blocker `no_customization_role`. Any other outcome of that read is a warning only.
//
// Exit code 0 always (so callers can parse stdout). Use `ok` field to gate.

const { execFileAsync } = require('./lib/process-runner.js');
const { dataverseRequest, getAuthTokenAsync, parseArgs, validateFlags, tokenFailureKind, tokenFailureMessage } = require('./lib/dataverse-auth');
const { azTimeoutMs, azTimeoutAdvice, cliFailureKind } = require('./lib/cli-failure.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');

// `pac org who` cold-starts the PAC CLI's .NET runtime (~7 s measured on Windows), and longer on a busy
// machine; a probe that runs out of time is reported as that, never as "not logged in".
const PAC_PROBE_TIMEOUT_MS = 60000;

// What a missing pac login costs, as the warnings state it. Only a run WITHOUT --require-pac reads it: a caller
// whose next steps run `pac` passes the flag and gets a hard block instead. The wording is the rule every plugin
// that ships this file can stand behind (see the header); naming one plugin's pac steps here is what made pcf
// print model-apps' flows.
const PAC_OPTIONAL_NOTE = 'That does not block a step that signs in with the az token alone: only a step that runs `pac` needs the login, and so does reading the environment when --env is omitted.';

// The Dataverse error code of a read refused to a user who holds no security role (see the capability probe in main()).
const NO_ROLE_CODE = '0x80042f09';

// Read the env URL from either `--env <url>` (the flag the build/verify/teardown scripts use) or
// the first positional arg, so a caller can copy the `--env` form here without silently passing
// the literal string "--env" as the URL (the prior positional-only parse did exactly that).
//
// `--env` is read through the shared parseArgs, which already encodes the rule that a flag followed
// by another FLAG is boolean `true` rather than a value — so `--env --require-pac` cannot read the
// next flag as the URL.
//
// The positional fallback deliberately does NOT use parseArgs' `positional` array. parseArgs has no
// flag contract, so it cannot know `--require-pac` is a boolean switch and consumes the token after
// it as its value: `check-auth.js --require-pac <url>` would lose the URL entirely and fall back to
// `pac org who`, silently probing a different environment than the caller named. The header
// documents both orderings, and an agent assembling this command does not control the order.
function parseEnvUrl(argv) {
  const { flags } = parseArgs(argv);
  if (flags.env !== undefined) return typeof flags.env === 'string' && flags.env.trim() ? flags.env : null;
  const positional = argv.find((a) => typeof a === 'string' && !a.startsWith('--'));
  return positional || null;
}

// `{ out, failure }`: the trimmed stdout, or null with the failure's kind — 'timeout' | 'missing' |
// 'failed' (cli-failure.js). The child runs in the background so the event loop stays free to drain
// other CLI stdout and service their timeout timers while Azure CLI and PAC cold-start.
function runQuietAsync(cmd, args, timeoutMs) {
  let child = null;
  let settled = false;
  const promise = new Promise((resolve) => {
    try {
      child = execFileAsync(cmd, args, {
        encoding: 'utf8',
        timeout: timeoutMs,
        windowsHide: true,
      }, (error, stdout) => {
        settled = true;
        resolve(error ? { out: null, failure: cliFailureKind(error) } : { out: String(stdout || '').trim(), failure: null });
      });
      // execFile always opens a stdin pipe; close it (the effect of stdio 'ignore'), so a CLI that
      // checks stdin can never wait on it.
      if (child && child.stdin) child.stdin.end();
    } catch (e) {
      settled = true;
      resolve({ out: null, failure: cliFailureKind(e) });
    }
  });
  return {
    promise,
    cancel() {
      if (!settled && child && typeof child.kill === 'function') {
        child.kill();
      }
    },
  };
}

// The result is a fixed shape whose strings are not bounded: a refused WhoAmI's whole diagnostic is its `message`, and a
// mistyped flag is quoted in a usage blocker. The process exits right after this one write, so the write is made blocking
// first (lib/output-redaction.js makeWritesBlocking): on Linux and macOS a pipe would otherwise take only what fits at once.
function emit(payload) {
  makeWritesBlocking(process.stdout, process.stderr);
  process.stdout.write(JSON.stringify(payload) + '\n');
  process.exit(0);
}

function buildResult(partial) {
  const base = {
    ok: false,
    blocker: null,
    message: '',
    warnings: [],
    azUser: null,
    pacUser: null,
    envUrl: null,
    identitiesMatch: false,
    whoAmI: null,
  };
  return Object.assign(base, partial);
}

function normalizeUser(u) {
  return (u || '').trim().toLowerCase();
}

// With an explicit environment the Dataverse token needs nothing from the other probes, so it is read
// beside `az account show` instead of after it, and WhoAmI is sent the moment the token is in hand — while
// `pac org who` (the slowest cold start) is still running. Only the START times move: every verdict is still
// reached in the same order by main() (account, token timeout, pac, WhoAmI), and WhoAmI's answer is read
// only when that order gets to it.
//
// The WhoAmI outcome is captured as data — `{ res }` or `{ error }` — because it can settle long before
// main() looks at it, and a rejection nobody awaited yet would otherwise be reported as unhandled. It is
// started only when the token read SUCCEEDED: with no token in the process memo, dataverseRequest would
// run a synchronous `az` read of its own, freezing the event loop (and pac's timeout timer) mid-probe;
// that case keeps today's order, after pac.
//
// The same rule is why the early request is sent with `refreshOn401: false`. On a 401 dataverseRequest would
// replace the token with a synchronous `az` read — up to twice, seconds each on a cold Windows start — while
// `az account show` and `pac` are still running. A wrong-tenant 401 is exactly what this preflight exists to
// diagnose, so that freeze is the case that matters. The 401 is handed back instead, and main() sends WhoAmI
// again at its old place (after pac), where the refresh blocks nothing.
function warmDataverseToken(envUrl, signal) {
  const token = Promise.resolve()
    .then(() => getAuthTokenAsync(envUrl, { signal }))
    .catch(() => null);
  const whoAmI = token.then((value) => (value
    ? dataverseRequest(envUrl, 'GET', 'WhoAmI', null, { timeout: 30000, refreshOn401: false }).then((res) => ({ res }), (error) => ({ error }))
    : null));
  return { token, whoAmI };
}

async function main() {
  const argv = process.argv.slice(2);
  // This tool always exits 0 so callers can parse stdout, so a usage error is reported as a
  // structured blocker rather than a non-zero exit — a `--requir-pac` typo must not silently
  // downgrade a hard pac requirement to a warning.
  const flagError = validateFlags(argv, { known: ['env', 'require-pac'], needValue: ['env'] });
  if (flagError) {
    return emit(buildResult({
      blocker: 'usage',
      message: `${flagError}. Usage: node check-auth.js --env <url> [--require-pac]`,
    }));
  }
  let envUrl = parseEnvUrl(argv);
  // A caller whose next steps run `pac` passes --require-pac to keep a missing pac login a hard blocker
  // (model-apps' genpage discovers connections through a script that falls back to pac; pcf's push and package
  // paths run it). A caller that only needs the az token omits the flag, and a missing pac login is downgraded
  // to a warning.
  const requirePac = argv.includes('--require-pac');
  const warnings = [];

  // Every probe below is a cold CLI start. Measured on Windows: `pac org who` ~7 s, and each `az`
  // call ~3-5 s. Run one after another (az --version, az account show, pac, then az again for the
  // WhoAmI token), the preflight cost ~19 s at the start of every skill run that begins with it.
  // pac needs nothing from az, so it is started FIRST and runs while the az probes run; with an explicit
  // environment the token read and WhoAmI are independent of the account probe too (warmDataverseToken).
  const pacOrgProbe = runQuietAsync('pac', ['org', 'who'], PAC_PROBE_TIMEOUT_MS);
  const azBudget = azTimeoutMs();
  // Every probe an early verdict could leave running. A non-detached child outlives the process that
  // started it, so each early return cancels all of them — pac, and the token read started beside the
  // account probe — before it emits.
  const tokenAbort = new AbortController();
  const cancelProbes = () => {
    pacOrgProbe.cancel();
    tokenAbort.abort();
  };
  // A slow Azure CLI is reported as slow — neither "not installed" nor "not logged in" is true of it,
  // and sending the user to reinstall or `az login` fixes nothing.
  const azTimedOut = (command, partial = {}) => {
    cancelProbes();
    return emit(buildResult(Object.assign({ blocker: 'az_timeout', message: azTimeoutAdvice(command, azBudget) }, partial)));
  };

  // 1) az login. `az account show` answers "installed?" and "logged in?" together on the happy path,
  //    so `az --version` runs only to tell those two failures apart — and not at all when the runner
  //    already found no `az` on PATH.
  const accountProbe = runQuietAsync('az', ['account', 'show', '--query', 'user.name', '-o', 'tsv'], azBudget);
  // Started with the account probe, awaited after it: the verdict order below is unchanged.
  const warm = envUrl ? warmDataverseToken(envUrl, tokenAbort.signal) : null;
  const account = await accountProbe.promise;
  const azUser = account.out;
  if (!azUser) {
    if (account.failure === 'timeout') return azTimedOut('az account show');
    const version = account.failure === 'missing' ? account : await runQuietAsync('az', ['--version'], azBudget).promise;
    if (version.failure === 'timeout') return azTimedOut('az --version');
    if (version.out == null) {
      // This branch returns before the pac probe is awaited. Kill the child explicitly so a
      // non-detached PAC process cannot outlive the preflight after its parent exits.
      cancelProbes();
      return emit(
        buildResult({
          blocker: 'az_missing',
          message: 'Azure CLI (`az`) is not installed. Install it from https://aka.ms/azure-cli and run `az login`.',
        })
      );
    }
    // Same early-return hazard as az_missing: once we know az is installed but logged out, the
    // pending PAC result cannot affect this verdict, so cancel it before emitting.
    cancelProbes();
    return emit(
      buildResult({
        blocker: 'az_not_logged_in',
        message: 'Azure CLI is installed but not logged in. Run `az login` with the same identity as your active `pac auth` profile.',
      })
    );
  }

  // The WhoAmI token, read while pac is still running. getAuthToken memoizes per process, so the
  // dataverseRequest below reuses it instead of paying another az cold start after pac returns. A
  // failure here is not reported: WhoAmI acquires again and reports it with the right blocker — except
  // a TIMEOUT, which WhoAmI's own attempt would only repeat, doubling the wait before saying so.
  if (warm) {
    const warmed = await warm.token;
    if (!warmed && tokenFailureKind(envUrl) === 'timeout') {
      return azTimedOut('az account get-access-token', { azUser, envUrl, warnings, message: tokenFailureMessage(envUrl, '') });
    }
  }

  // 2) pac user + env URL (best-effort — a pac login is NOT required unless the caller passed --require-pac)
  const pacProbe = await pacOrgProbe.promise;
  const pacOrg = pacProbe.out;
  const pacSlow = pacProbe.failure === 'timeout';
  let pacUser = null;
  if (pacOrg) {
    const m = pacOrg.match(/Connected as\s+([^\s\r\n]+)/i);
    if (m) pacUser = m[1];
    if (!envUrl) {
      const urlMatch = pacOrg.match(/Org URL:\s*(https:\/\/[^\s]+)/i);
      if (urlMatch) envUrl = urlMatch[1].replace(/\/+$/, '');
    }
  }
  if (!pacUser) {
    const slowPac = `\`pac org who\` did not answer within ${PAC_PROBE_TIMEOUT_MS / 1000} s — the PAC CLI can be that slow to start on a busy machine, so its login is unknown, not missing`;
    if (requirePac) {
      // The caller passed --require-pac because its next steps run pac, so keep the hard block.
      return emit(
        buildResult({
          azUser,
          envUrl,
          warnings,
          blocker: pacSlow ? 'pac_timeout' : 'pac_not_logged_in',
          message: pacSlow ? `${slowPac}. Retry.` : 'PAC CLI is not logged in. Run `pac auth create --environment <url>` to authenticate.',
        })
      );
    }
    // No --require-pac: not a blocker. The caller authenticates with the az token, and pac is used only by a step that
    // runs it and to read the environment when --env is omitted. Warn so a later pac step is not a surprise.
    warnings.push(pacSlow
      ? `${slowPac}. ${PAC_OPTIONAL_NOTE}`
      : `PAC CLI is not logged in. ${PAC_OPTIONAL_NOTE} Run \`pac auth create --environment <url>\` before such a step.`);
  }
  if (!envUrl) {
    return emit(
      buildResult({
        azUser,
        pacUser,
        warnings,
        blocker: 'no_env_url',
        message: 'Could not determine the Dataverse environment URL. Pass it as `--env <url>` (or the first argument), or set the active pac profile to an env.',
      })
    );
  }

  // Identity match only applies when pac is actually logged in.
  const identitiesMatch = pacUser ? normalizeUser(azUser) === normalizeUser(pacUser) : false;

  // 3) WhoAmI — authoritative test. Already in flight (or answered) when the token was read early, in
  //    which case its outcome is only READ here, after every verdict above; otherwise it is sent now. An early
  //    401 is not taken as the answer: that request could not refresh the token without freezing the probes
  //    still running (see warmDataverseToken), so it is sent again here, with the refresh, as it always was.
  let whoRes;
  try {
    const early = warm ? await warm.whoAmI : null;
    if (early && early.error) throw early.error;
    whoRes = early && early.res.status !== 401 ? early.res : await dataverseRequest(envUrl, 'GET', 'WhoAmI', null, { timeout: 30000 });
  } catch (e) {
    // The token for WhoAmI is read here when the env URL came from pac (nothing was warmed above); a
    // read that ran out of time is the Azure CLI being slow, not WhoAmI failing.
    const slow = tokenFailureKind(envUrl) === 'timeout';
    return emit(
      buildResult({
        azUser,
        pacUser,
        envUrl,
        identitiesMatch,
        warnings,
        blocker: slow ? 'az_timeout' : 'whoami_error',
        message: slow ? e.message : `WhoAmI probe failed: ${e.message}`,
      })
    );
  }

  if (whoRes.status === 401) {
    return emit(
      buildResult({
        azUser,
        pacUser,
        envUrl,
        identitiesMatch,
        warnings,
        blocker: 'whoami_401',
        message: 'Dataverse rejected the token (401). Run `az login` again to refresh.',
      })
    );
  }
  if (whoRes.status === 403) {
    const hint = identitiesMatch
      ? `WhoAmI returned 403 even though az and pac identities match (${azUser}). The user may need to be added to the env directly.`
      : pacUser
        ? `WhoAmI returned 403. az is signed in as "${azUser}" but pac is using "${pacUser}". Run \`az login --username ${pacUser}\` so both clients use the same identity.`
        : `WhoAmI returned 403. az is signed in as "${azUser}" but that identity lacks access to ${envUrl}. Sign in with an identity that has access, or ask an admin to add it to the environment.`;
    return emit(
      buildResult({
        azUser,
        pacUser,
        envUrl,
        identitiesMatch,
        warnings,
        whoAmI: { ok: false, status: 403, message: whoRes.data?.error?.message || '' },
        blocker: 'whoami_403',
        message: hint,
      })
    );
  }
  if (whoRes.status < 200 || whoRes.status >= 300) {
    return emit(
      buildResult({
        azUser,
        pacUser,
        envUrl,
        identitiesMatch,
        warnings,
        whoAmI: { ok: false, status: whoRes.status, message: whoRes.data?.error?.message || '' },
        blocker: 'whoami_error',
        message: `WhoAmI returned unexpected status ${whoRes.status}.`,
      })
    );
  }

  // 4) Capability probe. WhoAmI answers for ANY user the environment knows, role or not, so it said "ready" for an identity
  //    that holds no security role: every customization read then fails, and the first build step is where the maker found out.
  //    One read the build itself starts with (its solution) tells. Measured on an identity with no role:
  //      GET solutions?$select=solutionid&$top=1  ->  HTTP 403
  //      {"error":{"code":"0x80042f09","message":"The user with id <id> has not been assigned any roles. They need a role with the prvReadCustomization privilege."}}
  //    (`sitemaps`, `roles` and `publishers` answered the same.) A COUNT of the user's roles would be wrong: privileges also come
  //    through teams, so a user with no role of their own can read customizations. The code decides, never the words — the platform
  //    answers in the caller's language. Any other outcome of the probe (another 403 code, a 5xx, a transport failure) proves nothing
  //    about roles, so it is a warning and never a verdict: a false "no role" would send a working maker to an administrator.
  //    https://learn.microsoft.com/power-platform/admin/security-roles-privileges
  let probe = null;
  try {
    probe = await dataverseRequest(envUrl, 'GET', 'solutions?$select=solutionid&$top=1', null, { timeout: 30000 });
  } catch (e) {
    warnings.push(`Could not confirm the identity can read customizations (${e.message}). WhoAmI passed, so this is not taken as a missing role.`);
  }
  if (probe) {
    const probeCode = probe.data && probe.data.error && probe.data.error.code;
    if (probe.status === 403 && String(probeCode || '').toLowerCase() === NO_ROLE_CODE) {
      const otherIdentity = pacUser && !identitiesMatch
        ? ` Or sign in as the PAC user if that identity holds a role: \`az login --username ${pacUser}\`.`
        : '';
      return emit(
        buildResult({
          azUser,
          pacUser,
          envUrl,
          identitiesMatch,
          warnings,
          whoAmI: { ok: true, userId: whoRes.data?.UserId, organizationId: whoRes.data?.OrganizationId },
          blocker: 'no_customization_role',
          message: `WhoAmI passed, but "${azUser}" has no security role in ${envUrl}, so it cannot read customizations (HTTP 403 ${NO_ROLE_CODE}: the prvReadCustomization privilege is missing). Ask an environment administrator to assign a role such as System Customizer.${otherIdentity}`,
        })
      );
    }
    if (probe.status < 200 || probe.status >= 300) {
      warnings.push(`Could not confirm the identity can read customizations (HTTP ${probe.status}${probeCode ? ` ${probeCode}` : ''}). WhoAmI passed, so this is not taken as a missing role.`);
    }
  }

  // A pac probe that ran out of time says THAT here too — its warning already does, and "not logged in" beside
  // it contradicted it: a slow PAC CLI's login is unknown, not missing.
  const readyMessage = !pacUser
    ? (pacSlow
      ? `Ready (az signed in as ${azUser}, env ${envUrl}). PAC's login is unknown — \`pac org who\` did not answer in time; only a step that runs pac needs it.`
      : `Ready (az signed in as ${azUser}, env ${envUrl}). PAC is not logged in — only a step that runs pac needs it.`)
    : identitiesMatch
      ? `Ready (az + pac both signed in as ${azUser}, env ${envUrl}).`
      : `Ready, but az ("${azUser}") and pac ("${pacUser}") use different identities. WhoAmI passed so this works for now — but if a later step returns 403, run \`az login --username ${pacUser}\` to align them.`;
  return emit({
    ok: true,
    blocker: null,
    message: readyMessage,
    warnings,
    azUser,
    pacUser,
    envUrl,
    identitiesMatch,
    whoAmI: {
      ok: true,
      userId: whoRes.data?.UserId,
      organizationId: whoRes.data?.OrganizationId,
    },
  });
}

// Run only as a CLI; when required from a test, expose the pure helpers instead.
if (require.main === module) {
  main();
}

module.exports = { parseEnvUrl };