File: tracking_test.go

package info (click to toggle)
snapd 2.73-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 81,460 kB
  • sloc: sh: 16,736; ansic: 16,652; python: 11,215; makefile: 1,966; exp: 190; awk: 58; xml: 22
file content (1120 lines) | stat: -rw-r--r-- 41,891 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
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 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 cgroup_test

import (
	"errors"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/godbus/dbus/v5"
	. "gopkg.in/check.v1"

	"github.com/snapcore/snapd/dbusutil"
	"github.com/snapcore/snapd/dbusutil/dbustest"
	"github.com/snapcore/snapd/dirs"
	"github.com/snapcore/snapd/features"
	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/sandbox/cgroup"
	"github.com/snapcore/snapd/systemd"
	"github.com/snapcore/snapd/testutil"
)

func enableFeatures(c *C, ff ...features.SnapdFeature) {
	c.Assert(os.MkdirAll(dirs.FeaturesDir, 0755), IsNil)
	for _, f := range ff {
		c.Assert(os.WriteFile(f.ControlFile(), nil, 0755), IsNil)
	}
}

type trackingSuite struct{}

var _ = Suite(&trackingSuite{})

func (s *trackingSuite) SetUpTest(c *C) {
	dirs.SetRootDir(c.MkDir())
	cgroup.MockVersion(cgroup.V2, nil)
}

func (s *trackingSuite) TearDownTest(c *C) {
	dirs.SetRootDir("")
}

// CreateTransientScopeForTracking always attempts to track, even when refresh app awareness flag is off.
func (s *trackingSuite) TestCreateTransientScopeForTrackingFeatureDisabled(c *C) {
	noDBus := func() (*dbus.Conn, error) {
		return nil, fmt.Errorf("dbus not available")
	}
	restore := dbusutil.MockConnections(noDBus, noDBus)
	defer restore()

	// The feature is disabled but we still track applications. The feature
	// flag is now only observed in side snapd snap manager, while considering
	// snap refreshes.
	c.Assert(features.RefreshAppAwareness.IsEnabled(), Equals, false)
	err := cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "cannot track application process")
}

// TestCreateTransientScopeForTrackingUUIDFailure tests the UUID error path
func (s *trackingSuite) TestCreateTransientScopeForTrackingUUIDFailure(c *C) {
	// Hand out stub connections to both the system and session bus.
	// Neither is really used here but they must appear to be available.
	restore := dbusutil.MockConnections(dbustest.StubConnection, dbustest.StubConnection)
	defer restore()

	restore = cgroup.MockRandomUUID(func() (string, error) {
		return "", errors.New("mocked uuid error")
	})
	defer restore()

	err := cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "mocked uuid error")
}

// CreateTransientScopeForTracking does stuff when refresh app awareness is on
func (s *trackingSuite) TestCreateTransientScopeForTrackingFeatureEnabled(c *C) {
	// Pretend that refresh app awareness is enabled
	enableFeatures(c, features.RefreshAppAwareness)
	c.Assert(features.RefreshAppAwareness.IsEnabled(), Equals, true)
	// Pretend we are a non-root user so that session bus is used.
	restore := cgroup.MockOsGetuid(12345)
	defer restore()
	// Pretend our PID is this value.
	restore = cgroup.MockOsGetpid(312123)
	defer restore()
	// Rig the random UUID generator to return this value.
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return uuid, nil
	})
	defer restore()
	signalChan := make(chan struct{})
	// Replace interactions with DBus so that only session bus is available and responds with our logic.
	conn, inject, err := dbustest.InjectableConnection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
		switch n {
		case 0:
			return []*dbus.Message{checkSystemdSignalSubscribe(c, msg)}, nil
		case 1:
			defer func() {
				close(signalChan)
			}()
			return []*dbus.Message{checkAndRespondToStartTransientUnit(c, msg, "snap.pkg.app-"+uuid+".scope", 312123)}, nil
		case 2:
			return []*dbus.Message{checkSystemSignalUnsubscribe(c, msg)}, nil
		}
		return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
	})
	go func() {
		<-signalChan
		inject(mockJobRemovedSignal("snap.pkg.app-"+uuid+".scope", "done"))
	}()
	c.Assert(err, IsNil)
	restore = dbusutil.MockOnlySessionBusAvailable(conn)
	defer restore()
	// Replace the cgroup analyzer function
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		return "/user.slice/user-12345.slice/user@12345.service/snap.pkg.app-" + uuid + ".scope", nil
	})
	defer restore()

	err = cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Check(err, IsNil)
}

