From 77adbdfd2c36573cc014b7203643186f6e4bbd78 Mon Sep 17 00:00:00 2001 From: Brian Falk Date: Wed, 19 Feb 2020 19:59:26 +0000 Subject: [PATCH] internal/lsp: report use of disallowed internal packages An error should be reported if an "internal" package is imported into code that is outside of the tree rooted at the parent of the "internal" directory. Fixes #35937 Change-Id: If5ff3dd79b462087381d575dddb20b78c10f0a83 GitHub-Last-Rev: f5d19960046da7f9701325afc36b5bd0b9663ab6 GitHub-Pull-Request: golang/tools#207 Reviewed-on: https://go-review.googlesource.com/c/tools/+/218977 Reviewed-by: Rebecca Stambler Run-TryBot: Rebecca Stambler TryBot-Result: Gobot Gobot --- internal/lsp/cache/check.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/internal/lsp/cache/check.go b/internal/lsp/cache/check.go index 73eb48afad..e6f573dc8c 100644 --- a/internal/lsp/cache/check.go +++ b/internal/lsp/cache/check.go @@ -54,6 +54,19 @@ func (ph *packageHandle) packageKey() packageKey { } } +func (ph *packageHandle) isValidImportFor(parentPkgPath string) bool { + importPath := string(ph.m.pkgPath) + + pkgRootIndex := strings.Index(importPath, "/internal/") + if pkgRootIndex != -1 && parentPkgPath != "command-line-arguments" { + if !strings.HasPrefix(parentPkgPath, importPath[0:pkgRootIndex]) { + return false + } + } + + return true +} + // packageData contains the data produced by type-checking a package. type packageData struct { memoize.NoCopy @@ -368,6 +381,9 @@ func typeCheck(ctx context.Context, fset *token.FileSet, m *metadata, mode sourc if dep == nil { return nil, errors.Errorf("no package for import %s", pkgPath) } + if !dep.isValidImportFor(pkg.PkgPath()) { + return nil, errors.Errorf("invalid use of internal package %s", pkgPath) + } depPkg, err := dep.check(ctx) if err != nil { return nil, err