Module: Parse::CLPScope

Defined in:
lib/parse/clp_scope.rb

Defined Under Namespace

Classes: AccessEvaluation, CacheEntry, Denied

Constant Summary collapse

OPERATIONS =
%i[find count get create update delete].freeze
DEFAULT_PROTECTED_FIELDS =

Parse Server's default server-config protectedFields option. See default_protected_fields.

{ "_User" => { "*" => ["email"].freeze }.freeze }.freeze
POSITIVE_TTL =

Positive-cache TTL (seconds): how long a successful schema fetch is reused. Mirrors the previous module-level @cache_ttl knob; kept identical to preserve backwards-compatible cache behavior.

3600
NEGATIVE_TTL =

Negative-cache TTL (seconds): how long we remember that a class's schema was unresolvable. Short so a transient network blip doesn't gridlock the application for an hour, but non-zero so a permanent failure (auth credential rotated, schema endpoint disabled) doesn't melt the schema endpoint with a thundering herd of retries at request rate.

5
SUPPRESSED_NEGATIVE_TTL =

How long a schema fetch that failed inside Parse.without_master_key is remembered. Kept apart from the shared cache and consulted only inside the block, so it never denies another caller's reads; it only stops a down server from being refetched on every read in the block.

2

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.cache_ttl ⇒ Object

Returns the value of attribute cache_ttl.



105
106
107
# File 'lib/parse/clp_scope.rb', line 105

def cache_ttl
  @cache_ttl
end

.schema_client ⇒ Object

Returns the value of attribute schema_client.



105
106
107
# File 'lib/parse/clp_scope.rb', line 105

def schema_client
  @schema_client
end

Class Method Details

.__cache_put(class_name, clp:, client: nil) ⇒ Object

Test/operator-facing hook: pre-populate the cache with a known CLP for class_name. An empty/nil clp is recorded as :no_clp (matches the public-default semantics Parse Server exposes when no CLP is configured); a non-empty clp is recorded as :cached_clp (the standard happy path).



543
544
545
546
547
548
549
# File 'lib/parse/clp_scope.rb', line 543

def __cache_put(class_name, clp:, client: nil)
  normalized = clp || {}
  kind = normalized.empty? ? :no_clp : :cached_clp
  entry = CacheEntry.new(kind: kind, clp: normalized, fetched_at: monotonic_now)
  @cache_mutex.synchronize { @cache[cache_key(class_name, client)] = entry }
  entry
end

.assert_permitted!(class_name, op, permission_strings, client: nil) ⇒ Object

Raises:



163
164
165
166
167
# File 'lib/parse/clp_scope.rb', line 163

def assert_permitted!(class_name, op, permission_strings, client: nil)
  return if permits?(class_name, op, permission_strings, client: client)
  raise Denied.new(class_name, op,
                   "CLP refuses #{op} on '#{class_name}' for the current scope.")
end

.cache_stats ⇒ Object



528
529
530
531
532
533
534
535
536
# File 'lib/parse/clp_scope.rb', line 528

def cache_stats
  @cache_mutex.synchronize do
    {
      size: @cache.size,
      class_names: @cache.keys.map(&:last).uniq.sort,
      scopes: @cache.keys.map(&:first).uniq.sort,
    }
  end
end

.default_protected_fields ⇒ Hash{String => Hash{String => Array<String>}}

Parse Server's server-config protectedFields default, merged into every class's CLP protectedFields the way Parse Server's SchemaData merges them (union per group key).

Parse Server ships { _User: { "*": ["email"] } } as the default and does NOT expose the server-config value through GET /schemas/<Class>, so the SDK cannot discover it. Without this default a scoped mongo-direct read returned every user's email, and an email filter matched, where REST hides the field and refuses the filter. Set this to the same value as the server's protectedFields option when it is customized; {} disables the merge.

Returns:



346
347
348
# File 'lib/parse/clp_scope.rb', line 346

def default_protected_fields
  @default_protected_fields ||= DEFAULT_PROTECTED_FIELDS
end

.default_protected_fields=(value) ⇒ Object

Parameters:

  • value (Hash, nil) —

    class name => protectedFields map; nil restores Parse Server's default.



352
353
354
# File 'lib/parse/clp_scope.rb', line 352

def default_protected_fields=(value)
  @default_protected_fields = value.nil? ? DEFAULT_PROTECTED_FIELDS : value
end

.evaluate_access(class_name, op, claims:, authenticated:, user_id: nil, client: nil) ⇒ AccessEvaluation