func (s *trackingSuite) TestCreateTransientScopeForTrackingUnhappyNotRootGeneric(c *C) {
	// Pretend that refresh app awareness is enabled
	enableFeatures(c, features.RefreshAppAwareness)

	// Hand out stub connections to both the system and session bus.
	// Neither is really used here but they must appear to be available.
	restore := dbusutil.MockConnections(dbustest.StubConnection, dbustest.StubConnection)
	defer restore()

	// Pretend we are a non-root user so that session bus is used.
	restore = cgroup.MockOsGetuid(12345)
	defer restore()
	// Pretend our PID is this value.
	restore = cgroup.MockOsGetpid(312123)
	defer restore()

	// Rig the cgroup analyzer to return an answer not related to the snap name.
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		return "foo", nil
	})
	defer restore()

	// Pretend that attempting to create a transient scope fails with a canned error.
	restore = cgroup.MockDoCreateTransientScope(func(conn *dbus.Conn, unitName string, pid int) error {
		return fmt.Errorf("cannot create transient scope for testing")
	})
	defer restore()

	// Create a transient scope and see it fail according to how doCreateTransientScope is rigged.
	err := cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "cannot create transient scope for testing")

	// Calling StartTransientUnit fails with org.freedesktop.DBus.UnknownMethod error.
	// This is possible on old systemd or on deputy systemd.
	restore = cgroup.MockDoCreateTransientScope(func(conn *dbus.Conn, unitName string, pid int) error {
		return cgroup.ErrDBusUnknownMethod
	})
	defer restore()

	// Attempts to create a transient scope fail with a special error
	// indicating that we cannot track application process.
	err = cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "cannot track application process")

	// Calling StartTransientUnit fails with org.freedesktop.DBus.Spawn.ChildExited error.
	// This is possible where we try to activate socket activate session bus
	// but it's not available OR when we try to socket activate systemd --user.
	restore = cgroup.MockDoCreateTransientScope(func(conn *dbus.Conn, unitName string, pid int) error {
		return cgroup.ErrDBusSpawnChildExited
	})
	defer restore()

	// Attempts to create a transient scope fail with a special error
	// indicating that we cannot track application process and because we are
	// not root, we do not attempt to fall back to the system bus.
	err = cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "cannot track application process")
}

func (s *trackingSuite) TestCreateTransientScopeForTrackingUnhappyRootFallback(c *C) {
	// Pretend that refresh app awareness is enabled
	enableFeatures(c, features.RefreshAppAwareness)

	// Hand out stub connections to both the system and session bus.
	// Neither is really used here but they must appear to be available.
	restore := dbusutil.MockConnections(dbustest.StubConnection, dbustest.StubConnection)
	defer restore()

	// Pretend we are a root user so that we attempt to use the system bus as fallback.
	restore = cgroup.MockOsGetuid(0)
	defer restore()
	// Pretend our PID is this value.
	restore = cgroup.MockOsGetpid(312123)
	defer restore()

	// Rig the random UUID generator to return this value.
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return uuid, nil
	})
	defer restore()

	// Calling StartTransientUnit fails on the session and then works on the system bus.
	// This test emulates a root user falling back from the session bus to the system bus.
	n := 0
	restore = cgroup.MockDoCreateTransientScope(func(conn *dbus.Conn, unitName string, pid int) error {
		n++
		switch n {
		case 1:
			// On first try we fail. This is when we used the session bus/
			return cgroup.ErrDBusSpawnChildExited
		case 2:
			// On second try we succeed.
			return nil
		}
		panic("expected to call doCreateTransientScope at most twice")
	})
	defer restore()

	// Rig the cgroup analyzer to pretend that we got placed into the system slice.
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Assert(pid, Equals, 312123)
		return "/system.slice/snap.pkg.app-" + uuid + ".scope", nil
	})
	defer restore()

	// Attempts to create a transient scope fail with a special error
	// indicating that we cannot track application process and but because we were
	// root we attempted to fall back to the system bus.
	err := cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, IsNil)
}

func (s *trackingSuite) TestCreateTransientScopeForTrackingUnhappyRootFailedFallback(c *C) {
	// Pretend that refresh app awareness is enabled
	enableFeatures(c, features.RefreshAppAwareness)

	// Make it appear that session bus is there but system bus is not.
	noSystemBus := func() (*dbus.Conn, error) {
		return nil, fmt.Errorf("system bus is not available for testing")
	}
	restore := dbusutil.MockConnections(noSystemBus, dbustest.StubConnection)
	defer restore()

	// Pretend we are a root user so that we attempt to use the system bus as fallback.
	restore = cgroup.MockOsGetuid(0)
	defer restore()
	// Pretend our PID is this value.
	restore = cgroup.MockOsGetpid(312123)
	defer restore()

	// Rig the random UUID generator to return this value.
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return uuid, nil
	})
	defer restore()

	// Calling StartTransientUnit fails so that we try to use the system bus as fallback.
	restore = cgroup.MockDoCreateTransientScope(func(conn *dbus.Conn, unitName string, pid int) error {
		return cgroup.ErrDBusSpawnChildExited
	})
	defer restore()

	// Rig the cgroup analyzer to return an answer not related to the snap name.
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		return "foo", nil
	})
	defer restore()

	// Attempts to create a transient scope fail with a special error
	// indicating that we cannot track application process.
	err := cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "cannot track application process")
}

func (s *trackingSuite) TestCreateTransientScopeForTrackingUnhappyNoDBus(c *C) {
	// Pretend that refresh app awareness is enabled
	enableFeatures(c, features.RefreshAppAwareness)

	// Make it appear that DBus is entirely unavailable.
	noBus := func() (*dbus.Conn, error) {
		return nil, fmt.Errorf("dbus is not available for testing")
	}
	restore := dbusutil.MockConnections(noBus, noBus)
	defer restore()

	// Pretend we are a root user so that we attempt to use the system bus as fallback.
	restore = cgroup.MockOsGetuid(0)
	defer restore()
	// Pretend our PID is this value.
	restore = cgroup.MockOsGetpid(312123)
	defer restore()

	// Rig the random UUID generator to return this value.
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return uuid, nil
	})
	defer restore()

	// Calling StartTransientUnit is not attempted without a DBus connection.
	restore = cgroup.MockDoCreateTransientScope(func(conn *dbus.Conn, unitName string, pid int) error {
		c.Error("test sequence violated")
		return fmt.Errorf("test was not expected to create a transient scope")
	})
	defer restore()

	// Disable the cgroup analyzer function as we don't expect it to be used in this test.
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Error("test sequence violated")
		return "", fmt.Errorf("test was not expected to measure process path in the tracking cgroup")
	})
	defer restore()

	// Attempts to create a transient scope fail with a special error
	// indicating that we cannot track application process.
	err := cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "cannot track application process")
}

