Skip to content

Commit

Permalink
i/prompting: add package for prompting common types/functions (#13849)
Browse files Browse the repository at this point in the history
* i/prompting: add package for prompting common types/functions

Signed-off-by: Oliver Calder <[email protected]>

i/prompting: make `TimestampToTime()` return a local time, matching `time.Now()` and `time.Unix()`

Signed-off-by: Oliver Calder <[email protected]>

i/prompting: make duration a string parsable by `time.ParseDuration()`

Signed-off-by: Oliver Calder <[email protected]>

i/prompting: reorder functions

Signed-off-by: Oliver Calder <[email protected]>

i/prompting: remove "app" from prompts and rules

AppArmor permissions are granted by interfaces according to plugs/slots
which may or may not differ between apps within a given snap. For the
home interface, for example, there is never an instance where one app
within a snap is granted a permission that another app in that same snap
is not. Thus, it does not make sense for a rule to apply to only a
single app within a snap.

Instead, the interface field should optionally include the name of the
plug or slot which granted the permissions, which should be received
from the kernel using message tagging. The result should be of the form:

`<interface name>[/<plug or slot>]`

As such, rules should no longer be associated with a particular app, and
in order to match, neither should request prompts. Adjustments are made
to the prompting API to remove the "app" parameter when querying rules.

Signed-off-by: Oliver Calder <[email protected]>

i/prompting: add validation functions for expiration

Adds expiration-related analogues for `ValidateLifespanParseDuration`
and `ValidateConstraintsOutcomeLifespanDuration`.

Additionally, improves error messages by including the contents of the
invalid field in the message.

Signed-off-by: Oliver Calder <[email protected]>

i/prompting: move prompting common types/functions to interfaces/prompting

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting,snap: replace LabelToSnap with SplitSecurityTag

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: removed unused NewID function

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: removed unused CurrentTimestamp function

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: rearrange functions

Signed-off-by: Oliver Calder <[email protected]>

* snap: check that app is non-empty if it exists in security label

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: use time.Time for timestamp and *time.Time for expiration

Since `time.Time` values are marshalled as RFC3339Nano by default, there
is no reason to explicitly save timestamps and expirations as strings
and convert them to `time.Time` on the fly as necessary. Let the
marshaller do this automatically.

As expirations should only be populated when lifespan is "timespan",
expirations can be stored as `*time.Time`, which should be encoded as
`nil` when empty and an expiration timestamp in RFC3339Nano format when
non-empty.

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: store expiration as time.Time instead of *time.Time

Additionally, adjust related error messages to remove "invalid ...:"
prefix.

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: rename AsBool to IsAllow and adjust related error messages

Signed-off-by: Oliver Calder <[email protected]>

* snap: remove SplitSecurityTag function

Instead, use the existing `ParseSecurityTag` function and then call
`InstanceName` on the result.

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: remove LifespanSession

There is not currently a good way to identify when a session ends when a
user has logged in via multiple methods (e.g. tty, ssh). Until it is
deemed to be necessary and a good implementation is developed, do not
include LifespanSession.

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: validate outcome and lifespan when unmarshalling

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: remove NewIDAndTimestamp

IDs used for prompting (rules and prompt requests) must be unique across
reboots, and thus cannot rely on timestamps or even monotonic time. We
also want IDs to be sorted, so we cannot use boot ID along with
monotonic time either. Lastly, since we need IDs to be unique across
reboots, we can't simply use a counter based on the maximum of the
existing rule/prompt IDs. Instead, we should store the current maximum
ID in memory and on disk alongside the storage of rules and prompts.
This should be implemented in the respective forthcoming packages and
used at the former callsights of NewIDAndTimestamp.

Since IDs should no longer be tied to timestamps, we can simply use
`time.Now()` where the timestamps from `NewIDAndTimestamp` were formerly
used.

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: replaced ValidateLifespan* functions with methods on lifespan

Signed-off-by: Oliver Calder <[email protected]>

* i/prompting: add doc string and adjusted error messages and comments

Signed-off-by: Oliver Calder <[email protected]>

---------

Signed-off-by: Oliver Calder <[email protected]>
  • Loading branch information
olivercalder authored May 1, 2024
1 parent f84571b commit 356d7c1
Show file tree
Hide file tree
Showing 2 changed files with 379 additions and 0 deletions.
161 changes: 161 additions & 0 deletions interfaces/prompting/prompting.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// -*- Mode: Go; indent-tabs-mode: t -*-

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

import (
"encoding/json"
"fmt"
"time"
)

// OutcomeType describes the outcome associated with a reply or rule.
type OutcomeType string

const (
// OutcomeUnset indicates that no outcome was specified, and should only
// be used while unmarshalling outcome fields marked as omitempty.
OutcomeUnset OutcomeType = ""
// OutcomeAllow indicates that a corresponding request should be allowed.
OutcomeAllow OutcomeType = "allow"
// OutcomeDeny indicates that a corresponding request should be denied.
OutcomeDeny OutcomeType = "deny"
)

func (outcome *OutcomeType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
value := OutcomeType(s)
switch value {
case OutcomeAllow, OutcomeDeny:
*outcome = value
default:
return fmt.Errorf(`cannot have outcome other than %q or %q: %q`, OutcomeAllow, OutcomeDeny, value)
}
return nil
}

// IsAllow returns true if the outcome is OutcomeAllow, false if the outcome is
// OutcomeDeny, or an error if it cannot be parsed.
func (outcome OutcomeType) IsAllow() (bool, error) {
switch outcome {
case OutcomeAllow:
return true, nil
case OutcomeDeny:
return false, nil
default:
return false, fmt.Errorf(`internal error: invalid outcome: %q`, outcome)
}
}

// LifespanType describes the temporal scope for which a reply or rule applies.
type LifespanType string

const (
// LifespanUnset indicates that no lifespan was specified, and should only
// be used while unmarshalling lifespan fields marked as omitempty.
LifespanUnset LifespanType = ""
// LifespanForever indicates that the reply/rule should never expire.
LifespanForever LifespanType = "forever"
// LifespanSingle indicates that a reply should only apply once, and should
// not be used to create a rule.
LifespanSingle LifespanType = "single"
// LifespanTimespan indicates that a reply/rule should apply for a given
// duration or until a given expiration timestamp.
LifespanTimespan LifespanType = "timespan"
// TODO: add LifespanSession which expires after the user logs out
// LifespanSession LifespanType = "session"
)

func (lifespan *LifespanType) UnmarshalJSON(data []byte) error {
var lifespanStr string
if err := json.Unmarshal(data, &lifespanStr); err != nil {
return err
}
value := LifespanType(lifespanStr)
switch value {
case LifespanForever, LifespanSingle, LifespanTimespan:
*lifespan = value
default:
return fmt.Errorf(`cannot have lifespan other than %q, %q, or %q: %q`, LifespanForever, LifespanSingle, LifespanTimespan, value)
}
return nil
}

// ValidateExpiration checks that the given expiration is valid for the
// receiver lifespan.
//
// If the lifespan is LifespanTimespan, then expiration must be non-zero and be
// after the given currTime. Otherwise, it must be zero. Returns an error if
// any of the above are invalid.
func (lifespan LifespanType) ValidateExpiration(expiration time.Time, currTime time.Time) error {
switch lifespan {
case LifespanForever, LifespanSingle:
if !expiration.IsZero() {
return fmt.Errorf(`cannot have specified expiration when lifespan is %q: %q`, lifespan, expiration)
}
case LifespanTimespan:
if expiration.IsZero() {
return fmt.Errorf(`cannot have unspecified expiration when lifespan is %q`, lifespan)
}
if currTime.After(expiration) {
return fmt.Errorf("cannot have expiration time in the past: %q", expiration)
}
default:
// Should not occur, since lifespan is validated when unmarshalled
return fmt.Errorf(`internal error: invalid lifespan: %q`, lifespan)
}
return nil
}

// ParseDuration checks that the given duration is valid for the receiver
// lifespan and parses it into an expiration timestamp.
//
// If the lifespan is LifespanTimespan, then duration must be a string parsable
// by time.ParseDuration(), representing the duration of time for which the rule
// should be valid. Otherwise, it must be empty. Returns an error if any of the
// above are invalid, otherwise computes the expiration time of the rule based
// on the given currTime and the given duration and returns it.
func (lifespan LifespanType) ParseDuration(duration string, currTime time.Time) (time.Time, error) {
var expiration time.Time
switch lifespan {
case LifespanForever, LifespanSingle:
if duration != "" {
return expiration, fmt.Errorf(`cannot have specified duration when lifespan is %q: %q`, lifespan, duration)
}
case LifespanTimespan:
if duration == "" {
return expiration, fmt.Errorf(`cannot have unspecified duration when lifespan is %q`, lifespan)
}
parsedDuration, err := time.ParseDuration(duration)
if err != nil {
return expiration, fmt.Errorf(`cannot parse duration: %w`, err)
}
if parsedDuration <= 0 {
return expiration, fmt.Errorf(`cannot have zero or negative duration: %q`, duration)
}
expiration = currTime.Add(parsedDuration)
default:
// Should not occur, since lifespan is validated when unmarshalled
return expiration, fmt.Errorf(`internal error: invalid lifespan: %q`, lifespan)
}
return expiration, nil
}
218 changes: 218 additions & 0 deletions interfaces/prompting/prompting_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
// -*- Mode: Go; indent-tabs-mode: t -*-

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

import (
"encoding/json"
"fmt"
"testing"
"time"

. "gopkg.in/check.v1"

"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/interfaces/prompting"
)

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

type promptingSuite struct {
tmpdir string
}

var _ = Suite(&promptingSuite{})

func (s *promptingSuite) SetUpTest(c *C) {
s.tmpdir = c.MkDir()
dirs.SetRootDir(s.tmpdir)
}

func (s *promptingSuite) TestOutcomeIsAllow(c *C) {
result, err := prompting.OutcomeAllow.IsAllow()
c.Check(err, IsNil)
c.Check(result, Equals, true)
result, err = prompting.OutcomeDeny.IsAllow()
c.Check(err, IsNil)
c.Check(result, Equals, false)
_, err = prompting.OutcomeUnset.IsAllow()
c.Check(err, ErrorMatches, `internal error: invalid outcome.*`)
_, err = prompting.OutcomeType("foo").IsAllow()
c.Check(err, ErrorMatches, `internal error: invalid outcome.*`)
}

type fakeOutcomeWrapper struct {
Field1 prompting.OutcomeType `json:"field1"`
Field2 prompting.OutcomeType `json:"field2,omitempty"`
}

func (s *promptingSuite) TestUnmarshalOutcomeHappy(c *C) {
for _, outcome := range []prompting.OutcomeType{
prompting.OutcomeAllow,
prompting.OutcomeDeny,
} {
var fow1 fakeOutcomeWrapper
data := []byte(fmt.Sprintf(`{"field1": "%s", "field2": "%s"}`, outcome, outcome))
err := json.Unmarshal(data, &fow1)
c.Check(err, IsNil, Commentf("data: %v", string(data)))
c.Check(fow1.Field1, Equals, outcome, Commentf("data: %v", string(data)))
c.Check(fow1.Field2, Equals, outcome, Commentf("data: %v", string(data)))

var fow2 fakeOutcomeWrapper
data = []byte(fmt.Sprintf(`{"field1": "%s"}`, outcome))
err = json.Unmarshal(data, &fow2)
c.Check(err, IsNil, Commentf("data: %v", string(data)))
c.Check(fow2.Field1, Equals, outcome, Commentf("data: %v", string(data)))
c.Check(fow2.Field2, Equals, prompting.OutcomeUnset, Commentf("data: %v", string(data)))
}
}

func (s *promptingSuite) TestUnmarshalOutcomeUnhappy(c *C) {
for _, outcome := range []prompting.OutcomeType{
prompting.OutcomeUnset,
prompting.OutcomeType("foo"),
} {
var fow1 fakeOutcomeWrapper
data := []byte(fmt.Sprintf(`{"field1": "%s", "field2": "%s"}`, outcome, outcome))
err := json.Unmarshal(data, &fow1)
c.Check(err, ErrorMatches, `cannot have outcome other than.*`, Commentf("data: %v", string(data)))

var fow2 fakeOutcomeWrapper
data = []byte(fmt.Sprintf(`{"field1": "%s", "field2": "%s"}`, prompting.OutcomeAllow, outcome))
err = json.Unmarshal(data, &fow2)
c.Check(err, ErrorMatches, `cannot have outcome other than.*`, Commentf("data: %v", string(data)))
}
}

type fakeLifespanWrapper struct {
Field1 prompting.LifespanType `json:"field1"`
Field2 prompting.LifespanType `json:"field2,omitempty"`
}

func (s *promptingSuite) TestUnmarshalLifespanHappy(c *C) {
for _, lifespan := range []prompting.LifespanType{
prompting.LifespanForever,
prompting.LifespanSingle,
prompting.LifespanTimespan,
} {
var flw1 fakeLifespanWrapper
data := []byte(fmt.Sprintf(`{"field1": "%s", "field2": "%s"}`, lifespan, lifespan))
err := json.Unmarshal(data, &flw1)
c.Check(err, IsNil, Commentf("data: %v", string(data)))
c.Check(flw1.Field1, Equals, lifespan, Commentf("data: %v", string(data)))
c.Check(flw1.Field2, Equals, lifespan, Commentf("data: %v", string(data)))

var flw2 fakeLifespanWrapper
data = []byte(fmt.Sprintf(`{"field1": "%s"}`, lifespan))
err = json.Unmarshal(data, &flw2)
c.Check(err, IsNil, Commentf("data: %v", string(data)))
c.Check(flw2.Field1, Equals, lifespan, Commentf("data: %v", string(data)))
c.Check(flw2.Field2, Equals, prompting.LifespanUnset, Commentf("data: %v", string(data)))
}
}

func (s *promptingSuite) TestUnmarshalLifespanUnhappy(c *C) {
for _, lifespan := range []prompting.LifespanType{
prompting.LifespanUnset,
prompting.LifespanType("foo"),
} {
var flw1 fakeLifespanWrapper
data := []byte(fmt.Sprintf(`{"field1": "%s", "field2": "%s"}`, lifespan, lifespan))
err := json.Unmarshal(data, &flw1)
c.Check(err, ErrorMatches, `cannot have lifespan other than.*`, Commentf("data: %v", string(data)))

var flw2 fakeLifespanWrapper
data = []byte(fmt.Sprintf(`{"field1": "%s", "field2": "%s"}`, prompting.LifespanForever, lifespan))
err = json.Unmarshal(data, &flw2)
c.Check(err, ErrorMatches, `cannot have lifespan other than.*`, Commentf("data: %v", string(data)))
}
}

func (s *promptingSuite) TestValidateExpiration(c *C) {
var unsetExpiration time.Time
currTime := time.Now()
negativeExpiration := currTime.Add(-5 * time.Second)
validExpiration := currTime.Add(10 * time.Minute)

for _, lifespan := range []prompting.LifespanType{
prompting.LifespanForever,
prompting.LifespanSingle,
} {
err := lifespan.ValidateExpiration(unsetExpiration, currTime)
c.Check(err, IsNil)
for _, exp := range []time.Time{negativeExpiration, validExpiration} {
err = lifespan.ValidateExpiration(exp, currTime)
c.Check(err, ErrorMatches, `cannot have specified expiration when lifespan is.*`)
}
}

err := prompting.LifespanTimespan.ValidateExpiration(unsetExpiration, currTime)
c.Check(err, ErrorMatches, `cannot have unspecified expiration when lifespan is.*`)

err = prompting.LifespanTimespan.ValidateExpiration(negativeExpiration, currTime)
c.Check(err, ErrorMatches, `cannot have expiration time in the past.*`)

err = prompting.LifespanTimespan.ValidateExpiration(validExpiration, currTime)
c.Check(err, IsNil)
}

func (s *promptingSuite) TestParseDuration(c *C) {
unsetDuration := ""
invalidDuration := "foo"
negativeDuration := "-5s"
validDuration := "10m"
parsedValidDuration, err := time.ParseDuration(validDuration)
c.Assert(err, IsNil)
currTime := time.Now()

for _, lifespan := range []prompting.LifespanType{
prompting.LifespanForever,
prompting.LifespanSingle,
} {
expiration, err := lifespan.ParseDuration(unsetDuration, currTime)
c.Check(expiration.IsZero(), Equals, true)
c.Check(err, IsNil)
for _, dur := range []string{invalidDuration, negativeDuration, validDuration} {
expiration, err = lifespan.ParseDuration(dur, currTime)
c.Check(expiration.IsZero(), Equals, true)
c.Check(err, ErrorMatches, `cannot have specified duration when lifespan is.*`)
}
}

expiration, err := prompting.LifespanTimespan.ParseDuration(unsetDuration, currTime)
c.Check(expiration.IsZero(), Equals, true)
c.Check(err, ErrorMatches, `cannot have unspecified duration when lifespan is.*`)

expiration, err = prompting.LifespanTimespan.ParseDuration(invalidDuration, currTime)
c.Check(expiration.IsZero(), Equals, true)
c.Check(err, ErrorMatches, `cannot parse duration.*`)

expiration, err = prompting.LifespanTimespan.ParseDuration(negativeDuration, currTime)
c.Check(expiration.IsZero(), Equals, true)
c.Check(err, ErrorMatches, `cannot have zero or negative duration.*`)

expiration, err = prompting.LifespanTimespan.ParseDuration(validDuration, currTime)
c.Check(err, IsNil)
c.Check(expiration.After(time.Now()), Equals, true)
c.Check(expiration.Before(time.Now().Add(parsedValidDuration)), Equals, true)

expiration2, err := prompting.LifespanTimespan.ParseDuration(validDuration, currTime)
c.Check(err, IsNil)
c.Check(expiration2.Equal(expiration), Equals, true)
}

0 comments on commit 356d7c1

Please sign in to comment.