1
0
mirror of https://github.com/postgres/postgres.git synced 2025-06-16 06:01:02 +03:00

Fix column-privilege leak in error-message paths

While building error messages to return to the user,
BuildIndexValueDescription, ExecBuildSlotValueDescription and
ri_ReportViolation would happily include the entire key or entire row in
the result returned to the user, even if the user didn't have access to
view all of the columns being included.

Instead, include only those columns which the user is providing or which
the user has select rights on.  If the user does not have any rights
to view the table or any of the columns involved then no detail is
provided and a NULL value is returned from BuildIndexValueDescription
and ExecBuildSlotValueDescription.  Note that, for key cases, the user
must have access to all of the columns for the key to be shown; a
partial key will not be returned.

Back-patch all the way, as column-level privileges are now in all
supported versions.

This has been assigned CVE-2014-8161, but since the issue and the patch
have already been publicized on pgsql-hackers, there's no point in trying
to hide this commit.
This commit is contained in:
Stephen Frost
2015-01-12 17:04:11 -05:00
parent 3d5e857ab1
commit 3cc74a3d61
11 changed files with 361 additions and 70 deletions

View File

@ -25,10 +25,12 @@
#include "lib/stringinfo.h" #include "lib/stringinfo.h"
#include "miscadmin.h" #include "miscadmin.h"
#include "storage/bufmgr.h" #include "storage/bufmgr.h"
#include "utils/acl.h"
#include "utils/builtins.h" #include "utils/builtins.h"
#include "utils/lsyscache.h" #include "utils/lsyscache.h"
#include "utils/rel.h" #include "utils/rel.h"
#include "utils/snapmgr.h" #include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/tqual.h" #include "utils/tqual.h"
@ -154,6 +156,11 @@ IndexScanEnd(IndexScanDesc scan)
* form "(key_name, ...)=(key_value, ...)". This is currently used * form "(key_name, ...)=(key_value, ...)". This is currently used
* for building unique-constraint and exclusion-constraint error messages. * for building unique-constraint and exclusion-constraint error messages.
* *
* Note that if the user does not have permissions to view all of the
* columns involved then a NULL is returned. Returning a partial key seems
* unlikely to be useful and we have no way to know which of the columns the
* user provided (unlike in ExecBuildSlotValueDescription).
*
* The passed-in values/nulls arrays are the "raw" input to the index AM, * The passed-in values/nulls arrays are the "raw" input to the index AM,
* e.g. results of FormIndexDatum --- this is not necessarily what is stored * e.g. results of FormIndexDatum --- this is not necessarily what is stored
* in the index, but it's what the user perceives to be stored. * in the index, but it's what the user perceives to be stored.
@ -163,13 +170,62 @@ BuildIndexValueDescription(Relation indexRelation,
Datum *values, bool *isnull) Datum *values, bool *isnull)
{ {
StringInfoData buf; StringInfoData buf;
Form_pg_index idxrec;
HeapTuple ht_idx;
int natts = indexRelation->rd_rel->relnatts; int natts = indexRelation->rd_rel->relnatts;
int i; int i;
int keyno;
Oid indexrelid = RelationGetRelid(indexRelation);
Oid indrelid;
AclResult aclresult;
/*
* Check permissions- if the user does not have access to view all of the
* key columns then return NULL to avoid leaking data.
*
* First we need to check table-level SELECT access and then, if
* there is no access there, check column-level permissions.
*/
/*
* Fetch the pg_index tuple by the Oid of the index
*/
ht_idx = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexrelid));
if (!HeapTupleIsValid(ht_idx))
elog(ERROR, "cache lookup failed for index %u", indexrelid);
idxrec = (Form_pg_index) GETSTRUCT(ht_idx);
indrelid = idxrec->indrelid;
Assert(indexrelid == idxrec->indexrelid);
/* Table-level SELECT is enough, if the user has it */
aclresult = pg_class_aclcheck(indrelid, GetUserId(), ACL_SELECT);
if (aclresult != ACLCHECK_OK)
{
/*
* No table-level access, so step through the columns in the
* index and make sure the user has SELECT rights on all of them.
*/
for (keyno = 0; keyno < idxrec->indnatts; keyno++)
{
AttrNumber attnum = idxrec->indkey.values[keyno];
aclresult = pg_attribute_aclcheck(indrelid, attnum, GetUserId(),
ACL_SELECT);
if (aclresult != ACLCHECK_OK)
{
/* No access, so clean up and return */
ReleaseSysCache(ht_idx);
return NULL;
}
}
}
ReleaseSysCache(ht_idx);
initStringInfo(&buf); initStringInfo(&buf);
appendStringInfo(&buf, "(%s)=(", appendStringInfo(&buf, "(%s)=(",
pg_get_indexdef_columns(RelationGetRelid(indexRelation), pg_get_indexdef_columns(indexrelid, true));
true));
for (i = 0; i < natts; i++) for (i = 0; i < natts; i++)
{ {

View File

@ -388,16 +388,20 @@ _bt_check_unique(Relation rel, IndexTuple itup, Relation heapRel,
{ {
Datum values[INDEX_MAX_KEYS]; Datum values[INDEX_MAX_KEYS];
bool isnull[INDEX_MAX_KEYS]; bool isnull[INDEX_MAX_KEYS];
char *key_desc;
index_deform_tuple(itup, RelationGetDescr(rel), index_deform_tuple(itup, RelationGetDescr(rel),
values, isnull); values, isnull);
key_desc = BuildIndexValueDescription(rel, values,
isnull);
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_UNIQUE_VIOLATION), (errcode(ERRCODE_UNIQUE_VIOLATION),
errmsg("duplicate key value violates unique constraint \"%s\"", errmsg("duplicate key value violates unique constraint \"%s\"",
RelationGetRelationName(rel)), RelationGetRelationName(rel)),
errdetail("Key %s already exists.", key_desc ? errdetail("Key %s already exists.",
BuildIndexValueDescription(rel, key_desc) : 0,
values, isnull)),
errtableconstraint(heapRel, errtableconstraint(heapRel,
RelationGetRelationName(rel)))); RelationGetRelationName(rel))));
} }

