Repository: googleapis/api-linter
Pull request #655 (2020-10-10 18:37:28)

feat: Add three rules for AIP-154.
This adds three rules:

- Etags required on declarative-friendly resources
- Etags should not be duplicated on request messages that include the resource
- Etags should be strings.

apasel422: Separately we should probably also require the use of https://google.aip.dev/235#request-message-containing-standard-delete-request-messages for declarative-friendly resources, since otherwise there is no way to specify the etag for each name being deleted.

Patch:
diff --git a/docs/rules/0154/declarative-friendly-required.md b/docs/rules/0154/declarative-friendly-required.md
new file mode 100644
index 0000000..ba6bfb1
--- /dev/null
+++ b/docs/rules/0154/declarative-friendly-required.md
@@ -0,0 +1,106 @@
+---
+rule:
+  aip: 154
+  name: [core, '0154', declarative-friendly-required]
+  summary: Declarative-friendly resources must have an etag field.
+permalink: /154/declarative-friendly-required
+redirect_from:
+  - /0154/declarative-friendly-required
+---
+
+# Required etags
+
+This rule enforces that declarative-friendly resources have etags, as mandated
+in [AIP-154][].
+
+## Details
+
+This rule looks at any resource with a `google.api.resource` annotation that
+includes `style: DECLARATIVE_FRIENDLY`, and complains if it lacks a
+`string etag` field.
+
+Additionally, it looks at certain corresponding request messages (e.g.
+`DeleteBookRequest`) that _do not_ include the resource, and makes the same
+check.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "publishers/{publisher}/books/{book}"
+    style: DECLARATIVE_FRIENDLY
+  };
+
+  string name = 1;
+  // A string etag field should exist.
+}
+```
+
+```proto
+// Incorrect.
+message DeleteBookRequest {
+  string name = 1 [(google.api.resource_reference) = {
+    type: "library.googleapis.com/Book"
+  }];
+  // A string etag field should exist.
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "publishers/{publisher}/books/{book}"
+    style: DECLARATIVE_FRIENDLY
+  };
+
+  string name = 1;
+  string etag = 2;
+}
+```
+
+```proto
+// Correct.
+message DeleteBookRequest {
+  string name = 1 [(google.api.resource_reference) = {
+    type: "library.googleapis.com/Book"
+  }];
+  string etag = 2;
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the message.
+Remember to also include an [aip.dev/not-precedent][] comment explaining why.
+
+```proto
+// (-- api-linter: core::0154::declarative-friendly-required=disabled
+//     aip.dev/not-precedent: We need to do this because reasons. --)
+message Book {
+  option (google.api.resource) = {
+    type: "library.googleapis.com/Book"
+    pattern: "publishers/{publisher}/books/{book}"
+    style: DECLARATIVE_FRIENDLY
+  };
+
+  string name = 1;
+}
+```
+
+**Note:** Violations of declarative-friendly rules should be rare, as tools are
+likely to expect strong consistency.
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-154]: https://aip.dev/154
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/docs/rules/0154/field-type.md b/docs/rules/0154/field-type.md
new file mode 100644
index 0000000..bec89ad
--- /dev/null
+++ b/docs/rules/0154/field-type.md
@@ -0,0 +1,66 @@
+---
+rule:
+  aip: 154
+  name: [core, '0154', field-type]
+  summary: Etag fields must be strings.
+permalink: /154/field-type
+redirect_from:
+  - /0154/field-type
+---
+
+# Etag field type
+
+This rule enforces that `etag` fields are strings, as mandated in [AIP-154][].
+
+## Details
+
+This rule looks at any field named `etag` and complains if the type is anything
+other than `string`.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+message DeleteBookRequest {
+  string name = 1 [(google.api.resource_reference) = {
+    type: "library.googleapis.com/Book"
+  }];
+  bytes etag = 2;  // Should be string.
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+message DeleteBookRequest {
+  string name = 1 [(google.api.resource_reference) = {
+    type: "library.googleapis.com/Book"
+  }];
+  string etag = 2;
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the field.
+Remember to also include an [aip.dev/not-precedent][] comment explaining why.
+
+```proto
+message DeleteBookRequest {
+  string name = 1 [(google.api.resource_reference) = {
+    type: "library.googleapis.com/Book"
+  }];
+  // (-- api-linter: core::0154::field-type=disabled
+  //     aip.dev/not-precedent: We need to do this because reasons. --)
+  bytes etag = 2;
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-154]: https://aip.dev/154
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/docs/rules/0154/index.md b/docs/rules/0154/index.md
new file mode 100644
index 0000000..7cbd240
--- /dev/null
+++ b/docs/rules/0154/index.md
@@ -0,0 +1,10 @@
+---
+aip_listing: 154
+permalink: /154/
+redirect_from:
+  - /0154/
+---
+
+# Long-running operations
+
+{% include linter-aip-listing.md aip=154 %}
diff --git a/docs/rules/0154/no-duplicate-etag.md b/docs/rules/0154/no-duplicate-etag.md
new file mode 100644
index 0000000..d41e3dd
--- /dev/null
+++ b/docs/rules/0154/no-duplicate-etag.md
@@ -0,0 +1,66 @@
+---
+rule:
+  aip: 154
+  name: [core, '0154', no-duplicate-etag]
+  summary: |
+    Etag fields should not be set on request messages that include
+    the resource.
+permalink: /154/no-duplicate-etag
+redirect_from:
+  - /0154/no-duplicate-etag
+---
+
+# Required etags
+
+This rule enforces that `etag` fields are set on resources and requests that
+reference those resources by name, but not on requests that include the
+resource directly, as mandated in [AIP-154][].
+
+## Details
+
+This rule looks at any field named `etag` and complains if it is part of a
+request message including a resource that itself includes an etag.
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+message UpdateBookRequest {
+  Book book = 1;
+  google.protobuf.FieldMask update_mask = 2;
+  string etag = 3;  // The Book message already includes etag.
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+message UpdateBookRequest {
+  Book book = 1;
+  google.protobuf.FieldMask update_mask = 2;
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the field.
+Remember to also include an [aip.dev/not-precedent][] comment explaining why.
+
+```proto
+message UpdateBookRequest {
+  Book book = 1;
+  google.protobuf.FieldMask update_mask = 2;
+  // (-- api-linter: core::0154::no-duplicate-etag=disabled
+  //     aip.dev/not-precedent: We need to do this because reasons. --)
+  string etag = 3;
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-154]: https://aip.dev/154
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/rules/aip0154/aip0154.go b/rules/aip0154/aip0154.go
new file mode 100644
index 0000000..74d9674
--- /dev/null
+++ b/rules/aip0154/aip0154.go
@@ -0,0 +1,30 @@
+// Copyright 2020 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 aip0154 contains rules defined in https://aip.dev/154.
+package aip0154
+
+import (
+	"github.com/googleapis/api-linter/lint"
+)
+
+// AddRules adds all of the AIP-154 rules to the provided registry.
+func AddRules(r lint.RuleRegistry) error {
+	return r.Register(
+		154,
+		declarativeFriendlyRequired,
+		fieldType,
+		noDuplicateEtag,
+	)
+}
diff --git a/rules/aip0154/declarative_friendly_required.go b/rules/aip0154/declarative_friendly_required.go
new file mode 100644
index 0000000..d5f2703
--- /dev/null
+++ b/rules/aip0154/declarative_friendly_required.go
@@ -0,0 +1,84 @@
+// Copyright 2020 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 aip0154
+
+import (
+	"fmt"
+	"strings"
+
+	"github.com/googleapis/api-linter/lint"
+	"github.com/googleapis/api-linter/rules/internal/utils"
+	"github.com/jhump/protoreflect/desc"
+)
+
+var declarativeFriendlyRequired = &lint.MessageRule{
+	Name: lint.NewRuleName(154, "declarative-friendly-required"),
+	OnlyIf: func(m *desc.MessageDescriptor) bool {
+		// Sanity check: If the resource is not declarative-friendly, none of
+		// this logic applies.
+		if resource := utils.DeclarativeFriendlyResource(m); resource != nil {
+			// This should apply if the resource in question is declarative-friendly,
+			// but our IsDeclarativeFriendly method will return true for both
+			// resources and request messages, and they need to be handled subtly
+			// differently.
+			if m == resource {
+				return true
+			}
+
+			// If this is a request message, then make several more checks based on
+			// what the method looks like.
+			if name := m.GetName(); strings.HasSuffix(name, "Request") {
+				name = strings.TrimSuffix(name, "Request")
+
+				// If this is a GET request, then this message is exempt.
+				if method := utils.FindMethod(m.GetFile(), name); method != nil {
+					for _, rule := range utils.GetHTTPRules(method) {
+						if rule.Method == "GET" {
+							return false
+						}
+					}
+				}
+
+				// If the message contains the resource, then this message is exempt.
+				for _, field := range m.GetFields() {
+					if field.GetMessageType() == resource {
+						return false
+					}
+				}
+
+				// Okay, this message should include an etag.
+				return true
+			}
+		}
+
+		return false
+	},
+	LintMessage: func(m *desc.MessageDescriptor) []lint.Problem {
+		for _, field := range m.GetFields() {
+			if field.GetName() == "etag" {
+				return nil
+			}
+		}
+
+		whoami := "resources"
+		if strings.HasSuffix(m.GetName(), "Request") {
+			whoami = "mutation requests without the resource"
+		}
+		return []lint.Problem{{
+			Message:    fmt.Sprintf("Declarative-friendly %s should include `string etag`.", whoami),
+			Descriptor: m,
+		}}
+	},
+}
diff --git a/rules/aip0154/field_type.go b/rules/aip0154/field_type.go
new file mode 100644
index 0000000..a2108d0
--- /dev/null
+++ b/rules/aip0154/field_type.go
@@ -0,0 +1,42 @@
+// Copyright 2020 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 aip0154
+
+import (
+	"fmt"
+
+	"github.com/googleapis/api-linter/lint"
+	"github.com/googleapis/api-linter/locations"
+	"github.com/googleapis/api-linter/rules/internal/utils"
+	"github.com/jhump/protoreflect/desc"
+)
+
+var fieldType = &lint.FieldRule{
+	Name: lint.NewRuleName(154, "field-type"),
+	OnlyIf: func(f *desc.FieldDescriptor) bool {
+		return f.GetName() == "etag"
+	},
+	LintField: func(f *desc.FieldDescriptor) []lint.Problem {
+		if t := utils.GetTypeName(f); t != "string" {
+			return []lint.Problem{{
+				Message:    fmt.Sprintf("The etag field should be a string, not %s.", t),
+				Descriptor: f,
+				Location:   locations.FieldType(f),
+				Suggestion: "string",
+			}}
+		}
+		return nil
+	},
+}
diff --git a/rules/aip0154/no_duplicate_etag.go b/rules/aip0154/no_duplicate_etag.go
new file mode 100644
index 0000000..fc73927
--- /dev/null
+++ b/rules/aip0154/no_duplicate_etag.go
@@ -0,0 +1,48 @@
+// Copyright 2020 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 aip0154
+
+import (
+	"strings"
+
+	"github.com/googleapis/api-linter/lint"
+	"github.com/jhump/protoreflect/desc"
+)
+
+var noDuplicateEtag = &lint.FieldRule{
+	Name: lint.NewRuleName(154, "no-duplicate-etag"),
+	OnlyIf: func(f *desc.FieldDescriptor) bool {
+		return f.GetName() == "etag" && strings.HasSuffix(f.GetOwner().GetName(), "Request")
+	},
+	LintField: func(f *desc.FieldDescriptor) []lint.Problem {
+		for _, otherField := range f.GetOwner().GetFields() {
+			if m := otherField.GetMessageType(); m != nil {
+				// if strings.Contains("UpdateBookRequest", "Book")
+				//
+				// If this is a random, unrelated (not the resource) message, we want to ignore it.
+				// Ditto for *other* resources, which could be relevant for custom methods,
+				// which is why we do a string check and not a google.api.resource check.
+				if strings.Contains(f.GetOwner().GetName(), m.GetName()) && m.FindFieldByName("etag") != nil {
+					return []lint.Problem{{
+						Message:    "Request messages that include the resource should omit etag.",
+						Descriptor: f,
+						Suggestion: "",
+					}}
+				}
+			}
+		}
+		return nil
+	},
+}
diff --git a/rules/internal/utils/declarative_friendly.go b/rules/internal/utils/declarative_friendly.go
index 8239817..5b3b28b 100644
--- a/rules/internal/utils/declarative_friendly.go
+++ b/rules/internal/utils/declarative_friendly.go
@@ -22,155 +22,112 @@ import (
 	apb "google.golang.org/genproto/googleapis/api/annotations"
 )
 
-// IsDeclarativeFriendlyMessage returns true if the descriptor is
-// declarative-friendly.
+// DeclarativeFriendlyResource returns the declarative-friendly resource
+// associated with this descriptor.
 //
-// This is true if:
-// - The message is annotated with google.api.resource and
-//   style: DECLARATIVE_FRIENDLY is set.
-// - The message is a standard method request message for a resource with
-//   google.api.resource and style:DECLARATIVE_FRIENDLY set.
-func IsDeclarativeFriendlyMessage(m *desc.MessageDescriptor) bool {
-	// Get the google.api.resource annotation and see if it is styled
-	// declarative-friendly.
-	if resource := GetResource(m); resource != nil {
-		for _, style := range resource.GetStyle() {
-			if style == apb.ResourceDescriptor_DECLARATIVE_FRIENDLY {
-				return true
+// For messages:
+// If the message is annotated with google.api.resource and
+// style: DECLARATIVE_FRIENDLY is set, that message is returned.
+// If the message is a standard method request message for a resource with
+// google.api.resource and style:DECLARATIVE_FRIENDLY set, then the resource
+// is returned.
+//
+// For methods:
+// If the output message is a declarative-friendly resource, it is returned.
+// If the method begins with "List" and the first repeated field is a
+// declarative-friendly resource, the resource is returned.
+// If the method begins with "Delete", the return type is Empty, and an
+// appropriate resource message is found and is declarative-friendly, that
+// resource is returned.
+// If the method is a custom method where a matching resource is found (by
+// subset checks on the name) and is declarative-friendly, the resource is
+// returned.
+//
+// If there is no declarative-friendly resource, it returns nil.
+func DeclarativeFriendlyResource(d desc.Descriptor) *desc.MessageDescriptor {
+	switch m := d.(type) {
+	case *desc.MessageDescriptor:
+		// Get the google.api.resource annotation and see if it is styled
+		// declarative-friendly.
+		if resource := GetResource(m); resource != nil {
+			for _, style := range resource.GetStyle() {
+				if style == apb.ResourceDescriptor_DECLARATIVE_FRIENDLY {
+					return m
+				}
 			}
 		}
-	}
-
-	// If this is a standard method request message, find the corresponding
-	// resource message. The easiest way to do this is to farm it out to the
-	// corresponding method.
-	if n := m.GetName(); strings.HasSuffix(n, "Request") {
-		if method := findMethod(m.GetFile(), strings.TrimSuffix(n, "Request")); method != nil {
-			return IsDeclarativeFriendlyMethod(method)
-		}
-	}
-
-	// We found no evidence that this descriptor is supposed to be
-	// declarative-friendly. Return false.
-	return false
-}
 
-// IsDeclarativeFriendlyMethod returns true if the method is for a
-// declarative-friendly resource.
-//
-// This is true if:
-// - The output message is a declarative-friendly message
-//   (according to IsDeclarativeFriendlyMessage).
-// - The method begins with "List" and the first repeated field is a
-//   declarative-friendly resource.
-// - The method begins with "Delete", the return type is Empty, and an
-//   appropriate resource message is found and is declarative-friendly.
-// - The method is a custom method where a matching resource is found (by
-//   subset checks on the name) and is declarative-friendly.
-func IsDeclarativeFriendlyMethod(m *desc.MethodDescriptor) bool {
-	// Get the return type for the method. If the method is an LRO, then
-	// get the response type from the operation_info annotation.
-	response := m.GetOutputType()
-	if response.GetFullyQualifiedName() == "google.longrunning.Operation" {
-		if opInfo := GetOperationInfo(m); opInfo != nil {
-			response = findMessage(m.GetFile(), opInfo.GetResponseType())
-
-			// Sanity check: We may not have found the message.
-			// If that is the case, give up and assume the method is not
-			// declarative-friendly.
-			if response == nil {
-				return false
+		// If this is a standard method request message, find the corresponding
+		// resource message. The easiest way to do this is to farm it out to the
+		// corresponding method.
+		if n := m.GetName(); strings.HasSuffix(n, "Request") {
+			if method := FindMethod(m.GetFile(), strings.TrimSuffix(n, "Request")); method != nil {
+				return DeclarativeFriendlyResource(method)
 			}
 		}
-	}
-
-	// If the return value has a google.api.resource annotation, we can
-	// assume it is the resource and check it.
-	if IsResource(response) {
-		return IsDeclarativeFriendlyMessage(response)
-	}
-
-	// If the return value is a List response (AIP-132), we should be able
-	// to find the resource as a field in the response.
-	if n := response.GetName(); strings.HasPrefix(n, "List") && strings.HasSuffix(n, "Response") {
-		for _, field := range response.GetFields() {
-			if field.IsRepeated() && field.GetMessageType() != nil {
-				return IsDeclarativeFriendlyMessage(field.GetMessageType())
+	case *desc.MethodDescriptor:
+		// Get the return type for the method. If the method is an LRO, then
+		// get the response type from the operation_info annotation.
+		response := m.GetOutputType()
+		if response.GetFullyQualifiedName() == "google.longrunning.Operation" {
+			if opInfo := GetOperationInfo(m); opInfo != nil {
+				response = FindMessage(m.GetFile(), opInfo.GetResponseType())
+
+				// Sanity check: We may not have found the message.
+				// If that is the case, give up and assume the method is not
+				// declarative-friendly.
+				if response == nil {
+					return nil
+				}
 			}
 		}
-	}
 
-	// If this is a Delete method (AIP-135) with a return value of Empty,
-	// try to find the resource.
-	if strings.HasPrefix(m.GetName(), "Delete") && m.GetOutputType().GetName() == "Empty" {
-		if resource := findMessage(m.GetFile(), strings.TrimPrefix(m.GetName(), "Delete")); resource != nil {
-			return IsDeclarativeFriendlyMessage(resource)
+		// If the return value has a google.api.resource annotation, we can
+		// assume it is the resource and check it.
+		if IsResource(response) {
+			return DeclarativeFriendlyResource(response)
 		}
-	}
 
-	// At this point, we probably have a custom method.
-	// Try to identify a resource by whittling away at the method name and
-	// seeing if there is a match.
-	snakeName := strings.Split(strcase.SnakeCase(m.GetName()), "_")
-	for i := 1; i < len(snakeName); i++ {
-		name := strcase.UpperCamelCase(strings.Join(snakeName[i:], "_"))
-		if resource := findMessage(m.GetFile(), name); resource != nil {
-			return IsDeclarativeFriendlyMessage(resource)
+		// If the return value is a List response (AIP-132), we should be able
+		// to find the resource as a field in the response.
+		if n := response.GetName(); strings.HasPrefix(n, "List") && strings.HasSuffix(n, "Response") {
+			for _, field := range response.GetFields() {
+				if field.IsRepeated() && field.GetMessageType() != nil {
+					return DeclarativeFriendlyResource(field.GetMessageType())
+				}
+			}
 		}
-	}
-
-	// We found no evidence that this method is declarative-friendly.
-	return false
-}
-
-// findMessage looks for a message in a file and all imports within the
-// same package.
-func findMessage(f *desc.FileDescriptor, name string) *desc.MessageDescriptor {
-	// FileDescriptor.FindMessage requires fully-qualified message names;
-	// attempt to infer that.
-	if !strings.Contains(name, ".") && f.GetPackage() != "" {
-		name = f.GetPackage() + "." + name
-	}
-
-	// Attempt to find the message in the file provided.
-	if m := f.FindMessage(name); m != nil {
-		return m
-	}
 
-	// Attempt to find the message in any dependency files if they are in the
-	// same package.
-	for _, dep := range f.GetDependencies() {
-		if f.GetPackage() == dep.GetPackage() {
-			if m := findMessage(dep, name); m != nil {
-				return m
+		// If this is a Delete method (AIP-135) with a return value of Empty,
+		// try to find the resource.
+		if strings.HasPrefix(m.GetName(), "Delete") && m.GetOutputType().GetName() == "Empty" {
+			if resource := FindMessage(m.GetFile(), strings.TrimPrefix(m.GetName(), "Delete")); resource != nil {
+				return DeclarativeFriendlyResource(resource)
 			}
 		}
-	}
-
-	// Whelp, no luck. Too bad.
-	return nil
-}
 
-// findMethod returns a method with a given name, or nil if none is found.
-func findMethod(f *desc.FileDescriptor, name string) *desc.MethodDescriptor {
-	for _, s := range getServices(f) {
-		for _, m := range s.GetMethods() {
-			if m.GetName() == name {
-				return m
+		// At this point, we probably have a custom method.
+		// Try to identify a resource by whittling away at the method name and
+		// seeing if there is a match.
+		snakeName := strings.Split(strcase.SnakeCase(m.GetName()), "_")
+		for i := 1; i < len(snakeName); i++ {
+			name := strcase.UpperCamelCase(strings.Join(snakeName[i:], "_"))
+			if resource := FindMessage(m.GetFile(), name); resource != nil {
+				return DeclarativeFriendlyResource(resource)
 			}
 		}
 	}
 	return nil
 }
 
-// getServices finds all services in a file and all imports within the
-// same package.
-func getServices(f *desc.FileDescriptor) []*desc.ServiceDescriptor {
-	answer := f.GetServices()
-	for _, dep := range f.GetDependencies() {
-		if f.GetPackage() == dep.GetPackage() {
-			answer = append(answer, getServices(dep)...)
-		}
-	}
-	return answer
+// IsDeclarativeFriendlyMessage returns true if the descriptor is
+// declarative-friendly (if DeclarativeFriendlyResource(m) is not nil).
+func IsDeclarativeFriendlyMessage(m *desc.MessageDescriptor) bool {
+	return DeclarativeFriendlyResource(m) != nil
+}
+
+// IsDeclarativeFriendlyMethod returns true if the method is for a
+// declarative-friendly resource (if DeclarativeFriendlyResource(m) is not nil).
+func IsDeclarativeFriendlyMethod(m *desc.MethodDescriptor) bool {
+	return DeclarativeFriendlyResource(m) != nil
 }
diff --git a/rules/internal/utils/find.go b/rules/internal/utils/find.go
new file mode 100644
index 0000000..f92c2ef
--- /dev/null
+++ b/rules/internal/utils/find.go
@@ -0,0 +1,74 @@
+// Copyright 2020 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 utils
+
+import (
+	"strings"
+
+	"github.com/jhump/protoreflect/desc"
+)
+
+// FindMessage looks for a message in a file and all imports within the
+// same package.
+func FindMessage(f *desc.FileDescriptor, name string) *desc.MessageDescriptor {
+	// FileDescriptor.FindMessage requires fully-qualified message names;
+	// attempt to infer that.
+	if !strings.Contains(name, ".") && f.GetPackage() != "" {
+		name = f.GetPackage() + "." + name
+	}
+
+	// Attempt to find the message in the file provided.
+	if m := f.FindMessage(name); m != nil {
+		return m
+	}
+
+	// Attempt to find the message in any dependency files if they are in the
+	// same package.
+	for _, dep := range f.GetDependencies() {
+		if f.GetPackage() == dep.GetPackage() {
+			if m := FindMessage(dep, name); m != nil {
+				return m
+			}
+		}
+	}
+
+	// Whelp, no luck. Too bad.
+	return nil
+}
+
+// FindMethod searches a file and all imports within the same package, and
+// returns the method with a given name, or nil if none is found.
+func FindMethod(f *desc.FileDescriptor, name string) *desc.MethodDescriptor {
+	for _, s := range getServices(f) {
+		for _, m := range s.GetMethods() {
+			if m.GetName() == name {
+				return m
+			}
+		}
+	}
+	return nil
+}
+
+// getServices finds all services in a file and all imports within the
+// same package.
+func getServices(f *desc.FileDescriptor) []*desc.ServiceDescriptor {
+	answer := f.GetServices()
+	for _, dep := range f.GetDependencies() {
+		if f.GetPackage() == dep.GetPackage() {
+			answer = append(answer, getServices(dep)...)
+		}
+	}
+	return answer
+}
diff --git a/rules/rules.go b/rules/rules.go
index b416109..9747be7 100644
--- a/rules/rules.go
+++ b/rules/rules.go
@@ -68,6 +68,7 @@ import (
 	"github.com/googleapis/api-linter/rules/aip0143"
 	"github.com/googleapis/api-linter/rules/aip0146"
 	"github.com/googleapis/api-linter/rules/aip0151"
+	"github.com/googleapis/api-linter/rules/aip0154"
 	"github.com/googleapis/api-linter/rules/aip0156"
 	"github.com/googleapis/api-linter/rules/aip0158"
 	"github.com/googleapis/api-linter/rules/aip0159"
@@ -105,6 +106,7 @@ var aipAddRulesFuncs = []addRulesFuncType{
 	aip0143.AddRules,
 	aip0146.AddRules,
 	aip0151.AddRules,
+	aip0154.AddRules,
 	aip0156.AddRules,
 	aip0158.AddRules,
 	aip0159.AddRules,


Test patch:
diff --git a/rules/aip0154/aip0154_test.go b/rules/aip0154/aip0154_test.go
new file mode 100644
index 0000000..74a7de2
--- /dev/null
+++ b/rules/aip0154/aip0154_test.go
@@ -0,0 +1,27 @@
+// Copyright 2020 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 aip0154
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/lint"
+)
+
+func TestAddRules(t *testing.T) {
+	if err := AddRules(lint.NewRuleRegistry()); err != nil {
+		t.Errorf("AddRules got an error: %v", err)
+	}
+}
diff --git a/rules/aip0154/declarative_friendly_required_test.go b/rules/aip0154/declarative_friendly_required_test.go
new file mode 100644
index 0000000..489e86f
--- /dev/null
+++ b/rules/aip0154/declarative_friendly_required_test.go
@@ -0,0 +1,117 @@
+// Copyright 2020 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 aip0154
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestDeclarativeFriendlyRequired(t *testing.T) {
+	t.Run("Resource", func(t *testing.T) {
+		for _, test := range []struct {
+			name     string
+			Style    string
+			Etag     string
+			problems testutils.Problems
+		}{
+			{"ValidEtagNotDF", "", "string etag = 2;", nil},
+			{"ValidNoEtagNotDF", "", "", nil},
+			{"ValidEtagDF", "style: DECLARATIVE_FRIENDLY", "string etag = 2;", nil},
+			{"InvalidNoEtagDF", "style: DECLARATIVE_FRIENDLY", "", testutils.Problems{{Message: "string etag"}}},
+		} {
+			f := testutils.ParseProto3Tmpl(t, `
+				import "google/api/resource.proto";
+				message Book {
+					option (google.api.resource) = {
+						type: "library.googleapis.com/Book"
+						{{.Style}}
+					};
+
+					string name = 1;
+					{{.Etag}}
+				}
+			`, test)
+			m := f.GetMessageTypes()[0]
+			if diff := test.problems.SetDescriptor(m).Diff(declarativeFriendlyRequired.Lint(f)); diff != "" {
+				t.Errorf(diff)
+			}
+		}
+	})
+
+	t.Run("Requests", func(t *testing.T) {
+		for _, test := range []struct {
+			name     string
+			Style    string
+			Etag     string
+			problems testutils.Problems
+		}{
+			{"ValidEtagNotDF", "", "string etag = 2;", nil},
+			{"ValidNoEtagNotDF", "", "", nil},
+			{"ValidEtagDF", "style: DECLARATIVE_FRIENDLY", "string etag = 2;", nil},
+			{"InvalidNoEtagDF", "style: DECLARATIVE_FRIENDLY", "", testutils.Problems{{Message: "string etag"}}},
+		} {
+			t.Run(test.name, func(t *testing.T) {
+				f := testutils.ParseProto3Tmpl(t, `
+					import "google/api/annotations.proto";
+					import "google/api/resource.proto";
+					service Library {
+						rpc GetBook(GetBookRequest) returns (Book) {
+							option (google.api.http) = {
+								get: "/v1/{name=publishers/*/books/*}"
+							};
+						}
+						rpc CreateBook(CreateBookRequest) returns (Book) {
+							option (google.api.http) = {
+								post: "/v1/{parent=publishers/*}/books"
+								body: "*"
+							};
+						}
+						rpc DeleteBook(DeleteBookRequest) returns (Book) {
+							option (google.api.http) = {
+								delete: "/v1/{name=publishers/*/books/*}"
+							};
+						}
+					}
+					message Book {
+						option (google.api.resource) = {
+							type: "library.googleapis.com/Book"
+							{{.Style}}
+						};
+						string name = 1;
+						string etag = 2;
+					}
+					message GetBookRequest {
+						string name = 1;
+					}
+					message CreateBookRequest {
+						string parent = 1;
+						Book book = 2;
+						string book_id = 3;
+					}
+					message DeleteBookRequest {
+						string name = 1;
+						{{.Etag}}
+					}
+				`, test)
+				m := f.FindMessage("DeleteBookRequest")
+				if diff := test.problems.SetDescriptor(m).Diff(declarativeFriendlyRequired.Lint(f)); diff != "" {
+					t.Errorf(diff)
+				}
+			})
+		}
+	})
+}
diff --git a/rules/aip0154/field_type_test.go b/rules/aip0154/field_type_test.go
new file mode 100644
index 0000000..4743121
--- /dev/null
+++ b/rules/aip0154/field_type_test.go
@@ -0,0 +1,44 @@
+// Copyright 2020 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 aip0154
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestFieldType(t *testing.T) {
+	for _, test := range []struct {
+		name     string
+		Type     string
+		problems testutils.Problems
+	}{
+		{"ValidString", "string", nil},
+		{"Invalid", "bytes", testutils.Problems{{Suggestion: "string"}}},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			f := testutils.ParseProto3Tmpl(t, `
+				message Book {
+					{{.Type}} etag = 1;
+				}
+			`, test)
+			field := f.GetMessageTypes()[0].GetFields()[0]
+			if diff := test.problems.SetDescriptor(field).Diff(fieldType.Lint(f)); diff != "" {
+				t.Errorf(diff)
+			}
+		})
+	}
+}
diff --git a/rules/aip0154/no_duplicate_etag_test.go b/rules/aip0154/no_duplicate_etag_test.go
new file mode 100644
index 0000000..31b201b
--- /dev/null
+++ b/rules/aip0154/no_duplicate_etag_test.go
@@ -0,0 +1,60 @@
+// Copyright 2020 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 aip0154
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestNoDuplicateEtag(t *testing.T) {
+	for _, test := range []struct {
+		name     string
+		Etag     string
+		problems testutils.Problems
+	}{
+		{"InvalidUpdate", "string etag = 2;", testutils.Problems{{Message: "omit etag", Suggestion: ""}}},
+		{"ValidUpdate", "", nil},
+	} {
+		t.Run(test.name, func(t *testing.T) {
+			f := testutils.ParseProto3Tmpl(t, `
+				service Library {
+					rpc UpdateBook(UpdateBookRequest) returns (Book);
+					rpc DeleteBook(DeleteBookRequest) returns (Book);
+				}
+
+				message UpdateBookRequest {
+					Book book = 1;
+					{{.Etag}}
+				}
+
+				message DeleteBookRequest {
+					string name = 1;
+					string etag = 2;
+				}
+
+				message Book {
+					string name = 1;
+					string etag = 2;
+				}
+			`, test)
+			m := f.GetMessageTypes()
+			if diff := test.problems.SetDescriptor(m[0].FindFieldByName("etag")).Diff(noDuplicateEtag.Lint(f)); diff != "" {
+				t.Errorf(diff)
+			}
+		})
+	}
+}
diff --git a/rules/internal/utils/declarative_friendly_test.go b/rules/internal/utils/declarative_friendly_test.go
index 4e58cb8..5e4c974 100644
--- a/rules/internal/utils/declarative_friendly_test.go
+++ b/rules/internal/utils/declarative_friendly_test.go
@@ -194,27 +194,3 @@ func TestDeclarativeFriendlyMethod(t *testing.T) {
 		}
 	})
 }
-
-func TestFindMessage(t *testing.T) {
-	files := testutils.ParseProtoStrings(t, map[string]string{
-		"a.proto": `
-			package test;
-			message Book {}
-		`,
-		"b.proto": `
-			package other;
-			message Scroll {}
-		`,
-		"c.proto": `
-			package test;
-			import "a.proto";
-			import "b.proto";
-		`,
-	})
-	if book := findMessage(files["c.proto"], "Book"); book == nil {
-		t.Errorf("Got nil, expected Book message.")
-	}
-	if scroll := findMessage(files["c.proto"], "Scroll"); scroll != nil {
-		t.Errorf("Got Sctoll message, expected nil.")
-	}
-}
diff --git a/rules/internal/utils/find_test.go b/rules/internal/utils/find_test.go
new file mode 100644
index 0000000..e8b64be
--- /dev/null
+++ b/rules/internal/utils/find_test.go
@@ -0,0 +1,45 @@
+// Copyright 2020 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 utils
+
+import (
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+func TestFindMessage(t *testing.T) {
+	files := testutils.ParseProtoStrings(t, map[string]string{
+		"a.proto": `
+			package test;
+			message Book {}
+		`,
+		"b.proto": `
+			package other;
+			message Scroll {}
+		`,
+		"c.proto": `
+			package test;
+			import "a.proto";
+			import "b.proto";
+		`,
+	})
+	if book := FindMessage(files["c.proto"], "Book"); book == nil {
+		t.Errorf("Got nil, expected Book message.")
+	}
+	if scroll := FindMessage(files["c.proto"], "Scroll"); scroll != nil {
+		t.Errorf("Got Sctoll message, expected nil.")
+	}
+}