func (s *trackingSuite) TestCreateTransientScopeForTrackingSilentlyFails(c *C) {
	// Pretend that refresh app awareness is enabled
	enableFeatures(c, features.RefreshAppAwareness)

	// Hand out stub connections to both the system and session bus.
	// Neither is really used here but they must appear to be available.
	restore := dbusutil.MockConnections(dbustest.StubConnection, dbustest.StubConnection)
	defer restore()

	// Pretend we are a non-root user.
	restore = cgroup.MockOsGetuid(12345)
	defer restore()
	// Pretend our PID is this value.
	restore = cgroup.MockOsGetpid(312123)
	defer restore()

	// Rig the random UUID generator to return this value.
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return uuid, nil
	})
	defer restore()

	// Calling StartTransientUnit succeeds but in reality does not move our
	// process to the new cgroup hierarchy. This can happen when systemd
	// version is < 238 and when the calling user is in a hierarchy that is
	// owned by another user. One example is a user logging in remotely over
	// ssh.
	restore = cgroup.MockDoCreateTransientScope(func(conn *dbus.Conn, unitName string, pid int) error {
		return nil
	})
	defer restore()

	// Rig the cgroup analyzer to pretend that we are not placed in a snap-related slice.
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Assert(pid, Equals, 312123)
		return "/system.slice/foo.service", nil
	})
	defer restore()

	// Attempts to create a transient scope fail with a special error
	// indicating that we cannot track application process even though
	// the DBus call has returned no error.
	err := cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "cannot track application process")
}

func (s *trackingSuite) TestCreateTransientScopeForRootOnSystemBus(c *C) {
	// Pretend that refresh app awareness is enabled
	enableFeatures(c, features.RefreshAppAwareness)

	// Hand out stub connections to both the system and session bus. Remember
	// the identity of the system bus to that we can verify access later.
	// Neither is really used here but they must appear to be available.
	systemBus, err := dbustest.StubConnection()
	c.Assert(err, IsNil)
	restore := dbusutil.MockConnections(func() (*dbus.Conn, error) { return systemBus, nil }, dbustest.StubConnection)
	defer restore()

	// Pretend we are a root user. All hooks execute as root.
	restore = cgroup.MockOsGetuid(0)
	defer restore()

	// Pretend our PID is this value.
	restore = cgroup.MockOsGetpid(312123)
	defer restore()

	// Rig the random UUID generator to return this value.
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return uuid, nil
	})
	defer restore()

	// Pretend that attempting to create a transient scope succeeds.  Measure
	// the bus used and the unit name provided by the caller.  Note that the
	// call was made on the system bus, as requested by TrackingOptions below.
	restore = cgroup.MockDoCreateTransientScope(func(conn *dbus.Conn, unitName string, pid int) error {
		c.Assert(conn, Equals, systemBus)
		c.Assert(unitName, Equals, "snap.pkg.app-"+uuid+".scope")
		return nil
	})
	defer restore()

	// Rig the cgroup analyzer to indicate successful tracking.
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		return "snap.pkg.app-" + uuid + ".scope", nil
	})
	defer restore()

	// Create a transient scope and see it succeed.
	err = cgroup.CreateTransientScopeForTracking("snap.pkg.app", &cgroup.TrackingOptions{AllowSessionBus: false})
	c.Assert(err, IsNil)
}

type testTransientScopeConfirm struct {
	uuid        string
	securityTag string
	confirmUnit string
	confirmErr  error
	expectedErr string
}

func (s *trackingSuite) testCreateTransientScopeConfirm(c *C, tc testTransientScopeConfirm) {
	enableFeatures(c, features.RefreshAppAwareness)

	logBuf, restore := logger.MockLogger()
	defer restore()
	os.Setenv("SNAPD_DEBUG", "true")
	defer os.Unsetenv("SNAPD_DEBUG")
	restore = cgroup.MockOsGetuid(12345)
	defer restore()
	restore = cgroup.MockOsGetpid(312123)
	defer restore()
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return tc.uuid, nil
	})
	defer restore()
	sessionBus, err := dbustest.Connection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
		// we are not expecting any dbus traffic
		return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
	})

	c.Assert(err, IsNil)
	restore = dbusutil.MockOnlySessionBusAvailable(sessionBus)
	defer restore()
	restore = cgroup.MockDoCreateTransientScope(func(conn *dbus.Conn, unitName string, pid int) error {
		escapedTag, err := systemd.SecurityTagToUnitName(tc.securityTag)
		c.Assert(err, IsNil)

		c.Assert(conn, Equals, sessionBus)
		c.Assert(unitName, Equals, escapedTag+"-"+tc.uuid+".scope")
		return nil
	})
	defer restore()

	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		return tc.confirmUnit, tc.confirmErr
	})
	defer restore()

	// creating transient scope fails when systemd reports that the job failed
	err = cgroup.CreateTransientScopeForTracking(tc.securityTag, nil)
	if tc.expectedErr == "" {
		c.Assert(err, IsNil)
	} else {
		c.Assert(err, ErrorMatches, tc.expectedErr)
		if tc.confirmErr == nil {
			c.Check(logBuf.String(), testutil.Contains, "systemd could not associate process 312123 with transient scope")
		}
	}
}

