File: snap_app_set.go

package info (click to toggle)
snapd 2.74.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 81,428 kB
  • sloc: sh: 16,966; ansic: 16,788; python: 11,332; makefile: 1,897; exp: 190; awk: 58; xml: 22
file content (261 lines) | stat: -rw-r--r-- 8,258 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
package interfaces

import (
	"bytes"
	"fmt"
	"path/filepath"
	"sort"
	"strings"

	"github.com/snapcore/snapd/dirs"
	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/snap"
)

// SnapAppSet is a helper that provides information about executable elements of
// a snap. This currently includes snap apps and hooks.
type SnapAppSet struct {
	info       *snap.Info
	components []*snap.ComponentInfo
}

// NewSnapAppSet returns a new SnapAppSet for the given snap.Info.
func NewSnapAppSet(info *snap.Info, components []*snap.ComponentInfo) (*SnapAppSet, error) {
	for _, c := range components {
		if c.Component.SnapName != info.SnapName() {
			return nil, fmt.Errorf("internal error: snap %q does not own component %q", info.SnapName(), c.Component)
		}
	}
	return &SnapAppSet{info: info, components: components}, nil
}

// Info returns the snap.Info that this SnapAppSet is based on.
func (a *SnapAppSet) Info() *snap.Info {
	return a.info
}

// Components returns the components that this SnapAppSet was created with.
func (a *SnapAppSet) Components() []*snap.ComponentInfo {
	return a.components
}

// InstanceName returns the instance name of the snap that this SnapAppSet is
// based on.
func (a *SnapAppSet) InstanceName() string {
	return a.info.InstanceName()
}

// ExpandSliceSnapVariablesInRootfs resolves $SNAP, $SNAP_DATA, $SNAP_COMMON
// and $SNAP_COMPONENT(<component>) for paths, using the rootfs as mount
// namespace. Paths for components not installed are filtered out.
func (a *SnapAppSet) ExpandSliceSnapVariablesInRootfs(paths []string) []string {
	pathsWithDirIdx := a.ExpandSliceSnapVariablesWithOrder(paths)
	expanded := make([]string, 0, len(pathsWithDirIdx))
	for _, pwi := range pathsWithDirIdx {
		expanded = append(expanded, pwi.Path)
	}
	return expanded
}

// ExpandedDirWithIdx returns the path of an expanded directory and the index in the input
// slice.
type ExpandedDirWithIdx struct {
	Path string
	Idx  int
}

// ExpandSliceSnapVariablesInRootfs resolves $SNAP, $SNAP_DATA, $SNAP_COMMON and
// $SNAP_COMPONENT(<component>) for paths, using the rootfs as mount namespace. Paths for
// components not installed are filtered out. The order specified in paths is returned in the
// output.
func (a *SnapAppSet) ExpandSliceSnapVariablesWithOrder(paths []string) []ExpandedDirWithIdx {
	const componentPrefix = "$SNAP_COMPONENT("

	expandedDirs := make([]ExpandedDirWithIdx, 0, len(paths))
	for idx, dir := range paths {
		if strings.HasPrefix(dir, componentPrefix) {
			compAndPath := strings.SplitN(dir[len(componentPrefix):], ")/", 2)
			if len(compAndPath) != 2 {
				// Should not really happen as these paths are
				// validated by validateSourceDirs
				logger.Noticef("WARNING: wrongly formatted component path: %s",
					componentPrefix)
				continue
			}
			var ci *snap.ComponentInfo
			for _, comp := range a.components {
				if comp.Component.ComponentName == compAndPath[0] {
					ci = comp
					break
				}
			}
			if ci == nil {
				// Component not installed, so we filter out (note however that
				// the presence of the path influences the directory index
				// which might be used later to set the file priority).
				continue
			}
			cpi := snap.MinimalComponentContainerPlaceInfo(
				ci.Component.ComponentName, ci.Revision, a.info.SnapName())
			expandedDirs = append(expandedDirs, ExpandedDirWithIdx{Path: filepath.Clean(
				filepath.Join(cpi.MountDir(), compAndPath[1])),
				Idx: idx,
			})
		} else {
			expandedDirs = append(expandedDirs, ExpandedDirWithIdx{Path: filepath.Clean(
				a.info.ExpandSnapVariablesSetSnapMountDir(
					filepath.Join(dirs.GlobalRootDir, dir),
					dirs.StripRootDir(dirs.SnapMountDir))),
				Idx: idx,
			})
		}
	}
	return expandedDirs
}

// SecurityTagsForConnectedPlug returns the security tags for the given plug.
// These are derived from the security tags of the apps and hooks that are
// associated with the plug.
func (a *SnapAppSet) SecurityTagsForConnectedPlug(plug *ConnectedPlug) ([]string, error) {
	return a.SecurityTagsForPlug(plug.plugInfo)
}

