Repository: googleapis/api-linter
Pull request #1271 (2023-10-13 21:25:44)

feat(AIP-148): lint IP Address field format
As mandated in AIP-148, and IP Address field must have `(google.api.field_info).format` with one of the IP Address formats. This rule enforces that.


Patch:
diff --git a/docs/rules/0148/ip-address-format.md b/docs/rules/0148/ip-address-format.md
new file mode 100644
index 0000000..3f017b2
--- /dev/null
+++ b/docs/rules/0148/ip-address-format.md
@@ -0,0 +1,81 @@
+---
+rule:
+  aip: 148
+  name: [core, '0148', ip-address-format]
+  summary: Annotate IP address fields with an IP address format.
+permalink: /148/ip-address-format
+redirect_from:
+  - /0148/ip-address-format
+---
+
+# IP Address field format annotation
+
+This rule encourages the use of one of the IP Address format annotations,
+`IPV4`, `IPV6`, or `IPV4_OR_IPV6`, on the `ip_address` field or a field ending
+with `_ip_address`, as mandated in [AIP-148][].
+
+## Details
+
+This rule looks on for fields named `ip_address` or ending with `_ip_address`
+and complains if it does not have the `(google.api.field_info).format`
+annotation with one of `IPV4`, `IPV6`, or `IPV4_OR_IPV6`, or has a format other
+than than one of those.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "books/{book}"
+  };
+
+  string name = 1 [(google.api.field_behavior) = IDENTIFIER];
+  string ip_address = 2; // missing (google.api.field_info).format = IPV4
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "books/{book}"
+  };
+
+  string name = 1 [(google.api.field_behavior) = IDENTIFIER];
+  string ip_address = 2 [(google.api.field_info).format = IPV4];
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the field or its
+enclosing message. Remember to also include an [aip.dev/not-precedent][]
+comment explaining why.
+
+```proto
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "books/{book}"
+  };
+
+  string name = 1 [(google.api.field_behavior) = IDENTIFIER];
+
+  // (-- api-linter: core::0148::ip-address-format=disabled
+  //     aip.dev/not-precedent: We need to do this because reasons. --)
+  string ip_address = 2;
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-148]: https://aip.dev/148
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
\ No newline at end of file
diff --git a/rules/aip0148/aip0148.go b/rules/aip0148/aip0148.go
index 2432382..990288a 100644
--- a/rules/aip0148/aip0148.go
+++ b/rules/aip0148/aip0148.go
@@ -26,6 +26,7 @@ func AddRules(r lint.RuleRegistry) error {
 		declarativeFriendlyRequired,
 		fieldBehavior,
 		humanNames,
+		ipAddressFormat,
 		useUid,
 		uidFormat,
 	)
diff --git a/rules/aip0148/ip_address_format.go b/rules/aip0148/ip_address_format.go
new file mode 100644
index 0000000..3edcc91
--- /dev/null
+++ b/rules/aip0148/ip_address_format.go
@@ -0,0 +1,57 @@
+// Copyright 2023 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package aip0148
+
+import (
+	"strings"
+
+	"github.com/googleapis/api-linter/lint"
+	"github.com/googleapis/api-linter/rules/internal/utils"
+	"github.com/jhump/protoreflect/desc"
+	"google.golang.org/genproto/googleapis/api/annotations"
+	"google.golang.org/protobuf/types/descriptorpb"
+)
+
+var ipAddressFormats = []annotations.FieldInfo_Format{
+	annotations.FieldInfo_IPV4,
+	annotations.FieldInfo_IPV6,
+	annotations.FieldInfo_IPV4_OR_IPV6,
+}
+
+var ipAddressFormat = &lint.FieldRule{
+	Name: lint.NewRuleName(148, "ip-address-format"),
+	OnlyIf: func(fd *desc.FieldDescriptor) bool {
+		return fd.GetType() == descriptorpb.FieldDescriptorProto_TYPE_STRING && (fd.GetName() == "ip_address" || strings.HasSuffix(fd.GetName(), "_ip_address"))
+	},
+	LintField: func(fd *desc.FieldDescriptor) []lint.Problem {
+		if !utils.HasFormat(fd) || !oneofFormats(utils.GetFormat(fd), ipAddressFormats) {
+			return []lint.Problem{{
+				Message:    "IP Address fields must specify one of the `(google.api.field_info).format` values `IPV4`, `IPV6`, or `IPV4_OR_IPV6`",
+				Descriptor: fd,
+			}}
+		}
+		return nil
+	},
+}
+
+func oneofFormats(f annotations.FieldInfo_Format, desired []annotations.FieldInfo_Format) bool {
+	for _, d := range desired {
+		if f == d {
+			return true
+		}
+	}
+
+	return false
+}


Test patch:
diff --git a/rules/aip0148/ip_address_format_test.go b/rules/aip0148/ip_address_format_test.go
new file mode 100644
index 0000000..7c56ac2
--- /dev/null
+++ b/rules/aip0148/ip_address_format_test.go
@@ -0,0 +1,85 @@
+// Copyright 2023 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package aip0148
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestIpAddressFormat(t *testing.T) {
+	for _, test := range []struct {
+		name, Annotation, FieldName, Type string
+		problems                          testutils.Problems
+	}{
+		{
+			name:       "ValidIpAddressFormat",
+			FieldName:  "ip_address",
+			Annotation: "[(google.api.field_info).format = IPV4_OR_IPV6]",
+			Type:       "string",
+		},
+		{
+			name:       "ValidIpAddressSuffixFormat",
+			FieldName:  "incoming_ip_address",
+			Annotation: "[(google.api.field_info).format = IPV4_OR_IPV6]",
+			Type:       "string",
+		},
+		{
+			name:      "SkipNonIpAddress",
+			FieldName: "other",
+			Type:      "string",
+		},
+		{
+			name:      "SkipNonIpAddressSuffix",
+			FieldName: "zip_address",
+			Type:      "string",
+		},
+		{
+			name:      "SkipNonStringIpAddress",
+			FieldName: "ip_address",
+			Type:      "Foo",
+		},
+		{
+			name:      "InvalidMissingFormat",
+			FieldName: "ip_address",
+			Type:      "string",
+			problems:  testutils.Problems{{Message: "must specify one of"}},
+		},
+		{
+			name:       "InvalidWrongFormat",
+			FieldName:  "ip_address",
+			Annotation: "[(google.api.field_info).format = UUID4]",
+			Type:       "string",
+			problems:   testutils.Problems{{Message: "must specify one of"}},
+		},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			f := testutils.ParseProto3Tmpl(t, `
+				import "google/api/field_info.proto";
+
+				message Person {
+					{{.Type}} {{.FieldName}} = 2 {{.Annotation}};
+				}
+
+				message Foo {}
+			`, test)
+			field := f.GetMessageTypes()[0].GetFields()[0]
+			if diff := test.problems.SetDescriptor(field).Diff(ipAddressFormat.Lint(f)); diff != "" {
+				t.Errorf(diff)
+			}
+		})
+	}
+}