func (s *trackingSuite) TestCreateTransientScopeConfirmHappy(c *C) {
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	s.testCreateTransientScopeConfirm(c, testTransientScopeConfirm{
		securityTag: "snap.pkg.app",
		uuid:        uuid,
		confirmUnit: "foo/bar/baz/snap.pkg.app-" + uuid + ".scope",
	})
}

func (s *trackingSuite) TestCreateTransientScopeConfirmEscaped(c *C) {
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	s.testCreateTransientScopeConfirm(c, testTransientScopeConfirm{
		securityTag: "snap.pkg+comp.hook.install",
		uuid:        uuid,
		confirmUnit: "foo/bar/baz/snap.pkg\\x2bcomp.hook.install-" + uuid + ".scope",
	})
}

func (s *trackingSuite) TestCreateTransientScopeConfirmOtherUnit(c *C) {
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	s.testCreateTransientScopeConfirm(c, testTransientScopeConfirm{
		securityTag: "snap.pkg.app",
		uuid:        uuid,
		confirmUnit: "foo/bar/baz/other-unit.scope",
		expectedErr: cgroup.ErrCannotTrackProcess.Error(),
	})
}

func (s *trackingSuite) TestCreateTransientScopeConfirmCheckError(c *C) {
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	s.testCreateTransientScopeConfirm(c, testTransientScopeConfirm{
		securityTag: "snap.pkg.app",
		uuid:        uuid,
		confirmErr:  fmt.Errorf("mock failure"),
		expectedErr: "mock failure",
	})
}

func (s *trackingSuite) TestCreateTransientScopeConfirmInvalidTag(c *C) {
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	s.testCreateTransientScopeConfirm(c, testTransientScopeConfirm{
		securityTag: "snap.pkg/comp.hook.install",
		uuid:        uuid,
		confirmErr:  fmt.Errorf("invalid character in security tag: '/'"),
		expectedErr: "invalid character in security tag: '/'",
	})
}

const systemdSignalMatch = `type='signal',interface='org.freedesktop.systemd1.Manager',member='JobRemoved'`

func checkSystemdSignalSubscribe(c *C, msg *dbus.Message) *dbus.Message {
	var rule string
	dbus.Store(msg.Body, &rule)
	c.Check(rule, Equals, systemdSignalMatch)
	return &dbus.Message{
		Type: dbus.TypeMethodReply,
		Headers: map[dbus.HeaderField]dbus.Variant{
			dbus.FieldReplySerial: dbus.MakeVariant(msg.Serial()),
			dbus.FieldSender:      dbus.MakeVariant(":1"), // This does not matter.
		},
	}
}

func checkSystemSignalUnsubscribe(c *C, msg *dbus.Message) *dbus.Message {
	var rule string
	dbus.Store(msg.Body, &rule)
	c.Check(rule, Equals, systemdSignalMatch)
	return &dbus.Message{
		Type: dbus.TypeMethodReply,
		Headers: map[dbus.HeaderField]dbus.Variant{
			dbus.FieldReplySerial: dbus.MakeVariant(msg.Serial()),
			dbus.FieldSender:      dbus.MakeVariant(":1"), // This does not matter.
		},
	}
}

func checkAndRespondToStartTransientUnit(c *C, msg *dbus.Message, scopeName string, pid int) *dbus.Message {
	// XXX: Those types might live in a package somewhere
	type Property struct {
		Name  string
		Value any
	}
	type Unit struct {
		Name  string
		Props []Property
	}
	// Signature of StartTransientUnit, string, string, array of Property and array of Unit (see above).
	requestSig := dbus.SignatureOf("", "", []Property{}, []Unit{})

	c.Assert(msg.Type, Equals, dbus.TypeMethodCall)
	c.Check(msg.Flags, Equals, dbus.Flags(0))
	c.Check(msg.Headers, DeepEquals, map[dbus.HeaderField]dbus.Variant{
		dbus.FieldDestination: dbus.MakeVariant("org.freedesktop.systemd1"),
		dbus.FieldPath:        dbus.MakeVariant(dbus.ObjectPath("/org/freedesktop/systemd1")),
		dbus.FieldInterface:   dbus.MakeVariant("org.freedesktop.systemd1.Manager"),
		dbus.FieldMember:      dbus.MakeVariant("StartTransientUnit"),
		dbus.FieldSignature:   dbus.MakeVariant(requestSig),
	})
	c.Check(msg.Body, DeepEquals, []any{
		scopeName,
		"fail",
		[][]any{
			{"PIDs", dbus.MakeVariant([]uint32{uint32(pid)})},
		},
		[][]any{},
	})

	responseSig := dbus.SignatureOf(dbus.ObjectPath(""))
	return &dbus.Message{
		Type: dbus.TypeMethodReply,
		Headers: map[dbus.HeaderField]dbus.Variant{
			dbus.FieldReplySerial: dbus.MakeVariant(msg.Serial()),
			dbus.FieldSender:      dbus.MakeVariant(":1"), // This does not matter.
			// dbus.FieldDestination is provided automatically by DBus test helper.
			dbus.FieldSignature: dbus.MakeVariant(responseSig),
		},
		// The object path returned in the body is not used by snap run yet.
		Body: []any{dbus.ObjectPath("/org/freedesktop/systemd1/job/1462")},
	}
}

