github.com/bugraaydogar/snapd@v0.0.0-20210315170335-8c70bb858939/interfaces/policy/basedeclaration_test.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2016-2018 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package policy_test
    21  
    22  import (
    23  	"fmt"
    24  	"strings"
    25  
    26  	. "gopkg.in/check.v1"
    27  
    28  	"github.com/snapcore/snapd/asserts"
    29  	"github.com/snapcore/snapd/interfaces"
    30  	"github.com/snapcore/snapd/interfaces/builtin"
    31  	"github.com/snapcore/snapd/interfaces/policy"
    32  	"github.com/snapcore/snapd/release"
    33  	"github.com/snapcore/snapd/snap"
    34  	"github.com/snapcore/snapd/snap/snaptest"
    35  	"github.com/snapcore/snapd/strutil"
    36  	"github.com/snapcore/snapd/testutil"
    37  )
    38  
    39  type baseDeclSuite struct {
    40  	baseDecl        *asserts.BaseDeclaration
    41  	restoreSanitize func()
    42  }
    43  
    44  var _ = Suite(&baseDeclSuite{})
    45  
    46  func (s *baseDeclSuite) SetUpSuite(c *C) {
    47  	s.restoreSanitize = snap.MockSanitizePlugsSlots(func(snapInfo *snap.Info) {})
    48  	s.baseDecl = asserts.BuiltinBaseDeclaration()
    49  }
    50  
    51  func (s *baseDeclSuite) TearDownSuite(c *C) {
    52  	s.restoreSanitize()
    53  }
    54  
    55  func (s *baseDeclSuite) connectCand(c *C, iface, slotYaml, plugYaml string) *policy.ConnectCandidate {
    56  	if slotYaml == "" {
    57  		slotYaml = fmt.Sprintf(`name: slot-snap
    58  version: 0
    59  slots:
    60    %s:
    61  `, iface)
    62  	}
    63  	if plugYaml == "" {
    64  		plugYaml = fmt.Sprintf(`name: plug-snap
    65  version: 0
    66  plugs:
    67    %s:
    68  `, iface)
    69  	}
    70  	slotSnap := snaptest.MockInfo(c, slotYaml, nil)
    71  	plugSnap := snaptest.MockInfo(c, plugYaml, nil)
    72  	return &policy.ConnectCandidate{
    73  		Plug:            interfaces.NewConnectedPlug(plugSnap.Plugs[iface], nil, nil),
    74  		Slot:            interfaces.NewConnectedSlot(slotSnap.Slots[iface], nil, nil),
    75  		BaseDeclaration: s.baseDecl,
    76  	}
    77  }
    78  
    79  func (s *baseDeclSuite) installSlotCand(c *C, iface string, snapType snap.Type, yaml string) *policy.InstallCandidate {
    80  	if yaml == "" {
    81  		yaml = fmt.Sprintf(`name: install-slot-snap
    82  version: 0
    83  type: %s
    84  slots:
    85    %s:
    86  `, snapType, iface)
    87  	}
    88  	snap := snaptest.MockInfo(c, yaml, nil)
    89  	return &policy.InstallCandidate{
    90  		Snap:            snap,
    91  		BaseDeclaration: s.baseDecl,
    92  	}
    93  }
    94  
    95  func (s *baseDeclSuite) installPlugCand(c *C, iface string, snapType snap.Type, yaml string) *policy.InstallCandidate {
    96  	if yaml == "" {
    97  		yaml = fmt.Sprintf(`name: install-plug-snap
    98  version: 0
    99  type: %s
   100  plugs:
   101    %s:
   102  `, snapType, iface)
   103  	}
   104  	snap := snaptest.MockInfo(c, yaml, nil)
   105  	return &policy.InstallCandidate{
   106  		Snap:            snap,
   107  		BaseDeclaration: s.baseDecl,
   108  	}
   109  }
   110  
   111  const declTempl = `type: snap-declaration
   112  authority-id: canonical
   113  series: 16
   114  snap-name: @name@
   115  snap-id: @snapid@
   116  publisher-id: @publisher@
   117  @plugsSlots@
   118  timestamp: 2016-09-30T12:00:00Z
   119  sign-key-sha3-384: Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij
   120  
   121  AXNpZw==`
   122  
   123  func (s *baseDeclSuite) mockSnapDecl(c *C, name, snapID, publisher string, plugsSlots string) *asserts.SnapDeclaration {
   124  	encoded := strings.Replace(declTempl, "@name@", name, 1)
   125  	encoded = strings.Replace(encoded, "@snapid@", snapID, 1)
   126  	encoded = strings.Replace(encoded, "@publisher@", publisher, 1)
   127  	if plugsSlots != "" {
   128  		encoded = strings.Replace(encoded, "@plugsSlots@", strings.TrimSpace(plugsSlots), 1)
   129  	} else {
   130  		encoded = strings.Replace(encoded, "@plugsSlots@\n", "", 1)
   131  	}
   132  	a, err := asserts.Decode([]byte(encoded))
   133  	c.Assert(err, IsNil)
   134  	return a.(*asserts.SnapDeclaration)
   135  }
   136  
   137  func (s *baseDeclSuite) TestAutoConnection(c *C) {
   138  	all := builtin.Interfaces()
   139  
   140  	// these have more complex or in flux policies and have their
   141  	// own separate tests
   142  	snowflakes := map[string]bool{
   143  		"content":            true,
   144  		"core-support":       true,
   145  		"home":               true,
   146  		"lxd-support":        true,
   147  		"multipass-support":  true,
   148  		"packagekit-control": true,
   149  		"snapd-control":      true,
   150  		"dummy":              true,
   151  	}
   152  
   153  	// these simply auto-connect, anything else doesn't
   154  	autoconnect := map[string]bool{
   155  		"audio-playback":          true,
   156  		"browser-support":         true,
   157  		"desktop":                 true,
   158  		"desktop-legacy":          true,
   159  		"gsettings":               true,
   160  		"media-hub":               true,
   161  		"mir":                     true,
   162  		"network":                 true,
   163  		"network-bind":            true,
   164  		"network-status":          true,
   165  		"online-accounts-service": true,
   166  		"opengl":                  true,
   167  		"optical-drive":           true,
   168  		"screen-inhibit-control":  true,
   169  		"ubuntu-download-manager": true,
   170  		"unity7":                  true,
   171  		"unity8":                  true,
   172  		"upower-observe":          true,
   173  		"wayland":                 true,
   174  		"x11":                     true,
   175  	}
   176  
   177  	for _, iface := range all {
   178  		if snowflakes[iface.Name()] {
   179  			continue
   180  		}
   181  		expected := autoconnect[iface.Name()]
   182  		comm := Commentf(iface.Name())
   183  
   184  		// check base declaration
   185  		cand := s.connectCand(c, iface.Name(), "", "")
   186  		arity, err := cand.CheckAutoConnect()
   187  		if expected {
   188  			c.Check(err, IsNil, comm)
   189  			c.Check(arity.SlotsPerPlugAny(), Equals, false)
   190  		} else {
   191  			c.Check(err, NotNil, comm)
   192  		}
   193  	}
   194  }
   195  
   196  func (s *baseDeclSuite) TestAutoConnectPlugSlot(c *C) {
   197  	all := builtin.Interfaces()
   198  
   199  	// these have more complex or in flux policies and have their
   200  	// own separate tests
   201  	snowflakes := map[string]bool{
   202  		"classic-support": true,
   203  		"content":         true,
   204  		"home":            true,
   205  		"lxd-support":     true,
   206  	}
   207  
   208  	for _, iface := range all {
   209  		if snowflakes[iface.Name()] {
   210  			continue
   211  		}
   212  		c.Check(iface.AutoConnect(nil, nil), Equals, true)
   213  	}
   214  }
   215  
   216  func (s *baseDeclSuite) TestInterimAutoConnectionHome(c *C) {
   217  	restore := release.MockOnClassic(true)
   218  	defer restore()
   219  	cand := s.connectCand(c, "home", "", "")
   220  	arity, err := cand.CheckAutoConnect()
   221  	c.Check(err, IsNil)
   222  	c.Check(arity.SlotsPerPlugAny(), Equals, false)
   223  
   224  	release.OnClassic = false
   225  	_, err = cand.CheckAutoConnect()
   226  	c.Check(err, ErrorMatches, `auto-connection denied by slot rule of interface \"home\"`)
   227  }
   228  
   229  func (s *baseDeclSuite) TestHomeReadAll(c *C) {
   230  	const plugYaml = `name: plug-snap
   231  version: 0
   232  plugs:
   233    home:
   234      read: all
   235  `
   236  	restore := release.MockOnClassic(true)
   237  	defer restore()
   238  	cand := s.connectCand(c, "home", "", plugYaml)
   239  	err := cand.Check()
   240  	c.Check(err, NotNil)
   241  
   242  	_, err = cand.CheckAutoConnect()
   243  	c.Check(err, NotNil)
   244  
   245  	release.OnClassic = false
   246  	err = cand.Check()
   247  	c.Check(err, NotNil)
   248  
   249  	_, err = cand.CheckAutoConnect()
   250  	c.Check(err, NotNil)
   251  }
   252  
   253  func (s *baseDeclSuite) TestHomeReadDefault(c *C) {
   254  	const plugYaml = `name: plug-snap
   255  version: 0
   256  plugs:
   257    home: null
   258  `
   259  	restore := release.MockOnClassic(true)
   260  	defer restore()
   261  	cand := s.connectCand(c, "home", "", plugYaml)
   262  	err := cand.Check()
   263  	c.Check(err, IsNil)
   264  
   265  	// Same as TestInterimAutoConnectionHome()
   266  	arity, err := cand.CheckAutoConnect()
   267  	c.Check(err, IsNil)
   268  	c.Check(arity.SlotsPerPlugAny(), Equals, false)
   269  
   270  	release.OnClassic = false
   271  	err = cand.Check()
   272  	c.Check(err, IsNil)
   273  
   274  	// Same as TestInterimAutoConnectionHome()
   275  	_, err = cand.CheckAutoConnect()
   276  	c.Check(err, NotNil)
   277  }
   278  
   279  func (s *baseDeclSuite) TestAutoConnectionSnapdControl(c *C) {
   280  	cand := s.connectCand(c, "snapd-control", "", "")
   281  	_, err := cand.CheckAutoConnect()
   282  	c.Check(err, NotNil)
   283  	c.Assert(err, ErrorMatches, "auto-connection denied by plug rule of interface \"snapd-control\"")
   284  
   285  	plugsSlots := `
   286  plugs:
   287    snapd-control:
   288      allow-auto-connection: true
   289  `
   290  
   291  	lxdDecl := s.mockSnapDecl(c, "some-snap", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   292  	cand.PlugSnapDeclaration = lxdDecl
   293  	arity, err := cand.CheckAutoConnect()
   294  	c.Check(err, IsNil)
   295  	c.Check(arity.SlotsPerPlugAny(), Equals, false)
   296  }
   297  
   298  func (s *baseDeclSuite) TestAutoConnectionContent(c *C) {
   299  	// random snaps cannot connect with content
   300  	// (Sanitize* will now also block this)
   301  	cand := s.connectCand(c, "content", "", "")
   302  	_, err := cand.CheckAutoConnect()
   303  	c.Check(err, NotNil)
   304  
   305  	slotDecl1 := s.mockSnapDecl(c, "slot-snap", "slot-snap-id", "pub1", "")
   306  	plugDecl1 := s.mockSnapDecl(c, "plug-snap", "plug-snap-id", "pub1", "")
   307  	plugDecl2 := s.mockSnapDecl(c, "plug-snap", "plug-snap-id", "pub2", "")
   308  
   309  	// same publisher, same content
   310  	cand = s.connectCand(c, "stuff", `
   311  name: slot-snap
   312  version: 0
   313  slots:
   314    stuff:
   315      interface: content
   316      content: mk1
   317  `, `
   318  name: plug-snap
   319  version: 0
   320  plugs:
   321    stuff:
   322      interface: content
   323      content: mk1
   324  `)
   325  	cand.SlotSnapDeclaration = slotDecl1
   326  	cand.PlugSnapDeclaration = plugDecl1
   327  	arity, err := cand.CheckAutoConnect()
   328  	c.Check(err, IsNil)
   329  	c.Check(arity.SlotsPerPlugAny(), Equals, false)
   330  
   331  	// different publisher, same content
   332  	cand.SlotSnapDeclaration = slotDecl1
   333  	cand.PlugSnapDeclaration = plugDecl2
   334  	_, err = cand.CheckAutoConnect()
   335  	c.Check(err, NotNil)
   336  
   337  	// same publisher, different content
   338  	cand = s.connectCand(c, "stuff", `name: slot-snap
   339  version: 0
   340  slots:
   341    stuff:
   342      interface: content
   343      content: mk1
   344  `, `
   345  name: plug-snap
   346  version: 0
   347  plugs:
   348    stuff:
   349      interface: content
   350      content: mk2
   351  `)
   352  	cand.SlotSnapDeclaration = slotDecl1
   353  	cand.PlugSnapDeclaration = plugDecl1
   354  	_, err = cand.CheckAutoConnect()
   355  	c.Check(err, NotNil)
   356  }
   357  
   358  func (s *baseDeclSuite) TestAutoConnectionLxdSupportOverride(c *C) {
   359  	// by default, don't auto-connect
   360  	cand := s.connectCand(c, "lxd-support", "", "")
   361  	_, err := cand.CheckAutoConnect()
   362  	c.Check(err, NotNil)
   363  
   364  	plugsSlots := `
   365  plugs:
   366    lxd-support:
   367      allow-auto-connection: true
   368  `
   369  
   370  	lxdDecl := s.mockSnapDecl(c, "lxd", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   371  	cand.PlugSnapDeclaration = lxdDecl
   372  	_, err = cand.CheckAutoConnect()
   373  	c.Check(err, IsNil)
   374  }
   375  
   376  func (s *baseDeclSuite) TestAutoConnectionLxdSupportOverrideRevoke(c *C) {
   377  	cand := s.connectCand(c, "lxd-support", "", "")
   378  	plugsSlots := `
   379  plugs:
   380    lxd-support:
   381      allow-auto-connection: false
   382  `
   383  
   384  	lxdDecl := s.mockSnapDecl(c, "notlxd", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   385  	cand.PlugSnapDeclaration = lxdDecl
   386  	_, err := cand.CheckAutoConnect()
   387  	c.Check(err, NotNil)
   388  	c.Assert(err, ErrorMatches, "auto-connection not allowed by plug rule of interface \"lxd-support\" for \"notlxd\" snap")
   389  }
   390  
   391  func (s *baseDeclSuite) TestAutoConnectionKernelModuleControlOverride(c *C) {
   392  	cand := s.connectCand(c, "kernel-module-control", "", "")
   393  	_, err := cand.CheckAutoConnect()
   394  	c.Check(err, NotNil)
   395  	c.Assert(err, ErrorMatches, "auto-connection denied by plug rule of interface \"kernel-module-control\"")
   396  
   397  	plugsSlots := `
   398  plugs:
   399    kernel-module-control:
   400      allow-auto-connection: true
   401  `
   402  
   403  	snapDecl := s.mockSnapDecl(c, "some-snap", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   404  	cand.PlugSnapDeclaration = snapDecl
   405  	_, err = cand.CheckAutoConnect()
   406  	c.Check(err, IsNil)
   407  }
   408  
   409  func (s *baseDeclSuite) TestAutoConnectionDockerSupportOverride(c *C) {
   410  	cand := s.connectCand(c, "docker-support", "", "")
   411  	_, err := cand.CheckAutoConnect()
   412  	c.Check(err, NotNil)
   413  	c.Assert(err, ErrorMatches, "auto-connection denied by plug rule of interface \"docker-support\"")
   414  
   415  	plugsSlots := `
   416  plugs:
   417    docker-support:
   418      allow-auto-connection: true
   419  `
   420  
   421  	snapDecl := s.mockSnapDecl(c, "some-snap", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   422  	cand.PlugSnapDeclaration = snapDecl
   423  	_, err = cand.CheckAutoConnect()
   424  	c.Check(err, IsNil)
   425  }
   426  
   427  func (s *baseDeclSuite) TestAutoConnectionClassicSupportOverride(c *C) {
   428  	cand := s.connectCand(c, "classic-support", "", "")
   429  	_, err := cand.CheckAutoConnect()
   430  	c.Check(err, NotNil)
   431  	c.Assert(err, ErrorMatches, "auto-connection denied by plug rule of interface \"classic-support\"")
   432  
   433  	plugsSlots := `
   434  plugs:
   435    classic-support:
   436      allow-auto-connection: true
   437  `
   438  
   439  	snapDecl := s.mockSnapDecl(c, "classic", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   440  	cand.PlugSnapDeclaration = snapDecl
   441  	_, err = cand.CheckAutoConnect()
   442  	c.Check(err, IsNil)
   443  }
   444  
   445  func (s *baseDeclSuite) TestAutoConnectionKubernetesSupportOverride(c *C) {
   446  	cand := s.connectCand(c, "kubernetes-support", "", "")
   447  	_, err := cand.CheckAutoConnect()
   448  	c.Check(err, NotNil)
   449  	c.Assert(err, ErrorMatches, "auto-connection denied by plug rule of interface \"kubernetes-support\"")
   450  
   451  	plugsSlots := `
   452  plugs:
   453    kubernetes-support:
   454      allow-auto-connection: true
   455  `
   456  
   457  	snapDecl := s.mockSnapDecl(c, "some-snap", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   458  	cand.PlugSnapDeclaration = snapDecl
   459  	_, err = cand.CheckAutoConnect()
   460  	c.Check(err, IsNil)
   461  }
   462  
   463  func (s *baseDeclSuite) TestAutoConnectionGreengrassSupportOverride(c *C) {
   464  	cand := s.connectCand(c, "greengrass-support", "", "")
   465  	_, err := cand.CheckAutoConnect()
   466  	c.Check(err, NotNil)
   467  	c.Assert(err, ErrorMatches, "auto-connection denied by plug rule of interface \"greengrass-support\"")
   468  
   469  	plugsSlots := `
   470  plugs:
   471    greengrass-support:
   472      allow-auto-connection: true
   473  `
   474  
   475  	snapDecl := s.mockSnapDecl(c, "some-snap", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   476  	cand.PlugSnapDeclaration = snapDecl
   477  	_, err = cand.CheckAutoConnect()
   478  	c.Check(err, IsNil)
   479  }
   480  
   481  func (s *baseDeclSuite) TestAutoConnectionMultipassSupportOverride(c *C) {
   482  	cand := s.connectCand(c, "multipass-support", "", "")
   483  	_, err := cand.CheckAutoConnect()
   484  	c.Check(err, NotNil)
   485  	c.Assert(err, ErrorMatches, "auto-connection denied by plug rule of interface \"multipass-support\"")
   486  
   487  	plugsSlots := `
   488  plugs:
   489    multipass-support:
   490      allow-auto-connection: true
   491  `
   492  
   493  	snapDecl := s.mockSnapDecl(c, "multipass-snap", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   494  	cand.PlugSnapDeclaration = snapDecl
   495  	_, err = cand.CheckAutoConnect()
   496  	c.Check(err, IsNil)
   497  }
   498  
   499  func (s *baseDeclSuite) TestAutoConnectionBlockDevicesOverride(c *C) {
   500  	cand := s.connectCand(c, "block-devices", "", "")
   501  	_, err := cand.CheckAutoConnect()
   502  	c.Check(err, NotNil)
   503  	c.Assert(err, ErrorMatches, "auto-connection denied by plug rule of interface \"block-devices\"")
   504  
   505  	plugsSlots := `
   506  plugs:
   507    block-devices:
   508      allow-auto-connection: true
   509  `
   510  
   511  	snapDecl := s.mockSnapDecl(c, "some-snap", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   512  	cand.PlugSnapDeclaration = snapDecl
   513  	_, err = cand.CheckAutoConnect()
   514  	c.Check(err, IsNil)
   515  }
   516  
   517  func (s *baseDeclSuite) TestAutoConnectionPackagekitControlOverride(c *C) {
   518  	cand := s.connectCand(c, "packagekit-control", "", "")
   519  	_, err := cand.CheckAutoConnect()
   520  	c.Check(err, NotNil)
   521  	c.Assert(err, ErrorMatches, "auto-connection denied by plug rule of interface \"packagekit-control\"")
   522  
   523  	plugsSlots := `
   524  plugs:
   525    packagekit-control:
   526      allow-auto-connection: true
   527  `
   528  
   529  	snapDecl := s.mockSnapDecl(c, "some-snap", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   530  	cand.PlugSnapDeclaration = snapDecl
   531  	_, err = cand.CheckAutoConnect()
   532  	c.Check(err, IsNil)
   533  }
   534  
   535  func (s *baseDeclSuite) TestAutoConnectionOverrideMultiple(c *C) {
   536  	plugsSlots := `
   537  plugs:
   538    network-bind:
   539      allow-auto-connection: true
   540    network-control:
   541      allow-auto-connection: true
   542    kernel-module-control:
   543      allow-auto-connection: true
   544    system-observe:
   545      allow-auto-connection: true
   546    hardware-observe:
   547      allow-auto-connection: true
   548  `
   549  
   550  	snapDecl := s.mockSnapDecl(c, "some-snap", "J60k4JY0HppjwOjW8dZdYc8obXKxujRu", "canonical", plugsSlots)
   551  
   552  	all := builtin.Interfaces()
   553  	// these are a mixture interfaces that the snap plugs
   554  	plugged := map[string]bool{
   555  		"network-bind":          true,
   556  		"network-control":       true,
   557  		"kernel-module-control": true,
   558  		"system-observe":        true,
   559  		"hardware-observe":      true,
   560  	}
   561  	for _, iface := range all {
   562  		if !plugged[iface.Name()] {
   563  			continue
   564  		}
   565  
   566  		cand := s.connectCand(c, iface.Name(), "", "")
   567  		cand.PlugSnapDeclaration = snapDecl
   568  		arity, err := cand.CheckAutoConnect()
   569  		c.Check(err, IsNil)
   570  		c.Check(arity.SlotsPerPlugAny(), Equals, false)
   571  	}
   572  }
   573  
   574  // describe installation rules for slots succinctly for cross-checking,
   575  // if an interface is not mentioned here a slot of its type can only
   576  // be installed by a core snap (and this was taken care by
   577  // BeforePrepareSlot),
   578  // otherwise the entry for the interface is the list of snap types it
   579  // can be installed by (using the declaration naming);
   580  // ATM a nil entry means even stricter rules that would need be tested
   581  // separately and whose implementation is in flux for now
   582  var (
   583  	unconstrained = []string{"core", "kernel", "gadget", "app"}
   584  
   585  	slotInstallation = map[string][]string{
   586  		// other
   587  		"adb-support":             {"core"},
   588  		"audio-playback":          {"app", "core"},
   589  		"audio-record":            {"app", "core"},
   590  		"autopilot-introspection": {"core"},
   591  		"avahi-control":           {"app", "core"},
   592  		"avahi-observe":           {"app", "core"},
   593  		"bluez":                   {"app", "core"},
   594  		"bool-file":               {"core", "gadget"},
   595  		"browser-support":         {"core"},
   596  		"content":                 {"app", "gadget"},
   597  		"core-support":            {"core"},
   598  		"cups":                    {"app"},
   599  		"cups-control":            {"app", "core"},
   600  		"dbus":                    {"app"},
   601  		"docker-support":          {"core"},
   602  		"dummy":                   {"app"},
   603  		"fwupd":                   {"app", "core"},
   604  		"gpio":                    {"core", "gadget"},
   605  		"gpio-control":            {"core"},
   606  		"greengrass-support":      {"core"},
   607  		"hidraw":                  {"core", "gadget"},
   608  		"i2c":                     {"core", "gadget"},
   609  		"iio":                     {"core", "gadget"},
   610  		"kubernetes-support":      {"core"},
   611  		"location-control":        {"app"},
   612  		"location-observe":        {"app"},
   613  		"lxd-support":             {"core"},
   614  		"maliit":                  {"app"},
   615  		"media-hub":               {"app", "core"},
   616  		"mir":                     {"app"},
   617  		"modem-manager":           {"app", "core"},
   618  		"mpris":                   {"app"},
   619  		"network-manager":         {"app", "core"},
   620  		"network-manager-observe": {"app", "core"},
   621  		"network-status":          {"core"},
   622  		"ofono":                   {"app", "core"},
   623  		"online-accounts-service": {"app"},
   624  		"power-control":           {"core"},
   625  		"ppp":                     {"core"},
   626  		"pulseaudio":              {"app", "core"},
   627  		"raw-volume":              {"core", "gadget"},
   628  		"serial-port":             {"core", "gadget"},
   629  		"spi":                     {"core", "gadget"},
   630  		"storage-framework-service": {"app"},
   631  		"thumbnailer-service":       {"app"},
   632  		"ubuntu-download-manager":   {"app"},
   633  		"udisks2":                   {"app", "core"},
   634  		"uhid":                      {"core"},
   635  		"uio":                       {"core", "gadget"},
   636  		"unity8":                    {"app"},
   637  		"unity8-calendar":           {"app"},
   638  		"unity8-contacts":           {"app"},
   639  		"upower-observe":            {"app", "core"},
   640  		"wayland":                   {"app", "core"},
   641  		"x11":                       {"app", "core"},
   642  		// snowflakes
   643  		"classic-support": nil,
   644  		"docker":          nil,
   645  		"lxd":             nil,
   646  	}
   647  
   648  	restrictedPlugInstallation = map[string][]string{
   649  		"core-support": {"core"},
   650  	}
   651  
   652  	snapTypeMap = map[string]snap.Type{
   653  		"core":   snap.TypeOS,
   654  		"app":    snap.TypeApp,
   655  		"kernel": snap.TypeKernel,
   656  		"gadget": snap.TypeGadget,
   657  	}
   658  )
   659  
   660  func (s *baseDeclSuite) TestSlotInstallation(c *C) {
   661  	all := builtin.Interfaces()
   662  
   663  	for _, iface := range all {
   664  		types, ok := slotInstallation[iface.Name()]
   665  		if !ok { // common ones, only core can install them,
   666  			types = []string{"core"}
   667  		}
   668  
   669  		if types == nil {
   670  			// snowflake needs to be tested specially
   671  			continue
   672  		}
   673  		for name, snapType := range snapTypeMap {
   674  			ok := strutil.ListContains(types, name)
   675  			ic := s.installSlotCand(c, iface.Name(), snapType, ``)
   676  			err := ic.Check()
   677  			comm := Commentf("%s by %s snap", iface.Name(), name)
   678  			if ok {
   679  				c.Check(err, IsNil, comm)
   680  			} else {
   681  				c.Check(err, NotNil, comm)
   682  			}
   683  		}
   684  	}
   685  
   686  	// test docker specially
   687  	ic := s.installSlotCand(c, "docker", snap.TypeApp, ``)
   688  	err := ic.Check()
   689  	c.Assert(err, Not(IsNil))
   690  	c.Assert(err, ErrorMatches, "installation not allowed by \"docker\" slot rule of interface \"docker\"")
   691  
   692  	// test lxd specially
   693  	ic = s.installSlotCand(c, "lxd", snap.TypeApp, ``)
   694  	err = ic.Check()
   695  	c.Assert(err, Not(IsNil))
   696  	c.Assert(err, ErrorMatches, "installation not allowed by \"lxd\" slot rule of interface \"lxd\"")
   697  }
   698  
   699  func (s *baseDeclSuite) TestPlugInstallation(c *C) {
   700  	all := builtin.Interfaces()
   701  
   702  	restricted := map[string]bool{
   703  		"block-devices":         true,
   704  		"classic-support":       true,
   705  		"docker-support":        true,
   706  		"greengrass-support":    true,
   707  		"gpio-control":          true,
   708  		"kernel-module-control": true,
   709  		"kubernetes-support":    true,
   710  		"lxd-support":           true,
   711  		"multipass-support":     true,
   712  		"packagekit-control":    true,
   713  		"personal-files":        true,
   714  		"snapd-control":         true,
   715  		"system-files":          true,
   716  		"uinput":                true,
   717  		"unity8":                true,
   718  	}
   719  
   720  	for _, iface := range all {
   721  		types, ok := restrictedPlugInstallation[iface.Name()]
   722  		// If plug installation is restricted to specific snap types we
   723  		// need to make sure this is really the case here. If that is not
   724  		// the case we continue as normal.
   725  		if ok {
   726  			for name, snapType := range snapTypeMap {
   727  				ok := strutil.ListContains(types, name)
   728  				ic := s.installPlugCand(c, iface.Name(), snapType, ``)
   729  				err := ic.Check()
   730  				comm := Commentf("%s by %s snap", iface.Name(), name)
   731  				if ok {
   732  					c.Check(err, IsNil, comm)
   733  				} else {
   734  					c.Check(err, NotNil, comm)
   735  				}
   736  			}
   737  		} else {
   738  			ic := s.installPlugCand(c, iface.Name(), snap.TypeApp, ``)
   739  			err := ic.Check()
   740  			comm := Commentf("%s", iface.Name())
   741  			if restricted[iface.Name()] {
   742  				c.Check(err, NotNil, comm)
   743  			} else {
   744  				c.Check(err, IsNil, comm)
   745  			}
   746  		}
   747  	}
   748  }
   749  
   750  func (s *baseDeclSuite) TestConnection(c *C) {
   751  	all := builtin.Interfaces()
   752  
   753  	// connecting with these interfaces needs to be allowed on
   754  	// case-by-case basis
   755  	noconnect := map[string]bool{
   756  		"content":          true,
   757  		"cups":             true,
   758  		"docker":           true,
   759  		"fwupd":            true,
   760  		"location-control": true,
   761  		"location-observe": true,
   762  		"lxd":              true,
   763  		"maliit":           true,
   764  		"mir":              true,
   765  		"online-accounts-service":   true,
   766  		"raw-volume":                true,
   767  		"storage-framework-service": true,
   768  		"thumbnailer-service":       true,
   769  		"ubuntu-download-manager":   true,
   770  		"unity8-calendar":           true,
   771  		"unity8-contacts":           true,
   772  	}
   773  
   774  	for _, iface := range all {
   775  		expected := !noconnect[iface.Name()]
   776  		comm := Commentf(iface.Name())
   777  
   778  		// check base declaration
   779  		cand := s.connectCand(c, iface.Name(), "", "")
   780  		err := cand.Check()
   781  
   782  		if expected {
   783  			c.Check(err, IsNil, comm)
   784  		} else {
   785  			c.Check(err, NotNil, comm)
   786  		}
   787  	}
   788  }
   789  
   790  func (s *baseDeclSuite) TestConnectionOnClassic(c *C) {
   791  	restore := release.MockOnClassic(false)
   792  	defer restore()
   793  
   794  	all := builtin.Interfaces()
   795  
   796  	// connecting with these interfaces needs to be allowed on
   797  	// case-by-case basis when not on classic
   798  	noconnect := map[string]bool{
   799  		"audio-record":    true,
   800  		"modem-manager":   true,
   801  		"network-manager": true,
   802  		"ofono":           true,
   803  		"pulseaudio":      true,
   804  		"upower-observe":  true,
   805  	}
   806  
   807  	for _, onClassic := range []bool{true, false} {
   808  		release.OnClassic = onClassic
   809  		for _, iface := range all {
   810  			if !noconnect[iface.Name()] {
   811  				continue
   812  			}
   813  			expected := onClassic
   814  			comm := Commentf(iface.Name())
   815  
   816  			// check base declaration
   817  			cand := s.connectCand(c, iface.Name(), "", "")
   818  			err := cand.Check()
   819  
   820  			if expected {
   821  				c.Check(err, IsNil, comm)
   822  			} else {
   823  				c.Check(err, NotNil, comm)
   824  			}
   825  		}
   826  	}
   827  }
   828  
   829  func (s *baseDeclSuite) TestConnectionImplicitOnClassicOrAppSnap(c *C) {
   830  	restore := release.MockOnClassic(false)
   831  	defer restore()
   832  
   833  	all := builtin.Interfaces()
   834  
   835  	// These interfaces represent when the interface might be implicit on
   836  	// classic or when the interface is provided via an app snap. As such,
   837  	// they all share the following:
   838  	//
   839  	// - implicitOnCore: false
   840  	// - implicitOnClassis: true
   841  	// - base declaration uses:
   842  	//     allow-installation:
   843  	//       slot-snap-type:
   844  	//         - app
   845  	//         - core
   846  	//     deny-connection:
   847  	//       on-classic: false
   848  	//     deny-auto-connection: true|false|unspecified
   849  	//
   850  	// connecting with these interfaces needs to be allowed on
   851  	// case-by-case basis when not on classic
   852  	ifaces := map[string]bool{
   853  		"audio-playback":  true,
   854  		"audio-record":    true,
   855  		"cups-control":    true,
   856  		"modem-manager":   true,
   857  		"network-manager": true,
   858  		"ofono":           true,
   859  		"pulseaudio":      true,
   860  		"upower-observe":  true,
   861  	}
   862  
   863  	for _, iface := range all {
   864  		if !ifaces[iface.Name()] {
   865  			continue
   866  		}
   867  		comm := Commentf(iface.Name())
   868  
   869  		// verify the interface is setup as expected wrt
   870  		// implicitOnCore, implicitOnClassic, no plugs and has
   871  		// expected slots (ignoring AutoConnection)
   872  		si := interfaces.StaticInfoOf(iface)
   873  		c.Assert(si.ImplicitOnCore, Equals, false)
   874  		c.Assert(si.ImplicitOnClassic, Equals, true)
   875  
   876  		c.Assert(s.baseDecl.PlugRule(iface.Name()), IsNil)
   877  
   878  		sr := s.baseDecl.SlotRule(iface.Name())
   879  		c.Assert(sr, Not(IsNil))
   880  		c.Assert(sr.AllowInstallation, HasLen, 1)
   881  		c.Check(sr.AllowInstallation[0].SlotSnapTypes, DeepEquals, []string{"app", "core"}, comm)
   882  		c.Assert(sr.DenyConnection, HasLen, 1)
   883  		c.Check(sr.DenyConnection[0].OnClassic, DeepEquals, &asserts.OnClassicConstraint{Classic: false}, comm)
   884  
   885  		for _, onClassic := range []bool{true, false} {
   886  			release.OnClassic = onClassic
   887  
   888  			for _, implicit := range []bool{true, false} {
   889  				// When implicitOnCore is false, there is
   890  				// nothing to test on Core
   891  				if implicit && !onClassic {
   892  					continue
   893  				}
   894  
   895  				snapType := "app"
   896  				if implicit {
   897  					snapType = "os"
   898  				}
   899  				slotYaml := fmt.Sprintf(`name: slot-snap
   900  version: 0
   901  type: %s
   902  slots:
   903    %s:
   904  `, snapType, iface.Name())
   905  
   906  				// XXX: eventually 'onClassic && !implicit' but
   907  				// the current declaration allows connection on
   908  				// Core when 'type: app'. See:
   909  				// https://github.com/snapcore/snapd/pull/8920/files#r471678529
   910  				expected := onClassic
   911  
   912  				// check base declaration
   913  				cand := s.connectCand(c, iface.Name(), slotYaml, "")
   914  				err := cand.Check()
   915  
   916  				if expected {
   917  					c.Check(err, IsNil, comm)
   918  				} else {
   919  					c.Check(err, NotNil, comm)
   920  				}
   921  			}
   922  		}
   923  	}
   924  }
   925  
   926  func (s *baseDeclSuite) TestSanity(c *C) {
   927  	all := builtin.Interfaces()
   928  
   929  	// these interfaces have rules both for the slots and plugs side
   930  	// given how the rules work this can be delicate,
   931  	// listed here to make sure that was a conscious decision
   932  	bothSides := map[string]bool{
   933  		"block-devices":         true,
   934  		"audio-playback":        true,
   935  		"classic-support":       true,
   936  		"core-support":          true,
   937  		"docker-support":        true,
   938  		"greengrass-support":    true,
   939  		"gpio-control":          true,
   940  		"kernel-module-control": true,
   941  		"kubernetes-support":    true,
   942  		"lxd-support":           true,
   943  		"multipass-support":     true,
   944  		"packagekit-control":    true,
   945  		"personal-files":        true,
   946  		"snapd-control":         true,
   947  		"system-files":          true,
   948  		"udisks2":               true,
   949  		"uinput":                true,
   950  		"unity8":                true,
   951  		"wayland":               true,
   952  	}
   953  
   954  	for _, iface := range all {
   955  		plugRule := s.baseDecl.PlugRule(iface.Name())
   956  		slotRule := s.baseDecl.SlotRule(iface.Name())
   957  		if plugRule == nil && slotRule == nil {
   958  			c.Logf("%s is not considered in the base declaration", iface.Name())
   959  			c.Fail()
   960  		}
   961  		if plugRule != nil && slotRule != nil {
   962  			if !bothSides[iface.Name()] {
   963  				c.Logf("%s have both a base declaration slot rule and plug rule, make sure that's intended and correct", iface.Name())
   964  				c.Fail()
   965  			}
   966  		}
   967  	}
   968  }
   969  
   970  func (s *baseDeclSuite) TestConnectionContent(c *C) {
   971  	// we let connect explicitly as long as content matches (or is absent on both sides)
   972  
   973  	// random (Sanitize* will now also block this)
   974  	cand := s.connectCand(c, "content", "", "")
   975  	err := cand.Check()
   976  	c.Check(err, NotNil)
   977  
   978  	slotDecl1 := s.mockSnapDecl(c, "slot-snap", "slot-snap-id", "pub1", "")
   979  	plugDecl1 := s.mockSnapDecl(c, "plug-snap", "plug-snap-id", "pub1", "")
   980  	plugDecl2 := s.mockSnapDecl(c, "plug-snap", "plug-snap-id", "pub2", "")
   981  
   982  	// same publisher, same content
   983  	cand = s.connectCand(c, "stuff", `name: slot-snap
   984  version: 0
   985  slots:
   986    stuff:
   987      interface: content
   988      content: mk1
   989  `, `
   990  name: plug-snap
   991  version: 0
   992  plugs:
   993    stuff:
   994      interface: content
   995      content: mk1
   996  `)
   997  	cand.SlotSnapDeclaration = slotDecl1
   998  	cand.PlugSnapDeclaration = plugDecl1
   999  	err = cand.Check()
  1000  	c.Check(err, IsNil)
  1001  
  1002  	// different publisher, same content
  1003  	cand.SlotSnapDeclaration = slotDecl1
  1004  	cand.PlugSnapDeclaration = plugDecl2
  1005  	err = cand.Check()
  1006  	c.Check(err, IsNil)
  1007  
  1008  	// same publisher, different content
  1009  	cand = s.connectCand(c, "stuff", `
  1010  name: slot-snap
  1011  version: 0
  1012  slots:
  1013    stuff:
  1014      interface: content
  1015      content: mk1
  1016  `, `
  1017  name: plug-snap
  1018  version: 0
  1019  plugs:
  1020    stuff:
  1021      interface: content
  1022      content: mk2
  1023  `)
  1024  	cand.SlotSnapDeclaration = slotDecl1
  1025  	cand.PlugSnapDeclaration = plugDecl1
  1026  	err = cand.Check()
  1027  	c.Check(err, NotNil)
  1028  }
  1029  
  1030  func (s *baseDeclSuite) TestComposeBaseDeclaration(c *C) {
  1031  	decl, err := policy.ComposeBaseDeclaration(nil)
  1032  	c.Assert(err, IsNil)
  1033  	c.Assert(string(decl), testutil.Contains, `
  1034  type: base-declaration
  1035  authority-id: canonical
  1036  series: 16
  1037  revision: 0
  1038  `)
  1039  }
  1040  
  1041  func (s *baseDeclSuite) TestDoesNotPanic(c *C) {
  1042  	// In case there are any issues in the actual interfaces we'd get a panic
  1043  	// on snapd startup. This test prevents this from happing unnoticed.
  1044  	_, err := policy.ComposeBaseDeclaration(builtin.Interfaces())
  1045  	c.Assert(err, IsNil)
  1046  }
  1047  
  1048  func (s *baseDeclSuite) TestBrowserSupportAllowSandbox(c *C) {
  1049  	const plugYaml = `name: plug-snap
  1050  version: 0
  1051  plugs:
  1052    browser-support:
  1053     allow-sandbox: true
  1054  `
  1055  	cand := s.connectCand(c, "browser-support", "", plugYaml)
  1056  	err := cand.Check()
  1057  	c.Check(err, NotNil)
  1058  
  1059  	_, err = cand.CheckAutoConnect()
  1060  	c.Check(err, NotNil)
  1061  }
  1062  
  1063  func (s *baseDeclSuite) TestOpticalDriveWrite(c *C) {
  1064  	type options struct {
  1065  		readonlyYamls []string
  1066  		writableYamls []string
  1067  	}
  1068  
  1069  	opts := &options{
  1070  		readonlyYamls: []string{
  1071  			// Non-specified "write" attribute
  1072  			`name: plug-snap
  1073  version: 0
  1074  plugs:
  1075    optical-drive: null
  1076  `,
  1077  			// Undefined "write" attribute
  1078  			`name: plug-snap
  1079  version: 0
  1080  plugs:
  1081    optical-drive: {}
  1082  `,
  1083  			// False "write" attribute
  1084  			`name: plug-snap
  1085  version: 0
  1086  plugs:
  1087    optical-drive:
  1088      write: false
  1089  `,
  1090  		},
  1091  		writableYamls: []string{
  1092  			// True "write" attribute
  1093  			`name: plug-snap
  1094  version: 0
  1095  plugs:
  1096    optical-drive:
  1097      write: true
  1098  `,
  1099  		},
  1100  	}
  1101  
  1102  	checkOpticalDriveAutoConnect := func(plugYaml string, checker Checker) {
  1103  		cand := s.connectCand(c, "optical-drive", "", plugYaml)
  1104  		err := cand.Check()
  1105  		c.Check(err, checker)
  1106  		_, err = cand.CheckAutoConnect()
  1107  		c.Check(err, checker)
  1108  	}
  1109  
  1110  	for _, plugYaml := range opts.readonlyYamls {
  1111  		checkOpticalDriveAutoConnect(plugYaml, IsNil)
  1112  	}
  1113  	for _, plugYaml := range opts.writableYamls {
  1114  		checkOpticalDriveAutoConnect(plugYaml, NotNil)
  1115  	}
  1116  }
  1117  
  1118  func (s *baseDeclSuite) TestRawVolumeOverride(c *C) {
  1119  	slotYaml := `name: slot-snap
  1120  type: gadget
  1121  version: 0
  1122  slots:
  1123    raw-volume:
  1124      path: /dev/mmcblk0p1
  1125  `
  1126  	slotSnap := snaptest.MockInfo(c, slotYaml, nil)
  1127  	// mock a well-formed slot snap decl with SnapID
  1128  	slotSnapDecl := s.mockSnapDecl(c, "slot-snap", "slotsnapidididididididididididid", "canonical", "")
  1129  
  1130  	plugYaml := `name: plug-snap
  1131  version: 0
  1132  plugs:
  1133    raw-volume:
  1134  `
  1135  	plugSnap := snaptest.MockInfo(c, plugYaml, nil)
  1136  
  1137  	// no plug-side declaration
  1138  	cand := &policy.ConnectCandidate{
  1139  		Plug:                interfaces.NewConnectedPlug(plugSnap.Plugs["raw-volume"], nil, nil),
  1140  		Slot:                interfaces.NewConnectedSlot(slotSnap.Slots["raw-volume"], nil, nil),
  1141  		SlotSnapDeclaration: slotSnapDecl,
  1142  		BaseDeclaration:     s.baseDecl,
  1143  	}
  1144  
  1145  	err := cand.Check()
  1146  	c.Check(err, NotNil)
  1147  	c.Assert(err, ErrorMatches, "connection denied by slot rule of interface \"raw-volume\"")
  1148  	_, err = cand.CheckAutoConnect()
  1149  	c.Check(err, NotNil)
  1150  	c.Assert(err, ErrorMatches, "auto-connection denied by slot rule of interface \"raw-volume\"")
  1151  
  1152  	// specific plug-side declaration for connection only
  1153  	plugsOverride := `
  1154  plugs:
  1155    raw-volume:
  1156      allow-connection:
  1157        slot-snap-id:
  1158          - slotsnapidididididididididididid
  1159      allow-auto-connection: false
  1160  `
  1161  	plugSnapDecl := s.mockSnapDecl(c, "plug-snap", "plugsnapidididididididididididid", "canonical", plugsOverride)
  1162  	cand.PlugSnapDeclaration = plugSnapDecl
  1163  	err = cand.Check()
  1164  	c.Check(err, IsNil)
  1165  	_, err = cand.CheckAutoConnect()
  1166  	c.Check(err, NotNil)
  1167  	c.Assert(err, ErrorMatches, "auto-connection not allowed by plug rule of interface \"raw-volume\" for \"plug-snap\" snap")
  1168  
  1169  	// specific plug-side declaration for connection and auto-connection
  1170  	plugsOverride = `
  1171  plugs:
  1172    raw-volume:
  1173      allow-connection:
  1174        slot-snap-id:
  1175          - slotsnapidididididididididididid
  1176      allow-auto-connection:
  1177        slot-snap-id:
  1178          - slotsnapidididididididididididid
  1179  `
  1180  	plugSnapDecl = s.mockSnapDecl(c, "plug-snap", "plugsnapidididididididididididid", "canonical", plugsOverride)
  1181  	cand.PlugSnapDeclaration = plugSnapDecl
  1182  	err = cand.Check()
  1183  	c.Check(err, IsNil)
  1184  	arity, err := cand.CheckAutoConnect()
  1185  	c.Check(err, IsNil)
  1186  	c.Check(arity.SlotsPerPlugAny(), Equals, false)
  1187  
  1188  	// blanket allow for connection and auto-connection to any slotting snap
  1189  	plugsOverride = `
  1190  plugs:
  1191    raw-volume:
  1192      allow-connection: true
  1193      allow-auto-connection: true
  1194  `
  1195  	plugSnapDecl = s.mockSnapDecl(c, "some-snap", "plugsnapidididididididididididid", "canonical", plugsOverride)
  1196  	cand.PlugSnapDeclaration = plugSnapDecl
  1197  	err = cand.Check()
  1198  	c.Check(err, IsNil)
  1199  	arity, err = cand.CheckAutoConnect()
  1200  	c.Check(err, IsNil)
  1201  	c.Check(arity.SlotsPerPlugAny(), Equals, false)
  1202  }