-- +goose Up CREATE TABLE api_tokens ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), org_id uuid NOT NULL, user_id uuid NOT NULL, name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), token_hash bytea NOT NULL UNIQUE, -- First characters of the token, shown so users can tell tokens apart. prefix text NOT NULL, permissions text[] NOT NULL, expires_at timestamptz, last_used_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), -- Leaving the org revokes the member's tokens. FOREIGN KEY (org_id, user_id) REFERENCES memberships (org_id, user_id) ON DELETE CASCADE ); CREATE INDEX api_tokens_member_idx ON api_tokens (org_id, user_id); ALTER TABLE api_tokens ENABLE ROW LEVEL SECURITY; ALTER TABLE api_tokens FORCE ROW LEVEL SECURITY; CREATE POLICY api_tokens_tenant ON api_tokens FOR ALL USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id()); -- Requests carry only the token, so its org is unknown until it is found. -- Like org_id_by_slug, the system scope is raised for this single lookup by -- hash, which cannot enumerate other tokens. -- +goose StatementBegin CREATE FUNCTION api_token_org(hash bytea) RETURNS uuid LANGUAGE plpgsql VOLATILE AS $$ DECLARE prev text := coalesce(current_setting('app.scope', true), ''); result uuid; BEGIN PERFORM set_config('app.scope', 'system', true); SELECT org_id INTO result FROM api_tokens WHERE token_hash = hash; PERFORM set_config('app.scope', prev, true); RETURN result; END $$; -- +goose StatementEnd -- +goose Down DROP FUNCTION api_token_org(bytea); DROP TABLE api_tokens;