func checkAndFailToStartTransientUnit(c *C, msg *dbus.Message, errMsg string) *dbus.Message {
	c.Assert(msg.Type, Equals, dbus.TypeMethodCall)
	// ignore the message and just produce an error response
	return &dbus.Message{
		Type: dbus.TypeError,
		Headers: map[dbus.HeaderField]dbus.Variant{
			dbus.FieldReplySerial: dbus.MakeVariant(msg.Serial()),
			dbus.FieldSender:      dbus.MakeVariant(":1"), // This does not matter.
			// dbus.FieldDestination is provided automatically by DBus test helper.
			dbus.FieldErrorName: dbus.MakeVariant(errMsg),
		},
	}
}

func mockJobRemovedSignal(unit, result string) *dbus.Message {
	return &dbus.Message{
		Type: dbus.TypeSignal,
		Headers: map[dbus.HeaderField]dbus.Variant{
			dbus.FieldSender:    dbus.MakeVariant(":1"), // This does not matter.
			dbus.FieldPath:      dbus.MakeVariant(dbus.ObjectPath("/org/freedesktop/systemd1")),
			dbus.FieldInterface: dbus.MakeVariant("org.freedesktop.systemd1.Manager"),
			dbus.FieldMember:    dbus.MakeVariant("JobRemoved"),
			dbus.FieldSignature: dbus.MakeVariant(
				dbus.SignatureOf(uint32(0), dbus.ObjectPath(""), "", "")),
		},
		Body: []any{
			uint32(1),
			dbus.ObjectPath("/org/freedesktop/systemd1/job/1462"),
			unit,
			result,
		},
	}
}

func (s *trackingSuite) TestCreateTransientScopeHappyWithRetriedCheckCgroupV1(c *C) {
	enableFeatures(c, features.RefreshAppAwareness)

	restore := cgroup.MockVersion(cgroup.V1, nil)
	defer restore()
	logBuf, restore := logger.MockLogger()
	defer restore()
	os.Setenv("SNAPD_DEBUG", "true")
	defer os.Unsetenv("SNAPD_DEBUG")
	restore = cgroup.MockOsGetuid(12345)
	defer restore()
	restore = cgroup.MockOsGetpid(312123)
	defer restore()
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return uuid, nil
	})
	defer restore()
	sessionBus, err := dbustest.Connection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
		c.Logf("%v got msg: %v", n, msg)
		switch n {
		case 0:
			return []*dbus.Message{checkAndRespondToStartTransientUnit(c, msg, "snap.pkg.app-"+uuid+".scope", 312123)}, nil
			// CreateTransientScopeForTracking is called twice in the test
		case 1:
			return []*dbus.Message{checkAndRespondToStartTransientUnit(c, msg, "snap.pkg.app-"+uuid+".scope", 312123)}, nil
		}
		return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
	})

	c.Assert(err, IsNil)
	restore = dbusutil.MockOnlySessionBusAvailable(sessionBus)
	defer restore()

	pathInTrackingCgroupCallsToSuccess := 5
	pathInTrackingCgroupCalls := 0
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		pathInTrackingCgroupCalls++
		if pathInTrackingCgroupCalls < pathInTrackingCgroupCallsToSuccess {
			return "vte-spawn-1234-1234-1234.scope", nil
		}
		return "snap.pkg.app-" + uuid + ".scope", nil
	})
	defer restore()

	// creating transient scope succeeds even if check is retried
	err = cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, IsNil)
	c.Check(pathInTrackingCgroupCalls, Equals, 5)
	c.Check(logBuf.String(), Not(testutil.Contains), "systemd could not associate process 312123 with transient scope")

	// try again, but exhaust the limit if attempts which should be set to 100
	pathInTrackingCgroupCalls = 0
	pathInTrackingCgroupCallsToSuccess = 99999
	logBuf.Reset()
	err = cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "cannot track application process")
	c.Check(pathInTrackingCgroupCalls, Equals, 100)
	c.Check(logBuf.String(), testutil.Contains, "systemd could not associate process 312123 with transient scope")
}

func (s *trackingSuite) TestCreateTransientScopeUnhappyJobFailed(c *C) {
	enableFeatures(c, features.RefreshAppAwareness)

	restore := cgroup.MockOsGetuid(12345)
	defer restore()
	restore = cgroup.MockOsGetpid(312123)
	defer restore()
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return uuid, nil
	})
	defer restore()
	signalChan := make(chan struct{})
	sessionBus, inject, err := dbustest.InjectableConnection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
		c.Logf("dbus message %v", n)
		switch n {
		case 0:
			return []*dbus.Message{checkSystemdSignalSubscribe(c, msg)}, nil
		case 1:
			defer func() {
				close(signalChan)
			}()
			return []*dbus.Message{checkAndRespondToStartTransientUnit(c, msg, "snap.pkg.app-"+uuid+".scope", 312123)}, nil
		case 2:
			return []*dbus.Message{checkSystemSignalUnsubscribe(c, msg)}, nil
		}
		return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
	})
	go func() {
		<-signalChan
		inject(mockJobRemovedSignal("snap.pkg.app-"+uuid+".scope", "failed"))
	}()

	c.Assert(err, IsNil)
	restore = dbusutil.MockOnlySessionBusAvailable(sessionBus)
	defer restore()

	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Fatal("unexpected call")
		return "", fmt.Errorf("unexpected call")
	})
	defer restore()

	// creating transient scope fails when systemd reports that the job failed
	err = cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "transient scope could not be started, job /org/freedesktop/systemd1/job/1462 finished with result failed")
}

