All files / deployment validateReleaseArtifact.ts

100% Statements 286/286
100% Branches 76/76
100% Functions 10/10
100% Lines 286/286

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 2871x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 27x 27x 27x 69x 69x 69x 69x 69x 69x 67x 69x 2x 2x 2x 2x 69x 27x 27x 27x 1x 1x 2259x 2259x 2259x 2259x 2259x 1x 1x 33x 33x 33x 33x 1x 1x 33x 33x 32x 768x 32x 32x 33x 1x 1x 1x 1x 33x 33x 31x 217x 31x 31x 31x 31x 62x 62x 62x 31x 31x 31x 31x 33x 3x 3x 3x 3x 33x 33x 28x 33x 1x 1x 1x 1x 33x 33x 27x 27x 27x 27x 33x 1x 1x 1x 1x 33x 33x 26x 26x 33x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 25x 24x 26x 3x 3x 26x 26x 23x 23x 23x 22x 26x 1x 1x 26x 26x 26x 1x 1x 26x 26x 26x 26x 26x 26x 26x 1x 1x 26x 1x 1x 1x 1x 26x 20x 19x 26x 2x 2x 2x 2x 26x 1x 1x 26x 4x 4x 26x 26x 13x 13x 13x 13x 13x 26x 36x 3x 3x 36x 26x 26x 26x 1x 1x 26x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 26x 1x 1x 1x 1x 26x 29x 1x 1x 1x 1x 29x 1x 1x 1x 1x 29x 29x 27x 27x 27x 27x 29x 1x 1x 1x 1x 29x 26x 26x 3x 3x 3x 2x 26x 2x 2x 23x 23x 26x 1x 1x 2x 2x 2x 1x 1x 1x 1x 2x 1x 1x 38x 38x 38x 38x 37x 38x 38x 1x 17x 17x 2x 2x 17x 17x 15x 15x 14x 17x 17x 1x 55x 55x 55x  
import { createHash } from "node:crypto"
import { existsSync, lstatSync, readFileSync } from "node:fs"
import path from "node:path"
 
import artifactContract from "../../runtime-artifact.json" with { type: "json" }
 
export type DiscordReleaseArtifactContract = typeof artifactContract
 
export type DiscordReleaseManifest = {
  architecture: string
  artifactContractVersion: number
  artifactValidatorEntrypoint: string
  buildTimestamp: string
  commandFingerprint: string
  commandRegistrationEntrypoint: string
  commitSha: string
  criticalFileSha256: Record<string, string>
  nodeVersion: string
  platform: string
  runtimeEntrypoint: string
}
 
type ValidateReleaseArtifactOptions = {
  expectedPlatform: string
  expectedSha: string
}
 
const SHA_PATTERN = /^[0-9a-f]{40}$/
const SHA256_PATTERN = /^[0-9a-f]{64}$/
const BUILD_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/
 
function resolveRegularArtifactFile(
  artifactRoot: string,
  relativePath: string
): string {
  const segments = relativePath.split("/")
  let currentPath = path.resolve(artifactRoot)
 
  for (const [index, segment] of segments.entries()) {
    currentPath = path.join(currentPath, segment)
    const currentStat = lstatSync(currentPath, { throwIfNoEntry: false })
    const isLast = index === segments.length - 1
    if (
      currentStat === undefined ||
      currentStat.isSymbolicLink() ||
      (isLast ? !currentStat.isFile() : !currentStat.isDirectory())
    ) {
      throw new Error(
        `Discord release critical file must use regular non-symlink path components: ${relativePath}`
      )
    }
  }
 
  return currentPath
}
 
export function resolveArtifactPath(
  artifactRoot: string,
  relativePath: string
): string {
  return path.resolve(artifactRoot, ...relativePath.split("/"))
}
 
