evaluateRule function

RuleDecision evaluateRule(
  1. Map<String, Object?>? rule,
  2. Principal? principal,
  3. Map<String, Object?>? record, {
  4. RuleRequest? request,
  5. CelProgram? program,
  6. String? operation,
  7. Map<String, Object?>? fieldTypes,
  8. Map<String, Object?>? claimTypes,
})

Evaluates one operation rule for principal against record, the record the operation binds (05 §2.2). rule is a manifest rule ({kind, ownerField?, expression?, message?}) or a config rule ({allow, …}); a null rule denies categorically. program is the already parsed expression, else it is parsed from the rule. request defaults to the device clock and nothing else.

Pass operation (create, get, list, update, delete or subscribe, as the manifest names them):

  • create: record is the candidate (the input, plus id, createdAt, updatedAt and version = 1). owner allows any signed-in caller, whatever record holds, since FFX writes the owner field itself. Every denial is categorical (or unauthenticated), because FFX answers each create denial with a 403 (local data 3.1, 3.3). Without a candidate, an expression that reads record is RuleUndecided.
  • get, list, update, delete, subscribe: record is the stored record (each listed record on list; the pre-image on update and delete). Null means this host does not hold it: an owner rule, or an expression that reads record, newRecord or changedFields(), is then RuleUndecided, where the platform would answer 404.

Without operation, a null record stands for a create under owner and denials keep the reason the rule's reads give, exactly as the emulator's evaluateOperationRule.

Otherwise decides as the emulator and the platform do: none denies; authenticated needs a principal; owner compares the owner field with the principal; expression runs FFX-CEL, failing closed on an evaluation error, and its denial is record-dependent when the expression reads record, newRecord or changedFields().

Pass fieldTypes (celFieldTypes of the model) and claimTypes when the host knows them, as the platform does: record and newRecord values are then read by their declared types (CelEnvironment.fieldTypes).

Implementation

RuleDecision evaluateRule(
  Map<String, Object?>? rule,
  Principal? principal,
  Map<String, Object?>? record, {
  RuleRequest? request,
  CelProgram? program,
  String? operation,
  Map<String, Object?>? fieldTypes,
  Map<String, Object?>? claimTypes,
}) {
  if (rule == null) return const RuleDeny(RuleDenialReason.categorical);
  final message = rule['message'] is String ? rule['message'] as String : null;
  final kind = rule['kind'] ?? rule['allow'];
  final create = operation == 'create';
  final unknownRecord = operation != null && record == null;
  switch (kind) {
    case 'none':
      return RuleDeny(RuleDenialReason.categorical, message: message);
    case 'authenticated':
      return principal == null
          ? RuleDeny(RuleDenialReason.unauthenticated, message: message)
          : const RuleAllow();
    case 'owner':
      final ownerField = rule['ownerField'];
      if (ownerField is! String) {
        return const RuleUndecided('an owner rule without its ownerField');
      }
      if (principal == null) {
        return RuleDeny(RuleDenialReason.unauthenticated, message: message);
      }
      if (create) return const RuleAllow(); // FFX writes the owner field
      if (unknownRecord) {
        return const RuleUndecided('an owner rule without the stored record');
      }
      if (record == null) return const RuleAllow(); // create: FFX assigns it
      return record[ownerField] == principal.endUserId
          ? const RuleAllow()
          : RuleDeny(RuleDenialReason.recordDependent, message: message);
    case 'expression':
      final source = rule['expression'];
      if (program == null && source is! String) {
        return const RuleUndecided('an expression rule without its expression');
      }
      final CelProgram parsed;
      try {
        parsed = program ?? parseCel(source as String);
      } on CelParseError catch (error) {
        return RuleUndecided('the expression does not parse: ${error.message}');
      }
      if (unknownRecord && parsed.referencesRecord) {
        return const RuleUndecided(
          'an expression that reads the record, without the record',
        );
      }
      final reason = parsed.referencesRecord && !create
          ? RuleDenialReason.recordDependent
          : RuleDenialReason.categorical;
      final inputs = request ?? RuleRequest(DateTime.now().toUtc());
      final env = CelEnvironment(
        requestTime: inputs.time,
        userId: principal?.endUserId,
        accountType: principal?.accountType,
        claims: principal?.claims ?? const {},
        record: record,
        newRecord: inputs.newRecord,
        changedFields: inputs.changedFields,
        params: inputs.params,
        lookup: inputs.lookup,
        owned: inputs.owned,
        fieldTypes: fieldTypes,
        claimTypes: claimTypes,
        paramTypes: inputs.paramTypes,
      );
      try {
        final result = runCel(parsed, env);
        return result.allowed
            ? RuleAllow(spends: result.spends)
            : RuleDeny(reason, message: message);
      } on CelEvaluationError catch (error) {
        return RuleDeny(
          reason,
          message: message,
          evaluationError: error.message,
        );
      }
    default:
      return RuleUndecided('an unknown rule kind: $kind');
  }
}