@consiliency/agent-board-schema 1.76.0 → 1.79.0
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.
- package/fixtures/already-applied.json +12 -0
- package/migrations/20261120000200_agent_board_thread_key_serialize.sql +118 -0
- package/migrations/20261121000100_agent_board_thread_key_guards.sql +196 -0
- package/migrations/20261124000100_agent_board_step_up_enforcement.sql +1213 -0
- package/package.json +1 -1
- package/schema-manifest.json +30 -3
- package/src/deployment-drift-main.test.mjs +89 -6
- package/src/deployment-drift.test.mjs +20 -1
- package/src/tooling.test.mjs +9 -2
- package/tests/agent_board_717_message_replay_scope.test.sql +39 -2
- package/tests/agent_board_717_tasking_replay_scope.test.sql +21 -2
- package/tests/agent_board_role_guard.test.sql +3 -1
- package/tests/agent_board_send_outcome.test.sql +39 -1
- package/tests/agent_board_session_identity_approval_revocation.test.sql +5 -0
- package/tests/agent_board_step_up.test.sql +991 -0
- package/tests/agent_board_step_up_helper.test.sql +132 -28
- package/tests/agent_board_thread_key_guards.test.sql +186 -0
- package/tests/agent_board_thread_key_serialize.test.sql +182 -0
- package/tests/agent_board_write_enforcement_class.test.sql +3 -2
- package/tests/catalog/step_up_gated_closure.json +24 -0
- package/tests/fixtures/pgtap-unexposed.sql +9 -4
- package/tests/isolation/expected/create_or_find_thread_same_key_race.out +641 -0
- package/tests/isolation/expected/session_identity_links.out +4 -0
- package/tests/isolation/specs/create_or_find_thread_same_key_race.spec +252 -0
- package/tests/isolation/specs/session_identity_links.spec +5 -0
- package/tests/mutations/669/run.sh +12 -4
- package/tests/mutations/669b/M11_ceil_first.sql +10 -0
- package/tests/mutations/669b/M11_gate_first.sql +10 -0
- package/tests/mutations/669b/M11_grant_first.sql +10 -0
- package/tests/mutations/669b/M11_inv_first.sql +10 -0
- package/tests/mutations/669b/M11_mem_first.sql +10 -0
- package/tests/mutations/669b/M11_readmit_first.sql +10 -0
- package/tests/mutations/669b/M13a_gate_member_preset.sql +12 -0
- package/tests/mutations/669b/M13b_ungate_admin_preset.sql +12 -0
- package/tests/mutations/669b/M16_actor_is_target.sql +14 -0
- package/tests/mutations/669b/M19_drop_readmit.sql +9 -0
- package/tests/mutations/669b/M1_drop_grant.sql +9 -0
- package/tests/mutations/669b/M20_drop_d5_refusal.sql +9 -0
- package/tests/mutations/669b/M21_drop_removal.sql +9 -0
- package/tests/mutations/669b/M21b_only_removed.sql +9 -0
- package/tests/mutations/669b/M21c_gate_members.sql +12 -0
- package/tests/mutations/669b/M21d_requested_state.sql +9 -0
- package/tests/mutations/669b/M23b_api_wrapper_over_audit_writer.sql +6 -0
- package/tests/mutations/669b/M23c_drop_register_type_refusal.sql +9 -0
- package/tests/mutations/669b/M24_drop_kind_refusal.sql +9 -0
- package/tests/mutations/669b/M24b_drop_auth_bind_refusal.sql +9 -0
- package/tests/mutations/669b/M2a_drop_gate.sql +9 -0
- package/tests/mutations/669b/M2b_drop_ceiling.sql +9 -0
- package/tests/mutations/669b/M2c_drop_invite.sql +9 -0
- package/tests/mutations/669b/MAL2_drop_otp.sql +9 -0
- package/tests/mutations/669b/MAL3_admit_passkey.sql +9 -0
- package/tests/mutations/669b/MD7a_no_revocation.sql +2 -0
- package/tests/mutations/669b/MD7b_overwrite_revoked.sql +2 -0
- package/tests/mutations/669b/MD7c_revoke_members.sql +2 -0
- package/tests/mutations/669b/MD7d_revoke_expired.sql +2 -0
- package/tests/mutations/669b/ME1_wrapper_over_gate.sql +7 -0
- package/tests/mutations/669b/MEC2_write_after_helper.sql +10 -0
- package/tests/mutations/669b/MQX_query_to_xml_definer.sql +6 -0
- package/tests/mutations/669b/MQXb_ts_stat_other_schema.sql +4 -0
- package/tests/mutations/669b/MTR_trigger_route.sql +9 -0
- package/tests/mutations/669b/MTRb_new_assign.sql +11 -0
- package/tests/mutations/669b/MTRc_sync_assigns_value.sql +47 -0
- package/tests/mutations/669b/MTX1_tombstone_second_gated_call.sql +15 -0
- package/tests/mutations/669b/MTX2_tombstone_non_delegate_target.sql +10 -0
- package/tests/mutations/669b/MXS_other_schema_names_gated.sql +5 -0
- package/tests/mutations/669b/run.sh +83 -0
- package/tests/mutations/670/M18a_read_operation_default_dropped.sql +11 -0
- package/tests/mutations/670/M18b_read_operation_default_changed.sql +7 -0
- package/tests/mutations/670/M3-DM_helper_on_replay_branch.sql +10 -0
- package/tests/mutations/670/M3-MC_helper_on_replay_branch.sql +10 -0
- package/tests/mutations/s12/M0_identity.sql +56 -0
- package/tests/mutations/s12/M1_serialise_actor_key.sql +57 -0
- package/tests/mutations/s12/M1b_serialise_key_only.sql +57 -0
- package/tests/mutations/s12/M2_unique_index_no_handler.sql +9 -0
- package/tests/mutations/s12/M3_no_trim.sql +56 -0
- package/tests/mutations/s12/M4_casefold.sql +56 -0
- package/tests/mutations/s12/M5_lookup_ignores_actor.sql +56 -0
- package/tests/mutations/s12/M6_reuse_reports_false.sql +56 -0
- package/tests/mutations/s12/run.sh +112 -0
- package/tests/mutations/s12-fix/M0_identity.sql +83 -0
- package/tests/mutations/s12-fix/M10_security_invoker.sql +9 -0
- package/tests/mutations/s12-fix/M11_search_path_changed.sql +9 -0
- package/tests/mutations/s12-fix/M12_reuse_writes_task.sql +84 -0
- package/tests/mutations/s12-fix/M13_dead_inbox_write.sql +84 -0
- package/tests/mutations/s12-fix/M14_metadata_unchecked.sql +78 -0
- package/tests/mutations/s12-fix/M15_metadata_check_after_lock.sql +84 -0
- package/tests/mutations/s12-fix/M16_sql_null_metadata_refused.sql +83 -0
- package/tests/mutations/s12-fix/M17_isolation_unchecked.sql +70 -0
- package/tests/mutations/s12-fix/M18_isolation_check_after_lock.sql +82 -0
- package/tests/mutations/s12-fix/M19_isolation_rr_only.sql +83 -0
- package/tests/mutations/s12-fix/M1_lock_dropped.sql +78 -0
- package/tests/mutations/s12-fix/M1b_lock_key_only.sql +83 -0
- package/tests/mutations/s12-fix/M20_isolation_unsafe_levels_only.sql +83 -0
- package/tests/mutations/s12-fix/M21_isolation_check_miss_path_only.sql +83 -0
- package/tests/mutations/s12-fix/M22_isolation_inverted.sql +83 -0
- package/tests/mutations/s12-fix/M23_isolation_wrong_sqlstate.sql +83 -0
- package/tests/mutations/s12-fix/M24_create_thread_key_unchecked.sql +37 -0
- package/tests/mutations/s12-fix/M25_create_thread_key_nonnull_only.sql +45 -0
- package/tests/mutations/s12-fix/M26_create_thread_key_casefold.sql +45 -0
- package/tests/mutations/s12-fix/M27_create_thread_no_object_guard.sql +45 -0
- package/tests/mutations/s12-fix/M28_create_thread_key_stripped.sql +40 -0
- package/tests/mutations/s12-fix/M29_create_thread_key_nested_refused.sql +45 -0
- package/tests/mutations/s12-fix/M2_lock_actor_only.sql +83 -0
- package/tests/mutations/s12-fix/M30_create_thread_security_invoker.sql +9 -0
- package/tests/mutations/s12-fix/M31_create_thread_search_path_changed.sql +9 -0
- package/tests/mutations/s12-fix/M32_class_new_thread_inserter.sql +14 -0
- package/tests/mutations/s12-fix/M33_class_metadata_update.sql +12 -0
- package/tests/mutations/s12-fix/M33b_class_metadata_update_upper.sql +17 -0
- package/tests/mutations/s12-fix/M33c_class_metadata_update_row_form.sql +16 -0
- package/tests/mutations/s12-fix/M33d_class_metadata_merge_update.sql +16 -0
- package/tests/mutations/s12-fix/M33e_class_metadata_upsert.sql +16 -0
- package/tests/mutations/s12-fix/M34_class_api_role_insert.sql +9 -0
- package/tests/mutations/s12-fix/M3_lock_after_lookup.sql +83 -0
- package/tests/mutations/s12-fix/M4_lock_raw_key.sql +83 -0
- package/tests/mutations/s12-fix/M5_no_trim.sql +83 -0
- package/tests/mutations/s12-fix/M6_casefold.sql +83 -0
- package/tests/mutations/s12-fix/M7_lookup_ignores_actor.sql +82 -0
- package/tests/mutations/s12-fix/M8_reuse_reports_false.sql +83 -0
- package/tests/mutations/s12-fix/M9_blank_key_admitted.sql +83 -0
- package/tests/mutations/s12-fix/run.sh +288 -0
- package/tests/seeds/20261124000100_agent_board_step_up_enforcement.sql.pre.sql +47 -0
|
@@ -0,0 +1,1213 @@
|
|
|
1
|
+
-- #669 STEPUP PR-B: server-side step-up ENFORCEMENT on the gated conferral routes (X4).
|
|
2
|
+
--
|
|
3
|
+
-- Ruling: plans/STEPUP-669-plan.md R1, §11.2 (PR-B), with the §14 binding errata E-0..E-6, which
|
|
4
|
+
-- supersede conflicting text; president rulings R1 (D1-D16) and R2; owner answers Q1/Q3
|
|
5
|
+
-- (2026-11-08). PR-A (20261109000100) laid the authority-neutral helper, predicate, ledger and an
|
|
6
|
+
-- EMPTY allowlist. This migration makes the helper load-bearing.
|
|
7
|
+
--
|
|
8
|
+
-- MERGE AND DEPLOY ARE GATED (§11.3, E-4): G1 Portal emits agent_board_step_up_at in production,
|
|
9
|
+
-- G2 Portal maps MBS01, G3 the UI release is deployed, G4 the MB production census receipt.
|
|
10
|
+
-- scripts/check-stepup-gates.mjs keeps CI red while this file is in the tree and a gate is open.
|
|
11
|
+
--
|
|
12
|
+
-- WHAT CHANGES (each body is a fresh pg_get_functiondef of the tree at 20261109000100 plus only
|
|
13
|
+
-- the #669-marked edits; ACL and COMMENT restated for each, AGENTS.md "Schema-change mechanics"):
|
|
14
|
+
-- GATED (_require_human_step_up is the LAST statement before return, D1):
|
|
15
|
+
-- grant_board_role, set_board_role_gate, set_board_authority_ceiling (every call),
|
|
16
|
+
-- create_invite_link (preset 'admin'), readmit_session_identity (a written role above
|
|
17
|
+
-- member, D4), update_board_membership (another actor takes an owner/admin out of active
|
|
18
|
+
-- standing, keyed on the sink's resulting state, Q1 + E-5).
|
|
19
|
+
-- REFUSED: mint_delegated_child for a human true root with an owner/admin room (D5).
|
|
20
|
+
-- E-3: provision_agent refuses an API kind change (and an API auth-user bind) on an existing
|
|
21
|
+
-- principal.
|
|
22
|
+
-- D11/Q3: _step_up_amr_methods() frozen to {otp,totp} (see section 1).
|
|
23
|
+
-- D7: every unexpired, unrevoked admin-preset invite token is revoked (section 3).
|
|
24
|
+
--
|
|
25
|
+
-- Writes no agent_board.schema_version (stays 8).
|
|
26
|
+
|
|
27
|
+
-- D7 serialization. Taken FIRST and held to commit: SHARE ROW EXCLUSIVE conflicts with the ROW
|
|
28
|
+
-- EXCLUSIVE lock every token INSERT/UPDATE takes, so (a) any create_invite_link that already
|
|
29
|
+
-- inserted a token commits before this migration proceeds, and its token is then seen and revoked
|
|
30
|
+
-- by section 3, and (b) no new token is inserted until the gated body below is committed. The one
|
|
31
|
+
-- residual: a create_invite_link call that had already passed its checks under the OLD body and
|
|
32
|
+
-- was waiting on this lock inserts its (ungated) admin token after this commit. The production
|
|
33
|
+
-- receipt's AFTER count is taken post-commit and must be 0 (§7.7, G4(iii)), which catches it.
|
|
34
|
+
lock table agent_board.board_invite_tokens in share row exclusive mode;
|
|
35
|
+
|
|
36
|
+
do $$
|
|
37
|
+
declare n bigint;
|
|
38
|
+
begin
|
|
39
|
+
select count(*) into n from agent_board.board_invite_tokens t
|
|
40
|
+
where t.preset_role = 'admin' and t.revoked_at is null and t.expires_at > now();
|
|
41
|
+
raise notice '#669 D7 before: % unexpired, unrevoked admin-preset invite token(s)', n;
|
|
42
|
+
end $$;
|
|
43
|
+
|
|
44
|
+
-- =============================================================================
|
|
45
|
+
-- 1. The allowlist freeze (D11, Q3, plan §3.2 and §10.5)
|
|
46
|
+
--
|
|
47
|
+
-- A string goes in only if the owner's Q3 answer admits it AND §10.5 measured that exact string
|
|
48
|
+
-- on the pinned GoTrue image (plans/evidence/669/gotrue-amr-measurement.json, GoTrue v2.197.0):
|
|
49
|
+
-- * totp -- authenticator app (Q3 admits it); measured: TOTP verify writes `totp` and its
|
|
50
|
+
-- timestamp moves on re-verify. ADMITTED.
|
|
51
|
+
-- * otp -- one-time code (Q3 admits code entry); measured for code entry. The same receipt
|
|
52
|
+
-- measured that a magic-link click ALSO writes `otp` (finding 1), and amr cannot tell the two
|
|
53
|
+
-- apart. The owner was asked exactly that on 2026-11-21 and answered "Also allow email codes"
|
|
54
|
+
-- (plans/evidence/669/allowlist-decision.json): magic-link clicks therefore satisfy step-up for
|
|
55
|
+
-- LOCALAUTH humans, accepted explicitly. ADMITTED. (Portal-federated humans never use amr:
|
|
56
|
+
-- they prove the Portal ceremony claim plus its ledger row.)
|
|
57
|
+
-- * passkey, mfa/webauthn, mfa/phone -- not measured (virtual authenticator / test SMS needed).
|
|
58
|
+
-- Off (D11).
|
|
59
|
+
-- scripts/check-step-up-allowlist-freeze.mjs derives this set from the receipt and fails CI
|
|
60
|
+
-- when the database's value differs.
|
|
61
|
+
-- =============================================================================
|
|
62
|
+
create or replace function agent_board._step_up_amr_methods()
|
|
63
|
+
returns text[]
|
|
64
|
+
language sql
|
|
65
|
+
immutable
|
|
66
|
+
parallel safe
|
|
67
|
+
set search_path = ''
|
|
68
|
+
as $$
|
|
69
|
+
select '{otp,totp}'::text[]
|
|
70
|
+
$$;
|
|
71
|
+
|
|
72
|
+
revoke all on function agent_board._step_up_amr_methods()
|
|
73
|
+
from public, anon, authenticated, service_role, agent_board_delegate;
|
|
74
|
+
comment on function agent_board._step_up_amr_methods() is
|
|
75
|
+
'#669 D11/Q3: GoTrue amr methods that count as a fresh LOCALAUTH step-up. Frozen in PR-B to {otp,totp}: (Q3 candidates otp, totp, passkey, mfa/webauthn, mfa/phone) intersected with the strings measured on the pinned GoTrue image (plans/evidence/669/gotrue-amr-measurement.json). otp is also written for a magic-link click; the owner accepted that explicitly on 2026-11-21 (plans/evidence/669/allowlist-decision.json). password, magiclink, recovery, mfa/recovery_code, oauth, sso, token_refresh, passkey/mfa/webauthn/mfa/phone (unmeasured) and unseen strings are not admitted. IMMUTABLE. No API-role EXECUTE.';
|
|
76
|
+
|
|
77
|
+
-- =============================================================================
|
|
78
|
+
-- 2. The chokepoints (bodies from pg_get_functiondef; #669 edits marked inline)
|
|
79
|
+
-- =============================================================================
|
|
80
|
+
|
|
81
|
+
-- =============================================================================
|
|
82
|
+
-- 2.1 grant_board_role
|
|
83
|
+
-- =============================================================================
|
|
84
|
+
CREATE OR REPLACE FUNCTION agent_board.grant_board_role(p_board_id uuid, p_agent_id uuid, p_grantee_role text, p_grantor_agent_id uuid DEFAULT NULL::uuid)
|
|
85
|
+
RETURNS TABLE(board_id uuid, agent_id uuid, role text, updated_at timestamp with time zone)
|
|
86
|
+
LANGUAGE plpgsql
|
|
87
|
+
SECURITY DEFINER
|
|
88
|
+
SET search_path TO 'agent_board', 'public'
|
|
89
|
+
AS $function$
|
|
90
|
+
declare
|
|
91
|
+
v_grantor uuid;
|
|
92
|
+
v_updated agent_board.board_memberships%rowtype;
|
|
93
|
+
-- #674: the target's and the grantor's CURRENT active roles, read in one statement (step 6).
|
|
94
|
+
v_target_role text;
|
|
95
|
+
v_grantor_role text;
|
|
96
|
+
begin
|
|
97
|
+
if p_grantee_role not in ('owner', 'admin', 'member', 'observer') then
|
|
98
|
+
raise exception 'invalid grantee role' using errcode = '22023';
|
|
99
|
+
end if;
|
|
100
|
+
|
|
101
|
+
-- #276, FORCED BY AN EXISTING CLASS ASSERTION, not chosen. Adding the ledger gate makes this
|
|
102
|
+
-- function row-lock `agents` (transitively, through _assert_actor_not_fleet_revoked) as well
|
|
103
|
+
-- as board_memberships, which puts it in the class agent_board_signer_lifecycle.test.sql
|
|
104
|
+
-- section 9 pins from the call-graph closure: every function locking BOTH relations must take
|
|
105
|
+
-- the board advisory lock that serialises them against onboard_federated_fleet_agent. That
|
|
106
|
+
-- assertion FAILED and named this function when the gate was added without this line.
|
|
107
|
+
--
|
|
108
|
+
-- The tempting reply is that this function's order is agents -> board_memberships, the SAME
|
|
109
|
+
-- direction as onboarding, so it cannot close the F4 cycle. That is true today and is exactly
|
|
110
|
+
-- the ordering argument #269 refused: mutual exclusion survives a lock being added downstream,
|
|
111
|
+
-- a re-derived ordering does not. So the lock is taken rather than the assertion relaxed.
|
|
112
|
+
--
|
|
113
|
+
-- It also closes a gap 20260901000110 left open and explicitly declined to determine: this
|
|
114
|
+
-- function reads the ceiling for authorization (via _grant_within_ceiling below) and was one
|
|
115
|
+
-- of the three readers that did NOT take the lock serialising the ceiling row's ABSENCE, so a
|
|
116
|
+
-- concurrent first-ceiling insert could be missed and the read pass as default-owner. It is
|
|
117
|
+
-- now serialised, and agent_board_atomic_fleet_onboarding.test.sql's ceiling-reader registry
|
|
118
|
+
-- records it as such.
|
|
119
|
+
--
|
|
120
|
+
-- FIRST, before any row lock, so both routes are advisory -> agents -> board_memberships.
|
|
121
|
+
-- Re-taking it inside signed_grant_board_role (which already holds it) is a no-op: advisory
|
|
122
|
+
-- transaction locks are re-entrant within a session.
|
|
123
|
+
-- HOSTED (role-writer class): a hosted delegate is a member, never higher.
|
|
124
|
+
perform agent_board._refuse_delegate_membership_target(p_agent_id, 'grant_board_role');
|
|
125
|
+
|
|
126
|
+
perform agent_board._lock_board_authority_ceiling(p_board_id);
|
|
127
|
+
|
|
128
|
+
-- Grantor is the RESOLVED actor. service_role -> supplied arg; authenticated ->
|
|
129
|
+
-- current_agent_id() and raises 42501 if null (suspended/unmapped) or if the
|
|
130
|
+
-- supplied arg <> current_agent_id(). This closes the single-principal escalation.
|
|
131
|
+
v_grantor := agent_board._resolved_actor_agent_id(p_grantor_agent_id, 'p_grantor_agent_id');
|
|
132
|
+
|
|
133
|
+
-- #276. Fleet revocation removes board authority, not only send. Sited HERE — inside the
|
|
134
|
+
-- chokepoint, not in the signed wrapper — because signed_grant_board_role is the only other
|
|
135
|
+
-- referrer of this function in the whole database, so the signed route inherits this check
|
|
136
|
+
-- by construction and the unsigned `authenticated` route (the wider door) is closed by the
|
|
137
|
+
-- same line. Before the membership pre-check so the lock order is agents -> board_memberships,
|
|
138
|
+
-- matching onboard_federated_fleet_agent; below the write it would be the inversion #269
|
|
139
|
+
-- reproduced as `deadlock detected`, and this route has no advisory lock to be rescued by.
|
|
140
|
+
perform agent_board._assert_actor_not_fleet_revoked(v_grantor, 'grant_board_role');
|
|
141
|
+
|
|
142
|
+
-- #674 step 6. ONE statement replaces the bare EXISTS pre-check: the target's active row,
|
|
143
|
+
-- row-locked in NO KEY UPDATE mode, on t only (the mode the UPDATE below takes, only earlier),
|
|
144
|
+
-- LEFT JOINed to the grantor's active row, which is NOT locked. Its snapshot is taken after
|
|
145
|
+
-- the board advisory-lock wait above. After a row-lock wait, READ COMMITTED re-fetches only
|
|
146
|
+
-- the locked row t; the joined grantor row g keeps the statement snapshot's version. That is
|
|
147
|
+
-- benign (plan D5): every grant on this board and link_session_alias are excluded by the
|
|
148
|
+
-- advisory lock, and the one unserialized writer that can change an active grantor's role
|
|
149
|
+
-- (invite-link redeem's rank-max) only RAISES it, so a stale grantor rank is conservative.
|
|
150
|
+
-- A later change (#675's hook) must not rely on g being fresh after this statement.
|
|
151
|
+
-- Both reads are single-row by the partial unique index on active memberships.
|
|
152
|
+
select t.role, g.role
|
|
153
|
+
into v_target_role, v_grantor_role
|
|
154
|
+
from agent_board.board_memberships t
|
|
155
|
+
left join agent_board.board_memberships g
|
|
156
|
+
on g.board_id = t.board_id
|
|
157
|
+
and g.agent_id = v_grantor
|
|
158
|
+
and g.membership_state in ('joined', 'subscribed')
|
|
159
|
+
where t.board_id = p_board_id
|
|
160
|
+
and t.agent_id = p_agent_id
|
|
161
|
+
and t.membership_state in ('joined', 'subscribed')
|
|
162
|
+
for no key update of t;
|
|
163
|
+
if not found then
|
|
164
|
+
raise exception 'grantee has no membership on this board' using errcode = 'P0002';
|
|
165
|
+
end if;
|
|
166
|
+
|
|
167
|
+
-- Ceiling consumption: grantee-bounded against min(grantor role, board ceiling).
|
|
168
|
+
if not agent_board._grant_within_ceiling(v_grantor, p_board_id, p_grantee_role) then
|
|
169
|
+
raise exception 'grant exceeds grantor role or board authority ceiling' using errcode = '42501';
|
|
170
|
+
end if;
|
|
171
|
+
|
|
172
|
+
-- #674 step 8. Two checks for a grantor that is NOT the target (self = the same agent id,
|
|
173
|
+
-- not the same human). C-A (owner decision 3): only an owner or admin may change anyone
|
|
174
|
+
-- else's role. C-B (#674): the grantor must STRICTLY outrank the target's current role, so
|
|
175
|
+
-- equal rank is refused for every rank (owner -> owner, admin -> admin). Both read the roles
|
|
176
|
+
-- step 6 observed. A null role ranks 0, so a missing grantor row fails closed. C-A runs
|
|
177
|
+
-- before C-B; the ceiling above runs before both. Self-grants are exempt from both, and the
|
|
178
|
+
-- ceiling still bounds a self-grant to keep-or-lower.
|
|
179
|
+
if v_grantor is distinct from p_agent_id then
|
|
180
|
+
if agent_board._role_rank(v_grantor_role) < agent_board._role_rank('admin') then
|
|
181
|
+
raise exception 'grant on another member requires owner or admin role' using errcode = '42501';
|
|
182
|
+
end if;
|
|
183
|
+
if agent_board._role_rank(v_grantor_role) <= agent_board._role_rank(v_target_role) then
|
|
184
|
+
raise exception 'grant requires a higher board role than the target' using errcode = '42501';
|
|
185
|
+
end if;
|
|
186
|
+
end if;
|
|
187
|
+
|
|
188
|
+
update agent_board.board_memberships bm
|
|
189
|
+
set role = p_grantee_role,
|
|
190
|
+
updated_at = now()
|
|
191
|
+
where bm.board_id = p_board_id
|
|
192
|
+
and bm.agent_id = p_agent_id
|
|
193
|
+
and bm.membership_state in ('joined', 'subscribed')
|
|
194
|
+
returning * into v_updated;
|
|
195
|
+
|
|
196
|
+
-- CR finding: the state predicate above closes the unauthorized WRITE, but on its own it
|
|
197
|
+
-- CREATES a false-success path. If an eviction commits between the pre-check and this
|
|
198
|
+
-- UPDATE (the TOCTOU window the mirrored predicate exists for), the UPDATE matches zero
|
|
199
|
+
-- rows, v_updated stays NULL, and the RETURN QUERY below would emit ONE ALL-NULL ROW with
|
|
200
|
+
-- no error -- a caller that checks "did I get a row back?" reads that as a completed grant.
|
|
201
|
+
-- Fail closed with the same P0002 the pre-check raises, so the serial and racing cases are
|
|
202
|
+
-- indistinguishable to the caller.
|
|
203
|
+
if not found then
|
|
204
|
+
raise exception 'grantee has no membership on this board' using errcode = 'P0002';
|
|
205
|
+
end if;
|
|
206
|
+
|
|
207
|
+
-- #669 STEPUP PR-B (D1, plan §6.2): the step-up check is the LAST statement before the
|
|
208
|
+
-- function returns, after every refusal, the write and the fleet-revocation assert, so every
|
|
209
|
+
-- authorization refusal (22023, P0002, 42501 incl. fleet_revoked: and last-owner) comes first
|
|
210
|
+
-- by construction and MBS01 means "otherwise allowed; confirm it is you". The raise rolls the
|
|
211
|
+
-- whole transaction back. The helper takes no actor: it judges the SESSION (D2).
|
|
212
|
+
perform agent_board._require_human_step_up('grant_board_role');
|
|
213
|
+
|
|
214
|
+
return query
|
|
215
|
+
select v_updated.board_id, v_updated.agent_id, v_updated.role, v_updated.updated_at;
|
|
216
|
+
end;
|
|
217
|
+
$function$;
|
|
218
|
+
|
|
219
|
+
revoke all on function agent_board.grant_board_role(uuid, uuid, text, uuid)
|
|
220
|
+
from public, anon, authenticated, service_role, agent_board_delegate;
|
|
221
|
+
grant execute on function agent_board.grant_board_role(uuid, uuid, text, uuid) to authenticated, service_role;
|
|
222
|
+
comment on function agent_board.grant_board_role(uuid, uuid, text, uuid) is
|
|
223
|
+
'Live board-role grant chokepoint. Grantor is the resolved actor (_resolved_actor_agent_id: service_role uses the supplied arg, authenticated uses current_agent_id() and fails closed on null/mismatch). #276: the resolved grantor is then checked against the fleet revocation ledger by _assert_actor_not_fleet_revoked -- an agent carrying an agent-subject fleet_revocation_events row cannot complete a grant (42501, ''fleet_revoked:''), which is the same answer evaluate_fleet_sender_policy already gives that principal on the send path. The check sits in THIS function rather than in signed_grant_board_role because signed_grant_board_role is the only other referrer of it in the database, so the signed route inherits the gate and the wider unsigned authenticated route is closed by the same line; it is placed before the membership pre-check so the lock order is agents(FOR SHARE) -> board_memberships, matching onboard_federated_fleet_agent. A principal with no fleet binding has no such row and is unaffected. Then requires an ACTIVE grantee membership (joined|subscribed; P0002 otherwise) -- predicate on both the pre-check and the UPDATE (TOCTOU). Then enforces _grant_within_ceiling(grantor, board, grantee_role) before setting board_memberships.role. ROLERESET (#79): non-active rows cannot be re-armed with an elevated role. #674: the membership pre-check is ONE statement that locks the target''s active row FOR NO KEY UPDATE OF t (the mode the UPDATE takes, only earlier; lock order unchanged: advisory -> agents(SHARE) -> board_memberships) and LEFT JOINs the grantor''s active row, unlocked. After the unchanged ceiling check, a grantor that is not the target (self = the same agent id, not the same human) must be an owner or admin (C-A, 42501 ''grant on another member requires owner or admin role'') and must strictly outrank the target''s CURRENT role (C-B, 42501 ''grant requires a higher board role than the target''), so equal rank is refused for every rank. A self-grant is exempt from both and stays bounded to keep-or-lower by the ceiling. For service_role the checks run relative to the grantor the caller SUPPLIES -- the existing operator-trust boundary, which #674 does not change (passing p_grantor_agent_id = p_agent_id takes the self-exemption). #669 STEPUP PR-B: after the UPDATE and its not-found check, and before return, it calls _require_human_step_up(''grant_board_role'') on every call (D1: the last statement, so every existing refusal comes first; the raise rolls the grant back). A human principal, or a service_role relay token whose sub names a human, needs a fresh step-up proof of its class or gets MBS01 step_up_required; the operator key (no principal, no sub) and agent/system principals are exempt (D3). The helper judges the session, never the supplied grantor or the target (D2).';
|
|
224
|
+
|
|
225
|
+
-- =============================================================================
|
|
226
|
+
-- 2.2 set_board_role_gate
|
|
227
|
+
-- =============================================================================
|
|
228
|
+
CREATE OR REPLACE FUNCTION agent_board.set_board_role_gate(p_board_id uuid, p_enforced boolean)
|
|
229
|
+
RETURNS TABLE(board_id uuid, role_gate_enforced boolean, updated_at timestamp with time zone)
|
|
230
|
+
LANGUAGE plpgsql
|
|
231
|
+
SECURITY DEFINER
|
|
232
|
+
SET search_path TO 'agent_board', 'public'
|
|
233
|
+
AS $function$
|
|
234
|
+
declare
|
|
235
|
+
v_actor uuid := agent_board.current_agent_id();
|
|
236
|
+
v_row agent_board.boards%rowtype;
|
|
237
|
+
begin
|
|
238
|
+
if p_enforced is null then
|
|
239
|
+
raise exception 'p_enforced must not be null' using errcode = '22023';
|
|
240
|
+
end if;
|
|
241
|
+
|
|
242
|
+
-- Owner gate: only an active owner-role member may flip the gate. service_role
|
|
243
|
+
-- (current_agent_id() = null) is not an owner and is rejected here (it keeps its
|
|
244
|
+
-- direct table-write grant for operator provisioning).
|
|
245
|
+
if v_actor is null
|
|
246
|
+
or not exists (
|
|
247
|
+
select 1
|
|
248
|
+
from agent_board.board_memberships bm
|
|
249
|
+
where bm.board_id = p_board_id
|
|
250
|
+
and bm.agent_id = v_actor
|
|
251
|
+
and bm.role = 'owner'
|
|
252
|
+
and bm.membership_state in ('joined', 'subscribed')
|
|
253
|
+
) then
|
|
254
|
+
raise exception 'only a board owner may set the role gate' using errcode = '42501';
|
|
255
|
+
end if;
|
|
256
|
+
|
|
257
|
+
update agent_board.boards b
|
|
258
|
+
set role_gate_enforced = p_enforced,
|
|
259
|
+
updated_at = now()
|
|
260
|
+
where b.id = p_board_id
|
|
261
|
+
returning * into v_row;
|
|
262
|
+
|
|
263
|
+
if v_row.id is null then
|
|
264
|
+
raise exception 'board not found' using errcode = 'P0002';
|
|
265
|
+
end if;
|
|
266
|
+
|
|
267
|
+
-- #276, AFTER the boards UPDATE so this function's order is boards -> agents, the canonical
|
|
268
|
+
-- one (#194). Flipping role_gate_enforced decides whether the creator-identity exemption
|
|
269
|
+
-- applies to invite_board_member and resolve_board_request, so it is an authority write in
|
|
270
|
+
-- the same class as a grant. Same transaction: the raise rolls the UPDATE back.
|
|
271
|
+
perform agent_board._assert_actor_not_fleet_revoked(v_actor, 'set_board_role_gate');
|
|
272
|
+
|
|
273
|
+
-- #669 STEPUP PR-B (D1, plan §6.2): the step-up check is the LAST statement before the
|
|
274
|
+
-- function returns, after every refusal, the write and the fleet-revocation assert, so every
|
|
275
|
+
-- authorization refusal (22023, P0002, 42501 incl. fleet_revoked: and last-owner) comes first
|
|
276
|
+
-- by construction and MBS01 means "otherwise allowed; confirm it is you". The raise rolls the
|
|
277
|
+
-- whole transaction back. The helper takes no actor: it judges the SESSION (D2).
|
|
278
|
+
perform agent_board._require_human_step_up('set_board_role_gate');
|
|
279
|
+
|
|
280
|
+
return query
|
|
281
|
+
select v_row.id, v_row.role_gate_enforced, v_row.updated_at;
|
|
282
|
+
end;
|
|
283
|
+
$function$;
|
|
284
|
+
|
|
285
|
+
revoke all on function agent_board.set_board_role_gate(uuid, boolean)
|
|
286
|
+
from public, anon, authenticated, service_role, agent_board_delegate;
|
|
287
|
+
grant execute on function agent_board.set_board_role_gate(uuid, boolean) to authenticated, service_role;
|
|
288
|
+
comment on function agent_board.set_board_role_gate(uuid, boolean) is
|
|
289
|
+
'Owner-gated setter for a board''s role_gate_enforced flag: UPDATEs boards.role_gate_enforced only when current_agent_id() is an active owner of the board (else 42501; null p_enforced -> 22023; missing board -> P0002). service_role is not an owner here. #276: after the UPDATE it calls _assert_actor_not_fleet_revoked, so an owner carrying an agent-subject fleet_revocation_events row cannot flip the gate (42501, ''fleet_revoked:''); the flag decides whether the creator-identity exemption applies to invite_board_member and resolve_board_request, which makes it an authority write in the same class as a role grant. Placed after the UPDATE so the lock order is boards -> agents, the canonical order (#194); the function is one transaction, so the raise rolls the UPDATE back. #669 STEPUP PR-B: after _assert_actor_not_fleet_revoked and before return, it calls _require_human_step_up(''set_board_role_gate'') on every call (D1), so a human owner needs a fresh step-up proof (else MBS01 step_up_required, the UPDATE rolled back); agent/system principals and the operator key are exempt (D3).';
|
|
290
|
+
|
|
291
|
+
-- =============================================================================
|
|
292
|
+
-- 2.3 set_board_authority_ceiling
|
|
293
|
+
-- =============================================================================
|
|
294
|
+
CREATE OR REPLACE FUNCTION agent_board.set_board_authority_ceiling(p_board_id uuid, p_max_grantable_role text, p_actor_agent_id uuid DEFAULT NULL::uuid)
|
|
295
|
+
RETURNS TABLE(ceiling_board_id uuid, ceiling_max_grantable_role text)
|
|
296
|
+
LANGUAGE plpgsql
|
|
297
|
+
SECURITY DEFINER
|
|
298
|
+
SET search_path TO 'agent_board', 'public'
|
|
299
|
+
AS $function$
|
|
300
|
+
declare
|
|
301
|
+
v_actor uuid;
|
|
302
|
+
begin
|
|
303
|
+
if p_max_grantable_role not in ('owner', 'admin', 'member', 'observer') then
|
|
304
|
+
raise exception 'max_grantable_role must be one of owner/admin/member/observer' using errcode = '22023';
|
|
305
|
+
end if;
|
|
306
|
+
|
|
307
|
+
-- Same board-keyed advisory lock every ceiling READER for authorization takes.
|
|
308
|
+
-- Held to commit, it makes the insert of a first ceiling row serialize against a
|
|
309
|
+
-- concurrent authorization that would otherwise observe the pre-insert ABSENCE and
|
|
310
|
+
-- pass as default-owner. Taken before the owner gate so the gate and the write are
|
|
311
|
+
-- one critical section.
|
|
312
|
+
perform agent_board._lock_board_authority_ceiling(p_board_id);
|
|
313
|
+
|
|
314
|
+
-- #247. Actor resolution, NOT a widening of the gate. With p_actor_agent_id omitted this
|
|
315
|
+
-- is the pre-#247 expression for every role, so no existing caller changes behaviour
|
|
316
|
+
-- (D4). When it IS supplied, _resolved_actor_agent_id binds it: service_role takes the
|
|
317
|
+
-- argument (this is the signed_* gateway path, where the argument is the gateway-VERIFIED
|
|
318
|
+
-- signer, never a raw caller claim), while authenticated still resolves to
|
|
319
|
+
-- current_agent_id() and raises 42501 if the supplied id differs. The owner gate below is
|
|
320
|
+
-- untouched and remains the only thing that authorizes the write.
|
|
321
|
+
if p_actor_agent_id is null then
|
|
322
|
+
v_actor := agent_board.current_agent_id();
|
|
323
|
+
else
|
|
324
|
+
v_actor := agent_board._resolved_actor_agent_id(p_actor_agent_id, 'p_actor_agent_id');
|
|
325
|
+
end if;
|
|
326
|
+
|
|
327
|
+
if v_actor is null
|
|
328
|
+
or not exists (
|
|
329
|
+
select 1
|
|
330
|
+
from agent_board.board_memberships bm
|
|
331
|
+
where bm.board_id = p_board_id
|
|
332
|
+
and bm.agent_id = v_actor
|
|
333
|
+
and bm.role = 'owner'
|
|
334
|
+
and bm.membership_state in ('joined', 'subscribed')
|
|
335
|
+
) then
|
|
336
|
+
raise exception 'only a board owner may set the board authority ceiling' using errcode = '42501';
|
|
337
|
+
end if;
|
|
338
|
+
|
|
339
|
+
insert into agent_board.board_authority_ceilings(board_id, max_grantable_role)
|
|
340
|
+
values (p_board_id, p_max_grantable_role)
|
|
341
|
+
on conflict (board_id) do update
|
|
342
|
+
set max_grantable_role = excluded.max_grantable_role,
|
|
343
|
+
updated_at = now();
|
|
344
|
+
|
|
345
|
+
-- #276, AFTER the upsert by design (see the header's TOTAL ORDERS). The ceiling insert
|
|
346
|
+
-- reaches boards through board_authority_ceilings' FK, so checking here keeps this
|
|
347
|
+
-- function's order advisory -> boards -> agents, which is onboard_federated_fleet_agent's
|
|
348
|
+
-- order and the signed wrapper's. Same transaction: this raise rolls the upsert back, so
|
|
349
|
+
-- position costs nothing in correctness. Raising the ceiling is a strictly larger authority
|
|
350
|
+
-- act than a single grant, so a ledger-revoked owner must not reach it either.
|
|
351
|
+
perform agent_board._assert_actor_not_fleet_revoked(v_actor, 'set_board_authority_ceiling');
|
|
352
|
+
|
|
353
|
+
-- #669 STEPUP PR-B (D1, plan §6.2): the step-up check is the LAST statement before the
|
|
354
|
+
-- function returns, after every refusal, the write and the fleet-revocation assert, so every
|
|
355
|
+
-- authorization refusal (22023, P0002, 42501 incl. fleet_revoked: and last-owner) comes first
|
|
356
|
+
-- by construction and MBS01 means "otherwise allowed; confirm it is you". The raise rolls the
|
|
357
|
+
-- whole transaction back. The helper takes no actor: it judges the SESSION (D2).
|
|
358
|
+
perform agent_board._require_human_step_up('set_board_authority_ceiling');
|
|
359
|
+
|
|
360
|
+
return query
|
|
361
|
+
select p_board_id, p_max_grantable_role;
|
|
362
|
+
end;
|
|
363
|
+
$function$;
|
|
364
|
+
|
|
365
|
+
revoke all on function agent_board.set_board_authority_ceiling(uuid, text, uuid)
|
|
366
|
+
from public, anon, authenticated, service_role, agent_board_delegate;
|
|
367
|
+
grant execute on function agent_board.set_board_authority_ceiling(uuid, text, uuid) to authenticated, service_role;
|
|
368
|
+
comment on function agent_board.set_board_authority_ceiling(uuid, text, uuid) is
|
|
369
|
+
'Owner-gated setter for a board''s authority ceiling: takes the board-keyed _lock_board_authority_ceiling advisory lock, then upserts board_authority_ceilings only when the resolved actor is an owner of the board (else raises 42501). The actor is current_agent_id() when p_actor_agent_id is omitted — the pre-#247 behaviour for every role — and _resolved_actor_agent_id(p_actor_agent_id) when it is supplied, which lets the service_role-only signed_set_board_authority_ceiling gateway act for the gateway-verified signer while still forcing an authenticated caller to match current_agent_id(). #276: after the upsert it calls _assert_actor_not_fleet_revoked, so an actor carrying an agent-subject fleet_revocation_events row cannot raise or lower a board ceiling (42501, ''fleet_revoked:'') — the same principal the send path already refuses. It sits AFTER the upsert, not before, so the lock order stays advisory -> boards -> agents; hoisting it would give agents -> boards and invert against onboard_federated_fleet_agent on the (agents, boards) pair. The function is one transaction, so the raise rolls the upsert back. Leaves _grant_within_ceiling semantics unchanged. #669 STEPUP PR-B: after _assert_actor_not_fleet_revoked and before return, it calls _require_human_step_up(''set_board_authority_ceiling'') on every call (D1): changing the conferrable maximum is an authority act, so a human owner needs a fresh step-up proof (else MBS01 step_up_required, the upsert rolled back). Under service_role the helper judges the token''s sub, not the supplied p_actor_agent_id (D2/D3).';
|
|
370
|
+
|
|
371
|
+
-- =============================================================================
|
|
372
|
+
-- 2.4 create_invite_link
|
|
373
|
+
-- =============================================================================
|
|
374
|
+
CREATE OR REPLACE FUNCTION agent_board.create_invite_link(p_board_id uuid, p_preset_role text, p_preset_membership_state text DEFAULT 'joined'::text, p_max_uses integer DEFAULT NULL::integer, p_expires_at timestamp with time zone DEFAULT NULL::timestamp with time zone, p_created_by_agent_id uuid DEFAULT NULL::uuid, p_metadata jsonb DEFAULT '{}'::jsonb)
|
|
375
|
+
RETURNS TABLE(invite_id uuid, board_id uuid, code text, preset_role text, preset_membership_state text, max_uses integer, uses_count integer, expires_at timestamp with time zone, created_at timestamp with time zone)
|
|
376
|
+
LANGUAGE plpgsql
|
|
377
|
+
SECURITY DEFINER
|
|
378
|
+
SET search_path TO 'agent_board', 'public'
|
|
379
|
+
AS $function$
|
|
380
|
+
declare
|
|
381
|
+
v_creator uuid;
|
|
382
|
+
v_expires timestamptz;
|
|
383
|
+
v_code text;
|
|
384
|
+
v_row agent_board.board_invite_tokens%rowtype;
|
|
385
|
+
begin
|
|
386
|
+
if p_preset_role not in ('owner', 'admin', 'member', 'observer') then
|
|
387
|
+
raise exception 'invalid preset role' using errcode = '22023';
|
|
388
|
+
end if;
|
|
389
|
+
-- R-LINK-3: owner presets are not invite-linkable in v1 (a leaked owner link mints
|
|
390
|
+
-- co-owners). admin presets must be bounded: a use cap AND a short (<= 7d) TTL.
|
|
391
|
+
if p_preset_role = 'owner' then
|
|
392
|
+
raise exception 'owner presets are not invite-linkable' using errcode = '22023';
|
|
393
|
+
end if;
|
|
394
|
+
if coalesce(p_preset_membership_state, 'joined') not in ('joined', 'subscribed') then
|
|
395
|
+
raise exception 'invalid preset membership state' using errcode = '22023';
|
|
396
|
+
end if;
|
|
397
|
+
|
|
398
|
+
-- Effective creator: service_role -> supplied arg (create-on-behalf-of);
|
|
399
|
+
-- authenticated -> current_agent_id() and rejects arg <> current (42501).
|
|
400
|
+
v_creator := agent_board._resolved_actor_agent_id(p_created_by_agent_id, 'p_created_by_agent_id');
|
|
401
|
+
|
|
402
|
+
-- Grantor-bounded at mint: the creator's live authority must cover the preset role.
|
|
403
|
+
if not agent_board._grant_within_ceiling(v_creator, p_board_id, p_preset_role) then
|
|
404
|
+
raise exception 'preset role exceeds creator role or board authority ceiling' using errcode = '42501';
|
|
405
|
+
end if;
|
|
406
|
+
|
|
407
|
+
-- TTL: default 7d, hard cap 30d, reject a past/now expiry.
|
|
408
|
+
v_expires := coalesce(p_expires_at, now() + interval '7 days');
|
|
409
|
+
if v_expires <= now() then
|
|
410
|
+
raise exception 'invite expiry must be in the future' using errcode = '22023';
|
|
411
|
+
end if;
|
|
412
|
+
if v_expires > now() + interval '30 days' then
|
|
413
|
+
v_expires := now() + interval '30 days';
|
|
414
|
+
end if;
|
|
415
|
+
|
|
416
|
+
-- R-LINK-3 (admin): require a use cap and a <= 7d TTL.
|
|
417
|
+
if p_preset_role = 'admin' then
|
|
418
|
+
if p_max_uses is null then
|
|
419
|
+
raise exception 'admin invite links require a bounded p_max_uses' using errcode = '22023';
|
|
420
|
+
end if;
|
|
421
|
+
if v_expires > now() + interval '7 days' then
|
|
422
|
+
raise exception 'admin invite links require a TTL of at most 7 days' using errcode = '22023';
|
|
423
|
+
end if;
|
|
424
|
+
end if;
|
|
425
|
+
|
|
426
|
+
-- 256-bit opaque code, base64url (schema-qualify gen_random_bytes; encode/translate/
|
|
427
|
+
-- rtrim are pg_catalog builtins).
|
|
428
|
+
v_code := rtrim(translate(encode(extensions.gen_random_bytes(32), 'base64'), '+/', '-_'), '=');
|
|
429
|
+
|
|
430
|
+
insert into agent_board.board_invite_tokens as t(
|
|
431
|
+
code, board_id, preset_role, preset_membership_state, max_uses, expires_at,
|
|
432
|
+
created_by_agent_id, metadata
|
|
433
|
+
)
|
|
434
|
+
values (
|
|
435
|
+
v_code, p_board_id, p_preset_role, coalesce(p_preset_membership_state, 'joined'),
|
|
436
|
+
p_max_uses, v_expires, v_creator, coalesce(p_metadata, '{}'::jsonb)
|
|
437
|
+
)
|
|
438
|
+
returning * into v_row;
|
|
439
|
+
|
|
440
|
+
-- #276. AFTER the insert, so the order is boards(KEY SHARE via the token's board_id FK) ->
|
|
441
|
+
-- agents(SHARE) -- see the header. One transaction, so this raise discards the token; a
|
|
442
|
+
-- revoked creator never gets a code back. The `fleet_revoked:` prefix is kept here (unlike
|
|
443
|
+
-- the redeem side) because the caller is asking about ITSELF, so there is no oracle to leak.
|
|
444
|
+
perform agent_board._assert_actor_not_fleet_revoked(v_creator, 'create_invite_link');
|
|
445
|
+
|
|
446
|
+
-- #669 STEPUP PR-B (D1, plan §6.2): the step-up check is the LAST statement before the
|
|
447
|
+
-- function returns, after every refusal, the write and the fleet-revocation assert, so every
|
|
448
|
+
-- authorization refusal (22023, P0002, 42501 incl. fleet_revoked: and last-owner) comes first
|
|
449
|
+
-- by construction and MBS01 means "otherwise allowed; confirm it is you". The raise rolls the
|
|
450
|
+
-- whole transaction back. The helper takes no actor: it judges the SESSION (D2).
|
|
451
|
+
-- An admin-preset link is a deferred grant of admin, so minting one is gated; member and
|
|
452
|
+
-- observer presets are not (A-4). Owner presets were refused above (R-LINK-3).
|
|
453
|
+
if p_preset_role = 'admin' then
|
|
454
|
+
perform agent_board._require_human_step_up('create_invite_link');
|
|
455
|
+
end if;
|
|
456
|
+
|
|
457
|
+
return query
|
|
458
|
+
select v_row.id, v_row.board_id, v_row.code, v_row.preset_role,
|
|
459
|
+
v_row.preset_membership_state, v_row.max_uses, v_row.uses_count,
|
|
460
|
+
v_row.expires_at, v_row.created_at;
|
|
461
|
+
end;
|
|
462
|
+
$function$;
|
|
463
|
+
|
|
464
|
+
revoke all on function agent_board.create_invite_link(uuid, text, text, integer, timestamp with time zone, uuid, jsonb)
|
|
465
|
+
from public, anon, authenticated, service_role, agent_board_delegate;
|
|
466
|
+
grant execute on function agent_board.create_invite_link(uuid, text, text, integer, timestamp with time zone, uuid, jsonb) to authenticated, service_role;
|
|
467
|
+
comment on function agent_board.create_invite_link(uuid, text, text, integer, timestamp with time zone, uuid, jsonb) is
|
|
468
|
+
'Mints a shareable board invite link. Grantor-bounded (creator authority must cover the preset role via _grant_within_ceiling). Forbids owner presets; admin presets require a use cap + <=7d TTL. TTL default 7d, hard-capped 30d. Creator resolved via _resolved_actor_agent_id. Returns the opaque code (creator-only). #276: a creator carrying an agent-subject fleet_revocation_events row cannot mint at all (42501, ''fleet_revoked:'') — an admin-preset link is a deferred grant of admin, so minting one is conferring a board role by another route. The gate calls _assert_actor_not_fleet_revoked (share-locked) and sits AFTER the token insert so the lock order is boards(KEY SHARE via the board_id FK) -> agents; the raise discards the token in the same transaction, so a revoked creator never receives a code. #669 STEPUP PR-B: when p_preset_role = ''admin'', after _assert_actor_not_fleet_revoked and before return, it calls _require_human_step_up(''create_invite_link'') (D1), so a human needs a fresh step-up proof to mint an admin link (else MBS01 step_up_required and no token); member/observer presets are ungated. Its ceiling-lock serialization state is unchanged (#277).';
|
|
469
|
+
|
|
470
|
+
-- =============================================================================
|
|
471
|
+
-- 2.5 readmit_session_identity
|
|
472
|
+
-- =============================================================================
|
|
473
|
+
CREATE OR REPLACE FUNCTION agent_board.readmit_session_identity(p_identity_agent_id uuid, p_child_slug text, p_child_public_key text, p_requested_scopes jsonb DEFAULT '[]'::jsonb, p_requested_rooms jsonb DEFAULT '[]'::jsonb, p_ttl interval DEFAULT NULL::interval)
|
|
474
|
+
RETURNS TABLE(child_agent_id uuid, grant_expires_at timestamp with time zone, signing_key_id uuid)
|
|
475
|
+
LANGUAGE plpgsql
|
|
476
|
+
SECURITY DEFINER
|
|
477
|
+
SET search_path TO 'agent_board', 'public'
|
|
478
|
+
AS $function$
|
|
479
|
+
declare
|
|
480
|
+
v_old agent_board.session_identities%rowtype;
|
|
481
|
+
v_parent agent_board.agents%rowtype;
|
|
482
|
+
v_original_grant agent_board.delegation_grants%rowtype;
|
|
483
|
+
v_policy agent_board.delegation_policies%rowtype;
|
|
484
|
+
v_root uuid;
|
|
485
|
+
v_owner uuid;
|
|
486
|
+
v_parent_scopes jsonb;
|
|
487
|
+
v_requested jsonb := coalesce(p_requested_scopes, '[]'::jsonb);
|
|
488
|
+
v_rooms jsonb := coalesce(p_requested_rooms, '[]'::jsonb);
|
|
489
|
+
v_alias uuid;
|
|
490
|
+
v_new_id uuid := gen_random_uuid();
|
|
491
|
+
v_new_auth uuid;
|
|
492
|
+
v_key_id uuid;
|
|
493
|
+
v_slug text;
|
|
494
|
+
v_expires timestamptz;
|
|
495
|
+
v_ceiling interval;
|
|
496
|
+
v_ancestor_expires timestamptz;
|
|
497
|
+
v_room jsonb;
|
|
498
|
+
v_board uuid;
|
|
499
|
+
v_role text;
|
|
500
|
+
v_old_role text;
|
|
501
|
+
v_membership agent_board.board_memberships%rowtype;
|
|
502
|
+
-- #669 D4: set from the VALIDATED role the room loop writes, never from raw p_requested_rooms.
|
|
503
|
+
v_elevated boolean := false;
|
|
504
|
+
begin
|
|
505
|
+
-- Owner identity comes from this authenticated session, never from an argument.
|
|
506
|
+
if not agent_board._session_identity_owner(p_identity_agent_id) then
|
|
507
|
+
raise exception 'identity readmission requires the human owner' using errcode = '42501';
|
|
508
|
+
end if;
|
|
509
|
+
if jsonb_typeof(v_requested) <> 'array' or jsonb_typeof(v_rooms) <> 'array'
|
|
510
|
+
or p_ttl <= interval '0' then raise exception 'invalid readmission authority request' using errcode = '22023'; end if;
|
|
511
|
+
-- All board locks precede the root/accounting lock and identity rows.
|
|
512
|
+
for v_board in select distinct (r ->> 'board_id')::uuid from jsonb_array_elements(v_rooms) r order by 1 loop
|
|
513
|
+
perform agent_board._lock_board_authority_ceiling(v_board);
|
|
514
|
+
perform 1 from agent_board.boards where id = v_board for key share;
|
|
515
|
+
end loop;
|
|
516
|
+
select root_agent_id into v_root from agent_board.session_identities where agent_id = p_identity_agent_id;
|
|
517
|
+
select owner_user_id into v_owner from agent_board.agents where id = v_root;
|
|
518
|
+
perform 1 from auth.users where id = v_owner for key share;
|
|
519
|
+
perform 1 from agent_board.agents where id = v_root for update;
|
|
520
|
+
select * into v_old from agent_board.session_identities where agent_id = p_identity_agent_id for update;
|
|
521
|
+
if v_old.tombstoned_at is null or v_old.tombstone_reason = 'superseded_unclaimed'
|
|
522
|
+
or v_old.forked_from is null then
|
|
523
|
+
raise exception 'identity readmission requires a revoked fork' using errcode = '42501';
|
|
524
|
+
end if;
|
|
525
|
+
if exists (select 1 from agent_board.session_identities where readmitted_from = p_identity_agent_id) then
|
|
526
|
+
raise exception 'identity_already_readmitted' using errcode = '42501';
|
|
527
|
+
end if;
|
|
528
|
+
select * into v_parent from agent_board.agents where id = v_old.parent_agent_id;
|
|
529
|
+
if v_parent.id is null or v_parent.status <> 'active' or exists (
|
|
530
|
+
select 1 from agent_board.session_identities where agent_id = v_parent.id and tombstoned_at is not null
|
|
531
|
+
) then raise exception 'identity_parent_inactive' using errcode = '42501'; end if;
|
|
532
|
+
v_ancestor_expires := agent_board._session_identity_ancestor_ceiling(v_parent.id);
|
|
533
|
+
select * into v_original_grant from agent_board.delegation_grants g where g.child_agent_id = p_identity_agent_id;
|
|
534
|
+
select * into v_policy from agent_board.delegation_policies dp
|
|
535
|
+
where dp.root_agent_id = v_root and dp.revoked_at is null order by dp.created_at desc, dp.id desc limit 1 for update;
|
|
536
|
+
if not found or v_policy.mode <> 'root_minted' then
|
|
537
|
+
raise exception 'identity_parent_inactive' using errcode = '42501';
|
|
538
|
+
end if;
|
|
539
|
+
if v_parent.parent_agent_id is null then v_parent_scopes := v_policy.allowed_scopes;
|
|
540
|
+
else select g.granted_scopes into v_parent_scopes from agent_board.delegation_grants g where g.child_agent_id = v_parent.id;
|
|
541
|
+
end if;
|
|
542
|
+
if not (coalesce(v_parent_scopes, '[]'::jsonb) @> v_requested)
|
|
543
|
+
or not (coalesce(v_original_grant.granted_scopes, '[]'::jsonb) @> v_requested) then
|
|
544
|
+
raise exception 'scope_exceeded: readmission cannot widen original or parent scopes' using errcode = '42501';
|
|
545
|
+
end if;
|
|
546
|
+
perform agent_board._session_identity_check_limits(v_root, v_parent.id);
|
|
547
|
+
-- The most recently bound alias is reserved; no caller supplies a session id.
|
|
548
|
+
select a.id into v_alias from agent_board.session_id_aliases a
|
|
549
|
+
where a.identity_agent_id = p_identity_agent_id and a.id = v_old.lease_alias_id for update;
|
|
550
|
+
if v_alias is null then raise exception 'identity_continuity_refused' using errcode = '42501'; end if;
|
|
551
|
+
v_slug := agent_board._normalize_provision_slug(p_child_slug);
|
|
552
|
+
if exists (select 1 from agent_board.agents where handle = v_slug) then
|
|
553
|
+
raise exception 'readmission requires a new unique agent handle' using errcode = '23505';
|
|
554
|
+
end if;
|
|
555
|
+
if p_child_public_key is null or p_child_public_key = repeat('A', 43) then
|
|
556
|
+
raise exception 'readmission requires a fresh child public key' using errcode = '22023';
|
|
557
|
+
end if;
|
|
558
|
+
if exists (select 1 from agent_board.agent_signing_keys k where k.agent_id = p_identity_agent_id and k.public_key = p_child_public_key) then
|
|
559
|
+
raise exception 'readmission cannot reuse the revoked key' using errcode = '42501';
|
|
560
|
+
end if;
|
|
561
|
+
v_new_auth := agent_board._ensure_agent_auth_user(v_slug);
|
|
562
|
+
v_ceiling := least(v_policy.child_ttl_ceiling, v_policy.operator_child_ttl_ceiling, interval '24 hours');
|
|
563
|
+
v_expires := least(now() + least(coalesce(p_ttl, v_ceiling), v_ceiling), v_ancestor_expires);
|
|
564
|
+
insert into agent_board.agents(id, agent_type, kind, handle, display_name, status, auth_user_id, owner_user_id,
|
|
565
|
+
parent_agent_id, root_agent_id, metadata)
|
|
566
|
+
values (v_new_id, 'agent', 'agent'::agent_board.agent_kind, v_slug, agent_board._default_provision_display_name(v_slug),
|
|
567
|
+
'active', v_new_auth, v_parent.owner_user_id, v_parent.id, v_root, jsonb_build_object('readmittedFrom', p_identity_agent_id));
|
|
568
|
+
insert into agent_board.agent_signing_keys(agent_id, key_id, key_version, public_key, public_key_format,
|
|
569
|
+
fingerprint, status, proof_state, metadata)
|
|
570
|
+
values (v_new_id, 'readmitted-ephemeral', 1, p_child_public_key, 'raw_ed25519_base64url',
|
|
571
|
+
agent_board._raw_key_fingerprint(p_child_public_key), 'pending_proof', 'unproven', jsonb_build_object('readmittedFrom', p_identity_agent_id))
|
|
572
|
+
returning id into v_key_id;
|
|
573
|
+
insert into agent_board.delegation_grants(child_agent_id, root_agent_id, parent_agent_id, delegation_policy_id,
|
|
574
|
+
granted_scopes, grant_expires_at)
|
|
575
|
+
values (v_new_id, v_root, v_parent.id, v_policy.id, v_requested, v_expires);
|
|
576
|
+
insert into agent_board.session_identities(agent_id, parent_agent_id, root_agent_id, depth, identity_kind, harness,
|
|
577
|
+
forked_from, readmitted_from, current_risky_digest, recorded_fingerprint, resolution_state)
|
|
578
|
+
values (v_new_id, v_parent.id, v_root, v_old.depth, 'session', v_old.harness, v_old.forked_from,
|
|
579
|
+
p_identity_agent_id, v_old.current_risky_digest, v_old.recorded_fingerprint, 'frozen');
|
|
580
|
+
update agent_board.session_id_aliases set identity_agent_id = v_new_id where identity_agent_id = p_identity_agent_id;
|
|
581
|
+
update agent_board.session_identities set lease_alias_id = v_alias where agent_id = v_new_id;
|
|
582
|
+
perform agent_board._refuse_delegate_membership_target(v_new_id, 'readmit_session_identity');
|
|
583
|
+
for v_room in select value from jsonb_array_elements(v_rooms) order by value ->> 'board_id' loop
|
|
584
|
+
v_board := (v_room ->> 'board_id')::uuid;
|
|
585
|
+
v_role := v_room ->> 'role';
|
|
586
|
+
select bm.role into v_old_role from agent_board.board_memberships bm
|
|
587
|
+
where bm.board_id = v_board and bm.agent_id = p_identity_agent_id
|
|
588
|
+
order by case when bm.membership_state in ('joined', 'subscribed') then 0 else 1 end,
|
|
589
|
+
bm.created_at desc, bm.id desc limit 1;
|
|
590
|
+
if v_role not in ('owner', 'admin', 'member', 'observer') or v_role is null or v_old_role is null
|
|
591
|
+
or agent_board._role_rank(v_role) > agent_board._role_rank(v_old_role)
|
|
592
|
+
or not agent_board._grant_within_ceiling(v_parent.id, v_board, v_role) then
|
|
593
|
+
raise exception 'room_authority_exceeded' using errcode = '42501';
|
|
594
|
+
end if;
|
|
595
|
+
-- #669 D4: computed only after the room_authority_exceeded check accepted v_role.
|
|
596
|
+
v_elevated := v_elevated or agent_board._role_rank(v_role) > agent_board._role_rank('member');
|
|
597
|
+
select * into v_membership from agent_board._upsert_board_membership_state(v_board, v_new_id, 'joined');
|
|
598
|
+
update agent_board.board_memberships set role = v_role where id = v_membership.id;
|
|
599
|
+
end loop;
|
|
600
|
+
perform agent_board._assert_actor_not_fleet_revoked(agent_board.current_agent_id(), 'readmit_session_identity');
|
|
601
|
+
-- #669 STEPUP PR-B (D1, plan §6.2): the step-up check is the LAST statement before the
|
|
602
|
+
-- function returns, after every refusal, the write and the fleet-revocation assert, so every
|
|
603
|
+
-- authorization refusal (22023, P0002, 42501 incl. fleet_revoked: and last-owner) comes first
|
|
604
|
+
-- by construction and MBS01 means "otherwise allowed; confirm it is you". The raise rolls the
|
|
605
|
+
-- whole transaction back. The helper takes no actor: it judges the SESSION (D2).
|
|
606
|
+
-- D4: only when a written room role ranks above member; a member/observer readmission is
|
|
607
|
+
-- ungated (A-9b). MBS01 rolls back the new agent, key, grant, identity and memberships.
|
|
608
|
+
if v_elevated then
|
|
609
|
+
perform agent_board._require_human_step_up('readmit_session_identity');
|
|
610
|
+
end if;
|
|
611
|
+
return query select v_new_id, v_expires, v_key_id;
|
|
612
|
+
end;
|
|
613
|
+
$function$;
|
|
614
|
+
|
|
615
|
+
revoke all on function agent_board.readmit_session_identity(uuid, text, text, jsonb, jsonb, interval)
|
|
616
|
+
from public, anon, authenticated, service_role, agent_board_delegate;
|
|
617
|
+
grant execute on function agent_board.readmit_session_identity(uuid, text, text, jsonb, jsonb, interval) to authenticated;
|
|
618
|
+
comment on function agent_board.readmit_session_identity(uuid, text, text, jsonb, jsonb, interval) is
|
|
619
|
+
'Human root owner readmits a selected revoked fork by minting a fresh principal, unclaimed frozen identity and pending fresh key. The old principal, key and permanent ledger remain revoked. Parent/original scopes and roles only shrink, all ancestors and mint quotas are checked under the root lock, all aliases repoint and the latest is reserved. Approve the resolved fingerprint and prove the pending key via record_signing_key_proof_result before first claim. #669 STEPUP PR-B (D4): when any room role the loop writes (validated by room_authority_exceeded) ranks above member, it calls _require_human_step_up(''readmit_session_identity'') after _assert_actor_not_fleet_revoked and before return, so the human owner needs a fresh step-up proof (else MBS01 step_up_required and every new row is rolled back). A member/observer-only readmission is ungated.';
|
|
620
|
+
|
|
621
|
+
-- =============================================================================
|
|
622
|
+
-- 2.6 update_board_membership
|
|
623
|
+
-- =============================================================================
|
|
624
|
+
CREATE OR REPLACE FUNCTION agent_board.update_board_membership(p_board_id uuid, p_agent_id uuid, p_membership_state text, p_metadata jsonb DEFAULT '{}'::jsonb)
|
|
625
|
+
RETURNS TABLE(membership_id uuid, board_id uuid, agent_id uuid, membership_state text, left_at timestamp with time zone, updated_at timestamp with time zone)
|
|
626
|
+
LANGUAGE plpgsql
|
|
627
|
+
SECURITY DEFINER
|
|
628
|
+
SET search_path TO 'agent_board', 'public'
|
|
629
|
+
AS $function$
|
|
630
|
+
declare
|
|
631
|
+
v_membership agent_board.board_memberships%rowtype;
|
|
632
|
+
v_board agent_board.boards%rowtype;
|
|
633
|
+
v_actor uuid := agent_board.current_agent_id();
|
|
634
|
+
v_is_service boolean := agent_board._is_service_role();
|
|
635
|
+
v_existing_state text;
|
|
636
|
+
v_target_role text;
|
|
637
|
+
v_actor_role text;
|
|
638
|
+
-- HOSTED (D7): the caller is the target hosted delegate's principal asking for `left`.
|
|
639
|
+
v_principal_withdraw boolean;
|
|
640
|
+
begin
|
|
641
|
+
if v_actor is null and not v_is_service then
|
|
642
|
+
raise exception 'current agent principal not resolved' using errcode = '42501';
|
|
643
|
+
end if;
|
|
644
|
+
|
|
645
|
+
-- Board authority lock first, before the target row and the sink's FK locks.
|
|
646
|
+
perform agent_board._lock_board_authority_ceiling(p_board_id);
|
|
647
|
+
|
|
648
|
+
v_principal_withdraw := not v_is_service
|
|
649
|
+
and v_actor <> p_agent_id
|
|
650
|
+
and p_membership_state = 'left'
|
|
651
|
+
and v_actor = agent_board._delegate_principal_agent_id(p_agent_id);
|
|
652
|
+
|
|
653
|
+
if not v_is_service and v_actor <> p_agent_id and not v_principal_withdraw then
|
|
654
|
+
select * into v_board from agent_board.boards where id = p_board_id and status = 'active';
|
|
655
|
+
if v_board.id is null then
|
|
656
|
+
raise exception 'board not found' using errcode = 'P0002';
|
|
657
|
+
end if;
|
|
658
|
+
select bm.role
|
|
659
|
+
into v_actor_role
|
|
660
|
+
from agent_board.board_memberships bm
|
|
661
|
+
where bm.board_id = p_board_id
|
|
662
|
+
and bm.agent_id = v_actor
|
|
663
|
+
and bm.membership_state in ('joined', 'subscribed')
|
|
664
|
+
limit 1;
|
|
665
|
+
if v_actor_role is null or v_actor_role not in ('owner', 'admin') then
|
|
666
|
+
raise exception 'board membership change requires owner or admin role'
|
|
667
|
+
using errcode = '42501';
|
|
668
|
+
end if;
|
|
669
|
+
end if;
|
|
670
|
+
|
|
671
|
+
-- HOSTED: LOCKED, so every transition rule below is decided on the state the sink will
|
|
672
|
+
-- overwrite. Unlocked, an admin's uncommitted `removed` committed after this read, and the D7
|
|
673
|
+
-- withdrawal (and an ordinary self-leave, the same branch shape) then wrote `left` over it in
|
|
674
|
+
-- the sink, erasing the eviction R-LINK-7 reads (hosted_delegate_withdraw_evict_race). The
|
|
675
|
+
-- sink's own first lock is this same row in the same order, so the lock set is unchanged;
|
|
676
|
+
-- it is only taken earlier, before reads that lock nothing.
|
|
677
|
+
select bm.membership_state, bm.role
|
|
678
|
+
into v_existing_state, v_target_role
|
|
679
|
+
from agent_board.board_memberships bm
|
|
680
|
+
where bm.board_id = p_board_id
|
|
681
|
+
and bm.agent_id = p_agent_id
|
|
682
|
+
order by
|
|
683
|
+
case when bm.membership_state in ('joined', 'subscribed') then 0 else 1 end,
|
|
684
|
+
bm.created_at desc,
|
|
685
|
+
bm.id desc
|
|
686
|
+
limit 1
|
|
687
|
+
for update;
|
|
688
|
+
if v_existing_state is null then
|
|
689
|
+
raise exception 'board membership not found' using errcode = 'P0002';
|
|
690
|
+
end if;
|
|
691
|
+
|
|
692
|
+
if v_principal_withdraw then
|
|
693
|
+
-- HOSTED (D7): the owner withdraws its own delegate whatever its board role, but ONLY from
|
|
694
|
+
-- the states a self-leave may leave. Never from `removed`: turning an eviction into `left`
|
|
695
|
+
-- would erase the standing R-LINK-7 reads and let the owner re-add the evicted delegate.
|
|
696
|
+
if v_existing_state not in ('joined', 'subscribed', 'invited', 'requested') then
|
|
697
|
+
raise exception 'a principal may withdraw its delegate only from an active or pending membership'
|
|
698
|
+
using errcode = '42501';
|
|
699
|
+
end if;
|
|
700
|
+
elsif not v_is_service then
|
|
701
|
+
if v_actor = p_agent_id then
|
|
702
|
+
if not (
|
|
703
|
+
(p_membership_state = 'left'
|
|
704
|
+
and v_existing_state in ('joined', 'subscribed', 'invited', 'requested'))
|
|
705
|
+
or (p_membership_state in ('joined', 'subscribed')
|
|
706
|
+
and v_existing_state in ('joined', 'subscribed'))
|
|
707
|
+
or (p_membership_state = v_existing_state
|
|
708
|
+
and p_membership_state in ('left', 'removed'))
|
|
709
|
+
) then
|
|
710
|
+
raise exception 'self membership change not permitted; use the join/approval path'
|
|
711
|
+
using errcode = '42501';
|
|
712
|
+
end if;
|
|
713
|
+
else
|
|
714
|
+
if agent_board._role_rank(v_actor_role)
|
|
715
|
+
<= agent_board._role_rank(
|
|
716
|
+
case
|
|
717
|
+
when p_membership_state in ('joined', 'subscribed')
|
|
718
|
+
and coalesce(v_existing_state, '') not in ('joined', 'subscribed')
|
|
719
|
+
then 'member'
|
|
720
|
+
else coalesce(v_target_role, '')
|
|
721
|
+
end) then
|
|
722
|
+
raise exception 'board membership change requires a higher board role than the target'
|
|
723
|
+
using errcode = '42501';
|
|
724
|
+
end if;
|
|
725
|
+
|
|
726
|
+
if p_membership_state in ('joined', 'subscribed')
|
|
727
|
+
and coalesce(v_existing_state, '') not in ('joined', 'subscribed')
|
|
728
|
+
and not agent_board._membership_consent_present(p_board_id, p_agent_id) then
|
|
729
|
+
raise exception 'admitting % requires an act by that agent', p_agent_id
|
|
730
|
+
using errcode = '42501';
|
|
731
|
+
end if;
|
|
732
|
+
|
|
733
|
+
-- INVITEPOLICY (#90): seating an inbound-disclosure membership ('invited'/'requested')
|
|
734
|
+
-- for a target that has blocked THIS actor is refused, mirroring invite_board_member.
|
|
735
|
+
-- Without this, an owner/admin re-seats the exact row the block refuses. Active-admission
|
|
736
|
+
-- states are already consent-gated above; service_role/self never reach this branch.
|
|
737
|
+
if p_membership_state in ('invited', 'requested')
|
|
738
|
+
and not agent_board._invite_permitted(p_board_id, p_agent_id, v_actor) then
|
|
739
|
+
raise exception 'target has blocked invitations from this inviter on this board'
|
|
740
|
+
using errcode = '42501';
|
|
741
|
+
end if;
|
|
742
|
+
end if;
|
|
743
|
+
end if;
|
|
744
|
+
|
|
745
|
+
if not v_is_service
|
|
746
|
+
and p_membership_state = v_existing_state
|
|
747
|
+
and p_membership_state in ('left', 'removed') then
|
|
748
|
+
return query
|
|
749
|
+
select bm.id, bm.board_id, bm.agent_id, bm.membership_state, bm.left_at, bm.updated_at
|
|
750
|
+
from agent_board.board_memberships bm
|
|
751
|
+
where bm.board_id = p_board_id
|
|
752
|
+
and bm.agent_id = p_agent_id
|
|
753
|
+
order by
|
|
754
|
+
case when bm.membership_state in ('joined', 'subscribed') then 0 else 1 end,
|
|
755
|
+
bm.created_at desc,
|
|
756
|
+
bm.id desc
|
|
757
|
+
limit 1;
|
|
758
|
+
return;
|
|
759
|
+
end if;
|
|
760
|
+
|
|
761
|
+
select * into v_membership
|
|
762
|
+
from agent_board._upsert_board_membership_state(
|
|
763
|
+
p_board_id,
|
|
764
|
+
p_agent_id,
|
|
765
|
+
p_membership_state,
|
|
766
|
+
null,
|
|
767
|
+
p_metadata
|
|
768
|
+
);
|
|
769
|
+
|
|
770
|
+
-- #669 STEPUP PR-B (D1, plan §6.2): the step-up check is the LAST statement before the
|
|
771
|
+
-- function returns, after every refusal, the write and the fleet-revocation assert, so every
|
|
772
|
+
-- authorization refusal (22023, P0002, 42501 incl. fleet_revoked: and last-owner) comes first
|
|
773
|
+
-- by construction and MBS01 means "otherwise allowed; confirm it is you". The raise rolls the
|
|
774
|
+
-- whole transaction back. The helper takes no actor: it judges the SESSION (D2).
|
|
775
|
+
-- Q1 as amended by E-5: another actor takes an owner/admin target out of active standing.
|
|
776
|
+
-- Keyed on the target's role and prior state read FOR UPDATE above, and on the state the SINK
|
|
777
|
+
-- RESULTED in, never on the requested state: the #317 sink suppresses an offer (`invited`/
|
|
778
|
+
-- `requested`) over an active row, so a re-invite of an active admin keeps it joined and is
|
|
779
|
+
-- ungated (A-11d), while `removed` or `left` set by another member is gated (R-17/R-17b).
|
|
780
|
+
-- IS DISTINCT FROM: a NULL actor (the operator key) reaches the helper, which exempts it.
|
|
781
|
+
-- coalesce: a NULL resulting state must gate, never pass by three-valued logic.
|
|
782
|
+
if v_actor is distinct from p_agent_id
|
|
783
|
+
and v_target_role in ('owner', 'admin')
|
|
784
|
+
and v_existing_state in ('joined', 'subscribed')
|
|
785
|
+
and coalesce(v_membership.membership_state, '') not in ('joined', 'subscribed') then
|
|
786
|
+
perform agent_board._require_human_step_up('update_board_membership');
|
|
787
|
+
end if;
|
|
788
|
+
|
|
789
|
+
return query
|
|
790
|
+
select v_membership.id, v_membership.board_id, v_membership.agent_id, v_membership.membership_state, v_membership.left_at, v_membership.updated_at;
|
|
791
|
+
end;
|
|
792
|
+
$function$;
|
|
793
|
+
|
|
794
|
+
revoke all on function agent_board.update_board_membership(uuid, uuid, text, jsonb)
|
|
795
|
+
from public, anon, authenticated, service_role, agent_board_delegate;
|
|
796
|
+
grant execute on function agent_board.update_board_membership(uuid, uuid, text, jsonb) to authenticated, service_role;
|
|
797
|
+
comment on function agent_board.update_board_membership(uuid, uuid, text, jsonb) is
|
|
798
|
+
'Authorized membership state transitions with existing self, principal-withdrawal, rank, consent and idempotency rules. Consiliency/message-board#675: board advisory lock before target membership/FK locks; the table refuses any transition removing the last active owner. #669 STEPUP PR-B (Q1, E-5): after the membership sink and before the final return, when the actor is not the target, the target''s role (read FOR UPDATE before the write) is owner or admin, its prior state was joined/subscribed and the sink''s RESULTING state is not joined/subscribed, it calls _require_human_step_up(''update_board_membership''), so a human removing an owner/admin, or setting one to left, needs a fresh step-up proof (else MBS01 step_up_required, the transition rolled back). Ordinary members, self transitions, idempotent no-ops and a re-invite the sink suppresses are ungated.';
|
|
799
|
+
|
|
800
|
+
-- =============================================================================
|
|
801
|
+
-- 2.7 mint_delegated_child
|
|
802
|
+
-- =============================================================================
|
|
803
|
+
CREATE OR REPLACE FUNCTION agent_board.mint_delegated_child(p_root_agent_id uuid, p_child_slug text, p_requested_scopes jsonb, p_child_public_key text DEFAULT NULL::text, p_ttl interval DEFAULT NULL::interval, p_self_service boolean DEFAULT false, p_session_harness text DEFAULT NULL::text, p_session_id text DEFAULT NULL::text, p_minter_lease_epoch text DEFAULT NULL::text, p_requested_rooms jsonb DEFAULT '[]'::jsonb, p_fingerprint jsonb DEFAULT NULL::jsonb, p_forked_from uuid DEFAULT NULL::uuid)
|
|
804
|
+
RETURNS TABLE(child_agent_id uuid, grant_expires_at timestamp with time zone, signing_key_id uuid)
|
|
805
|
+
LANGUAGE plpgsql
|
|
806
|
+
SECURITY DEFINER
|
|
807
|
+
SET search_path TO 'agent_board', 'public'
|
|
808
|
+
AS $function$
|
|
809
|
+
declare
|
|
810
|
+
v_minter agent_board.session_identities%rowtype;
|
|
811
|
+
v_root agent_board.agents%rowtype;
|
|
812
|
+
v_policy agent_board.delegation_policies%rowtype;
|
|
813
|
+
v_true_root uuid;
|
|
814
|
+
v_depth smallint;
|
|
815
|
+
v_allowed jsonb;
|
|
816
|
+
v_requested jsonb := coalesce(p_requested_scopes, '[]'::jsonb);
|
|
817
|
+
v_child_id uuid;
|
|
818
|
+
v_key_id uuid;
|
|
819
|
+
v_child_auth uuid;
|
|
820
|
+
v_slug text;
|
|
821
|
+
v_ceiling interval;
|
|
822
|
+
v_ancestor_expires timestamptz := 'infinity';
|
|
823
|
+
v_expires timestamptz;
|
|
824
|
+
v_room jsonb;
|
|
825
|
+
v_board uuid;
|
|
826
|
+
v_role text;
|
|
827
|
+
v_parent_role text;
|
|
828
|
+
v_membership agent_board.board_memberships%rowtype;
|
|
829
|
+
v_approved text;
|
|
830
|
+
v_reserved agent_board.session_identities%rowtype;
|
|
831
|
+
v_reserved_id uuid;
|
|
832
|
+
v_reserved_alias uuid;
|
|
833
|
+
v_owner uuid;
|
|
834
|
+
begin
|
|
835
|
+
if not agent_board._is_service_role() then
|
|
836
|
+
raise exception 'mint_delegated_child is service_role-only' using errcode = '42501';
|
|
837
|
+
end if;
|
|
838
|
+
if p_ttl is not null and p_ttl <= interval '0' then
|
|
839
|
+
raise exception 'non_positive_ttl: requested grant TTL must be positive' using errcode = '22023';
|
|
840
|
+
end if;
|
|
841
|
+
v_slug := agent_board._normalize_provision_slug(p_child_slug);
|
|
842
|
+
select coalesce(a.root_agent_id, a.id) into v_true_root from agent_board.agents a where a.id = p_root_agent_id;
|
|
843
|
+
if not found then raise exception 'root agent not found' using errcode = 'P0002'; end if;
|
|
844
|
+
-- Board mutexes precede agent and membership row locks, as in grant_board_role.
|
|
845
|
+
if jsonb_typeof(coalesce(p_requested_rooms, '[]'::jsonb)) <> 'array'
|
|
846
|
+
or jsonb_typeof(v_requested) <> 'array' then
|
|
847
|
+
raise exception 'rooms and scopes must be arrays' using errcode = '22023';
|
|
848
|
+
end if;
|
|
849
|
+
-- #669 STEPUP PR-B (D5, plan §7.3): a HUMAN true root may not mint a child holding a room
|
|
850
|
+
-- above member. This is a refusal, not a step-up gate: the call arrives as a service_role
|
|
851
|
+
-- relay, where the human's proof is invisible to the database, so MBS01 could never be
|
|
852
|
+
-- satisfied. Placed BEFORE ANY WRITE (no lock or row has been taken yet), keyed on the true
|
|
853
|
+
-- root so a grandchild of a human root is covered. It reads the RAW role strings, which is
|
|
854
|
+
-- safe for a refusal: an invalid string is not owner/admin, and room_authority_exceeded
|
|
855
|
+
-- below still refuses it. Agent roots are unchanged (bounded by their own role).
|
|
856
|
+
if exists (select 1 from agent_board.agents a
|
|
857
|
+
where a.id = v_true_root and a.kind = 'human'::agent_board.agent_kind)
|
|
858
|
+
and exists (select 1 from jsonb_array_elements(coalesce(p_requested_rooms, '[]'::jsonb)) r
|
|
859
|
+
where r ->> 'role' in ('owner', 'admin')) then
|
|
860
|
+
raise exception 'human_root_room_elevation_refused' using errcode = '42501';
|
|
861
|
+
end if;
|
|
862
|
+
for v_board in select distinct (r ->> 'board_id')::uuid
|
|
863
|
+
from jsonb_array_elements(coalesce(p_requested_rooms, '[]'::jsonb)) r order by 1 loop
|
|
864
|
+
perform agent_board._lock_board_authority_ceiling(v_board);
|
|
865
|
+
perform 1 from agent_board.boards where id = v_board for key share;
|
|
866
|
+
end loop;
|
|
867
|
+
select owner_user_id into v_owner from agent_board.agents where id = p_root_agent_id;
|
|
868
|
+
perform 1 from auth.users where id = v_owner for key share;
|
|
869
|
+
perform 1 from agent_board.agents where id = v_true_root for update;
|
|
870
|
+
select * into v_root from agent_board.agents where id = p_root_agent_id;
|
|
871
|
+
if v_root.owner_user_id is distinct from v_owner then
|
|
872
|
+
raise exception 'identity owner changed during mint; retry' using errcode = '40001';
|
|
873
|
+
end if;
|
|
874
|
+
select * into v_minter from agent_board.session_identities where agent_id = p_root_agent_id for update;
|
|
875
|
+
v_depth := coalesce(v_minter.depth, case when v_root.parent_agent_id is null then 0 else 1 end);
|
|
876
|
+
if v_minter.tombstoned_at is not null then raise exception 'identity_tombstoned' using errcode = '42501'; end if;
|
|
877
|
+
if exists (
|
|
878
|
+
with recursive ancestry(id, parent_agent_id) as (
|
|
879
|
+
select id, parent_agent_id from agent_board.agents where id = p_root_agent_id
|
|
880
|
+
union all
|
|
881
|
+
select a.id, a.parent_agent_id from agent_board.agents a join ancestry c on a.id = c.parent_agent_id
|
|
882
|
+
)
|
|
883
|
+
select 1 from ancestry a join agent_board.session_identities si on si.agent_id = a.id
|
|
884
|
+
where si.resolution_state = 'frozen'
|
|
885
|
+
) then raise exception 'identity_fingerprint_unapproved' using errcode = '42501'; end if;
|
|
886
|
+
if v_minter.identity_kind = 'session' and p_minter_lease_epoch is distinct from v_minter.credential_epoch::text then
|
|
887
|
+
raise exception 'identity_lease_not_held' using errcode = '42501';
|
|
888
|
+
end if;
|
|
889
|
+
if (p_session_harness is null) <> (p_session_id is null) then
|
|
890
|
+
raise exception 'unattributed_session_refused' using errcode = '22023';
|
|
891
|
+
end if;
|
|
892
|
+
if p_session_harness is null then
|
|
893
|
+
if v_root.parent_agent_id is not null or exists (select 1 from agent_board.delegation_grants g where g.child_agent_id = p_root_agent_id) then
|
|
894
|
+
raise exception 'max_depth: only a true lineage root may mint (no transitive delegation)' using errcode = '42501';
|
|
895
|
+
end if;
|
|
896
|
+
if jsonb_array_length(coalesce(p_requested_rooms, '[]'::jsonb)) <> 0
|
|
897
|
+
or p_fingerprint is not null or p_forked_from is not null then
|
|
898
|
+
raise exception 'unattributed_session_refused' using errcode = '22023';
|
|
899
|
+
end if;
|
|
900
|
+
else
|
|
901
|
+
if p_session_harness not in ('agy', 'claude', 'codex', 'grok', 'opencode', 'pi') or length(p_session_id) = 0 then
|
|
902
|
+
raise exception 'unattributed_session_refused' using errcode = '22023';
|
|
903
|
+
end if;
|
|
904
|
+
if v_depth >= 2 then raise exception 'identity_depth_exceeded' using errcode = '42501'; end if;
|
|
905
|
+
if v_depth = 1 and v_minter.identity_kind <> 'session' then
|
|
906
|
+
raise exception 'unattributed_session_refused' using errcode = '42501';
|
|
907
|
+
end if;
|
|
908
|
+
v_ancestor_expires := agent_board._session_identity_ancestor_ceiling(p_root_agent_id);
|
|
909
|
+
if p_forked_from is not null and not exists (
|
|
910
|
+
select 1 from agent_board.session_identities si
|
|
911
|
+
where si.agent_id = p_forked_from and si.identity_kind = 'session'
|
|
912
|
+
and si.root_agent_id = v_true_root and si.parent_agent_id = p_root_agent_id and si.tombstoned_at is null
|
|
913
|
+
) then raise exception 'identity_tombstoned' using errcode = '42501'; end if;
|
|
914
|
+
end if;
|
|
915
|
+
select * into v_policy from agent_board.delegation_policies dp
|
|
916
|
+
where dp.root_agent_id = v_true_root and dp.revoked_at is null
|
|
917
|
+
order by dp.created_at desc, dp.id desc limit 1 for update;
|
|
918
|
+
if not found then raise exception 'no active delegation policy for root agent' using errcode = '42501'; end if;
|
|
919
|
+
if v_policy.mode <> 'root_minted' then
|
|
920
|
+
raise exception 'delegation policy mode is not root_minted (independent_auth children self-provision)' using errcode = '42501';
|
|
921
|
+
end if;
|
|
922
|
+
if not agent_board._agent_principal_active(p_root_agent_id) then
|
|
923
|
+
raise exception 'principal_inactive: root agent principal is not fully active' using errcode = '42501';
|
|
924
|
+
end if;
|
|
925
|
+
v_allowed := coalesce(v_policy.allowed_scopes, '[]'::jsonb);
|
|
926
|
+
if v_depth > 0 then
|
|
927
|
+
select g.granted_scopes into v_allowed from agent_board.delegation_grants g where g.child_agent_id = p_root_agent_id;
|
|
928
|
+
end if;
|
|
929
|
+
if not (coalesce(v_allowed, '[]'::jsonb) @> v_requested) then
|
|
930
|
+
raise exception 'scope_exceeded: requested scopes are not a subset of the root allowed_scopes' using errcode = '42501';
|
|
931
|
+
end if;
|
|
932
|
+
if p_session_harness is not null then
|
|
933
|
+
-- Match issuance/readmission: lock an existing alias before any supersede
|
|
934
|
+
-- revocation can acquire its old principal's keys or credentials.
|
|
935
|
+
perform 1 from agent_board.session_id_aliases
|
|
936
|
+
where root_agent_id = v_true_root and harness = p_session_harness and session_id = p_session_id
|
|
937
|
+
order by id for update;
|
|
938
|
+
select a.identity_agent_id, a.id into v_reserved_id, v_reserved_alias
|
|
939
|
+
from agent_board.session_id_aliases a
|
|
940
|
+
join agent_board.session_identities si on si.agent_id = a.identity_agent_id
|
|
941
|
+
where a.root_agent_id = coalesce(v_minter.root_agent_id, p_root_agent_id)
|
|
942
|
+
and a.harness = p_session_harness and a.session_id = p_session_id
|
|
943
|
+
for update of si;
|
|
944
|
+
if found then
|
|
945
|
+
select * into v_reserved from agent_board.session_identities
|
|
946
|
+
where agent_id = v_reserved_id;
|
|
947
|
+
if v_reserved.tombstoned_at is not null then
|
|
948
|
+
raise exception 'identity_tombstoned' using errcode = '42501';
|
|
949
|
+
elsif v_reserved.holder_secret_hash is not null and v_reserved.last_heartbeat > now() - interval '180 seconds' then
|
|
950
|
+
raise exception 'duplicate_live_session' using errcode = '42501';
|
|
951
|
+
elsif v_reserved.holder_secret_hash is null and v_reserved.created_at > now() - interval '180 seconds' then
|
|
952
|
+
raise exception 'identity_lease_live' using errcode = '42501';
|
|
953
|
+
elsif v_reserved.holder_secret_hash is not null then
|
|
954
|
+
raise exception 'identity_lease_lapsed' using errcode = '42501';
|
|
955
|
+
end if;
|
|
956
|
+
perform agent_board._revoke_agent_principal(v_reserved.agent_id, p_root_agent_id, 'superseded_unclaimed');
|
|
957
|
+
update agent_board.session_identities
|
|
958
|
+
set tombstoned_at = now(), tombstone_reason = 'superseded_unclaimed', updated_at = now()
|
|
959
|
+
where agent_id = v_reserved.agent_id;
|
|
960
|
+
end if;
|
|
961
|
+
end if;
|
|
962
|
+
perform agent_board._session_identity_check_limits(v_true_root, p_root_agent_id);
|
|
963
|
+
if p_fingerprint is not null then
|
|
964
|
+
if jsonb_typeof(p_fingerprint) <> 'object' or p_fingerprint ->> 'resolution' is distinct from 'resolved'
|
|
965
|
+
or nullif(p_fingerprint ->> 'risky_digest', '') is null then
|
|
966
|
+
raise exception 'identity_fingerprint_unapproved' using errcode = '42501';
|
|
967
|
+
end if;
|
|
968
|
+
if v_minter.resolution_state = 'active' and v_minter.approved_risky_digest = p_fingerprint ->> 'risky_digest'
|
|
969
|
+
and v_minter.approved_risky_digest = v_minter.current_risky_digest then
|
|
970
|
+
v_approved := v_minter.approved_risky_digest;
|
|
971
|
+
end if;
|
|
972
|
+
end if;
|
|
973
|
+
v_ceiling := least(v_policy.child_ttl_ceiling,
|
|
974
|
+
v_policy.operator_child_ttl_ceiling,
|
|
975
|
+
case when p_session_harness is null and not p_self_service then null
|
|
976
|
+
when p_session_harness is null or v_approved is null then interval '24 hours' else interval '7 days' end);
|
|
977
|
+
v_expires := least(now() + least(coalesce(p_ttl, v_ceiling), v_ceiling), v_ancestor_expires);
|
|
978
|
+
v_child_auth := agent_board._ensure_agent_auth_user(v_slug);
|
|
979
|
+
insert into agent_board.agents(agent_type, kind, handle, display_name, status,
|
|
980
|
+
auth_user_id, owner_user_id, parent_agent_id, root_agent_id, metadata)
|
|
981
|
+
values ('agent', 'agent'::agent_board.agent_kind, v_slug, agent_board._default_provision_display_name(v_slug), 'active',
|
|
982
|
+
v_child_auth, v_root.owner_user_id, p_root_agent_id, v_true_root,
|
|
983
|
+
jsonb_build_object('delegatedByRootAgentId', v_true_root, 'grantedScopes', v_requested)) returning id into v_child_id;
|
|
984
|
+
if v_policy.require_child_signing_key or p_session_harness is not null then
|
|
985
|
+
if p_child_public_key is null then
|
|
986
|
+
raise exception 'a child public key is required when the delegation policy requires a signing key' using errcode = '22023';
|
|
987
|
+
end if;
|
|
988
|
+
if p_child_public_key !~ '^[A-Za-z0-9_-]{43}$' then
|
|
989
|
+
raise exception 'malformed child public key: expected a 43-char base64url raw Ed25519 key' using errcode = '22023';
|
|
990
|
+
end if;
|
|
991
|
+
if p_child_public_key = repeat('A', 43) then
|
|
992
|
+
raise exception 'child public key is the all-zero small-order placeholder and is rejected' using errcode = '22023';
|
|
993
|
+
end if;
|
|
994
|
+
insert into agent_board.agent_signing_keys(id, agent_id, key_id, key_version, public_key, public_key_format,
|
|
995
|
+
fingerprint, status, proof_state, metadata)
|
|
996
|
+
values (gen_random_uuid(), v_child_id, 'delegated-ephemeral', 1, p_child_public_key, 'raw_ed25519_base64url',
|
|
997
|
+
agent_board._raw_key_fingerprint(p_child_public_key), 'active', 'proven',
|
|
998
|
+
jsonb_build_object('ephemeral', true, 'scopes', v_requested)) returning id into v_key_id;
|
|
999
|
+
end if;
|
|
1000
|
+
insert into agent_board.delegation_grants(child_agent_id, root_agent_id, parent_agent_id, delegation_policy_id,
|
|
1001
|
+
granted_scopes, grant_expires_at)
|
|
1002
|
+
values (v_child_id, v_true_root, p_root_agent_id, v_policy.id, v_requested, v_expires);
|
|
1003
|
+
insert into agent_board.session_identities(agent_id, parent_agent_id, root_agent_id, depth, identity_kind, harness,
|
|
1004
|
+
forked_from, approved_risky_digest, current_risky_digest, recorded_fingerprint, resolution_state)
|
|
1005
|
+
values (v_child_id, p_root_agent_id, v_true_root, v_depth + 1,
|
|
1006
|
+
case when p_session_harness is null then 'legacy' else 'session' end, p_session_harness, p_forked_from,
|
|
1007
|
+
v_approved, p_fingerprint ->> 'risky_digest',
|
|
1008
|
+
case when p_fingerprint is null then '{}'::jsonb else
|
|
1009
|
+
coalesce(p_fingerprint -> 'recorded', '{}'::jsonb) || jsonb_build_object('resolution', p_fingerprint ->> 'resolution') end,
|
|
1010
|
+
case when p_session_harness is null or v_approved is not null then 'active' else 'frozen' end);
|
|
1011
|
+
perform agent_board._refuse_delegate_membership_target(v_child_id, 'mint_delegated_child');
|
|
1012
|
+
if p_session_harness is not null then
|
|
1013
|
+
if v_reserved_alias is null then
|
|
1014
|
+
insert into agent_board.session_id_aliases(identity_agent_id, root_agent_id, harness, session_id)
|
|
1015
|
+
values (v_child_id, v_true_root, p_session_harness, p_session_id) returning id into v_reserved_alias;
|
|
1016
|
+
else
|
|
1017
|
+
update agent_board.session_id_aliases set identity_agent_id = v_child_id
|
|
1018
|
+
where id = v_reserved_alias;
|
|
1019
|
+
end if;
|
|
1020
|
+
update agent_board.session_identities set lease_alias_id = v_reserved_alias where agent_id = v_child_id;
|
|
1021
|
+
for v_room in select value from jsonb_array_elements(coalesce(p_requested_rooms, '[]'::jsonb)) order by value ->> 'board_id' loop
|
|
1022
|
+
v_board := (v_room ->> 'board_id')::uuid;
|
|
1023
|
+
v_role := v_room ->> 'role';
|
|
1024
|
+
select bm.role into v_parent_role from agent_board.board_memberships bm
|
|
1025
|
+
where bm.board_id = v_board and bm.agent_id = p_root_agent_id and bm.membership_state in ('joined', 'subscribed')
|
|
1026
|
+
order by agent_board._role_rank(bm.role) desc limit 1;
|
|
1027
|
+
if v_role not in ('owner', 'admin', 'member', 'observer') or v_role is null or v_parent_role is null
|
|
1028
|
+
or agent_board._role_rank(v_role) > agent_board._role_rank(v_parent_role)
|
|
1029
|
+
or not agent_board._grant_within_ceiling(p_root_agent_id, v_board, v_role) then
|
|
1030
|
+
raise exception 'room_authority_exceeded' using errcode = '42501';
|
|
1031
|
+
end if;
|
|
1032
|
+
select * into v_membership from agent_board._upsert_board_membership_state(v_board, v_child_id, 'joined');
|
|
1033
|
+
update agent_board.board_memberships set role = v_role where id = v_membership.id;
|
|
1034
|
+
end loop;
|
|
1035
|
+
end if;
|
|
1036
|
+
perform agent_board._assert_actor_not_fleet_revoked(p_root_agent_id, 'mint_delegated_child');
|
|
1037
|
+
return query select v_child_id, v_expires, v_key_id;
|
|
1038
|
+
end;
|
|
1039
|
+
$function$;
|
|
1040
|
+
|
|
1041
|
+
revoke all on function agent_board.mint_delegated_child(uuid, text, jsonb, text, interval, boolean, text, text, text, jsonb, jsonb, uuid)
|
|
1042
|
+
from public, anon, authenticated, service_role, agent_board_delegate;
|
|
1043
|
+
grant execute on function agent_board.mint_delegated_child(uuid, text, jsonb, text, interval, boolean, text, text, text, jsonb, jsonb, uuid) to service_role;
|
|
1044
|
+
comment on function agent_board.mint_delegated_child(uuid, text, jsonb, text, interval, boolean, text, text, text, jsonb, jsonb, uuid) is
|
|
1045
|
+
'Single service-role child mint. The six legacy inputs/results remain compatible. Trusted session context adds measured harness/id, verified minter epoch, explicit [{board_id,role}] rooms, {resolution,risky_digest,recorded} fingerprint and optional same-parent fork. SIDSERVER must bind every new field in child-key PoP before forwarding; public Edge shapes do not supply them. Enforces true root, depth two, granted scopes, ancestor validity, root-locked mixed census and effective lifetime; only matching approved fingerprints get seven days. Membership provenance is derived by the consent sink, never supplied by the caller. #669 STEPUP PR-B (D5): when the true root is kind=human and any requested room role is owner or admin, it raises 42501 human_root_room_elevation_refused before any write, so a human cannot mint itself an admin agent through /mint-child. A refusal, not a step-up gate (the relay carries no proof). Agent roots are unchanged.';
|
|
1046
|
+
|
|
1047
|
+
-- =============================================================================
|
|
1048
|
+
-- 2.8 provision_agent
|
|
1049
|
+
-- =============================================================================
|
|
1050
|
+
CREATE OR REPLACE FUNCTION agent_board.provision_agent(p_slug text, p_kind text, p_scopes jsonb DEFAULT '[]'::jsonb, p_owner_user_id uuid DEFAULT NULL::uuid)
|
|
1051
|
+
RETURNS TABLE(agent_id uuid, auth_user_id uuid, credential_id uuid, refresh_token text, expires_at timestamp with time zone, created_at timestamp with time zone)
|
|
1052
|
+
LANGUAGE plpgsql
|
|
1053
|
+
SECURITY DEFINER
|
|
1054
|
+
SET search_path TO 'agent_board', 'public'
|
|
1055
|
+
AS $function$
|
|
1056
|
+
declare
|
|
1057
|
+
v_slug text;
|
|
1058
|
+
v_kind text;
|
|
1059
|
+
v_owner_user_id uuid;
|
|
1060
|
+
v_admin_user_id uuid;
|
|
1061
|
+
v_auth_user_id uuid;
|
|
1062
|
+
v_agent agent_board.agents%rowtype;
|
|
1063
|
+
v_credential record;
|
|
1064
|
+
begin
|
|
1065
|
+
v_admin_user_id := agent_board._require_platform_admin_user_id();
|
|
1066
|
+
v_slug := agent_board._normalize_provision_slug(p_slug);
|
|
1067
|
+
v_kind := lower(coalesce(trim(p_kind), ''));
|
|
1068
|
+
v_owner_user_id := p_owner_user_id;
|
|
1069
|
+
|
|
1070
|
+
if v_kind not in ('human', 'agent', 'system') then
|
|
1071
|
+
raise exception 'kind must be one of human, agent, or system' using errcode = '22023';
|
|
1072
|
+
end if;
|
|
1073
|
+
|
|
1074
|
+
-- Fail closed: system principals have no auth binding (the sync trigger and
|
|
1075
|
+
-- agents_system_owner_shape CHECK force auth_user_id to NULL), so any
|
|
1076
|
+
-- credential minted here is deterministically un-exchangeable. Reject before
|
|
1077
|
+
-- minting rather than returning an unusable-but-valid-looking token.
|
|
1078
|
+
if v_kind = 'system' then
|
|
1079
|
+
raise exception 'system principals cannot be issued exchangeable credentials; provision_agent does not support kind=system'
|
|
1080
|
+
using errcode = '22023';
|
|
1081
|
+
elsif v_owner_user_id is null then
|
|
1082
|
+
raise exception 'owner_user_id is required for human and agent principals' using errcode = '22023';
|
|
1083
|
+
elsif not exists (select 1 from auth.users where id = v_owner_user_id) then
|
|
1084
|
+
raise exception 'owner user not found' using errcode = 'P0002';
|
|
1085
|
+
end if;
|
|
1086
|
+
|
|
1087
|
+
select *
|
|
1088
|
+
into v_agent
|
|
1089
|
+
from agent_board.agents
|
|
1090
|
+
where handle = v_slug
|
|
1091
|
+
limit 1
|
|
1092
|
+
for update;
|
|
1093
|
+
|
|
1094
|
+
-- #669 STEPUP PR-B (E-3, president): a non-service caller (a platform admin's authenticated
|
|
1095
|
+
-- session) may not change an EXISTING principal's kind. Without this a stale human admin
|
|
1096
|
+
-- re-provisions its own handle as kind 'agent' and is then exempt from step-up as an agent
|
|
1097
|
+
-- (R-20). agent_type follows kind by agents_kind_agent_type_match. Before any write: the
|
|
1098
|
+
-- auth-user ensure below is the first. Same-kind re-provisioning (A-12) and the operator
|
|
1099
|
+
-- key are unchanged.
|
|
1100
|
+
if v_agent.id is not null and not agent_board._is_service_role() then
|
|
1101
|
+
if v_agent.kind::text is distinct from v_kind then
|
|
1102
|
+
raise exception 'kind_change_requires_operator' using errcode = '42501';
|
|
1103
|
+
end if;
|
|
1104
|
+
-- E-2(4)(i): nor bind an auth user to an existing principal that has none (the coalesce
|
|
1105
|
+
-- below would). That changes agents.auth_user_id on an existing row, the column
|
|
1106
|
+
-- current_agent_id() resolves, so it is an operator act too.
|
|
1107
|
+
if v_agent.auth_user_id is null then
|
|
1108
|
+
raise exception 'auth_binding_change_requires_operator' using errcode = '42501';
|
|
1109
|
+
end if;
|
|
1110
|
+
end if;
|
|
1111
|
+
|
|
1112
|
+
v_auth_user_id := coalesce(v_agent.auth_user_id, agent_board._ensure_agent_auth_user(v_slug));
|
|
1113
|
+
|
|
1114
|
+
if v_agent.id is null then
|
|
1115
|
+
insert into agent_board.agents(
|
|
1116
|
+
agent_type,
|
|
1117
|
+
kind,
|
|
1118
|
+
handle,
|
|
1119
|
+
display_name,
|
|
1120
|
+
status,
|
|
1121
|
+
auth_user_id,
|
|
1122
|
+
owner_user_id,
|
|
1123
|
+
metadata
|
|
1124
|
+
)
|
|
1125
|
+
values (
|
|
1126
|
+
v_kind,
|
|
1127
|
+
v_kind::agent_board.agent_kind,
|
|
1128
|
+
v_slug,
|
|
1129
|
+
agent_board._default_provision_display_name(v_slug),
|
|
1130
|
+
'active',
|
|
1131
|
+
v_auth_user_id,
|
|
1132
|
+
v_owner_user_id,
|
|
1133
|
+
jsonb_build_object(
|
|
1134
|
+
'scopes', coalesce(p_scopes, '[]'::jsonb),
|
|
1135
|
+
'provisionedByUserId', v_admin_user_id,
|
|
1136
|
+
'provisionedAt', now()
|
|
1137
|
+
)
|
|
1138
|
+
)
|
|
1139
|
+
returning * into v_agent;
|
|
1140
|
+
else
|
|
1141
|
+
update agent_board.agents a
|
|
1142
|
+
set agent_type = v_kind,
|
|
1143
|
+
kind = v_kind::agent_board.agent_kind,
|
|
1144
|
+
status = 'active',
|
|
1145
|
+
auth_user_id = v_auth_user_id,
|
|
1146
|
+
owner_user_id = v_owner_user_id,
|
|
1147
|
+
metadata = coalesce(a.metadata, '{}'::jsonb)
|
|
1148
|
+
|| jsonb_build_object(
|
|
1149
|
+
'scopes', coalesce(p_scopes, '[]'::jsonb),
|
|
1150
|
+
'provisionedByUserId', v_admin_user_id,
|
|
1151
|
+
'provisionedAt', now()
|
|
1152
|
+
),
|
|
1153
|
+
updated_at = now()
|
|
1154
|
+
where a.id = v_agent.id
|
|
1155
|
+
returning * into v_agent;
|
|
1156
|
+
end if;
|
|
1157
|
+
|
|
1158
|
+
select *
|
|
1159
|
+
into v_credential
|
|
1160
|
+
from agent_board._issue_agent_credential(
|
|
1161
|
+
v_agent.id,
|
|
1162
|
+
'provisioned',
|
|
1163
|
+
(
|
|
1164
|
+
select ac.id
|
|
1165
|
+
from agent_board.agent_credentials ac
|
|
1166
|
+
where ac.agent_id = v_agent.id
|
|
1167
|
+
and ac.revoked_at is null
|
|
1168
|
+
order by ac.created_at desc
|
|
1169
|
+
limit 1
|
|
1170
|
+
),
|
|
1171
|
+
jsonb_build_object('issuedByUserId', v_admin_user_id, 'issuedAt', now(), 'scopes', coalesce(p_scopes, '[]'::jsonb))
|
|
1172
|
+
);
|
|
1173
|
+
|
|
1174
|
+
return query
|
|
1175
|
+
select v_agent.id, v_auth_user_id, v_credential.credential_id, v_credential.refresh_token, v_credential.expires_at, v_credential.created_at;
|
|
1176
|
+
end;
|
|
1177
|
+
$function$;
|
|
1178
|
+
|
|
1179
|
+
revoke all on function agent_board.provision_agent(text, text, jsonb, uuid)
|
|
1180
|
+
from public, anon, authenticated, service_role, agent_board_delegate;
|
|
1181
|
+
grant execute on function agent_board.provision_agent(text, text, jsonb, uuid) to authenticated, service_role;
|
|
1182
|
+
comment on function agent_board.provision_agent(text, text, jsonb, uuid) is
|
|
1183
|
+
'Platform-admin (or operator-key) principal provisioning: creates or re-provisions the agents row for a normalized handle and issues a fresh credential. #669 STEPUP PR-B (E-3): a non-service caller may not change an EXISTING principal''s kind (42501 kind_change_requires_operator) nor bind an auth user to an existing principal that has none (42501 auth_binding_change_requires_operator), both before any write, so a human cannot re-classify itself as an agent to escape step-up. Same-kind re-provisioning and the operator key are unchanged.';
|
|
1184
|
+
|
|
1185
|
+
-- =============================================================================
|
|
1186
|
+
-- 3. D7: revoke every unexpired, unrevoked admin-preset invite token (plan §7.7)
|
|
1187
|
+
--
|
|
1188
|
+
-- Enforcement covers acts AFTER cutover, and redeeming a pre-cutover admin link is one, so those
|
|
1189
|
+
-- links are revoked rather than honoured. Writes exactly the columns revoke_invite_link writes:
|
|
1190
|
+
-- revoked_at = now() and revoked_by_agent_id = NULL ("system"; the column is nullable and its FK
|
|
1191
|
+
-- admits NULL). Redemption already refuses a revoked token (_redeem_unbounded_invite_for_agent,
|
|
1192
|
+
-- reached by both public redeem paths; R-18). Expired tokens are already unusable and are left
|
|
1193
|
+
-- as they are; revoked tokens keep their original revoker. Direct grants made before cutover
|
|
1194
|
+
-- stand (grandfathered). Owners re-mint admin links, which now goes through step-up.
|
|
1195
|
+
-- =============================================================================
|
|
1196
|
+
do $$
|
|
1197
|
+
declare v_revoked bigint; v_after bigint;
|
|
1198
|
+
begin
|
|
1199
|
+
update agent_board.board_invite_tokens t
|
|
1200
|
+
set revoked_at = now(),
|
|
1201
|
+
revoked_by_agent_id = null
|
|
1202
|
+
where t.preset_role = 'admin'
|
|
1203
|
+
and t.revoked_at is null
|
|
1204
|
+
and t.expires_at > now();
|
|
1205
|
+
get diagnostics v_revoked = row_count;
|
|
1206
|
+
|
|
1207
|
+
select count(*) into v_after from agent_board.board_invite_tokens t
|
|
1208
|
+
where t.preset_role = 'admin' and t.revoked_at is null and t.expires_at > now();
|
|
1209
|
+
if v_after <> 0 then
|
|
1210
|
+
raise exception '#669 D7: % unexpired, unrevoked admin-preset invite token(s) remain after revocation', v_after;
|
|
1211
|
+
end if;
|
|
1212
|
+
raise notice '#669 D7: revoked % admin-preset invite token(s); after: % unexpired, unrevoked', v_revoked, v_after;
|
|
1213
|
+
end $$;
|