File: backend_test.go

package info (click to toggle)
snapd 2.49-1%2Bdeb11u2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 36,432 kB
  • sloc: ansic: 12,125; sh: 8,453; python: 2,163; makefile: 1,284; exp: 173; xml: 22
file content (2281 lines) | stat: -rw-r--r-- 86,839 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2016-2020 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package apparmor_test

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/user"
	"path/filepath"
	"regexp"
	"strings"

	. "gopkg.in/check.v1"

	"github.com/snapcore/snapd/dirs"
	"github.com/snapcore/snapd/interfaces"
	"github.com/snapcore/snapd/interfaces/apparmor"
	"github.com/snapcore/snapd/interfaces/ifacetest"
	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/osutil"
	"github.com/snapcore/snapd/overlord/state"
	"github.com/snapcore/snapd/release"
	apparmor_sandbox "github.com/snapcore/snapd/sandbox/apparmor"
	"github.com/snapcore/snapd/snap"
	"github.com/snapcore/snapd/snap/snaptest"
	"github.com/snapcore/snapd/testutil"
	"github.com/snapcore/snapd/timings"
)

type backendSuite struct {
	ifacetest.BackendSuite

	parserCmd *testutil.MockCmd

	perf *timings.Timings
	meas *timings.Span
}

var _ = Suite(&backendSuite{})

var testedConfinementOpts = []interfaces.ConfinementOptions{
	{},
	{DevMode: true},
	{JailMode: true},
	{Classic: true},
}

// fakeAppAprmorParser contains shell program that creates fake binary cache entries
// in accordance with what real apparmor_parser would do.
const fakeAppArmorParser = `
cache_dir=""
profile=""
write=""
while [ -n "$1" ]; do
	case "$1" in
		--cache-loc=*)
			cache_dir="$(echo "$1" | cut -d = -f 2)" || exit 1
			;;
		--write-cache)
			write=yes
			;;
		--quiet|--replace|--remove)
			# Ignore
			;;
		-O)
			# Ignore, discard argument
			shift
			;;
		*)
			profile=$(basename "$1")
			;;
	esac
	shift
done
if [ "$write" = yes ]; then
	echo fake > "$cache_dir/$profile"
fi
`

// permanently broken apparmor parser
const fakeBrokenAppArmorParser = `
echo "permanent failure"
exit 1
`

// apparmor parser that fails when processing more than 3 profiles, i.e.
// when reloading profiles in a batch, but succeeds when run for individual
// runs for snaps with less profiles.
const fakeFailingAppArmorParser = `
profiles="0"
while [ -n "$1" ]; do
	case "$1" in
		--cache-loc=*)
			;;
		--write-cache|--quiet|--replace|--remove|-j*)
			;;
		-O)
			# Ignore, discard argument
			shift
			;;
		*)
			profiles=$(( profiles + 1 ))
			;;
	esac
	shift
done
if [ "$profiles" -gt 3 ]; then
	echo "batch failure ($profiles profiles)"
	exit 1
fi
`

// apparmor parser that fails on snap.samba.smbd profile
const fakeFailingAppArmorParserOneProfile = `
profile=""
while [ -n "$1" ]; do
	case "$1" in
		--cache-loc=*)
			# Ignore
			;;
		--quiet|--replace|--remove|--write-cache|-j*)
			# Ignore
			;;
		-O)
			# Ignore, discard argument
			shift
			;;
		*)
			profile=$(basename "$1")
			if [ "$profile" = "snap.samba.smbd" ]; then
				echo "failure: $profile"
				exit 1
			fi
			;;
	esac
	shift
done
`

func (s *backendSuite) SetUpTest(c *C) {
	s.Backend = &apparmor.Backend{}
	s.BackendSuite.SetUpTest(c)
	c.Assert(s.Repo.AddBackend(s.Backend), IsNil)

	s.perf = timings.New(nil)
	s.meas = s.perf.StartSpan("", "")

	err := os.MkdirAll(apparmor_sandbox.CacheDir, 0700)
	c.Assert(err, IsNil)
	// Mock away any real apparmor interaction
	s.parserCmd = testutil.MockCommand(c, "apparmor_parser", fakeAppArmorParser)

	apparmor.MockRuntimeNumCPU(func() int { return 99 })

	err = s.Backend.Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, IsNil)
}

func (s *backendSuite) TearDownTest(c *C) {
	s.parserCmd.Restore()

	s.BackendSuite.TearDownTest(c)
}

// Tests for Setup() and Remove()

func (s *backendSuite) TestName(c *C) {
	c.Check(s.Backend.Name(), Equals, interfaces.SecurityAppArmor)
}

func (s *backendSuite) TestInstallingSnapWritesAndLoadsProfiles(c *C) {
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", ifacetest.SambaYamlV1, 1)
	updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
	profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
	// file called "snap.sambda.smbd" was created
	_, err := os.Stat(profile)
	c.Check(err, IsNil)
	// apparmor_parser was used to load that file
	c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
		{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--skip-read-cache", "--quiet", updateNSProfile, profile},
	})
}

func (s *backendSuite) TestInstallingSnapWithHookWritesAndLoadsProfiles(c *C) {
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", ifacetest.HookYaml, 1)
	profile := filepath.Join(dirs.SnapAppArmorDir, "snap.foo.hook.configure")
	updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.foo")

	// Verify that profile "snap.foo.hook.configure" was created
	_, err := os.Stat(profile)
	c.Check(err, IsNil)
	// apparmor_parser was used to load that file
	c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
		{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--skip-read-cache", "--quiet", updateNSProfile, profile},
	})
}

const layoutYaml = `name: myapp
version: 1
apps:
  myapp:
    command: myapp
layout:
  /usr/share/myapp:
    bind: $SNAP/usr/share/myapp
`

func (s *backendSuite) TestInstallingSnapWithLayoutWritesAndLoadsProfiles(c *C) {
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", layoutYaml, 1)
	appProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.myapp.myapp")
	updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.myapp")
	// both profiles were created
	_, err := os.Stat(appProfile)
	c.Check(err, IsNil)
	_, err = os.Stat(updateNSProfile)
	c.Check(err, IsNil)
	// TODO: check for layout snippets inside the generated file once we have some snippets to check for.
	// apparmor_parser was used to load them
	c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
		{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--skip-read-cache", "--quiet", updateNSProfile, appProfile},
	})
}

const gadgetYaml = `name: mydevice
type: gadget
version: 1
`

func (s *backendSuite) TestInstallingSnapWithoutAppsOrHooksDoesntAddProfiles(c *C) {
	// Installing a snap that doesn't have either hooks or apps doesn't generate
	// any apparmor profiles because there is no executable content that would need
	// an execution environment and the corresponding mount namespace.
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", gadgetYaml, 1)
	c.Check(s.parserCmd.Calls(), HasLen, 0)
}

func (s *backendSuite) TestTimings(c *C) {
	oldDurationThreshold := timings.DurationThreshold
	defer func() {
		timings.DurationThreshold = oldDurationThreshold
	}()
	timings.DurationThreshold = 0

	for _, opts := range testedConfinementOpts {
		perf := timings.New(nil)
		meas := perf.StartSpan("", "")

		snapInfo := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		c.Assert(s.Backend.Setup(snapInfo, opts, s.Repo, meas), IsNil)

		st := state.New(nil)
		st.Lock()
		defer st.Unlock()
		perf.Save(st)

		var allTimings []map[string]interface{}
		c.Assert(st.Get("timings", &allTimings), IsNil)
		c.Assert(allTimings, HasLen, 1)

		timings, ok := allTimings[0]["timings"]
		c.Assert(ok, Equals, true)

		c.Assert(timings, HasLen, 2)
		timingsList, ok := timings.([]interface{})
		c.Assert(ok, Equals, true)
		tm := timingsList[0].(map[string]interface{})
		c.Check(tm["label"], Equals, "load-profiles[changed]")

		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestProfilesAreAlwaysLoaded(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		s.parserCmd.ForgetCalls()
		err := s.Backend.Setup(snapInfo, opts, s.Repo, s.meas)
		c.Assert(err, IsNil)
		updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--quiet", updateNSProfile, profile},
		})
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestRemovingSnapRemovesAndUnloadsProfiles(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		s.parserCmd.ForgetCalls()
		s.RemoveSnap(c, snapInfo)
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		// file called "snap.sambda.smbd" was removed
		_, err := os.Stat(profile)
		c.Check(os.IsNotExist(err), Equals, true)
		// apparmor cache file was removed
		cache := filepath.Join(apparmor_sandbox.CacheDir, "snap.samba.smbd")
		_, err = os.Stat(cache)
		c.Check(os.IsNotExist(err), Equals, true)
	}
}

func (s *backendSuite) TestRemovingSnapWithHookRemovesAndUnloadsProfiles(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo := s.InstallSnap(c, opts, "", ifacetest.HookYaml, 1)
		s.parserCmd.ForgetCalls()
		s.RemoveSnap(c, snapInfo)
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.foo.hook.configure")
		// file called "snap.foo.hook.configure" was removed
		_, err := os.Stat(profile)
		c.Check(os.IsNotExist(err), Equals, true)
		// apparmor cache file was removed
		cache := filepath.Join(apparmor_sandbox.CacheDir, "snap.foo.hook.configure")
		_, err = os.Stat(cache)
		c.Check(os.IsNotExist(err), Equals, true)
	}
}

func (s *backendSuite) TestUpdatingSnapMakesNeccesaryChanges(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		s.parserCmd.ForgetCalls()
		snapInfo = s.UpdateSnap(c, snapInfo, opts, ifacetest.SambaYamlV1, 2)
		updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		// apparmor_parser was used to reload the profile because snap revision
		// is inside the generated policy.
		c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--skip-read-cache", "--quiet", profile},
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--quiet", updateNSProfile},
		})
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestUpdatingSnapToOneWithMoreApps(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		s.parserCmd.ForgetCalls()
		// NOTE: the revision is kept the same to just test on the new application being added
		snapInfo = s.UpdateSnap(c, snapInfo, opts, ifacetest.SambaYamlV1WithNmbd, 1)
		updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		smbdProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		nmbdProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.nmbd")
		// file called "snap.sambda.nmbd" was created
		_, err := os.Stat(nmbdProfile)
		c.Check(err, IsNil)
		// apparmor_parser was used to load all the profiles, the nmbd profile is new so we force invalidate its cache (if any).
		c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--skip-read-cache", "--quiet", nmbdProfile},
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--quiet", updateNSProfile, smbdProfile},
		})
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestUpdatingSnapToOneWithMoreHooks(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1WithNmbd, 1)
		s.parserCmd.ForgetCalls()
		// NOTE: the revision is kept the same to just test on the new application being added
		snapInfo = s.UpdateSnap(c, snapInfo, opts, ifacetest.SambaYamlWithHook, 1)
		updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		smbdProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		nmbdProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.nmbd")
		hookProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.hook.configure")

		// Verify that profile "snap.samba.hook.configure" was created
		_, err := os.Stat(hookProfile)
		c.Check(err, IsNil)
		// apparmor_parser was used to load all the profiles, the hook profile has changed so we force invalidate its cache.
		c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--skip-read-cache", "--quiet", hookProfile},
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--quiet", updateNSProfile, nmbdProfile, smbdProfile},
		})
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestUpdatingSnapToOneWithFewerApps(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1WithNmbd, 1)
		s.parserCmd.ForgetCalls()
		// NOTE: the revision is kept the same to just test on the application being removed
		snapInfo = s.UpdateSnap(c, snapInfo, opts, ifacetest.SambaYamlV1, 1)
		updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		smbdProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		nmbdProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.nmbd")
		// file called "snap.sambda.nmbd" was removed
		_, err := os.Stat(nmbdProfile)
		c.Check(os.IsNotExist(err), Equals, true)
		// apparmor_parser was used to remove the unused profile
		c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--quiet", updateNSProfile, smbdProfile},
		})
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestUpdatingSnapToOneWithFewerHooks(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo := s.InstallSnap(c, opts, "", ifacetest.SambaYamlWithHook, 1)
		s.parserCmd.ForgetCalls()
		// NOTE: the revision is kept the same to just test on the application being removed
		snapInfo = s.UpdateSnap(c, snapInfo, opts, ifacetest.SambaYamlV1WithNmbd, 1)
		updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		smbdProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		nmbdProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.nmbd")
		hookProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.hook.configure")

		// Verify profile "snap.samba.hook.configure" was removed
		_, err := os.Stat(hookProfile)
		c.Check(os.IsNotExist(err), Equals, true)
		// apparmor_parser was used to remove the unused profile
		c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--quiet", updateNSProfile, nmbdProfile, smbdProfile},
		})
		s.RemoveSnap(c, snapInfo)
	}
}