View File

@ -160,6 +160,7 @@ typedef struct CopyStateData
int *defmap; /* array of default att numbers */ int *defmap; /* array of default att numbers */
ExprState **defexprs; /* array of default att expressions */ ExprState **defexprs; /* array of default att expressions */
bool volatile_defexprs; /* is any of defexprs volatile? */ bool volatile_defexprs; /* is any of defexprs volatile? */
List *range_table;
/* /*
* These variables are used to reduce overhead in textual COPY FROM. * These variables are used to reduce overhead in textual COPY FROM.
@ -784,6 +785,7 @@ DoCopy(const CopyStmt *stmt, const char *queryString, uint64 *processed)
bool pipe = (stmt->filename == NULL); bool pipe = (stmt->filename == NULL);
Relation rel; Relation rel;
Oid relid; Oid relid;
RangeTblEntry *rte;
/* Disallow COPY to/from file or program except to superusers. */ /* Disallow COPY to/from file or program except to superusers. */
if (!pipe && !superuser()) if (!pipe && !superuser())
@ -806,7 +808,6 @@ DoCopy(const CopyStmt *stmt, const char *queryString, uint64 *processed)
{ {
TupleDesc tupDesc; TupleDesc tupDesc;
AclMode required_access = (is_from ? ACL_INSERT : ACL_SELECT); AclMode required_access = (is_from ? ACL_INSERT : ACL_SELECT);
RangeTblEntry *rte;
List *attnums; List *attnums;
ListCell *cur; ListCell *cur;
@ -856,6 +857,7 @@ DoCopy(const CopyStmt *stmt, const char *queryString, uint64 *processed)
cstate = BeginCopyFrom(rel, stmt->filename, stmt->is_program, cstate = BeginCopyFrom(rel, stmt->filename, stmt->is_program,
stmt->attlist, stmt->options); stmt->attlist, stmt->options);
cstate->range_table = list_make1(rte);
*processed = CopyFrom(cstate); /* copy from file to database */ *processed = CopyFrom(cstate); /* copy from file to database */
EndCopyFrom(cstate); EndCopyFrom(cstate);
} }
@ -864,6 +866,7 @@ DoCopy(const CopyStmt *stmt, const char *queryString, uint64 *processed)
cstate = BeginCopyTo(rel, stmt->query, queryString, cstate = BeginCopyTo(rel, stmt->query, queryString,
stmt->filename, stmt->is_program, stmt->filename, stmt->is_program,
stmt->attlist, stmt->options); stmt->attlist, stmt->options);
cstate->range_table = list_make1(rte);
*processed = DoCopyTo(cstate); /* copy from database to file */ *processed = DoCopyTo(cstate); /* copy from database to file */
EndCopyTo(cstate); EndCopyTo(cstate);
} }
@ -2184,6 +2187,7 @@ CopyFrom(CopyState cstate)
estate->es_result_relations = resultRelInfo; estate->es_result_relations = resultRelInfo;
estate->es_num_result_relations = 1; estate->es_num_result_relations = 1;
estate->es_result_relation_info = resultRelInfo; estate->es_result_relation_info = resultRelInfo;
estate->es_range_table = cstate->range_table;
/* Set up a tuple slot too */ /* Set up a tuple slot too */
myslot = ExecInitExtraTupleSlot(estate); myslot = ExecInitExtraTupleSlot(estate);

