Module: Clickwrap::Lifecycle

Defined in:
lib/clickwrap/lifecycle.rb

Overview

Everything that happens to evidence after it is captured.

The rule that governs all of it: nothing here rewrites history. Withdrawing consent, correcting a declaration, consuming an authorization, expiring an acknowledgment, superseding an agreement — each appends a new event linked to the one it acts on, and updates the current-state projection. The original event stays exactly as it was written, because a receipt has to be able to show both what is true now and what was true then.

The lifecycle each kind gets is the one it actually needs. Consent is withdrawable because someone must be able to change their mind as easily as they agreed. An agreement is not: withdrawing future consent to marketing does not retroactively unmake a contract, and a gem that let it would be recording something false.

Class Method Summary collapse

Class Method Details

.append_lifecycle_event!(event:, event_type:, reason:, actor: nil, extra: {}, &block) ⇒ Object

Appends a linked lifecycle event without touching the projection. Used by holds and dispositions, which record that something happened to the evidence rather than changing what the evidence says.



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/clickwrap/lifecycle.rb', line 365

def append_lifecycle_event!(event:, event_type:, reason:, actor: nil, extra: {}, &block)
  now = Clickwrap.now
  lifecycle_actor = actor || SystemActor.new("clickwrap_lifecycle")
  human_operator = actor.present? && !actor.is_a?(SystemActor)

  Event.transaction do
    # Actor lock BEFORE the event insert (which reserves the chain head):
    # every evidence writer takes these two locks actor-first, the order
    # capture uses, so no two paths can deadlock against each other.
    StatementIdentityLock.acquire_for_actor!(event.actor_reference)

    appended = Event.create!(
      {
        event_type: event_type,
        policy_key: event.policy_key,
        policy_revision_id: event.policy_revision_id,
        root_event_id: event.root_event_id || event.id,
        predecessor_event_id: event.id,
        actor: lifecycle_actor.is_a?(::ActiveRecord::Base) ? lifecycle_actor : nil,
        actor_reference: reference_for(lifecycle_actor),
        tenant_key: event.tenant_key,
        subject_key: event.subject_key,
        capture_channel: "system",
        attribution_method: human_operator ? "operator_session" : "system_process",
        recorded_at_by_server: now,
        reason: reason,
        retention_class_key: event.retention_class_key,
        canonical_schema_version: Clickwrap::CANONICAL_SCHEMA_VERSION,
        gem_version: Clickwrap::VERSION,
        created_at: now
      }.merge(extra)
    )

    block&.call(appended)
    appended.finalize_integrity!
    appended
  end
end


163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/clickwrap/lifecycle.rb', line 163

def change_consent_scope!(statement_key, actor:, because:, subject: nil, tenant: nil,
                          acting_for: nil, http_request: nil, submission: nil, answers: nil)
  require_reason!(because, "Changing consent scope")
  state = find_state!(statement_key, actor: actor, subject: subject, tenant: tenant,
                                     acting_for: acting_for)

  unless state.kind == "consent"
    raise LifecycleError, "Only consent has a changeable scope; #{statement_key} is #{state.kind}."
  end

  Capture.new(
    policy: Clickwrap.policy!(state.policy_key), actor: actor, subject: subject, tenant: tenant,
    http_request: http_request, submission: submission, answers: answers, reason: because,
    acting_for: acting_for,
    event_type: "scope_change", root_event_id: state.root_event_id,
    predecessor_event_id: state.current_event_id,
    statement_action_overrides: { statement_key.to_s => "scope_changed" }
  ).capture!
end

.consume_authorization!(event:, because: nil) ⇒ Object

Consumes a one-time authorization. Called inside the transaction that performs the protected action, after the row lock the capture took, so two concurrent attempts cannot both spend the same authorization.



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
# File 'lib/clickwrap/lifecycle.rb', line 206