export function validateReleaseArtifactDirectory(
  artifactRoot: string,
  { expectedPlatform, expectedSha }: ValidateReleaseArtifactOptions
): DiscordReleaseArtifactContract {
  if (!SHA_PATTERN.test(expectedSha)) {
    throw new Error(`Expected release SHA is invalid: ${expectedSha}`)
  }
 
  const missingFiles = artifactContract.requiredFiles.filter(
    (relativePath) =>
      !existsSync(resolveArtifactPath(artifactRoot, relativePath))
  )
 
  if (missingFiles.length > 0) {
    throw new Error(
      `Discord release artifact is missing required files: ${missingFiles.join(", ")}`
    )
  }
 
  const forbiddenFiles = artifactContract.forbiddenFiles.filter(
    (relativePath) =>
      existsSync(resolveArtifactPath(artifactRoot, relativePath))
  )
 
  const forbiddenPathPrefixes = artifactContract.forbiddenPathPrefixes.filter(
    (relativePath) =>
      lstatSync(resolveArtifactPath(artifactRoot, relativePath.slice(0, -1)), {
        throwIfNoEntry: false,
      }) !== undefined
  )
 
  const forbiddenPaths = [...forbiddenFiles, ...forbiddenPathPrefixes]
 
  if (forbiddenPaths.length > 0) {
    throw new Error(
      `Discord release artifact contains forbidden production files: ${forbiddenPaths.join(", ")}`
    )
  }
 
  const artifactSha = readArtifactMarker(artifactRoot, ".cleo-release-sha")
 
  if (artifactSha !== expectedSha) {
    throw new Error(
      `Discord release artifact SHA ${artifactSha} does not match ${expectedSha}`
    )
  }
 
  const artifactPlatform = readArtifactMarker(
    artifactRoot,
    ".cleo-release-platform"
  )
 
  if (artifactPlatform !== expectedPlatform) {
    throw new Error(
      `Discord release platform ${artifactPlatform} does not match ${expectedPlatform}`
    )
  }
 
  validateReleaseManifest(artifactRoot, { expectedPlatform, expectedSha })
 
  return artifactContract
}
 
export function readReleaseManifest(
  artifactRoot: string
): DiscordReleaseManifest {
  const manifestPath = resolveArtifactPath(
    artifactRoot,
    artifactContract.releaseManifest
  )
  const parsedManifest = JSON.parse(readFileSync(manifestPath, "utf8")) as unknown
  if (
    typeof parsedManifest !== "object" ||
    parsedManifest === null ||
    Array.isArray(parsedManifest)
  ) {
    throw new Error("Discord release manifest must be a JSON object")
  }
 
  const manifest = parsedManifest as DiscordReleaseManifest
  if (
    typeof manifest.criticalFileSha256 !== "object" ||
    manifest.criticalFileSha256 === null ||
    Array.isArray(manifest.criticalFileSha256)
  ) {
    throw new Error("Discord release manifest critical file hashes are invalid")
  }
 
  return manifest
}
 