func (s *trackingSuite) TestCreateTransientScopeUnhappyJobTimeout(c *C) {
	enableFeatures(c, features.RefreshAppAwareness)

	restore := cgroup.MockOsGetuid(12345)
	defer restore()
	restore = cgroup.MockOsGetpid(312123)
	defer restore()
	uuid := "cc98cd01-6a25-46bd-b71b-82069b71b770"
	restore = cgroup.MockRandomUUID(func() (string, error) {
		return uuid, nil
	})
	defer restore()
	restore = cgroup.MockCreateScopeJobTimeout(100 * time.Millisecond)
	defer restore()
	// mock a connection, but without support for injecting signal messages
	sessionBus, err := dbustest.Connection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
		c.Logf("dbus message %v", n)
		switch n {
		case 0:
			return []*dbus.Message{checkSystemdSignalSubscribe(c, msg)}, nil
		case 1:
			return []*dbus.Message{checkAndRespondToStartTransientUnit(c, msg, "snap.pkg.app-"+uuid+".scope", 312123)}, nil
		case 2:
			return []*dbus.Message{checkSystemSignalUnsubscribe(c, msg)}, nil
		}
		return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
	})

	c.Assert(err, IsNil)
	restore = dbusutil.MockOnlySessionBusAvailable(sessionBus)
	defer restore()

	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Fatal("unexpected call")
		return "", fmt.Errorf("unexpected call")
	})
	defer restore()

	// creating transient scope fails when systemd reports that the job failed
	err = cgroup.CreateTransientScopeForTracking("snap.pkg.app", nil)
	c.Assert(err, ErrorMatches, "transient scope not created in 100ms")
}

func (s *trackingSuite) TestDoCreateTransientScopeHappyCgroupV2(c *C) {
	signalChan := make(chan struct{})
	conn, inject, err := dbustest.InjectableConnection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
		c.Logf("message: %v", msg)
		switch n {
		case 0:
			return []*dbus.Message{checkSystemdSignalSubscribe(c, msg)}, nil
		case 1:
			defer func() {
				close(signalChan)
			}()
			return []*dbus.Message{checkAndRespondToStartTransientUnit(c, msg, "foo.scope", 312123)}, nil
		case 2:
			return []*dbus.Message{checkSystemSignalUnsubscribe(c, msg)}, nil
		}
		return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
	})
	go func() {
		<-signalChan
		inject(mockJobRemovedSignal("foo.scope", "done"))
	}()

	c.Assert(err, IsNil)
	defer conn.Close()
	err = cgroup.DoCreateTransientScope(conn, "foo.scope", 312123)
	c.Assert(err, IsNil)
}

func (s *trackingSuite) TestDoCreateTransientScopeHappyCgroupV1(c *C) {
	restore := cgroup.MockVersion(cgroup.V1, nil)
	defer restore()

	conn, err := dbustest.Connection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
		c.Logf("message: %v", msg)
		switch n {
		case 0:
			return []*dbus.Message{checkAndRespondToStartTransientUnit(c, msg, "foo.scope", 312123)}, nil
		}
		return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
	})
	c.Assert(err, IsNil)
	defer conn.Close()
	err = cgroup.DoCreateTransientScope(conn, "foo.scope", 312123)
	c.Assert(err, IsNil)
}

func (s *trackingSuite) TestDoCreateTransientScopeForwardedErrors(c *C) {
	// Certain errors are forwarded and handled in the logic calling into
	// DoCreateTransientScope. Those are tested here.
	for _, t := range []struct {
		dbusError, msg string
	}{
		{"org.freedesktop.DBus.Error.NameHasNoOwner", "dbus name has no owner"},
		{"org.freedesktop.DBus.Error.UnknownMethod", "unknown dbus object method"},
		{"org.freedesktop.DBus.Error.Spawn.ChildExited", "dbus spawned child process exited"},
	} {
		conn, err := dbustest.Connection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
			switch n {
			case 0:
				return []*dbus.Message{checkSystemdSignalSubscribe(c, msg)}, nil
			case 1:
				return []*dbus.Message{checkAndFailToStartTransientUnit(c, msg, t.dbusError)}, nil
			case 2:
				return []*dbus.Message{checkSystemSignalUnsubscribe(c, msg)}, nil
			}
			return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
		})
		c.Assert(err, IsNil)
		defer conn.Close()
		err = cgroup.DoCreateTransientScope(conn, "foo.scope", 312123)
		c.Assert(strings.HasSuffix(err.Error(), fmt.Sprintf(" [%s]", t.dbusError)), Equals, true, Commentf("%q ~ %s", err, t.dbusError))
		c.Check(err, ErrorMatches, t.msg+" .*")
	}
}