// SecurityTagsForPlug returns the security tags for the given plug. These are
// derived from the security tags of the apps and hooks that are associated with
// the plug.
func (a *SnapAppSet) SecurityTagsForPlug(plug *snap.PlugInfo) ([]string, error) {
	if plug.Snap.InstanceName() != a.info.InstanceName() {
		return nil, fmt.Errorf("internal error: plug %q is from snap %q, security tags can only be computed for processed target snap: %q", plug.Name, plug.Snap.InstanceName(), a.info.InstanceName())
	}

	apps := a.info.AppsForPlug(plug)
	hooks := a.info.HooksForPlug(plug)

	for _, component := range a.components {
		hooks = append(hooks, component.HooksForPlug(plug)...)
	}

	tags := make([]string, 0, len(apps)+len(hooks))
	for _, app := range apps {
		tags = append(tags, app.SecurityTag())
	}

	for _, hook := range hooks {
		tags = append(tags, hook.SecurityTag())
	}

	sort.Strings(tags)

	return tags, nil
}

// SecurityTagsForConnectedSlot returns the security tags for the given slot. These
// are derived from the security tags of the apps and hooks that are associated
// with the slot.
func (a *SnapAppSet) SecurityTagsForConnectedSlot(slot *ConnectedSlot) ([]string, error) {
	return a.SecurityTagsForSlot(slot.slotInfo)
}

// SecurityTagsForSlot returns the security tags for the given slot. These are
// derived from the security tags of the apps and hooks that are associated with
// the slot.
func (a *SnapAppSet) SecurityTagsForSlot(slot *snap.SlotInfo) ([]string, error) {
	if slot.Snap.InstanceName() != a.info.InstanceName() {
		return nil, fmt.Errorf("internal error: slot %q is from snap %q, security tags can only be computed for processed target snap: %q", slot.Name, slot.Snap.InstanceName(), a.info.InstanceName())
	}

	apps := a.info.AppsForSlot(slot)
	hooks := a.info.HooksForSlot(slot)

	tags := make([]string, 0, len(apps)+len(hooks))
	for _, app := range apps {
		tags = append(tags, app.SecurityTag())
	}

	for _, hook := range hooks {
		tags = append(tags, hook.SecurityTag())
	}

	sort.Strings(tags)

	return tags, nil
}

// Runnables returns a list of all runnables known by the app set.
func (a *SnapAppSet) Runnables() []snap.Runnable {
	var runnables []snap.Runnable

	for _, app := range a.info.Apps {
		runnables = append(runnables, app.Runnable())
	}

	for _, hook := range a.info.Hooks {
		runnables = append(runnables, hook.Runnable())
	}

	for _, component := range a.components {
		for _, hook := range component.Hooks {
			runnables = append(runnables, hook.Runnable())
		}
	}

	return runnables
}

// labelExpr returns the specification of the apparmor label describing the
// given connected plug/slot. The result has one of three forms, depending on
// how apps are bound to the slot:
//
//   - "snap.$snap_instance.$app" if there is exactly one app/hook bound
//   - "snap.$snap_instance.{$app1,...$appN, $hook1...$hookN}" if there are
//     some, but not all, apps/hooks bound
//   - "snap.$snap_instance.*" if all apps/hooks are bound to the plug or slot
func labelExpr(connected interface {
	AppSet() *SnapAppSet
	Runnables() []snap.Runnable
}) string {
	appSet := connected.AppSet()
	runnables := connected.Runnables()

	// all security tags are prefixed with snap.$snap_instance, we use this
	// knowledge to build a pattern that will match against all of the connected
	// runnables
	prefix := fmt.Sprintf("snap.%s", appSet.InstanceName())

	suffixes := make([]string, 0, len(runnables))
	for _, r := range runnables {
		suffix := strings.TrimPrefix(r.SecurityTag, prefix)
		if suffix == r.SecurityTag {
			logger.Noticef("security tag %q does not have expected prefix: %q", r.SecurityTag, prefix)
			continue
		}
		suffixes = append(suffixes, suffix)
	}

	sort.Strings(suffixes)

	var buf bytes.Buffer
	fmt.Fprintf(&buf, `"%s`, prefix)

	switch len(suffixes) {
	case 0:
		buf.WriteString(".")
	case 1:
		buf.WriteString(suffixes[0])
	case len(appSet.Runnables()):
		buf.WriteString(".*")
	default:
		buf.WriteByte('{')
		for _, name := range suffixes {
			buf.WriteString(name)
			buf.WriteByte(',')
		}
		// remove trailing comma
		buf.Truncate(buf.Len() - 1)
		buf.WriteByte('}')
	}

	buf.WriteByte('"')

	return buf.String()
}