View File

@ -586,6 +586,13 @@ refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
elog(ERROR, "SPI_exec failed: %s", querybuf.data); elog(ERROR, "SPI_exec failed: %s", querybuf.data);
if (SPI_processed > 0) if (SPI_processed > 0)
{ {
/*
* Note that this ereport() is returning data to the user. Generally,
* we would want to make sure that the user has been granted access to
* this data. However, REFRESH MAT VIEW is only able to be run by the
* owner of the mat view (or a superuser) and therefore there is no
* need to check for access to data in the mat view.
*/
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_CARDINALITY_VIOLATION), (errcode(ERRCODE_CARDINALITY_VIOLATION),
errmsg("new data for \"%s\" contains duplicate rows without any null columns", errmsg("new data for \"%s\" contains duplicate rows without any null columns",

View File

@ -65,6 +65,12 @@ int SessionReplicationRole = SESSION_REPLICATION_ROLE_ORIGIN;
/* How many levels deep into trigger execution are we? */ /* How many levels deep into trigger execution are we? */
static int MyTriggerDepth = 0; static int MyTriggerDepth = 0;
/*
* Note that this macro also exists in executor/execMain.c. There does not
* appear to be any good header to put it into, given the structures that
* it uses, so we let them be duplicated. Be sure to update both if one needs
* to be changed, however.
*/
#define GetModifiedColumns(relinfo, estate) \ #define GetModifiedColumns(relinfo, estate) \
(rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->modifiedCols) (rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->modifiedCols)

View File

@ -82,12 +82,23 @@ static void ExecutePlan(EState *estate, PlanState *planstate,
DestReceiver *dest); DestReceiver *dest);
static bool ExecCheckRTEPerms(RangeTblEntry *rte); static bool ExecCheckRTEPerms(RangeTblEntry *rte);
static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt); static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
static char *ExecBuildSlotValueDescription(TupleTableSlot *slot, static char *ExecBuildSlotValueDescription(Oid reloid,
TupleTableSlot *slot,
TupleDesc tupdesc, TupleDesc tupdesc,
Bitmapset *modifiedCols,
int maxfieldlen); int maxfieldlen);
static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate, static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
Plan *planTree); Plan *planTree);
/*
* Note that this macro also exists in commands/trigger.c. There does not
* appear to be any good header to put it into, given the structures that
* it uses, so we let them be duplicated. Be sure to update both if one needs
* to be changed, however.
*/
#define GetModifiedColumns(relinfo, estate) \
(rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->modifiedCols)
/* end of local decls */ /* end of local decls */
@ -1602,34 +1613,51 @@ ExecConstraints(ResultRelInfo *resultRelInfo,
{ {
if (tupdesc->attrs[attrChk - 1]->attnotnull && if (tupdesc->attrs[attrChk - 1]->attnotnull &&
slot_attisnull(slot, attrChk)) slot_attisnull(slot, attrChk))
{
char *val_desc;
Bitmapset *modifiedCols;
modifiedCols = GetModifiedColumns(resultRelInfo, estate);
val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
slot,
tupdesc,
modifiedCols,
64);
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_NOT_NULL_VIOLATION), (errcode(ERRCODE_NOT_NULL_VIOLATION),
errmsg("null value in column \"%s\" violates not-null constraint", errmsg("null value in column \"%s\" violates not-null constraint",
NameStr(tupdesc->attrs[attrChk - 1]->attname)), NameStr(tupdesc->attrs[attrChk - 1]->attname)),
errdetail("Failing row contains %s.", val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
ExecBuildSlotValueDescription(slot,
tupdesc,
64)),
errtablecol(rel, attrChk))); errtablecol(rel, attrChk)));
} }
} }
}
if (constr->num_check > 0) if (constr->num_check > 0)
{ {
const char *failed; const char *failed;
if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL) if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
{
char *val_desc;
Bitmapset *modifiedCols;
modifiedCols = GetModifiedColumns(resultRelInfo, estate);
val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
slot,
tupdesc,
modifiedCols,
64);
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_CHECK_VIOLATION), (errcode(ERRCODE_CHECK_VIOLATION),
errmsg("new row for relation \"%s\" violates check constraint \"%s\"", errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
RelationGetRelationName(rel), failed), RelationGetRelationName(rel), failed),
errdetail("Failing row contains %s.", val_desc ? errdetail("Failing row contains %s.", val_desc) : 0,
ExecBuildSlotValueDescription(slot,
tupdesc,
64)),
errtableconstraint(rel, failed))); errtableconstraint(rel, failed)));
} }
} }
}
/* /*
* ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
@ -1638,6 +1666,8 @@ void
ExecWithCheckOptions(ResultRelInfo *resultRelInfo, ExecWithCheckOptions(ResultRelInfo *resultRelInfo,
TupleTableSlot *slot, EState *estate) TupleTableSlot *slot, EState *estate)
{ {
Relation rel = resultRelInfo->ri_RelationDesc;
TupleDesc tupdesc = RelationGetDescr(rel);
ExprContext *econtext; ExprContext *econtext;
ListCell *l1, ListCell *l1,
*l2; *l2;
@ -1666,14 +1696,24 @@ ExecWithCheckOptions(ResultRelInfo *resultRelInfo,
* above for CHECK constraints). * above for CHECK constraints).
*/ */
if (!ExecQual((List *) wcoExpr, econtext, false)) if (!ExecQual((List *) wcoExpr, econtext, false))
{
char *val_desc;
Bitmapset *modifiedCols;
modifiedCols = GetModifiedColumns(resultRelInfo, estate);
val_desc = ExecBuildSlotValueDescription(RelationGetRelid(rel),
slot,
tupdesc,
modifiedCols,
64);
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION), (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
errmsg("new row violates WITH CHECK OPTION for view \"%s\"", errmsg("new row violates WITH CHECK OPTION for view \"%s\"",
wco->viewname), wco->viewname),
errdetail("Failing row contains %s.", val_desc ? errdetail("Failing row contains %s.", val_desc) :
ExecBuildSlotValueDescription(slot, 0));
RelationGetDescr(resultRelInfo->ri_RelationDesc), }
64))));
} }
} }
@ -1689,25 +1729,56 @@ ExecWithCheckOptions(ResultRelInfo *resultRelInfo,
* dropped columns. We used to use the slot's tuple descriptor to decode the * dropped columns. We used to use the slot's tuple descriptor to decode the
* data, but the slot's descriptor doesn't identify dropped columns, so we * data, but the slot's descriptor doesn't identify dropped columns, so we
* now need to be passed the relation's descriptor. * now need to be passed the relation's descriptor.
*
* Note that, like BuildIndexValueDescription, if the user does not have
* permission to view any of the columns involved, a NULL is returned. Unlike
* BuildIndexValueDescription, if the user has access to view a subset of the
* column involved, that subset will be returned with a key identifying which
* columns they are.
*/ */
static char * static char *
ExecBuildSlotValueDescription(TupleTableSlot *slot, ExecBuildSlotValueDescription(Oid reloid,
TupleTableSlot *slot,
TupleDesc tupdesc, TupleDesc tupdesc,
Bitmapset *modifiedCols,
int maxfieldlen) int maxfieldlen)
{ {
StringInfoData buf; StringInfoData buf;
StringInfoData collist;
bool write_comma = false; bool write_comma = false;
bool write_comma_collist = false;
int i; int i;
AclResult aclresult;
/* Make sure the tuple is fully deconstructed */ bool table_perm = false;
slot_getallattrs(slot); bool any_perm = false;
initStringInfo(&buf); initStringInfo(&buf);
appendStringInfoChar(&buf, '('); appendStringInfoChar(&buf, '(');
/*
* Check if the user has permissions to see the row. Table-level SELECT
* allows access to all columns. If the user does not have table-level
* SELECT then we check each column and include those the user has SELECT
* rights on. Additionally, we always include columns the user provided
* data for.
*/
aclresult = pg_class_aclcheck(reloid, GetUserId(), ACL_SELECT);
if (aclresult != ACLCHECK_OK)
{
/* Set up the buffer for the column list */
initStringInfo(&collist);
appendStringInfoChar(&collist, '(');
}
else
table_perm = any_perm = true;
/* Make sure the tuple is fully deconstructed */
slot_getallattrs(slot);
for (i = 0; i < tupdesc->natts; i++) for (i = 0; i < tupdesc->natts; i++)
{ {
bool column_perm = false;
char *val; char *val;
int vallen; int vallen;
@ -1715,6 +1786,32 @@ ExecBuildSlotValueDescription(TupleTableSlot *slot,
if (tupdesc->attrs[i]->attisdropped) if (tupdesc->attrs[i]->attisdropped)
continue; continue;
if (!table_perm)
{
/*
* No table-level SELECT, so need to make sure they either have
* SELECT rights on the column or that they have provided the
* data for the column. If not, omit this column from the error
* message.
*/
aclresult = pg_attribute_aclcheck(reloid, tupdesc->attrs[i]->attnum,
GetUserId(), ACL_SELECT);
if (bms_is_member(tupdesc->attrs[i]->attnum - FirstLowInvalidHeapAttributeNumber,
modifiedCols) || aclresult == ACLCHECK_OK)
{
column_perm = any_perm = true;
if (write_comma_collist)
appendStringInfoString(&collist, ", ");
else
write_comma_collist = true;
appendStringInfoString(&collist, NameStr(tupdesc->attrs[i]->attname));
}
}
if (table_perm || column_perm)
{
if (slot->tts_isnull[i]) if (slot->tts_isnull[i])
val = "null"; val = "null";
else else
@ -1743,9 +1840,22 @@ ExecBuildSlotValueDescription(TupleTableSlot *slot,
appendStringInfoString(&buf, "..."); appendStringInfoString(&buf, "...");
} }
} }
}
/* If we end up with zero columns being returned, then return NULL. */
if (!any_perm)
return NULL;
appendStringInfoChar(&buf, ')'); appendStringInfoChar(&buf, ')');
if (!table_perm)
{
appendStringInfoString(&collist, ") = ");
appendStringInfoString(&collist, buf.data);
return collist.data;
}
return buf.data; return buf.data;
} }

View File

@ -1323,8 +1323,10 @@ retry:
(errcode(ERRCODE_EXCLUSION_VIOLATION), (errcode(ERRCODE_EXCLUSION_VIOLATION),
errmsg("could not create exclusion constraint \"%s\"", errmsg("could not create exclusion constraint \"%s\"",
RelationGetRelationName(index)), RelationGetRelationName(index)),
error_new && error_existing ?
errdetail("Key %s conflicts with key %s.", errdetail("Key %s conflicts with key %s.",
error_new, error_existing), error_new, error_existing) :
errdetail("Key conflicts exist."),
errtableconstraint(heap, errtableconstraint(heap,
RelationGetRelationName(index)))); RelationGetRelationName(index))));
else else
@ -1332,8 +1334,10 @@ retry:
(errcode(ERRCODE_EXCLUSION_VIOLATION), (errcode(ERRCODE_EXCLUSION_VIOLATION),
errmsg("conflicting key value violates exclusion constraint \"%s\"", errmsg("conflicting key value violates exclusion constraint \"%s\"",
RelationGetRelationName(index)), RelationGetRelationName(index)),
error_new && error_existing ?
errdetail("Key %s conflicts with existing key %s.", errdetail("Key %s conflicts with existing key %s.",
error_new, error_existing), error_new, error_existing) :
errdetail("Key conflicts with existing key."),
errtableconstraint(heap, errtableconstraint(heap,
RelationGetRelationName(index)))); RelationGetRelationName(index))));
} }

