canvas_sync 0.27.16 → 0.27.17

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.
data/doc/joblin.md ADDED
@@ -0,0 +1,72 @@
1
+ # Job orchestration (Joblin)
2
+
3
+ CanvasSync runs its jobs on [Joblin](https://rubygems.org/gems/joblin) (`~> 0.2.1`), a separate gem that handles batching, pooling, and uniqueness for both ActiveJob and Sidekiq. `CanvasSync::JobBatches` and `CanvasSync::JobUniqueness` are aliases for `Joblin::Batching` and `Joblin::Uniqueness`, so code written against the old in-gem modules still works.
4
+
5
+ Joblin stores its state in Redis. It reads `BEARCAT_REDIS_URL` first and falls back to `REDIS_URL`.
6
+
7
+ ## Batches
8
+ Batches work like Sidekiq Pro batches: group jobs, share context, and run callbacks when the group finishes.
9
+
10
+ ```ruby
11
+ batch = Joblin::Batching::Batch.new
12
+ batch.description = "Some Batch" # Optional; shows in the Web UI
13
+ batch.context = { some_value: "blah" } # Jobs read this as `batch_context`; nested batches merge it
14
+ batch.on(:success, "SomeClass.on_success", some_param: "foo")
15
+ batch.jobs do
16
+ SomeJob.perform_later
17
+ end
18
+ ```
19
+
20
+ Callbacks:
21
+ - `:success` - every job succeeded
22
+ - `:complete` - every job ran, even if some failed
23
+ - `:death` - a job moved to the dead state
24
+ - `:stagnated` - a job died and nothing else in the batch is still running
25
+
26
+ Other helpers: `Batch.current`, `Batch.current_context`, and `keep_open!(token)` / `let_close!(token)` to hold a batch open while you add jobs to it later.
27
+
28
+ ## Serial, concurrent, and managed batches
29
+ - `SerialBatchJob` runs sub-jobs one after another.
30
+ - `ConcurrentBatchJob` runs them all at once.
31
+ - `ManagedBatchJob.make_batch(sub_jobs, ordered:, concurrency:, preflight_check:)` runs them with a concurrency cap. `preflight_check` is a `"Class.method"` string that runs before each job. Return truthy to run the job, falsy to skip it, or `:abort` to stop the whole batch.
32
+
33
+ `CanvasSync.default_provisioning_report_chain` returns a `Joblin::Batching::ChainBuilder` (see [Adding custom jobs](provisioning-sync.md#adding-custom-jobs)).
34
+
35
+ ## Job pools
36
+ A pool is a virtual queue that feeds jobs into your real queues.
37
+
38
+ ```ruby
39
+ pool = Joblin::Batching::Pool.new(concurrency: 4, order: :priority, clean_when_empty: false)
40
+ pool << { job: SomeJob, args: [1, 2, 3], kwargs: {}, priority: 100 }
41
+ pool.add_jobs([{ job: SomeJob, args: [4, 5, 6] }])
42
+
43
+ # ...Later
44
+ Joblin::Batching::Pool.from_pid(pool.pid).cleanup_redis
45
+ ```
46
+
47
+ - `concurrency` (default `1`) - how many pool jobs can run at once
48
+ - `order` (default `:fifo`) - `:fifo`, `:lifo`, `:random`, or `:priority` (higher runs first; ties run in random order)
49
+ - `clean_when_empty` (default `true`) - clean up the pool once it's empty
50
+ - `on_failed_job` (default `:wait`) - `:wait` for a failed job to succeed, or `:continue` to keep going
51
+
52
+ ## Job uniqueness
53
+ Add `ensure_uniqueness` to a job class to stop duplicate runs. It requires the `sidekiq-unique-jobs` gem.
54
+
55
+ ```ruby
56
+ class MyJob < ApplicationJob
57
+ ensure_uniqueness(
58
+ strategy: :until_executed, # :until_executing, :until_expired, :until_and_while_executing, :while_executing
59
+ on_conflict: :log, # :raise (default), :reject, :reschedule, or a proc
60
+ scope: :per_queue, # or :global
61
+ ttl: 7.days,
62
+ )
63
+ end
64
+ ```
65
+
66
+ Set global defaults with `Joblin::Uniqueness.configure { |c| c.lock_ttl = ...; c.on_conflict = ... }`.
67
+
68
+ ## Background tasks
69
+ `Joblin::BackgroundTask` is an ActiveRecord model for tracking a long-running job. Its `workflow_state` moves through `unscheduled → scheduled → started → completed/failed/cancelled`. Subclass it, implement `perform`, and call `enqueue!`. It also supports file attachments, opt-in API access, and `record_retention` for automatic cleanup. CanvasSync doesn't use it itself, but Joblin's engine adds its migrations to your app, so `db:migrate` creates the `joblin_background_tasks` table.
70
+
71
+ ## Sidekiq Web UI
72
+ When Sidekiq is installed and `sidekiq/web` is loaded, Joblin adds **Batches** and **Pools** tabs to `Sidekiq::Web` on its own. You can browse batch trees, context, and job counts there.
@@ -0,0 +1,55 @@
1
+ # Live Events
2
+
3
+ ## Dependencies
4
+
5
+ Live Events need these additional gems:
6
+ - If using Core/Data Services events: `httparty`, `json-jwt`
7
+ - If using EventsManager/DejaVu events: `symmetric-encryption`
8
+
9
+ ## Setup
10
+
11
+ Ensure that
12
+ ```ruby
13
+ mount CanvasSync::Engine, at: '/canvas_sync'
14
+ ```
15
+ is added to your `routes.rb`. Configure `DataServices` or `EventsManager` to send events to `https://YOUR_APP/canvas_sync/api/v1/live_event` (if using `DataServices`, event must be signed).
16
+
17
+ Uncomment `include CanvasSync::Concerns::LiveEventSync` and related lines in the appropriate models. (Some models provide some basic hooks to address a "typical" workflow).
18
+
19
+ When Live Events are received, the corresponding model (if present) instance will receive `process_live_event(subtype, payload, metadata)` (where `subtype` is the event name w/o the model name - eg `user_created` => `created`). The default logic is to call `ApiSyncable` and update the model from the Canvas API. `process_live_event` can be overridden directly, or hooked with the usual Rails callbacks system (eg `before_process_live_event`).
20
+
21
+ If the event's payload has `workflow_state: 'deleted'` (and the model has a `workflow_state` column), the default logic skips the API call, since Canvas would return a 404, and just updates `workflow_state` locally.
22
+
23
+ You can listen for Live Events outside of a model context using an initializer like so:
24
+ ```ruby
25
+ CanvasSync::LiveEvents.listen do |event|
26
+ next unless %w[user_created user_updated].include?(event[:metadata][:event_name])
27
+
28
+ # Your code here. event[:body] holds the event body and event[:metadata] its metadata.
29
+ # Note that this code is _not_ retried if it fails. If you need retries, use this block to trigger another Job.
30
+ end
31
+ ```
32
+
33
+ Every listener gets every event, so filter inside the block. (`listen` also accepts a list of event names as its first argument, but that form currently raises a `NameError` for matching events, so filter in the block for now.)
34
+
35
+ ### Event Provenance
36
+
37
+ When using `EventsManager` events, events are verified as having come from a legitimate source by use of `SymmetricEncryption` (and thus `PRODUCTION_KEY1` will need to be set correctly when deployed).
38
+
39
+ When using `DataServices`, CanvasSync uses the `DataServices` JWK to authenticate incoming events. CanvasSync is coded to default to the Prod & Beta JWK URL at https://8axpcl50e4.execute-api.us-east-1.amazonaws.com/main/jwks, but this can be overridden with the `DATASERVICES_JWK_URL` ENV variable.
40
+
41
+ Additionally, when `PandaPal` is installed too, use `https://YOUR_APP/canvas_sync/api/v1/live_event?org=ORG_ID` instead. `CanvasSync` will automatically switch to the correct organization and will validate that the event was indeed from the correct Canvas instance. If you are not using `PandaPal`, you'll need to monkey-patch `CanvasSync::Api::V1::LiveEventsController#validate_tenant!`
42
+
43
+ ### Legacy-Style Event Jobs
44
+
45
+ CanvasSync also supports the legacy style of Event Handlers. In this design, properly-named classes are defined in the `::LiveEvents` module, such as (`class LiveEvents::UserCreatedEvent`). Any `ActiveJob` job is compatible, but CanvasSync also provides `CanvasSync::LiveEvents::BaseHandler` as a helpful base class.
46
+
47
+ When present, these jobs will, per event type (eg `user_created`), override the default behavior, meaning that `listen` blocks and `process_live_event` and related callbacks will _not_ be called unless you call them. In other words: If you define `class LiveEvents::UserCreatedEvent` and also
48
+ ```ruby
49
+ CanvasSync::LiveEvents.listen do |event|
50
+ # ...
51
+ end
52
+ ```
53
+ the listen block (and User model) will receive `user_updated` events, but not `user_created` events.
54
+
55
+ These jobs can also be generated from template using `bin/rails generate canvas_sync:install_live_events --events users,courses,etc`
@@ -0,0 +1,220 @@
1
+ # Provisioning sync
2
+
3
+ Once you've used the generator to create your models and migrations, run the standard provisioning sync:
4
+
5
+ ```ruby
6
+ CanvasSync.provisioning_sync(<array of models to sync>, term_scope: <optional term scope>)
7
+ ```
8
+
9
+ *Note: pass in 'xlist' to your array of models if you would like sections to include cross listing information*
10
+
11
+ Example:
12
+
13
+ ```ruby
14
+ CanvasSync.provisioning_sync(['users', 'courses'], term_scope: :active)
15
+ ```
16
+
17
+ This will kick off a string of jobs to sync your specified models.
18
+
19
+ If you pass in the optional `term_scope` the provisioning reports will be run for only the terms returned by that scope. The scope must be defined on your `Term` model. (A sample one is provided in the generated `Term`.) If you don't pass one, CanvasSync picks Terms with `CanvasSync.sync_scope` (see [below](#which-records-get-synced)).
20
+
21
+ Other options:
22
+ - `term_scope: false` - Don't split reports by Term. Each report runs once for the whole account.
23
+ - `account_id:` - Sync a sub-account instead of the root account. The Accounts sync treats this account as its root, and the value is passed to your `canvas_sync_client`.
24
+
25
+ ## Which records get synced
26
+
27
+ When CanvasSync needs to decide which records of a model to sync (for example, which Terms to run reports for), it uses `CanvasSync.sync_scope`. It uses the first of these scopes your model defines:
28
+
29
+ 1. `should_canvas_sync`
30
+ 2. `active_for_canvas_sync`
31
+ 3. `should_sync`
32
+ 4. `active_for_sync`
33
+ 5. `active`
34
+
35
+ If none exist, it falls back to filtering out `workflow_state: 'deleted'`. The generated model templates define sensible `active` scopes.
36
+
37
+ Imports are inserted in bulk with [activerecord-import](https://github.com/zdennis/activerecord-import) so they should be very fast.
38
+
39
+ ## `updated_after`
40
+ An `updated_after` param may be passed when triggering a provision or making a chain:
41
+ ```ruby
42
+ CanvasSync.default_provisioning_report_chain(
43
+ %i[list of models to sync], updated_after: false
44
+ )
45
+ ```
46
+ It may be one of the following values:
47
+ * `false` - Will not apply any `updated_after` filtering to the requested reports
48
+ * An ISO-8601 Date - Will pass the supplied date as the `updated_after` param for the requested reports
49
+ * `true` (Default) - Will use the start date of the last successful sync
50
+
51
+ If `updated_after` is true, CanvasSync will, by default, perform a full sync every other Sunday.
52
+ This logic can be customized by passing `full_sync_every` parameter.
53
+ If you pass a date to `updated_after`, this logic will be disabled unless you explicitly pass a `full_sync_every` parameter.
54
+ `full_sync_every` accepts the following format strings:
55
+ - `15%` - Each sync will have a 15% chance of running a full sync
56
+ - `10 days` - A full sync will be run every 10 days
57
+ - `sunday` - A full sync will run every Sunday
58
+ - `saturday/4` - A full sync will run every fourth Saturday
59
+
60
+ ### Multiple Sync Chains
61
+ If your app uses multiple Sync Chains, you may run into issues with the automatic `updated_after` and `full_sync_every` logic.
62
+ You can fix this by using custom logic or by setting the `batch_genre` parameter when creating the Job Chain. Chains will only
63
+ use chains of the same genre when computing `updated_after` and `full_sync_every`.
64
+
65
+ ## Adding custom jobs
66
+
67
+ You can add your own jobs to a sync chain. Typical uses are post-processing after the sync finishes, syncing an extra model alongside the built-in ones, or doing per-term work for every Term the sync covers.
68
+
69
+ ### Write the job
70
+
71
+ Any ActiveJob job or Sidekiq worker works. Inheriting from `CanvasSync::Job` gets you a few extras:
72
+ - A `CanvasSync::JobLog` row for each run (see [Job logs](job-logs.md))
73
+ - The chain's `on_failure` handler (see [Handling Job errors](#handling-job-errors))
74
+ - `update_or_create_model(Model, api_params)` for saving Canvas API responses
75
+
76
+ ```ruby
77
+ class CanvasSyncCompleteJob < CanvasSync::Job
78
+ def perform(notify_user_id, mode: :summary)
79
+ # batch_context holds the chain's shared state
80
+ sync_batch = CanvasSync::SyncBatch.find(batch_context[:sync_batch_id])
81
+ # ...
82
+ end
83
+ end
84
+ ```
85
+
86
+ Every job in a chain can read `batch_context`. CanvasSync puts these keys in it:
87
+
88
+ | Key | Set where | Value |
89
+ |---|---|---|
90
+ | `sync_batch_id` | Whole chain | ID of the `CanvasSync::SyncBatch` row for this run |
91
+ | `batch_start_time` | Whole chain | ISO-8601 start time of this run |
92
+ | `batch_genre` | Whole chain | The chain's `batch_genre` (default `"default"`) |
93
+ | `updated_after` | Whole chain | Date reports are filtered by, or `nil` for a full sync |
94
+ | `account_id` | Whole chain | The `account_id:` you passed, if any |
95
+ | `canvas_term_id` | Per-term sub-chain only | The Term being synced |
96
+
97
+ Anything you pass in `options: { global: { ... } }` lands in `batch_context` too, so you can use it to send your own settings to your jobs.
98
+
99
+ ### Add it to the chain
100
+
101
+ Build the chain with `default_provisioning_report_chain` (not `provisioning_sync`, which starts the chain right away), add your jobs, then call `process!`:
102
+
103
+ ```ruby
104
+ chain = CanvasSync.default_provisioning_report_chain(%w[users courses enrollments], term_scope: :active)
105
+
106
+ # Runs after every sync job has finished
107
+ chain << { job: CanvasSyncCompleteJob, args: [current_user.id], kwargs: { mode: :full } }
108
+
109
+ chain.process!
110
+ ```
111
+
112
+ Each job entry is a Hash:
113
+ - `job` - the job class (or its name as a String)
114
+ - `args` / `kwargs` - arguments for `perform`
115
+ - `options` - a Hash merged into the last positional argument. Built-in sync jobs take their settings this way.
116
+
117
+ The top level of the chain runs in order, one entry after another, so `<<` adds a job that runs after all the syncing is done. To control where a job runs, use `insert`:
118
+
119
+ ```ruby
120
+ chain.insert({ job: SomeJob }) # End of the chain (same as <<)
121
+ chain.insert_at(0, { job: SomeJob }) # Start of the chain, before any syncing
122
+ chain.insert({ job: SomeJob }, after: 'CanvasSync::Jobs::SyncTermsJob') # Right after SyncTermsJob
123
+ chain.insert({ job: SomeJob }, before: 'CanvasSync::Jobs::SyncTermsJob') # Right before SyncTermsJob
124
+ chain.insert({ job: SomeJob }, with: 'CanvasSync::Jobs::SyncRolesJob') # Alongside SyncRolesJob
125
+ ```
126
+
127
+ Things to know about `insert`:
128
+ - The `before:`/`after:`/`with:` target must appear exactly once in the chain. If it isn't there, or appears more than once, `insert` raises.
129
+ - Most sync jobs run concurrently with each other. `after: 'X'` puts your job after `X` specifically. It can still run alongside the jobs that run next to `X`.
130
+
131
+ ### Per-term jobs
132
+
133
+ `SyncTermsJob` has a sub-chain that runs once for each Term in `term_scope`, with `canvas_term_id` set in `batch_context`. Add to it directly:
134
+
135
+ ```ruby
136
+ chain.get_sub_chain('CanvasSync::Jobs::SyncTermsJob') << { job: MyPerTermJob }
137
+ ```
138
+
139
+ `insert` also searches sub-chains when it looks for a `before:`, `after:`, or `with:` target, so placing a job next to a term-scoped job (for example, `with: 'CanvasSync::Jobs::SyncAssignmentsJob'`) puts it in the per-term sub-chain. Don't target `SyncProvisioningReportJob`. It usually appears twice (once for unscoped models like users, once per term), so `insert` raises.
140
+
141
+ Jobs in the per-term sub-chain run concurrently (up to eight at a time), not in order.
142
+
143
+ ### Jobs that sync a Canvas report
144
+
145
+ If your job's main work is pulling a Canvas report into a table, subclass `CanvasSync::Jobs::ReportSyncTask` instead. It handles starting, polling, downloading, retrying, and caching for you. See [Custom report syncs](custom-reports.md).
146
+
147
+ ### Older name for this section
148
+
149
+ This used to be called "Extensible chain". The API is Joblin's `ChainBuilder`. See [Job orchestration (Joblin)](joblin.md).
150
+
151
+ ## Job Chain options
152
+
153
+ Options can be passed into the job_chain and delivered to specific jobs tied to models.
154
+ For example: options { roles: { show_inherited: true } } will pass "show_inherited" into the SyncRolesJob.
155
+
156
+ * roles
157
+ * `show_inherited` - this applies to the roles model. If it is set to true we will use the "show_inherited" option when pulling roles from Canvas API.
158
+ "show_inherited" will include things like shadow records. It will also include roles from parent accounts if you are not syncing at the root account.
159
+
160
+ * `global` - See "Global Options"
161
+
162
+ ## Global Options
163
+ You can pass in global_options to a job chain. Global options are added to the batch_context and referenced by
164
+ various internal processes.
165
+
166
+ Pass global options into a job chain, using the options param nested in a :global key.
167
+ `options: { global: {...} }`
168
+
169
+ * `report_timeout` - How long a report can run in total before CanvasSync gives up on it. Default is `24.hours`.
170
+ * `report_compilation_timeout` - How long a report can sit in Canvas's `compiling` state before CanvasSync gives up on it. Default is `3.hours`.
171
+ * `report_max_tries` - The number of times to attempt a report before giving up. A report is considered failed if it has an `error` status in Canvas or is deleted. Default is 3.
172
+ * `report_caching` - Turns on report caching for every report in the chain. See [Report caching](custom-reports.md#report-caching).
173
+ * `on_failure` - See [Handling Job errors](#handling-job-errors).
174
+
175
+ Pass timeouts as an `ActiveSupport::Duration` (for example, `2.hours`). A plain Integer is read as a number of days.
176
+
177
+ This is an example job chain with global options:
178
+ ```ruby
179
+ job_chain = CanvasSync.default_provisioning_report_chain(
180
+ MODELS_TO_SYNC,
181
+ term_scope: :active,
182
+ full_sync_every: 'sunday',
183
+ options: { global: { report_timeout: 2.days } }
184
+ )
185
+ ```
186
+
187
+ ## Handling Job errors
188
+
189
+ CanvasSync reports job and Live Event errors through `Rails.error.report` (Rails 7+), so any error tracker that subscribes to the Rails error reporter (Sentry, Honeybadger, Bugsnag, AppSignal, and others) picks them up without extra setup. On older Rails versions, it falls back to `Sentry.capture_exception` if Sentry is loaded.
190
+
191
+ If you need custom handling for when a CanvasSync Job fails, you can add an `:on_failure` option to your chain's global options.
192
+ The value should be a String in the following format: `ModuleOrClass::AnotherModuleOrClass.class_method`.
193
+ The given method of the given class will be called when an error occurs.
194
+ The handling method should accept 2 arguments: `[error, **options]`
195
+
196
+ The current parameters provided in `**options` are:
197
+ - `batch_context` - the chain's shared state (see [Adding custom jobs](#write-the-job))
198
+ - `job_log` - the failing job's `CanvasSync::JobLog`
199
+
200
+ It only runs for jobs that inherit from `CanvasSync::Job`. The original error is still raised after the handler runs.
201
+
202
+ Example:
203
+ ```ruby
204
+ class CanvasSyncStarterWorker
205
+ def perform
206
+ job_chain = CanvasSync.default_provisioning_report_chain(
207
+ %w[desired models],
208
+ options: {
209
+ global: {
210
+ on_failure: 'CanvasSyncStarterWorker.handle_canvas_sync_error',
211
+ }
212
+ }
213
+ )
214
+ end
215
+
216
+ def self.handle_canvas_sync_error(error, **options)
217
+ # Do Stuff
218
+ end
219
+ end
220
+ ```
data/doc/upgrading.md ADDED
@@ -0,0 +1,21 @@
1
+ # Upgrading
2
+
3
+ Re-running the generator when there's been a gem change will give you several choices if it detects conflicts between your local files and the updated generators. You can either view a diff or allow the generator to overwrite your local file. In most cases you may just want to add the code from the diff yourself so as not to break any of your customizations.
4
+
5
+ Additionally, if there have been schema changes to an existing model you may have to run your own migration to bring it up to speed. For example, the Enrollments mapping now includes a `restricted_access` boolean column. Apps generated before that change need to add it:
6
+
7
+ ```ruby
8
+ add_column :enrollments, :restricted_access, :boolean
9
+ ```
10
+
11
+ Also see `CHANGELOG.md`.
12
+
13
+ If you make updates to the gem please add any upgrade instructions to `CHANGELOG.md`.
14
+
15
+ ## Canvas ID as primary key
16
+
17
+ As of 0.26, newly generated models don't have a separate `canvas_id` column. The Canvas ID is stored directly in `id` (see `CanvasSync::Concerns::CanvasIdAsPrimary`). Models generated before 0.26 keep their `canvas_id` column, and CanvasSync still uses it when it's present, so existing apps don't need to change.
18
+
19
+ ## Integrating with existing applications
20
+
21
+ In order for this to work properly your database tables will need to have at least the columns defined in this gem. (Adding additional columns is fine.) As such, you may need to run some migrations to rename existing columns or add missing ones. The generator only works well in a situation where that table does not already exist. Take a look at the migration templates in `lib/canvas_sync/generators/templates` to see what you need.
@@ -0,0 +1,60 @@
1
+ # UserViaPseudonym
2
+
3
+ CanvasSync provides the `CanvasSync::Concerns::UserViaPseudonym` concern for models that need to associate with Canvas users through their pseudonym (login) records. This is particularly useful so that records will always be linked to the correct user, regardless of whether users are merged in Canvas.
4
+
5
+ ## Basic Usage
6
+
7
+ Include the concern in your model and use the `belongs_to_user` class method:
8
+
9
+ ```ruby
10
+ class MyModel < ApplicationRecord
11
+ include CanvasSync::Concerns::UserViaPseudonym
12
+
13
+ # Associate with user using Canvas ID
14
+ belongs_to_user :teacher
15
+
16
+ # Or associate using SIS ID
17
+ belongs_to_user :student, using_sis_id: true
18
+ end
19
+ ```
20
+
21
+ This translates largely into:
22
+ ```ruby
23
+ belongs_to :teacher_pseudonym, class_name: "Pseudonym"
24
+ has_one :teacher, through: :pseudonym, class_name: "User"
25
+
26
+ def user=(u)
27
+ self.pseudonym = u.pseudonyms.active.last || u.pseudonyms.last
28
+ end
29
+ ```
30
+
31
+ ## Cached User IDs (Performance Optimization)
32
+
33
+ For better performance, you can add a cached user ID column to your table. This eliminates the need for joins when you just need the user ID:
34
+
35
+ ```ruby
36
+ # In your migration:
37
+ add_column :my_models, :cached_teacher_user_id, :bigint
38
+ add_index :my_models, :cached_teacher_user_id
39
+
40
+ # In your model:
41
+ class MyModel < ApplicationRecord
42
+ include CanvasSync::Concerns::UserViaPseudonym
43
+
44
+ belongs_to_user :teacher, cache_column: :cached_teacher_user_id
45
+ end
46
+ ```
47
+
48
+ ### Refreshing Cached User IDs
49
+
50
+ When using cached columns, you can refresh them in bulk:
51
+
52
+ ```ruby
53
+ # Refresh all records
54
+ MyModel.update_cached_user_ids!
55
+
56
+ # Or refresh specific records
57
+ MyModel.where(some_condition: true).update_cached_user_ids!
58
+ ```
59
+
60
+ CanvasSync will also do this automatically after syncing.
@@ -1,3 +1,3 @@
1
1
  module CanvasSync
2
- VERSION = "0.27.16".freeze
2
+ VERSION = "0.27.17".freeze
3
3
  end
@@ -67,4 +67,81 @@ RSpec.describe CanvasSync::Api::V1::LiveEventsController, type: :controller do
67
67
  expect(response).to be_successful
68
68
  end
69
69
  end
70
+
71
+ describe "rejections" do
72
+ let(:private_key) { OpenSSL::PKey::RSA.new(2048) }
73
+ let(:jwk) { JSON::JWK.new(private_key) }
74
+ let(:jwks) { JSON::JWK::Set.new([jwk]) }
75
+ let(:root_uuid) { "synthetic-root-uuid" }
76
+ let(:organization) { double("organization", root_account_info: { uuid: root_uuid }) }
77
+ let(:signed_event) { JSON::JWT.new(event.deep_merge(metadata: { root_account_uuid: event_uuid })).sign(jwk).to_s }
78
+ let(:event_uuid) { root_uuid }
79
+
80
+ before :each do
81
+ stub_const("PandaPal", Module.new)
82
+ allow(controller).to receive(:dataservices_jwks).and_return(jwks)
83
+ org = organization
84
+ controller.define_singleton_method(:current_organization) { org }
85
+ end
86
+
87
+ it "dispatches an event for the organization's root account" do
88
+ expect(controller).to receive(:dispatch_event)
89
+ post :process_event, params: { "_json" => signed_event }
90
+ expect(response).to have_http_status(:ok)
91
+ end
92
+
93
+ context "when the event is for another root account" do
94
+ let(:event_uuid) { "another-root-uuid" }
95
+
96
+ it "answers 403 and dispatches nothing" do
97
+ expect(controller).to_not receive(:dispatch_event)
98
+ post :process_event, params: { "_json" => signed_event }
99
+ expect(response).to have_http_status(:forbidden)
100
+ end
101
+ end
102
+
103
+ context "when the event has no root account" do
104
+ let(:event_uuid) { nil }
105
+
106
+ it "answers 403 and dispatches nothing" do
107
+ expect(controller).to_not receive(:dispatch_event)
108
+ post :process_event, params: { "_json" => signed_event }
109
+ expect(response).to have_http_status(:forbidden)
110
+ end
111
+ end
112
+
113
+ context "when there is no organization" do
114
+ let(:organization) { nil }
115
+
116
+ it "answers 403 without exposing the error" do
117
+ expect(controller).to_not receive(:dispatch_event)
118
+ post :process_event, params: { "_json" => signed_event }
119
+ expect(response).to have_http_status(:forbidden)
120
+ expect(response.body).to_not include("undefined method")
121
+ end
122
+ end
123
+
124
+ it "answers 401 with a generic body for a forged signature" do
125
+ forged = JSON::JWT.new(event).sign(JSON::JWK.new(OpenSSL::PKey::RSA.new(2048), kid: jwk[:kid])).to_s
126
+ expect(controller).to_not receive(:dispatch_event)
127
+ post :process_event, params: { "_json" => forged }
128
+ expect(response).to have_http_status(:unauthorized)
129
+ expect(JSON.parse(response.body)).to eq("error" => "Invalid live event")
130
+ end
131
+
132
+ it "answers 422 with a generic body for any other failure" do
133
+ allow(controller).to receive(:transform_ids!).and_raise(NoMethodError, "internal detail")
134
+ post :process_event, params: { "_json" => signed_event }
135
+ expect(response).to have_http_status(:unprocessable_entity)
136
+ expect(response.body).to_not include("internal detail")
137
+ end
138
+
139
+ it "keeps the event payload out of the error log" do
140
+ logged = []
141
+ allow(Rails.logger).to receive(:error) { |line| logged << line }
142
+ allow(controller).to receive(:transform_ids!).and_raise(NoMethodError, "user_id 42660000000000001")
143
+ post :process_event, params: { "_json" => signed_event }
144
+ expect(logged.join).to_not include("42660000000000001")
145
+ end
146
+ end
70
147
  end
data/spec/spec_helper.rb CHANGED
@@ -9,15 +9,15 @@ ENV['REDIS_URL'] ||= 'redis://localhost:6379/9'
9
9
  require "bundler/setup"
10
10
  Bundler.require :default, :development
11
11
 
12
- Combustion::Application.configure do
12
+ # Register application/jwt MIME type for testing
13
+ Mime::Type.register "application/jwt", :jwt
14
+ Combustion.initialize! :active_record, :active_job do
13
15
  config.enable_reloading = true # Required for with_model
14
16
  config.active_support.deprecation = :raise
17
+ config.active_record.belongs_to_required_by_default = false
18
+ config.active_record.default_column_serializer = YAML if ActiveRecord.version >= Gem::Version.new("7.1")
15
19
  end
16
20
 
17
- # Register application/jwt MIME type for testing
18
- Mime::Type.register "application/jwt", :jwt
19
- Combustion.initialize! :active_record, :active_job
20
-
21
21
  require 'rspec/rails'
22
22
  require 'spec_helper'
23
23
  require 'factory_bot_rails'
@@ -4,6 +4,8 @@ require 'sinatra/base'
4
4
  # format by hitting a real Canvas API for the route you're looking at,
5
5
  # and then save the result as a .json file in spec/support/fixtures/canvas_responses
6
6
  class FakeCanvas < Sinatra::Base
7
+ set :host_authorization, permitted_hosts: []
8
+
7
9
  get '/api/v1/accounts/self/terms' do
8
10
  json_response 200, 'terms.json'
9
11
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: canvas_sync
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.27.16
4
+ version: 0.27.17
5
5
  platform: ruby
6
6
  authors:
7
7
  - Instructure CustomDev
@@ -440,6 +440,18 @@ files:
440
440
  - db/migrate/20190916154829_add_fork_count_to_canvas_sync_job_logs.rb
441
441
  - db/migrate/20201018210836_create_canvas_sync_sync_batches.rb
442
442
  - db/migrate/20201030210836_add_full_sync_to_canvas_sync_sync_batch.rb
443
+ - doc/ability-helper.md
444
+ - doc/api-sync.md
445
+ - doc/architecture.md
446
+ - doc/custom-reports.md
447
+ - doc/development.md
448
+ - doc/importing-and-mappings.md
449
+ - doc/job-logs.md
450
+ - doc/joblin.md
451
+ - doc/live-events.md
452
+ - doc/provisioning-sync.md
453
+ - doc/upgrading.md
454
+ - doc/user-via-pseudonym.md
443
455
  - lib/canvas_sync.rb
444
456
  - lib/canvas_sync/api_syncable.rb
445
457
  - lib/canvas_sync/batch_processor.rb