Evaluate the same mutually-exclusive CLP branches Parse Server uses before applying a query to a particular row. Public, direct-user, and role grants bypass pointer constraints. requiresAuthentication does not: when pointer/user fields exist, a concrete authenticated _User id must still match the row.

Unlike permits?, schema lookup failures are reported as :unknown rather than collapsed into a denial. Authorization-enforcing callers can still fail closed by accepting only Parse::CLPScope::AccessEvaluation#allowed?.

Parameters:

  • class_name (String) —

    Parse class name.

  • op (Symbol) —

    one of OPERATIONS.

  • claims (Enumerable<String>) —

    public, user, and role claims.

  • authenticated (Boolean) —

    whether authentication is established.

  • user_id (String, nil) (defaults to: nil) —

    concrete authenticated _User.objectId.

  • client (Parse::Client) (defaults to: nil) —

    application whose schema owns the CLP.

Returns:



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
# File 'lib/parse/clp_scope.rb', line 226

def evaluate_access(class_name, op, claims:, authenticated:, user_id: nil, client: nil)
  op = op.to_sym
  unless OPERATIONS.include?(op)
    return access_evaluation(:unknown, reason: :unsupported_operation)
  end

  entry = fetch(class_name, client: client)
  case entry.kind
  when :unresolvable
    return access_evaluation(:unknown, reason: :clp_unresolvable)
  when :no_clp
    return access_evaluation(:allowed, via: :public_default)
  end

  op_map = entry.clp[op.to_s] || entry.clp[op]
  # Parse Server treats an omitted operation map as public. Because that
  # is already a base grant, grouped pointer fields do not narrow it.
  return access_evaluation(:allowed, via: :public_default) if op_map.nil?
  unless op_map.is_a?(Hash)
    return access_evaluation(:unknown, reason: :malformed_clp)
  end

  claim_set = claims.is_a?(Set) ? claims : Set.new(Array(claims).map(&:to_s))
  role_claims = op_map.each_with_object([]) do |(principal, allowed), memo|
    key = principal.to_s
    memo << key if allowed == true && key.start_with?("role:")
  end.freeze

  if op_map["*"] == true || op_map[:"*"] == true
    return access_evaluation(:allowed, via: :public, role_claims: role_claims)
  end

  direct_claim = op_map.find do |principal, allowed|
    key = principal.to_s
    allowed == true && key != "*" && key != "requiresAuthentication" &&
      key != "pointerFields" && claim_set.include?(key)
  end
  if direct_claim
    return access_evaluation(
             :allowed,
             via: direct_claim.first.to_s.start_with?("role:") ? :role : :user,
             role_claims: role_claims,
           )
  end

  pointer_fields = pointer_fields_from(entry.clp, op)
  requires_authentication =
    op_map["requiresAuthentication"] == true || op_map[:requiresAuthentication] == true

  if pointer_fields.any?
    if authenticated == true && !user_id.to_s.empty?
      return access_evaluation(
               :allowed,
               via: :pointer,
               pointer_fields: pointer_fields,
               role_claims: role_claims,
             )
    end

    status = authenticated == true ? :unknown : :denied
    reason = authenticated == true ? :concrete_user_required : :authentication_required
    return access_evaluation(status, role_claims: role_claims, reason: reason)
  end

  if requires_authentication && authenticated == true
    return access_evaluation(:allowed, via: :authenticated, role_claims: role_claims)
  end

  reason = requires_authentication ? :authentication_required : :clp_denied
  access_evaluation(:denied, role_claims: role_claims, reason: reason)
end

.filter_by_pointer_fields(documents, pointer_fields, user_id) ⇒ Object



498
499
500
501
502
# File 'lib/parse/clp_scope.rb', line 498

def filter_by_pointer_fields(documents, pointer_fields, user_id)
  return documents if pointer_fields.nil? || pointer_fields.empty?
  return [] if user_id.nil? || user_id.to_s.empty?
  documents.select { |doc| any_pointer_matches?(doc, pointer_fields, user_id.to_s) }
end

.invalidate!(class_name, client: nil) ⇒ Object



504
505
506
507
508
509
510
511
512
513
514
# File 'lib/parse/clp_scope.rb', line 504

def invalidate!(class_name, client: nil)
  class_key = class_name.to_s
  @cache_mutex.synchronize do
    if client
      @cache.delete(cache_key(class_key, client))
    else
      @cache.delete_if { |(_scope, cached_class), _entry| cached_class == class_key }
    end
  end
  nil
end

.permits?(class_name, op, permission_strings, client: nil) ⇒ Boolean

Returns:

  • (Boolean)


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
# File 'lib/parse/clp_scope.rb', line 107

