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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 68x 68x 68x 68x 68x 67x 67x 67x 1x 66x 2x 64x 63x 1x 62x 1x 61x 2x 59x 59x 59x 59x 59x 59x 59x 1x 58x 58x 58x 58x 29x 29x 2x 56x 56x 2x 54x 54x 2x 52x 52x 4x 48x 48x 3x 45x 2x 2x 1x 44x 44x 43x 1x 42x 1x 41x 40x 1x 39x 39x 39x 39x 39x 1x 39x 39x 39x 3x 3x 1x | const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { permissionChecker } = require('../utils/PermissionChecker')
const { validateWorkflowTransitions } = require('./workflow-transitions')
const { withoutReservedKeys } = require('./reservedKeys')
const { MAX_ITEM_SIZE_BYTES } = require('../utils/constants')
const {
validateMandatoryFields,
validateFieldConstraints,
validateFieldTypes
} = require('./field-validation')
const { writeItemUpdate, finishItemUpdate } = require('./itemUpdate')
const { getCreditsBalance, debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
const { S3Client } = require('@aws-sdk/client-s3')
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const s3Client = new S3Client({ region: 'eu-central-1' })
// 409: the item changed since the caller loaded it
function itemModifiedResponse(updatedAt) {
return {
statusCode: 409,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'ITEM_MODIFIED', ...(updatedAt ? { updatedAt } : {}) })
}
}
const updateItemHandler = async (event) => {
try {
const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
const entityId = event.pathParameters?.entityId
const id = event.pathParameters?.itemId
const body = JSON.parse(event.body || '{}')
const flowId = await getActiveFlowId(event)
// This endpoint only ever goes through the Cognito authorizer (no
// API-key support here, unlike items/create.js), so the billing user is
// always the caller's own JWT sub claim.
const billingUserId = event.requestContext?.authorizer?.claims?.sub
if (!flowId) {
return {
statusCode: 401,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Missing flow context' })
}
}
if (!entityId || !id) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Missing entityId or id' })
}
}
// Verify item exists and ownership
const result = await docClient.send(
new GetCommand({
TableName: process.env.TABLE_NAME,
Key: { entityId, id }
})
)
if (!result.Item) {
return {
statusCode: 404,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Item not found' })
}
}
// Optimistic concurrency: a client sending the `updatedAt` it loaded is
// told when the item changed since — by someone else or by an automatic
// transition — instead of overwriting it with a stale form.
if (
body.expectedUpdatedAt !== undefined &&
body.expectedUpdatedAt !== (result.Item.updatedAt ?? null)
) {
return itemModifiedResponse(result.Item.updatedAt)
}
// Only owner flow can update
if (result.Item.flowId !== flowId) {
return {
statusCode: 403,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Access denied - only owner can update' })
}
}
// Fetch entity to get field definitions for uniqueness validation
const entityResult = await docClient.send(
new GetCommand({
TableName: process.env.ENTITIES_TABLE_NAME,
Key: { id: entityId }
})
)
const fields = entityResult.Item?.fields || []
const data = body.data || {}
// Reserved/auto-managed keys are never accepted from the client, even if
// present in `data` — filtered out up front so downstream validation, the
// update expression, and the reconstructed response all agree on exactly
// what changed.
const filteredData = withoutReservedKeys(data)
// Validate against the merged final state (existing item overridden by
// whatever is present in this request), so a partial update that never
// touches a mandatory field isn't rejected, but clearing one is.
const mergedData = { ...result.Item, ...filteredData }
const mergedDataSizeBytes = Buffer.byteLength(JSON.stringify(mergedData))
if (mergedDataSizeBytes > MAX_ITEM_SIZE_BYTES) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: 'ITEM_TOO_LARGE',
maxBytes: MAX_ITEM_SIZE_BYTES,
actualBytes: mergedDataSizeBytes
})
}
}
// Storage-credit preflight: only the *growth* in serialized size is
// charged — an update that shrinks or leaves size unchanged costs 0
// dynamodb_storage credits (no refund on shrink, but no charge either).
// The exact dynamodb_throughput cost is only known after the write
// below actually happens — see the debit after the transaction
// succeeds. See docs/architecture/USAGE_METERING.md "DynamoDB storage
// credits".
const previousDataSizeBytes = Buffer.byteLength(JSON.stringify(result.Item))
const growthBytes = Math.max(0, mergedDataSizeBytes - previousDataSizeBytes)
const storageCreditDelta = Math.ceil(
(growthBytes / 1024) * pricing.dynamodb_storage_credits_per_kb
)
if (storageCreditDelta > 0) {
const { balance: creditsBalance, isPlatformAdmin } = billingUserId
? await getCreditsBalance(docClient, process.env.USERS_TABLE_NAME, billingUserId)
: { balance: 0, isPlatformAdmin: false }
if (!billingUserId || (!isPlatformAdmin && creditsBalance < storageCreditDelta)) {
return {
statusCode: 402,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: 'INSUFFICIENT_CREDITS',
required: storageCreditDelta,
balance: creditsBalance
})
}
}
}
const mandatoryCheck = validateMandatoryFields(fields, mergedData)
if (!mandatoryCheck.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'MANDATORY_FIELD_MISSING', fieldId: mandatoryCheck.fieldId })
}
}
// Validate max length / max line count against the merged final state
const constraintsCheck = validateFieldConstraints(fields, mergedData)
if (!constraintsCheck.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: constraintsCheck.error, fieldId: constraintsCheck.fieldId })
}
}
// Validate type/shape correctness against the merged final state
const typeCheck = validateFieldTypes(fields, mergedData)
if (!typeCheck.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: typeCheck.error, fieldId: typeCheck.fieldId })
}
}
// Workflow state changes must follow a defined transition, and a protected
// transition needs its own permission on top of items:update.
const transitionCheck = validateWorkflowTransitions(fields, result.Item, filteredData, entityId)
if (!transitionCheck.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: transitionCheck.error, fieldId: transitionCheck.fieldId })
}
}
for (const required of transitionCheck.requiredPermissions) {
const permission = await permissionChecker.hasPermission(billingUserId, flowId, required, {
entity: entityResult.Item || null
})
if (!permission.hasPermission) {
return {
statusCode: 403,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Forbidden - Insufficient permissions', required })
}
}
}
const updatedAt = new Date().toISOString()
const written = await writeItemUpdate({
docClient,
itemsTableName: process.env.TABLE_NAME,
entityId,
existing: result.Item,
fields,
changes: filteredData,
actor: billingUserId,
flowId,
now: updatedAt
})
if (written.status === 'invalid') {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: written.error,
fieldId: written.fieldId,
referenceType: written.referenceType
})
}
}
if (written.status === 'empty') {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'No fields to update' })
}
}
if (written.status === 'modified') return itemModifiedResponse(undefined)
if (written.status === 'conflict') {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'UNIQUE_FIELD_CONFLICT', fieldId: written.fieldId })
}
}
// The item is now durably updated — debit credits for the real cost:
// the storage-growth delta finalized above (0 if the item didn't grow),
// and throughput now known exactly from every DynamoDB call this
// invocation made, via the SDK patch in shared/usage-tracking.js.
// Best-effort from here: a failure doesn't unwind the write, it only
// means this write went unbilled — see
// docs/architecture/USAGE_METERING.md "DynamoDB storage credits" for why
// that's an accepted, bounded gap rather than something to retry/block on.
Eif (billingUserId) {
try {
const { writeUnits } = getConsumedCapacity()
const throughputCreditCost = Math.ceil(
writeUnits * pricing.dynamodb_throughput_credits_per_wru
)
await debitCredits(docClient, {
usersTableName: process.env.USERS_TABLE_NAME,
creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
userId: billingUserId,
flowId,
charges: [
{
pool: 'dynamodb_storage',
operation: 'item_update',
costCredits: storageCreditDelta,
referenceId: id
},
{
pool: 'dynamodb_throughput',
operation: 'item_update',
costCredits: throughputCreditCost,
referenceId: id
}
]
})
} catch (creditError) {
console.error('Failed to debit credits for item update:', creditError)
}
}
const updatedItem = written.item
await finishItemUpdate({
docClient,
s3Client,
entityId,
existing: result.Item,
fields,
item: updatedItem,
flowId
})
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(updatedItem)
}
} catch (error) {
console.error('Error:', error)
return {
statusCode: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Failed to update item' })
}
}
}
// Wrap with permission check: require 'entities-{entityId}:items:update' permission
exports.handler = requirePermission(updateItemHandler, {
permission: (event) => `entities-${event.pathParameters?.entityId}:items:update`
})
|