// SetupMany tests

func (s *backendSuite) TestSetupManyProfilesAreAlwaysLoaded(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo1 := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		snapInfo2 := s.InstallSnap(c, opts, "", ifacetest.SomeSnapYamlV1, 1)
		s.parserCmd.ForgetCalls()
		setupManyInterface, ok := s.Backend.(interfaces.SecurityBackendSetupMany)
		c.Assert(ok, Equals, true)
		err := setupManyInterface.SetupMany([]*snap.Info{snapInfo1, snapInfo2}, func(snapName string) interfaces.ConfinementOptions { return opts }, s.Repo, s.meas)
		c.Assert(err, IsNil)
		snap1nsProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		snap1AAprofile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		snap2nsProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.some-snap")
		snap2AAprofile := filepath.Join(dirs.SnapAppArmorDir, "snap.some-snap.someapp")
		c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "-j97", "--quiet", snap1nsProfile, snap1AAprofile, snap2nsProfile, snap2AAprofile},
		})
		s.RemoveSnap(c, snapInfo1)
		s.RemoveSnap(c, snapInfo2)
	}
}

func (s *backendSuite) TestSetupManyProfilesWithChanged(c *C) {
	for _, opts := range testedConfinementOpts {
		snapInfo1 := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		snapInfo2 := s.InstallSnap(c, opts, "", ifacetest.SomeSnapYamlV1, 1)
		s.parserCmd.ForgetCalls()

		snap1nsProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		snap1AAprofile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		snap2nsProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.some-snap")
		snap2AAprofile := filepath.Join(dirs.SnapAppArmorDir, "snap.some-snap.someapp")

		// simulate outdated profiles by changing their data on the disk
		c.Assert(ioutil.WriteFile(snap1AAprofile, []byte("# an outdated profile"), 0644), IsNil)
		c.Assert(ioutil.WriteFile(snap2AAprofile, []byte("# an outdated profile"), 0644), IsNil)

		setupManyInterface, ok := s.Backend.(interfaces.SecurityBackendSetupMany)
		c.Assert(ok, Equals, true)
		err := setupManyInterface.SetupMany([]*snap.Info{snapInfo1, snapInfo2}, func(snapName string) interfaces.ConfinementOptions { return opts }, s.Repo, s.meas)
		c.Assert(err, IsNil)

		// expect two batch executions - one for changed profiles, second for unchanged profiles.
		c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "-j97", "--skip-read-cache", "--quiet", snap1AAprofile, snap2AAprofile},
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "-j97", "--quiet", snap1nsProfile, snap2nsProfile},
		})
		s.RemoveSnap(c, snapInfo1)
		s.RemoveSnap(c, snapInfo2)
	}
}