View File

@ -43,6 +43,7 @@
#include "parser/parse_coerce.h" #include "parser/parse_coerce.h"
#include "parser/parse_relation.h" #include "parser/parse_relation.h"
#include "miscadmin.h" #include "miscadmin.h"
#include "utils/acl.h"
#include "utils/builtins.h" #include "utils/builtins.h"
#include "utils/fmgroids.h" #include "utils/fmgroids.h"
#include "utils/guc.h" #include "utils/guc.h"
@ -3170,6 +3171,9 @@ ri_ReportViolation(const RI_ConstraintInfo *riinfo,
bool onfk; bool onfk;
const int16 *attnums; const int16 *attnums;
int idx; int idx;
Oid rel_oid;
AclResult aclresult;
bool has_perm = true;
if (spi_err) if (spi_err)
ereport(ERROR, ereport(ERROR,
@ -3188,16 +3192,46 @@ ri_ReportViolation(const RI_ConstraintInfo *riinfo,
if (onfk) if (onfk)
{ {
attnums = riinfo->fk_attnums; attnums = riinfo->fk_attnums;
rel_oid = fk_rel->rd_id;
if (tupdesc == NULL) if (tupdesc == NULL)
tupdesc = fk_rel->rd_att; tupdesc = fk_rel->rd_att;
} }
else else
{ {
attnums = riinfo->pk_attnums; attnums = riinfo->pk_attnums;
rel_oid = pk_rel->rd_id;
if (tupdesc == NULL) if (tupdesc == NULL)
tupdesc = pk_rel->rd_att; tupdesc = pk_rel->rd_att;
} }
/*
* Check permissions- if the user does not have access to view the data in
* any of the key columns then we don't include the errdetail() below.
*
* Check table-level permissions first and, failing that, column-level
* privileges.
*/
aclresult = pg_class_aclcheck(rel_oid, GetUserId(), ACL_SELECT);
if (aclresult != ACLCHECK_OK)
{
/* Try for column-level permissions */
for (idx = 0; idx < riinfo->nkeys; idx++)
{
aclresult = pg_attribute_aclcheck(rel_oid, attnums[idx],
GetUserId(),
ACL_SELECT);
/* No access to the key */
if (aclresult != ACLCHECK_OK)
{
has_perm = false;
break;
}
}
}
if (has_perm)
{
/* Get printable versions of the keys involved */ /* Get printable versions of the keys involved */
initStringInfo(&key_names); initStringInfo(&key_names);
initStringInfo(&key_values); initStringInfo(&key_values);
@ -3220,6 +3254,7 @@ ri_ReportViolation(const RI_ConstraintInfo *riinfo,
appendStringInfoString(&key_names, name); appendStringInfoString(&key_names, name);
appendStringInfoString(&key_values, val); appendStringInfoString(&key_values, val);
} }
}
if (onfk) if (onfk)
ereport(ERROR, ereport(ERROR,
@ -3227,8 +3262,11 @@ ri_ReportViolation(const RI_ConstraintInfo *riinfo,
errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"", errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
RelationGetRelationName(fk_rel), RelationGetRelationName(fk_rel),
NameStr(riinfo->conname)), NameStr(riinfo->conname)),
has_perm ?
errdetail("Key (%s)=(%s) is not present in table \"%s\".", errdetail("Key (%s)=(%s) is not present in table \"%s\".",
key_names.data, key_values.data, key_names.data, key_values.data,
RelationGetRelationName(pk_rel)) :
errdetail("Key is not present in table \"%s\".",
RelationGetRelationName(pk_rel)), RelationGetRelationName(pk_rel)),
errtableconstraint(fk_rel, NameStr(riinfo->conname)))); errtableconstraint(fk_rel, NameStr(riinfo->conname))));
else else
@ -3238,8 +3276,11 @@ ri_ReportViolation(const RI_ConstraintInfo *riinfo,
RelationGetRelationName(pk_rel), RelationGetRelationName(pk_rel),
NameStr(riinfo->conname), NameStr(riinfo->conname),
RelationGetRelationName(fk_rel)), RelationGetRelationName(fk_rel)),
has_perm ?
errdetail("Key (%s)=(%s) is still referenced from table \"%s\".", errdetail("Key (%s)=(%s) is still referenced from table \"%s\".",
key_names.data, key_values.data, key_names.data, key_values.data,
RelationGetRelationName(fk_rel)) :
errdetail("Key is still referenced from table \"%s\".",
RelationGetRelationName(fk_rel)), RelationGetRelationName(fk_rel)),
errtableconstraint(fk_rel, NameStr(riinfo->conname)))); errtableconstraint(fk_rel, NameStr(riinfo->conname))));
} }

View File

@ -3240,6 +3240,7 @@ comparetup_index_btree(const SortTuple *a, const SortTuple *b,
{ {
Datum values[INDEX_MAX_KEYS]; Datum values[INDEX_MAX_KEYS];
bool isnull[INDEX_MAX_KEYS]; bool isnull[INDEX_MAX_KEYS];
char *key_desc;
/* /*
* Some rather brain-dead implementations of qsort (such as the one in * Some rather brain-dead implementations of qsort (such as the one in
@ -3250,13 +3251,15 @@ comparetup_index_btree(const SortTuple *a, const SortTuple *b,
Assert(tuple1 != tuple2); Assert(tuple1 != tuple2);
index_deform_tuple(tuple1, tupDes, values, isnull); index_deform_tuple(tuple1, tupDes, values, isnull);
key_desc = BuildIndexValueDescription(state->indexRel, values, isnull);
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_UNIQUE_VIOLATION), (errcode(ERRCODE_UNIQUE_VIOLATION),
errmsg("could not create unique index \"%s\"", errmsg("could not create unique index \"%s\"",
RelationGetRelationName(state->indexRel)), RelationGetRelationName(state->indexRel)),
errdetail("Key %s is duplicated.", key_desc ? errdetail("Key %s is duplicated.", key_desc) :
BuildIndexValueDescription(state->indexRel, errdetail("Duplicate keys exist."),
values, isnull)),
errtableconstraint(state->heapRel, errtableconstraint(state->heapRel,
RelationGetRelationName(state->indexRel)))); RelationGetRelationName(state->indexRel))));
} }

View File

@ -381,6 +381,37 @@ SELECT atest6 FROM atest6; -- ok
(0 rows) (0 rows)
COPY atest6 TO stdout; -- ok COPY atest6 TO stdout; -- ok
-- check error reporting with column privs
SET SESSION AUTHORIZATION regressuser1;
CREATE TABLE t1 (c1 int, c2 int, c3 int check (c3 < 5), primary key (c1, c2));
GRANT SELECT (c1) ON t1 TO regressuser2;
GRANT INSERT (c1, c2, c3) ON t1 TO regressuser2;
GRANT UPDATE (c1, c2, c3) ON t1 TO regressuser2;
-- seed data
INSERT INTO t1 VALUES (1, 1, 1);
INSERT INTO t1 VALUES (1, 2, 1);
INSERT INTO t1 VALUES (2, 1, 2);
INSERT INTO t1 VALUES (2, 2, 2);
INSERT INTO t1 VALUES (3, 1, 3);
SET SESSION AUTHORIZATION regressuser2;
INSERT INTO t1 (c1, c2) VALUES (1, 1); -- fail, but row not shown
ERROR: duplicate key value violates unique constraint "t1_pkey"
UPDATE t1 SET c2 = 1; -- fail, but row not shown
ERROR: duplicate key value violates unique constraint "t1_pkey"
INSERT INTO t1 (c1, c2) VALUES (null, null); -- fail, but see columns being inserted
ERROR: null value in column "c1" violates not-null constraint
DETAIL: Failing row contains (c1, c2) = (null, null).
INSERT INTO t1 (c3) VALUES (null); -- fail, but see columns being inserted or have SELECT
ERROR: null value in column "c1" violates not-null constraint
DETAIL: Failing row contains (c1, c3) = (null, null).
INSERT INTO t1 (c1) VALUES (5); -- fail, but see columns being inserted or have SELECT
ERROR: null value in column "c2" violates not-null constraint
DETAIL: Failing row contains (c1) = (5).
UPDATE t1 SET c3 = 10; -- fail, but see columns with SELECT rights, or being modified
ERROR: new row for relation "t1" violates check constraint "t1_c3_check"
DETAIL: Failing row contains (c1, c3) = (1, 10).
SET SESSION AUTHORIZATION regressuser1;
DROP TABLE t1;
-- test column-level privileges when involved with DELETE -- test column-level privileges when involved with DELETE
SET SESSION AUTHORIZATION regressuser1; SET SESSION AUTHORIZATION regressuser1;
ALTER TABLE atest6 ADD COLUMN three integer; ALTER TABLE atest6 ADD COLUMN three integer;

View File

@ -256,6 +256,31 @@ UPDATE atest5 SET one = 1; -- fail
SELECT atest6 FROM atest6; -- ok SELECT atest6 FROM atest6; -- ok
COPY atest6 TO stdout; -- ok COPY atest6 TO stdout; -- ok
-- check error reporting with column privs
SET SESSION AUTHORIZATION regressuser1;
CREATE TABLE t1 (c1 int, c2 int, c3 int check (c3 < 5), primary key (c1, c2));
GRANT SELECT (c1) ON t1 TO regressuser2;
GRANT INSERT (c1, c2, c3) ON t1 TO regressuser2;
GRANT UPDATE (c1, c2, c3) ON t1 TO regressuser2;
-- seed data
INSERT INTO t1 VALUES (1, 1, 1);
INSERT INTO t1 VALUES (1, 2, 1);
INSERT INTO t1 VALUES (2, 1, 2);
INSERT INTO t1 VALUES (2, 2, 2);
INSERT INTO t1 VALUES (3, 1, 3);
SET SESSION AUTHORIZATION regressuser2;
INSERT INTO t1 (c1, c2) VALUES (1, 1); -- fail, but row not shown
UPDATE t1 SET c2 = 1; -- fail, but row not shown
INSERT INTO t1 (c1, c2) VALUES (null, null); -- fail, but see columns being inserted
INSERT INTO t1 (c3) VALUES (null); -- fail, but see columns being inserted or have SELECT
INSERT INTO t1 (c1) VALUES (5); -- fail, but see columns being inserted or have SELECT
UPDATE t1 SET c3 = 10; -- fail, but see columns with SELECT rights, or being modified
SET SESSION AUTHORIZATION regressuser1;
DROP TABLE t1;
-- test column-level privileges when involved with DELETE -- test column-level privileges when involved with DELETE
SET SESSION AUTHORIZATION regressuser1; SET SESSION AUTHORIZATION regressuser1;
ALTER TABLE atest6 ADD COLUMN three integer; ALTER TABLE atest6 ADD COLUMN three integer;