export function validateReleaseManifest(
  artifactRoot: string,
  { expectedPlatform, expectedSha }: ValidateReleaseArtifactOptions
): DiscordReleaseManifest {
  const manifest = readReleaseManifest(artifactRoot)
  const [platform, architecture] = expectedPlatform.split("-", 2)
 
  if (manifest.artifactContractVersion !== artifactContract.schemaVersion) {
    throw new Error("Discord release manifest contract version is invalid")
  }
  if (manifest.commitSha !== expectedSha) {
    throw new Error(
      `Discord release manifest SHA ${manifest.commitSha} does not match ${expectedSha}`
    )
  }
  if (
    manifest.platform !== platform ||
    manifest.architecture !== architecture
  ) {
    throw new Error(
      `Discord release manifest platform ${manifest.platform}-${manifest.architecture} does not match ${expectedPlatform}`
    )
  }
  if (!/^\d+\.\d+\.\d+$/.test(manifest.nodeVersion)) {
    throw new Error("Discord release manifest Node version is invalid")
  }
  if (!isCanonicalBuildTimestamp(manifest.buildTimestamp)) {
    throw new Error("Discord release manifest build timestamp is invalid")
  }
 
  const expectedEntrypoints = {
    artifactValidatorEntrypoint: artifactContract.artifactValidatorEntrypoint,
    commandRegistrationEntrypoint:
      artifactContract.commandRegistrationEntrypoint,
    runtimeEntrypoint: artifactContract.runtimeEntrypoint,
  }
  for (const [key, expectedValue] of Object.entries(expectedEntrypoints)) {
    if (manifest[key as keyof typeof expectedEntrypoints] !== expectedValue) {
      throw new Error(`Discord release manifest ${key} is invalid`)
    }
  }
 
  const criticalEntries = Object.entries(manifest.criticalFileSha256)
  if (criticalEntries.length === 0) {
    throw new Error("Discord release manifest has no critical file hashes")
  }
  const expectedCriticalPaths = [
    artifactContract.runtimeEntrypoint,
    `${artifactContract.runtimeEntrypoint}.map`,
    artifactContract.commandRegistrationEntrypoint,
    `${artifactContract.commandRegistrationEntrypoint}.map`,
    artifactContract.artifactValidatorEntrypoint,
    `${artifactContract.artifactValidatorEntrypoint}.map`,
  ]
  const missingCriticalHashes = expectedCriticalPaths.filter(
    (relativePath) => manifest.criticalFileSha256[relativePath] === undefined
  )
  if (missingCriticalHashes.length > 0) {
    throw new Error(
      `Discord release manifest is missing critical hashes: ${missingCriticalHashes.join(", ")}`
    )
  }
  for (const [relativePath, expectedHash] of criticalEntries) {
    if (!isSafeArchivePath(relativePath)) {
      throw new Error(
        `Discord release manifest path is unsafe: ${relativePath}`
      )
    }
    if (!SHA256_PATTERN.test(expectedHash)) {
      throw new Error(
        `Discord release manifest hash is invalid: ${relativePath}`
      )
    }
 
    const criticalPath = resolveRegularArtifactFile(artifactRoot, relativePath)
 
    const actualHash = createHash("sha256")
      .update(readFileSync(criticalPath))
      .digest("hex")
    if (actualHash !== expectedHash) {
      throw new Error(
        `Discord release critical file hash mismatch: ${relativePath}`
      )
    }
  }
 
  const commandHash =
    manifest.criticalFileSha256[artifactContract.commandRegistrationEntrypoint]
  if (
    !SHA256_PATTERN.test(manifest.commandFingerprint) ||
    manifest.commandFingerprint !== commandHash
  ) {
    throw new Error("Discord release command fingerprint is invalid")
  }
 
  return manifest
}
 
export function assertSafeArchivePaths(entries: readonly string[]): void {
  const unsafePaths = entries.filter((entry) => !isSafeArchivePath(entry))
 
  if (unsafePaths.length > 0) {
    throw new Error(
      `Discord release archive contains unsafe paths: ${unsafePaths.join(", ")}`
    )
  }
}
 
export function isSafeArchivePath(entry: string): boolean {
  const normalizedEntry = entry.replaceAll("\\", "/")
 
  return (
    !normalizedEntry.startsWith("/") &&
    normalizedEntry.split("/").every((segment) => segment !== "..")
  )
}
 
function isCanonicalBuildTimestamp(value: unknown): value is string {
  if (typeof value !== "string" || !BUILD_TIMESTAMP_PATTERN.test(value)) {
    return false
  }
 
  const parsed = Date.parse(value)
  return (
    !Number.isNaN(parsed) &&
    new Date(parsed).toISOString() === `${value.slice(0, -1)}.000Z`
  )
}
 
function readArtifactMarker(artifactRoot: string, marker: string): string {
  return readFileSync(resolveArtifactPath(artifactRoot, marker), "utf8").trim()
}