def consume_authorization!(event:, because: nil)
  source_event = Event.includes(:statements).find(event.id)
  authorizations = source_event.statements.select(&:one_time?)

  authorizations.map do |authorization|
    ::ActiveRecord::Base.transaction do
      identity = StatementState.identity_for(
        policy_key: source_event.policy_key,
        statement_key: authorization.statement_key,
        actor_reference: source_event.actor_reference,
        tenant_key: source_event.tenant_key,
        subject_key: source_event.subject_key,
        represented_party_reference: source_event.represented_party_reference
      )
      StatementIdentityLock.acquire_for_actor!(source_event.actor_reference)
      StatementIdentityLock.acquire!(identity.fetch(:identity_digest))
      state = StatementState.lock.find_by(
        identity
      )

      if authorization_was_consumed?(source_event, authorization.statement_key)
        raise AlreadyConsumedError,
              "Authorization #{authorization.statement_key} from event #{source_event.id} " \
              "was already consumed. A one-time authorization cannot be spent twice."
      end

      consumed_at = Clickwrap.now
      consumption = append_lifecycle_event!(
        event: source_event,
        event_type: "consumption",
        reason: because.presence || "The one-time authorization was consumed",
        actor: nil
      ) do |appended|
        appended.statements.create!(
          ordinal: 0,
          statement_key: authorization.statement_key,
          kind: authorization.kind,
          action: "consumed",
          assertion_text: "The authorization #{authorization.statement_key} was consumed.",
          assertion_locale: "en",
          required: false,
          optional: false,
          answered: false,
          purpose_key: authorization.purpose_key,
          valid_from: consumed_at,
          created_at: consumed_at
        )
      end

      # A later authorization for the same actor/subject may already be
      # current while an earlier provider result is being reconciled.
      # Record consumption of the earlier authorization without spending
      # or deactivating the later one.
      if state && state.root_event_id.to_s == source_event.id.to_s && state.state == "active"
        CurrentState.transition!(state, to: "consumed", event: consumption, at: consumed_at)
      end

      consumption
    end
  end
end

.correct!(statement_key, actor:, subject: nil, tenant: nil, replaces: nil, acting_for: nil, because: nil, http_request: nil, submission: nil, answers: nil) ⇒ Object

Records a corrected factual statement. A correction does not imply the original was false when it was made — people's circumstances change, and conflating "this changed" with "this was a lie" would be both wrong and unfair to the person who declared it.



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/clickwrap/lifecycle.rb', line 98

def correct!(statement_key, actor:, subject: nil, tenant: nil, replaces: nil,
             acting_for: nil, because: nil, http_request: nil, submission: nil, answers: nil)
  require_reason!(because, "Correcting a declaration or attestation")
  state = find_state!(statement_key, actor: actor, subject: subject, tenant: tenant,
                                     acting_for: acting_for)

  unless Vocabulary.correctable?(state.kind)
    raise LifecycleError,
          "#{statement_key} is a #{state.kind}, which is not corrected. An agreement is " \
          "superseded by a new version; consent is withdrawn and granted again."
  end

  origin = lifecycle_origin!(state, replaces)
  policy = Clickwrap.policy!(state.policy_key)

  Capture.new(
    policy: policy,
    actor: actor,
    subject: subject,
    tenant: tenant,
    acting_for: acting_for,
    http_request: http_request,
    submission: submission,
    answers: answers,
    reason: because,
    event_type: "correction",
    root_event_id: state.root_event_id,
    predecessor_event_id: origin.id,
    statement_action_overrides: { statement_key.to_s => "corrected" }
  ).capture!
end

.exempt!(policy_key, actor:, because:, subject: nil, tenant: nil) ⇒ Object

An explicitly recorded system exemption.

Seeds, imports, invitations, admin actions, and service accounts must never "accept" by omitting a browser parameter or by fabricating a human click. An exemption says plainly that no human action occurred, records who created it and why, and never satisfies agreed_to? — it answers the separate exempted_from? question. There is no "missing checkbox means system account" inference anywhere in this gem.



295
296
297
298
299
300
301
302
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/clickwrap/lifecycle.rb', line 295

