Skip to content

pkg/keys: implement SafeFormatter for roachpb.Key - #86813

Merged
craig[bot] merged 1 commit into
cockroachdb:masterfrom
abarganier:redact_keys
Sep 8, 2022
Merged

craig[bot] merged 1 commit into
cockroachdb:masterfrom
abarganier:redact_keys

Conversation

@abarganier

@abarganier abarganier commented Aug 24, 2022 •

Copy link
Copy Markdown
Contributor

Currently, when a key is logged, the entirety of the pretty-printed
key is redacted, hindering observability when parsing through redacted
logs (something that will become more common with upcoming compliance
requirements).

For example, prior to this patch, a pretty-printed key would appear
in the following way for the unredacted/redacted cases, respectively:

- unredacted: ‹/Table/42/1222/"index key"›
- redacted:   ‹x›

This patch addresses this by implementing the SafeFormatter interface
for roachpb.Key and roachpb.RKey, yielding the following result
when looking at the same example above:

- unredacted: /Table/42/1222/‹"index key"›
- redacted:   /Table/42/1222/‹x›

While the index key itself remains redacted, the ability to see the
specific table, index, and in the case of tenant tables, the tenant
itself, provides much better observability into which table & index
a log line is referring to than before.

Note that this implementation is only partial. It currently only
supports keys that fall in the /Table keyspace for application
tenants and system tenants. Keyspaces such as Meta1, Meta2, Local,
etc. are not yet supported, but can be added with much more ease
in the future now that the example has been set.

Finally, we remove the maxLen and related truncation logic from
StringWithDirs, as this is no longer used. Furthermore, the
truncation was invalid as it could have truncated a utf-8
sequence in the wrong place, making the result invalid utf-8.

This PR is a continuation of the work originally done by @kzh in
#67065. See the original PR for some initial discussions.

Release note (security update): redacted logs will now reveal
pretty-printed keys, except for the index key values themselves.
For example /Table/42/1222/‹x› will be shown instead of ‹x›
(which was shown previously). This improved redaction is available
for the /Table keyspace for both system and application tenants.
Other keyspaces such as /Meta1, /Meta2, /Local, etc. are not
yet supported.

Release justification: low risk, high benefit observability changes

Addresses #86316

@abarganier
abarganier requested review from a team, knz and kzh August 24, 2022 20:22
@abarganier
abarganier requested a review from a team as a code owner August 24, 2022 20:22
@abarganier
abarganier requested a review from a team August 24, 2022 20:22
@cockroach-teamcity

Copy link
Copy Markdown
Member

This change is Reviewable

@abarganier
abarganier removed the request for review from a team August 24, 2022 20:22

@knz knz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm overall OK on the architecture. Well done 💯
(you still need a detailed review but I'm OOO this week and next)

Reviewable status: :shipit: complete! 0 of 0 LGTMs obtained (waiting on @kzh)

@abarganier abarganier left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm overall OK on the architecture. Well done 💯
(you still need a detailed review but I'm OOO this week and next)

Thanks for taking a look - enjoy your time off!

Reviewable status: :shipit: complete! 0 of 0 LGTMs obtained (waiting on @kzh)

@andreimatei andreimatei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good stuff

Reviewable status: :shipit: complete! 0 of 0 LGTMs obtained (waiting on @abarganier and @kzh)


pkg/keys/printer.go line 553 at r1 (raw file):

	}
	return fmt.Sprintf("/%s%s", tID, key.WithFormat(valDirs, true))
}

please comment the true as true /* quoteRaw */. Better yet:

type QuoteOpt bool
const (
  QuoteRaw QuoteOpt = true
  DontQuoteRaw QuoteOpt = false
)

I think this API is prominent enough to deserve this kind of polish.


pkg/keys/printer.go line 636 at r1 (raw file):