// helper for checking for apparmor parser calls where batch run is expected to fail and is followed by two separate runs for individual snaps.
func (s *backendSuite) checkSetupManyCallsWithFallback(c *C, cmd *testutil.MockCmd) {
	snap1nsProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
	snap1AAprofile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
	snap2nsProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.some-snap")
	snap2AAprofile := filepath.Join(dirs.SnapAppArmorDir, "snap.some-snap.someapp")

	// We expect three calls to apparmor_parser due to the failure of batch run. First is the failed batch run, followed by succesfull fallback runs.
	c.Check(cmd.Calls(), DeepEquals, [][]string{
		{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "-j97", "--quiet", snap1nsProfile, snap1AAprofile, snap2nsProfile, snap2AAprofile},
		{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--quiet", snap1nsProfile, snap1AAprofile},
		{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--quiet", snap2nsProfile, snap2AAprofile},
	})
}

func (s *backendSuite) TestSetupManyApparmorBatchProcessingPermanentError(c *C) {
	log, restore := logger.MockLogger()
	defer restore()

	for _, opts := range testedConfinementOpts {
		log.Reset()

		// note, InstallSnap here uses s.parserCmd which mocks happy apparmor_parser
		snapInfo1 := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		snapInfo2 := s.InstallSnap(c, opts, "", ifacetest.SomeSnapYamlV1, 1)
		s.parserCmd.ForgetCalls()
		setupManyInterface, ok := s.Backend.(interfaces.SecurityBackendSetupMany)
		c.Assert(ok, Equals, true)

		// mock apparmor_parser again with a failing one (and restore immediately for the next iteration of the test)
		failingParserCmd := testutil.MockCommand(c, "apparmor_parser", fakeBrokenAppArmorParser)
		errs := setupManyInterface.SetupMany([]*snap.Info{snapInfo1, snapInfo2}, func(snapName string) interfaces.ConfinementOptions { return opts }, s.Repo, s.meas)
		failingParserCmd.Restore()

		s.checkSetupManyCallsWithFallback(c, failingParserCmd)

		// two errors expected: SetupMany failure on multiple snaps falls back to one-by-one apparmor invocations. Both fail on apparmor_parser again and we only see
		// individual failures. Error from batch run is only logged.
		c.Assert(errs, HasLen, 2)
		c.Check(errs[0], ErrorMatches, ".*cannot setup profiles for snap \"samba\".*\napparmor_parser output:\npermanent failure\n")
		c.Check(errs[1], ErrorMatches, ".*cannot setup profiles for snap \"some-snap\".*\napparmor_parser output:\npermanent failure\n")
		c.Check(log.String(), Matches, ".*failed to batch-reload unchanged profiles: cannot load apparmor profiles: exit status 1\n.*\n.*\n")

		s.RemoveSnap(c, snapInfo1)
		s.RemoveSnap(c, snapInfo2)
	}
}

func (s *backendSuite) TestSetupManyApparmorBatchProcessingErrorWithFallbackOK(c *C) {
	log, restore := logger.MockLogger()
	defer restore()

	for _, opts := range testedConfinementOpts {
		log.Reset()

		// note, InstallSnap here uses s.parserCmd which mocks happy apparmor_parser
		snapInfo1 := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		snapInfo2 := s.InstallSnap(c, opts, "", ifacetest.SomeSnapYamlV1, 1)
		s.parserCmd.ForgetCalls()
		setupManyInterface, ok := s.Backend.(interfaces.SecurityBackendSetupMany)
		c.Assert(ok, Equals, true)

		// mock apparmor_parser again with a failing one (and restore immediately for the next iteration of the test)
		failingParserCmd := testutil.MockCommand(c, "apparmor_parser", fakeFailingAppArmorParser)
		errs := setupManyInterface.SetupMany([]*snap.Info{snapInfo1, snapInfo2}, func(snapName string) interfaces.ConfinementOptions { return opts }, s.Repo, s.meas)
		failingParserCmd.Restore()

		s.checkSetupManyCallsWithFallback(c, failingParserCmd)

		// no errors expected: error from batch run is only logged, but individual apparmor parser execution as part of the fallback are successful.
		// note, tnis scenario is unlikely to happen in real life, because if a profile failed in a batch, it would fail when parsed alone too. It is
		// tested here just to exercise various execution paths.
		c.Assert(errs, HasLen, 0)
		c.Check(log.String(), Matches, ".*failed to batch-reload unchanged profiles: cannot load apparmor profiles: exit status 1\napparmor_parser output:\nbatch failure \\(4 profiles\\)\n")

		s.RemoveSnap(c, snapInfo1)
		s.RemoveSnap(c, snapInfo2)
	}
}

func (s *backendSuite) TestSetupManyApparmorBatchProcessingErrorWithFallbackPartiallyOK(c *C) {
	log, restore := logger.MockLogger()
	defer restore()

	for _, opts := range testedConfinementOpts {
		log.Reset()

		// note, InstallSnap here uses s.parserCmd which mocks happy apparmor_parser
		snapInfo1 := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		snapInfo2 := s.InstallSnap(c, opts, "", ifacetest.SomeSnapYamlV1, 1)
		s.parserCmd.ForgetCalls()
		setupManyInterface, ok := s.Backend.(interfaces.SecurityBackendSetupMany)
		c.Assert(ok, Equals, true)

		// mock apparmor_parser with a failing one
		failingParserCmd := testutil.MockCommand(c, "apparmor_parser", fakeFailingAppArmorParserOneProfile)
		errs := setupManyInterface.SetupMany([]*snap.Info{snapInfo1, snapInfo2}, func(snapName string) interfaces.ConfinementOptions { return opts }, s.Repo, s.meas)
		failingParserCmd.Restore()

		s.checkSetupManyCallsWithFallback(c, failingParserCmd)

		// the batch reload fails because of snap.samba.smbd profile failing
		c.Check(log.String(), Matches, ".* failed to batch-reload unchanged profiles: cannot load apparmor profiles: exit status 1\napparmor_parser output:\nfailure: snap.samba.smbd\n")
		// and we also fail when running that profile in fallback mode
		c.Assert(errs, HasLen, 1)
		c.Assert(errs[0], ErrorMatches, "cannot setup profiles for snap \"samba\": cannot load apparmor profiles: exit status 1\n.*apparmor_parser output:\nfailure: snap.samba.smbd\n")

		s.RemoveSnap(c, snapInfo1)
		s.RemoveSnap(c, snapInfo2)
	}
}

const snapcraftPrYaml = `name: snapcraft-pr
version: 1
apps:
  snapcraft-pr:
    cmd: snapcraft-pr
`

const snapcraftYaml = `name: snapcraft
version: 1
apps:
  snapcraft:
    cmd: snapcraft
`

func (s *backendSuite) TestInstallingSnapDoesntBreakSnapsWithPrefixName(c *C) {
	snapcraftProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.snapcraft.snapcraft")
	snapcraftPrProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.snapcraft-pr.snapcraft-pr")
	// Install snapcraft-pr and check that its profile was created.
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", snapcraftPrYaml, 1)
	_, err := os.Stat(snapcraftPrProfile)
	c.Check(err, IsNil)

	// Install snapcraft (sans the -pr suffix) and check that its profile was created.
	// Check that this didn't remove the profile of snapcraft-pr installed earlier.
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", snapcraftYaml, 1)
	_, err = os.Stat(snapcraftProfile)
	c.Check(err, IsNil)
	_, err = os.Stat(snapcraftPrProfile)
	c.Check(err, IsNil)
}

func (s *backendSuite) TestRemovingSnapDoesntBreakSnapsWIthPrefixName(c *C) {
	snapcraftProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.snapcraft.snapcraft")
	snapcraftPrProfile := filepath.Join(dirs.SnapAppArmorDir, "snap.snapcraft-pr.snapcraft-pr")

	// Install snapcraft-pr and check that its profile was created.
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", snapcraftPrYaml, 1)
	_, err := os.Stat(snapcraftPrProfile)
	c.Check(err, IsNil)

	// Install snapcraft (sans the -pr suffix) and check that its profile was created.
	// Check that this didn't remove the profile of snapcraft-pr installed earlier.
	snapInfo := s.InstallSnap(c, interfaces.ConfinementOptions{}, "", snapcraftYaml, 1)
	_, err = os.Stat(snapcraftProfile)
	c.Check(err, IsNil)
	_, err = os.Stat(snapcraftPrProfile)
	c.Check(err, IsNil)

	// Remove snapcraft (sans the -pr suffix) and check that its profile was removed.
	// Check that this didn't remove the profile of snapcraft-pr installed earlier.
	s.RemoveSnap(c, snapInfo)
	_, err = os.Stat(snapcraftProfile)
	c.Check(os.IsNotExist(err), Equals, true)
	_, err = os.Stat(snapcraftPrProfile)
	c.Check(err, IsNil)
}

func (s *backendSuite) TestDefaultCoreRuntimesTemplateOnlyUsed(c *C) {
	for _, base := range []string{
		"",
		"base: core16",
		"base: core18",
		"base: core20",
		"base: core22",
		"base: core98",
	} {
		restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
		defer restore()

		testYaml := ifacetest.SambaYamlV1 + base + "\n"

		snapInfo := snaptest.MockInfo(c, testYaml, nil)
		// NOTE: we don't call apparmor.MockTemplate()
		err := s.Backend.Setup(snapInfo, interfaces.ConfinementOptions{}, s.Repo, s.meas)
		c.Assert(err, IsNil)
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		data, err := ioutil.ReadFile(profile)
		c.Assert(err, IsNil)
		for _, line := range []string{
			// preamble
			"#include <tunables/global>\n",
			// footer
			"}\n",
			// templateCommon
			"/etc/ld.so.preload r,\n",
			"owner @{PROC}/@{pid}/maps k,\n",
			"/tmp/   r,\n",
			"/sys/class/ r,\n",
			// defaultCoreRuntimeTemplateRules
			"# Default rules for core base runtimes\n",
			"/usr/share/terminfo/** k,\n",
		} {
			c.Assert(string(data), testutil.Contains, line)
		}
		for _, line := range []string{
			// defaultOtherBaseTemplateRules should not be present
			"# Default rules for non-core base runtimes\n",
			"/{,s}bin/** mrklix,\n",
		} {
			c.Assert(string(data), Not(testutil.Contains), line)
		}
	}
}

func (s *backendSuite) TestBaseDefaultTemplateOnlyUsed(c *C) {
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()

	testYaml := ifacetest.SambaYamlV1 + "base: other\n"

	snapInfo := snaptest.MockInfo(c, testYaml, nil)
	// NOTE: we don't call apparmor.MockTemplate()
	err := s.Backend.Setup(snapInfo, interfaces.ConfinementOptions{}, s.Repo, s.meas)
	c.Assert(err, IsNil)
	profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
	data, err := ioutil.ReadFile(profile)
	c.Assert(err, IsNil)
	for _, line := range []string{
		// preamble
		"#include <tunables/global>\n",
		// footer
		"}\n",
		// templateCommon
		"/etc/ld.so.preload r,\n",
		"owner @{PROC}/@{pid}/maps k,\n",
		"/tmp/   r,\n",
		"/sys/class/ r,\n",
		// defaultOtherBaseTemplateRules
		"# Default rules for non-core base runtimes\n",
		"/{,s}bin/** mrklix,\n",
	} {
		c.Assert(string(data), testutil.Contains, line)
	}
	for _, line := range []string{
		// defaultCoreRuntimeTemplateRules should not be present
		"# Default rules for core base runtimes\n",
		"/usr/share/terminfo/** k,\n",
		"/{,usr/}bin/arch ixr,\n",
	} {
		c.Assert(string(data), Not(testutil.Contains), line)
	}
}

func (s *backendSuite) TestTemplateRulesInCommon(c *C) {
	// assume that we lstrip() the line
	commonFiles := regexp.MustCompile(`^(audit +)?(deny +)?(owner +)?/((dev|etc|run|sys|tmp|{dev,run}|{,var/}run|usr/lib/snapd|var/lib/extrausers|var/lib/snapd)/|var/snap/{?@{SNAP_)`)
	commonFilesVar := regexp.MustCompile(`^(audit +)?(deny +)?(owner +)?@{(HOME|HOMEDIRS|INSTALL_DIR|PROC)}/`)
	commonOther := regexp.MustCompile(`^([^/@#]|#include +<)`)

	// first, verify the regexes themselves

	// Expected matches
	for idx, tc := range []string{
		// abstraction
		"#include <abstractions/base>",
		// file
		"/dev/{,u}random w,",
		"/dev/{,u}random w, # test comment",
		"/{dev,run}/shm/snap.@{SNAP_INSTANCE_NAME}.** mrwlkix,",
		"/etc/ld.so.preload r,",
		"@{INSTALL_DIR}/{@{SNAP_NAME},@{SNAP_INSTANCE_NAME}}/ r,",
		"deny @{INSTALL_DIR}/{@{SNAP_NAME},@{SNAP_INSTANCE_NAME}}/**/__pycache__/*.pyc.[0-9]* w,",
		"audit /dev/something r,",
		"audit deny /dev/something r,",
		"audit deny owner /dev/something r,",
		"@{PROC}/ r,",
		"owner @{PROC}/@{pid}/{,task/@{tid}}fd/[0-9]* rw,",
		"/run/uuidd/request rw,",
		"owner /run/user/[0-9]*/snap.@{SNAP_INSTANCE_NAME}/   rw,",
		"/sys/devices/virtual/tty/{console,tty*}/active r,",
		"/tmp/   r,",
		"/{,var/}run/udev/tags/snappy-assign/ r,",
		"/usr/lib/snapd/foo r,",
		"/var/lib/extrausers/foo r,",
		"/var/lib/snapd/foo r,",
		"/var/snap/{@{SNAP_NAME},@{SNAP_INSTANCE_NAME}}/ r",
		"/var/snap/@{SNAP_NAME}/ r",
		// capability
		"capability ipc_lock,",
		// dbus - single line
		"dbus (receive, send) peer=(label=snap.@{SNAP_INSTANCE_NAME}.*),",
		// dbus - multiline
		"dbus (send)",
		"bus={session,system}",
		"path=/org/freedesktop/DBus",
		"interface=org.freedesktop.DBus.Introspectable",
		"member=Introspect",
		"peer=(label=unconfined),",
		// mount
		"mount,",
		"remount,",
		"umount,",
		// network
		"network,",
		// pivot_root
		"pivot_root,",
		// ptrace
		"ptrace,",
		// signal
		"signal peer=snap.@{SNAP_INSTANCE_NAME}.*,",
		// unix
		"unix peer=(label=snap.@{SNAP_INSTANCE_NAME}.*),",
	} {
		c.Logf("trying %d: %s", idx, tc)
		cf := commonFiles.MatchString(tc)
		cfv := commonFilesVar.MatchString(tc)
		co := commonOther.MatchString(tc)
		c.Check(cf || cfv || co, Equals, true)
	}

	// Expected no matches
	for idx, tc := range []string{
		"/bin/ls",
		"# some comment",
		"deny /usr/lib/python3*/{,**/}__pycache__/ w,",
	} {
		c.Logf("trying %d: %s", idx, tc)
		cf := commonFiles.MatchString(tc)
		cfv := commonFilesVar.MatchString(tc)
		co := commonOther.MatchString(tc)
		c.Check(cf && cfv && co, Equals, false)
	}

	for _, raw := range strings.Split(apparmor.DefaultCoreRuntimeTemplateRules, "\n") {
		line := strings.TrimLeft(raw, " \t")
		cf := commonFiles.MatchString(line)
		cfv := commonFilesVar.MatchString(line)
		co := commonOther.MatchString(line)
		res := cf || cfv || co
		if res {
			c.Logf("ERROR: found rule that should be in templateCommon (default template rules): %s", line)
		}
		c.Check(res, Equals, false)
	}

	for _, raw := range strings.Split(apparmor.DefaultOtherBaseTemplateRules, "\n") {
		line := strings.TrimLeft(raw, " \t")
		cf := commonFiles.MatchString(line)
		cfv := commonFilesVar.MatchString(line)
		co := commonOther.MatchString(line)
		res := cf || cfv || co
		if res {
			c.Logf("ERROR: found rule that should be in templateCommon (default base template rules): %s", line)
		}
		c.Check(res, Equals, false)
	}
}

type combineSnippetsScenario struct {
	opts    interfaces.ConfinementOptions
	snippet string
	content string
}

const commonPrefix = `
# This is a snap name without the instance key
@{SNAP_NAME}="samba"
# This is a snap name with instance key
@{SNAP_INSTANCE_NAME}="samba"
@{SNAP_INSTANCE_DESKTOP}="samba"
@{SNAP_COMMAND_NAME}="smbd"
@{SNAP_REVISION}="1"
@{PROFILE_DBUS}="snap_2esamba_2esmbd"
@{INSTALL_DIR}="/{,var/lib/snapd/}snap"`

var combineSnippetsScenarios = []combineSnippetsScenario{{
	// By default apparmor is enforcing mode.
	opts:    interfaces.ConfinementOptions{},
	content: commonPrefix + "\nprofile \"snap.samba.smbd\" (attach_disconnected,mediate_deleted) {\n\n}\n",
}, {
	// Snippets are injected in the space between "{" and "}"
	opts:    interfaces.ConfinementOptions{},
	snippet: "snippet",
	content: commonPrefix + "\nprofile \"snap.samba.smbd\" (attach_disconnected,mediate_deleted) {\nsnippet\n}\n",
}, {
	// DevMode switches apparmor to non-enforcing (complain) mode.
	opts:    interfaces.ConfinementOptions{DevMode: true},
	snippet: "snippet",
	content: commonPrefix + "\nprofile \"snap.samba.smbd\" (attach_disconnected,mediate_deleted,complain) {\nsnippet\n}\n",
}, {
	// JailMode switches apparmor to enforcing mode even in the presence of DevMode.
	opts:    interfaces.ConfinementOptions{DevMode: true},
	snippet: "snippet",
	content: commonPrefix + "\nprofile \"snap.samba.smbd\" (attach_disconnected,mediate_deleted,complain) {\nsnippet\n}\n",
}, {
	// Classic confinement (without jailmode) uses apparmor in complain mode by default and ignores all snippets.
	opts:    interfaces.ConfinementOptions{Classic: true},
	snippet: "snippet",
	content: "\n#classic" + commonPrefix + "\nprofile \"snap.samba.smbd\" (attach_disconnected,mediate_deleted,complain) {\n\n}\n",
}, {
	// Classic confinement in JailMode uses enforcing apparmor.
	opts:    interfaces.ConfinementOptions{Classic: true, JailMode: true},
	snippet: "snippet",
	content: commonPrefix + `
profile "snap.samba.smbd" (attach_disconnected,mediate_deleted) {

  # Read-only access to the core snap.
  @{INSTALL_DIR}/core/** r,
  # Read only access to the core snap to load libc from.
  # This is related to LP: #1666897
  @{INSTALL_DIR}/core/*/{,usr/}lib/@{multiarch}/{,**/}lib*.so* m,

  # For snappy reexec on 4.8+ kernels
  @{INSTALL_DIR}/core/*/usr/lib/snapd/snap-exec m,

snippet
}
`,
}}

func (s *backendSuite) TestCombineSnippets(c *C) {
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()
	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	// NOTE: replace the real template with a shorter variant
	restoreTemplate := apparmor.MockTemplate("\n" +
		"###VAR###\n" +
		"###PROFILEATTACH### (attach_disconnected,mediate_deleted) {\n" +
		"###SNIPPETS###\n" +
		"}\n")
	defer restoreTemplate()
	restoreClassicTemplate := apparmor.MockClassicTemplate("\n" +
		"#classic\n" +
		"###VAR###\n" +
		"###PROFILEATTACH### (attach_disconnected,mediate_deleted) {\n" +
		"###SNIPPETS###\n" +
		"}\n")
	defer restoreClassicTemplate()
	for i, scenario := range combineSnippetsScenarios {
		s.Iface.AppArmorPermanentSlotCallback = func(spec *apparmor.Specification, slot *snap.SlotInfo) error {
			if scenario.snippet == "" {
				return nil
			}
			spec.AddSnippet(scenario.snippet)
			return nil
		}
		snapInfo := s.InstallSnap(c, scenario.opts, "", ifacetest.SambaYamlV1, 1)
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		c.Check(profile, testutil.FileEquals, scenario.content, Commentf("scenario %d: %#v", i, scenario))
		stat, err := os.Stat(profile)
		c.Assert(err, IsNil)
		c.Check(stat.Mode(), Equals, os.FileMode(0644))
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestCombineSnippetsChangeProfile(c *C) {
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()
	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	restoreClassicTemplate := apparmor.MockClassicTemplate("###CHANGEPROFILE_RULE###")
	defer restoreClassicTemplate()

	type changeProfileScenario struct {
		features []string
		expected string
	}

	var changeProfileScenarios = []changeProfileScenario{{
		features: []string{},
		expected: "change_profile,",
	}, {
		features: []string{"unsafe"},
		expected: "change_profile unsafe /**,",
	}}

	for i, scenario := range changeProfileScenarios {
		restore = apparmor.MockParserFeatures(func() ([]string, error) { return scenario.features, nil })
		defer restore()

		snapInfo := s.InstallSnap(c, interfaces.ConfinementOptions{Classic: true}, "", ifacetest.SambaYamlV1, 1)
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		c.Check(profile, testutil.FileEquals, scenario.expected, Commentf("scenario %d: %#v", i, scenario))
		stat, err := os.Stat(profile)
		c.Assert(err, IsNil)
		c.Check(stat.Mode(), Equals, os.FileMode(0644))
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestParallelInstallCombineSnippets(c *C) {
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()
	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	// NOTE: replace the real template with a shorter variant
	restoreTemplate := apparmor.MockTemplate("\n" +
		"###VAR###\n" +
		"###PROFILEATTACH### (attach_disconnected,mediate_deleted) {\n" +
		"###SNIPPETS###\n" +
		"}\n")
	defer restoreTemplate()
	restoreClassicTemplate := apparmor.MockClassicTemplate("\n" +
		"#classic\n" +
		"###VAR###\n" +
		"###PROFILEATTACH### (attach_disconnected,mediate_deleted) {\n" +
		"###SNIPPETS###\n" +
		"}\n")
	defer restoreClassicTemplate()
	s.Iface.AppArmorPermanentSlotCallback = func(spec *apparmor.Specification, slot *snap.SlotInfo) error {
		return nil
	}
	expected := `
# This is a snap name without the instance key
@{SNAP_NAME}="samba"
# This is a snap name with instance key
@{SNAP_INSTANCE_NAME}="samba_foo"
@{SNAP_INSTANCE_DESKTOP}="samba+foo"
@{SNAP_COMMAND_NAME}="smbd"
@{SNAP_REVISION}="1"
@{PROFILE_DBUS}="snap_2esamba_5ffoo_2esmbd"
@{INSTALL_DIR}="/{,var/lib/snapd/}snap"
profile "snap.samba_foo.smbd" (attach_disconnected,mediate_deleted) {

}
`
	snapInfo := s.InstallSnap(c, interfaces.ConfinementOptions{}, "samba_foo", ifacetest.SambaYamlV1, 1)
	c.Assert(snapInfo, NotNil)
	profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba_foo.smbd")
	stat, err := os.Stat(profile)
	c.Assert(err, IsNil)
	c.Check(profile, testutil.FileEquals, expected)
	c.Check(stat.Mode(), Equals, os.FileMode(0644))
	s.RemoveSnap(c, snapInfo)
}

func (s *backendSuite) TestTemplateVarsWithHook(c *C) {
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()
	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()
	// NOTE: replace the real template with a shorter variant
	restoreTemplate := apparmor.MockTemplate("\n" +
		"###VAR###\n" +
		"###PROFILEATTACH### (attach_disconnected,mediate_deleted) {\n" +
		"###SNIPPETS###\n" +
		"}\n")
	defer restoreTemplate()

	expected := `
# This is a snap name without the instance key
@{SNAP_NAME}="foo"
# This is a snap name with instance key
@{SNAP_INSTANCE_NAME}="foo"
@{SNAP_INSTANCE_DESKTOP}="foo"
@{SNAP_COMMAND_NAME}="hook.configure"
@{SNAP_REVISION}="1"
@{PROFILE_DBUS}="snap_2efoo_2ehook_2econfigure"
@{INSTALL_DIR}="/{,var/lib/snapd/}snap"
profile "snap.foo.hook.configure" (attach_disconnected,mediate_deleted) {

}
`
	snapInfo := s.InstallSnap(c, interfaces.ConfinementOptions{}, "", ifacetest.HookYaml, 1)
	c.Assert(snapInfo, NotNil)
	profile := filepath.Join(dirs.SnapAppArmorDir, "snap.foo.hook.configure")
	stat, err := os.Stat(profile)
	c.Assert(err, IsNil)
	c.Check(profile, testutil.FileEquals, expected)
	c.Check(stat.Mode(), Equals, os.FileMode(0644))
	s.RemoveSnap(c, snapInfo)
}

func mockPartalAppArmorOnDistro(c *C, kernelVersion string, releaseID string, releaseIDLike ...string) (restore func()) {
	restore1 := apparmor_sandbox.MockLevel(apparmor_sandbox.Partial)
	restore2 := release.MockReleaseInfo(&release.OS{ID: releaseID, IDLike: releaseIDLike})
	restore3 := osutil.MockKernelVersion(kernelVersion)
	restore4 := apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	restore5 := apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	// Replace the real template with a shorter variant that is easier to test.
	restore6 := apparmor.MockTemplate("\n" +
		"###VAR###\n" +
		"###PROFILEATTACH### (attach_disconnected) {\n" +
		"###SNIPPETS###\n" +
		"}\n")
	restore7 := apparmor.MockClassicTemplate("\n" +
		"#classic\n" +
		"###VAR###\n" +
		"###PROFILEATTACH### (attach_disconnected) {\n" +
		"###SNIPPETS###\n" +
		"}\n")

	return func() {
		restore1()
		restore2()
		restore3()
		restore4()
		restore5()
		restore6()
		restore7()
	}
}

const coreYaml = `name: core
version: 1
type: os
`

const snapdYaml = `name: snapd
version: 1
type: snapd
`

func (s *backendSuite) writeVanillaSnapConfineProfile(c *C, coreOrSnapdInfo *snap.Info) {
	vanillaProfilePath := filepath.Join(coreOrSnapdInfo.MountDir(), "/etc/apparmor.d/usr.lib.snapd.snap-confine.real")
	vanillaProfileText := []byte(`#include <tunables/global>
/usr/lib/snapd/snap-confine (attach_disconnected) {
    # We run privileged, so be fanatical about what we include and don't use
    # any abstractions
    /etc/ld.so.cache r,
}
`)
	c.Assert(os.MkdirAll(filepath.Dir(vanillaProfilePath), 0755), IsNil)
	c.Assert(ioutil.WriteFile(vanillaProfilePath, vanillaProfileText, 0644), IsNil)
}

func (s *backendSuite) TestSnapConfineProfile(c *C) {
	// Let's say we're working with the core snap at revision 111.
	coreInfo := snaptest.MockInfo(c, coreYaml, &snap.SideInfo{Revision: snap.R(111)})
	s.writeVanillaSnapConfineProfile(c, coreInfo)
	// We expect to see the same profile, just anchored at a different directory.
	expectedProfileDir := filepath.Join(dirs.GlobalRootDir, "/var/lib/snapd/apparmor/profiles")
	expectedProfileName := "snap-confine.core.111"
	expectedProfileGlob := "snap-confine.core.*"
	expectedProfileText := fmt.Sprintf(`#include <tunables/global>
%s/usr/lib/snapd/snap-confine (attach_disconnected) {
    # We run privileged, so be fanatical about what we include and don't use
    # any abstractions
    /etc/ld.so.cache r,
}
`, coreInfo.MountDir())

	c.Assert(expectedProfileName, testutil.Contains, coreInfo.Revision.String())

	// Compute the profile and see if it matches.
	dir, glob, content, err := apparmor.SnapConfineFromSnapProfile(coreInfo)
	c.Assert(err, IsNil)
	c.Assert(dir, Equals, expectedProfileDir)
	c.Assert(glob, Equals, expectedProfileGlob)
	c.Assert(content, DeepEquals, map[string]osutil.FileState{
		expectedProfileName: &osutil.MemoryFileState{
			Content: []byte(expectedProfileText),
			Mode:    0644,
		},
	})
}

func (s *backendSuite) TestSnapConfineProfileFromSnapdSnap(c *C) {
	restore := release.MockOnClassic(false)
	defer restore()
	dirs.SetRootDir(s.RootDir)

	snapdInfo := snaptest.MockInfo(c, snapdYaml, &snap.SideInfo{Revision: snap.R(222)})
	s.writeVanillaSnapConfineProfile(c, snapdInfo)

	// We expect to see the same profile, just anchored at a different directory.
	expectedProfileDir := filepath.Join(dirs.GlobalRootDir, "/var/lib/snapd/apparmor/profiles")
	expectedProfileName := "snap-confine.snapd.222"
	expectedProfileGlob := "snap-confine.snapd.*"
	expectedProfileText := fmt.Sprintf(`#include <tunables/global>
%s/usr/lib/snapd/snap-confine (attach_disconnected) {
    # We run privileged, so be fanatical about what we include and don't use
    # any abstractions
    /etc/ld.so.cache r,
}
`, snapdInfo.MountDir())

	c.Assert(expectedProfileName, testutil.Contains, snapdInfo.Revision.String())

	// Compute the profile and see if it matches.
	dir, glob, content, err := apparmor.SnapConfineFromSnapProfile(snapdInfo)
	c.Assert(err, IsNil)
	c.Assert(dir, Equals, expectedProfileDir)
	c.Assert(glob, Equals, expectedProfileGlob)
	c.Assert(content, DeepEquals, map[string]osutil.FileState{
		expectedProfileName: &osutil.MemoryFileState{
			Content: []byte(expectedProfileText),
			Mode:    0644,
		},
	})
}

func (s *backendSuite) TestSnapConfineFromSnapProfileCreatesAllDirs(c *C) {
	c.Assert(osutil.IsDirectory(dirs.SnapAppArmorDir), Equals, false)
	coreInfo := snaptest.MockInfo(c, coreYaml, &snap.SideInfo{Revision: snap.R(111)})

	s.writeVanillaSnapConfineProfile(c, coreInfo)

	aa := &apparmor.Backend{}
	err := aa.SetupSnapConfineReexec(coreInfo)
	c.Assert(err, IsNil)
	c.Assert(osutil.IsDirectory(dirs.SnapAppArmorDir), Equals, true)
}

func (s *backendSuite) TestSetupHostSnapConfineApparmorForReexecCleans(c *C) {
	restorer := release.MockOnClassic(true)
	defer restorer()
	restorer = apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restorer()

	coreInfo := snaptest.MockInfo(c, coreYaml, &snap.SideInfo{Revision: snap.R(111)})
	s.writeVanillaSnapConfineProfile(c, coreInfo)

	canaryName := "snap-confine.core.2718"
	canary := filepath.Join(dirs.SnapAppArmorDir, canaryName)
	err := os.MkdirAll(filepath.Dir(canary), 0755)
	c.Assert(err, IsNil)
	err = ioutil.WriteFile(canary, nil, 0644)
	c.Assert(err, IsNil)

	// install the new core snap on classic triggers cleanup
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", coreYaml, 111)

	c.Check(osutil.FileExists(canary), Equals, false)
}

func (s *backendSuite) TestSetupHostSnapConfineApparmorForReexecWritesNew(c *C) {
	restorer := release.MockOnClassic(true)
	defer restorer()
	restorer = apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restorer()

	coreInfo := snaptest.MockInfo(c, coreYaml, &snap.SideInfo{Revision: snap.R(111)})
	s.writeVanillaSnapConfineProfile(c, coreInfo)

	// Install the new core snap on classic triggers a new snap-confine
	// for this snap-confine on core
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", coreYaml, 111)

	newAA, err := filepath.Glob(filepath.Join(dirs.SnapAppArmorDir, "*"))
	c.Assert(err, IsNil)
	c.Assert(newAA, HasLen, 1)
	c.Check(newAA[0], Matches, `.*/var/lib/snapd/apparmor/profiles/snap-confine.core.111`)

	// This is the key, rewriting "/usr/lib/snapd/snap-confine
	c.Check(newAA[0], testutil.FileContains, "/snap/core/111/usr/lib/snapd/snap-confine (attach_disconnected) {")
	// No other changes other than that to the input
	c.Check(newAA[0], testutil.FileEquals, fmt.Sprintf(`#include <tunables/global>
%s/core/111/usr/lib/snapd/snap-confine (attach_disconnected) {
    # We run privileged, so be fanatical about what we include and don't use
    # any abstractions
    /etc/ld.so.cache r,
}
`, dirs.SnapMountDir))

	c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
		{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s", apparmor_sandbox.CacheDir), "--quiet", newAA[0]},
	})

	// snap-confine directory was created
	_, err = os.Stat(dirs.SnapConfineAppArmorDir)
	c.Check(err, IsNil)
}

func (s *backendSuite) TestCoreOnCoreCleansApparmorCache(c *C) {
	coreInfo := snaptest.MockInfo(c, coreYaml, &snap.SideInfo{Revision: snap.R(111)})
	s.writeVanillaSnapConfineProfile(c, coreInfo)
	s.testCoreOrSnapdOnCoreCleansApparmorCache(c, coreYaml)
}

func (s *backendSuite) TestSnapdOnCoreCleansApparmorCache(c *C) {
	snapdInfo := snaptest.MockInfo(c, snapdYaml, &snap.SideInfo{Revision: snap.R(111)})
	s.writeVanillaSnapConfineProfile(c, snapdInfo)
	s.testCoreOrSnapdOnCoreCleansApparmorCache(c, snapdYaml)
}

func (s *backendSuite) testCoreOrSnapdOnCoreCleansApparmorCache(c *C, coreOrSnapdYaml string) {
	restorer := release.MockOnClassic(false)
	defer restorer()

	err := os.MkdirAll(apparmor_sandbox.SystemCacheDir, 0755)
	c.Assert(err, IsNil)
	// the canary file in the cache will be removed
	canaryPath := filepath.Join(apparmor_sandbox.SystemCacheDir, "meep")
	err = ioutil.WriteFile(canaryPath, nil, 0644)
	c.Assert(err, IsNil)
	// and the snap-confine profiles are removed
	scCanaryPath := filepath.Join(apparmor_sandbox.SystemCacheDir, "usr.lib.snapd.snap-confine.real")
	err = ioutil.WriteFile(scCanaryPath, nil, 0644)
	c.Assert(err, IsNil)
	scCanaryPath = filepath.Join(apparmor_sandbox.SystemCacheDir, "usr.lib.snapd.snap-confine")
	err = ioutil.WriteFile(scCanaryPath, nil, 0644)
	c.Assert(err, IsNil)
	scCanaryPath = filepath.Join(apparmor_sandbox.SystemCacheDir, "snap-confine.core.6405")
	err = ioutil.WriteFile(scCanaryPath, nil, 0644)
	c.Assert(err, IsNil)
	scCanaryPath = filepath.Join(apparmor_sandbox.SystemCacheDir, "snap-confine.snapd.6405")
	err = ioutil.WriteFile(scCanaryPath, nil, 0644)
	c.Assert(err, IsNil)
	scCanaryPath = filepath.Join(apparmor_sandbox.SystemCacheDir, "snap.core.4938.usr.lib.snapd.snap-confine")
	err = ioutil.WriteFile(scCanaryPath, nil, 0644)
	c.Assert(err, IsNil)
	scCanaryPath = filepath.Join(apparmor_sandbox.SystemCacheDir, "var.lib.snapd.snap.core.1234.usr.lib.snapd.snap-confine")
	err = ioutil.WriteFile(scCanaryPath, nil, 0644)
	c.Assert(err, IsNil)
	// but non-regular entries in the cache dir are kept
	dirsAreKept := filepath.Join(apparmor_sandbox.SystemCacheDir, "dir")
	err = os.MkdirAll(dirsAreKept, 0755)
	c.Assert(err, IsNil)
	symlinksAreKept := filepath.Join(apparmor_sandbox.SystemCacheDir, "symlink")
	err = os.Symlink("some-sylink-target", symlinksAreKept)
	c.Assert(err, IsNil)
	// and the snap profiles are kept
	snapCanaryKept := filepath.Join(apparmor_sandbox.SystemCacheDir, "snap.canary.meep")
	err = ioutil.WriteFile(snapCanaryKept, nil, 0644)
	c.Assert(err, IsNil)
	sunCanaryKept := filepath.Join(apparmor_sandbox.SystemCacheDir, "snap-update-ns.canary")
	err = ioutil.WriteFile(sunCanaryKept, nil, 0644)
	c.Assert(err, IsNil)
	// and the .features file is kept
	dotKept := filepath.Join(apparmor_sandbox.SystemCacheDir, ".features")
	err = ioutil.WriteFile(dotKept, nil, 0644)
	c.Assert(err, IsNil)

	// install the new core snap on classic triggers a new snap-confine
	// for this snap-confine on core
	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", coreOrSnapdYaml, 111)

	l, err := filepath.Glob(filepath.Join(apparmor_sandbox.SystemCacheDir, "*"))
	c.Assert(err, IsNil)
	// canary is gone, extra stuff is kept
	c.Check(l, DeepEquals, []string{dotKept, dirsAreKept, sunCanaryKept, snapCanaryKept, symlinksAreKept})
}

// snap-confine policy when NFS is not used.
func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyNoNFS(c *C) {
	// Make it appear as if NFS was not used.
	restore := apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()

	// Make it appear as if overlay was not used.
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	// Intercept interaction with apparmor_parser
	cmd := testutil.MockCommand(c, "apparmor_parser", "")
	defer cmd.Restore()

	// Setup generated policy for snap-confine.
	err := (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, IsNil)
	c.Assert(cmd.Calls(), HasLen, 0)

	// Because NFS is not used there are no local policy files but the
	// directory was created.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 0)

	// The policy was not reloaded.
	c.Assert(cmd.Calls(), HasLen, 0)
}

// Ensure that both names of the snap-confine apparmor profile are supported.

func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyWithNFS1(c *C) {
	s.testSetupSnapConfineGeneratedPolicyWithNFS(c, "usr.lib.snapd.snap-confine")
}

func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyWithNFS2(c *C) {
	s.testSetupSnapConfineGeneratedPolicyWithNFS(c, "usr.lib.snapd.snap-confine.real")
}

// snap-confine policy when NFS is used and snapd has not re-executed.
func (s *backendSuite) testSetupSnapConfineGeneratedPolicyWithNFS(c *C, profileFname string) {
	// Make it appear as if NFS workaround was needed.
	restore := apparmor.MockIsHomeUsingNFS(func() (bool, error) { return true, nil })
	defer restore()

	// Make it appear as if overlay was not used.
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	// Intercept interaction with apparmor_parser
	cmd := testutil.MockCommand(c, "apparmor_parser", "")
	defer cmd.Restore()

	// Intercept the /proc/self/exe symlink and point it to the distribution
	// executable (the path doesn't matter as long as it is not from the
	// mounted core snap). This indicates that snapd is not re-executing
	// and that we should reload snap-confine profile.
	fakeExe := filepath.Join(s.RootDir, "fake-proc-self-exe")
	err := os.Symlink("/usr/lib/snapd/snapd", fakeExe)
	c.Assert(err, IsNil)
	restore = apparmor.MockProcSelfExe(fakeExe)
	defer restore()

	profilePath := filepath.Join(apparmor_sandbox.ConfDir, profileFname)

	// Create the directory where system apparmor profiles are stored and write
	// the system apparmor profile of snap-confine.
	c.Assert(os.MkdirAll(apparmor_sandbox.ConfDir, 0755), IsNil)
	c.Assert(ioutil.WriteFile(profilePath, []byte(""), 0644), IsNil)

	// Setup generated policy for snap-confine.
	err = (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, IsNil)

	// Because NFS is being used, we have the extra policy file.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 1)
	c.Assert(files[0].Name(), Equals, "nfs-support")
	c.Assert(files[0].Mode(), Equals, os.FileMode(0644))
	c.Assert(files[0].IsDir(), Equals, false)

	// The policy allows network access.
	fn := filepath.Join(dirs.SnapConfineAppArmorDir, files[0].Name())
	c.Assert(fn, testutil.FileContains, "network inet,")
	c.Assert(fn, testutil.FileContains, "network inet6,")

	// The system apparmor profile of snap-confine was reloaded.
	c.Assert(cmd.Calls(), HasLen, 1)
	c.Assert(cmd.Calls(), DeepEquals, [][]string{{
		"apparmor_parser", "--replace",
		"--write-cache",
		"-O", "no-expr-simplify",
		"--cache-loc=" + apparmor_sandbox.SystemCacheDir,
		"--skip-read-cache",
		"--quiet",
		profilePath,
	}})
}

// snap-confine policy when NFS is used and snapd has re-executed.
func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyWithNFSAndReExec(c *C) {
	// Make it appear as if NFS workaround was needed.
	restore := apparmor.MockIsHomeUsingNFS(func() (bool, error) { return true, nil })
	defer restore()

	// Make it appear as if overlay was not used.
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	// Intercept interaction with apparmor_parser
	cmd := testutil.MockCommand(c, "apparmor_parser", "")
	defer cmd.Restore()

	// Intercept the /proc/self/exe symlink and point it to the snapd from the
	// mounted core snap. This indicates that snapd has re-executed and
	// should not reload snap-confine policy.
	fakeExe := filepath.Join(s.RootDir, "fake-proc-self-exe")
	err := os.Symlink(filepath.Join(dirs.SnapMountDir, "/core/1234/usr/lib/snapd/snapd"), fakeExe)
	c.Assert(err, IsNil)
	restore = apparmor.MockProcSelfExe(fakeExe)
	defer restore()

	// Setup generated policy for snap-confine.
	err = (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, IsNil)

	// Because NFS is being used, we have the extra policy file.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 1)
	c.Assert(files[0].Name(), Equals, "nfs-support")
	c.Assert(files[0].Mode(), Equals, os.FileMode(0644))
	c.Assert(files[0].IsDir(), Equals, false)

	// The policy allows network access.
	fn := filepath.Join(dirs.SnapConfineAppArmorDir, files[0].Name())
	c.Assert(fn, testutil.FileContains, "network inet,")
	c.Assert(fn, testutil.FileContains, "network inet6,")

	// The distribution policy was not reloaded because snap-confine executes
	// from core snap. This is handled separately by per-profile Setup.
	c.Assert(cmd.Calls(), HasLen, 0)
}

// Test behavior when isHomeUsingNFS fails.
func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyError1(c *C) {
	// Make it appear as if NFS detection was broken.
	restore := apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, fmt.Errorf("broken") })
	defer restore()

	// Make it appear as if overlay was not used.
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	// Intercept interaction with apparmor_parser
	cmd := testutil.MockCommand(c, "apparmor_parser", "")
	defer cmd.Restore()

	// Intercept the /proc/self/exe symlink and point it to the snapd from the
	// distribution.  This indicates that snapd has not re-executed and should
	// reload snap-confine policy.
	fakeExe := filepath.Join(s.RootDir, "fake-proc-self-exe")
	err := os.Symlink(filepath.Join(dirs.SnapMountDir, "/usr/lib/snapd/snapd"), fakeExe)
	c.Assert(err, IsNil)
	restore = apparmor.MockProcSelfExe(fakeExe)
	defer restore()

	// Setup generated policy for snap-confine.
	err = (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	// NOTE: Errors in determining NFS are non-fatal to prevent snapd from
	// failing to operate. A warning message is logged but system operates as
	// if NFS was not active.
	c.Assert(err, IsNil)

	// While other stuff failed we created the policy directory and didn't
	// write any files to it.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 0)

	// We didn't reload the policy.
	c.Assert(cmd.Calls(), HasLen, 0)
}

// Test behavior when os.Readlink "/proc/self/exe" fails.
func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyError2(c *C) {
	// Make it appear as if NFS workaround was needed.
	restore := apparmor.MockIsHomeUsingNFS(func() (bool, error) { return true, nil })
	defer restore()

	// Make it appear as if overlay was not used.
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	// Intercept interaction with apparmor_parser
	cmd := testutil.MockCommand(c, "apparmor_parser", "")
	defer cmd.Restore()

	// Intercept the /proc/self/exe symlink and make it point to something that
	// doesn't exist (break it).
	fakeExe := filepath.Join(s.RootDir, "corrupt-proc-self-exe")
	restore = apparmor.MockProcSelfExe(fakeExe)
	defer restore()

	// Setup generated policy for snap-confine.
	err := (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, ErrorMatches, "cannot read .*corrupt-proc-self-exe: .*")

	// We didn't create the policy file.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 0)

	// We didn't reload the policy though.
	c.Assert(cmd.Calls(), HasLen, 0)
}

// Test behavior when exec.Command "apparmor_parser" fails
func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyError3(c *C) {
	// Make it appear as if NFS workaround was needed.
	restore := apparmor.MockIsHomeUsingNFS(func() (bool, error) { return true, nil })
	defer restore()

	// Make it appear as if overlay was not used.
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	// Intercept interaction with apparmor_parser and make it fail.
	cmd := testutil.MockCommand(c, "apparmor_parser", "echo testing; exit 1")
	defer cmd.Restore()

	// Intercept the /proc/self/exe symlink.
	fakeExe := filepath.Join(s.RootDir, "fake-proc-self-exe")
	err := os.Symlink("/usr/lib/snapd/snapd", fakeExe)
	c.Assert(err, IsNil)
	restore = apparmor.MockProcSelfExe(fakeExe)
	defer restore()

	// Create the directory where system apparmor profiles are stored and Write
	// the system apparmor profile of snap-confine.
	c.Assert(os.MkdirAll(apparmor_sandbox.ConfDir, 0755), IsNil)
	c.Assert(ioutil.WriteFile(filepath.Join(apparmor_sandbox.ConfDir, "usr.lib.snapd.snap-confine"), []byte(""), 0644), IsNil)

	// Setup generated policy for snap-confine.
	err = (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, ErrorMatches, "cannot reload snap-confine apparmor profile: .*\n.*\ntesting\n")

	// While created the policy file initially we also removed it so that
	// no side-effects remain.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 0)

	// We tried to reload the policy.
	c.Assert(cmd.Calls(), HasLen, 1)
}

// Test behavior when MkdirAll fails
func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyError4(c *C) {
	// Create a file where we would expect to find the local policy.
	err := os.RemoveAll(filepath.Dir(dirs.SnapConfineAppArmorDir))
	c.Assert(err, IsNil)
	err = os.MkdirAll(filepath.Dir(dirs.SnapConfineAppArmorDir), 0755)
	c.Assert(err, IsNil)
	err = ioutil.WriteFile(dirs.SnapConfineAppArmorDir, []byte(""), 0644)
	c.Assert(err, IsNil)

	// Setup generated policy for snap-confine.
	err = (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, ErrorMatches, "*.: not a directory")
}

// Test behavior when EnsureDirState fails
func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyError5(c *C) {
	// This test cannot run as root as root bypassed DAC checks.
	u, err := user.Current()
	c.Assert(err, IsNil)
	if u.Uid == "0" {
		c.Skip("this test cannot run as root")
	}

	// Make it appear as if NFS workaround was not needed.
	restore := apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()

	// Make it appear as if overlay was not used.
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	// Intercept interaction with apparmor_parser and make it fail.
	cmd := testutil.MockCommand(c, "apparmor_parser", "")
	defer cmd.Restore()

	// Intercept the /proc/self/exe symlink.
	fakeExe := filepath.Join(s.RootDir, "fake-proc-self-exe")
	err = os.Symlink("/usr/lib/snapd/snapd", fakeExe)
	c.Assert(err, IsNil)
	restore = apparmor.MockProcSelfExe(fakeExe)
	defer restore()

	// Create the snap-confine directory and put a file. Because the file name
	// matches the glob generated-* snapd will attempt to remove it but because
	// the directory is not writable, that operation will fail.
	err = os.MkdirAll(dirs.SnapConfineAppArmorDir, 0755)
	c.Assert(err, IsNil)
	f := filepath.Join(dirs.SnapConfineAppArmorDir, "generated-test")
	err = ioutil.WriteFile(f, []byte("spurious content"), 0644)
	c.Assert(err, IsNil)
	err = os.Chmod(dirs.SnapConfineAppArmorDir, 0555)
	c.Assert(err, IsNil)

	// Make the directory writable for cleanup.
	defer os.Chmod(dirs.SnapConfineAppArmorDir, 0755)

	// Setup generated policy for snap-confine.
	err = (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, ErrorMatches, `cannot synchronize snap-confine policy: remove .*/generated-test: permission denied`)

	// The policy directory was unchanged.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 1)

	// We didn't try to reload the policy.
	c.Assert(cmd.Calls(), HasLen, 0)
}

// snap-confine policy when overlay is not used.
func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyNoOverlay(c *C) {
	// Make it appear as if overlay was not used.
	restore := apparmor.MockIsRootWritableOverlay(func() (string, error) { return "", nil })
	defer restore()

	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()

	// Intercept interaction with apparmor_parser
	cmd := testutil.MockCommand(c, "apparmor_parser", "")
	defer cmd.Restore()

	// Setup generated policy for snap-confine.
	err := (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, IsNil)
	c.Assert(cmd.Calls(), HasLen, 0)

	// Because overlay is not used there are no local policy files but the
	// directory was created.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 0)

	// The policy was not reloaded.
	c.Assert(cmd.Calls(), HasLen, 0)
}

// Ensure that both names of the snap-confine apparmor profile are supported.

func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyWithOverlay1(c *C) {
	s.testSetupSnapConfineGeneratedPolicyWithOverlay(c, "usr.lib.snapd.snap-confine")
}

func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyWithOverlay2(c *C) {
	s.testSetupSnapConfineGeneratedPolicyWithOverlay(c, "usr.lib.snapd.snap-confine.real")
}

// snap-confine policy when overlay is used and snapd has not re-executed.
func (s *backendSuite) testSetupSnapConfineGeneratedPolicyWithOverlay(c *C, profileFname string) {
	// Make it appear as if overlay workaround was needed.
	restore := apparmor.MockIsRootWritableOverlay(func() (string, error) { return "/upper", nil })
	defer restore()
	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()
	// Intercept interaction with apparmor_parser
	cmd := testutil.MockCommand(c, "apparmor_parser", "")
	defer cmd.Restore()

	// Intercept the /proc/self/exe symlink and point it to the distribution
	// executable (the path doesn't matter as long as it is not from the
	// mounted core snap). This indicates that snapd is not re-executing
	// and that we should reload snap-confine profile.
	fakeExe := filepath.Join(s.RootDir, "fake-proc-self-exe")
	err := os.Symlink("/usr/lib/snapd/snapd", fakeExe)
	c.Assert(err, IsNil)
	restore = apparmor.MockProcSelfExe(fakeExe)
	defer restore()

	profilePath := filepath.Join(apparmor_sandbox.ConfDir, profileFname)

	// Create the directory where system apparmor profiles are stored and write
	// the system apparmor profile of snap-confine.
	c.Assert(os.MkdirAll(apparmor_sandbox.ConfDir, 0755), IsNil)
	c.Assert(ioutil.WriteFile(profilePath, []byte(""), 0644), IsNil)

	// Setup generated policy for snap-confine.
	err = (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, IsNil)

	// Because overlay is being used, we have the extra policy file.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 1)
	c.Assert(files[0].Name(), Equals, "overlay-root")
	c.Assert(files[0].Mode(), Equals, os.FileMode(0644))
	c.Assert(files[0].IsDir(), Equals, false)

	// The policy allows upperdir access.
	data, err := ioutil.ReadFile(filepath.Join(dirs.SnapConfineAppArmorDir, files[0].Name()))
	c.Assert(err, IsNil)
	c.Assert(string(data), testutil.Contains, "\"/upper/{,**/}\" r,")

	// The system apparmor profile of snap-confine was reloaded.
	c.Assert(cmd.Calls(), HasLen, 1)
	c.Assert(cmd.Calls(), DeepEquals, [][]string{{
		"apparmor_parser", "--replace",
		"--write-cache",
		"-O", "no-expr-simplify",
		"--cache-loc=" + apparmor_sandbox.SystemCacheDir,
		"--skip-read-cache",
		"--quiet",
		profilePath,
	}})
}

// snap-confine policy when overlay is used and snapd has re-executed.
func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyWithOverlayAndReExec(c *C) {
	// Make it appear as if overlay workaround was needed.
	restore := apparmor.MockIsRootWritableOverlay(func() (string, error) { return "/upper", nil })
	defer restore()

	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()

	// Intercept interaction with apparmor_parser
	cmd := testutil.MockCommand(c, "apparmor_parser", "")
	defer cmd.Restore()

	// Intercept the /proc/self/exe symlink and point it to the snapd from the
	// mounted core snap. This indicates that snapd has re-executed and
	// should not reload snap-confine policy.
	fakeExe := filepath.Join(s.RootDir, "fake-proc-self-exe")
	err := os.Symlink(filepath.Join(dirs.SnapMountDir, "/core/1234/usr/lib/snapd/snapd"), fakeExe)
	c.Assert(err, IsNil)
	restore = apparmor.MockProcSelfExe(fakeExe)
	defer restore()

	// Setup generated policy for snap-confine.
	err = (&apparmor.Backend{}).Initialize(ifacetest.DefaultInitializeOpts)
	c.Assert(err, IsNil)

	// Because overlay is being used, we have the extra policy file.
	files, err := ioutil.ReadDir(dirs.SnapConfineAppArmorDir)
	c.Assert(err, IsNil)
	c.Assert(files, HasLen, 1)
	c.Assert(files[0].Name(), Equals, "overlay-root")
	c.Assert(files[0].Mode(), Equals, os.FileMode(0644))
	c.Assert(files[0].IsDir(), Equals, false)

	// The policy allows upperdir access
	data, err := ioutil.ReadFile(filepath.Join(dirs.SnapConfineAppArmorDir, files[0].Name()))
	c.Assert(err, IsNil)
	c.Assert(string(data), testutil.Contains, "\"/upper/{,**/}\" r,")

	// The distribution policy was not reloaded because snap-confine executes
	// from core snap. This is handled separately by per-profile Setup.
	c.Assert(cmd.Calls(), HasLen, 0)
}

type nfsAndOverlaySnippetsScenario struct {
	opts           interfaces.ConfinementOptions
	overlaySnippet string
	nfsSnippet     string
}

var nfsAndOverlaySnippetsScenarios = []nfsAndOverlaySnippetsScenario{{
	// By default apparmor is enforcing mode.
	opts:           interfaces.ConfinementOptions{},
	overlaySnippet: `"/upper/{,**/}" r,`,
	nfsSnippet:     "network inet,\n  network inet6,",
}, {
	// DevMode switches apparmor to non-enforcing (complain) mode.
	opts:           interfaces.ConfinementOptions{DevMode: true},
	overlaySnippet: `"/upper/{,**/}" r,`,
	nfsSnippet:     "network inet,\n  network inet6,",
}, {
	// JailMode switches apparmor to enforcing mode even in the presence of DevMode.
	opts:           interfaces.ConfinementOptions{DevMode: true, JailMode: true},
	overlaySnippet: `"/upper/{,**/}" r,`,
	nfsSnippet:     "network inet,\n  network inet6,",
}, {
	// Classic confinement (without jailmode) uses apparmor in complain mode by default and ignores all snippets.
	opts:           interfaces.ConfinementOptions{Classic: true},
	overlaySnippet: "",
	nfsSnippet:     "",
}, {
	// Classic confinement in JailMode uses enforcing apparmor.
	opts: interfaces.ConfinementOptions{Classic: true, JailMode: true},
	// FIXME: logic in backend.addContent is wrong for this case
	//overlaySnippet: `"/upper/{,**/}" r,`,
	//nfsSnippet: "network inet,\n  network inet6,",
	overlaySnippet: "",
	nfsSnippet:     "",
}}

func (s *backendSuite) TestNFSAndOverlaySnippets(c *C) {
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()
	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return true, nil })
	defer restore()
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "/upper", nil })
	defer restore()
	s.Iface.AppArmorPermanentSlotCallback = func(spec *apparmor.Specification, slot *snap.SlotInfo) error {
		return nil
	}

	for _, scenario := range nfsAndOverlaySnippetsScenarios {
		snapInfo := s.InstallSnap(c, scenario.opts, "", ifacetest.SambaYamlV1, 1)
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		c.Check(profile, testutil.FileContains, scenario.overlaySnippet)
		c.Check(profile, testutil.FileContains, scenario.nfsSnippet)
		updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		c.Check(updateNSProfile, testutil.FileContains, scenario.overlaySnippet)
		s.RemoveSnap(c, snapInfo)
	}
}

var casperOverlaySnippetsScenarios = []nfsAndOverlaySnippetsScenario{{
	// By default apparmor is enforcing mode.
	opts:           interfaces.ConfinementOptions{},
	overlaySnippet: `"/upper/{,**/}" r,`,
}, {
	// DevMode switches apparmor to non-enforcing (complain) mode.
	opts:           interfaces.ConfinementOptions{DevMode: true},
	overlaySnippet: `"/upper/{,**/}" r,`,
}, {
	// JailMode switches apparmor to enforcing mode even in the presence of DevMode.
	opts:           interfaces.ConfinementOptions{DevMode: true, JailMode: true},
	overlaySnippet: `"/upper/{,**/}" r,`,
}, {
	// Classic confinement (without jailmode) uses apparmor in complain mode by default and ignores all snippets.
	opts:           interfaces.ConfinementOptions{Classic: true},
	overlaySnippet: "",
}, {
	// Classic confinement in JailMode uses enforcing apparmor.
	opts: interfaces.ConfinementOptions{Classic: true, JailMode: true},
	// FIXME: logic in backend.addContent is wrong for this case
	//overlaySnippet: `"/upper/{,**/}" r,`,
	overlaySnippet: "",
}}

func (s *backendSuite) TestCasperOverlaySnippets(c *C) {
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()
	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()
	restore = apparmor.MockIsRootWritableOverlay(func() (string, error) { return "/upper", nil })
	defer restore()
	s.Iface.AppArmorPermanentSlotCallback = func(spec *apparmor.Specification, slot *snap.SlotInfo) error {
		return nil
	}

	for _, scenario := range casperOverlaySnippetsScenarios {
		snapInfo := s.InstallSnap(c, scenario.opts, "", ifacetest.SambaYamlV1, 1)
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		c.Check(profile, testutil.FileContains, scenario.overlaySnippet)
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestProfileGlobs(c *C) {
	globs := apparmor.ProfileGlobs("foo")
	c.Assert(globs, DeepEquals, []string{"snap.foo.*", "snap-update-ns.foo"})
}

func (s *backendSuite) TestNsProfile(c *C) {
	c.Assert(apparmor.NsProfile("foo"), Equals, "snap-update-ns.foo")
}

func (s *backendSuite) TestSandboxFeatures(c *C) {
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()
	restore = apparmor.MockKernelFeatures(func() ([]string, error) { return []string{"foo", "bar"}, nil })
	defer restore()
	restore = apparmor.MockParserFeatures(func() ([]string, error) { return []string{"baz", "norf"}, nil })
	defer restore()

	c.Assert(s.Backend.SandboxFeatures(), DeepEquals, []string{"kernel:foo", "kernel:bar", "parser:baz", "parser:norf", "support-level:full", "policy:default"})
}

func (s *backendSuite) TestSandboxFeaturesPartial(c *C) {
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Partial)
	defer restore()
	restore = release.MockReleaseInfo(&release.OS{ID: "opensuse-tumbleweed"})
	defer restore()
	restore = osutil.MockKernelVersion("4.16.10-1-default")
	defer restore()
	restore = apparmor.MockKernelFeatures(func() ([]string, error) { return []string{"foo", "bar"}, nil })
	defer restore()
	restore = apparmor.MockParserFeatures(func() ([]string, error) { return []string{"baz", "norf"}, nil })
	defer restore()

	c.Assert(s.Backend.SandboxFeatures(), DeepEquals, []string{"kernel:foo", "kernel:bar", "parser:baz", "parser:norf", "support-level:partial", "policy:default"})

	restore = osutil.MockKernelVersion("4.14.1-default")
	defer restore()

	c.Assert(s.Backend.SandboxFeatures(), DeepEquals, []string{"kernel:foo", "kernel:bar", "parser:baz", "parser:norf", "support-level:partial", "policy:default"})
}

func (s *backendSuite) TestParallelInstanceSetupSnapUpdateNS(c *C) {
	dirs.SetRootDir(s.RootDir)

	const trivialSnapYaml = `name: some-snap
version: 1.0
apps:
  app:
    command: app-command
`
	snapInfo := snaptest.MockInfo(c, trivialSnapYaml, &snap.SideInfo{Revision: snap.R(222)})
	snapInfo.InstanceKey = "instance"

	s.InstallSnap(c, interfaces.ConfinementOptions{}, "some-snap_instance", trivialSnapYaml, 1)
	profileUpdateNS := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.some-snap_instance")
	c.Check(profileUpdateNS, testutil.FileContains, `profile snap-update-ns.some-snap_instance (`)
	c.Check(profileUpdateNS, testutil.FileContains, `
  # Allow parallel instance snap mount namespace adjustments
  mount options=(rw rbind) /snap/some-snap_instance/ -> /snap/some-snap/,
  mount options=(rw rbind) /var/snap/some-snap_instance/ -> /var/snap/some-snap/,
`)
}

func (s *backendSuite) TestPtraceTraceRule(c *C) {
	restoreTemplate := apparmor.MockTemplate("template\n###SNIPPETS###\n")
	defer restoreTemplate()
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()
	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()

	needle := `deny ptrace (trace),`
	for _, tc := range []struct {
		opts     interfaces.ConfinementOptions
		uses     bool
		suppress bool
		expected bool
	}{
		// strict, only suppress if suppress == true and uses == false
		{
			opts:     interfaces.ConfinementOptions{},
			uses:     false,
			suppress: false,
			expected: false,
		},
		{
			opts:     interfaces.ConfinementOptions{},
			uses:     false,
			suppress: true,
			expected: true,
		},
		{
			opts:     interfaces.ConfinementOptions{},
			uses:     true,
			suppress: false,
			expected: false,
		},
		{
			opts:     interfaces.ConfinementOptions{},
			uses:     true,
			suppress: true,
			expected: false,
		},
		// devmode, only suppress if suppress == true and uses == false
		{
			opts:     interfaces.ConfinementOptions{DevMode: true},
			uses:     false,
			suppress: false,
			expected: false,
		},
		{
			opts:     interfaces.ConfinementOptions{DevMode: true},
			uses:     false,
			suppress: true,
			expected: true,
		},
		{
			opts:     interfaces.ConfinementOptions{DevMode: true},
			uses:     true,
			suppress: false,
			expected: false,
		},
		{
			opts:     interfaces.ConfinementOptions{DevMode: true},
			uses:     true,
			suppress: true,
			expected: false,
		},
		// classic, never suppress
		{
			opts:     interfaces.ConfinementOptions{Classic: true},
			uses:     false,
			suppress: false,
			expected: false,
		},
		{
			opts:     interfaces.ConfinementOptions{Classic: true},
			uses:     false,
			suppress: true,
			expected: false,
		},
		{
			opts:     interfaces.ConfinementOptions{Classic: true},
			uses:     true,
			suppress: false,
			expected: false,
		},
		{
			opts:     interfaces.ConfinementOptions{Classic: true},
			uses:     true,
			suppress: true,
			expected: false,
		},
		// classic with jail, only suppress if suppress == true and uses == false
		{
			opts:     interfaces.ConfinementOptions{Classic: true, JailMode: true},
			uses:     false,
			suppress: false,
			expected: false,
		},
		{
			opts:     interfaces.ConfinementOptions{Classic: true, JailMode: true},
			uses:     false,
			suppress: true,
			expected: true,
		},
		{
			opts:     interfaces.ConfinementOptions{Classic: true, JailMode: true},
			uses:     true,
			suppress: false,
			expected: false,
		},
		{
			opts:     interfaces.ConfinementOptions{Classic: true, JailMode: true},
			uses:     true,
			suppress: true,
			expected: false,
		},
	} {
		s.Iface.AppArmorPermanentSlotCallback = func(spec *apparmor.Specification, slot *snap.SlotInfo) error {
			if tc.uses {
				spec.SetUsesPtraceTrace()
			}
			if tc.suppress {
				spec.SetSuppressPtraceTrace()
			}
			return nil
		}

		snapInfo := s.InstallSnap(c, tc.opts, "", ifacetest.SambaYamlV1, 1)
		s.parserCmd.ForgetCalls()

		err := s.Backend.Setup(snapInfo, tc.opts, s.Repo, s.meas)
		c.Assert(err, IsNil)

		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		data, err := ioutil.ReadFile(profile)
		c.Assert(err, IsNil)

		if tc.expected {
			c.Assert(string(data), testutil.Contains, needle)
		} else {
			c.Assert(string(data), Not(testutil.Contains), needle)
		}
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestHomeIxRule(c *C) {
	restoreTemplate := apparmor.MockTemplate("template\n###SNIPPETS###\nneedle rwkl###HOME_IX###,\n")
	defer restoreTemplate()
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()
	restore = apparmor.MockIsHomeUsingNFS(func() (bool, error) { return false, nil })
	defer restore()

	for _, tc := range []struct {
		opts     interfaces.ConfinementOptions
		suppress bool
		expected string
	}{
		{
			opts:     interfaces.ConfinementOptions{},
			suppress: true,
			expected: "needle rwkl,",
		},
		{
			opts:     interfaces.ConfinementOptions{},
			suppress: false,
			expected: "needle rwklix,",
		},
	} {
		s.Iface.AppArmorPermanentSlotCallback = func(spec *apparmor.Specification, slot *snap.SlotInfo) error {
			if tc.suppress {
				spec.SetSuppressHomeIx()
			}
			spec.AddSnippet("needle rwkl###HOME_IX###,")
			return nil
		}

		snapInfo := s.InstallSnap(c, tc.opts, "", ifacetest.SambaYamlV1, 1)
		profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		data, err := ioutil.ReadFile(profile)
		c.Assert(err, IsNil)

		c.Assert(string(data), testutil.Contains, tc.expected)
		s.RemoveSnap(c, snapInfo)
	}
}

func (s *backendSuite) TestSystemUsernamesPolicy(c *C) {
	restoreTemplate := apparmor.MockTemplate("template\n###SNIPPETS###\n")
	defer restoreTemplate()
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()

	snapYaml := `
name: app
version: 0.1
system-usernames:
  testid: shared
apps:
  cmd:
`

	snapInfo := s.InstallSnap(c, interfaces.ConfinementOptions{}, "", snapYaml, 1)
	profile := filepath.Join(dirs.SnapAppArmorDir, "snap.app.cmd")
	data, err := ioutil.ReadFile(profile)
	c.Assert(err, IsNil)
	c.Assert(string(data), testutil.Contains, "capability setuid,")
	c.Assert(string(data), testutil.Contains, "capability setgid,")
	c.Assert(string(data), testutil.Contains, "capability chown,")
	s.RemoveSnap(c, snapInfo)
}

func (s *backendSuite) TestNoSystemUsernamesPolicy(c *C) {
	restoreTemplate := apparmor.MockTemplate("template\n###SNIPPETS###\n")
	defer restoreTemplate()
	restore := apparmor_sandbox.MockLevel(apparmor_sandbox.Full)
	defer restore()

	snapYaml := `
name: app
version: 0.1
apps:
  cmd:
`

	snapInfo := s.InstallSnap(c, interfaces.ConfinementOptions{}, "", snapYaml, 1)
	profile := filepath.Join(dirs.SnapAppArmorDir, "snap.app.cmd")
	data, err := ioutil.ReadFile(profile)
	c.Assert(err, IsNil)
	c.Assert(string(data), Not(testutil.Contains), "capability setuid,")
	c.Assert(string(data), Not(testutil.Contains), "capability setgid,")
	c.Assert(string(data), Not(testutil.Contains), "capability chown,")
	s.RemoveSnap(c, snapInfo)
}

func (s *backendSuite) TestSetupManySmoke(c *C) {
	setupManyInterface, ok := s.Backend.(interfaces.SecurityBackendSetupMany)
	c.Assert(ok, Equals, true)
	c.Assert(setupManyInterface, NotNil)
}

func (s *backendSuite) TestInstallingSnapInPreseedMode(c *C) {
	// Intercept the /proc/self/exe symlink and point it to the snapd from the
	// mounted core snap. This indicates that snapd has re-executed and
	// should not reload snap-confine policy.
	fakeExe := filepath.Join(s.RootDir, "fake-proc-self-exe")
	err := os.Symlink(filepath.Join(dirs.SnapMountDir, "/core/1234/usr/lib/snapd/snapd"), fakeExe)
	c.Assert(err, IsNil)
	restore := apparmor.MockProcSelfExe(fakeExe)
	defer restore()

	aa, ok := s.Backend.(*apparmor.Backend)
	c.Assert(ok, Equals, true)

	opts := interfaces.SecurityBackendOptions{Preseed: true}
	c.Assert(aa.Initialize(&opts), IsNil)

	s.InstallSnap(c, interfaces.ConfinementOptions{}, "", ifacetest.SambaYamlV1, 1)

	updateNSProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
	profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
	// file called "snap.sambda.smbd" was created
	_, err = os.Stat(profile)
	c.Check(err, IsNil)
	// apparmor_parser was used to load that file
	c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
		{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "--skip-kernel-load", "--skip-read-cache", "--quiet", updateNSProfile, profile},
	})
}

func (s *backendSuite) TestSetupManyInPreseedMode(c *C) {
	aa, ok := s.Backend.(*apparmor.Backend)
	c.Assert(ok, Equals, true)

	opts := interfaces.SecurityBackendOptions{
		Preseed:      true,
		CoreSnapInfo: ifacetest.DefaultInitializeOpts.CoreSnapInfo,
	}
	c.Assert(aa.Initialize(&opts), IsNil)

	for _, opts := range testedConfinementOpts {
		snapInfo1 := s.InstallSnap(c, opts, "", ifacetest.SambaYamlV1, 1)
		snapInfo2 := s.InstallSnap(c, opts, "", ifacetest.SomeSnapYamlV1, 1)
		s.parserCmd.ForgetCalls()

		snap1nsProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.samba")
		snap1AAprofile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd")
		snap2nsProfile := filepath.Join(dirs.SnapAppArmorDir, "snap-update-ns.some-snap")
		snap2AAprofile := filepath.Join(dirs.SnapAppArmorDir, "snap.some-snap.someapp")

		// simulate outdated profiles by changing their data on the disk
		c.Assert(ioutil.WriteFile(snap1AAprofile, []byte("# an outdated profile"), 0644), IsNil)
		c.Assert(ioutil.WriteFile(snap2AAprofile, []byte("# an outdated profile"), 0644), IsNil)

		setupManyInterface, ok := s.Backend.(interfaces.SecurityBackendSetupMany)
		c.Assert(ok, Equals, true)
		err := setupManyInterface.SetupMany([]*snap.Info{snapInfo1, snapInfo2}, func(snapName string) interfaces.ConfinementOptions { return opts }, s.Repo, s.meas)
		c.Assert(err, IsNil)

		// expect two batch executions - one for changed profiles, second for unchanged profiles.
		c.Check(s.parserCmd.Calls(), DeepEquals, [][]string{
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "-j97", "--skip-kernel-load", "--skip-read-cache", "--quiet", snap1AAprofile, snap2AAprofile},
			{"apparmor_parser", "--replace", "--write-cache", "-O", "no-expr-simplify", fmt.Sprintf("--cache-loc=%s/var/cache/apparmor", s.RootDir), "-j97", "--skip-kernel-load", "--quiet", snap1nsProfile, snap2nsProfile},
		})
		s.RemoveSnap(c, snapInfo1)
		s.RemoveSnap(c, snapInfo2)
	}
}