// -*- Mode: Go; indent-tabs-mode: t -*-
/*
 * Copyright (C) 2023-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 daemon_test

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strings"
	"time"

	"gopkg.in/check.v1"
	. "gopkg.in/check.v1"

	"github.com/snapcore/snapd/asserts"
	"github.com/snapcore/snapd/asserts/assertstest"
	"github.com/snapcore/snapd/client"
	"github.com/snapcore/snapd/confdb"
	"github.com/snapcore/snapd/daemon"
	"github.com/snapcore/snapd/features"
	"github.com/snapcore/snapd/overlord"
	"github.com/snapcore/snapd/overlord/assertstate"
	"github.com/snapcore/snapd/overlord/auth"
	"github.com/snapcore/snapd/overlord/confdbstate"
	"github.com/snapcore/snapd/overlord/configstate/config"
	"github.com/snapcore/snapd/overlord/devicestate"
	"github.com/snapcore/snapd/overlord/devicestate/devicestatetest"
	"github.com/snapcore/snapd/overlord/hookstate"
	"github.com/snapcore/snapd/overlord/state"
)

type confdbSuite struct {
	apiBaseSuite

	st     *state.State
	schema *confdb.Schema
}

var _ = Suite(&confdbSuite{})

func (s *confdbSuite) SetUpTest(c *C) {
	s.apiBaseSuite.SetUpTest(c)

	s.expectReadAccess(daemon.AuthenticatedAccess{Polkit: "io.snapcraft.snapd.manage"})
	s.expectWriteAccess(daemon.AuthenticatedAccess{Polkit: "io.snapcraft.snapd.manage"})

	s.st = state.New(nil)
	o := overlord.MockWithState(s.st)
	s.d = daemon.NewWithOverlord(o)

	s.st.Lock()
	databags := map[string]map[string]confdb.JSONDatabag{
		"system": {"network": confdb.NewJSONDatabag()},
	}
	s.st.Set("confdb-databags", databags)
	s.st.Unlock()

	views := map[string]any{
		"wifi-setup": map[string]any{
			"rules": []any{
				map[string]any{"request": "ssid", "storage": "wifi.ssid"},
			},
		},
	}

	schema, err := confdb.NewSchema("system", "network", views, confdb.NewJSONSchema())
	c.Assert(err, IsNil)
	s.schema = schema
}

func (s *confdbSuite) setFeatureFlag(c *C) {
	_, confOption := features.Confdb.ConfigOption()

	s.st.Lock()
	defer s.st.Unlock()

	tr := config.NewTransaction(s.st)
	err := tr.Set("core", confOption, true)
	c.Assert(err, IsNil)
	tr.Commit()
}

func (s *confdbSuite) TestGetView(c *C) {
	s.setFeatureFlag(c)

	type test struct {
		name  string
		value any
	}

	for _, t := range []test{
		{name: "string", value: "foo"},
		{name: "integer", value: 123},
		{name: "list", value: []string{"foo", "bar"}},
		{name: "map", value: map[string]int{"foo": 123}},
	} {
		cmt := Commentf("%s test", t.name)

		restoreGet := daemon.MockConfdbstateGetView(func(_ *state.State, acc, confdbSchema, viewName string) (*confdb.View, error) {
			c.Check(acc, Equals, "system", cmt)
			c.Check(confdbSchema, Equals, "network", cmt)
			c.Check(viewName, Equals, "wifi-setup", cmt)

			return s.schema.View(viewName), nil
		})

		restoreLoad := daemon.MockConfdbstateReadConfdb(func(ctx context.Context, _ *state.State, view *confdb.View, requests []string, _ map[string]any, access confdb.Access) (string, error) {
			_, ok := ctx.Deadline()
			c.Check(ok, Equals, false)

			c.Assert(view.Name, Equals, "wifi-setup")
			c.Assert(requests, DeepEquals, []string{"ssid"})
			c.Assert(access, Equals, confdb.AdminAccess)
			return "123", nil
		})

		req, err := http.NewRequest("GET", "/v2/confdb/system/network/wifi-setup?keys=ssid", nil)
		c.Assert(err, IsNil, cmt)
		req.RemoteAddr = "pid=100;uid=1000;socket=;"

		rspe := s.asyncReq(c, req, nil, actionIsExpected)
		c.Check(rspe.Status, Equals, 202, cmt)
		c.Check(rspe.Change, Equals, "123", cmt)

		restoreGet()
		restoreLoad()
	}
}

func (s *confdbSuite) TestViewGetMany(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(_ *state.State, acc, confdbSchema, viewName string) (*confdb.View, error) {
		c.Assert(acc, Equals, "system")
		c.Assert(confdbSchema, Equals, "network")
		c.Assert(viewName, Equals, "wifi-setup")

		return s.schema.View(viewName), nil
	})
	defer restore()

	restore = daemon.MockConfdbstateReadConfdb(func(_ context.Context, _ *state.State, view *confdb.View, requests []string, _ map[string]any, access confdb.Access) (string, error) {
		c.Assert(requests, DeepEquals, []string{"ssid", "password"})
		c.Assert(view.Name, Equals, "wifi-setup")
		c.Assert(access, Equals, confdb.AdminAccess)
		return "123", nil
	})
	defer restore()

	req, err := http.NewRequest("GET", "/v2/confdb/system/network/wifi-setup?keys=ssid,password", nil)
	c.Assert(err, IsNil)
	req.RemoteAddr = "pid=100;uid=1000;socket=;"

	rspe := s.asyncReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 202)
	c.Check(rspe.Change, Equals, "123")
}

func (s *confdbSuite) TestViewSetMany(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(st *state.State, account, confdbName, viewName string) (*confdb.View, error) {
		return s.schema.View(viewName), nil
	})
	defer restore()

	restore = daemon.MockConfdbstateWriteConfdb(func(_ context.Context, _ *state.State, view *confdb.View, values map[string]any) (string, error) {
		c.Assert(view.Name, Equals, "wifi-setup")
		c.Assert(values, DeepEquals, map[string]any{"ssid": "foo", "password": "bar"})
		return "123", nil
	})
	defer restore()

	buf := bytes.NewBufferString(`{"values":{"ssid": "foo", "password": "bar"}}`)
	req, err := http.NewRequest("PUT", "/v2/confdb/system/network/wifi-setup", buf)
	c.Assert(err, IsNil)

	rspe := s.asyncReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 202)
	c.Check(rspe.Change, Equals, "123")
}

func (s *confdbSuite) TestGetViewError(c *C) {
	s.setFeatureFlag(c)

	type test struct {
		name   string
		err    error
		status int
		kind   client.ErrorKind
	}

	notFoundErr := &asserts.NotFoundError{
		Type:    asserts.ConfdbSchemaType,
		Headers: map[string]string{"name": "network", "account-id": "system"},
	}

	for _, t := range []test{
		{name: "no assertion", err: notFoundErr, status: 400, kind: client.ErrorKindAssertionNotFound},
		{name: "no view", err: &confdbstate.NoViewError{}, status: 400, kind: client.ErrorKindOptionNotAvailable},
		{name: "no match", err: confdb.NewNoMatchError(s.schema.View("wifi-setup"), "", nil), status: 400, kind: client.ErrorKindOptionNotAvailable},
		{name: "internal", err: errors.New("internal"), status: 500},
	} {
		restore := daemon.MockConfdbstateGetView(func(_ *state.State, _, _, _ string) (*confdb.View, error) {
			return nil, t.err
		})

		cmt := Commentf("%s test", t.name)
		req, err := http.NewRequest("GET", "/v2/confdb/system/network/wifi-setup?keys=ssid", nil)
		c.Assert(err, IsNil, cmt)

		rspe := s.errorReq(c, req, nil, actionIsExpected)
		c.Check(rspe.Status, Equals, t.status, cmt)
		c.Check(rspe.Kind, Equals, t.kind, cmt)

		buf := bytes.NewBufferString(`{"values":{"ssid": "foo", "password": "bar"}}`)
		req, err = http.NewRequest("PUT", "/v2/confdb/system/network/wifi-setup", buf)
		c.Assert(err, IsNil, cmt)

		rspe = s.errorReq(c, req, nil, actionIsExpected)
		c.Check(rspe.Status, Equals, t.status, cmt)
		c.Check(rspe.Kind, Equals, t.kind, cmt)
		restore()
	}
}

func (s *confdbSuite) TestGetErrorHandling(c *C) {
	s.setFeatureFlag(c)

	type test struct {
		name   string
		err    error
		status int
		kind   client.ErrorKind
	}

	view := s.schema.View("wifi-setup")
	restore := daemon.MockConfdbstateGetView(func(_ *state.State, acc, confdbSchema, viewName string) (*confdb.View, error) {
		return view, nil
	})
	defer restore()

	for _, t := range []test{
		{name: "no data", err: confdb.NewNoDataError(view, nil), status: 400, kind: client.ErrorKindConfigNoSuchOption},
		{name: "no view", err: &confdbstate.NoViewError{}, status: 400, kind: client.ErrorKindOptionNotAvailable},
		{name: "no match", err: confdb.NewNoMatchError(view, "", nil), status: 400, kind: client.ErrorKindOptionNotAvailable},
		{name: "unmatched constraints", err: &confdb.UnmatchedConstraintsError{}, status: 400},
		{name: "unconstrained filter params", err: &confdb.UnconstrainedParamsError{}, status: 400},
		{name: "internal", err: errors.New("internal"), status: 500},
	} {
		restore := daemon.MockConfdbstateReadConfdb(func(context.Context, *state.State, *confdb.View, []string, map[string]any, confdb.Access) (string, error) {
			return "", t.err
		})

		cmt := Commentf("%s test", t.name)
		req, err := http.NewRequest("GET", "/v2/confdb/system/network/wifi-setup?keys=ssid", nil)
		c.Assert(err, IsNil, cmt)
		req.RemoteAddr = "pid=100;uid=1000;socket=;"

		rspe := s.errorReq(c, req, nil, actionIsExpected)
		c.Check(rspe.Status, Equals, t.status, cmt)
		c.Check(rspe.Kind, Equals, t.kind, cmt)
		restore()
	}
}

func (s *confdbSuite) TestGetViewMisshapenQuery(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(_ *state.State, acc, confdbSchema, viewName string) (*confdb.View, error) {
		c.Assert(acc, Equals, "system")
		c.Assert(confdbSchema, Equals, "network")
		c.Assert(viewName, Equals, "wifi-setup")

		return s.schema.View(viewName), nil
	})
	defer restore()

	restore = daemon.MockConfdbstateReadConfdb(func(_ context.Context, _ *state.State, _ *confdb.View, requests []string, _ map[string]any, _ confdb.Access) (string, error) {
		c.Check(requests, DeepEquals, []string{"foo.bar", "[1].foo", "foo"})
		return "123", nil
	})
	defer restore()

	req, err := http.NewRequest("GET", "/v2/confdb/system/network/wifi-setup?keys=,foo.bar,,[1].foo,foo,", nil)
	c.Assert(err, IsNil)
	req.RemoteAddr = "pid=100;uid=1000;socket=;"

	rspe := s.asyncReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 202)
	c.Check(rspe.Change, Equals, "123")
}

func (s *confdbSuite) TestSetView(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(st *state.State, account, confdbName, viewName string) (*confdb.View, error) {

		return s.schema.View(viewName), nil
	})
	defer restore()

	type test struct {
		name  string
		value any
	}

	for _, t := range []test{
		{name: "string", value: "foo"},
		{name: "integer", value: float64(123)},
		{name: "list", value: []any{"foo", "bar"}},
		{name: "map", value: map[string]any{"foo": "bar"}},
	} {
		cmt := Commentf("%s test", t.name)

		var called bool
		restoreSet := daemon.MockConfdbstateWriteConfdb(func(ctx context.Context, _ *state.State, view *confdb.View, values map[string]any) (string, error) {
			called = true
			_, ok := ctx.Deadline()
			c.Check(ok, Equals, false)

			c.Assert(view.Name, Equals, "wifi-setup", cmt)
			c.Assert(values, DeepEquals, map[string]any{"ssid": t.value}, cmt)
			return "123", nil
		})

		jsonVal, err := json.Marshal(t.value)
		c.Check(err, IsNil, cmt)

		buf := bytes.NewBufferString(fmt.Sprintf(`{"values":{"ssid": %s}}`, jsonVal))
		req, err := http.NewRequest("PUT", "/v2/confdb/system/network/wifi-setup", buf)
		c.Check(err, IsNil, cmt)
		req.Header.Set("Content-Type", "application/json")

		rspe := s.asyncReq(c, req, nil, actionIsExpected)
		c.Assert(rspe.Status, Equals, 202, cmt)
		c.Assert(rspe.Change, Equals, "123", cmt)
		c.Assert(called, Equals, true, cmt)

		restoreSet()
	}
}

func (s *confdbSuite) TestSetEmpty(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(st *state.State, account, confdbName, viewName string) (*confdb.View, error) {
		return s.schema.View(viewName), nil
	})
	defer restore()

	var called bool
	restore = daemon.MockConfdbstateWriteConfdb(func(context.Context, *state.State, *confdb.View, map[string]any) (string, error) {
		called = true
		return "", nil
	})
	defer restore()

	for _, val := range []string{"", `"values":{}`} {
		buf := bytes.NewBufferString(fmt.Sprintf(`{%s}`, val))
		req, err := http.NewRequest("PUT", "/v2/confdb/system/network/wifi-setup", buf)
		c.Check(err, IsNil)
		req.Header.Set("Content-Type", "application/json")

		rspe := s.errorReq(c, req, nil, actionIsExpected)
		c.Assert(rspe.Status, Equals, 400)
		c.Assert(rspe.Message, Equals, "cannot write confdb: request body contains no values")
		c.Assert(called, Equals, false)
	}
}

func (s *confdbSuite) TestUnsetView(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(st *state.State, account, confdbName, viewName string) (*confdb.View, error) {
		return s.schema.View(viewName), nil
	})
	defer restore()

	s.st.Lock()
	tx, err := confdbstate.NewTransaction(s.st, "system", "network")
	s.st.Unlock()
	c.Assert(err, IsNil)

	path, err := confdb.ParsePathIntoAccessors("wifi.ssid", confdb.ParseOptions{})
	c.Assert(err, IsNil)

	err = tx.Set(path, "foo")
	c.Assert(err, IsNil)

	var called bool
	restore = daemon.MockConfdbstateWriteConfdb(func(_ context.Context, _ *state.State, view *confdb.View, values map[string]any) (string, error) {
		called = true
		c.Assert(view.Name, Equals, "wifi-setup")
		c.Assert(values, DeepEquals, map[string]any{"ssid": nil})
		return "123", nil
	})
	defer restore()

	buf := bytes.NewBufferString(`{"values":{"ssid": null}}`)
	req, err := http.NewRequest("PUT", "/v2/confdb/system/network/wifi-setup", buf)
	c.Check(err, IsNil)
	req.Header.Set("Content-Type", "application/json")

	rspe := s.asyncReq(c, req, nil, actionIsExpected)
	c.Assert(rspe.Status, Equals, 202)
	c.Assert(rspe.Change, Equals, "123")
	c.Assert(called, Equals, true)
}

func (s *confdbSuite) TestSetViewError(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(st *state.State, account, confdbName, viewName string) (*confdb.View, error) {
		return s.schema.View(viewName), nil
	})
	defer restore()

	type test struct {
		name   string
		err    error
		status int
		kind   client.ErrorKind
	}

	view := s.schema.View("wifi-setup")
	for _, t := range []test{
		{name: "no data", err: confdb.NewNoDataError(view, nil), status: 400, kind: client.ErrorKindConfigNoSuchOption},
		{name: "no match", err: confdb.NewNoMatchError(view, "", nil), status: 400, kind: client.ErrorKindOptionNotAvailable},
		{name: "internal", err: errors.New("internal"), status: 500},
		{name: "bad query", err: &confdb.BadRequestError{}, status: 400},
	} {
		restore := daemon.MockConfdbstateWriteConfdb(func(context.Context, *state.State, *confdb.View, map[string]any) (string, error) {
			return "", t.err
		})
		cmt := Commentf("%s test", t.name)

		buf := bytes.NewBufferString(`{"values":{"ssid": "foo"}}`)
		req, err := http.NewRequest("PUT", "/v2/confdb/system/network/wifi-setup", buf)
		c.Assert(err, IsNil, cmt)
		req.Header.Set("Content-Type", "application/json")

		rspe := s.errorReq(c, req, nil, actionIsExpected)
		c.Check(rspe.Status, Equals, t.status, cmt)
		c.Check(rspe.Kind, Equals, t.kind, cmt)
		restore()
	}
}

func (s *confdbSuite) TestSetViewBadRequests(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateWriteConfdb(func(context.Context, *state.State, *confdb.View, map[string]any) (string, error) {
		err := errors.New("unexpected call to confdbstate.Set")
		c.Error(err)
		return "", err
	})
	defer restore()

	type testcase struct {
		body   *bytes.Buffer
		errMsg string
	}
	tcs := []testcase{
		{
			body:   &bytes.Buffer{},
			errMsg: "cannot decode confdb request body: EOF",
		},
		{
			body:   bytes.NewBufferString("{"),
			errMsg: "cannot decode confdb request body: unexpected EOF",
		},
	}

	for _, tc := range tcs {
		req, err := http.NewRequest("PUT", "/v2/confdb/system/network/wifi-setup", tc.body)
		req.Header.Set("Content-Type", "application/json")
		c.Assert(err, IsNil)

		rspe := s.errorReq(c, req, nil, actionIsExpected)
		c.Check(rspe.Status, Equals, 400)
		c.Check(rspe.Message, Equals, tc.errMsg)
	}
}

func (s *confdbSuite) TestSetFailUnsetFeatureFlag(c *C) {
	restore := daemon.MockConfdbstateGetView(func(st *state.State, account, confdbName, viewName string) (*confdb.View, error) {
		err := fmt.Errorf("unexpected call to confdbstate")
		c.Error(err)
		return nil, err
	})
	defer restore()

	buf := bytes.NewBufferString(`{"values":{"a.b.c": "foo"}}`)
	req, err := http.NewRequest("PUT", "/v2/confdb/system/network/wifi-setup", buf)
	req.Header.Set("Content-Type", "application/json")
	c.Assert(err, IsNil)

	rspe := s.errorReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 400)
	c.Check(rspe.Message, Equals, `feature flag "confdb" is disabled: set 'experimental.confdb' to true`)
	c.Check(rspe.Kind, Equals, client.ErrorKind(""))
}

func (s *confdbSuite) TestGetFailUnsetFeatureFlag(c *C) {
	req, err := http.NewRequest("GET", "/v2/confdb/system/network/wifi-setup?keys=my-key", nil)
	c.Assert(err, IsNil)

	rspe := s.errorReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 400)
	c.Check(rspe.Message, Equals, `feature flag "confdb" is disabled: set 'experimental.confdb' to true`)
	c.Check(rspe.Kind, Equals, client.ErrorKind(""))
}

func (s *confdbSuite) TestGetNoKeys(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(_ *state.State, acc, confdbSchema, viewName string) (*confdb.View, error) {
		c.Assert(acc, Equals, "system")
		c.Assert(confdbSchema, Equals, "network")
		c.Assert(viewName, Equals, "wifi-setup")

		return s.schema.View(viewName), nil
	})
	defer restore()

	restore = daemon.MockConfdbstateReadConfdb(func(_ context.Context, _ *state.State, _ *confdb.View, requests []string, _ map[string]any, _ confdb.Access) (string, error) {
		c.Assert(requests, IsNil)
		return "123", nil
	})
	defer restore()

	req, err := http.NewRequest("GET", "/v2/confdb/system/network/wifi-setup", nil)
	c.Assert(err, IsNil)
	req.RemoteAddr = "pid=100;uid=1000;socket=;"

	rspe := s.asyncReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 202)
	c.Check(rspe.Change, Equals, "123")
}

func (s *confdbSuite) TestGetConstraints(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(_ *state.State, _, _, _ string) (*confdb.View, error) {
		return s.schema.View("wifi-setup"), nil
	})
	defer restore()

	restore = daemon.MockConfdbstateReadConfdb(func(_ context.Context, _ *state.State, _ *confdb.View, requests []string, constraints map[string]any, _ confdb.Access) (string, error) {
		c.Assert(requests, DeepEquals, []string{"ssid"})
		c.Assert(constraints, DeepEquals, map[string]any{
			"foo": "bar",
			"baz": "abc",
		})
		return "123", nil
	})
	defer restore()

	query := url.Values{}
	query.Add("keys", "ssid")
	cstrs, err := json.Marshal(map[string]string{"foo": "bar", "baz": "abc"})
	c.Assert(err, IsNil)
	query.Add("constraints", string(cstrs))
	endpoint := "/v2/confdb/system/network/wifi-setup?" + query.Encode()

	req, err := http.NewRequest("GET", endpoint, nil)
	c.Assert(err, IsNil)
	req.RemoteAddr = "pid=100;uid=1000;socket=;"

	rspe := s.asyncReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 202)
	c.Check(rspe.Change, Equals, "123")
}

func (s *confdbSuite) TestGetBadConstraints(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(_ *state.State, _ string, _ string, view string) (*confdb.View, error) {
		return s.schema.View(view), nil
	})
	defer restore()

	restore = daemon.MockConfdbstateReadConfdb(func(context.Context, *state.State, *confdb.View, []string, map[string]any, confdb.Access) (string, error) {
		c.Error("unexpected call to LoadConfdbAsync")
		return "", errors.New("unexpected call to LoadConfdbAsync")
	})
	defer restore()

	type testcase struct {
		constraint string
		err        string
	}

	tcs := []testcase{
		{
			constraint: `not-json`,
			err:        `"constraints" must be a JSON object`,
		},
		{
			constraint: `null`,
			err:        `"constraints" must be a JSON object`,
		},
		{
			constraint: `{invalid}`,
			err:        `"constraints" must be a JSON object`,
		},
		{
			constraint: `["foo"]`,
			err:        `"constraints" must be a JSON object`,
		},
		{
			constraint: `{"foo": ["bar"]}`,
			err:        `constraint value must be non-null scalar but parameter "foo" has array constraint`,
		},
		{
			constraint: `{"foo": {"bar": "baz"}}`,
			err:        `constraint value must be non-null scalar but parameter "foo" has map constraint`,
		},
		{
			constraint: `{"foo": null}`,
			err:        `constraint value must be non-null scalar but parameter "foo" has null constraint`,
		},
	}

	for i, tc := range tcs {
		cmt := Commentf("failed test %d/%d", i+1, len(tcs))
		query := url.Values{}
		query.Add("keys", "ssid")
		query.Add("constraints", tc.constraint)
		endpoint := "/v2/confdb/system/network/wifi-setup?" + query.Encode()

		req, err := http.NewRequest("GET", endpoint, nil)
		c.Assert(err, IsNil, cmt)

		rspe := s.errorReq(c, req, nil, actionIsExpected)
		c.Check(rspe.Status, Equals, 400, cmt)
		c.Check(rspe.Message, Matches, tc.err, cmt)
	}
}

func (s *confdbSuite) TestReadAccessTimeout(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(_ *state.State, _, _, _ string) (*confdb.View, error) {
		return s.schema.View("wifi-setup"), nil
	})
	defer restore()

	restore = daemon.MockConfdbstateReadConfdb(func(ctx context.Context, _ *state.State, _ *confdb.View, _ []string, _ map[string]any, _ confdb.Access) (string, error) {
		deadline, ok := ctx.Deadline()
		c.Assert(ok, Equals, true)
		c.Check(time.Until(deadline) <= 10*time.Second, Equals, true)
		return "123", nil
	})
	defer restore()

	type testcase struct {
		timeout  string
		error    string
		ctxCheck func(ctx context.Context)
	}

	tcs := []testcase{
		{
			timeout: "10s",
			ctxCheck: func(ctx context.Context) {
				deadline, ok := ctx.Deadline()
				c.Assert(ok, Equals, true)
				c.Check(time.Until(deadline) <= 10*time.Second, Equals, true)
			},
		},
		{
			// this might seen useless but it could be used to do an attempt at read
			// that would exit immediately if it had to wait
			timeout: "0s",
			ctxCheck: func(ctx context.Context) {
				deadline, ok := ctx.Deadline()
				c.Assert(ok, Equals, true)
				c.Check(time.Until(deadline) <= 0, Equals, true)
			},
		},
		{
			timeout: "-10m",
			error:   "cannot read confdb: access timeout must be non-negative",
		},
		{
			timeout: "invalid",
			error:   "cannot read confdb: invalid access-timeout: \"invalid\"",
		},
	}

	for _, tc := range tcs {
		req, err := http.NewRequest("GET", "/v2/confdb/system/network/wifi-setup?keys=ssid&access-timeout="+tc.timeout, nil)
		c.Assert(err, IsNil)
		req.RemoteAddr = "pid=100;uid=1000;socket=;"

		if tc.error == "" {
			restore = daemon.MockConfdbstateReadConfdb(func(ctx context.Context, _ *state.State, _ *confdb.View, _ []string, _ map[string]any, _ confdb.Access) (string, error) {
				tc.ctxCheck(ctx)
				return "123", nil
			})

			rspe := s.asyncReq(c, req, nil, actionIsExpected)
			c.Check(rspe.Status, Equals, 202)
			c.Check(rspe.Change, Equals, "123")
			restore()
		} else {
			rspe := s.errorReq(c, req, nil, actionIsExpected)
			c.Check(rspe.Status, Equals, 400)
			c.Check(rspe.Message, Matches, tc.error)
		}
	}
}

func (s *confdbSuite) TestWriteAccessTimeout(c *C) {
	s.setFeatureFlag(c)

	restore := daemon.MockConfdbstateGetView(func(_ *state.State, _, _, _ string) (*confdb.View, error) {
		return s.schema.View("wifi-setup"), nil
	})
	defer restore()

	restore = daemon.MockConfdbstateWriteConfdb(func(ctx context.Context, _ *state.State, _ *confdb.View, _ map[string]any) (string, error) {
		deadline, ok := ctx.Deadline()
		c.Assert(ok, Equals, true)
		c.Check(time.Until(deadline) <= 10*time.Second, Equals, true)
		return "123", nil
	})
	defer restore()

	type testcase struct {
		timeout  string
		error    string
		ctxCheck func(ctx context.Context)
	}

	tcs := []testcase{
		{
			timeout: `10s`,
			ctxCheck: func(ctx context.Context) {
				deadline, ok := ctx.Deadline()
				c.Assert(ok, Equals, true)
				c.Check(time.Until(deadline) <= 10*time.Second, Equals, true)
			},
		},
		{
			timeout: `0s`,
			ctxCheck: func(ctx context.Context) {
				_, ok := ctx.Deadline()
				c.Assert(ok, Equals, true)
			},
		},
		{
			timeout: `-10m`,
			error:   "cannot write confdb: access timeout must be non-negative",
		},
		{
			timeout: `invalid`,
			error:   "cannot write confdb: invalid access-timeout: \"invalid\"",
		},
	}

	for i, tc := range tcs {
		cmt := Commentf("testcase %d/%d", i+1, len(tcs))
		body := fmt.Sprintf(`{"values": {"ssid": "foo"}, "options": {"access-timeout": %q}}`, tc.timeout)

		req, err := http.NewRequest("PUT", "/v2/confdb/system/network/wifi-setup", bytes.NewBufferString(body))
		c.Assert(err, IsNil, cmt)
		req.Header.Set("Content-Type", "application/json")
		req.RemoteAddr = "pid=100;uid=1000;socket=;"

		if tc.error == "" {
			restore = daemon.MockConfdbstateWriteConfdb(func(ctx context.Context, _ *state.State, _ *confdb.View, _ map[string]any) (string, error) {
				tc.ctxCheck(ctx)
				return "123", nil
			})

			rspe := s.asyncReq(c, req, nil, actionIsExpected)
			c.Check(rspe.Status, Equals, 202, cmt)
			c.Check(rspe.Change, Equals, "123", cmt)
			restore()
		} else {
			rspe := s.errorReq(c, req, nil, actionIsExpected)
			c.Check(rspe.Status, Equals, 400, cmt)
			c.Check(rspe.Message, Matches, tc.error, cmt)
		}
	}
}

type confdbControlSuite struct {
	apiBaseSuite

	st     *state.State
	brands *assertstest.SigningAccounts
	serial *asserts.Serial
}

var _ = Suite(&confdbControlSuite{})

var (
	deviceKey, _ = assertstest.GenerateKey(752)
)

func (s *confdbControlSuite) SetUpTest(c *C) {
	s.apiBaseSuite.SetUpTest(c)
	s.expectWriteAccess(daemon.AuthenticatedAccess{Polkit: "io.snapcraft.snapd.manage"})

	s.st = state.New(nil)
	o := overlord.MockWithState(s.st)
	s.d = daemon.NewWithOverlord(o)

	hookMgr, err := hookstate.Manager(s.st, o.TaskRunner())
	c.Assert(err, check.IsNil)

	deviceMgr, err := devicestate.Manager(s.st, hookMgr, o.TaskRunner(), nil)
	c.Assert(err, check.IsNil)
	o.AddManager(deviceMgr)

	assertMgr, err := assertstate.Manager(s.st, o.TaskRunner())
	c.Assert(err, check.IsNil)
	o.AddManager(assertMgr)

	storeStack := assertstest.NewStoreStack("can0nical", nil)
	s.brands = assertstest.NewSigningAccounts(storeStack)
}

func (s *confdbControlSuite) setFeatureFlag(c *C, confName string) {
	s.st.Lock()
	tr := config.NewTransaction(s.st)
	err := tr.Set("core", confName, true)
	c.Assert(err, IsNil)
	tr.Commit()
	s.st.Unlock()
}

func (s *confdbControlSuite) prereqs(c *C) {
	s.setFeatureFlag(c, "experimental.confdb")
	s.setFeatureFlag(c, "experimental.confdb-control")

	s.st.Lock()
	encDevKey, _ := asserts.EncodePublicKey(deviceKey.PublicKey())
	a, err := s.brands.Signing("can0nical").Sign(asserts.SerialType, map[string]any{
		"brand-id":            "can0nical",
		"model":               "generic-classic",
		"serial":              "serial-serial",
		"device-key":          string(encDevKey),
		"device-key-sha3-384": deviceKey.PublicKey().ID(),
		"timestamp":           time.Now().Format(time.RFC3339),
	}, nil, "")
	c.Assert(err, IsNil)

	err = assertstate.Add(s.st, a)
	c.Assert(err, IsNil)
	s.serial = a.(*asserts.Serial)

	devicestatetest.SetDevice(s.st, &auth.DeviceState{
		Brand:  "can0nical",
		Model:  "generic-classic",
		Serial: "serial-serial",
	})
	s.st.Unlock()
}

func (s *confdbControlSuite) TestConfdbFlagNotEnabled(c *C) {
	req, err := http.NewRequest("POST", "/v2/confdb", nil)
	c.Assert(err, IsNil)

	rspe := s.errorReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 400)
	c.Check(rspe.Message, Equals, `feature flag "confdb" is disabled: set 'experimental.confdb' to true`)
}

func (s *confdbControlSuite) TestConfdbControlFlagNotEnabled(c *C) {
	s.setFeatureFlag(c, "experimental.confdb")

	req, err := http.NewRequest("POST", "/v2/confdb", nil)
	c.Assert(err, IsNil)

	rspe := s.errorReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 400)
	c.Check(rspe.Message, Equals, `feature flag "confdb-control" is disabled: set 'experimental.confdb-control' to true`)
}

func (s *confdbControlSuite) TestConfdbControlActionNoSerial(c *C) {
	s.setFeatureFlag(c, "experimental.confdb")
	s.setFeatureFlag(c, "experimental.confdb-control")

	req, err := http.NewRequest("POST", "/v2/confdb", nil)
	c.Assert(err, IsNil)

	rspe := s.errorReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 500)
	c.Check(rspe.Message, Equals, "device has no identity yet")
}

func (s *confdbControlSuite) TestConfdbControlActionOK(c *C) {
	s.prereqs(c)
	jane := map[string]any{
		"operators":       []any{"jane"},
		"authentications": []any{"store"},
		"views":           []any{"account/confdb/view"},
	}
	restore := daemon.MockDeviceStateSignConfdbControl(func(m *devicestate.DeviceManager, groups []any, revision int) (*asserts.ConfdbControl, error) {
		a, err := asserts.SignWithoutAuthority(asserts.ConfdbControlType, map[string]any{
			"brand-id": "can0nical",
			"model":    "generic-classic",
			"serial":   "serial-serial",
			"groups":   []any{jane},
		}, nil, deviceKey)
		c.Assert(err, IsNil)
		return a.(*asserts.ConfdbControl), nil
	})
	defer restore()

	body := `{"action": "delegate", "operator-id": "jane", "authentications": ["store"], "views": ["account/confdb/view"]}`
	req, err := http.NewRequest("POST", "/v2/confdb", bytes.NewBufferString(body))
	c.Assert(err, IsNil)
	s.asUserAuth(c, req)

	rsp := s.syncReq(c, req, nil, actionIsExpected)
	c.Assert(rsp.Status, Equals, 200)
	c.Check(rsp.Result, DeepEquals, nil)

	s.st.Lock()
	a, err := assertstate.DB(s.st).Find(
		asserts.ConfdbControlType,
		map[string]string{"brand-id": "can0nical", "model": "generic-classic", "serial": "serial-serial"},
	)
	c.Assert(err, IsNil)
	cc := a.(*asserts.ConfdbControl)
	ctrl := cc.Control()
	c.Check(ctrl.Groups(), DeepEquals, []any{jane})
	s.st.Unlock()
}

func (s *confdbControlSuite) TestConfdbControlActionSigningErr(c *C) {
	s.prereqs(c)

	body := `{"action": "delegate", "operator-id": "jane", "authentications": ["store"], "views": ["account/confdb/view"]}`
	req, err := http.NewRequest("POST", "/v2/confdb", bytes.NewBufferString(body))
	c.Assert(err, IsNil)
	s.asUserAuth(c, req)

	rspe := s.errorReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 500)
	c.Check(rspe.Message, Equals, "cannot sign confdb-control without device key")
}

func (s *confdbControlSuite) TestConfdbControlActionAckErr(c *C) {
	s.prereqs(c)
	restore := daemon.MockDeviceStateSignConfdbControl(func(m *devicestate.DeviceManager, groups []any, revision int) (*asserts.ConfdbControl, error) {
		a := assertstest.FakeAssertion(
			map[string]any{
				"type":     "confdb-control",
				"brand-id": "can0nical",
				"model":    "generic-classic",
				"serial":   "serial-serial",
				"groups":   []any{},
			},
		)
		return a.(*asserts.ConfdbControl), nil
	})
	defer restore()

	s.st.Lock()
	jane := map[string]any{
		"operators":       []any{"jane"},
		"authentications": []any{"store"},
		"views":           []any{"account/confdb/view"},
	}
	a, err := asserts.SignWithoutAuthority(asserts.ConfdbControlType, map[string]any{
		"brand-id": "can0nical",
		"model":    "generic-classic",
		"serial":   "serial-serial",
		"groups":   []any{jane},
	}, nil, deviceKey)
	c.Assert(err, IsNil)
	assertstate.Add(s.st, a)
	s.st.Unlock()

	body := `{"action": "undelegate", "operator-id": "jane", "authentications": ["store"]}`
	req, err := http.NewRequest("POST", "/v2/confdb", bytes.NewBufferString(body))
	c.Assert(err, IsNil)
	s.asUserAuth(c, req)

	rspe := s.errorReq(c, req, nil, actionIsExpected)
	c.Check(rspe.Status, Equals, 500)
	c.Check(
		rspe.Message,
		Equals,
		`cannot check no-authority assertion type "confdb-control": confdb-control's signing key doesn't match the device key`,
	)
}

func (s *confdbControlSuite) TestConfdbControlActionInvalidRequest(c *C) {
	s.prereqs(c)

	type testcase struct {
		body   string
		errMsg string
	}
	tcs := []testcase{
		{
			body:   "}",
			errMsg: "cannot decode request body: invalid character '}' looking for beginning of value",
		},
		{
			body:   `{"action": "unknown", "operator-id": "jane"}`,
			errMsg: `unknown action "unknown"`,
		},
		{
			body:   `{"action": "delegate", "operator-id": "jane", "authentications": ["unknown"]}`,
			errMsg: "cannot delegate: invalid authentication method: unknown",
		},
	}

	for _, tc := range tcs {
		req, err := http.NewRequest("POST", "/v2/confdb", bytes.NewBufferString(tc.body))
		c.Assert(err, IsNil)
		s.asUserAuth(c, req)

		rspe := s.errorReq(c, req, nil, actionExpectedBool(!strings.Contains(tc.errMsg, "unknown action")))
		c.Check(rspe.Status, Equals, 400)
		c.Check(rspe.Message, Equals, tc.errMsg)
	}
}