//
// See keysutil.UglyPrint() for an inverse.
func PrettyPrint(valDirs []encoding.Direction, key roachpb.Key) string {

maybe also link to SafeFormat in the comment.


pkg/keys/printer.go line 641 at r1 (raw file):

// formatTableKey formats the given key in the system tenant table keyspace & redacts any
// sensitive information from the result. For example:

make this comment explicit about what's redacted and what's not. No reason to be vague about "sensitive information".


pkg/keys/printer.go line 642 at r1 (raw file):

// formatTableKey formats the given key in the system tenant table keyspace & redacts any
// sensitive information from the result. For example:
//		Pretty-printed: "/Table/42/122/"index key""

from this comment I don't understand which of the two strings will be produced.


pkg/keys/printer.go line 648 at r1 (raw file):

	prefixLength := 1

	// Accommodate for if the table key contains a primary index field in the prefix.

the "for if" sounds weird to me


pkg/keys/printer.go line 650 at r1 (raw file):

	// Accommodate for if the table key contains a primary index field in the prefix.
	// ex: /Table/<table id>/<index id>
	if len(vals) > 1 && types[1] == encoding.Int {

Shouldn't we increase prefixLength by 2 when there's an index id?


pkg/keys/printer.go line 650 at r1 (raw file):

	// Accommodate for if the table key contains a primary index field in the prefix.
	// ex: /Table/<table id>/<index id>
	if len(vals) > 1 && types[1] == encoding.Int {

would it be better to return an error if types[1] is not an Int? And also if types[0] is not a Uvarint?
Or perhaps to render an error instead of returning it.


pkg/keys/printer.go line 657 at r1 (raw file):

		w.Printf("/%v", redact.Safe(vals[i]))
	}
	for _, val := range vals[prefixLength:] {

If I understand correctly, I think this will separately redact every datum, as opposed to one big set of redaction markers.
So, we'll get/Table/1/2</x></y></z> instead of /Table/1/2/<x/y/z>`. Is this on purpose?


pkg/keys/printer.go line 669 at r1 (raw file):

	key, tID, err := DecodeTenantPrefix(key)
	if err != nil {
		w.Printf("/err:%v", redact.SafeString(err.Error()))

I'm not sure this redact.SafeString() is right. What makes err.Error() safe? Shouldn't we pass err directly and let the redact library work its magic?


pkg/keys/printer.go line 695 at r1 (raw file):

	}

	w.Print(prettyPrintInternal(opts.Dirs, key, opts.QuoteRaw /* quoteRawKeys */))

this is a fallback for keys not recognized by the table and keys for which the table doesn't have an sfFunc? Please add a comment, also suggesting what the result will be.


pkg/keys/printer_test.go line 134 at r1 (raw file):

	}{
		{
			"table with string index key",

can you please add a test with a simple multi-column value?


pkg/roachpb/data.go line 85 at r1 (raw file):

	PrettyPrintKey func(valDirs []encoding.Direction, key Key) string

	SafeFormatKey func(w redact.SafeWriter, key Key, opts KeyFormatOptions)

pls comment and hint to where this is initialized. And also link from PrettyPrintKey above to this one?


pkg/roachpb/data.go line 107 at r1 (raw file):

}

// FormattedKey is a wrapper for Key to include formatting options.

hint to why this weird type is necessary - I think it's because we want to pass info through the redact library and back into key.SafeFormat().
But actually, is it really necessary? AFAICS, this key.WithFormat() has only one caller (in tenantKeyPrint()), and that caller doesn't even care about redaction - so can't it operate directly on a roachpb.Key and call functions that take the options separately?


pkg/util/encoding/encoding.go line 1945 at r1 (raw file):

		bb, s, err := prettyPrintFirstValue(valDir, b)
		if err != nil {
			allDecoded = false

is there a point in continuing after an error? Will bb be meaningful or will this loop forever? If it does make sense to continue, please add a comment. And, if prettyPrintFirstValue can return both an error and other meaningful return values, please take the opportunity to improve comments on that function too.

@abarganier abarganier left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the feedback, I found it very helpful. RFAL.

Reviewable status: :shipit: complete! 0 of 0 LGTMs obtained (waiting on @andreimatei and @kzh)


pkg/keys/printer.go line 553 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

please comment the true as true /* quoteRaw */. Better yet:

type QuoteOpt bool
const (
  QuoteRaw QuoteOpt = true
  DontQuoteRaw QuoteOpt = false
)

I think this API is prominent enough to deserve this kind of polish.

Yup good idea - done.


pkg/keys/printer.go line 636 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

maybe also link to SafeFormat in the comment.

Done.


pkg/keys/printer.go line 641 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

make this comment explicit about what's redacted and what's not. No reason to be vague about "sensitive information".

Done.


pkg/keys/printer.go line 642 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

from this comment I don't understand which of the two strings will be produced.

Fixed - let me know if you think I should clarify further.


pkg/keys/printer.go line 648 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

the "for if" sounds weird to me

Done.


pkg/keys/printer.go line 650 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

Shouldn't we increase prefixLength by 2 when there's an index id?

The comments here are a bit confusing as the /Table piece of the resulting string is added by the caller, not here in formatTableKey. I've updated the comments to reflect this.

My understanding is that by default we are expecting a table ID, so the prefix length by default is 1. If the 2nd value is of type encoding.Int, then we bump the prefix length by 1 to include the <index_id>. Is there some case I'm not considering where we'd want to bump it by 2 instead of 1?


pkg/keys/printer.go line 650 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

would it be better to return an error if types[1] is not an Int? And also if types[0] is not a Uvarint?
Or perhaps to render an error instead of returning it.

I think for cases like "/Table/42/12.34", it's acceptable for types[1] to not be an Int, but I've added a check to ensure types[0] is a Uvarint. If it's not, we render an error.


pkg/keys/printer.go line 657 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

If I understand correctly, I think this will separately redact every datum, as opposed to one big set of redaction markers.
So, we'll get/Table/1/2</x></y></z> instead of /Table/1/2/<x/y/z>`. Is this on purpose?

My intention was to produce /Table/1/2/‹x›/‹y›/‹x›, but I'm open to changing the format if you think we should just collapse the entire remainder into /Table/1/2/‹x/y/z›


pkg/keys/printer.go line 669 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

I'm not sure this redact.SafeString() is right. What makes err.Error() safe? Shouldn't we pass err directly and let the redact library work its magic?

Ah yes, good catch. Removed the redact.SafeString call.


pkg/keys/printer.go line 695 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

this is a fallback for keys not recognized by the table and keys for which the table doesn't have an sfFunc? Please add a comment, also suggesting what the result will be.

Done.


pkg/keys/printer_test.go line 134 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

can you please add a test with a simple multi-column value?

Sure. My bad, I realize this made the expected format a bit confusing.


pkg/roachpb/data.go line 85 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

pls comment and hint to where this is initialized. And also link from PrettyPrintKey above to this one?

Done.


pkg/roachpb/data.go line 107 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

hint to why this weird type is necessary - I think it's because we want to pass info through the redact library and back into key.SafeFormat().
But actually, is it really necessary? AFAICS, this key.WithFormat() has only one caller (in tenantKeyPrint()), and that caller doesn't even care about redaction - so can't it operate directly on a roachpb.Key and call functions that take the options separately?

Thanks for calling this out - I agree this type is confusing & not necessary. I've removed FormattedKey entirely and included the valDirs argument where appropriate as a replacement (this is better aligned with the existing DictEntry/PrettyPrint interface anyway).


pkg/util/encoding/encoding.go line 1945 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

is there a point in continuing after an error? Will bb be meaningful or will this loop forever? If it does make sense to continue, please add a comment. And, if prettyPrintFirstValue can return both an error and other meaningful return values, please take the opportunity to improve comments on that function too.

I think you're right that bb won't be meaningful for our purposes here. While I don't expect things to loop forever (see below), I also don't see any reason to continue if we failed to decode.

If err != nil then bb comes back as nil in most cases. In the few cases where it isn't nil, such as with Duration, it will trim the type identifier prefix byte and return that as bb. Whether the subsequent call returns nil, bb with another prefix type identifier byte trimmed off, or successfully decodes, depends on the following bytes.

In any case, any failure to decode a value will trigger the only eventual callers of prettyPrintFirstValue (PrettyPrintValue and PrettyPrintValuesWithTypes) to re-attempt the decoding from scratch anyway, so I see no reason to continue here or in prettyPrintValueImpl.

I've since updated both prettyPrintValuesWithTypesImpl and prettyPrintValueImpl to quit early in this error case.

@andreimatei andreimatei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:lgtm:

Reviewable status: :shipit: complete! 1 of 0 LGTMs obtained (waiting on @abarganier and @kzh)


pkg/keys/printer.go line 650 at r1 (raw file):

Previously, abarganier (Alex Barganier) wrote…

The comments here are a bit confusing as the /Table piece of the resulting string is added by the caller, not here in formatTableKey. I've updated the comments to reflect this.

My understanding is that by default we are expecting a table ID, so the prefix length by default is 1. If the 2nd value is of type encoding.Int, then we bump the prefix length by 1 to include the <index_id>. Is there some case I'm not considering where we'd want to bump it by 2 instead of 1?

you know more than I do. Sounds good.


pkg/keys/printer.go line 657 at r1 (raw file):

Previously, abarganier (Alex Barganier) wrote…

My intention was to produce /Table/1/2/‹x›/‹y›/‹x›, but I'm open to changing the format if you think we should just collapse the entire remainder into /Table/1/2/‹x/y/z›

No, I think /Table/1/2/‹x›/‹y›/‹x›. It just wasn't clear to me that that's what we're getting.


pkg/keys/printer.go line 662 at r4 (raw file):

// `safeString` is instead marked & used as a `redact.SafeString`, and
// we short-circuit the rest of the redaction operation.
var tableKeyOverrides = []struct {

could we integrate this in KeyDict? I think it'd be nicer to avoid having a parallel structure.


pkg/keys/printer.go line 664 at r4 (raw file):

var tableKeyOverrides = []struct {
	key        roachpb.Key
	safeString string

should this be redact.SafeString if the main point of this structure is to use the values for redaction? Then you won't need a cast in formatTableKey.


pkg/keys/printer.go line 666 at r4 (raw file):

	safeString string
}{
	{SystemDescriptorTableSpan.Key, "/SystemDescriptorTableSpan/Start"},

could we make it such that any key within this span gets rendered with the SystemDescriptorTableSpan prefix?


pkg/keys/printer.go line 666 at r4 (raw file):

	safeString string
}{
	{SystemDescriptorTableSpan.Key, "/SystemDescriptorTableSpan/Start"},

How about /Table/SystemDescriptors?


pkg/keys/printer.go line 667 at r4 (raw file):

}{
	{SystemDescriptorTableSpan.Key, "/SystemDescriptorTableSpan/Start"},
	{SystemZonesTableSpan.Key, "/SystemZonesTableSpan/Start"},

Can we do better and display the name of all system tables? At least the tables with IDs below 50 we know for sure are system tables; I think more recently we added some scheme to have system tables with dynamic IDs above 50, so I guess those can't be identified.


pkg/util/encoding/encoding.go line 1912 at r3 (raw file):

		return vals1, types1
	}
	if undoPrefixEnd, ok := UndoPrefixEnd(b); ok {

if you copy this code, please add a few more comments. Say here that, if the straight-up decoding above failed, we try again assuming that the key was a result of a PrefixEnd() call.

@abarganier abarganier left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewable status: :shipit: complete! 0 of 0 LGTMs obtained (and 1 stale) (waiting on @andreimatei and @kzh)


pkg/keys/printer.go line 650 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

you know more than I do. Sounds good.

👍


pkg/keys/printer.go line 657 at r1 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

No, I think /Table/1/2/‹x›/‹y›/‹x›. It just wasn't clear to me that that's what we're getting.

Gotcha - I appreciate the callout. I went ahead and updated the comments to include an example to help make it clearer.


pkg/keys/printer.go line 662 at r4 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

could we integrate this in KeyDict? I think it'd be nicer to avoid having a parallel structure.

Yeah agreed - we can do better to fit this into the existing KeyDict/KeyComprehensionTable logic and get away from this structure. I think we can add a single KeyDict entry for table IDs 0->50 where we can alter the pretty-print prefix (e.g. /Table/System) and then create a mapping of TableID->Friendly name.

To managed the scope of this PR, I'm going to do this in a follow up PR.


pkg/keys/printer.go line 664 at r4 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

should this be redact.SafeString if the main point of this structure is to use the values for redaction? Then you won't need a cast in formatTableKey.

Will handle in follow-up PR.


pkg/keys/printer.go line 666 at r4 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

could we make it such that any key within this span gets rendered with the SystemDescriptorTableSpan prefix?

Will handle in follow-up PR.


pkg/keys/printer.go line 666 at r4 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

How about /Table/SystemDescriptors?

Will handle in follow-up PR.


pkg/keys/printer.go line 667 at r4 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

Can we do better and display the name of all system tables? At least the tables with IDs below 50 we know for sure are system tables; I think more recently we added some scheme to have system tables with dynamic IDs above 50, so I guess those can't be identified.

Will handle in follow-up PR.


pkg/util/encoding/encoding.go line 1945 at r1 (raw file):

Previously, abarganier (Alex Barganier) wrote…

I think you're right that bb won't be meaningful for our purposes here. While I don't expect things to loop forever (see below), I also don't see any reason to continue if we failed to decode.

If err != nil then bb comes back as nil in most cases. In the few cases where it isn't nil, such as with Duration, it will trim the type identifier prefix byte and return that as bb. Whether the subsequent call returns nil, bb with another prefix type identifier byte trimmed off, or successfully decodes, depends on the following bytes.

In any case, any failure to decode a value will trigger the only eventual callers of prettyPrintFirstValue (PrettyPrintValue and PrettyPrintValuesWithTypes) to re-attempt the decoding from scratch anyway, so I see no reason to continue here or in prettyPrintValueImpl.

I've since updated both prettyPrintValuesWithTypesImpl and prettyPrintValueImpl to quit early in this error case.

Welp, I was wrong here. I didn't notice that PrettyPrintValue will still return the decoded string if the call to UndoPrefixEnd fails... By returning in this error case we broke some tests that expect the remainder of the key to be decoded. e.g.:

../../../../sql/logictest/testdata/logic_test/crdb_internal:701: SELECT crdb_internal.pretty_key(e'\\xa82a00918ed9':::BYTES, (-5096189069466142898):::INT8);
        expected:
            /Table/32/???/9/6/81
        but found (query options: "") :
            /Table/32/???

I've reverted the change to return in this case & added a comment explaining why we continue.


pkg/util/encoding/encoding.go line 1912 at r3 (raw file):

Previously, andreimatei (Andrei Matei) wrote…

if you copy this code, please add a few more comments. Say here that, if the straight-up decoding above failed, we try again assuming that the key was a result of a PrefixEnd() call.

Done.

@abarganier
abarganier force-pushed the redact_keys branch 8 times, most recently from dafdc3c to fca4e07 Compare September 6, 2022 14:28
@abarganier
abarganier force-pushed the redact_keys branch 2 times, most recently from 36961e1 to 5a92a32 Compare September 8, 2022 18:10
Currently, when a key is logged, the entirety of the pretty-printed
key is redacted, hindering observability when parsing through redacted
logs (something that will become more common with upcoming compliance
requirements).

For example, prior to this patch, a pretty-printed key would appear
in the following way for the unredacted/redacted cases, respectively:

	- unredacted: ‹/Table/42/1222/"index key"›
	- redacted:   ‹x›

This patch addresses this by implementing the SafeFormatter interface
for `roachpb.Key` and `roachpb.RKey`, yielding the following result
when looking at the same example above:

	- unredacted: /Table/42/1222/‹"index key"›
	- redacted:   /Table/42/1222/‹x›

While the index key itself remains redacted, the ability to see the
specific table, index, and in the case of tenant tables, the tenant
itself, provides much better observability into which table & index
a log line is referring to than before.

Note that this implementation is only partial. It currently only
supports keys that fall in the `/Table` keyspace for application
tenants and system tenants. Keyspaces such as Meta1, Meta2, Local,
etc. are not yet supported, but can be added with much more ease
in the future now that the example has been set.

Finally, we remove the `maxLen` and related truncation logic from
`StringWithDirs`, as this is no longer used. Furthermore, the
truncation was invalid as it could have truncated a utf-8
sequence in the wrong place, making the result invalid utf-8.

Release note (security update): redacted logs will now reveal
pretty-printed keys, except for the index key values themselves.
For example `/Table/42/1222/‹x›` will be shown instead of `‹x›`
(which was shown previously). This improved redaction is available
for the `/Table` keyspace for both system and application tenants.
Other keyspaces such as `/Meta1`, `/Meta2`, `/Local`, etc. are not
yet supported.

Release justification: low risk, high benefit observability changes
@abarganier

Copy link
Copy Markdown
Contributor Author

bors r=andreimatei

@craig

craig Bot commented Sep 8, 2022

Copy link
Copy Markdown
Contributor

Build succeeded:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants