From 6d0dd113362056de4ddd8bcf3a9e8b71ed794aa4 Mon Sep 17 00:00:00 2001 From: Abhineet Deshpande Date: Mon, 4 Mar 2024 13:42:05 -0800 Subject: [PATCH] Add truncation for GCE term description length, GCE generator errors out on long descriptions. PiperOrigin-RevId: 612569559 --- capirca/lib/gce.py | 12 +++++++++--- tests/lib/gce_test.py | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/capirca/lib/gce.py b/capirca/lib/gce.py index edd115fb..46987297 100644 --- a/capirca/lib/gce.py +++ b/capirca/lib/gce.py @@ -97,6 +97,7 @@ class Term(gcp.Term): _TERM_TARGET_TAGS_LIMIT = 70 _TERM_PORTS_LIMIT = 256 _TERM_SERVICE_ACCOUNTS_LIMIT = 10 + _MAX_TERM_COMMENT_LENGTH = 2047 # Firewall rule name has to match specific RE: # The first character must be a lowercase letter, and all following characters @@ -200,11 +201,16 @@ def ConvertToDict(self): """ if self.term.owner: self.term.comment.append('Owner: %s' % self.term.owner) + description = ' '.join(self.term.comment) + if len(description) > self._MAX_TERM_COMMENT_LENGTH: + description = gcp.TruncateString( + description, self._MAX_TERM_COMMENT_LENGTH + ) term_dict = { - 'description': ' '.join(self.term.comment), + 'description': description, 'name': self.term.name, - 'direction': self.term.direction - } + 'direction': self.term.direction, + } if self.term.network: term_dict['network'] = self.term.network term_dict['name'] = '%s-%s' % ( diff --git a/tests/lib/gce_test.py b/tests/lib/gce_test.py index 53648f59..154897d0 100644 --- a/tests/lib/gce_test.py +++ b/tests/lib/gce_test.py @@ -578,6 +578,15 @@ } """ +BAD_TERM_COMMENT_LENGTH = """ +term bad-term-service-accounts-count {{ + comment:: "{very_long_comment}" + protocol:: tcp + action:: accept + source-tag:: ssh-bastion +}}""".format(very_long_comment='a' * + (gce.Term._MAX_TERM_COMMENT_LENGTH + 1) + 'truncated') + GOOD_TERM_EXCLUDE_RANGE = """ [ { @@ -1427,6 +1436,14 @@ def testTargetTagsAndTargetServiceAccountsError(self): GOOD_HEADER_INET + BAD_TERM_TARGET_TAGS_AND_SERVICE_ACCOUNTS, self.naming), EXP_INFO) + def testLongCommentTruncation(self): + self.naming.GetNetAddr.return_value = TEST_IPS + acl = gce.GCE( + policy.ParsePolicy(GOOD_HEADER + BAD_TERM_COMMENT_LENGTH, self.naming), + EXP_INFO) + self.assertIn('a' * gce.Term._MAX_TERM_COMMENT_LENGTH, str(acl)) + self.assertNotIn('truncated', str(acl)) + def testMixed(self): self.naming.GetNetAddr.return_value = TEST_IPS self.naming.GetServiceByProto.side_effect = [['53'], ['53']]