def exempt!(policy_key, actor:, because:, subject: nil, tenant: nil)
  require_reason!(because, "Recording an exemption")

  policy = Clickwrap.policy!(policy_key.to_s)

  unless policy.permits_exemptions?
    raise LifecycleError,
          "Policy #{policy.key} does not permit exemptions. If system-created records " \
          "legitimately bypass it, say so in the policy with `permit_exemptions`, so the " \
          "decision is visible in review rather than implied by a call site."
  end

  now = Clickwrap.now
  revision = PolicyRevision.freeze_for(policy)

  ::ActiveRecord::Base.transaction do
    # Actor lock BEFORE the event insert: creating the event reserves the
    # chain head, and every writer must take these two locks in the same
    # order (actor first, chain head second — the order capture uses) or
    # two concurrent paths deadlock against each other.
    StatementIdentityLock.acquire_for_actor!(reference_for(actor))

    event = Event.create!(
      event_type: "exemption",
      policy_key: policy.key,
      policy_revision: revision,
      actor: actor.is_a?(::ActiveRecord::Base) ? actor : nil,
      actor_reference: reference_for(actor),
      # Reference.tenant, never to_s: an Active Record tenant's to_s is a
      # per-process memory address, which would make the exemption
      # permanently unfindable (and no two exemptions equal).
      tenant_key: Reference.tenant(tenant),
      subject: subject.is_a?(::ActiveRecord::Base) ? subject : nil,
      subject_key: StatementState.subject_key_for(subject),
      capture_channel: "system",
      attribution_method: "system_process",
      recorded_at_by_server: now,
      reason: because,
      retention_class_key: policy.retention_class_key,
      canonical_schema_version: Clickwrap::CANONICAL_SCHEMA_VERSION,
      gem_version: Clickwrap::VERSION,
      created_at: now
    )

    policy.statements.each_with_index do |statement, index|
      event.statements.create!(
        ordinal: index,
        statement_key: statement.key,
        kind: statement.kind,
        action: statement.initial_action,
        assertion_text: "Exempted: no human action was recorded for this statement.",
        assertion_locale: "en",
        required: statement.required?,
        optional: statement.optional?,
        answered: false,
        purpose_key: statement.purpose_key,
        valid_from: now,
        created_at: now
      )
    end

    event.finalize_integrity!
    CurrentState.apply!(event.reload)
    event
  end
end

.expected_tenant_key_for(state, tenant) ⇒ Object

The tenant key this state's grant was recorded under, given what the withdrawing caller can see. The state's own policy translates the caller's ambient tenant (:not_applicable policies always record nil); a state whose policy is no longer declared falls back to the raw value, which is the only reading its records can support.



83
84
85
86
87
88
89
90
91
92
# File 'lib/clickwrap/lifecycle.rb', line 83

def expected_tenant_key_for(state, tenant)
  policy = begin
    Clickwrap.policy!(state.policy_key)
  rescue UnknownPolicyError
    nil
  end
  return Reference.tenant(tenant) if policy.nil?

  Reference.tenant(policy.tenant_from_controller(tenant))
end

.expire_due!(at: Clickwrap.now) ⇒ Object

Expires everything past its validity. Reporting and tidiness only: verification evaluates expiry live against the clock, so evidence never becomes wrongly valid because a job did not run — which is also why one contended row (a person withdrawing mid-sweep) skips instead of aborting the whole batch and leaving every later state untouched.



273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/clickwrap/lifecycle.rb', line 273

def expire_due!(at: Clickwrap.now)
  expired = []
  StatementState.due_for_expiry(at).find_each do |state|
    expired << transition!(state, to: "expired", event_type: "expiry", action: "expired",
                                  because: "The validity period recorded at capture ended",
                                  actor: nil, at: at)
  rescue LifecycleError, ::ActiveRecord::ActiveRecordError
    # This row moved under the sweep (withdrawn, consumed, or locked by a
    # live transition). The next sweep — or live verification — owns it.
    next
  end
  expired
end

.renew!(statement_key, actor:, subject: nil, tenant: nil, because: nil, acting_for: nil, http_request: nil, submission: nil, answers: nil) ⇒ Object

A renewal always starts a new validity period rather than extending the old one, so a stale expiry can never quietly survive a renewal.



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/clickwrap/lifecycle.rb', line 132

def renew!(statement_key, actor:, subject: nil, tenant: nil, because: nil,
           acting_for: nil, http_request: nil, submission: nil, answers: nil)
  require_reason!(because, "Renewing a statement")
  state = find_state!(statement_key, actor: actor, subject: subject, tenant: tenant,
                                     acting_for: acting_for)
  policy = Clickwrap.policy!(state.policy_key)
  statement = policy.statement!(statement_key)

  unless statement.expirable? && statement.valid_for.present?
    raise LifecycleError,
          "#{statement_key} is a #{statement.kind} with no validity period, so it cannot be renewed."
  end

  action = statement.kind == "consent" ? "renewed" : statement.initial_action
  Capture.new(
    policy: policy,
    actor: actor,
    subject: subject,
    tenant: tenant,
    acting_for: acting_for,
    http_request: http_request,
    submission: submission,
    answers: answers,
    reason: because,
    event_type: "renewal",
    root_event_id: state.root_event_id,
    predecessor_event_id: state.current_event_id,
    statement_action_overrides: { statement_key.to_s => action }
  ).capture!
end

.revoke!(statement_key, actor:, because:, subject: nil, tenant: nil, acting_for: nil, http_request: nil) ⇒ Object



183
184
185
186
187
188
189
190
191
192
# File 'lib/clickwrap/lifecycle.rb', line 183

def revoke!(statement_key, actor:, because:, subject: nil, tenant: nil,
            acting_for: nil, http_request: nil)
  require_reason!(because, "Revoking an authorization")

  state = find_state!(statement_key, actor: actor, subject: subject, tenant: tenant,
                                     acting_for: acting_for)

  transition!(state, to: "revoked", event_type: "revocation", action: "revoked",
                     because: because, http_request: http_request, actor: actor)
end

.supersede!(statement_key, actor:, subject: nil, tenant: nil, acting_for: nil, because: nil, http_request: nil) ⇒ Object



194
195
196
197
198
199
200
201
# File 'lib/clickwrap/lifecycle.rb', line 194

def supersede!(statement_key, actor:, subject: nil, tenant: nil, acting_for: nil,
               because: nil, http_request: nil)
  state = find_state!(statement_key, actor: actor, subject: subject, tenant: tenant,
                                     acting_for: acting_for)

  transition!(state, to: "superseded", event_type: "supersession", action: "superseded",
                     because: because, http_request: http_request, actor: actor)
end

.withdraw!(purpose_key, actor:, because:, tenant: nil, subject: nil, acting_for: nil, http_request: nil) ⇒ Object

Withdraws a consent purpose. First-class, because consent that cannot be withdrawn as easily as it was given is not what this gem will record as consent — the policy compiler already refused to accept one without a withdrawal route.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/clickwrap/lifecycle.rb', line 24

def withdraw!(purpose_key, actor:, because:, tenant: nil, subject: nil,
              acting_for: nil, http_request: nil)
  require_reason!(because, "Withdrawing consent")

  candidates = StatementState
               .for_actor(reference_for(actor))
               .for_purpose(purpose_key)
               .where(kind: "consent",
                      subject_key: Reference.subject(subject),
                      represented_party_reference: Reference.represented_party(acting_for))
               .to_a

  # Tenant is matched under EACH state's own policy semantics, exactly as
  # the grant was recorded: a consent captured under
  # `tenant_is :not_applicable` lives at a nil tenant key, and the
  # ambient organization in the withdrawing session must not hide it —
  # that would make consent granted personally unwithdrawable the moment
  # the person joins an organization.
  for_purpose = candidates.select do |state|
    state.tenant_key == expected_tenant_key_for(state, tenant)
  end

  states = for_purpose.select { |state| state.state == "active" }

  if states.empty?
    # Two different situations, told apart, because a person pressing
    # "withdraw" twice is not the same as an application withdrawing
    # something that was never granted — and a controller showing the
    # first person an error would be both wrong and alarming.
    if for_purpose.any? { |state| state.state == "withdrawn" }
      raise AlreadyWithdrawnError,
            "Consent for #{purpose_key.inspect} was already withdrawn. Nothing further " \
            "was recorded; withdrawing twice is not an error worth showing a person."
    end

    raise NotWithdrawableError,
          "There is no consent for #{purpose_key.inspect} to withdraw. It was never " \
          "granted — and leaving an optional control unselected creates no grant, so " \
          "there may be nothing here to find."
  end

  # One transaction for every matching state: a person withdrawing a
  # purpose granted under several statements must never end up half
  # withdrawn with an error implying nothing happened.
  events = StatementState.transaction do
    states.map do |state|
      transition!(state, to: "withdrawn", event_type: "withdrawal", action: "withdrawn",
                         because: because, http_request: http_request, actor: actor)
    end
  end

  events.length == 1 ? events.first : events
end