calmlens 0.28.2 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,11 +62,11 @@ module CalmLens
62
62
  'original' => 'original', 'rendered' => 'rendered', 'preview' => 'preview',
63
63
  'hls' => 'hls/index.m3u8', 'embed' => 'embed', 'placeholder' => 'placeholder', 'info' => 'info'
64
64
  }.freeze
65
- # The moderation status each `asset.<status>` event announces.
66
- ANNOUNCED_STATUSES = REVIEW_DECISIONS.to_h { |status| ["asset.#{status}", status] }.freeze
67
65
  MAX_DECISION_NOTE_LENGTH = 1499
68
- # The actor of events the mock's API key causes: mock keys have no ID.
69
- API_KEY_ACTOR = { 'type' => 'api-key', 'id' => nil }.freeze
66
+ # The ID of every mock API key ({MockServerClient::API_KEY_ID}).
67
+ API_KEY_ID = 'key_mock0000000000000000'
68
+ # The actor of the events and reviews the mock's API key causes.
69
+ API_KEY_ACTOR = { 'type' => 'api-key', 'id' => API_KEY_ID }.freeze
70
70
  # The actor of a reviewer's decision through {MockServerClient#decide}.
71
71
  REVIEWER_ACTOR = { 'type' => 'user', 'id' => nil }.freeze
72
72
  # The actor of the pipeline's processing events.
@@ -110,6 +110,12 @@ module CalmLens
110
110
  'education-support' => 'Learning and support', 'wholesome-community' => 'Teen-safe' }.freeze
111
111
  # Like the API: 1 to 255 printable ASCII characters, without a space at either end.
112
112
  IDEMPOTENCY_KEY = /\A[\x21-\x7e](?:[\x20-\x7e]{0,253}[\x21-\x7e])?\z/
113
+ # Entries with a lower PDQ quality never match (HashList.ts, HASH_MATCH_MIN_QUALITY).
114
+ HASH_MATCH_MIN_QUALITY = 50
115
+ # The most hash matches an asset records (HashList.ts).
116
+ MAX_RECORDED_HASH_MATCHES = 10
117
+ # Content types a URL upload stores nothing for: the URL is a web page, a `website` asset.
118
+ WEBSITE_TYPES = %w[text/html application/xhtml+xml].freeze
113
119
  # Content a browser could run as a document, which the CDN serves as a download.
114
120
  ACTIVE_TYPES = %w[image/svg+xml application/xhtml+xml text/html application/xml text/xml].freeze
115
121
 
@@ -168,10 +174,33 @@ module CalmLens
168
174
  @metadata_fields = []
169
175
  @settings_revision = 1
170
176
  @request_count = 0
171
- # Each asset's latest `assetSequence`, which the API keeps on the asset row.
177
+ # Each asset's latest `assetSequence`, which the API keeps on the asset row and returns as its
178
+ # `eventSequence`. Kept here as well as on stored assets, which a deleted asset's events outlive.
172
179
  @asset_event_sequences = Hash.new(0)
173
180
  # The processing options each asset was uploaded with, which the API keeps but doesn't return.
174
181
  @processing_options = {}
182
+ # Each served URL's content, by its normalized URL (see {#serve_url}).
183
+ @served_urls = {}
184
+ # The review the queue holds for each asset waiting for one, by asset ID.
185
+ @pending_reviews = {}
186
+ end
187
+
188
+ # Makes `url` answer a URL upload's fetch with `bytes` of content type `type`.
189
+ def serve_url(url, bytes, type)
190
+ key = FakeAPI.url_key(url)
191
+ raise Internal.invalid('url must be an absolute URL') unless key
192
+ raise Internal.invalid('type must be a content type, such as image/png') unless type.is_a?(String) && !type.strip.empty?
193
+ raise Internal.invalid('content must be a String of bytes') unless bytes.is_a?(String)
194
+
195
+ @served_urls[key] = { bytes: bytes.b, type: type.strip }
196
+ end
197
+
198
+ # A URL as {#serve_url} compares it, parsed and normalized; nil for one that isn't absolute.
199
+ def self.url_key(url)
200
+ uri = URI.parse(url.to_s)
201
+ uri.absolute? && uri.host ? uri.normalize.to_s : nil
202
+ rescue URI::InvalidURIError
203
+ nil
175
204
  end
176
205
 
177
206
  # Adds an event to the feed, filling the fields the API always sets. Its `actor` is the mock's
@@ -180,28 +209,21 @@ module CalmLens
180
209
  time = @now.call
181
210
  record = { 'id' => @create_id.call('evt'), 'projectId' => @project_id, 'actor' => deep_copy(API_KEY_ACTOR),
182
211
  'severity' => 'low', 'description' => nil,
183
- 'assetId' => nil, 'assetSequence' => nil, 'asset' => nil, 'facts' => [],
212
+ 'assetId' => nil, 'assetSequence' => nil, 'facts' => [],
184
213
  'createdAt' => time }.merge(event)
185
214
  record['title'] ||= record['type']
186
215
  # Like the API: each event about an asset takes the asset's next number; others have none.
187
216
  asset_id = record['assetId']
188
217
  record['assetSequence'] = asset_id ? (@asset_event_sequences[asset_id] += 1) : nil
218
+ # The asset's `eventSequence` follows, so every copy of it returned from now on has it.
219
+ stored = asset_id && @state.assets[asset_id]
220
+ stored['eventSequence'] = record['assetSequence'] if stored
189
221
  @state.events << record
190
222
  record
191
223
  end
192
224
 
193
- # Adds an event like {#add_event}; one about a stored asset carries the asset as it is now,
194
- # with the moderation status an `asset.<status>` event announces.
195
- def enqueue_event(event)
196
- item = own_asset(event['assetId'])
197
- if item && !event.key?('asset')
198
- asset = snapshot(item)
199
- announced = ANNOUNCED_STATUSES[event['type']]
200
- asset['classification']['moderation']['decision'] = announced if announced
201
- event = event.merge('asset' => asset)
202
- end
203
- add_event(event)
204
- end
225
+ # Adds an event like {#add_event}, for {MockServerClient#enqueue_event}.
226
+ def enqueue_event(event) = add_event(event)
205
227
 
206
228
  # Applies a reviewer's decision, adds the matching events and returns the asset, or nil when
207
229
  # there is no such asset. A purge removes the content with reason `requested`.
@@ -265,7 +287,7 @@ module CalmLens
265
287
 
266
288
  # Applies a reviewer's decision like `decideAssetManually` in the API: the status and the review,
267
289
  # then (for `purged`) the content removal and its event, then `asset.<decision>`. Either way the
268
- # review is the mock API key's, which has no ID. A decision through the API (`by_api_key`) has
290
+ # review is the mock API key's ({API_KEY_ID}). A decision through the API (`by_api_key`) has
269
291
  # the API key as its events' actor; the test hook's is a reviewer's (a `user`).
270
292
  def record_decision(item, decision, note, by_api_key)
271
293
  apply_outcome(item, decision, 'requested')
@@ -273,13 +295,13 @@ module CalmLens
273
295
  # leaves it waiting.
274
296
  item['classification']['moderation']['pendingReview'] = nil unless by_api_key
275
297
  review = { 'id' => @create_id.call('rev'), 'decision' => decision, 'note' => note,
276
- 'decidedBy' => { 'type' => 'api-key', 'id' => nil }, 'reviewedAt' => @now.call, 'applied' => true }
298
+ 'decidedBy' => deep_copy(API_KEY_ACTOR), 'reviewedAt' => @now.call, 'applied' => true }
277
299
  actor = by_api_key ? API_KEY_ACTOR : REVIEWER_ACTOR
278
300
  item['classification']['moderation']['manualReviews'] << review
279
301
  lifecycle_event('asset.content-removed', item, actor: actor) if decision == 'purged'
280
302
  # Like the event catalog: only allowing and limiting are low severity.