def permits?(class_name, op, permission_strings, client: nil)
  return true if permission_strings.nil?  # master-key bypass
  return true unless OPERATIONS.include?(op)

  entry = fetch(class_name, client: client)
  # `fetch` never returns nil now — it returns an `:unresolvable`
  # CacheEntry on failure so callers must branch on `kind`.
  case entry.kind
  when :unresolvable
    # FAIL CLOSED. The SDK is the only enforcement layer on the
    # mongo-direct path; without a verified CLP we can't tell
    # whether the class is public or admin-only, and the safe
    # default is to refuse rather than silently surrender row
    # filtering. Operators who want a different posture can
    # pre-populate the cache via {.__cache_put} from a startup
    # hook or static config.
    warn_unresolvable_once!(class_name)
    return false
  when :no_clp
    # Schema fetch succeeded; class has no CLP configured.
    # Parse Server's default is public, so permit.
    return true
  end

  op_map = entry.clp[op.to_s] || entry.clp[op]
  # nil op_map: the operation has no CLP entry. Parse Server's
  # default is public, so permit.
  return true if op_map.nil?
  # Empty op_map (`delete: {}` etc.): nobody but master-key.
  # Master-key already short-circuited above, so deny here.
  return false if op_map.is_a?(Hash) && op_map.empty?

  claim_set = permission_strings.is_a?(Set) ? permission_strings : permission_strings.to_set

  op_map.each do |principal, allowed|
    case principal.to_s
    when "*"
      return true if allowed == true
    when "requiresAuthentication"
      return true if allowed == true && claim_set.any? { |e| user_identity?(e) }
    when "pointerFields"
      # Value is an Array of pointer field names, not a boolean.
      # At the boundary, permit iff the claim set has a user
      # identity to satisfy the constraint with; the actual
      # row-by-row check runs post-fetch via {.pointer_fields_for}.
      next if allowed.nil? || (allowed.respond_to?(:empty?) && allowed.empty?)
      return true if claim_set.any? { |e| user_identity?(e) }
    else
      # Bare userObjectId or "role:Name" — claim-set match.
      return true if allowed == true && claim_set.include?(principal.to_s)
    end
  end

  false
end

.pointer_fields_for(class_name, op, client: nil) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/parse/clp_scope.rb', line 169

def pointer_fields_for(class_name, op, client: nil)
  entry = fetch(class_name, client: client)
  # No CLP at all, or schema unresolvable: there's no
  # pointerFields constraint to apply. (For :unresolvable the
  # caller's `permits?` already failed closed; this helper just
  # returns nil so a post-fetch row-filter step is skipped.)
  return nil if entry.kind == :no_clp || entry.kind == :unresolvable
  op_map = entry.clp[op.to_s] || entry.clp[op]
  return nil unless op_map.is_a?(Hash)
  fields = op_map["pointerFields"] || op_map[:pointerFields]
  return nil if fields.nil?
  arr = Array(fields).map(&:to_s)
  arr.empty? ? nil : arr
end

.pointer_fields_predicate(pointer_fields, user_id) ⇒ Hash

A $match predicate keeping only rows whose pointer fields reference user_id, in Mongo storage form. A single pointer is stored as _p_<field>: "_User$<id>"; an array of pointers is stored under the bare field name as { __type, className, objectId } elements. Both forms are matched, ORed across fields, as Parse Server's addPointerPermissions does.

Parameters:

Returns:

  • (Hash) —

    a $match predicate.



485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/parse/clp_scope.rb', line 485

def pointer_fields_predicate(pointer_fields, user_id)
  uid = user_id.to_s
  storage = "#{Parse::Model::CLASS_USER}$#{uid}"
  clauses = Array(pointer_fields).flat_map do |field|
    f = field.to_s
    [
      { "_p_#{f}" => storage },
      { f => { "$elemMatch" => { "className" => Parse::Model::CLASS_USER, "objectId" => uid } } },
    ]
  end
  { "$or" => clauses }
end

.protected_fields_for(class_name, permission_strings, client: nil, strict: false) ⇒ Object

Parameters:

  • strict (Boolean) (defaults to: false) —

    when true, an unresolvable schema raises Denied instead of returning an empty set. Callers that use the set to REFUSE a request (the pipeline reference scanner) pass true: an empty set there would let the request through.

Raises:

  • (Denied) —

    when strict and the schema is unresolvable.



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
# File 'lib/parse/clp_scope.rb', line 303