func (s *trackingSuite) TestDoCreateTransientScopeClashingScopeName(c *C) {
	// In case our UUID algorithm is bad and systemd reports that an unit with
	// identical name already exists, we provide a special error handler for that.
	errMsg := "org.freedesktop.systemd1.UnitExists"
	conn, err := dbustest.Connection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
		switch n {
		case 0:
			return []*dbus.Message{checkSystemdSignalSubscribe(c, msg)}, nil
		case 1:
			return []*dbus.Message{checkAndFailToStartTransientUnit(c, msg, errMsg)}, nil
		case 2:
			return []*dbus.Message{checkSystemSignalUnsubscribe(c, msg)}, nil
		}
		return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
	})
	c.Assert(err, IsNil)
	defer conn.Close()
	err = cgroup.DoCreateTransientScope(conn, "foo.scope", 312123)
	c.Assert(err, ErrorMatches, "cannot create transient scope: scope .* clashed: .*")
}

func (s *trackingSuite) TestDoCreateTransientScopeOtherDBusErrors(c *C) {
	// Other DBus errors are not special-cased and cause a generic failure handler.
	errMsg := "org.example.BadHairDay"
	conn, err := dbustest.Connection(func(msg *dbus.Message, n int) ([]*dbus.Message, error) {
		switch n {
		case 0:
			return []*dbus.Message{checkSystemdSignalSubscribe(c, msg)}, nil
		case 1:
			return []*dbus.Message{checkAndFailToStartTransientUnit(c, msg, errMsg)}, nil
		case 2:
			return []*dbus.Message{checkSystemSignalUnsubscribe(c, msg)}, nil
		}
		return nil, fmt.Errorf("unexpected message #%d: %s", n, msg)
	})
	c.Assert(err, IsNil)
	defer conn.Close()
	err = cgroup.DoCreateTransientScope(conn, "foo.scope", 312123)
	c.Assert(err, ErrorMatches, `cannot create transient scope: DBus error "org.example.BadHairDay": \[\]`)
}

func (s *trackingSuite) TestSessionOrMaybeSystemBusTotalFailureForRoot(c *C) {
	system := func() (*dbus.Conn, error) {
		return nil, fmt.Errorf("system bus unavailable for testing")
	}
	session := func() (*dbus.Conn, error) {
		return nil, fmt.Errorf("session bus unavailable for testing")
	}
	restore := dbusutil.MockConnections(system, session)
	defer restore()
	logBuf, restore := logger.MockLogger()
	defer restore()
	os.Setenv("SNAPD_DEBUG", "true")
	defer os.Unsetenv("SNAPD_DEBUG")

	uid := 0
	isSession, conn, err := cgroup.SessionOrMaybeSystemBus(uid)
	c.Assert(err, ErrorMatches, "system bus unavailable for testing")
	c.Check(conn, IsNil)
	c.Check(isSession, Equals, false)
	c.Check(logBuf.String(), testutil.Contains, "DEBUG: session bus is not available: session bus unavailable for testing\n")
	c.Check(logBuf.String(), testutil.Contains, "DEBUG: falling back to system bus\n")
	c.Check(logBuf.String(), testutil.Contains, "DEBUG: system bus is not available: system bus unavailable for testing\n")
}

func (s *trackingSuite) TestSessionOrMaybeSystemBusFallbackForRoot(c *C) {
	system := func() (*dbus.Conn, error) {
		return dbustest.StubConnection()
	}
	session := func() (*dbus.Conn, error) {
		return nil, fmt.Errorf("session bus unavailable for testing")
	}
	restore := dbusutil.MockConnections(system, session)
	defer restore()
	logBuf, restore := logger.MockLogger()
	defer restore()
	os.Setenv("SNAPD_DEBUG", "true")
	defer os.Unsetenv("SNAPD_DEBUG")

	uid := 0
	isSession, conn, err := cgroup.SessionOrMaybeSystemBus(uid)
	c.Assert(err, IsNil)
	conn.Close()
	c.Check(isSession, Equals, false)
	c.Check(logBuf.String(), testutil.Contains, "DEBUG: session bus is not available: session bus unavailable for testing\n")
	c.Check(logBuf.String(), testutil.Contains, "DEBUG: falling back to system bus\n")
	c.Check(logBuf.String(), testutil.Contains, "DEBUG: using system bus now, session bus was not available\n")
}

func (s *trackingSuite) TestSessionOrMaybeSystemBusNonRootSessionFailure(c *C) {
	system := func() (*dbus.Conn, error) {
		return dbustest.StubConnection()
	}
	session := func() (*dbus.Conn, error) {
		return nil, fmt.Errorf("session bus unavailable for testing")
	}
	restore := dbusutil.MockConnections(system, session)
	defer restore()
	logBuf, restore := logger.MockLogger()
	defer restore()
	os.Setenv("SNAPD_DEBUG", "true")
	defer os.Unsetenv("SNAPD_DEBUG")

	uid := 12345
	isSession, conn, err := cgroup.SessionOrMaybeSystemBus(uid)
	c.Assert(err, ErrorMatches, "session bus unavailable for testing")
	c.Check(conn, IsNil)
	c.Check(isSession, Equals, false)
	c.Check(logBuf.String(), testutil.Contains, "DEBUG: session bus is not available: session bus unavailable for testing\n")
}

