Repository: googleapis/api-linter
Pull request #1125 (2023-03-17 20:27:08)

feat(AIP-122): enforce output_only resource IDs
Adds rule to check that either Resource ID field allowed by AIP-122 is classified as `OUTPUT_ONLY`.

See https://github.com/aip-dev/google.aip.dev/pull/1040.


Patch:
diff --git a/docs/rules/0122/resource-id-output-only.md b/docs/rules/0122/resource-id-output-only.md
new file mode 100644
index 0000000..3ee56d0
--- /dev/null
+++ b/docs/rules/0122/resource-id-output-only.md
@@ -0,0 +1,79 @@
+---
+rule:
+  aip: 122
+  name: [core, '0122', resource-id-output-only]
+  summary: Resource ID fields must be classified as `OUTPUT_ONLY`.
+permalink: /122/resource-id-output-only
+redirect_from:
+  - /0122/resource-id-output-only
+---
+
+# Name field suffix
+
+This rule enforces that resource ID fields are classified as `OUTPUT_ONLY`, as
+mandated in [AIP-122][].
+
+## Details
+
+This rule scans all resource fields and complains if it sees an ID field, named
+as `uid` or with the `_id` suffix, that is not classified as `OUTPUT_ONLY`.
+
+## 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;
+  // Should have `(google.api.field_behavior) = OUTPUT_ONLY`.
+  string book_id = 2;
+  // Should have `(google.api.field_behavior) = OUTPUT_ONLY`.
+  string uid = 3;
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "books/{book}"
+  };
+  string name = 1;
+  string book_id = 2 [(google.api.field_behavior) = OUTPUT_ONLY];
+  string uid = 3 [(google.api.field_behavior) = OUTPUT_ONLY];
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the field.
+
+```proto
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "books/{book}"
+  };
+  string name = 1;
+  // (-- api-linter: core::0122::resource-id-output-only=disabled
+  //     aip.dev/not-precedent: We need to do this because reasons. --)
+  string book_id = 2;
+  // (-- api-linter: core::0122::resource-id-output-only=disabled
+  //     aip.dev/not-precedent: We need to do this because reasons. --)
+  string uid = 3;
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-122]: http://aip.dev/122
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/rules/aip0122/aip0122.go b/rules/aip0122/aip0122.go
index 9600d57..e5075ba 100644
--- a/rules/aip0122/aip0122.go
+++ b/rules/aip0122/aip0122.go
@@ -28,5 +28,6 @@ func AddRules(r lint.RuleRegistry) error {
 		httpURICase,
 		nameSuffix,
 		resourceReferenceType,
+		resourceIdOutputOnly,
 	)
 }
diff --git a/rules/aip0122/resource_id_output_only.go b/rules/aip0122/resource_id_output_only.go
new file mode 100644
index 0000000..d00ade0
--- /dev/null
+++ b/rules/aip0122/resource_id_output_only.go
@@ -0,0 +1,60 @@
+// Copyright 2019 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 aip0122
+
+import (
+	"github.com/googleapis/api-linter/lint"
+	"github.com/googleapis/api-linter/rules/internal/utils"
+	"github.com/jhump/protoreflect/desc"
+	"github.com/stoewer/go-strcase"
+	"google.golang.org/genproto/googleapis/api/annotations"
+)
+
+var resourceIdOutputOnly = &lint.FieldRule{
+	Name: lint.NewRuleName(122, "resource-id-output-only"),
+	OnlyIf: func(f *desc.FieldDescriptor) bool {
+		var idName string
+		p := f.GetParent().(*desc.MessageDescriptor)
+
+		// Build an expected ID field name based on the Resource `singular`
+		// field or by parsing the `type`.
+		isRes := utils.IsResource(p)
+		if isRes {
+			res := utils.GetResource(p)
+			idName = res.GetSingular()
+			if idName == "" {
+				if _, t, ok := utils.SplitResourceTypeName(res.GetType()); ok {
+					idName = strcase.SnakeCase(t)
+				}
+			}
+			idName += "_id"
+		}
+
+		isId := f.GetName() == "uid" || f.GetName() == idName
+		return isRes && isId
+	},
+	LintField: func(f *desc.FieldDescriptor) []lint.Problem {
+		behaviors := utils.GetFieldBehavior(f)
+		if !behaviors.Contains(annotations.FieldBehavior_OUTPUT_ONLY.String()) {
+			return []lint.Problem{
+				{
+					Message:    "Resource ID fields must have field_behavior OUTPUT_ONLY",
+					Descriptor: f,
+				},
+			}
+		}
+		return nil
+	},
+}
diff --git a/rules/aip0123/resource_type_name.go b/rules/aip0123/resource_type_name.go
index 42c960c..36ae6f7 100644
--- a/rules/aip0123/resource_type_name.go
+++ b/rules/aip0123/resource_type_name.go
@@ -17,7 +17,6 @@ package aip0123
 import (
 	"fmt"
 	"regexp"
-	"strings"
 	"unicode"
 
 	"github.com/googleapis/api-linter/lint"
@@ -37,15 +36,14 @@ var resourceTypeName = &lint.MessageRule{
 	},
 	LintMessage: func(m *desc.MessageDescriptor) []lint.Problem {
 		resource := utils.GetResource(m)
-		resourceType := resource.GetType()
-		if strings.Count(resourceType, "/") != 1 {
+		_, typeName, ok := utils.SplitResourceTypeName(resource.GetType())
+		if !ok {
 			return []lint.Problem{{
 				Message:    "Resource type names must be of the form {Service Name}/{Type}.",
 				Descriptor: m,
 				Location:   locations.MessageResource(m),
 			}}
 		}
-		typeName := strings.Split(resourceType, "/")[1]
 		if !unicode.IsUpper(rune(typeName[0])) {
 			return []lint.Problem{{
 				Message:    fmt.Sprintf("Type %q must be UpperCamelCase", typeName),
diff --git a/rules/internal/utils/extension.go b/rules/internal/utils/extension.go
index bd7267a..5228943 100644
--- a/rules/internal/utils/extension.go
+++ b/rules/internal/utils/extension.go
@@ -166,3 +166,18 @@ func FindResource(reference string, file *desc.FileDescriptor) *apb.ResourceDesc
 	}
 	return nil
 }
+
+// SplitResourceTypeName splits the `Resource.type` field into the service name
+// and the resource type name.
+func SplitResourceTypeName(typ string) (service string, typeName string, ok bool) {
+	split := strings.Split(typ, "/")
+	if len(split) != 2 || split[0] == "" || split[1] == "" {
+		return
+	}
+
+	service = split[0]
+	typeName = split[1]
+	ok = true
+
+	return
+}


Test patch:
diff --git a/rules/aip0122/resource_id_output_only_test.go b/rules/aip0122/resource_id_output_only_test.go
new file mode 100644
index 0000000..a4c50fb
--- /dev/null
+++ b/rules/aip0122/resource_id_output_only_test.go
@@ -0,0 +1,54 @@
+// Copyright 2019 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 aip0122
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestResourceIdOutputOnly(t *testing.T) {
+	for _, test := range []struct {
+		name          string
+		FieldName     string
+		FieldBehavior string
+		problems      testutils.Problems
+	}{
+		{"ValidWithSuffix", "book_id", "[(google.api.field_behavior) = OUTPUT_ONLY]", testutils.Problems{}},
+		{"ValidUID", "uid", "[(google.api.field_behavior) = OUTPUT_ONLY]", testutils.Problems{}},
+		{"InvalidWithSuffix", "book_id", "", testutils.Problems{{Message: "OUTPUT_ONLY"}}},
+		{"InvalidUID", "uid", "", testutils.Problems{{Message: "OUTPUT_ONLY"}}},
+		{"SkipDifferentIdField", "foo_id", "", testutils.Problems{}},
+	} {
+		f := testutils.ParseProto3Tmpl(t, `
+			import "google/api/resource.proto";
+			import "google/api/field_behavior.proto";
+
+			message Book {
+				option (google.api.resource) = {
+					type: "library.googleapis.com/Book"
+					pattern: "books/{book}"
+				};
+				string name = 1;
+				string {{.FieldName}} = 2 {{.FieldBehavior}};
+			}
+		`, test)
+		field := f.GetMessageTypes()[0].GetFields()[1]
+		if diff := test.problems.SetDescriptor(field).Diff(resourceIdOutputOnly.Lint(f)); diff != "" {
+			t.Errorf(diff)
+		}
+	}
+}
diff --git a/rules/internal/utils/extension_test.go b/rules/internal/utils/extension_test.go
index a5c6654..06d8d3e 100644
--- a/rules/internal/utils/extension_test.go
+++ b/rules/internal/utils/extension_test.go
@@ -373,3 +373,28 @@ func TestFindResource(t *testing.T) {
 		})
 	}
 }
+
+func TestSplitResourceTypeName(t *testing.T) {
+	for _, tst := range []struct {
+		name, input, service, typeName string
+		ok                             bool
+	}{
+		{"Valid", "foo.googleapis.com/Foo", "foo.googleapis.com", "Foo", true},
+		{"InvalidExtraSlashes", "foo.googleapis.com/Foo/Bar", "", "", false},
+		{"InvalidNoService", "/Foo", "", "", false},
+		{"InvalidNoTypeName", "foo.googleapis.com/", "", "", false},
+	} {
+		t.Run(tst.name, func(t *testing.T) {
+			s, typ, ok := SplitResourceTypeName(tst.input)
+			if ok != tst.ok {
+				t.Fatalf("Expected %v for ok, but got %v", tst.ok, ok)
+			}
+			if diff := cmp.Diff(s, tst.service); diff != "" {
+				t.Errorf("service: got(-),want(+):\n%s", diff)
+			}
+			if diff := cmp.Diff(typ, tst.typeName); diff != "" {
+				t.Errorf("type name: got(-),want(+):\n%s", diff)
+			}
+		})
+	}
+}