def protected_fields_for(class_name, permission_strings, client: nil, strict: false)
  return EMPTY_SET if permission_strings.nil?

  entry = fetch(class_name, client: client)
  # No CLP / unresolvable: nothing to strip. For :unresolvable,
  # `permits?` already refused the query, so this branch is only
  # reached when callers ask for the protected-fields set directly
  # (e.g. for documentation or audit tooling).
  if entry.kind == :unresolvable
    if strict
      warn_unresolvable_once!(class_name)
      raise Denied.new(class_name, :find,
                       "protectedFields for '#{class_name}' are unresolvable; " \
                       "refusing the pipeline for the current scope.")
    end
    return EMPTY_SET
  end
  stored_map = if entry.kind == :no_clp
      nil
    else
      entry.clp["protectedFields"] || entry.clp[:protectedFields]
    end
  protected_map = merge_default_protected_fields(class_name, stored_map)
  return EMPTY_SET if protected_map.nil? || protected_map.empty?

  claim_set = permission_strings.is_a?(Set) ? permission_strings : permission_strings.to_set
  protected_sets_for(protected_map, claim_set).reduce { |acc, set| acc & set }&.freeze || EMPTY_SET
end

.protected_strip_stage(strip_set, class_name: nil, user_id: nil) ⇒ Hash?

A pipeline stage that removes protected fields at the database, placed at the head of a (sub-)pipeline before any caller stage runs.

Ownership of a _User row is decided here, on the stored _id, so the self exemption cannot be claimed by a later stage that rewrites _id. For a _User read by a known user the fields are kept only on that user's own row; everywhere else they are unset. The _p_<field> storage column of a protected pointer is removed with the field.

Parameters:

  • strip_set (Set<String>) —

    protected field names for the scope.

  • class_name (String, nil) (defaults to: nil) —

    the class the stage reads.

  • user_id (String, nil) (defaults to: nil) —

    the requesting user's objectId.

Returns:

  • (Hash, nil) —

    a $unset or $set stage, or nil when nothing is protected.



410
411
412
413
414
415
416
417
418
419
# File 'lib/parse/clp_scope.rb', line 410

def protected_strip_stage(strip_set, class_name: nil, user_id: nil)
  return nil if strip_set.nil? || strip_set.empty?
  columns = strip_set.flat_map { |f| [f.to_s, "_p_#{f}"] }.uniq
  if class_name.to_s == Parse::Model::CLASS_USER && !user_id.to_s.empty?
    own_row = { "$eq" => ["$_id", { "$literal" => user_id.to_s }] }
    { "$set" => columns.to_h { |c| [c, { "$cond" => [own_row, "$#{c}", "$$REMOVE"] }] } }
  else
    { "$unset" => columns }
  end
end

.redact_protected_fields!(documents, strip_set, class_name: nil, user_id: nil) ⇒ Array<Hash>

Strip protected fields from result rows, top-level keys only.

Parse Server deletes object[key] for each protected key on the returned object and does not descend into nested values, so an :object column holding { "secret" => ... } keeps that key even when a top-level secret column is protected. Included objects are separate rows of another class; strip them with that class's own set (see MongoDB.aggregate).

Parse Server also skips the strip for a _User row that IS the requesting user, so a user always sees their own email. Pass class_name: and user_id: to apply that exemption.

The exemption reads the row's _id (or objectId) as it comes out of the pipeline. A caller stage can rewrite that value, so pass user_id: only when ownership was settled before any caller stage ran: either no caller stage can change the identity (see PipelineSecurity.identity_preserving?), or the rows went through protected_strip_stage at the head of their pipeline.

Parameters:

  • documents (Array<Hash>) —

    rows (Mongo storage or Parse form).

  • strip_set (Set<String>) —

    protected field names.

  • class_name (String, nil) (defaults to: nil) —

    the rows' class.

  • user_id (String, nil) (defaults to: nil) —

    the requesting user's objectId.

Returns:

  • (Array<Hash>) —

    the same array, modified in place.



381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/parse/clp_scope.rb', line 381

def redact_protected_fields!(documents, strip_set, class_name: nil, user_id: nil)
  return documents if documents.nil? || documents.empty?
  return documents if strip_set.nil? || strip_set.empty?
  self_exempt = class_name.to_s == Parse::Model::CLASS_USER && !user_id.to_s.empty?
  documents.each do |doc|
    next unless doc.is_a?(Hash)
    if self_exempt
      row_id = doc["_id"] || doc[:_id] || doc["objectId"] || doc[:objectId]
      next if row_id.to_s == user_id.to_s
    end
    strip_top_level!(doc, strip_set)
  end
  documents
end

.reset_cache! ⇒ Object



516
517
518
519
520
521
522
523
524
525
526
# File 'lib/parse/clp_scope.rb', line 516