func (s *trackingSuite) TestConfirmSystemdServiceTrackingHappy(c *C) {
	// Pretend our PID is this value.
	restore := cgroup.MockOsGetpid(312123)
	defer restore()
	// Replace the cgroup analyzer function
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Assert(pid, Equals, 312123)
		return "/user.slice/user-12345.slice/user@12345.service/snap.pkg.app.service", nil
	})
	defer restore()

	// With the cgroup path faked as above, we are being tracked as the systemd
	// service so no error is reported.
	err := cgroup.ConfirmSystemdServiceTracking("snap.pkg.app")
	c.Assert(err, IsNil)
}

func (s *trackingSuite) TestConfirmSystemdServiceTrackingSad(c *C) {
	// Pretend our PID is this value.
	restore := cgroup.MockOsGetpid(312123)
	defer restore()
	// Replace the cgroup analyzer function
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Assert(pid, Equals, 312123)
		// Tracking path of a gnome terminal helper process. Meant to illustrate a tracking but not related to a snap application.
		return "user.slice/user-12345.slice/user@12345.service/apps.slice/apps-org.gnome.Terminal.slice/vte-spawn-e640104a-cddf-4bd8-ba4b-2c1baf0270c3.scope", nil
	})
	defer restore()

	// With the cgroup path faked as above, tracking is not effective.
	err := cgroup.ConfirmSystemdServiceTracking("snap.pkg.app")
	c.Assert(err, Equals, cgroup.ErrCannotTrackProcess)
}

func (s *trackingSuite) TestConfirmSystemdAppTrackingHappy(c *C) {
	// Pretend our PID is this value.
	restore := cgroup.MockOsGetpid(312123)
	defer restore()
	// Replace the cgroup analyzer function
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Assert(pid, Equals, 312123)
		return "user.slice/user-12345.slice/user@12345.service/apps.slice/snap.pkg.app-ae6d0825-dacd-454c-baec-67289f067c28.scope", nil
	})
	defer restore()

	// With the cgroup path faked as above, we are being tracked so no error is reported.
	err := cgroup.ConfirmSystemdAppTracking("snap.pkg.app")
	c.Assert(err, IsNil)
}

func (s *trackingSuite) TestConfirmSystemdAppTrackingEscaped(c *C) {
	// Pretend our PID is this value.
	restore := cgroup.MockOsGetpid(312123)
	defer restore()
	// Replace the cgroup analyzer function
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Assert(pid, Equals, 312123)
		return "user.slice/user-12345.slice/user@12345.service/apps.slice/snap.pkg\\x2bcomp.hook.install-ae6d0825-dacd-454c-baec-67289f067c28.scope", nil
	})
	defer restore()

	// With the cgroup path faked as above, we are being tracked so no error is reported.
	err := cgroup.ConfirmSystemdAppTracking("snap.pkg+comp.hook.install")
	c.Assert(err, IsNil)
}

func (s *trackingSuite) TestConfirmSystemdAppTrackingInvalidTag(c *C) {
	restore := cgroup.MockOsGetpid(312123)
	defer restore()

	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Fatalf("unexpected call")
		return "", nil
	})
	defer restore()

	err := cgroup.ConfirmSystemdAppTracking("snap.pkg/comp.hook.install")
	c.Assert(err, ErrorMatches, "invalid character in security tag: '/'")
}

func (s *trackingSuite) TestConfirmSystemdAppTrackingSad1(c *C) {
	// Pretend our PID is this value.
	restore := cgroup.MockOsGetpid(312123)
	defer restore()
	// Replace the cgroup analyzer function
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Assert(pid, Equals, 312123)
		// mark as being tracked as a service
		return "/user.slice/user-12345.slice/user@12345.service/snap.pkg.app.service", nil
	})
	defer restore()

	// With the cgroup path faked as above, tracking is not effective.
	err := cgroup.ConfirmSystemdAppTracking("snap.pkg.app")
	c.Assert(err, Equals, cgroup.ErrCannotTrackProcess)
}

func (s *trackingSuite) TestConfirmSystemdAppTrackingSad2(c *C) {
	// Pretend our PID is this value.
	restore := cgroup.MockOsGetpid(312123)
	defer restore()
	// Replace the cgroup analyzer function
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Assert(pid, Equals, 312123)
		// Tracking path of a gnome terminal helper process. Meant to illustrate a tracking but not related to a snap application.
		return "user.slice/user-12345.slice/user@12345.service/apps.slice/apps-org.gnome.Terminal.slice/vte-spawn-e640104a-cddf-4bd8-ba4b-2c1baf0270c3.scope", nil
	})
	defer restore()

	// With the cgroup path faked as above, tracking is not effective.
	err := cgroup.ConfirmSystemdAppTracking("snap.pkg.app")
	c.Assert(err, Equals, cgroup.ErrCannotTrackProcess)
}

func (s *trackingSuite) TestConfirmSystemdAppTrackingSad3(c *C) {
	// Pretend our PID is this value.
	restore := cgroup.MockOsGetpid(312123)
	defer restore()
	// Replace the cgroup analyzer function
	restore = cgroup.MockCgroupProcessPathInTrackingCgroup(func(pid int) (string, error) {
		c.Assert(pid, Equals, 312123)
		// bad security tag
		return "user.slice/user-12345.slice/user@12345.service/apps.slice/snap.pkg-ae6d0825-dacd-454c-baec-67289f067c28.scope", nil
	})
	defer restore()

	// With the cgroup path faked as above, tracking is not effective.
	err := cgroup.ConfirmSystemdAppTracking("snap.pkg.app")
	c.Assert(err, Equals, cgroup.ErrCannotTrackProcess)
}