52 lines
2.5 KiB
PL/PgSQL
52 lines
2.5 KiB
PL/PgSQL
-- A TOTP timestep may authenticate once per independently provisioned secret.
|
|
CREATE TABLE local_totp_replay (
|
|
tenant_id uuid NOT NULL,
|
|
principal text NOT NULL,
|
|
secret_sha256 text NOT NULL CHECK (secret_sha256 ~ '^[0-9a-f]{64}$'),
|
|
last_step bigint NOT NULL CHECK (last_step >= 0),
|
|
consumed_at timestamptz NOT NULL DEFAULT now(),
|
|
PRIMARY KEY (tenant_id, principal, secret_sha256),
|
|
FOREIGN KEY (tenant_id, principal) REFERENCES memberships (tenant_id, principal)
|
|
);
|
|
ALTER TABLE local_totp_replay ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE local_totp_replay FORCE ROW LEVEL SECURITY;
|
|
CREATE POLICY tenant_scope ON local_totp_replay
|
|
USING (tenant_id::text = current_setting('app.tenant_id', true))
|
|
WITH CHECK (tenant_id::text = current_setting('app.tenant_id', true));
|
|
REVOKE ALL ON local_totp_replay FROM PUBLIC;
|
|
GRANT SELECT ON local_totp_replay TO rmm_app;
|
|
|
|
-- The application cannot modify memberships. The owner performs the row lock
|
|
-- and atomic replay consumption in the caller's selected tenant transaction.
|
|
CREATE FUNCTION local_totp_consume(selected_principal text, secret_hash text, selected_step bigint)
|
|
RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$
|
|
DECLARE selected_tenant uuid;
|
|
BEGIN
|
|
selected_tenant := nullif(current_setting('app.tenant_id', true), '')::uuid;
|
|
IF selected_tenant IS NULL THEN RETURN false; END IF;
|
|
PERFORM 1 FROM memberships WHERE tenant_id=selected_tenant AND principal=selected_principal
|
|
AND kind='human' AND revoked_at IS NULL FOR SHARE;
|
|
IF NOT FOUND THEN RETURN false; END IF;
|
|
INSERT INTO local_totp_replay(tenant_id,principal,secret_sha256,last_step)
|
|
VALUES(selected_tenant,selected_principal,secret_hash,selected_step)
|
|
ON CONFLICT(tenant_id,principal,secret_sha256) DO UPDATE
|
|
SET last_step=excluded.last_step,consumed_at=now()
|
|
WHERE local_totp_replay.last_step < excluded.last_step;
|
|
RETURN FOUND;
|
|
END;
|
|
$$;
|
|
REVOKE ALL ON FUNCTION local_totp_consume(text,text,bigint) FROM PUBLIC;
|
|
GRANT EXECUTE ON FUNCTION local_totp_consume(text,text,bigint) TO rmm_app;
|
|
|
|
DO $$
|
|
DECLARE current_tenant uuid;
|
|
BEGIN
|
|
FOR current_tenant IN SELECT tenant_id FROM tenants LOOP
|
|
PERFORM set_config('app.tenant_id', current_tenant::text, true);
|
|
UPDATE memberships SET permissions = array_append(permissions, 'tokens:manage')
|
|
WHERE tenant_id = current_tenant AND kind = 'human' AND revoked_at IS NULL
|
|
AND 'plans:approve' = ANY(permissions) AND NOT ('tokens:manage' = ANY(permissions));
|
|
END LOOP;
|
|
END;
|
|
$$;
|