/* * DBMS_VECTOR / DBMS_VECTOR_CHAIN shared REST/credential core (see * dbms_vector_rest.hpp). Moved out of dbms_vector.cpp verbatim; the SQL * facades and future shared text consumers link this single implementation. */ #include "dbms_vector_rest.hpp" #include "dbms_vector_common.hpp" #include #include #include extern "C" { #include "catalog/pg_type.h" #include "executor/spi.h" #include "fmgr.h" #include "utils/builtins.h" /// Версия RUDB пакета DBMS_VECTOR (Oracle DBMS_VECTOR пакет) #define RUDB_DBMS_VECTOR_VERSION "0.7.0" /* * Максимальный размер ответа провайдера (защита от неограниченного чтения). */ #define DBMS_VECTOR_HTTP_MAX_RESPONSE_BYTES (64 * 1024 * 1024) } // extern "C" /* * Parse the jsonb params of a REST call: provider (default 'database', * lowercased), url, model, credential_name and transfer_timeout * (default 60 s, pls:270). */ void dbms_vector_rest_parse_params(Jsonb *params, DbmsVectorRestParams &out) { out = DbmsVectorRestParams(); if (params == nullptr) return; JsonbContainer *container = ¶ms->root; if (!JsonContainerIsObject(container)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("params must be a JSON object"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); std::string provider; if (dbms_vector_param_string(container, "provider", "PROVIDER", provider)) out.provider = dbms_vector_ascii_lower(provider); dbms_vector_param_string(container, "url", "URL", out.url); dbms_vector_param_string(container, "model", "MODEL", out.model); dbms_vector_param_string(container, "credential_name", "CREDENTIAL_NAME", out.credential_name); JsonbValue buffer; JsonbValue *found = dbms_vector_getobjectfield(container, "transfer_timeout", &buffer); if (found != nullptr) { int32_t timeout; if (found->type != jbvNumeric) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for transfer_timeout parameter"), errdetail("Oracle error: ORA-29225."))); PG_TRY(); { timeout = DatumGetInt32(DirectFunctionCall1( numeric_int4, NumericGetDatum(found->val.numeric))); } PG_CATCH(); { FlushErrorState(); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for transfer_timeout parameter"), errdetail("Oracle error: ORA-29225."))); } PG_END_TRY(); if (timeout < 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for transfer_timeout parameter"), errdetail("Oracle error: ORA-29225."))); out.transfer_timeout = timeout; } } /* * CHECK_REST_PARAMS parity (pls:3639): url, model and credential_name are * required. */ void dbms_vector_rest_check_params(const DbmsVectorRestParams ¶ms) { if (params.url.empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("missing URL parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); if (params.model.empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("missing MODEL parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); if (params.credential_name.empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("missing CREDENTIAL_NAME parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } bool dbms_vector_rest_is_reserved_key(const char *key, int len) { static const char *reserved[] = { "provider", "credential_name", "url", "model", "transfer_timeout", "batch_size", }; for (const char *candidate : reserved) if ((int) strlen(candidate) == len && strncmp(candidate, key, len) == 0) return true; return false; } void dbms_vector_rest_push_passthrough(JsonbInState *state, Jsonb *params) { if (params == nullptr || !JsonContainerIsObject(¶ms->root)) return; JsonbIterator *iterator = JsonbIteratorInit(¶ms->root); JsonbValue passthrough_key; JsonbValue passthrough_value; JsonbIteratorToken token; while ((token = JsonbIteratorNext(&iterator, &passthrough_key, true)) != WJB_DONE) { if (token != WJB_KEY) continue; bool reserved = dbms_vector_rest_is_reserved_key( passthrough_key.val.string.val, passthrough_key.val.string.len); if (JsonbIteratorNext(&iterator, &passthrough_value, true) != WJB_VALUE) break; /* malformed object; jsonb guarantees a value next */ if (!reserved) { pushJsonbValue(state, WJB_KEY, &passthrough_key); pushJsonbValue(state, WJB_VALUE, &passthrough_value); } } } static size_t dbms_vector_curl_write_cb(char *ptr, size_t size, size_t nmemb, void *userdata) { auto *response = static_cast(userdata); size_t real = size * nmemb; if (response->body.size() + real > (size_t) DBMS_VECTOR_HTTP_MAX_RESPONSE_BYTES) return 0; /* aborts the transfer with CURLE_WRITE_ERROR */ response->body.append(ptr, real); return real; } DbmsVectorRestResponse dbms_vector_rest_call(const DbmsVectorRestParams ¶ms, const std::string &api_key, const char *body) { static bool curl_inited = false; if (!curl_inited) { curl_global_init(CURL_GLOBAL_DEFAULT); curl_inited = true; } CURL *curl = curl_easy_init(); if (curl == nullptr) ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("could not initialize libcurl"))); DbmsVectorRestResponse response; struct curl_slist *headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, params.url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(body)); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, dbms_vector_curl_write_cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_setopt(curl, CURLOPT_USERAGENT, "RuDB-DBMS_VECTOR/" RUDB_DBMS_VECTOR_VERSION); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); if (params.transfer_timeout > 0) { curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long) params.transfer_timeout); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, (long) params.transfer_timeout); } CURLcode rc = curl_easy_perform(curl); curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response.status_code); curl_slist_free_all(headers); curl_easy_cleanup(curl); if (rc == CURLE_WRITE_ERROR && response.body.size() >= (size_t) DBMS_VECTOR_HTTP_MAX_RESPONSE_BYTES) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("provider response exceeds the maximum supported " "size of %d bytes", DBMS_VECTOR_HTTP_MAX_RESPONSE_BYTES))); if (rc != CURLE_OK) ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("provider request failed: %s", curl_easy_strerror(rc)))); return response; } std::string dbms_vector_rest_provider_error(const char *output) { if (output == nullptr) return std::string(); if (strlen(output) >= 512) return std::string(output); Jsonb *parsed = nullptr; PG_TRY(); { parsed = DatumGetJsonbP(DirectFunctionCall1( jsonb_in, CStringGetDatum(output))); } PG_CATCH(); { FlushErrorState(); return std::string(output); } PG_END_TRY(); std::string message; JsonbContainer *root = &parsed->root; if (JsonContainerIsObject(root)) { JsonbValue buffer; if (dbms_vector_getobjectfield(root, "message", &buffer) != nullptr && buffer.type == jbvString) message.assign(buffer.val.string.val, buffer.val.string.len); if (message.empty() && dbms_vector_getobjectfield(root, "error", &buffer) != nullptr) { if (buffer.type == jbvBinary && JsonContainerIsObject(buffer.val.binary.data)) { JsonbValue nested; if (dbms_vector_getobjectfield(buffer.val.binary.data, "message", &nested) != nullptr && nested.type == jbvString) message.assign(nested.val.string.val, nested.val.string.len); } else if (buffer.type == jbvBinary && JsonContainerIsArray(buffer.val.binary.data)) { JsonbValue *first = getIthJsonbValueFromContainer( buffer.val.binary.data, 0); if (first != nullptr && first->type == jbvString) message.assign(first->val.string.val, first->val.string.len); } else if (buffer.type == jbvString) message.assign(buffer.val.string.val, buffer.val.string.len); } } return message.empty() ? std::string(output) : message; } /* * Raw stored params of a credential (secrets included), honoring the * OWNER.NAME qualification rules and the owner-or-superuser access rule; * returns a copy of the params jsonb allocated in the caller's memory * context, or raises the ORA-20001 parity error. */ Jsonb * dbms_vector_credential_lookup(const std::string &credential_name) { std::string owner; std::string name; dbms_vector_parse_qualified_name(credential_name.c_str(), owner, name); dbms_vector_check_simple_name(name, "credential name"); if (credential_name.find('.') != std::string::npos) dbms_vector_check_simple_name(owner, "credential owner"); SPI_connect(); Jsonb *result = nullptr; PG_TRY(); { static const char *sql = "SELECT owner, params FROM \"SYS\".vector_credentials " "WHERE owner = $1 AND credential_name = $2"; Oid argtypes[2] = {TEXTOID, TEXTOID}; Datum values[2]; char nulls[2] = {' ', ' '}; values[0] = CStringGetTextDatum(owner.c_str()); values[1] = CStringGetTextDatum(name.c_str()); int rc = SPI_execute_with_args(sql, 2, argtypes, values, nulls, true, 1); if (rc != SPI_OK_SELECT) ereport(ERROR, (errmsg("SPI_execute_with_args failed: %s (rc=%d)", SPI_result_code_string(rc), rc))); if (SPI_processed == 0) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("credential %s does not exist", name.c_str()), errdetail("Oracle error: ORA-20001 (EXCP_CRED_NOT_EXIST)."))); bool owner_isnull = false; bool params_isnull = false; Datum owner_datum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &owner_isnull); Datum params_datum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, ¶ms_isnull); if (params_isnull) ereport(ERROR, (errmsg("params is NULL for credential %s", name.c_str()))); const char *row_owner = owner_isnull ? "" : TextDatumGetCString(owner_datum); if (strcmp(row_owner, GetUserNameFromId(GetUserId(), false)) != 0 && !superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("permission denied for credential %s", name.c_str()))); /* * Detoast before copying: jsonb values in heap tuples may use the * short 1-byte varlena header, which is unusable as a Jsonb *. */ Jsonb *params = DatumGetJsonbP(params_datum); result = (Jsonb *) SPI_palloc(VARSIZE(params)); memcpy(result, params, VARSIZE(params)); } PG_FINALLY(); { SPI_finish(); } PG_END_TRY(); return result; } std::string dbms_vector_rest_credential_key(Jsonb *credential, const std::string &credential_name) { JsonbContainer *container = &credential->root; DbmsVectorCredForm form = dbms_vector_credential_form(container); if (form == DBMS_VECTOR_CRED_USERPASS) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("username/password credentials cannot be used with " "the openai provider"), errdetail("Oracle providers always send the stored key as " "a bearer token (pls:2253); a username/password " "credential has no key."))); if (form == DBMS_VECTOR_CRED_OCI) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("OCI request signing credentials are not supported " "by the REST provider"), errhint("Use an access_token credential with provider " "'openai'."))); JsonbValue value; JsonbValue *found = dbms_vector_getobjectfield(container, "access_token", &value); if (found == nullptr || found->type != jbvString || found->val.string.len == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("credential %s does not specify a supported " "authentication form", credential_name.c_str()))); return std::string(found->val.string.val, found->val.string.len); }