Sha256: 959fc2e46b7475a76ebb3409cbfc13bf34a1de48e6f834389911e02e03d9e76f

Contents?: true

Size: 1.94 KB

Versions: 33

Compression:

Stored size: 1.94 KB

Contents

# frozen_string_literal: true

require_relative 'errors'
require_relative 'request_helper'

module StytchB2B
  class PolicyCache
    def initialize(rbac_client:)
      @rbac_client = rbac_client
      @policy_last_update = 0
      @cached_policy = nil
    end

    def reload_policy
      @cached_policy = @rbac_client.policy['policy']
      @policy_last_update = Time.now.to_i
    end

    def get_policy(invalidate: false)
      reload_policy if invalidate || @cached_policy.nil? || @policy_last_update < Time.now.to_i - 300
      @cached_policy
    end

    # Performs an authorization check against the project's policy and a set of roles. If the
    # check succeeds, this method will return. If the check fails, a PermissionError
    # will be raised. It's also possible for a TenancyError to be raised if the
    # subject_org_id does not match the authZ request organization_id.
    # authorization_check is an object with keys 'action', 'resource_id', and 'organization_id'
    def perform_authorization_check(
      subject_roles:,
      subject_org_id:,
      authorization_check:
    )
      request_org_id = authorization_check['organization_id']
      raise Stytch::TenancyError.new(subject_org_id, request_org_id) if request_org_id != subject_org_id

      policy = get_policy

      for role in policy['roles']
        next unless subject_roles.include?(role['role_id'])

        for permission in role['permissions']
          actions = permission['actions']
          resource = permission['resource_id']
          has_matching_action = actions.include?('*') || actions.include?(authorization_check['action'])
          has_matching_resource = resource == authorization_check['resource_id']
          if has_matching_action && has_matching_resource
            # All good
            return
          end
        end
      end

      # If we get here, we didn't find a matching permission
      raise Stytch::PermissionError, authorization_check
    end
  end
end

Version data entries

33 entries across 33 versions & 1 rubygems

Version Path
stytch-10.3.0 lib/stytch/rbac_local.rb
stytch-10.2.0 lib/stytch/rbac_local.rb
stytch-10.1.0 lib/stytch/rbac_local.rb
stytch-10.0.0 lib/stytch/rbac_local.rb
stytch-9.12.0 lib/stytch/rbac_local.rb
stytch-9.11.1 lib/stytch/rbac_local.rb
stytch-9.11.0 lib/stytch/rbac_local.rb
stytch-9.10.0 lib/stytch/rbac_local.rb
stytch-9.9.0 lib/stytch/rbac_local.rb
stytch-9.8.0 lib/stytch/rbac_local.rb
stytch-9.7.0 lib/stytch/rbac_local.rb
stytch-9.6.0 lib/stytch/rbac_local.rb
stytch-9.5.0 lib/stytch/rbac_local.rb
stytch-9.4.0 lib/stytch/rbac_local.rb
stytch-9.3.0 lib/stytch/rbac_local.rb
stytch-9.2.0 lib/stytch/rbac_local.rb
stytch-9.1.0 lib/stytch/rbac_local.rb
stytch-9.0.0 lib/stytch/rbac_local.rb
stytch-8.0.0 lib/stytch/rbac_local.rb
stytch-7.8.1 lib/stytch/rbac_local.rb