File: session_agent_test.go

package info (click to toggle)
snapd 2.72-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 80,412 kB
  • sloc: sh: 16,506; ansic: 16,211; python: 11,213; makefile: 1,919; exp: 190; awk: 58; xml: 22
file content (306 lines) | stat: -rw-r--r-- 8,990 bytes parent folder | download | duplicates (3)
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
// -*- Mode: Go; indent-tabs-mode: t -*-

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

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"syscall"
	"testing"
	"time"

	. "gopkg.in/check.v1"

	"github.com/snapcore/snapd/desktop/notification/notificationtest"
	"github.com/snapcore/snapd/dirs"
	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/osutil/sys"
	"github.com/snapcore/snapd/testutil"
	"github.com/snapcore/snapd/usersession/agent"
)

func Test(t *testing.T) { TestingT(t) }

type sessionAgentSuite struct {
	testutil.DBusTest
	socketPath string
	client     *http.Client
}

var _ = Suite(&sessionAgentSuite{})

func (s *sessionAgentSuite) SetUpTest(c *C) {
	s.DBusTest.SetUpTest(c)
	dirs.SetRootDir(c.MkDir())
	xdgRuntimeDir := fmt.Sprintf("%s/%d", dirs.XdgRuntimeDirBase, os.Getuid())
	c.Assert(os.MkdirAll(xdgRuntimeDir, 0700), IsNil)
	s.socketPath = fmt.Sprintf("%s/snapd-session-agent.socket", xdgRuntimeDir)

	transport := &http.Transport{
		Dial: func(_, _ string) (net.Conn, error) {
			return net.Dial("unix", s.socketPath)
		},
		DisableKeepAlives: true,
	}
	s.client = &http.Client{Transport: transport}
}

func (s *sessionAgentSuite) TearDownTest(c *C) {
	dirs.SetRootDir("")
	logger.SetLogger(logger.NullLogger)
	s.DBusTest.TearDownTest(c)
}

func (s *sessionAgentSuite) TestStartStop(c *C) {
	agent, err := agent.New()
	c.Assert(err, IsNil)
	agent.Version = "42"
	agent.Start()
	defer func() { c.Check(agent.Stop(), IsNil) }()

	// The agent has connected to the session bus
	var hasOwner bool
	c.Check(s.DBusTest.SessionBus.BusObject().Call("org.freedesktop.DBus.NameHasOwner", 0, "io.snapcraft.SessionAgent").Store(&hasOwner), IsNil)
	c.Check(hasOwner, Equals, true)

	// The agent is listening for REST API requests
	response, err := s.client.Get("http://localhost/v1/session-info")
	c.Assert(err, IsNil)
	defer response.Body.Close()
	c.Check(response.StatusCode, Equals, 200)

	var rst struct {
		Result struct {
			Version string `json:"version"`
		} `json:"result"`
	}
	c.Assert(json.NewDecoder(response.Body).Decode(&rst), IsNil)
	c.Check(rst.Result.Version, Equals, "42")
	response.Body.Close()

	c.Check(agent.Stop(), IsNil)
}

func (s *sessionAgentSuite) TestDying(c *C) {
	agent, err := agent.New()
	c.Assert(err, IsNil)
	agent.Start()
	select {
	case <-agent.Dying():
		c.Error("agent.Dying() channel closed prematurely")
	default:
	}
	go func() {
		time.Sleep(5 * time.Millisecond)
		c.Check(agent.Stop(), IsNil)
	}()
	select {
	case <-agent.Dying():
	case <-time.After(2 * time.Second):
		c.Error("agent.Dying() channel was not closed when agent stopped")
	}
}

func (s *sessionAgentSuite) TestExitOnIdle(c *C) {
	agent, err := agent.New()
	c.Assert(err, IsNil)
	agent.IdleTimeout = 150 * time.Millisecond
	startTime := time.Now()
	agent.Start()
	defer agent.Stop()

	makeRequest := func() {
		response, err := s.client.Get("http://localhost/v1/session-info")
		c.Assert(err, IsNil)
		defer response.Body.Close()
		c.Check(response.StatusCode, Equals, 200)
	}
	makeRequest()
	time.Sleep(25 * time.Millisecond)
	makeRequest()

	select {
	case <-agent.Dying():
	case <-time.After(2 * time.Second):
		c.Fatal("agent did not exit after idle timeout expired")
	}
	elapsed := time.Since(startTime)
	if elapsed < 175*time.Millisecond || elapsed > 450*time.Millisecond {
		// The idle timeout should have been extended when we
		// issued a second request after 25ms.
		c.Errorf("Expected ellaped time close to 175 ms, but got %v", elapsed)
	}
}