281
303
  add_event('type' => "asset.#{decision}", 'severity' => %w[allowed limited].include?(decision) ? 'low' : 'high',
282
- 'title' => "asset.#{decision}", 'assetId' => item['id'], 'asset' => snapshot(item),
304
+ 'title' => "asset.#{decision}", 'assetId' => item['id'],
283
305
  'actor' => deep_copy(actor),
284
306
  'facts' => [{ 'key' => 'asset-type', 'value' => item['type'] },
285
307
  { 'key' => 'asset-name', 'value' => item['name'], 'url' => "https://calmlens.com/go/asset/#{item['id']}" },
@@ -308,13 +330,50 @@ module CalmLens
308
330
  item
309
331
  end
310
332
 
311
- # The asset summary events carry.
312
- def snapshot(item)
313
- { 'id' => item['id'], 'externalId' => item['externalId'], 'uploadPresetId' => item['uploadPresetId'],
314
- 'upload' => { 'status' => item['upload']['status'] },
315
- 'classification' => { 'status' => item['classification']['status'], 'testInput' => item['classification']['testInput'],
316
- 'moderation' => { 'decision' => item['classification']['moderation']['decision'] } },
317
- 'content' => { 'status' => item['content']['status'] } }
333
+ # The review the queue holds for an asset, or nil when none is waiting. A review a decision left
334
+ # waiting (`pendingReview`) gets its ID the first time it is read.
335
+ def pending_review_of(item)
336
+ pending = item['classification']['moderation']['pendingReview']
337
+ unless pending
338
+ @pending_reviews.delete(item['id'])
339
+ return
340
+ end
341
+
342
+ @pending_reviews[item['id']] ||= { 'id' => @create_id.call('rev'), 'assetId' => item['id'], 'reason' => pending['reason'],
343
+ 'status' => 'pending', 'note' => nil, 'createdAt' => pending['requestedAt'] }
344
+ end
345
+
346
+ # `POST /assets/:assetId/review-requests`, like the API (publicPostAssetReviewRequest.ts and
347
+ # getReportRefusal): a held asset is `asset/held`; a child asset, an asset not yet decided, and
348
+ # a purged one or one whose content is gone are `asset/not-reviewable` with that `reason`. A
349
+ # review already waiting is returned unchanged with 200; otherwise a `reported` review joins
350
+ # the queue with 201, the asset's `pendingReview` is set and `asset.review-requested` is
351
+ # recorded with the API key as its actor.
352
+ def request_review(item, json)
353
+ fail!(ErrorCodes::ASSET_HELD, details: { 'hold' => 'safety' }) if item['content']['safetyHold']
354
+ decision = item['classification']['moderation']['decision']
355
+ reason = if item['parentId'] then 'child-asset'
356
+ elsif item['upload']['status'] == 'uploading' || item['classification']['status'] != 'completed' || decision.nil?
357
+ 'not-moderated'
358
+ elsif decision == 'purged' || item['content']['status'] == 'removed' then 'content-unavailable'
359
+ end
360
+ fail!(ErrorCodes::ASSET_NOT_REVIEWABLE, details: { 'reason' => reason }) if reason
361
+ waiting = pending_review_of(item)
362
+ return respond(200, deep_copy(waiting)) if waiting
363
+
364
+ now = @now.call
365
+ note = json['note']&.strip
366
+ review = { 'id' => @create_id.call('rev'), 'assetId' => item['id'], 'reason' => 'reported', 'status' => 'pending',
367
+ 'note' => note, 'createdAt' => now }
368
+ @pending_reviews[item['id']] = review
369
+ item['classification']['moderation']['pendingReview'] = { 'requestedAt' => now, 'reason' => 'reported',
370
+ 'uncertainCategories' => [] }
371
+ facts = [asset_name_fact(item), { 'key' => 'asset-type', 'value' => item['type'] },
372
+ { 'key' => 'review-id', 'value' => review['id'] }, { 'key' => 'automated-status', 'value' => decision },
373
+ { 'key' => 'review-reason', 'value' => 'reported' }, { 'key' => 'uncertain-categories', 'value' => [] }]
374
+ facts << { 'key' => 'note', 'value' => note } if note
375
+ add_event('type' => 'asset.review-requested', 'severity' => 'low', 'assetId' => item['id'], 'facts' => facts)
376
+ respond(201, deep_copy(review))
318
377
  end
319
378
 
320
379
  # The `asset.deleted`, `asset.content-removed` and `asset.retried` events the API records, with
@@ -325,12 +384,15 @@ module CalmLens
325
384
  name['url'] = "https://calmlens.com/go/asset/#{item['id']}" unless type == 'asset.deleted'
326
385
  facts = [name, { 'key' => 'asset-type', 'value' => item['type'] }]
327
386
  facts << { 'key' => 'batch-id', 'value' => batch_id } if batch_id
328
- add_event('type' => type, 'severity' => 'low', 'assetId' => item['id'], 'asset' => snapshot(item),
329
- 'actor' => deep_copy(actor), 'facts' => facts)
387
+ add_event('type' => type, 'severity' => 'low', 'assetId' => item['id'], 'actor' => deep_copy(actor), 'facts' => facts)
330
388
  end
331
389
 
332
390
  def fail!(code, message = nil, details: nil) = raise(Failure.new(code, message, details: details))
333
391
 
392
+ # `asset/duplicate-external-id`, naming the stored asset that holds the external ID in
393
+ # `details['assetId']`, like the API.
394
+ def duplicate_external_id!(holder) = fail!(ErrorCodes::DUPLICATE_EXTERNAL_ID, details: { 'assetId' => holder['id'] })
395
+
334
396
  def route_not_found!(method, parts) = fail!(ErrorCodes::ROUTE_NOT_FOUND, "No route for #{method} /#{parts.join('/')}")
335
397
 
336
398
  # A request the API's schema refuses: `validation/invalid-request` with HTTP 400, listing the
@@ -354,14 +416,25 @@ module CalmLens
354
416
  end
355
417
  end
356
418
 
357
- # Like the API's schema, checked before the asset is looked up: asset updates take no null name.
419
+ # Like the API's schema, checked before the asset is looked up: asset updates take no null
420
+ # name, and a review request's note is 1 to 1499 characters once trimmed.
358
421
  def check_asset_body(method, action, json)
422
+ return check_review_note(json) if method == 'POST' && action == 'review-requests'
359
423
  return unless method == 'PATCH' && action.nil?
360
424
 
361
425
  check_metadata(json['metadata'])
362
426
  invalid!('validation/invalid-type', 'name') if json.key?('name') && json['name'].nil?
363
427
  end
364
428
 
429
+ def check_review_note(json)
430
+ return unless json.key?('note')
431
+
432
+ note = json['note']
433
+ invalid!('validation/invalid-type', 'note') unless note.is_a?(String)
434
+ invalid!('validation/too-small', 'note') if note.strip.empty?
435
+ invalid!('validation/too-big', 'note') if note.strip.length > MAX_DECISION_NOTE_LENGTH
436
+ end
437
+
365
438
  # Like the API: an upload's metadata is checked, then its MIME type, which must be one the
366
439
  # API can moderate (`upload/unsupported-type` with `details.mimeType` and `details.source`).
367
440
  def check_upload(options)
@@ -392,7 +465,8 @@ module CalmLens
392
465
  # HTTP stacks trim header values, so the API sees the key without surrounding whitespace.
393
466
  key = header(headers, 'Idempotency-Key')&.to_s&.gsub(/\A[ \t\r\n]+|[ \t\r\n]+\z/, '')
394
467
  request = { query: query, json: json, body: body, upload: upload, content_type: content_type }
395
- return dispatch(method, parts, request) unless key && method == 'POST'
468
+ # Only the API's idempotent endpoints read the header.
469
+ return dispatch(method, parts, request) unless key && method == 'POST' && idempotent_route?(parts)
396
470
 
397
471
  fail!(ErrorCodes::INVALID_IDEMPOTENCY_KEY) unless key.match?(IDEMPOTENCY_KEY)
398
472
  # Like the API: a successful response is saved and replayed for the same key and request;
@@ -419,6 +493,17 @@ module CalmLens
419
493
 
420
494
  def header(headers, name) = headers.find { |key, _| key.to_s.casecmp?(name) }&.last
421
495
 
496
+ # The POST routes the API runs under an `Idempotency-Key` (`idempotent` in its request
497
+ # definitions): uploads and their parts, decisions, review requests and hash list entries.
498
+ # Others ignore the header, so a repeat runs again.
499
+ def idempotent_route?(parts)
500
+ case parts
501
+ in ['projects', String, 'assets'] | ['assets', String, 'part' | 'decision' | 'review-requests'] |
502
+ ['hash-lists', String, 'entries'] then true
503
+ else false
504
+ end
505
+ end
506
+
422
507
  def query_value(key, value)
423
508
  return value unless JSON_QUERY.include?(key)
424
509
 
@@ -461,6 +546,7 @@ module CalmLens
461
546
  in ['PUT', ['policy']] then show_policy(assign_policy(json))
462
547
  in ['GET', ['assets']] then list(query)
463
548
  in ['GET', ['assets', 'search']] then search(query)
549
+ in ['GET', ['assets', 'by-external-id', String => external_id]] then by_external_id(external_id)
464
550
  in ['GET', ['assets', String => asset_id, 'timeline']] then timeline(asset_id, query)
465
551
  in ['POST', ['assets', 'batch']] then batch(json)
466
552
  in ['POST', ['signed-asset-urls']] then sign_asset_url(json)
@@ -469,6 +555,11 @@ module CalmLens
469
555
  end
470
556
  end
471
557
 
558
+ # `GET /projects/:projectId/assets/by-external-id/:externalId`: the asset with that external ID.
559
+ def by_external_id(external_id)
560
+ project_assets.find { |item| item['externalId'] == external_id } || fail!(ErrorCodes::ASSET_NOT_FOUND)
561
+ end
562
+
472
563
  # A project's upload presets, settings and metadata fields.
473
564
  def configuration(method, parts, query, json)
474
565
  case [method, parts[2..]]
@@ -830,6 +921,9 @@ module CalmLens
830
921
 
831
922
  def kind(mime, url)
832
923
  return url_asset_type(url) if url
924
+
925
+ mime = mime_type(mime)
926
+ return 'website' if WEBSITE_TYPES.include?(mime)
833
927
  return mime.split('/').first if mime.start_with?('image/', 'video/', 'audio/')
834
928
  return 'plaintext-document' if mime.start_with?('text/')
835
929
  return 'multimedia-document' if mime.include?('pdf') || mime.include?('document')
@@ -839,7 +933,8 @@ module CalmLens
839
933
 
840
934
  # A URL upload's type: the type of its path's file extension ({MOCK_URL_EXTENSION_TYPES}),
841
935
  # compared lower-case without the query or fragment, or `website` for any other extension or
842
- # none. The mock fetches nothing, so the extension stands in for the fetched content's type.
936
+ # none. The mock fetches only URLs {#serve_url} registered, so for any other URL the extension
937
+ # stands in for the fetched content's type.
843
938
  def url_asset_type(url)
844
939
  path = begin
845
940
  URI.parse(url.to_s).path.to_s
@@ -851,11 +946,12 @@ module CalmLens
851
946
  dot ? MOCK_URL_EXTENSION_TYPES.fetch(segment[(dot + 1)..].downcase, 'website') : 'website'
852
947
  end
853
948
 
854
- def create_asset(options, queue, url: nil, data: nil, open: false)
949
+ def create_asset(options, queue, url: nil, data: nil, open: false, type: nil)
855
950
  check_upload(options)
856
951
  check_folder(options['folderId']) if options['folderId']
857
- if options['externalId'] && project_assets.any? { |item| item['externalId'] == options['externalId'] }
858
- fail!(ErrorCodes::DUPLICATE_EXTERNAL_ID)
952
+ if options['externalId']
953
+ holder = project_assets.find { |item| item['externalId'] == options['externalId'] }
954
+ duplicate_external_id!(holder) if holder
859
955
  end
860
956
  now = @now.call
861
957
  mime = options['contentType'].to_s
@@ -868,10 +964,12 @@ module CalmLens
868
964
  'folderId' => options['folderId'], 'uploadPresetId' => options['uploadPresetId'],
869
965
  'createdAt' => now, 'updatedAt' => now, 'name' => options['name'], 'description' => options['description'],
870
966
  'externalId' => options['externalId'], 'externalUrl' => url || options['externalUrl'],
871
- 'type' => kind(mime, url), 'metadata' => options['metadata'] || [], 'authorId' => options['authorId'],
967
+ 'type' => type || kind(mime, url), 'metadata' => options['metadata'] || [], 'authorId' => options['authorId'],
872
968
  # Like the API, only the posts CalmLens uses are kept, and only while the content is held.
873
969
  'context' => context.empty? ? nil : { 'items' => context }, 'tags' => options['tags'] || [],
874
970
  'visibility' => options.fetch('visibility', 'private'),
971
+ # Set as the asset's events are added (add_event).
972
+ 'eventSequence' => 0,
875
973
  **sections(now: now, open: open, keep: keep, format: mime, size: data&.bytesize) }
876
974
  @state.assets[asset['id']] = asset
877
975
  @processing_options[asset['id']] = processing
@@ -1006,7 +1104,7 @@ module CalmLens
1006
1104
  # A JSON create: text as `content` or a first `part` (`{ plainText, type }`), or a URL.
1007
1105
  def create_from_json(json, queue)
1008
1106
  key = %w[content part].find { |name| json.key?(name) }
1009
- return create_asset(apply_upload_preset(json), queue, url: json['url']) unless key
1107
+ return create_from_url(apply_upload_preset(json), queue) unless key
1010
1108
 
1011
1109
  text = json[key]
1012
1110
  invalid!('validation/invalid-type', key) unless text.is_a?(Hash) && text['plainText'].is_a?(String) && text['type'].is_a?(String)
@@ -1018,6 +1116,20 @@ module CalmLens
1018
1116
  start_multipart(apply_upload_preset(part, data), data, queue)
1019
1117
  end
1020
1118
 
1119
+ # A URL upload: the mock fetches a URL {#serve_url} registered, storing its content and typing
1120
+ # it by its content type as an upload of those bytes would be, except that a web page is a
1121
+ # `website` and stores nothing. Any other URL is typed by its path's extension, without content.
1122
+ def create_from_url(fields, queue)
1123
+ url = fields['url']
1124
+ served = (key = FakeAPI.url_key(url)) && @served_urls[key]
1125
+ return create_asset(fields, queue, url: url) unless served
1126
+
1127
+ type = kind(served[:type], nil)
1128
+ return create_asset(fields, queue, url: url, type: type) if type == 'website'
1129
+
1130
+ create_asset(fields.merge('contentType' => served[:type]), queue, url: url, data: served[:bytes].dup, type: type)
1131
+ end
1132
+
1021
1133
  # The asset fields in an upload form's options part, and the file's bytes. Like the API, a raw
1022
1134
  # upload must be `multipart/form-data` (`request/unsupported-content-type`, 415), holding an
1023
1135
  # `options` JSON object of known fields with a name, then a `file` part.
@@ -1067,10 +1179,9 @@ module CalmLens
1067
1179
  # `asset.uploaded` (the asset before moderation) and then the processing events.
1068
1180
  def upload_completed(asset, queue, bytes = :stored)
1069
1181
  decision = decision_for(asset, 'upload', queue, bytes)
1070
- uploaded = snapshot(asset)
1071
1182
  format = asset['content']['format']
1072
1183
  decided(asset, decision) unless decision.status == 'pending'
1073
- add_event('type' => 'asset.uploaded', 'severity' => 'low', 'assetId' => asset['id'], 'asset' => uploaded,
1184
+ add_event('type' => 'asset.uploaded', 'severity' => 'low', 'assetId' => asset['id'],
1074
1185
  'facts' => [{ 'key' => 'asset-type', 'value' => asset['type'] }, asset_name_fact(asset),
1075
1186
  { 'key' => 'file-format', 'value' => format }])
1076
1187
  record_processing_events(asset, decision)
@@ -1103,10 +1214,14 @@ module CalmLens
1103
1214
  # turned off. Like the API, a face has its `ageRange` only when the upload asked for age
1104
1215
  # estimation.
1105
1216
  def decided(asset, decision)
1217
+ # Read before the outcome removes content kept only for processing.
1218
+ image = asset['type'] == 'image' ? stored_bytes(asset) : nil
1106
1219
  apply_outcome(asset, decision.status, 'policy', decision.report(@now.call))
1107
1220
  classification = asset['classification']
1108
1221
  return asset unless classification['status'] == 'completed' && asset['type'] == 'image'
1109
1222
 
1223
+ match_hash_lists(asset, image) if image
1224
+
1110
1225
  processing = @processing_options[asset['id']]
1111
1226
  features = processing.is_a?(Hash) && processing['features'].is_a?(Hash) ? processing['features'] : {}
1112
1227
  setting = ->(name) { features[name].is_a?(Hash) ? features[name]['enabled'] : nil }
@@ -1131,6 +1246,42 @@ module CalmLens
1131
1246
  asset
1132
1247
  end
1133
1248
 
1249
+ # An asset's stored content, its parts in order, or nil once it is removed.
1250
+ def stored_bytes(asset)
1251
+ stored = asset['content']['status'] == 'removed' ? nil : @state.content[asset['id']]
1252
+ stored && stored['parts'].sort.map { |_, part| part.to_s.b }.join.b
1253
+ end
1254
+
1255
+ # Gives a decided image its hash and the project's hash list matches, as the API records them
1256
+ # (AssetClassification.ts, Project.ts and HashList.ts). The mock computes no PDQ hash: an
1257
+ # image's `content.perceptualHash` is the SHA-256 of its bytes in lowercase hex, with quality
1258
+ # 100, so an entry matches an image whose bytes equal those it was taken from, at distance 0.
1259
+ # Entries below quality 50 never match. Each match takes its list's action, blocking matches
1260
+ # first; a block raises an allowed, limited or age-restricted decision to `blocked`, with
1261
+ # `source: "hash-list"`, and a flag only records the match.
1262
+ def match_hash_lists(asset, bytes)
1263
+ hash = Digest::SHA256.hexdigest(bytes)
1264
+ asset['content'].merge!('perceptualHash' => hash, 'perceptualHashQuality' => 100)
1265
+ matches = @state.hash_list_entries.values.select do |entry|
1266
+ entry['hash'] == hash && (entry['quality'].nil? || entry['quality'] >= HASH_MATCH_MIN_QUALITY) &&
1267
+ @state.hash_lists.key?(entry['hashListId'])
1268
+ end
1269
+ matches = matches.map do |entry|
1270
+ { 'source' => 'hash-list', 'hashListId' => entry['hashListId'], 'hashListEntryId' => entry['id'], 'distance' => 0,
1271
+ 'action' => @state.hash_lists[entry['hashListId']]['action'] }
1272
+ end
1273
+ # A stable sort: blocking matches first, each kind in the order its entries were added.
1274
+ matches = matches.each_with_index.sort_by { |match, index| [match['action'] == 'block' ? 0 : 1, index] }.map(&:first)
1275
+ .first(MAX_RECORDED_HASH_MATCHES)
1276
+ return if matches.empty?
1277
+
1278
+ moderation = asset['classification']['moderation']
1279
+ if matches.any? { |match| match['action'] == 'block' } && %w[allowed limited age-restricted].include?(moderation['decision'])
1280
+ moderation.merge!('decision' => 'blocked', 'automatedStatus' => 'blocked', 'source' => 'hash-list')
1281
+ end
1282
+ moderation['raw'] = (moderation['raw'] || {}).merge('hashMatches' => matches)
1283
+ end
1284
+
1134
1285
  # Asks `moderate` (unless `decision` is given) and settles a processing asset: a decision and
1135
1286
  # its events, or nothing for `pending`.
1136
1287
  def moderate_stored(asset, trigger, decision = nil)
@@ -1150,7 +1301,7 @@ module CalmLens
1150
1301
  return if decision.status == 'pending'
1151
1302
 
1152
1303
  if decision.status == 'failed'
1153
- return add_event('type' => 'asset.failed', 'severity' => 'high', 'assetId' => item['id'], 'asset' => snapshot(item),
1304
+ return add_event('type' => 'asset.failed', 'severity' => 'high', 'assetId' => item['id'],
1154
1305
  'actor' => deep_copy(AUTOMATED_ACTOR),
1155
1306
  'facts' => [asset_name_fact(item), { 'key' => 'asset-type', 'value' => item['type'] },
1156
1307
  { 'key' => 'previous-status', 'value' => 'processing' },
@@ -1159,16 +1310,35 @@ module CalmLens
1159
1310
  end
1160
1311
 
1161
1312
  flagged = decision.report['flaggedCategories']
1162
- add_event('type' => 'asset.classified', 'severity' => 'low', 'assetId' => item['id'], 'asset' => snapshot(item),
1313
+ # A hash list match can block what the decision allowed.
1314
+ status = item['classification']['moderation']['decision'] || decision.status
1315
+ add_event('type' => 'asset.classified', 'severity' => 'low', 'assetId' => item['id'],
1163
1316
  'actor' => deep_copy(AUTOMATED_ACTOR),
1164
1317
  'facts' => [{ 'key' => 'flagged-categories', 'value' => flagged },
1165
- { 'key' => 'moderation-status', 'value' => decision.status },
1318
+ { 'key' => 'moderation-status', 'value' => status },
1166
1319
  { 'key' => 'asset-type', 'value' => item['type'] }, asset_name_fact(item)])
1167
1320
  # Like the event catalog: only allowing and limiting are low severity.
1168
- add_event('type' => "asset.#{decision.status}", 'severity' => %w[allowed limited].include?(decision.status) ? 'low' : 'high',
1169
- 'assetId' => item['id'], 'asset' => snapshot(item), 'actor' => deep_copy(AUTOMATED_ACTOR),
1321
+ add_event('type' => "asset.#{status}", 'severity' => %w[allowed limited].include?(status) ? 'low' : 'high',
1322
+ 'assetId' => item['id'], 'actor' => deep_copy(AUTOMATED_ACTOR),
1170
1323
  'facts' => [{ 'key' => 'flagged-categories', 'value' => flagged },
1171
1324
  { 'key' => 'asset-type', 'value' => item['type'] }, asset_name_fact(item)])
1325
+ record_hash_match(item)
1326
+ end
1327
+
1328
+ # Like AssetDecisionEvents.ts: `asset.hash-matched` for the closest match, after the decision.
1329
+ def record_hash_match(item)
1330
+ match = item.dig('classification', 'moderation', 'raw', 'hashMatches')&.first
1331
+ return unless match
1332
+
1333
+ list_id = match['hashListId']
1334
+ add_event('type' => 'asset.hash-matched', 'severity' => 'high', 'assetId' => item['id'],
1335
+ 'actor' => deep_copy(AUTOMATED_ACTOR),
1336
+ 'facts' => [{ 'key' => 'hash-list-id', 'value' => list_id },
1337
+ { 'key' => 'hash-list-name', 'value' => @state.hash_lists.dig(list_id, 'name') || '',
1338
+ 'url' => "https://calmlens.com/go/hash-list/#{Internal.component(list_id)}" },
1339
+ { 'key' => 'distance', 'value' => match['distance'] },
1340
+ { 'key' => 'match-action', 'value' => match['action'] },
1341
+ { 'key' => 'asset-type', 'value' => item['type'] }, asset_name_fact(item)])
1172
1342
  end
1173
1343
 
1174
1344
  # Moves an asset to an outcome like the pipeline would: a decision finishes processing, `purged`
@@ -1275,6 +1445,7 @@ module CalmLens
1275
1445
  in ['GET', 'children'] then page(project_assets.select { |child| child['parentId'] == id }, query, id)
1276
1446
  in ['POST', 'retry'] then retry_asset(item)
1277
1447
  in ['POST', 'decision'] then decide_request(item, json)
1448
+ in ['POST', 'review-requests'] then request_review(item, json)
1278
1449
  in ['POST', 'move']
1279
1450
  check_folder(json['folderId']) if json['folderId']
1280
1451
  touch(item.merge!('folderId' => json['folderId']))
@@ -1290,10 +1461,11 @@ module CalmLens
1290
1461
 
1291
1462
  # Like the API: an externalId stays unique in the project; null clears a field.
1292
1463
  def update(item, json)
1293
- if json['externalId'] && project_assets.any? { |other| other['id'] != item['id'] && other['externalId'] == json['externalId'] }
1294
- fail!(ErrorCodes::DUPLICATE_EXTERNAL_ID)
1464
+ if json['externalId']
1465
+ holder = project_assets.find { |other| other['id'] != item['id'] && other['externalId'] == json['externalId'] }
1466
+ duplicate_external_id!(holder) if holder
1295
1467
  end
1296
- touch(item.merge!(json.except('id', 'projectId', 'upload', 'classification', 'content')))
1468
+ touch(item.merge!(json.except('id', 'projectId', 'upload', 'classification', 'content', 'eventSequence')))
1297
1469
  end
1298
1470
 
1299
1471
  # Like the API: the record and report stay; stored content, extracted text, metadata, the
@@ -1987,18 +2159,18 @@ module CalmLens
1987
2159
 
1988
2160
  def not_available = error('asset/not-available', 'Asset is not available', status: 403)
1989
2161
 
1990
- # A preview requires access for private or blocked assets and disappears with its content.
2162
+ # Like the CDN (uzeServeAssetPlaceholder), a public asset's placeholder stands in for it whatever
2163
+ # its decision, a block included; a private one needs a grant or download access. It
2164
+ # disappears with the content.
1991
2165
  def placeholder(method, item, authorised)
1992
2166
  private_asset = item['visibility'] != 'public'
1993
- blocked = item['classification']['moderation']['decision'] == 'blocked'
1994
2167
  return asset_not_found if private_asset && !authorised
1995
- return not_available if blocked && !authorised
1996
2168
 
1997
2169
  thumbhash = item.dig('content', 'preview', 'thumbhash')
1998
2170
  return not_available if thumbhash.nil? || item['classification']['moderation']['decision'] == 'purged'
1999
2171
 
2000
2172
  cdn_response(method, Placeholder.png(thumbhash),
2001
- 'content-type' => 'image/png', 'cache-control' => private_asset || blocked ? 'private, no-store' : 'public, no-cache',
2173
+ 'content-type' => 'image/png', 'cache-control' => private_asset ? 'private, no-store' : 'public, no-cache',
2002
2174
  'cache-tag' => "asset-#{item['id']}", 'etag' => "\"#{thumbhash}\"")
2003
2175
  end
2004
2176