|
| 1 | +import * as crypto from 'node:crypto'; |
| 2 | +import type { CloudFormationTemplate } from './cloudformation'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Computes the digest for each resource in the template. |
| 6 | + * |
| 7 | + * Conceptually, the digest is computed as: |
| 8 | + * |
| 9 | + * digest(resource) = hash(type + properties + dependencies.map(d)) |
| 10 | + * |
| 11 | + * where `hash` is a cryptographic hash function. In other words, the digest of a |
| 12 | + * resource is computed from its type, its own properties (that is, excluding |
| 13 | + * properties that refer to other resources), and the digests of each of its |
| 14 | + * dependencies. |
| 15 | + * |
| 16 | + * The digest of a resource, defined recursively this way, remains stable even if |
| 17 | + * one or more of its dependencies gets renamed. Since the resources in a |
| 18 | + * CloudFormation template form a directed acyclic graph, this function is |
| 19 | + * well-defined. |
| 20 | + */ |
| 21 | +export function computeResourceDigests(template: CloudFormationTemplate): Record<string, string> { |
| 22 | + const resources = template.Resources || {}; |
| 23 | + const graph: Record<string, Set<string>> = {}; |
| 24 | + const reverseGraph: Record<string, Set<string>> = {}; |
| 25 | + |
| 26 | + // 1. Build adjacency lists |
| 27 | + for (const id of Object.keys(resources)) { |
| 28 | + graph[id] = new Set(); |
| 29 | + reverseGraph[id] = new Set(); |
| 30 | + } |
| 31 | + |
| 32 | + // 2. Detect dependencies by searching for Ref/Fn::GetAtt |
| 33 | + const findDependencies = (value: any): string[] => { |
| 34 | + if (!value || typeof value !== 'object') return []; |
| 35 | + if (Array.isArray(value)) { |
| 36 | + return value.flatMap(findDependencies); |
| 37 | + } |
| 38 | + if ('Ref' in value) { |
| 39 | + return [value.Ref]; |
| 40 | + } |
| 41 | + if ('Fn::GetAtt' in value) { |
| 42 | + const refTarget = Array.isArray(value['Fn::GetAtt']) ? value['Fn::GetAtt'][0] : value['Fn::GetAtt'].split('.')[0]; |
| 43 | + return [refTarget]; |
| 44 | + } |
| 45 | + if ('DependsOn' in value) { |
| 46 | + return [value.DependsOn]; |
| 47 | + } |
| 48 | + return Object.values(value).flatMap(findDependencies); |
| 49 | + }; |
| 50 | + |
| 51 | + for (const [id, res] of Object.entries(resources)) { |
| 52 | + const deps = findDependencies(res || {}); |
| 53 | + for (const dep of deps) { |
| 54 | + if (dep in resources && dep !== id) { |
| 55 | + graph[id].add(dep); |
| 56 | + reverseGraph[dep].add(id); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // 3. Topological sort |
| 62 | + const outDegree = Object.keys(graph).reduce((acc, k) => { |
| 63 | + acc[k] = graph[k].size; |
| 64 | + return acc; |
| 65 | + }, {} as Record<string, number>); |
| 66 | + |
| 67 | + const queue = Object.keys(outDegree).filter((k) => outDegree[k] === 0); |
| 68 | + const order: string[] = []; |
| 69 | + |
| 70 | + while (queue.length > 0) { |
| 71 | + const node = queue.shift()!; |
| 72 | + order.push(node); |
| 73 | + for (const nxt of reverseGraph[node]) { |
| 74 | + outDegree[nxt]--; |
| 75 | + if (outDegree[nxt] === 0) { |
| 76 | + queue.push(nxt); |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + // 4. Compute digests in sorted order |
| 82 | + const result: Record<string, string> = {}; |
| 83 | + for (const id of order) { |
| 84 | + const resource = resources[id]; |
| 85 | + const depDigests = Array.from(graph[id]).map((d) => result[d]); |
| 86 | + const propsWithoutRefs = hashObject(stripReferences(stripConstructPath(resource))); |
| 87 | + const toHash = resource.Type + propsWithoutRefs + depDigests.join(''); |
| 88 | + result[id] = crypto.createHash('sha256').update(toHash).digest('hex'); |
| 89 | + } |
| 90 | + |
| 91 | + return result; |
| 92 | +} |
| 93 | + |
| 94 | +export function hashObject(obj: any): string { |
| 95 | + const hash = crypto.createHash('sha256'); |
| 96 | + |
| 97 | + function addToHash(value: any) { |
| 98 | + if (value == null) { |
| 99 | + addToHash('null'); |
| 100 | + } else if (typeof value === 'object') { |
| 101 | + if (Array.isArray(value)) { |
| 102 | + value.forEach(addToHash); |
| 103 | + } else { |
| 104 | + Object.keys(value) |
| 105 | + .sort() |
| 106 | + .forEach((key) => { |
| 107 | + hash.update(key); |
| 108 | + addToHash(value[key]); |
| 109 | + }); |
| 110 | + } |
| 111 | + } else { |
| 112 | + hash.update(typeof value + value.toString()); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + addToHash(obj); |
| 117 | + return hash.digest('hex'); |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Removes sub-properties containing Ref or Fn::GetAtt to avoid hashing |
| 122 | + * references themselves but keeps the property structure. |
| 123 | + */ |
| 124 | +function stripReferences(value: any): any { |
| 125 | + if (!value || typeof value !== 'object') return value; |
| 126 | + if (Array.isArray(value)) { |
| 127 | + return value.map(stripReferences); |
| 128 | + } |
| 129 | + if ('Ref' in value) { |
| 130 | + return { __cloud_ref__: 'Ref' }; |
| 131 | + } |
| 132 | + if ('Fn::GetAtt' in value) { |
| 133 | + return { __cloud_ref__: 'Fn::GetAtt' }; |
| 134 | + } |
| 135 | + if ('DependsOn' in value) { |
| 136 | + return { __cloud_ref__: 'DependsOn' }; |
| 137 | + } |
| 138 | + const result: any = {}; |
| 139 | + for (const [k, v] of Object.entries(value)) { |
| 140 | + result[k] = stripReferences(v); |
| 141 | + } |
| 142 | + return result; |
| 143 | +} |
| 144 | + |
| 145 | +function stripConstructPath(resource: any): any { |
| 146 | + if (resource?.Metadata?.['aws:cdk:path'] == null) { |
| 147 | + return resource; |
| 148 | + } |
| 149 | + |
| 150 | + const copy = JSON.parse(JSON.stringify(resource)); |
| 151 | + delete copy.Metadata['aws:cdk:path']; |
| 152 | + return copy; |
| 153 | +} |
0 commit comments