func (s *sessionAgentSuite) TestFdoNotification(c *C) {
	desktopFile := "[Desktop Entry]\nIcon=/path/appicon.png"
	c.Assert(os.MkdirAll(filepath.Join(dirs.SnapDesktopFilesDir), 0755), IsNil)
	c.Assert(os.WriteFile(filepath.Join(dirs.SnapDesktopFilesDir, "app.desktop"), []byte(desktopFile), 0644), IsNil)

	backend, err := notificationtest.NewFdoServer()
	c.Assert(err, IsNil)
	defer backend.Stop()

	agent, err := agent.New()
	c.Assert(err, IsNil)
	agent.IdleTimeout = 150 * time.Millisecond
	agent.Start()
	defer agent.Stop()

	// simulate snap refresh message
	makeRequest := func() {
		data := bytes.NewBufferString(`{"instance-name":"some-snap", "busy-app-name":"App", "busy-app-desktop-entry":"app"}`)
		response, err := s.client.Post("http://localhost/v1/notifications/pending-refresh", "application/json", data)
		c.Assert(err, IsNil)
		defer response.Body.Close()
		c.Check(response.StatusCode, Equals, 200)
	}
	makeRequest()

	// wait for a while, we want the message to trigger FDO notification
	time.Sleep(50 * time.Millisecond)

	// our fake FDO backend should receive the notification
	fdoNotification := backend.Get(1)
	c.Assert(fdoNotification, NotNil)
	c.Check(fdoNotification.AppName, Equals, "App")
	c.Check(fdoNotification.Icon, Equals, "/path/appicon.png")

	// trigger notification close signal over dbus
	c.Assert(backend.Close(1, 0), IsNil)

	select {
	case <-agent.Dying():
	case <-time.After(2 * time.Second):
		c.Fatal("agent did not exit after idle timeout expired")
	}
}

func (s *sessionAgentSuite) TestGtkNotification(c *C) {
	desktopFile := "[Desktop Entry]\nIcon=/path/appicon.png"
	c.Assert(os.MkdirAll(filepath.Join(dirs.SnapDesktopFilesDir), 0755), IsNil)
	c.Assert(os.WriteFile(filepath.Join(dirs.SnapDesktopFilesDir, "app.desktop"), []byte(desktopFile), 0644), IsNil)

	backend, err := notificationtest.NewGtkServer()
	c.Assert(err, IsNil)
	defer backend.Stop()

	agent, err := agent.New()
	c.Assert(err, IsNil)
	agent.IdleTimeout = 150 * time.Millisecond
	agent.Start()
	defer agent.Stop()

	// simulate snap refresh message
	makeRequest := func() {
		data := bytes.NewBufferString(`{"instance-name":"some-snap", "busy-app-name":"App", "busy-app-desktop-entry":"app"}`)
		response, err := s.client.Post("http://localhost/v1/notifications/pending-refresh", "application/json", data)
		c.Assert(err, IsNil)
		defer response.Body.Close()
		c.Check(response.StatusCode, Equals, 200)
	}
	makeRequest()

	// wait for a while, we want the message to trigger FDO notification
	time.Sleep(50 * time.Millisecond)

	// our fake FDO backend should receive the notification
	gtkNotification := backend.Get("some-snap")
	c.Assert(gtkNotification, NotNil)
	c.Check(gtkNotification.DesktopID, Equals, "io.snapcraft.SessionAgent")

	// trigger notification close signal over dbus
	c.Assert(backend.Close("some-snap"), IsNil)

	select {
	case <-agent.Dying():
	case <-time.After(2 * time.Second):
		c.Fatal("agent did not exit after idle timeout expired")
	}
}

func (s *sessionAgentSuite) TestConnectFromOtherUser(c *C) {
	logbuf, restore := logger.MockLogger()
	defer restore()

	// Mock connections to appear to come from a different user ID
	uid := uint32(sys.Geteuid())
	restore = agent.MockUcred(&syscall.Ucred{Uid: uid + 1}, nil)
	defer restore()

	sa, err := agent.New()
	c.Assert(err, IsNil)
	sa.Start()
	defer sa.Stop()

	_, err = s.client.Get("http://localhost/v1/session-info")
	// This could be an EOF error or a failed read, depending on timing
	c.Assert(err, ErrorMatches, "Get \"?http://localhost/v1/session-info\"?: .*")
	logger.WithLoggerLock(func() {
		c.Check(logbuf.String(), testutil.Contains, "Blocking request from user ID")
	})
}

func (s *sessionAgentSuite) TestConnectFromRoot(c *C) {
	logbuf, restore := logger.MockLogger()
	defer restore()

	// Mock connections to appear to come from root
	restore = agent.MockUcred(&syscall.Ucred{Uid: 0}, nil)
	defer restore()

	sa, err := agent.New()
	c.Assert(err, IsNil)
	sa.Start()
	defer sa.Stop()

	response, err := s.client.Get("http://localhost/v1/session-info")
	c.Assert(err, IsNil)
	defer response.Body.Close()
	c.Check(response.StatusCode, Equals, 200)
	logger.WithLoggerLock(func() {
		c.Check(logbuf.String(), Equals, "")
	})
}

func (s *sessionAgentSuite) TestConnectWithFailedPeerCredentials(c *C) {
	logbuf, restore := logger.MockLogger()
	defer restore()

	// Connections are dropped if peer credential lookup fails.
	restore = agent.MockUcred(nil, fmt.Errorf("SO_PEERCRED failed"))
	defer restore()

	sa, err := agent.New()
	c.Assert(err, IsNil)
	sa.Start()
	defer sa.Stop()

	_, err = s.client.Get("http://localhost/v1/session-info")
	c.Assert(err, ErrorMatches, "Get \"?http://localhost/v1/session-info\"?: .*")
	logger.WithLoggerLock(func() {
		c.Check(logbuf.String(), testutil.Contains, "Failed to retrieve peer credentials: SO_PEERCRED failed")
	})
}