def reset_cache!
  @cache_mutex.synchronize do
    @cache.clear
    @suppressed_failures.clear
  end
  # Also drop the unresolvable-class warned-once registry so
  # tests that assert on `warn` emission for a class don't get
  # silenced by an earlier test's call.
  @warned_unresolvable_classes = Set.new
  nil
end

.row_constraint_for!(class_name, op, resolution, client: nil, label: nil) ⇒ Array<String>?

Evaluate the op CLP for a resolved mongo-direct scope with the same mutually exclusive branches Parse Server uses, and return the row constraint the caller must apply.

A public, user, or role grant permits every row, even when the CLP also lists pointerFields / readUserFields (Parse Server only consults those when no other branch grants). When the only grant is a pointer branch, the caller must keep just the rows whose named pointer fields reference the requesting user. readUserFields counts as a pointer branch here; the older permits? plus pointer_fields_for pair ignored it, so a readUserFields class let every authenticated user read every row on the direct path.

Parameters:

Returns:

  • (Array<String>, nil) —

    pointer field names that must reference the requesting user, or nil when every row is permitted. Always nil for master and nil resolutions.

Raises:

  • (Denied) —

    when the scope cannot perform op at all, including when the CLP is unresolvable (fail closed).



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/parse/clp_scope.rb', line 444

def row_constraint_for!(class_name, op, resolution, client: nil, label: nil)
  return nil if resolution.nil?
  return nil if resolution.respond_to?(:master?) && resolution.master?
  perms = resolution.respond_to?(:permission_strings) ? resolution.permission_strings : nil
  return nil if perms.nil?

  user_id = resolution.respond_to?(:user_id) ? resolution.user_id.to_s : ""
  evaluation = evaluate_access(
    class_name, op,
    claims: perms,
    authenticated: !user_id.empty?,
    user_id: user_id.empty? ? nil : user_id,
    client: client,
  )
  if evaluation.allowed?
    fields = Array(evaluation.pointer_fields)
    return fields.empty? ? nil : fields
  end

  warn_unresolvable_once!(class_name) if evaluation.reason == :clp_unresolvable
  scope = label ? "the current #{label} scope" : "the current scope"
  message = if %i[concrete_user_required authentication_required].include?(evaluation.reason) &&
               !pointer_fields_from_entry(class_name, op, client).empty?
      "CLP requires user identity (pointerFields=#{pointer_fields_from_entry(class_name, op, client).inspect}) " \
      "but #{scope} has no user_id."
    else
      "CLP refuses #{op} on '#{class_name}' for #{scope}."
    end
  raise Denied.new(class_name, op, message)
end

.user_fields_for(class_name, op, client: nil) ⇒ Array<String>?

Return Parse Server's top-level readUserFields or writeUserFields row constraint for an operation. Unlike an operation's pointerFields grant, these keys live alongside the operation maps in classLevelPermissions and therefore need their own lookup.

Parameters:

  • class_name (String) —

    Parse class name.

  • op (Symbol) —

    CLP operation.

Returns:

  • (Array<String>, nil) —

    pointer field names, or nil when the operation has no corresponding user-field constraint.



194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/parse/clp_scope.rb', line 194

def user_fields_for(class_name, op, client: nil)
  key = case op.to_sym
    when :find, :get, :count then "readUserFields"
    when :create, :update, :delete then "writeUserFields"
    end
  return nil if key.nil?

  entry = fetch(class_name, client: client)
  return nil if entry.kind == :no_clp || entry.kind == :unresolvable

  fields = entry.clp[key] || entry.clp[key.to_sym]
  arr = Array(fields).map(&:to_s)
  arr.empty? ? nil : arr
end

.with_snapshot { ... } ⇒ Object

Pin every schema entry read inside the block to the first value read for its cache key, for the current thread (fiber).

A scoped mongo-direct request reads the schema several times: the protected-field reference scanner, the CLP row gate, the join gate, and the protected-field strip. Each read used to consult the shared cache on its own, so a TTL expiry and refetch between two reads could give the scanner one schema and the gate another (an unresolvable scan with an empty protected set, then a successful gate). Inside this block every read for a class sees one entry, so the decisions agree. Nested calls reuse the outer snapshot.

Yields:

  • the request whose schema reads should agree.

Returns:

  • (Object) —

    the block's value.



573
574
575
576
577
578
579
580
581
# File 'lib/parse/clp_scope.rb', line 573

def with_snapshot
  return yield if Thread.current[SNAPSHOT_KEY]
  Thread.current[SNAPSHOT_KEY] = {}
  begin
    yield
  ensure
    Thread.current[SNAPSHOT_KEY] = nil
  end
end