Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

feat: declarative configuration with plan, apply, and API ownership (#6507)

ABirde216c28863cd
diff --git a/AGENTS.md b/AGENTS.md
index ae12e6ad1..5716713e3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -37,6 +37,7 @@ Run from the repository root unless a command starts with `cd`.
```bash
# Backend
go run -buildvcs=true ./cmd/memos --port 8081 # Start backend with commit-derived CalVer
+go run -buildvcs=true ./cmd/memos config plan --data DIR --config-dir DIR # Declarative configuration: also validate, apply, state
go test ./... # Run all Go tests
go test -v ./store/... # Store tests, including DB drivers via TestContainers
go test -v -race ./server/... # Server tests with race detector
@@ -75,7 +76,7 @@ Every root folder is named for what it holds. Read the folder's `doc.go` or `REA
| `server/frontend/` | Static SPA serving; `dist/` is the built SPA baked in by `go:embed` | |
| `server/mcp/` | Model Context Protocol server | |
| `server/auth/` | JWT access tokens, refresh tokens, PAT handling | |
-| `core/` | Business rules with no HTTP and no SQL: `access`, `notification`, `memopayload`, `memoexport`, `usagelimit` | store, provider, markdown, filter, internal |
+| `core/` | Business rules with no HTTP and no SQL: `access`, `notification`, `memopayload`, `memoexport`, `usagelimit`, `identityprovider`, `instancesetting`, `user`, `configuration` | store, provider, markdown, filter, internal |
| `store/` | Store facade, cache, migrations, `Driver` interface; `store/db/{sqlite,mysql,postgres}/` implement it | provider, markdown, filter, internal |
| `markdown/` | Markdown engine: parser, AST, memos syntax extensions, renderer, memo payload | proto/gen, internal |
| `filter/` | CEL filter compiler: parse to IR, render to SQL per driver, filterable field schema | internal |
@@ -94,6 +95,8 @@ Layering rules, enforced by `depguard` in `.golangci.yaml`:
File convention inside `server/api/`: `<resource>_service.go` holds the RPC handlers, `<resource>_service_converters.go` the
store↔proto conversion, and `<resource>_service_<topic>.go` further splits. Extend the matching file; do not add `*_helpers2.go`.
+Identity providers and instance settings are the exception: declarative configuration files use their API messages, so their
+conversion lives in `core/identityprovider` and `core/instancesetting`, and `server/api` keeps only response redaction.
Black-box service tests live in `server/api/test/`, unit tests next to the code.
## Change Routing
diff --git a/cmd/memos/config.go b/cmd/memos/config.go
new file mode 100644
index 000000000..b51881c90
--- /dev/null
+++ b/cmd/memos/config.go
@@ -0,0 +1,320 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "github.com/spf13/viper"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/usememos/memos/core/configuration"
+ "github.com/usememos/memos/internal/profile"
+ "github.com/usememos/memos/internal/version"
+ apipb "github.com/usememos/memos/proto/gen/api"
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+ "github.com/usememos/memos/store/db"
+)
+
+// The plan exit statuses of --detailed-exitcode, matching terraform plan.
+const (
+ planExitChanges = 2
+)
+
+var (
+ configCmd = &cobra.Command{
+ Use: "config",
+ Short: "Work with declarative configuration files",
+ }
+ configValidateCmd = &cobra.Command{
+ Use: "validate",
+ Short: "Check the configuration files without a database",
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ return runConfigValidate(flagOrSetting(cmd, "config-dir"), configuration.OSResolver(), cmd.OutOrStdout(), cmd.ErrOrStderr())
+ },
+ }
+ configPlanCmd = &cobra.Command{
+ Use: "plan",
+ Short: "Show what applying the configuration files would change, without writing",
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ storeInstance, err := openConfigurationStore(cmd.Context(), cmd, false)
+ if err != nil {
+ return err
+ }
+ defer storeInstance.Close()
+ options := planOptions{}
+ options.json, _ = cmd.Flags().GetBool("json")
+ options.detailedExitCode, _ = cmd.Flags().GetBool("detailed-exitcode")
+ return runConfigPlan(cmd.Context(), flagOrSetting(cmd, "config-dir"), configuration.OSResolver(), storeInstance, options, cmd.OutOrStdout(), cmd.ErrOrStderr())
+ },
+ }
+ configApplyCmd = &cobra.Command{
+ Use: "apply",
+ Short: "Apply the configuration files to the instance in one transaction",
+ Long: "Apply migrates the database as server startup does, plans the configuration files against it, and writes " +
+ "the plan and the state record in one transaction: it either completes or changes nothing.",
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ storeInstance, err := openConfigurationStore(cmd.Context(), cmd, true)
+ if err != nil {
+ return err
+ }
+ defer storeInstance.Close()
+ jsonOutput, _ := cmd.Flags().GetBool("json")
+ return runConfigApply(cmd.Context(), flagOrSetting(cmd, "config-dir"), configuration.OSResolver(), storeInstance, configMetadata("cli"), jsonOutput, cmd.OutOrStdout(), cmd.ErrOrStderr())
+ },
+ }
+ configStateCmd = &cobra.Command{
+ Use: "state",
+ Short: "Show the state record: the managed resources and the last apply",
+ Args: cobra.NoArgs,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ storeInstance, err := openConfigurationStore(cmd.Context(), cmd, false)
+ if err != nil {
+ return err
+ }
+ defer storeInstance.Close()
+ jsonOutput, _ := cmd.Flags().GetBool("json")
+ return runConfigState(cmd.Context(), storeInstance, jsonOutput, cmd.OutOrStdout())
+ },
+ }
+)
+
+func init() {
+ // The server's own flags are local to the root command, so these are
+ // declared again and read through flagOrSetting rather than bound to the
+ // same viper keys, which would unbind the server's flags.
+ flags := configCmd.PersistentFlags()
+ flags.String("config-dir", configuration.DefaultDir, "directory of declarative configuration files")
+ flags.String("data", "", "data directory of the instance")
+ flags.String("driver", "sqlite", "database driver of the instance (sqlite, mysql, postgres)")
+ flags.String("dsn", "", "database source name of the instance")
+
+ configPlanCmd.Flags().Bool("json", false, "print the plan as JSON")
+ configPlanCmd.Flags().Bool("detailed-exitcode", false, "exit 0 for no changes, 1 for an error, 2 for changes")
+ configApplyCmd.Flags().Bool("json", false, "print the applied plan as JSON")
+ configStateCmd.Flags().Bool("json", false, "print the state record as JSON")
+
+ configCmd.AddCommand(configValidateCmd, configPlanCmd, configApplyCmd, configStateCmd)
+ rootCmd.AddCommand(configCmd)
+}
+
+// flagOrSetting returns a config command's flag when it was given, and
+// otherwise the setting viper resolves from the environment and defaults.
+func flagOrSetting(cmd *cobra.Command, name string) string {
+ if flag := cmd.Flags().Lookup(name); flag != nil && flag.Changed {
+ return flag.Value.String()
+ }
+ if value := viper.GetString(name); value != "" {
+ return value
+ }
+ if flag := cmd.Flags().Lookup(name); flag != nil {
+ return flag.DefValue
+ }
+ return ""
+}
+
+// configMetadata identifies an apply in the state record by path and host.
+func configMetadata(path string) configuration.ApplyMetadata {
+ hostname, err := os.Hostname()
+ if err != nil {
+ hostname = "unknown"
+ }
+ return configuration.ApplyMetadata{AppliedBy: path + " " + hostname, Version: version.GetCurrentVersion(), Now: time.Now()}
+}
+
+// loadConfiguration loads dir, printing every problem on its own line so a
+// long list stays readable, and returns a one-line error for the exit status.
+func loadConfiguration(dir string, resolver configuration.Resolver, stderr io.Writer) (*configuration.Desired, error) {
+ desired, err := configuration.Load(dir, resolver)
+ var validationError *configuration.ValidationError
+ if errors.As(err, &validationError) {
+ for _, problem := range validationError.Problems {
+ fmt.Fprintln(stderr, "error:", problem)
+ }
+ noun := "problems"
+ if len(validationError.Problems) == 1 {
+ noun = "problem"
+ }
+ return nil, errors.Errorf("configuration in %s is invalid: %d %s", dir, len(validationError.Problems), noun)
+ }
+ if err != nil {
+ return nil, err
+ }
+ for _, warning := range desired.Warnings {
+ fmt.Fprintln(stderr, "warning:", warning)
+ }
+ return desired, nil
+}
+
+func runConfigValidate(dir string, resolver configuration.Resolver, stdout, stderr io.Writer) error {
+ // A missing directory is a valid, empty configuration at startup, but here
+ // it is more likely a mistyped --config-dir, so say so.
+ if _, err := os.Stat(dir); errors.Is(err, fs.ErrNotExist) {
+ fmt.Fprintf(stdout, "Configuration directory %s does not exist; there is nothing to validate.\n", dir)
+ return nil
+ }
+ desired, err := loadConfiguration(dir, resolver, stderr)
+ if err != nil {
+ return err
+ }
+ config := desired.Configuration
+ fmt.Fprintf(stdout, "Configuration in %s is valid: %d identity providers, %d instance settings, %d users.\n",
+ dir, len(config.IdentityProviders), len(config.InstanceSettings), len(config.Users))
+ return nil
+}
+
+type planOptions struct {
+ json bool
+ detailedExitCode bool
+}
+
+func runConfigPlan(ctx context.Context, dir string, resolver configuration.Resolver, reader configuration.Reader, options planOptions, stdout, stderr io.Writer) error {
+ if _, err := os.Stat(dir); errors.Is(err, fs.ErrNotExist) {
+ // An empty configuration is still worth planning: it shows every
+ // managed resource that now lacks a declaration.
+ fmt.Fprintf(stderr, "warning: configuration directory %s does not exist; planning an empty configuration\n", dir)
+ }
+ desired, err := loadConfiguration(dir, resolver, stderr)
+ if err != nil {
+ return err
+ }
+ plan, err := configuration.ComputePlan(ctx, desired, reader)
+ if err != nil {
+ return err
+ }
+ if err := printPlan(stdout, plan.Message, options.json); err != nil {
+ return err
+ }
+ if !plan.Valid() {
+ return errors.New("the plan cannot be applied")
+ }
+ if options.detailedExitCode && plan.HasChanges() {
+ return exitCodeError{code: planExitChanges}
+ }
+ return nil
+}
+
+// openConfigurationStore opens the instance database. To read, as plan and
+// state do, it never creates or migrates a database. To write, as apply does,
+// it migrates exactly as server startup would, creating a fresh one.
+func openConfigurationStore(ctx context.Context, cmd *cobra.Command, write bool) (*store.Store, error) {
+ instanceProfile := &profile.Profile{
+ Data: flagOrSetting(cmd, "data"),
+ Driver: flagOrSetting(cmd, "driver"),
+ DSN: flagOrSetting(cmd, "dsn"),
+ Version: version.GetCurrentVersion(),
+ Commit: version.Commit,
+ }
+ if instanceProfile.Data != "" {
+ if _, err := os.Stat(instanceProfile.Data); err != nil {
+ return nil, errors.Wrap(err, "failed to open the data directory")
+ }
+ }
+ if err := instanceProfile.Validate(); err != nil {
+ return nil, errors.Wrap(err, "failed to validate profile")
+ }
+ if instanceProfile.Driver == "sqlite" && !write {
+ if _, err := os.Stat(instanceProfile.DSN); errors.Is(err, fs.ErrNotExist) {
+ return nil, errors.Errorf("no SQLite database at %s; pass the instance's --data or --dsn", instanceProfile.DSN)
+ }
+ }
+ dbDriver, err := db.NewDBDriver(instanceProfile)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create database driver")
+ }
+ storeInstance := store.New(dbDriver, instanceProfile)
+ check := storeInstance.CheckSchemaCurrent
+ if write {
+ check = storeInstance.Migrate
+ }
+ if err := check(ctx); err != nil {
+ storeInstance.Close()
+ return nil, err
+ }
+ return storeInstance, nil
+}
+
+func runConfigApply(ctx context.Context, dir string, resolver configuration.Resolver, s *store.Store, metadata configuration.ApplyMetadata, jsonOutput bool, stdout, stderr io.Writer) error {
+ if _, err := os.Stat(dir); errors.Is(err, fs.ErrNotExist) {
+ fmt.Fprintf(stderr, "warning: configuration directory %s does not exist; applying an empty configuration\n", dir)
+ }
+ desired, err := loadConfiguration(dir, resolver, stderr)
+ if err != nil {
+ return err
+ }
+ plan, state, err := configuration.Apply(ctx, desired, s, metadata)
+ if err != nil {
+ return err
+ }
+ if err := printPlan(stdout, plan.Message, jsonOutput); err != nil {
+ return err
+ }
+ if !plan.Valid() {
+ return errors.New("the plan cannot be applied; nothing was written")
+ }
+ if !jsonOutput && plan.HasChanges() {
+ fmt.Fprintf(stdout, "\nApply complete. The state record is at serial %d.\n", state.Serial)
+ }
+ return nil
+}
+
+// printPlan writes a plan as text, or as the Plan message in JSON.
+func printPlan(stdout io.Writer, plan *apipb.Plan, jsonOutput bool) error {
+ if !jsonOutput {
+ configuration.RenderPlan(stdout, plan)
+ return nil
+ }
+ encoded, err := protojson.MarshalOptions{Multiline: true, Indent: " "}.Marshal(plan)
+ if err != nil {
+ return errors.Wrap(err, "failed to encode the plan")
+ }
+ fmt.Fprintln(stdout, string(encoded))
+ return nil
+}
+
+func runConfigState(ctx context.Context, s *store.Store, jsonOutput bool, stdout io.Writer) error {
+ state, err := s.GetConfigurationState(ctx)
+ if err != nil {
+ return err
+ }
+ if jsonOutput {
+ encoded, err := protojson.MarshalOptions{Multiline: true, Indent: " "}.Marshal(state)
+ if err != nil {
+ return errors.Wrap(err, "failed to encode the state record")
+ }
+ fmt.Fprintln(stdout, string(encoded))
+ return nil
+ }
+ if proto.Equal(state, &storepb.InstanceConfigurationState{}) {
+ fmt.Fprintln(stdout, "No configuration has been applied; nothing is managed.")
+ return nil
+ }
+ fmt.Fprintf(stdout, "Serial %d, applied %s by %s (Memos %s).\n", state.Serial,
+ time.Unix(state.AppliedTs, 0).UTC().Format(time.RFC3339), state.AppliedBy, state.Version)
+ width := 0
+ for _, resource := range state.Resources {
+ width = max(width, len(resource.Name))
+ }
+ for _, resource := range state.Resources {
+ line := fmt.Sprintf(" %-*s %-16s %s managed: %s", width, resource.Name, resource.Kind, resource.Source, strings.Join(resource.ManagedFields, ", "))
+ if len(resource.IgnoredFields) > 0 {
+ line += "; ignored: " + strings.Join(resource.IgnoredFields, ", ")
+ }
+ if resource.PreventDestroy {
+ line += "; prevent destroy"
+ }
+ fmt.Fprintln(stdout, line)
+ }
+ return nil
+}
diff --git a/cmd/memos/config_test.go b/cmd/memos/config_test.go
new file mode 100644
index 000000000..806cd6705
--- /dev/null
+++ b/cmd/memos/config_test.go
@@ -0,0 +1,161 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/spf13/cobra"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/usememos/memos/core/configuration"
+ "github.com/usememos/memos/internal/profile"
+ "github.com/usememos/memos/internal/version"
+ apipb "github.com/usememos/memos/proto/gen/api"
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+ "github.com/usememos/memos/store/db"
+)
+
+func TestConfigValidate(t *testing.T) {
+ dir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(dir, "users.json"),
+ []byte(`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}]}`), 0o600))
+
+ var stdout, stderr bytes.Buffer
+ require.NoError(t, runConfigValidate(dir, configuration.OSResolver(), &stdout, &stderr))
+ require.Contains(t, stdout.String(), "is valid: 0 identity providers, 0 instance settings, 1 users")
+ require.Empty(t, stderr.String())
+
+ require.NoError(t, os.WriteFile(filepath.Join(dir, "bad.json"), []byte(`{"users":[{"name":"users/root"}]}`), 0o600))
+ stdout.Reset()
+ err := runConfigValidate(dir, configuration.OSResolver(), &stdout, &stderr)
+ require.ErrorContains(t, err, "is invalid: 2 problems")
+ require.Contains(t, stderr.String(), "error: bad.json: users[0].username must equal")
+ require.Contains(t, stderr.String(), "error: bad.json: users[0].role is required")
+ require.Empty(t, stdout.String())
+
+ stdout.Reset()
+ require.NoError(t, runConfigValidate(filepath.Join(dir, "missing"), configuration.OSResolver(), &stdout, &stderr))
+ require.Contains(t, stdout.String(), "does not exist")
+}
+
+func TestConfigCommandsDoNotInheritServerFlags(t *testing.T) {
+ for _, cmd := range []*cobra.Command{configValidateCmd, configPlanCmd} {
+ require.Nil(t, cmd.InheritedFlags().Lookup("port"), cmd.Name())
+ require.Nil(t, cmd.InheritedFlags().Lookup("instance-url"), cmd.Name())
+ require.NotNil(t, cmd.InheritedFlags().Lookup("config-dir"), cmd.Name())
+ // The database flags are the config command's own, so binding them
+ // does not unbind the server's.
+ require.Equal(t, "database source name of the instance", cmd.InheritedFlags().Lookup("dsn").Usage, cmd.Name())
+ }
+}
+
+func newMigratedStore(t *testing.T) (*store.Store, string) {
+ t.Helper()
+ data := t.TempDir()
+ instanceProfile := &profile.Profile{Data: data, Driver: "sqlite", Version: version.GetCurrentVersion()}
+ require.NoError(t, instanceProfile.Validate())
+ dbDriver, err := db.NewDBDriver(instanceProfile)
+ require.NoError(t, err)
+ storeInstance := store.New(dbDriver, instanceProfile)
+ t.Cleanup(func() { require.NoError(t, storeInstance.Close()) })
+ require.NoError(t, storeInstance.Migrate(context.Background()))
+ return storeInstance, data
+}
+
+func TestConfigPlan(t *testing.T) {
+ ctx := context.Background()
+ storeInstance, _ := newMigratedStore(t)
+ dir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(dir, "users.json"),
+ []byte(`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"${env:MEMOS_TEST_ADMIN_PASSWORD}"}]}`), 0o600))
+ t.Setenv("MEMOS_TEST_ADMIN_PASSWORD", "correct horse")
+
+ var stdout, stderr bytes.Buffer
+ err := runConfigPlan(ctx, dir, configuration.OSResolver(), storeInstance, planOptions{detailedExitCode: true}, &stdout, &stderr)
+ var exit exitCodeError
+ require.ErrorAs(t, err, &exit)
+ require.Equal(t, planExitChanges, exit.code)
+ require.Contains(t, stdout.String(), "Plan: 1 to create, 0 to update, 0 to destroy.")
+ require.Contains(t, stdout.String(), "+ users/admin (users.json)")
+ require.NotContains(t, stdout.String(), "correct horse")
+
+ stdout.Reset()
+ require.NoError(t, runConfigPlan(ctx, dir, configuration.OSResolver(), storeInstance, planOptions{json: true}, &stdout, &stderr),
+ "changes exit 0 without --detailed-exitcode")
+ plan := &apipb.Plan{}
+ require.NoError(t, protojson.Unmarshal(stdout.Bytes(), plan))
+ require.Equal(t, apipb.ResourceChange_CREATE, plan.ResourceChanges[0].Action)
+ require.True(t, plan.StateRecordChanges)
+ require.NotContains(t, stdout.String(), "correct horse")
+
+ stdout.Reset()
+ stderr.Reset()
+ require.NoError(t, runConfigPlan(ctx, filepath.Join(dir, "missing"), configuration.OSResolver(), storeInstance, planOptions{detailedExitCode: true}, &stdout, &stderr))
+ require.Contains(t, stderr.String(), "planning an empty configuration")
+ require.Equal(t, "No changes. The instance matches the configuration.\n", stdout.String())
+
+ require.NoError(t, os.WriteFile(filepath.Join(dir, "users.json"), []byte(`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}]}`), 0o600))
+ stdout.Reset()
+ err = runConfigPlan(ctx, dir, configuration.OSResolver(), storeInstance, planOptions{detailedExitCode: true}, &stdout, &stderr)
+ require.ErrorContains(t, err, "the plan cannot be applied")
+ require.Contains(t, stdout.String(), "Error: users/admin: password is required to create the user")
+}
+
+func TestConfigPlanRefusesMissingDatabase(t *testing.T) {
+ var stdout, stderr bytes.Buffer
+ rootCmd.SetOut(&stdout)
+ rootCmd.SetErr(&stderr)
+ rootCmd.SetArgs([]string{"config", "plan", "--data", t.TempDir(), "--config-dir", t.TempDir()})
+ t.Cleanup(func() { rootCmd.SetArgs(nil) })
+ err := rootCmd.ExecuteContext(context.Background())
+ require.ErrorContains(t, err, "no SQLite database at")
+}
+
+func TestConfigApplyAndState(t *testing.T) {
+ ctx := context.Background()
+ storeInstance, _ := newMigratedStore(t)
+ dir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(dir, "users.json"),
+ []byte(`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"pw"}],"lifecycle":[{"resource":"users/admin","preventDestroy":true}]}`), 0o600))
+ metadata := configuration.ApplyMetadata{AppliedBy: "cli test-host", Version: "test", Now: time.Unix(1_800_000_000, 0)}
+
+ var stdout, stderr bytes.Buffer
+ require.NoError(t, runConfigApply(ctx, dir, configuration.OSResolver(), storeInstance, metadata, false, &stdout, &stderr))
+ require.Contains(t, stdout.String(), "+ users/admin (users.json)")
+ require.Contains(t, stdout.String(), "Apply complete. The state record is at serial 1.")
+
+ stdout.Reset()
+ require.NoError(t, runConfigApply(ctx, dir, configuration.OSResolver(), storeInstance, metadata, false, &stdout, &stderr))
+ require.Equal(t, "No changes. The instance matches the configuration.\n", stdout.String())
+
+ stdout.Reset()
+ require.NoError(t, runConfigState(ctx, storeInstance, false, &stdout))
+ require.Equal(t, "Serial 1, applied 2027-01-15T08:00:00Z by cli test-host (Memos test).\n"+
+ " users/admin User users.json managed: username, role; prevent destroy\n", stdout.String())
+
+ stdout.Reset()
+ require.NoError(t, runConfigState(ctx, storeInstance, true, &stdout))
+ state := &storepb.InstanceConfigurationState{}
+ require.NoError(t, protojson.Unmarshal(stdout.Bytes(), state))
+ require.Equal(t, int64(1), state.Serial)
+}
+
+func TestConfigApplyCreatesTheDatabase(t *testing.T) {
+ data, dir := t.TempDir(), t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(dir, "users.json"),
+ []byte(`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"pw"}]}`), 0o600))
+ var stdout, stderr bytes.Buffer
+ rootCmd.SetOut(&stdout)
+ rootCmd.SetErr(&stderr)
+ rootCmd.SetArgs([]string{"config", "apply", "--data", data, "--config-dir", dir})
+ t.Cleanup(func() { rootCmd.SetArgs(nil) })
+ require.NoError(t, rootCmd.ExecuteContext(context.Background()), stderr.String())
+ require.Contains(t, stdout.String(), "Apply complete.", "apply bootstraps a fresh instance")
+ require.FileExists(t, filepath.Join(data, "memos_prod.db"))
+}
diff --git a/cmd/memos/main.go b/cmd/memos/main.go
index 40035c294..bb46b19f5 100644
--- a/cmd/memos/main.go
+++ b/cmd/memos/main.go
@@ -13,9 +13,11 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
+ "github.com/usememos/memos/core/configuration"
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/internal/version"
"github.com/usememos/memos/internal/webhook"
+ apipb "github.com/usememos/memos/proto/gen/api"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/server"
"github.com/usememos/memos/store"
@@ -68,6 +70,8 @@ func init() {
rootCmd.Flags().StringSlice("webhook-private-network-allowlist", nil, "private webhook destinations to allow (exact hostname, IP, or CIDR)")
rootCmd.Flags().String("log-level", "info", "log verbosity level (debug, info, warn, error)")
rootCmd.Flags().Bool("rate-limit", true, "enable request rate limiting")
+ rootCmd.Flags().String("config-dir", configuration.DefaultDir, "directory of declarative configuration files")
+ rootCmd.Flags().String("config-apply", "startup", "when to apply the declarative configuration: startup, or off to leave it to memos config apply")
rootCmd.Flags().StringSlice("trusted-proxies", []string{"private"}, "proxies whose forwarding headers identify the client: CIDRs, IPs, \"private\" (default; the loopback and private ranges), or \"none\" when the instance is reached without a header-rewriting proxy")
if err := rootCmd.Flags().MarkDeprecated("allow-private-webhooks", "use --webhook-private-network-allowlist to allow only required destinations"); err != nil {
@@ -87,6 +91,8 @@ func init() {
"log-level",
"rate-limit",
"trusted-proxies",
+ "config-dir",
+ "config-apply",
} {
if err := viper.BindPFlag(key, rootCmd.Flags().Lookup(key)); err != nil {
panic(err)
@@ -156,8 +162,8 @@ func runServer() error {
if err := storeInstance.Migrate(ctx); err != nil {
return errors.Wrap(err, "failed to migrate database")
}
- if err := storeInstance.LoadDeploymentConfiguration(ctx); err != nil {
- return errors.Wrap(err, "failed to load deployment configuration")
+ if err := applyConfigurationAtStartup(ctx, storeInstance); err != nil {
+ return errors.Wrap(err, "failed to apply the declarative configuration")
}
accessSetting, err := storeInstance.GetInstanceAccessSetting(ctx)
if err != nil {
@@ -232,7 +238,67 @@ func main() {
os.Exit(1)
}
if err := rootCmd.Execute(); err != nil {
+ var exit exitCodeError
+ if errors.As(err, &exit) {
+ os.Exit(exit.code)
+ }
slog.Error("memos failed", slog.String("error", err.Error()))
os.Exit(1)
}
}
+
+// applyConfigurationAtStartup applies the configuration directory after
+// migration and before any service starts, so the instance never serves with a
+// configuration it could not apply. Replicas that apply through a job before a
+// rollout pass --config-apply=off.
+func applyConfigurationAtStartup(ctx context.Context, storeInstance *store.Store) error {
+ switch mode := viper.GetString("config-apply"); mode {
+ case "off":
+ return nil
+ case "startup":
+ default:
+ return errors.Errorf("--config-apply must be startup or off, got %q", mode)
+ }
+ dir := viper.GetString("config-dir")
+ desired, err := configuration.Load(dir, configuration.OSResolver())
+ if err != nil {
+ return err
+ }
+ for _, warning := range desired.Warnings {
+ slog.Warn("configuration warning", "warning", warning)
+ }
+ plan, state, err := configuration.Apply(ctx, desired, storeInstance, configMetadata("startup"))
+ if err != nil {
+ return err
+ }
+ for _, warning := range plan.Message.Warnings {
+ slog.Warn("configuration warning", "warning", warning)
+ }
+ if !plan.Valid() {
+ return errors.Errorf("configuration in %s cannot be applied:\n %s", dir, strings.Join(plan.Message.Errors, "\n "))
+ }
+ if !plan.HasChanges() {
+ if plan.Message.Serial > 0 {
+ slog.Info("configuration unchanged", "dir", dir, "serial", plan.Message.Serial)
+ }
+ return nil
+ }
+ changed := []string{}
+ for _, change := range plan.Message.ResourceChanges {
+ if change.Action != apipb.ResourceChange_NO_OP {
+ changed = append(changed, strings.ToLower(change.Action.String())+" "+change.Resource)
+ }
+ }
+ slog.Info("applied configuration", "dir", dir, "serial", state.Serial, "digest", state.ConfigDigest, "changes", changed)
+ return nil
+}
+
+// exitCodeError ends the process with code once a command has printed its own
+// output, such as a plan with changes under --detailed-exitcode.
+type exitCodeError struct {
+ code int
+}
+
+func (e exitCodeError) Error() string {
+ return fmt.Sprintf("exit status %d", e.code)
+}
diff --git a/core/README.md b/core/README.md
index e6ead176c..53b2ba1c6 100644
--- a/core/README.md
+++ b/core/README.md
@@ -11,6 +11,17 @@ apply the same way.
| `memopayload/` | rebuilding a memo's derived payload from its markdown |
| `memoexport/` | the Memos Export Format container and records used for export and import |
| `usagelimit/` | which usage limits apply to a user, and whether memo counts, memo content, and uploads stay within them |
+| `identityprovider/` | the rules an identity provider must meet before it is stored, and its API↔store conversion |
+| `instancesetting/` | the rules each instance setting group must meet before it is stored, AI setting normalization, and the API↔store conversion |
+| `user/` | the rules a username and password must meet before they are stored |
+| `configuration/` | declarative configuration: reading files (substitution, strict decoding, schema checks, merging), planning and applying them against the instance, and the API ownership guard |
+
+The three validation packages check the complete value as it will be stored.
+`identityprovider` and `instancesetting` also convert between API and store
+messages, because declarative configuration files are API messages; their
+`FromStore` keeps secrets, and API responses redact them in `server/api`.
+A write path's own conveniences, such as the API treating an empty secret as
+"keep the stored one", run before validation, never inside it.
Layering: `core` may import `store`, `provider`, `markdown`, `filter`,
`proto/gen`, and `internal`. It must not import `server` or `cmd`. New
diff --git a/core/configuration/apply.go b/core/configuration/apply.go
new file mode 100644
index 000000000..706fc5c09
--- /dev/null
+++ b/core/configuration/apply.go
@@ -0,0 +1,205 @@
+package configuration
+
+import (
+ "context"
+ stderrors "errors"
+ "strings"
+ "time"
+
+ "github.com/pkg/errors"
+ "golang.org/x/crypto/bcrypt"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+
+ coreuser "github.com/usememos/memos/core/user"
+ apipb "github.com/usememos/memos/proto/gen/api"
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+)
+
+// ApplyMetadata says who applied, for the state record.
+type ApplyMetadata struct {
+ // AppliedBy names the apply path and host, such as "cli host-1".
+ AppliedBy string
+ // Version is the Memos version applying.
+ Version string
+ // Now is the time to record.
+ Now time.Time
+}
+
+// errPlanInvalid ends the apply transaction without writing.
+var errPlanInvalid = stderrors.New("the plan cannot be applied")
+
+// Apply plans desired against the instance inside one serializable
+// transaction and, when the plan is valid and has changes, writes it and the
+// state record in that same transaction: an apply either completes or changes
+// nothing. It returns the plan it applied; a plan with errors is returned
+// with them and nothing is written. The state is the record after the apply.
+func Apply(ctx context.Context, desired *Desired, s *store.Store, metadata ApplyMetadata) (*Plan, *storepb.InstanceConfigurationState, error) {
+ var applied *Plan
+ state, err := s.RunConfigurationTransaction(ctx, func(ctx context.Context, tx *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ plan, err := ComputePlan(ctx, desired, tx)
+ if err != nil {
+ return nil, err
+ }
+ applied = plan
+ if !plan.Valid() {
+ return nil, errPlanInvalid
+ }
+ if !plan.HasChanges() {
+ return nil, nil
+ }
+ for _, op := range plan.operations {
+ if err := applyOperation(ctx, tx, op, metadata.Now); err != nil {
+ return nil, errors.Wrap(err, op.change.Resource)
+ }
+ }
+ next := proto.CloneOf(plan.next)
+ next.AppliedTs = metadata.Now.Unix()
+ next.AppliedBy = metadata.AppliedBy
+ next.Version = metadata.Version
+ for _, resource := range next.Resources {
+ if resource.AppliedTs == 0 {
+ resource.AppliedTs = metadata.Now.Unix()
+ }
+ }
+ return next, nil
+ })
+ if errors.Is(err, errPlanInvalid) {
+ return applied, nil, nil
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+ return applied, state, nil
+}
+
+func applyOperation(ctx context.Context, tx *store.ConfigurationTransaction, op *operation, now time.Time) error {
+ action := op.change.Action
+ switch action {
+ case apipb.ResourceChange_NO_OP, apipb.ResourceChange_RELEASE:
+ return nil
+ case apipb.ResourceChange_CREATE, apipb.ResourceChange_ADOPT, apipb.ResourceChange_UPDATE:
+ if action == apipb.ResourceChange_ADOPT && len(op.change.FieldChanges) == 0 {
+ // The stored value already is the declared one.
+ return nil
+ }
+ case apipb.ResourceChange_DESTROY, apipb.ResourceChange_RESET:
+ default:
+ return errors.Errorf("unexpected action %s", action)
+ }
+
+ switch op.kind {
+ case KindIdentityProvider:
+ switch {
+ case action == apipb.ResourceChange_DESTROY:
+ return tx.DeleteIdentityProvider(ctx, op.providerID)
+ case op.providerID != 0:
+ return tx.ReplaceIdentityProvider(ctx, op.providerID, op.provider)
+ default:
+ return tx.CreateIdentityProvider(ctx, op.provider)
+ }
+ case KindInstanceSetting:
+ if action != apipb.ResourceChange_RESET {
+ return tx.UpsertInstanceSetting(ctx, op.setting)
+ }
+ // ACCESS is written explicitly: a missing row would be initialized at
+ // the next start from the legacy instance URL rule.
+ if op.settingKey == storepb.InstanceSettingKey_ACCESS {
+ return tx.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey_ACCESS,
+ Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{
+ AccessMode: storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE,
+ }},
+ })
+ }
+ return tx.DeleteInstanceSetting(ctx, op.settingKey)
+ default:
+ return applyUser(ctx, tx, op, now)
+ }
+}
+
+// applyUser writes exactly the fields the plan lists, which already leave out
+// ignored fields, undeclared profile fields, and values that did not change.
+func applyUser(ctx context.Context, tx *store.ConfigurationTransaction, op *operation, now time.Time) error {
+ role := coreuser.RoleToStore(op.user.Role)
+ var passwordHash string
+ for _, field := range op.change.FieldChanges {
+ if field.Path == "password" {
+ hash, err := bcrypt.GenerateFromPassword([]byte(op.user.Password), bcrypt.DefaultCost)
+ if err != nil {
+ return errors.Wrap(err, "failed to hash the password")
+ }
+ passwordHash = string(hash)
+ }
+ }
+
+ if op.actualUser == nil {
+ _, err := tx.CreateUser(ctx, &store.User{
+ Username: op.user.Username,
+ Role: role,
+ Email: op.user.Email,
+ Nickname: op.user.DisplayName,
+ PasswordHash: passwordHash,
+ })
+ return err
+ }
+ if len(op.change.FieldChanges) == 0 {
+ return nil
+ }
+ updatedTsSec := now.Unix()
+ update := &store.UpdateUser{ID: op.actualUser.ID, UpdatedTs: &updatedTsSec}
+ for _, field := range op.change.FieldChanges {
+ switch field.Path {
+ case "role":
+ update.Role = &role
+ case "displayName":
+ update.Nickname = &op.user.DisplayName
+ case "email":
+ update.Email = &op.user.Email
+ case "password":
+ update.PasswordHash = &passwordHash
+ default:
+ }
+ }
+ return tx.UpdateUser(ctx, update)
+}
+
+// copyFields sets each JSON-name path of dst to its value in src, clearing it
+// where src has none. Paths name singular fields, as ignoreChanges must.
+func copyFields(dst, src proto.Message, paths []string) {
+ for _, path := range paths {
+ segments := strings.Split(path, ".")
+ to, from := dst.ProtoReflect(), src.ProtoReflect()
+ fromSet := true
+ for i, segment := range segments {
+ field := to.Descriptor().Fields().ByJSONName(segment)
+ if field == nil {
+ break
+ }
+ if i == len(segments)-1 {
+ if fromSet && from.Has(field) {
+ to.Set(field, cloneValue(from.Get(field)))
+ } else {
+ to.Clear(field)
+ }
+ break
+ }
+ if fromSet && from.Has(field) {
+ from = from.Get(field).Message()
+ } else {
+ fromSet = false
+ }
+ to = to.Mutable(field).Message()
+ }
+ }
+}
+
+// cloneValue copies a message value so dst never shares it with src; scalars
+// and lists of scalars are immutable from here on and are shared as they are.
+func cloneValue(value protoreflect.Value) protoreflect.Value {
+ if message, ok := value.Interface().(protoreflect.Message); ok {
+ return protoreflect.ValueOfMessage(proto.Clone(message.Interface()).ProtoReflect())
+ }
+ return value
+}
diff --git a/core/configuration/apply_test.go b/core/configuration/apply_test.go
new file mode 100644
index 000000000..ecfcc8ef1
--- /dev/null
+++ b/core/configuration/apply_test.go
@@ -0,0 +1,188 @@
+package configuration
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "golang.org/x/crypto/bcrypt"
+
+ "github.com/usememos/memos/internal/profile"
+ "github.com/usememos/memos/internal/version"
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+ "github.com/usememos/memos/store/db/sqlite"
+)
+
+func newTestStore(t *testing.T) *store.Store {
+ t.Helper()
+ instanceProfile := &profile.Profile{Data: t.TempDir(), Driver: "sqlite", Version: version.GetCurrentVersion()}
+ require.NoError(t, instanceProfile.Validate())
+ driver, err := sqlite.NewDB(instanceProfile)
+ require.NoError(t, err)
+ s := store.New(driver, instanceProfile)
+ t.Cleanup(func() { require.NoError(t, s.Close()) })
+ require.NoError(t, s.Migrate(context.Background()))
+ return s
+}
+
+func applyFor(t *testing.T, desired *Desired, s *store.Store) (*Plan, *storepb.InstanceConfigurationState) {
+ t.Helper()
+ plan, state, err := Apply(context.Background(), desired, s, ApplyMetadata{AppliedBy: "test host", Version: "test", Now: time.Unix(1_800_000_000, 0)})
+ require.NoError(t, err)
+ return plan, state
+}
+
+func requirePassword(t *testing.T, s *store.Store, username, password string) {
+ t.Helper()
+ user, err := s.GetUser(context.Background(), &store.FindUser{Username: &username})
+ require.NoError(t, err)
+ require.NotNil(t, user)
+ require.NoError(t, bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)))
+}
+
+func instanceFiles(title, password string, version string) map[string]string {
+ withSecret := `{"name":"identity-providers/sso","type":"OAUTH2","title":"SSO","config":{"oauth2Config":{"clientId":"memos","clientSecret":"file-secret",
+ "authUrl":"https://idp.example.com/authorize","tokenUrl":"https://idp.example.com/token","userInfoUrl":"https://idp.example.com/userinfo",
+ "fieldMapping":{"identifier":"sub"}}}}`
+ return map[string]string{
+ "idp.json": `{"identityProviders":[` + withSecret + `]}`,
+ "general.json": generalDocument(title),
+ "users.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"` + password + `"}],
+ "lifecycle":[{"resource":"users/admin","writeOnlyVersion":` + version + `}]}`,
+ }
+}
+
+func TestApplyLifecycle(t *testing.T) {
+ ctx := context.Background()
+ s := newTestStore(t)
+
+ plan, state := applyFor(t, loadDesired(t, instanceFiles("Company", "first-password", "1")), s)
+ require.True(t, plan.Valid())
+ require.True(t, plan.HasChanges())
+ require.Equal(t, int64(1), state.Serial)
+ require.Equal(t, "test host", state.AppliedBy)
+ require.Len(t, state.Resources, 3)
+ for _, resource := range state.Resources {
+ require.Equal(t, int64(1_800_000_000), resource.AppliedTs, resource.Name)
+ }
+
+ provider, err := s.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("sso")})
+ require.NoError(t, err)
+ require.Equal(t, "file-secret", provider.Config.GetOauth2Config().ClientSecret)
+ general, err := s.GetInstanceGeneralSetting(ctx)
+ require.NoError(t, err)
+ require.Equal(t, "Company", general.GetCustomProfile().GetTitle())
+ requirePassword(t, s, "admin", "first-password")
+
+ // Applying the same files again changes nothing.
+ again, state := applyFor(t, loadDesired(t, instanceFiles("Company", "first-password", "1")), s)
+ require.False(t, again.HasChanges())
+ require.Equal(t, int64(1), state.Serial)
+
+ // An edit outside the configuration is reverted as drift.
+ _, err = s.UpsertInstanceSetting(ctx, generalSetting("Edited in the UI"))
+ require.NoError(t, err)
+ repaired, state := applyFor(t, loadDesired(t, instanceFiles("Company", "first-password", "1")), s)
+ require.True(t, changeFor(t, repaired, "instance/settings/GENERAL").Drift)
+ require.Equal(t, int64(2), state.Serial)
+ general, err = s.GetInstanceGeneralSetting(ctx)
+ require.NoError(t, err)
+ require.Equal(t, "Company", general.GetCustomProfile().GetTitle())
+
+ // A new password is sent only when writeOnlyVersion goes up.
+ _, _ = applyFor(t, loadDesired(t, instanceFiles("Company", "second-password", "1")), s)
+ requirePassword(t, s, "admin", "first-password")
+ _, state = applyFor(t, loadDesired(t, instanceFiles("Company", "second-password", "2")), s)
+ requirePassword(t, s, "admin", "second-password")
+ for _, resource := range state.Resources {
+ if resource.Name == "users/admin" {
+ require.Equal(t, int32(2), resource.WriteOnlyVersion)
+ }
+ }
+}
+
+func TestApplyInvalidPlanWritesNothing(t *testing.T) {
+ ctx := context.Background()
+ s := newTestStore(t)
+ desired := loadDesired(t, map[string]string{
+ "general.json": `{"instanceSettings":[{"name":"instance/settings/GENERAL","generalSetting":{"disallowPasswordAuth":true}}]}`,
+ })
+ plan, state := applyFor(t, desired, s)
+ require.False(t, plan.Valid())
+ require.Nil(t, state)
+ general, err := s.GetInstanceGeneralSetting(ctx)
+ require.NoError(t, err)
+ require.False(t, general.DisallowPasswordAuth)
+ record, err := s.GetConfigurationState(ctx)
+ require.NoError(t, err)
+ require.Zero(t, record.Serial)
+}
+
+func TestApplyKeepsIgnoredFields(t *testing.T) {
+ ctx := context.Background()
+ s := newTestStore(t)
+ _, err := s.UpsertInstanceSetting(ctx, generalSetting("Chosen in the UI"))
+ require.NoError(t, err)
+
+ desired := loadDesired(t, map[string]string{"general.json": `{"instanceSettings":[{"name":"instance/settings/GENERAL","generalSetting":{
+ "disallowUserRegistration":true,"customProfile":{"title":"From the file"}}}],
+ "lifecycle":[{"resource":"instance/settings/GENERAL","ignoreChanges":["generalSetting.customProfile"]}]}`})
+ _, state := applyFor(t, desired, s)
+ require.Equal(t, int64(1), state.Serial)
+ general, err := s.GetInstanceGeneralSetting(ctx)
+ require.NoError(t, err)
+ require.True(t, general.DisallowUserRegistration, "managed fields are written")
+ require.Equal(t, "Chosen in the UI", general.GetCustomProfile().GetTitle(), "ignored fields keep their stored value")
+}
+
+func TestApplyRemovals(t *testing.T) {
+ ctx := context.Background()
+ s := newTestStore(t)
+ declared := map[string]string{
+ "idp.json": `{"identityProviders":[` + validIDP + `]}`,
+ "settings.json": `{"instanceSettings":[
+ {"name":"instance/settings/ACCESS","accessSetting":{"accessMode":"INSTANCE_ACCESS_MODE_PUBLIC"}},
+ {"name":"instance/settings/MEMO_RELATED","memoRelatedSetting":{"reactions":["👍"]}}]}`,
+ }
+ _, state := applyFor(t, loadDesired(t, declared), s)
+ require.Len(t, state.Resources, 3)
+
+ _, state = applyFor(t, loadDesired(t, map[string]string{"removed.json": `{"removed":[
+ {"resource":"identity-providers/sso","destroy":true},
+ {"resource":"instance/settings/ACCESS","destroy":true},
+ {"resource":"instance/settings/MEMO_RELATED"}]}`}), s)
+ require.Empty(t, state.Resources)
+
+ providers, err := s.ListIdentityProviders(ctx, &store.FindIdentityProvider{})
+ require.NoError(t, err)
+ require.Empty(t, providers, "a destroyed provider is deleted")
+ access, err := s.GetInstanceAccessSetting(ctx)
+ require.NoError(t, err)
+ require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, access.AccessMode, "a reset ACCESS is private")
+ memoRelated, err := s.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: "MEMO_RELATED"})
+ require.NoError(t, err)
+ require.Equal(t, []string{"👍"}, memoRelated.GetMemoRelatedSetting().GetReactions(), "a released setting is left as it is")
+}
+
+func TestApplyFailureRollsBack(t *testing.T) {
+ ctx := context.Background()
+ s := newTestStore(t)
+ _, err := s.CreateUser(ctx, &store.User{Username: "root", Role: store.RoleAdmin, PasswordHash: "hash"})
+ require.NoError(t, err)
+
+ desired := loadDesired(t, map[string]string{
+ "idp.json": `{"identityProviders":[` + validIDP + `]}`,
+ "users.json": `{"users":[{"name":"users/root","username":"root","role":"USER","password":"pw"}]}`,
+ })
+ _, _, err = Apply(ctx, desired, s, ApplyMetadata{Now: time.Now()})
+ require.ErrorIs(t, err, store.ErrLastInstanceAdmin)
+
+ providers, err := s.ListIdentityProviders(ctx, &store.FindIdentityProvider{})
+ require.NoError(t, err)
+ require.Empty(t, providers, "the provider written before the failure rolled back")
+ record, err := s.GetConfigurationState(ctx)
+ require.NoError(t, err)
+ require.Zero(t, record.Serial)
+}
diff --git a/core/configuration/configuration.go b/core/configuration/configuration.go
new file mode 100644
index 000000000..d3d941074
--- /dev/null
+++ b/core/configuration/configuration.go
@@ -0,0 +1,154 @@
+// Package configuration reads declarative configuration: the identity
+// providers, instance settings, and users an instance should have, declared in
+// JSON files as public API resources.
+//
+// Load reads every *.json file in a directory, substitutes ${env:NAME} and
+// ${file:PATH} references, decodes each file strictly as one
+// memos.api.Configuration, checks the schema rules that need no database,
+// merges the files into one desired state, and runs each resource's own rules
+// from core/identityprovider and core/instancesetting. See
+// docs/design/declarative-configuration.md.
+package configuration
+
+import (
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/pkg/errors"
+
+ apipb "github.com/usememos/memos/proto/gen/api"
+)
+
+// DefaultDir is the configuration directory used when none is given.
+const DefaultDir = "/etc/memos/config"
+
+const (
+ maxFileSize = 1 << 20
+ maxReferencedFileSize = 64 << 10
+)
+
+// Desired is the desired state merged from every file in a configuration directory.
+type Desired struct {
+ // Configuration is every file merged into one document.
+ Configuration *apipb.Configuration
+ // Sources maps each declared resource name to the file that declares it.
+ Sources map[string]string
+ // UserFields maps each declared user to the optional fields its file
+ // declares, by JSON name. A user's profile is managed only where declared,
+ // and presence is lost once a document is decoded.
+ UserFields map[string][]string
+ // Warnings are diagnostics that do not stop the load, such as deprecated fields.
+ Warnings []string
+}
+
+// Resolver supplies the values ${env:NAME} and ${file:PATH} references name.
+type Resolver struct {
+ LookupEnv func(name string) (string, bool)
+ ReadFile func(path string) ([]byte, error)
+}
+
+// OSResolver resolves references from the process environment and filesystem.
+func OSResolver() Resolver {
+ return Resolver{
+ LookupEnv: os.LookupEnv,
+ ReadFile: func(path string) ([]byte, error) {
+ return readRegularFile(path, maxReferencedFileSize)
+ },
+ }
+}
+
+// ValidationError lists every problem found in a configuration directory.
+type ValidationError struct {
+ Problems []string
+}
+
+func (e *ValidationError) Error() string {
+ return "invalid configuration:\n " + strings.Join(e.Problems, "\n ")
+}
+
+// Load reads, decodes, and merges the configuration files in dir. A missing
+// directory is an empty desired state. Problems in the files are returned
+// together as a *ValidationError; an unreadable directory or file is returned
+// on its own.
+func Load(dir string, resolver Resolver) (*Desired, error) {
+ desired := &Desired{
+ Configuration: &apipb.Configuration{},
+ Sources: map[string]string{},
+ UserFields: map[string][]string{},
+ }
+ entries, err := os.ReadDir(dir)
+ if errors.Is(err, fs.ErrNotExist) {
+ return desired, nil
+ }
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to read configuration directory")
+ }
+
+ m := newMerger(desired)
+ for _, entry := range entries {
+ name := entry.Name()
+ if !strings.HasSuffix(name, ".json") {
+ continue
+ }
+ path := filepath.Join(dir, name)
+ info, err := os.Stat(path)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to inspect %s", name)
+ }
+ if !info.Mode().IsRegular() {
+ continue
+ }
+ content, err := readRegularFile(path, maxFileSize)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to read %s", name)
+ }
+ document, userFields, warnings, problems := decodeDocument(content, resolver)
+ for _, warning := range warnings {
+ desired.Warnings = append(desired.Warnings, name+": "+warning)
+ }
+ if len(problems) == 0 {
+ problems = checkDocument(document)
+ }
+ if len(problems) > 0 {
+ for _, problem := range problems {
+ m.problems = append(m.problems, name+": "+problem)
+ }
+ continue
+ }
+ m.add(name, document, userFields)
+ }
+ m.checkReferences()
+ m.problems = append(m.problems, checkResources(desired)...)
+ if len(m.problems) > 0 {
+ return nil, &ValidationError{Problems: m.problems}
+ }
+ return desired, nil
+}
+
+// readRegularFile reads at most limit bytes of a regular file, following
+// symlinks, and fails when the file is larger.
+func readRegularFile(path string, limit int64) ([]byte, error) {
+ file, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ info, err := file.Stat()
+ if err != nil {
+ return nil, err
+ }
+ if !info.Mode().IsRegular() {
+ return nil, errors.New("not a regular file")
+ }
+ content, err := io.ReadAll(io.LimitReader(file, limit+1))
+ if err != nil {
+ return nil, err
+ }
+ if int64(len(content)) > limit {
+ return nil, errors.Errorf("larger than %d bytes", limit)
+ }
+ return content, nil
+}
diff --git a/core/configuration/configuration_test.go b/core/configuration/configuration_test.go
new file mode 100644
index 000000000..3f9e42555
--- /dev/null
+++ b/core/configuration/configuration_test.go
@@ -0,0 +1,307 @@
+package configuration
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/reflect/protodesc"
+ "google.golang.org/protobuf/types/descriptorpb"
+
+ apipb "github.com/usememos/memos/proto/gen/api"
+)
+
+// placeholderResolver resolves every reference, so fixtures exercise the
+// schema rather than the host's secrets.
+func placeholderResolver() Resolver {
+ return Resolver{
+ LookupEnv: func(string) (string, bool) { return "placeholder", true },
+ ReadFile: func(string) ([]byte, error) { return []byte("placeholder\n"), nil },
+ }
+}
+
+// validIDP is an identity provider that meets every rule.
+const validIDP = `{"name":"identity-providers/sso","type":"OAUTH2","title":"SSO","config":{"oauth2Config":{"clientId":"memos",
+ "authUrl":"https://idp.example.com/authorize","tokenUrl":"https://idp.example.com/token","userInfoUrl":"https://idp.example.com/userinfo",
+ "fieldMapping":{"identifier":"sub"}}}}`
+
+func writeFiles(t *testing.T, files map[string]string) string {
+ t.Helper()
+ dir := t.TempDir()
+ for name, content := range files {
+ require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600))
+ }
+ return dir
+}
+
+func requireProblems(t *testing.T, err error, want ...string) {
+ t.Helper()
+ var validationError *ValidationError
+ require.ErrorAs(t, err, &validationError)
+ joined := strings.Join(validationError.Problems, "\n")
+ for _, w := range want {
+ require.Contains(t, joined, w)
+ }
+}
+
+// TestCompatibilityFixtures decodes the example files of every release. A
+// change that stops one from decoding is a break to record in
+// proto/api/CHANGELOG.md, updating the fixture in the same change.
+func TestCompatibilityFixtures(t *testing.T) {
+ releases, err := os.ReadDir("testdata/compat")
+ require.NoError(t, err)
+ require.NotEmpty(t, releases)
+ for _, release := range releases {
+ t.Run(release.Name(), func(t *testing.T) {
+ desired, err := Load(filepath.Join("testdata/compat", release.Name()), placeholderResolver())
+ require.NoError(t, err)
+ require.NotEmpty(t, desired.Sources)
+ require.Empty(t, desired.Warnings)
+ })
+ }
+}
+
+func TestLoadMergesFilesAndRecordsSources(t *testing.T) {
+ dir := writeFiles(t, map[string]string{
+ "a-idp.json": `{"identityProviders":[` + validIDP + `]}`,
+ "b-access.json": `{"instanceSettings":[{"name":"instance/settings/ACCESS","accessSetting":{"accessMode":"INSTANCE_ACCESS_MODE_PUBLIC"}}]}`,
+ "c-users.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}],"lifecycle":[{"resource":"identity-providers/sso","preventDestroy":true}]}`,
+ "notes.txt": `not configuration`,
+ "README.md.json": `{}`,
+ })
+ require.NoError(t, os.Mkdir(filepath.Join(dir, "nested.json"), 0o700))
+
+ desired, err := Load(dir, placeholderResolver())
+ require.NoError(t, err)
+ require.Len(t, desired.Configuration.IdentityProviders, 1)
+ require.Len(t, desired.Configuration.InstanceSettings, 1)
+ require.Len(t, desired.Configuration.Users, 1)
+ require.Len(t, desired.Configuration.Lifecycle, 1)
+ require.Equal(t, map[string]string{
+ "identity-providers/sso": "a-idp.json",
+ "instance/settings/ACCESS": "b-access.json",
+ "users/admin": "c-users.json",
+ }, desired.Sources)
+ require.Equal(t, apipb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC,
+ desired.Configuration.InstanceSettings[0].GetAccessSetting().GetAccessMode())
+}
+
+func TestLoadDirectoryEdgeCases(t *testing.T) {
+ desired, err := Load(filepath.Join(t.TempDir(), "missing"), placeholderResolver())
+ require.NoError(t, err, "a missing directory is an empty desired state")
+ require.Empty(t, desired.Sources)
+
+ dir := writeFiles(t, map[string]string{"target.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}]}`})
+ linkDir := t.TempDir()
+ require.NoError(t, os.Symlink(filepath.Join(dir, "target.json"), filepath.Join(linkDir, "linked.json")))
+ desired, err = Load(linkDir, placeholderResolver())
+ require.NoError(t, err, "a symlink to a regular file is followed, as in Kubernetes volumes")
+ require.Contains(t, desired.Sources, "users/admin")
+
+ big := writeFiles(t, map[string]string{"big.json": `{"users":[]}` + strings.Repeat(" ", maxFileSize)})
+ _, err = Load(big, placeholderResolver())
+ require.ErrorContains(t, err, "larger than")
+}
+
+func TestLoadDecodesStrictly(t *testing.T) {
+ tests := map[string]struct {
+ document string
+ want string
+ }{
+ "syntax error": {`{"users": [}`, "line 1, column 12"},
+ "not an object": {`[]`, "must be a JSON object"},
+ "trailing data": {`{} {}`, "unexpected data"},
+ "duplicate key": {`{"users":[],"users":[]}`, "users: duplicate key"},
+ "unknown field": {`{"identityProviders":[{"name":"identity-providers/sso","titel":"SSO"}]}`, `unknown field "titel"`},
+ "numeric enum": {`{"users":[{"name":"users/admin","username":"admin","role":1}]}`, "users[0].role: use the enum value name"},
+ "output only": {`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","createTime":"2026-01-01T00:00:00Z"}]}`, "users[0].createTime is output only"},
+ "nested output": {`{"instanceSettings":[{"name":"instance/settings/AI","aiSetting":{"providers":[{"id":"a","apiKeySet":true}]}}]}`, "aiSetting.providers[0].apiKeySet is output only"},
+ "wrong value": {`{"lifecycle":[{"resource":"users/admin","preventDestroy":"yes"}]}`, "invalid value for bool field preventDestroy"},
+ "oneof conflict": {`{"instanceSettings":[{"name":"instance/settings/ACCESS","accessSetting":{},"generalSetting":{}}]}`, "is already set"},
+ "proto name keys": {`{"identity_providers":[` + validIDP + `]}`, ""},
+ }
+ for name, test := range tests {
+ t.Run(name, func(t *testing.T) {
+ _, err := Load(writeFiles(t, map[string]string{"config.json": test.document}), placeholderResolver())
+ if test.want == "" {
+ require.NoError(t, err)
+ return
+ }
+ requireProblems(t, err, "config.json: ", test.want)
+ })
+ }
+}
+
+func TestLoadSubstitutesReferences(t *testing.T) {
+ secretFile := filepath.Join(t.TempDir(), "password")
+ require.NoError(t, os.WriteFile(secretFile, []byte("file-secret\n"), 0o600))
+ t.Setenv("MEMOS_TEST_SECRET", "env-secret")
+
+ dir := writeFiles(t, map[string]string{"config.json": `{
+ "identityProviders": [{"name":"identity-providers/sso","type":"OAUTH2","title":"$${not a reference}",
+ "config":{"oauth2Config":{"clientId":"${env:MEMOS_TEST_SECRET}","clientSecret":"${file:` + secretFile + `}",
+ "authUrl":"https://idp.example.com/authorize","tokenUrl":"https://idp.example.com/token",
+ "userInfoUrl":"https://idp.example.com/userinfo","fieldMapping":{"identifier":"sub"}}}}]
+ }`})
+ desired, err := Load(dir, OSResolver())
+ require.NoError(t, err)
+ provider := desired.Configuration.IdentityProviders[0]
+ require.Equal(t, "env-secret", provider.GetConfig().GetOauth2Config().GetClientId())
+ require.Equal(t, "file-secret", provider.GetConfig().GetOauth2Config().GetClientSecret(), "trailing line breaks are removed")
+ require.Equal(t, "${not a reference}", provider.GetTitle(), "$${ is a literal ${")
+
+ for name, test := range map[string]struct {
+ value string
+ want string
+ }{
+ "unset variable": {`${env:MEMOS_TEST_UNSET}`, "environment variable MEMOS_TEST_UNSET is not set"},
+ "embedded": {`Bearer ${env:MEMOS_TEST_SECRET}`, "must be the whole string value"},
+ "unsupported kind": {`${vault:secret/memos}`, "unsupported reference"},
+ "relative file": {`${file:secrets/password}`, "must be an absolute path"},
+ "missing file": {`${file:/nonexistent/memos-secret}`, "cannot read /nonexistent/memos-secret"},
+ "invalid name": {`${env:1BAD}`, "invalid environment variable name"},
+ "empty env allowed": {`${env:MEMOS_TEST_EMPTY}`, ""},
+ } {
+ t.Run(name, func(t *testing.T) {
+ t.Setenv("MEMOS_TEST_EMPTY", "")
+ dir := writeFiles(t, map[string]string{"config.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","displayName":"` + test.value + `"}]}`})
+ _, err := Load(dir, OSResolver())
+ if test.want == "" {
+ require.NoError(t, err)
+ return
+ }
+ requireProblems(t, err, "config.json: users[0].displayName: ", test.want)
+ })
+ }
+}
+
+func TestLoadNeverPrintsSubstitutedValues(t *testing.T) {
+ t.Setenv("MEMOS_TEST_PORT", "hunter2-not-a-port")
+ dir := writeFiles(t, map[string]string{"config.json": `{"instanceSettings":[{"name":"instance/settings/NOTIFICATION",
+ "notificationSetting":{"email":{"enabled":true,"smtpPort":"${env:MEMOS_TEST_PORT}"}}}]}`})
+ _, err := Load(dir, OSResolver())
+ requireProblems(t, err, "invalid value for int32 field smtpPort")
+ require.NotContains(t, err.Error(), "hunter2")
+}
+
+func TestLoadChecksSchema(t *testing.T) {
+ tests := map[string]struct {
+ document string
+ want string
+ }{
+ "missing name": {`{"identityProviders":[{"title":"SSO"}]}`, "identityProviders[0].name is required"},
+ "wrong kind": {`{"identityProviders":[{"name":"users/admin"}]}`, "is not a IdentityProvider name"},
+ "invalid uid": {`{"identityProviders":[{"name":"identity-providers/-sso"}]}`, "invalid identity provider name"},
+ "basic": {`{"instanceSettings":[{"name":"instance/settings/BASIC"}]}`, "BASIC holds the instance secret"},
+ "tags": {`{"instanceSettings":[{"name":"instance/settings/TAGS","tagsSetting":{}}]}`, "TAGS is kept only for compatibility"},
+ "unknown key": {`{"instanceSettings":[{"name":"instance/settings/THEME"}]}`, "unknown instance setting"},
+ "state record": {`{"instanceSettings":[{"name":"instance/settings/CONFIGURATION_STATE"}]}`, "is the configuration state record"},
+ "missing value": {`{"instanceSettings":[{"name":"instance/settings/GENERAL"}]}`, "generalSetting is required for GENERAL"},
+ "mismatched value": {`{"instanceSettings":[{"name":"instance/settings/GENERAL","accessSetting":{}}]}`, "accessSetting does not match GENERAL; use generalSetting"},
+ "username mismatch": {`{"users":[{"name":"users/admin","username":"root","role":"ADMIN"}]}`, `users[0].username must equal "admin"`},
+ "missing role": {`{"users":[{"name":"users/admin","username":"admin"}]}`, "users[0].role is required"},
+ "profile field": {`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","description":"hi"}]}`, "users[0].description cannot be configured"},
+ "lifecycle no name": {`{"lifecycle":[{"preventDestroy":true}]}`, "lifecycle[0].resource is required"},
+ "write-only on idp": {`{"identityProviders":[{"name":"identity-providers/sso"}],"lifecycle":[{"resource":"identity-providers/sso","writeOnlyVersion":1}]}`, "writeOnlyVersion applies only to users"},
+ "negative version": {`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}],"lifecycle":[{"resource":"users/admin","writeOnlyVersion":-1}]}`, "must not be negative"},
+ "unknown path": {`{"identityProviders":[{"name":"identity-providers/sso"}],"lifecycle":[{"resource":"identity-providers/sso","ignoreChanges":["config.oauth2Config.scope"]}]}`, `has no field "scope"`},
+ "ignore name": {`{"identityProviders":[{"name":"identity-providers/sso"}],"lifecycle":[{"resource":"identity-providers/sso","ignoreChanges":["name"]}]}`, "cannot be ignored"},
+ "path through list": {`{"identityProviders":[{"name":"identity-providers/sso"}],"lifecycle":[{"resource":"identity-providers/sso","ignoreChanges":["config.oauth2Config.scopes.x"]}]}`, "is not a message field"},
+ "removed bad name": {`{"removed":[{"resource":"memos/123"}]}`, "removed[0].resource"},
+ "lifecycle dangling": {`{"lifecycle":[{"resource":"users/admin"}]}`, "names users/admin, which no file declares"},
+ "removed declared": {`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}],"removed":[{"resource":"users/admin"}]}`, "is removed but still declared"},
+ }
+ for name, test := range tests {
+ t.Run(name, func(t *testing.T) {
+ _, err := Load(writeFiles(t, map[string]string{"config.json": test.document}), placeholderResolver())
+ requireProblems(t, err, test.want)
+ })
+ }
+
+ _, err := Load(writeFiles(t, map[string]string{
+ "config.json": `{"identityProviders":[` + validIDP + `],"lifecycle":[{"resource":"identity-providers/sso","ignoreChanges":["config.oauth2Config.scopes","title"]}]}`,
+ }), placeholderResolver())
+ require.NoError(t, err, "ignoreChanges may name nested and top-level fields")
+}
+
+func TestLoadChecksResourceRules(t *testing.T) {
+ tests := map[string]struct {
+ document string
+ want string
+ }{
+ "incomplete provider": {`{"identityProviders":[{"name":"identity-providers/sso","type":"OAUTH2","title":"SSO"}]}`,
+ "config.json: identity-providers/sso: config.oauth2_config is required"},
+ "storage default typo": {`{"instanceSettings":[{"name":"instance/settings/STORAGE","storageSetting":{"defaultStorageId":"mian",
+ "storages":[{"id":"main","type":"LOCAL"}]}}]}`, `instance/settings/STORAGE: default storage "mian" is not configured`},
+ "incomplete s3": {`{"instanceSettings":[{"name":"instance/settings/STORAGE","storageSetting":{"defaultStorageId":"s3",
+ "storages":[{"id":"s3","type":"S3","s3Config":{"endpoint":"https://s3.example.com","bucket":"memos"}}]}}]}`, "storage s3 region is required"},
+ "ai without key": {`{"instanceSettings":[{"name":"instance/settings/AI","aiSetting":{"providers":[{"id":"openai","title":"OpenAI","type":"OPENAI"}]}}]}`,
+ `provider "openai" API key is required`},
+ "ai without id": {`{"instanceSettings":[{"name":"instance/settings/AI","aiSetting":{"providers":[{"title":"OpenAI","type":"OPENAI","apiKey":"k"}]}}]}`,
+ "providers[0].id is required"},
+ "email without host": {`{"instanceSettings":[{"name":"instance/settings/NOTIFICATION","notificationSetting":{"email":{"enabled":true}}}]}`,
+ "requires smtp_host"},
+ "usage limits order": {`{"instanceSettings":[{"name":"instance/settings/USAGE_LIMITS","usageLimitsSetting":{"limits":[
+ {"allUsers":true},{"users":["users/alice"],"memoCount":"10"}]}}]}`, "instance/settings/USAGE_LIMITS:"},
+ "usage limits bad user": {`{"instanceSettings":[{"name":"instance/settings/USAGE_LIMITS","usageLimitsSetting":{"limits":[
+ {"users":["memos/1"]},{"allUsers":true}]}}]}`, `names "memos/1", which is not a user name`},
+ "invalid email": {`{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","email":"not an email"}]}`, "users/admin:"},
+ "week start": {`{"instanceSettings":[{"name":"instance/settings/GENERAL","generalSetting":{"weekStartDayOffset":9}}]}`,
+ "week_start_day_offset"},
+ }
+ for name, test := range tests {
+ t.Run(name, func(t *testing.T) {
+ _, err := Load(writeFiles(t, map[string]string{"config.json": test.document}), placeholderResolver())
+ requireProblems(t, err, test.want)
+ })
+ }
+
+ _, err := Load(writeFiles(t, map[string]string{"config.json": `{"instanceSettings":[
+ {"name":"instance/settings/USAGE_LIMITS","usageLimitsSetting":{"limits":[{"users":["users/alice","users/bob"],"memoCount":"100"},{"allUsers":true,"memoCount":"10"}]}},
+ {"name":"instance/settings/AI","aiSetting":{"providers":[{"id":"openai","title":"OpenAI","type":"OPENAI","apiKey":"k"}],"transcription":{"providerId":"openai"}}},
+ {"name":"instance/settings/STORAGE","storageSetting":{"storageType":"LOCAL"}}
+ ]}`}), placeholderResolver())
+ require.NoError(t, err, "valid usage limits, AI, and legacy storage settings load")
+}
+
+func TestLoadRejectsDeclarationsInTwoFiles(t *testing.T) {
+ user := `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}],"lifecycle":[{"resource":"users/admin"}]}`
+ _, err := Load(writeFiles(t, map[string]string{"a.json": user, "b.json": user}), placeholderResolver())
+ requireProblems(t, err,
+ "b.json: resource for users/admin is also declared in a.json",
+ "b.json: a lifecycle rule for users/admin is also declared in a.json")
+}
+
+func TestLoadReportsEveryFile(t *testing.T) {
+ _, err := Load(writeFiles(t, map[string]string{
+ "a.json": `{"users":[{"name":"users/admin"}]}`,
+ "b.json": `{"bogus":true}`,
+ }), placeholderResolver())
+ requireProblems(t, err, "a.json: users[0]", `b.json: unknown field "bogus"`)
+}
+
+func TestInspectorWarnsOnDeprecatedFields(t *testing.T) {
+ file, err := protodesc.NewFile(&descriptorpb.FileDescriptorProto{
+ Name: new("deprecated_test.proto"),
+ Package: new("memos.test"),
+ Syntax: new("proto3"),
+ MessageType: []*descriptorpb.DescriptorProto{{
+ Name: new("Settings"),
+ Field: []*descriptorpb.FieldDescriptorProto{{
+ Name: new("old_flag"),
+ JsonName: new("oldFlag"),
+ Number: new(int32(1)),
+ Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
+ Type: descriptorpb.FieldDescriptorProto_TYPE_BOOL.Enum(),
+ Options: &descriptorpb.FieldOptions{Deprecated: new(true)},
+ }},
+ }},
+ }, nil)
+ require.NoError(t, err)
+ in := &inspector{}
+ in.message("settings", map[string]any{"oldFlag": true}, file.Messages().ByName("Settings"))
+ require.Equal(t, []string{"settings.oldFlag is deprecated"}, in.warnings)
+ require.Empty(t, in.problems)
+}
diff --git a/core/configuration/decode.go b/core/configuration/decode.go
new file mode 100644
index 000000000..3a162b9d3
--- /dev/null
+++ b/core/configuration/decode.go
@@ -0,0 +1,312 @@
+package configuration
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/types/descriptorpb"
+
+ apipb "github.com/usememos/memos/proto/gen/api"
+)
+
+var (
+ referencePattern = regexp.MustCompile(`^\$\{(env|file):([^}]*)\}$`)
+ envNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
+
+ // protojson errors can quote the rejected value, which may be a
+ // substituted secret. Only these value-free forms are passed on.
+ unknownFieldPattern = regexp.MustCompile(`unknown field "[^"]+"`)
+ duplicateFieldPattern = regexp.MustCompile(`duplicate field "[^"]+"`)
+ invalidValuePattern = regexp.MustCompile(`invalid value for [a-z0-9]+ field [A-Za-z0-9_]+`)
+ oneofPattern = regexp.MustCompile(`oneof [A-Za-z0-9_.]+ is already set`)
+)
+
+// decodeDocument substitutes references in one file and decodes it strictly.
+// It also returns, for each user by index, the optional user fields the file
+// declares.
+func decodeDocument(content []byte, resolver Resolver) (*apipb.Configuration, map[int][]string, []string, []string) {
+ decoder := json.NewDecoder(bytes.NewReader(content))
+ decoder.UseNumber()
+ r := &jsonReader{decoder: decoder, resolver: resolver}
+ value, err := r.value("")
+ if err != nil {
+ return nil, nil, nil, []string{describeJSONError(err, content)}
+ }
+ if _, err := decoder.Token(); err != io.EOF {
+ return nil, nil, nil, []string{"unexpected data after the JSON document"}
+ }
+ object, ok := value.(map[string]any)
+ if !ok {
+ return nil, nil, nil, []string{"the document must be a JSON object"}
+ }
+
+ // Marshalling a substituted tree cannot fail: it holds only JSON values.
+ normalized, _ := json.Marshal(value)
+ document := &apipb.Configuration{}
+ if err := (protojson.UnmarshalOptions{}).Unmarshal(normalized, document); err != nil {
+ return nil, nil, nil, []string{describeProtoJSONError(err)}
+ }
+
+ inspector := &inspector{}
+ inspector.message("", value, document.ProtoReflect().Descriptor())
+ return document, declaredUserFields(object), inspector.warnings, inspector.problems
+}
+
+// optionalUserFields are the User fields managed only when a file declares them.
+var optionalUserFields = []string{"displayName", "email"}
+
+// declaredUserFields returns, for each user in a decoded document by index,
+// which optional fields the document names, in either JSON or proto spelling.
+func declaredUserFields(document map[string]any) map[int][]string {
+ users, ok := document["users"].([]any)
+ if !ok {
+ return nil
+ }
+ descriptor := (&apipb.User{}).ProtoReflect().Descriptor()
+ result := map[int][]string{}
+ for i, entry := range users {
+ object, ok := entry.(map[string]any)
+ if !ok {
+ continue
+ }
+ for _, jsonName := range optionalUserFields {
+ field := descriptor.Fields().ByJSONName(jsonName)
+ if _, declared := object[jsonName]; declared {
+ result[i] = append(result[i], jsonName)
+ } else if _, declared := object[string(field.Name())]; declared {
+ result[i] = append(result[i], jsonName)
+ }
+ }
+ }
+ return result
+}
+
+// jsonReader reads a JSON value token by token, substituting references in
+// string values and reporting paths in the document's own key spelling.
+type jsonReader struct {
+ decoder *json.Decoder
+ resolver Resolver
+}
+
+func (r *jsonReader) value(path string) (any, error) {
+ token, err := r.decoder.Token()
+ if err != nil {
+ return nil, err
+ }
+ switch t := token.(type) {
+ case json.Delim:
+ switch t {
+ case '{':
+ object := map[string]any{}
+ for r.decoder.More() {
+ keyToken, err := r.decoder.Token()
+ if err != nil {
+ return nil, err
+ }
+ // Inside an object, encoding/json returns every key as a string.
+ key, ok := keyToken.(string)
+ if !ok {
+ return nil, errors.Errorf("%s: object key must be a string", path)
+ }
+ childPath := joinKey(path, key)
+ if _, ok := object[key]; ok {
+ return nil, errors.Errorf("%s: duplicate key", childPath)
+ }
+ child, err := r.value(childPath)
+ if err != nil {
+ return nil, err
+ }
+ object[key] = child
+ }
+ if _, err := r.decoder.Token(); err != nil {
+ return nil, err
+ }
+ return object, nil
+ case '[':
+ list := []any{}
+ for r.decoder.More() {
+ child, err := r.value(fmt.Sprintf("%s[%d]", path, len(list)))
+ if err != nil {
+ return nil, err
+ }
+ list = append(list, child)
+ }
+ if _, err := r.decoder.Token(); err != nil {
+ return nil, err
+ }
+ return list, nil
+ default:
+ return nil, errors.Errorf("unexpected %q", t.String())
+ }
+ case string:
+ return r.substitute(path, t)
+ default:
+ return token, nil
+ }
+}
+
+// substitute resolves a string that is exactly one ${env:NAME} or
+// ${file:PATH} reference, and turns each $${ into a literal ${. Errors name
+// the path and the reference, never a resolved value.
+func (r *jsonReader) substitute(path, value string) (string, error) {
+ if !hasUnescapedReference(value) {
+ return strings.ReplaceAll(value, "$${", "${"), nil
+ }
+ match := referencePattern.FindStringSubmatch(value)
+ if match == nil {
+ if strings.HasPrefix(value, "${") && strings.HasSuffix(value, "}") && strings.Count(value, "${") == 1 {
+ return "", errors.Errorf("%s: unsupported reference; use ${env:NAME} or ${file:/absolute/path}", path)
+ }
+ return "", errors.Errorf("%s: a reference must be the whole string value; write $${ for a literal ${", path)
+ }
+ switch kind, target := match[1], match[2]; kind {
+ case "env":
+ if !envNamePattern.MatchString(target) {
+ return "", errors.Errorf("%s: invalid environment variable name %q", path, target)
+ }
+ resolved, ok := r.resolver.LookupEnv(target)
+ if !ok {
+ return "", errors.Errorf("%s: environment variable %s is not set", path, target)
+ }
+ return resolved, nil
+ default:
+ if !filepath.IsAbs(target) {
+ return "", errors.Errorf("%s: file reference %q must be an absolute path", path, target)
+ }
+ content, err := r.resolver.ReadFile(target)
+ if err != nil {
+ return "", errors.Errorf("%s: cannot read %s: %v", path, target, err)
+ }
+ if len(content) > maxReferencedFileSize {
+ return "", errors.Errorf("%s: %s is larger than %d bytes", path, target, maxReferencedFileSize)
+ }
+ return strings.TrimRight(string(content), "\r\n"), nil
+ }
+}
+
+func hasUnescapedReference(value string) bool {
+ for i := 0; i+1 < len(value); i++ {
+ if value[i] == '$' && value[i+1] == '{' && (i == 0 || value[i-1] != '$') {
+ return true
+ }
+ }
+ return false
+}
+
+func joinKey(path, key string) string {
+ if path == "" {
+ return key
+ }
+ return path + "." + key
+}
+
+func describeJSONError(err error, content []byte) string {
+ var syntaxError *json.SyntaxError
+ if errors.As(err, &syntaxError) {
+ line, column := position(content, syntaxError.Offset)
+ return fmt.Sprintf("line %d, column %d: %s", line, column, syntaxError.Error())
+ }
+ if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
+ return "unexpected end of JSON"
+ }
+ return err.Error()
+}
+
+func position(content []byte, offset int64) (int, int) {
+ offset = min(offset, int64(len(content)))
+ before := content[:offset]
+ line := bytes.Count(before, []byte("\n")) + 1
+ column := len(before) - bytes.LastIndexByte(before, '\n') - 1
+ return line, column
+}
+
+func describeProtoJSONError(err error) string {
+ message := err.Error()
+ for _, pattern := range []*regexp.Regexp{unknownFieldPattern, duplicateFieldPattern, invalidValuePattern, oneofPattern} {
+ if found := pattern.FindString(message); found != "" {
+ return found
+ }
+ }
+ return "invalid protobuf JSON; check field names and value types"
+}
+
+// inspector walks a decoded document beside its message descriptor and
+// reports what protojson accepts but configuration does not: numeric enum
+// values and output-only fields. Deprecated fields are warnings.
+type inspector struct {
+ problems []string
+ warnings []string
+}
+
+func (in *inspector) message(path string, value any, descriptor protoreflect.MessageDescriptor) {
+ object, ok := value.(map[string]any)
+ if !ok || strings.HasPrefix(string(descriptor.FullName()), "google.protobuf.") {
+ return
+ }
+ keys := make([]string, 0, len(object))
+ for key := range object {
+ keys = append(keys, key)
+ }
+ slices.Sort(keys)
+ for _, key := range keys {
+ field := descriptor.Fields().ByJSONName(key)
+ if field == nil {
+ field = descriptor.Fields().ByTextName(key)
+ }
+ if field == nil || object[key] == nil {
+ continue
+ }
+ in.field(joinKey(path, key), object[key], field)
+ }
+}
+
+func (in *inspector) field(path string, value any, field protoreflect.FieldDescriptor) {
+ if options, ok := field.Options().(*descriptorpb.FieldOptions); ok && options.GetDeprecated() {
+ in.warnings = append(in.warnings, path+" is deprecated")
+ }
+ if isOutputOnly(field) {
+ in.problems = append(in.problems, path+" is output only and cannot be configured")
+ return
+ }
+
+ element := func(elementPath string, elementValue any, kind protoreflect.Kind, message protoreflect.MessageDescriptor) {
+ switch kind {
+ case protoreflect.EnumKind:
+ if _, isNumber := elementValue.(json.Number); isNumber {
+ in.problems = append(in.problems, elementPath+": use the enum value name, not its number")
+ }
+ case protoreflect.MessageKind, protoreflect.GroupKind:
+ in.message(elementPath, elementValue, message)
+ default:
+ }
+ }
+ switch {
+ case field.IsMap():
+ object, ok := value.(map[string]any)
+ if !ok {
+ return
+ }
+ for key, entry := range object {
+ element(path+"."+key, entry, field.MapValue().Kind(), field.MapValue().Message())
+ }
+ case field.IsList():
+ list, ok := value.([]any)
+ if !ok {
+ return
+ }
+ for i, entry := range list {
+ element(fmt.Sprintf("%s[%d]", path, i), entry, field.Kind(), field.Message())
+ }
+ default:
+ element(path, value, field.Kind(), field.Message())
+ }
+}
diff --git a/core/configuration/diff.go b/core/configuration/diff.go
new file mode 100644
index 000000000..2e83a7b85
--- /dev/null
+++ b/core/configuration/diff.go
@@ -0,0 +1,262 @@
+package configuration
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "strconv"
+ "strings"
+
+ "google.golang.org/genproto/googleapis/api/annotations"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoreflect"
+ "google.golang.org/protobuf/types/descriptorpb"
+
+ apipb "github.com/usememos/memos/proto/gen/api"
+)
+
+// Placeholders printed in place of values a plan must not reveal.
+const (
+ sensitivePlaceholder = "(sensitive)"
+ writeOnlyPlaceholder = "(write-only)"
+)
+
+// sensitiveFields are the fields a plan compares but never prints: the same
+// secrets API responses leave out. User.password is write-only and is never
+// read back to compare at all.
+var sensitiveFields = []protoreflect.FullName{
+ "memos.api.OAuth2Config.client_secret",
+ "memos.api.InstanceSetting.StorageSetting.S3Config.access_key_secret",
+ "memos.api.InstanceSetting.Storage.S3Config.access_key_secret",
+ "memos.api.InstanceSetting.NotificationSetting.EmailSetting.smtp_password",
+ "memos.api.InstanceSetting.AIProviderConfig.api_key",
+ "memos.api.User.password",
+}
+
+func isSensitive(field protoreflect.FieldDescriptor) bool {
+ return slices.Contains(sensitiveFields, field.FullName())
+}
+
+func isOutputOnly(field protoreflect.FieldDescriptor) bool {
+ options, ok := field.Options().(*descriptorpb.FieldOptions)
+ if !ok {
+ return false
+ }
+ behaviors, ok := proto.GetExtension(options, annotations.E_FieldBehavior).([]annotations.FieldBehavior)
+ return ok && slices.Contains(behaviors, annotations.FieldBehavior_OUTPUT_ONLY)
+}
+
+// diffResource lists the fields that differ between two resources of the
+// same kind, by JSON-name path, skipping the resource name and every path
+// ignored covers. A nil before means the resource does not exist yet, so
+// every set field of after is listed with an empty before.
+func diffResource(before, after proto.Message, ignored []string) []*apipb.FieldChange {
+ d := &differ{ignored: ignored, creating: before == nil}
+ if before == nil {
+ before = after.ProtoReflect().Type().New().Interface()
+ }
+ d.message("", before.ProtoReflect(), after.ProtoReflect())
+ return d.changes
+}
+
+type differ struct {
+ ignored []string
+ creating bool
+ changes []*apipb.FieldChange
+}
+
+func (d *differ) message(path string, before, after protoreflect.Message) {
+ fields := after.Descriptor().Fields()
+ for i := range fields.Len() {
+ field := fields.Get(i)
+ if path == "" && field.Name() == "name" {
+ continue
+ }
+ if isOutputOnly(field) {
+ continue
+ }
+ fieldPath := joinKey(path, field.JSONName())
+ if coveredBy(fieldPath, d.ignored) {
+ continue
+ }
+ d.field(fieldPath, field, before, after)
+ }
+}
+
+func (d *differ) field(path string, field protoreflect.FieldDescriptor, before, after protoreflect.Message) {
+ beforeSet, afterSet := before.Has(field), after.Has(field)
+ if !beforeSet && !afterSet {
+ return
+ }
+ beforeValue, afterValue := before.Get(field), after.Get(field)
+ switch {
+ case field.IsList() && isMessageKind(field) && beforeValue.List().Len() == afterValue.List().Len():
+ // Lists of the same length are compared element by element, so a change
+ // deep in one storage or AI provider names its own path.
+ for i := range afterValue.List().Len() {
+ d.message(fmt.Sprintf("%s[%d]", path, i), beforeValue.List().Get(i).Message(), afterValue.List().Get(i).Message())
+ }
+ case !field.IsList() && !field.IsMap() && isMessageKind(field):
+ // An unset message reads as an empty one, so a message set on only one
+ // side is listed field by field, the way a created resource is.
+ d.message(path, beforeValue.Message(), afterValue.Message())
+ default:
+ if valuesEqual(field, beforeValue, afterValue) {
+ return
+ }
+ change := &apipb.FieldChange{Path: path, After: renderField(field, afterValue)}
+ if !d.creating {
+ change.Before = renderField(field, beforeValue)
+ }
+ d.changes = append(d.changes, change)
+ }
+}
+
+func isMessageKind(field protoreflect.FieldDescriptor) bool {
+ return field.Kind() == protoreflect.MessageKind || field.Kind() == protoreflect.GroupKind
+}
+
+func valuesEqual(field protoreflect.FieldDescriptor, a, b protoreflect.Value) bool {
+ switch {
+ case field.IsList():
+ if a.List().Len() != b.List().Len() {
+ return false
+ }
+ for i := range a.List().Len() {
+ if !elementEqual(field, a.List().Get(i), b.List().Get(i)) {
+ return false
+ }
+ }
+ return true
+ case field.IsMap():
+ if a.Map().Len() != b.Map().Len() {
+ return false
+ }
+ equal := true
+ a.Map().Range(func(key protoreflect.MapKey, value protoreflect.Value) bool {
+ other := b.Map().Get(key)
+ equal = b.Map().Has(key) && elementEqual(field.MapValue(), value, other)
+ return equal
+ })
+ return equal
+ default:
+ return elementEqual(field, a, b)
+ }
+}
+
+func elementEqual(field protoreflect.FieldDescriptor, a, b protoreflect.Value) bool {
+ switch field.Kind() {
+ case protoreflect.MessageKind, protoreflect.GroupKind:
+ return proto.Equal(a.Message().Interface(), b.Message().Interface())
+ case protoreflect.BytesKind:
+ return string(a.Bytes()) == string(b.Bytes())
+ default:
+ return a.Interface() == b.Interface()
+ }
+}
+
+// renderField prints a field value as JSON, with sensitive values replaced.
+func renderField(field protoreflect.FieldDescriptor, value protoreflect.Value) string {
+ if isSensitive(field) {
+ if value.String() == "" {
+ return `""`
+ }
+ return sensitivePlaceholder
+ }
+ switch {
+ case field.IsList():
+ elements := make([]string, 0, value.List().Len())
+ for i := range value.List().Len() {
+ elements = append(elements, renderElement(field, value.List().Get(i)))
+ }
+ return "[" + strings.Join(elements, ", ") + "]"
+ case field.IsMap():
+ entries := []string{}
+ value.Map().Range(func(key protoreflect.MapKey, entry protoreflect.Value) bool {
+ entries = append(entries, strconv.Quote(key.String())+": "+renderElement(field.MapValue(), entry))
+ return true
+ })
+ slices.Sort(entries)
+ return "{" + strings.Join(entries, ", ") + "}"
+ default:
+ return renderElement(field, value)
+ }
+}
+
+func renderElement(field protoreflect.FieldDescriptor, value protoreflect.Value) string {
+ switch field.Kind() {
+ case protoreflect.MessageKind, protoreflect.GroupKind:
+ message := proto.Clone(value.Message().Interface())
+ maskSensitive(message.ProtoReflect(), sensitivePlaceholder)
+ rendered, err := protojson.MarshalOptions{UseProtoNames: false}.Marshal(message)
+ if err != nil {
+ return "(unprintable)"
+ }
+ // protojson output spacing is deliberately unstable; reformat it.
+ var compact any
+ if json.Unmarshal(rendered, &compact) != nil {
+ return "(unprintable)"
+ }
+ stable, _ := json.Marshal(compact)
+ return string(stable)
+ case protoreflect.EnumKind:
+ if enumValue := field.Enum().Values().ByNumber(value.Enum()); enumValue != nil {
+ return string(enumValue.Name())
+ }
+ return strconv.Itoa(int(value.Enum()))
+ case protoreflect.StringKind:
+ return strconv.Quote(value.String())
+ case protoreflect.BytesKind:
+ return strconv.Quote(base64.StdEncoding.EncodeToString(value.Bytes()))
+ default:
+ return fmt.Sprint(value.Interface())
+ }
+}
+
+// maskSensitive replaces every non-empty sensitive string in message, at any depth, with placeholder.
+func maskSensitive(message protoreflect.Message, placeholder string) {
+ message.Range(func(field protoreflect.FieldDescriptor, value protoreflect.Value) bool {
+ switch {
+ case isSensitive(field) && field.Kind() == protoreflect.StringKind && !field.IsList():
+ if value.String() != "" {
+ message.Set(field, protoreflect.ValueOfString(placeholder))
+ }
+ case field.IsList() && isMessageKind(field):
+ for i := range value.List().Len() {
+ maskSensitive(value.List().Get(i).Message(), placeholder)
+ }
+ case field.IsMap() && isMessageKind(field.MapValue()):
+ value.Map().Range(func(_ protoreflect.MapKey, entry protoreflect.Value) bool {
+ maskSensitive(entry.Message(), placeholder)
+ return true
+ })
+ case !field.IsList() && !field.IsMap() && isMessageKind(field):
+ maskSensitive(value.Message(), placeholder)
+ default:
+ }
+ return true
+ })
+}
+
+// digest identifies a declared value without being derivable into a secret:
+// sensitive and write-only values are masked before hashing, so only whether
+// they are set affects it.
+func digest(messages ...proto.Message) string {
+ hash := sha256.New()
+ for _, message := range messages {
+ masked := proto.Clone(message)
+ maskSensitive(masked.ProtoReflect(), "set")
+ encoded, err := proto.MarshalOptions{Deterministic: true}.Marshal(masked)
+ if err != nil {
+ // A generated message always marshals; fall back to a fixed digest.
+ encoded = nil
+ }
+ fmt.Fprintf(hash, "%d:", len(encoded))
+ hash.Write(encoded)
+ }
+ return hex.EncodeToString(hash.Sum(nil))
+}
diff --git a/core/configuration/guard.go b/core/configuration/guard.go
new file mode 100644
index 000000000..48eedd9c5
--- /dev/null
+++ b/core/configuration/guard.go
@@ -0,0 +1,110 @@
+package configuration
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+
+ "google.golang.org/protobuf/proto"
+
+ storepb "github.com/usememos/memos/proto/gen/store"
+)
+
+// ManagedError reports an API write refused because the configuration
+// manages what it would change.
+type ManagedError struct {
+ // Resource is the resource name.
+ Resource string
+ // Source is the configuration file that declares it.
+ Source string
+ // Fields are the managed JSON-name paths the write would change.
+ Fields []string
+ // ReferencedBy, when set, is the managed resource that names Resource;
+ // Source is then the file that declares it.
+ ReferencedBy string
+}
+
+func (e *ManagedError) Error() string {
+ if e.ReferencedBy != "" {
+ return fmt.Sprintf("%s is named by %s in %s; remove it there and apply first", e.Resource, e.ReferencedBy, e.Source)
+ }
+ return fmt.Sprintf("%s is managed by configuration in %s; change %s there", e.Resource, e.Source, strings.Join(e.Fields, ", "))
+}
+
+// CheckChange returns a *ManagedError when state manages resource and changed,
+// the JSON-name paths a write would change, includes a managed field that
+// lifecycle ignoreChanges does not release. A write that changes nothing the
+// configuration manages, such as one resending managed values, passes.
+func CheckChange(state *storepb.InstanceConfigurationState, resource string, changed []string) error {
+ managed := findManaged(state, resource)
+ if managed == nil {
+ return nil
+ }
+ var refused []string
+ for _, path := range changed {
+ if coveredBy(path, managed.ManagedFields) && !coveredBy(path, managed.IgnoredFields) {
+ refused = append(refused, path)
+ }
+ }
+ if len(refused) == 0 {
+ return nil
+ }
+ return &ManagedError{Resource: resource, Source: managed.Source, Fields: refused}
+}
+
+// CheckExistence returns a *ManagedError when state manages resource, so the
+// API can neither create one with its name nor delete it.
+func CheckExistence(state *storepb.InstanceConfigurationState, resource string) error {
+ managed := findManaged(state, resource)
+ if managed == nil {
+ return nil
+ }
+ return &ManagedError{Resource: resource, Source: managed.Source, Fields: slices.Clone(managed.ManagedFields)}
+}
+
+// CheckReference returns a *ManagedError when a resource state manages names
+// resource, so the API can neither rename nor delete it: the next plan would
+// not resolve the name.
+func CheckReference(state *storepb.InstanceConfigurationState, resource string) error {
+ for _, managed := range state.GetResources() {
+ if slices.Contains(managed.References, resource) {
+ return &ManagedError{Resource: resource, Source: managed.Source, ReferencedBy: managed.Name}
+ }
+ }
+ return nil
+}
+
+// Manages reports whether state manages resource.
+func Manages(state *storepb.InstanceConfigurationState, resource string) bool {
+ return findManaged(state, resource) != nil
+}
+
+// ChangedPaths lists the JSON-name paths that differ between two API
+// messages of the same type; a nil before lists every set field of after.
+func ChangedPaths(before, after proto.Message) []string {
+ paths := []string{}
+ for _, change := range diffResource(before, after, nil) {
+ paths = append(paths, change.Path)
+ }
+ return paths
+}
+
+func findManaged(state *storepb.InstanceConfigurationState, resource string) *storepb.InstanceConfigurationState_ManagedResource {
+ for _, managed := range state.GetResources() {
+ if managed.Name == resource {
+ return managed
+ }
+ }
+ return nil
+}
+
+// coveredBy reports whether path is one of fields or lies beneath one; "*"
+// covers every path.
+func coveredBy(path string, fields []string) bool {
+ for _, field := range fields {
+ if field == "*" || path == field || strings.HasPrefix(path, field+".") || strings.HasPrefix(path, field+"[") {
+ return true
+ }
+ }
+ return false
+}
diff --git a/core/configuration/guard_test.go b/core/configuration/guard_test.go
new file mode 100644
index 000000000..46ab11cec
--- /dev/null
+++ b/core/configuration/guard_test.go
@@ -0,0 +1,45 @@
+package configuration
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/usememos/memos/proto/gen/store"
+)
+
+func TestGuard(t *testing.T) {
+ state := &storepb.InstanceConfigurationState{Resources: []*storepb.InstanceConfigurationState_ManagedResource{
+ {Name: "instance/settings/GENERAL", Source: "general.json", ManagedFields: []string{"*"}, IgnoredFields: []string{"generalSetting.customProfile"}},
+ {Name: "users/admin", Source: "users.json", ManagedFields: []string{"username", "role"}},
+ }}
+
+ require.NoError(t, CheckChange(state, "instance/settings/GENERAL", nil), "a write that changes nothing passes")
+ require.NoError(t, CheckChange(state, "instance/settings/GENERAL", []string{"generalSetting.customProfile.title"}), "ignored fields are released")
+ err := CheckChange(state, "instance/settings/GENERAL", []string{"generalSetting.customProfile.title", "generalSetting.disallowPasswordAuth"})
+ var managed *ManagedError
+ require.ErrorAs(t, err, &managed)
+ require.Equal(t, &ManagedError{Resource: "instance/settings/GENERAL", Source: "general.json", Fields: []string{"generalSetting.disallowPasswordAuth"}}, managed)
+ require.Contains(t, err.Error(), "managed by configuration in general.json")
+
+ require.NoError(t, CheckChange(state, "users/admin", []string{"displayName"}), "an undeclared profile field is the user's")
+ require.Error(t, CheckChange(state, "users/admin", []string{"role"}))
+ require.NoError(t, CheckChange(state, "users/other", []string{"role"}), "unmanaged resources are not guarded")
+
+ require.Error(t, CheckExistence(state, "users/admin"))
+ require.NoError(t, CheckExistence(state, "identity-providers/sso"))
+ require.NoError(t, CheckExistence(&storepb.InstanceConfigurationState{}, "users/admin"))
+}
+
+func TestCheckReference(t *testing.T) {
+ state := &storepb.InstanceConfigurationState{Resources: []*storepb.InstanceConfigurationState_ManagedResource{
+ {Name: "instance/settings/USAGE_LIMITS", Source: "limits.json", ManagedFields: []string{"*"}, References: []string{"users/alice"}},
+ }}
+
+ err := CheckReference(state, "users/alice")
+ var managed *ManagedError
+ require.ErrorAs(t, err, &managed)
+ require.Equal(t, &ManagedError{Resource: "users/alice", Source: "limits.json", ReferencedBy: "instance/settings/USAGE_LIMITS"}, managed)
+ require.Contains(t, err.Error(), "users/alice is named by instance/settings/USAGE_LIMITS in limits.json")
+ require.NoError(t, CheckReference(state, "users/bob"), "a user no managed resource names is not guarded")
+}
diff --git a/core/configuration/plan.go b/core/configuration/plan.go
new file mode 100644
index 000000000..b4d4f602a
--- /dev/null
+++ b/core/configuration/plan.go
@@ -0,0 +1,591 @@
+package configuration
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/usememos/memos/core/identityprovider"
+ "github.com/usememos/memos/core/instancesetting"
+ coreuser "github.com/usememos/memos/core/user"
+ apipb "github.com/usememos/memos/proto/gen/api"
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+)
+
+// Reader is what a plan reads from the instance. *store.Store implements it.
+// Every read bypasses caches, so a plan sees what is stored.
+type Reader interface {
+ GetConfigurationState(ctx context.Context) (*storepb.InstanceConfigurationState, error)
+ ListIdentityProviders(ctx context.Context, find *store.FindIdentityProvider) ([]*storepb.IdentityProvider, error)
+ GetUncachedInstanceSetting(ctx context.Context, find *store.FindInstanceSetting) (*storepb.InstanceSetting, error)
+ ListUsers(ctx context.Context, find *store.FindUser) ([]*store.User, error)
+}
+
+// Plan is what apply would change.
+type Plan struct {
+ // Message is the plan as printed and as --json returns it.
+ Message *apipb.Plan
+ // next is the state record apply writes; nil when the plan has errors.
+ next *storepb.InstanceConfigurationState
+ // operations are the writes apply makes, in apply order.
+ operations []*operation
+}
+
+// operation is what apply writes for one resource change.
+type operation struct {
+ change *apipb.ResourceChange
+ kind Kind
+
+ // The identity provider to write, and the stored one's ID when it exists.
+ provider *storepb.IdentityProvider
+ providerID int32
+
+ // The instance setting to write, or the key to reset.
+ setting *storepb.InstanceSetting
+ settingKey storepb.InstanceSettingKey
+
+ // The managed part of a declared user, and the stored user when it exists.
+ user *apipb.User
+ actualUser *store.User
+}
+
+// Valid reports whether the plan can be applied.
+func (p *Plan) Valid() bool {
+ return len(p.Message.Errors) == 0
+}
+
+// HasChanges reports whether apply would write anything.
+func (p *Plan) HasChanges() bool {
+ return p.Message.StateRecordChanges
+}
+
+// Apply order: identity providers are created and updated first, so a GENERAL
+// setting that needs one finds it; users are destroyed before providers.
+const (
+ rankIdentityProvider = iota
+ rankInstanceSetting
+ rankUser
+ rankUserDestroy
+ rankIdentityProviderDestroy
+)
+
+type rankedChange struct {
+ rank int
+ change *apipb.ResourceChange
+ op *operation
+}
+
+// ComputePlan compares the desired state with what reader holds and returns
+// what apply would do. It never writes. Problems that stop an apply, such as
+// a managed resource no file declares any longer, are in the plan's errors.
+func ComputePlan(ctx context.Context, desired *Desired, reader Reader) (*Plan, error) {
+ state, err := reader.GetConfigurationState(ctx)
+ if err != nil {
+ return nil, err
+ }
+ p := &planner{
+ ctx: ctx,
+ desired: desired,
+ reader: reader,
+ state: state,
+ managed: map[string]*storepb.InstanceConfigurationState_ManagedResource{},
+ lifecycle: map[string]*apipb.Lifecycle{},
+ removed: map[string]*apipb.Removed{},
+ message: &apipb.Plan{Serial: state.Serial, Warnings: slices.Clone(desired.Warnings)},
+ }
+ for _, resource := range state.Resources {
+ p.managed[resource.Name] = resource
+ }
+ for _, lifecycle := range desired.Configuration.Lifecycle {
+ p.lifecycle[lifecycle.Resource] = lifecycle
+ }
+ for _, removed := range desired.Configuration.Removed {
+ p.removed[removed.Resource] = removed
+ }
+
+ steps := []func() error{p.planIdentityProviders, p.planInstanceSettings, p.planUsers, p.planUndeclared, p.checkAuthentication}
+ for _, step := range steps {
+ if err := step(); err != nil {
+ return nil, err
+ }
+ }
+ return p.finish(), nil
+}
+
+type planner struct {
+ ctx context.Context
+ desired *Desired
+ reader Reader
+ state *storepb.InstanceConfigurationState
+ managed map[string]*storepb.InstanceConfigurationState_ManagedResource
+ lifecycle map[string]*apipb.Lifecycle
+ removed map[string]*apipb.Removed
+ message *apipb.Plan
+ changes []rankedChange
+ next []*storepb.InstanceConfigurationState_ManagedResource
+
+ providersByUID map[string]*storepb.IdentityProvider
+
+ // What the authentication invariant needs about the planned end state.
+ providersAfter map[string]bool
+ providerDestroyed bool
+ generalAfter *storepb.InstanceGeneralSetting
+ generalPlanned bool
+}
+
+func (p *planner) fail(resource string, format string, args ...any) {
+ p.message.Errors = append(p.message.Errors, resource+": "+fmt.Sprintf(format, args...))
+}
+
+// declared records the action for a declared resource from its field changes
+// and whether it exists, and the state record entry apply would write.
+func (p *planner) declared(rank int, name string, kind Kind, exists bool, changes []*apipb.FieldChange, entry *storepb.InstanceConfigurationState_ManagedResource, op *operation) {
+ managed := p.managed[name]
+ change := &apipb.ResourceChange{Resource: name, Source: p.desired.Sources[name], FieldChanges: changes}
+ switch {
+ case !exists:
+ change.Action = apipb.ResourceChange_CREATE
+ if managed != nil {
+ change.Drift = true
+ change.Message = "deleted outside the configuration since the last apply"
+ }
+ case managed == nil:
+ change.Action = apipb.ResourceChange_ADOPT
+ case len(changes) > 0:
+ change.Action = apipb.ResourceChange_UPDATE
+ // The declaration is what was last applied, so the instance changed.
+ change.Drift = managed.Digest == entry.Digest
+ default:
+ change.Action = apipb.ResourceChange_NO_OP
+ }
+
+ lifecycle := p.lifecycle[name]
+ entry.Name = name
+ entry.Kind = string(kind)
+ entry.Source = p.desired.Sources[name]
+ entry.IgnoredFields = slices.Clone(lifecycle.GetIgnoreChanges())
+ entry.PreventDestroy = lifecycle.GetPreventDestroy()
+ if change.Action == apipb.ResourceChange_NO_OP && managed != nil {
+ entry.AppliedTs = managed.AppliedTs
+ }
+ op.change, op.kind = change, kind
+ p.changes = append(p.changes, rankedChange{rank: rank, change: change, op: op})
+ p.next = append(p.next, entry)
+}
+
+func (p *planner) planIdentityProviders() error {
+ providers, err := p.reader.ListIdentityProviders(p.ctx, &store.FindIdentityProvider{})
+ if err != nil {
+ return errors.Wrap(err, "failed to read identity providers")
+ }
+ p.providersByUID = map[string]*storepb.IdentityProvider{}
+ p.providersAfter = map[string]bool{}
+ for _, provider := range providers {
+ p.providersByUID[provider.Uid] = provider
+ p.providersAfter[provider.Uid] = true
+ }
+
+ for _, declared := range sortedByName(p.desired.Configuration.IdentityProviders, (*apipb.IdentityProvider).GetName) {
+ desiredStore := identityprovider.ToStore(declared)
+ desiredAPI := identityprovider.FromStore(desiredStore)
+ var actualAPI proto.Message
+ ignored := p.lifecycle[declared.Name].GetIgnoreChanges()
+ op := &operation{provider: desiredStore}
+ actual, exists := p.providersByUID[desiredStore.Uid]
+ if exists {
+ actualAPI = identityprovider.FromStore(actual)
+ op.providerID = actual.Id
+ if len(ignored) > 0 {
+ merged := proto.CloneOf(desiredAPI)
+ copyFields(merged, actualAPI, ignored)
+ op.provider = identityprovider.ToStore(merged)
+ }
+ }
+ changes := diffResource(actualAPI, desiredAPI, ignored)
+ entry := &storepb.InstanceConfigurationState_ManagedResource{
+ ManagedFields: []string{"*"},
+ Digest: digest(desiredAPI, p.lifecycle[declared.Name]),
+ }
+ p.declared(rankIdentityProvider, declared.Name, KindIdentityProvider, exists, changes, entry, op)
+ p.providersAfter[desiredStore.Uid] = true
+ }
+ return nil
+}
+
+func (p *planner) planInstanceSettings() error {
+ for _, declared := range sortedByName(p.desired.Configuration.InstanceSettings, (*apipb.InstanceSetting).GetName) {
+ desiredStore, err := p.settingToStore(declared)
+ if err != nil {
+ p.fail(declared.Name, "%v", err)
+ continue
+ }
+ actual, err := p.reader.GetUncachedInstanceSetting(p.ctx, &store.FindInstanceSetting{Name: desiredStore.Key.String()})
+ if err != nil {
+ return errors.Wrapf(err, "failed to read %s", declared.Name)
+ }
+ desiredAPI, err := p.settingFromStore(desiredStore)
+ if err != nil {
+ return err
+ }
+ var actualAPI proto.Message
+ ignored := p.lifecycle[declared.Name].GetIgnoreChanges()
+ op := &operation{setting: desiredStore, settingKey: desiredStore.Key}
+ if actual != nil {
+ instancesetting.Normalize(actual)
+ if actualAPI, err = p.settingFromStore(actual); err != nil {
+ return err
+ }
+ if len(ignored) > 0 {
+ merged := proto.CloneOf(desiredAPI)
+ copyFields(merged, actualAPI, ignored)
+ if op.setting, err = p.settingToStore(merged); err != nil {
+ p.fail(declared.Name, "%v", err)
+ continue
+ }
+ }
+ }
+ changes := diffResource(actualAPI, desiredAPI, ignored)
+ entry := &storepb.InstanceConfigurationState_ManagedResource{
+ ManagedFields: []string{"*"},
+ Digest: digest(desiredAPI, p.lifecycle[declared.Name]),
+ References: settingReferences(declared),
+ }
+ p.declared(rankInstanceSetting, declared.Name, KindInstanceSetting, actual != nil, changes, entry, op)
+ if desiredStore.Key == storepb.InstanceSettingKey_GENERAL {
+ p.generalAfter = desiredStore.GetGeneralSetting()
+ p.generalPlanned = true
+ }
+ }
+ return nil
+}
+
+// settingToStore converts a declared setting as apply writes it: usage limits
+// name users by resource name, resolved here, and the value is normalized the
+// way every stored write normalizes it, so equal settings compare equal.
+func (p *planner) settingToStore(setting *apipb.InstanceSetting) (*storepb.InstanceSetting, error) {
+ stored := instancesetting.ToStore(setting)
+ if stored.Key == storepb.InstanceSettingKey_USAGE_LIMITS {
+ names := []string{}
+ for _, limit := range setting.GetUsageLimitsSetting().GetLimits() {
+ names = append(names, limit.GetUsers()...)
+ }
+ userIDs, err := p.resolveUserNames(names)
+ if err != nil {
+ return nil, err
+ }
+ usageLimits, err := instancesetting.UsageLimitsToStore(setting.GetUsageLimitsSetting(), userIDs)
+ if err != nil {
+ return nil, err
+ }
+ stored.Value = &storepb.InstanceSetting_UsageLimitsSetting{UsageLimitsSetting: usageLimits}
+ }
+ instancesetting.Normalize(stored)
+ return stored, nil
+}
+
+// settingReferences lists the users a declared usage-limits setting names,
+// sorted and without repeats; other settings name no resources.
+func settingReferences(setting *apipb.InstanceSetting) []string {
+ var names []string
+ for _, limit := range setting.GetUsageLimitsSetting().GetLimits() {
+ names = append(names, limit.GetUsers()...)
+ }
+ slices.Sort(names)
+ return slices.Compact(names)
+}
+
+func (p *planner) settingFromStore(setting *storepb.InstanceSetting) (*apipb.InstanceSetting, error) {
+ result := instancesetting.FromStore(setting)
+ if setting.Key == storepb.InstanceSettingKey_USAGE_LIMITS {
+ userIDs := []int32{}
+ for _, limit := range setting.GetUsageLimitsSetting().GetLimits() {
+ userIDs = append(userIDs, limit.GetUserIds()...)
+ }
+ userNames := map[int32]string{}
+ if len(userIDs) > 0 {
+ users, err := p.reader.ListUsers(p.ctx, &store.FindUser{IDList: userIDs})
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to read users named by usage limits")
+ }
+ for _, user := range users {
+ userNames[user.ID] = coreuser.NamePrefix + user.Username
+ }
+ }
+ result.Value = &apipb.InstanceSetting_UsageLimitsSetting_{
+ UsageLimitsSetting: instancesetting.UsageLimitsFromStore(setting.GetUsageLimitsSetting(), userNames),
+ }
+ }
+ return result, nil
+}
+
+func (p *planner) resolveUserNames(names []string) (map[string]int32, error) {
+ if len(names) == 0 {
+ return map[string]int32{}, nil
+ }
+ usernames := make([]string, 0, len(names))
+ for _, name := range names {
+ usernames = append(usernames, strings.TrimPrefix(name, coreuser.NamePrefix))
+ }
+ users, err := p.reader.ListUsers(p.ctx, &store.FindUser{UsernameList: usernames})
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to read users named by usage limits")
+ }
+ byName := map[string]int32{}
+ for _, user := range users {
+ byName[coreuser.NamePrefix+user.Username] = user.ID
+ }
+ for _, name := range names {
+ if _, ok := byName[name]; !ok {
+ return nil, errors.Errorf("usageLimitsSetting names %s, which does not exist", name)
+ }
+ }
+ return byName, nil
+}
+
+func (p *planner) planUsers() error {
+ declaredUsers := sortedByName(p.desired.Configuration.Users, (*apipb.User).GetName)
+ usernames := make([]string, 0, len(declaredUsers))
+ for _, user := range declaredUsers {
+ usernames = append(usernames, user.Username)
+ }
+ actualByName := map[string]*store.User{}
+ if len(usernames) > 0 {
+ users, err := p.reader.ListUsers(p.ctx, &store.FindUser{UsernameList: usernames})
+ if err != nil {
+ return errors.Wrap(err, "failed to read users")
+ }
+ for _, user := range users {
+ actualByName[user.Username] = user
+ }
+ }
+
+ for _, declared := range declaredUsers {
+ name := declared.Name
+ actual := actualByName[declared.Username]
+ lifecycle := p.lifecycle[name]
+ optional := p.desired.UserFields[name]
+ version := lifecycle.GetWriteOnlyVersion()
+ recorded := p.managed[name].GetWriteOnlyVersion()
+ sendPassword := actual == nil || version > recorded
+ if sendPassword && declared.Password == "" {
+ if actual == nil {
+ p.fail(name, "password is required to create the user")
+ } else {
+ p.fail(name, "writeOnlyVersion is %d, above the %d last applied, but no password is declared", version, recorded)
+ }
+ continue
+ }
+
+ managedView := managedUserView(declared, optional)
+ changes := p.userChanges(managedView, actual, sendPassword, version)
+ entry := &storepb.InstanceConfigurationState_ManagedResource{
+ ManagedFields: append([]string{"username", "role"}, optional...),
+ Digest: digest(managedView, lifecycle),
+ WriteOnlyVersion: max(version, recorded),
+ }
+ p.declared(rankUser, name, KindUser, actual != nil, changes, entry, &operation{user: managedView, actualUser: actual})
+ }
+ return nil
+}
+
+// managedUserView is the part of a declared user the configuration manages.
+func managedUserView(declared *apipb.User, optional []string) *apipb.User {
+ view := &apipb.User{Name: declared.Name, Username: declared.Username, Role: declared.Role, Password: declared.Password}
+ if slices.Contains(optional, "displayName") {
+ view.DisplayName = declared.DisplayName
+ }
+ if slices.Contains(optional, "email") {
+ // Layer 2 already rejected an email that does not normalize.
+ view.Email, _ = store.NormalizeEmail(declared.Email)
+ }
+ return view
+}
+
+func (p *planner) userChanges(view *apipb.User, actual *store.User, sendPassword bool, version int32) []*apipb.FieldChange {
+ ignored := p.lifecycle[view.Name].GetIgnoreChanges()
+ optional := p.desired.UserFields[view.Name]
+ changes := []*apipb.FieldChange{}
+ add := func(path, before, after string) {
+ if slices.Contains(ignored, path) {
+ return
+ }
+ if before != after {
+ changes = append(changes, &apipb.FieldChange{Path: path, Before: before, After: after})
+ }
+ }
+ if actual == nil {
+ add("username", "", strconv.Quote(view.Username))
+ add("role", "", view.Role.String())
+ for _, field := range optional {
+ if field == "displayName" {
+ add(field, "", strconv.Quote(view.DisplayName))
+ } else {
+ add(field, "", strconv.Quote(view.Email))
+ }
+ }
+ } else {
+ add("role", coreuser.RoleFromStore(actual.Role).String(), view.Role.String())
+ for _, field := range optional {
+ if field == "displayName" {
+ add(field, strconv.Quote(actual.Nickname), strconv.Quote(view.DisplayName))
+ } else {
+ add(field, strconv.Quote(actual.Email), strconv.Quote(view.Email))
+ }
+ }
+ }
+ if sendPassword {
+ before := ""
+ if actual != nil {
+ before = writeOnlyPlaceholder
+ }
+ changes = append(changes, &apipb.FieldChange{Path: "password", Before: before, After: fmt.Sprintf("(write-only, version %d)", version)})
+ }
+ return changes
+}
+
+// planUndeclared handles managed resources no file declares any longer: a
+// removed entry destroys, resets, or releases them; without one, removal was
+// not explicit and the plan fails.
+func (p *planner) planUndeclared() error {
+ for _, managed := range p.state.Resources {
+ name := managed.Name
+ if _, declared := p.desired.Sources[name]; declared {
+ continue
+ }
+ removed := p.removed[name]
+ kind, id, err := ParseResourceName(name)
+ if err != nil {
+ p.fail(name, "the state record names a resource this version cannot manage: %v", err)
+ continue
+ }
+ change := &apipb.ResourceChange{Resource: name}
+ op := &operation{change: change, kind: kind}
+ rank := map[Kind]int{KindIdentityProvider: rankIdentityProvider, KindInstanceSetting: rankInstanceSetting, KindUser: rankUser}[kind]
+ switch {
+ case removed == nil:
+ change.Action = apipb.ResourceChange_ERROR
+ change.Message = "managed but no longer declared; add a removed entry to destroy or release it"
+ p.fail(name, "%s", change.Message)
+ case !removed.Destroy:
+ change.Action = apipb.ResourceChange_RELEASE
+ case managed.PreventDestroy:
+ change.Action = apipb.ResourceChange_ERROR
+ change.Message = "preventDestroy was set when last applied; apply once without it, then destroy"
+ p.fail(name, "%s", change.Message)
+ case kind == KindUser:
+ // Deleting a user deletes their memos and attachment files and must
+ // respect their spaces; that belongs to the deletion flow in Settings.
+ change.Action = apipb.ResourceChange_ERROR
+ change.Message = "configuration cannot delete a user; release it with destroy false, then delete the user in Settings"
+ p.fail(name, "%s", change.Message)
+ case kind == KindInstanceSetting:
+ change.Action = apipb.ResourceChange_RESET
+ op.settingKey = storepb.InstanceSettingKey(storepb.InstanceSettingKey_value[id])
+ if id == storepb.InstanceSettingKey_GENERAL.String() {
+ p.generalAfter = &storepb.InstanceGeneralSetting{}
+ p.generalPlanned = true
+ }
+ default:
+ if !p.providersAfter[id] {
+ change.Action = apipb.ResourceChange_RELEASE
+ change.Message = "already deleted outside the configuration"
+ break
+ }
+ change.Action = apipb.ResourceChange_DESTROY
+ rank = rankIdentityProviderDestroy
+ op.providerID = p.providersByUID[id].GetId()
+ delete(p.providersAfter, id)
+ p.providerDestroyed = true
+ }
+ p.changes = append(p.changes, rankedChange{rank: rank, change: change, op: op})
+ }
+ return nil
+}
+
+// checkAuthentication fails a plan that ends with password sign-in disabled
+// for regular users and no identity provider, when the plan itself touches
+// either. An unrelated plan only warns about a stored state already like that.
+func (p *planner) checkAuthentication() error {
+ general := p.generalAfter
+ if !p.generalPlanned {
+ stored, err := p.reader.GetUncachedInstanceSetting(p.ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_GENERAL.String()})
+ if err != nil {
+ return errors.Wrap(err, "failed to read GENERAL")
+ }
+ general = stored.GetGeneralSetting()
+ }
+ if !general.GetDisallowPasswordAuth() || len(p.providersAfter) > 0 {
+ return nil
+ }
+ const problem = "password sign-in is disabled for regular users and no identity provider would remain"
+ if p.generalPlanned || p.providerDestroyed {
+ p.message.Errors = append(p.message.Errors, problem)
+ } else {
+ p.message.Warnings = append(p.message.Warnings, "the stored configuration already has "+problem+"; administrators can still sign in with a password")
+ }
+ return nil
+}
+
+func (p *planner) finish() *Plan {
+ slices.SortStableFunc(p.changes, func(a, b rankedChange) int {
+ if a.rank != b.rank {
+ return a.rank - b.rank
+ }
+ return strings.Compare(a.change.Resource, b.change.Resource)
+ })
+ writes := false
+ plan := &Plan{Message: p.message}
+ for _, ranked := range p.changes {
+ p.message.ResourceChanges = append(p.message.ResourceChanges, ranked.change)
+ plan.operations = append(plan.operations, ranked.op)
+ if ranked.change.Action != apipb.ResourceChange_NO_OP {
+ writes = true
+ }
+ }
+ if !plan.Valid() {
+ return plan
+ }
+
+ slices.SortFunc(p.next, func(a, b *storepb.InstanceConfigurationState_ManagedResource) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+ plan.next = &storepb.InstanceConfigurationState{
+ Serial: p.state.Serial,
+ ConfigDigest: digest(p.desired.Configuration),
+ Resources: p.next,
+ }
+ p.message.StateRecordChanges = writes || !sameRecord(p.state, plan.next)
+ return plan
+}
+
+// sameRecord compares the managed resources of two state records, ignoring
+// the apply metadata a plan does not compute. The config digest is left out:
+// it is informational, so a change to it alone, such as a deleted leftover
+// removed entry, is not worth an apply.
+func sameRecord(a, b *storepb.InstanceConfigurationState) bool {
+ strip := func(state *storepb.InstanceConfigurationState) *storepb.InstanceConfigurationState {
+ stripped := &storepb.InstanceConfigurationState{}
+ for _, resource := range state.Resources {
+ resource = proto.CloneOf(resource)
+ resource.AppliedTs = 0
+ stripped.Resources = append(stripped.Resources, resource)
+ }
+ slices.SortFunc(stripped.Resources, func(x, y *storepb.InstanceConfigurationState_ManagedResource) int {
+ return strings.Compare(x.Name, y.Name)
+ })
+ return stripped
+ }
+ return proto.Equal(strip(a), strip(b))
+}
+
+func sortedByName[T any](items []T, name func(T) string) []T {
+ sorted := slices.Clone(items)
+ slices.SortFunc(sorted, func(a, b T) int { return strings.Compare(name(a), name(b)) })
+ return sorted
+}
diff --git a/core/configuration/plan_test.go b/core/configuration/plan_test.go
new file mode 100644
index 000000000..2ff993572
--- /dev/null
+++ b/core/configuration/plan_test.go
@@ -0,0 +1,417 @@
+package configuration
+
+import (
+ "bytes"
+ "context"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/reflect/protoregistry"
+
+ "github.com/usememos/memos/core/identityprovider"
+ "github.com/usememos/memos/core/instancesetting"
+ apipb "github.com/usememos/memos/proto/gen/api"
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+)
+
+// fakeReader is an in-memory instance for planning.
+type fakeReader struct {
+ state *storepb.InstanceConfigurationState
+ providers []*storepb.IdentityProvider
+ settings map[storepb.InstanceSettingKey]*storepb.InstanceSetting
+ users []*store.User
+}
+
+func newFakeReader() *fakeReader {
+ return &fakeReader{state: &storepb.InstanceConfigurationState{}, settings: map[storepb.InstanceSettingKey]*storepb.InstanceSetting{}}
+}
+
+func (f *fakeReader) GetConfigurationState(context.Context) (*storepb.InstanceConfigurationState, error) {
+ return proto.CloneOf(f.state), nil
+}
+
+func (f *fakeReader) ListIdentityProviders(context.Context, *store.FindIdentityProvider) ([]*storepb.IdentityProvider, error) {
+ result := []*storepb.IdentityProvider{}
+ for _, provider := range f.providers {
+ result = append(result, proto.CloneOf(provider))
+ }
+ return result, nil
+}
+
+func (f *fakeReader) GetUncachedInstanceSetting(_ context.Context, find *store.FindInstanceSetting) (*storepb.InstanceSetting, error) {
+ setting := f.settings[storepb.InstanceSettingKey(storepb.InstanceSettingKey_value[find.Name])]
+ if setting == nil {
+ return nil, nil
+ }
+ return proto.CloneOf(setting), nil
+}
+
+func (f *fakeReader) ListUsers(_ context.Context, find *store.FindUser) ([]*store.User, error) {
+ result := []*store.User{}
+ for _, user := range f.users {
+ if find.Username != nil && user.Username != *find.Username ||
+ len(find.UsernameList) > 0 && !slices.Contains(find.UsernameList, user.Username) ||
+ len(find.IDList) > 0 && !slices.Contains(find.IDList, user.ID) {
+ continue
+ }
+ copied := *user
+ result = append(result, &copied)
+ }
+ return result, nil
+}
+
+// apply stands in for apply: the instance takes the declared values and the
+// state record becomes the plan's.
+func (f *fakeReader) apply(t *testing.T, desired *Desired, plan *Plan) {
+ t.Helper()
+ require.True(t, plan.Valid(), plan.Message.Errors)
+ f.providers = nil
+ for i, provider := range desired.Configuration.IdentityProviders {
+ stored := identityprovider.ToStore(provider)
+ stored.Id = int32(i + 1)
+ f.providers = append(f.providers, stored)
+ }
+ for _, setting := range desired.Configuration.InstanceSettings {
+ stored := instancesetting.ToStore(setting)
+ instancesetting.Normalize(stored)
+ f.settings[stored.Key] = stored
+ }
+ next := proto.CloneOf(plan.next)
+ next.Serial = f.state.Serial + 1
+ f.state = next
+}
+
+func loadDesired(t *testing.T, files map[string]string) *Desired {
+ t.Helper()
+ desired, err := Load(writeFiles(t, files), placeholderResolver())
+ require.NoError(t, err)
+ return desired
+}
+
+func planFor(t *testing.T, desired *Desired, reader Reader) *Plan {
+ t.Helper()
+ result, err := ComputePlan(context.Background(), desired, reader)
+ require.NoError(t, err)
+ return result
+}
+
+func changeFor(t *testing.T, plan *Plan, resource string) *apipb.ResourceChange {
+ t.Helper()
+ for _, change := range plan.Message.ResourceChanges {
+ if change.Resource == resource {
+ return change
+ }
+ }
+ require.Failf(t, "no change", "plan has no change for %s", resource)
+ return nil
+}
+
+func generalSetting(title string) *storepb.InstanceSetting {
+ return &storepb.InstanceSetting{Key: storepb.InstanceSettingKey_GENERAL, Value: &storepb.InstanceSetting_GeneralSetting{
+ GeneralSetting: &storepb.InstanceGeneralSetting{CustomProfile: &storepb.InstanceCustomProfile{Title: title}},
+ }}
+}
+
+func generalDocument(title string) string {
+ return `{"instanceSettings":[{"name":"instance/settings/GENERAL","generalSetting":{"customProfile":{"title":"` + title + `"}}}]}`
+}
+
+func TestPlanCreateAdoptNoOpAndDrift(t *testing.T) {
+ reader := newFakeReader()
+ reader.settings[storepb.InstanceSettingKey_GENERAL] = generalSetting("memos")
+ desired := loadDesired(t, map[string]string{"idp.json": `{"identityProviders":[` + validIDP + `]}`, "general.json": generalDocument("Company")})
+
+ first := planFor(t, desired, reader)
+ require.True(t, first.Valid())
+ require.True(t, first.HasChanges())
+ require.Equal(t, apipb.ResourceChange_CREATE, changeFor(t, first, "identity-providers/sso").Action)
+ general := changeFor(t, first, "instance/settings/GENERAL")
+ require.Equal(t, apipb.ResourceChange_ADOPT, general.Action)
+ require.Equal(t, "general.json", general.Source)
+ require.Equal(t, []*apipb.FieldChange{{Path: "generalSetting.customProfile.title", Before: `"memos"`, After: `"Company"`}}, general.FieldChanges)
+
+ reader.apply(t, desired, first)
+ second := planFor(t, desired, reader)
+ require.False(t, second.HasChanges(), "a second plan after apply is empty")
+ for _, change := range second.Message.ResourceChanges {
+ require.Equal(t, apipb.ResourceChange_NO_OP, change.Action, change.Resource)
+ }
+
+ // An edit outside the configuration is drift.
+ reader.settings[storepb.InstanceSettingKey_GENERAL] = generalSetting("Edited in the UI")
+ drifted := changeFor(t, planFor(t, desired, reader), "instance/settings/GENERAL")
+ require.Equal(t, apipb.ResourceChange_UPDATE, drifted.Action)
+ require.True(t, drifted.Drift)
+
+ // A changed file is an update, not drift.
+ changed := loadDesired(t, map[string]string{"idp.json": `{"identityProviders":[` + validIDP + `]}`, "general.json": generalDocument("Renamed")})
+ updated := changeFor(t, planFor(t, changed, reader), "instance/settings/GENERAL")
+ require.Equal(t, apipb.ResourceChange_UPDATE, updated.Action)
+ require.False(t, updated.Drift)
+
+ // A managed resource deleted outside the configuration is recreated, as drift.
+ reader.providers = nil
+ recreated := changeFor(t, planFor(t, desired, reader), "identity-providers/sso")
+ require.Equal(t, apipb.ResourceChange_CREATE, recreated.Action)
+ require.True(t, recreated.Drift)
+}
+
+func TestPlanComparesNormalizedValues(t *testing.T) {
+ reader := newFakeReader()
+ reader.settings[storepb.InstanceSettingKey_AI] = &storepb.InstanceSetting{Key: storepb.InstanceSettingKey_AI, Value: &storepb.InstanceSetting_AiSetting{
+ AiSetting: &storepb.InstanceAISetting{Providers: []*storepb.AIProviderConfig{
+ {Id: "openai", Title: "OpenAI", Type: storepb.AIProviderType_OPENAI, Endpoint: instancesetting.DefaultOpenAIEndpoint, ApiKey: "placeholder"},
+ }},
+ }}
+ storage := &storepb.InstanceStorageSetting{StorageType: storepb.InstanceStorageSetting_LOCAL}
+ store.NormalizeInstanceStorageSetting(storage)
+ reader.settings[storepb.InstanceSettingKey_STORAGE] = &storepb.InstanceSetting{Key: storepb.InstanceSettingKey_STORAGE, Value: &storepb.InstanceSetting_StorageSetting{StorageSetting: storage}}
+
+ desired := loadDesired(t, map[string]string{"settings.json": `{"instanceSettings":[
+ {"name":"instance/settings/AI","aiSetting":{"providers":[{"id":"openai","title":"OpenAI","type":"OPENAI","apiKey":"${env:KEY}"}]}},
+ {"name":"instance/settings/STORAGE","storageSetting":{"storageType":"LOCAL"}}
+ ]}`})
+ for _, change := range planFor(t, desired, reader).Message.ResourceChanges {
+ require.Equal(t, apipb.ResourceChange_ADOPT, change.Action, change.Resource)
+ require.Empty(t, change.FieldChanges, "a default endpoint and a normalized storage registry are not differences: %s", change.Resource)
+ }
+}
+
+func TestPlanNeverPrintsSecrets(t *testing.T) {
+ reader := newFakeReader()
+ stored := identityprovider.ToStore(loadDesired(t, map[string]string{"idp.json": `{"identityProviders":[` + validIDP + `]}`}).Configuration.IdentityProviders[0])
+ stored.Config.GetOauth2Config().ClientSecret = "old-client-secret"
+ reader.providers = []*storepb.IdentityProvider{stored}
+
+ withSecret := strings.Replace(validIDP, `"clientId":"memos",`, `"clientId":"memos","clientSecret":"new-client-secret",`, 1)
+ result := planFor(t, loadDesired(t, map[string]string{"idp.json": `{"identityProviders":[` + withSecret + `]}`}), reader)
+ change := changeFor(t, result, "identity-providers/sso")
+ require.Equal(t, []*apipb.FieldChange{{Path: "config.oauth2Config.clientSecret", Before: "(sensitive)", After: "(sensitive)"}}, change.FieldChanges)
+
+ var text bytes.Buffer
+ RenderPlan(&text, result.Message)
+ encoded, err := protojson.Marshal(result.Message)
+ require.NoError(t, err)
+ for _, output := range []string{text.String(), string(encoded), result.next.String()} {
+ require.NotContains(t, output, "old-client-secret")
+ require.NotContains(t, output, "new-client-secret")
+ }
+}
+
+func TestPlanIgnoreChanges(t *testing.T) {
+ reader := newFakeReader()
+ reader.settings[storepb.InstanceSettingKey_GENERAL] = generalSetting("Edited in the UI")
+ desired := loadDesired(t, map[string]string{"general.json": `{"instanceSettings":[{"name":"instance/settings/GENERAL","generalSetting":{"customProfile":{"title":"Company"}}}],
+ "lifecycle":[{"resource":"instance/settings/GENERAL","ignoreChanges":["generalSetting.customProfile"]}]}`})
+ result := planFor(t, desired, reader)
+ change := changeFor(t, result, "instance/settings/GENERAL")
+ require.Empty(t, change.FieldChanges)
+ require.Equal(t, []string{"generalSetting.customProfile"}, result.next.Resources[0].IgnoredFields)
+ require.Equal(t, []string{"*"}, result.next.Resources[0].ManagedFields)
+}
+
+func TestPlanUndeclaredManagedResources(t *testing.T) {
+ reader := newFakeReader()
+ managed := func(name, kind string) *storepb.InstanceConfigurationState_ManagedResource {
+ return &storepb.InstanceConfigurationState_ManagedResource{Name: name, Kind: kind, ManagedFields: []string{"*"}}
+ }
+ locked := managed("identity-providers/locked", "IdentityProvider")
+ locked.PreventDestroy = true
+ reader.state = &storepb.InstanceConfigurationState{Serial: 4, Resources: []*storepb.InstanceConfigurationState_ManagedResource{
+ managed("identity-providers/destroyed", "IdentityProvider"),
+ managed("identity-providers/vanished", "IdentityProvider"),
+ locked,
+ managed("identity-providers/forgotten", "IdentityProvider"),
+ managed("instance/settings/MEMO_RELATED", "InstanceSetting"),
+ managed("users/old", "User"),
+ managed("users/kept", "User"),
+ }}
+ reader.providers = []*storepb.IdentityProvider{{Id: 1, Uid: "destroyed"}, {Id: 2, Uid: "locked"}, {Id: 3, Uid: "forgotten"}}
+ reader.users = []*store.User{{ID: 1, Username: "old"}, {ID: 2, Username: "kept"}}
+
+ desired := loadDesired(t, map[string]string{"removed.json": `{"removed":[
+ {"resource":"identity-providers/destroyed","destroy":true},
+ {"resource":"identity-providers/vanished","destroy":true},
+ {"resource":"identity-providers/locked","destroy":true},
+ {"resource":"instance/settings/MEMO_RELATED","destroy":true},
+ {"resource":"users/old","destroy":true},
+ {"resource":"users/kept"},
+ {"resource":"users/never-managed","destroy":true}
+ ]}`})
+ result := planFor(t, desired, reader)
+ want := map[string]apipb.ResourceChange_Action{
+ "identity-providers/destroyed": apipb.ResourceChange_DESTROY,
+ "identity-providers/vanished": apipb.ResourceChange_RELEASE,
+ "identity-providers/locked": apipb.ResourceChange_ERROR,
+ "identity-providers/forgotten": apipb.ResourceChange_ERROR,
+ "instance/settings/MEMO_RELATED": apipb.ResourceChange_RESET,
+ "users/old": apipb.ResourceChange_ERROR,
+ "users/kept": apipb.ResourceChange_RELEASE,
+ }
+ require.Len(t, result.Message.ResourceChanges, len(want), "a removed entry for a resource never managed is a no-op")
+ for resource, action := range want {
+ require.Equal(t, action, changeFor(t, result, resource).Action, resource)
+ }
+ require.False(t, result.Valid())
+ require.Len(t, result.Message.Errors, 3)
+ require.Contains(t, strings.Join(result.Message.Errors, "\n"), "users/old: configuration cannot delete a user")
+ require.Contains(t, strings.Join(result.Message.Errors, "\n"), "identity-providers/forgotten: managed but no longer declared")
+ require.Contains(t, strings.Join(result.Message.Errors, "\n"), "identity-providers/locked: preventDestroy was set")
+ require.Equal(t, int64(4), result.Message.Serial)
+}
+
+func TestPlanOrdersActions(t *testing.T) {
+ reader := newFakeReader()
+ reader.state = &storepb.InstanceConfigurationState{Resources: []*storepb.InstanceConfigurationState_ManagedResource{
+ {Name: "identity-providers/old", Kind: "IdentityProvider"},
+ }}
+ reader.providers = []*storepb.IdentityProvider{{Id: 1, Uid: "old"}}
+ desired := loadDesired(t, map[string]string{"all.json": `{
+ "identityProviders":[` + validIDP + `],
+ "instanceSettings":[{"name":"instance/settings/ACCESS","accessSetting":{"accessMode":"INSTANCE_ACCESS_MODE_PRIVATE"}}],
+ "users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"secret"}],
+ "removed":[{"resource":"identity-providers/old","destroy":true}]
+ }`})
+ result := planFor(t, desired, reader)
+ require.True(t, result.Valid(), result.Message.Errors)
+ order := []string{}
+ for _, change := range result.Message.ResourceChanges {
+ order = append(order, change.Resource)
+ }
+ require.Equal(t, []string{"identity-providers/sso", "instance/settings/ACCESS", "users/admin", "identity-providers/old"}, order)
+}
+
+func TestPlanUsers(t *testing.T) {
+ reader := newFakeReader()
+ require.Contains(t, strings.Join(planFor(t, loadDesired(t, map[string]string{"u.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}]}`}), reader).Message.Errors, ""),
+ "password is required to create the user")
+
+ created := changeFor(t, planFor(t, loadDesired(t, map[string]string{"u.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"pw"}]}`}), reader), "users/admin")
+ require.Equal(t, apipb.ResourceChange_CREATE, created.Action)
+ require.Equal(t, []*apipb.FieldChange{
+ {Path: "username", After: `"admin"`},
+ {Path: "role", After: "ADMIN"},
+ {Path: "password", After: "(write-only, version 0)"},
+ }, created.FieldChanges, "an undeclared displayName or email is not managed")
+
+ reader.users = []*store.User{{ID: 1, Username: "admin", Role: store.RoleAdmin, Nickname: "Set by the user", Email: "[email protected]"}}
+ reader.state = &storepb.InstanceConfigurationState{Resources: []*storepb.InstanceConfigurationState_ManagedResource{
+ {Name: "users/admin", Kind: "User", ManagedFields: []string{"username", "role"}, WriteOnlyVersion: 1},
+ }}
+ user := func(extra, lifecycle string) *Desired {
+ return loadDesired(t, map[string]string{"u.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"pw"` + extra + `}]` + lifecycle + `}`})
+ }
+ untouched := planFor(t, user("", `,"lifecycle":[{"resource":"users/admin","writeOnlyVersion":1}]`), reader)
+ require.Equal(t, apipb.ResourceChange_NO_OP, changeFor(t, untouched, "users/admin").Action, "the profile and the password are left alone")
+
+ cleared := changeFor(t, planFor(t, user(`,"displayName":""`, `,"lifecycle":[{"resource":"users/admin","writeOnlyVersion":1}]`), reader), "users/admin")
+ require.Equal(t, []*apipb.FieldChange{{Path: "displayName", Before: `"Set by the user"`, After: `""`}}, cleared.FieldChanges,
+ "a declared empty displayName is managed")
+
+ bumped := planFor(t, user("", `,"lifecycle":[{"resource":"users/admin","writeOnlyVersion":2}]`), reader)
+ require.Equal(t, []*apipb.FieldChange{{Path: "password", Before: "(write-only)", After: "(write-only, version 2)"}}, changeFor(t, bumped, "users/admin").FieldChanges)
+ require.Equal(t, int32(2), bumped.next.Resources[0].WriteOnlyVersion)
+
+ noPassword := loadDesired(t, map[string]string{"u.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN"}],"lifecycle":[{"resource":"users/admin","writeOnlyVersion":2}]}`})
+ require.Contains(t, strings.Join(planFor(t, noPassword, reader).Message.Errors, ""), "no password is declared")
+}
+
+func TestPlanAuthenticationInvariant(t *testing.T) {
+ disallow := `{"instanceSettings":[{"name":"instance/settings/GENERAL","generalSetting":{"disallowPasswordAuth":true}}]}`
+ reader := newFakeReader()
+ require.Contains(t, strings.Join(planFor(t, loadDesired(t, map[string]string{"g.json": disallow}), reader).Message.Errors, ""), "no identity provider would remain")
+
+ require.True(t, planFor(t, loadDesired(t, map[string]string{"g.json": disallow, "idp.json": `{"identityProviders":[` + validIDP + `]}`}), reader).Valid(),
+ "a declared provider satisfies it")
+
+ reader.settings[storepb.InstanceSettingKey_GENERAL] = &storepb.InstanceSetting{Key: storepb.InstanceSettingKey_GENERAL, Value: &storepb.InstanceSetting_GeneralSetting{
+ GeneralSetting: &storepb.InstanceGeneralSetting{DisallowPasswordAuth: true},
+ }}
+ reader.providers = []*storepb.IdentityProvider{{Id: 1, Uid: "last"}}
+ reader.state = &storepb.InstanceConfigurationState{Resources: []*storepb.InstanceConfigurationState_ManagedResource{{Name: "identity-providers/last", Kind: "IdentityProvider"}}}
+ destroyLast := planFor(t, loadDesired(t, map[string]string{"r.json": `{"removed":[{"resource":"identity-providers/last","destroy":true}]}`}), reader)
+ require.Contains(t, strings.Join(destroyLast.Message.Errors, ""), "no identity provider would remain")
+
+ reader.providers = nil
+ reader.state = &storepb.InstanceConfigurationState{}
+ unrelated := planFor(t, loadDesired(t, map[string]string{"a.json": `{"instanceSettings":[{"name":"instance/settings/ACCESS","accessSetting":{"accessMode":"INSTANCE_ACCESS_MODE_PRIVATE"}}]}`}), reader)
+ require.True(t, unrelated.Valid(), "an unrelated plan does not fail on an existing condition")
+ require.Contains(t, strings.Join(unrelated.Message.Warnings, ""), "already has")
+}
+
+func TestPlanUsageLimitsResolveUsers(t *testing.T) {
+ reader := newFakeReader()
+ reader.users = []*store.User{{ID: 7, Username: "alice"}}
+ reader.settings[storepb.InstanceSettingKey_USAGE_LIMITS] = &storepb.InstanceSetting{Key: storepb.InstanceSettingKey_USAGE_LIMITS, Value: &storepb.InstanceSetting_UsageLimitsSetting{
+ UsageLimitsSetting: &storepb.InstanceUsageLimitsSetting{Limits: []*storepb.InstanceUsageLimitsSetting_UsageLimit{
+ {UserIds: []int32{7}, MemoCount: new(int64(10))},
+ {AllUsers: true},
+ }},
+ }}
+ limits := func(users string) *Desired {
+ return loadDesired(t, map[string]string{"l.json": `{"instanceSettings":[{"name":"instance/settings/USAGE_LIMITS","usageLimitsSetting":{"limits":[
+ {"users":[` + users + `],"memoCount":"10"},{"allUsers":true}]}}]}`})
+ }
+ change := changeFor(t, planFor(t, limits(`"users/alice"`), reader), "instance/settings/USAGE_LIMITS")
+ require.Empty(t, change.FieldChanges, "user names resolve to the stored IDs")
+
+ missing := planFor(t, limits(`"users/carol"`), reader)
+ require.Contains(t, strings.Join(missing.Message.Errors, ""), "names users/carol, which does not exist")
+}
+
+func TestPlanStateOnlyChange(t *testing.T) {
+ reader := newFakeReader()
+ reader.settings[storepb.InstanceSettingKey_GENERAL] = generalSetting("Company")
+ desired := loadDesired(t, map[string]string{"general.json": generalDocument("Company")})
+ reader.apply(t, desired, planFor(t, desired, reader))
+
+ locked := loadDesired(t, map[string]string{"general.json": `{"instanceSettings":[{"name":"instance/settings/GENERAL","generalSetting":{"customProfile":{"title":"Company"}}}],
+ "lifecycle":[{"resource":"instance/settings/GENERAL","preventDestroy":true}]}`})
+ result := planFor(t, locked, reader)
+ require.Equal(t, apipb.ResourceChange_NO_OP, changeFor(t, result, "instance/settings/GENERAL").Action)
+ require.True(t, result.HasChanges(), "the state record now records preventDestroy")
+
+ var text bytes.Buffer
+ RenderPlan(&text, result.Message)
+ require.Equal(t, "No resource changes. Apply would only update the state record.\n", text.String())
+}
+
+func TestRenderPlan(t *testing.T) {
+ var text bytes.Buffer
+ RenderPlan(&text, &apipb.Plan{ResourceChanges: []*apipb.ResourceChange{
+ {Resource: "identity-providers/company-sso", Source: "instance.json", Action: apipb.ResourceChange_CREATE},
+ {Resource: "instance/settings/GENERAL", Source: "instance.json", Action: apipb.ResourceChange_ADOPT, FieldChanges: []*apipb.FieldChange{
+ {Path: "generalSetting.disallowPasswordAuth", Before: "false", After: "true"},
+ {Path: "generalSetting.customProfile.title", Before: `"memos"`, After: `"Company Memos"`},
+ }},
+ {Resource: "instance/settings/ACCESS", Source: "instance.json", Action: apipb.ResourceChange_NO_OP},
+ {Resource: "users/admin", Source: "instance.json", Action: apipb.ResourceChange_UPDATE, Drift: true, FieldChanges: []*apipb.FieldChange{
+ {Path: "role", Before: "USER", After: "ADMIN"},
+ }},
+ }, StateRecordChanges: true})
+ require.Equal(t, `Plan: 1 to create, 1 to update, 0 to destroy; 1 to adopt.
+
+ + identity-providers/company-sso (instance.json)
+ ~ instance/settings/GENERAL (instance.json) adopt
+ generalSetting.disallowPasswordAuth: false -> true
+ generalSetting.customProfile.title: "memos" -> "Company Memos"
+ ~ users/admin (instance.json) drift
+ role: USER -> ADMIN
+`, text.String())
+
+ text.Reset()
+ RenderPlan(&text, &apipb.Plan{ResourceChanges: []*apipb.ResourceChange{{Resource: "instance/settings/ACCESS", Action: apipb.ResourceChange_NO_OP}}})
+ require.Equal(t, "No changes. The instance matches the configuration.\n", text.String())
+}
+
+func TestSensitiveFieldsExist(t *testing.T) {
+ for _, name := range sensitiveFields {
+ _, err := protoregistry.GlobalFiles.FindDescriptorByName(name)
+ require.NoError(t, err, "%s was renamed; update sensitiveFields", name)
+ }
+}
diff --git a/core/configuration/render.go b/core/configuration/render.go
new file mode 100644
index 000000000..c3ba21cd1
--- /dev/null
+++ b/core/configuration/render.go
@@ -0,0 +1,118 @@
+package configuration
+
+import (
+ "fmt"
+ "io"
+ "strings"
+
+ apipb "github.com/usememos/memos/proto/gen/api"
+)
+
+var actionSymbols = map[apipb.ResourceChange_Action]string{
+ apipb.ResourceChange_CREATE: "+",
+ apipb.ResourceChange_ADOPT: "~",
+ apipb.ResourceChange_UPDATE: "~",
+ apipb.ResourceChange_DESTROY: "-",
+ apipb.ResourceChange_RESET: "-/+",
+ apipb.ResourceChange_RELEASE: ".",
+ apipb.ResourceChange_ERROR: "!",
+}
+
+// RenderPlan writes a plan as text in the shape Terraform operators know: a
+// summary line, then one line per resource apply would act on, with the
+// fields it would write beneath updates and adoptions.
+func RenderPlan(w io.Writer, plan *apipb.Plan) {
+ counts := map[apipb.ResourceChange_Action]int{}
+ width, symbolWidth := 0, 0
+ for _, change := range plan.ResourceChanges {
+ counts[change.Action]++
+ if change.Action != apipb.ResourceChange_NO_OP {
+ width = max(width, len(change.Resource))
+ symbolWidth = max(symbolWidth, len(actionSymbols[change.Action]))
+ }
+ }
+
+ resourceWrites := len(plan.ResourceChanges) - counts[apipb.ResourceChange_NO_OP] - counts[apipb.ResourceChange_ERROR]
+ switch {
+ case len(plan.Errors) > 0:
+ fmt.Fprintln(w, "The plan cannot be applied.")
+ case resourceWrites == 0 && !plan.StateRecordChanges:
+ fmt.Fprintln(w, "No changes. The instance matches the configuration.")
+ case resourceWrites == 0:
+ fmt.Fprintln(w, "No resource changes. Apply would only update the state record.")
+ default:
+ summary := fmt.Sprintf("Plan: %d to create, %d to update, %d to destroy",
+ counts[apipb.ResourceChange_CREATE], counts[apipb.ResourceChange_UPDATE],
+ counts[apipb.ResourceChange_DESTROY]+counts[apipb.ResourceChange_RESET])
+ var extras []string
+ if n := counts[apipb.ResourceChange_ADOPT]; n > 0 {
+ extras = append(extras, fmt.Sprintf("%d to adopt", n))
+ }
+ if n := counts[apipb.ResourceChange_RELEASE]; n > 0 {
+ extras = append(extras, fmt.Sprintf("%d to release", n))
+ }
+ if len(extras) > 0 {
+ summary += "; " + strings.Join(extras, ", ")
+ }
+ fmt.Fprintln(w, summary+".")
+ }
+
+ if len(plan.ResourceChanges) > counts[apipb.ResourceChange_NO_OP] {
+ fmt.Fprintln(w)
+ }
+ for _, change := range plan.ResourceChanges {
+ if change.Action == apipb.ResourceChange_NO_OP {
+ continue
+ }
+ line := fmt.Sprintf(" %*s %-*s", symbolWidth, actionSymbols[change.Action], width, change.Resource)
+ if change.Source != "" {
+ line += " (" + change.Source + ")"
+ }
+ if label := actionLabel(change); label != "" {
+ line += " " + label
+ }
+ fmt.Fprintln(w, strings.TrimRight(line, " "))
+ if change.Message != "" {
+ fmt.Fprintln(w, " # "+change.Message)
+ }
+ if change.Action != apipb.ResourceChange_UPDATE && change.Action != apipb.ResourceChange_ADOPT {
+ continue
+ }
+ pathWidth := 0
+ for _, field := range change.FieldChanges {
+ pathWidth = max(pathWidth, len(field.Path)+1)
+ }
+ for _, field := range change.FieldChanges {
+ fmt.Fprintf(w, " %-*s %s -> %s\n", pathWidth, field.Path+":", orNone(field.Before), orNone(field.After))
+ }
+ }
+
+ for _, warning := range plan.Warnings {
+ fmt.Fprintln(w, "\nWarning: "+warning)
+ }
+ for _, problem := range plan.Errors {
+ fmt.Fprintln(w, "\nError: "+problem)
+ }
+}
+
+func actionLabel(change *apipb.ResourceChange) string {
+ switch {
+ case change.Drift:
+ return "drift"
+ case change.Action == apipb.ResourceChange_ADOPT:
+ return "adopt"
+ case change.Action == apipb.ResourceChange_RESET:
+ return "reset"
+ case change.Action == apipb.ResourceChange_RELEASE:
+ return "release"
+ default:
+ return ""
+ }
+}
+
+func orNone(value string) string {
+ if value == "" {
+ return "(none)"
+ }
+ return value
+}
diff --git a/core/configuration/resources.go b/core/configuration/resources.go
new file mode 100644
index 000000000..743050fc3
--- /dev/null
+++ b/core/configuration/resources.go
@@ -0,0 +1,78 @@
+package configuration
+
+import (
+ "fmt"
+
+ "github.com/pkg/errors"
+
+ "github.com/usememos/memos/core/identityprovider"
+ "github.com/usememos/memos/core/instancesetting"
+ apipb "github.com/usememos/memos/proto/gen/api"
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+)
+
+// checkResources runs the rules each resource must meet before it is stored,
+// the same rules the API applies, on every merged resource. A declared value
+// is the whole value, so nothing is exempt as unchanged.
+func checkResources(desired *Desired) []string {
+ var problems []string
+ report := func(name string, err error) {
+ problems = append(problems, fmt.Sprintf("%s: %s: %v", desired.Sources[name], name, err))
+ }
+ config := desired.Configuration
+ for _, provider := range config.IdentityProviders {
+ if err := identityprovider.Validate(identityprovider.ToStore(provider)); err != nil {
+ report(provider.GetName(), err)
+ }
+ }
+ for _, setting := range config.InstanceSettings {
+ stored, err := instanceSettingToStore(setting)
+ if err != nil {
+ report(setting.GetName(), err)
+ continue
+ }
+ if err := instancesetting.Validate(stored); err != nil {
+ report(setting.GetName(), err)
+ }
+ }
+ for _, user := range config.Users {
+ if user.GetEmail() != "" {
+ if _, err := store.NormalizeEmail(user.GetEmail()); err != nil {
+ report(user.GetName(), err)
+ }
+ }
+ }
+ return problems
+}
+
+// instanceSettingToStore converts a declared setting as apply will write it.
+// Usage limits name users, which only a database can resolve, so each named
+// user gets a stand-in ID here; the structural rules do not depend on which.
+// Whether the users exist is checked when the configuration is planned.
+func instanceSettingToStore(setting *apipb.InstanceSetting) (*storepb.InstanceSetting, error) {
+ stored := instancesetting.ToStore(setting)
+ switch stored.Key {
+ case storepb.InstanceSettingKey_AI:
+ instancesetting.NormalizeAISetting(stored.GetAiSetting())
+ case storepb.InstanceSettingKey_USAGE_LIMITS:
+ standInIDs := map[string]int32{}
+ for _, limit := range setting.GetUsageLimitsSetting().GetLimits() {
+ for _, name := range limit.GetUsers() {
+ if kind, _, err := ParseResourceName(name); err != nil || kind != KindUser {
+ return nil, errors.Errorf("usageLimitsSetting names %q, which is not a user name", name)
+ }
+ if _, ok := standInIDs[name]; !ok {
+ standInIDs[name] = int32(len(standInIDs) + 1)
+ }
+ }
+ }
+ usageLimits, err := instancesetting.UsageLimitsToStore(setting.GetUsageLimitsSetting(), standInIDs)
+ if err != nil {
+ return nil, err
+ }
+ stored.Value = &storepb.InstanceSetting_UsageLimitsSetting{UsageLimitsSetting: usageLimits}
+ default:
+ }
+ return stored, nil
+}
diff --git a/core/configuration/schema.go b/core/configuration/schema.go
new file mode 100644
index 000000000..b36897181
--- /dev/null
+++ b/core/configuration/schema.go
@@ -0,0 +1,270 @@
+package configuration
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/reflect/protoreflect"
+
+ "github.com/usememos/memos/core/identityprovider"
+ "github.com/usememos/memos/core/instancesetting"
+ coreuser "github.com/usememos/memos/core/user"
+ "github.com/usememos/memos/internal/identifier"
+ apipb "github.com/usememos/memos/proto/gen/api"
+)
+
+// Kind is the kind of a configurable resource.
+type Kind string
+
+// The configurable kinds.
+const (
+ KindIdentityProvider Kind = "IdentityProvider"
+ KindInstanceSetting Kind = "InstanceSetting"
+ KindUser Kind = "User"
+)
+
+// ConfigurableInstanceSettingKeys are the instance setting keys a file may declare.
+var ConfigurableInstanceSettingKeys = []string{"ACCESS", "GENERAL", "STORAGE", "MEMO_RELATED", "NOTIFICATION", "AI", "USAGE_LIMITS"}
+
+// userFields are the User fields a file may set. The rest of a profile belongs
+// to the user.
+var userFields = []protoreflect.Name{"name", "username", "display_name", "email", "password", "role"}
+
+// ParseResourceName returns the kind and identifier of a configurable resource name.
+func ParseResourceName(name string) (Kind, string, error) {
+ switch {
+ case strings.HasPrefix(name, identityprovider.NamePrefix):
+ uid := strings.TrimPrefix(name, identityprovider.NamePrefix)
+ if !identifier.UIDMatcher.MatchString(uid) {
+ return "", "", errors.Errorf("invalid identity provider name %q", name)
+ }
+ return KindIdentityProvider, uid, nil
+ case strings.HasPrefix(name, instancesetting.NamePrefix):
+ key := strings.TrimPrefix(name, instancesetting.NamePrefix)
+ switch {
+ case slices.Contains(ConfigurableInstanceSettingKeys, key):
+ return KindInstanceSetting, key, nil
+ case key == "BASIC":
+ return "", "", errors.New("instance/settings/BASIC holds the instance secret and schema version and cannot be configured")
+ case key == "TAGS":
+ return "", "", errors.New("instance/settings/TAGS is kept only for compatibility and cannot be configured")
+ case key == "CONFIGURATION_STATE":
+ return "", "", errors.New("instance/settings/CONFIGURATION_STATE is the configuration state record and cannot be configured")
+ default:
+ return "", "", errors.Errorf("unknown instance setting %q", name)
+ }
+ case strings.HasPrefix(name, coreuser.NamePrefix):
+ username := strings.TrimPrefix(name, coreuser.NamePrefix)
+ if err := coreuser.ValidateUsername(username); err != nil {
+ return "", "", errors.Errorf("invalid user name %q", name)
+ }
+ return KindUser, username, nil
+ default:
+ return "", "", errors.Errorf("%q is not an identity provider, instance setting, or user name", name)
+ }
+}
+
+// checkDocument checks the rules one file must meet on its own.
+func checkDocument(document *apipb.Configuration) []string {
+ var problems []string
+ report := func(format string, args ...any) {
+ problems = append(problems, fmt.Sprintf(format, args...))
+ }
+ checkName := func(path, name string, want Kind) (string, bool) {
+ if name == "" {
+ report("%s.name is required", path)
+ return "", false
+ }
+ kind, id, err := ParseResourceName(name)
+ if err != nil {
+ report("%s.name: %v", path, err)
+ return "", false
+ }
+ if kind != want {
+ report("%s.name: %s is not a %s name", path, name, want)
+ return "", false
+ }
+ return id, true
+ }
+
+ for i, provider := range document.IdentityProviders {
+ checkName(fmt.Sprintf("identityProviders[%d]", i), provider.GetName(), KindIdentityProvider)
+ }
+
+ for i, setting := range document.InstanceSettings {
+ path := fmt.Sprintf("instanceSettings[%d]", i)
+ key, ok := checkName(path, setting.GetName(), KindInstanceSetting)
+ if !ok {
+ continue
+ }
+ message := setting.ProtoReflect()
+ expected := message.Descriptor().Fields().ByName(protoreflect.Name(strings.ToLower(key) + "_setting"))
+ populated := message.WhichOneof(message.Descriptor().Oneofs().ByName("value"))
+ switch {
+ case populated == nil:
+ report("%s.%s is required for %s", path, expected.JSONName(), key)
+ case populated.Name() != expected.Name():
+ report("%s.%s does not match %s; use %s", path, populated.JSONName(), key, expected.JSONName())
+ default:
+ }
+ }
+
+ for i, user := range document.Users {
+ path := fmt.Sprintf("users[%d]", i)
+ username, ok := checkName(path, user.GetName(), KindUser)
+ if ok && user.GetUsername() != username {
+ report("%s.username must equal %q, the username in name", path, username)
+ }
+ if user.GetRole() == apipb.User_ROLE_UNSPECIFIED {
+ report("%s.role is required", path)
+ }
+ user.ProtoReflect().Range(func(field protoreflect.FieldDescriptor, _ protoreflect.Value) bool {
+ if !slices.Contains(userFields, field.Name()) {
+ report("%s.%s cannot be configured; it belongs to the user", path, field.JSONName())
+ }
+ return true
+ })
+ }
+
+ for i, lifecycle := range document.Lifecycle {
+ path := fmt.Sprintf("lifecycle[%d]", i)
+ if lifecycle.GetResource() == "" {
+ report("%s.resource is required", path)
+ continue
+ }
+ kind, _, err := ParseResourceName(lifecycle.GetResource())
+ if err != nil {
+ report("%s.resource: %v", path, err)
+ continue
+ }
+ if lifecycle.GetWriteOnlyVersion() < 0 {
+ report("%s.writeOnlyVersion must not be negative", path)
+ }
+ if lifecycle.GetWriteOnlyVersion() != 0 && kind != KindUser {
+ report("%s.writeOnlyVersion applies only to users", path)
+ }
+ for j, fieldPath := range lifecycle.GetIgnoreChanges() {
+ if err := checkFieldPath(kindDescriptor(kind), fieldPath); err != nil {
+ report("%s.ignoreChanges[%d]: %v", path, j, err)
+ }
+ }
+ }
+
+ for i, removed := range document.Removed {
+ path := fmt.Sprintf("removed[%d]", i)
+ if removed.GetResource() == "" {
+ report("%s.resource is required", path)
+ continue
+ }
+ if _, _, err := ParseResourceName(removed.GetResource()); err != nil {
+ report("%s.resource: %v", path, err)
+ }
+ }
+ return problems
+}
+
+func kindDescriptor(kind Kind) protoreflect.MessageDescriptor {
+ switch kind {
+ case KindIdentityProvider:
+ return (&apipb.IdentityProvider{}).ProtoReflect().Descriptor()
+ case KindInstanceSetting:
+ return (&apipb.InstanceSetting{}).ProtoReflect().Descriptor()
+ default:
+ return (&apipb.User{}).ProtoReflect().Descriptor()
+ }
+}
+
+// checkFieldPath reports whether path names a field of descriptor by JSON
+// names, descending through singular message fields.
+func checkFieldPath(descriptor protoreflect.MessageDescriptor, path string) error {
+ if path == "" {
+ return errors.New("field path must not be empty")
+ }
+ segments := strings.Split(path, ".")
+ for i, segment := range segments {
+ field := descriptor.Fields().ByJSONName(segment)
+ if field == nil {
+ return errors.Errorf("%q has no field %q", descriptor.Name(), segment)
+ }
+ if i == 0 && field.Name() == "name" {
+ return errors.New("name is the resource identity and cannot be ignored")
+ }
+ if i == len(segments)-1 {
+ return nil
+ }
+ if field.Kind() != protoreflect.MessageKind || field.IsList() || field.IsMap() {
+ return errors.Errorf("%q is not a message field", strings.Join(segments[:i+1], "."))
+ }
+ descriptor = field.Message()
+ }
+ return nil
+}
+
+// merger combines files into one desired state and checks the rules that span
+// files: one declaration per resource, lifecycle rules for declared resources,
+// and removals of resources no file still declares.
+type merger struct {
+ desired *Desired
+ problems []string
+ lifecycleSources map[string]string
+ removedSources map[string]string
+}
+
+func newMerger(desired *Desired) *merger {
+ return &merger{desired: desired, lifecycleSources: map[string]string{}, removedSources: map[string]string{}}
+}
+
+func (m *merger) add(file string, document *apipb.Configuration, userFields map[int][]string) {
+ claim := func(sources map[string]string, name, what string) bool {
+ if previous, ok := sources[name]; ok {
+ m.problems = append(m.problems, fmt.Sprintf("%s: %s for %s is also declared in %s", file, what, name, previous))
+ return false
+ }
+ sources[name] = file
+ return true
+ }
+ config := m.desired.Configuration
+ for _, provider := range document.IdentityProviders {
+ if claim(m.desired.Sources, provider.GetName(), "resource") {
+ config.IdentityProviders = append(config.IdentityProviders, provider)
+ }
+ }
+ for _, setting := range document.InstanceSettings {
+ if claim(m.desired.Sources, setting.GetName(), "resource") {
+ config.InstanceSettings = append(config.InstanceSettings, setting)
+ }
+ }
+ for i, user := range document.Users {
+ if claim(m.desired.Sources, user.GetName(), "resource") {
+ config.Users = append(config.Users, user)
+ m.desired.UserFields[user.GetName()] = userFields[i]
+ }
+ }
+ for _, lifecycle := range document.Lifecycle {
+ if claim(m.lifecycleSources, lifecycle.GetResource(), "a lifecycle rule") {
+ config.Lifecycle = append(config.Lifecycle, lifecycle)
+ }
+ }
+ for _, removed := range document.Removed {
+ if claim(m.removedSources, removed.GetResource(), "a removed entry") {
+ config.Removed = append(config.Removed, removed)
+ }
+ }
+}
+
+func (m *merger) checkReferences() {
+ for _, lifecycle := range m.desired.Configuration.Lifecycle {
+ if _, ok := m.desired.Sources[lifecycle.GetResource()]; !ok {
+ m.problems = append(m.problems, fmt.Sprintf("%s: the lifecycle rule names %s, which no file declares",
+ m.lifecycleSources[lifecycle.GetResource()], lifecycle.GetResource()))
+ }
+ }
+ for _, removed := range m.desired.Configuration.Removed {
+ if declaredIn, ok := m.desired.Sources[removed.GetResource()]; ok {
+ m.problems = append(m.problems, fmt.Sprintf("%s: %s is removed but still declared in %s",
+ m.removedSources[removed.GetResource()], removed.GetResource(), declaredIn))
+ }
+ }
+}
diff --git a/core/configuration/testdata/compat/unreleased/instance.json b/core/configuration/testdata/compat/unreleased/instance.json
new file mode 100644
index 000000000..8b236bf83
--- /dev/null
+++ b/core/configuration/testdata/compat/unreleased/instance.json
@@ -0,0 +1,37 @@
+{
+ "identityProviders": [
+ {
+ "name": "identity-providers/company-sso",
+ "type": "OAUTH2",
+ "title": "Company SSO",
+ "config": {
+ "oauth2Config": {
+ "clientId": "memos",
+ "clientSecret": "${env:OIDC_CLIENT_SECRET}",
+ "authUrl": "https://idp.example.com/oauth/authorize",
+ "tokenUrl": "https://idp.example.com/oauth/token",
+ "userInfoUrl": "https://idp.example.com/oauth/userinfo",
+ "scopes": ["openid", "profile", "email"],
+ "fieldMapping": { "identifier": "sub", "displayName": "name", "email": "email" }
+ }
+ }
+ }
+ ],
+ "instanceSettings": [
+ { "name": "instance/settings/ACCESS", "accessSetting": { "accessMode": "INSTANCE_ACCESS_MODE_PRIVATE" } },
+ {
+ "name": "instance/settings/GENERAL",
+ "generalSetting": {
+ "disallowPasswordAuth": true,
+ "disallowUserRegistration": false,
+ "customProfile": { "title": "Company Memos" }
+ }
+ }
+ ],
+ "users": [
+ { "name": "users/admin", "username": "admin", "role": "ADMIN", "password": "${file:/run/secrets/memos-admin-password}" }
+ ],
+ "lifecycle": [
+ { "resource": "users/admin", "preventDestroy": true, "writeOnlyVersion": 1 }
+ ]
+}
diff --git a/core/identityprovider/convert.go b/core/identityprovider/convert.go
new file mode 100644
index 000000000..89036ff88
--- /dev/null
+++ b/core/identityprovider/convert.go
@@ -0,0 +1,94 @@
+package identityprovider
+
+import (
+ "strings"
+
+ apipb "github.com/usememos/memos/proto/gen/api"
+ storepb "github.com/usememos/memos/proto/gen/store"
+)
+
+// NamePrefix starts every identity provider resource name.
+const NamePrefix = "identity-providers/"
+
+// ToStore converts an API identity provider for the store. The UID comes from
+// the resource name when it has one.
+func ToStore(provider *apipb.IdentityProvider) *storepb.IdentityProvider {
+ if provider == nil {
+ return nil
+ }
+ return &storepb.IdentityProvider{
+ Uid: strings.TrimPrefix(provider.Name, NamePrefix),
+ Name: provider.Title,
+ IdentifierFilter: provider.IdentifierFilter,
+ Type: storepb.IdentityProvider_Type(storepb.IdentityProvider_Type_value[provider.Type.String()]),
+ Config: ConfigToStore(provider.Type, provider.Config),
+ }
+}
+
+// ConfigToStore converts the type-specific configuration for the store. It
+// returns nil for a type without a configuration.
+func ConfigToStore(providerType apipb.IdentityProvider_Type, config *apipb.IdentityProviderConfig) *storepb.IdentityProviderConfig {
+ if providerType != apipb.IdentityProvider_OAUTH2 {
+ return nil
+ }
+ oauth2Config := config.GetOauth2Config()
+ if oauth2Config == nil {
+ return &storepb.IdentityProviderConfig{}
+ }
+ fieldMapping := oauth2Config.GetFieldMapping()
+ return &storepb.IdentityProviderConfig{
+ Config: &storepb.IdentityProviderConfig_Oauth2Config{
+ Oauth2Config: &storepb.OAuth2Config{
+ ClientId: oauth2Config.ClientId,
+ ClientSecret: oauth2Config.ClientSecret,
+ AuthUrl: oauth2Config.AuthUrl,
+ TokenUrl: oauth2Config.TokenUrl,
+ UserInfoUrl: oauth2Config.UserInfoUrl,
+ Scopes: oauth2Config.Scopes,
+ FieldMapping: &storepb.FieldMapping{
+ Identifier: fieldMapping.GetIdentifier(),
+ DisplayName: fieldMapping.GetDisplayName(),
+ Email: fieldMapping.GetEmail(),
+ AvatarUrl: fieldMapping.GetAvatarUrl(),
+ },
+ },
+ },
+ }
+}
+
+// FromStore converts a stored identity provider for the API. It keeps the
+// client secret; a response must clear it.
+func FromStore(provider *storepb.IdentityProvider) *apipb.IdentityProvider {
+ if provider == nil {
+ return nil
+ }
+ result := &apipb.IdentityProvider{
+ Name: NamePrefix + provider.Uid,
+ Title: provider.Name,
+ IdentifierFilter: provider.IdentifierFilter,
+ Type: apipb.IdentityProvider_Type(apipb.IdentityProvider_Type_value[provider.Type.String()]),
+ }
+ if provider.Type == storepb.IdentityProvider_OAUTH2 {
+ oauth2Config := provider.GetConfig().GetOauth2Config()
+ fieldMapping := oauth2Config.GetFieldMapping()
+ result.Config = &apipb.IdentityProviderConfig{
+ Config: &apipb.IdentityProviderConfig_Oauth2Config{
+ Oauth2Config: &apipb.OAuth2Config{
+ ClientId: oauth2Config.GetClientId(),
+ ClientSecret: oauth2Config.GetClientSecret(),
+ AuthUrl: oauth2Config.GetAuthUrl(),
+ TokenUrl: oauth2Config.GetTokenUrl(),
+ UserInfoUrl: oauth2Config.GetUserInfoUrl(),
+ Scopes: oauth2Config.GetScopes(),
+ FieldMapping: &apipb.FieldMapping{
+ Identifier: fieldMapping.GetIdentifier(),
+ DisplayName: fieldMapping.GetDisplayName(),
+ Email: fieldMapping.GetEmail(),
+ AvatarUrl: fieldMapping.GetAvatarUrl(),
+ },
+ },
+ },
+ }
+ }
+ return result
+}
diff --git a/core/identityprovider/identityprovider.go b/core/identityprovider/identityprovider.go
new file mode 100644
index 000000000..667202256
--- /dev/null
+++ b/core/identityprovider/identityprovider.go
@@ -0,0 +1,78 @@
+// Package identityprovider holds the rules an identity provider must meet
+// before it is stored, whichever path writes it.
+package identityprovider
+
+import (
+ "net/url"
+ "regexp"
+ "strings"
+
+ "github.com/pkg/errors"
+
+ "github.com/usememos/memos/internal/identifier"
+ storepb "github.com/usememos/memos/proto/gen/store"
+)
+
+// Validate reports the first rule the provider breaks, or nil. It checks the
+// complete provider as it would be stored, so an update is validated after it
+// is merged with the stored provider.
+func Validate(provider *storepb.IdentityProvider) error {
+ if provider == nil {
+ return errors.New("identity provider is required")
+ }
+ if !identifier.UIDMatcher.MatchString(provider.Uid) {
+ return errors.New("uid must be 1-36 characters, contain only letters, digits, or hyphens, and start and end with a letter or digit")
+ }
+ if strings.TrimSpace(provider.Name) == "" {
+ return errors.New("title is required")
+ }
+ if provider.IdentifierFilter != "" {
+ if _, err := regexp.Compile(provider.IdentifierFilter); err != nil {
+ return errors.Wrap(err, "identifier_filter must be a valid regular expression")
+ }
+ }
+ switch provider.Type {
+ case storepb.IdentityProvider_OAUTH2:
+ return validateOAuth2Config(provider.GetConfig().GetOauth2Config())
+ default:
+ return errors.New("type must be OAUTH2")
+ }
+}
+
+func validateOAuth2Config(config *storepb.OAuth2Config) error {
+ if config == nil {
+ return errors.New("config.oauth2_config is required")
+ }
+ if strings.TrimSpace(config.ClientId) == "" {
+ return errors.New("config.oauth2_config.client_id is required")
+ }
+ for _, field := range []struct {
+ name string
+ value string
+ }{
+ {name: "auth_url", value: config.AuthUrl},
+ {name: "token_url", value: config.TokenUrl},
+ {name: "user_info_url", value: config.UserInfoUrl},
+ } {
+ if !isAbsoluteHTTPURL(field.value) {
+ return errors.Errorf("config.oauth2_config.%s must be an absolute HTTP(S) URL", field.name)
+ }
+ }
+ for i, scope := range config.Scopes {
+ if strings.TrimSpace(scope) == "" {
+ return errors.Errorf("config.oauth2_config.scopes[%d] must not be empty", i)
+ }
+ }
+ if strings.TrimSpace(config.GetFieldMapping().GetIdentifier()) == "" {
+ return errors.New("config.oauth2_config.field_mapping.identifier is required")
+ }
+ return nil
+}
+
+func isAbsoluteHTTPURL(value string) bool {
+ parsed, err := url.ParseRequestURI(value)
+ if err != nil {
+ return false
+ }
+ return (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != ""
+}
diff --git a/core/identityprovider/identityprovider_test.go b/core/identityprovider/identityprovider_test.go
new file mode 100644
index 000000000..71c21f50c
--- /dev/null
+++ b/core/identityprovider/identityprovider_test.go
@@ -0,0 +1,83 @@
+package identityprovider
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
+
+ storepb "github.com/usememos/memos/proto/gen/store"
+)
+
+func validProvider() *storepb.IdentityProvider {
+ return &storepb.IdentityProvider{
+ Uid: "company-sso",
+ Name: "Company SSO",
+ Type: storepb.IdentityProvider_OAUTH2,
+ Config: &storepb.IdentityProviderConfig{
+ Config: &storepb.IdentityProviderConfig_Oauth2Config{
+ Oauth2Config: &storepb.OAuth2Config{
+ ClientId: "memos",
+ ClientSecret: "secret",
+ AuthUrl: "https://idp.example.com/authorize",
+ TokenUrl: "https://idp.example.com/token",
+ UserInfoUrl: "http://idp.internal/userinfo",
+ Scopes: []string{"openid"},
+ FieldMapping: &storepb.FieldMapping{Identifier: "sub"},
+ },
+ },
+ },
+ }
+}
+
+func TestValidate(t *testing.T) {
+ require.NoError(t, Validate(validProvider()))
+
+ public := validProvider()
+ public.Config.GetOauth2Config().ClientSecret = ""
+ public.Config.GetOauth2Config().Scopes = nil
+ require.NoError(t, Validate(public), "a public client without a secret or scopes is allowed")
+
+ tests := map[string]struct {
+ mutate func(*storepb.IdentityProvider)
+ want string
+ }{
+ "invalid uid": {func(p *storepb.IdentityProvider) { p.Uid = "-sso" }, "uid must be"},
+ "blank title": {func(p *storepb.IdentityProvider) { p.Name = " " }, "title is required"},
+ "unspecified type": {func(p *storepb.IdentityProvider) { p.Type = storepb.IdentityProvider_TYPE_UNSPECIFIED }, "type must be OAUTH2"},
+ "invalid filter": {func(p *storepb.IdentityProvider) { p.IdentifierFilter = "(" }, "identifier_filter"},
+ "missing config": {func(p *storepb.IdentityProvider) { p.Config = nil }, "config.oauth2_config is required"},
+ "missing client id": {func(p *storepb.IdentityProvider) { p.Config.GetOauth2Config().ClientId = "" }, "client_id is required"},
+ "relative auth url": {func(p *storepb.IdentityProvider) { p.Config.GetOauth2Config().AuthUrl = "/authorize" }, "auth_url must be"},
+ "non-http token url": {func(p *storepb.IdentityProvider) { p.Config.GetOauth2Config().TokenUrl = "ftp://idp/token" }, "token_url must be"},
+ "empty scope": {func(p *storepb.IdentityProvider) { p.Config.GetOauth2Config().Scopes = []string{"openid", " "} }, "scopes[1]"},
+ "missing mapping": {func(p *storepb.IdentityProvider) { p.Config.GetOauth2Config().FieldMapping = nil }, "field_mapping.identifier"},
+ "missing identifier": {func(p *storepb.IdentityProvider) { p.Config.GetOauth2Config().FieldMapping.Identifier = "" }, "field_mapping.identifier"},
+ }
+ for name, test := range tests {
+ t.Run(name, func(t *testing.T) {
+ provider := proto.CloneOf(validProvider())
+ test.mutate(provider)
+ err := Validate(provider)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), test.want)
+ })
+ }
+
+ require.Error(t, Validate(nil))
+}
+
+func TestConversionRoundTrips(t *testing.T) {
+ stored := validProvider()
+ stored.IdentifierFilter = "^.+@example\\.com$"
+ stored.Config.GetOauth2Config().FieldMapping = &storepb.FieldMapping{Identifier: "sub", DisplayName: "name", Email: "email", AvatarUrl: "picture"}
+
+ api := FromStore(stored)
+ require.Equal(t, NamePrefix+"company-sso", api.GetName())
+ require.Equal(t, "secret", api.GetConfig().GetOauth2Config().GetClientSecret(), "FromStore keeps the secret; responses clear it")
+ require.True(t, proto.Equal(stored, ToStore(api)))
+
+ // A missing config or field mapping converts without panicking and then fails validation.
+ api.Config = nil
+ require.Error(t, Validate(ToStore(api)))
+}
diff --git a/core/instancesetting/convert.go b/core/instancesetting/convert.go
new file mode 100644
index 000000000..abe099029
--- /dev/null
+++ b/core/instancesetting/convert.go
@@ -0,0 +1,482 @@
+package instancesetting
+
+import (
+ "strings"
+
+ "github.com/pkg/errors"
+
+ apipb "github.com/usememos/memos/proto/gen/api"
+ storepb "github.com/usememos/memos/proto/gen/store"
+)
+
+// NamePrefix starts every instance setting resource name.
+const NamePrefix = "instance/settings/"
+
+// ToStore converts an API instance setting for the store. The key comes from
+// the resource name; an unknown name gives an unspecified key and no value,
+// which Validate rejects. USAGE_LIMITS names users, so its value is converted
+// by UsageLimitsToStore once the names are resolved.
+func ToStore(setting *apipb.InstanceSetting) *storepb.InstanceSetting {
+ if setting == nil {
+ return nil
+ }
+ result := &storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey(storepb.InstanceSettingKey_value[strings.TrimPrefix(setting.Name, NamePrefix)]),
+ }
+ if !strings.HasPrefix(setting.Name, NamePrefix) {
+ result.Key = storepb.InstanceSettingKey_INSTANCE_SETTING_KEY_UNSPECIFIED
+ }
+ switch result.Key {
+ case storepb.InstanceSettingKey_GENERAL:
+ if value := setting.GetGeneralSetting(); value != nil {
+ result.Value = &storepb.InstanceSetting_GeneralSetting{GeneralSetting: generalSettingToStore(value)}
+ }
+ case storepb.InstanceSettingKey_STORAGE:
+ if value := setting.GetStorageSetting(); value != nil {
+ result.Value = &storepb.InstanceSetting_StorageSetting{StorageSetting: storageSettingToStore(value)}
+ }
+ case storepb.InstanceSettingKey_MEMO_RELATED:
+ if value := setting.GetMemoRelatedSetting(); value != nil {
+ result.Value = &storepb.InstanceSetting_MemoRelatedSetting{MemoRelatedSetting: memoRelatedSettingToStore(value)}
+ }
+ case storepb.InstanceSettingKey_TAGS:
+ if value := setting.GetTagsSetting(); value != nil {
+ result.Value = &storepb.InstanceSetting_TagsSetting{TagsSetting: tagsSettingToStore(value)}
+ }
+ case storepb.InstanceSettingKey_NOTIFICATION:
+ if value := setting.GetNotificationSetting(); value != nil {
+ result.Value = &storepb.InstanceSetting_NotificationSetting{NotificationSetting: NotificationSettingToStore(value)}
+ }
+ case storepb.InstanceSettingKey_AI:
+ if value := setting.GetAiSetting(); value != nil {
+ result.Value = &storepb.InstanceSetting_AiSetting{AiSetting: aiSettingToStore(value)}
+ }
+ case storepb.InstanceSettingKey_ACCESS:
+ if value := setting.GetAccessSetting(); value != nil {
+ result.Value = &storepb.InstanceSetting_AccessSetting{AccessSetting: accessSettingToStore(value)}
+ }
+ default:
+ // BASIC has no API value, and USAGE_LIMITS is converted by UsageLimitsToStore.
+ }
+ return result
+}
+
+// FromStore converts a stored instance setting for the API. It keeps every
+// secret; a response must redact them. USAGE_LIMITS is left without a value,
+// since naming its users needs the store; see UsageLimitsFromStore.
+func FromStore(setting *storepb.InstanceSetting) *apipb.InstanceSetting {
+ if setting == nil {
+ return nil
+ }
+ result := &apipb.InstanceSetting{Name: NamePrefix + setting.Key.String()}
+ switch setting.Value.(type) {
+ case *storepb.InstanceSetting_GeneralSetting:
+ result.Value = &apipb.InstanceSetting_GeneralSetting_{GeneralSetting: generalSettingFromStore(setting.GetGeneralSetting())}
+ case *storepb.InstanceSetting_StorageSetting:
+ result.Value = &apipb.InstanceSetting_StorageSetting_{StorageSetting: storageSettingFromStore(setting.GetStorageSetting())}
+ case *storepb.InstanceSetting_MemoRelatedSetting:
+ result.Value = &apipb.InstanceSetting_MemoRelatedSetting_{MemoRelatedSetting: memoRelatedSettingFromStore(setting.GetMemoRelatedSetting())}
+ case *storepb.InstanceSetting_TagsSetting:
+ result.Value = &apipb.InstanceSetting_TagsSetting_{TagsSetting: tagsSettingFromStore(setting.GetTagsSetting())}
+ case *storepb.InstanceSetting_NotificationSetting:
+ result.Value = &apipb.InstanceSetting_NotificationSetting_{NotificationSetting: notificationSettingFromStore(setting.GetNotificationSetting())}
+ case *storepb.InstanceSetting_AiSetting:
+ result.Value = &apipb.InstanceSetting_AiSetting{AiSetting: aiSettingFromStore(setting.GetAiSetting())}
+ case *storepb.InstanceSetting_AccessSetting:
+ result.Value = &apipb.InstanceSetting_AccessSetting_{AccessSetting: accessSettingFromStore(setting.GetAccessSetting())}
+ default:
+ // Leave Value unset for BASIC and USAGE_LIMITS.
+ }
+ return result
+}
+
+// UsageLimitsToStore converts API usage limits for the store. userIDs maps
+// each user resource name the limits use to its user ID.
+func UsageLimitsToStore(setting *apipb.InstanceSetting_UsageLimitsSetting, userIDs map[string]int32) (*storepb.InstanceUsageLimitsSetting, error) {
+ if setting == nil {
+ return nil, errors.New("usage limits setting is required")
+ }
+ result := &storepb.InstanceUsageLimitsSetting{}
+ for _, limit := range setting.GetLimits() {
+ entry := &storepb.InstanceUsageLimitsSetting_UsageLimit{
+ AllUsers: limit.GetAllUsers(),
+ MemoCount: limit.MemoCount,
+ MemoContentBytes: limit.MemoContentBytes,
+ StorageBytes: limit.StorageBytes,
+ UploadBytes: limit.UploadBytes,
+ }
+ for _, name := range limit.GetUsers() {
+ userID, ok := userIDs[name]
+ if !ok {
+ return nil, errors.Errorf("user %q not found", name)
+ }
+ entry.UserIds = append(entry.UserIds, userID)
+ }
+ result.Limits = append(result.Limits, entry)
+ }
+ return result, nil
+}
+
+// UsageLimitsFromStore converts stored usage limits for the API. userNames
+// maps user IDs to user resource names; an ID without a name, a user that no
+// longer exists, is left out because it never matches anyone.
+func UsageLimitsFromStore(setting *storepb.InstanceUsageLimitsSetting, userNames map[int32]string) *apipb.InstanceSetting_UsageLimitsSetting {
+ result := &apipb.InstanceSetting_UsageLimitsSetting{}
+ for _, limit := range setting.GetLimits() {
+ entry := &apipb.InstanceSetting_UsageLimitsSetting_UsageLimit{
+ AllUsers: limit.GetAllUsers(),
+ MemoCount: limit.MemoCount,
+ MemoContentBytes: limit.MemoContentBytes,
+ StorageBytes: limit.StorageBytes,
+ UploadBytes: limit.UploadBytes,
+ }
+ for _, userID := range limit.GetUserIds() {
+ if name, ok := userNames[userID]; ok {
+ entry.Users = append(entry.Users, name)
+ }
+ }
+ result.Limits = append(result.Limits, entry)
+ }
+ return result
+}
+
+func accessSettingFromStore(setting *storepb.InstanceAccessSetting) *apipb.InstanceSetting_AccessSetting {
+ if setting == nil {
+ return nil
+ }
+ return &apipb.InstanceSetting_AccessSetting{
+ AccessMode: AccessModeFromStore(setting.AccessMode),
+ }
+}
+
+func accessSettingToStore(setting *apipb.InstanceSetting_AccessSetting) *storepb.InstanceAccessSetting {
+ if setting == nil {
+ return nil
+ }
+ return &storepb.InstanceAccessSetting{
+ AccessMode: storepb.InstanceAccessMode(setting.AccessMode),
+ }
+}
+
+// AccessModeFromStore converts a stored access mode for the API.
+func AccessModeFromStore(mode storepb.InstanceAccessMode) apipb.InstanceAccessMode {
+ return apipb.InstanceAccessMode(mode)
+}
+
+func generalSettingFromStore(setting *storepb.InstanceGeneralSetting) *apipb.InstanceSetting_GeneralSetting {
+ if setting == nil {
+ return nil
+ }
+
+ generalSetting := &apipb.InstanceSetting_GeneralSetting{
+ DisallowUserRegistration: setting.DisallowUserRegistration,
+ DisallowPasswordAuth: setting.DisallowPasswordAuth,
+ AdditionalScript: setting.AdditionalScript,
+ AdditionalStyle: setting.AdditionalStyle,
+ WeekStartDayOffset: setting.WeekStartDayOffset,
+ DisallowChangeUsername: setting.DisallowChangeUsername,
+ DisallowChangeNickname: setting.DisallowChangeNickname,
+ }
+ if setting.CustomProfile != nil {
+ generalSetting.CustomProfile = &apipb.InstanceSetting_GeneralSetting_CustomProfile{
+ Title: setting.CustomProfile.Title,
+ Description: setting.CustomProfile.Description,
+ LogoUrl: setting.CustomProfile.LogoUrl,
+ }
+ }
+ return generalSetting
+}
+
+func generalSettingToStore(setting *apipb.InstanceSetting_GeneralSetting) *storepb.InstanceGeneralSetting {
+ if setting == nil {
+ return nil
+ }
+ generalSetting := &storepb.InstanceGeneralSetting{
+ DisallowUserRegistration: setting.DisallowUserRegistration,
+ DisallowPasswordAuth: setting.DisallowPasswordAuth,
+ AdditionalScript: setting.AdditionalScript,
+ AdditionalStyle: setting.AdditionalStyle,
+ WeekStartDayOffset: setting.WeekStartDayOffset,
+ DisallowChangeUsername: setting.DisallowChangeUsername,
+ DisallowChangeNickname: setting.DisallowChangeNickname,
+ }
+ if setting.CustomProfile != nil {
+ generalSetting.CustomProfile = &storepb.InstanceCustomProfile{
+ Title: setting.CustomProfile.Title,
+ Description: setting.CustomProfile.Description,
+ LogoUrl: setting.CustomProfile.LogoUrl,
+ }
+ }
+ return generalSetting
+}
+
+func storageSettingFromStore(settingpb *storepb.InstanceStorageSetting) *apipb.InstanceSetting_StorageSetting {
+ if settingpb == nil {
+ return nil
+ }
+ setting := &apipb.InstanceSetting_StorageSetting{
+ StorageType: apipb.InstanceSetting_StorageSetting_StorageType(settingpb.StorageType),
+ FilepathTemplate: settingpb.FilepathTemplate,
+ DefaultStorageId: settingpb.DefaultStorageId,
+ }
+ for _, storagepb := range settingpb.Storages {
+ setting.Storages = append(setting.Storages, storageFromStore(storagepb))
+ }
+ if settingpb.S3Config != nil {
+ setting.S3Config = &apipb.InstanceSetting_StorageSetting_S3Config{
+ AccessKeyId: settingpb.S3Config.AccessKeyId,
+ AccessKeySecret: settingpb.S3Config.AccessKeySecret,
+ Endpoint: settingpb.S3Config.Endpoint,
+ Region: settingpb.S3Config.Region,
+ Bucket: settingpb.S3Config.Bucket,
+ UsePathStyle: settingpb.S3Config.UsePathStyle,
+ InsecureSkipTlsVerify: settingpb.S3Config.InsecureSkipTlsVerify,
+ }
+ }
+ return setting
+}
+
+func storageSettingToStore(setting *apipb.InstanceSetting_StorageSetting) *storepb.InstanceStorageSetting {
+ if setting == nil {
+ return nil
+ }
+ settingpb := &storepb.InstanceStorageSetting{
+ StorageType: storepb.InstanceStorageSetting_StorageType(setting.StorageType),
+ FilepathTemplate: setting.FilepathTemplate,
+ DefaultStorageId: setting.DefaultStorageId,
+ }
+ for _, storage := range setting.Storages {
+ settingpb.Storages = append(settingpb.Storages, storageToStore(storage))
+ }
+ if setting.S3Config != nil {
+ settingpb.S3Config = &storepb.StorageS3Config{
+ AccessKeyId: setting.S3Config.AccessKeyId,
+ AccessKeySecret: setting.S3Config.AccessKeySecret,
+ Endpoint: setting.S3Config.Endpoint,
+ Region: setting.S3Config.Region,
+ Bucket: setting.S3Config.Bucket,
+ UsePathStyle: setting.S3Config.UsePathStyle,
+ InsecureSkipTlsVerify: setting.S3Config.InsecureSkipTlsVerify,
+ }
+ }
+ return settingpb
+}
+
+func storageFromStore(storagepb *storepb.Storage) *apipb.InstanceSetting_Storage {
+ if storagepb == nil {
+ return nil
+ }
+ storage := &apipb.InstanceSetting_Storage{
+ Id: storagepb.Id,
+ Name: storagepb.Name,
+ Type: apipb.InstanceSetting_StorageType(storagepb.Type),
+ }
+ if s3Config := storagepb.GetS3Config(); s3Config != nil {
+ storage.Config = &apipb.InstanceSetting_Storage_S3Config_{
+ S3Config: &apipb.InstanceSetting_Storage_S3Config{
+ AccessKeyId: s3Config.AccessKeyId,
+ AccessKeySecret: s3Config.AccessKeySecret,
+ Endpoint: s3Config.Endpoint,
+ Region: s3Config.Region,
+ Bucket: s3Config.Bucket,
+ UsePathStyle: s3Config.UsePathStyle,
+ InsecureSkipTlsVerify: s3Config.InsecureSkipTlsVerify,
+ },
+ }
+ }
+ return storage
+}
+
+func storageToStore(storage *apipb.InstanceSetting_Storage) *storepb.Storage {
+ if storage == nil {
+ return nil
+ }
+ storagepb := &storepb.Storage{
+ Id: storage.Id,
+ Name: storage.Name,
+ Type: storepb.StorageType(storage.Type),
+ }
+ if s3Config := storage.GetS3Config(); s3Config != nil {
+ storagepb.Config = &storepb.Storage_S3Config{
+ S3Config: &storepb.StorageS3Config{
+ AccessKeyId: s3Config.AccessKeyId,
+ AccessKeySecret: s3Config.AccessKeySecret,
+ Endpoint: s3Config.Endpoint,
+ Region: s3Config.Region,
+ Bucket: s3Config.Bucket,
+ UsePathStyle: s3Config.UsePathStyle,
+ InsecureSkipTlsVerify: s3Config.InsecureSkipTlsVerify,
+ },
+ }
+ }
+ return storagepb
+}
+
+func memoRelatedSettingFromStore(setting *storepb.InstanceMemoRelatedSetting) *apipb.InstanceSetting_MemoRelatedSetting {
+ if setting == nil {
+ return nil
+ }
+ return &apipb.InstanceSetting_MemoRelatedSetting{
+ Reactions: setting.Reactions,
+ }
+}
+
+func memoRelatedSettingToStore(setting *apipb.InstanceSetting_MemoRelatedSetting) *storepb.InstanceMemoRelatedSetting {
+ if setting == nil {
+ return nil
+ }
+ return &storepb.InstanceMemoRelatedSetting{
+ Reactions: setting.Reactions,
+ }
+}
+
+func tagsSettingFromStore(setting *storepb.InstanceTagsSetting) *apipb.InstanceSetting_TagsSetting {
+ if setting == nil {
+ return nil
+ }
+ tags := make(map[string]*apipb.InstanceSetting_TagMetadata, len(setting.Tags))
+ for tag, metadata := range setting.Tags {
+ tags[tag] = &apipb.InstanceSetting_TagMetadata{
+ BackgroundColor: metadata.GetBackgroundColor(),
+ BlurContent: metadata.GetBlurContent(),
+ }
+ }
+ return &apipb.InstanceSetting_TagsSetting{
+ Tags: tags,
+ }
+}
+
+func tagsSettingToStore(setting *apipb.InstanceSetting_TagsSetting) *storepb.InstanceTagsSetting {
+ if setting == nil {
+ return nil
+ }
+ tags := make(map[string]*storepb.InstanceTagMetadata, len(setting.Tags))
+ for tag, metadata := range setting.Tags {
+ tags[tag] = &storepb.InstanceTagMetadata{
+ BackgroundColor: metadata.GetBackgroundColor(),
+ BlurContent: metadata.GetBlurContent(),
+ }
+ }
+ return &storepb.InstanceTagsSetting{
+ Tags: tags,
+ }
+}
+
+func notificationSettingFromStore(setting *storepb.InstanceNotificationSetting) *apipb.InstanceSetting_NotificationSetting {
+ if setting == nil {
+ return nil
+ }
+
+ notificationSetting := &apipb.InstanceSetting_NotificationSetting{}
+ if setting.Email != nil {
+ notificationSetting.Email = &apipb.InstanceSetting_NotificationSetting_EmailSetting{
+ Enabled: setting.Email.Enabled,
+ SmtpHost: setting.Email.SmtpHost,
+ SmtpPort: setting.Email.SmtpPort,
+ SmtpUsername: setting.Email.SmtpUsername,
+ SmtpPassword: setting.Email.SmtpPassword,
+ FromEmail: setting.Email.FromEmail,
+ FromName: setting.Email.FromName,
+ ReplyTo: setting.Email.ReplyTo,
+ UseTls: setting.Email.UseTls,
+ UseSsl: setting.Email.UseSsl,
+ }
+ }
+ return notificationSetting
+}
+
+// NotificationSettingToStore converts an API notification setting for the store.
+func NotificationSettingToStore(setting *apipb.InstanceSetting_NotificationSetting) *storepb.InstanceNotificationSetting {
+ if setting == nil {
+ return nil
+ }
+
+ notificationSetting := &storepb.InstanceNotificationSetting{}
+ if setting.Email != nil {
+ notificationSetting.Email = &storepb.InstanceNotificationSetting_EmailSetting{
+ Enabled: setting.Email.Enabled,
+ SmtpHost: setting.Email.SmtpHost,
+ SmtpPort: setting.Email.SmtpPort,
+ SmtpUsername: setting.Email.SmtpUsername,
+ SmtpPassword: setting.Email.SmtpPassword,
+ FromEmail: setting.Email.FromEmail,
+ FromName: setting.Email.FromName,
+ ReplyTo: setting.Email.ReplyTo,
+ UseTls: setting.Email.UseTls,
+ UseSsl: setting.Email.UseSsl,
+ }
+ }
+ return notificationSetting
+}
+
+func aiSettingFromStore(setting *storepb.InstanceAISetting) *apipb.InstanceSetting_AISetting {
+ if setting == nil {
+ return nil
+ }
+
+ aiSetting := &apipb.InstanceSetting_AISetting{
+ Providers: make([]*apipb.InstanceSetting_AIProviderConfig, 0, len(setting.Providers)),
+ Transcription: transcriptionConfigFromStore(setting.GetTranscription()),
+ }
+ for _, provider := range setting.Providers {
+ if provider == nil {
+ continue
+ }
+ aiSetting.Providers = append(aiSetting.Providers, &apipb.InstanceSetting_AIProviderConfig{
+ Id: provider.GetId(),
+ Title: provider.GetTitle(),
+ Type: apipb.InstanceSetting_AIProviderType(provider.GetType()),
+ Endpoint: provider.GetEndpoint(),
+ ApiKey: provider.GetApiKey(),
+ })
+ }
+ return aiSetting
+}
+
+func aiSettingToStore(setting *apipb.InstanceSetting_AISetting) *storepb.InstanceAISetting {
+ if setting == nil {
+ return nil
+ }
+
+ aiSetting := &storepb.InstanceAISetting{
+ Providers: make([]*storepb.AIProviderConfig, 0, len(setting.Providers)),
+ Transcription: transcriptionConfigToStore(setting.GetTranscription()),
+ }
+ for _, provider := range setting.Providers {
+ if provider == nil {
+ continue
+ }
+ aiSetting.Providers = append(aiSetting.Providers, &storepb.AIProviderConfig{
+ Id: provider.GetId(),
+ Title: provider.GetTitle(),
+ Type: storepb.AIProviderType(provider.GetType()),
+ Endpoint: provider.GetEndpoint(),
+ ApiKey: provider.GetApiKey(),
+ })
+ }
+ return aiSetting
+}
+
+func transcriptionConfigFromStore(setting *storepb.TranscriptionConfig) *apipb.InstanceSetting_TranscriptionConfig {
+ if setting == nil {
+ return nil
+ }
+ return &apipb.InstanceSetting_TranscriptionConfig{
+ ProviderId: setting.GetProviderId(),
+ Model: setting.GetModel(),
+ Language: setting.GetLanguage(),
+ Prompt: setting.GetPrompt(),
+ }
+}
+
+func transcriptionConfigToStore(setting *apipb.InstanceSetting_TranscriptionConfig) *storepb.TranscriptionConfig {
+ if setting == nil {
+ return nil
+ }
+ return &storepb.TranscriptionConfig{
+ ProviderId: setting.GetProviderId(),
+ Model: setting.GetModel(),
+ Language: setting.GetLanguage(),
+ Prompt: setting.GetPrompt(),
+ }
+}
diff --git a/core/instancesetting/convert_test.go b/core/instancesetting/convert_test.go
new file mode 100644
index 000000000..692e25cb8
--- /dev/null
+++ b/core/instancesetting/convert_test.go
@@ -0,0 +1,90 @@
+package instancesetting
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ colorpb "google.golang.org/genproto/googleapis/type/color"
+ "google.golang.org/protobuf/proto"
+
+ storepb "github.com/usememos/memos/proto/gen/store"
+)
+
+// TestConversionRoundTrips converts fully populated stored settings to the API
+// and back. Secrets survive, because comparing configuration with stored state
+// needs them; responses redact them in server/api.
+func TestConversionRoundTrips(t *testing.T) {
+ s3 := &storepb.StorageS3Config{
+ AccessKeyId: "AKID", AccessKeySecret: "secret", Endpoint: "https://s3.example.com", Region: "auto",
+ Bucket: "memos", UsePathStyle: true, InsecureSkipTlsVerify: true,
+ }
+ settings := []*storepb.InstanceSetting{
+ {Key: storepb.InstanceSettingKey_GENERAL, Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{
+ DisallowUserRegistration: true, DisallowPasswordAuth: true, AdditionalScript: "s", AdditionalStyle: "c",
+ WeekStartDayOffset: 1, DisallowChangeUsername: true, DisallowChangeNickname: true,
+ CustomProfile: &storepb.InstanceCustomProfile{Title: "t", Description: "d", LogoUrl: "https://example.com/logo.png"},
+ }}},
+ {Key: storepb.InstanceSettingKey_STORAGE, Value: &storepb.InstanceSetting_StorageSetting{StorageSetting: &storepb.InstanceStorageSetting{
+ StorageType: storepb.InstanceStorageSetting_S3, FilepathTemplate: "assets/{filename}", S3Config: proto.CloneOf(s3),
+ Storages: []*storepb.Storage{
+ {Id: "s3", Name: "Archive", Type: storepb.StorageType_STORAGE_TYPE_S3, Config: &storepb.Storage_S3Config{S3Config: proto.CloneOf(s3)}},
+ {Id: "local", Name: "Local", Type: storepb.StorageType_STORAGE_TYPE_LOCAL},
+ },
+ DefaultStorageId: "s3",
+ }}},
+ {Key: storepb.InstanceSettingKey_MEMO_RELATED, Value: &storepb.InstanceSetting_MemoRelatedSetting{MemoRelatedSetting: &storepb.InstanceMemoRelatedSetting{
+ Reactions: []string{"👍", "🎉"},
+ }}},
+ {Key: storepb.InstanceSettingKey_TAGS, Value: &storepb.InstanceSetting_TagsSetting{TagsSetting: &storepb.InstanceTagsSetting{
+ Tags: map[string]*storepb.InstanceTagMetadata{"work": {BackgroundColor: &colorpb.Color{Red: 1}, BlurContent: true}},
+ }}},
+ {Key: storepb.InstanceSettingKey_NOTIFICATION, Value: &storepb.InstanceSetting_NotificationSetting{NotificationSetting: &storepb.InstanceNotificationSetting{
+ Email: &storepb.InstanceNotificationSetting_EmailSetting{
+ Enabled: true, SmtpHost: "smtp.example.com", SmtpPort: 587, SmtpUsername: "memos", SmtpPassword: "password",
+ FromEmail: "[email protected]", FromName: "Memos", ReplyTo: "[email protected]", UseTls: true,
+ },
+ }}},
+ {Key: storepb.InstanceSettingKey_AI, Value: &storepb.InstanceSetting_AiSetting{AiSetting: &storepb.InstanceAISetting{
+ Providers: []*storepb.AIProviderConfig{
+ {Id: "openai", Title: "OpenAI", Type: storepb.AIProviderType_OPENAI, Endpoint: DefaultOpenAIEndpoint, ApiKey: "sk-secret"},
+ },
+ Transcription: &storepb.TranscriptionConfig{ProviderId: "openai", Model: "whisper-1", Language: "en", Prompt: "notes"},
+ }}},
+ {Key: storepb.InstanceSettingKey_ACCESS, Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{
+ AccessMode: storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC,
+ }}},
+ }
+ for _, setting := range settings {
+ t.Run(setting.Key.String(), func(t *testing.T) {
+ api := FromStore(setting)
+ require.Equal(t, NamePrefix+setting.Key.String(), api.GetName())
+ require.True(t, proto.Equal(setting, ToStore(api)), "round trip changed %s", setting.Key)
+ })
+ }
+}
+
+func TestUsageLimitsConversion(t *testing.T) {
+ stored := &storepb.InstanceUsageLimitsSetting{Limits: []*storepb.InstanceUsageLimitsSetting_UsageLimit{
+ {UserIds: []int32{1, 2, 3}, MemoCount: new(int64(100))},
+ {AllUsers: true, UploadBytes: new(int64(1 << 20))},
+ }}
+ // User 3 no longer exists, so it is left out.
+ api := UsageLimitsFromStore(stored, map[int32]string{1: "users/alice", 2: "users/bob"})
+ require.Equal(t, []string{"users/alice", "users/bob"}, api.GetLimits()[0].GetUsers())
+ require.True(t, api.GetLimits()[1].GetAllUsers())
+
+ back, err := UsageLimitsToStore(api, map[string]int32{"users/alice": 1, "users/bob": 2})
+ require.NoError(t, err)
+ require.Equal(t, []int32{1, 2}, back.GetLimits()[0].GetUserIds())
+ require.Equal(t, int64(100), back.GetLimits()[0].GetMemoCount())
+ require.Equal(t, int64(1<<20), back.GetLimits()[1].GetUploadBytes())
+
+ _, err = UsageLimitsToStore(api, map[string]int32{"users/alice": 1})
+ require.ErrorContains(t, err, `user "users/bob" not found`)
+}
+
+func TestToStoreRejectsUnknownNames(t *testing.T) {
+ require.Equal(t, storepb.InstanceSettingKey_INSTANCE_SETTING_KEY_UNSPECIFIED, ToStore(FromStore(&storepb.InstanceSetting{})).Key)
+ require.Error(t, Validate(ToStore(FromStore(&storepb.InstanceSetting{Key: storepb.InstanceSettingKey_GENERAL}))),
+ "a setting without a value fails validation")
+}
diff --git a/core/instancesetting/instancesetting.go b/core/instancesetting/instancesetting.go
new file mode 100644
index 000000000..27beb509e
--- /dev/null
+++ b/core/instancesetting/instancesetting.go
@@ -0,0 +1,268 @@
+// Package instancesetting holds the rules an instance setting must meet before
+// it is stored, whichever path writes it.
+//
+// Validate checks the complete value as it would be stored. Conveniences of
+// one write path, such as the API treating an empty secret as "keep the stored
+// one", run before validation, so the rules here never see a partial value.
+package instancesetting
+
+import (
+ "strings"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/proto"
+
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+)
+
+// Length limits of the AI transcription configuration.
+const (
+ MaxTranscriptionModelLength = 256
+ MaxTranscriptionLanguageLength = 32
+ MaxTranscriptionPromptLength = 4096
+)
+
+// Default endpoints applied by NormalizeAISetting when a provider has none.
+const (
+ DefaultOpenAIEndpoint = "https://api.openai.com/v1"
+ DefaultGeminiEndpoint = "https://generativelanguage.googleapis.com/v1beta"
+)
+
+// Validate reports the first rule the setting breaks, or nil.
+func Validate(setting *storepb.InstanceSetting) error {
+ return ValidateUpdate(setting, nil)
+}
+
+// ValidateUpdate is Validate for a setting that replaces existing. A storage
+// the update leaves unchanged is not checked again, so a storage stored before
+// a rule existed does not block editing the others.
+func ValidateUpdate(setting, existing *storepb.InstanceSetting) error {
+ if setting == nil {
+ return errors.New("instance setting is required")
+ }
+ switch setting.Key {
+ case storepb.InstanceSettingKey_GENERAL:
+ general := setting.GetGeneralSetting()
+ if general == nil {
+ return errors.New("general setting is required")
+ }
+ if general.WeekStartDayOffset < -1 || general.WeekStartDayOffset > 6 {
+ return errors.New("week_start_day_offset must be between -1 and 6")
+ }
+ case storepb.InstanceSettingKey_STORAGE:
+ if setting.GetStorageSetting() == nil {
+ return errors.New("storage setting is required")
+ }
+ return validateStorageSetting(setting.GetStorageSetting(), existing.GetStorageSetting())
+ case storepb.InstanceSettingKey_MEMO_RELATED:
+ if setting.GetMemoRelatedSetting() == nil {
+ return errors.New("memo related setting is required")
+ }
+ case storepb.InstanceSettingKey_TAGS:
+ if setting.GetTagsSetting() == nil {
+ return errors.New("tags setting is required")
+ }
+ case storepb.InstanceSettingKey_NOTIFICATION:
+ if setting.GetNotificationSetting() == nil {
+ return errors.New("notification setting is required")
+ }
+ return validateNotificationSetting(setting.GetNotificationSetting())
+ case storepb.InstanceSettingKey_AI:
+ if setting.GetAiSetting() == nil {
+ return errors.New("AI setting is required")
+ }
+ return validateAISetting(setting.GetAiSetting())
+ case storepb.InstanceSettingKey_ACCESS:
+ access := setting.GetAccessSetting()
+ if access == nil {
+ return errors.New("access setting is required")
+ }
+ switch access.AccessMode {
+ case storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC:
+ default:
+ return errors.New("access_mode must be PRIVATE or PUBLIC")
+ }
+ case storepb.InstanceSettingKey_USAGE_LIMITS:
+ usageLimits := setting.GetUsageLimitsSetting()
+ if usageLimits == nil {
+ return errors.New("usage limits setting is required")
+ }
+ return store.ValidateInstanceUsageLimitsSetting(usageLimits)
+ case storepb.InstanceSettingKey_BASIC:
+ return errors.New("BASIC holds the instance secret and schema version and cannot be written")
+ case storepb.InstanceSettingKey_CONFIGURATION_STATE:
+ return errors.New("CONFIGURATION_STATE is the declarative configuration state record and cannot be written")
+ default:
+ return errors.Errorf("unsupported instance setting key %s", setting.Key)
+ }
+ return nil
+}
+
+// validateStorageSetting checks the storage registry. The legacy shape, with no
+// storages and only the top-level fields, is accepted for older clients.
+func validateStorageSetting(setting, existing *storepb.InstanceStorageSetting) error {
+ if len(setting.Storages) == 0 {
+ if setting.StorageType == storepb.InstanceStorageSetting_S3 {
+ if setting.S3Config == nil {
+ return errors.New("s3_config is required for S3 storage")
+ }
+ return validateS3Config("s3_config", setting.S3Config)
+ }
+ return nil
+ }
+
+ existingByID := make(map[string]*storepb.Storage, len(existing.GetStorages()))
+ for _, storage := range existing.GetStorages() {
+ existingByID[storage.GetId()] = storage
+ }
+ seenIDs := make(map[string]bool, len(setting.Storages))
+ for i, storage := range setting.Storages {
+ if storage == nil || strings.TrimSpace(storage.Id) == "" {
+ return errors.Errorf("storages[%d].id is required", i)
+ }
+ if seenIDs[storage.Id] {
+ return errors.Errorf("storage ID %q is duplicated", storage.Id)
+ }
+ seenIDs[storage.Id] = true
+ if previous := existingByID[storage.Id]; previous != nil && proto.Equal(previous, storage) {
+ continue
+ }
+ switch storage.Type {
+ case storepb.StorageType_STORAGE_TYPE_DATABASE, storepb.StorageType_STORAGE_TYPE_LOCAL:
+ case storepb.StorageType_STORAGE_TYPE_S3:
+ if storage.GetS3Config() == nil {
+ return errors.Errorf("storage %q S3 config is required", storage.Id)
+ }
+ if err := validateS3Config("storage "+storage.Id, storage.GetS3Config()); err != nil {
+ return err
+ }
+ default:
+ return errors.Errorf("storage %q type is required", storage.Id)
+ }
+ }
+ if !seenIDs[setting.DefaultStorageId] {
+ return errors.Errorf("default storage %q is not configured", setting.DefaultStorageId)
+ }
+ return nil
+}
+
+func validateS3Config(subject string, config *storepb.StorageS3Config) error {
+ for _, field := range []struct {
+ name string
+ value string
+ }{
+ {name: "endpoint", value: config.Endpoint},
+ {name: "region", value: config.Region},
+ {name: "bucket", value: config.Bucket},
+ {name: "access_key_id", value: config.AccessKeyId},
+ {name: "access_key_secret", value: config.AccessKeySecret},
+ } {
+ if strings.TrimSpace(field.value) == "" {
+ return errors.Errorf("%s %s is required", subject, field.name)
+ }
+ }
+ return nil
+}
+
+// validateNotificationSetting requires enabled email to have a host, a
+// positive port, and a from address, and keeps TLS and SSL mutually exclusive.
+func validateNotificationSetting(setting *storepb.InstanceNotificationSetting) error {
+ email := setting.GetEmail()
+ if email == nil || !email.Enabled {
+ return nil
+ }
+ if strings.TrimSpace(email.SmtpHost) == "" || email.SmtpPort <= 0 || strings.TrimSpace(email.FromEmail) == "" {
+ return errors.New("enabled notification email requires smtp_host, a positive smtp_port, and from_email")
+ }
+ if email.UseTls && email.UseSsl {
+ return errors.New("notification email cannot enable both use_tls and use_ssl")
+ }
+ return nil
+}
+
+// Normalize applies to a setting the normalization every stored write applies:
+// trimmed AI providers with default endpoints, and a normalized storage registry.
+func Normalize(setting *storepb.InstanceSetting) {
+ switch setting.Key {
+ case storepb.InstanceSettingKey_AI:
+ NormalizeAISetting(setting.GetAiSetting())
+ case storepb.InstanceSettingKey_STORAGE:
+ store.NormalizeInstanceStorageSetting(setting.GetStorageSetting())
+ default:
+ }
+}
+
+// NormalizeAISetting trims provider and transcription fields and fills a
+// provider's default endpoint. It never generates IDs or copies secrets.
+func NormalizeAISetting(setting *storepb.InstanceAISetting) {
+ if setting == nil {
+ return
+ }
+ for _, provider := range setting.Providers {
+ if provider == nil {
+ continue
+ }
+ provider.Id = strings.TrimSpace(provider.Id)
+ provider.Title = strings.TrimSpace(provider.Title)
+ provider.Endpoint = strings.TrimSpace(provider.Endpoint)
+ if provider.Endpoint == "" {
+ switch provider.Type {
+ case storepb.AIProviderType_OPENAI:
+ provider.Endpoint = DefaultOpenAIEndpoint
+ case storepb.AIProviderType_GEMINI:
+ provider.Endpoint = DefaultGeminiEndpoint
+ default:
+ }
+ }
+ }
+ if transcription := setting.Transcription; transcription != nil {
+ transcription.ProviderId = strings.TrimSpace(transcription.ProviderId)
+ transcription.Model = strings.TrimSpace(transcription.Model)
+ transcription.Language = strings.TrimSpace(transcription.Language)
+ transcription.Prompt = strings.TrimSpace(transcription.Prompt)
+ }
+}
+
+func validateAISetting(setting *storepb.InstanceAISetting) error {
+ seenIDs := make(map[string]bool, len(setting.Providers))
+ for i, provider := range setting.Providers {
+ if provider == nil {
+ return errors.Errorf("providers[%d] must not be null", i)
+ }
+ if provider.Id == "" {
+ return errors.Errorf("providers[%d].id is required", i)
+ }
+ if seenIDs[provider.Id] {
+ return errors.Errorf("duplicate provider ID %q", provider.Id)
+ }
+ seenIDs[provider.Id] = true
+ if provider.Title == "" {
+ return errors.Errorf("provider %q title is required", provider.Id)
+ }
+ if provider.Type != storepb.AIProviderType_OPENAI && provider.Type != storepb.AIProviderType_GEMINI {
+ return errors.Errorf("provider %q has unsupported type", provider.Id)
+ }
+ if provider.ApiKey == "" {
+ return errors.Errorf("provider %q API key is required", provider.Id)
+ }
+ }
+
+ transcription := setting.Transcription
+ if transcription == nil {
+ return nil
+ }
+ if transcription.ProviderId != "" && !seenIDs[transcription.ProviderId] {
+ return errors.Errorf("transcription provider_id %q does not reference any configured provider", transcription.ProviderId)
+ }
+ if len(transcription.Model) > MaxTranscriptionModelLength {
+ return errors.Errorf("transcription model is too long; maximum length is %d characters", MaxTranscriptionModelLength)
+ }
+ if len(transcription.Language) > MaxTranscriptionLanguageLength {
+ return errors.Errorf("transcription language is too long; maximum length is %d characters", MaxTranscriptionLanguageLength)
+ }
+ if len(transcription.Prompt) > MaxTranscriptionPromptLength {
+ return errors.Errorf("transcription prompt is too long; maximum length is %d characters", MaxTranscriptionPromptLength)
+ }
+ return nil
+}
diff --git a/core/instancesetting/instancesetting_test.go b/core/instancesetting/instancesetting_test.go
new file mode 100644
index 000000000..6c00439fb
--- /dev/null
+++ b/core/instancesetting/instancesetting_test.go
@@ -0,0 +1,208 @@
+package instancesetting
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
+
+ storepb "github.com/usememos/memos/proto/gen/store"
+)
+
+func TestValidateRequiresValueMatchingKey(t *testing.T) {
+ for _, key := range []storepb.InstanceSettingKey{
+ storepb.InstanceSettingKey_GENERAL,
+ storepb.InstanceSettingKey_STORAGE,
+ storepb.InstanceSettingKey_MEMO_RELATED,
+ storepb.InstanceSettingKey_TAGS,
+ storepb.InstanceSettingKey_NOTIFICATION,
+ storepb.InstanceSettingKey_AI,
+ storepb.InstanceSettingKey_ACCESS,
+ storepb.InstanceSettingKey_USAGE_LIMITS,
+ } {
+ // A GENERAL value under every other key is a mismatch; under GENERAL
+ // the MEMO_RELATED value is.
+ setting := &storepb.InstanceSetting{
+ Key: key,
+ Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{}},
+ }
+ if key == storepb.InstanceSettingKey_GENERAL {
+ setting.Value = &storepb.InstanceSetting_MemoRelatedSetting{MemoRelatedSetting: &storepb.InstanceMemoRelatedSetting{}}
+ }
+ require.Error(t, Validate(setting), key.String())
+ }
+}
+
+func TestValidateRejectsUnwritableKeys(t *testing.T) {
+ err := Validate(&storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey_BASIC,
+ Value: &storepb.InstanceSetting_BasicSetting{BasicSetting: &storepb.InstanceBasicSetting{}},
+ })
+ require.ErrorContains(t, err, "cannot be written")
+ require.ErrorContains(t, Validate(&storepb.InstanceSetting{Key: storepb.InstanceSettingKey_CONFIGURATION_STATE}), "state record")
+ require.ErrorContains(t, Validate(&storepb.InstanceSetting{}), "unsupported instance setting key")
+ require.Error(t, Validate(nil))
+}
+
+func TestValidateGeneral(t *testing.T) {
+ general := func(offset int32) *storepb.InstanceSetting {
+ return &storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey_GENERAL,
+ Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{WeekStartDayOffset: offset}},
+ }
+ }
+ require.NoError(t, Validate(general(-1)))
+ require.NoError(t, Validate(general(6)))
+ require.ErrorContains(t, Validate(general(7)), "week_start_day_offset")
+ require.ErrorContains(t, Validate(general(-2)), "week_start_day_offset")
+}
+
+func TestValidateAccess(t *testing.T) {
+ access := func(mode storepb.InstanceAccessMode) *storepb.InstanceSetting {
+ return &storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey_ACCESS,
+ Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{AccessMode: mode}},
+ }
+ }
+ require.NoError(t, Validate(access(storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE)))
+ require.NoError(t, Validate(access(storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)))
+ require.ErrorContains(t, Validate(access(storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_UNSPECIFIED)), "access_mode")
+}
+
+func TestValidateNotification(t *testing.T) {
+ notification := func(email *storepb.InstanceNotificationSetting_EmailSetting) *storepb.InstanceSetting {
+ return &storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey_NOTIFICATION,
+ Value: &storepb.InstanceSetting_NotificationSetting{NotificationSetting: &storepb.InstanceNotificationSetting{Email: email}},
+ }
+ }
+ require.NoError(t, Validate(notification(nil)))
+ require.NoError(t, Validate(notification(&storepb.InstanceNotificationSetting_EmailSetting{Enabled: false})))
+ require.NoError(t, Validate(notification(&storepb.InstanceNotificationSetting_EmailSetting{
+ Enabled: true, SmtpHost: "smtp.example.com", SmtpPort: 587, FromEmail: "[email protected]", UseTls: true,
+ })))
+ require.ErrorContains(t, Validate(notification(&storepb.InstanceNotificationSetting_EmailSetting{
+ Enabled: true, SmtpHost: "smtp.example.com", FromEmail: "[email protected]",
+ })), "smtp_port")
+ require.ErrorContains(t, Validate(notification(&storepb.InstanceNotificationSetting_EmailSetting{
+ Enabled: true, SmtpHost: "smtp.example.com", SmtpPort: 465, FromEmail: "[email protected]", UseTls: true, UseSsl: true,
+ })), "use_tls and use_ssl")
+}
+
+func aiSetting(providers ...*storepb.AIProviderConfig) *storepb.InstanceSetting {
+ return &storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey_AI,
+ Value: &storepb.InstanceSetting_AiSetting{AiSetting: &storepb.InstanceAISetting{Providers: providers}},
+ }
+}
+
+func TestValidateAI(t *testing.T) {
+ provider := func(id string) *storepb.AIProviderConfig {
+ return &storepb.AIProviderConfig{Id: id, Title: "OpenAI", Type: storepb.AIProviderType_OPENAI, ApiKey: "key"}
+ }
+ require.NoError(t, Validate(aiSetting()))
+ require.NoError(t, Validate(aiSetting(provider("a"), provider("b"))))
+ require.ErrorContains(t, Validate(aiSetting(provider(""))), "id is required")
+ require.ErrorContains(t, Validate(aiSetting(provider("a"), provider("a"))), "duplicate provider ID")
+
+ noKey := provider("a")
+ noKey.ApiKey = ""
+ require.ErrorContains(t, Validate(aiSetting(noKey)), "API key is required")
+
+ badType := provider("a")
+ badType.Type = storepb.AIProviderType_AI_PROVIDER_TYPE_UNSPECIFIED
+ require.ErrorContains(t, Validate(aiSetting(badType)), "unsupported type")
+
+ setting := aiSetting(provider("a"))
+ setting.GetAiSetting().Transcription = &storepb.TranscriptionConfig{ProviderId: "missing"}
+ require.ErrorContains(t, Validate(setting), "does not reference")
+ setting.GetAiSetting().Transcription = &storepb.TranscriptionConfig{ProviderId: "a", Language: strings.Repeat("x", MaxTranscriptionLanguageLength+1)}
+ require.ErrorContains(t, Validate(setting), "language is too long")
+}
+
+func TestNormalizeAISetting(t *testing.T) {
+ setting := &storepb.InstanceAISetting{
+ Providers: []*storepb.AIProviderConfig{
+ {Id: " a ", Title: " OpenAI ", Type: storepb.AIProviderType_OPENAI},
+ {Id: "b", Type: storepb.AIProviderType_GEMINI, Endpoint: " https://proxy.example.com "},
+ nil,
+ },
+ Transcription: &storepb.TranscriptionConfig{ProviderId: " a ", Model: " whisper-1 "},
+ }
+ NormalizeAISetting(setting)
+ require.Equal(t, "a", setting.Providers[0].Id)
+ require.Equal(t, "OpenAI", setting.Providers[0].Title)
+ require.Equal(t, DefaultOpenAIEndpoint, setting.Providers[0].Endpoint)
+ require.Equal(t, "https://proxy.example.com", setting.Providers[1].Endpoint)
+ require.Equal(t, "a", setting.Transcription.ProviderId)
+ require.Equal(t, "whisper-1", setting.Transcription.Model)
+}
+
+func s3Storage(id string) *storepb.Storage {
+ return &storepb.Storage{
+ Id: id,
+ Type: storepb.StorageType_STORAGE_TYPE_S3,
+ Config: &storepb.Storage_S3Config{S3Config: &storepb.StorageS3Config{
+ Endpoint: "https://s3.example.com", Region: "us-east-1", Bucket: "memos", AccessKeyId: "AKID", AccessKeySecret: "secret",
+ }},
+ }
+}
+
+func storageSetting(defaultID string, storages ...*storepb.Storage) *storepb.InstanceSetting {
+ return &storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey_STORAGE,
+ Value: &storepb.InstanceSetting_StorageSetting{StorageSetting: &storepb.InstanceStorageSetting{
+ Storages: storages,
+ DefaultStorageId: defaultID,
+ }},
+ }
+}
+
+func TestValidateStorage(t *testing.T) {
+ local := &storepb.Storage{Id: "local", Type: storepb.StorageType_STORAGE_TYPE_LOCAL}
+ require.NoError(t, Validate(storageSetting("main", s3Storage("main"), local)))
+ require.ErrorContains(t, Validate(storageSetting("mian", s3Storage("main"))), `default storage "mian" is not configured`)
+ require.ErrorContains(t, Validate(storageSetting("main", s3Storage("main"), s3Storage("main"))), "duplicated")
+ require.ErrorContains(t, Validate(storageSetting("main", s3Storage(""))), "storages[0].id is required")
+ require.ErrorContains(t, Validate(storageSetting("x", &storepb.Storage{Id: "x"})), "type is required")
+
+ for field, clear := range map[string]func(*storepb.StorageS3Config){
+ "endpoint": func(c *storepb.StorageS3Config) { c.Endpoint = "" },
+ "region": func(c *storepb.StorageS3Config) { c.Region = "" },
+ "bucket": func(c *storepb.StorageS3Config) { c.Bucket = "" },
+ "access_key_id": func(c *storepb.StorageS3Config) { c.AccessKeyId = "" },
+ "access_key_secret": func(c *storepb.StorageS3Config) { c.AccessKeySecret = "" },
+ } {
+ incomplete := s3Storage("archive")
+ clear(incomplete.GetS3Config())
+ // A non-default storage is checked as strictly as the default one.
+ err := Validate(storageSetting("local", local, incomplete))
+ require.ErrorContains(t, err, `storage archive `+field+` is required`, field)
+ }
+
+ legacy := &storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey_STORAGE,
+ Value: &storepb.InstanceSetting_StorageSetting{StorageSetting: &storepb.InstanceStorageSetting{StorageType: storepb.InstanceStorageSetting_S3}},
+ }
+ require.ErrorContains(t, Validate(legacy), "s3_config is required")
+ legacy.GetStorageSetting().StorageType = storepb.InstanceStorageSetting_LOCAL
+ require.NoError(t, Validate(legacy))
+}
+
+func TestValidateUpdateSkipsUnchangedStorages(t *testing.T) {
+ stale := s3Storage("old")
+ stale.GetS3Config().Region = ""
+ existing := storageSetting("old", stale)
+
+ // Switching the default away from a storage stored before region was
+ // required does not fail on that storage.
+ update := storageSetting("local", &storepb.Storage{Id: "local", Type: storepb.StorageType_STORAGE_TYPE_LOCAL}, proto.CloneOf(stale))
+ require.NoError(t, ValidateUpdate(update, existing))
+ require.Error(t, Validate(update), "without an existing setting every storage is checked")
+
+ // Editing the stale storage checks it again.
+ edited := proto.CloneOf(stale)
+ edited.GetS3Config().Bucket = "renamed"
+ require.ErrorContains(t, ValidateUpdate(storageSetting("old", edited), existing), "region is required")
+}
diff --git a/core/user/user.go b/core/user/user.go
new file mode 100644
index 000000000..6d293f1d2
--- /dev/null
+++ b/core/user/user.go
@@ -0,0 +1,52 @@
+// Package user holds the rules a user's sign-in fields must meet before they
+// are stored, whichever path writes them, and its role's API and store forms.
+package user
+
+import (
+ "github.com/pkg/errors"
+
+ "github.com/usememos/memos/internal/identifier"
+ apipb "github.com/usememos/memos/proto/gen/api"
+ "github.com/usememos/memos/store"
+)
+
+// NamePrefix starts every user resource name.
+const NamePrefix = "users/"
+
+// ValidateUsername reports whether username may be written as a new or
+// changed username.
+func ValidateUsername(username string) error {
+ if !identifier.IsValidUsername(username) {
+ return errors.Errorf("invalid username %q", username)
+ }
+ return nil
+}
+
+// ValidatePassword reports whether password may be set as a user's password.
+func ValidatePassword(password string) error {
+ if password == "" {
+ return errors.New("password must not be empty")
+ }
+ return nil
+}
+
+// RoleToStore converts an API role for the store; anything but ADMIN is a
+// regular user.
+func RoleToStore(role apipb.User_Role) store.Role {
+ if role == apipb.User_ADMIN {
+ return store.RoleAdmin
+ }
+ return store.RoleUser
+}
+
+// RoleFromStore converts a stored role for the API.
+func RoleFromStore(role store.Role) apipb.User_Role {
+ switch role {
+ case store.RoleAdmin:
+ return apipb.User_ADMIN
+ case store.RoleUser:
+ return apipb.User_USER
+ default:
+ return apipb.User_ROLE_UNSPECIFIED
+ }
+}
diff --git a/core/user/user_test.go b/core/user/user_test.go
new file mode 100644
index 000000000..2ff9a748e
--- /dev/null
+++ b/core/user/user_test.go
@@ -0,0 +1,99 @@
+package user
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestValidateUsername(t *testing.T) {
+ tests := []struct {
+ name string
+ username string
+ wantError bool
+ }{
+ {
+ name: "lowercase",
+ username: "alice",
+ },
+ {
+ name: "mixed case",
+ username: "Alice",
+ },
+ {
+ name: "hyphenated",
+ username: "alice-smith",
+ },
+ {
+ name: "one character",
+ username: "a",
+ },
+ {
+ name: "maximum length",
+ username: "a" + strings.Repeat("b", 35),
+ },
+ {
+ name: "too long",
+ username: "a" + strings.Repeat("b", 36),
+ wantError: true,
+ },
+ {
+ name: "digit first",
+ username: "1alice",
+ },
+ {
+ name: "hyphen last",
+ username: "alice-",
+ wantError: true,
+ },
+ {
+ name: "empty",
+ username: "",
+ wantError: true,
+ },
+ {
+ name: "numeric",
+ username: "123",
+ },
+ {
+ name: "email",
+ username: "[email protected]",
+ wantError: true,
+ },
+ {
+ name: "underscore",
+ username: "alice_smith",
+ wantError: true,
+ },
+ {
+ name: "space",
+ username: "alice smith",
+ wantError: true,
+ },
+ {
+ name: "slash",
+ username: "alice/smith",
+ wantError: true,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ err := ValidateUsername(test.username)
+ if test.wantError && err == nil {
+ t.Fatalf("ValidateUsername(%q) succeeded, want error", test.username)
+ }
+ if !test.wantError && err != nil {
+ t.Fatalf("ValidateUsername(%q) returned error: %v", test.username, err)
+ }
+ })
+ }
+}
+
+func TestValidatePassword(t *testing.T) {
+ if err := ValidatePassword(""); err == nil {
+ t.Fatal("ValidatePassword(\"\") succeeded, want error")
+ }
+ if err := ValidatePassword("secret"); err != nil {
+ t.Fatalf("ValidatePassword(\"secret\") returned error: %v", err)
+ }
+}
diff --git a/docs/design/README.md b/docs/design/README.md
index 183ab6dc7..9571636b3 100644
--- a/docs/design/README.md
+++ b/docs/design/README.md
@@ -20,12 +20,12 @@ Drafts, merged but not yet released:
Drafts, implemented but not yet merged:
+- [Declarative configuration](declarative-configuration.md)
- [Memo attachment and image filters](memo-attachment-filters.md)
Implemented and frozen:
- [API abuse controls](api-abuse-controls.md)
-- [Configuration provisioning](configuration-provisioning.md), moved here from `docs/configuration-provisioning.md` after implementation
- [Memos Export Format](memos-export-format.md), including the schemas under `memo-export/1.0/`
- [Multi-Spaces](multi-spaces.md)
- [Unique email](unique-email.md)
diff --git a/docs/design/configuration-provisioning.md b/docs/design/configuration-provisioning.md
deleted file mode 100644
index d0bc432c3..000000000
--- a/docs/design/configuration-provisioning.md
+++ /dev/null
@@ -1,556 +0,0 @@
-# Configuration Provisioning
-
-Status: Implemented
-
-## Summary
-
-Memos should follow Mastodon's deployment-configuration model: configuration supplied by the deployment is loaded directly into each server process and
-remains authoritative for that process lifetime. It is not imported into the database and is not tracked as database-owned application state.
-
-The first supported file-backed configuration resources are:
-
-- OAuth2 identity providers.
-- Instance settings for access policy, general policy, storage, memo behavior, notifications, and AI providers.
-
-Memos scans `/etc/secrets` after database migration and demo seeding, validates every matching file, builds one immutable configuration snapshot, and
-publishes that snapshot before HTTP or background services start. Applying a changed file requires a process restart.
-
-Every resource file contains exactly one existing `memos.store` protobuf message encoded as protobuf JSON. No resource envelope, state file, ownership
-table, or second persistent copy of a secret is introduced. The process necessarily holds decoded secrets in its private runtime snapshot.
-
-## Design model
-
-Mastodon reads external authentication and other deployment configuration from environment variables or a dotenv file during process initialization. It
-does not copy that configuration into an administrator-editable database resource or maintain Terraform-style ownership state.
-
-Memos should use the same lifecycle while adapting the input format to its existing generated store messages:
-
-- Mounted JSON files replace a large collection of environment variables.
-- File-backed resources exist in the effective runtime configuration.
-- Stored resources continue to exist in the database but are shadowed when a file declares the same stable key.
-- UI and API mutations cannot change an actively file-backed resource.
-- Removing a file and restarting removes the runtime override; it does not delete or modify the stored resource.
-
-This is deployment configuration, not resource reconciliation. Terms such as adoption, import, unmanage, drift, prune, and Terraform state do not apply.
-
-## Goals
-
-- Accept secrets through mounted files without committing them to seed SQL or command-line arguments.
-- Keep each file equal to one generated store protobuf message.
-- Load and validate the complete file set before exposing any of it.
-- Make deployment configuration authoritative for the lifetime of the process.
-- Preserve database-backed UI configuration for keys not supplied by files.
-- Prevent API writes from appearing to change an effective file-backed resource.
-- Keep secret values out of logs, API responses, caches that expose values, and additional persistence.
-- Preserve the administrator password sign-in path when password sign-in is disabled for regular users.
-
-## Non-goals
-
-- Persist file contents or file ownership metadata in the database.
-- Add a `provisioning_resource` table or provisioning columns to existing tables.
-- Reconcile database state to match a desired resource graph.
-- Delete database resources when files disappear.
-- Support multiple configuration sources with precedence rules in the first version.
-- Write UI changes back into mounted files.
-- Watch files or reload configuration without restarting in the first version.
-- Support partial field ownership within an instance-setting group.
-
-## Terminology
-
-**Stored configuration**
-: Configuration stored in the existing `idp` and `system_setting` database tables.
-
-**Deployment configuration**
-: Configuration decoded from matching files during process startup.
-
-**Effective configuration**
-: The configuration used by APIs, authentication, and background services. Deployment configuration shadows stored configuration with the same stable key.
-
-**Stable key**
-: The identity-provider UID or instance-setting key used to merge deployment and stored configuration.
-
-## File discovery
-
-Memos scans direct children of `/etc/secrets`. The directory may contain unrelated platform secrets; only supported filename patterns are read. Memos does
-not recurse into subdirectories and does not create, modify, or delete anything in the directory.
-
-| Filename pattern | Protobuf message | Stable key |
-| --- | --- | --- |
-| `memos-idp-<label>.json` | `memos.store.IdentityProvider` | `uid` |
-| `memos-instance-setting-<label>.json` | `memos.store.InstanceSetting` | `key` |
-
-`<label>` uses lowercase kebab case and must match `[a-z0-9]+(?:-[a-z0-9]+)*`. Matching is case-sensitive and the extension is lowercase `.json`.
-For upgrade compatibility, identity-provider filenames accepted by the original bootstrap (`memos-idp-*.json`) continue to load when the label is not
-lowercase kebab case, but startup logs a deprecation warning. New files should always use the canonical convention.
-
-Recommended labels mirror the resource key for operator readability:
-
-| Resource | Canonical filename |
-| --- | --- |
-| Identity provider with UID `primary-sso` | `memos-idp-primary-sso.json` |
-| `ACCESS` | `memos-instance-setting-access.json` |
-| `GENERAL` | `memos-instance-setting-general.json` |
-| `STORAGE` | `memos-instance-setting-storage.json` |
-| `MEMO_RELATED` | `memos-instance-setting-memo-related.json` |
-| `NOTIFICATION` | `memos-instance-setting-notification.json` |
-| `AI` | `memos-instance-setting-ai.json` |
-
-The filename label remains descriptive rather than authoritative. The `uid` or `key` inside the message is the resource identity, so renaming a file does
-not change account links or effective resource identity. Files are read in lexical order only to produce deterministic diagnostics; ordering has no
-configuration semantics.
-
-Each matching file:
-
-- Must be a valid protobuf JSON representation of the expected message.
-- Must not contain unknown fields.
-- Must not exceed 1 MiB.
-- Must contain exactly one resource.
-- May contain plaintext secrets because the containing directory is treated as sensitive.
-- May be a regular file or a platform-managed symlink that resolves to a regular file, as used by Kubernetes Secret volumes.
-
-A missing directory or a readable directory without matching files is a normal no-op. An unreadable directory or matching file is a startup error. Startup
-logs include matched counts by resource type so a misspelled filename is visible without logging file contents. A direct child beginning with `memos-` but
-not matching a supported pattern produces a warning; unrelated filenames are silently ignored.
-
-### SSO-only deployments
-
-An SSO-only deployment mounts both an identity-provider file and `memos-instance-setting-general.json` with `disallowPasswordAuth` enabled. These resources
-are validated and published together during startup. The public demo seed does not contain authentication policy, so both files must be mounted to enable
-SSO-only behavior. Keep `disallowUserRegistration` disabled when first-time SSO users should be created automatically.
-
-## Identity-provider files
-
-An identity-provider file contains exactly one `memos.store.IdentityProvider`. The database-generated `id` must be omitted. `uid` is required and is the
-stable key.
-
-Example `/etc/secrets/memos-idp-primary-sso.json`:
-
-```json
-{
- "uid": "primary-sso",
- "name": "Company SSO",
- "type": "OAUTH2",
- "identifierFilter": "",
- "config": {
- "oauth2Config": {
- "clientId": "client-id",
- "clientSecret": "client-secret",
- "authUrl": "https://idp.example.com/oauth/authorize",
- "tokenUrl": "https://idp.example.com/oauth/token",
- "userInfoUrl": "https://idp.example.com/oauth/userinfo",
- "scopes": ["openid", "profile", "email"],
- "fieldMapping": {
- "identifier": "sub",
- "displayName": "name",
- "email": "email",
- "avatarUrl": "picture"
- }
- }
- }
-}
-```
-
-Initial validation supports only OAuth2 providers and requires:
-
-- A valid, nonempty UID and display name.
-- Client ID and client secret.
-- Authorization, token, and user-info URLs.
-- At least one scope, with no empty scope entries.
-- A field-mapping object with a nonempty identifier field.
-
-Duplicate UIDs across files are rejected.
-
-User identity links already use the provider UID as their stable provider value. A file-backed provider therefore does not need a database-generated IdP ID
-to preserve account links or complete SSO sign-in.
-
-## Instance-setting files
-
-An instance-setting file contains exactly one `memos.store.InstanceSetting`. `key` is required and is the stable key. The populated `oneof` must match the
-key.
-
-Example `/etc/secrets/memos-instance-setting-general.json`:
-
-```json
-{
- "key": "GENERAL",
- "generalSetting": {
- "disallowUserRegistration": false,
- "disallowPasswordAuth": true,
- "additionalScript": "",
- "additionalStyle": "",
- "weekStartDayOffset": 1,
- "disallowChangeUsername": false,
- "disallowChangeNickname": false,
- "customProfile": {
- "title": "Company Memos",
- "description": "Internal notes",
- "logoUrl": "https://example.com/logo.png"
- }
- }
-}
-```
-
-Example `/etc/secrets/memos-instance-setting-access.json`:
-
-```json
-{
- "key": "ACCESS",
- "accessSetting": {
- "accessMode": "INSTANCE_ACCESS_MODE_PRIVATE"
- }
-}
-```
-
-`ACCESS` must explicitly select `INSTANCE_ACCESS_MODE_PRIVATE` or `INSTANCE_ACCESS_MODE_PUBLIC`. The canonical external instance URL is a separate
-deployment property and does not change who may access the instance. `--instance-url` (or `MEMOS_INSTANCE_URL`) must be an absolute HTTP(S) URL without
-credentials, a query, or a fragment; Memos trims surrounding whitespace and trailing slashes during startup.
-
-Example `/etc/secrets/memos-instance-setting-notification.json`:
-
-```json
-{
- "key": "NOTIFICATION",
- "notificationSetting": {
- "email": {
- "enabled": true,
- "smtpHost": "smtp.example.com",
- "smtpPort": 587,
- "smtpUsername": "memos",
- "smtpPassword": "smtp-secret",
- "fromEmail": "[email protected]",
- "fromName": "Memos",
- "replyTo": "[email protected]",
- "useTls": true,
- "useSsl": false
- }
- }
-}
-```
-
-Supported keys:
-
-| Key | Deployment use |
-| --- | --- |
-| `ACCESS` | Private or public instance access policy |
-| `GENERAL` | Registration, authentication, branding, scripts, styles, and user-profile policy |
-| `STORAGE` | Attachment storage type, limits, paths, and S3 credentials |
-| `MEMO_RELATED` | Memo limits, editing behavior, and reactions |
-| `NOTIFICATION` | SMTP transport and credentials |
-| `AI` | AI providers, API keys, and transcription defaults |
-
-Rejected keys:
-
-- `BASIC` contains the instance secret key and database schema version. Replacing the secret key invalidates sessions, while replacing the schema version
- interferes with database migration state.
-- `TAGS` is retained for backward compatibility; active tag metadata is stored per user.
-
-Only one file may declare a given setting key.
-
-### Complete-group replacement
-
-An instance-setting group is the smallest deployment-configured unit. A file replaces the complete effective group. A scalar omitted from protobuf JSON is
-stored in the decoded message as its protobuf default; omission does not preserve a field from the database value.
-
-Some existing setting getters apply application defaults after decoding zero values. For example, STORAGE defaults to local storage, a 30 MiB upload limit,
-and `assets/{timestamp}_{uuid}_{filename}` when the corresponding decoded fields are unspecified. The effective behavior is therefore the decoded file plus
-the same read-time defaults used for database-backed configuration.
-
-Empty secret fields in a file mean empty values; they never mean "preserve the database secret." Credential-preservation behavior used by UI updates does
-not apply to deployment configuration.
-
-### AI normalization
-
-AI deployment configuration uses deterministic, self-contained normalization rather than the UI update path:
-
-- Every provider requires an explicit stable `id`; the loader never generates one.
-- Every provider requires a title, a supported provider type, and an API key.
-- An empty OpenAI endpoint becomes `https://api.openai.com/v1`.
-- An empty Gemini endpoint becomes `https://generativelanguage.googleapis.com/v1beta`.
-- Duplicate provider IDs are rejected.
-- A transcription provider ID must reference a provider in the same effective AI setting.
-- Model, language, and prompt use the same length limits as API-managed settings.
-- No provider, API key, or transcription value is copied from the shadowed database setting.
-
-## Configuration format compatibility
-
-Using store protobuf JSON makes the selected messages a supported deployment-configuration interface even though the messages remain internal to the
-application. For every provisionable message, Memos must preserve:
-
-- Existing protobuf JSON field names.
-- Existing enum names and meanings.
-- Stable resource-key and `oneof` mappings.
-- Previously valid omissions for fields that have defaults.
-
-New optional fields and enum values may be added. A provisionable field may be deprecated, but its existing JSON spelling must continue to decode for the
-supported upgrade window. Field names must not be reused with a different meaning. New validation should not invalidate an existing safe configuration
-without an upgrade note and a documented replacement.
-
-Unknown fields remain startup errors because this catches misspellings and configuration written for a newer, incompatible Memos version. Compatibility
-tests should keep representative JSON fixtures from earlier releases and decode them with the current loader.
-
-## Runtime configuration snapshot
-
-The loader builds an immutable snapshot containing maps keyed by provider UID and setting key. It does not mutate the database while loading. The `Store`
-owns this snapshot so all existing consumers resolve configuration through one boundary.
-
-Startup follows this sequence:
-
-```text
-Initialize or migrate database
- -> apply demo seed when enabled
- -> initialize a missing ACCESS row from legacy instance-URL behavior
- -> read all matching deployment-configuration files
- -> decode and validate every resource
- -> validate affected cross-resource invariants
- -> publish one immutable runtime snapshot
- -> construct HTTP and background services
- -> accept requests
-```
-
-If any matching file is invalid, no snapshot is published and startup fails. Atomicity comes from publishing the snapshot only after complete validation;
-no cross-database transaction abstraction is required because deployment configuration performs no database writes.
-
-The snapshot is loaded once. Files changed after startup have no effect until the process restarts.
-
-### Immutability and copy semantics
-
-Generated protobuf messages are mutable pointers, so immutability must be enforced rather than assumed:
-
-- Canonical snapshot messages remain private to the `Store`.
-- Effective getters return deep clones, using `proto.Clone`, rather than canonical pointers.
-- Read-time defaults and redaction are applied only to clones.
-- Canonical snapshot messages are never inserted into the existing instance-setting TTL cache.
-- Callers cannot obtain a mutable map or message owned by the snapshot.
-
-This prevents one request, background runner, defaulting helper, or redaction path from changing configuration observed by another goroutine.
-
-### Effective and stored access
-
-The store facade has an explicit separation between effective reads and stored-resource access:
-
-- Normal list/get operations used by authentication, APIs, and background services return effective configuration.
-- Internal raw list/get operations read only the database and are used by migration, snapshot planning, and permitted mutation paths.
-- Mutation services check the snapshot source before loading a raw database row.
-- A file-backed IdP has no database ID and must never be passed to a driver update or delete operation.
-- The loader reads stored configuration through raw access before publishing the snapshot, avoiding recursive effective resolution.
-
-## Effective configuration resolution
-
-### Identity providers
-
-List and get operations return the union of stored and file-backed providers by UID:
-
-- A file-backed provider shadows a stored provider with the same UID.
-- Stored providers with other UIDs remain available.
-- Authentication resolves the same effective provider collection.
-- Removing the file and restarting reveals any stored provider that had been shadowed; it does not restore values from the file.
-- Stored providers retain their database insertion order, and a file-backed provider that shadows one occupies the same position. Providers that exist only
- in deployment configuration are appended in UID order, keeping existing API and sign-in ordering stable while remaining deterministic.
-
-Operators migrating an existing stored provider to a file should keep the same UID so existing user-identity links continue to work. They should remove or
-update the shadowed stored provider before later removing the file if they do not want the old database configuration to reappear.
-
-### Instance settings
-
-Every effective instance-setting getter checks the runtime snapshot before its database cache:
-
-- A file-backed group completely shadows the `system_setting` row with the same key.
-- Other setting groups continue to use stored values and existing application defaults.
-- The runtime snapshot must never be overwritten by a cached database value.
-- Removing a file and restarting returns the group to its stored database value.
-
-The `ACCESS` getter intentionally bypasses the general ten-minute database setting cache when no deployment file shadows it. This makes a change from
-public to private visible to every replica on its next policy check instead of leaving a stale public authorization decision in another process.
-
-The demo seed writes `MEMO_RELATED` but does not write `GENERAL`. Loading deployment configuration after seeding supplies the complete effective General
-settings without embedding deployment authentication policy in demo data.
-
-## Validation and authentication safety
-
-All file-local validation runs before snapshot publication. Relationships between file-backed resources are validated against the resulting effective
-configuration when the desired files affect that relationship.
-
-At minimum, validation rejects:
-
-- A file-backed `GENERAL` setting that disables password authentication for regular users when the resulting effective configuration has no identity
- provider.
-- An instance-setting key whose populated `oneof` does not match the key.
-- An `ACCESS` setting whose mode is omitted or unspecified.
-- S3 storage without the required endpoint, bucket, region, or credentials.
-- Enabled email delivery without the required SMTP host, port, or sender.
-- Duplicate AI provider IDs.
-- Transcription referencing an AI provider ID absent from the effective AI setting.
-- Duplicate stable keys across files.
-
-An unrelated file must not turn an existing database condition into a new startup failure. For example, a STORAGE-only file does not fail startup merely
-because the database already disables regular-user password sign-in while containing no IdP; Memos logs that existing condition as a warning. A file that
-configures GENERAL or an IdP evaluates the authentication invariant against the resulting effective state.
-
-The administrator password path remains available regardless of `disallowPasswordAuth`. Runtime mutations reject transitions from a safe authentication
-state to one where password sign-in is disabled for regular users without an effective IdP. An unrelated edit may preserve an already-existing legacy
-violation so an upgrade does not make the complete `GENERAL` group uneditable; the administrator can resolve that state by enabling password sign-in or
-configuring an IdP. Deleting the last effective IdP from a previously safe state remains rejected.
-
-The validation and database mutation must be one serializable store operation. In particular, updating `GENERAL` and deleting an IdP cannot use separate
-check-then-write calls, because concurrent requests could each validate an old safe state and together produce an unsafe state. The narrow runtime mutation
-operation:
-
-1. Starts a serializable database transaction.
-2. Reads the stored `GENERAL` setting and stored IdPs inside that transaction.
-3. Combines them with the immutable file snapshot and the proposed mutation.
-4. Validates the resulting effective authentication state.
-5. Applies the stored-resource mutation and commits.
-6. Retries serialization conflicts a bounded number of times.
-
-This transaction is required for runtime authentication-policy safety, not for loading deployment files. It adds no table or schema migration. Each
-database driver must provide equivalent transaction semantics for this narrow operation.
-
-## API behavior
-
-The API operates on effective resources for reads and stored resources for permitted writes.
-
-Mutation behavior:
-
-- Creating a stored IdP with a UID reserved by a file-backed provider returns `codes.FailedPrecondition`.
-- Updating or deleting a file-backed IdP returns `codes.FailedPrecondition`.
-- Updating a file-backed instance-setting group returns `codes.FailedPrecondition`.
-- The instance-setting guard runs before validation or future field-mask application, so every masked update to a file-backed group is rejected.
-- Mutations of unshadowed stored configuration continue normally, subject to authentication safety invariants.
-- API responses continue to redact client secrets, SMTP passwords, S3 secrets, and AI API keys.
-
-No API operation writes to the mounted files. Test operations that do not change stored configuration, such as testing the effective SMTP configuration,
-remain available.
-
-## Frontend behavior
-
-The frontend does not receive configuration-source metadata. It presents the normal mutation controls and reports the API's `FailedPrecondition` error when
-an administrator attempts to create, update, or delete a deployment-managed resource. The API remains the sole authority for mutation enforcement.
-
-## Security
-
-- Treat `/etc/secrets` and every matching file as sensitive plaintext.
-- Recommend owner-only or application-group-readable filesystem permissions.
-- Never log file contents, decoded messages, before/after values, or secret fields.
-- Redact secrets from validation errors and startup summaries.
-- Do not persist deployment secrets in `idp`, `system_setting`, a state file, or ownership metadata.
-- Fail startup on an invalid or unreadable matching file rather than publishing partial configuration.
-- Keep the immutable snapshot process-local and expose only redacted API representations.
-
-### Webhook private-network destinations
-
-Webhook delivery blocks private and reserved IP destinations by default. Deployments that intentionally send to internal services should allow only the
-required exact hostnames, IP addresses, or CIDRs with `--webhook-private-network-allowlist`; the equivalent environment variable is
-`MEMOS_WEBHOOK_PRIVATE_NETWORK_ALLOWLIST`. Multiple entries may be repeated or comma-separated, for example:
-
-```text
---webhook-private-network-allowlist hooks.internal,10.20.0.0/16
-```
-
-The legacy `--allow-private-webhooks` flag and `MEMOS_ALLOW_PRIVATE_WEBHOOKS` environment variable remain compatible for upgrades but are deprecated.
-They disable private-network destination protection globally and should be replaced with the allowlist.
-
-## Multiple server replicas
-
-Every replica independently loads deployment configuration at startup, as Mastodon processes independently load environment configuration. All replicas in
-one deployment must mount identical files.
-
-A rolling deployment can temporarily run old and new configuration generations at the same time. Memos does not attempt distributed reconciliation or
-cache invalidation for this process-local configuration. Deployments changing authentication or storage configuration should use a rollout strategy that
-does not route traffic to replicas with different file generations, and readiness must be reported only after the new snapshot validates successfully.
-
-Crossing the version boundary that introduced `ACCESS` requires a coordinated rollout. Older replicas ignore `ACCESS` and continue using the legacy
-rule in which a nonempty instance URL permits anonymous access. Drain all older replicas before changing `ACCESS` or routing traffic to replicas whose
-policy differs from that legacy rule; do not serve traffic from old and new replicas with different effective access policies. Before rolling back,
-make the legacy instance URL rule match the intended policy—nonempty for public or empty for private—then drain the newer replicas and complete the
-rollback. Otherwise, an older replica can expose an instance whose stored `ACCESS` policy is `PRIVATE` but whose instance URL is nonempty.
-
-Because file-backed settings bypass the database setting cache, a replica cannot replace a deployment value with a stale cached database value.
-
-## Database and migration impact
-
-This design requires no database schema changes:
-
-- File-backed IdPs are not inserted into `idp`.
-- File-backed settings are not inserted into `system_setting`.
-- Existing user-identity links remain database-backed and continue to reference provider UIDs.
-- Existing stored configuration remains untouched beneath runtime overrides.
-
-The first startup with ACCESS support creates one database-backed `ACCESS` setting when the row is missing. To preserve upgrade behavior, it records
-`PUBLIC` when the legacy startup profile has a nonempty canonical instance URL and `PRIVATE` otherwise. This is a one-time compatibility decision: after
-the row exists, adding, removing, or changing the instance URL never changes access policy. A deployment-provided ACCESS file may shadow that stored row
-without modifying it.
-
-### Transition from the database-writing bootstrap
-
-Versions with the original `memos-idp-*.json` bootstrap copied file-backed IdPs, including client secrets, into the `idp` table during migration. The new
-loader cannot reliably distinguish those rows from providers created through the UI, so it must not delete or scrub them automatically.
-
-When a file shadows a stored provider with the same UID, startup logs a secret-free warning that a stored copy remains. Operators who previously used the
-database-writing bootstrap should clean up explicitly:
-
-1. Back up the database and retain administrator password access.
-2. Temporarily remove the IdP file and restart Memos so the stored provider is no longer shadowed.
-3. Delete or update the stored provider through the administrator UI or API, or perform equivalent offline database maintenance.
-4. Restore the file and restart Memos.
-
-Until that cleanup is complete, the old stored provider and secret remain in the database and can reappear if the file is removed. The no-persistence
-guarantee applies to the new loader; it does not claim to erase secrets written by earlier versions.
-
-## Implementation
-
-The implementation:
-
-1. Replaces the database-writing IdP bootstrap with a typed deployment-configuration loader.
-2. Decodes and validates `memos-instance-setting-*.json` resources.
-3. Loads configuration after migration and demo seeding but before service construction.
-4. Publishes an immutable provider/settings snapshot owned by the store facade, with clone-on-read semantics.
-5. Resolves file-backed values before database values and caches for IdP authentication and instance settings.
-6. Uses explicit raw database reads for snapshot planning and permitted mutation paths.
-7. Validates affected startup state and uses a narrow serializable transaction for runtime authentication mutations.
-8. Enforces deployment ownership through API mutation guards and returns `codes.FailedPrecondition` for rejected writes.
-9. Initializes and reads the dedicated ACCESS policy independently from the canonical external instance URL.
-
-## Test strategy
-
-The implementation requires tests for:
-
-- Every canonical filename pattern, legacy identity-provider filename compatibility, and supported message type.
-- Unknown fields, oversized files, unreadable files, invalid protobuf JSON, and invalid enum values.
-- Duplicate provider UIDs and setting keys.
-- Rejection of `BASIC`, `TAGS`, and key/`oneof` mismatches.
-- Complete validation before snapshot publication.
-- Store-proto JSON compatibility fixtures from earlier releases.
-- Effective merging and shadowing by provider UID and setting key.
-- Stable stored ordering and deterministic placement of deployment-only identity providers.
-- Removal of a file taking effect after constructing a new process snapshot without deleting stored configuration.
-- Existing user-identity links working with a file-backed provider of the same UID.
-- File-backed settings bypassing database cache entries.
-- Clone-on-read behavior and race tests proving snapshot messages cannot be mutated by callers.
-- Authentication safety for startup and runtime IdP deletion.
-- Concurrent `GENERAL` updates and IdP deletion preserving the runtime authentication invariant across database drivers.
-- An unrelated deployment file not failing because of untouched pre-existing authentication state.
-- Storage read-time defaults, SMTP validation, and deterministic AI normalization without database secret preservation.
-- Missing-directory behavior and matched-file count logging.
-- Mutation guards, including requests carrying field masks.
-- A stored provider shadowed by a file producing a secret-free legacy-bootstrap warning.
-- Secret redaction in errors, logs, and API responses.
-- One-time legacy ACCESS initialization and persistence across later instance-URL changes.
-- Immediate cross-replica database-backed ACCESS reads and explicit PRIVATE/PUBLIC API behavior.
-
-## Research references
-
-- [Mastodon environment configuration](https://docs.joinmastodon.org/admin/config/)
-- [Mastodon OmniAuth initialization](https://github.com/mastodon/mastodon/blob/main/config/initializers/3_omniauth.rb)
-- [GitLab OpenID Connect configuration](https://docs.gitlab.com/administration/auth/oidc/)
-- [Keycloak startup import](https://www.keycloak.org/server/importExport)
-- [Grafana provisioning](https://grafana.com/docs/grafana/latest/administration/provisioning/)
-
-## Amendments
-
-### 2026-10-14: usage limits
-
-- `USAGE_LIMITS` is a deployment-configurable key, provided as `memos-instance-setting-usage-limits.json`. The file is the ordered entry list: every
- entry lists positive `userIds` except the last, which sets `allUsers: true`. While the file is mounted, `UpdateInstanceSetting` for the key returns
- `FAILED_PRECONDITION`.
-- `STORAGE` no longer carries an upload size limit. The per-file cap is the `UPLOAD_BYTES` usage limit, and an absent `USAGE_LIMITS` setting means
- the built-in defaults of 8 KiB per memo and 32 MiB per file. See [User usage limits](user-usage-limits.md).
diff --git a/docs/design/declarative-configuration.md b/docs/design/declarative-configuration.md
new file mode 100644
index 000000000..bb8fd573d
--- /dev/null
+++ b/docs/design/declarative-configuration.md
@@ -0,0 +1,791 @@
+# Declarative Configuration
+
+Status: Draft
+
+## Summary
+
+Operators describe the identity providers, instance settings, and bootstrap users an instance should have in configuration files. Memos
+treats those files as the desired state, compares them with the actual state in the database, shows the difference as a plan, and applies
+the plan as one atomic database transaction. A state record remembers which resources the configuration manages, so Memos can detect
+drift, release or destroy resources that leave the configuration, and refuse API writes that would silently diverge from the files.
+
+The model is the one Terraform and Kubernetes made standard: desired state in files, actual state in the system, a state record that links
+the two, an explicit plan, and an idempotent apply. The file schema is the public API resource model, so the compatibility promise for
+configuration files is the API compatibility policy and nothing separate.
+
+## Design model
+
+A declarative configuration system has five parts. Every decision below is a choice about one of them.
+
+| Part | Memos |
+| --- | --- |
+| Desired state | JSON documents in a configuration directory, merged into one `memos.api.Configuration` |
+| Actual state | The `idp`, `system_setting`, and `user` tables, read through the store |
+| State record | One `CONFIGURATION_STATE` row in `system_setting`: a serial and the list of managed resources, never a value |
+| Plan | A deterministic list of per-resource actions computed from desired, actual, and state record, printable as text or JSON |
+| Apply | The plan executed inside one serializable transaction, followed by an update of the state record in the same transaction |
+
+Terraform's vocabulary is used throughout: a resource is *managed* when the state record lists it, *drift* is a difference between the
+actual state and the last applied desired state, *lifecycle* rules adjust how a resource is planned, a *removed* declaration takes a
+resource out of management, and *import* (called *adopt* here) brings an existing resource under management.
+
+Two places deliberately depart from Terraform, and each is called out where it happens:
+
+- Apply is atomic. Terraform applies resource by resource and can stop halfway; every Memos resource lives in one database, so the plan
+ either applies completely or not at all.
+- Managed resources are read-only through the API. Terraform tolerates drift and corrects it at the next apply; Memos refuses the write
+ up front, because a change that silently disappears at the next restart is worse for an administrator than an immediate error.
+
+## Scope
+
+Three different things are called "configuration", and only one of them is declarative configuration.
+
+| Layer | What it is | How it is set | Terraform analogue |
+| --- | --- | --- | --- |
+| Process | Inputs the binary needs before it can reach the database: `--port`, `--driver`, `--dsn`, `--data`, `--instance-url`, `--config-dir` | Flags and environment variables | The provider block |
+| Instance | Database-resident resources that define how the instance behaves for everyone | Declarative files or the admin API | Resources |
+| Content | What people make while using the product | UI and API only | Out of scope |
+
+This design covers the instance layer only. The process layer stays in flags, because the files cannot be read until the process layer has
+said where the database is. The content layer stays out because it has no operator-chosen names and is edited by every user every day.
+
+### The test for a resource
+
+A resource belongs in the files when all five hold:
+
+1. **Operator-owned.** An administrator decides it, not the person using the product.
+2. **Stable name.** The operator chooses the identifier (`identity-providers/company-sso`, `users/admin`), so one file addresses the same
+ resource in every environment. Server-generated identifiers such as `memos/{uid}` fail this.
+3. **Low cardinality, low churn.** Tens of entries, edited in a reviewed file; not thousands, not hourly.
+4. **Wanted identical across environments or before first sign-in.** Staging equals production; a fresh instance is usable without a browser.
+5. **Fully expressible.** Everything about it fits in a file; nothing essential is computed at runtime.
+
+Failing one puts the resource in the UI and API.
+
+### Inventory
+
+| Resource | Verdict | Reason |
+| --- | --- | --- |
+| `instance/settings/{ACCESS, GENERAL, STORAGE, MEMO_RELATED, NOTIFICATION, AI, USAGE_LIMITS}` | In | Policy; the reason the feature exists |
+| `instance/settings/BASIC` | Never | Instance secret and schema version are state, not policy |
+| `instance/settings/TAGS` | Never | Legacy; tag metadata is per user |
+| `identity-providers/*` | In | Authentication infrastructure, needed before the first SSO sign-in |
+| `users/*` | In, narrowly | Bootstrap administrators: `username`, `role`, `password`, optionally `displayName` and `email`; the rest of the profile is the user's |
+| `spaces/*` | Later | `title` and `description` pass the test; `spaces/*/members` does not, because membership runs through invite and accept |
+| `users/*/webhooks/*` | Later | Reproducible wiring for an automation user; content for anyone else |
+| `users/*/personalAccessTokens/*` | Later, with care | Bootstrapping an MCP client needs a token before anyone signs in; the value would be a write-only field the operator supplies |
+| `users/*/settings/*`, `users/*/views/*` | Never | Personal preferences |
+| `users/*/linkedIdentities/*` | Never | Created by signing in, not declared |
+| `users/*/notifications/*`, `users/*/stats`, `users/*/usage`, `spaces/*/invitations/*` | Never | Transient or computed |
+| `memos/*`, `attachments/*`, reactions, shares, comments | Never | Content |
+
+The "In" rows are the whole first version. The "Later" rows are what the machinery must not make hard: the state record keys on resource
+name and each kind declares its field classes in one place, so adding a kind is one table in this document and one package.
+
+### Rule for new features
+
+When a change adds an instance setting or an admin-managed resource, ask: would an operator want this in version control, identical in
+staging and production, set before anyone signs in? Yes means the same change gives it a field class table below and a fixture. No means it
+is a UI concern and the files never learn about it.
+
+## Goals
+
+- One file format with one compatibility policy: files are public API resources in protobuf JSON.
+- A plan that shows exactly what apply will change, with secrets redacted, before anything is written.
+- Atomic, idempotent apply: the same files applied twice produce an empty second plan; a failed apply changes nothing.
+- A state record that makes removal, release, adoption, and drift explicit instead of inferred.
+- Administrators can see which resources the configuration manages and why an edit is refused.
+- Secrets reach the files only through references to the environment or to other files; the state record stores no values.
+- Validation without a database, planning without writes, and apply from both the CLI and server startup.
+- Headless bootstrap: an instance can come up with its administrator, identity provider, and policy without a browser.
+
+## Non-goals
+
+- Field-level ownership of one resource by several managers (Kubernetes server-side apply). A resource is managed whole, with
+ `ignoreChanges` to release individual fields.
+- Watching the directory and re-applying without a restart or an explicit `apply`.
+- Managing anything outside the "In" rows of the inventory above.
+- Writing API changes back into the files.
+- A remote state backend. The state record lives in the instance database.
+- Templates, modules, or variables beyond `${env:…}` and `${file:…}` substitution.
+
+## Terminology
+
+**Desired state**
+: The merged `Configuration` document decoded from every file in the configuration directory.
+
+**Actual state**
+: The resources currently stored in the database, read without caches.
+
+**State record**
+: The `CONFIGURATION_STATE` row. It lists managed resources and the last apply; it never stores values.
+
+**Managed resource**
+: A resource listed in the state record. Its managed fields are read-only through the API.
+
+**Plan**
+: The ordered list of actions that turn the actual state into the desired state, together with the drift and adoption it detected.
+
+**Drift**
+: A managed resource whose actual state differs from the desired state. With the API guard in place, drift can only come from direct
+database edits, a restored backup, or a change to the files.
+
+**Adopt**
+: Bringing a resource that already exists in the database under management because the desired state declares it.
+
+**Release**
+: Removing a resource from the state record without changing it in the database.
+
+**Destroy**
+: Removing a resource from the state record and deleting it, or for a singleton setting group, resetting it to its defaults.
+
+## Configuration source
+
+### Directory
+
+Memos reads every regular file named `*.json` in one directory, in lexical filename order, without recursing. The directory comes from
+`--config-dir` or `MEMOS_CONFIG_DIR`; the default is `/etc/memos/config`. A missing directory means an empty desired state. An unreadable
+directory or file is an error. Symlinks that resolve to regular files are followed, because Kubernetes Secret and ConfigMap volumes are
+symlink farms. Files larger than 1 MiB are rejected. Files with other extensions are ignored so the directory can hold unrelated mounts.
+
+Lexical order affects only diagnostics. As in a Terraform root module, all files form one configuration; a resource may be declared in
+exactly one file, and declaring the same resource name twice is an error that names both files.
+
+### Document
+
+Every file is one `memos.api.Configuration` message in protobuf JSON:
+
+```proto
+// Configuration is one declarative configuration document. All files in the
+// configuration directory are merged into one Configuration.
+message Configuration {
+ // Identity providers to manage, by resource name.
+ repeated IdentityProvider identity_providers = 1;
+ // Instance setting groups to manage, by resource name.
+ repeated InstanceSetting instance_settings = 2;
+ // Users to manage, by resource name. Intended for bootstrap administrators.
+ repeated User users = 3;
+ // Lifecycle rules for declared resources.
+ repeated Lifecycle lifecycle = 4;
+ // Resources to take out of management.
+ repeated Removed removed = 5;
+}
+
+// Lifecycle adjusts how one declared resource is planned. Mirrors Terraform's
+// lifecycle meta-argument.
+message Lifecycle {
+ // Required. The resource name the rule applies to.
+ string resource = 1;
+ // Field paths, in JSON name form, that the configuration does not manage.
+ // Apply never writes them after creation and the API guard never protects them.
+ repeated string ignore_changes = 2;
+ // A removed entry cannot destroy the resource while the last apply set this.
+ bool prevent_destroy = 3;
+ // Increment to resend write-only fields such as User.password. Mirrors the
+ // `_wo_version` convention of Terraform write-only arguments.
+ int32 write_only_version = 4;
+}
+
+// Removed takes a resource out of management. Mirrors Terraform's removed block.
+message Removed {
+ // Required. The resource name.
+ string resource = 1;
+ // Delete the resource (or reset a setting group) instead of only releasing it.
+ bool destroy = 2;
+}
+```
+
+The message lives in `proto/api/configuration.proto` next to `Plan`. It is a public API message: `buf breaking`,
+`proto/api/CHANGELOG.md`, and the review-time compatibility check apply to it exactly as to every request and response message.
+
+Example `/etc/memos/config/instance.json`:
+
+```json
+{
+ "identityProviders": [
+ {
+ "name": "identity-providers/company-sso",
+ "type": "OAUTH2",
+ "title": "Company SSO",
+ "config": {
+ "oauth2Config": {
+ "clientId": "memos",
+ "clientSecret": "${env:OIDC_CLIENT_SECRET}",
+ "authUrl": "https://idp.example.com/oauth/authorize",
+ "tokenUrl": "https://idp.example.com/oauth/token",
+ "userInfoUrl": "https://idp.example.com/oauth/userinfo",
+ "scopes": ["openid", "profile", "email"],
+ "fieldMapping": { "identifier": "sub", "displayName": "name", "email": "email" }
+ }
+ }
+ }
+ ],
+ "instanceSettings": [
+ { "name": "instance/settings/ACCESS", "accessSetting": { "accessMode": "INSTANCE_ACCESS_MODE_PRIVATE" } },
+ {
+ "name": "instance/settings/GENERAL",
+ "generalSetting": {
+ "disallowPasswordAuth": true,
+ "disallowUserRegistration": false,
+ "customProfile": { "title": "Company Memos" }
+ }
+ }
+ ],
+ "users": [
+ { "name": "users/admin", "username": "admin", "role": "ADMIN", "password": "${file:/run/secrets/memos-admin-password}" }
+ ],
+ "lifecycle": [
+ { "resource": "users/admin", "preventDestroy": true, "writeOnlyVersion": 1 }
+ ]
+}
+```
+
+### Decoding
+
+Decoding is strict, as `terraform validate` and `kubectl apply --validate=strict` are:
+
+- Unknown fields are errors. They catch misspellings and files written for a newer Memos.
+- Fields marked `deprecated = true` in the proto decode normally and produce one warning per field naming the replacement. The decoder
+ walks the message descriptor for set fields; protojson itself has no deprecation hook.
+- Output-only fields (`create_time`, `update_time`, `avatar_url` and similar) are errors when set, because the configuration cannot
+ manage them.
+- Enum values are accepted by name only; numeric enum values are errors, because numbers are not part of the compatibility promise.
+
+### Value substitution
+
+Before decoding, string values of the form `${env:NAME}` and `${file:/absolute/path}` are replaced by the environment variable or the
+file contents with trailing line breaks removed. A variable set to the empty string is a value, not an error. `$${` escapes a literal `${`. Substitution applies to the whole string value only; a reference embedded in a longer
+string is an error, which keeps the rule simple and keeps secrets from being concatenated into URLs by accident. An unset variable, an
+unreadable file, or a file above 64 KiB is an error that names the reference, never the value.
+
+Substitution is how secrets enter the configuration. The files themselves can then be committed to version control or baked into an
+image with no secret in them, which is the practice both Terraform (`TF_VAR_…`, sensitive variables) and Kubernetes (`valueFrom`) push
+operators toward. Plain secret values in a file remain allowed for deployments that mount the file itself as a secret.
+
+## Resources
+
+Resource identity is the API resource name. It is the plan address, the state record key, and the join key for adoption and for the API
+guard. Renaming a file never changes identity; changing a `name` is a destroy of the old resource and a create of the new one, as in
+Terraform.
+
+Each kind declares what apply writes and what it leaves alone. In Terraform terms, these are the attributes the provider marks
+`Required`, `Optional`, `Optional+Computed`, `Sensitive`, and `WriteOnly`.
+
+### IdentityProvider
+
+| Field | Class |
+| --- | --- |
+| `name` | identity, `identity-providers/{idp}` |
+| `type`, `title`, `identifierFilter`, `config` | managed |
+| `config.oauth2Config.clientSecret` | managed, sensitive |
+
+The resource is managed whole: an omitted field is applied as its protobuf default. The stored client secret is readable through the
+store, so it is compared like any other field, and the plan prints it as `(sensitive)`.
+
+Destroy deletes the provider. Linked identities keep their `provider` value; sign-in through that provider stops until a provider with the
+same name exists again, at which point the links work unchanged. The authentication invariant (below) is checked before a destroy is
+planned.
+
+### InstanceSetting
+
+| Field | Class |
+| --- | --- |
+| `name` | identity, `instance/settings/{setting}` |
+| the `oneof` value matching the key | managed whole |
+| SMTP password, S3 secret, AI API keys | managed, sensitive |
+
+Allowed keys: `ACCESS`, `GENERAL`, `STORAGE`, `MEMO_RELATED`, `NOTIFICATION`, `AI`, `USAGE_LIMITS`. `BASIC` holds the instance secret and
+schema version and is never configurable. `TAGS` is retained only for compatibility and is not configurable.
+
+A setting group is a singleton: it cannot be created or deleted, only updated. Destroy therefore means "reset to the defaults a fresh
+instance would have" (`ACCESS` becomes `PRIVATE`, `STORAGE` becomes local storage, and so on), and the plan prints it as `reset`. Managed
+whole: a field omitted from the file is applied as its protobuf default, so a file is the complete group and never a patch.
+
+Read-time defaults that the store applies to zero values (a default local storage, a default file path template) apply to configured
+values exactly as to values written through the API, because both paths write the same stored message.
+
+### User
+
+| Field | Class |
+| --- | --- |
+| `name` | identity, `users/{user}` |
+| `username` | managed, must equal the `{user}` segment |
+| `role` | managed |
+| `displayName`, `email` | optional: managed only when declared, otherwise left as the user set them |
+| `password` | write-only |
+
+Users are included for one purpose: bringing up an instance without a browser. The user owns their profile, so the configuration manages
+only what it declares. Presence is taken from the JSON document, not from the decoded message, so `"displayName": ""` manages the field as
+empty while omitting it leaves the field alone.
+
+`password` is write-only in the Terraform 1.11 sense: it is never readable, never stored in the state record, never compared, and never
+protected by the API guard, so the administrator can change their own password in the UI. Apply sends it on create and whenever the
+resource's `lifecycle.writeOnlyVersion` is greater than the version recorded in the state record. Resending on every apply would undo a
+password change at every restart; resending only on an explicit version bump is the behavior Terraform standardized on for the same reason.
+
+Configuration never deletes a user. Deleting one deletes their memos and attachment files and must respect the spaces they belong to,
+which is the deletion flow in Settings, with its confirmations. A `removed` entry with `destroy: true` for a user is therefore a plan
+error; `destroy: false` releases the user, who can then be deleted in Settings. `preventDestroy` still guards a user's identity provider
+and settings, and is recommended for every declared user for the day that changes.
+
+## State record
+
+Terraform keeps a state file because the files alone cannot answer three questions: which existing resources are managed, what was removed
+from the files since the last apply, and what was last sent for values that cannot be read back. The same three questions apply here.
+
+The answer is one document, exactly the shape of a Terraform state file: a serial and a list of resources. It is stored as one row of
+`system_setting` under the key `CONFIGURATION_STATE`, the table that already holds the instance's other JSON-encoded state such as `BASIC`.
+Terraform's own `pg` backend stores its state the same way, one document per row. Keeping the record in the database, next to the resources
+it describes, lets apply update both in one transaction, which a state file on disk never can, and lets every replica read it.
+
+```proto
+// proto/store/instance_setting.proto
+
+enum InstanceSettingKey {
+ // ...
+ // CONFIGURATION_STATE is the declarative configuration state record.
+ CONFIGURATION_STATE = 10;
+}
+
+// InstanceConfigurationState is the declarative configuration state record. It is
+// state, not a setting: hidden from the API, never configurable, never a value.
+message InstanceConfigurationState {
+ // Increases by one per apply that changed something.
+ int64 serial = 1;
+ // SHA-256 of the merged document with sensitive and write-only values masked.
+ string config_digest = 2;
+ int64 applied_ts = 3;
+ // "cli" or "startup", followed by the hostname.
+ string applied_by = 4;
+ // The Memos version that applied.
+ string version = 5;
+ repeated ManagedResource resources = 6;
+
+ message ManagedResource {
+ // The API resource name.
+ string name = 1;
+ // "IdentityProvider", "InstanceSetting", or "User".
+ string kind = 2;
+ // The filename the resource was declared in.
+ string source = 3;
+ // JSON-name field paths: ["*"] for whole-resource kinds, the declared
+ // field list for users.
+ repeated string managed_fields = 4;
+ int32 write_only_version = 5;
+ int64 applied_ts = 6;
+ // The lifecycle ignoreChanges paths, which managed_fields covers but apply
+ // does not write after creation and the API guard does not protect.
+ repeated string ignored_fields = 7;
+ // SHA-256 of the declared value last applied, sensitive and write-only
+ // values masked; how a plan tells drift from a file change.
+ string digest = 8;
+ // The lifecycle preventDestroy last applied.
+ bool prevent_destroy = 9;
+ // The resource names the declaration names: the users a usage-limits
+ // setting lists.
+ repeated string references = 10;
+ }
+}
+```
+
+- The row is state, not a setting. The store's setting reads skip its key, the API's setting reads reject it as unsupported,
+ `UpdateInstanceSetting` rejects it, and a file may not declare it.
+- `serial` is the Terraform state serial. Apply reads, and on MySQL and PostgreSQL locks, the record at the start of its transaction
+ and writes it back with `serial + 1` only when the row still holds what it read, inserting it only when it is still absent;
+ serializable isolation makes this the lock, and the conditional write turns any lost update into a retry.
+- `config_digest` identifies a configuration generation in logs and the API without being derivable into a secret. It is informational:
+ plan never uses it to skip work, and a change to it alone, such as deleting a leftover `removed` entry, is not a change to apply.
+- `digest` does per resource what the state record otherwise cannot: it identifies the declared value last applied, so a plan can tell
+ whether a difference comes from the file or from an edit made outside it. A change to a sensitive value alone leaves it unchanged,
+ so such an update reads as drift; it is still applied.
+- `prevent_destroy` is recorded because a `removed` entry can only name a resource no file declares any longer, and so no lifecycle rule
+ can still name it. Destroying a resource that set it takes two applies, as in Terraform: one without `preventDestroy`, then the removal.
+- `managed_fields` and `references` are what the API guard reads, so a replica that never opened the files still enforces ownership.
+- Nothing in the document is a configured value. A database dump exposes which resources are managed and nothing more.
+
+The record is tens of entries and a few kilobytes. It would outgrow one row only with thousands of managed resources, SQL queries over them,
+or several writers updating parts of it independently; none of these exist, and if a later kind crossed that line, the document can be
+split into a table then with a one-off migration that reads the row.
+
+## Plan
+
+Plan reads the desired state, the actual state, and the state record, and produces one action per resource in a deterministic order. It
+never writes. The actions, with their Terraform equivalents:
+
+| Action | Meaning | Terraform |
+| --- | --- | --- |
+| `create` | Declared, absent from database and state record | `+` |
+| `adopt` | Declared, present in database, absent from state record; shown with the field diff that apply will write | `import` block |
+| `update` | Declared and managed; actual differs from desired in a managed field | `~` |
+| `no-op` | Declared and managed; no difference | unchanged |
+| `destroy` | `removed` with `destroy: true` for an identity provider; for a user it is an `error`, see User | `-` |
+| `reset` | `destroy` of a setting group | `-` then `+` |
+| `release` | `removed` with `destroy: false`; state record row removed, database untouched | `removed { destroy = false }` |
+| `error` | Managed, no longer declared, and no `removed` entry | — |
+
+Each `update` lists the changed field paths, in JSON names from the resource such as `generalSetting.customProfile.title`, with old and
+new values; sensitive fields print `(sensitive)` on both sides, and write-only fields print `(write-only, version N)`. An `update` caused
+by drift rather than by a file change is marked `drift`: the resource's declaration has the same `digest` as when it was last applied, so
+the instance changed. A managed resource deleted outside the configuration is a `create` marked `drift`. This is the signal an operator
+needs to find an out-of-band edit.
+
+Both sides are compared as a write would leave them. The declared value is normalized the way a stored write normalizes it, with default
+AI endpoints and the normalized storage registry, so an omitted default is not a perpetual difference. Usage limits name users, so plan
+resolves the names against the database and fails for a user that does not exist. A change only to what the state record holds, such as
+a new lifecycle rule, is still a change: apply writes the record and nothing else.
+
+### Removal is explicit
+
+A managed resource missing from the files is a plan error, not an implicit destroy. Terraform destroys by default and added `removed`
+blocks because implicit destruction of a shared resource is the most common serious mistake; `kubectl apply` prunes only with an explicit
+flag. The configuration is edited by hand, and an accidentally deleted identity-provider block locking every user out of an instance is
+exactly the mistake to make impossible. Declaring the removal is still declarative: the file states the intent, and once applied the entry
+is a no-op that may be deleted.
+
+### Adoption is implicit
+
+A declared resource that already exists is adopted and brought to the desired state. Terraform requires an explicit `import` because a
+cloud account may hold a same-named resource the operator did not intend to manage; here resource names are instance-global and the
+intent of declaring `identity-providers/company-sso` when one exists is unambiguous. The plan shows the adoption and the diff, so nothing
+is hidden.
+
+### Ordering and dependencies
+
+Actions are ordered so every intermediate state is valid even though apply is atomic (the order matters for the plan text and for the
+invariant check): identity provider creates and updates, then instance setting updates and resets, then user creates and updates, then
+identity provider destroys. Within a group, resource names sort lexically.
+
+### Validation
+
+Validation runs in three layers, and the first two are the same code the API uses:
+
+1. Schema: strict decoding, substitution, resource name format, the `oneof` matching the setting key, `username` matching `{user}`.
+2. Resource: the per-resource rules the API applies on create and update, called from one shared package per resource under `core/`
+ (S3 credentials present for an S3 storage, SMTP host and sender present when email is enabled, AI providers have IDs and keys,
+ `ACCESS` mode is explicit, week start offset in range, `defaultStorageId` names a declared storage, storage IDs unique and non-empty,
+ every S3 storage complete). A rule that exists in one path and not the other is a bug, and the shared package is how that is
+ enforced. The packages check the complete value as it will be stored; a write path's own conveniences, such as the API treating an
+ empty secret as "keep the stored one" or generating a missing AI provider ID, run before validation and never inside it. An update
+ does not re-check a storage it leaves unchanged, so a storage stored before a rule existed does not block editing the others; a
+ declared file has no such exemption, since it states the whole value. An OAuth2 provider needs a client ID, absolute HTTP(S)
+ endpoints, and an identifier mapping; a client secret and scopes stay optional because public clients have neither.
+3. Cross-resource: rules that hold over the whole desired state. The one such rule today is the authentication invariant: when the
+ effective `GENERAL` setting disables password sign-in for regular users, at least one identity provider must exist after apply. It is
+ checked against the planned end state, so a plan that both deletes the last provider and leaves password sign-in disabled fails before
+ anything is written.
+
+`memos config validate` runs layer 1 and 2 without a database. `memos config plan` runs all three. Without a database, the users a
+`USAGE_LIMITS` setting names get stand-in IDs for layer 2, since its rules depend only on the list's shape; whether those users exist is
+checked by `plan`.
+
+### Compatibility of files across releases
+
+Because the schema is the public API, a file written for release N decodes under release N+1 unless `proto/api/CHANGELOG.md` says
+otherwise, and a removed field goes through the existing `Deprecated` entry for at least one release before a `Breaking` entry removes it.
+The decoder's deprecation warning is what makes that window useful to operators.
+
+Two mechanisms keep the promise honest:
+
+- `core/configuration/testdata/compat/<release>/` holds the example files from this document as they were at each release, and
+ `testdata/compat/unreleased/` the current ones until a release ships and they are copied to a directory named for its tag. A test decodes
+ every fixture with the current decoder. Removing a field makes the test fail until the fixture is updated in the same change, which
+ forces the `CHANGELOG.md` entry into the same review.
+- The `CHANGELOG.md` template gains one line under `Breaking`: when a field is removed, state that configuration files setting it are
+ rejected from this release and which replacement to write.
+
+## Apply
+
+Apply executes a plan inside one serializable transaction:
+
+1. Open the transaction. Read the state record and its serial.
+2. Compute the plan from the actual state inside the transaction; this is the plan `memos config apply` prints, so what it shows is what
+ it applied even if the instance changed since a separate `plan`. The CLI has no interactive prompt because it runs from automation.
+3. Apply every action through the store's transaction-scoped writes, which keep the store's own rules: a normalized storage registry,
+ normalized email addresses, unique usernames and addresses, and the last active administrator. An `ignoreChanges` path is written
+ with its stored value, and a user gets only the fields the plan lists.
+4. Write the state record with the new managed set and `serial + 1`, conditional on the serial read in step 1.
+5. Commit. A serialization failure or a failed conditional write rolls back and runs the transaction again, up to five attempts with
+ jittered backoff so replicas that start together do not keep colliding; any other error rolls back and fails.
+6. In-process caches for instance settings, users, and storage drivers are reset after commit, and a user whose password apply changed
+ loses every session, as after an administrator's password reset.
+
+A plan with no changes commits nothing and leaves `serial` unchanged.
+
+Atomicity is the main thing this design gets for free that Terraform cannot. There is no partially applied state, no refresh of a half
+world, and no need for a separate lock: serializable isolation plus the serial check is the lock. SQLite gets this from an immediate
+transaction, PostgreSQL from `SERIALIZABLE`, MySQL from `SERIALIZABLE` with `SELECT … FOR UPDATE` on the state row.
+
+### When apply runs
+
+- `memos config apply` from the CLI, against the instance database. This is the canonical path for a deployment pipeline: run it as a job
+ before rolling the replicas, the same place database migration runs. It migrates the database first, exactly as server startup does,
+ so it also bootstraps a fresh instance before its first start.
+- Server startup, controlled by `--config-apply=startup|off` (`MEMOS_CONFIG_APPLY`), default `startup`, and `--config-dir`
+ (`MEMOS_CONFIG_DIR`). The sequence is migrate, seed (demo mode), apply, then construct services. A plan error or apply failure stops startup, as an invalid `nginx.conf` stops nginx; the
+ process never serves with a configuration it could not apply.
+
+`off` is for fleets that apply through the job and want replicas to never touch the files. Replicas started with `off` still read the
+state record, so the API guard works everywhere.
+
+### Multiple replicas
+
+Every replica with `startup` applies at boot. With identical files, the first to commit makes the changes and every later one computes
+an empty plan. Serializable isolation makes a race between two replicas safe: one commits, the other retries and finds nothing to do.
+
+A rolling update can run two configuration generations at once, and the last replica to restart wins. That is inherent to applying from
+each process and is why the job path exists. The state record's `applied_by` and `version` fields and the startup log line make a flapping
+generation visible: the log reports the serial, the digest, the counts per action, and the resource names changed, never values.
+
+Replicas that are already running do not see a setting applied by another process until their setting cache expires (ten minutes), with
+the exception of `ACCESS`, which bypasses the cache. A deployment that changes settings should restart its replicas, which a rollout does
+anyway. The API guard reads the state record from the database on every guarded write, so ownership changes apply on every replica at
+once.
+
+## Ownership and the API
+
+### The guard
+
+A mutation through the API that would change a managed field of a managed resource fails with `FAILED_PRECONDITION` and an
+`google.rpc.ErrorInfo` detail:
+
+```text
+reason: MANAGED_BY_CONFIGURATION
+domain: memos.api
+metadata: resource = identity-providers/company-sso
+ source = instance.json
+ fields = title,config.oauth2Config.scopes
+```
+
+The guard is a rule in `core/configuration` applied by `CreateIdentityProvider`, `UpdateIdentityProvider`, `DeleteIdentityProvider`,
+`UpdateInstanceSetting`, `UpdateUser`, and `DeleteUser`. It makes three checks, each refused with the same error:
+
+- **Change.** `UpdateIdentityProvider`, `UpdateInstanceSetting`, and `UpdateUser` compare the request against the stored resource and
+ refuse only when a managed field would change.
+- **Existence.** `CreateIdentityProvider` refuses a name the configuration manages, so the resource cannot exist twice;
+ `DeleteIdentityProvider` and `DeleteUser` refuse to delete a managed resource.
+- **Reference.** `UpdateUser` refuses a username change and `DeleteUser` a deletion when a managed resource names the user, such as a
+ managed usage-limits setting listing it, though the user is not itself managed: the next plan could not resolve the name, and a
+ startup apply would stop the server. The error names the user, the referring resource in `metadata.referenced_by`, and its file; the
+ operator removes the name there and applies first.
+
+Consequences:
+
+- A whole-group `UpdateInstanceSetting` that resends the managed values unchanged succeeds, so a settings page can save an unrelated field
+ the configuration released with `ignoreChanges`.
+- Write-only fields are never guarded. The administrator changes their password freely.
+- Fields in `ignoreChanges` are never guarded.
+
+Terraform does not enforce ownership; Grafana provisioning does (`allowUiUpdates: false`), and Kubernetes server-side apply reports a
+conflict. Refusing is chosen over tolerate-and-revert because the person at the settings page should learn now, not at the next restart.
+Drift remains possible from direct database edits and backups, and the plan reports it. The guard's read and the API's write are two
+steps, so an apply that starts managing a resource between them lets that one write through; the next plan reports it as drift.
+
+Each update computes what it changes after the API's own conveniences: an empty secret meaning "keep the stored one" is resolved first,
+so resending a form with the secret left blank changes nothing. Usage limits name users only in their API form, so their stored values
+are compared instead.
+
+### Configuration status
+
+Administrators see what is managed through one admin-only `InstanceService` RPC. It is absent from `server/api/acl_config.go`, which
+lists only public methods, so it requires authentication; the handler then requires an administrator. Like `GetInstanceProfile`, it is a
+singleton read at a fixed path with an empty request:
+
+```proto
+service InstanceService {
+ rpc GetConfigurationStatus(GetConfigurationStatusRequest) returns (ConfigurationStatus) {
+ option (google.api.http) = {get: "/api/instance/configuration"};
+ }
+}
+
+message ConfigurationStatus {
+ int64 serial = 1;
+ string config_digest = 2;
+ string applied_by = 3;
+ string version = 4;
+ repeated ManagedResource managed_resources = 5;
+ google.protobuf.Timestamp apply_time = 6;
+
+ message ManagedResource {
+ string resource = 1;
+ string source = 2;
+ repeated string managed_fields = 3;
+ repeated string ignored_fields = 4;
+ }
+}
+```
+
+The response carries names, sources, and field paths; never values.
+
+### Web presentation
+
+The web app reads the status once per session, and only for administrators. Every place that edits a managed resource:
+
+- Shows the existing `InfoChip` reading "Managed by configuration" with the source file, and a tooltip saying to edit the file and apply it.
+ A settings group shows it only when one of its own fields is managed, so a group the configuration releases through `ignoreChanges`
+ carries no chip.
+- Disables the controls for managed fields, each by the JSON-name path it edits, so an ignored path stays editable. Storage locks its
+ registry, default storage, and S3 fields together because the page edits them as one value; usage limits lock as one ordered list.
+- Hides Delete for a managed identity provider or user, and disables Edit for a managed provider. In the user dialog the username and role
+ of a managed user are disabled; the password stays editable because it is write-only.
+
+An administrator-only Configuration section lists the managed resources, their files and managed fields, and the serial and last apply.
+A write refused anyway, from a second tab or a stale page, shows the server's message, which names the file. The labels and disabled
+controls are presentation; the API is the authority.
+
+## CLI
+
+```text
+memos config validate [--config-dir DIR]
+ Decode and validate the files without a database. Exit 0 or 1.
+
+memos config plan [--config-dir DIR] [--json] [--detailed-exitcode]
+ Print the plan. With --detailed-exitcode: 0 no changes, 1 error, 2 changes, matching terraform plan.
+
+memos config apply [--config-dir DIR] [--json]
+ Migrate the database, plan, apply in one transaction, and print the plan applied. Exit 1 on any error; nothing is written on error.
+
+memos config state [--json]
+ Print the state record: managed resources, serial, last apply.
+```
+
+Text plan output follows Terraform's conventions so operators recognise it:
+
+```text
+Plan: 1 to create, 1 to update, 0 to destroy; 1 to adopt.
+
+ + identity-providers/company-sso (instance.json)
+ ~ instance/settings/GENERAL (instance.json) adopt
+ generalSetting.disallowPasswordAuth: false -> true
+ generalSetting.customProfile.title: "memos" -> "Company Memos"
+ ~ users/admin (instance.json) drift
+ role: USER -> ADMIN
+```
+
+The JSON form is the `Plan` message from `configuration.proto`, so a pipeline can gate on it without parsing text. The commands
+that read the database take `--data`, `--driver`, and `--dsn` (or `MEMOS_DATA`, `MEMOS_DRIVER`, `MEMOS_DSN`) as `memos` does, and every
+command uses the same `--config-dir` default and `MEMOS_CONFIG_DIR` variable. `plan` never creates or migrates a database: it fails when
+the SQLite file does not exist or the schema is not the one this binary migrates to.
+
+## Security
+
+- The configuration directory and every file in it may contain secrets and are treated as such; the documentation recommends owner-only
+ permissions and references over inline values.
+- Neither the plan, the logs, the state record, nor `ConfigurationStatus` ever contains a configured value. Sensitive fields are the fields
+ the API already redacts in responses; the engine and the API share that one list.
+- Substitution errors name the reference, not the content; decode errors name the field, not the value.
+- Write-only values are held in memory only for the duration of apply.
+- `GetConfigurationStatus` is admin-only. `memos config` commands need database access and therefore the same trust as the server.
+- A failed apply leaves the database and the state record exactly as they were.
+
+## Database and migration impact
+
+No schema change. The state record is one enum value and one message in `proto/store/instance_setting.proto`. The store runs a
+serializable transaction itself, with retries, through one helper that the authentication mutation now shares. The `Driver` interface
+supplies only what differs by database: the retry classification, and transaction-scoped forms of the setting read and the two
+conditional setting writes.
+
+## Implementation layout
+
+| Path | Holds |
+| --- | --- |
+| `proto/api/configuration.proto` | `Configuration`, `Lifecycle`, `Removed`, `Plan` |
+| `proto/api/instance_service.proto` | `GetConfigurationStatus`, `ConfigurationStatus` |
+| `core/configuration/` | Reading and substituting files, decoding, the plan engine, the digest, the API guard rule |
+| `core/identityprovider/`, `core/instancesetting/`, `core/user/` | Per-resource validation shared by the API and the plan engine; API↔store conversion for identity providers and instance settings, since files are API messages and `core` cannot import `server/api` |
+| `store/configuration_state.go`, `store/transaction.go` | State record read and write; the serializable transaction helper with retries |
+| `server/api/instance_service_configuration.go` | `GetConfigurationStatus`; the guard the six mutating handlers call |
+| `cmd/memos/config.go` | The `memos config` subcommands |
+| `web/src/` | The managed label, disabled controls, and error presentation |
+
+### Delivery
+
+The work starts from zero: the first change removes the previous startup configuration loader, its runtime shadowing of stored
+resources, its API checks, and its design document, so no two configuration models ever coexist. Then eight changes, each shippable alone,
+in the order an operator adopts Terraform: validate, then plan, then apply, then enforcement.
+
+| # | Change | Stands alone because |
+| --- | --- | --- |
+| 0 | Remove the previous loader, shadow reads, API checks, tests, and design document | A deletion with a passing test suite; the instance runs on stored configuration only |
+| 1 | Shared resource validation in `core/identityprovider`, `core/instancesetting`, `core/user`; the API handlers call it | Refactor with tests. New API errors: identity providers are validated (they were stored unchecked, and an omitted `config` or `field_mapping` panicked), every changed S3 storage must be complete, and `BASIC` cannot be written |
+| 2 | `Configuration`, `Lifecycle`, `Removed` protos; reading, substitution, strict decoding; `memos config validate`; first compatibility fixture; the `CHANGELOG.md` template line; API↔store conversion for identity providers and instance settings moved into `core/` | No database, no runtime change; operators can start writing files |
+| 3 | State record message and store access; the serializable transaction helper, which the authentication mutation moves onto | No callers but tests. Independent of 1 and 2 |
+| 4 | Plan engine, text and JSON output, `memos config plan --detailed-exitcode` | Read-only against a real database; the first operational value. Needs 1 to 3 |
+| 5 | Apply, `memos config apply`, `memos config state` | CLI only, opt-in through a job; startup untouched |
+| 6 | The guard in the mutating handlers; `GetConfigurationStatus` | Reads the state record, so it covers CLI-applied resources at once |
+| 7 | `--config-apply` at startup, default `startup` | Startup integration only; everything it calls already exists |
+| 8 | Web presentation: managed label, disabled controls, error display, the Configuration section | Last, after mockups |
+
+Changes 1, 2, and 3 are independent and can proceed in parallel. The smallest useful release point is after 5: validate, plan, and apply
+from a job.
+
+## Test strategy
+
+- Decoding: every kind; unknown, deprecated, output-only, and numeric-enum fields; substitution success, missing reference, embedded
+ reference, escape; duplicate names across files; oversized file; symlink; missing directory.
+- Plan: each action for each kind; adoption diff; drift marking; missing-without-`removed` error; `preventDestroy`; `ignoreChanges`
+ excluded from diff and guard; `writeOnlyVersion` bump resends and no bump does not; ordering; authentication invariant over the end
+ state; determinism (same inputs, byte-identical plan).
+- Apply: idempotence (second apply is empty); atomic failure leaves rows and state record untouched; serial compare-and-set under two
+ concurrent applies on every driver; cache reset; startup sequence and startup failure on an invalid plan.
+- Guard: every guarded RPC refuses a managed-field change and accepts an unmanaged-field change, with the `ErrorInfo` detail; write-only
+ and ignored fields pass.
+- Status RPC: admin-only, no values in the response.
+- Compatibility: fixtures from each release decode; a fixture with a removed field fails the test.
+- Secrets: plan text and JSON, logs, state rows, and the status response contain no configured secret, checked by grepping test output
+ for the planted values.
+
+## Alternatives considered
+
+**Field-level ownership for every kind (Kubernetes server-side apply).** It would let a file manage two fields of a setting group while
+the UI manages the rest. It needs per-field managers, list merge semantics, and a conflict model, and the settings UI edits whole groups.
+Whole-resource ownership with `ignoreChanges` covers the real cases with one concept.
+
+**Dedicated state tables.** A `configuration_run` row and a `configuration_resource` row per managed resource. Queryable by SQL and
+indexed by name, at the cost of two tables in three drivers plus `LATEST.sql`, for a record of tens of entries that is read once per apply
+and cached in process. The single document keeps every property the design needs; the tables can be introduced later if the record
+ever outgrows a row.
+
+**Columns on the resource tables.** A `managed_source` column on `idp`, `system_setting`, and `user`, as Kubernetes keeps `managedFields`
+on each object. More invasive than the tables above, since it alters three existing tables in three drivers, and awkward for singleton
+setting groups.
+
+**A state file in `--data`.** Terraform's literal design. It breaks with several replicas, is not in the same transaction as the resources,
+and diverges from database backups.
+
+**Runtime override without state.** Load files into memory, let them shadow database rows for the process lifetime, write nothing. It
+needs no tables and no plan, but it cannot answer what happens when a file disappears, cannot show an administrator what is managed
+without re-reading files on every replica, has no drift concept, and ties the file format to internal storage messages that have no
+compatibility policy.
+
+**Implicit destroy (Terraform's default).** Rejected for the reasons given under "Removal is explicit".
+
+**Explicit import (Terraform's default).** Rejected for the reasons given under "Adoption is implicit".
+
+**Environment variables.** Fine for a dozen scalars; identity providers, storage registries, and AI provider lists are nested and
+repeated. Substitution gives environment variables their proper role, carrying secrets into a structured document.
+
+**HCL or YAML.** HCL is Terraform's and would need a new parser and a schema mapping; YAML is a superset of JSON and adds a dependency for
+comments and less quoting. Protobuf JSON is already the API's wire format and needs nothing new. YAML remains an open question.
+
+## Open questions
+
+- YAML input alongside JSON.
+- A `PlanConfiguration` RPC so the status page can show drift without shell access; it needs the files on the serving replica.
+- Further kinds once the machinery exists: spaces, user webhooks, personal access tokens for automation.
+- Whether `memos config apply` should refuse to run against a database a newer Memos version has migrated.
+
+## References
+
+- Terraform: [State](https://developer.hashicorp.com/terraform/language/state),
+ [`lifecycle` meta-argument](https://developer.hashicorp.com/terraform/language/meta-arguments/lifecycle),
+ [`import` blocks](https://developer.hashicorp.com/terraform/language/import),
+ [`removed` blocks](https://developer.hashicorp.com/terraform/language/resources/syntax#removing-resources),
+ [write-only arguments](https://developer.hashicorp.com/terraform/language/resources/ephemeral/write-only),
+ [`plan -detailed-exitcode`](https://developer.hashicorp.com/terraform/cli/commands/plan#detailed-exitcode)
+- Kubernetes: [Declarative management with `kubectl apply`](https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/),
+ [Server-side apply and field management](https://kubernetes.io/docs/reference/using-api/server-side-apply/)
+- Argo CD: [Automated sync, prune, and self-heal](https://argo-cd.readthedocs.io/en/stable/user-guide/auto_sync/)
+- Grafana: [Provisioning](https://grafana.com/docs/grafana/latest/administration/provisioning/)
+- Keycloak: [Importing and exporting realms](https://www.keycloak.org/server/importExport)
+- Google AIP: [AIP-122 Resource names](https://google.aip.dev/122), [AIP-193 Errors](https://google.aip.dev/193),
+ [AIP-203 Field behavior](https://google.aip.dev/203)
diff --git a/docs/design/user-usage-limits.md b/docs/design/user-usage-limits.md
index 683463532..48705f0f8 100644
--- a/docs/design/user-usage-limits.md
+++ b/docs/design/user-usage-limits.md
@@ -6,7 +6,7 @@ Date: 2026-10-11, revised 2026-10-14
Existing domain language: [Memos context](../../CONTEXT.md)
-Related: [API Abuse Controls Design](api-abuse-controls.md), [Configuration Provisioning Design](configuration-provisioning.md)
+Related: [API Abuse Controls Design](api-abuse-controls.md)
## Summary
@@ -23,7 +23,6 @@ This revision replaces the first merged shape, which stored one resource per met
- A refused memo save keeps the draft, and its uploaded files, in the editor.
- A user can see their usage and the limits that apply to them.
- An instance with no count or storage limit runs no extra count or sum queries.
-- A deployment can provide the whole setting as a file.
## Non-goals
@@ -75,7 +74,7 @@ message InstanceUsageLimitsSetting {
}
```
-Validation, applied to every stored list whether it comes from the API or a file:
+Validation, applied to every stored list:
- At most 100 entries, and at most 1,000 user IDs across all entries.
- Every entry has at least one user ID or `all_users`, never both.
@@ -85,8 +84,6 @@ Validation, applied to every stored list whether it comes from the API or a file
Reads for checks skip the settings cache, as `ACCESS` does, so a change applies on every replica at the next check. Writes replace the whole row; there is no per-entry write. Entries naming a user that no longer exists are ignored on read and dropped on the next write. User deletion drops the user's ID from every entry; an entry left with no users and no `all_users` is dropped with it.
-**Settings file.** A deployment can provide `memos-instance-setting-usage-limits.json` in the store format. The setting is then read-only through the API.
-
## API
The setting is an ordinary instance setting. `GetInstanceSetting` and `UpdateInstanceSetting` on `instance/settings/USAGE_LIMITS` read and replace it. There are no per-entry calls; the API shape mirrors the store shape, with `users` as `users/{user}` names in place of IDs. The admin-only `usageLimits/{usage_limit}` resource and its five calls from the first merged shape are removed.
diff --git a/proto/api/CHANGELOG.md b/proto/api/CHANGELOG.md
index 461f12e62..51a176a21 100644
--- a/proto/api/CHANGELOG.md
+++ b/proto/api/CHANGELOG.md
@@ -6,12 +6,19 @@ Record schema, REST route, and behavior breaks here. API compatibility is checke
Add entries under a `## Unreleased` heading. After the release ships, rename it to the release tag.
+`IdentityProvider`, `InstanceSetting`, and `User` are also the declarative configuration file format. When a break removes or
+renames a field a configuration file can set, say that files setting it are rejected from this release and what to write
+instead, and update `core/configuration/testdata/compat/` in the same change. After a release ships, copy
+`testdata/compat/unreleased/` to a directory named for the release tag.
+
```markdown
## Unreleased
### Breaking
- `MemoService.ListShortcuts`: removed. Use `UserService.ListMemoViews`.
+- `InstanceSetting.StorageSetting.upload_size_limit_mb`: removed. Configuration files that set `uploadSizeLimitMb` are
+ rejected from this release; set the `UPLOAD_BYTES` usage limit instead.
### Deprecated
@@ -33,8 +40,15 @@ Add entries under a `## Unreleased` heading. After the release ships, rename it
the limit set in effect as `limits` plus `limit_index`. Exceeding a limit returns `RESOURCE_EXHAUSTED` with reason
`QUOTA_EXCEEDED` and metadata `metric`, `limit`, and `usage`.
- `MemoRelatedSetting.enable_double_click_edit` is removed; double-click editing is now a per-browser preference in
- the web client and is no longer an instance setting. `MemoRelatedSetting` keeps the single field `reactions = 1`. A
- deployment config file that still sets `enableDoubleClickEdit` is rejected.
+ the web client and is no longer an instance setting. `MemoRelatedSetting` keeps the single field `reactions = 1`.
+- `CreateIdentityProvider` and `UpdateIdentityProvider` validate the provider as it will be stored and return
+ `INVALID_ARGUMENT` when it has no title, an invalid `identifier_filter`, no `client_id`, a non-absolute or non-HTTP(S)
+ `auth_url`, `token_url`, or `user_info_url`, an empty scope entry, or no `field_mapping.identifier`. A request that
+ omitted `config` or `field_mapping` previously failed with `INTERNAL`.
+- `UpdateInstanceSetting` for `STORAGE` requires every new or changed S3 storage to have `endpoint`, `region`, `bucket`,
+ `access_key_id`, and `access_key_secret` (an empty secret still keeps the stored one). For `GENERAL`,
+ `week_start_day_offset` must be between -1 and 6. `BASIC` cannot be written. Notification validation errors name
+ fields in proto form (`smtp_host`, `use_tls`).
- The API no longer carries a `v1` version marker. Every client must update its paths:
- REST routes move from `/api/v1/...` to `/api/...` (for example `GET /api/memos`). Server-sent events move from
`/api/v1/sse` to `/api/sse`.
diff --git a/proto/api/configuration.proto b/proto/api/configuration.proto
new file mode 100644
index 000000000..b094a3e24
--- /dev/null
+++ b/proto/api/configuration.proto
@@ -0,0 +1,134 @@
+syntax = "proto3";
+
+package memos.api;
+
+import "api/idp_service.proto";
+import "api/instance_service.proto";
+import "api/user_service.proto";
+import "google/api/field_behavior.proto";
+
+option go_package = "gen/api";
+
+// Configuration is one declarative configuration document. Every file in the
+// configuration directory is one Configuration, and all files are merged into
+// one desired state. A resource may be declared in exactly one file.
+message Configuration {
+ // Optional. Identity providers to manage, by resource name.
+ repeated IdentityProvider identity_providers = 1 [(google.api.field_behavior) = OPTIONAL];
+
+ // Optional. Instance setting groups to manage, by resource name.
+ repeated InstanceSetting instance_settings = 2 [(google.api.field_behavior) = OPTIONAL];
+
+ // Optional. Users to manage, by resource name. Intended for bootstrap administrators.
+ repeated User users = 3 [(google.api.field_behavior) = OPTIONAL];
+
+ // Optional. Lifecycle rules for declared resources.
+ repeated Lifecycle lifecycle = 4 [(google.api.field_behavior) = OPTIONAL];
+
+ // Optional. Resources to take out of management.
+ repeated Removed removed = 5 [(google.api.field_behavior) = OPTIONAL];
+}
+
+// Lifecycle adjusts how one declared resource is planned and applied.
+message Lifecycle {
+ // Required. The resource name of a resource declared in the configuration.
+ // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ string resource = 1 [(google.api.field_behavior) = REQUIRED];
+
+ // Optional. Field paths, in JSON name form, that the configuration does not manage.
+ // Apply writes them only when it creates the resource, and the API does not protect them.
+ repeated string ignore_changes = 2 [(google.api.field_behavior) = OPTIONAL];
+
+ // Optional. Plan fails instead of destroying the resource.
+ bool prevent_destroy = 3 [(google.api.field_behavior) = OPTIONAL];
+
+ // Optional. Increment to send write-only fields, such as a user's password, again.
+ int32 write_only_version = 4 [(google.api.field_behavior) = OPTIONAL];
+}
+
+// Removed takes a resource out of management.
+message Removed {
+ // Required. The resource name of a resource the configuration manages.
+ // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ string resource = 1 [(google.api.field_behavior) = REQUIRED];
+
+ // Optional. Delete the resource, or reset an instance setting group to its defaults,
+ // instead of only releasing it from management.
+ bool destroy = 2 [(google.api.field_behavior) = OPTIONAL];
+}
+
+// Plan is the difference between the declarative configuration and the
+// instance: what apply would change. Configured values never appear in it.
+message Plan {
+ // The state record serial the plan was computed against.
+ int64 serial = 1;
+
+ // One entry per resource the configuration declares or manages, in the order apply would act.
+ repeated ResourceChange resource_changes = 2;
+
+ // Whether apply would write the state record. It is true whenever a resource
+ // changes, and also when only what the record holds changes, such as a lifecycle rule.
+ bool state_record_changes = 3;
+
+ // Problems that stop the plan from being applied.
+ repeated string errors = 4;
+
+ // Diagnostics that do not stop the plan.
+ repeated string warnings = 5;
+}
+
+// ResourceChange is what apply would do to one resource.
+message ResourceChange {
+ // The resource name.
+ // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ string resource = 1;
+
+ // The configuration file that declares the resource; empty for one that is no longer declared.
+ string source = 2;
+
+ // What apply would do.
+ Action action = 3;
+
+ // Whether the change undoes an edit made outside the configuration since the last apply.
+ bool drift = 4;
+
+ // The fields apply would write, with their values before and after.
+ repeated FieldChange field_changes = 5;
+
+ // Why the resource has this action, when the action alone does not say.
+ string message = 6;
+
+ // Action is what apply does to a resource.
+ enum Action {
+ ACTION_UNSPECIFIED = 0;
+ // Write a resource that does not exist.
+ CREATE = 1;
+ // Bring an existing resource under management and write the declared value.
+ ADOPT = 2;
+ // Write a managed resource that differs from its declaration.
+ UPDATE = 3;
+ // Nothing; the managed resource matches its declaration.
+ NO_OP = 4;
+ // Delete a managed resource a removed entry destroys.
+ DESTROY = 5;
+ // Reset a managed instance setting a removed entry destroys to its defaults.
+ RESET = 6;
+ // Stop managing a resource and leave it as it is.
+ RELEASE = 7;
+ // None; the resource is managed but no longer declared and has no removed entry.
+ ERROR = 8;
+ }
+}
+
+// FieldChange is one field apply would write.
+message FieldChange {
+ // The field path, in JSON names from the resource, such as config.oauth2Config.scopes.
+ string path = 1;
+
+ // The value before, as JSON. Sensitive values print as (sensitive) and write-only values
+ // as (write-only); an empty string means the resource does not exist yet.
+ string before = 2;
+
+ // The value after, in the same form as before.
+ string after = 3;
+}
diff --git a/proto/api/instance_service.proto b/proto/api/instance_service.proto
index 66dec8589..dc815b8e8 100644
--- a/proto/api/instance_service.proto
+++ b/proto/api/instance_service.proto
@@ -37,8 +37,8 @@ service InstanceService {
};
}
- // UpdateInstanceSetting replaces an instance setting. Admin only. Settings configured by the deployment cannot be
- // updated. Empty write-only credentials keep the stored values.
+ // UpdateInstanceSetting replaces an instance setting. Admin only. Fields declarative configuration manages cannot be
+ // changed. Empty write-only credentials keep the stored values.
rpc UpdateInstanceSetting(UpdateInstanceSettingRequest) returns (InstanceSetting) {
option (google.api.http) = {
patch: "/api/{instance_setting.name=instance/settings/*}"
@@ -59,6 +59,12 @@ service InstanceService {
rpc GetInstanceStats(GetInstanceStatsRequest) returns (InstanceStats) {
option (google.api.http) = {get: "/api/instance/stats"};
}
+
+ // GetConfigurationStatus gets what declarative configuration manages: the managed resources and the last apply.
+ // Admin only. It carries resource names and field paths, never a configured value.
+ rpc GetConfigurationStatus(GetConfigurationStatusRequest) returns (ConfigurationStatus) {
+ option (google.api.http) = {get: "/api/instance/configuration"};
+ }
}
// InstanceAccessMode controls whether unauthenticated users may access instance content.
@@ -562,3 +568,43 @@ message InstanceStats {
// Request message for InstanceService.GetInstanceStats.
message GetInstanceStatsRequest {}
+
+// Request message for InstanceService.GetConfigurationStatus.
+message GetConfigurationStatusRequest {}
+
+// ConfigurationStatus is what declarative configuration manages on the instance.
+message ConfigurationStatus {
+ // The state record serial; zero before any apply has changed something.
+ int64 serial = 1;
+
+ // Identifies the applied configuration, with sensitive values masked before hashing.
+ string config_digest = 2;
+
+ // The apply path ("cli" or "startup") and the host of the last apply.
+ string applied_by = 3;
+
+ // The Memos version of the last apply.
+ string version = 4;
+
+ // The resources the configuration manages.
+ repeated ManagedResource managed_resources = 5;
+
+ // When the last apply that changed something ran.
+ google.protobuf.Timestamp apply_time = 6;
+
+ // ManagedResource is one resource the configuration manages.
+ message ManagedResource {
+ // The resource name.
+ // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ string resource = 1;
+
+ // The configuration file that declares the resource.
+ string source = 2;
+
+ // The field paths, in JSON names, the configuration manages; "*" means the whole resource.
+ repeated string managed_fields = 3;
+
+ // The managed field paths the configuration does not write after creation, so the API accepts edits to them.
+ repeated string ignored_fields = 4;
+ }
+}
diff --git a/proto/gen/api/apiconnect/instance_service.connect.go b/proto/gen/api/apiconnect/instance_service.connect.go
index 0bc173a52..6ca0826e2 100644
--- a/proto/gen/api/apiconnect/instance_service.connect.go
+++ b/proto/gen/api/apiconnect/instance_service.connect.go
@@ -52,6 +52,9 @@ const (
// InstanceServiceGetInstanceStatsProcedure is the fully-qualified name of the InstanceService's
// GetInstanceStats RPC.
InstanceServiceGetInstanceStatsProcedure = "/memos.api.InstanceService/GetInstanceStats"
+ // InstanceServiceGetConfigurationStatusProcedure is the fully-qualified name of the
+ // InstanceService's GetConfigurationStatus RPC.
+ InstanceServiceGetConfigurationStatusProcedure = "/memos.api.InstanceService/GetConfigurationStatus"
)
// InstanceServiceClient is a client for the memos.api.InstanceService service.
@@ -64,13 +67,16 @@ type InstanceServiceClient interface {
// BatchGetInstanceSettings gets up to 100 instance settings in request order, with the same access rules as
// GetInstanceSetting. The call fails if any setting cannot be returned.
BatchGetInstanceSettings(context.Context, *connect.Request[api.BatchGetInstanceSettingsRequest]) (*connect.Response[api.BatchGetInstanceSettingsResponse], error)
- // UpdateInstanceSetting replaces an instance setting. Admin only. Settings configured by the deployment cannot be
- // updated. Empty write-only credentials keep the stored values.
+ // UpdateInstanceSetting replaces an instance setting. Admin only. Fields declarative configuration manages cannot be
+ // changed. Empty write-only credentials keep the stored values.
UpdateInstanceSetting(context.Context, *connect.Request[api.UpdateInstanceSettingRequest]) (*connect.Response[api.InstanceSetting], error)
// TestInstanceEmailSetting sends a test email with the provided or stored SMTP settings. Admin only.
TestInstanceEmailSetting(context.Context, *connect.Request[api.TestInstanceEmailSettingRequest]) (*connect.Response[emptypb.Empty], error)
// GetInstanceStats gets resource usage statistics for the instance. Admin only. Results are cached for 60 seconds.
GetInstanceStats(context.Context, *connect.Request[api.GetInstanceStatsRequest]) (*connect.Response[api.InstanceStats], error)
+ // GetConfigurationStatus gets what declarative configuration manages: the managed resources and the last apply.
+ // Admin only. It carries resource names and field paths, never a configured value.
+ GetConfigurationStatus(context.Context, *connect.Request[api.GetConfigurationStatusRequest]) (*connect.Response[api.ConfigurationStatus], error)
}
// NewInstanceServiceClient constructs a client for the memos.api.InstanceService service. By
@@ -120,6 +126,12 @@ func NewInstanceServiceClient(httpClient connect.HTTPClient, baseURL string, opt
connect.WithSchema(instanceServiceMethods.ByName("GetInstanceStats")),
connect.WithClientOptions(opts...),
),
+ getConfigurationStatus: connect.NewClient[api.GetConfigurationStatusRequest, api.ConfigurationStatus](
+ httpClient,
+ baseURL+InstanceServiceGetConfigurationStatusProcedure,
+ connect.WithSchema(instanceServiceMethods.ByName("GetConfigurationStatus")),
+ connect.WithClientOptions(opts...),
+ ),
}
}
@@ -131,6 +143,7 @@ type instanceServiceClient struct {
updateInstanceSetting *connect.Client[api.UpdateInstanceSettingRequest, api.InstanceSetting]
testInstanceEmailSetting *connect.Client[api.TestInstanceEmailSettingRequest, emptypb.Empty]
getInstanceStats *connect.Client[api.GetInstanceStatsRequest, api.InstanceStats]
+ getConfigurationStatus *connect.Client[api.GetConfigurationStatusRequest, api.ConfigurationStatus]
}
// GetInstanceProfile calls memos.api.InstanceService.GetInstanceProfile.
@@ -163,6 +176,11 @@ func (c *instanceServiceClient) GetInstanceStats(ctx context.Context, req *conne
return c.getInstanceStats.CallUnary(ctx, req)
}
+// GetConfigurationStatus calls memos.api.InstanceService.GetConfigurationStatus.
+func (c *instanceServiceClient) GetConfigurationStatus(ctx context.Context, req *connect.Request[api.GetConfigurationStatusRequest]) (*connect.Response[api.ConfigurationStatus], error) {
+ return c.getConfigurationStatus.CallUnary(ctx, req)
+}
+
// InstanceServiceHandler is an implementation of the memos.api.InstanceService service.
type InstanceServiceHandler interface {
// GetInstanceProfile gets the instance profile. Available without authentication, including on a private instance.
@@ -173,13 +191,16 @@ type InstanceServiceHandler interface {
// BatchGetInstanceSettings gets up to 100 instance settings in request order, with the same access rules as
// GetInstanceSetting. The call fails if any setting cannot be returned.
BatchGetInstanceSettings(context.Context, *connect.Request[api.BatchGetInstanceSettingsRequest]) (*connect.Response[api.BatchGetInstanceSettingsResponse], error)
- // UpdateInstanceSetting replaces an instance setting. Admin only. Settings configured by the deployment cannot be
- // updated. Empty write-only credentials keep the stored values.
+ // UpdateInstanceSetting replaces an instance setting. Admin only. Fields declarative configuration manages cannot be
+ // changed. Empty write-only credentials keep the stored values.
UpdateInstanceSetting(context.Context, *connect.Request[api.UpdateInstanceSettingRequest]) (*connect.Response[api.InstanceSetting], error)
// TestInstanceEmailSetting sends a test email with the provided or stored SMTP settings. Admin only.
TestInstanceEmailSetting(context.Context, *connect.Request[api.TestInstanceEmailSettingRequest]) (*connect.Response[emptypb.Empty], error)
// GetInstanceStats gets resource usage statistics for the instance. Admin only. Results are cached for 60 seconds.
GetInstanceStats(context.Context, *connect.Request[api.GetInstanceStatsRequest]) (*connect.Response[api.InstanceStats], error)
+ // GetConfigurationStatus gets what declarative configuration manages: the managed resources and the last apply.
+ // Admin only. It carries resource names and field paths, never a configured value.
+ GetConfigurationStatus(context.Context, *connect.Request[api.GetConfigurationStatusRequest]) (*connect.Response[api.ConfigurationStatus], error)
}
// NewInstanceServiceHandler builds an HTTP handler from the service implementation. It returns the
@@ -225,6 +246,12 @@ func NewInstanceServiceHandler(svc InstanceServiceHandler, opts ...connect.Handl
connect.WithSchema(instanceServiceMethods.ByName("GetInstanceStats")),
connect.WithHandlerOptions(opts...),
)
+ instanceServiceGetConfigurationStatusHandler := connect.NewUnaryHandler(
+ InstanceServiceGetConfigurationStatusProcedure,
+ svc.GetConfigurationStatus,
+ connect.WithSchema(instanceServiceMethods.ByName("GetConfigurationStatus")),
+ connect.WithHandlerOptions(opts...),
+ )
return "/memos.api.InstanceService/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case InstanceServiceGetInstanceProfileProcedure:
@@ -239,6 +266,8 @@ func NewInstanceServiceHandler(svc InstanceServiceHandler, opts ...connect.Handl
instanceServiceTestInstanceEmailSettingHandler.ServeHTTP(w, r)
case InstanceServiceGetInstanceStatsProcedure:
instanceServiceGetInstanceStatsHandler.ServeHTTP(w, r)
+ case InstanceServiceGetConfigurationStatusProcedure:
+ instanceServiceGetConfigurationStatusHandler.ServeHTTP(w, r)
default:
http.NotFound(w, r)
}
@@ -271,3 +300,7 @@ func (UnimplementedInstanceServiceHandler) TestInstanceEmailSetting(context.Cont
func (UnimplementedInstanceServiceHandler) GetInstanceStats(context.Context, *connect.Request[api.GetInstanceStatsRequest]) (*connect.Response[api.InstanceStats], error) {
return nil, connect.NewError(connect.CodeUnimplemented, errors.New("memos.api.InstanceService.GetInstanceStats is not implemented"))
}
+
+func (UnimplementedInstanceServiceHandler) GetConfigurationStatus(context.Context, *connect.Request[api.GetConfigurationStatusRequest]) (*connect.Response[api.ConfigurationStatus], error) {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("memos.api.InstanceService.GetConfigurationStatus is not implemented"))
+}
diff --git a/proto/gen/api/configuration.pb.go b/proto/gen/api/configuration.pb.go
new file mode 100644
index 000000000..796423877
--- /dev/null
+++ b/proto/gen/api/configuration.pb.go
@@ -0,0 +1,677 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.36.12
+// protoc (unknown)
+// source: api/configuration.proto
+
+package api
+
+import (
+ _ "google.golang.org/genproto/googleapis/api/annotations"
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ reflect "reflect"
+ sync "sync"
+ unsafe "unsafe"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+// Action is what apply does to a resource.
+type ResourceChange_Action int32
+
+const (
+ ResourceChange_ACTION_UNSPECIFIED ResourceChange_Action = 0
+ // Write a resource that does not exist.
+ ResourceChange_CREATE ResourceChange_Action = 1
+ // Bring an existing resource under management and write the declared value.
+ ResourceChange_ADOPT ResourceChange_Action = 2
+ // Write a managed resource that differs from its declaration.
+ ResourceChange_UPDATE ResourceChange_Action = 3
+ // Nothing; the managed resource matches its declaration.
+ ResourceChange_NO_OP ResourceChange_Action = 4
+ // Delete a managed resource a removed entry destroys.
+ ResourceChange_DESTROY ResourceChange_Action = 5
+ // Reset a managed instance setting a removed entry destroys to its defaults.
+ ResourceChange_RESET ResourceChange_Action = 6
+ // Stop managing a resource and leave it as it is.
+ ResourceChange_RELEASE ResourceChange_Action = 7
+ // None; the resource is managed but no longer declared and has no removed entry.
+ ResourceChange_ERROR ResourceChange_Action = 8
+)
+
+// Enum value maps for ResourceChange_Action.
+var (
+ ResourceChange_Action_name = map[int32]string{
+ 0: "ACTION_UNSPECIFIED",
+ 1: "CREATE",
+ 2: "ADOPT",
+ 3: "UPDATE",
+ 4: "NO_OP",
+ 5: "DESTROY",
+ 6: "RESET",
+ 7: "RELEASE",
+ 8: "ERROR",
+ }
+ ResourceChange_Action_value = map[string]int32{
+ "ACTION_UNSPECIFIED": 0,
+ "CREATE": 1,
+ "ADOPT": 2,
+ "UPDATE": 3,
+ "NO_OP": 4,
+ "DESTROY": 5,
+ "RESET": 6,
+ "RELEASE": 7,
+ "ERROR": 8,
+ }
+)
+
+func (x ResourceChange_Action) Enum() *ResourceChange_Action {
+ p := new(ResourceChange_Action)
+ *p = x
+ return p
+}
+
+func (x ResourceChange_Action) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (ResourceChange_Action) Descriptor() protoreflect.EnumDescriptor {
+ return file_api_configuration_proto_enumTypes[0].Descriptor()
+}
+
+func (ResourceChange_Action) Type() protoreflect.EnumType {
+ return &file_api_configuration_proto_enumTypes[0]
+}
+
+func (x ResourceChange_Action) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use ResourceChange_Action.Descriptor instead.
+func (ResourceChange_Action) EnumDescriptor() ([]byte, []int) {
+ return file_api_configuration_proto_rawDescGZIP(), []int{4, 0}
+}
+
+// Configuration is one declarative configuration document. Every file in the
+// configuration directory is one Configuration, and all files are merged into
+// one desired state. A resource may be declared in exactly one file.
+type Configuration struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Optional. Identity providers to manage, by resource name.
+ IdentityProviders []*IdentityProvider `protobuf:"bytes,1,rep,name=identity_providers,json=identityProviders,proto3" json:"identity_providers,omitempty"`
+ // Optional. Instance setting groups to manage, by resource name.
+ InstanceSettings []*InstanceSetting `protobuf:"bytes,2,rep,name=instance_settings,json=instanceSettings,proto3" json:"instance_settings,omitempty"`
+ // Optional. Users to manage, by resource name. Intended for bootstrap administrators.
+ Users []*User `protobuf:"bytes,3,rep,name=users,proto3" json:"users,omitempty"`
+ // Optional. Lifecycle rules for declared resources.
+ Lifecycle []*Lifecycle `protobuf:"bytes,4,rep,name=lifecycle,proto3" json:"lifecycle,omitempty"`
+ // Optional. Resources to take out of management.
+ Removed []*Removed `protobuf:"bytes,5,rep,name=removed,proto3" json:"removed,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *Configuration) Reset() {
+ *x = Configuration{}
+ mi := &file_api_configuration_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *Configuration) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Configuration) ProtoMessage() {}
+
+func (x *Configuration) ProtoReflect() protoreflect.Message {
+ mi := &file_api_configuration_proto_msgTypes[0]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use Configuration.ProtoReflect.Descriptor instead.
+func (*Configuration) Descriptor() ([]byte, []int) {
+ return file_api_configuration_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *Configuration) GetIdentityProviders() []*IdentityProvider {
+ if x != nil {
+ return x.IdentityProviders
+ }
+ return nil
+}
+
+func (x *Configuration) GetInstanceSettings() []*InstanceSetting {
+ if x != nil {
+ return x.InstanceSettings
+ }
+ return nil
+}
+
+func (x *Configuration) GetUsers() []*User {
+ if x != nil {
+ return x.Users
+ }
+ return nil
+}
+
+func (x *Configuration) GetLifecycle() []*Lifecycle {
+ if x != nil {
+ return x.Lifecycle
+ }
+ return nil
+}
+
+func (x *Configuration) GetRemoved() []*Removed {
+ if x != nil {
+ return x.Removed
+ }
+ return nil
+}
+
+// Lifecycle adjusts how one declared resource is planned and applied.
+type Lifecycle struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Required. The resource name of a resource declared in the configuration.
+ // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
+ // Optional. Field paths, in JSON name form, that the configuration does not manage.
+ // Apply writes them only when it creates the resource, and the API does not protect them.
+ IgnoreChanges []string `protobuf:"bytes,2,rep,name=ignore_changes,json=ignoreChanges,proto3" json:"ignore_changes,omitempty"`
+ // Optional. Plan fails instead of destroying the resource.
+ PreventDestroy bool `protobuf:"varint,3,opt,name=prevent_destroy,json=preventDestroy,proto3" json:"prevent_destroy,omitempty"`
+ // Optional. Increment to send write-only fields, such as a user's password, again.
+ WriteOnlyVersion int32 `protobuf:"varint,4,opt,name=write_only_version,json=writeOnlyVersion,proto3" json:"write_only_version,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *Lifecycle) Reset() {
+ *x = Lifecycle{}
+ mi := &file_api_configuration_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *Lifecycle) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Lifecycle) ProtoMessage() {}
+
+func (x *Lifecycle) ProtoReflect() protoreflect.Message {
+ mi := &file_api_configuration_proto_msgTypes[1]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use Lifecycle.ProtoReflect.Descriptor instead.
+func (*Lifecycle) Descriptor() ([]byte, []int) {
+ return file_api_configuration_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *Lifecycle) GetResource() string {
+ if x != nil {
+ return x.Resource
+ }
+ return ""
+}
+
+func (x *Lifecycle) GetIgnoreChanges() []string {
+ if x != nil {
+ return x.IgnoreChanges
+ }
+ return nil
+}
+
+func (x *Lifecycle) GetPreventDestroy() bool {
+ if x != nil {
+ return x.PreventDestroy
+ }
+ return false
+}
+
+func (x *Lifecycle) GetWriteOnlyVersion() int32 {
+ if x != nil {
+ return x.WriteOnlyVersion
+ }
+ return 0
+}
+
+// Removed takes a resource out of management.
+type Removed struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Required. The resource name of a resource the configuration manages.
+ // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
+ // Optional. Delete the resource, or reset an instance setting group to its defaults,
+ // instead of only releasing it from management.
+ Destroy bool `protobuf:"varint,2,opt,name=destroy,proto3" json:"destroy,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *Removed) Reset() {
+ *x = Removed{}
+ mi := &file_api_configuration_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *Removed) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Removed) ProtoMessage() {}
+
+func (x *Removed) ProtoReflect() protoreflect.Message {
+ mi := &file_api_configuration_proto_msgTypes[2]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use Removed.ProtoReflect.Descriptor instead.
+func (*Removed) Descriptor() ([]byte, []int) {
+ return file_api_configuration_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *Removed) GetResource() string {
+ if x != nil {
+ return x.Resource
+ }
+ return ""
+}
+
+func (x *Removed) GetDestroy() bool {
+ if x != nil {
+ return x.Destroy
+ }
+ return false
+}
+
+// Plan is the difference between the declarative configuration and the
+// instance: what apply would change. Configured values never appear in it.
+type Plan struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The state record serial the plan was computed against.
+ Serial int64 `protobuf:"varint,1,opt,name=serial,proto3" json:"serial,omitempty"`
+ // One entry per resource the configuration declares or manages, in the order apply would act.
+ ResourceChanges []*ResourceChange `protobuf:"bytes,2,rep,name=resource_changes,json=resourceChanges,proto3" json:"resource_changes,omitempty"`
+ // Whether apply would write the state record. It is true whenever a resource
+ // changes, and also when only what the record holds changes, such as a lifecycle rule.
+ StateRecordChanges bool `protobuf:"varint,3,opt,name=state_record_changes,json=stateRecordChanges,proto3" json:"state_record_changes,omitempty"`
+ // Problems that stop the plan from being applied.
+ Errors []string `protobuf:"bytes,4,rep,name=errors,proto3" json:"errors,omitempty"`
+ // Diagnostics that do not stop the plan.
+ Warnings []string `protobuf:"bytes,5,rep,name=warnings,proto3" json:"warnings,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *Plan) Reset() {
+ *x = Plan{}
+ mi := &file_api_configuration_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *Plan) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Plan) ProtoMessage() {}
+
+func (x *Plan) ProtoReflect() protoreflect.Message {
+ mi := &file_api_configuration_proto_msgTypes[3]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use Plan.ProtoReflect.Descriptor instead.
+func (*Plan) Descriptor() ([]byte, []int) {
+ return file_api_configuration_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *Plan) GetSerial() int64 {
+ if x != nil {
+ return x.Serial
+ }
+ return 0
+}
+
+func (x *Plan) GetResourceChanges() []*ResourceChange {
+ if x != nil {
+ return x.ResourceChanges
+ }
+ return nil
+}
+
+func (x *Plan) GetStateRecordChanges() bool {
+ if x != nil {
+ return x.StateRecordChanges
+ }
+ return false
+}
+
+func (x *Plan) GetErrors() []string {
+ if x != nil {
+ return x.Errors
+ }
+ return nil
+}
+
+func (x *Plan) GetWarnings() []string {
+ if x != nil {
+ return x.Warnings
+ }
+ return nil
+}
+
+// ResourceChange is what apply would do to one resource.
+type ResourceChange struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The resource name.
+ // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
+ // The configuration file that declares the resource; empty for one that is no longer declared.
+ Source string `protobuf:"bytes,2,opt,name=source,proto3" json:"source,omitempty"`
+ // What apply would do.
+ Action ResourceChange_Action `protobuf:"varint,3,opt,name=action,proto3,enum=memos.api.ResourceChange_Action" json:"action,omitempty"`
+ // Whether the change undoes an edit made outside the configuration since the last apply.
+ Drift bool `protobuf:"varint,4,opt,name=drift,proto3" json:"drift,omitempty"`
+ // The fields apply would write, with their values before and after.
+ FieldChanges []*FieldChange `protobuf:"bytes,5,rep,name=field_changes,json=fieldChanges,proto3" json:"field_changes,omitempty"`
+ // Why the resource has this action, when the action alone does not say.
+ Message string `protobuf:"bytes,6,opt,name=message,proto3" json:"message,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ResourceChange) Reset() {
+ *x = ResourceChange{}
+ mi := &file_api_configuration_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ResourceChange) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ResourceChange) ProtoMessage() {}
+
+func (x *ResourceChange) ProtoReflect() protoreflect.Message {
+ mi := &file_api_configuration_proto_msgTypes[4]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ResourceChange.ProtoReflect.Descriptor instead.
+func (*ResourceChange) Descriptor() ([]byte, []int) {
+ return file_api_configuration_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *ResourceChange) GetResource() string {
+ if x != nil {
+ return x.Resource
+ }
+ return ""
+}
+
+func (x *ResourceChange) GetSource() string {
+ if x != nil {
+ return x.Source
+ }
+ return ""
+}
+
+func (x *ResourceChange) GetAction() ResourceChange_Action {
+ if x != nil {
+ return x.Action
+ }
+ return ResourceChange_ACTION_UNSPECIFIED
+}
+
+func (x *ResourceChange) GetDrift() bool {
+ if x != nil {
+ return x.Drift
+ }
+ return false
+}
+
+func (x *ResourceChange) GetFieldChanges() []*FieldChange {
+ if x != nil {
+ return x.FieldChanges
+ }
+ return nil
+}
+
+func (x *ResourceChange) GetMessage() string {
+ if x != nil {
+ return x.Message
+ }
+ return ""
+}
+
+// FieldChange is one field apply would write.
+type FieldChange struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The field path, in JSON names from the resource, such as config.oauth2Config.scopes.
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ // The value before, as JSON. Sensitive values print as (sensitive) and write-only values
+ // as (write-only); an empty string means the resource does not exist yet.
+ Before string `protobuf:"bytes,2,opt,name=before,proto3" json:"before,omitempty"`
+ // The value after, in the same form as before.
+ After string `protobuf:"bytes,3,opt,name=after,proto3" json:"after,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *FieldChange) Reset() {
+ *x = FieldChange{}
+ mi := &file_api_configuration_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *FieldChange) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*FieldChange) ProtoMessage() {}
+
+func (x *FieldChange) ProtoReflect() protoreflect.Message {
+ mi := &file_api_configuration_proto_msgTypes[5]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use FieldChange.ProtoReflect.Descriptor instead.
+func (*FieldChange) Descriptor() ([]byte, []int) {
+ return file_api_configuration_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *FieldChange) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+func (x *FieldChange) GetBefore() string {
+ if x != nil {
+ return x.Before
+ }
+ return ""
+}
+
+func (x *FieldChange) GetAfter() string {
+ if x != nil {
+ return x.After
+ }
+ return ""
+}
+
+var File_api_configuration_proto protoreflect.FileDescriptor
+
+const file_api_configuration_proto_rawDesc = "" +
+ "\n" +
+ "\x17api/configuration.proto\x12\tmemos.api\x1a\x15api/idp_service.proto\x1a\x1aapi/instance_service.proto\x1a\x16api/user_service.proto\x1a\x1fgoogle/api/field_behavior.proto\"\xc6\x02\n" +
+ "\rConfiguration\x12O\n" +
+ "\x12identity_providers\x18\x01 \x03(\v2\x1b.memos.api.IdentityProviderB\x03\xe0A\x01R\x11identityProviders\x12L\n" +
+ "\x11instance_settings\x18\x02 \x03(\v2\x1a.memos.api.InstanceSettingB\x03\xe0A\x01R\x10instanceSettings\x12*\n" +
+ "\x05users\x18\x03 \x03(\v2\x0f.memos.api.UserB\x03\xe0A\x01R\x05users\x127\n" +
+ "\tlifecycle\x18\x04 \x03(\v2\x14.memos.api.LifecycleB\x03\xe0A\x01R\tlifecycle\x121\n" +
+ "\aremoved\x18\x05 \x03(\v2\x12.memos.api.RemovedB\x03\xe0A\x01R\aremoved\"\xb9\x01\n" +
+ "\tLifecycle\x12\x1f\n" +
+ "\bresource\x18\x01 \x01(\tB\x03\xe0A\x02R\bresource\x12*\n" +
+ "\x0eignore_changes\x18\x02 \x03(\tB\x03\xe0A\x01R\rignoreChanges\x12,\n" +
+ "\x0fprevent_destroy\x18\x03 \x01(\bB\x03\xe0A\x01R\x0epreventDestroy\x121\n" +
+ "\x12write_only_version\x18\x04 \x01(\x05B\x03\xe0A\x01R\x10writeOnlyVersion\"I\n" +
+ "\aRemoved\x12\x1f\n" +
+ "\bresource\x18\x01 \x01(\tB\x03\xe0A\x02R\bresource\x12\x1d\n" +
+ "\adestroy\x18\x02 \x01(\bB\x03\xe0A\x01R\adestroy\"\xca\x01\n" +
+ "\x04Plan\x12\x16\n" +
+ "\x06serial\x18\x01 \x01(\x03R\x06serial\x12D\n" +
+ "\x10resource_changes\x18\x02 \x03(\v2\x19.memos.api.ResourceChangeR\x0fresourceChanges\x120\n" +
+ "\x14state_record_changes\x18\x03 \x01(\bR\x12stateRecordChanges\x12\x16\n" +
+ "\x06errors\x18\x04 \x03(\tR\x06errors\x12\x1a\n" +
+ "\bwarnings\x18\x05 \x03(\tR\bwarnings\"\xeb\x02\n" +
+ "\x0eResourceChange\x12\x1a\n" +
+ "\bresource\x18\x01 \x01(\tR\bresource\x12\x16\n" +
+ "\x06source\x18\x02 \x01(\tR\x06source\x128\n" +
+ "\x06action\x18\x03 \x01(\x0e2 .memos.api.ResourceChange.ActionR\x06action\x12\x14\n" +
+ "\x05drift\x18\x04 \x01(\bR\x05drift\x12;\n" +
+ "\rfield_changes\x18\x05 \x03(\v2\x16.memos.api.FieldChangeR\ffieldChanges\x12\x18\n" +
+ "\amessage\x18\x06 \x01(\tR\amessage\"~\n" +
+ "\x06Action\x12\x16\n" +
+ "\x12ACTION_UNSPECIFIED\x10\x00\x12\n" +
+ "\n" +
+ "\x06CREATE\x10\x01\x12\t\n" +
+ "\x05ADOPT\x10\x02\x12\n" +
+ "\n" +
+ "\x06UPDATE\x10\x03\x12\t\n" +
+ "\x05NO_OP\x10\x04\x12\v\n" +
+ "\aDESTROY\x10\x05\x12\t\n" +
+ "\x05RESET\x10\x06\x12\v\n" +
+ "\aRELEASE\x10\a\x12\t\n" +
+ "\x05ERROR\x10\b\"O\n" +
+ "\vFieldChange\x12\x12\n" +
+ "\x04path\x18\x01 \x01(\tR\x04path\x12\x16\n" +
+ "\x06before\x18\x02 \x01(\tR\x06before\x12\x14\n" +
+ "\x05after\x18\x03 \x01(\tR\x05afterB\x91\x01\n" +
+ "\rcom.memos.apiB\x12ConfigurationProtoP\x01Z'github.com/usememos/memos/proto/gen/api\xa2\x02\x03MAX\xaa\x02\tMemos.Api\xca\x02\tMemos\\Api\xe2\x02\x15Memos\\Api\\GPBMetadata\xea\x02\n" +
+ "Memos::Apib\x06proto3"
+
+var (
+ file_api_configuration_proto_rawDescOnce sync.Once
+ file_api_configuration_proto_rawDescData []byte
+)
+
+func file_api_configuration_proto_rawDescGZIP() []byte {
+ file_api_configuration_proto_rawDescOnce.Do(func() {
+ file_api_configuration_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_api_configuration_proto_rawDesc), len(file_api_configuration_proto_rawDesc)))
+ })
+ return file_api_configuration_proto_rawDescData
+}
+
+var file_api_configuration_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
+var file_api_configuration_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
+var file_api_configuration_proto_goTypes = []any{
+ (ResourceChange_Action)(0), // 0: memos.api.ResourceChange.Action
+ (*Configuration)(nil), // 1: memos.api.Configuration
+ (*Lifecycle)(nil), // 2: memos.api.Lifecycle
+ (*Removed)(nil), // 3: memos.api.Removed
+ (*Plan)(nil), // 4: memos.api.Plan
+ (*ResourceChange)(nil), // 5: memos.api.ResourceChange
+ (*FieldChange)(nil), // 6: memos.api.FieldChange
+ (*IdentityProvider)(nil), // 7: memos.api.IdentityProvider
+ (*InstanceSetting)(nil), // 8: memos.api.InstanceSetting
+ (*User)(nil), // 9: memos.api.User
+}
+var file_api_configuration_proto_depIdxs = []int32{
+ 7, // 0: memos.api.Configuration.identity_providers:type_name -> memos.api.IdentityProvider
+ 8, // 1: memos.api.Configuration.instance_settings:type_name -> memos.api.InstanceSetting
+ 9, // 2: memos.api.Configuration.users:type_name -> memos.api.User
+ 2, // 3: memos.api.Configuration.lifecycle:type_name -> memos.api.Lifecycle
+ 3, // 4: memos.api.Configuration.removed:type_name -> memos.api.Removed
+ 5, // 5: memos.api.Plan.resource_changes:type_name -> memos.api.ResourceChange
+ 0, // 6: memos.api.ResourceChange.action:type_name -> memos.api.ResourceChange.Action
+ 6, // 7: memos.api.ResourceChange.field_changes:type_name -> memos.api.FieldChange
+ 8, // [8:8] is the sub-list for method output_type
+ 8, // [8:8] is the sub-list for method input_type
+ 8, // [8:8] is the sub-list for extension type_name
+ 8, // [8:8] is the sub-list for extension extendee
+ 0, // [0:8] is the sub-list for field type_name
+}
+
+func init() { file_api_configuration_proto_init() }
+func file_api_configuration_proto_init() {
+ if File_api_configuration_proto != nil {
+ return
+ }
+ file_api_idp_service_proto_init()
+ file_api_instance_service_proto_init()
+ file_api_user_service_proto_init()
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_configuration_proto_rawDesc), len(file_api_configuration_proto_rawDesc)),
+ NumEnums: 1,
+ NumMessages: 6,
+ NumExtensions: 0,
+ NumServices: 0,
+ },
+ GoTypes: file_api_configuration_proto_goTypes,
+ DependencyIndexes: file_api_configuration_proto_depIdxs,
+ EnumInfos: file_api_configuration_proto_enumTypes,
+ MessageInfos: file_api_configuration_proto_msgTypes,
+ }.Build()
+ File_api_configuration_proto = out.File
+ file_api_configuration_proto_goTypes = nil
+ file_api_configuration_proto_depIdxs = nil
+}
diff --git a/proto/gen/api/instance_service.pb.go b/proto/gen/api/instance_service.pb.go
index 4c6c7fc9c..70ce9c76d 100644
--- a/proto/gen/api/instance_service.pb.go
+++ b/proto/gen/api/instance_service.pb.go
@@ -1022,6 +1022,134 @@ func (*GetInstanceStatsRequest) Descriptor() ([]byte, []int) {
return file_api_instance_service_proto_rawDescGZIP(), []int{9}
}
+// Request message for InstanceService.GetConfigurationStatus.
+type GetConfigurationStatusRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *GetConfigurationStatusRequest) Reset() {
+ *x = GetConfigurationStatusRequest{}
+ mi := &file_api_instance_service_proto_msgTypes[10]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *GetConfigurationStatusRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*GetConfigurationStatusRequest) ProtoMessage() {}
+
+func (x *GetConfigurationStatusRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_api_instance_service_proto_msgTypes[10]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use GetConfigurationStatusRequest.ProtoReflect.Descriptor instead.
+func (*GetConfigurationStatusRequest) Descriptor() ([]byte, []int) {
+ return file_api_instance_service_proto_rawDescGZIP(), []int{10}
+}
+
+// ConfigurationStatus is what declarative configuration manages on the instance.
+type ConfigurationStatus struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The state record serial; zero before any apply has changed something.
+ Serial int64 `protobuf:"varint,1,opt,name=serial,proto3" json:"serial,omitempty"`
+ // Identifies the applied configuration, with sensitive values masked before hashing.
+ ConfigDigest string `protobuf:"bytes,2,opt,name=config_digest,json=configDigest,proto3" json:"config_digest,omitempty"`
+ // The apply path ("cli" or "startup") and the host of the last apply.
+ AppliedBy string `protobuf:"bytes,3,opt,name=applied_by,json=appliedBy,proto3" json:"applied_by,omitempty"`
+ // The Memos version of the last apply.
+ Version string `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"`
+ // The resources the configuration manages.
+ ManagedResources []*ConfigurationStatus_ManagedResource `protobuf:"bytes,5,rep,name=managed_resources,json=managedResources,proto3" json:"managed_resources,omitempty"`
+ // When the last apply that changed something ran.
+ ApplyTime *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=apply_time,json=applyTime,proto3" json:"apply_time,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ConfigurationStatus) Reset() {
+ *x = ConfigurationStatus{}
+ mi := &file_api_instance_service_proto_msgTypes[11]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ConfigurationStatus) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ConfigurationStatus) ProtoMessage() {}
+
+func (x *ConfigurationStatus) ProtoReflect() protoreflect.Message {
+ mi := &file_api_instance_service_proto_msgTypes[11]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ConfigurationStatus.ProtoReflect.Descriptor instead.
+func (*ConfigurationStatus) Descriptor() ([]byte, []int) {
+ return file_api_instance_service_proto_rawDescGZIP(), []int{11}
+}
+
+func (x *ConfigurationStatus) GetSerial() int64 {
+ if x != nil {
+ return x.Serial
+ }
+ return 0
+}
+
+func (x *ConfigurationStatus) GetConfigDigest() string {
+ if x != nil {
+ return x.ConfigDigest
+ }
+ return ""
+}
+
+func (x *ConfigurationStatus) GetAppliedBy() string {
+ if x != nil {
+ return x.AppliedBy
+ }
+ return ""
+}
+
+func (x *ConfigurationStatus) GetVersion() string {
+ if x != nil {
+ return x.Version
+ }
+ return ""
+}
+
+func (x *ConfigurationStatus) GetManagedResources() []*ConfigurationStatus_ManagedResource {
+ if x != nil {
+ return x.ManagedResources
+ }
+ return nil
+}
+
+func (x *ConfigurationStatus) GetApplyTime() *timestamppb.Timestamp {
+ if x != nil {
+ return x.ApplyTime
+ }
+ return nil
+}
+
// Challenge describes a proof-of-humanity challenge widget.
type InstanceProfile_Challenge struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -1035,7 +1163,7 @@ type InstanceProfile_Challenge struct {
func (x *InstanceProfile_Challenge) Reset() {
*x = InstanceProfile_Challenge{}
- mi := &file_api_instance_service_proto_msgTypes[10]
+ mi := &file_api_instance_service_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1047,7 +1175,7 @@ func (x *InstanceProfile_Challenge) String() string {
func (*InstanceProfile_Challenge) ProtoMessage() {}
func (x *InstanceProfile_Challenge) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[10]
+ mi := &file_api_instance_service_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1104,7 +1232,7 @@ type InstanceSetting_GeneralSetting struct {
func (x *InstanceSetting_GeneralSetting) Reset() {
*x = InstanceSetting_GeneralSetting{}
- mi := &file_api_instance_service_proto_msgTypes[11]
+ mi := &file_api_instance_service_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1116,7 +1244,7 @@ func (x *InstanceSetting_GeneralSetting) String() string {
func (*InstanceSetting_GeneralSetting) ProtoMessage() {}
func (x *InstanceSetting_GeneralSetting) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[11]
+ mi := &file_api_instance_service_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1208,7 +1336,7 @@ type InstanceSetting_StorageSetting struct {
func (x *InstanceSetting_StorageSetting) Reset() {
*x = InstanceSetting_StorageSetting{}
- mi := &file_api_instance_service_proto_msgTypes[12]
+ mi := &file_api_instance_service_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1220,7 +1348,7 @@ func (x *InstanceSetting_StorageSetting) String() string {
func (*InstanceSetting_StorageSetting) ProtoMessage() {}
func (x *InstanceSetting_StorageSetting) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[12]
+ mi := &file_api_instance_service_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1292,7 +1420,7 @@ type InstanceSetting_Storage struct {
func (x *InstanceSetting_Storage) Reset() {
*x = InstanceSetting_Storage{}
- mi := &file_api_instance_service_proto_msgTypes[13]
+ mi := &file_api_instance_service_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1304,7 +1432,7 @@ func (x *InstanceSetting_Storage) String() string {
func (*InstanceSetting_Storage) ProtoMessage() {}
func (x *InstanceSetting_Storage) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[13]
+ mi := &file_api_instance_service_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1379,7 +1507,7 @@ type InstanceSetting_MemoRelatedSetting struct {
func (x *InstanceSetting_MemoRelatedSetting) Reset() {
*x = InstanceSetting_MemoRelatedSetting{}
- mi := &file_api_instance_service_proto_msgTypes[14]
+ mi := &file_api_instance_service_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1391,7 +1519,7 @@ func (x *InstanceSetting_MemoRelatedSetting) String() string {
func (*InstanceSetting_MemoRelatedSetting) ProtoMessage() {}
func (x *InstanceSetting_MemoRelatedSetting) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[14]
+ mi := &file_api_instance_service_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1429,7 +1557,7 @@ type InstanceSetting_TagsSetting struct {
func (x *InstanceSetting_TagsSetting) Reset() {
*x = InstanceSetting_TagsSetting{}
- mi := &file_api_instance_service_proto_msgTypes[15]
+ mi := &file_api_instance_service_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1441,7 +1569,7 @@ func (x *InstanceSetting_TagsSetting) String() string {
func (*InstanceSetting_TagsSetting) ProtoMessage() {}
func (x *InstanceSetting_TagsSetting) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[15]
+ mi := &file_api_instance_service_proto_msgTypes[17]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1477,7 +1605,7 @@ type InstanceSetting_TagMetadata struct {
func (x *InstanceSetting_TagMetadata) Reset() {
*x = InstanceSetting_TagMetadata{}
- mi := &file_api_instance_service_proto_msgTypes[16]
+ mi := &file_api_instance_service_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1489,7 +1617,7 @@ func (x *InstanceSetting_TagMetadata) String() string {
func (*InstanceSetting_TagMetadata) ProtoMessage() {}
func (x *InstanceSetting_TagMetadata) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[16]
+ mi := &file_api_instance_service_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1530,7 +1658,7 @@ type InstanceSetting_NotificationSetting struct {
func (x *InstanceSetting_NotificationSetting) Reset() {
*x = InstanceSetting_NotificationSetting{}
- mi := &file_api_instance_service_proto_msgTypes[17]
+ mi := &file_api_instance_service_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1542,7 +1670,7 @@ func (x *InstanceSetting_NotificationSetting) String() string {
func (*InstanceSetting_NotificationSetting) ProtoMessage() {}
func (x *InstanceSetting_NotificationSetting) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[17]
+ mi := &file_api_instance_service_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1580,7 +1708,7 @@ type InstanceSetting_AISetting struct {
func (x *InstanceSetting_AISetting) Reset() {
*x = InstanceSetting_AISetting{}
- mi := &file_api_instance_service_proto_msgTypes[18]
+ mi := &file_api_instance_service_proto_msgTypes[20]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1592,7 +1720,7 @@ func (x *InstanceSetting_AISetting) String() string {
func (*InstanceSetting_AISetting) ProtoMessage() {}
func (x *InstanceSetting_AISetting) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[18]
+ mi := &file_api_instance_service_proto_msgTypes[20]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1645,7 +1773,7 @@ type InstanceSetting_AIProviderConfig struct {
func (x *InstanceSetting_AIProviderConfig) Reset() {
*x = InstanceSetting_AIProviderConfig{}
- mi := &file_api_instance_service_proto_msgTypes[19]
+ mi := &file_api_instance_service_proto_msgTypes[21]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1657,7 +1785,7 @@ func (x *InstanceSetting_AIProviderConfig) String() string {
func (*InstanceSetting_AIProviderConfig) ProtoMessage() {}
func (x *InstanceSetting_AIProviderConfig) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[19]
+ mi := &file_api_instance_service_proto_msgTypes[21]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1742,7 +1870,7 @@ type InstanceSetting_TranscriptionConfig struct {
func (x *InstanceSetting_TranscriptionConfig) Reset() {
*x = InstanceSetting_TranscriptionConfig{}
- mi := &file_api_instance_service_proto_msgTypes[20]
+ mi := &file_api_instance_service_proto_msgTypes[22]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1754,7 +1882,7 @@ func (x *InstanceSetting_TranscriptionConfig) String() string {
func (*InstanceSetting_TranscriptionConfig) ProtoMessage() {}
func (x *InstanceSetting_TranscriptionConfig) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[20]
+ mi := &file_api_instance_service_proto_msgTypes[22]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1809,7 +1937,7 @@ type InstanceSetting_AccessSetting struct {
func (x *InstanceSetting_AccessSetting) Reset() {
*x = InstanceSetting_AccessSetting{}
- mi := &file_api_instance_service_proto_msgTypes[21]
+ mi := &file_api_instance_service_proto_msgTypes[23]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1821,7 +1949,7 @@ func (x *InstanceSetting_AccessSetting) String() string {
func (*InstanceSetting_AccessSetting) ProtoMessage() {}
func (x *InstanceSetting_AccessSetting) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[21]
+ mi := &file_api_instance_service_proto_msgTypes[23]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1859,7 +1987,7 @@ type InstanceSetting_UsageLimitsSetting struct {
func (x *InstanceSetting_UsageLimitsSetting) Reset() {
*x = InstanceSetting_UsageLimitsSetting{}
- mi := &file_api_instance_service_proto_msgTypes[22]
+ mi := &file_api_instance_service_proto_msgTypes[24]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1871,7 +1999,7 @@ func (x *InstanceSetting_UsageLimitsSetting) String() string {
func (*InstanceSetting_UsageLimitsSetting) ProtoMessage() {}
func (x *InstanceSetting_UsageLimitsSetting) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[22]
+ mi := &file_api_instance_service_proto_msgTypes[24]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1909,7 +2037,7 @@ type InstanceSetting_GeneralSetting_CustomProfile struct {
func (x *InstanceSetting_GeneralSetting_CustomProfile) Reset() {
*x = InstanceSetting_GeneralSetting_CustomProfile{}
- mi := &file_api_instance_service_proto_msgTypes[23]
+ mi := &file_api_instance_service_proto_msgTypes[25]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1921,7 +2049,7 @@ func (x *InstanceSetting_GeneralSetting_CustomProfile) String() string {
func (*InstanceSetting_GeneralSetting_CustomProfile) ProtoMessage() {}
func (x *InstanceSetting_GeneralSetting_CustomProfile) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[23]
+ mi := &file_api_instance_service_proto_msgTypes[25]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1984,7 +2112,7 @@ type InstanceSetting_StorageSetting_S3Config struct {
func (x *InstanceSetting_StorageSetting_S3Config) Reset() {
*x = InstanceSetting_StorageSetting_S3Config{}
- mi := &file_api_instance_service_proto_msgTypes[24]
+ mi := &file_api_instance_service_proto_msgTypes[26]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1996,7 +2124,7 @@ func (x *InstanceSetting_StorageSetting_S3Config) String() string {
func (*InstanceSetting_StorageSetting_S3Config) ProtoMessage() {}
func (x *InstanceSetting_StorageSetting_S3Config) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[24]
+ mi := &file_api_instance_service_proto_msgTypes[26]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2087,7 +2215,7 @@ type InstanceSetting_Storage_S3Config struct {
func (x *InstanceSetting_Storage_S3Config) Reset() {
*x = InstanceSetting_Storage_S3Config{}
- mi := &file_api_instance_service_proto_msgTypes[25]
+ mi := &file_api_instance_service_proto_msgTypes[27]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2099,7 +2227,7 @@ func (x *InstanceSetting_Storage_S3Config) String() string {
func (*InstanceSetting_Storage_S3Config) ProtoMessage() {}
func (x *InstanceSetting_Storage_S3Config) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[25]
+ mi := &file_api_instance_service_proto_msgTypes[27]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2194,7 +2322,7 @@ type InstanceSetting_NotificationSetting_EmailSetting struct {
func (x *InstanceSetting_NotificationSetting_EmailSetting) Reset() {
*x = InstanceSetting_NotificationSetting_EmailSetting{}
- mi := &file_api_instance_service_proto_msgTypes[27]
+ mi := &file_api_instance_service_proto_msgTypes[29]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2206,7 +2334,7 @@ func (x *InstanceSetting_NotificationSetting_EmailSetting) String() string {
func (*InstanceSetting_NotificationSetting_EmailSetting) ProtoMessage() {}
func (x *InstanceSetting_NotificationSetting_EmailSetting) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[27]
+ mi := &file_api_instance_service_proto_msgTypes[29]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2318,7 +2446,7 @@ type InstanceSetting_UsageLimitsSetting_UsageLimit struct {
func (x *InstanceSetting_UsageLimitsSetting_UsageLimit) Reset() {
*x = InstanceSetting_UsageLimitsSetting_UsageLimit{}
- mi := &file_api_instance_service_proto_msgTypes[28]
+ mi := &file_api_instance_service_proto_msgTypes[30]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2330,7 +2458,7 @@ func (x *InstanceSetting_UsageLimitsSetting_UsageLimit) String() string {
func (*InstanceSetting_UsageLimitsSetting_UsageLimit) ProtoMessage() {}
func (x *InstanceSetting_UsageLimitsSetting_UsageLimit) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[28]
+ mi := &file_api_instance_service_proto_msgTypes[30]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2401,7 +2529,7 @@ type InstanceStats_DatabaseStats struct {
func (x *InstanceStats_DatabaseStats) Reset() {
*x = InstanceStats_DatabaseStats{}
- mi := &file_api_instance_service_proto_msgTypes[29]
+ mi := &file_api_instance_service_proto_msgTypes[31]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2413,7 +2541,7 @@ func (x *InstanceStats_DatabaseStats) String() string {
func (*InstanceStats_DatabaseStats) ProtoMessage() {}
func (x *InstanceStats_DatabaseStats) ProtoReflect() protoreflect.Message {
- mi := &file_api_instance_service_proto_msgTypes[29]
+ mi := &file_api_instance_service_proto_msgTypes[31]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2443,6 +2571,80 @@ func (x *InstanceStats_DatabaseStats) GetSizeBytes() int64 {
return 0
}
+// ManagedResource is one resource the configuration manages.
+type ConfigurationStatus_ManagedResource struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // The resource name.
+ // Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
+ // The configuration file that declares the resource.
+ Source string `protobuf:"bytes,2,opt,name=source,proto3" json:"source,omitempty"`
+ // The field paths, in JSON names, the configuration manages; "*" means the whole resource.
+ ManagedFields []string `protobuf:"bytes,3,rep,name=managed_fields,json=managedFields,proto3" json:"managed_fields,omitempty"`
+ // The managed field paths the configuration does not write after creation, so the API accepts edits to them.
+ IgnoredFields []string `protobuf:"bytes,4,rep,name=ignored_fields,json=ignoredFields,proto3" json:"ignored_fields,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ConfigurationStatus_ManagedResource) Reset() {
+ *x = ConfigurationStatus_ManagedResource{}
+ mi := &file_api_instance_service_proto_msgTypes[32]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ConfigurationStatus_ManagedResource) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ConfigurationStatus_ManagedResource) ProtoMessage() {}
+
+func (x *ConfigurationStatus_ManagedResource) ProtoReflect() protoreflect.Message {
+ mi := &file_api_instance_service_proto_msgTypes[32]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ConfigurationStatus_ManagedResource.ProtoReflect.Descriptor instead.
+func (*ConfigurationStatus_ManagedResource) Descriptor() ([]byte, []int) {
+ return file_api_instance_service_proto_rawDescGZIP(), []int{11, 0}
+}
+
+func (x *ConfigurationStatus_ManagedResource) GetResource() string {
+ if x != nil {
+ return x.Resource
+ }
+ return ""
+}
+
+func (x *ConfigurationStatus_ManagedResource) GetSource() string {
+ if x != nil {
+ return x.Source
+ }
+ return ""
+}
+
+func (x *ConfigurationStatus_ManagedResource) GetManagedFields() []string {
+ if x != nil {
+ return x.ManagedFields
+ }
+ return nil
+}
+
+func (x *ConfigurationStatus_ManagedResource) GetIgnoredFields() []string {
+ if x != nil {
+ return x.IgnoredFields
+ }
+ return nil
+}
+
var File_api_instance_service_proto protoreflect.FileDescriptor
const file_api_instance_service_proto_rawDesc = "" +
@@ -2629,18 +2831,34 @@ const file_api_instance_service_proto_rawDesc = "" +
"\x06driver\x18\x01 \x01(\tR\x06driver\x12\x1d\n" +
"\n" +
"size_bytes\x18\x02 \x01(\x03R\tsizeBytes\"\x19\n" +
- "\x17GetInstanceStatsRequest*}\n" +
+ "\x17GetInstanceStatsRequest\"\x1f\n" +
+ "\x1dGetConfigurationStatusRequest\"\xb9\x03\n" +
+ "\x13ConfigurationStatus\x12\x16\n" +
+ "\x06serial\x18\x01 \x01(\x03R\x06serial\x12#\n" +
+ "\rconfig_digest\x18\x02 \x01(\tR\fconfigDigest\x12\x1d\n" +
+ "\n" +
+ "applied_by\x18\x03 \x01(\tR\tappliedBy\x12\x18\n" +
+ "\aversion\x18\x04 \x01(\tR\aversion\x12[\n" +
+ "\x11managed_resources\x18\x05 \x03(\v2..memos.api.ConfigurationStatus.ManagedResourceR\x10managedResources\x129\n" +
+ "\n" +
+ "apply_time\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\tapplyTime\x1a\x93\x01\n" +
+ "\x0fManagedResource\x12\x1a\n" +
+ "\bresource\x18\x01 \x01(\tR\bresource\x12\x16\n" +
+ "\x06source\x18\x02 \x01(\tR\x06source\x12%\n" +
+ "\x0emanaged_fields\x18\x03 \x03(\tR\rmanagedFields\x12%\n" +
+ "\x0eignored_fields\x18\x04 \x03(\tR\rignoredFields*}\n" +
"\x12InstanceAccessMode\x12$\n" +
" INSTANCE_ACCESS_MODE_UNSPECIFIED\x10\x00\x12 \n" +
"\x1cINSTANCE_ACCESS_MODE_PRIVATE\x10\x01\x12\x1f\n" +
- "\x1bINSTANCE_ACCESS_MODE_PUBLIC\x10\x022\x87\a\n" +
+ "\x1bINSTANCE_ACCESS_MODE_PUBLIC\x10\x022\x91\b\n" +
"\x0fInstanceService\x12u\n" +
"\x12GetInstanceProfile\x12$.memos.api.GetInstanceProfileRequest\x1a\x1a.memos.api.InstanceProfile\"\x1d\x82\xd3\xe4\x93\x02\x17\x12\x15/api/instance/profile\x12\x86\x01\n" +
"\x12GetInstanceSetting\x12$.memos.api.GetInstanceSettingRequest\x1a\x1a.memos.api.InstanceSetting\".\xdaA\x04name\x82\xd3\xe4\x93\x02!\x12\x1f/api/{name=instance/settings/*}\x12\x9f\x01\n" +
"\x18BatchGetInstanceSettings\x12*.memos.api.BatchGetInstanceSettingsRequest\x1a+.memos.api.BatchGetInstanceSettingsResponse\"*\x82\xd3\xe4\x93\x02$:\x01*\"\x1f/api/instance/settings:batchGet\x12\xc7\x01\n" +
"\x15UpdateInstanceSetting\x12'.memos.api.UpdateInstanceSettingRequest\x1a\x1a.memos.api.InstanceSetting\"i\xdaA\x1cinstance_setting,update_mask\x82\xd3\xe4\x93\x02D:\x10instance_setting20/api/{instance_setting.name=instance/settings/*}\x12\x98\x01\n" +
"\x18TestInstanceEmailSetting\x12*.memos.api.TestInstanceEmailSettingRequest\x1a\x16.google.protobuf.Empty\"8\x82\xd3\xe4\x93\x022:\x01*\"-/api/instance/settings/notification:testEmail\x12m\n" +
- "\x10GetInstanceStats\x12\".memos.api.GetInstanceStatsRequest\x1a\x18.memos.api.InstanceStats\"\x1b\x82\xd3\xe4\x93\x02\x15\x12\x13/api/instance/statsB\x93\x01\n" +
+ "\x10GetInstanceStats\x12\".memos.api.GetInstanceStatsRequest\x1a\x18.memos.api.InstanceStats\"\x1b\x82\xd3\xe4\x93\x02\x15\x12\x13/api/instance/stats\x12\x87\x01\n" +
+ "\x16GetConfigurationStatus\x12(.memos.api.GetConfigurationStatusRequest\x1a\x1e.memos.api.ConfigurationStatus\"#\x82\xd3\xe4\x93\x02\x1d\x12\x1b/api/instance/configurationB\x93\x01\n" +
"\rcom.memos.apiB\x14InstanceServiceProtoP\x01Z'github.com/usememos/memos/proto/gen/api\xa2\x02\x03MAX\xaa\x02\tMemos.Api\xca\x02\tMemos\\Api\xe2\x02\x15Memos\\Api\\GPBMetadata\xea\x02\n" +
"Memos::Apib\x06proto3"
@@ -2657,7 +2875,7 @@ func file_api_instance_service_proto_rawDescGZIP() []byte {
}
var file_api_instance_service_proto_enumTypes = make([]protoimpl.EnumInfo, 5)
-var file_api_instance_service_proto_msgTypes = make([]protoimpl.MessageInfo, 30)
+var file_api_instance_service_proto_msgTypes = make([]protoimpl.MessageInfo, 33)
var file_api_instance_service_proto_goTypes = []any{
(InstanceAccessMode)(0), // 0: memos.api.InstanceAccessMode
(InstanceSetting_Key)(0), // 1: memos.api.InstanceSetting.Key
@@ -2674,82 +2892,89 @@ var file_api_instance_service_proto_goTypes = []any{
(*TestInstanceEmailSettingRequest)(nil), // 12: memos.api.TestInstanceEmailSettingRequest
(*InstanceStats)(nil), // 13: memos.api.InstanceStats
(*GetInstanceStatsRequest)(nil), // 14: memos.api.GetInstanceStatsRequest
- (*InstanceProfile_Challenge)(nil), // 15: memos.api.InstanceProfile.Challenge
- (*InstanceSetting_GeneralSetting)(nil), // 16: memos.api.InstanceSetting.GeneralSetting
- (*InstanceSetting_StorageSetting)(nil), // 17: memos.api.InstanceSetting.StorageSetting
- (*InstanceSetting_Storage)(nil), // 18: memos.api.InstanceSetting.Storage
- (*InstanceSetting_MemoRelatedSetting)(nil), // 19: memos.api.InstanceSetting.MemoRelatedSetting
- (*InstanceSetting_TagsSetting)(nil), // 20: memos.api.InstanceSetting.TagsSetting
- (*InstanceSetting_TagMetadata)(nil), // 21: memos.api.InstanceSetting.TagMetadata
- (*InstanceSetting_NotificationSetting)(nil), // 22: memos.api.InstanceSetting.NotificationSetting
- (*InstanceSetting_AISetting)(nil), // 23: memos.api.InstanceSetting.AISetting
- (*InstanceSetting_AIProviderConfig)(nil), // 24: memos.api.InstanceSetting.AIProviderConfig
- (*InstanceSetting_TranscriptionConfig)(nil), // 25: memos.api.InstanceSetting.TranscriptionConfig
- (*InstanceSetting_AccessSetting)(nil), // 26: memos.api.InstanceSetting.AccessSetting
- (*InstanceSetting_UsageLimitsSetting)(nil), // 27: memos.api.InstanceSetting.UsageLimitsSetting
- (*InstanceSetting_GeneralSetting_CustomProfile)(nil), // 28: memos.api.InstanceSetting.GeneralSetting.CustomProfile
- (*InstanceSetting_StorageSetting_S3Config)(nil), // 29: memos.api.InstanceSetting.StorageSetting.S3Config
- (*InstanceSetting_Storage_S3Config)(nil), // 30: memos.api.InstanceSetting.Storage.S3Config
- nil, // 31: memos.api.InstanceSetting.TagsSetting.TagsEntry
- (*InstanceSetting_NotificationSetting_EmailSetting)(nil), // 32: memos.api.InstanceSetting.NotificationSetting.EmailSetting
- (*InstanceSetting_UsageLimitsSetting_UsageLimit)(nil), // 33: memos.api.InstanceSetting.UsageLimitsSetting.UsageLimit
- (*InstanceStats_DatabaseStats)(nil), // 34: memos.api.InstanceStats.DatabaseStats
- (*User)(nil), // 35: memos.api.User
- (*fieldmaskpb.FieldMask)(nil), // 36: google.protobuf.FieldMask
- (*timestamppb.Timestamp)(nil), // 37: google.protobuf.Timestamp
- (*color.Color)(nil), // 38: google.type.Color
- (*emptypb.Empty)(nil), // 39: google.protobuf.Empty
+ (*GetConfigurationStatusRequest)(nil), // 15: memos.api.GetConfigurationStatusRequest
+ (*ConfigurationStatus)(nil), // 16: memos.api.ConfigurationStatus
+ (*InstanceProfile_Challenge)(nil), // 17: memos.api.InstanceProfile.Challenge
+ (*InstanceSetting_GeneralSetting)(nil), // 18: memos.api.InstanceSetting.GeneralSetting
+ (*InstanceSetting_StorageSetting)(nil), // 19: memos.api.InstanceSetting.StorageSetting
+ (*InstanceSetting_Storage)(nil), // 20: memos.api.InstanceSetting.Storage
+ (*InstanceSetting_MemoRelatedSetting)(nil), // 21: memos.api.InstanceSetting.MemoRelatedSetting
+ (*InstanceSetting_TagsSetting)(nil), // 22: memos.api.InstanceSetting.TagsSetting
+ (*InstanceSetting_TagMetadata)(nil), // 23: memos.api.InstanceSetting.TagMetadata
+ (*InstanceSetting_NotificationSetting)(nil), // 24: memos.api.InstanceSetting.NotificationSetting
+ (*InstanceSetting_AISetting)(nil), // 25: memos.api.InstanceSetting.AISetting
+ (*InstanceSetting_AIProviderConfig)(nil), // 26: memos.api.InstanceSetting.AIProviderConfig
+ (*InstanceSetting_TranscriptionConfig)(nil), // 27: memos.api.InstanceSetting.TranscriptionConfig
+ (*InstanceSetting_AccessSetting)(nil), // 28: memos.api.InstanceSetting.AccessSetting
+ (*InstanceSetting_UsageLimitsSetting)(nil), // 29: memos.api.InstanceSetting.UsageLimitsSetting
+ (*InstanceSetting_GeneralSetting_CustomProfile)(nil), // 30: memos.api.InstanceSetting.GeneralSetting.CustomProfile
+ (*InstanceSetting_StorageSetting_S3Config)(nil), // 31: memos.api.InstanceSetting.StorageSetting.S3Config
+ (*InstanceSetting_Storage_S3Config)(nil), // 32: memos.api.InstanceSetting.Storage.S3Config
+ nil, // 33: memos.api.InstanceSetting.TagsSetting.TagsEntry
+ (*InstanceSetting_NotificationSetting_EmailSetting)(nil), // 34: memos.api.InstanceSetting.NotificationSetting.EmailSetting
+ (*InstanceSetting_UsageLimitsSetting_UsageLimit)(nil), // 35: memos.api.InstanceSetting.UsageLimitsSetting.UsageLimit
+ (*InstanceStats_DatabaseStats)(nil), // 36: memos.api.InstanceStats.DatabaseStats
+ (*ConfigurationStatus_ManagedResource)(nil), // 37: memos.api.ConfigurationStatus.ManagedResource
+ (*User)(nil), // 38: memos.api.User
+ (*fieldmaskpb.FieldMask)(nil), // 39: google.protobuf.FieldMask
+ (*timestamppb.Timestamp)(nil), // 40: google.protobuf.Timestamp
+ (*color.Color)(nil), // 41: google.type.Color
+ (*emptypb.Empty)(nil), // 42: google.protobuf.Empty
}
var file_api_instance_service_proto_depIdxs = []int32{
0, // 0: memos.api.InstanceProfile.access_mode:type_name -> memos.api.InstanceAccessMode
- 35, // 1: memos.api.InstanceProfile.admin:type_name -> memos.api.User
- 15, // 2: memos.api.InstanceProfile.challenge:type_name -> memos.api.InstanceProfile.Challenge
- 16, // 3: memos.api.InstanceSetting.general_setting:type_name -> memos.api.InstanceSetting.GeneralSetting
- 17, // 4: memos.api.InstanceSetting.storage_setting:type_name -> memos.api.InstanceSetting.StorageSetting
- 19, // 5: memos.api.InstanceSetting.memo_related_setting:type_name -> memos.api.InstanceSetting.MemoRelatedSetting
- 20, // 6: memos.api.InstanceSetting.tags_setting:type_name -> memos.api.InstanceSetting.TagsSetting
- 22, // 7: memos.api.InstanceSetting.notification_setting:type_name -> memos.api.InstanceSetting.NotificationSetting
- 23, // 8: memos.api.InstanceSetting.ai_setting:type_name -> memos.api.InstanceSetting.AISetting
- 26, // 9: memos.api.InstanceSetting.access_setting:type_name -> memos.api.InstanceSetting.AccessSetting
- 27, // 10: memos.api.InstanceSetting.usage_limits_setting:type_name -> memos.api.InstanceSetting.UsageLimitsSetting
+ 38, // 1: memos.api.InstanceProfile.admin:type_name -> memos.api.User
+ 17, // 2: memos.api.InstanceProfile.challenge:type_name -> memos.api.InstanceProfile.Challenge
+ 18, // 3: memos.api.InstanceSetting.general_setting:type_name -> memos.api.InstanceSetting.GeneralSetting
+ 19, // 4: memos.api.InstanceSetting.storage_setting:type_name -> memos.api.InstanceSetting.StorageSetting
+ 21, // 5: memos.api.InstanceSetting.memo_related_setting:type_name -> memos.api.InstanceSetting.MemoRelatedSetting
+ 22, // 6: memos.api.InstanceSetting.tags_setting:type_name -> memos.api.InstanceSetting.TagsSetting
+ 24, // 7: memos.api.InstanceSetting.notification_setting:type_name -> memos.api.InstanceSetting.NotificationSetting
+ 25, // 8: memos.api.InstanceSetting.ai_setting:type_name -> memos.api.InstanceSetting.AISetting
+ 28, // 9: memos.api.InstanceSetting.access_setting:type_name -> memos.api.InstanceSetting.AccessSetting
+ 29, // 10: memos.api.InstanceSetting.usage_limits_setting:type_name -> memos.api.InstanceSetting.UsageLimitsSetting
7, // 11: memos.api.BatchGetInstanceSettingsResponse.instance_settings:type_name -> memos.api.InstanceSetting
7, // 12: memos.api.UpdateInstanceSettingRequest.instance_setting:type_name -> memos.api.InstanceSetting
- 36, // 13: memos.api.UpdateInstanceSettingRequest.update_mask:type_name -> google.protobuf.FieldMask
- 32, // 14: memos.api.TestInstanceEmailSettingRequest.email:type_name -> memos.api.InstanceSetting.NotificationSetting.EmailSetting
- 34, // 15: memos.api.InstanceStats.database:type_name -> memos.api.InstanceStats.DatabaseStats
- 37, // 16: memos.api.InstanceStats.generated_time:type_name -> google.protobuf.Timestamp
- 28, // 17: memos.api.InstanceSetting.GeneralSetting.custom_profile:type_name -> memos.api.InstanceSetting.GeneralSetting.CustomProfile
- 18, // 18: memos.api.InstanceSetting.StorageSetting.storages:type_name -> memos.api.InstanceSetting.Storage
- 4, // 19: memos.api.InstanceSetting.StorageSetting.storage_type:type_name -> memos.api.InstanceSetting.StorageSetting.StorageType
- 29, // 20: memos.api.InstanceSetting.StorageSetting.s3_config:type_name -> memos.api.InstanceSetting.StorageSetting.S3Config
- 2, // 21: memos.api.InstanceSetting.Storage.type:type_name -> memos.api.InstanceSetting.StorageType
- 30, // 22: memos.api.InstanceSetting.Storage.s3_config:type_name -> memos.api.InstanceSetting.Storage.S3Config
- 31, // 23: memos.api.InstanceSetting.TagsSetting.tags:type_name -> memos.api.InstanceSetting.TagsSetting.TagsEntry
- 38, // 24: memos.api.InstanceSetting.TagMetadata.background_color:type_name -> google.type.Color
- 32, // 25: memos.api.InstanceSetting.NotificationSetting.email:type_name -> memos.api.InstanceSetting.NotificationSetting.EmailSetting
- 24, // 26: memos.api.InstanceSetting.AISetting.providers:type_name -> memos.api.InstanceSetting.AIProviderConfig
- 25, // 27: memos.api.InstanceSetting.AISetting.transcription:type_name -> memos.api.InstanceSetting.TranscriptionConfig
- 3, // 28: memos.api.InstanceSetting.AIProviderConfig.type:type_name -> memos.api.InstanceSetting.AIProviderType
- 0, // 29: memos.api.InstanceSetting.AccessSetting.access_mode:type_name -> memos.api.InstanceAccessMode
- 33, // 30: memos.api.InstanceSetting.UsageLimitsSetting.limits:type_name -> memos.api.InstanceSetting.UsageLimitsSetting.UsageLimit
- 21, // 31: memos.api.InstanceSetting.TagsSetting.TagsEntry.value:type_name -> memos.api.InstanceSetting.TagMetadata
- 6, // 32: memos.api.InstanceService.GetInstanceProfile:input_type -> memos.api.GetInstanceProfileRequest
- 8, // 33: memos.api.InstanceService.GetInstanceSetting:input_type -> memos.api.GetInstanceSettingRequest
- 9, // 34: memos.api.InstanceService.BatchGetInstanceSettings:input_type -> memos.api.BatchGetInstanceSettingsRequest
- 11, // 35: memos.api.InstanceService.UpdateInstanceSetting:input_type -> memos.api.UpdateInstanceSettingRequest
- 12, // 36: memos.api.InstanceService.TestInstanceEmailSetting:input_type -> memos.api.TestInstanceEmailSettingRequest
- 14, // 37: memos.api.InstanceService.GetInstanceStats:input_type -> memos.api.GetInstanceStatsRequest
- 5, // 38: memos.api.InstanceService.GetInstanceProfile:output_type -> memos.api.InstanceProfile
- 7, // 39: memos.api.InstanceService.GetInstanceSetting:output_type -> memos.api.InstanceSetting
- 10, // 40: memos.api.InstanceService.BatchGetInstanceSettings:output_type -> memos.api.BatchGetInstanceSettingsResponse
- 7, // 41: memos.api.InstanceService.UpdateInstanceSetting:output_type -> memos.api.InstanceSetting
- 39, // 42: memos.api.InstanceService.TestInstanceEmailSetting:output_type -> google.protobuf.Empty
- 13, // 43: memos.api.InstanceService.GetInstanceStats:output_type -> memos.api.InstanceStats
- 38, // [38:44] is the sub-list for method output_type
- 32, // [32:38] is the sub-list for method input_type
- 32, // [32:32] is the sub-list for extension type_name
- 32, // [32:32] is the sub-list for extension extendee
- 0, // [0:32] is the sub-list for field type_name
+ 39, // 13: memos.api.UpdateInstanceSettingRequest.update_mask:type_name -> google.protobuf.FieldMask
+ 34, // 14: memos.api.TestInstanceEmailSettingRequest.email:type_name -> memos.api.InstanceSetting.NotificationSetting.EmailSetting
+ 36, // 15: memos.api.InstanceStats.database:type_name -> memos.api.InstanceStats.DatabaseStats
+ 40, // 16: memos.api.InstanceStats.generated_time:type_name -> google.protobuf.Timestamp
+ 37, // 17: memos.api.ConfigurationStatus.managed_resources:type_name -> memos.api.ConfigurationStatus.ManagedResource
+ 40, // 18: memos.api.ConfigurationStatus.apply_time:type_name -> google.protobuf.Timestamp
+ 30, // 19: memos.api.InstanceSetting.GeneralSetting.custom_profile:type_name -> memos.api.InstanceSetting.GeneralSetting.CustomProfile
+ 20, // 20: memos.api.InstanceSetting.StorageSetting.storages:type_name -> memos.api.InstanceSetting.Storage
+ 4, // 21: memos.api.InstanceSetting.StorageSetting.storage_type:type_name -> memos.api.InstanceSetting.StorageSetting.StorageType
+ 31, // 22: memos.api.InstanceSetting.StorageSetting.s3_config:type_name -> memos.api.InstanceSetting.StorageSetting.S3Config
+ 2, // 23: memos.api.InstanceSetting.Storage.type:type_name -> memos.api.InstanceSetting.StorageType
+ 32, // 24: memos.api.InstanceSetting.Storage.s3_config:type_name -> memos.api.InstanceSetting.Storage.S3Config
+ 33, // 25: memos.api.InstanceSetting.TagsSetting.tags:type_name -> memos.api.InstanceSetting.TagsSetting.TagsEntry
+ 41, // 26: memos.api.InstanceSetting.TagMetadata.background_color:type_name -> google.type.Color
+ 34, // 27: memos.api.InstanceSetting.NotificationSetting.email:type_name -> memos.api.InstanceSetting.NotificationSetting.EmailSetting
+ 26, // 28: memos.api.InstanceSetting.AISetting.providers:type_name -> memos.api.InstanceSetting.AIProviderConfig
+ 27, // 29: memos.api.InstanceSetting.AISetting.transcription:type_name -> memos.api.InstanceSetting.TranscriptionConfig
+ 3, // 30: memos.api.InstanceSetting.AIProviderConfig.type:type_name -> memos.api.InstanceSetting.AIProviderType
+ 0, // 31: memos.api.InstanceSetting.AccessSetting.access_mode:type_name -> memos.api.InstanceAccessMode
+ 35, // 32: memos.api.InstanceSetting.UsageLimitsSetting.limits:type_name -> memos.api.InstanceSetting.UsageLimitsSetting.UsageLimit
+ 23, // 33: memos.api.InstanceSetting.TagsSetting.TagsEntry.value:type_name -> memos.api.InstanceSetting.TagMetadata
+ 6, // 34: memos.api.InstanceService.GetInstanceProfile:input_type -> memos.api.GetInstanceProfileRequest
+ 8, // 35: memos.api.InstanceService.GetInstanceSetting:input_type -> memos.api.GetInstanceSettingRequest
+ 9, // 36: memos.api.InstanceService.BatchGetInstanceSettings:input_type -> memos.api.BatchGetInstanceSettingsRequest
+ 11, // 37: memos.api.InstanceService.UpdateInstanceSetting:input_type -> memos.api.UpdateInstanceSettingRequest
+ 12, // 38: memos.api.InstanceService.TestInstanceEmailSetting:input_type -> memos.api.TestInstanceEmailSettingRequest
+ 14, // 39: memos.api.InstanceService.GetInstanceStats:input_type -> memos.api.GetInstanceStatsRequest
+ 15, // 40: memos.api.InstanceService.GetConfigurationStatus:input_type -> memos.api.GetConfigurationStatusRequest
+ 5, // 41: memos.api.InstanceService.GetInstanceProfile:output_type -> memos.api.InstanceProfile
+ 7, // 42: memos.api.InstanceService.GetInstanceSetting:output_type -> memos.api.InstanceSetting
+ 10, // 43: memos.api.InstanceService.BatchGetInstanceSettings:output_type -> memos.api.BatchGetInstanceSettingsResponse
+ 7, // 44: memos.api.InstanceService.UpdateInstanceSetting:output_type -> memos.api.InstanceSetting
+ 42, // 45: memos.api.InstanceService.TestInstanceEmailSetting:output_type -> google.protobuf.Empty
+ 13, // 46: memos.api.InstanceService.GetInstanceStats:output_type -> memos.api.InstanceStats
+ 16, // 47: memos.api.InstanceService.GetConfigurationStatus:output_type -> memos.api.ConfigurationStatus
+ 41, // [41:48] is the sub-list for method output_type
+ 34, // [34:41] is the sub-list for method input_type
+ 34, // [34:34] is the sub-list for extension type_name
+ 34, // [34:34] is the sub-list for extension extendee
+ 0, // [0:34] is the sub-list for field type_name
}
func init() { file_api_instance_service_proto_init() }
@@ -2768,17 +2993,17 @@ func file_api_instance_service_proto_init() {
(*InstanceSetting_AccessSetting_)(nil),
(*InstanceSetting_UsageLimitsSetting_)(nil),
}
- file_api_instance_service_proto_msgTypes[13].OneofWrappers = []any{
+ file_api_instance_service_proto_msgTypes[15].OneofWrappers = []any{
(*InstanceSetting_Storage_S3Config_)(nil),
}
- file_api_instance_service_proto_msgTypes[28].OneofWrappers = []any{}
+ file_api_instance_service_proto_msgTypes[30].OneofWrappers = []any{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_instance_service_proto_rawDesc), len(file_api_instance_service_proto_rawDesc)),
NumEnums: 5,
- NumMessages: 30,
+ NumMessages: 33,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/gen/api/instance_service.pb.gw.go b/proto/gen/api/instance_service.pb.gw.go
index cdc9000b8..f736b9c58 100644
--- a/proto/gen/api/instance_service.pb.gw.go
+++ b/proto/gen/api/instance_service.pb.gw.go
@@ -251,6 +251,27 @@ func local_request_InstanceService_GetInstanceStats_0(ctx context.Context, marsh
return msg, metadata, err
}
+func request_InstanceService_GetConfigurationStatus_0(ctx context.Context, marshaler runtime.Marshaler, client InstanceServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq GetConfigurationStatusRequest
+ metadata runtime.ServerMetadata
+ )
+ if req.Body != nil {
+ _, _ = io.Copy(io.Discard, req.Body)
+ }
+ msg, err := client.GetConfigurationStatus(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
+ return msg, metadata, err
+}
+
+func local_request_InstanceService_GetConfigurationStatus_0(ctx context.Context, marshaler runtime.Marshaler, server InstanceServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
+ var (
+ protoReq GetConfigurationStatusRequest
+ metadata runtime.ServerMetadata
+ )
+ msg, err := server.GetConfigurationStatus(ctx, &protoReq)
+ return msg, metadata, err
+}
+
// RegisterInstanceServiceHandlerServer registers the http handlers for service InstanceService to "mux".
// UnaryRPC :call InstanceServiceServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
@@ -377,6 +398,26 @@ func RegisterInstanceServiceHandlerServer(ctx context.Context, mux *runtime.Serv
}
forward_InstanceService_GetInstanceStats_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodGet, pattern_InstanceService_GetConfigurationStatus_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ var stream runtime.ServerTransportStream
+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/memos.api.InstanceService/GetConfigurationStatus", runtime.WithHTTPPathPattern("/api/instance/configuration"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := local_request_InstanceService_GetConfigurationStatus_0(annotatedContext, inboundMarshaler, server, req, pathParams)
+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_InstanceService_GetConfigurationStatus_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
return nil
}
@@ -519,6 +560,23 @@ func RegisterInstanceServiceHandlerClient(ctx context.Context, mux *runtime.Serv
}
forward_InstanceService_GetInstanceStats_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
+ mux.Handle(http.MethodGet, pattern_InstanceService_GetConfigurationStatus_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/memos.api.InstanceService/GetConfigurationStatus", runtime.WithHTTPPathPattern("/api/instance/configuration"))
+ if err != nil {
+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ resp, md, err := request_InstanceService_GetConfigurationStatus_0(annotatedContext, inboundMarshaler, client, req, pathParams)
+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
+ if err != nil {
+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
+ return
+ }
+ forward_InstanceService_GetConfigurationStatus_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
+ })
return nil
}
@@ -529,6 +587,7 @@ var (
pattern_InstanceService_UpdateInstanceSetting_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 3, 5, 3}, []string{"api", "instance", "settings", "instance_setting.name"}, ""))
pattern_InstanceService_TestInstanceEmailSetting_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"api", "instance", "settings", "notification"}, "testEmail"))
pattern_InstanceService_GetInstanceStats_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"api", "instance", "stats"}, ""))
+ pattern_InstanceService_GetConfigurationStatus_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"api", "instance", "configuration"}, ""))
)
var (
@@ -538,4 +597,5 @@ var (
forward_InstanceService_UpdateInstanceSetting_0 = runtime.ForwardResponseMessage
forward_InstanceService_TestInstanceEmailSetting_0 = runtime.ForwardResponseMessage
forward_InstanceService_GetInstanceStats_0 = runtime.ForwardResponseMessage
+ forward_InstanceService_GetConfigurationStatus_0 = runtime.ForwardResponseMessage
)
diff --git a/proto/gen/api/instance_service_grpc.pb.go b/proto/gen/api/instance_service_grpc.pb.go
index 7ed219ead..fe8de0d84 100644
--- a/proto/gen/api/instance_service_grpc.pb.go
+++ b/proto/gen/api/instance_service_grpc.pb.go
@@ -26,6 +26,7 @@ const (
InstanceService_UpdateInstanceSetting_FullMethodName = "/memos.api.InstanceService/UpdateInstanceSetting"
InstanceService_TestInstanceEmailSetting_FullMethodName = "/memos.api.InstanceService/TestInstanceEmailSetting"
InstanceService_GetInstanceStats_FullMethodName = "/memos.api.InstanceService/GetInstanceStats"
+ InstanceService_GetConfigurationStatus_FullMethodName = "/memos.api.InstanceService/GetConfigurationStatus"
)
// InstanceServiceClient is the client API for InstanceService service.
@@ -42,13 +43,16 @@ type InstanceServiceClient interface {
// BatchGetInstanceSettings gets up to 100 instance settings in request order, with the same access rules as
// GetInstanceSetting. The call fails if any setting cannot be returned.
BatchGetInstanceSettings(ctx context.Context, in *BatchGetInstanceSettingsRequest, opts ...grpc.CallOption) (*BatchGetInstanceSettingsResponse, error)
- // UpdateInstanceSetting replaces an instance setting. Admin only. Settings configured by the deployment cannot be
- // updated. Empty write-only credentials keep the stored values.
+ // UpdateInstanceSetting replaces an instance setting. Admin only. Fields declarative configuration manages cannot be
+ // changed. Empty write-only credentials keep the stored values.
UpdateInstanceSetting(ctx context.Context, in *UpdateInstanceSettingRequest, opts ...grpc.CallOption) (*InstanceSetting, error)
// TestInstanceEmailSetting sends a test email with the provided or stored SMTP settings. Admin only.
TestInstanceEmailSetting(ctx context.Context, in *TestInstanceEmailSettingRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
// GetInstanceStats gets resource usage statistics for the instance. Admin only. Results are cached for 60 seconds.
GetInstanceStats(ctx context.Context, in *GetInstanceStatsRequest, opts ...grpc.CallOption) (*InstanceStats, error)
+ // GetConfigurationStatus gets what declarative configuration manages: the managed resources and the last apply.
+ // Admin only. It carries resource names and field paths, never a configured value.
+ GetConfigurationStatus(ctx context.Context, in *GetConfigurationStatusRequest, opts ...grpc.CallOption) (*ConfigurationStatus, error)
}
type instanceServiceClient struct {
@@ -119,6 +123,16 @@ func (c *instanceServiceClient) GetInstanceStats(ctx context.Context, in *GetIns
return out, nil
}
+func (c *instanceServiceClient) GetConfigurationStatus(ctx context.Context, in *GetConfigurationStatusRequest, opts ...grpc.CallOption) (*ConfigurationStatus, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ConfigurationStatus)
+ err := c.cc.Invoke(ctx, InstanceService_GetConfigurationStatus_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// InstanceServiceServer is the server API for InstanceService service.
// All implementations must embed UnimplementedInstanceServiceServer
// for forward compatibility.
@@ -133,13 +147,16 @@ type InstanceServiceServer interface {
// BatchGetInstanceSettings gets up to 100 instance settings in request order, with the same access rules as
// GetInstanceSetting. The call fails if any setting cannot be returned.
BatchGetInstanceSettings(context.Context, *BatchGetInstanceSettingsRequest) (*BatchGetInstanceSettingsResponse, error)
- // UpdateInstanceSetting replaces an instance setting. Admin only. Settings configured by the deployment cannot be
- // updated. Empty write-only credentials keep the stored values.
+ // UpdateInstanceSetting replaces an instance setting. Admin only. Fields declarative configuration manages cannot be
+ // changed. Empty write-only credentials keep the stored values.
UpdateInstanceSetting(context.Context, *UpdateInstanceSettingRequest) (*InstanceSetting, error)
// TestInstanceEmailSetting sends a test email with the provided or stored SMTP settings. Admin only.
TestInstanceEmailSetting(context.Context, *TestInstanceEmailSettingRequest) (*emptypb.Empty, error)
// GetInstanceStats gets resource usage statistics for the instance. Admin only. Results are cached for 60 seconds.
GetInstanceStats(context.Context, *GetInstanceStatsRequest) (*InstanceStats, error)
+ // GetConfigurationStatus gets what declarative configuration manages: the managed resources and the last apply.
+ // Admin only. It carries resource names and field paths, never a configured value.
+ GetConfigurationStatus(context.Context, *GetConfigurationStatusRequest) (*ConfigurationStatus, error)
mustEmbedUnimplementedInstanceServiceServer()
}
@@ -168,6 +185,9 @@ func (UnimplementedInstanceServiceServer) TestInstanceEmailSetting(context.Conte
func (UnimplementedInstanceServiceServer) GetInstanceStats(context.Context, *GetInstanceStatsRequest) (*InstanceStats, error) {
return nil, status.Error(codes.Unimplemented, "method GetInstanceStats not implemented")
}
+func (UnimplementedInstanceServiceServer) GetConfigurationStatus(context.Context, *GetConfigurationStatusRequest) (*ConfigurationStatus, error) {
+ return nil, status.Error(codes.Unimplemented, "method GetConfigurationStatus not implemented")
+}
func (UnimplementedInstanceServiceServer) mustEmbedUnimplementedInstanceServiceServer() {}
func (UnimplementedInstanceServiceServer) testEmbeddedByValue() {}
@@ -297,6 +317,24 @@ func _InstanceService_GetInstanceStats_Handler(srv interface{}, ctx context.Cont
return interceptor(ctx, in, info, handler)
}
+func _InstanceService_GetConfigurationStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetConfigurationStatusRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(InstanceServiceServer).GetConfigurationStatus(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: InstanceService_GetConfigurationStatus_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(InstanceServiceServer).GetConfigurationStatus(ctx, req.(*GetConfigurationStatusRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// InstanceService_ServiceDesc is the grpc.ServiceDesc for InstanceService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -328,6 +366,10 @@ var InstanceService_ServiceDesc = grpc.ServiceDesc{
MethodName: "GetInstanceStats",
Handler: _InstanceService_GetInstanceStats_Handler,
},
+ {
+ MethodName: "GetConfigurationStatus",
+ Handler: _InstanceService_GetConfigurationStatus_Handler,
+ },
},
Streams: []grpc.StreamDesc{},
Metadata: "api/instance_service.proto",
diff --git a/proto/gen/openapi.yaml b/proto/gen/openapi.yaml
index 7baac2c62..1c47bef02 100644
--- a/proto/gen/openapi.yaml
+++ b/proto/gen/openapi.yaml
@@ -507,6 +507,27 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Status'
+ /api/instance/configuration:
+ get:
+ tags:
+ - InstanceService
+ description: |-
+ GetConfigurationStatus gets what declarative configuration manages: the managed resources and the last apply.
+ Admin only. It carries resource names and field paths, never a configured value.
+ operationId: InstanceService_GetConfigurationStatus
+ responses:
+ "200":
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ConfigurationStatus'
+ default:
+ description: Default error response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Status'
/api/instance/profile:
get:
tags:
@@ -626,8 +647,8 @@ paths:
tags:
- InstanceService
description: |-
- UpdateInstanceSetting replaces an instance setting. Admin only. Settings configured by the deployment cannot be
- updated. Empty write-only credentials keep the stored values.
+ UpdateInstanceSetting replaces an instance setting. Admin only. Fields declarative configuration manages cannot be
+ changed. Empty write-only credentials keep the stored values.
operationId: InstanceService_UpdateInstanceSetting
parameters:
- name: instance
@@ -3507,6 +3528,53 @@ components:
};
// ...
+ ConfigurationStatus:
+ type: object
+ properties:
+ serial:
+ type: string
+ description: The state record serial; zero before any apply has changed something.
+ configDigest:
+ type: string
+ description: Identifies the applied configuration, with sensitive values masked before hashing.
+ appliedBy:
+ type: string
+ description: The apply path ("cli" or "startup") and the host of the last apply.
+ version:
+ type: string
+ description: The Memos version of the last apply.
+ managedResources:
+ type: array
+ items:
+ $ref: '#/components/schemas/ConfigurationStatus_ManagedResource'
+ description: The resources the configuration manages.
+ applyTime:
+ type: string
+ description: When the last apply that changed something ran.
+ format: date-time
+ description: ConfigurationStatus is what declarative configuration manages on the instance.
+ ConfigurationStatus_ManagedResource:
+ type: object
+ properties:
+ resource:
+ type: string
+ description: |-
+ The resource name.
+ Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ source:
+ type: string
+ description: The configuration file that declares the resource.
+ managedFields:
+ type: array
+ items:
+ type: string
+ description: The field paths, in JSON names, the configuration manages; "*" means the whole resource.
+ ignoredFields:
+ type: array
+ items:
+ type: string
+ description: The managed field paths the configuration does not write after creation, so the API accepts edits to them.
+ description: ManagedResource is one resource the configuration manages.
CreateLinkedIdentityRequest:
required:
- parent
diff --git a/proto/gen/store/instance_setting.pb.go b/proto/gen/store/instance_setting.pb.go
index 2d606c492..a57697018 100644
--- a/proto/gen/store/instance_setting.pb.go
+++ b/proto/gen/store/instance_setting.pb.go
@@ -45,21 +45,26 @@ const (
// USAGE_LIMITS is the key for the ordered usage limits list, read and
// replaced whole through the instance settings API.
InstanceSettingKey_USAGE_LIMITS InstanceSettingKey = 9
+ // CONFIGURATION_STATE is the key for the declarative configuration state
+ // record. It is state, not a setting: the instance settings API never reads
+ // or writes it, and configuration files cannot declare it.
+ InstanceSettingKey_CONFIGURATION_STATE InstanceSettingKey = 10
)
// Enum value maps for InstanceSettingKey.
var (
InstanceSettingKey_name = map[int32]string{
- 0: "INSTANCE_SETTING_KEY_UNSPECIFIED",
- 1: "BASIC",
- 2: "GENERAL",
- 3: "STORAGE",
- 4: "MEMO_RELATED",
- 5: "TAGS",
- 6: "NOTIFICATION",
- 7: "AI",
- 8: "ACCESS",
- 9: "USAGE_LIMITS",
+ 0: "INSTANCE_SETTING_KEY_UNSPECIFIED",
+ 1: "BASIC",
+ 2: "GENERAL",
+ 3: "STORAGE",
+ 4: "MEMO_RELATED",
+ 5: "TAGS",
+ 6: "NOTIFICATION",
+ 7: "AI",
+ 8: "ACCESS",
+ 9: "USAGE_LIMITS",
+ 10: "CONFIGURATION_STATE",
}
InstanceSettingKey_value = map[string]int32{
"INSTANCE_SETTING_KEY_UNSPECIFIED": 0,
@@ -72,6 +77,7 @@ var (
"AI": 7,
"ACCESS": 8,
"USAGE_LIMITS": 9,
+ "CONFIGURATION_STATE": 10,
}
)
@@ -1523,6 +1529,100 @@ func (x *InstanceUsageLimitsSetting) GetLimits() []*InstanceUsageLimitsSetting_U
return nil
}
+// InstanceConfigurationState is the declarative configuration state record: which
+// resources the configuration manages and when it was last applied. It holds no
+// configured value.
+type InstanceConfigurationState struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // serial increases by one with every apply that changes something.
+ Serial int64 `protobuf:"varint,1,opt,name=serial,proto3" json:"serial,omitempty"`
+ // config_digest identifies the applied configuration, with sensitive and
+ // write-only values masked before hashing.
+ ConfigDigest string `protobuf:"bytes,2,opt,name=config_digest,json=configDigest,proto3" json:"config_digest,omitempty"`
+ // applied_ts is the Unix time of the last apply that changed something.
+ AppliedTs int64 `protobuf:"varint,3,opt,name=applied_ts,json=appliedTs,proto3" json:"applied_ts,omitempty"`
+ // applied_by names the apply path ("cli" or "startup") and the host.
+ AppliedBy string `protobuf:"bytes,4,opt,name=applied_by,json=appliedBy,proto3" json:"applied_by,omitempty"`
+ // version is the Memos version that applied.
+ Version string `protobuf:"bytes,5,opt,name=version,proto3" json:"version,omitempty"`
+ // resources are the managed resources.
+ Resources []*InstanceConfigurationState_ManagedResource `protobuf:"bytes,6,rep,name=resources,proto3" json:"resources,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *InstanceConfigurationState) Reset() {
+ *x = InstanceConfigurationState{}
+ mi := &file_store_instance_setting_proto_msgTypes[16]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *InstanceConfigurationState) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*InstanceConfigurationState) ProtoMessage() {}
+
+func (x *InstanceConfigurationState) ProtoReflect() protoreflect.Message {
+ mi := &file_store_instance_setting_proto_msgTypes[16]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use InstanceConfigurationState.ProtoReflect.Descriptor instead.
+func (*InstanceConfigurationState) Descriptor() ([]byte, []int) {
+ return file_store_instance_setting_proto_rawDescGZIP(), []int{16}
+}
+
+func (x *InstanceConfigurationState) GetSerial() int64 {
+ if x != nil {
+ return x.Serial
+ }
+ return 0
+}
+
+func (x *InstanceConfigurationState) GetConfigDigest() string {
+ if x != nil {
+ return x.ConfigDigest
+ }
+ return ""
+}
+
+func (x *InstanceConfigurationState) GetAppliedTs() int64 {
+ if x != nil {
+ return x.AppliedTs
+ }
+ return 0
+}
+
+func (x *InstanceConfigurationState) GetAppliedBy() string {
+ if x != nil {
+ return x.AppliedBy
+ }
+ return ""
+}
+
+func (x *InstanceConfigurationState) GetVersion() string {
+ if x != nil {
+ return x.Version
+ }
+ return ""
+}
+
+func (x *InstanceConfigurationState) GetResources() []*InstanceConfigurationState_ManagedResource {
+ if x != nil {
+ return x.Resources
+ }
+ return nil
+}
+
type InstanceNotificationSetting_EmailSetting struct {
state protoimpl.MessageState `protogen:"open.v1"`
Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
@@ -1541,7 +1641,7 @@ type InstanceNotificationSetting_EmailSetting struct {
func (x *InstanceNotificationSetting_EmailSetting) Reset() {
*x = InstanceNotificationSetting_EmailSetting{}
- mi := &file_store_instance_setting_proto_msgTypes[17]
+ mi := &file_store_instance_setting_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1553,7 +1653,7 @@ func (x *InstanceNotificationSetting_EmailSetting) String() string {
func (*InstanceNotificationSetting_EmailSetting) ProtoMessage() {}
func (x *InstanceNotificationSetting_EmailSetting) ProtoReflect() protoreflect.Message {
- mi := &file_store_instance_setting_proto_msgTypes[17]
+ mi := &file_store_instance_setting_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1662,7 +1762,7 @@ type InstanceUsageLimitsSetting_UsageLimit struct {
func (x *InstanceUsageLimitsSetting_UsageLimit) Reset() {
*x = InstanceUsageLimitsSetting_UsageLimit{}
- mi := &file_store_instance_setting_proto_msgTypes[18]
+ mi := &file_store_instance_setting_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1674,7 +1774,7 @@ func (x *InstanceUsageLimitsSetting_UsageLimit) String() string {
func (*InstanceUsageLimitsSetting_UsageLimit) ProtoMessage() {}
func (x *InstanceUsageLimitsSetting_UsageLimit) ProtoReflect() protoreflect.Message {
- mi := &file_store_instance_setting_proto_msgTypes[18]
+ mi := &file_store_instance_setting_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1732,6 +1832,139 @@ func (x *InstanceUsageLimitsSetting_UsageLimit) GetUploadBytes() int64 {
return 0
}
+// ManagedResource is one resource the configuration manages.
+type InstanceConfigurationState_ManagedResource struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // name is the API resource name, such as identity-providers/company-sso.
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ // kind is IdentityProvider, InstanceSetting, or User.
+ Kind string `protobuf:"bytes,2,opt,name=kind,proto3" json:"kind,omitempty"`
+ // source is the configuration file that declares the resource.
+ Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"`
+ // managed_fields are the JSON-name field paths the configuration manages;
+ // "*" means the whole resource.
+ ManagedFields []string `protobuf:"bytes,4,rep,name=managed_fields,json=managedFields,proto3" json:"managed_fields,omitempty"`
+ // write_only_version is the lifecycle write_only_version last applied.
+ WriteOnlyVersion int32 `protobuf:"varint,5,opt,name=write_only_version,json=writeOnlyVersion,proto3" json:"write_only_version,omitempty"`
+ // applied_ts is the Unix time the resource was last written by an apply.
+ AppliedTs int64 `protobuf:"varint,6,opt,name=applied_ts,json=appliedTs,proto3" json:"applied_ts,omitempty"`
+ // ignored_fields are the lifecycle ignore_changes paths: covered by
+ // managed_fields, but neither written after creation nor protected.
+ IgnoredFields []string `protobuf:"bytes,7,rep,name=ignored_fields,json=ignoredFields,proto3" json:"ignored_fields,omitempty"`
+ // digest identifies the declared value last applied, with sensitive and
+ // write-only values masked, so a later plan can tell drift from a file change.
+ Digest string `protobuf:"bytes,8,opt,name=digest,proto3" json:"digest,omitempty"`
+ // prevent_destroy is the lifecycle prevent_destroy last applied. A removed
+ // entry cannot destroy the resource until an apply has cleared it.
+ PreventDestroy bool `protobuf:"varint,9,opt,name=prevent_destroy,json=preventDestroy,proto3" json:"prevent_destroy,omitempty"`
+ // references are the resource names the declaration names, such as the
+ // users a usage-limits setting lists. The API cannot rename or delete them
+ // while the resource is managed, since the next plan could not resolve them.
+ References []string `protobuf:"bytes,10,rep,name=references,proto3" json:"references,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *InstanceConfigurationState_ManagedResource) Reset() {
+ *x = InstanceConfigurationState_ManagedResource{}
+ mi := &file_store_instance_setting_proto_msgTypes[20]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *InstanceConfigurationState_ManagedResource) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*InstanceConfigurationState_ManagedResource) ProtoMessage() {}
+
+func (x *InstanceConfigurationState_ManagedResource) ProtoReflect() protoreflect.Message {
+ mi := &file_store_instance_setting_proto_msgTypes[20]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use InstanceConfigurationState_ManagedResource.ProtoReflect.Descriptor instead.
+func (*InstanceConfigurationState_ManagedResource) Descriptor() ([]byte, []int) {
+ return file_store_instance_setting_proto_rawDescGZIP(), []int{16, 0}
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetKind() string {
+ if x != nil {
+ return x.Kind
+ }
+ return ""
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetSource() string {
+ if x != nil {
+ return x.Source
+ }
+ return ""
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetManagedFields() []string {
+ if x != nil {
+ return x.ManagedFields
+ }
+ return nil
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetWriteOnlyVersion() int32 {
+ if x != nil {
+ return x.WriteOnlyVersion
+ }
+ return 0
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetAppliedTs() int64 {
+ if x != nil {
+ return x.AppliedTs
+ }
+ return 0
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetIgnoredFields() []string {
+ if x != nil {
+ return x.IgnoredFields
+ }
+ return nil
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetDigest() string {
+ if x != nil {
+ return x.Digest
+ }
+ return ""
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetPreventDestroy() bool {
+ if x != nil {
+ return x.PreventDestroy
+ }
+ return false
+}
+
+func (x *InstanceConfigurationState_ManagedResource) GetReferences() []string {
+ if x != nil {
+ return x.References
+ }
+ return nil
+}
+
var File_store_instance_setting_proto protoreflect.FileDescriptor
const file_store_instance_setting_proto_rawDesc = "" +
@@ -1851,7 +2084,31 @@ const file_store_instance_setting_proto_rawDesc = "" +
"\v_memo_countB\x15\n" +
"\x13_memo_content_bytesB\x10\n" +
"\x0e_storage_bytesB\x0f\n" +
- "\r_upload_bytes*\xb3\x01\n" +
+ "\r_upload_bytes\"\xd8\x04\n" +
+ "\x1aInstanceConfigurationState\x12\x16\n" +
+ "\x06serial\x18\x01 \x01(\x03R\x06serial\x12#\n" +
+ "\rconfig_digest\x18\x02 \x01(\tR\fconfigDigest\x12\x1d\n" +
+ "\n" +
+ "applied_ts\x18\x03 \x01(\x03R\tappliedTs\x12\x1d\n" +
+ "\n" +
+ "applied_by\x18\x04 \x01(\tR\tappliedBy\x12\x18\n" +
+ "\aversion\x18\x05 \x01(\tR\aversion\x12U\n" +
+ "\tresources\x18\x06 \x03(\v27.memos.store.InstanceConfigurationState.ManagedResourceR\tresources\x1a\xcd\x02\n" +
+ "\x0fManagedResource\x12\x12\n" +
+ "\x04name\x18\x01 \x01(\tR\x04name\x12\x12\n" +
+ "\x04kind\x18\x02 \x01(\tR\x04kind\x12\x16\n" +
+ "\x06source\x18\x03 \x01(\tR\x06source\x12%\n" +
+ "\x0emanaged_fields\x18\x04 \x03(\tR\rmanagedFields\x12,\n" +
+ "\x12write_only_version\x18\x05 \x01(\x05R\x10writeOnlyVersion\x12\x1d\n" +
+ "\n" +
+ "applied_ts\x18\x06 \x01(\x03R\tappliedTs\x12%\n" +
+ "\x0eignored_fields\x18\a \x03(\tR\rignoredFields\x12\x16\n" +
+ "\x06digest\x18\b \x01(\tR\x06digest\x12'\n" +
+ "\x0fprevent_destroy\x18\t \x01(\bR\x0epreventDestroy\x12\x1e\n" +
+ "\n" +
+ "references\x18\n" +
+ " \x03(\tR\n" +
+ "references*\xcc\x01\n" +
"\x12InstanceSettingKey\x12$\n" +
" INSTANCE_SETTING_KEY_UNSPECIFIED\x10\x00\x12\t\n" +
"\x05BASIC\x10\x01\x12\v\n" +
@@ -1863,7 +2120,9 @@ const file_store_instance_setting_proto_rawDesc = "" +
"\x02AI\x10\a\x12\n" +
"\n" +
"\x06ACCESS\x10\b\x12\x10\n" +
- "\fUSAGE_LIMITS\x10\t*s\n" +
+ "\fUSAGE_LIMITS\x10\t\x12\x17\n" +
+ "\x13CONFIGURATION_STATE\x10\n" +
+ "*s\n" +
"\vStorageType\x12\x1c\n" +
"\x18STORAGE_TYPE_UNSPECIFIED\x10\x00\x12\x19\n" +
"\x15STORAGE_TYPE_DATABASE\x10\x01\x12\x16\n" +
@@ -1894,33 +2153,35 @@ func file_store_instance_setting_proto_rawDescGZIP() []byte {
}
var file_store_instance_setting_proto_enumTypes = make([]protoimpl.EnumInfo, 5)
-var file_store_instance_setting_proto_msgTypes = make([]protoimpl.MessageInfo, 19)
+var file_store_instance_setting_proto_msgTypes = make([]protoimpl.MessageInfo, 21)
var file_store_instance_setting_proto_goTypes = []any{
- (InstanceSettingKey)(0), // 0: memos.store.InstanceSettingKey
- (StorageType)(0), // 1: memos.store.StorageType
- (AIProviderType)(0), // 2: memos.store.AIProviderType
- (InstanceAccessMode)(0), // 3: memos.store.InstanceAccessMode
- (InstanceStorageSetting_StorageType)(0), // 4: memos.store.InstanceStorageSetting.StorageType
- (*InstanceSetting)(nil), // 5: memos.store.InstanceSetting
- (*InstanceBasicSetting)(nil), // 6: memos.store.InstanceBasicSetting
- (*InstanceGeneralSetting)(nil), // 7: memos.store.InstanceGeneralSetting
- (*InstanceCustomProfile)(nil), // 8: memos.store.InstanceCustomProfile
- (*Storage)(nil), // 9: memos.store.Storage
- (*InstanceStorageSetting)(nil), // 10: memos.store.InstanceStorageSetting
- (*StorageS3Config)(nil), // 11: memos.store.StorageS3Config
- (*InstanceMemoRelatedSetting)(nil), // 12: memos.store.InstanceMemoRelatedSetting
- (*InstanceTagMetadata)(nil), // 13: memos.store.InstanceTagMetadata
- (*InstanceTagsSetting)(nil), // 14: memos.store.InstanceTagsSetting
- (*InstanceNotificationSetting)(nil), // 15: memos.store.InstanceNotificationSetting
- (*InstanceAISetting)(nil), // 16: memos.store.InstanceAISetting
- (*AIProviderConfig)(nil), // 17: memos.store.AIProviderConfig
- (*TranscriptionConfig)(nil), // 18: memos.store.TranscriptionConfig
- (*InstanceAccessSetting)(nil), // 19: memos.store.InstanceAccessSetting
- (*InstanceUsageLimitsSetting)(nil), // 20: memos.store.InstanceUsageLimitsSetting
- nil, // 21: memos.store.InstanceTagsSetting.TagsEntry
- (*InstanceNotificationSetting_EmailSetting)(nil), // 22: memos.store.InstanceNotificationSetting.EmailSetting
- (*InstanceUsageLimitsSetting_UsageLimit)(nil), // 23: memos.store.InstanceUsageLimitsSetting.UsageLimit
- (*color.Color)(nil), // 24: google.type.Color
+ (InstanceSettingKey)(0), // 0: memos.store.InstanceSettingKey
+ (StorageType)(0), // 1: memos.store.StorageType
+ (AIProviderType)(0), // 2: memos.store.AIProviderType
+ (InstanceAccessMode)(0), // 3: memos.store.InstanceAccessMode
+ (InstanceStorageSetting_StorageType)(0), // 4: memos.store.InstanceStorageSetting.StorageType
+ (*InstanceSetting)(nil), // 5: memos.store.InstanceSetting
+ (*InstanceBasicSetting)(nil), // 6: memos.store.InstanceBasicSetting
+ (*InstanceGeneralSetting)(nil), // 7: memos.store.InstanceGeneralSetting
+ (*InstanceCustomProfile)(nil), // 8: memos.store.InstanceCustomProfile
+ (*Storage)(nil), // 9: memos.store.Storage
+ (*InstanceStorageSetting)(nil), // 10: memos.store.InstanceStorageSetting
+ (*StorageS3Config)(nil), // 11: memos.store.StorageS3Config
+ (*InstanceMemoRelatedSetting)(nil), // 12: memos.store.InstanceMemoRelatedSetting
+ (*InstanceTagMetadata)(nil), // 13: memos.store.InstanceTagMetadata
+ (*InstanceTagsSetting)(nil), // 14: memos.store.InstanceTagsSetting
+ (*InstanceNotificationSetting)(nil), // 15: memos.store.InstanceNotificationSetting
+ (*InstanceAISetting)(nil), // 16: memos.store.InstanceAISetting
+ (*AIProviderConfig)(nil), // 17: memos.store.AIProviderConfig
+ (*TranscriptionConfig)(nil), // 18: memos.store.TranscriptionConfig
+ (*InstanceAccessSetting)(nil), // 19: memos.store.InstanceAccessSetting
+ (*InstanceUsageLimitsSetting)(nil), // 20: memos.store.InstanceUsageLimitsSetting
+ (*InstanceConfigurationState)(nil), // 21: memos.store.InstanceConfigurationState
+ nil, // 22: memos.store.InstanceTagsSetting.TagsEntry
+ (*InstanceNotificationSetting_EmailSetting)(nil), // 23: memos.store.InstanceNotificationSetting.EmailSetting
+ (*InstanceUsageLimitsSetting_UsageLimit)(nil), // 24: memos.store.InstanceUsageLimitsSetting.UsageLimit
+ (*InstanceConfigurationState_ManagedResource)(nil), // 25: memos.store.InstanceConfigurationState.ManagedResource
+ (*color.Color)(nil), // 26: google.type.Color
}
var file_store_instance_setting_proto_depIdxs = []int32{
0, // 0: memos.store.InstanceSetting.key:type_name -> memos.store.InstanceSettingKey
@@ -1939,20 +2200,21 @@ var file_store_instance_setting_proto_depIdxs = []int32{
4, // 13: memos.store.InstanceStorageSetting.storage_type:type_name -> memos.store.InstanceStorageSetting.StorageType
11, // 14: memos.store.InstanceStorageSetting.s3_config:type_name -> memos.store.StorageS3Config
9, // 15: memos.store.InstanceStorageSetting.storages:type_name -> memos.store.Storage
- 24, // 16: memos.store.InstanceTagMetadata.background_color:type_name -> google.type.Color
- 21, // 17: memos.store.InstanceTagsSetting.tags:type_name -> memos.store.InstanceTagsSetting.TagsEntry
- 22, // 18: memos.store.InstanceNotificationSetting.email:type_name -> memos.store.InstanceNotificationSetting.EmailSetting
+ 26, // 16: memos.store.InstanceTagMetadata.background_color:type_name -> google.type.Color
+ 22, // 17: memos.store.InstanceTagsSetting.tags:type_name -> memos.store.InstanceTagsSetting.TagsEntry
+ 23, // 18: memos.store.InstanceNotificationSetting.email:type_name -> memos.store.InstanceNotificationSetting.EmailSetting
17, // 19: memos.store.InstanceAISetting.providers:type_name -> memos.store.AIProviderConfig
18, // 20: memos.store.InstanceAISetting.transcription:type_name -> memos.store.TranscriptionConfig
2, // 21: memos.store.AIProviderConfig.type:type_name -> memos.store.AIProviderType
3, // 22: memos.store.InstanceAccessSetting.access_mode:type_name -> memos.store.InstanceAccessMode
- 23, // 23: memos.store.InstanceUsageLimitsSetting.limits:type_name -> memos.store.InstanceUsageLimitsSetting.UsageLimit
- 13, // 24: memos.store.InstanceTagsSetting.TagsEntry.value:type_name -> memos.store.InstanceTagMetadata
- 25, // [25:25] is the sub-list for method output_type
- 25, // [25:25] is the sub-list for method input_type
- 25, // [25:25] is the sub-list for extension type_name
- 25, // [25:25] is the sub-list for extension extendee
- 0, // [0:25] is the sub-list for field type_name
+ 24, // 23: memos.store.InstanceUsageLimitsSetting.limits:type_name -> memos.store.InstanceUsageLimitsSetting.UsageLimit
+ 25, // 24: memos.store.InstanceConfigurationState.resources:type_name -> memos.store.InstanceConfigurationState.ManagedResource
+ 13, // 25: memos.store.InstanceTagsSetting.TagsEntry.value:type_name -> memos.store.InstanceTagMetadata
+ 26, // [26:26] is the sub-list for method output_type
+ 26, // [26:26] is the sub-list for method input_type
+ 26, // [26:26] is the sub-list for extension type_name
+ 26, // [26:26] is the sub-list for extension extendee
+ 0, // [0:26] is the sub-list for field type_name
}
func init() { file_store_instance_setting_proto_init() }
@@ -1974,14 +2236,14 @@ func file_store_instance_setting_proto_init() {
file_store_instance_setting_proto_msgTypes[4].OneofWrappers = []any{
(*Storage_S3Config)(nil),
}
- file_store_instance_setting_proto_msgTypes[18].OneofWrappers = []any{}
+ file_store_instance_setting_proto_msgTypes[19].OneofWrappers = []any{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_instance_setting_proto_rawDesc), len(file_store_instance_setting_proto_rawDesc)),
NumEnums: 5,
- NumMessages: 19,
+ NumMessages: 21,
NumExtensions: 0,
NumServices: 0,
},
diff --git a/proto/store/instance_setting.proto b/proto/store/instance_setting.proto
index 2ec5efb76..49ad18726 100644
--- a/proto/store/instance_setting.proto
+++ b/proto/store/instance_setting.proto
@@ -27,6 +27,10 @@ enum InstanceSettingKey {
// USAGE_LIMITS is the key for the ordered usage limits list, read and
// replaced whole through the instance settings API.
USAGE_LIMITS = 9;
+ // CONFIGURATION_STATE is the key for the declarative configuration state
+ // record. It is state, not a setting: the instance settings API never reads
+ // or writes it, and configuration files cannot declare it.
+ CONFIGURATION_STATE = 10;
}
message InstanceSetting {
@@ -269,3 +273,52 @@ message InstanceUsageLimitsSetting {
optional int64 upload_bytes = 7;
}
}
+
+// InstanceConfigurationState is the declarative configuration state record: which
+// resources the configuration manages and when it was last applied. It holds no
+// configured value.
+message InstanceConfigurationState {
+ // serial increases by one with every apply that changes something.
+ int64 serial = 1;
+ // config_digest identifies the applied configuration, with sensitive and
+ // write-only values masked before hashing.
+ string config_digest = 2;
+ // applied_ts is the Unix time of the last apply that changed something.
+ int64 applied_ts = 3;
+ // applied_by names the apply path ("cli" or "startup") and the host.
+ string applied_by = 4;
+ // version is the Memos version that applied.
+ string version = 5;
+ // resources are the managed resources.
+ repeated ManagedResource resources = 6;
+
+ // ManagedResource is one resource the configuration manages.
+ message ManagedResource {
+ // name is the API resource name, such as identity-providers/company-sso.
+ string name = 1;
+ // kind is IdentityProvider, InstanceSetting, or User.
+ string kind = 2;
+ // source is the configuration file that declares the resource.
+ string source = 3;
+ // managed_fields are the JSON-name field paths the configuration manages;
+ // "*" means the whole resource.
+ repeated string managed_fields = 4;
+ // write_only_version is the lifecycle write_only_version last applied.
+ int32 write_only_version = 5;
+ // applied_ts is the Unix time the resource was last written by an apply.
+ int64 applied_ts = 6;
+ // ignored_fields are the lifecycle ignore_changes paths: covered by
+ // managed_fields, but neither written after creation nor protected.
+ repeated string ignored_fields = 7;
+ // digest identifies the declared value last applied, with sensitive and
+ // write-only values masked, so a later plan can tell drift from a file change.
+ string digest = 8;
+ // prevent_destroy is the lifecycle prevent_destroy last applied. A removed
+ // entry cannot destroy the resource until an apply has cleared it.
+ bool prevent_destroy = 9;
+ // references are the resource names the declaration names, such as the
+ // users a usage-limits setting lists. The API cannot rename or delete them
+ // while the resource is managed, since the next plan could not resolve them.
+ repeated string references = 10;
+ }
+}
diff --git a/server/api/acl_config_test.go b/server/api/acl_config_test.go
index 10a2ee6de..022306beb 100644
--- a/server/api/acl_config_test.go
+++ b/server/api/acl_config_test.go
@@ -60,6 +60,7 @@ func TestProtectedMethodsRequireAuth(t *testing.T) {
// Instance Service - admin operations
"/memos.api.InstanceService/UpdateInstanceSetting",
"/memos.api.InstanceService/TestInstanceEmailSetting",
+ "/memos.api.InstanceService/GetConfigurationStatus",
// User Service - modification operations
"/memos.api.UserService/ListUsers",
"/memos.api.UserService/UpdateUser",
diff --git a/server/api/auth_service_sso.go b/server/api/auth_service_sso.go
index 5e3771fc2..92bfb9094 100644
--- a/server/api/auth_service_sso.go
+++ b/server/api/auth_service_sso.go
@@ -10,6 +10,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
+ coreuser "github.com/usememos/memos/core/user"
"github.com/usememos/memos/internal/random"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/provider/idp"
@@ -163,7 +164,7 @@ func (s *APIService) createSSOUser(
}
// Adopt any valid external identifier. Invalid names fall back to an opaque UUID.
- if err := validateWritableUsername(userInfo.Identifier); err == nil {
+ if err := coreuser.ValidateUsername(userInfo.Identifier); err == nil {
user, err := tryUsername(userInfo.Identifier)
if err != nil {
return nil, err
diff --git a/server/api/connect_services.go b/server/api/connect_services.go
index 33b157cfa..838c31b6a 100644
--- a/server/api/connect_services.go
+++ b/server/api/connect_services.go
@@ -64,6 +64,14 @@ func (s *ConnectServiceHandler) GetInstanceStats(ctx context.Context, req *conne
return connect.NewResponse(resp), nil
}
+func (s *ConnectServiceHandler) GetConfigurationStatus(ctx context.Context, req *connect.Request[apipb.GetConfigurationStatusRequest]) (*connect.Response[apipb.ConfigurationStatus], error) {
+ resp, err := s.APIService.GetConfigurationStatus(ctx, req.Msg)
+ if err != nil {
+ return nil, convertGRPCError(err)
+ }
+ return connect.NewResponse(resp), nil
+}
+
// AuthService
//
// Auth service methods need special handling for response headers (cookies).
diff --git a/server/api/idp_service.go b/server/api/idp_service.go
index aad94ec70..80538e1eb 100644
--- a/server/api/idp_service.go
+++ b/server/api/idp_service.go
@@ -2,13 +2,15 @@ package api
import (
"context"
- "fmt"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
+ "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/emptypb"
+ "github.com/usememos/memos/core/configuration"
+ "github.com/usememos/memos/core/identityprovider"
apipb "github.com/usememos/memos/proto/gen/api"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
@@ -26,16 +28,21 @@ func (s *APIService) CreateIdentityProvider(ctx context.Context, request *apipb.
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
+ if request.IdentityProvider == nil {
+ return nil, status.Errorf(codes.InvalidArgument, "identity provider is required")
+ }
idpUID, err := ValidateAndGenerateUID(request.IdentityProviderId)
if err != nil {
return nil, err
}
- if s.Store.IsIdentityProviderDeploymentConfigured(idpUID) {
- return nil, status.Errorf(codes.FailedPrecondition, "identity provider %q is configured by the deployment", idpUID)
+ if err := s.checkManagedExistence(ctx, identityprovider.NamePrefix+idpUID); err != nil {
+ return nil, err
}
-
- storeIdp := convertIdentityProviderToStore(request.IdentityProvider)
+ storeIdp := identityprovider.ToStore(request.IdentityProvider)
storeIdp.Uid = idpUID
+ if err := identityprovider.Validate(storeIdp); err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "invalid identity provider: %v", err)
+ }
identityProvider, err := s.Store.CreateIdentityProvider(ctx, storeIdp)
if err != nil {
@@ -89,6 +96,9 @@ func (s *APIService) UpdateIdentityProvider(ctx context.Context, request *apipb.
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
+ if request.IdentityProvider == nil {
+ return nil, status.Errorf(codes.InvalidArgument, "identity provider is required")
+ }
if request.UpdateMask == nil || len(request.UpdateMask.Paths) == 0 {
return nil, status.Errorf(codes.InvalidArgument, "update_mask is required")
}
@@ -97,12 +107,8 @@ func (s *APIService) UpdateIdentityProvider(ctx context.Context, request *apipb.
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid identity provider name: %v", err)
}
- if s.Store.IsIdentityProviderDeploymentConfigured(uid) {
- return nil, status.Errorf(codes.FailedPrecondition, "identity provider %q is configured by the deployment", uid)
- }
-
// Look up the IdP by UID to get the internal ID for update.
- existing, err := s.Store.GetStoredIdentityProvider(ctx, &store.FindIdentityProvider{UID: &uid})
+ existing, err := s.Store.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: &uid})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get identity provider, error: %+v", err)
}
@@ -121,7 +127,7 @@ func (s *APIService) UpdateIdentityProvider(ctx context.Context, request *apipb.
case "identifier_filter":
update.IdentifierFilter = &request.IdentityProvider.IdentifierFilter
case "config":
- update.Config = convertIdentityProviderConfigToStore(request.IdentityProvider.Type, request.IdentityProvider.Config)
+ update.Config = identityprovider.ConfigToStore(request.IdentityProvider.Type, request.IdentityProvider.Config)
default:
// Ignore unsupported fields
}
@@ -136,6 +142,25 @@ func (s *APIService) UpdateIdentityProvider(ctx context.Context, request *apipb.
}
}
+ // Validate the provider as it will be stored, not the partial update.
+ merged := proto.CloneOf(existing)
+ if update.Name != nil {
+ merged.Name = *update.Name
+ }
+ if update.IdentifierFilter != nil {
+ merged.IdentifierFilter = *update.IdentifierFilter
+ }
+ if update.Config != nil {
+ merged.Config = update.Config
+ }
+ if err := identityprovider.Validate(merged); err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "invalid identity provider: %v", err)
+ }
+ changed := configuration.ChangedPaths(identityprovider.FromStore(existing), identityprovider.FromStore(merged))
+ if err := s.checkManagedChange(ctx, identityprovider.NamePrefix+uid, changed); err != nil {
+ return nil, err
+ }
+
identityProvider, err := s.Store.UpdateIdentityProvider(ctx, update)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to update identity provider, error: %+v", err)
@@ -159,12 +184,11 @@ func (s *APIService) DeleteIdentityProvider(ctx context.Context, request *apipb.
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid identity provider name: %v", err)
}
- if s.Store.IsIdentityProviderDeploymentConfigured(uid) {
- return nil, status.Errorf(codes.FailedPrecondition, "identity provider %q is configured by the deployment", uid)
+ if err := s.checkManagedExistence(ctx, identityprovider.NamePrefix+uid); err != nil {
+ return nil, err
}
-
// Look up the IdP by UID to get the internal ID for deletion.
- identityProvider, err := s.Store.GetStoredIdentityProvider(ctx, &store.FindIdentityProvider{UID: &uid})
+ identityProvider, err := s.Store.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: &uid})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to check identity provider existence: %v", err)
}
@@ -181,68 +205,12 @@ func (s *APIService) DeleteIdentityProvider(ctx context.Context, request *apipb.
return &emptypb.Empty{}, nil
}
-func convertIdentityProviderFromStore(identityProvider *storepb.IdentityProvider) *apipb.IdentityProvider {
- temp := &apipb.IdentityProvider{
- Name: fmt.Sprintf("%s%s", IdentityProviderNamePrefix, identityProvider.Uid),
- Title: identityProvider.Name,
- IdentifierFilter: identityProvider.IdentifierFilter,
- Type: apipb.IdentityProvider_Type(apipb.IdentityProvider_Type_value[identityProvider.Type.String()]),
- }
- if identityProvider.Type == storepb.IdentityProvider_OAUTH2 {
- oauth2Config := identityProvider.Config.GetOauth2Config()
- temp.Config = &apipb.IdentityProviderConfig{
- Config: &apipb.IdentityProviderConfig_Oauth2Config{
- Oauth2Config: &apipb.OAuth2Config{
- ClientId: oauth2Config.ClientId,
- // ClientSecret is write-only: never returned in responses.
- AuthUrl: oauth2Config.AuthUrl,
- TokenUrl: oauth2Config.TokenUrl,
- UserInfoUrl: oauth2Config.UserInfoUrl,
- Scopes: oauth2Config.Scopes,
- FieldMapping: &apipb.FieldMapping{
- Identifier: oauth2Config.FieldMapping.Identifier,
- DisplayName: oauth2Config.FieldMapping.DisplayName,
- Email: oauth2Config.FieldMapping.Email,
- AvatarUrl: oauth2Config.FieldMapping.AvatarUrl,
- },
- },
- },
- }
- }
- return temp
-}
-
-func convertIdentityProviderToStore(identityProvider *apipb.IdentityProvider) *storepb.IdentityProvider {
- temp := &storepb.IdentityProvider{
- Name: identityProvider.Title,
- IdentifierFilter: identityProvider.IdentifierFilter,
- Type: storepb.IdentityProvider_Type(storepb.IdentityProvider_Type_value[identityProvider.Type.String()]),
- Config: convertIdentityProviderConfigToStore(identityProvider.Type, identityProvider.Config),
- }
- return temp
-}
-
-func convertIdentityProviderConfigToStore(identityProviderType apipb.IdentityProvider_Type, config *apipb.IdentityProviderConfig) *storepb.IdentityProviderConfig {
- if identityProviderType == apipb.IdentityProvider_OAUTH2 {
- oauth2Config := config.GetOauth2Config()
- return &storepb.IdentityProviderConfig{
- Config: &storepb.IdentityProviderConfig_Oauth2Config{
- Oauth2Config: &storepb.OAuth2Config{
- ClientId: oauth2Config.ClientId,
- ClientSecret: oauth2Config.ClientSecret,
- AuthUrl: oauth2Config.AuthUrl,
- TokenUrl: oauth2Config.TokenUrl,
- UserInfoUrl: oauth2Config.UserInfoUrl,
- Scopes: oauth2Config.Scopes,
- FieldMapping: &storepb.FieldMapping{
- Identifier: oauth2Config.FieldMapping.Identifier,
- DisplayName: oauth2Config.FieldMapping.DisplayName,
- Email: oauth2Config.FieldMapping.Email,
- AvatarUrl: oauth2Config.FieldMapping.AvatarUrl,
- },
- },
- },
- }
+// convertIdentityProviderFromStore converts a stored provider for a response.
+// The client secret is write-only and never returned.
+func convertIdentityProviderFromStore(provider *storepb.IdentityProvider) *apipb.IdentityProvider {
+ result := identityprovider.FromStore(provider)
+ if oauth2Config := result.GetConfig().GetOauth2Config(); oauth2Config != nil {
+ oauth2Config.ClientSecret = ""
}
- return nil
+ return result
}
diff --git a/server/api/instance_service.go b/server/api/instance_service.go
index b95f5500b..5b07b239d 100644
--- a/server/api/instance_service.go
+++ b/server/api/instance_service.go
@@ -8,20 +8,18 @@ import (
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
+ "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/emptypb"
+ "github.com/usememos/memos/core/configuration"
+ "github.com/usememos/memos/core/instancesetting"
"github.com/usememos/memos/core/notification"
apipb "github.com/usememos/memos/proto/gen/api"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
)
-const (
- maxTranscriptionConfigModelLength = 256
- maxTranscriptionConfigLanguageLength = 32
- maxTranscriptionConfigPromptLength = 4096
- maxBatchGetInstanceSettings = 100
-)
+const maxBatchGetInstanceSettings = 100
type instanceSettingCaller struct {
user *store.User
@@ -73,7 +71,7 @@ func (s *APIService) GetInstanceProfile(ctx context.Context, _ *apipb.GetInstanc
Admin: admin, // signed-in callers only; may be nil even on a populated instance
Commit: s.Profile.Commit,
NeedsSetup: len(users) == 0,
- AccessMode: convertInstanceAccessModeFromStore(accessSetting.AccessMode),
+ AccessMode: instancesetting.AccessModeFromStore(accessSetting.AccessMode),
Challenge: s.challengeProfile(),
}
return instanceProfile, nil
@@ -215,23 +213,13 @@ func (s *APIService) UpdateInstanceSetting(ctx context.Context, request *apipb.U
if request.InstanceSetting == nil {
return nil, status.Errorf(codes.InvalidArgument, "instance setting is required")
}
- settingKeyString, err := ExtractInstanceSettingKeyFromName(request.InstanceSetting.Name)
- if err != nil {
+ if _, err := ExtractInstanceSettingKeyFromName(request.InstanceSetting.Name); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid instance setting name: %v", err)
}
- settingKey := storepb.InstanceSettingKey(storepb.InstanceSettingKey_value[settingKeyString])
- if s.Store.IsInstanceSettingDeploymentConfigured(settingKey) {
- return nil, status.Errorf(codes.FailedPrecondition, "instance setting %q is configured by the deployment", settingKeyString)
- }
-
// TODO: Apply update_mask if specified
_ = request.UpdateMask
- if err := validateInstanceSetting(request.InstanceSetting); err != nil {
- return nil, status.Errorf(codes.InvalidArgument, "invalid instance setting: %v", err)
- }
-
- updateSetting := convertInstanceSettingToStore(request.InstanceSetting)
+ updateSetting := instancesetting.ToStore(request.InstanceSetting)
if updateSetting.Key == storepb.InstanceSettingKey_USAGE_LIMITS {
usageLimits, err := s.convertUsageLimitsSettingToStore(ctx, request.InstanceSetting.GetUsageLimitsSetting())
if err != nil {
@@ -242,11 +230,13 @@ func (s *APIService) UpdateInstanceSetting(ctx context.Context, request *apipb.U
// Preserve write-only credential fields when the caller sends an empty value.
// An empty string means "no change", not "clear the credential".
+ var existingSetting *storepb.InstanceSetting
switch updateSetting.Key {
- case storepb.InstanceSettingKey_NOTIFICATION:
- if err := store.ValidateInstanceNotificationSetting(updateSetting.GetNotificationSetting()); err != nil {
+ case storepb.InstanceSettingKey_TAGS:
+ if err := validateInstanceTagsSetting(request.InstanceSetting.GetTagsSetting()); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid instance setting: %v", err)
}
+ case storepb.InstanceSettingKey_NOTIFICATION:
if notif := updateSetting.GetNotificationSetting(); notif != nil && notif.Email != nil && notif.Email.SmtpPassword == "" {
existing, err := s.Store.GetInstanceNotificationSetting(ctx)
if err == nil && existing != nil && existing.Email != nil {
@@ -267,6 +257,10 @@ func (s *APIService) UpdateInstanceSetting(ctx context.Context, request *apipb.U
if err := store.PrepareInstanceStorageSettingUpdate(updateSetting.GetStorageSetting(), existing); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid storage setting: %v", err)
}
+ existingSetting = &storepb.InstanceSetting{
+ Key: storepb.InstanceSettingKey_STORAGE,
+ Value: &storepb.InstanceSetting_StorageSetting{StorageSetting: existing},
+ }
case storepb.InstanceSettingKey_AI:
if err := s.prepareInstanceAISettingForUpdate(ctx, updateSetting.GetAiSetting()); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid AI setting: %v", err)
@@ -274,6 +268,12 @@ func (s *APIService) UpdateInstanceSetting(ctx context.Context, request *apipb.U
default:
// No credential preservation needed for other setting types.
}
+ if err := instancesetting.ValidateUpdate(updateSetting, existingSetting); err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "invalid instance setting: %v", err)
+ }
+ if err := s.checkManagedSettingChange(ctx, updateSetting); err != nil {
+ return nil, err
+ }
var instanceSetting *storepb.InstanceSetting
if updateSetting.Key == storepb.InstanceSettingKey_GENERAL {
@@ -294,6 +294,39 @@ func (s *APIService) UpdateInstanceSetting(ctx context.Context, request *apipb.U
return s.convertInstanceSettingResponse(ctx, instanceSetting)
}
+// checkManagedSettingChange refuses an update that changes managed fields of
+// a setting the configuration manages. It compares the stored value with the
+// prepared update, so resending managed values unchanged passes.
+func (s *APIService) checkManagedSettingChange(ctx context.Context, update *storepb.InstanceSetting) error {
+ name := instancesetting.NamePrefix + update.Key.String()
+ // Most settings are not managed; skip reading and diffing the stored value for those.
+ state, err := s.Store.GetConfigurationState(ctx)
+ if err != nil {
+ return status.Errorf(codes.Internal, "failed to read the configuration state: %v", err)
+ }
+ if !configuration.Manages(state, name) {
+ return nil
+ }
+ stored, err := s.Store.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: update.Key.String()})
+ if err != nil {
+ return status.Errorf(codes.Internal, "failed to read instance setting: %v", err)
+ }
+ var changed []string
+ if update.Key == storepb.InstanceSettingKey_USAGE_LIMITS {
+ // Usage limits name users only in the API form, so compare stored values.
+ if !proto.Equal(stored.GetUsageLimitsSetting(), update.GetUsageLimitsSetting()) {
+ changed = []string{"usageLimitsSetting"}
+ }
+ } else {
+ var before proto.Message
+ if stored != nil {
+ before = instancesetting.FromStore(stored)
+ }
+ changed = configuration.ChangedPaths(before, instancesetting.FromStore(update))
+ }
+ return managedStatus(configuration.CheckChange(state, name, changed))
+}
+
// challengeProfile describes the configured challenge so the web app can
// render the matching widget, or nil when none is configured.
func (s *APIService) challengeProfile() *apipb.InstanceProfile_Challenge {
@@ -351,7 +384,7 @@ func (s *APIService) resolveTestEmailSetting(ctx context.Context, requestEmail *
return existing.GetEmail(), nil
}
- emailSetting := convertInstanceNotificationSettingToStore(&apipb.InstanceSetting_NotificationSetting{Email: requestEmail}).GetEmail()
+ emailSetting := instancesetting.NotificationSettingToStore(&apipb.InstanceSetting_NotificationSetting{Email: requestEmail}).GetEmail()
if emailSetting.SmtpPassword != "" {
return emailSetting, nil
}
diff --git a/server/api/instance_service_configuration.go b/server/api/instance_service_configuration.go
new file mode 100644
index 000000000..01b4e0dfe
--- /dev/null
+++ b/server/api/instance_service_configuration.go
@@ -0,0 +1,120 @@
+package api
+
+import (
+ "context"
+ stderrors "errors"
+ "strings"
+ "time"
+
+ "google.golang.org/genproto/googleapis/rpc/errdetails"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+ "google.golang.org/protobuf/types/known/timestamppb"
+
+ "github.com/usememos/memos/core/configuration"
+ apipb "github.com/usememos/memos/proto/gen/api"
+ "github.com/usememos/memos/store"
+)
+
+// reasonManagedByConfiguration is the ErrorInfo reason of a write refused
+// because declarative configuration manages what it would change.
+const reasonManagedByConfiguration = "MANAGED_BY_CONFIGURATION"
+
+func (s *APIService) GetConfigurationStatus(ctx context.Context, _ *apipb.GetConfigurationStatusRequest) (*apipb.ConfigurationStatus, error) {
+ user, err := s.fetchCurrentUser(ctx)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
+ }
+ if user == nil {
+ return nil, status.Errorf(codes.Unauthenticated, "user not authenticated")
+ }
+ if user.Role != store.RoleAdmin {
+ return nil, status.Errorf(codes.PermissionDenied, "permission denied")
+ }
+ state, err := s.Store.GetConfigurationState(ctx)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, "failed to read the configuration state: %v", err)
+ }
+ result := &apipb.ConfigurationStatus{
+ Serial: state.Serial,
+ ConfigDigest: state.ConfigDigest,
+ AppliedBy: state.AppliedBy,
+ Version: state.Version,
+ }
+ if state.AppliedTs != 0 {
+ result.ApplyTime = timestamppb.New(time.Unix(state.AppliedTs, 0))
+ }
+ for _, resource := range state.Resources {
+ result.ManagedResources = append(result.ManagedResources, &apipb.ConfigurationStatus_ManagedResource{
+ Resource: resource.Name,
+ Source: resource.Source,
+ ManagedFields: resource.ManagedFields,
+ IgnoredFields: resource.IgnoredFields,
+ })
+ }
+ return result, nil
+}
+
+// checkManagedChange refuses a write that would change fields of a resource
+// the configuration manages; changed lists the JSON-name paths the write
+// changes. The configuration state is read from the database, so every
+// replica enforces ownership whether or not it read the files.
+func (s *APIService) checkManagedChange(ctx context.Context, resource string, changed []string) error {
+ if len(changed) == 0 {
+ // A write that changes nothing is never refused.
+ return nil
+ }
+ state, err := s.Store.GetConfigurationState(ctx)
+ if err != nil {
+ return status.Errorf(codes.Internal, "failed to read the configuration state: %v", err)
+ }
+ return managedStatus(configuration.CheckChange(state, resource, changed))
+}
+
+// checkManagedExistence refuses creating or deleting a resource the
+// configuration manages.
+func (s *APIService) checkManagedExistence(ctx context.Context, resource string) error {
+ state, err := s.Store.GetConfigurationState(ctx)
+ if err != nil {
+ return status.Errorf(codes.Internal, "failed to read the configuration state: %v", err)
+ }
+ return managedStatus(configuration.CheckExistence(state, resource))
+}
+
+// checkManagedReference refuses renaming or deleting a resource that a
+// resource the configuration manages names, such as a user a managed
+// usage-limits setting lists.
+func (s *APIService) checkManagedReference(ctx context.Context, resource string) error {
+ state, err := s.Store.GetConfigurationState(ctx)
+ if err != nil {
+ return status.Errorf(codes.Internal, "failed to read the configuration state: %v", err)
+ }
+ return managedStatus(configuration.CheckReference(state, resource))
+}
+
+// managedStatus turns a refusal into FAILED_PRECONDITION with an ErrorInfo
+// naming the resource, the file that declares it, and the fields.
+func managedStatus(err error) error {
+ var managed *configuration.ManagedError
+ if !stderrors.As(err, &managed) {
+ return err
+ }
+ st := status.New(codes.FailedPrecondition, managed.Error())
+ metadata := map[string]string{
+ "resource": managed.Resource,
+ "source": managed.Source,
+ "fields": strings.Join(managed.Fields, ","),
+ }
+ if managed.ReferencedBy != "" {
+ metadata["referenced_by"] = managed.ReferencedBy
+ }
+ detailed, detailErr := st.WithDetails(&errdetails.ErrorInfo{
+ Reason: reasonManagedByConfiguration,
+ Domain: errorInfoDomain,
+ Metadata: metadata,
+ })
+ if detailErr != nil {
+ return st.Err()
+ }
+ return detailed.Err()
+}
diff --git a/server/api/instance_service_converters.go b/server/api/instance_service_converters.go
index f8aa607ca..e1379da45 100644
--- a/server/api/instance_service_converters.go
+++ b/server/api/instance_service_converters.go
@@ -1,431 +1,42 @@
package api
import (
- "fmt"
-
+ "github.com/usememos/memos/core/instancesetting"
apipb "github.com/usememos/memos/proto/gen/api"
storepb "github.com/usememos/memos/proto/gen/store"
)
-func convertInstanceSettingFromStore(setting *storepb.InstanceSetting) *apipb.InstanceSetting {
- instanceSetting := &apipb.InstanceSetting{
- Name: fmt.Sprintf("instance/settings/%s", setting.Key.String()),
- }
- switch setting.Value.(type) {
- case *storepb.InstanceSetting_GeneralSetting:
- instanceSetting.Value = &apipb.InstanceSetting_GeneralSetting_{
- GeneralSetting: convertInstanceGeneralSettingFromStore(setting.GetGeneralSetting()),
- }
- case *storepb.InstanceSetting_StorageSetting:
- instanceSetting.Value = &apipb.InstanceSetting_StorageSetting_{
- StorageSetting: convertInstanceStorageSettingFromStore(setting.GetStorageSetting()),
- }
- case *storepb.InstanceSetting_MemoRelatedSetting:
- instanceSetting.Value = &apipb.InstanceSetting_MemoRelatedSetting_{
- MemoRelatedSetting: convertInstanceMemoRelatedSettingFromStore(setting.GetMemoRelatedSetting()),
- }
- case *storepb.InstanceSetting_TagsSetting:
- instanceSetting.Value = &apipb.InstanceSetting_TagsSetting_{
- TagsSetting: convertInstanceTagsSettingFromStore(setting.GetTagsSetting()),
- }
- case *storepb.InstanceSetting_NotificationSetting:
- instanceSetting.Value = &apipb.InstanceSetting_NotificationSetting_{
- NotificationSetting: convertInstanceNotificationSettingFromStore(setting.GetNotificationSetting()),
- }
- case *storepb.InstanceSetting_AiSetting:
- instanceSetting.Value = &apipb.InstanceSetting_AiSetting{
- AiSetting: convertInstanceAISettingFromStore(setting.GetAiSetting()),
- }
- case *storepb.InstanceSetting_AccessSetting:
- instanceSetting.Value = &apipb.InstanceSetting_AccessSetting_{
- AccessSetting: convertInstanceAccessSettingFromStore(setting.GetAccessSetting()),
- }
- default:
- // Leave Value unset for unsupported setting variants.
- }
- return instanceSetting
-}
-
-func convertInstanceSettingToStore(setting *apipb.InstanceSetting) *storepb.InstanceSetting {
- settingKeyString, _ := ExtractInstanceSettingKeyFromName(setting.Name)
- instanceSetting := &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey(storepb.InstanceSettingKey_value[settingKeyString]),
- Value: &storepb.InstanceSetting_GeneralSetting{
- GeneralSetting: convertInstanceGeneralSettingToStore(setting.GetGeneralSetting()),
- },
- }
- switch instanceSetting.Key {
- case storepb.InstanceSettingKey_GENERAL:
- instanceSetting.Value = &storepb.InstanceSetting_GeneralSetting{
- GeneralSetting: convertInstanceGeneralSettingToStore(setting.GetGeneralSetting()),
- }
- case storepb.InstanceSettingKey_STORAGE:
- instanceSetting.Value = &storepb.InstanceSetting_StorageSetting{
- StorageSetting: convertInstanceStorageSettingToStore(setting.GetStorageSetting()),
- }
- case storepb.InstanceSettingKey_MEMO_RELATED:
- instanceSetting.Value = &storepb.InstanceSetting_MemoRelatedSetting{
- MemoRelatedSetting: convertInstanceMemoRelatedSettingToStore(setting.GetMemoRelatedSetting()),
- }
- case storepb.InstanceSettingKey_TAGS:
- instanceSetting.Value = &storepb.InstanceSetting_TagsSetting{
- TagsSetting: convertInstanceTagsSettingToStore(setting.GetTagsSetting()),
- }
- case storepb.InstanceSettingKey_NOTIFICATION:
- instanceSetting.Value = &storepb.InstanceSetting_NotificationSetting{
- NotificationSetting: convertInstanceNotificationSettingToStore(setting.GetNotificationSetting()),
- }
- case storepb.InstanceSettingKey_AI:
- instanceSetting.Value = &storepb.InstanceSetting_AiSetting{
- AiSetting: convertInstanceAISettingToStore(setting.GetAiSetting()),
- }
- case storepb.InstanceSettingKey_ACCESS:
- instanceSetting.Value = &storepb.InstanceSetting_AccessSetting{
- AccessSetting: convertInstanceAccessSettingToStore(setting.GetAccessSetting()),
- }
- default:
- // Keep the default GeneralSetting value
- }
- return instanceSetting
-}
-
-func convertInstanceAccessSettingFromStore(setting *storepb.InstanceAccessSetting) *apipb.InstanceSetting_AccessSetting {
- if setting == nil {
- return nil
- }
- return &apipb.InstanceSetting_AccessSetting{
- AccessMode: convertInstanceAccessModeFromStore(setting.AccessMode),
- }
-}
-
-func convertInstanceAccessSettingToStore(setting *apipb.InstanceSetting_AccessSetting) *storepb.InstanceAccessSetting {
- if setting == nil {
- return nil
- }
- return &storepb.InstanceAccessSetting{
- AccessMode: storepb.InstanceAccessMode(setting.AccessMode),
- }
-}
-
-func convertInstanceAccessModeFromStore(mode storepb.InstanceAccessMode) apipb.InstanceAccessMode {
- return apipb.InstanceAccessMode(mode)
-}
-
-func convertInstanceGeneralSettingFromStore(setting *storepb.InstanceGeneralSetting) *apipb.InstanceSetting_GeneralSetting {
- if setting == nil {
- return nil
- }
-
- generalSetting := &apipb.InstanceSetting_GeneralSetting{
- DisallowUserRegistration: setting.DisallowUserRegistration,
- DisallowPasswordAuth: setting.DisallowPasswordAuth,
- AdditionalScript: setting.AdditionalScript,
- AdditionalStyle: setting.AdditionalStyle,
- WeekStartDayOffset: setting.WeekStartDayOffset,
- DisallowChangeUsername: setting.DisallowChangeUsername,
- DisallowChangeNickname: setting.DisallowChangeNickname,
- }
- if setting.CustomProfile != nil {
- generalSetting.CustomProfile = &apipb.InstanceSetting_GeneralSetting_CustomProfile{
- Title: setting.CustomProfile.Title,
- Description: setting.CustomProfile.Description,
- LogoUrl: setting.CustomProfile.LogoUrl,
- }
- }
- return generalSetting
-}
-
-func convertInstanceGeneralSettingToStore(setting *apipb.InstanceSetting_GeneralSetting) *storepb.InstanceGeneralSetting {
- if setting == nil {
- return nil
- }
- generalSetting := &storepb.InstanceGeneralSetting{
- DisallowUserRegistration: setting.DisallowUserRegistration,
- DisallowPasswordAuth: setting.DisallowPasswordAuth,
- AdditionalScript: setting.AdditionalScript,
- AdditionalStyle: setting.AdditionalStyle,
- WeekStartDayOffset: setting.WeekStartDayOffset,
- DisallowChangeUsername: setting.DisallowChangeUsername,
- DisallowChangeNickname: setting.DisallowChangeNickname,
- }
- if setting.CustomProfile != nil {
- generalSetting.CustomProfile = &storepb.InstanceCustomProfile{
- Title: setting.CustomProfile.Title,
- Description: setting.CustomProfile.Description,
- LogoUrl: setting.CustomProfile.LogoUrl,
- }
- }
- return generalSetting
-}
-
-func convertInstanceStorageSettingFromStore(settingpb *storepb.InstanceStorageSetting) *apipb.InstanceSetting_StorageSetting {
- if settingpb == nil {
- return nil
- }
- setting := &apipb.InstanceSetting_StorageSetting{
- StorageType: apipb.InstanceSetting_StorageSetting_StorageType(settingpb.StorageType),
- FilepathTemplate: settingpb.FilepathTemplate,
- DefaultStorageId: settingpb.DefaultStorageId,
- }
- for _, storagepb := range settingpb.Storages {
- setting.Storages = append(setting.Storages, convertStorageFromStore(storagepb))
- }
- if settingpb.S3Config != nil {
- setting.S3Config = &apipb.InstanceSetting_StorageSetting_S3Config{
- AccessKeyId: settingpb.S3Config.AccessKeyId,
- // AccessKeySecret is write-only: never returned in responses.
- Endpoint: settingpb.S3Config.Endpoint,
- Region: settingpb.S3Config.Region,
- Bucket: settingpb.S3Config.Bucket,
- UsePathStyle: settingpb.S3Config.UsePathStyle,
- InsecureSkipTlsVerify: settingpb.S3Config.InsecureSkipTlsVerify,
- }
- }
- return setting
-}
-
-func convertInstanceStorageSettingToStore(setting *apipb.InstanceSetting_StorageSetting) *storepb.InstanceStorageSetting {
- if setting == nil {
- return nil
- }
- settingpb := &storepb.InstanceStorageSetting{
- StorageType: storepb.InstanceStorageSetting_StorageType(setting.StorageType),
- FilepathTemplate: setting.FilepathTemplate,
- DefaultStorageId: setting.DefaultStorageId,
- }
- for _, storage := range setting.Storages {
- settingpb.Storages = append(settingpb.Storages, convertStorageToStore(storage))
- }
- if setting.S3Config != nil {
- settingpb.S3Config = &storepb.StorageS3Config{
- AccessKeyId: setting.S3Config.AccessKeyId,
- AccessKeySecret: setting.S3Config.AccessKeySecret,
- Endpoint: setting.S3Config.Endpoint,
- Region: setting.S3Config.Region,
- Bucket: setting.S3Config.Bucket,
- UsePathStyle: setting.S3Config.UsePathStyle,
- InsecureSkipTlsVerify: setting.S3Config.InsecureSkipTlsVerify,
- }
- }
- return settingpb
-}
-
-func convertStorageFromStore(storagepb *storepb.Storage) *apipb.InstanceSetting_Storage {
- if storagepb == nil {
- return nil
- }
- storage := &apipb.InstanceSetting_Storage{
- Id: storagepb.Id,
- Name: storagepb.Name,
- Type: apipb.InstanceSetting_StorageType(storagepb.Type),
- }
- if s3Config := storagepb.GetS3Config(); s3Config != nil {
- storage.Config = &apipb.InstanceSetting_Storage_S3Config_{
- S3Config: &apipb.InstanceSetting_Storage_S3Config{
- AccessKeyId: s3Config.AccessKeyId,
- // AccessKeySecret is write-only: never returned in responses.
- Endpoint: s3Config.Endpoint,
- Region: s3Config.Region,
- Bucket: s3Config.Bucket,
- UsePathStyle: s3Config.UsePathStyle,
- InsecureSkipTlsVerify: s3Config.InsecureSkipTlsVerify,
- },
- }
- }
- return storage
-}
-
-func convertStorageToStore(storage *apipb.InstanceSetting_Storage) *storepb.Storage {
- if storage == nil {
- return nil
- }
- storagepb := &storepb.Storage{
- Id: storage.Id,
- Name: storage.Name,
- Type: storepb.StorageType(storage.Type),
- }
- if s3Config := storage.GetS3Config(); s3Config != nil {
- storagepb.Config = &storepb.Storage_S3Config{
- S3Config: &storepb.StorageS3Config{
- AccessKeyId: s3Config.AccessKeyId,
- AccessKeySecret: s3Config.AccessKeySecret,
- Endpoint: s3Config.Endpoint,
- Region: s3Config.Region,
- Bucket: s3Config.Bucket,
- UsePathStyle: s3Config.UsePathStyle,
- InsecureSkipTlsVerify: s3Config.InsecureSkipTlsVerify,
- },
- }
- }
- return storagepb
-}
-
-func convertInstanceMemoRelatedSettingFromStore(setting *storepb.InstanceMemoRelatedSetting) *apipb.InstanceSetting_MemoRelatedSetting {
- if setting == nil {
- return nil
- }
- return &apipb.InstanceSetting_MemoRelatedSetting{
- Reactions: setting.Reactions,
- }
-}
-
-func convertInstanceMemoRelatedSettingToStore(setting *apipb.InstanceSetting_MemoRelatedSetting) *storepb.InstanceMemoRelatedSetting {
- if setting == nil {
- return nil
- }
- return &storepb.InstanceMemoRelatedSetting{
- Reactions: setting.Reactions,
- }
-}
+// The conversion between API and store settings lives in core/instancesetting,
+// because declarative configuration files use the same API messages. This file
+// holds what only responses need.
-func convertInstanceTagsSettingFromStore(setting *storepb.InstanceTagsSetting) *apipb.InstanceSetting_TagsSetting {
- if setting == nil {
- return nil
- }
- tags := make(map[string]*apipb.InstanceSetting_TagMetadata, len(setting.Tags))
- for tag, metadata := range setting.Tags {
- tags[tag] = &apipb.InstanceSetting_TagMetadata{
- BackgroundColor: metadata.GetBackgroundColor(),
- BlurContent: metadata.GetBlurContent(),
- }
- }
- return &apipb.InstanceSetting_TagsSetting{
- Tags: tags,
- }
-}
-
-func convertInstanceTagsSettingToStore(setting *apipb.InstanceSetting_TagsSetting) *storepb.InstanceTagsSetting {
- if setting == nil {
- return nil
- }
- tags := make(map[string]*storepb.InstanceTagMetadata, len(setting.Tags))
- for tag, metadata := range setting.Tags {
- tags[tag] = &storepb.InstanceTagMetadata{
- BackgroundColor: metadata.GetBackgroundColor(),
- BlurContent: metadata.GetBlurContent(),
- }
- }
- return &storepb.InstanceTagsSetting{
- Tags: tags,
- }
+// convertInstanceSettingFromStore converts a stored setting for a response,
+// with write-only secrets cleared.
+func convertInstanceSettingFromStore(setting *storepb.InstanceSetting) *apipb.InstanceSetting {
+ result := instancesetting.FromStore(setting)
+ redactInstanceSetting(result)
+ return result
}
-func convertInstanceNotificationSettingFromStore(setting *storepb.InstanceNotificationSetting) *apipb.InstanceSetting_NotificationSetting {
- if setting == nil {
- return nil
- }
-
- notificationSetting := &apipb.InstanceSetting_NotificationSetting{}
- if setting.Email != nil {
- notificationSetting.Email = &apipb.InstanceSetting_NotificationSetting_EmailSetting{
- Enabled: setting.Email.Enabled,
- SmtpHost: setting.Email.SmtpHost,
- SmtpPort: setting.Email.SmtpPort,
- SmtpUsername: setting.Email.SmtpUsername,
- // SmtpPassword is write-only: never returned in responses.
- FromEmail: setting.Email.FromEmail,
- FromName: setting.Email.FromName,
- ReplyTo: setting.Email.ReplyTo,
- UseTls: setting.Email.UseTls,
- UseSsl: setting.Email.UseSsl,
+// redactInstanceSetting clears the S3 secrets and SMTP password and replaces
+// each AI API key with whether it is set and a masked hint.
+func redactInstanceSetting(setting *apipb.InstanceSetting) {
+ if storage := setting.GetStorageSetting(); storage != nil {
+ if storage.S3Config != nil {
+ storage.S3Config.AccessKeySecret = ""
}
- }
- return notificationSetting
-}
-
-func convertInstanceNotificationSettingToStore(setting *apipb.InstanceSetting_NotificationSetting) *storepb.InstanceNotificationSetting {
- if setting == nil {
- return nil
- }
-
- notificationSetting := &storepb.InstanceNotificationSetting{}
- if setting.Email != nil {
- notificationSetting.Email = &storepb.InstanceNotificationSetting_EmailSetting{
- Enabled: setting.Email.Enabled,
- SmtpHost: setting.Email.SmtpHost,
- SmtpPort: setting.Email.SmtpPort,
- SmtpUsername: setting.Email.SmtpUsername,
- SmtpPassword: setting.Email.SmtpPassword,
- FromEmail: setting.Email.FromEmail,
- FromName: setting.Email.FromName,
- ReplyTo: setting.Email.ReplyTo,
- UseTls: setting.Email.UseTls,
- UseSsl: setting.Email.UseSsl,
+ for _, configured := range storage.Storages {
+ if s3Config := configured.GetS3Config(); s3Config != nil {
+ s3Config.AccessKeySecret = ""
+ }
}
}
- return notificationSetting
-}
-
-func convertInstanceAISettingFromStore(setting *storepb.InstanceAISetting) *apipb.InstanceSetting_AISetting {
- if setting == nil {
- return nil
- }
-
- aiSetting := &apipb.InstanceSetting_AISetting{
- Providers: make([]*apipb.InstanceSetting_AIProviderConfig, 0, len(setting.Providers)),
- Transcription: convertTranscriptionConfigFromStore(setting.GetTranscription()),
- }
- for _, provider := range setting.Providers {
- if provider == nil {
- continue
- }
- apiKey := provider.GetApiKey()
- aiSetting.Providers = append(aiSetting.Providers, &apipb.InstanceSetting_AIProviderConfig{
- Id: provider.GetId(),
- Title: provider.GetTitle(),
- Type: apipb.InstanceSetting_AIProviderType(provider.GetType()),
- Endpoint: provider.GetEndpoint(),
- ApiKeySet: apiKey != "",
- ApiKeyHint: maskAPIKey(apiKey),
- })
- }
- return aiSetting
-}
-
-func convertInstanceAISettingToStore(setting *apipb.InstanceSetting_AISetting) *storepb.InstanceAISetting {
- if setting == nil {
- return nil
- }
-
- aiSetting := &storepb.InstanceAISetting{
- Providers: make([]*storepb.AIProviderConfig, 0, len(setting.Providers)),
- Transcription: convertTranscriptionConfigToStore(setting.GetTranscription()),
- }
- for _, provider := range setting.Providers {
- if provider == nil {
- continue
- }
- aiSetting.Providers = append(aiSetting.Providers, &storepb.AIProviderConfig{
- Id: provider.GetId(),
- Title: provider.GetTitle(),
- Type: storepb.AIProviderType(provider.GetType()),
- Endpoint: provider.GetEndpoint(),
- ApiKey: provider.GetApiKey(),
- })
- }
- return aiSetting
-}
-
-func convertTranscriptionConfigFromStore(setting *storepb.TranscriptionConfig) *apipb.InstanceSetting_TranscriptionConfig {
- if setting == nil {
- return nil
- }
- return &apipb.InstanceSetting_TranscriptionConfig{
- ProviderId: setting.GetProviderId(),
- Model: setting.GetModel(),
- Language: setting.GetLanguage(),
- Prompt: setting.GetPrompt(),
- }
-}
-
-func convertTranscriptionConfigToStore(setting *apipb.InstanceSetting_TranscriptionConfig) *storepb.TranscriptionConfig {
- if setting == nil {
- return nil
+ if email := setting.GetNotificationSetting().GetEmail(); email != nil {
+ email.SmtpPassword = ""
}
- return &storepb.TranscriptionConfig{
- ProviderId: setting.GetProviderId(),
- Model: setting.GetModel(),
- Language: setting.GetLanguage(),
- Prompt: setting.GetPrompt(),
+ for _, provider := range setting.GetAiSetting().GetProviders() {
+ provider.ApiKeySet = provider.ApiKey != ""
+ provider.ApiKeyHint = maskAPIKey(provider.ApiKey)
+ provider.ApiKey = ""
}
}
diff --git a/server/api/instance_service_usage_limits.go b/server/api/instance_service_usage_limits.go
index 59efa8a90..2cf86944e 100644
--- a/server/api/instance_service_usage_limits.go
+++ b/server/api/instance_service_usage_limits.go
@@ -9,6 +9,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
+ "github.com/usememos/memos/core/instancesetting"
apipb "github.com/usememos/memos/proto/gen/api"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
@@ -40,23 +41,11 @@ func (s *APIService) convertUsageLimitsSettingFromStore(ctx context.Context, set
if err != nil {
return nil, errors.Wrap(err, "failed to list users")
}
- result := &apipb.InstanceSetting_UsageLimitsSetting{}
- for _, limit := range setting.GetLimits() {
- entry := &apipb.InstanceSetting_UsageLimitsSetting_UsageLimit{
- AllUsers: limit.GetAllUsers(),
- MemoCount: limit.MemoCount,
- MemoContentBytes: limit.MemoContentBytes,
- StorageBytes: limit.StorageBytes,
- UploadBytes: limit.UploadBytes,
- }
- for _, userID := range limit.GetUserIds() {
- if username, ok := usernames[userID]; ok {
- entry.Users = append(entry.Users, BuildUserName(username))
- }
- }
- result.Limits = append(result.Limits, entry)
+ userNames := make(map[int32]string, len(usernames))
+ for userID, username := range usernames {
+ userNames[userID] = BuildUserName(username)
}
- return result, nil
+ return instancesetting.UsageLimitsFromStore(setting, userNames), nil
}
// convertUsageLimitsSettingToStore converts usage limits from the API for the
@@ -88,23 +77,19 @@ func (s *APIService) convertUsageLimitsSettingToStore(ctx context.Context, setti
userIDs[user.Username] = user.ID
}
}
- result := &storepb.InstanceUsageLimitsSetting{}
+ userIDOf := make(map[string]int32, len(usernameOf))
for _, limit := range setting.GetLimits() {
- entry := &storepb.InstanceUsageLimitsSetting_UsageLimit{
- AllUsers: limit.GetAllUsers(),
- MemoCount: limit.MemoCount,
- MemoContentBytes: limit.MemoContentBytes,
- StorageBytes: limit.StorageBytes,
- UploadBytes: limit.UploadBytes,
- }
for _, name := range limit.GetUsers() {
userID, ok := userIDs[usernameOf[name]]
if !ok {
return nil, status.Errorf(codes.NotFound, "user %q not found", name)
}
- entry.UserIds = append(entry.UserIds, userID)
+ userIDOf[name] = userID
}
- result.Limits = append(result.Limits, entry)
+ }
+ result, err := instancesetting.UsageLimitsToStore(setting, userIDOf)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
return result, nil
}
diff --git a/server/api/instance_service_validation.go b/server/api/instance_service_validation.go
index 1e93e3201..38cf4a419 100644
--- a/server/api/instance_service_validation.go
+++ b/server/api/instance_service_validation.go
@@ -10,47 +10,15 @@ import (
"github.com/pkg/errors"
colorpb "google.golang.org/genproto/googleapis/type/color"
+ "github.com/usememos/memos/core/instancesetting"
apipb "github.com/usememos/memos/proto/gen/api"
storepb "github.com/usememos/memos/proto/gen/store"
)
-func validateInstanceSetting(setting *apipb.InstanceSetting) error {
- key, err := ExtractInstanceSettingKeyFromName(setting.Name)
- if err != nil {
- return err
- }
- switch key {
- case storepb.InstanceSettingKey_MEMO_RELATED.String():
- if setting.GetMemoRelatedSetting() == nil {
- return errors.New("memo related setting is required")
- }
- return nil
- case storepb.InstanceSettingKey_TAGS.String():
- return validateInstanceTagsSetting(setting.GetTagsSetting())
- case storepb.InstanceSettingKey_ACCESS.String():
- return validateInstanceAccessSetting(setting.GetAccessSetting())
- case storepb.InstanceSettingKey_USAGE_LIMITS.String():
- if setting.GetUsageLimitsSetting() == nil {
- return errors.New("usage limits setting is required")
- }
- return nil
- default:
- return nil
- }
-}
-
-func validateInstanceAccessSetting(setting *apipb.InstanceSetting_AccessSetting) error {
- if setting == nil {
- return errors.New("access setting is required")
- }
- switch setting.AccessMode {
- case apipb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, apipb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC:
- return nil
- default:
- return errors.New("access_mode must be PRIVATE or PUBLIC")
- }
-}
-
+// prepareInstanceAISettingForUpdate applies the API's update conveniences to an
+// AI setting before it is validated: trimming and default endpoints, generated
+// IDs for new providers, an empty API key meaning "keep the stored key", and an
+// omitted transcription config meaning "keep the stored config".
func (s *APIService) prepareInstanceAISettingForUpdate(ctx context.Context, setting *storepb.InstanceAISetting) error {
if setting == nil {
return errors.New("AI setting is required")
@@ -69,93 +37,25 @@ func (s *APIService) prepareInstanceAISettingForUpdate(ctx context.Context, sett
}
}
- seenIDs := map[string]bool{}
+ instancesetting.NormalizeAISetting(setting)
for _, provider := range setting.Providers {
if provider == nil {
- return errors.New("provider cannot be nil")
+ continue
}
-
- provider.Id = strings.TrimSpace(provider.Id)
if provider.Id == "" {
provider.Id = shortuuid.New()
}
- if seenIDs[provider.Id] {
- return errors.Errorf("duplicate provider ID %q", provider.Id)
- }
- seenIDs[provider.Id] = true
-
- provider.Title = strings.TrimSpace(provider.Title)
- if provider.Title == "" {
- return errors.New("provider title is required")
- }
- if provider.Type != storepb.AIProviderType_OPENAI && provider.Type != storepb.AIProviderType_GEMINI {
- return errors.Errorf("provider %q has unsupported type", provider.Id)
- }
-
- provider.Endpoint = strings.TrimSpace(provider.Endpoint)
- if provider.Type == storepb.AIProviderType_OPENAI && provider.Endpoint == "" {
- provider.Endpoint = "https://api.openai.com/v1"
- }
- if provider.Type == storepb.AIProviderType_GEMINI && provider.Endpoint == "" {
- provider.Endpoint = "https://generativelanguage.googleapis.com/v1beta"
- }
-
if provider.ApiKey == "" {
if existingProvider, ok := existingProviders[provider.Id]; ok {
provider.ApiKey = existingProvider.ApiKey
}
}
- if provider.ApiKey == "" {
- return errors.Errorf("provider %q API key is required", provider.Id)
- }
- }
-
- if err := preparePersistedTranscriptionConfig(setting, existing); err != nil {
- return err
}
- return nil
-}
-
-func preparePersistedTranscriptionConfig(setting *storepb.InstanceAISetting, existing *storepb.InstanceAISetting) error {
- // Preserve the previously stored transcription config when the request omits it,
- // matching the same "absence == keep" semantics used for API keys. The preserved
- // config still falls through to validation below, so a stale provider_id is
+ // The preserved config is still validated, so a stale provider_id is
// rejected if the same update removed or renamed its referenced provider.
if setting.Transcription == nil && existing != nil {
setting.Transcription = existing.GetTranscription()
}
- if setting.Transcription == nil {
- return nil
- }
-
- cfg := setting.Transcription
- cfg.ProviderId = strings.TrimSpace(cfg.ProviderId)
- cfg.Model = strings.TrimSpace(cfg.Model)
- cfg.Language = strings.TrimSpace(cfg.Language)
- cfg.Prompt = strings.TrimSpace(cfg.Prompt)
-
- if cfg.ProviderId != "" {
- referenced := false
- for _, provider := range setting.Providers {
- if provider != nil && provider.Id == cfg.ProviderId {
- referenced = true
- break
- }
- }
- if !referenced {
- return errors.Errorf("transcription provider_id %q does not reference any configured provider", cfg.ProviderId)
- }
- }
-
- if len(cfg.Model) > maxTranscriptionConfigModelLength {
- return errors.Errorf("transcription model is too long; maximum length is %d characters", maxTranscriptionConfigModelLength)
- }
- if len(cfg.Language) > maxTranscriptionConfigLanguageLength {
- return errors.Errorf("transcription language is too long; maximum length is %d characters", maxTranscriptionConfigLanguageLength)
- }
- if len(cfg.Prompt) > maxTranscriptionConfigPromptLength {
- return errors.Errorf("transcription prompt is too long; maximum length is %d characters", maxTranscriptionConfigPromptLength)
- }
return nil
}
diff --git a/server/api/resource_name.go b/server/api/resource_name.go
index 21dce301e..8ad725105 100644
--- a/server/api/resource_name.go
+++ b/server/api/resource_name.go
@@ -10,19 +10,22 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
+ "github.com/usememos/memos/core/identityprovider"
+ "github.com/usememos/memos/core/instancesetting"
+ coreuser "github.com/usememos/memos/core/user"
"github.com/usememos/memos/internal/identifier"
"github.com/usememos/memos/internal/random"
)
const (
- InstanceSettingNamePrefix = "instance/settings/"
- UserNamePrefix = "users/"
+ InstanceSettingNamePrefix = instancesetting.NamePrefix
+ UserNamePrefix = coreuser.NamePrefix
MemoNamePrefix = "memos/"
MemoShareNamePrefix = "shares/"
AttachmentNamePrefix = "attachments/"
ReactionNamePrefix = "reactions/"
InboxNamePrefix = "inboxes/"
- IdentityProviderNamePrefix = "identity-providers/"
+ IdentityProviderNamePrefix = identityprovider.NamePrefix
WebhookNamePrefix = "webhooks/"
SpaceNamePrefix = "spaces/"
SpaceMemberNamePrefix = "members/"
diff --git a/server/api/sso_username.go b/server/api/sso_username.go
index c966a31fe..4b71d4d19 100644
--- a/server/api/sso_username.go
+++ b/server/api/sso_username.go
@@ -3,6 +3,7 @@ package api
import (
"github.com/pkg/errors"
+ coreuser "github.com/usememos/memos/core/user"
"github.com/usememos/memos/internal/random"
)
@@ -15,7 +16,7 @@ const ssoUsernameFallbackAttempts = 5
// another local account.
func deriveSSOUsername() (string, error) {
username := random.UUID()
- if err := validateWritableUsername(username); err != nil {
+ if err := coreuser.ValidateUsername(username); err != nil {
return "", errors.Wrap(err, "generated UUID did not satisfy username constraints")
}
return username, nil
diff --git a/server/api/sso_username_test.go b/server/api/sso_username_test.go
index 5b663dcff..efaeb96bc 100644
--- a/server/api/sso_username_test.go
+++ b/server/api/sso_username_test.go
@@ -2,6 +2,8 @@ package api
import (
"testing"
+
+ coreuser "github.com/usememos/memos/core/user"
)
func TestDeriveSSOUsername(t *testing.T) {
@@ -12,7 +14,7 @@ func TestDeriveSSOUsername(t *testing.T) {
if len(username) != 36 {
t.Fatalf("deriveSSOUsername() = %q, want a 36-character UUID", username)
}
- if err := validateWritableUsername(username); err != nil {
+ if err := coreuser.ValidateUsername(username); err != nil {
t.Fatalf("deriveSSOUsername() produced invalid username %q: %v", username, err)
}
}
diff --git a/server/api/test/configuration_provisioning_test.go b/server/api/test/configuration_provisioning_test.go
deleted file mode 100644
index da50b7b32..000000000
--- a/server/api/test/configuration_provisioning_test.go
+++ /dev/null
@@ -1,160 +0,0 @@
-package test
-
-import (
- "context"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/stretchr/testify/require"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
- "google.golang.org/protobuf/encoding/protojson"
- "google.golang.org/protobuf/proto"
- "google.golang.org/protobuf/types/known/fieldmaskpb"
-
- apipb "github.com/usememos/memos/proto/gen/api"
- storepb "github.com/usememos/memos/proto/gen/store"
-)
-
-func TestDeploymentConfiguredResourcesRejectMutations(t *testing.T) {
- ctx := context.Background()
- ts := NewTestService(t)
- defer ts.Cleanup()
- admin, err := ts.CreateHostUser(ctx, "admin")
- require.NoError(t, err)
- adminCtx := ts.CreateUserContext(ctx, admin.ID)
-
- dir := t.TempDir()
- writeDeploymentProto(t, filepath.Join(dir, "memos-idp-primary.json"), testStoreIdentityProvider("primary-sso"))
- writeDeploymentProto(t, filepath.Join(dir, "memos-instance-setting-general.json"), &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{WeekStartDayOffset: 1}},
- })
- writeDeploymentProto(t, filepath.Join(dir, "memos-instance-setting-storage.json"), &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_STORAGE,
- Value: &storepb.InstanceSetting_StorageSetting{StorageSetting: &storepb.InstanceStorageSetting{
- StorageType: storepb.InstanceStorageSetting_LOCAL,
- }},
- })
- require.NoError(t, ts.Store.LoadDeploymentConfigurationDir(ctx, dir))
-
- providers, err := ts.Service.ListIdentityProviders(ctx, &apipb.ListIdentityProvidersRequest{})
- require.NoError(t, err)
- require.Len(t, providers.IdentityProviders, 1)
- require.Equal(t, "Primary SSO", providers.IdentityProviders[0].Title)
-
- setting, err := ts.Service.GetInstanceSetting(ctx, &apipb.GetInstanceSettingRequest{Name: "instance/settings/GENERAL"})
- require.NoError(t, err)
- require.Equal(t, int32(1), setting.GetGeneralSetting().WeekStartDayOffset)
- storageSetting, err := ts.Service.GetInstanceSetting(adminCtx, &apipb.GetInstanceSettingRequest{Name: "instance/settings/STORAGE"})
- require.NoError(t, err)
- require.Equal(t, "assets/{timestamp}_{uuid}_{filename}", storageSetting.GetStorageSetting().FilepathTemplate)
-
- _, err = ts.Service.CreateIdentityProvider(adminCtx, &apipb.CreateIdentityProviderRequest{
- IdentityProviderId: "primary-sso",
- IdentityProvider: testAPIIdentityProvider("Replacement"),
- })
- require.Equal(t, codes.FailedPrecondition, status.Code(err))
-
- _, err = ts.Service.UpdateIdentityProvider(adminCtx, &apipb.UpdateIdentityProviderRequest{
- IdentityProvider: &apipb.IdentityProvider{Name: "identity-providers/primary-sso", Title: "Changed"},
- UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},
- })
- require.Equal(t, codes.FailedPrecondition, status.Code(err))
-
- _, err = ts.Service.DeleteIdentityProvider(adminCtx, &apipb.DeleteIdentityProviderRequest{Name: "identity-providers/primary-sso"})
- require.Equal(t, codes.FailedPrecondition, status.Code(err))
-
- _, err = ts.Service.UpdateInstanceSetting(adminCtx, &apipb.UpdateInstanceSettingRequest{
- InstanceSetting: &apipb.InstanceSetting{
- Name: "instance/settings/GENERAL",
- Value: &apipb.InstanceSetting_GeneralSetting_{GeneralSetting: &apipb.InstanceSetting_GeneralSetting{}},
- },
- UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"general_setting"}},
- })
- require.Equal(t, codes.FailedPrecondition, status.Code(err))
-}
-
-func TestAuthenticationMutationAPIRejectsLockout(t *testing.T) {
- ctx := context.Background()
-
- t.Run("GENERAL update requires an effective identity provider", func(t *testing.T) {
- ts := NewTestService(t)
- defer ts.Cleanup()
- admin, err := ts.CreateHostUser(ctx, "admin")
- require.NoError(t, err)
- adminCtx := ts.CreateUserContext(ctx, admin.ID)
-
- _, err = ts.Service.UpdateInstanceSetting(adminCtx, &apipb.UpdateInstanceSettingRequest{InstanceSetting: &apipb.InstanceSetting{
- Name: "instance/settings/GENERAL",
- Value: &apipb.InstanceSetting_GeneralSetting_{GeneralSetting: &apipb.InstanceSetting_GeneralSetting{
- DisallowPasswordAuth: true,
- }},
- }})
- require.Equal(t, codes.FailedPrecondition, status.Code(err))
- })
-
- t.Run("last IdP cannot be deleted while regular password auth is disabled", func(t *testing.T) {
- ts := NewTestService(t)
- defer ts.Cleanup()
- admin, err := ts.CreateHostUser(ctx, "admin")
- require.NoError(t, err)
- adminCtx := ts.CreateUserContext(ctx, admin.ID)
- created, err := ts.Service.CreateIdentityProvider(adminCtx, &apipb.CreateIdentityProviderRequest{
- IdentityProviderId: "primary-sso",
- IdentityProvider: testAPIIdentityProvider("Primary"),
- })
- require.NoError(t, err)
- _, err = ts.Service.UpdateInstanceSetting(adminCtx, &apipb.UpdateInstanceSettingRequest{InstanceSetting: &apipb.InstanceSetting{
- Name: "instance/settings/GENERAL",
- Value: &apipb.InstanceSetting_GeneralSetting_{GeneralSetting: &apipb.InstanceSetting_GeneralSetting{
- DisallowPasswordAuth: true,
- }},
- }})
- require.NoError(t, err)
-
- _, err = ts.Service.DeleteIdentityProvider(adminCtx, &apipb.DeleteIdentityProviderRequest{Name: created.Name})
- require.Equal(t, codes.FailedPrecondition, status.Code(err))
- })
-}
-
-func testStoreIdentityProvider(uid string) *storepb.IdentityProvider {
- return &storepb.IdentityProvider{
- Uid: uid,
- Name: "Primary SSO",
- Type: storepb.IdentityProvider_OAUTH2,
- Config: &storepb.IdentityProviderConfig{Config: &storepb.IdentityProviderConfig_Oauth2Config{Oauth2Config: &storepb.OAuth2Config{
- ClientId: "client-id",
- ClientSecret: "client-secret",
- AuthUrl: "https://example.com/authorize",
- TokenUrl: "https://example.com/token",
- UserInfoUrl: "https://example.com/userinfo",
- Scopes: []string{"openid", "profile"},
- FieldMapping: &storepb.FieldMapping{Identifier: "sub"},
- }}},
- }
-}
-
-func testAPIIdentityProvider(title string) *apipb.IdentityProvider {
- return &apipb.IdentityProvider{
- Title: title,
- Type: apipb.IdentityProvider_OAUTH2,
- Config: &apipb.IdentityProviderConfig{Config: &apipb.IdentityProviderConfig_Oauth2Config{Oauth2Config: &apipb.OAuth2Config{
- ClientId: "client-id",
- ClientSecret: "client-secret",
- AuthUrl: "https://example.com/authorize",
- TokenUrl: "https://example.com/token",
- UserInfoUrl: "https://example.com/userinfo",
- Scopes: []string{"openid", "profile"},
- FieldMapping: &apipb.FieldMapping{Identifier: "sub"},
- }}},
- }
-}
-
-func writeDeploymentProto(t *testing.T, path string, message proto.Message) {
- t.Helper()
- content, err := (protojson.MarshalOptions{Indent: " "}).Marshal(message)
- require.NoError(t, err)
- require.NoError(t, os.WriteFile(path, content, 0600))
-}
diff --git a/server/api/test/idp_service_test.go b/server/api/test/idp_service_test.go
index 8fdd42b5e..347be4e3d 100644
--- a/server/api/test/idp_service_test.go
+++ b/server/api/test/idp_service_test.go
@@ -5,6 +5,8 @@ import (
"testing"
"github.com/stretchr/testify/require"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/fieldmaskpb"
apipb "github.com/usememos/memos/proto/gen/api"
@@ -611,3 +613,60 @@ func TestIdentityProviderPermissions(t *testing.T) {
require.Contains(t, err.Error(), "user not authenticated")
})
}
+
+func TestIdentityProviderValidation(t *testing.T) {
+ ctx := context.Background()
+ ts := NewTestService(t)
+ defer ts.Cleanup()
+ hostUser, err := ts.CreateHostUser(ctx, "admin")
+ require.NoError(t, err)
+ adminCtx := ts.CreateUserContext(ctx, hostUser.ID)
+
+ oauth2 := func(mutate func(*apipb.OAuth2Config)) *apipb.IdentityProvider {
+ config := &apipb.OAuth2Config{
+ ClientId: "client",
+ ClientSecret: "secret",
+ AuthUrl: "https://idp.example.com/authorize",
+ TokenUrl: "https://idp.example.com/token",
+ UserInfoUrl: "https://idp.example.com/userinfo",
+ FieldMapping: &apipb.FieldMapping{Identifier: "sub"},
+ }
+ if mutate != nil {
+ mutate(config)
+ }
+ return &apipb.IdentityProvider{
+ Title: "SSO",
+ Type: apipb.IdentityProvider_OAUTH2,
+ Config: &apipb.IdentityProviderConfig{Config: &apipb.IdentityProviderConfig_Oauth2Config{Oauth2Config: config}},
+ }
+ }
+
+ for name, provider := range map[string]*apipb.IdentityProvider{
+ "missing field mapping": oauth2(func(c *apipb.OAuth2Config) { c.FieldMapping = nil }),
+ "relative token url": oauth2(func(c *apipb.OAuth2Config) { c.TokenUrl = "/token" }),
+ "missing client id": oauth2(func(c *apipb.OAuth2Config) { c.ClientId = "" }),
+ "missing config": {Title: "SSO", Type: apipb.IdentityProvider_OAUTH2},
+ } {
+ _, err := ts.Service.CreateIdentityProvider(adminCtx, &apipb.CreateIdentityProviderRequest{IdentityProvider: provider})
+ require.Equal(t, codes.InvalidArgument, status.Code(err), name)
+ }
+ _, err = ts.Service.CreateIdentityProvider(adminCtx, &apipb.CreateIdentityProviderRequest{})
+ require.Equal(t, codes.InvalidArgument, status.Code(err))
+
+ created, err := ts.Service.CreateIdentityProvider(adminCtx, &apipb.CreateIdentityProviderRequest{IdentityProvider: oauth2(nil)})
+ require.NoError(t, err)
+
+ // An update is validated as the merged provider, so clearing the title fails
+ // even though the request only names one field.
+ _, err = ts.Service.UpdateIdentityProvider(adminCtx, &apipb.UpdateIdentityProviderRequest{
+ IdentityProvider: &apipb.IdentityProvider{Name: created.Name, Title: " "},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},
+ })
+ require.Equal(t, codes.InvalidArgument, status.Code(err))
+
+ _, err = ts.Service.UpdateIdentityProvider(adminCtx, &apipb.UpdateIdentityProviderRequest{
+ IdentityProvider: &apipb.IdentityProvider{Name: created.Name, Title: "Renamed"},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},
+ })
+ require.NoError(t, err)
+}
diff --git a/server/api/test/instance_service_configuration_test.go b/server/api/test/instance_service_configuration_test.go
new file mode 100644
index 000000000..e5e097f8a
--- /dev/null
+++ b/server/api/test/instance_service_configuration_test.go
@@ -0,0 +1,182 @@
+package test
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "google.golang.org/genproto/googleapis/rpc/errdetails"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+ "google.golang.org/protobuf/types/known/fieldmaskpb"
+
+ "github.com/usememos/memos/core/configuration"
+ apipb "github.com/usememos/memos/proto/gen/api"
+)
+
+// applyConfiguration applies files to the test instance as `memos config apply` would.
+func applyConfiguration(ctx context.Context, t *testing.T, ts *TestService, files map[string]string) {
+ t.Helper()
+ dir := t.TempDir()
+ for name, content := range files {
+ require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600))
+ }
+ desired, err := configuration.Load(dir, configuration.OSResolver())
+ require.NoError(t, err)
+ plan, _, err := configuration.Apply(ctx, desired, ts.Store, configuration.ApplyMetadata{AppliedBy: "test", Version: "test", Now: time.Unix(1_800_000_000, 0)})
+ require.NoError(t, err)
+ require.True(t, plan.Valid(), plan.Message.Errors)
+}
+
+func requireManaged(t *testing.T, err error, resource string) map[string]string {
+ t.Helper()
+ st := status.Convert(err)
+ require.Equal(t, codes.FailedPrecondition, st.Code(), "got %v", err)
+ for _, detail := range st.Details() {
+ if info, ok := detail.(*errdetails.ErrorInfo); ok {
+ require.Equal(t, "MANAGED_BY_CONFIGURATION", info.Reason)
+ require.Equal(t, "memos.api", info.Domain)
+ require.Equal(t, resource, info.Metadata["resource"])
+ return info.Metadata
+ }
+ }
+ require.Fail(t, "no ErrorInfo detail", "%v", err)
+ return nil
+}
+
+const managedProvider = `{"name":"identity-providers/sso","type":"OAUTH2","title":"SSO","config":{"oauth2Config":{"clientId":"memos","clientSecret":"secret",
+ "authUrl":"https://idp.example.com/authorize","tokenUrl":"https://idp.example.com/token","userInfoUrl":"https://idp.example.com/userinfo",
+ "fieldMapping":{"identifier":"sub"}}}}`
+
+func TestConfigurationGuard(t *testing.T) {
+ ctx := context.Background()
+ ts := NewTestService(t)
+ defer ts.Cleanup()
+ admin, err := ts.CreateHostUser(ctx, "admin")
+ require.NoError(t, err)
+ adminCtx := ts.CreateUserContext(ctx, admin.ID)
+ applyConfiguration(ctx, t, ts, map[string]string{
+ "idp.json": `{"identityProviders":[` + managedProvider + `]}`,
+ "general.json": `{"instanceSettings":[{"name":"instance/settings/GENERAL","generalSetting":{"customProfile":{"title":"Company"}}}],
+ "lifecycle":[{"resource":"instance/settings/GENERAL","ignoreChanges":["generalSetting.additionalStyle"]}]}`,
+ "users.json": `{"users":[{"name":"users/admin","username":"admin","role":"ADMIN","password":"pw"}]}`,
+ })
+
+ // Instance settings: a managed change is refused, with the file and the field.
+ general := func(title, style string) error {
+ _, err := ts.Service.UpdateInstanceSetting(adminCtx, &apipb.UpdateInstanceSettingRequest{InstanceSetting: &apipb.InstanceSetting{
+ Name: "instance/settings/GENERAL",
+ Value: &apipb.InstanceSetting_GeneralSetting_{GeneralSetting: &apipb.InstanceSetting_GeneralSetting{
+ CustomProfile: &apipb.InstanceSetting_GeneralSetting_CustomProfile{Title: title}, AdditionalStyle: style,
+ }},
+ }})
+ return err
+ }
+ metadata := requireManaged(t, general("Renamed", ""), "instance/settings/GENERAL")
+ require.Equal(t, "general.json", metadata["source"])
+ require.Equal(t, "generalSetting.customProfile.title", metadata["fields"])
+ require.NoError(t, general("Company", ""), "resending the managed values passes")
+ require.NoError(t, general("Company", "body{}"), "an ignored field is the API's to change")
+
+ // Identity providers: updates, deletes, and a create with the same name are refused.
+ _, err = ts.Service.UpdateIdentityProvider(adminCtx, &apipb.UpdateIdentityProviderRequest{
+ IdentityProvider: &apipb.IdentityProvider{Name: "identity-providers/sso", Title: "Renamed"},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},
+ })
+ require.Equal(t, "title", requireManaged(t, err, "identity-providers/sso")["fields"])
+ _, err = ts.Service.DeleteIdentityProvider(adminCtx, &apipb.DeleteIdentityProviderRequest{Name: "identity-providers/sso"})
+ requireManaged(t, err, "identity-providers/sso")
+ _, err = ts.Service.UpdateIdentityProvider(adminCtx, &apipb.UpdateIdentityProviderRequest{
+ IdentityProvider: &apipb.IdentityProvider{Name: "identity-providers/sso", Title: "SSO"},
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},
+ })
+ require.NoError(t, err, "an update that changes nothing passes")
+
+ // Users: username and role are managed; the profile and the password are not.
+ update := func(user *apipb.User, paths ...string) error {
+ user.Name = "users/admin"
+ _, err := ts.Service.UpdateUser(adminCtx, &apipb.UpdateUserRequest{User: user, UpdateMask: &fieldmaskpb.FieldMask{Paths: paths}})
+ return err
+ }
+ require.Equal(t, "role", requireManaged(t, update(&apipb.User{Role: apipb.User_USER}, "role"), "users/admin")["fields"])
+ require.NoError(t, update(&apipb.User{DisplayName: "Admin"}, "display_name"))
+ require.NoError(t, update(&apipb.User{Password: "changed in the UI"}, "password"), "the password is write-only and never guarded")
+ _, err = ts.Service.DeleteUser(adminCtx, &apipb.DeleteUserRequest{Name: "users/admin"})
+ requireManaged(t, err, "users/admin")
+
+ // Unmanaged resources are not guarded.
+ _, err = ts.Service.UpdateInstanceSetting(adminCtx, &apipb.UpdateInstanceSettingRequest{InstanceSetting: &apipb.InstanceSetting{
+ Name: "instance/settings/MEMO_RELATED",
+ Value: &apipb.InstanceSetting_MemoRelatedSetting_{MemoRelatedSetting: &apipb.InstanceSetting_MemoRelatedSetting{Reactions: []string{"👍"}}},
+ }})
+ require.NoError(t, err)
+}
+
+func TestConfigurationGuardReferencedUser(t *testing.T) {
+ ctx := context.Background()
+ ts := NewTestService(t)
+ defer ts.Cleanup()
+ admin, err := ts.CreateHostUser(ctx, "admin")
+ require.NoError(t, err)
+ adminCtx := ts.CreateUserContext(ctx, admin.ID)
+ _, err = ts.CreateRegularUser(ctx, "alice")
+ require.NoError(t, err)
+ _, err = ts.CreateRegularUser(ctx, "bob")
+ require.NoError(t, err)
+ applyConfiguration(ctx, t, ts, map[string]string{
+ "limits.json": `{"instanceSettings":[{"name":"instance/settings/USAGE_LIMITS","usageLimitsSetting":{"limits":[
+ {"users":["users/alice"],"memoCount":"100"},{"allUsers":true,"memoCount":"10"}]}}]}`,
+ })
+
+ // A user the managed usage limits name can be neither renamed nor deleted,
+ // since the next plan could not resolve the name.
+ update := func(name string, user *apipb.User, paths ...string) error {
+ user.Name = name
+ _, err := ts.Service.UpdateUser(adminCtx, &apipb.UpdateUserRequest{User: user, UpdateMask: &fieldmaskpb.FieldMask{Paths: paths}})
+ return err
+ }
+ metadata := requireManaged(t, update("users/alice", &apipb.User{Username: "alice2"}, "username"), "users/alice")
+ require.Equal(t, "limits.json", metadata["source"])
+ require.Equal(t, "instance/settings/USAGE_LIMITS", metadata["referenced_by"])
+ _, err = ts.Service.DeleteUser(adminCtx, &apipb.DeleteUserRequest{Name: "users/alice"})
+ requireManaged(t, err, "users/alice")
+
+ // The rest of the user stays the API's, and unnamed users are not guarded.
+ require.NoError(t, update("users/alice", &apipb.User{DisplayName: "Alice"}, "display_name"))
+ require.NoError(t, update("users/alice", &apipb.User{Username: "alice"}, "username"), "resending the username passes")
+ require.NoError(t, update("users/bob", &apipb.User{Username: "bob2"}, "username"))
+ _, err = ts.Service.DeleteUser(adminCtx, &apipb.DeleteUserRequest{Name: "users/bob2"})
+ require.NoError(t, err)
+}
+
+func TestGetConfigurationStatus(t *testing.T) {
+ ctx := context.Background()
+ ts := NewTestService(t)
+ defer ts.Cleanup()
+ admin, err := ts.CreateHostUser(ctx, "admin")
+ require.NoError(t, err)
+ member, err := ts.CreateRegularUser(ctx, "member")
+ require.NoError(t, err)
+
+ empty, err := ts.Service.GetConfigurationStatus(ts.CreateUserContext(ctx, admin.ID), &apipb.GetConfigurationStatusRequest{})
+ require.NoError(t, err)
+ require.Zero(t, empty.Serial)
+ require.Empty(t, empty.ManagedResources)
+
+ applyConfiguration(ctx, t, ts, map[string]string{"idp.json": `{"identityProviders":[` + managedProvider + `]}`})
+ got, err := ts.Service.GetConfigurationStatus(ts.CreateUserContext(ctx, admin.ID), &apipb.GetConfigurationStatusRequest{})
+ require.NoError(t, err)
+ require.Equal(t, int64(1), got.Serial)
+ require.Equal(t, "test", got.AppliedBy)
+ require.Equal(t, int64(1_800_000_000), got.ApplyTime.GetSeconds())
+ require.Equal(t, []*apipb.ConfigurationStatus_ManagedResource{{Resource: "identity-providers/sso", Source: "idp.json", ManagedFields: []string{"*"}}}, got.ManagedResources)
+ require.NotContains(t, got.String(), "secret", "the status carries no configured value")
+
+ _, err = ts.Service.GetConfigurationStatus(ts.CreateUserContext(ctx, member.ID), &apipb.GetConfigurationStatusRequest{})
+ require.Equal(t, codes.PermissionDenied, status.Code(err))
+ _, err = ts.Service.GetConfigurationStatus(ctx, &apipb.GetConfigurationStatusRequest{})
+ require.Equal(t, codes.Unauthenticated, status.Code(err))
+}
diff --git a/server/api/test/instance_service_test.go b/server/api/test/instance_service_test.go
index ad893a9e4..48ff24037 100644
--- a/server/api/test/instance_service_test.go
+++ b/server/api/test/instance_service_test.go
@@ -13,6 +13,7 @@ import (
apipb "github.com/usememos/memos/proto/gen/api"
storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
)
func TestGetInstanceProfile(t *testing.T) {
@@ -526,7 +527,7 @@ func TestUpdateInstanceSetting(t *testing.T) {
bothEncryptions.UseSsl = true
err = update(bothEncryptions)
require.Equal(t, codes.InvalidArgument, status.Code(err))
- require.Contains(t, err.Error(), "cannot enable both useTls and useSsl")
+ require.Contains(t, err.Error(), "cannot enable both use_tls and use_ssl")
for name, mutate := range map[string]func(*apipb.InstanceSetting_NotificationSetting_EmailSetting){
"host": func(e *apipb.InstanceSetting_NotificationSetting_EmailSetting) { e.SmtpHost = " " },
@@ -537,7 +538,7 @@ func TestUpdateInstanceSetting(t *testing.T) {
mutate(email)
err := update(email)
require.Equal(t, codes.InvalidArgument, status.Code(err), "missing %s", name)
- require.Contains(t, err.Error(), "requires smtpHost", "missing %s", name)
+ require.Contains(t, err.Error(), "requires smtp_host", "missing %s", name)
}
require.NoError(t, update(valid()))
@@ -1134,3 +1135,68 @@ func TestUpdateInstanceSetting(t *testing.T) {
require.Equal(t, "names: Alice", stored.GetTranscription().GetPrompt())
})
}
+
+func TestUpdateInstanceSettingValidatesStorages(t *testing.T) {
+ ctx := context.Background()
+ ts := NewTestService(t)
+ defer ts.Cleanup()
+ hostUser, err := ts.CreateHostUser(ctx, "admin")
+ require.NoError(t, err)
+ adminCtx := ts.CreateUserContext(ctx, hostUser.ID)
+
+ update := func(storages []*apipb.InstanceSetting_Storage, defaultID string) error {
+ _, err := ts.Service.UpdateInstanceSetting(adminCtx, &apipb.UpdateInstanceSettingRequest{
+ InstanceSetting: &apipb.InstanceSetting{
+ Name: "instance/settings/STORAGE",
+ Value: &apipb.InstanceSetting_StorageSetting_{StorageSetting: &apipb.InstanceSetting_StorageSetting{
+ Storages: storages,
+ DefaultStorageId: defaultID,
+ }},
+ },
+ })
+ return err
+ }
+ local := &apipb.InstanceSetting_Storage{Id: "local", Type: apipb.InstanceSetting_LOCAL}
+ archive := &apipb.InstanceSetting_Storage{
+ Id: "archive",
+ Type: apipb.InstanceSetting_S3,
+ Config: &apipb.InstanceSetting_Storage_S3Config_{S3Config: &apipb.InstanceSetting_Storage_S3Config{
+ AccessKeyId: "AKID", AccessKeySecret: "secret", Endpoint: "https://s3.example.com", Bucket: "memos",
+ }},
+ }
+
+ // A non-default S3 storage without a region would fail on first use.
+ err = update([]*apipb.InstanceSetting_Storage{local, archive}, "local")
+ require.Equal(t, codes.InvalidArgument, status.Code(err))
+ require.Contains(t, err.Error(), "storage archive region is required")
+
+ archive.GetS3Config().Region = "us-east-1"
+ require.NoError(t, update([]*apipb.InstanceSetting_Storage{local, archive}, "local"))
+}
+
+func TestConfigurationStateIsNotExposed(t *testing.T) {
+ ctx := context.Background()
+ ts := NewTestService(t)
+ defer ts.Cleanup()
+ hostUser, err := ts.CreateHostUser(ctx, "admin")
+ require.NoError(t, err)
+ adminCtx := ts.CreateUserContext(ctx, hostUser.ID)
+
+ _, err = ts.Store.RunConfigurationTransaction(ctx, func(context.Context, *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ return &storepb.InstanceConfigurationState{ConfigDigest: "digest"}, nil
+ })
+ require.NoError(t, err)
+
+ const name = "instance/settings/CONFIGURATION_STATE"
+ _, err = ts.Service.GetInstanceSetting(adminCtx, &apipb.GetInstanceSettingRequest{Name: name})
+ require.Equal(t, codes.InvalidArgument, status.Code(err))
+ _, err = ts.Service.BatchGetInstanceSettings(adminCtx, &apipb.BatchGetInstanceSettingsRequest{Names: []string{name}})
+ require.Equal(t, codes.InvalidArgument, status.Code(err))
+ _, err = ts.Service.UpdateInstanceSetting(adminCtx, &apipb.UpdateInstanceSettingRequest{InstanceSetting: &apipb.InstanceSetting{Name: name}})
+ require.Equal(t, codes.InvalidArgument, status.Code(err))
+ require.Contains(t, err.Error(), "state record and cannot be written")
+
+ state, err := ts.Store.GetConfigurationState(ctx)
+ require.NoError(t, err)
+ require.Equal(t, "digest", state.ConfigDigest, "the API did not overwrite the record")
+}
diff --git a/server/api/test/usage_limit_service_test.go b/server/api/test/usage_limit_service_test.go
index 02e3ef5ce..9d467f413 100644
--- a/server/api/test/usage_limit_service_test.go
+++ b/server/api/test/usage_limit_service_test.go
@@ -2,7 +2,6 @@ package test
import (
"context"
- "os"
"path/filepath"
"strings"
"testing"
@@ -193,33 +192,6 @@ func TestUsageLimitsSettingUpdate(t *testing.T) {
require.True(t, got.GetUsageLimitsSetting().Limits[1].AllUsers)
}
-func TestUsageLimitsDeploymentFile(t *testing.T) {
- ctx := context.Background()
- ts := NewTestService(t)
- defer ts.Cleanup()
- admin, err := ts.CreateHostUser(ctx, "file-admin")
- require.NoError(t, err)
- adminCtx := ts.CreateUserContext(ctx, admin.ID)
-
- dir := t.TempDir()
- require.NoError(t, os.WriteFile(filepath.Join(dir, "memos-instance-setting-usage-limits.json"),
- []byte(`{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[{"allUsers":true,"memoCount":"1"}]}}`), 0o600))
- require.NoError(t, ts.Store.LoadDeploymentConfigurationDir(ctx, dir))
-
- got, err := ts.Service.GetInstanceSetting(adminCtx, &apipb.GetInstanceSettingRequest{Name: usageLimitsSettingName})
- require.NoError(t, err)
- require.Len(t, got.GetUsageLimitsSetting().Limits, 1)
- require.Equal(t, int64(1), got.GetUsageLimitsSetting().Limits[0].GetMemoCount())
- _, err = ts.Service.UpdateInstanceSetting(adminCtx, &apipb.UpdateInstanceSettingRequest{InstanceSetting: usageLimitsSetting(&usageLimitEntry{AllUsers: true})})
- require.Equal(t, codes.FailedPrecondition, status.Code(err))
-
- // The file-provided limit is enforced.
- _, err = ts.Service.CreateMemo(adminCtx, &apipb.CreateMemoRequest{Memo: &apipb.Memo{Content: "first", Visibility: apipb.Visibility_PRIVATE}})
- require.NoError(t, err)
- _, err = ts.Service.CreateMemo(adminCtx, &apipb.CreateMemoRequest{Memo: &apipb.Memo{Content: "second", Visibility: apipb.Visibility_PRIVATE}})
- requireQuotaExceeded(t, err, "MEMO_COUNT", api.BuildUserName(admin.Username))
-}
-
func TestMemoLimitEnforcement(t *testing.T) {
ctx := context.Background()
ts := NewTestService(t)
diff --git a/server/api/user_resource_name.go b/server/api/user_resource_name.go
index dcbcd5bfc..31b592fd6 100644
--- a/server/api/user_resource_name.go
+++ b/server/api/user_resource_name.go
@@ -5,7 +5,6 @@ import (
"github.com/pkg/errors"
- "github.com/usememos/memos/internal/identifier"
"github.com/usememos/memos/store"
)
@@ -26,13 +25,6 @@ func parseUsernameFromName(name string) (string, error) {
return username, nil
}
-func validateWritableUsername(username string) error {
- if !identifier.IsValidUsername(username) {
- return errors.Errorf("invalid username %q", username)
- }
- return nil
-}
-
// ResolveUserByName resolves a username-based user resource name to a store user.
func ResolveUserByName(ctx context.Context, stores *store.Store, name string) (*store.User, error) {
username, err := parseUsernameFromName(name)
diff --git a/server/api/user_resource_name_test.go b/server/api/user_resource_name_test.go
index 69774a4c0..daaff1628 100644
--- a/server/api/user_resource_name_test.go
+++ b/server/api/user_resource_name_test.go
@@ -1,94 +1,9 @@
package api
import (
- "strings"
"testing"
)
-func TestValidateWritableUsername(t *testing.T) {
- tests := []struct {
- name string
- username string
- wantError bool
- }{
- {
- name: "lowercase",
- username: "alice",
- },
- {
- name: "mixed case",
- username: "Alice",
- },
- {
- name: "hyphenated",
- username: "alice-smith",
- },
- {
- name: "one character",
- username: "a",
- },
- {
- name: "maximum length",
- username: "a" + strings.Repeat("b", 35),
- },
- {
- name: "too long",
- username: "a" + strings.Repeat("b", 36),
- wantError: true,
- },
- {
- name: "digit first",
- username: "1alice",
- },
- {
- name: "hyphen last",
- username: "alice-",
- wantError: true,
- },
- {
- name: "empty",
- username: "",
- wantError: true,
- },
- {
- name: "numeric",
- username: "123",
- },
- {
- name: "email",
- username: "[email protected]",
- wantError: true,
- },
- {
- name: "underscore",
- username: "alice_smith",
- wantError: true,
- },
- {
- name: "space",
- username: "alice smith",
- wantError: true,
- },
- {
- name: "slash",
- username: "alice/smith",
- wantError: true,
- },
- }
-
- for _, test := range tests {
- t.Run(test.name, func(t *testing.T) {
- err := validateWritableUsername(test.username)
- if test.wantError && err == nil {
- t.Fatalf("validateWritableUsername(%q) succeeded, want error", test.username)
- }
- if !test.wantError && err != nil {
- t.Fatalf("validateWritableUsername(%q) returned error: %v", test.username, err)
- }
- })
- }
-}
-
func TestParseUsernameFromNameAllowsLegacyUsernames(t *testing.T) {
tests := []struct {
name string
diff --git a/server/api/user_service.go b/server/api/user_service.go
index 66c0fb11a..6b358e0f2 100644
--- a/server/api/user_service.go
+++ b/server/api/user_service.go
@@ -6,6 +6,7 @@ import (
"fmt"
"log/slog"
"regexp"
+ "slices"
"strconv"
"strings"
"time"
@@ -16,6 +17,7 @@ import (
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
+ coreuser "github.com/usememos/memos/core/user"
"github.com/usememos/memos/internal/clientip"
"github.com/usememos/memos/internal/ratelimit"
apipb "github.com/usememos/memos/proto/gen/api"
@@ -33,13 +35,6 @@ const (
maxAvatarDataURIBytes = maxAvatarImageBytes/3*4 + 256
)
-func validatePassword(password string) error {
- if password == "" {
- return errors.New("password must not be empty")
- }
- return nil
-}
-
func validateUserTagsSetting(setting *apipb.UserSetting_TagsSetting) error {
if setting == nil {
return errors.New("tags setting is required")
@@ -215,10 +210,10 @@ func (s *APIService) CreateUser(ctx context.Context, request *apipb.CreateUserRe
if request.UserId != "" && request.UserId != request.User.Username {
return nil, status.Errorf(codes.InvalidArgument, "user_id must match user.username")
}
- if err := validateWritableUsername(request.User.Username); err != nil {
+ if err := coreuser.ValidateUsername(request.User.Username); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
- if err := validatePassword(request.User.Password); err != nil {
+ if err := coreuser.ValidatePassword(request.User.Password); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
email, err := store.NormalizeEmail(request.User.Email)
@@ -278,7 +273,7 @@ func (s *APIService) CreateUser(ctx context.Context, request *apipb.CreateUserRe
}
// Self-service registration is bounded per address, may require a challenge,
- // and may be vetoed by the deployment's signup policy. Admin creation and
+ // and may be vetoed by the instance's signup policy. Admin creation and
// first-user setup are not.
if currentUser == nil || currentUser.Role != store.RoleAdmin {
clientIP := clientip.FromContext(ctx)
@@ -373,6 +368,10 @@ func (s *APIService) UpdateUser(ctx context.Context, request *apipb.UpdateUserRe
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
+ if err := s.checkManagedUserChange(ctx, user, request); err != nil {
+ return nil, err
+ }
+
currentTsSec := time.Now().Unix()
update := &store.UpdateUser{
ID: user.ID,
@@ -389,7 +388,7 @@ func (s *APIService) UpdateUser(ctx context.Context, request *apipb.UpdateUserRe
if instanceGeneralSetting.DisallowChangeUsername {
return nil, status.Errorf(codes.PermissionDenied, "permission denied: disallow change username")
}
- if err := validateWritableUsername(request.User.Username); err != nil {
+ if err := coreuser.ValidateUsername(request.User.Username); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
update.Username = &request.User.Username
@@ -437,7 +436,7 @@ func (s *APIService) UpdateUser(ctx context.Context, request *apipb.UpdateUserRe
role := convertUserRoleToStore(request.User.Role)
update.Role = &role
case "password":
- if err := validatePassword(request.User.Password); err != nil {
+ if err := coreuser.ValidatePassword(request.User.Password); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
}
passwordHash, err := bcrypt.GenerateFromPassword([]byte(request.User.Password), bcrypt.DefaultCost)
@@ -504,6 +503,12 @@ func (s *APIService) DeleteUser(ctx context.Context, request *apipb.DeleteUserRe
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
isSelfDelete := currentUser.ID == userID
+ if err := s.checkManagedExistence(ctx, BuildUserName(user.Username)); err != nil {
+ return nil, err
+ }
+ if err := s.checkManagedReference(ctx, BuildUserName(user.Username)); err != nil {
+ return nil, err
+ }
deleteResult, err := s.Store.DeleteUser(ctx, &store.DeleteUser{
ID: user.ID,
@@ -533,6 +538,41 @@ const emailTakenMessage = "email is already in use"
const lastInstanceAdminMessage = "the instance must retain an active administrator"
+// checkManagedUserChange refuses an update that changes the fields of a user
+// the configuration manages: username, role, and the profile fields its file
+// declares. The password is write-only and never refused. A rename is also
+// refused while a managed resource names the user.
+func (s *APIService) checkManagedUserChange(ctx context.Context, user *store.User, request *apipb.UpdateUserRequest) error {
+ changed := []string{}
+ for _, path := range request.UpdateMask.Paths {
+ switch path {
+ case "username":
+ if request.User.Username != user.Username {
+ changed = append(changed, "username")
+ }
+ case "display_name":
+ if request.User.DisplayName != user.Nickname {
+ changed = append(changed, "displayName")
+ }
+ case "email":
+ if email, err := store.NormalizeEmail(request.User.Email); err != nil || email != user.Email {
+ changed = append(changed, "email")
+ }
+ case "role":
+ if convertUserRoleToStore(request.User.Role) != user.Role {
+ changed = append(changed, "role")
+ }
+ default:
+ }
+ }
+ if slices.Contains(changed, "username") {
+ if err := s.checkManagedReference(ctx, BuildUserName(user.Username)); err != nil {
+ return err
+ }
+ }
+ return s.checkManagedChange(ctx, BuildUserName(user.Username), changed)
+}
+
// convertUserWriteError maps the store's uniqueness sentinels onto
// AlreadyExists and everything else onto Internal with the given context.
func convertUserWriteError(err error, context string) error {
diff --git a/server/api/user_service_converters.go b/server/api/user_service_converters.go
index 15a162ee0..2055d341b 100644
--- a/server/api/user_service_converters.go
+++ b/server/api/user_service_converters.go
@@ -8,6 +8,7 @@ import (
"github.com/pkg/errors"
"google.golang.org/protobuf/types/known/timestamppb"
+ coreuser "github.com/usememos/memos/core/user"
apipb "github.com/usememos/memos/proto/gen/api"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
@@ -49,23 +50,11 @@ func canViewerAccessUserEmail(viewer, user *store.User) bool {
}
func convertUserRoleFromStore(role store.Role) apipb.User_Role {
- switch role {
- case store.RoleAdmin:
- return apipb.User_ADMIN
- case store.RoleUser:
- return apipb.User_USER
- default:
- return apipb.User_ROLE_UNSPECIFIED
- }
+ return coreuser.RoleFromStore(role)
}
func convertUserRoleToStore(role apipb.User_Role) store.Role {
- switch role {
- case apipb.User_ADMIN:
- return store.RoleAdmin
- default:
- return store.RoleUser
- }
+ return coreuser.RoleToStore(role)
}
// extractImageInfo extracts image type and base64 data from a data URI.
diff --git a/server/test/startup_test.go b/server/test/startup_test.go
index 9337ed8da..8a12942c9 100644
--- a/server/test/startup_test.go
+++ b/server/test/startup_test.go
@@ -14,6 +14,7 @@ import (
"fmt"
"net"
"net/http"
+ "os"
"path/filepath"
"strings"
"testing"
@@ -24,6 +25,7 @@ import (
// sqlite driver.
_ "modernc.org/sqlite"
+ "github.com/usememos/memos/core/configuration"
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/internal/version"
storepb "github.com/usememos/memos/proto/gen/store"
@@ -51,6 +53,9 @@ type instanceOptions struct {
// dataDir reuses an existing data directory instead of a fresh one, which
// is how a restart against an already-migrated database is simulated.
dataDir string
+ // configDir is the declarative configuration directory applied at
+ // startup; empty means a directory that does not exist.
+ configDir string
}
// instance is a booted server plus the HTTP plumbing needed to talk to it.
@@ -62,8 +67,8 @@ type instance struct {
}
// bootInstance starts a full server following the same sequence as
-// cmd/memos/main.go: validate profile, open the driver, migrate, load
-// deployment configuration, construct the server, then listen.
+// cmd/memos/main.go: validate profile, open the driver, migrate, apply the
+// declarative configuration, construct the server, then listen.
//
// Keep this in lockstep with main.go. The value of these tests comes from
// exercising the real startup path rather than a hand-assembled subset of it.
@@ -94,11 +99,15 @@ func bootInstance(ctx context.Context, t *testing.T, opts instanceOptions) *inst
storeInstance := store.New(dbDriver, instanceProfile)
require.NoError(t, storeInstance.Migrate(ctx), "should migrate database")
- // main.go calls LoadDeploymentConfiguration, which scans the fixed
- // /etc/secrets path. Point the scan at a per-test directory so the result
- // cannot depend on host state; the missing-directory branch is identical.
- require.NoError(t, storeInstance.LoadDeploymentConfigurationDir(ctx, filepath.Join(dataDir, "secrets")),
- "should load deployment configuration")
+ configDir := opts.configDir
+ if configDir == "" {
+ configDir = filepath.Join(dataDir, "no-configuration")
+ }
+ desired, err := configuration.Load(configDir, configuration.OSResolver())
+ require.NoError(t, err, "should load the configuration")
+ plan, _, err := configuration.Apply(ctx, desired, storeInstance, configuration.ApplyMetadata{AppliedBy: "startup test", Now: time.Now()})
+ require.NoError(t, err, "should apply the configuration")
+ require.True(t, plan.Valid(), "the configuration should be applicable: %v", plan.Message.Errors)
s, err := server.NewServer(ctx, instanceProfile, storeInstance)
require.NoError(t, err, "should construct server")
@@ -546,3 +555,37 @@ func TestStartupDemoMode(t *testing.T) {
require.NoError(t, json.Unmarshal(body, &listed))
require.NotEmpty(t, listed.Memos, "demo mode should seed memos")
}
+
+// TestStartupAppliesConfiguration boots a headless instance from files alone:
+// the administrator signs in without anyone having opened the browser, and the
+// configured settings are what the API serves.
+func TestStartupAppliesConfiguration(t *testing.T) {
+ ctx := context.Background()
+ configDir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(configDir, "instance.json"), []byte(`{
+ "instanceSettings": [
+ {"name": "instance/settings/ACCESS", "accessSetting": {"accessMode": "INSTANCE_ACCESS_MODE_PUBLIC"}},
+ {"name": "instance/settings/GENERAL", "generalSetting": {"customProfile": {"title": "Configured Memos"}}}
+ ],
+ "users": [{"name": "users/`+testAdminUsername+`", "username": "`+testAdminUsername+`", "role": "ADMIN", "password": "${env:MEMOS_TEST_ADMIN_PASSWORD}"}]
+ }`), 0o600))
+ t.Setenv("MEMOS_TEST_ADMIN_PASSWORD", testAdminPassword)
+ inst := bootInstance(ctx, t, instanceOptions{configDir: configDir})
+
+ token := inst.signIn(t)
+ status, body := inst.do(t, http.MethodGet, "/api/instance/settings/GENERAL", "", nil)
+ require.Equal(t, http.StatusOK, status, "a public instance serves GENERAL anonymously: %s", body)
+ require.Contains(t, string(body), "Configured Memos")
+
+ status, body = inst.do(t, http.MethodGet, "/api/instance/configuration", token, nil)
+ require.Equal(t, http.StatusOK, status, "%s", body)
+ var configurationStatus struct {
+ Serial string `json:"serial"`
+ ManagedResources []struct {
+ Resource string `json:"resource"`
+ } `json:"managedResources"`
+ }
+ require.NoError(t, json.Unmarshal(body, &configurationStatus))
+ require.Equal(t, "1", configurationStatus.Serial)
+ require.Len(t, configurationStatus.ManagedResources, 3)
+}
diff --git a/store/auth_config.go b/store/auth_config.go
index 899e18475..c404e771f 100644
--- a/store/auth_config.go
+++ b/store/auth_config.go
@@ -2,16 +2,15 @@ package store
import (
"context"
- "time"
+ "database/sql"
"github.com/pkg/errors"
"google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
storepb "github.com/usememos/memos/proto/gen/store"
)
-const authenticationMutationMaxAttempts = 3
-
// ErrUnsafeAuthenticationConfiguration indicates a mutation would lock regular users out.
var ErrUnsafeAuthenticationConfiguration = errors.New("password authentication for regular users cannot be disabled without an effective identity provider")
@@ -41,13 +40,13 @@ func (s *Store) UpsertInstanceGeneralSettingSafely(ctx context.Context, setting
mutation := &AuthenticationConfigMutation{
UpsertGeneralSetting: raw,
Validate: func(state *AuthenticationConfigState) error {
- return s.validateAuthenticationMutationState(state, setting.GetGeneralSetting(), nil)
+ return validateAuthenticationMutationState(state, setting.GetGeneralSetting(), nil)
},
}
if err := s.applyAuthenticationConfigMutation(ctx, mutation); err != nil {
return nil, err
}
- result := cloneInstanceSetting(setting)
+ result := proto.CloneOf(setting)
s.cacheInstanceSetting(ctx, result)
return result, nil
}
@@ -60,7 +59,7 @@ func (s *Store) DeleteIdentityProviderSafely(ctx context.Context, delete *Delete
mutation := &AuthenticationConfigMutation{
DeleteIdentityProviderID: &delete.ID,
Validate: func(state *AuthenticationConfigState) error {
- return s.validateAuthenticationMutationState(state, nil, &delete.ID)
+ return validateAuthenticationMutationState(state, nil, &delete.ID)
},
}
return s.applyAuthenticationConfigMutation(ctx, mutation)
@@ -70,22 +69,12 @@ func (s *Store) applyAuthenticationConfigMutation(ctx context.Context, mutation
s.authConfigMu.Lock()
defer s.authConfigMu.Unlock()
- var err error
- for attempt := range authenticationMutationMaxAttempts {
- err = s.driver.ApplyAuthenticationConfigMutation(ctx, mutation)
- if err == nil || !s.driver.IsRetryableAuthenticationMutationError(err) {
- return err
- }
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-time.After(time.Duration(attempt+1) * 10 * time.Millisecond):
- }
- }
- return errors.Wrap(err, "authentication configuration mutation failed after retries")
+ return s.runSerializable(ctx, func(tx *sql.Tx) error {
+ return s.driver.ApplyAuthenticationConfigMutationTx(ctx, tx, mutation)
+ })
}
-func (s *Store) validateAuthenticationMutationState(state *AuthenticationConfigState, proposedGeneral *storepb.InstanceGeneralSetting, deletedProviderID *int32) error {
+func validateAuthenticationMutationState(state *AuthenticationConfigState, proposedGeneral *storepb.InstanceGeneralSetting, deletedProviderID *int32) error {
var storedGeneral *storepb.InstanceGeneralSetting
if state.GeneralSetting != nil {
stored, err := convertInstanceSettingFromRaw(state.GeneralSetting)
@@ -95,49 +84,21 @@ func (s *Store) validateAuthenticationMutationState(state *AuthenticationConfigS
storedGeneral = stored.GetGeneralSetting()
}
- storedUIDs := make(map[string]struct{}, len(state.IdentityProviders))
- for _, provider := range state.IdentityProviders {
- storedUIDs[provider.UID] = struct{}{}
- }
- effectiveUIDs := make(map[string]struct{}, len(state.IdentityProviders))
+ oldUIDs := make(map[string]struct{}, len(state.IdentityProviders))
+ newUIDs := make(map[string]struct{}, len(state.IdentityProviders))
for _, provider := range state.IdentityProviders {
+ oldUIDs[provider.UID] = struct{}{}
if deletedProviderID != nil && provider.ID == *deletedProviderID {
continue
}
- effectiveUIDs[provider.UID] = struct{}{}
- }
- for _, provider := range s.listDeploymentIdentityProviders() {
- effectiveUIDs[provider.Uid] = struct{}{}
- }
-
- configuredGeneral := s.getDeploymentInstanceSetting(storepb.InstanceSettingKey_GENERAL)
- if proposedGeneral != nil && configuredGeneral != nil {
- // A deployment-managed GENERAL setting keeps the proposal from becoming
- // effective now, but the stored fallback must not move from safe to unsafe
- // if the deployment file is removed later.
- if isUnsafeAuthenticationState(proposedGeneral, storedUIDs) && !isUnsafeAuthenticationState(storedGeneral, storedUIDs) {
- return ErrUnsafeAuthenticationConfiguration
- }
- return nil
+ newUIDs[provider.UID] = struct{}{}
}
- oldGeneral := storedGeneral
- if configuredGeneral != nil {
- oldGeneral = configuredGeneral.GetGeneralSetting()
- }
- newGeneral := oldGeneral
+ newGeneral := storedGeneral
if proposedGeneral != nil {
newGeneral = proposedGeneral
}
-
- oldEffectiveUIDs := make(map[string]struct{}, len(storedUIDs))
- for uid := range storedUIDs {
- oldEffectiveUIDs[uid] = struct{}{}
- }
- for _, provider := range s.listDeploymentIdentityProviders() {
- oldEffectiveUIDs[provider.Uid] = struct{}{}
- }
- if isUnsafeAuthenticationState(newGeneral, effectiveUIDs) && !isUnsafeAuthenticationState(oldGeneral, oldEffectiveUIDs) {
+ if isUnsafeAuthenticationState(newGeneral, newUIDs) && !isUnsafeAuthenticationState(storedGeneral, oldUIDs) {
return ErrUnsafeAuthenticationConfiguration
}
return nil
diff --git a/store/configuration_state.go b/store/configuration_state.go
new file mode 100644
index 000000000..9a865aa4d
--- /dev/null
+++ b/store/configuration_state.go
@@ -0,0 +1,279 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "log/slog"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
+
+ storepb "github.com/usememos/memos/proto/gen/store"
+)
+
+// The state record is one system_setting row. It is state, not a setting: the
+// instance setting reads skip it, because convertInstanceSettingFromRaw has no
+// case for its key.
+var configurationStateName = storepb.InstanceSettingKey_CONFIGURATION_STATE.String()
+
+// GetConfigurationState returns the declarative configuration state record,
+// read from the database without the instance setting cache. Before any apply
+// has changed something, it is an empty record with serial 0.
+func (s *Store) GetConfigurationState(ctx context.Context) (*storepb.InstanceConfigurationState, error) {
+ list, err := s.driver.ListInstanceSettings(ctx, &FindInstanceSetting{Name: configurationStateName})
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to read configuration state")
+ }
+ if len(list) == 0 {
+ return &storepb.InstanceConfigurationState{}, nil
+ }
+ return decodeConfigurationState(list[0])
+}
+
+// ConfigurationTransaction is one serializable transaction over declarative
+// configuration, opened by RunConfigurationTransaction. Its reads see what the
+// transaction has written, and its writes apply the same normalization and
+// checks as the store's own writes; caches are invalidated once it commits.
+type ConfigurationTransaction struct {
+ store *Store
+ tx *sql.Tx
+ state *storepb.InstanceConfigurationState
+
+ settingNames []string
+ userIDs []int32
+ passwordsChanged []int32
+}
+
+// State returns the state record as read at the start of the transaction.
+func (t *ConfigurationTransaction) State() *storepb.InstanceConfigurationState {
+ return proto.CloneOf(t.state)
+}
+
+// GetConfigurationState is State, so a transaction can be read like a store.
+func (t *ConfigurationTransaction) GetConfigurationState(context.Context) (*storepb.InstanceConfigurationState, error) {
+ return t.State(), nil
+}
+
+// ListIdentityProviders reads identity providers within the transaction.
+func (t *ConfigurationTransaction) ListIdentityProviders(ctx context.Context, find *FindIdentityProvider) ([]*storepb.IdentityProvider, error) {
+ list, err := t.store.driver.ListIdentityProvidersTx(ctx, t.tx, find)
+ if err != nil {
+ return nil, err
+ }
+ providers := make([]*storepb.IdentityProvider, 0, len(list))
+ for _, raw := range list {
+ provider, err := convertIdentityProviderFromRaw(raw)
+ if err != nil {
+ return nil, err
+ }
+ providers = append(providers, provider)
+ }
+ return providers, nil
+}
+
+// GetUncachedInstanceSetting reads one setting within the transaction.
+func (t *ConfigurationTransaction) GetUncachedInstanceSetting(ctx context.Context, find *FindInstanceSetting) (*storepb.InstanceSetting, error) {
+ raw, err := t.store.driver.GetInstanceSettingTx(ctx, t.tx, find.Name)
+ if err != nil || raw == nil {
+ return nil, err
+ }
+ return convertInstanceSettingFromRaw(raw)
+}
+
+// ListUsers reads users within the transaction.
+func (t *ConfigurationTransaction) ListUsers(ctx context.Context, find *FindUser) ([]*User, error) {
+ return t.store.driver.ListUsersTx(ctx, t.tx, find)
+}
+
+// CreateIdentityProvider creates an identity provider within the transaction.
+func (t *ConfigurationTransaction) CreateIdentityProvider(ctx context.Context, provider *storepb.IdentityProvider) error {
+ raw, err := convertIdentityProviderToRaw(provider)
+ if err != nil {
+ return err
+ }
+ if _, err := t.store.driver.CreateIdentityProviderTx(ctx, t.tx, raw); err != nil {
+ return errors.Wrapf(err, "failed to create identity provider %s", provider.Uid)
+ }
+ return nil
+}
+
+// ReplaceIdentityProvider writes every field of the identity provider with id.
+func (t *ConfigurationTransaction) ReplaceIdentityProvider(ctx context.Context, id int32, provider *storepb.IdentityProvider) error {
+ config, err := convertIdentityProviderConfigToRaw(provider.Type, provider.Config)
+ if err != nil {
+ return err
+ }
+ name, filter := provider.Name, provider.IdentifierFilter
+ if _, err := t.store.driver.UpdateIdentityProviderTx(ctx, t.tx, &UpdateIdentityProvider{
+ ID: id, Name: &name, IdentifierFilter: &filter, Config: &config,
+ }); err != nil {
+ return errors.Wrapf(err, "failed to update identity provider %s", provider.Uid)
+ }
+ return nil
+}
+
+// DeleteIdentityProvider deletes the identity provider with id.
+func (t *ConfigurationTransaction) DeleteIdentityProvider(ctx context.Context, id int32) error {
+ if err := t.store.driver.DeleteIdentityProviderTx(ctx, t.tx, &DeleteIdentityProvider{ID: id}); err != nil {
+ return errors.Wrap(err, "failed to delete identity provider")
+ }
+ return nil
+}
+
+// UpsertInstanceSetting writes a setting within the transaction.
+func (t *ConfigurationTransaction) UpsertInstanceSetting(ctx context.Context, setting *storepb.InstanceSetting) error {
+ raw, err := encodeInstanceSetting(setting)
+ if err != nil {
+ return err
+ }
+ if err := t.store.driver.UpsertInstanceSettingTx(ctx, t.tx, raw); err != nil {
+ return errors.Wrapf(err, "failed to write instance setting %s", raw.Name)
+ }
+ t.settingNames = append(t.settingNames, raw.Name)
+ return nil
+}
+
+// DeleteInstanceSetting deletes a setting, so its defaults apply again.
+func (t *ConfigurationTransaction) DeleteInstanceSetting(ctx context.Context, key storepb.InstanceSettingKey) error {
+ if err := t.store.driver.DeleteInstanceSettingTx(ctx, t.tx, &DeleteInstanceSetting{Name: key.String()}); err != nil {
+ return errors.Wrapf(err, "failed to delete instance setting %s", key)
+ }
+ t.settingNames = append(t.settingNames, key.String())
+ return nil
+}
+
+// CreateUser creates a user within the transaction.
+func (t *ConfigurationTransaction) CreateUser(ctx context.Context, create *User) (*User, error) {
+ email, err := normalizeUserEmail(create.Email)
+ if err != nil {
+ return nil, err
+ }
+ create.Email = email
+ user, err := t.store.driver.CreateUserTx(ctx, t.tx, create)
+ if err != nil {
+ if uniqueErr := classifyUserUniqueViolation(err); uniqueErr != nil {
+ return nil, uniqueErr
+ }
+ return nil, errors.Wrapf(err, "failed to create user %s", create.Username)
+ }
+ t.userIDs = append(t.userIDs, user.ID)
+ return user, nil
+}
+
+// UpdateUser updates a user within the transaction, keeping the last active
+// administrator as the store's own update does.
+func (t *ConfigurationTransaction) UpdateUser(ctx context.Context, update *UpdateUser) error {
+ if update.Email != nil {
+ email, err := normalizeUserEmail(*update.Email)
+ if err != nil {
+ return err
+ }
+ update.Email = &email
+ }
+ if _, err := t.store.driver.UpdateUserTx(ctx, t.tx, update); err != nil {
+ if uniqueErr := classifyUserUniqueViolation(err); uniqueErr != nil {
+ return uniqueErr
+ }
+ return errors.Wrap(err, "failed to update user")
+ }
+ t.userIDs = append(t.userIDs, update.ID)
+ if update.PasswordHash != nil {
+ t.passwordsChanged = append(t.passwordsChanged, update.ID)
+ }
+ return nil
+}
+
+// afterCommit drops what the committed writes made stale. A new password ends
+// every session of that user, as an administrator's password reset does.
+func (t *ConfigurationTransaction) afterCommit(ctx context.Context) {
+ s := t.store
+ for _, name := range t.settingNames {
+ s.instanceSettingCache.Delete(ctx, name)
+ if name == storepb.InstanceSettingKey_STORAGE.String() {
+ s.resetStorageDriverCache()
+ }
+ }
+ for _, userID := range t.userIDs {
+ s.userCache.Delete(ctx, userCacheKey(userID))
+ }
+ for _, userID := range t.passwordsChanged {
+ if err := s.RemoveUserRefreshTokensExcept(ctx, userID, ""); err != nil {
+ slog.Warn("failed to revoke sessions after a configured password change", "user_id", userID, "error", err)
+ }
+ }
+}
+
+// RunConfigurationTransaction runs fn in one serializable transaction that
+// starts by reading, and where the database supports it locking, the state
+// record. fn returns the record to store, or nil when nothing changed; a
+// returned record is written with the next serial, whatever serial it carries.
+// fn runs again when the transaction conflicts with a concurrent one, so it
+// must derive what it writes from what it reads through tx. The result is the
+// record as stored when the transaction commits.
+func (s *Store) RunConfigurationTransaction(
+ ctx context.Context,
+ fn func(ctx context.Context, tx *ConfigurationTransaction) (*storepb.InstanceConfigurationState, error),
+) (*storepb.InstanceConfigurationState, error) {
+ var result *storepb.InstanceConfigurationState
+ var committed *ConfigurationTransaction
+ err := s.runSerializable(ctx, func(tx *sql.Tx) error {
+ raw, err := s.driver.GetInstanceSettingTx(ctx, tx, configurationStateName)
+ if err != nil {
+ return errors.Wrap(err, "failed to read configuration state")
+ }
+ current := &storepb.InstanceConfigurationState{}
+ if raw != nil {
+ if current, err = decodeConfigurationState(raw); err != nil {
+ return err
+ }
+ }
+
+ transaction := &ConfigurationTransaction{store: s, tx: tx, state: current}
+ committed = transaction
+ next, err := fn(ctx, transaction)
+ if err != nil {
+ return err
+ }
+ if next == nil {
+ result = current
+ return nil
+ }
+ next = proto.CloneOf(next)
+ next.Serial = current.Serial + 1
+ value, err := protojson.Marshal(next)
+ if err != nil {
+ return errors.Wrap(err, "failed to encode configuration state")
+ }
+
+ // The write is conditional on the row read above, so a concurrent apply
+ // that slipped past the database's isolation still cannot be overwritten.
+ var written bool
+ if raw == nil {
+ written, err = s.driver.CreateInstanceSettingIfNotExistsTx(ctx, tx, &InstanceSetting{Name: configurationStateName, Value: string(value)})
+ } else {
+ written, err = s.driver.UpdateInstanceSettingIfUnchangedTx(ctx, tx, configurationStateName, raw.Value, string(value))
+ }
+ if err != nil {
+ return errors.Wrap(err, "failed to write configuration state")
+ }
+ if !written {
+ return errTransactionConflict
+ }
+ result = next
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ committed.afterCommit(ctx)
+ return result, nil
+}
+
+func decodeConfigurationState(raw *InstanceSetting) (*storepb.InstanceConfigurationState, error) {
+ state := &storepb.InstanceConfigurationState{}
+ if err := protojsonUnmarshaler.Unmarshal([]byte(raw.Value), state); err != nil {
+ return nil, errors.Wrap(err, "failed to decode configuration state")
+ }
+ return state, nil
+}
diff --git a/store/db/mysql/auth_config.go b/store/db/mysql/auth_config.go
index 0c0f78ddf..b2ca489e0 100644
--- a/store/db/mysql/auth_config.go
+++ b/store/db/mysql/auth_config.go
@@ -10,8 +10,8 @@ import (
"github.com/usememos/memos/store"
)
-// IsRetryableAuthenticationMutationError reports whether err is a transient MySQL transaction failure.
-func (*DB) IsRetryableAuthenticationMutationError(err error) bool {
+// IsRetryableTransactionError reports whether err is a transient MySQL transaction failure.
+func (*DB) IsRetryableTransactionError(err error) bool {
var mysqlErr *mysqldriver.MySQLError
if !errors.As(err, &mysqlErr) {
return false
@@ -19,19 +19,11 @@ func (*DB) IsRetryableAuthenticationMutationError(err error) bool {
return mysqlErr.Number == 1205 || mysqlErr.Number == 1213
}
-// ApplyAuthenticationConfigMutation validates and applies an auth mutation in a serializable transaction.
-func (d *DB) ApplyAuthenticationConfigMutation(ctx context.Context, mutation *store.AuthenticationConfigMutation) error {
- tx, err := d.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
- if err != nil {
- return errors.Wrap(err, "failed to begin authentication configuration transaction")
- }
- defer func() {
- _ = tx.Rollback()
- }()
-
+// ApplyAuthenticationConfigMutationTx validates and applies an auth mutation within tx, a serializable transaction.
+func (*DB) ApplyAuthenticationConfigMutationTx(ctx context.Context, tx *sql.Tx, mutation *store.AuthenticationConfigMutation) error {
state := &store.AuthenticationConfigState{}
general := &store.InstanceSetting{}
- err = tx.QueryRowContext(ctx, "SELECT `name`, `value`, `description` FROM `system_setting` WHERE `name` = ? FOR UPDATE", "GENERAL").Scan(
+ err := tx.QueryRowContext(ctx, "SELECT `name`, `value`, `description` FROM `system_setting` WHERE `name` = ? FOR UPDATE", "GENERAL").Scan(
&general.Name, &general.Value, &general.Description,
)
if err == nil {
@@ -74,8 +66,5 @@ func (d *DB) ApplyAuthenticationConfigMutation(ctx context.Context, mutation *st
if err != nil {
return errors.Wrap(err, "failed to apply authentication configuration mutation")
}
- if err := tx.Commit(); err != nil {
- return errors.Wrap(err, "failed to commit authentication configuration transaction")
- }
return nil
}
diff --git a/store/db/mysql/auth_config_test.go b/store/db/mysql/auth_config_test.go
index 6d02a9353..45e99ee8a 100644
--- a/store/db/mysql/auth_config_test.go
+++ b/store/db/mysql/auth_config_test.go
@@ -8,9 +8,9 @@ import (
"github.com/stretchr/testify/require"
)
-func TestIsRetryableAuthenticationMutationError(t *testing.T) {
+func TestIsRetryableTransactionError(t *testing.T) {
db := &DB{}
- require.True(t, db.IsRetryableAuthenticationMutationError(errors.Wrap(&mysqldriver.MySQLError{Number: 1213}, "commit failed")))
- require.True(t, db.IsRetryableAuthenticationMutationError(&mysqldriver.MySQLError{Number: 1205}))
- require.False(t, db.IsRetryableAuthenticationMutationError(&mysqldriver.MySQLError{Number: 1062}))
+ require.True(t, db.IsRetryableTransactionError(errors.Wrap(&mysqldriver.MySQLError{Number: 1213}, "commit failed")))
+ require.True(t, db.IsRetryableTransactionError(&mysqldriver.MySQLError{Number: 1205}))
+ require.False(t, db.IsRetryableTransactionError(&mysqldriver.MySQLError{Number: 1062}))
}
diff --git a/store/db/mysql/executor.go b/store/db/mysql/executor.go
new file mode 100644
index 000000000..b98f8bfff
--- /dev/null
+++ b/store/db/mysql/executor.go
@@ -0,0 +1,14 @@
+package mysql
+
+import (
+ "context"
+ "database/sql"
+)
+
+// dbExecutor is the common query surface implemented by the database handle
+// and its transactions.
+type dbExecutor interface {
+ ExecContext(context.Context, string, ...any) (sql.Result, error)
+ QueryRowContext(context.Context, string, ...any) *sql.Row
+ QueryContext(context.Context, string, ...any) (*sql.Rows, error)
+}
diff --git a/store/db/mysql/idp.go b/store/db/mysql/idp.go
index 9af3f8046..19981b49a 100644
--- a/store/db/mysql/idp.go
+++ b/store/db/mysql/idp.go
@@ -2,6 +2,7 @@ package mysql
import (
"context"
+ "database/sql"
"strings"
"github.com/pkg/errors"
@@ -11,12 +12,21 @@ import (
)
func (d *DB) CreateIdentityProvider(ctx context.Context, create *store.IdentityProvider) (*store.IdentityProvider, error) {
+ return createIdentityProvider(ctx, d.db, create)
+}
+
+// CreateIdentityProviderTx is CreateIdentityProvider within tx.
+func (*DB) CreateIdentityProviderTx(ctx context.Context, tx *sql.Tx, create *store.IdentityProvider) (*store.IdentityProvider, error) {
+ return createIdentityProvider(ctx, tx, create)
+}
+
+func createIdentityProvider(ctx context.Context, q dbExecutor, create *store.IdentityProvider) (*store.IdentityProvider, error) {
placeholders := []string{"?", "?", "?", "?", "?"}
fields := []string{"`uid`", "`name`", "`type`", "`identifier_filter`", "`config`"}
args := []any{create.UID, create.Name, create.Type.String(), create.IdentifierFilter, create.Config}
stmt := "INSERT INTO `idp` (" + strings.Join(fields, ", ") + ") VALUES (" + strings.Join(placeholders, ", ") + ")"
- result, err := d.db.ExecContext(ctx, stmt, args...)
+ result, err := q.ExecContext(ctx, stmt, args...)
if err != nil {
return nil, err
}
@@ -31,6 +41,15 @@ func (d *DB) CreateIdentityProvider(ctx context.Context, create *store.IdentityP
}
func (d *DB) ListIdentityProviders(ctx context.Context, find *store.FindIdentityProvider) ([]*store.IdentityProvider, error) {
+ return listIdentityProviders(ctx, d.db, find)
+}
+
+// ListIdentityProvidersTx is ListIdentityProviders within tx.
+func (*DB) ListIdentityProvidersTx(ctx context.Context, tx *sql.Tx, find *store.FindIdentityProvider) ([]*store.IdentityProvider, error) {
+ return listIdentityProviders(ctx, tx, find)
+}
+
+func listIdentityProviders(ctx context.Context, q dbExecutor, find *store.FindIdentityProvider) ([]*store.IdentityProvider, error) {
where, args := []string{"1 = 1"}, []any{}
if v := find.ID; v != nil {
where, args = append(where, "`id` = ?"), append(args, *v)
@@ -39,7 +58,7 @@ func (d *DB) ListIdentityProviders(ctx context.Context, find *store.FindIdentity
where, args = append(where, "`uid` = ?"), append(args, *v)
}
- rows, err := d.db.QueryContext(ctx, "SELECT `id`, `uid`, `name`, `type`, `identifier_filter`, `config` FROM `idp` WHERE "+strings.Join(where, " AND ")+" ORDER BY `id` ASC",
+ rows, err := q.QueryContext(ctx, "SELECT `id`, `uid`, `name`, `type`, `identifier_filter`, `config` FROM `idp` WHERE "+strings.Join(where, " AND ")+" ORDER BY `id` ASC",
args...,
)
if err != nil {
@@ -86,6 +105,15 @@ func (d *DB) GetIdentityProvider(ctx context.Context, find *store.FindIdentityPr
}
func (d *DB) UpdateIdentityProvider(ctx context.Context, update *store.UpdateIdentityProvider) (*store.IdentityProvider, error) {
+ return updateIdentityProvider(ctx, d.db, update)
+}
+
+// UpdateIdentityProviderTx is UpdateIdentityProvider within tx.
+func (*DB) UpdateIdentityProviderTx(ctx context.Context, tx *sql.Tx, update *store.UpdateIdentityProvider) (*store.IdentityProvider, error) {
+ return updateIdentityProvider(ctx, tx, update)
+}
+
+func updateIdentityProvider(ctx context.Context, q dbExecutor, update *store.UpdateIdentityProvider) (*store.IdentityProvider, error) {
set, args := []string{}, []any{}
if v := update.Name; v != nil {
set, args = append(set, "`name` = ?"), append(args, *v)
@@ -99,27 +127,34 @@ func (d *DB) UpdateIdentityProvider(ctx context.Context, update *store.UpdateIde
args = append(args, update.ID)
stmt := "UPDATE `idp` SET " + strings.Join(set, ", ") + " WHERE `id` = ?"
- _, err := d.db.ExecContext(ctx, stmt, args...)
+ _, err := q.ExecContext(ctx, stmt, args...)
if err != nil {
return nil, err
}
- identityProvider, err := d.GetIdentityProvider(ctx, &store.FindIdentityProvider{
- ID: &update.ID,
- })
+ list, err := listIdentityProviders(ctx, q, &store.FindIdentityProvider{ID: &update.ID})
if err != nil {
return nil, err
}
- if identityProvider == nil {
+ if len(list) == 0 {
return nil, errors.Errorf("idp %d not found", update.ID)
}
- return identityProvider, nil
+ return list[0], nil
}
func (d *DB) DeleteIdentityProvider(ctx context.Context, delete *store.DeleteIdentityProvider) error {
+ return deleteIdentityProvider(ctx, d.db, delete)
+}
+
+// DeleteIdentityProviderTx is DeleteIdentityProvider within tx.
+func (*DB) DeleteIdentityProviderTx(ctx context.Context, tx *sql.Tx, delete *store.DeleteIdentityProvider) error {
+ return deleteIdentityProvider(ctx, tx, delete)
+}
+
+func deleteIdentityProvider(ctx context.Context, q dbExecutor, delete *store.DeleteIdentityProvider) error {
where, args := []string{"`id` = ?"}, []any{delete.ID}
stmt := "DELETE FROM `idp` WHERE " + strings.Join(where, " AND ")
- result, err := d.db.ExecContext(ctx, stmt, args...)
+ result, err := q.ExecContext(ctx, stmt, args...)
if err != nil {
return err
}
diff --git a/store/db/mysql/instance_setting.go b/store/db/mysql/instance_setting.go
index 2601fb277..96d8d139f 100644
--- a/store/db/mysql/instance_setting.go
+++ b/store/db/mysql/instance_setting.go
@@ -12,8 +12,17 @@ import (
// CreateInstanceSettingIfNotExists atomically creates the setting when its name is absent and reports whether it inserted the row.
func (d *DB) CreateInstanceSettingIfNotExists(ctx context.Context, create *store.InstanceSetting) (bool, error) {
+ return createInstanceSettingIfNotExists(ctx, d.db, create)
+}
+
+// CreateInstanceSettingIfNotExistsTx is CreateInstanceSettingIfNotExists within tx.
+func (*DB) CreateInstanceSettingIfNotExistsTx(ctx context.Context, tx *sql.Tx, create *store.InstanceSetting) (bool, error) {
+ return createInstanceSettingIfNotExists(ctx, tx, create)
+}
+
+func createInstanceSettingIfNotExists(ctx context.Context, executor instanceSettingExecer, create *store.InstanceSetting) (bool, error) {
stmt := "INSERT IGNORE INTO `system_setting` (`name`, `value`, `description`) VALUES (?, ?, ?)"
- result, err := d.db.ExecContext(ctx, stmt, create.Name, create.Value, create.Description)
+ result, err := executor.ExecContext(ctx, stmt, create.Name, create.Value, create.Description)
if err != nil {
return false, errors.Wrap(err, "failed to conditionally create instance setting")
}
@@ -27,14 +36,23 @@ func (d *DB) CreateInstanceSettingIfNotExists(ctx context.Context, create *store
// UpdateInstanceSettingIfUnchanged replaces the setting value only when the
// stored value still equals oldValue, and reports whether it did.
func (d *DB) UpdateInstanceSettingIfUnchanged(ctx context.Context, name, oldValue, newValue string) (bool, error) {
+ return updateInstanceSettingIfUnchanged(ctx, d.db, name, oldValue, newValue)
+}
+
+// UpdateInstanceSettingIfUnchangedTx is UpdateInstanceSettingIfUnchanged within tx.
+func (*DB) UpdateInstanceSettingIfUnchangedTx(ctx context.Context, tx *sql.Tx, name, oldValue, newValue string) (bool, error) {
+ return updateInstanceSettingIfUnchanged(ctx, tx, name, oldValue, newValue)
+}
+
+func updateInstanceSettingIfUnchanged(ctx context.Context, executor instanceSettingExecer, name, oldValue, newValue string) (bool, error) {
// MySQL reports zero affected rows when the new value equals the stored
// one, which would read as a conflict. An unchanged write is a no-op.
if oldValue == newValue {
- return d.instanceSettingHasValue(ctx, name, oldValue)
+ return instanceSettingHasValue(ctx, executor, name, oldValue)
}
// A binary comparison is exact; the column collation may ignore case
// and trailing spaces.
- result, err := d.db.ExecContext(ctx, "UPDATE `system_setting` SET `value` = ? WHERE `name` = ? AND `value` = CAST(? AS BINARY)", newValue, name, oldValue)
+ result, err := executor.ExecContext(ctx, "UPDATE `system_setting` SET `value` = ? WHERE `name` = ? AND `value` = CAST(? AS BINARY)", newValue, name, oldValue)
if err != nil {
return false, errors.Wrap(err, "failed to conditionally update instance setting")
}
@@ -45,14 +63,30 @@ func (d *DB) UpdateInstanceSettingIfUnchanged(ctx context.Context, name, oldValu
return rowsAffected == 1, nil
}
-func (d *DB) instanceSettingHasValue(ctx context.Context, name, value string) (bool, error) {
+func instanceSettingHasValue(ctx context.Context, executor instanceSettingExecer, name, value string) (bool, error) {
var count int
- if err := d.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM `system_setting` WHERE `name` = ? AND `value` = CAST(? AS BINARY)", name, value).Scan(&count); err != nil {
+ if err := executor.QueryRowContext(ctx, "SELECT COUNT(*) FROM `system_setting` WHERE `name` = ? AND `value` = CAST(? AS BINARY)", name, value).Scan(&count); err != nil {
return false, errors.Wrap(err, "failed to read instance setting")
}
return count == 1, nil
}
+// GetInstanceSettingTx reads and locks one setting within tx, or returns nil
+// when it is absent.
+func (*DB) GetInstanceSettingTx(ctx context.Context, tx *sql.Tx, name string) (*store.InstanceSetting, error) {
+ setting := &store.InstanceSetting{}
+ err := tx.QueryRowContext(ctx, "SELECT `name`, `value`, `description` FROM `system_setting` WHERE `name` = ? FOR UPDATE", name).Scan(
+ &setting.Name, &setting.Value, &setting.Description,
+ )
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to read instance setting")
+ }
+ return setting, nil
+}
+
func (d *DB) UpsertInstanceSetting(ctx context.Context, upsert *store.InstanceSetting) (*store.InstanceSetting, error) {
if err := upsertInstanceSetting(ctx, d.db, upsert); err != nil {
return nil, err
@@ -67,6 +101,7 @@ func (*DB) UpsertInstanceSettingTx(ctx context.Context, tx *sql.Tx, upsert *stor
type instanceSettingExecer interface {
ExecContext(context.Context, string, ...any) (sql.Result, error)
+ QueryRowContext(context.Context, string, ...any) *sql.Row
}
func upsertInstanceSetting(ctx context.Context, executor instanceSettingExecer, upsert *store.InstanceSetting) error {
@@ -117,7 +152,16 @@ func (d *DB) ListInstanceSettings(ctx context.Context, find *store.FindInstanceS
}
func (d *DB) DeleteInstanceSetting(ctx context.Context, delete *store.DeleteInstanceSetting) error {
+ return deleteInstanceSetting(ctx, d.db, delete)
+}
+
+// DeleteInstanceSettingTx is DeleteInstanceSetting within tx.
+func (*DB) DeleteInstanceSettingTx(ctx context.Context, tx *sql.Tx, delete *store.DeleteInstanceSetting) error {
+ return deleteInstanceSetting(ctx, tx, delete)
+}
+
+func deleteInstanceSetting(ctx context.Context, q dbExecutor, delete *store.DeleteInstanceSetting) error {
stmt := "DELETE FROM `system_setting` WHERE `name` = ?"
- _, err := d.db.ExecContext(ctx, stmt, delete.Name)
+ _, err := q.ExecContext(ctx, stmt, delete.Name)
return err
}
diff --git a/store/db/mysql/user.go b/store/db/mysql/user.go
index a365e5ceb..a3d5015e1 100644
--- a/store/db/mysql/user.go
+++ b/store/db/mysql/user.go
@@ -12,7 +12,16 @@ import (
)
func (d *DB) CreateUser(ctx context.Context, create *store.User) (*store.User, error) {
- result, err := insertUser(ctx, d.db, create)
+ return createUser(ctx, d.db, create)
+}
+
+// CreateUserTx is CreateUser within tx.
+func (*DB) CreateUserTx(ctx context.Context, tx *sql.Tx, create *store.User) (*store.User, error) {
+ return createUser(ctx, tx, create)
+}
+
+func createUser(ctx context.Context, q dbExecutor, create *store.User) (*store.User, error) {
+ result, err := insertUser(ctx, q, create)
if err != nil {
return nil, err
}
@@ -23,7 +32,7 @@ func (d *DB) CreateUser(ctx context.Context, create *store.User) (*store.User, e
}
id32 := int32(id)
- list, err := d.ListUsers(ctx, &store.FindUser{ID: &id32})
+ list, err := listUsers(ctx, q, &store.FindUser{ID: &id32})
if err != nil {
return nil, err
}
@@ -40,6 +49,22 @@ func (d *DB) UpdateUser(ctx context.Context, update *store.UpdateUser) (*store.U
return nil, err
}
defer func() { _ = tx.Rollback() }()
+ user, err := updateUser(ctx, tx, update)
+ if err != nil {
+ return nil, err
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, err
+ }
+ return user, nil
+}
+
+// UpdateUserTx is UpdateUser within tx.
+func (*DB) UpdateUserTx(ctx context.Context, tx *sql.Tx, update *store.UpdateUser) (*store.User, error) {
+ return updateUser(ctx, tx, update)
+}
+
+func updateUser(ctx context.Context, tx *sql.Tx, update *store.UpdateUser) (*store.User, error) {
if update.RemovesInstanceAdmin() {
if err := ensureInstanceAdminRetained(ctx, tx, update.ID); err != nil {
return nil, err
@@ -94,9 +119,6 @@ func (d *DB) UpdateUser(ctx context.Context, update *store.UpdateUser) (*store.U
return nil, err
}
user.Email = email.String
- if err := tx.Commit(); err != nil {
- return nil, err
- }
return user, nil
}
@@ -165,6 +187,15 @@ func ensureInstanceAdminRetained(ctx context.Context, tx *sql.Tx, userID int32)
}
func (d *DB) ListUsers(ctx context.Context, find *store.FindUser) ([]*store.User, error) {
+ return listUsers(ctx, d.db, find)
+}
+
+// ListUsersTx is ListUsers within tx.
+func (*DB) ListUsersTx(ctx context.Context, tx *sql.Tx, find *store.FindUser) ([]*store.User, error) {
+ return listUsers(ctx, tx, find)
+}
+
+func listUsers(ctx context.Context, q dbExecutor, find *store.FindUser) ([]*store.User, error) {
where, args := []string{"1 = 1"}, []any{}
orderBy := []string{"`created_ts` DESC", "`row_status` DESC", "`id` DESC"}
@@ -234,7 +265,7 @@ func (d *DB) ListUsers(ctx context.Context, find *store.FindUser) ([]*store.User
query += fmt.Sprintf(" OFFSET %d", *v)
}
}
- rows, err := d.db.QueryContext(ctx, query, args...)
+ rows, err := q.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
diff --git a/store/db/postgres/auth_config.go b/store/db/postgres/auth_config.go
index 4f174163d..24ee714b7 100644
--- a/store/db/postgres/auth_config.go
+++ b/store/db/postgres/auth_config.go
@@ -10,8 +10,8 @@ import (
"github.com/usememos/memos/store"
)
-// IsRetryableAuthenticationMutationError reports whether err is a transient PostgreSQL transaction failure.
-func (*DB) IsRetryableAuthenticationMutationError(err error) bool {
+// IsRetryableTransactionError reports whether err is a transient PostgreSQL transaction failure.
+func (*DB) IsRetryableTransactionError(err error) bool {
var pqErr *pq.Error
if !errors.As(err, &pqErr) {
return false
@@ -19,19 +19,11 @@ func (*DB) IsRetryableAuthenticationMutationError(err error) bool {
return pqErr.Code == "40001" || pqErr.Code == "40P01"
}
-// ApplyAuthenticationConfigMutation validates and applies an auth mutation in a serializable transaction.
-func (d *DB) ApplyAuthenticationConfigMutation(ctx context.Context, mutation *store.AuthenticationConfigMutation) error {
- tx, err := d.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
- if err != nil {
- return errors.Wrap(err, "failed to begin authentication configuration transaction")
- }
- defer func() {
- _ = tx.Rollback()
- }()
-
+// ApplyAuthenticationConfigMutationTx validates and applies an auth mutation within tx, a serializable transaction.
+func (*DB) ApplyAuthenticationConfigMutationTx(ctx context.Context, tx *sql.Tx, mutation *store.AuthenticationConfigMutation) error {
state := &store.AuthenticationConfigState{}
general := &store.InstanceSetting{}
- err = tx.QueryRowContext(ctx, `SELECT name, value, description FROM system_setting WHERE name = $1 FOR UPDATE`, "GENERAL").Scan(
+ err := tx.QueryRowContext(ctx, `SELECT name, value, description FROM system_setting WHERE name = $1 FOR UPDATE`, "GENERAL").Scan(
&general.Name, &general.Value, &general.Description,
)
if err == nil {
@@ -74,8 +66,5 @@ func (d *DB) ApplyAuthenticationConfigMutation(ctx context.Context, mutation *st
if err != nil {
return errors.Wrap(err, "failed to apply authentication configuration mutation")
}
- if err := tx.Commit(); err != nil {
- return errors.Wrap(err, "failed to commit authentication configuration transaction")
- }
return nil
}
diff --git a/store/db/postgres/auth_config_test.go b/store/db/postgres/auth_config_test.go
index d8261140c..04d4ef7f7 100644
--- a/store/db/postgres/auth_config_test.go
+++ b/store/db/postgres/auth_config_test.go
@@ -8,9 +8,9 @@ import (
"github.com/stretchr/testify/require"
)
-func TestIsRetryableAuthenticationMutationError(t *testing.T) {
+func TestIsRetryableTransactionError(t *testing.T) {
db := &DB{}
- require.True(t, db.IsRetryableAuthenticationMutationError(errors.Wrap(&pq.Error{Code: "40001"}, "commit failed")))
- require.True(t, db.IsRetryableAuthenticationMutationError(&pq.Error{Code: "40P01"}))
- require.False(t, db.IsRetryableAuthenticationMutationError(&pq.Error{Code: "23505"}))
+ require.True(t, db.IsRetryableTransactionError(errors.Wrap(&pq.Error{Code: "40001"}, "commit failed")))
+ require.True(t, db.IsRetryableTransactionError(&pq.Error{Code: "40P01"}))
+ require.False(t, db.IsRetryableTransactionError(&pq.Error{Code: "23505"}))
}
diff --git a/store/db/postgres/executor.go b/store/db/postgres/executor.go
new file mode 100644
index 000000000..b09cc6eac
--- /dev/null
+++ b/store/db/postgres/executor.go
@@ -0,0 +1,14 @@
+package postgres
+
+import (
+ "context"
+ "database/sql"
+)
+
+// dbExecutor is the common query surface implemented by the database handle
+// and its transactions.
+type dbExecutor interface {
+ ExecContext(context.Context, string, ...any) (sql.Result, error)
+ QueryRowContext(context.Context, string, ...any) *sql.Row
+ QueryContext(context.Context, string, ...any) (*sql.Rows, error)
+}
diff --git a/store/db/postgres/idp.go b/store/db/postgres/idp.go
index 2cfce4879..54988bfae 100644
--- a/store/db/postgres/idp.go
+++ b/store/db/postgres/idp.go
@@ -2,6 +2,7 @@ package postgres
import (
"context"
+ "database/sql"
"strings"
storepb "github.com/usememos/memos/proto/gen/store"
@@ -9,10 +10,19 @@ import (
)
func (d *DB) CreateIdentityProvider(ctx context.Context, create *store.IdentityProvider) (*store.IdentityProvider, error) {
+ return createIdentityProvider(ctx, d.db, create)
+}
+
+// CreateIdentityProviderTx is CreateIdentityProvider within tx.
+func (*DB) CreateIdentityProviderTx(ctx context.Context, tx *sql.Tx, create *store.IdentityProvider) (*store.IdentityProvider, error) {
+ return createIdentityProvider(ctx, tx, create)
+}
+
+func createIdentityProvider(ctx context.Context, q dbExecutor, create *store.IdentityProvider) (*store.IdentityProvider, error) {
fields := []string{"uid", "name", "type", "identifier_filter", "config"}
args := []any{create.UID, create.Name, create.Type.String(), create.IdentifierFilter, create.Config}
stmt := "INSERT INTO idp (" + strings.Join(fields, ", ") + ") VALUES (" + placeholders(len(args)) + ") RETURNING id"
- if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(&create.ID); err != nil {
+ if err := q.QueryRowContext(ctx, stmt, args...).Scan(&create.ID); err != nil {
return nil, err
}
@@ -21,6 +31,15 @@ func (d *DB) CreateIdentityProvider(ctx context.Context, create *store.IdentityP
}
func (d *DB) ListIdentityProviders(ctx context.Context, find *store.FindIdentityProvider) ([]*store.IdentityProvider, error) {
+ return listIdentityProviders(ctx, d.db, find)
+}
+
+// ListIdentityProvidersTx is ListIdentityProviders within tx.
+func (*DB) ListIdentityProvidersTx(ctx context.Context, tx *sql.Tx, find *store.FindIdentityProvider) ([]*store.IdentityProvider, error) {
+ return listIdentityProviders(ctx, tx, find)
+}
+
+func listIdentityProviders(ctx context.Context, q dbExecutor, find *store.FindIdentityProvider) ([]*store.IdentityProvider, error) {
where, args := []string{"1 = 1"}, []any{}
if v := find.ID; v != nil {
where, args = append(where, "id = "+placeholder(len(args)+1)), append(args, *v)
@@ -29,7 +48,7 @@ func (d *DB) ListIdentityProviders(ctx context.Context, find *store.FindIdentity
where, args = append(where, "uid = "+placeholder(len(args)+1)), append(args, *v)
}
- rows, err := d.db.QueryContext(ctx, `
+ rows, err := q.QueryContext(ctx, `
SELECT
id,
uid,
@@ -73,6 +92,15 @@ func (d *DB) ListIdentityProviders(ctx context.Context, find *store.FindIdentity
}
func (d *DB) UpdateIdentityProvider(ctx context.Context, update *store.UpdateIdentityProvider) (*store.IdentityProvider, error) {
+ return updateIdentityProvider(ctx, d.db, update)
+}
+
+// UpdateIdentityProviderTx is UpdateIdentityProvider within tx.
+func (*DB) UpdateIdentityProviderTx(ctx context.Context, tx *sql.Tx, update *store.UpdateIdentityProvider) (*store.IdentityProvider, error) {
+ return updateIdentityProvider(ctx, tx, update)
+}
+
+func updateIdentityProvider(ctx context.Context, q dbExecutor, update *store.UpdateIdentityProvider) (*store.IdentityProvider, error) {
set, args := []string{}, []any{}
if v := update.Name; v != nil {
set, args = append(set, "name = "+placeholder(len(args)+1)), append(args, *v)
@@ -94,7 +122,7 @@ func (d *DB) UpdateIdentityProvider(ctx context.Context, update *store.UpdateIde
var identityProvider store.IdentityProvider
var typeString string
- if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(
+ if err := q.QueryRowContext(ctx, stmt, args...).Scan(
&identityProvider.ID,
&identityProvider.UID,
&identityProvider.Name,
@@ -110,9 +138,18 @@ func (d *DB) UpdateIdentityProvider(ctx context.Context, update *store.UpdateIde
}
func (d *DB) DeleteIdentityProvider(ctx context.Context, delete *store.DeleteIdentityProvider) error {
+ return deleteIdentityProvider(ctx, d.db, delete)
+}
+
+// DeleteIdentityProviderTx is DeleteIdentityProvider within tx.
+func (*DB) DeleteIdentityProviderTx(ctx context.Context, tx *sql.Tx, delete *store.DeleteIdentityProvider) error {
+ return deleteIdentityProvider(ctx, tx, delete)
+}
+
+func deleteIdentityProvider(ctx context.Context, q dbExecutor, delete *store.DeleteIdentityProvider) error {
where, args := []string{"id = $1"}, []any{delete.ID}
stmt := `DELETE FROM idp WHERE ` + strings.Join(where, " AND ")
- result, err := d.db.ExecContext(ctx, stmt, args...)
+ result, err := q.ExecContext(ctx, stmt, args...)
if err != nil {
return err
}
diff --git a/store/db/postgres/instance_setting.go b/store/db/postgres/instance_setting.go
index c40de42c6..afb394d6c 100644
--- a/store/db/postgres/instance_setting.go
+++ b/store/db/postgres/instance_setting.go
@@ -12,6 +12,15 @@ import (
// CreateInstanceSettingIfNotExists atomically creates the setting when its name is absent and reports whether it inserted the row.
func (d *DB) CreateInstanceSettingIfNotExists(ctx context.Context, create *store.InstanceSetting) (bool, error) {
+ return createInstanceSettingIfNotExists(ctx, d.db, create)
+}
+
+// CreateInstanceSettingIfNotExistsTx is CreateInstanceSettingIfNotExists within tx.
+func (*DB) CreateInstanceSettingIfNotExistsTx(ctx context.Context, tx *sql.Tx, create *store.InstanceSetting) (bool, error) {
+ return createInstanceSettingIfNotExists(ctx, tx, create)
+}
+
+func createInstanceSettingIfNotExists(ctx context.Context, executor instanceSettingExecer, create *store.InstanceSetting) (bool, error) {
stmt := `
INSERT INTO system_setting (
name, value, description
@@ -19,7 +28,7 @@ func (d *DB) CreateInstanceSettingIfNotExists(ctx context.Context, create *store
VALUES ($1, $2, $3)
ON CONFLICT(name) DO NOTHING
`
- result, err := d.db.ExecContext(ctx, stmt, create.Name, create.Value, create.Description)
+ result, err := executor.ExecContext(ctx, stmt, create.Name, create.Value, create.Description)
if err != nil {
return false, errors.Wrap(err, "failed to conditionally create instance setting")
}
@@ -33,7 +42,16 @@ func (d *DB) CreateInstanceSettingIfNotExists(ctx context.Context, create *store
// UpdateInstanceSettingIfUnchanged replaces the setting value only when the
// stored value still equals oldValue, and reports whether it did.
func (d *DB) UpdateInstanceSettingIfUnchanged(ctx context.Context, name, oldValue, newValue string) (bool, error) {
- result, err := d.db.ExecContext(ctx, "UPDATE system_setting SET value = $1 WHERE name = $2 AND value = $3", newValue, name, oldValue)
+ return updateInstanceSettingIfUnchanged(ctx, d.db, name, oldValue, newValue)
+}
+
+// UpdateInstanceSettingIfUnchangedTx is UpdateInstanceSettingIfUnchanged within tx.
+func (*DB) UpdateInstanceSettingIfUnchangedTx(ctx context.Context, tx *sql.Tx, name, oldValue, newValue string) (bool, error) {
+ return updateInstanceSettingIfUnchanged(ctx, tx, name, oldValue, newValue)
+}
+
+func updateInstanceSettingIfUnchanged(ctx context.Context, executor instanceSettingExecer, name, oldValue, newValue string) (bool, error) {
+ result, err := executor.ExecContext(ctx, "UPDATE system_setting SET value = $1 WHERE name = $2 AND value = $3", newValue, name, oldValue)
if err != nil {
return false, errors.Wrap(err, "failed to conditionally update instance setting")
}
@@ -44,6 +62,22 @@ func (d *DB) UpdateInstanceSettingIfUnchanged(ctx context.Context, name, oldValu
return rowsAffected == 1, nil
}
+// GetInstanceSettingTx reads and locks one setting within tx, or returns nil
+// when it is absent.
+func (*DB) GetInstanceSettingTx(ctx context.Context, tx *sql.Tx, name string) (*store.InstanceSetting, error) {
+ setting := &store.InstanceSetting{}
+ err := tx.QueryRowContext(ctx, "SELECT name, value, description FROM system_setting WHERE name = $1 FOR UPDATE", name).Scan(
+ &setting.Name, &setting.Value, &setting.Description,
+ )
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to read instance setting")
+ }
+ return setting, nil
+}
+
func (d *DB) UpsertInstanceSetting(ctx context.Context, upsert *store.InstanceSetting) (*store.InstanceSetting, error) {
if err := upsertInstanceSetting(ctx, d.db, upsert); err != nil {
return nil, err
@@ -115,7 +149,16 @@ func (d *DB) ListInstanceSettings(ctx context.Context, find *store.FindInstanceS
}
func (d *DB) DeleteInstanceSetting(ctx context.Context, delete *store.DeleteInstanceSetting) error {
+ return deleteInstanceSetting(ctx, d.db, delete)
+}
+
+// DeleteInstanceSettingTx is DeleteInstanceSetting within tx.
+func (*DB) DeleteInstanceSettingTx(ctx context.Context, tx *sql.Tx, delete *store.DeleteInstanceSetting) error {
+ return deleteInstanceSetting(ctx, tx, delete)
+}
+
+func deleteInstanceSetting(ctx context.Context, q dbExecutor, delete *store.DeleteInstanceSetting) error {
stmt := `DELETE FROM system_setting WHERE name = $1`
- _, err := d.db.ExecContext(ctx, stmt, delete.Name)
+ _, err := q.ExecContext(ctx, stmt, delete.Name)
return err
}
diff --git a/store/db/postgres/user.go b/store/db/postgres/user.go
index 3cee31754..b3a977909 100644
--- a/store/db/postgres/user.go
+++ b/store/db/postgres/user.go
@@ -12,7 +12,16 @@ import (
)
func (d *DB) CreateUser(ctx context.Context, create *store.User) (*store.User, error) {
- if err := insertUser(ctx, d.db, create); err != nil {
+ return createUser(ctx, d.db, create)
+}
+
+// CreateUserTx is CreateUser within tx.
+func (*DB) CreateUserTx(ctx context.Context, tx *sql.Tx, create *store.User) (*store.User, error) {
+ return createUser(ctx, tx, create)
+}
+
+func createUser(ctx context.Context, q dbExecutor, create *store.User) (*store.User, error) {
+ if err := insertUser(ctx, q, create); err != nil {
return nil, err
}
return create, nil
@@ -24,6 +33,22 @@ func (d *DB) UpdateUser(ctx context.Context, update *store.UpdateUser) (*store.U
return nil, err
}
defer func() { _ = tx.Rollback() }()
+ user, err := updateUser(ctx, tx, update)
+ if err != nil {
+ return nil, err
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, err
+ }
+ return user, nil
+}
+
+// UpdateUserTx is UpdateUser within tx.
+func (*DB) UpdateUserTx(ctx context.Context, tx *sql.Tx, update *store.UpdateUser) (*store.User, error) {
+ return updateUser(ctx, tx, update)
+}
+
+func updateUser(ctx context.Context, tx *sql.Tx, update *store.UpdateUser) (*store.User, error) {
if update.RemovesInstanceAdmin() {
if err := ensureInstanceAdminRetained(ctx, tx, update.ID); err != nil {
return nil, err
@@ -88,9 +113,6 @@ func (d *DB) UpdateUser(ctx context.Context, update *store.UpdateUser) (*store.U
return nil, err
}
user.Email = email.String
- if err := tx.Commit(); err != nil {
- return nil, err
- }
return user, nil
}
@@ -162,6 +184,15 @@ func ensureInstanceAdminRetained(ctx context.Context, tx *sql.Tx, userID int32)
}
func (d *DB) ListUsers(ctx context.Context, find *store.FindUser) ([]*store.User, error) {
+ return listUsers(ctx, d.db, find)
+}
+
+// ListUsersTx is ListUsers within tx.
+func (*DB) ListUsersTx(ctx context.Context, tx *sql.Tx, find *store.FindUser) ([]*store.User, error) {
+ return listUsers(ctx, tx, find)
+}
+
+func listUsers(ctx context.Context, q dbExecutor, find *store.FindUser) ([]*store.User, error) {
where, args := []string{"1 = 1"}, []any{}
orderBy := []string{"created_ts DESC", "row_status DESC", "id DESC"}
@@ -237,7 +268,7 @@ func (d *DB) ListUsers(ctx context.Context, find *store.FindUser) ([]*store.User
query += fmt.Sprintf(" OFFSET %d", *v)
}
}
- rows, err := d.db.QueryContext(ctx, query, args...)
+ rows, err := q.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
diff --git a/store/db/sqlite/auth_config.go b/store/db/sqlite/auth_config.go
index 5a9cb0b71..6a237e8de 100644
--- a/store/db/sqlite/auth_config.go
+++ b/store/db/sqlite/auth_config.go
@@ -11,8 +11,8 @@ import (
"github.com/usememos/memos/store"
)
-// IsRetryableAuthenticationMutationError reports whether err is a transient SQLite locking failure.
-func (*DB) IsRetryableAuthenticationMutationError(err error) bool {
+// IsRetryableTransactionError reports whether err is a transient SQLite locking failure.
+func (*DB) IsRetryableTransactionError(err error) bool {
var sqliteErr *msqlite.Error
if !errors.As(err, &sqliteErr) {
return false
@@ -21,19 +21,11 @@ func (*DB) IsRetryableAuthenticationMutationError(err error) bool {
return code == sqlite3.SQLITE_BUSY || code == sqlite3.SQLITE_LOCKED
}
-// ApplyAuthenticationConfigMutation validates and applies an auth mutation in a serializable transaction.
-func (d *DB) ApplyAuthenticationConfigMutation(ctx context.Context, mutation *store.AuthenticationConfigMutation) error {
- tx, err := d.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
- if err != nil {
- return errors.Wrap(err, "failed to begin authentication configuration transaction")
- }
- defer func() {
- _ = tx.Rollback()
- }()
-
+// ApplyAuthenticationConfigMutationTx validates and applies an auth mutation within tx, a serializable transaction.
+func (*DB) ApplyAuthenticationConfigMutationTx(ctx context.Context, tx *sql.Tx, mutation *store.AuthenticationConfigMutation) error {
state := &store.AuthenticationConfigState{}
general := &store.InstanceSetting{}
- err = tx.QueryRowContext(ctx, `SELECT name, value, description FROM system_setting WHERE name = ?`, "GENERAL").Scan(
+ err := tx.QueryRowContext(ctx, `SELECT name, value, description FROM system_setting WHERE name = ?`, "GENERAL").Scan(
&general.Name, &general.Value, &general.Description,
)
if err == nil {
@@ -76,8 +68,5 @@ func (d *DB) ApplyAuthenticationConfigMutation(ctx context.Context, mutation *st
if err != nil {
return errors.Wrap(err, "failed to apply authentication configuration mutation")
}
- if err := tx.Commit(); err != nil {
- return errors.Wrap(err, "failed to commit authentication configuration transaction")
- }
return nil
}
diff --git a/store/db/sqlite/idp.go b/store/db/sqlite/idp.go
index 41c6b5d00..9e4bcd105 100644
--- a/store/db/sqlite/idp.go
+++ b/store/db/sqlite/idp.go
@@ -2,6 +2,7 @@ package sqlite
import (
"context"
+ "database/sql"
"fmt"
"strings"
@@ -10,12 +11,21 @@ import (
)
func (d *DB) CreateIdentityProvider(ctx context.Context, create *store.IdentityProvider) (*store.IdentityProvider, error) {
+ return createIdentityProvider(ctx, d.db, create)
+}
+
+// CreateIdentityProviderTx is CreateIdentityProvider within tx.
+func (*DB) CreateIdentityProviderTx(ctx context.Context, tx *sql.Tx, create *store.IdentityProvider) (*store.IdentityProvider, error) {
+ return createIdentityProvider(ctx, tx, create)
+}
+
+func createIdentityProvider(ctx context.Context, q dbExecutor, create *store.IdentityProvider) (*store.IdentityProvider, error) {
placeholders := []string{"?", "?", "?", "?", "?"}
fields := []string{"`uid`", "`name`", "`type`", "`identifier_filter`", "`config`"}
args := []any{create.UID, create.Name, create.Type.String(), create.IdentifierFilter, create.Config}
stmt := "INSERT INTO `idp` (" + strings.Join(fields, ", ") + ") VALUES (" + strings.Join(placeholders, ", ") + ") RETURNING `id`"
- if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(&create.ID); err != nil {
+ if err := q.QueryRowContext(ctx, stmt, args...).Scan(&create.ID); err != nil {
return nil, err
}
@@ -24,6 +34,15 @@ func (d *DB) CreateIdentityProvider(ctx context.Context, create *store.IdentityP
}
func (d *DB) ListIdentityProviders(ctx context.Context, find *store.FindIdentityProvider) ([]*store.IdentityProvider, error) {
+ return listIdentityProviders(ctx, d.db, find)
+}
+
+// ListIdentityProvidersTx is ListIdentityProviders within tx.
+func (*DB) ListIdentityProvidersTx(ctx context.Context, tx *sql.Tx, find *store.FindIdentityProvider) ([]*store.IdentityProvider, error) {
+ return listIdentityProviders(ctx, tx, find)
+}
+
+func listIdentityProviders(ctx context.Context, q dbExecutor, find *store.FindIdentityProvider) ([]*store.IdentityProvider, error) {
where, args := []string{"1 = 1"}, []any{}
if v := find.ID; v != nil {
where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)
@@ -32,7 +51,7 @@ func (d *DB) ListIdentityProviders(ctx context.Context, find *store.FindIdentity
where, args = append(where, fmt.Sprintf("uid = $%d", len(args)+1)), append(args, *v)
}
- rows, err := d.db.QueryContext(ctx, `
+ rows, err := q.QueryContext(ctx, `
SELECT
id,
uid,
@@ -75,6 +94,15 @@ func (d *DB) ListIdentityProviders(ctx context.Context, find *store.FindIdentity
}
func (d *DB) UpdateIdentityProvider(ctx context.Context, update *store.UpdateIdentityProvider) (*store.IdentityProvider, error) {
+ return updateIdentityProvider(ctx, d.db, update)
+}
+
+// UpdateIdentityProviderTx is UpdateIdentityProvider within tx.
+func (*DB) UpdateIdentityProviderTx(ctx context.Context, tx *sql.Tx, update *store.UpdateIdentityProvider) (*store.IdentityProvider, error) {
+ return updateIdentityProvider(ctx, tx, update)
+}
+
+func updateIdentityProvider(ctx context.Context, q dbExecutor, update *store.UpdateIdentityProvider) (*store.IdentityProvider, error) {
set, args := []string{}, []any{}
if v := update.Name; v != nil {
set, args = append(set, "name = ?"), append(args, *v)
@@ -95,7 +123,7 @@ func (d *DB) UpdateIdentityProvider(ctx context.Context, update *store.UpdateIde
`
var identityProvider store.IdentityProvider
var typeString string
- if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(
+ if err := q.QueryRowContext(ctx, stmt, args...).Scan(
&identityProvider.ID,
&identityProvider.UID,
&identityProvider.Name,
@@ -110,9 +138,18 @@ func (d *DB) UpdateIdentityProvider(ctx context.Context, update *store.UpdateIde
}
func (d *DB) DeleteIdentityProvider(ctx context.Context, delete *store.DeleteIdentityProvider) error {
+ return deleteIdentityProvider(ctx, d.db, delete)
+}
+
+// DeleteIdentityProviderTx is DeleteIdentityProvider within tx.
+func (*DB) DeleteIdentityProviderTx(ctx context.Context, tx *sql.Tx, delete *store.DeleteIdentityProvider) error {
+ return deleteIdentityProvider(ctx, tx, delete)
+}
+
+func deleteIdentityProvider(ctx context.Context, q dbExecutor, delete *store.DeleteIdentityProvider) error {
where, args := []string{"id = ?"}, []any{delete.ID}
stmt := `DELETE FROM idp WHERE ` + strings.Join(where, " AND ")
- result, err := d.db.ExecContext(ctx, stmt, args...)
+ result, err := q.ExecContext(ctx, stmt, args...)
if err != nil {
return err
}
diff --git a/store/db/sqlite/instance_setting.go b/store/db/sqlite/instance_setting.go
index b76c07d44..0919751ad 100644
--- a/store/db/sqlite/instance_setting.go
+++ b/store/db/sqlite/instance_setting.go
@@ -12,6 +12,15 @@ import (
// CreateInstanceSettingIfNotExists atomically creates the setting when its name is absent and reports whether it inserted the row.
func (d *DB) CreateInstanceSettingIfNotExists(ctx context.Context, create *store.InstanceSetting) (bool, error) {
+ return createInstanceSettingIfNotExists(ctx, d.db, create)
+}
+
+// CreateInstanceSettingIfNotExistsTx is CreateInstanceSettingIfNotExists within tx.
+func (*DB) CreateInstanceSettingIfNotExistsTx(ctx context.Context, tx *sql.Tx, create *store.InstanceSetting) (bool, error) {
+ return createInstanceSettingIfNotExists(ctx, tx, create)
+}
+
+func createInstanceSettingIfNotExists(ctx context.Context, executor dbExecutor, create *store.InstanceSetting) (bool, error) {
stmt := `
INSERT INTO system_setting (
name, value, description
@@ -19,7 +28,7 @@ func (d *DB) CreateInstanceSettingIfNotExists(ctx context.Context, create *store
VALUES (?, ?, ?)
ON CONFLICT(name) DO NOTHING
`
- result, err := d.db.ExecContext(ctx, stmt, create.Name, create.Value, create.Description)
+ result, err := executor.ExecContext(ctx, stmt, create.Name, create.Value, create.Description)
if err != nil {
return false, errors.Wrap(err, "failed to conditionally create instance setting")
}
@@ -33,7 +42,16 @@ func (d *DB) CreateInstanceSettingIfNotExists(ctx context.Context, create *store
// UpdateInstanceSettingIfUnchanged replaces the setting value only when the
// stored value still equals oldValue, and reports whether it did.
func (d *DB) UpdateInstanceSettingIfUnchanged(ctx context.Context, name, oldValue, newValue string) (bool, error) {
- result, err := d.db.ExecContext(ctx, "UPDATE system_setting SET value = ? WHERE name = ? AND value = ?", newValue, name, oldValue)
+ return updateInstanceSettingIfUnchanged(ctx, d.db, name, oldValue, newValue)
+}
+
+// UpdateInstanceSettingIfUnchangedTx is UpdateInstanceSettingIfUnchanged within tx.
+func (*DB) UpdateInstanceSettingIfUnchangedTx(ctx context.Context, tx *sql.Tx, name, oldValue, newValue string) (bool, error) {
+ return updateInstanceSettingIfUnchanged(ctx, tx, name, oldValue, newValue)
+}
+
+func updateInstanceSettingIfUnchanged(ctx context.Context, executor dbExecutor, name, oldValue, newValue string) (bool, error) {
+ result, err := executor.ExecContext(ctx, "UPDATE system_setting SET value = ? WHERE name = ? AND value = ?", newValue, name, oldValue)
if err != nil {
return false, errors.Wrap(err, "failed to conditionally update instance setting")
}
@@ -44,6 +62,22 @@ func (d *DB) UpdateInstanceSettingIfUnchanged(ctx context.Context, name, oldValu
return rowsAffected == 1, nil
}
+// GetInstanceSettingTx reads one setting within tx, or returns nil when it is
+// absent. The immediate transaction already holds the database write lock.
+func (*DB) GetInstanceSettingTx(ctx context.Context, tx *sql.Tx, name string) (*store.InstanceSetting, error) {
+ setting := &store.InstanceSetting{}
+ err := tx.QueryRowContext(ctx, "SELECT name, value, description FROM system_setting WHERE name = ?", name).Scan(
+ &setting.Name, &setting.Value, &setting.Description,
+ )
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to read instance setting")
+ }
+ return setting, nil
+}
+
func (d *DB) UpsertInstanceSetting(ctx context.Context, upsert *store.InstanceSetting) (*store.InstanceSetting, error) {
if err := upsertInstanceSetting(ctx, d.db, upsert); err != nil {
return nil, err
@@ -111,7 +145,16 @@ func (d *DB) ListInstanceSettings(ctx context.Context, find *store.FindInstanceS
}
func (d *DB) DeleteInstanceSetting(ctx context.Context, delete *store.DeleteInstanceSetting) error {
+ return deleteInstanceSetting(ctx, d.db, delete)
+}
+
+// DeleteInstanceSettingTx is DeleteInstanceSetting within tx.
+func (*DB) DeleteInstanceSettingTx(ctx context.Context, tx *sql.Tx, delete *store.DeleteInstanceSetting) error {
+ return deleteInstanceSetting(ctx, tx, delete)
+}
+
+func deleteInstanceSetting(ctx context.Context, q dbExecutor, delete *store.DeleteInstanceSetting) error {
stmt := "DELETE FROM system_setting WHERE name = ?"
- _, err := d.db.ExecContext(ctx, stmt, delete.Name)
+ _, err := q.ExecContext(ctx, stmt, delete.Name)
return err
}
diff --git a/store/db/sqlite/user.go b/store/db/sqlite/user.go
index fe7b06428..399735af9 100644
--- a/store/db/sqlite/user.go
+++ b/store/db/sqlite/user.go
@@ -12,7 +12,16 @@ import (
)
func (d *DB) CreateUser(ctx context.Context, create *store.User) (*store.User, error) {
- if err := insertUser(ctx, d.db, create); err != nil {
+ return createUser(ctx, d.db, create)
+}
+
+// CreateUserTx is CreateUser within tx.
+func (*DB) CreateUserTx(ctx context.Context, tx *sql.Tx, create *store.User) (*store.User, error) {
+ return createUser(ctx, tx, create)
+}
+
+func createUser(ctx context.Context, q dbExecutor, create *store.User) (*store.User, error) {
+ if err := insertUser(ctx, q, create); err != nil {
return nil, err
}
return create, nil
@@ -24,6 +33,22 @@ func (d *DB) UpdateUser(ctx context.Context, update *store.UpdateUser) (*store.U
return nil, err
}
defer func() { _ = tx.Rollback() }()
+ user, err := updateUser(ctx, tx, update)
+ if err != nil {
+ return nil, err
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, err
+ }
+ return user, nil
+}
+
+// UpdateUserTx is UpdateUser within tx.
+func (*DB) UpdateUserTx(ctx context.Context, tx *sql.Tx, update *store.UpdateUser) (*store.User, error) {
+ return updateUser(ctx, tx, update)
+}
+
+func updateUser(ctx context.Context, tx *sql.Tx, update *store.UpdateUser) (*store.User, error) {
if update.RemovesInstanceAdmin() {
if err := ensureInstanceAdminRetained(ctx, tx, update.ID); err != nil {
return nil, err
@@ -88,9 +113,6 @@ func (d *DB) UpdateUser(ctx context.Context, update *store.UpdateUser) (*store.U
return nil, err
}
user.Email = email.String
- if err := tx.Commit(); err != nil {
- return nil, err
- }
return user, nil
}
@@ -145,6 +167,15 @@ func ensureInstanceAdminRetained(ctx context.Context, tx dbExecutor, userID int3
}
func (d *DB) ListUsers(ctx context.Context, find *store.FindUser) ([]*store.User, error) {
+ return listUsers(ctx, d.db, find)
+}
+
+// ListUsersTx is ListUsers within tx.
+func (*DB) ListUsersTx(ctx context.Context, tx *sql.Tx, find *store.FindUser) ([]*store.User, error) {
+ return listUsers(ctx, tx, find)
+}
+
+func listUsers(ctx context.Context, q dbExecutor, find *store.FindUser) ([]*store.User, error) {
where, args := []string{"1 = 1"}, []any{}
orderBy := []string{"created_ts DESC", "row_status DESC", "id DESC"}
@@ -229,7 +260,7 @@ func (d *DB) ListUsers(ctx context.Context, find *store.FindUser) ([]*store.User
}
}
- rows, err := d.db.QueryContext(ctx, query, args...)
+ rows, err := q.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
diff --git a/store/demo_seed_test.go b/store/demo_seed_test.go
index 6fe45ba6e..ee74fc91b 100644
--- a/store/demo_seed_test.go
+++ b/store/demo_seed_test.go
@@ -14,7 +14,7 @@ import (
"github.com/usememos/memos/store/db/sqlite"
)
-func TestDemoSeedUsesDeploymentAuthenticationPolicy(t *testing.T) {
+func TestDemoSeed(t *testing.T) {
ctx := context.Background()
p := &profile.Profile{
Demo: true,
@@ -32,21 +32,9 @@ func TestDemoSeedUsesDeploymentAuthenticationPolicy(t *testing.T) {
require.NoError(t, stores.Migrate(ctx))
generalSetting, err := stores.GetInstanceGeneralSetting(ctx)
require.NoError(t, err)
- require.False(t, generalSetting.DisallowPasswordAuth, "authentication policy must come from deployment configuration")
+ require.False(t, generalSetting.DisallowPasswordAuth, "the demo seed does not set an authentication policy")
require.False(t, generalSetting.DisallowUserRegistration, "SSO first-login provisioning must remain enabled")
- secretDir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(secretDir, "memos-idp-primary-sso.json"), "primary-sso", "Primary SSO", "secret")
- writeDeploymentGeneralSetting(t, filepath.Join(secretDir, "memos-instance-setting-general.json"), 0, true)
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, secretDir))
- generalSetting, err = stores.GetInstanceGeneralSetting(ctx)
- require.NoError(t, err)
- require.True(t, generalSetting.DisallowPasswordAuth)
- require.False(t, generalSetting.DisallowUserRegistration, "SSO first-login provisioning must remain enabled")
- provider, err := stores.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("primary-sso")})
- require.NoError(t, err)
- require.NotNil(t, provider)
-
adminUsername := "steven"
adminUser, err := stores.GetUser(ctx, &store.FindUser{Username: &adminUsername})
require.NoError(t, err)
diff --git a/store/deployment_config.go b/store/deployment_config.go
deleted file mode 100644
index 46a7a3b30..000000000
--- a/store/deployment_config.go
+++ /dev/null
@@ -1,486 +0,0 @@
-package store
-
-import (
- "context"
- "io"
- "log/slog"
- "net/url"
- "os"
- "path/filepath"
- "regexp"
- "slices"
- "strings"
-
- "github.com/pkg/errors"
- "google.golang.org/protobuf/encoding/protojson"
- "google.golang.org/protobuf/proto"
-
- "github.com/usememos/memos/internal/identifier"
- storepb "github.com/usememos/memos/proto/gen/store"
-)
-
-const (
- // DefaultDeploymentConfigurationDir is the directory scanned for runtime configuration files.
- DefaultDeploymentConfigurationDir = "/etc/secrets"
- maxDeploymentConfigurationSize = 1 << 20
- maxTranscriptionModelLength = 256
- maxTranscriptionLanguageLength = 32
- maxTranscriptionPromptLength = 4096
-)
-
-var (
- idpDeploymentFilenameMatcher = regexp.MustCompile(`^memos-idp-[a-z0-9]+(?:-[a-z0-9]+)*\.json$`)
- instanceSettingDeploymentFilenameMatcher = regexp.MustCompile(`^memos-instance-setting-[a-z0-9]+(?:-[a-z0-9]+)*\.json$`)
- protoJSONUnknownFieldMatcher = regexp.MustCompile(`unknown field "([^"]+)"`)
-)
-
-// LoadDeploymentConfiguration loads the default runtime deployment configuration.
-func (s *Store) LoadDeploymentConfiguration(ctx context.Context) error {
- return s.LoadDeploymentConfigurationDir(ctx, DefaultDeploymentConfigurationDir)
-}
-
-// LoadDeploymentConfigurationDir loads and atomically publishes runtime configuration from dir.
-func (s *Store) LoadDeploymentConfigurationDir(ctx context.Context, dir string) error {
- entries, err := os.ReadDir(dir)
- if err != nil {
- if os.IsNotExist(err) {
- s.setDeploymentConfiguration(newDeploymentConfiguration())
- return nil
- }
- return errors.Wrap(err, "failed to read deployment configuration directory")
- }
-
- config := newDeploymentConfiguration()
- idpFiles := map[string]string{}
- settingFiles := map[storepb.InstanceSettingKey]string{}
- for _, entry := range entries {
- name := entry.Name()
- path := filepath.Join(dir, name)
- switch {
- case isIdentityProviderDeploymentFilename(name):
- if !idpDeploymentFilenameMatcher.MatchString(name) {
- slog.Warn("loading identity provider deployment file with a legacy filename; rename it to lowercase kebab case", "filename", name)
- }
- provider := &storepb.IdentityProvider{}
- if err := readDeploymentProtoJSON(path, provider); err != nil {
- return errors.Wrapf(err, "invalid identity provider deployment file %q", name)
- }
- if err := validateDeploymentIdentityProvider(provider); err != nil {
- return errors.Wrapf(err, "invalid identity provider deployment file %q", name)
- }
- if previous, ok := idpFiles[provider.Uid]; ok {
- return errors.Errorf("identity provider UID %q is declared by both %q and %q", provider.Uid, previous, name)
- }
- idpFiles[provider.Uid] = name
- config.identityProviders[provider.Uid] = cloneIdentityProvider(provider)
- case instanceSettingDeploymentFilenameMatcher.MatchString(name):
- setting := &storepb.InstanceSetting{}
- if err := readDeploymentProtoJSON(path, setting); err != nil {
- return errors.Wrapf(err, "invalid instance setting deployment file %q", name)
- }
- if err := validateAndNormalizeDeploymentInstanceSetting(setting); err != nil {
- return errors.Wrapf(err, "invalid instance setting deployment file %q", name)
- }
- if previous, ok := settingFiles[setting.Key]; ok {
- return errors.Errorf("instance setting key %q is declared by both %q and %q", setting.Key, previous, name)
- }
- settingFiles[setting.Key] = name
- config.instanceSettings[setting.Key] = cloneInstanceSetting(setting)
- case strings.HasPrefix(name, "memos-"):
- slog.Warn("ignoring unrecognized Memos deployment configuration filename", "filename", name)
- default:
- // The directory may contain unrelated platform secret files.
- }
- }
-
- if err := s.validateDeploymentAuthenticationState(ctx, config); err != nil {
- return err
- }
- if err := s.warnShadowedStoredIdentityProviders(ctx, config); err != nil {
- return err
- }
-
- s.setDeploymentConfiguration(config)
- slog.Info("loaded deployment configuration", "identityProviders", len(config.identityProviders), "instanceSettings", len(config.instanceSettings))
- return nil
-}
-
-func newDeploymentConfiguration() *deploymentConfiguration {
- return &deploymentConfiguration{
- identityProviders: map[string]*storepb.IdentityProvider{},
- instanceSettings: map[storepb.InstanceSettingKey]*storepb.InstanceSetting{},
- }
-}
-
-func isIdentityProviderDeploymentFilename(name string) bool {
- // The original database-writing bootstrap accepted every filename with this
- // prefix and suffix. Continue loading those names so an upgrade cannot
- // silently fall back to stale credentials stored in the database.
- return strings.HasPrefix(name, "memos-idp-") && strings.HasSuffix(name, ".json")
-}
-
-func readDeploymentProtoJSON(path string, message proto.Message) error {
- info, err := os.Stat(path)
- if err != nil {
- return errors.Wrap(err, "failed to inspect file")
- }
- if !info.Mode().IsRegular() {
- return errors.New("file must resolve to a regular file")
- }
- file, err := os.Open(path)
- if err != nil {
- return errors.Wrap(err, "failed to open file")
- }
- defer file.Close()
- info, err = file.Stat()
- if err != nil {
- return errors.Wrap(err, "failed to inspect file")
- }
- if !info.Mode().IsRegular() {
- return errors.New("file must resolve to a regular file")
- }
- content, err := io.ReadAll(io.LimitReader(file, maxDeploymentConfigurationSize+1))
- if err != nil {
- return errors.Wrap(err, "failed to read file")
- }
- if len(content) > maxDeploymentConfigurationSize {
- return errors.Errorf("file exceeds %d bytes", maxDeploymentConfigurationSize)
- }
- if err := (protojson.UnmarshalOptions{DiscardUnknown: false}).Unmarshal(content, message); err != nil {
- if matches := protoJSONUnknownFieldMatcher.FindStringSubmatch(err.Error()); len(matches) == 2 {
- return errors.Errorf("failed to decode protobuf JSON: unknown field %q", matches[1])
- }
- return errors.New("failed to decode protobuf JSON; verify field names, value types, and JSON syntax")
- }
- return nil
-}
-
-func validateDeploymentIdentityProvider(provider *storepb.IdentityProvider) error {
- if provider.Id != 0 {
- return errors.New("id must be omitted")
- }
- if !identifier.UIDMatcher.MatchString(provider.Uid) {
- return errors.New("uid is invalid")
- }
- if strings.TrimSpace(provider.Name) == "" {
- return errors.New("name is required")
- }
- if provider.Type != storepb.IdentityProvider_OAUTH2 {
- return errors.New("type must be OAUTH2")
- }
- if provider.IdentifierFilter != "" {
- if _, err := regexp.Compile(provider.IdentifierFilter); err != nil {
- return errors.Wrap(err, "identifierFilter must be a valid regular expression")
- }
- }
- config := provider.Config.GetOauth2Config()
- if config == nil {
- return errors.New("config.oauth2Config is required")
- }
- required := []struct {
- name string
- value string
- }{
- {name: "clientId", value: config.ClientId},
- {name: "clientSecret", value: config.ClientSecret},
- {name: "authUrl", value: config.AuthUrl},
- {name: "tokenUrl", value: config.TokenUrl},
- {name: "userInfoUrl", value: config.UserInfoUrl},
- }
- for _, field := range required {
- if strings.TrimSpace(field.value) == "" {
- return errors.Errorf("config.oauth2Config.%s is required", field.name)
- }
- }
- for _, field := range []struct {
- name string
- value string
- }{
- {name: "authUrl", value: config.AuthUrl},
- {name: "tokenUrl", value: config.TokenUrl},
- {name: "userInfoUrl", value: config.UserInfoUrl},
- } {
- parsed, err := url.ParseRequestURI(field.value)
- if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
- return errors.Errorf("config.oauth2Config.%s must be an absolute HTTP(S) URL", field.name)
- }
- }
- if len(config.Scopes) == 0 {
- return errors.New("config.oauth2Config.scopes is required")
- }
- for i, scope := range config.Scopes {
- if strings.TrimSpace(scope) == "" {
- return errors.Errorf("config.oauth2Config.scopes[%d] must not be empty", i)
- }
- }
- if config.FieldMapping == nil || strings.TrimSpace(config.FieldMapping.Identifier) == "" {
- return errors.New("config.oauth2Config.fieldMapping.identifier is required")
- }
- return nil
-}
-
-func validateAndNormalizeDeploymentInstanceSetting(setting *storepb.InstanceSetting) error {
- switch setting.Key {
- case storepb.InstanceSettingKey_GENERAL:
- if setting.GetGeneralSetting() == nil {
- return errors.New("generalSetting must be populated for key GENERAL")
- }
- if offset := setting.GetGeneralSetting().WeekStartDayOffset; offset < -1 || offset > 6 {
- return errors.New("generalSetting.weekStartDayOffset must be between -1 and 6")
- }
- case storepb.InstanceSettingKey_STORAGE:
- storage := setting.GetStorageSetting()
- if storage == nil {
- return errors.New("storageSetting must be populated for key STORAGE")
- }
- // Normalization would silently self-heal this misconfiguration to LOCAL;
- // a deployment file declaring S3 without a config should fail loudly.
- if storage.StorageType == storepb.InstanceStorageSetting_S3 && storage.S3Config == nil && len(storage.Storages) == 0 {
- return errors.New("storageSetting.s3Config is required for S3")
- }
- NormalizeInstanceStorageSetting(storage)
- defaultStorage := GetDefaultStorage(storage)
- if defaultStorage != nil && defaultStorage.Type == storepb.StorageType_STORAGE_TYPE_S3 {
- s3Config := defaultStorage.GetS3Config()
- if s3Config == nil {
- return errors.New("storageSetting default storage S3 config is required")
- }
- for _, field := range []struct {
- name string
- value string
- }{
- {name: "accessKeyId", value: s3Config.AccessKeyId},
- {name: "accessKeySecret", value: s3Config.AccessKeySecret},
- {name: "endpoint", value: s3Config.Endpoint},
- {name: "region", value: s3Config.Region},
- {name: "bucket", value: s3Config.Bucket},
- } {
- if strings.TrimSpace(field.value) == "" {
- return errors.Errorf("storageSetting default S3 config.%s is required", field.name)
- }
- }
- }
- case storepb.InstanceSettingKey_MEMO_RELATED:
- if setting.GetMemoRelatedSetting() == nil {
- return errors.New("memoRelatedSetting must be populated for key MEMO_RELATED")
- }
- case storepb.InstanceSettingKey_NOTIFICATION:
- notification := setting.GetNotificationSetting()
- if notification == nil {
- return errors.New("notificationSetting must be populated for key NOTIFICATION")
- }
- if err := ValidateInstanceNotificationSetting(notification); err != nil {
- return err
- }
- case storepb.InstanceSettingKey_AI:
- if setting.GetAiSetting() == nil {
- return errors.New("aiSetting must be populated for key AI")
- }
- if err := normalizeDeploymentAISetting(setting.GetAiSetting()); err != nil {
- return err
- }
- case storepb.InstanceSettingKey_ACCESS:
- access := setting.GetAccessSetting()
- if access == nil {
- return errors.New("accessSetting must be populated for key ACCESS")
- }
- switch access.AccessMode {
- case storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC:
- default:
- return errors.New("accessSetting.accessMode must be PRIVATE or PUBLIC")
- }
- case storepb.InstanceSettingKey_USAGE_LIMITS:
- usageLimits := setting.GetUsageLimitsSetting()
- if usageLimits == nil {
- return errors.New("usageLimitsSetting must be populated for key USAGE_LIMITS")
- }
- if err := ValidateInstanceUsageLimitsSetting(usageLimits); err != nil {
- return errors.Wrap(err, "usageLimitsSetting")
- }
- case storepb.InstanceSettingKey_BASIC, storepb.InstanceSettingKey_TAGS:
- return errors.Errorf("key %s cannot be deployment configured", setting.Key)
- default:
- return errors.Errorf("unsupported instance setting key %s", setting.Key)
- }
- return nil
-}
-
-func normalizeDeploymentAISetting(setting *storepb.InstanceAISetting) error {
- providers := map[string]struct{}{}
- for i, provider := range setting.Providers {
- if provider == nil {
- return errors.Errorf("aiSetting.providers[%d] must not be null", i)
- }
- provider.Id = strings.TrimSpace(provider.Id)
- provider.Title = strings.TrimSpace(provider.Title)
- provider.Endpoint = strings.TrimSpace(provider.Endpoint)
- if provider.Id == "" || provider.Title == "" || provider.ApiKey == "" {
- return errors.Errorf("aiSetting.providers[%d] requires id, title, and apiKey", i)
- }
- if _, ok := providers[provider.Id]; ok {
- return errors.Errorf("aiSetting provider ID %q is duplicated", provider.Id)
- }
- providers[provider.Id] = struct{}{}
- switch provider.Type {
- case storepb.AIProviderType_OPENAI:
- if provider.Endpoint == "" {
- provider.Endpoint = "https://api.openai.com/v1"
- }
- case storepb.AIProviderType_GEMINI:
- if provider.Endpoint == "" {
- provider.Endpoint = "https://generativelanguage.googleapis.com/v1beta"
- }
- default:
- return errors.Errorf("aiSetting provider %q has unsupported type", provider.Id)
- }
- }
- if transcription := setting.Transcription; transcription != nil {
- transcription.ProviderId = strings.TrimSpace(transcription.ProviderId)
- transcription.Model = strings.TrimSpace(transcription.Model)
- transcription.Language = strings.TrimSpace(transcription.Language)
- transcription.Prompt = strings.TrimSpace(transcription.Prompt)
- if transcription.ProviderId != "" {
- if _, ok := providers[transcription.ProviderId]; !ok {
- return errors.Errorf("aiSetting transcription providerId %q does not reference a provider", transcription.ProviderId)
- }
- }
- if len(transcription.Model) > maxTranscriptionModelLength || len(transcription.Language) > maxTranscriptionLanguageLength || len(transcription.Prompt) > maxTranscriptionPromptLength {
- return errors.New("aiSetting transcription configuration exceeds a supported length limit")
- }
- }
- return nil
-}
-
-func (s *Store) validateDeploymentAuthenticationState(ctx context.Context, config *deploymentConfiguration) error {
- _, generalConfigured := config.instanceSettings[storepb.InstanceSettingKey_GENERAL]
- if !generalConfigured && len(config.identityProviders) == 0 {
- general, err := s.getRawInstanceSetting(ctx, storepb.InstanceSettingKey_GENERAL.String())
- if err != nil {
- return errors.Wrap(err, "failed to inspect stored GENERAL setting")
- }
- if general == nil || !general.GetGeneralSetting().DisallowPasswordAuth {
- return nil
- }
- providers, err := s.listStoredIdentityProviders(ctx, &FindIdentityProvider{})
- if err != nil {
- return errors.Wrap(err, "failed to inspect stored identity providers")
- }
- if len(providers) == 0 {
- slog.Warn("stored configuration disables password authentication for regular users but has no identity provider; unrelated deployment files remain loadable because administrator password sign-in is available")
- }
- return nil
- }
- general, err := s.getRawInstanceSetting(ctx, storepb.InstanceSettingKey_GENERAL.String())
- if err != nil {
- return errors.Wrap(err, "failed to read stored GENERAL setting")
- }
- if configured := config.instanceSettings[storepb.InstanceSettingKey_GENERAL]; configured != nil {
- general = cloneInstanceSetting(configured)
- }
- if general == nil || !general.GetGeneralSetting().DisallowPasswordAuth {
- return nil
- }
- providers, err := s.listStoredIdentityProviders(ctx, &FindIdentityProvider{})
- if err != nil {
- return errors.Wrap(err, "failed to read stored identity providers")
- }
- effectiveUIDs := map[string]struct{}{}
- for _, provider := range providers {
- effectiveUIDs[provider.Uid] = struct{}{}
- }
- for uid := range config.identityProviders {
- effectiveUIDs[uid] = struct{}{}
- }
- if len(effectiveUIDs) == 0 {
- return errors.New("deployment configuration disables password authentication for regular users but has no effective identity provider")
- }
- return nil
-}
-
-func (s *Store) warnShadowedStoredIdentityProviders(ctx context.Context, config *deploymentConfiguration) error {
- if len(config.identityProviders) == 0 {
- return nil
- }
- providers, err := s.listStoredIdentityProviders(ctx, &FindIdentityProvider{})
- if err != nil {
- return errors.Wrap(err, "failed to inspect stored identity providers")
- }
- for _, provider := range providers {
- if _, ok := config.identityProviders[provider.Uid]; ok {
- slog.Warn("deployment identity provider shadows a stored provider; the stored configuration remains in the database", "uid", provider.Uid)
- }
- }
- return nil
-}
-
-func (s *Store) setDeploymentConfiguration(config *deploymentConfiguration) {
- copy := newDeploymentConfiguration()
- for uid, provider := range config.identityProviders {
- copy.identityProviders[uid] = cloneIdentityProvider(provider)
- }
- for key, setting := range config.instanceSettings {
- copy.instanceSettings[key] = cloneInstanceSetting(setting)
- }
- s.deploymentConfigMu.Lock()
- s.deploymentConfig = copy
- s.deploymentConfigMu.Unlock()
- // A deployment configuration can supply the STORAGE setting.
- s.resetStorageDriverCache()
-}
-
-// IsIdentityProviderDeploymentConfigured reports whether uid is file-backed.
-func (s *Store) IsIdentityProviderDeploymentConfigured(uid string) bool {
- s.deploymentConfigMu.RLock()
- defer s.deploymentConfigMu.RUnlock()
- _, ok := s.deploymentConfig.identityProviders[uid]
- return ok
-}
-
-// IsInstanceSettingDeploymentConfigured reports whether key is file-backed.
-func (s *Store) IsInstanceSettingDeploymentConfigured(key storepb.InstanceSettingKey) bool {
- s.deploymentConfigMu.RLock()
- defer s.deploymentConfigMu.RUnlock()
- _, ok := s.deploymentConfig.instanceSettings[key]
- return ok
-}
-
-func (s *Store) getDeploymentIdentityProvider(uid string) *storepb.IdentityProvider {
- s.deploymentConfigMu.RLock()
- defer s.deploymentConfigMu.RUnlock()
- return cloneIdentityProvider(s.deploymentConfig.identityProviders[uid])
-}
-
-func (s *Store) listDeploymentIdentityProviders() []*storepb.IdentityProvider {
- s.deploymentConfigMu.RLock()
- defer s.deploymentConfigMu.RUnlock()
- providers := make([]*storepb.IdentityProvider, 0, len(s.deploymentConfig.identityProviders))
- for _, provider := range s.deploymentConfig.identityProviders {
- providers = append(providers, cloneIdentityProvider(provider))
- }
- slices.SortFunc(providers, func(a, b *storepb.IdentityProvider) int { return strings.Compare(a.Uid, b.Uid) })
- return providers
-}
-
-func (s *Store) getDeploymentInstanceSetting(key storepb.InstanceSettingKey) *storepb.InstanceSetting {
- s.deploymentConfigMu.RLock()
- defer s.deploymentConfigMu.RUnlock()
- return cloneInstanceSetting(s.deploymentConfig.instanceSettings[key])
-}
-
-func cloneIdentityProvider(provider *storepb.IdentityProvider) *storepb.IdentityProvider {
- if provider == nil {
- return nil
- }
- cloned := &storepb.IdentityProvider{}
- proto.Merge(cloned, provider)
- return cloned
-}
-
-func cloneInstanceSetting(setting *storepb.InstanceSetting) *storepb.InstanceSetting {
- if setting == nil {
- return nil
- }
- cloned := &storepb.InstanceSetting{}
- proto.Merge(cloned, setting)
- return cloned
-}
diff --git a/store/deployment_config_test.go b/store/deployment_config_test.go
deleted file mode 100644
index 91362d202..000000000
--- a/store/deployment_config_test.go
+++ /dev/null
@@ -1,570 +0,0 @@
-package store_test
-
-import (
- "context"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "testing"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
- "google.golang.org/protobuf/encoding/protojson"
- "google.golang.org/protobuf/proto"
-
- "github.com/usememos/memos/internal/profile"
- storepb "github.com/usememos/memos/proto/gen/store"
- "github.com/usememos/memos/store"
- "github.com/usememos/memos/store/db/sqlite"
-)
-
-func TestLoadDeploymentConfigurationPublishesRuntimeOnlyIdentityProvider(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(dir, "memos-idp-primary.json"), "primary-sso", "File SSO", "file-secret")
-
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
-
- effective, err := stores.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("primary-sso")})
- require.NoError(t, err)
- require.NotNil(t, effective)
- assert.Zero(t, effective.Id)
- assert.Equal(t, "File SSO", effective.Name)
- assert.Equal(t, "file-secret", effective.Config.GetOauth2Config().ClientSecret)
- assert.True(t, stores.IsIdentityProviderDeploymentConfigured("primary-sso"))
-
- stored, err := stores.GetStoredIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("primary-sso")})
- require.NoError(t, err)
- assert.Nil(t, stored)
-}
-
-func TestLoadDeploymentConfigurationShadowsWithoutChangingStoredResources(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- stored, err := stores.CreateIdentityProvider(ctx, deploymentIdentityProvider("primary-sso", "Stored SSO", "stored-secret"))
- require.NoError(t, err)
- storedID := stored.Id
- _, err = stores.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{
- WeekStartDayOffset: 1,
- }},
- })
- require.NoError(t, err)
-
- dir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(dir, "memos-idp-primary.json"), "primary-sso", "File SSO", "file-secret")
- writeDeploymentGeneralSetting(t, filepath.Join(dir, "memos-instance-setting-general.json"), 4, true)
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
-
- effectiveProvider, err := stores.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("primary-sso")})
- require.NoError(t, err)
- assert.Equal(t, "File SSO", effectiveProvider.Name)
- storedProvider, err := stores.GetStoredIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("primary-sso")})
- require.NoError(t, err)
- assert.Equal(t, storedID, storedProvider.Id)
- assert.Equal(t, "Stored SSO", storedProvider.Name)
-
- effectiveGeneral, err := stores.GetInstanceGeneralSetting(ctx)
- require.NoError(t, err)
- assert.Equal(t, int32(4), effectiveGeneral.WeekStartDayOffset)
- assert.True(t, effectiveGeneral.DisallowPasswordAuth)
- rawGeneral, err := stores.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_GENERAL.String()})
- require.NoError(t, err)
- require.NotNil(t, rawGeneral)
- assert.Equal(t, int32(1), rawGeneral.GetGeneralSetting().WeekStartDayOffset)
-}
-
-func TestLoadDeploymentConfigurationReturnsDefensiveClones(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(dir, "memos-idp-primary.json"), "primary-sso", "File SSO", "file-secret")
- writeDeploymentGeneralSetting(t, filepath.Join(dir, "memos-instance-setting-general.json"), 2, false)
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
-
- provider, err := stores.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("primary-sso")})
- require.NoError(t, err)
- provider.Name = "Mutated"
- provider.Config.GetOauth2Config().ClientSecret = "mutated-secret"
- providerAgain, err := stores.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("primary-sso")})
- require.NoError(t, err)
- assert.Equal(t, "File SSO", providerAgain.Name)
- assert.Equal(t, "file-secret", providerAgain.Config.GetOauth2Config().ClientSecret)
-
- general, err := stores.GetInstanceGeneralSetting(ctx)
- require.NoError(t, err)
- general.WeekStartDayOffset = 6
- generalAgain, err := stores.GetInstanceGeneralSetting(ctx)
- require.NoError(t, err)
- assert.Equal(t, int32(2), generalAgain.WeekStartDayOffset)
-}
-
-func TestLoadDeploymentConfigurationPublishesAtomically(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- validDir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(validDir, "memos-idp-primary.json"), "primary-sso", "File SSO", "file-secret")
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, validDir))
-
- invalidDir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(invalidDir, "memos-idp-primary.json"), "primary-sso", "Changed SSO", "changed-secret")
- require.NoError(t, os.WriteFile(filepath.Join(invalidDir, "memos-instance-setting-invalid.json"), []byte(`{"key":"GENERAL","unknown":true}`), 0600))
- err := stores.LoadDeploymentConfigurationDir(ctx, invalidDir)
- require.Error(t, err)
- assert.ErrorContains(t, err, `unknown field "unknown"`)
-
- provider, getErr := stores.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("primary-sso")})
- require.NoError(t, getErr)
- assert.Equal(t, "File SSO", provider.Name)
-}
-
-func TestLoadDeploymentConfigurationRejectsDuplicateResources(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(dir, "memos-idp-first.json"), "primary-sso", "First", "first-secret")
- writeDeploymentIdentityProvider(t, filepath.Join(dir, "memos-idp-second.json"), "primary-sso", "Second", "second-secret")
-
- err := stores.LoadDeploymentConfigurationDir(context.Background(), dir)
- require.Error(t, err)
- assert.ErrorContains(t, err, `identity provider UID "primary-sso" is declared by both`)
-}
-
-func TestLoadDeploymentConfigurationValidatesAffectedAuthState(t *testing.T) {
- ctx := context.Background()
-
- t.Run("managed GENERAL cannot disable regular password auth without SSO", func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- writeDeploymentGeneralSetting(t, filepath.Join(dir, "memos-instance-setting-general.json"), 0, true)
- err := stores.LoadDeploymentConfigurationDir(ctx, dir)
- require.Error(t, err)
- assert.ErrorContains(t, err, "has no effective identity provider")
- })
-
- t.Run("unrelated file does not reject unmanaged legacy state", func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- _, err := stores.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{
- DisallowPasswordAuth: true,
- }},
- })
- require.NoError(t, err)
- dir := t.TempDir()
- require.NoError(t, os.WriteFile(filepath.Join(dir, "memos-instance-setting-storage.json"), []byte(`{
- "key": "STORAGE",
- "storageSetting": {"storageType": "LOCAL"}
-}`), 0600))
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
- })
-}
-
-func TestLoadDeploymentConfigurationIgnoresUnrelatedFilesAndMissingDirectory(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- require.NoError(t, os.WriteFile(filepath.Join(dir, ".env"), []byte("DATABASE_PASSWORD=secret"), 0600))
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, filepath.Join(t.TempDir(), "missing")))
-}
-
-func TestLoadDeploymentConfigurationSupportsLegacyIdentityProviderFilenames(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(dir, "memos-idp-Primary_SSO.json"), "primary-sso", "Primary", "secret")
-
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
- assert.True(t, stores.IsIdentityProviderDeploymentConfigured("primary-sso"))
-
- invalidDir := t.TempDir()
- require.NoError(t, os.WriteFile(filepath.Join(invalidDir, "memos-idp-Bad.json"), []byte("not-json"), 0600))
- require.Error(t, stores.LoadDeploymentConfigurationDir(ctx, invalidDir))
-}
-
-func TestLoadDeploymentConfigurationAcceptsSaturdayWeekStart(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- writeDeploymentGeneralSetting(t, filepath.Join(dir, "memos-instance-setting-general.json"), -1, false)
- require.NoError(t, stores.LoadDeploymentConfigurationDir(context.Background(), dir))
-
- general, err := stores.GetInstanceGeneralSetting(context.Background())
- require.NoError(t, err)
- assert.Equal(t, int32(-1), general.WeekStartDayOffset)
-}
-
-func TestLoadDeploymentConfigurationAcceptsRegularFileSymlink(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- target := filepath.Join(t.TempDir(), "provider.json")
- writeDeploymentIdentityProvider(t, target, "primary-sso", "Primary", "secret")
- require.NoError(t, os.Symlink(target, filepath.Join(dir, "memos-idp-primary.json")))
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
- assert.True(t, stores.IsIdentityProviderDeploymentConfigured("primary-sso"))
-}
-
-func TestLoadDeploymentConfigurationSupportsEveryProvisionableSettingGroup(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- settings := map[string]*storepb.InstanceSetting{
- "memos-instance-setting-general.json": {
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{WeekStartDayOffset: 1}},
- },
- "memos-instance-setting-storage.json": {
- Key: storepb.InstanceSettingKey_STORAGE,
- Value: &storepb.InstanceSetting_StorageSetting{StorageSetting: &storepb.InstanceStorageSetting{StorageType: storepb.InstanceStorageSetting_LOCAL}},
- },
- "memos-instance-setting-memo-related.json": {
- Key: storepb.InstanceSettingKey_MEMO_RELATED,
- Value: &storepb.InstanceSetting_MemoRelatedSetting{MemoRelatedSetting: &storepb.InstanceMemoRelatedSetting{
- Reactions: []string{"👍"},
- }},
- },
- "memos-instance-setting-notification.json": {
- Key: storepb.InstanceSettingKey_NOTIFICATION,
- Value: &storepb.InstanceSetting_NotificationSetting{NotificationSetting: &storepb.InstanceNotificationSetting{}},
- },
- "memos-instance-setting-ai.json": {
- Key: storepb.InstanceSettingKey_AI,
- Value: &storepb.InstanceSetting_AiSetting{AiSetting: &storepb.InstanceAISetting{Providers: []*storepb.AIProviderConfig{
- {Id: "primary", Title: "Primary", Type: storepb.AIProviderType_OPENAI, ApiKey: "ai-secret"},
- }}},
- },
- "memos-instance-setting-access.json": {
- Key: storepb.InstanceSettingKey_ACCESS,
- Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{
- AccessMode: storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC,
- }},
- },
- }
- for filename, setting := range settings {
- writeDeploymentMessage(t, filepath.Join(dir, filename), setting)
- }
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
- for _, setting := range settings {
- assert.True(t, stores.IsInstanceSettingDeploymentConfigured(setting.Key))
- }
- ai, err := stores.GetInstanceAISetting(ctx)
- require.NoError(t, err)
- require.Len(t, ai.Providers, 1)
- assert.Equal(t, "https://api.openai.com/v1", ai.Providers[0].Endpoint)
- access, err := stores.GetInstanceAccessSetting(ctx)
- require.NoError(t, err)
- assert.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC, access.AccessMode)
-}
-
-func TestLoadDeploymentConfigurationRejectsInvalidSettingResources(t *testing.T) {
- tests := []struct {
- name string
- content string
- errorString string
- }{
- {name: "BASIC", content: `{"key":"BASIC","basicSetting":{}}`, errorString: "cannot be deployment configured"},
- {name: "TAGS", content: `{"key":"TAGS","tagsSetting":{}}`, errorString: "cannot be deployment configured"},
- {name: "mismatched oneof", content: `{"key":"GENERAL","storageSetting":{}}`, errorString: "generalSetting must be populated"},
- {name: "invalid week start", content: `{"key":"GENERAL","generalSetting":{"weekStartDayOffset":-2}}`, errorString: "must be between -1 and 6"},
- {name: "unspecified access mode", content: `{"key":"ACCESS","accessSetting":{}}`, errorString: "accessSetting.accessMode must be PRIVATE or PUBLIC"},
- {name: "mismatched access oneof", content: `{"key":"ACCESS","generalSetting":{}}`, errorString: "accessSetting must be populated"},
- {name: "unknown field", content: `{"key":"GENERAL","generalSetting":{},"typo":true}`, errorString: `unknown field "typo"`},
- }
- for _, test := range tests {
- t.Run(test.name, func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- require.NoError(t, os.WriteFile(filepath.Join(dir, "memos-instance-setting-invalid.json"), []byte(test.content), 0600))
- err := stores.LoadDeploymentConfigurationDir(context.Background(), dir)
- require.Error(t, err)
- assert.ErrorContains(t, err, test.errorString)
- })
- }
-}
-
-func TestLoadDeploymentUsageLimitsPreservesStoreTargets(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- alice, err := stores.CreateUser(ctx, &store.User{Username: "alice", Role: store.RoleUser, PasswordHash: "hash"})
- require.NoError(t, err)
- dir := t.TempDir()
- path := filepath.Join(dir, "memos-instance-setting-usage-limits.json")
- uploadBytes, unlimited := int64(32<<20), int64(0)
- input := &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_USAGE_LIMITS,
- Value: &storepb.InstanceSetting_UsageLimitsSetting{UsageLimitsSetting: &storepb.InstanceUsageLimitsSetting{
- Limits: []*storepb.InstanceUsageLimitsSetting_UsageLimit{
- {UserIds: []int32{alice.ID}, UploadBytes: &unlimited},
- {AllUsers: true, UploadBytes: &uploadBytes},
- },
- }},
- }
- writeDeploymentMessage(t, path, input)
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
- setting, err := stores.GetInstanceUsageLimitsSetting(ctx)
- require.NoError(t, err)
- require.True(t, proto.Equal(input.GetUsageLimitsSetting(), setting), "configuration uses the stored schema without converting users")
-
- _, err = stores.UpdateUser(ctx, &store.UpdateUser{ID: alice.ID, Username: new("alice-renamed")})
- require.NoError(t, err)
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir), "a rename does not require editing the configuration")
- setting, err = stores.GetInstanceUsageLimitsSetting(ctx)
- require.NoError(t, err)
- require.True(t, proto.Equal(input.GetUsageLimitsSetting(), setting))
-}
-
-func TestLoadDeploymentUsageLimitsRejectsInvalidTargets(t *testing.T) {
- for name, limits := range map[string]string{
- "no all-users entry": `[{"userIds":[1],"uploadBytes":"1"}]`,
- "all users not last": `[{"allUsers":true,"uploadBytes":"1"},{"userIds":[1],"uploadBytes":"1"}]`,
- "zero user ID": `[{"userIds":[0],"uploadBytes":"1"},{"allUsers":true}]`,
- "negative user ID": `[{"userIds":[-1],"uploadBytes":"1"},{"allUsers":true}]`,
- "entry without users": `[{"uploadBytes":"1"},{"allUsers":true}]`,
- "both targets": `[{"allUsers":true,"userIds":[1],"uploadBytes":"1"}]`,
- "user resource name": `[{"users":["users/alice"],"uploadBytes":"1"},{"allUsers":true}]`,
- "repeated user": `[{"userIds":[1,1],"uploadBytes":"1"},{"allUsers":true}]`,
- "negative value": `[{"allUsers":true,"uploadBytes":"-1"}]`,
- "old per-metric": `[{"uid":"a","metric":"UPLOAD_BYTES","allUsers":{},"value":"1"}]`,
- } {
- t.Run(name, func(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- path := filepath.Join(dir, "memos-instance-setting-usage-limits.json")
- valid := `{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[{"allUsers":true,"uploadBytes":"33554432"}]}}`
- require.NoError(t, os.WriteFile(path, []byte(valid), 0600))
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
- previous, err := stores.GetInstanceUsageLimitsSetting(ctx)
- require.NoError(t, err)
-
- content := `{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":` + limits + `}}`
- require.NoError(t, os.WriteFile(path, []byte(content), 0600))
- err = stores.LoadDeploymentConfigurationDir(ctx, dir)
- require.Error(t, err)
- require.ErrorContains(t, err, "memos-instance-setting-usage-limits.json")
- setting, err := stores.GetInstanceUsageLimitsSetting(ctx)
- require.NoError(t, err)
- require.True(t, proto.Equal(previous, setting), "an invalid reload preserves the active configuration")
- })
- }
-}
-
-func TestLoadDeploymentConfigurationBoundsFilesAndRedactsDecodeErrors(t *testing.T) {
- t.Run("oversized file", func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- require.NoError(t, os.WriteFile(filepath.Join(dir, "memos-idp-oversized.json"), []byte(strings.Repeat("x", (1<<20)+1)), 0600))
- err := stores.LoadDeploymentConfigurationDir(context.Background(), dir)
- require.Error(t, err)
- assert.ErrorContains(t, err, "exceeds 1048576 bytes")
- })
-
- t.Run("secret value is not included in a type error", func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- content := `{
- "uid":"primary-sso",
- "name":"Primary",
- "type":"OAUTH2",
- "config":{"oauth2Config":{"clientSecret":{"value":"must-not-appear"}}}
-}`
- require.NoError(t, os.WriteFile(filepath.Join(dir, "memos-idp-primary.json"), []byte(content), 0600))
- err := stores.LoadDeploymentConfigurationDir(context.Background(), dir)
- require.Error(t, err)
- assert.NotContains(t, err.Error(), "must-not-appear")
- })
-}
-
-func TestAuthenticationConfigurationMutationsAreSafe(t *testing.T) {
- ctx := context.Background()
-
- t.Run("rejects disabling regular password auth without an IdP", func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- _, err := stores.UpsertInstanceGeneralSettingSafely(ctx, &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{
- DisallowPasswordAuth: true,
- }},
- })
- require.ErrorIs(t, err, store.ErrUnsafeAuthenticationConfiguration)
- stored, getErr := stores.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_GENERAL.String()})
- require.NoError(t, getErr)
- assert.Nil(t, stored)
- })
-
- t.Run("rejects deleting the last effective IdP", func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- provider, err := stores.CreateIdentityProvider(ctx, deploymentIdentityProvider("primary-sso", "Primary", "secret"))
- require.NoError(t, err)
- _, err = stores.UpsertInstanceGeneralSettingSafely(ctx, &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{
- DisallowPasswordAuth: true,
- }},
- })
- require.NoError(t, err)
- err = stores.DeleteIdentityProviderSafely(ctx, &store.DeleteIdentityProvider{ID: provider.Id})
- require.ErrorIs(t, err, store.ErrUnsafeAuthenticationConfiguration)
- stored, getErr := stores.GetStoredIdentityProvider(ctx, &store.FindIdentityProvider{ID: &provider.Id})
- require.NoError(t, getErr)
- assert.NotNil(t, stored)
- })
-
- t.Run("file-backed IdP satisfies the invariant", func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(dir, "memos-idp-primary.json"), "primary-sso", "Primary", "secret")
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
- _, err := stores.UpsertInstanceGeneralSettingSafely(ctx, &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{
- DisallowPasswordAuth: true,
- }},
- })
- require.NoError(t, err)
- })
-
- t.Run("allows unrelated edits to an existing unsafe GENERAL state", func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- _, err := stores.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{
- DisallowPasswordAuth: true,
- }},
- })
- require.NoError(t, err)
-
- _, err = stores.UpsertInstanceGeneralSettingSafely(ctx, &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{
- DisallowPasswordAuth: true,
- WeekStartDayOffset: 1,
- }},
- })
- require.NoError(t, err)
- })
-
- t.Run("rejects making the stored fallback unsafe under deployment GENERAL", func(t *testing.T) {
- stores := newDeploymentConfigurationTestStore(t)
- dir := t.TempDir()
- writeDeploymentGeneralSetting(t, filepath.Join(dir, "memos-instance-setting-general.json"), 0, false)
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
-
- _, err := stores.UpsertInstanceGeneralSettingSafely(ctx, &storepb.InstanceSetting{
- Key: storepb.InstanceSettingKey_GENERAL,
- Value: &storepb.InstanceSetting_GeneralSetting{GeneralSetting: &storepb.InstanceGeneralSetting{
- DisallowPasswordAuth: true,
- }},
- })
- require.ErrorIs(t, err, store.ErrUnsafeAuthenticationConfiguration)
- })
-}
-
-func TestListIdentityProvidersPreservesStoredOrder(t *testing.T) {
- ctx := context.Background()
- stores := newDeploymentConfigurationTestStore(t)
- _, err := stores.CreateIdentityProvider(ctx, deploymentIdentityProvider("zeta-sso", "Stored Zeta", "stored-secret"))
- require.NoError(t, err)
- _, err = stores.CreateIdentityProvider(ctx, deploymentIdentityProvider("alpha-test", "Stored Alpha", "stored-secret"))
- require.NoError(t, err)
-
- dir := t.TempDir()
- writeDeploymentIdentityProvider(t, filepath.Join(dir, "memos-idp-zeta.json"), "zeta-sso", "File Zeta", "file-secret")
- writeDeploymentIdentityProvider(t, filepath.Join(dir, "memos-idp-beta.json"), "beta-file", "File Beta", "file-secret")
- require.NoError(t, stores.LoadDeploymentConfigurationDir(ctx, dir))
-
- providers, err := stores.ListIdentityProviders(ctx, &store.FindIdentityProvider{})
- require.NoError(t, err)
- require.Len(t, providers, 3)
- assert.Equal(t, []string{"zeta-sso", "alpha-test", "beta-file"}, []string{providers[0].Uid, providers[1].Uid, providers[2].Uid})
- assert.Equal(t, "File Zeta", providers[0].Name)
-}
-
-func newDeploymentConfigurationTestStore(t *testing.T) *store.Store {
- t.Helper()
- p := &profile.Profile{
- Data: t.TempDir(),
- Driver: "sqlite",
- DSN: filepath.Join(t.TempDir(), "deployment.db"),
- }
- driver, err := sqlite.NewDB(p)
- require.NoError(t, err)
- stores := store.New(driver, p)
- require.NoError(t, stores.Migrate(context.Background()))
- t.Cleanup(func() {
- require.NoError(t, stores.Close())
- })
- return stores
-}
-
-func deploymentIdentityProvider(uid, title, secret string) *storepb.IdentityProvider {
- return &storepb.IdentityProvider{
- Uid: uid,
- Name: title,
- Type: storepb.IdentityProvider_OAUTH2,
- Config: &storepb.IdentityProviderConfig{Config: &storepb.IdentityProviderConfig_Oauth2Config{Oauth2Config: &storepb.OAuth2Config{
- ClientId: "client-id",
- ClientSecret: secret,
- AuthUrl: "https://example.com/authorize",
- TokenUrl: "https://example.com/token",
- UserInfoUrl: "https://example.com/userinfo",
- Scopes: []string{"profile", "email"},
- FieldMapping: &storepb.FieldMapping{Identifier: "sub"},
- }}},
- }
-}
-
-func writeDeploymentIdentityProvider(t *testing.T, path, uid, title, secret string) {
- t.Helper()
- content := `{
- "uid": "` + uid + `",
- "name": "` + title + `",
- "type": "OAUTH2",
- "config": {
- "oauth2Config": {
- "clientId": "client-id",
- "clientSecret": "` + secret + `",
- "authUrl": "https://example.com/authorize",
- "tokenUrl": "https://example.com/token",
- "userInfoUrl": "https://example.com/userinfo",
- "scopes": ["profile", "email"],
- "fieldMapping": {"identifier": "sub"}
- }
- }
-}`
- require.False(t, strings.Contains(uid+title+secret, `"`))
- require.NoError(t, os.WriteFile(path, []byte(content), 0600))
-}
-
-func writeDeploymentGeneralSetting(t *testing.T, path string, weekStart int32, disallowPasswordAuth bool) {
- t.Helper()
- content := `{
- "key": "GENERAL",
- "generalSetting": {
- "weekStartDayOffset": ` + assertInt32(weekStart) + `,
- "disallowPasswordAuth": ` + assertBool(disallowPasswordAuth) + `
- }
-}`
- require.NoError(t, os.WriteFile(path, []byte(content), 0600))
-}
-
-func writeDeploymentMessage(t *testing.T, path string, message proto.Message) {
- t.Helper()
- content, err := (protojson.MarshalOptions{Indent: " "}).Marshal(message)
- require.NoError(t, err)
- require.NoError(t, os.WriteFile(path, content, 0600))
-}
-
-func assertInt32(value int32) string {
- return strconv.FormatInt(int64(value), 10)
-}
-
-func assertBool(value bool) string {
- if value {
- return "true"
- }
- return "false"
-}
diff --git a/store/doc.go b/store/doc.go
index 616e17898..edc347315 100644
--- a/store/doc.go
+++ b/store/doc.go
@@ -2,6 +2,10 @@
// interface implemented by store/db/{sqlite,mysql,postgres}, migrations, seed
// data, and the in-memory cache.
//
+// Writes that must validate what they read run in runSerializable, which owns
+// the transaction and its retries; a driver supplies only the SQL that differs
+// by database, as methods that take the *sql.Tx.
+//
// Layering: store may import provider, markdown, filter, proto/gen, and
// internal. It must not import core or server; business rules that need
// several store calls live in core.
diff --git a/store/driver.go b/store/driver.go
index 4868a6f3d..41cec070a 100644
--- a/store/driver.go
+++ b/store/driver.go
@@ -62,16 +62,27 @@ type Driver interface {
CreateInstanceSettingIfNotExists(ctx context.Context, create *InstanceSetting) (bool, error)
// UpdateInstanceSettingIfUnchanged replaces the value only when the stored value still equals oldValue, and reports whether it did.
UpdateInstanceSettingIfUnchanged(ctx context.Context, name, oldValue, newValue string) (bool, error)
+ // GetInstanceSettingTx reads one setting within tx, locking its row where the database supports row locks, or returns nil when it is absent.
+ GetInstanceSettingTx(ctx context.Context, tx *sql.Tx, name string) (*InstanceSetting, error)
+ // CreateInstanceSettingIfNotExistsTx is CreateInstanceSettingIfNotExists within tx.
+ CreateInstanceSettingIfNotExistsTx(ctx context.Context, tx *sql.Tx, create *InstanceSetting) (bool, error)
+ // UpdateInstanceSettingIfUnchangedTx is UpdateInstanceSettingIfUnchanged within tx.
+ UpdateInstanceSettingIfUnchangedTx(ctx context.Context, tx *sql.Tx, name, oldValue, newValue string) (bool, error)
UpsertInstanceSetting(ctx context.Context, upsert *InstanceSetting) (*InstanceSetting, error)
// UpsertInstanceSettingTx writes the setting within tx, for callers that must commit it together with other statements.
UpsertInstanceSettingTx(ctx context.Context, tx *sql.Tx, upsert *InstanceSetting) error
ListInstanceSettings(ctx context.Context, find *FindInstanceSetting) ([]*InstanceSetting, error)
DeleteInstanceSetting(ctx context.Context, delete *DeleteInstanceSetting) error
+ DeleteInstanceSettingTx(ctx context.Context, tx *sql.Tx, delete *DeleteInstanceSetting) error
// User model related methods.
CreateUser(ctx context.Context, create *User) (*User, error)
UpdateUser(ctx context.Context, update *UpdateUser) (*User, error)
ListUsers(ctx context.Context, find *FindUser) ([]*User, error)
+ // CreateUserTx, UpdateUserTx, and ListUsersTx are the same methods within tx.
+ CreateUserTx(ctx context.Context, tx *sql.Tx, create *User) (*User, error)
+ UpdateUserTx(ctx context.Context, tx *sql.Tx, update *UpdateUser) (*User, error)
+ ListUsersTx(ctx context.Context, tx *sql.Tx, find *FindUser) ([]*User, error)
DeleteUser(ctx context.Context, delete *DeleteUser) (*DeleteUserResult, error)
// UserSetting model related methods.
@@ -88,8 +99,16 @@ type Driver interface {
ListIdentityProviders(ctx context.Context, find *FindIdentityProvider) ([]*IdentityProvider, error)
UpdateIdentityProvider(ctx context.Context, update *UpdateIdentityProvider) (*IdentityProvider, error)
DeleteIdentityProvider(ctx context.Context, delete *DeleteIdentityProvider) error
- ApplyAuthenticationConfigMutation(ctx context.Context, mutation *AuthenticationConfigMutation) error
- IsRetryableAuthenticationMutationError(err error) bool
+ // The identity provider methods within tx.
+ CreateIdentityProviderTx(ctx context.Context, tx *sql.Tx, create *IdentityProvider) (*IdentityProvider, error)
+ ListIdentityProvidersTx(ctx context.Context, tx *sql.Tx, find *FindIdentityProvider) ([]*IdentityProvider, error)
+ UpdateIdentityProviderTx(ctx context.Context, tx *sql.Tx, update *UpdateIdentityProvider) (*IdentityProvider, error)
+ DeleteIdentityProviderTx(ctx context.Context, tx *sql.Tx, delete *DeleteIdentityProvider) error
+ // ApplyAuthenticationConfigMutationTx reads the authentication configuration, validates the mutation, and applies it within tx.
+ ApplyAuthenticationConfigMutationTx(ctx context.Context, tx *sql.Tx, mutation *AuthenticationConfigMutation) error
+
+ // IsRetryableTransactionError reports whether err is a serialization or locking conflict that running the transaction again can resolve.
+ IsRetryableTransactionError(err error) bool
// Inbox model related methods.
CreateInbox(ctx context.Context, create *Inbox) (*Inbox, error)
diff --git a/store/idp.go b/store/idp.go
index b597ba8f5..69897400a 100644
--- a/store/idp.go
+++ b/store/idp.go
@@ -52,48 +52,6 @@ func (s *Store) CreateIdentityProvider(ctx context.Context, create *storepb.Iden
}
func (s *Store) ListIdentityProviders(ctx context.Context, find *FindIdentityProvider) ([]*storepb.IdentityProvider, error) {
- stored, err := s.listStoredIdentityProviders(ctx, find)
- if err != nil {
- return nil, err
- }
- // File-backed providers do not have database IDs. ID-filtered reads are raw
- // stored-resource lookups used by mutation paths.
- if find.ID != nil {
- return stored, nil
- }
- if find.UID != nil {
- if provider := s.getDeploymentIdentityProvider(*find.UID); provider != nil {
- return []*storepb.IdentityProvider{provider}, nil
- }
- return stored, nil
- }
-
- deploymentProviders := s.listDeploymentIdentityProviders()
- deploymentByUID := make(map[string]*storepb.IdentityProvider, len(deploymentProviders))
- for _, provider := range deploymentProviders {
- deploymentByUID[provider.Uid] = provider
- }
- identityProviders := make([]*storepb.IdentityProvider, 0, len(stored)+len(deploymentProviders))
- for _, provider := range stored {
- if configured := deploymentByUID[provider.Uid]; configured != nil {
- identityProviders = append(identityProviders, configured)
- delete(deploymentByUID, provider.Uid)
- continue
- }
- identityProviders = append(identityProviders, provider)
- }
- // listDeploymentIdentityProviders is UID-sorted, so providers that exist
- // only in deployment configuration are appended deterministically without
- // reordering existing database-backed providers.
- for _, provider := range deploymentProviders {
- if deploymentByUID[provider.Uid] != nil {
- identityProviders = append(identityProviders, provider)
- }
- }
- return identityProviders, nil
-}
-
-func (s *Store) listStoredIdentityProviders(ctx context.Context, find *FindIdentityProvider) ([]*storepb.IdentityProvider, error) {
list, err := s.driver.ListIdentityProviders(ctx, find)
if err != nil {
return nil, err
@@ -126,21 +84,6 @@ func (s *Store) GetIdentityProvider(ctx context.Context, find *FindIdentityProvi
return identityProvider, nil
}
-// GetStoredIdentityProvider returns a database-backed provider without deployment shadowing.
-func (s *Store) GetStoredIdentityProvider(ctx context.Context, find *FindIdentityProvider) (*storepb.IdentityProvider, error) {
- list, err := s.listStoredIdentityProviders(ctx, find)
- if err != nil {
- return nil, err
- }
- if len(list) == 0 {
- return nil, nil
- }
- if len(list) > 1 {
- return nil, errors.New("found multiple stored identity providers")
- }
- return list[0], nil
-}
-
type UpdateIdentityProviderV1 struct {
ID int32
Type storepb.IdentityProvider_Type
diff --git a/store/instance_setting.go b/store/instance_setting.go
index 23d9008f8..dba9671b3 100644
--- a/store/instance_setting.go
+++ b/store/instance_setting.go
@@ -1,10 +1,7 @@
package store
import (
- "cmp"
"context"
- "slices"
- "strings"
"github.com/pkg/errors"
"google.golang.org/protobuf/encoding/protojson"
@@ -27,7 +24,9 @@ type DeleteInstanceSetting struct {
Name string
}
-func (s *Store) UpsertInstanceSetting(ctx context.Context, upsert *storepb.InstanceSetting) (*storepb.InstanceSetting, error) {
+// encodeInstanceSetting turns a setting into its stored row, normalizing a
+// storage setting and validating usage limits as every write must.
+func encodeInstanceSetting(upsert *storepb.InstanceSetting) (*InstanceSetting, error) {
instanceSettingRaw := &InstanceSetting{
Name: upsert.Key.String(),
}
@@ -61,8 +60,15 @@ func (s *Store) UpsertInstanceSetting(ctx context.Context, upsert *storepb.Insta
if err != nil {
return nil, errors.Wrap(err, "failed to marshal instance setting value")
}
- valueString := string(valueBytes)
- instanceSettingRaw.Value = valueString
+ instanceSettingRaw.Value = string(valueBytes)
+ return instanceSettingRaw, nil
+}
+
+func (s *Store) UpsertInstanceSetting(ctx context.Context, upsert *storepb.InstanceSetting) (*storepb.InstanceSetting, error) {
+ instanceSettingRaw, err := encodeInstanceSetting(upsert)
+ if err != nil {
+ return nil, err
+ }
instanceSettingRaw, err = s.driver.UpsertInstanceSetting(ctx, instanceSettingRaw)
if err != nil {
return nil, errors.Wrap(err, "Failed to upsert instance setting")
@@ -93,38 +99,6 @@ func (s *Store) DeleteInstanceSetting(ctx context.Context, delete *DeleteInstanc
}
func (s *Store) ListInstanceSettings(ctx context.Context, find *FindInstanceSetting) ([]*storepb.InstanceSetting, error) {
- stored, err := s.listStoredInstanceSettings(ctx, find)
- if err != nil {
- return nil, err
- }
- if find.Name != "" {
- key, ok := storepb.InstanceSettingKey_value[find.Name]
- if ok {
- if configured := s.getDeploymentInstanceSetting(storepb.InstanceSettingKey(key)); configured != nil {
- return []*storepb.InstanceSetting{configured}, nil
- }
- }
- return stored, nil
- }
-
- byKey := make(map[storepb.InstanceSettingKey]*storepb.InstanceSetting, len(stored))
- for _, setting := range stored {
- byKey[setting.Key] = setting
- }
- s.deploymentConfigMu.RLock()
- for key, setting := range s.deploymentConfig.instanceSettings {
- byKey[key] = cloneInstanceSetting(setting)
- }
- s.deploymentConfigMu.RUnlock()
- settings := make([]*storepb.InstanceSetting, 0, len(byKey))
- for _, setting := range byKey {
- settings = append(settings, setting)
- }
- slices.SortFunc(settings, func(a, b *storepb.InstanceSetting) int { return cmp.Compare(a.Key, b.Key) })
- return settings, nil
-}
-
-func (s *Store) listStoredInstanceSettings(ctx context.Context, find *FindInstanceSetting) ([]*storepb.InstanceSetting, error) {
list, err := s.driver.ListInstanceSettings(ctx, find)
if err != nil {
return nil, err
@@ -145,8 +119,10 @@ func (s *Store) listStoredInstanceSettings(ctx context.Context, find *FindInstan
return instanceSettings, nil
}
-func (s *Store) getRawInstanceSetting(ctx context.Context, name string) (*storepb.InstanceSetting, error) {
- list, err := s.listStoredInstanceSettings(ctx, &FindInstanceSetting{Name: name})
+// GetUncachedInstanceSetting reads one setting from the database, bypassing
+// the instance setting cache.
+func (s *Store) GetUncachedInstanceSetting(ctx context.Context, find *FindInstanceSetting) (*storepb.InstanceSetting, error) {
+ list, err := s.ListInstanceSettings(ctx, find)
if err != nil {
return nil, err
}
@@ -154,22 +130,12 @@ func (s *Store) getRawInstanceSetting(ctx context.Context, name string) (*storep
return nil, nil
}
if len(list) > 1 {
- return nil, errors.Errorf("found multiple stored instance settings with key %s", name)
+ return nil, errors.Errorf("found multiple instance settings with key %s", find.Name)
}
return list[0], nil
}
-// GetStoredInstanceSetting returns a database-backed setting without deployment shadowing.
-func (s *Store) GetStoredInstanceSetting(ctx context.Context, find *FindInstanceSetting) (*storepb.InstanceSetting, error) {
- return s.getRawInstanceSetting(ctx, find.Name)
-}
-
func (s *Store) GetInstanceSetting(ctx context.Context, find *FindInstanceSetting) (*storepb.InstanceSetting, error) {
- if key, ok := storepb.InstanceSettingKey_value[find.Name]; ok {
- if setting := s.getDeploymentInstanceSetting(storepb.InstanceSettingKey(key)); setting != nil {
- return setting, nil
- }
- }
if cache, ok := s.instanceSettingCache.Get(ctx, find.Name); ok {
instanceSetting, ok := cache.(*storepb.InstanceSetting)
if ok {
@@ -191,7 +157,7 @@ func (s *Store) GetInstanceSetting(ctx context.Context, find *FindInstanceSettin
}
func (s *Store) cacheInstanceSetting(ctx context.Context, setting *storepb.InstanceSetting) {
- if setting == nil || s.IsInstanceSettingDeploymentConfigured(setting.Key) {
+ if setting == nil {
return
}
s.instanceSettingCache.Set(ctx, setting.Key.String(), setting)
@@ -237,15 +203,11 @@ func (s *Store) GetInstanceGeneralSetting(ctx context.Context) (*storepb.Instanc
// GetInstanceAccessSetting gets the instance access policy, defaulting to private.
func (s *Store) GetInstanceAccessSetting(ctx context.Context) (*storepb.InstanceAccessSetting, error) {
- instanceSetting := s.getDeploymentInstanceSetting(storepb.InstanceSettingKey_ACCESS)
- if instanceSetting == nil {
- var err error
- // Access policy changes must take effect across replicas without waiting for
- // the general instance-setting cache to expire.
- instanceSetting, err = s.getRawInstanceSetting(ctx, storepb.InstanceSettingKey_ACCESS.String())
- if err != nil {
- return nil, errors.Wrap(err, "failed to get instance access setting")
- }
+ // Access policy changes must take effect across replicas without waiting for
+ // the general instance-setting cache to expire.
+ instanceSetting, err := s.GetUncachedInstanceSetting(ctx, &FindInstanceSetting{Name: storepb.InstanceSettingKey_ACCESS.String()})
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get instance access setting")
}
instanceAccessSetting := &storepb.InstanceAccessSetting{}
@@ -314,24 +276,6 @@ func (s *Store) GetInstanceTagsSetting(ctx context.Context) (*storepb.InstanceTa
return instanceTagsSetting, nil
}
-// ValidateInstanceNotificationSetting checks the rules a notification setting
-// must meet before it is stored, whether it comes from the API or from
-// deployment configuration: enabled email needs a host, a positive port, and
-// a from address, and TLS and SSL are mutually exclusive.
-func ValidateInstanceNotificationSetting(setting *storepb.InstanceNotificationSetting) error {
- email := setting.GetEmail()
- if email == nil || !email.Enabled {
- return nil
- }
- if strings.TrimSpace(email.SmtpHost) == "" || email.SmtpPort <= 0 || strings.TrimSpace(email.FromEmail) == "" {
- return errors.New("enabled notification email requires smtpHost, a positive smtpPort, and fromEmail")
- }
- if email.UseTls && email.UseSsl {
- return errors.New("notification email cannot enable both useTls and useSsl")
- }
- return nil
-}
-
func (s *Store) GetInstanceNotificationSetting(ctx context.Context) (*storepb.InstanceNotificationSetting, error) {
instanceSetting, err := s.GetInstanceSetting(ctx, &FindInstanceSetting{
Name: storepb.InstanceSettingKey_NOTIFICATION.String(),
diff --git a/store/migrator.go b/store/migrator.go
index e4b8478d9..b7d142e21 100644
--- a/store/migrator.go
+++ b/store/migrator.go
@@ -28,7 +28,6 @@ import (
// 2. checkMinimumUpgradeVersion: Verify the database meets the fixed v0.31.0 baseline
// 3. Migrate (prod mode): Apply incremental migrations from current to target version
// 4. Migrate (demo mode): Seed database with demo data
-// Deployment configuration is loaded separately after migration completes.
//
// Version Tracking:
// - New installations: Schema version set in system_setting immediately
@@ -326,6 +325,31 @@ func (s *Store) seed(ctx context.Context) error {
return tx.Commit()
}
+// CheckSchemaCurrent fails unless the database is initialized and at the
+// schema version this binary migrates to. Commands that only read, such as a
+// configuration plan, call it instead of Migrate, which writes.
+func (s *Store) CheckSchemaCurrent(ctx context.Context) error {
+ initialized, err := s.driver.IsInitialized(ctx)
+ if err != nil {
+ return errors.Wrap(err, "failed to check whether the database is initialized")
+ }
+ if !initialized {
+ return errors.New("the database is not initialized; start Memos once to create it")
+ }
+ basic, err := s.GetInstanceBasicSetting(ctx)
+ if err != nil {
+ return err
+ }
+ current, err := s.GetCurrentSchemaVersion()
+ if err != nil {
+ return errors.Wrap(err, "failed to get current schema version")
+ }
+ if basic.SchemaVersion != current {
+ return errors.Errorf("the database schema is %s but this Memos expects %s; start this version of Memos once to migrate it", basic.SchemaVersion, current)
+ }
+ return nil
+}
+
// GetCurrentSchemaVersion returns the latest schema version available for the configured database driver.
// With no incremental migrations, it returns the fixed v0.31.0 baseline.
//
diff --git a/store/storage.go b/store/storage.go
index 0a643c1c5..9348b4d95 100644
--- a/store/storage.go
+++ b/store/storage.go
@@ -220,9 +220,9 @@ func ResolveStorage(
if configuredStorage := FindStorage(setting, storageID); configuredStorage != nil {
return configuredStorage, nil
}
- // The registry may have been rebuilt without preserving IDs (deployment
- // config file, restored backup, rollback round-trip); fall through to the
- // legacy chain rather than permanently orphaning the attachment.
+ // The registry may have been rebuilt without preserving IDs (restored
+ // backup, rollback round-trip); fall through to the legacy chain rather
+ // than permanently orphaning the attachment.
}
s3Config := legacyS3Config
diff --git a/store/storage_test.go b/store/storage_test.go
index 09cf4df96..2e206039c 100644
--- a/store/storage_test.go
+++ b/store/storage_test.go
@@ -247,8 +247,8 @@ func TestResolveStorageFallsBackWhenStorageIDMissing(t *testing.T) {
setting := legacyS3StorageSetting("https://s3.example.com", "memos", "secret")
store.NormalizeInstanceStorageSetting(setting)
- // The registry may be rebuilt without preserving IDs (deployment file,
- // restored backup); a dangling reference must fall back to the namespace
+ // The registry may be rebuilt without preserving IDs (restored backup,
+ // rollback round-trip); a dangling reference must fall back to the namespace
// chain instead of permanently orphaning the attachment.
resolved, err := store.ResolveStorage(setting, "s3-dangling", nil)
require.NoError(t, err)
diff --git a/store/store.go b/store/store.go
index 03260eab3..b221029cf 100644
--- a/store/store.go
+++ b/store/store.go
@@ -5,7 +5,6 @@ import (
"time"
"github.com/usememos/memos/internal/profile"
- storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/provider/storage"
"github.com/usememos/memos/store/cache"
)
@@ -21,9 +20,6 @@ type Store struct {
patMu sync.Mutex
memoViewMu sync.Mutex
- deploymentConfigMu sync.RWMutex
- deploymentConfig *deploymentConfiguration
-
// Cache settings
cacheConfig cache.Config
@@ -39,11 +35,6 @@ type Store struct {
storageDriverCache map[storageDriverCacheKey]storage.Driver
}
-type deploymentConfiguration struct {
- identityProviders map[string]*storepb.IdentityProvider
- instanceSettings map[storepb.InstanceSettingKey]*storepb.InstanceSetting
-}
-
// New creates a new instance of Store.
func New(driver Driver, profile *profile.Profile) *Store {
// Default cache settings
@@ -61,10 +52,6 @@ func New(driver Driver, profile *profile.Profile) *Store {
instanceSettingCache: cache.New(cacheConfig),
userCache: cache.New(cacheConfig),
userSettingCache: cache.New(cacheConfig),
- deploymentConfig: &deploymentConfiguration{
- identityProviders: map[string]*storepb.IdentityProvider{},
- instanceSettings: map[storepb.InstanceSettingKey]*storepb.InstanceSetting{},
- },
}
return store
diff --git a/store/test/configuration_state_test.go b/store/test/configuration_state_test.go
new file mode 100644
index 000000000..910fe610a
--- /dev/null
+++ b/store/test/configuration_state_test.go
@@ -0,0 +1,221 @@
+package test
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+
+ "github.com/pkg/errors"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
+
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+)
+
+func managedResource(name string) *storepb.InstanceConfigurationState_ManagedResource {
+ return &storepb.InstanceConfigurationState_ManagedResource{
+ Name: name,
+ Kind: "InstanceSetting",
+ Source: "instance.json",
+ ManagedFields: []string{"*"},
+ }
+}
+
+func TestConfigurationStateSerial(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ ts := NewTestingStore(ctx, t)
+ t.Cleanup(func() { require.NoError(t, ts.Close()) })
+
+ initial, err := ts.GetConfigurationState(ctx)
+ require.NoError(t, err)
+ require.Zero(t, initial.Serial, "before any apply the record is empty")
+ require.Empty(t, initial.Resources)
+
+ // The first change creates the row with serial 1, whatever serial the body sets.
+ stored, err := ts.RunConfigurationTransaction(ctx, func(_ context.Context, tx *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ require.Zero(t, tx.State().Serial)
+ return &storepb.InstanceConfigurationState{Serial: 99, ConfigDigest: "a", Resources: []*storepb.InstanceConfigurationState_ManagedResource{
+ managedResource("instance/settings/ACCESS"),
+ }}, nil
+ })
+ require.NoError(t, err)
+ require.Equal(t, int64(1), stored.Serial)
+
+ // A body with no change commits nothing and keeps the serial.
+ unchanged, err := ts.RunConfigurationTransaction(ctx, func(_ context.Context, tx *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ require.Equal(t, int64(1), tx.State().Serial)
+ return nil, nil
+ })
+ require.NoError(t, err)
+ require.True(t, proto.Equal(stored, unchanged))
+
+ // A failing body rolls back.
+ failure := errors.New("plan failed")
+ _, err = ts.RunConfigurationTransaction(ctx, func(context.Context, *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ return &storepb.InstanceConfigurationState{ConfigDigest: "discarded"}, failure
+ })
+ require.ErrorIs(t, err, failure)
+
+ // A second change updates the row.
+ stored, err = ts.RunConfigurationTransaction(ctx, func(_ context.Context, tx *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ next := tx.State()
+ next.ConfigDigest = "b"
+ next.Resources = append(next.Resources, managedResource("instance/settings/GENERAL"))
+ return next, nil
+ })
+ require.NoError(t, err)
+ require.Equal(t, int64(2), stored.Serial)
+
+ read, err := ts.GetConfigurationState(ctx)
+ require.NoError(t, err)
+ require.True(t, proto.Equal(stored, read))
+ require.Equal(t, "b", read.ConfigDigest)
+ require.Len(t, read.Resources, 2)
+}
+
+func TestConfigurationStateIsNotAnInstanceSetting(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ ts := NewTestingStore(ctx, t)
+ t.Cleanup(func() { require.NoError(t, ts.Close()) })
+
+ _, err := ts.RunConfigurationTransaction(ctx, func(context.Context, *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ return &storepb.InstanceConfigurationState{Resources: []*storepb.InstanceConfigurationState_ManagedResource{managedResource("instance/settings/ACCESS")}}, nil
+ })
+ require.NoError(t, err)
+
+ settings, err := ts.ListInstanceSettings(ctx, &store.FindInstanceSetting{})
+ require.NoError(t, err)
+ for _, setting := range settings {
+ require.NotEqual(t, storepb.InstanceSettingKey_CONFIGURATION_STATE, setting.Key)
+ }
+ setting, err := ts.GetInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_CONFIGURATION_STATE.String()})
+ require.NoError(t, err)
+ require.Nil(t, setting)
+}
+
+// TestConfigurationStateConcurrentApplies runs transactions that each add one
+// managed resource, as replicas starting together each apply at boot.
+// Serializable isolation plus the conditional write must serialize them, and
+// the retries must absorb the conflicts: every transaction commits once and
+// none overwrites another.
+func TestConfigurationStateConcurrentApplies(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ ts := NewTestingStore(ctx, t)
+ t.Cleanup(func() { require.NoError(t, ts.Close()) })
+
+ const applies = 6
+ var wg sync.WaitGroup
+ errs := make(chan error, applies)
+ for i := range applies {
+ wg.Go(func() {
+ _, err := ts.RunConfigurationTransaction(ctx, func(_ context.Context, tx *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ next := tx.State()
+ next.Resources = append(next.Resources, managedResource(fmt.Sprintf("users/user-%d", i)))
+ return next, nil
+ })
+ errs <- err
+ })
+ }
+ wg.Wait()
+ close(errs)
+
+ for err := range errs {
+ require.NoError(t, err)
+ }
+ state, err := ts.GetConfigurationState(ctx)
+ require.NoError(t, err)
+ require.Equal(t, int64(applies), state.Serial)
+ require.Len(t, state.Resources, applies)
+}
+
+// TestConfigurationTransactionWrites runs every write apply makes inside one
+// transaction: the transaction reads what it wrote, and the commit makes it
+// visible through the store's cached reads.
+func TestConfigurationTransactionWrites(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ ts := NewTestingStore(ctx, t)
+ t.Cleanup(func() { require.NoError(t, ts.Close()) })
+
+ // Prime the setting cache, so the test sees whether the commit invalidates it.
+ _, err := ts.GetInstanceGeneralSetting(ctx)
+ require.NoError(t, err)
+ existing, err := ts.CreateUser(ctx, &store.User{Username: "existing", Role: store.RoleAdmin, PasswordHash: "hash"})
+ require.NoError(t, err)
+
+ _, err = ts.RunConfigurationTransaction(ctx, func(ctx context.Context, tx *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ require.NoError(t, tx.CreateIdentityProvider(ctx, createTestOAuth2IDP("SSO", "sso")))
+ providers, err := tx.ListIdentityProviders(ctx, &store.FindIdentityProvider{})
+ require.NoError(t, err)
+ require.Len(t, providers, 1, "the transaction reads its own write")
+ replaced := proto.CloneOf(providers[0])
+ replaced.Name = "Renamed SSO"
+ replaced.Config.GetOauth2Config().Scopes = []string{"openid"}
+ require.NoError(t, tx.ReplaceIdentityProvider(ctx, providers[0].Id, replaced))
+
+ require.NoError(t, tx.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{Key: storepb.InstanceSettingKey_GENERAL, Value: &storepb.InstanceSetting_GeneralSetting{
+ GeneralSetting: &storepb.InstanceGeneralSetting{CustomProfile: &storepb.InstanceCustomProfile{Title: "Configured"}},
+ }}))
+ general, err := tx.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: "GENERAL"})
+ require.NoError(t, err)
+ require.Equal(t, "Configured", general.GetGeneralSetting().GetCustomProfile().GetTitle())
+ require.NoError(t, tx.DeleteInstanceSetting(ctx, storepb.InstanceSettingKey_MEMO_RELATED))
+
+ created, err := tx.CreateUser(ctx, &store.User{Username: "admin", Role: store.RoleAdmin, Email: " [email protected] ", PasswordHash: "hash"})
+ require.NoError(t, err)
+ role := store.RoleUser
+ nickname := "Demoted"
+ require.NoError(t, tx.UpdateUser(ctx, &store.UpdateUser{ID: existing.ID, Role: &role, Nickname: &nickname}))
+ users, err := tx.ListUsers(ctx, &store.FindUser{UsernameList: []string{"admin", "existing"}})
+ require.NoError(t, err)
+ require.Len(t, users, 2)
+ require.Equal(t, "[email protected]", created.Email, "the email is normalized as the store's writes do")
+ return &storepb.InstanceConfigurationState{}, nil
+ })
+ require.NoError(t, err)
+
+ provider, err := ts.GetIdentityProvider(ctx, &store.FindIdentityProvider{UID: new("sso")})
+ require.NoError(t, err)
+ require.Equal(t, "Renamed SSO", provider.Name)
+ require.Equal(t, []string{"openid"}, provider.Config.GetOauth2Config().Scopes)
+ general, err := ts.GetInstanceGeneralSetting(ctx)
+ require.NoError(t, err)
+ require.Equal(t, "Configured", general.GetCustomProfile().GetTitle(), "the commit invalidated the cached setting")
+ memoRelated, err := ts.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: "MEMO_RELATED"})
+ require.NoError(t, err)
+ require.Nil(t, memoRelated)
+ demoted, err := ts.GetUser(ctx, &store.FindUser{ID: &existing.ID})
+ require.NoError(t, err)
+ require.Equal(t, store.RoleUser, demoted.Role)
+ require.Equal(t, "Demoted", demoted.Nickname, "the commit invalidated the cached user")
+}
+
+func TestConfigurationTransactionRollsBack(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ ts := NewTestingStore(ctx, t)
+ t.Cleanup(func() { require.NoError(t, ts.Close()) })
+ only, err := ts.CreateUser(ctx, &store.User{Username: "only", Role: store.RoleAdmin, PasswordHash: "hash"})
+ require.NoError(t, err)
+
+ _, err = ts.RunConfigurationTransaction(ctx, func(ctx context.Context, tx *store.ConfigurationTransaction) (*storepb.InstanceConfigurationState, error) {
+ require.NoError(t, tx.CreateIdentityProvider(ctx, createTestOAuth2IDP("SSO", "sso")))
+ role := store.RoleUser
+ // Demoting the last administrator fails as it does through the API,
+ // and the whole transaction rolls back with it.
+ return nil, tx.UpdateUser(ctx, &store.UpdateUser{ID: only.ID, Role: &role})
+ })
+ require.ErrorIs(t, err, store.ErrLastInstanceAdmin)
+
+ providers, err := ts.ListIdentityProviders(ctx, &store.FindIdentityProvider{})
+ require.NoError(t, err)
+ require.Empty(t, providers, "nothing from the failed transaction remains")
+ state, err := ts.GetConfigurationState(ctx)
+ require.NoError(t, err)
+ require.Zero(t, state.Serial)
+}
diff --git a/store/test/instance_setting_test.go b/store/test/instance_setting_test.go
index 1079151e2..4467a9013 100644
--- a/store/test/instance_setting_test.go
+++ b/store/test/instance_setting_test.go
@@ -174,7 +174,7 @@ func TestInstanceAccessSetting(t *testing.T) {
})
require.NoError(t, err)
- stored, err := ts.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_ACCESS.String()})
+ stored, err := ts.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_ACCESS.String()})
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC, stored.GetAccessSetting().AccessMode)
@@ -344,7 +344,7 @@ func TestDeleteInstanceStorageSettingInvalidatesCaches(t *testing.T) {
err = ts.DeleteInstanceSetting(ctx, &store.DeleteInstanceSetting{Name: storepb.InstanceSettingKey_STORAGE.String()})
require.NoError(t, err)
- stored, err := ts.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_STORAGE.String()})
+ stored, err := ts.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_STORAGE.String()})
require.NoError(t, err)
require.Nil(t, stored)
defaultSetting, err := ts.GetInstanceStorageSetting(ctx)
diff --git a/store/test/migrator_test.go b/store/test/migrator_test.go
index d3bd52686..dcc03d3d1 100644
--- a/store/test/migrator_test.go
+++ b/store/test/migrator_test.go
@@ -239,7 +239,7 @@ func TestConcurrentInstanceAccessInitializationKeepsFirstInsert(t *testing.T) {
released = true
require.NoError(t, <-publicMigration)
- setting, err := privateStore.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{
+ setting, err := privateStore.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{
Name: storepb.InstanceSettingKey_ACCESS.String(),
})
require.NoError(t, err)
@@ -248,9 +248,24 @@ func TestConcurrentInstanceAccessInitializationKeepsFirstInsert(t *testing.T) {
// Re-running either initializer is also a no-op once ACCESS is persisted.
require.NoError(t, publicStore.Migrate(ctx))
- setting, err = publicStore.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{
+ setting, err = publicStore.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{
Name: storepb.InstanceSettingKey_ACCESS.String(),
})
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, setting.GetAccessSetting().AccessMode)
}
+
+func TestCheckSchemaCurrent(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ ts := NewTestingStore(ctx, t)
+ t.Cleanup(func() { require.NoError(t, ts.Close()) })
+ require.NoError(t, ts.CheckSchemaCurrent(ctx), "a migrated database is current")
+
+ basic, err := ts.GetInstanceBasicSetting(ctx)
+ require.NoError(t, err)
+ basic.SchemaVersion = "0.31.8"
+ _, err = ts.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{Key: storepb.InstanceSettingKey_BASIC, Value: &storepb.InstanceSetting_BasicSetting{BasicSetting: basic}})
+ require.NoError(t, err)
+ require.ErrorContains(t, ts.CheckSchemaCurrent(ctx), "start this version of Memos once to migrate it")
+}
diff --git a/store/test/usage_limit_test.go b/store/test/usage_limit_test.go
index 253c5d1dd..5b5dc903b 100644
--- a/store/test/usage_limit_test.go
+++ b/store/test/usage_limit_test.go
@@ -2,9 +2,6 @@ package test
import (
"context"
- "fmt"
- "os"
- "path/filepath"
"testing"
"github.com/stretchr/testify/require"
@@ -131,7 +128,7 @@ func TestUsageLimitsDefaultSetting(t *testing.T) {
require.Equal(t, store.DefaultMemoContentBytes, setting.Limits[0].GetMemoContentBytes())
require.Nil(t, setting.Limits[0].MemoCount)
require.Nil(t, setting.Limits[0].StorageBytes)
- stored, err := ts.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_USAGE_LIMITS.String()})
+ stored, err := ts.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_USAGE_LIMITS.String()})
require.NoError(t, err)
require.Nil(t, stored, "reading defaults does not persist a setting")
@@ -148,7 +145,7 @@ func TestUsageLimitsDefaultSetting(t *testing.T) {
require.Nil(t, setting.Limits[0].MemoContentBytes, "the stored list is the whole truth; built-in defaults do not come back")
// The row round-trips through the generic setting reads too.
- stored, err = ts.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_USAGE_LIMITS.String()})
+ stored, err = ts.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_USAGE_LIMITS.String()})
require.NoError(t, err)
require.True(t, proto.Equal(setting, stored.GetUsageLimitsSetting()))
}
@@ -209,7 +206,7 @@ func TestUpsertInstanceSettingValidatesUsageLimits(t *testing.T) {
Value: &storepb.InstanceSetting_UsageLimitsSetting{UsageLimitsSetting: usageLimitsSetting(&usageLimitEntry{UserIds: []int32{1}})},
})
require.ErrorIs(t, err, store.ErrInvalidUsageLimits)
- stored, err := ts.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_USAGE_LIMITS.String()})
+ stored, err := ts.GetUncachedInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_USAGE_LIMITS.String()})
require.NoError(t, err)
require.Nil(t, stored, "an invalid write stores nothing")
@@ -251,53 +248,3 @@ func TestDeleteUserRemovesFromUsageLimits(t *testing.T) {
require.NoError(t, ts.RemoveUserFromUsageLimits(ctx, 99999), "an unknown user is a no-op")
require.Equal(t, [][]int32{{bob.ID}, {bob.ID}, nil}, storedUserIDs(ctx, t, ts))
}
-
-func TestUsageLimitsDeploymentFile(t *testing.T) {
- t.Parallel()
- ctx := context.Background()
- ts := NewTestingStore(ctx, t)
- defer ts.Close()
- alice, err := ts.CreateUser(ctx, &store.User{Username: "alice", Role: store.RoleUser, PasswordHash: "hash"})
- require.NoError(t, err)
- writeUsageLimits(ctx, t, ts, &usageLimitEntry{AllUsers: true, MemoCount: new(int64(10))})
-
- dir := t.TempDir()
- path := filepath.Join(dir, "memos-instance-setting-usage-limits.json")
- require.NoError(t, os.WriteFile(path, []byte(`{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[
- {"userIds":[`+fmt.Sprint(alice.ID)+`],"storageBytes":"5368709120"},
- {"allUsers":true,"storageBytes":"1073741824"}
- ]}}`), 0o600))
- require.NoError(t, ts.LoadDeploymentConfigurationDir(ctx, dir))
-
- effective, err := ts.GetInstanceUsageLimitsSetting(ctx)
- require.NoError(t, err)
- require.Len(t, effective.Limits, 2, "the file shadows the stored row")
- require.Equal(t, []int32{alice.ID}, effective.Limits[0].UserIds)
- require.Equal(t, int64(5<<30), effective.Limits[0].GetStorageBytes())
- require.True(t, effective.Limits[1].AllUsers)
- require.Nil(t, effective.Limits[1].MemoCount)
- require.True(t, ts.IsInstanceSettingDeploymentConfigured(storepb.InstanceSettingKey_USAGE_LIMITS))
- require.NoError(t, ts.RemoveUserFromUsageLimits(ctx, alice.ID), "user deletion cleanup skips file-provided limits")
-
- stored, err := ts.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_USAGE_LIMITS.String()})
- require.NoError(t, err)
- require.Equal(t, int64(10), stored.GetUsageLimitsSetting().Limits[0].GetMemoCount(), "the stored row is unchanged")
-
- for name, content := range map[string]string{
- "missing value": `{"key":"USAGE_LIMITS"}`,
- "negative value": `{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[{"allUsers":true,"memoCount":"-1"}]}}`,
- "no all-users entry": `{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[{"userIds":[1],"memoCount":"1"}]}}`,
- "all users not last": `{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[{"allUsers":true},{"userIds":[1]}]}}`,
- "users and all users": `{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[{"allUsers":true,"userIds":[1]}]}}`,
- "user resource names": `{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[{"users":["users/alice"]},{"allUsers":true}]}}`,
- "unknown field": `{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[{"allUsers":true,"plan":"pro"}]}}`,
- "old per-metric shape": `{"key":"USAGE_LIMITS","usageLimitsSetting":{"limits":[{"uid":"a","metric":"MEMO_COUNT","allUsers":{},"value":"1"}]}}`,
- } {
- invalidDir := t.TempDir()
- require.NoError(t, os.WriteFile(filepath.Join(invalidDir, "memos-instance-setting-usage-limits.json"), []byte(content), 0o600))
- require.Error(t, ts.LoadDeploymentConfigurationDir(ctx, invalidDir), name)
- effective, err := ts.GetInstanceUsageLimitsSetting(ctx)
- require.NoError(t, err)
- require.Len(t, effective.Limits, 2, "an invalid reload preserves the active configuration: %s", name)
- }
-}
diff --git a/store/transaction.go b/store/transaction.go
new file mode 100644
index 000000000..52dd48eb7
--- /dev/null
+++ b/store/transaction.go
@@ -0,0 +1,61 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ stderrors "errors"
+ "math/rand/v2"
+ "time"
+
+ "github.com/pkg/errors"
+)
+
+// serializableMaxAttempts bounds how many times runSerializable runs a
+// transaction that conflicted with a concurrent one.
+const serializableMaxAttempts = 5
+
+// errTransactionConflict is returned by a transaction body that found a
+// concurrent writer had changed what it read, so the body runs again.
+var errTransactionConflict = stderrors.New("transaction conflicted with a concurrent write")
+
+// runSerializable runs fn in one serializable transaction and commits it when
+// fn returns nil. When the database reports a serialization or locking
+// conflict, or fn returns errTransactionConflict, the transaction is rolled
+// back and fn runs again, up to serializableMaxAttempts times, so fn must
+// derive everything it writes from what it reads inside tx.
+func (s *Store) runSerializable(ctx context.Context, fn func(tx *sql.Tx) error) error {
+ var err error
+ for attempt := range serializableMaxAttempts {
+ err = s.runSerializableOnce(ctx, fn)
+ retryable := errors.Is(err, errTransactionConflict) || s.driver.IsRetryableTransactionError(err)
+ if err == nil || !retryable {
+ return err
+ }
+ // Jitter keeps transactions that conflicted once from retrying in lockstep
+ // and conflicting again.
+ backoff := time.Duration(attempt+1)*10*time.Millisecond + rand.N(10*time.Millisecond)
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(backoff):
+ }
+ }
+ return errors.Wrap(err, "serializable transaction failed after retries")
+}
+
+func (s *Store) runSerializableOnce(ctx context.Context, fn func(tx *sql.Tx) error) error {
+ tx, err := s.driver.GetDB().BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
+ if err != nil {
+ return errors.Wrap(err, "failed to begin serializable transaction")
+ }
+ defer func() {
+ _ = tx.Rollback()
+ }()
+ if err := fn(tx); err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return errors.Wrap(err, "failed to commit serializable transaction")
+ }
+ return nil
+}
diff --git a/store/usage_limit.go b/store/usage_limit.go
index 0ae081f71..0b518ec84 100644
--- a/store/usage_limit.go
+++ b/store/usage_limit.go
@@ -113,19 +113,14 @@ func ValidateInstanceUsageLimitsSetting(setting *storepb.InstanceUsageLimitsSett
return nil
}
-// GetInstanceUsageLimitsSetting returns the usage limits setting. A deployment
-// file takes precedence over the database. The database row is read directly,
-// without the instance setting cache, so a change made through any replica
-// applies at the next check on every replica. An absent setting is
-// DefaultInstanceUsageLimitsSetting.
+// GetInstanceUsageLimitsSetting returns the usage limits setting. The database
+// row is read directly, without the instance setting cache, so a change made
+// through any replica applies at the next check on every replica. An absent
+// setting is DefaultInstanceUsageLimitsSetting.
func (s *Store) GetInstanceUsageLimitsSetting(ctx context.Context) (*storepb.InstanceUsageLimitsSetting, error) {
- instanceSetting := s.getDeploymentInstanceSetting(storepb.InstanceSettingKey_USAGE_LIMITS)
- if instanceSetting == nil {
- var err error
- instanceSetting, err = s.getRawInstanceSetting(ctx, storepb.InstanceSettingKey_USAGE_LIMITS.String())
- if err != nil {
- return nil, errors.Wrap(err, "failed to get usage limits setting")
- }
+ instanceSetting, err := s.GetUncachedInstanceSetting(ctx, &FindInstanceSetting{Name: storepb.InstanceSettingKey_USAGE_LIMITS.String()})
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get usage limits setting")
}
if setting := instanceSetting.GetUsageLimitsSetting(); setting != nil {
if err := ValidateInstanceUsageLimitsSetting(setting); err != nil {
@@ -137,11 +132,9 @@ func (s *Store) GetInstanceUsageLimitsSetting(ctx context.Context) (*storepb.Ins
}
// RemoveUserFromUsageLimits drops userID from every entry of the stored usage
-// limits, and drops entries left without users. It does nothing when the
-// limits come from a deployment file, because the store cannot change them;
-// an entry naming a missing user never matches anyone.
+// limits, and drops entries left without users.
func (s *Store) RemoveUserFromUsageLimits(ctx context.Context, userID int32) error {
- if userID == 0 || s.IsInstanceSettingDeploymentConfigured(storepb.InstanceSettingKey_USAGE_LIMITS) {
+ if userID == 0 {
return nil
}
name := storepb.InstanceSettingKey_USAGE_LIMITS.String()
diff --git a/web/src/components/CreateUserDialog.tsx b/web/src/components/CreateUserDialog.tsx
index 8caf68ac8..f92e22616 100644
--- a/web/src/components/CreateUserDialog.tsx
+++ b/web/src/components/CreateUserDialog.tsx
@@ -8,10 +8,12 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { userServiceClient } from "@/connect";
+import { isFieldManaged, useManagedResource } from "@/hooks/useConfigurationQueries";
import useLoading from "@/hooks/useLoading";
import { handleError } from "@/lib/error";
import { User, User_Role, UserSchema } from "@/types/proto/api/user_service_pb";
import { useTranslate } from "@/utils/i18n";
+import ManagedByConfigurationChip from "./Settings/ManagedByConfigurationChip";
interface Props {
open: boolean;
@@ -27,6 +29,8 @@ function CreateUserDialog({ open, onOpenChange, user: initialUser, onSuccess }:
);
const requestState = useLoading(false);
const isCreating = !initialUser;
+ // The password is write-only, so configuration never locks it.
+ const managed = useManagedResource(initialUser?.name ?? "");
useEffect(() => {
if (initialUser) {
@@ -85,6 +89,11 @@ function CreateUserDialog({ open, onOpenChange, user: initialUser, onSuccess }:
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>{`${isCreating ? t("common.create") : t("common.edit")} ${t("common.user")}`}</DialogTitle>
+ {managed ? (
+ <div className="flex">
+ <ManagedByConfigurationChip resource={managed} />
+ </div>
+ ) : null}
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="grid gap-2">
@@ -93,6 +102,7 @@ function CreateUserDialog({ open, onOpenChange, user: initialUser, onSuccess }:
id="username"
type="text"
placeholder={t("common.username")}
+ disabled={isFieldManaged(managed, "username")}
value={user.username}
onChange={(e) =>
setPartialUser({
@@ -119,6 +129,7 @@ function CreateUserDialog({ open, onOpenChange, user: initialUser, onSuccess }:
<div className="grid gap-2">
<Label>{t("common.role")}</Label>
<RadioGroup
+ disabled={isFieldManaged(managed, "role")}
value={String(user.role)}
onValueChange={(value) => setPartialUser({ role: Number(value) as User_Role })}
className="flex flex-row gap-4"
diff --git a/web/src/components/Settings/AISection.tsx b/web/src/components/Settings/AISection.tsx
index e1a8221f9..489ab4368 100644
--- a/web/src/components/Settings/AISection.tsx
+++ b/web/src/components/Settings/AISection.tsx
@@ -13,6 +13,7 @@ import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useInstance } from "@/contexts/InstanceContext";
+import { isFieldManaged, useManagedResource } from "@/hooks/useConfigurationQueries";
import {
InstanceSetting_AIProviderConfig,
InstanceSetting_AIProviderConfigSchema,
@@ -24,6 +25,7 @@ import {
InstanceSettingSchema,
} from "@/types/proto/api/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
+import ManagedByConfigurationChip from "./ManagedByConfigurationChip";
import SettingGroup from "./SettingGroup";
import { SettingPanel } from "./SettingList";
import SettingSection from "./SettingSection";
@@ -103,6 +105,9 @@ const toTranscriptionConfig = (transcription: LocalTranscription) =>
const AISection = () => {
const t = useTranslate();
+ const managed = useManagedResource(buildInstanceSettingName(InstanceSetting_Key.AI));
+ const providersLocked = isFieldManaged(managed, "aiSetting.providers");
+ const transcriptionLocked = isFieldManaged(managed, "aiSetting.transcription");
const saveInstanceSetting = useInstanceSettingUpdater();
const { aiSetting: originalSetting } = useInstance();
const [providers, setProviders] = useState<LocalAIProvider[]>(() => originalSetting.providers.map(toLocalProvider));
@@ -227,7 +232,7 @@ const AISection = () => {
<SettingSection
title={t("setting.ai.label")}
actions={
- <Button onClick={handleCreateProvider}>
+ <Button disabled={providersLocked} onClick={handleCreateProvider}>
<PlusIcon className="w-4 h-4 mr-2" />
{t("setting.ai.add-provider")}
</Button>
@@ -253,7 +258,11 @@ const AISection = () => {
</div>
</SettingPanel>
- <SettingGroup title={t("setting.ai.integrations-title")} description={t("setting.ai.integrations-description")}>
+ <SettingGroup
+ title={t("setting.ai.integrations-title")}
+ description={t("setting.ai.integrations-description")}
+ actions={providersLocked ? <ManagedByConfigurationChip resource={managed} /> : undefined}
+ >
<SettingTable
columns={[
{
@@ -295,10 +304,14 @@ const AISection = () => {
<MoreVerticalIcon className="w-4 h-auto" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={2}>
- <DropdownMenuItem onClick={() => handleEditProvider(provider)}>{t("common.edit")}</DropdownMenuItem>
- <DropdownMenuItem onClick={() => setDeleteTarget(provider)} className="text-destructive focus:text-destructive">
- {t("common.delete")}
+ <DropdownMenuItem disabled={providersLocked} onClick={() => handleEditProvider(provider)}>
+ {t("common.edit")}
</DropdownMenuItem>
+ {providersLocked ? null : (
+ <DropdownMenuItem onClick={() => setDeleteTarget(provider)} className="text-destructive focus:text-destructive">
+ {t("common.delete")}
+ </DropdownMenuItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
),
@@ -315,12 +328,16 @@ const AISection = () => {
description={t("setting.ai.transcription-description")}
showSeparator
actions={
- <Button disabled={!transcriptionHasChanges} onClick={handleSaveTranscription}>
- {t("common.save")}
- </Button>
+ <>
+ {transcriptionLocked ? <ManagedByConfigurationChip resource={managed} /> : null}
+ <Button disabled={transcriptionLocked || !transcriptionHasChanges} onClick={handleSaveTranscription}>
+ {t("common.save")}
+ </Button>
+ </>
}
>
<TranscriptionForm
+ locked={transcriptionLocked}
providers={providers}
transcription={transcription}
onChange={setTranscription}
@@ -348,15 +365,17 @@ const AISection = () => {
};
interface TranscriptionFormProps {
+ locked: boolean;
providers: LocalAIProvider[];
transcription: LocalTranscription;
referencedProvider: LocalAIProvider | undefined;
onChange: (next: LocalTranscription) => void;
}
-const TranscriptionForm = ({ providers, transcription, referencedProvider, onChange }: TranscriptionFormProps) => {
+const TranscriptionForm = ({ locked, providers, transcription, referencedProvider, onChange }: TranscriptionFormProps) => {
const t = useTranslate();
const noProviders = providers.length === 0;
+ const fieldsDisabled = locked || !transcription.providerId;
const providerOptions = useMemo(
() => [
@@ -385,7 +404,7 @@ const TranscriptionForm = ({ providers, transcription, referencedProvider, onCha
value={transcription.providerId || "__none__"}
items={providerOptions}
onValueChange={(value) => update({ providerId: value === "__none__" ? "" : value })}
- disabled={noProviders}
+ disabled={locked || noProviders}
>
<SelectTrigger className="w-full">
<SelectValue />
@@ -410,7 +429,7 @@ const TranscriptionForm = ({ providers, transcription, referencedProvider, onCha
value={transcription.model}
onChange={(e) => update({ model: e.target.value })}
placeholder={placeholderForProvider(referencedProvider)}
- disabled={!transcription.providerId}
+ disabled={fieldsDisabled}
maxLength={256}
/>
<p className="text-xs text-muted-foreground">{t("setting.ai.transcription-model-help")}</p>
@@ -422,7 +441,7 @@ const TranscriptionForm = ({ providers, transcription, referencedProvider, onCha
value={transcription.language}
onChange={(e) => update({ language: e.target.value })}
placeholder={t("setting.ai.transcription-language-placeholder")}
- disabled={!transcription.providerId}
+ disabled={fieldsDisabled}
maxLength={32}
/>
<p className="text-xs text-muted-foreground">{t("setting.ai.transcription-language-help")}</p>
@@ -435,7 +454,7 @@ const TranscriptionForm = ({ providers, transcription, referencedProvider, onCha
onChange={(e) => update({ prompt: e.target.value })}
placeholder={t("setting.ai.transcription-prompt-placeholder")}
rows={3}
- disabled={!transcription.providerId}
+ disabled={fieldsDisabled}
maxLength={4096}
/>
<p className="text-xs text-muted-foreground">{t("setting.ai.transcription-prompt-help")}</p>
diff --git a/web/src/components/Settings/ConfigurationSection.tsx b/web/src/components/Settings/ConfigurationSection.tsx
new file mode 100644
index 000000000..149743410
--- /dev/null
+++ b/web/src/components/Settings/ConfigurationSection.tsx
@@ -0,0 +1,71 @@
+import { timestampDate } from "@bufbuild/protobuf/wkt";
+import { useConfigurationStatus } from "@/hooks/useConfigurationQueries";
+import type { ConfigurationStatus_ManagedResource } from "@/types/proto/api/instance_service_pb";
+import { useTranslate } from "@/utils/i18n";
+import InfoChip from "./InfoChip";
+import SettingSection from "./SettingSection";
+import SettingTable from "./SettingTable";
+
+interface ManagedResourceRow extends Record<string, unknown> {
+ resource: ConfigurationStatus_ManagedResource;
+}
+
+// What configuration files manage, read-only: changing it means editing a file.
+const ConfigurationSection = () => {
+ const t = useTranslate();
+ const status = useConfigurationStatus();
+ const rows: ManagedResourceRow[] = (status?.managedResources ?? []).map((resource) => ({ resource }));
+
+ return (
+ <SettingSection title={t("setting.configuration.label")} description={t("setting.configuration.description")}>
+ {status && status.serial > 0n ? (
+ <div className="flex flex-wrap gap-2">
+ <InfoChip label={t("setting.configuration.serial")} value={status.serial.toString()} />
+ {status.applyTime ? (
+ <InfoChip label={t("setting.configuration.last-apply")} value={timestampDate(status.applyTime).toLocaleString()} />
+ ) : null}
+ <InfoChip label={t("setting.configuration.applied-by")} value={`${status.appliedBy} · ${status.version}`} />
+ </div>
+ ) : null}
+ <SettingTable
+ variant="info-flow"
+ columns={[
+ {
+ key: "resource",
+ header: t("setting.configuration.resource"),
+ render: (_, row: ManagedResourceRow) => <span className="font-mono text-xs text-foreground">{row.resource.resource}</span>,
+ },
+ {
+ key: "source",
+ header: t("setting.configuration.source"),
+ render: (_, row: ManagedResourceRow) => <span className="text-sm text-muted-foreground">{row.resource.source}</span>,
+ },
+ {
+ key: "fields",
+ header: t("setting.configuration.managed-fields"),
+ render: (_, row: ManagedResourceRow) => (
+ <div className="flex flex-wrap gap-2">
+ <InfoChip
+ label={t("setting.configuration.managed-fields")}
+ value={
+ row.resource.managedFields.includes("*")
+ ? t("setting.configuration.whole-resource")
+ : row.resource.managedFields.join(", ")
+ }
+ />
+ {row.resource.ignoredFields.length > 0 ? (
+ <InfoChip label={t("setting.configuration.ignored-fields")} value={row.resource.ignoredFields.join(", ")} />
+ ) : null}
+ </div>
+ ),
+ },
+ ]}
+ data={rows}
+ emptyMessage={t("setting.configuration.nothing-managed")}
+ getRowKey={(row) => row.resource.resource}
+ />
+ </SettingSection>
+ );
+};
+
+export default ConfigurationSection;
diff --git a/web/src/components/Settings/InstanceSection.tsx b/web/src/components/Settings/InstanceSection.tsx
index d2fd34510..ce72a97b3 100644
--- a/web/src/components/Settings/InstanceSection.tsx
+++ b/web/src/components/Settings/InstanceSection.tsx
@@ -7,6 +7,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Switch } from "@/components/ui/switch";
import { identityProviderServiceClient } from "@/connect";
import { useInstance } from "@/contexts/InstanceContext";
+import { isFieldManaged, useManagedResource } from "@/hooks/useConfigurationQueries";
import useDialog from "@/hooks/useDialog";
import { IdentityProvider } from "@/types/proto/api/idp_service_pb";
import {
@@ -20,6 +21,7 @@ import {
} from "@/types/proto/api/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
import UpdateCustomizedProfileDialog from "../UpdateCustomizedProfileDialog";
+import ManagedByConfigurationChip from "./ManagedByConfigurationChip";
import SettingGroup from "./SettingGroup";
import { SettingCodeEditor, SettingList, SettingListItem } from "./SettingList";
import SettingSection from "./SettingSection";
@@ -33,6 +35,13 @@ const InstanceSection = () => {
const [instanceAccessSetting, setInstanceAccessSetting] = useState<InstanceSetting_AccessSetting>(originalAccessSetting);
const [instanceGeneralSetting, setInstanceGeneralSetting] = useState<InstanceSetting_GeneralSetting>(originalGeneralSetting);
const [identityProviderList, setIdentityProviderList] = useState<IdentityProvider[]>([]);
+ const managedGeneral = useManagedResource(buildInstanceSettingName(InstanceSetting_Key.GENERAL));
+ const managedAccess = useManagedResource(buildInstanceSettingName(InstanceSetting_Key.ACCESS));
+ const generalLocked = (field: string) => isFieldManaged(managedGeneral, `generalSetting.${field}`);
+ const accessLocked = isFieldManaged(managedAccess, "accessSetting.accessMode");
+ // A group names its configuration file only when one of its own fields is managed.
+ const groupChip = (locked: boolean, resource = managedGeneral) =>
+ locked ? <ManagedByConfigurationChip resource={resource} /> : undefined;
useEffect(() => {
setInstanceAccessSetting(originalAccessSetting);
@@ -115,16 +124,21 @@ const InstanceSection = () => {
return (
<SettingSection title={t("setting.system.label")}>
- <SettingGroup title={t("common.basic")} description={t("setting.system.basic-description")}>
+ <SettingGroup
+ title={t("common.basic")}
+ description={t("setting.system.basic-description")}
+ actions={groupChip(generalLocked("customProfile") || generalLocked("weekStartDayOffset"))}
+ >
<SettingList>
<SettingListItem label={t("setting.system.server-name")} description={instanceGeneralSetting.customProfile?.title || "Memos"}>
- <Button variant="outline" onClick={customizeDialog.open}>
+ <Button variant="outline" disabled={generalLocked("customProfile")} onClick={customizeDialog.open}>
{t("common.edit")}
</Button>
</SettingListItem>
<SettingListItem label={t("setting.instance.week-start-day")} description={t("setting.instance.week-start-day-description")}>
<Select
+ disabled={generalLocked("weekStartDayOffset")}
value={instanceGeneralSetting.weekStartDayOffset.toString()}
items={weekStartDayOptions}
onValueChange={(value) => {
@@ -146,14 +160,24 @@ const InstanceSection = () => {
</SettingList>
</SettingGroup>
- <SettingGroup title={t("setting.instance.access-title")} description={t("setting.instance.access-description")} showSeparator>
+ <SettingGroup
+ title={t("setting.instance.access-title")}
+ description={t("setting.instance.access-description")}
+ showSeparator
+ actions={
+ groupChip(accessLocked, managedAccess) ??
+ groupChip(
+ ["disallowUserRegistration", "disallowPasswordAuth", "disallowChangeUsername", "disallowChangeNickname"].some(generalLocked),
+ )
+ }
+ >
<SettingList>
<SettingListItem
label={t("setting.instance.allow-public-access")}
description={t("setting.instance.allow-public-access-description")}
>
<Switch
- disabled={profile.demo}
+ disabled={profile.demo || accessLocked}
checked={instanceAccessSetting.accessMode === InstanceAccessMode.PUBLIC}
onCheckedChange={(checked) => updateAccessMode(checked ? InstanceAccessMode.PUBLIC : InstanceAccessMode.PRIVATE)}
/>
@@ -164,7 +188,7 @@ const InstanceSection = () => {
description={t("setting.instance.disallow-user-registration-description")}
>
<Switch
- disabled={profile.demo}
+ disabled={profile.demo || generalLocked("disallowUserRegistration")}
checked={instanceGeneralSetting.disallowUserRegistration}
onCheckedChange={(checked) => updatePartialSetting({ disallowUserRegistration: checked })}
/>
@@ -175,7 +199,11 @@ const InstanceSection = () => {
description={t("setting.instance.disallow-password-auth-description")}
>
<Switch
- disabled={profile.demo || (identityProviderList.length === 0 && !instanceGeneralSetting.disallowPasswordAuth)}
+ disabled={
+ profile.demo ||
+ generalLocked("disallowPasswordAuth") ||
+ (identityProviderList.length === 0 && !instanceGeneralSetting.disallowPasswordAuth)
+ }
checked={instanceGeneralSetting.disallowPasswordAuth}
onCheckedChange={(checked) => updatePartialSetting({ disallowPasswordAuth: checked })}
/>
@@ -186,6 +214,7 @@ const InstanceSection = () => {
description={t("setting.instance.disallow-change-username-description")}
>
<Switch
+ disabled={generalLocked("disallowChangeUsername")}
checked={instanceGeneralSetting.disallowChangeUsername}
onCheckedChange={(checked) => updatePartialSetting({ disallowChangeUsername: checked })}
/>
@@ -196,6 +225,7 @@ const InstanceSection = () => {
description={t("setting.instance.disallow-change-nickname-description")}
>
<Switch
+ disabled={generalLocked("disallowChangeNickname")}
checked={instanceGeneralSetting.disallowChangeNickname}
onCheckedChange={(checked) => updatePartialSetting({ disallowChangeNickname: checked })}
/>
@@ -203,12 +233,18 @@ const InstanceSection = () => {
</SettingList>
</SettingGroup>
- <SettingGroup title={t("setting.system.custom-code-title")} description={t("setting.system.custom-code-description")} showSeparator>
+ <SettingGroup
+ title={t("setting.system.custom-code-title")}
+ description={t("setting.system.custom-code-description")}
+ showSeparator
+ actions={groupChip(generalLocked("additionalStyle") || generalLocked("additionalScript"))}
+ >
<SettingCodeEditor
label={t("setting.system.additional-style")}
description={t("setting.system.additional-style-description")}
placeholder={t("setting.system.additional-style-placeholder")}
value={instanceGeneralSetting.additionalStyle}
+ disabled={generalLocked("additionalStyle")}
onChange={(additionalStyle) => updatePartialSetting({ additionalStyle })}
/>
@@ -217,6 +253,7 @@ const InstanceSection = () => {
description={t("setting.system.additional-script-description")}
placeholder={t("setting.system.additional-script-placeholder")}
value={instanceGeneralSetting.additionalScript}
+ disabled={generalLocked("additionalScript")}
onChange={(additionalScript) => updatePartialSetting({ additionalScript })}
/>
</SettingGroup>
diff --git a/web/src/components/Settings/ManagedByConfigurationChip.tsx b/web/src/components/Settings/ManagedByConfigurationChip.tsx
new file mode 100644
index 000000000..e7c0dac67
--- /dev/null
+++ b/web/src/components/Settings/ManagedByConfigurationChip.tsx
@@ -0,0 +1,24 @@
+import type { ConfigurationStatus_ManagedResource } from "@/types/proto/api/instance_service_pb";
+import { useTranslate } from "@/utils/i18n";
+import InfoChip from "./InfoChip";
+
+interface Props {
+ resource?: ConfigurationStatus_ManagedResource;
+}
+
+// Marks a resource configuration files manage, naming the file to edit.
+const ManagedByConfigurationChip = ({ resource }: Props) => {
+ const t = useTranslate();
+ if (!resource) {
+ return null;
+ }
+ return (
+ <InfoChip
+ label={t("setting.configuration.managed-by")}
+ value={resource.source}
+ tooltip={t("setting.configuration.managed-tooltip", { source: resource.source })}
+ />
+ );
+};
+
+export default ManagedByConfigurationChip;
diff --git a/web/src/components/Settings/MemberSection.tsx b/web/src/components/Settings/MemberSection.tsx
index 95030ba31..dbdbc685b 100644
--- a/web/src/components/Settings/MemberSection.tsx
+++ b/web/src/components/Settings/MemberSection.tsx
@@ -10,6 +10,7 @@ import UserAvatar from "@/components/UserAvatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { userServiceClient } from "@/connect";
+import { findManagedResource, useConfigurationStatus } from "@/hooks/useConfigurationQueries";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useDialog } from "@/hooks/useDialog";
import { useDeleteUser, useListUsers } from "@/hooks/useUserQueries";
@@ -19,11 +20,13 @@ import { User, User_Role } from "@/types/proto/api/user_service_pb";
import { useTranslate } from "@/utils/i18n";
import CreateUserDialog from "../CreateUserDialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "../ui/dropdown-menu";
+import ManagedByConfigurationChip from "./ManagedByConfigurationChip";
import SettingSection from "./SettingSection";
import SettingTable from "./SettingTable";
const MemberSection = () => {
const t = useTranslate();
+ const configurationStatus = useConfigurationStatus();
const currentUser = useCurrentUser();
const { data: users = [], refetch: refetchUsers } = useListUsers();
const deleteUserMutation = useDeleteUser();
@@ -153,9 +156,10 @@ const MemberSection = () => {
{user.state === State.ARCHIVED ? t("setting.member.archived") : t("setting.member.active")}
</Badge>
</div>
- {user.email ? (
+ {user.email || findManagedResource(configurationStatus, user.name) ? (
<div className="flex flex-wrap gap-2">
- <InfoChip label={t("common.email")} value={user.email} tooltip={user.email} />
+ {user.email ? <InfoChip label={t("common.email")} value={user.email} tooltip={user.email} /> : null}
+ <ManagedByConfigurationChip resource={findManagedResource(configurationStatus, user.name)} />
</div>
) : null}
</div>
@@ -178,9 +182,11 @@ const MemberSection = () => {
) : (
<>
<DropdownMenuItem onClick={() => handleRestoreUserClick(user)}>{t("common.restore")}</DropdownMenuItem>
- <DropdownMenuItem onClick={() => handleDeleteUserClick(user)} className="text-destructive focus:text-destructive">
- {t("setting.member.delete-member")}
- </DropdownMenuItem>
+ {findManagedResource(configurationStatus, user.name) ? null : (
+ <DropdownMenuItem onClick={() => handleDeleteUserClick(user)} className="text-destructive focus:text-destructive">
+ {t("setting.member.delete-member")}
+ </DropdownMenuItem>
+ )}
</>
)}
</DropdownMenuContent>
diff --git a/web/src/components/Settings/MemoRelatedSettings.tsx b/web/src/components/Settings/MemoRelatedSettings.tsx
index 53d4dcc49..d81a37605 100644
--- a/web/src/components/Settings/MemoRelatedSettings.tsx
+++ b/web/src/components/Settings/MemoRelatedSettings.tsx
@@ -7,6 +7,7 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useInstance } from "@/contexts/InstanceContext";
+import { isFieldManaged, useManagedResource } from "@/hooks/useConfigurationQueries";
import {
InstanceSetting_Key,
InstanceSetting_MemoRelatedSetting,
@@ -14,6 +15,7 @@ import {
InstanceSettingSchema,
} from "@/types/proto/api/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
+import ManagedByConfigurationChip from "./ManagedByConfigurationChip";
import SettingGroup from "./SettingGroup";
import { SettingPanel } from "./SettingList";
import SettingSection from "./SettingSection";
@@ -25,6 +27,8 @@ const MemoRelatedSettings = () => {
const { memoRelatedSetting: originalSetting } = useInstance();
const [memoRelatedSetting, setMemoRelatedSetting] = useState<InstanceSetting_MemoRelatedSetting>(originalSetting);
const [editingReaction, setEditingReaction] = useState<string>("");
+ const managed = useManagedResource(buildInstanceSettingName(InstanceSetting_Key.MEMO_RELATED));
+ const reactionsLocked = isFieldManaged(managed, "memoRelatedSetting.reactions");
useEffect(() => {
setMemoRelatedSetting(originalSetting);
@@ -69,7 +73,11 @@ const MemoRelatedSettings = () => {
return (
<SettingSection title={t("setting.memo.label")}>
- <SettingGroup title={t("setting.memo.reactions")} description={t("setting.memo.reactions-description")}>
+ <SettingGroup
+ title={t("setting.memo.reactions")}
+ description={t("setting.memo.reactions-description")}
+ actions={reactionsLocked ? <ManagedByConfigurationChip resource={managed} /> : undefined}
+ >
<SettingPanel
header={
<div className="flex items-center justify-between gap-3">
@@ -85,10 +93,11 @@ const MemoRelatedSettings = () => {
className="h-8 max-w-48 font-mono"
placeholder={t("setting.memo.reaction-placeholder")}
value={editingReaction}
+ disabled={reactionsLocked}
onChange={(event) => setEditingReaction(event.target.value)}
onKeyDown={(e) => e.key === "Enter" && upsertReaction()}
/>
- <Button variant="outline" size="sm" onClick={upsertReaction} disabled={!editingReaction.trim()}>
+ <Button variant="outline" size="sm" onClick={upsertReaction} disabled={reactionsLocked || !editingReaction.trim()}>
<CheckIcon className="w-4 h-4 mr-1.5" />
{t("setting.memo.add-reaction")}
</Button>
@@ -102,6 +111,7 @@ const MemoRelatedSettings = () => {
<Button
variant="ghost"
size="icon-sm"
+ disabled={reactionsLocked}
onClick={() => updatePartialSetting({ reactions: memoRelatedSetting.reactions.filter((r) => r !== reactionType) })}
aria-label={t("setting.memo.remove-reaction")}
>
diff --git a/web/src/components/Settings/NotificationSection.tsx b/web/src/components/Settings/NotificationSection.tsx
index f2aaf0637..f9e1375fd 100644
--- a/web/src/components/Settings/NotificationSection.tsx
+++ b/web/src/components/Settings/NotificationSection.tsx
@@ -9,6 +9,7 @@ import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { instanceServiceClient } from "@/connect";
import { useInstance } from "@/contexts/InstanceContext";
+import { isFieldManaged, useManagedResource } from "@/hooks/useConfigurationQueries";
import useCurrentUser from "@/hooks/useCurrentUser";
import { handleError } from "@/lib/error";
import {
@@ -21,11 +22,25 @@ import {
TestInstanceEmailSettingRequestSchema,
} from "@/types/proto/api/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
+import ManagedByConfigurationChip from "./ManagedByConfigurationChip";
import SettingGroup from "./SettingGroup";
import SettingRow from "./SettingRow";
import SettingSection from "./SettingSection";
import useInstanceSettingUpdater, { buildInstanceSettingName } from "./useInstanceSettingUpdater";
+const EMAIL_FIELDS = [
+ "enabled",
+ "smtpHost",
+ "smtpPort",
+ "smtpUsername",
+ "smtpPassword",
+ "fromEmail",
+ "fromName",
+ "replyTo",
+ "useTls",
+ "useSsl",
+];
+
const defaultEmailSetting = () =>
create(InstanceSetting_NotificationSetting_EmailSettingSchema, {
smtpPort: 587,
@@ -69,6 +84,8 @@ const FieldLabel = ({ label, requirementLabel, requirement }: { label: string; r
const NotificationSection = () => {
const t = useTranslate();
+ const managed = useManagedResource(buildInstanceSettingName(InstanceSetting_Key.NOTIFICATION));
+ const emailLocked = (field: string) => isFieldManaged(managed, `notificationSetting.email.${field}`);
const saveInstanceSetting = useInstanceSettingUpdater();
const currentUser = useCurrentUser();
const { notificationSetting: originalSetting } = useInstance();
@@ -173,9 +190,17 @@ const NotificationSection = () => {
return (
<SettingSection title={t("setting.notification.label")}>
- <SettingGroup title={t("setting.notification.email-title")} description={t("setting.notification.email-description")}>
+ <SettingGroup
+ title={t("setting.notification.email-title")}
+ description={t("setting.notification.email-description")}
+ actions={EMAIL_FIELDS.some(emailLocked) ? <ManagedByConfigurationChip resource={managed} /> : undefined}
+ >
<SettingRow label={t("setting.notification.email-enabled")} description={t("setting.notification.email-enabled-description")}>
- <Switch checked={emailSetting.enabled} onCheckedChange={(enabled) => updateEmailSetting({ enabled })} />
+ <Switch
+ disabled={emailLocked("enabled")}
+ checked={emailSetting.enabled}
+ onCheckedChange={(enabled) => updateEmailSetting({ enabled })}
+ />
</SettingRow>
<SettingRow
@@ -185,6 +210,7 @@ const NotificationSection = () => {
<Input
className="w-full sm:w-80"
value={emailSetting.smtpHost}
+ disabled={emailLocked("smtpHost")}
placeholder="smtp.gmail.com"
aria-required={emailSetting.enabled}
onChange={(e) => updateEmailSetting({ smtpHost: e.target.value })}
@@ -201,6 +227,7 @@ const NotificationSection = () => {
min={1}
max={65535}
value={emailSetting.smtpPort}
+ disabled={emailLocked("smtpPort")}
placeholder="587"
aria-required={emailSetting.enabled}
onChange={handlePortChanged}
@@ -215,6 +242,7 @@ const NotificationSection = () => {
className="w-full sm:w-80"
type="email"
value={emailSetting.smtpUsername}
+ disabled={emailLocked("smtpUsername")}
placeholder="[email protected]"
autoComplete="username"
onChange={(e) => updateEmailSetting({ smtpUsername: e.target.value })}
@@ -233,6 +261,7 @@ const NotificationSection = () => {
className="w-full sm:w-80"
type="password"
value={emailSetting.smtpPassword}
+ disabled={emailLocked("smtpPassword")}
placeholder={hasExistingEmailSetting ? t("setting.notification.smtp-password-placeholder-existing") : "abcd efgh ijkl mnop"}
autoComplete="new-password"
onChange={(e) => updateEmailSetting({ smtpPassword: e.target.value })}
@@ -247,6 +276,7 @@ const NotificationSection = () => {
className="w-full sm:w-80"
type="email"
value={emailSetting.fromEmail}
+ disabled={emailLocked("fromEmail")}
placeholder="[email protected]"
aria-required={emailSetting.enabled}
onChange={(e) => updateEmailSetting({ fromEmail: e.target.value })}
@@ -260,6 +290,7 @@ const NotificationSection = () => {
<Input
className="w-full sm:w-80"
value={emailSetting.fromName}
+ disabled={emailLocked("fromName")}
placeholder="Memos"
onChange={(e) => updateEmailSetting({ fromName: e.target.value })}
/>
@@ -273,6 +304,7 @@ const NotificationSection = () => {
className="w-full sm:w-80"
type="email"
value={emailSetting.replyTo}
+ disabled={emailLocked("replyTo")}
placeholder="[email protected]"
onChange={(e) => updateEmailSetting({ replyTo: e.target.value })}
/>
@@ -282,14 +314,14 @@ const NotificationSection = () => {
label={fieldLabel(t("setting.notification.use-tls"), "recommended")}
description={t("setting.notification.use-tls-description")}
>
- <Switch checked={emailSetting.useTls} onCheckedChange={handleUseTLSChanged} />
+ <Switch disabled={emailLocked("useTls")} checked={emailSetting.useTls} onCheckedChange={handleUseTLSChanged} />
</SettingRow>
<SettingRow
label={fieldLabel(t("setting.notification.use-ssl"), "optional")}
description={t("setting.notification.use-ssl-description")}
>
- <Switch checked={emailSetting.useSsl} onCheckedChange={handleUseSSLChanged} />
+ <Switch disabled={emailLocked("useSsl")} checked={emailSetting.useSsl} onCheckedChange={handleUseSSLChanged} />
</SettingRow>
</SettingGroup>
diff --git a/web/src/components/Settings/SSOSection.tsx b/web/src/components/Settings/SSOSection.tsx
index 5cf725e84..04c90171f 100644
--- a/web/src/components/Settings/SSOSection.tsx
+++ b/web/src/components/Settings/SSOSection.tsx
@@ -13,12 +13,14 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { identityProviderServiceClient } from "@/connect";
+import { findManagedResource, useConfigurationStatus } from "@/hooks/useConfigurationQueries";
import { useDialog } from "@/hooks/useDialog";
import { handleError } from "@/lib/error";
import { IdentityProvider } from "@/types/proto/api/idp_service_pb";
import { useTranslate } from "@/utils/i18n";
import CreateIdentityProviderDialog from "../CreateIdentityProviderDialog";
import LearnMore from "../LearnMore";
+import ManagedByConfigurationChip from "./ManagedByConfigurationChip";
import SettingSection from "./SettingSection";
import SettingTable from "./SettingTable";
@@ -33,6 +35,7 @@ interface IdentityProviderRow extends Record<string, unknown> {
const SSOSection = () => {
const t = useTranslate();
+ const configurationStatus = useConfigurationStatus();
const [identityProviderList, setIdentityProviderList] = useState<IdentityProvider[]>([]);
const [editingIdentityProvider, setEditingIdentityProvider] = useState<IdentityProvider | undefined>();
const [deleteTarget, setDeleteTarget] = useState<IdentityProvider | undefined>(undefined);
@@ -137,6 +140,7 @@ const SSOSection = () => {
</div>
<div className="flex flex-wrap items-center gap-2">
<InfoChip label={t("setting.sso.provider-uid")} value={row.providerUid} />
+ <ManagedByConfigurationChip resource={findManagedResource(configurationStatus, row.name)} />
</div>
</div>
),
@@ -165,13 +169,20 @@ const SSOSection = () => {
<MoreVerticalIcon className="w-4 h-auto" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={2}>
- <DropdownMenuItem onClick={() => handleEditIdentityProvider(row.provider)}>{t("common.edit")}</DropdownMenuItem>
<DropdownMenuItem
- onClick={() => handleDeleteIdentityProvider(row.provider)}
- className="text-destructive focus:text-destructive"
+ disabled={!!findManagedResource(configurationStatus, row.name)}
+ onClick={() => handleEditIdentityProvider(row.provider)}
>
- {t("common.delete")}
+ {t("common.edit")}
</DropdownMenuItem>
+ {findManagedResource(configurationStatus, row.name) ? null : (
+ <DropdownMenuItem
+ onClick={() => handleDeleteIdentityProvider(row.provider)}
+ className="text-destructive focus:text-destructive"
+ >
+ {t("common.delete")}
+ </DropdownMenuItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
),
diff --git a/web/src/components/Settings/SettingList.tsx b/web/src/components/Settings/SettingList.tsx
index a09dd3658..554dd859b 100644
--- a/web/src/components/Settings/SettingList.tsx
+++ b/web/src/components/Settings/SettingList.tsx
@@ -81,9 +81,10 @@ interface SettingCodeEditorProps {
value: string;
placeholder: string;
onChange: (value: string) => void;
+ disabled?: boolean;
}
-export const SettingCodeEditor = ({ label, description, value, placeholder, onChange }: SettingCodeEditorProps) => {
+export const SettingCodeEditor = ({ label, description, value, placeholder, onChange, disabled }: SettingCodeEditorProps) => {
return (
<SettingPanel
header={
@@ -98,6 +99,7 @@ export const SettingCodeEditor = ({ label, description, value, placeholder, onCh
rows={4}
placeholder={placeholder}
value={value}
+ disabled={disabled}
onChange={(event) => onChange(event.target.value)}
/>
</SettingPanel>
diff --git a/web/src/components/Settings/StorageSection.tsx b/web/src/components/Settings/StorageSection.tsx
index 2a792a209..99b6eac34 100644
--- a/web/src/components/Settings/StorageSection.tsx
+++ b/web/src/components/Settings/StorageSection.tsx
@@ -10,6 +10,7 @@ import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Switch } from "@/components/ui/switch";
import { useInstance } from "@/contexts/InstanceContext";
+import { isFieldManaged, useManagedResource } from "@/hooks/useConfigurationQueries";
import { cn } from "@/lib/utils";
import {
InstanceSetting_Key,
@@ -24,6 +25,7 @@ import {
InstanceSettingSchema,
} from "@/types/proto/api/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
+import ManagedByConfigurationChip from "./ManagedByConfigurationChip";
import SettingGroup from "./SettingGroup";
import { SettingPanel } from "./SettingList";
import SettingRow from "./SettingRow";
@@ -151,6 +153,10 @@ const canonicalizeStorageSetting = (
const StorageSection = () => {
const t = useTranslate();
+ const managed = useManagedResource(buildInstanceSettingName(InstanceSetting_Key.STORAGE));
+ // The registry, its default, and the S3 fields are edited together, so they lock together.
+ const registryLocked = isFieldManaged(managed, "storageSetting.storages") || isFieldManaged(managed, "storageSetting.defaultStorageId");
+ const templateLocked = isFieldManaged(managed, "storageSetting.filepathTemplate");
const saveInstanceSetting = useInstanceSettingUpdater();
const { storageSetting: originalSetting } = useInstance();
const [instanceStorageSetting, setInstanceStorageSetting] = useState<InstanceSetting_StorageSetting>(originalSetting);
@@ -268,8 +274,13 @@ const StorageSection = () => {
return (
<SettingSection title={t("setting.storage.label")}>
- <SettingGroup title={t("setting.storage.current-storage")} description={t("setting.storage.current-storage-description")}>
+ <SettingGroup
+ title={t("setting.storage.current-storage")}
+ description={t("setting.storage.current-storage-description")}
+ actions={registryLocked || templateLocked ? <ManagedByConfigurationChip resource={managed} /> : undefined}
+ >
<RadioGroup
+ disabled={registryLocked}
value={String(selectedStorageType)}
onValueChange={(value) => {
handleStorageTypeChanged(Number(value) as InstanceSetting_StorageType);
@@ -349,6 +360,7 @@ const StorageSection = () => {
<Input
className="w-full max-w-lg font-mono"
value={instanceStorageSetting.filepathTemplate}
+ disabled={templateLocked}
placeholder={DEFAULT_FILEPATH_TEMPLATE}
onChange={handleFilepathTemplateChanged}
/>
@@ -366,6 +378,7 @@ const StorageSection = () => {
<Input
className="w-64"
value={selectedS3Config?.accessKeyId ?? ""}
+ disabled={registryLocked}
onChange={(e) => handleS3FieldChange("accessKeyId", e.target.value)}
/>
</SettingRow>
@@ -380,6 +393,7 @@ const StorageSection = () => {
className="w-64"
type="password"
value={selectedS3Config?.accessKeySecret ?? ""}
+ disabled={registryLocked}
onChange={(e) => handleS3FieldChange("accessKeySecret", e.target.value)}
/>
</SettingRow>
@@ -388,6 +402,7 @@ const StorageSection = () => {
<Input
className="w-64"
value={selectedS3Config?.endpoint ?? ""}
+ disabled={registryLocked}
onChange={(e) => handleS3FieldChange("endpoint", e.target.value)}
/>
</SettingRow>
@@ -396,6 +411,7 @@ const StorageSection = () => {
<Input
className="w-64"
value={selectedS3Config?.region ?? ""}
+ disabled={registryLocked}
onChange={(e) => handleS3FieldChange("region", e.target.value)}
/>
</SettingRow>
@@ -404,6 +420,7 @@ const StorageSection = () => {
<Input
className="w-64"
value={selectedS3Config?.bucket ?? ""}
+ disabled={registryLocked}
onChange={(e) => handleS3FieldChange("bucket", e.target.value)}
/>
</SettingRow>
@@ -411,6 +428,7 @@ const StorageSection = () => {
<SettingRow label={t("setting.storage.use-path-style")} description={t("setting.storage.use-path-style-description")}>
<Switch
checked={selectedS3Config?.usePathStyle ?? false}
+ disabled={registryLocked}
onCheckedChange={(checked) => handleS3FieldChange("usePathStyle", checked)}
/>
</SettingRow>
@@ -421,6 +439,7 @@ const StorageSection = () => {
>
<Switch
checked={selectedS3Config?.insecureSkipTlsVerify ?? false}
+ disabled={registryLocked}
onCheckedChange={(checked) => handleS3FieldChange("insecureSkipTlsVerify", checked)}
/>
</SettingRow>
@@ -428,7 +447,7 @@ const StorageSection = () => {
)}
<div className="w-full flex justify-end">
- <Button disabled={!allowSaveStorageSetting} onClick={saveInstanceStorageSetting}>
+ <Button disabled={(registryLocked && templateLocked) || !allowSaveStorageSetting} onClick={saveInstanceStorageSetting}>
{t("common.save")}
</Button>
</div>
diff --git a/web/src/components/Settings/UsageLimitsSection.tsx b/web/src/components/Settings/UsageLimitsSection.tsx
index c37093e02..1b5d96203 100644
--- a/web/src/components/Settings/UsageLimitsSection.tsx
+++ b/web/src/components/Settings/UsageLimitsSection.tsx
@@ -12,16 +12,20 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { isFieldManaged, useManagedResource } from "@/hooks/useConfigurationQueries";
import { type UsageLimitEntry, useSaveUsageLimits, useUsageLimits } from "@/hooks/useUsageLimitQueries";
import { useListUsers } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
import { extractUsernameFromName } from "@/lib/resource-names";
+import { InstanceSetting_Key } from "@/types/proto/api/instance_service_pb";
import type { User } from "@/types/proto/api/user_service_pb";
import { useTranslate } from "@/utils/i18n";
+import ManagedByConfigurationChip from "./ManagedByConfigurationChip";
import SettingSection from "./SettingSection";
import SettingTable from "./SettingTable";
import UsageLimitDialog from "./UsageLimitDialog";
import { formatLimitValue, isLimited, type UsageMetric } from "./usageLimitValues";
+import { buildInstanceSettingName } from "./useInstanceSettingUpdater";
/** A table row: one entry and its position in the list. */
type LimitRow = { index: number; entry: UsageLimitEntry; shadowed: boolean } & Record<string, unknown>;
@@ -48,6 +52,8 @@ const metricColumns: {
*/
const UsageLimitsSection = () => {
const t = useTranslate();
+ const managed = useManagedResource(buildInstanceSettingName(InstanceSetting_Key.USAGE_LIMITS));
+ const locked = isFieldManaged(managed, "usageLimitsSetting");
const { limits, isLoading } = useUsageLimits();
const { data: users = [] } = useListUsers();
const save = useSaveUsageLimits();
@@ -134,10 +140,13 @@ const UsageLimitsSection = () => {
title={t("setting.usage-limits.title")}
description={t("setting.usage-limits.description")}
actions={
- <Button disabled={isLoading || !defaults} onClick={() => setDialog({ open: true })}>
- <PlusIcon className="w-4 h-4 mr-2" />
- {t("setting.usage-limits.add-entry")}
- </Button>
+ <>
+ {locked ? <ManagedByConfigurationChip resource={managed} /> : null}
+ <Button disabled={locked || isLoading || !defaults} onClick={() => setDialog({ open: true })}>
+ <PlusIcon className="w-4 h-4 mr-2" />
+ {t("setting.usage-limits.add-entry")}
+ </Button>
+ </>
}
>
<p className="text-sm text-muted-foreground">{t("setting.usage-limits.order-note")}</p>
@@ -188,7 +197,7 @@ const UsageLimitsSection = () => {
<Button
variant="outline"
size="sm"
- disabled={isLoading || save.isPending}
+ disabled={locked || isLoading || save.isPending}
aria-label={t("setting.usage-limits.row-actions", { name })}
/>
}
diff --git a/web/src/components/Settings/settingSections.ts b/web/src/components/Settings/settingSections.ts
index afdf29c76..22ae8f9d8 100644
--- a/web/src/components/Settings/settingSections.ts
+++ b/web/src/components/Settings/settingSections.ts
@@ -4,6 +4,7 @@ import {
BarChart3Icon,
CogIcon,
DatabaseIcon,
+ FileCogIcon,
GaugeIcon,
HeartHandshakeIcon,
KeyIcon,
@@ -20,6 +21,7 @@ import {
import { type ComponentType } from "react";
import AccessTokenSection from "@/components/Settings/AccessTokenSection";
import AISection from "@/components/Settings/AISection";
+import ConfigurationSection from "@/components/Settings/ConfigurationSection";
import InstanceSection from "@/components/Settings/InstanceSection";
import MemberSection from "@/components/Settings/MemberSection";
import MemoExportSection from "@/components/Settings/MemoExportSection";
@@ -52,7 +54,8 @@ export type SettingSectionKey =
| "sso"
| "tags"
| "ai"
- | "resource-stats";
+ | "resource-stats"
+ | "configuration";
type SettingSectionScope = "basic" | "admin";
@@ -181,6 +184,13 @@ export const SETTINGS_SECTIONS: SettingSectionDefinition[] = [
icon: BarChart3Icon,
component: ResourceStatsSection,
},
+ {
+ key: "configuration",
+ scope: "admin",
+ labelKey: "setting.configuration.label",
+ icon: FileCogIcon,
+ component: ConfigurationSection,
+ },
];
export const DEFAULT_SETTING_SECTION: SettingSectionKey = "my-account";
diff --git a/web/src/hooks/useConfigurationQueries.ts b/web/src/hooks/useConfigurationQueries.ts
new file mode 100644
index 000000000..749ec2981
--- /dev/null
+++ b/web/src/hooks/useConfigurationQueries.ts
@@ -0,0 +1,47 @@
+import { useQuery } from "@tanstack/react-query";
+import { instanceServiceClient } from "@/connect";
+import useCurrentUser from "@/hooks/useCurrentUser";
+import type { ConfigurationStatus, ConfigurationStatus_ManagedResource } from "@/types/proto/api/instance_service_pb";
+import { isSuperUser } from "@/utils/user";
+
+export const configurationKeys = {
+ status: ["configurationStatus"] as const,
+};
+
+// What declarative configuration manages. Only administrators can read it, and
+// they read it once per session; the server enforces ownership either way.
+export function useConfigurationStatus() {
+ const currentUser = useCurrentUser();
+ const { data } = useQuery({
+ queryKey: configurationKeys.status,
+ queryFn: () => instanceServiceClient.getConfigurationStatus({}),
+ staleTime: Number.POSITIVE_INFINITY,
+ enabled: !!isSuperUser(currentUser),
+ });
+ return data;
+}
+
+// The managed resource with name in status, or undefined when configuration does not manage it.
+export function findManagedResource(
+ status: ConfigurationStatus | undefined,
+ name: string,
+): ConfigurationStatus_ManagedResource | undefined {
+ return status?.managedResources.find((resource) => resource.resource === name);
+}
+
+// The managed resource with name, or undefined when configuration does not manage it.
+export function useManagedResource(name: string): ConfigurationStatus_ManagedResource | undefined {
+ return findManagedResource(useConfigurationStatus(), name);
+}
+
+const covers = (fields: string[], path: string) =>
+ fields.some((field) => field === "*" || path === field || path.startsWith(`${field}.`) || path.startsWith(`${field}[`));
+
+// Whether the API refuses a change to path, a JSON-name field path such as
+// generalSetting.customProfile, because configuration manages it.
+export function isFieldManaged(resource: ConfigurationStatus_ManagedResource | undefined, path: string): boolean {
+ if (!resource) {
+ return false;
+ }
+ return covers(resource.managedFields, path) && !covers(resource.ignoredFields, path);
+}
diff --git a/web/src/locales/ar.json b/web/src/locales/ar.json
index 4426eb47d..6e05a32d7 100644
--- a/web/src/locales/ar.json
+++ b/web/src/locales/ar.json
@@ -439,6 +439,21 @@
"delete-success": "تم حذف طريقة العرض `{{title}}` بنجاح",
"change-icon": "تغيير أيقونة العرض"
},
+ "configuration": {
+ "label": "الإعداد",
+ "description": "موارد تحددها ملفات الإعداد. عدّل ملفًا وطبّقه لتغييرها؛ ويبقى باقي المثيل قابلًا للتعديل هنا.",
+ "managed-by": "تُدار بواسطة الإعداد",
+ "managed-tooltip": "محدد في {{source}}. عدّل الملف وطبّقه لتغيير ذلك.",
+ "resource": "المورد",
+ "source": "الملف",
+ "managed-fields": "الحقول المُدارة",
+ "whole-resource": "كل الحقول",
+ "ignored-fields": "قابلة للتعديل هنا",
+ "serial": "الرقم التسلسلي",
+ "last-apply": "آخر تطبيق",
+ "applied-by": "طُبّق بواسطة",
+ "nothing-managed": "لم يُطبَّق أي إعداد. كل شيء يُضبط من هنا."
+ },
"sso": {
"authorization-endpoint": "نقطة نهاية التفويض",
"client-id": "معرف العميل",
diff --git a/web/src/locales/az.json b/web/src/locales/az.json
index 3cb58701a..de710e909 100644
--- a/web/src/locales/az.json
+++ b/web/src/locales/az.json
@@ -838,6 +838,21 @@
"delete-confirm": "`{{title}}` görünüşünü silmək istədiyinizə əminsiniz?",
"delete-success": "`{{title}}` görünüşü silindi"
},
+ "configuration": {
+ "label": "Konfiqurasiya",
+ "description": "Konfiqurasiya faylları ilə təyin olunan resurslar. Onları dəyişmək üçün faylı redaktə edib tətbiq edin; nümunənin qalan hissəsi burada redaktə oluna bilər.",
+ "managed-by": "Konfiqurasiya ilə idarə olunur",
+ "managed-tooltip": "{{source}} faylında təyin olunub. Bunu dəyişmək üçün faylı redaktə edib tətbiq edin.",
+ "resource": "Resurs",
+ "source": "Fayl",
+ "managed-fields": "İdarə olunan sahələr",
+ "whole-resource": "Bütün sahələr",
+ "ignored-fields": "Burada redaktə oluna bilər",
+ "serial": "Seriya nömrəsi",
+ "last-apply": "Son tətbiq",
+ "applied-by": "Tətbiq edən",
+ "nothing-managed": "Heç bir konfiqurasiya tətbiq olunmayıb. Hər şey burada təyin olunur."
+ },
"sso": {
"account": "Hesab",
"accounts-description": "Hər kimlik provayderini nəzərdən keçirin, cari bağlantı vəziyyətini görün və xarici kimlikləri bu hesaba qoşun və ya ondan ayırın.",
diff --git a/web/src/locales/bg.json b/web/src/locales/bg.json
index 5ac8b2567..fa9741611 100644
--- a/web/src/locales/bg.json
+++ b/web/src/locales/bg.json
@@ -644,6 +644,21 @@
"delete-success": "Изгледът `{{title}}` е изтрит успешно",
"change-icon": "Промяна на иконата на изгледа"
},
+ "configuration": {
+ "label": "Конфигурация",
+ "description": "Ресурси, зададени от конфигурационни файлове. Редактирайте файл и го приложете, за да ги промените; останалата част от инстанцията остава редактируема тук.",
+ "managed-by": "Управлява се от конфигурация",
+ "managed-tooltip": "Зададено в {{source}}. Редактирайте файла и го приложете, за да промените това.",
+ "resource": "Ресурс",
+ "source": "Файл",
+ "managed-fields": "Управлявани полета",
+ "whole-resource": "Всички полета",
+ "ignored-fields": "Редактируеми тук",
+ "serial": "Сериен номер",
+ "last-apply": "Последно приложено",
+ "applied-by": "Приложено от",
+ "nothing-managed": "Не е приложена конфигурация. Всичко се задава тук."
+ },
"sso": {
"account": "акаунт",
"accounts-description": "Прегледайте всеки доставчик на самоличност, вижте текущото състояние на връзката и свържете или прекъснете връзката с външни самоличности от този акаунт.",
diff --git a/web/src/locales/ca.json b/web/src/locales/ca.json
index f54e3707f..f5e695a52 100644
--- a/web/src/locales/ca.json
+++ b/web/src/locales/ca.json
@@ -528,6 +528,21 @@
"delete-success": "Vista `{{title}}` eliminada correctament",
"change-icon": "Canvia la icona de vista"
},
+ "configuration": {
+ "label": "Configuració",
+ "description": "Recursos definits per fitxers de configuració. Editeu un fitxer i apliqueu-lo per canviar-los; la resta de la instància continua sent editable aquí.",
+ "managed-by": "Gestionat per la configuració",
+ "managed-tooltip": "Definit a {{source}}. Editeu el fitxer i apliqueu-lo per canviar-ho.",
+ "resource": "Recurs",
+ "source": "Fitxer",
+ "managed-fields": "Camps gestionats",
+ "whole-resource": "Tots els camps",
+ "ignored-fields": "Editables aquí",
+ "serial": "Número de sèrie",
+ "last-apply": "Darrera aplicació",
+ "applied-by": "Aplicat per",
+ "nothing-managed": "No s'ha aplicat cap configuració. Tot es defineix aquí."
+ },
"sso": {
"authorization-endpoint": "Punt final d'autorització",
"client-id": "ID de client",
diff --git a/web/src/locales/cs.json b/web/src/locales/cs.json
index 6f6936f8b..0a643b35c 100644
--- a/web/src/locales/cs.json
+++ b/web/src/locales/cs.json
@@ -528,6 +528,21 @@
"delete-success": "Zobrazení `{{title}}` bylo úspěšně odstraněno",
"change-icon": "Změnit ikonu zobrazení"
},
+ "configuration": {
+ "label": "Konfigurace",
+ "description": "Prostředky nastavené konfiguračními soubory. Chcete-li je změnit, upravte soubor a použijte jej; zbytek instance zůstává upravitelný zde.",
+ "managed-by": "Spravováno konfigurací",
+ "managed-tooltip": "Nastaveno v {{source}}. Chcete-li to změnit, upravte soubor a použijte jej.",
+ "resource": "Prostředek",
+ "source": "Soubor",
+ "managed-fields": "Spravovaná pole",
+ "whole-resource": "Všechna pole",
+ "ignored-fields": "Upravitelné zde",
+ "serial": "Pořadové číslo",
+ "last-apply": "Naposledy použito",
+ "applied-by": "Použil",
+ "nothing-managed": "Nebyla použita žádná konfigurace. Vše se nastavuje zde."
+ },
"sso": {
"authorization-endpoint": "Autorizační koncový bod",
"client-id": "ID klienta",
diff --git a/web/src/locales/da.json b/web/src/locales/da.json
index 8f95b6ef9..a40bc6cda 100644
--- a/web/src/locales/da.json
+++ b/web/src/locales/da.json
@@ -644,6 +644,21 @@
"delete-success": "Visningen `{{title}}` blev slettet",
"change-icon": "Skift visningsikon"
},
+ "configuration": {
+ "label": "Konfiguration",
+ "description": "Ressourcer angivet af konfigurationsfiler. Rediger en fil, og anvend den for at ændre dem; resten af instansen kan stadig redigeres her.",
+ "managed-by": "Styret af konfiguration",
+ "managed-tooltip": "Angivet i {{source}}. Rediger filen, og anvend den for at ændre dette.",
+ "resource": "Ressource",
+ "source": "Fil",
+ "managed-fields": "Styrede felter",
+ "whole-resource": "Alle felter",
+ "ignored-fields": "Kan redigeres her",
+ "serial": "Serienummer",
+ "last-apply": "Senest anvendt",
+ "applied-by": "Anvendt af",
+ "nothing-managed": "Der er ikke anvendt nogen konfiguration. Alt indstilles her."
+ },
"sso": {
"account": "Konto",
"accounts-description": "Gennemgå hver identitetsudbyder, se den aktuelle linktilstand, og tilslut eller afbryd eksterne identiteter fra denne konto.",
diff --git a/web/src/locales/de.json b/web/src/locales/de.json
index c122e1c35..b13406ee5 100644
--- a/web/src/locales/de.json
+++ b/web/src/locales/de.json
@@ -528,6 +528,21 @@
"delete-success": "Ansicht `{{title}}` erfolgreich gelöscht",
"change-icon": "Ansichtssymbol ändern"
},
+ "configuration": {
+ "label": "Konfiguration",
+ "description": "Ressourcen, die über Konfigurationsdateien festgelegt werden. Bearbeiten Sie eine Datei und wenden Sie sie an, um sie zu ändern; der Rest der Instanz bleibt hier bearbeitbar.",
+ "managed-by": "Durch Konfiguration verwaltet",
+ "managed-tooltip": "Festgelegt in {{source}}. Bearbeiten Sie die Datei und wenden Sie sie an, um dies zu ändern.",
+ "resource": "Ressource",
+ "source": "Datei",
+ "managed-fields": "Verwaltete Felder",
+ "whole-resource": "Alle Felder",
+ "ignored-fields": "Hier bearbeitbar",
+ "serial": "Seriennummer",
+ "last-apply": "Zuletzt angewendet",
+ "applied-by": "Angewendet von",
+ "nothing-managed": "Es wurde keine Konfiguration angewendet. Alles wird hier festgelegt."
+ },
"sso": {
"authorization-endpoint": "Autorisierungsendpunkt",
"client-id": "Client ID",
diff --git a/web/src/locales/el.json b/web/src/locales/el.json
index c56ec1ee1..535f38dc2 100644
--- a/web/src/locales/el.json
+++ b/web/src/locales/el.json
@@ -644,6 +644,21 @@
"delete-success": "Η προβολή `{{title}}` διαγράφηκε με επιτυχία",
"change-icon": "Αλλαγή εικονιδίου προβολής"
},
+ "configuration": {
+ "label": "Διαμόρφωση",
+ "description": "Πόροι που ορίζονται από αρχεία διαμόρφωσης. Επεξεργαστείτε ένα αρχείο και εφαρμόστε το για να τους αλλάξετε· το υπόλοιπο της εγκατάστασης παραμένει επεξεργάσιμο εδώ.",
+ "managed-by": "Διαχειρίζεται από τη διαμόρφωση",
+ "managed-tooltip": "Ορίζεται στο {{source}}. Επεξεργαστείτε το αρχείο και εφαρμόστε το για να το αλλάξετε.",
+ "resource": "Πόρος",
+ "source": "Αρχείο",
+ "managed-fields": "Διαχειριζόμενα πεδία",
+ "whole-resource": "Όλα τα πεδία",
+ "ignored-fields": "Επεξεργάσιμα εδώ",
+ "serial": "Αύξων αριθμός",
+ "last-apply": "Τελευταία εφαρμογή",
+ "applied-by": "Εφαρμόστηκε από",
+ "nothing-managed": "Δεν έχει εφαρμοστεί διαμόρφωση. Όλα ορίζονται εδώ."
+ },
"sso": {
"account": "Λογαριασμός",
"accounts-description": "Ελέγξτε κάθε πάροχο ταυτότητας, δείτε την τρέχουσα κατάσταση σύνδεσης και συνδέστε ή αποσυνδέστε εξωτερικές ταυτότητες από αυτόν τον λογαριασμό.",
diff --git a/web/src/locales/en-GB.json b/web/src/locales/en-GB.json
index c91331390..511066909 100644
--- a/web/src/locales/en-GB.json
+++ b/web/src/locales/en-GB.json
@@ -528,6 +528,21 @@
"delete-success": "View `{{title}}` deleted successfully",
"change-icon": "Change view icon"
},
+ "configuration": {
+ "label": "Configuration",
+ "description": "Resources set by configuration files. Edit a file and apply it to change them; the rest of the instance stays editable here.",
+ "managed-by": "Managed by configuration",
+ "managed-tooltip": "Set in {{source}}. Edit the file and apply it to change this.",
+ "resource": "Resource",
+ "source": "File",
+ "managed-fields": "Managed fields",
+ "whole-resource": "All fields",
+ "ignored-fields": "Editable here",
+ "serial": "Serial",
+ "last-apply": "Last applied",
+ "applied-by": "Applied by",
+ "nothing-managed": "No configuration has been applied. Everything is set here."
+ },
"sso": {
"authorization-endpoint": "Authorisation endpoint",
"client-id": "Client ID",
diff --git a/web/src/locales/en.json b/web/src/locales/en.json
index b7f6c8247..8322ad7fb 100644
--- a/web/src/locales/en.json
+++ b/web/src/locales/en.json
@@ -838,6 +838,21 @@
"delete-confirm": "Are you sure you want to delete view `{{title}}`?",
"delete-success": "View `{{title}}` deleted successfully"
},
+ "configuration": {
+ "label": "Configuration",
+ "description": "Resources set by configuration files. Edit a file and apply it to change them; the rest of the instance stays editable here.",
+ "managed-by": "Managed by configuration",
+ "managed-tooltip": "Set in {{source}}. Edit the file and apply it to change this.",
+ "resource": "Resource",
+ "source": "File",
+ "managed-fields": "Managed fields",
+ "whole-resource": "All fields",
+ "ignored-fields": "Editable here",
+ "serial": "Serial",
+ "last-apply": "Last applied",
+ "applied-by": "Applied by",
+ "nothing-managed": "No configuration has been applied. Everything is set here."
+ },
"sso": {
"account": "Account",
"accounts-description": "Review each identity provider, see the current link state, and connect or disconnect external identities from this account.",
diff --git a/web/src/locales/es.json b/web/src/locales/es.json
index 8409638df..e804562ac 100644
--- a/web/src/locales/es.json
+++ b/web/src/locales/es.json
@@ -528,6 +528,21 @@
"delete-success": "Vista `{{title}}` eliminada correctamente",
"change-icon": "Cambiar icono de vista"
},
+ "configuration": {
+ "label": "Configuración",
+ "description": "Recursos definidos por archivos de configuración. Edita un archivo y aplícalo para cambiarlos; el resto de la instancia sigue siendo editable aquí.",
+ "managed-by": "Gestionado por la configuración",
+ "managed-tooltip": "Definido en {{source}}. Edita el archivo y aplícalo para cambiarlo.",
+ "resource": "Recurso",
+ "source": "Archivo",
+ "managed-fields": "Campos gestionados",
+ "whole-resource": "Todos los campos",
+ "ignored-fields": "Editables aquí",
+ "serial": "Número de serie",
+ "last-apply": "Última aplicación",
+ "applied-by": "Aplicado por",
+ "nothing-managed": "No se ha aplicado ninguna configuración. Todo se define aquí."
+ },
"sso": {
"authorization-endpoint": "Punto final de autorización",
"client-id": "ID del cliente",
diff --git a/web/src/locales/et.json b/web/src/locales/et.json
index aba0602f1..f71b45296 100644
--- a/web/src/locales/et.json
+++ b/web/src/locales/et.json
@@ -644,6 +644,21 @@
"delete-success": "Vaade `{{title}}` kustutati edukalt",
"change-icon": "Muuda vaate ikooni"
},
+ "configuration": {
+ "label": "Konfiguratsioon",
+ "description": "Konfiguratsioonifailidega määratud ressursid. Nende muutmiseks muutke faili ja rakendage see; ülejäänud eksemplar jääb siin muudetavaks.",
+ "managed-by": "Hallatud konfiguratsiooniga",
+ "managed-tooltip": "Määratud failis {{source}}. Selle muutmiseks muutke faili ja rakendage see.",
+ "resource": "Ressurss",
+ "source": "Fail",
+ "managed-fields": "Hallatud väljad",
+ "whole-resource": "Kõik väljad",
+ "ignored-fields": "Siin muudetav",
+ "serial": "Järjekorranumber",
+ "last-apply": "Viimati rakendatud",
+ "applied-by": "Rakendaja",
+ "nothing-managed": "Konfiguratsiooni pole rakendatud. Kõik määratakse siin."
+ },
"sso": {
"account": "konto",
"accounts-description": "Vaadake üle iga identiteedipakkuja, vaadake praegust lingi olekut ja ühendage selle kontoga välised identiteedid või ühendage need lahti.",
diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json
index 9a4b3ac31..3dd347d8c 100644
--- a/web/src/locales/fa.json
+++ b/web/src/locales/fa.json
@@ -439,6 +439,21 @@
"delete-success": "نمای «{{title}}» با موفقیت حذف شد",
"change-icon": "تغییر نماد نمایش"
},
+ "configuration": {
+ "label": "پیکربندی",
+ "description": "منابعی که با فایل‌های پیکربندی تعیین می‌شوند. برای تغییر آن‌ها فایل را ویرایش و اعمال کنید؛ بقیهٔ نمونه همچنان اینجا قابل ویرایش است.",
+ "managed-by": "مدیریت‌شده با پیکربندی",
+ "managed-tooltip": "در {{source}} تعیین شده است. برای تغییر آن، فایل را ویرایش و اعمال کنید.",
+ "resource": "منبع",
+ "source": "فایل",
+ "managed-fields": "فیلدهای مدیریت‌شده",
+ "whole-resource": "همهٔ فیلدها",
+ "ignored-fields": "قابل ویرایش در اینجا",
+ "serial": "شمارهٔ سریال",
+ "last-apply": "آخرین اعمال",
+ "applied-by": "اعمال‌شده توسط",
+ "nothing-managed": "هیچ پیکربندی‌ای اعمال نشده است. همه‌چیز اینجا تنظیم می‌شود."
+ },
"sso": {
"authorization-endpoint": "آدرس نقطه مجوز",
"client-id": "شناسه کلاینت",
diff --git a/web/src/locales/fi.json b/web/src/locales/fi.json
index 3ea69374c..3e4f78eca 100644
--- a/web/src/locales/fi.json
+++ b/web/src/locales/fi.json
@@ -644,6 +644,21 @@
"delete-success": "Näkymä `{{title}}` poistettu onnistuneesti",
"change-icon": "Vaihda näkymäkuvaketta"
},
+ "configuration": {
+ "label": "Konfiguraatio",
+ "description": "Konfiguraatiotiedostoilla määritetyt resurssit. Muuta niitä muokkaamalla tiedostoa ja ottamalla se käyttöön; muuta instanssia voi edelleen muokata täällä.",
+ "managed-by": "Konfiguraation hallitsema",
+ "managed-tooltip": "Määritetty tiedostossa {{source}}. Muuta tätä muokkaamalla tiedostoa ja ottamalla se käyttöön.",
+ "resource": "Resurssi",
+ "source": "Tiedosto",
+ "managed-fields": "Hallitut kentät",
+ "whole-resource": "Kaikki kentät",
+ "ignored-fields": "Muokattavissa täällä",
+ "serial": "Sarjanumero",
+ "last-apply": "Viimeksi otettu käyttöön",
+ "applied-by": "Käyttöön ottanut",
+ "nothing-managed": "Konfiguraatiota ei ole otettu käyttöön. Kaikki asetetaan täällä."
+ },
"sso": {
"account": "Tili",
"accounts-description": "Tarkista jokainen identiteetin tarjoaja, katso linkin nykyinen tila ja yhdistä tai irrota ulkoiset identiteetit tästä tilistä.",
diff --git a/web/src/locales/fr.json b/web/src/locales/fr.json
index a63e4d394..6ce39cdf7 100644
--- a/web/src/locales/fr.json
+++ b/web/src/locales/fr.json
@@ -528,6 +528,21 @@
"delete-success": "Vue `{{title}}` supprimée avec succès",
"change-icon": "Modifier l'icône d'affichage"
},
+ "configuration": {
+ "label": "Configuration",
+ "description": "Ressources définies par des fichiers de configuration. Modifiez un fichier et appliquez-le pour les changer ; le reste de l'instance reste modifiable ici.",
+ "managed-by": "Géré par la configuration",
+ "managed-tooltip": "Défini dans {{source}}. Modifiez le fichier et appliquez-le pour changer ceci.",
+ "resource": "Ressource",
+ "source": "Fichier",
+ "managed-fields": "Champs gérés",
+ "whole-resource": "Tous les champs",
+ "ignored-fields": "Modifiables ici",
+ "serial": "Numéro de série",
+ "last-apply": "Dernière application",
+ "applied-by": "Appliqué par",
+ "nothing-managed": "Aucune configuration n'a été appliquée. Tout se règle ici."
+ },
"sso": {
"authorization-endpoint": "Point de terminaison d'autorisation",
"client-id": "ID client",
diff --git a/web/src/locales/gl.json b/web/src/locales/gl.json
index 0567fa896..f302609c4 100644
--- a/web/src/locales/gl.json
+++ b/web/src/locales/gl.json
@@ -528,6 +528,21 @@
"delete-success": "Eliminouse correctamente a vista `{{title}}`",
"change-icon": "Cambiar a icona da vista"
},
+ "configuration": {
+ "label": "Configuración",
+ "description": "Recursos definidos por ficheiros de configuración. Edita un ficheiro e aplícao para cambialos; o resto da instancia segue sendo editable aquí.",
+ "managed-by": "Xestionado pola configuración",
+ "managed-tooltip": "Definido en {{source}}. Edita o ficheiro e aplícao para cambialo.",
+ "resource": "Recurso",
+ "source": "Ficheiro",
+ "managed-fields": "Campos xestionados",
+ "whole-resource": "Todos os campos",
+ "ignored-fields": "Editables aquí",
+ "serial": "Número de serie",
+ "last-apply": "Última aplicación",
+ "applied-by": "Aplicado por",
+ "nothing-managed": "Non se aplicou ningunha configuración. Todo se define aquí."
+ },
"sso": {
"authorization-endpoint": "Punto de acceso para autorización",
"client-id": "ID do cliente",
diff --git a/web/src/locales/he.json b/web/src/locales/he.json
index dd8e4acb4..6ba210675 100644
--- a/web/src/locales/he.json
+++ b/web/src/locales/he.json
@@ -677,6 +677,21 @@
"delete-success": "התצוגה `{{title}}` נמחקה בהצלחה",
"change-icon": "שינוי סמל התצוגה"
},
+ "configuration": {
+ "label": "תצורה",
+ "description": "משאבים שנקבעים על ידי קובצי תצורה. ערכו קובץ והחילו אותו כדי לשנות אותם; שאר המופע נשאר ניתן לעריכה כאן.",
+ "managed-by": "מנוהל על ידי תצורה",
+ "managed-tooltip": "נקבע ב-{{source}}. ערכו את הקובץ והחילו אותו כדי לשנות זאת.",
+ "resource": "משאב",
+ "source": "קובץ",
+ "managed-fields": "שדות מנוהלים",
+ "whole-resource": "כל השדות",
+ "ignored-fields": "ניתנים לעריכה כאן",
+ "serial": "מספר סידורי",
+ "last-apply": "הוחל לאחרונה",
+ "applied-by": "הוחל על ידי",
+ "nothing-managed": "לא הוחלה תצורה. הכול נקבע כאן."
+ },
"sso": {
"account": "חשבון",
"accounts-description": "עיינו בכל ספק זהות, בדקו את מצב הקישור הנוכחי וחברו או נתקו זהויות חיצוניות מהחשבון הזה.",
diff --git a/web/src/locales/hi.json b/web/src/locales/hi.json
index adc96b2cf..b3b64ce19 100644
--- a/web/src/locales/hi.json
+++ b/web/src/locales/hi.json
@@ -439,6 +439,21 @@
"delete-success": "दृश्य `{{title}}` सफलतापूर्वक हटाया गया",
"change-icon": "व्यू आइकन बदलें"
},
+ "configuration": {
+ "label": "कॉन्फ़िगरेशन",
+ "description": "कॉन्फ़िगरेशन फ़ाइलों द्वारा सेट किए गए संसाधन। इन्हें बदलने के लिए फ़ाइल संपादित करें और लागू करें; बाकी इंस्टेंस यहाँ संपादन योग्य रहता है।",
+ "managed-by": "कॉन्फ़िगरेशन द्वारा प्रबंधित",
+ "managed-tooltip": "{{source}} में सेट है। इसे बदलने के लिए फ़ाइल संपादित करें और लागू करें।",
+ "resource": "संसाधन",
+ "source": "फ़ाइल",
+ "managed-fields": "प्रबंधित फ़ील्ड",
+ "whole-resource": "सभी फ़ील्ड",
+ "ignored-fields": "यहाँ संपादन योग्य",
+ "serial": "क्रम संख्या",
+ "last-apply": "अंतिम बार लागू",
+ "applied-by": "लागू करने वाला",
+ "nothing-managed": "कोई कॉन्फ़िगरेशन लागू नहीं किया गया है। सब कुछ यहीं सेट होता है।"
+ },
"sso": {
"authorization-endpoint": "प्राधिकरण एंडपॉइंट",
"client-id": "क्लाइंट आईडी",
diff --git a/web/src/locales/hr.json b/web/src/locales/hr.json
index 656f1a7be..9627bc05b 100644
--- a/web/src/locales/hr.json
+++ b/web/src/locales/hr.json
@@ -528,6 +528,21 @@
"delete-success": "Prikaz `{{title}}` uspješno obrisan",
"change-icon": "Promijeni ikonu prikaza"
},
+ "configuration": {
+ "label": "Konfiguracija",
+ "description": "Resursi postavljeni konfiguracijskim datotekama. Uredite datoteku i primijenite je da biste ih promijenili; ostatak instance ostaje ovdje uredljiv.",
+ "managed-by": "Upravlja konfiguracija",
+ "managed-tooltip": "Postavljeno u {{source}}. Uredite datoteku i primijenite je da biste ovo promijenili.",
+ "resource": "Resurs",
+ "source": "Datoteka",
+ "managed-fields": "Upravljana polja",
+ "whole-resource": "Sva polja",
+ "ignored-fields": "Uredljivo ovdje",
+ "serial": "Serijski broj",
+ "last-apply": "Zadnja primjena",
+ "applied-by": "Primijenio",
+ "nothing-managed": "Nije primijenjena nijedna konfiguracija. Sve se postavlja ovdje."
+ },
"sso": {
"authorization-endpoint": "Krajnja točka autorizacije",
"client-id": "ID klijenta",
diff --git a/web/src/locales/hu.json b/web/src/locales/hu.json
index 9a5fbb54a..b0271ef30 100644
--- a/web/src/locales/hu.json
+++ b/web/src/locales/hu.json
@@ -528,6 +528,21 @@
"delete-success": "`{{title}}` nézet sikeresen törölve",
"change-icon": "Nézet ikonjának módosítása"
},
+ "configuration": {
+ "label": "Konfiguráció",
+ "description": "Konfigurációs fájlok által beállított erőforrások. A módosításukhoz szerkessze a fájlt, és alkalmazza; a példány többi része itt továbbra is szerkeszthető.",
+ "managed-by": "Konfiguráció kezeli",
+ "managed-tooltip": "Beállítva itt: {{source}}. A módosításhoz szerkessze a fájlt, és alkalmazza.",
+ "resource": "Erőforrás",
+ "source": "Fájl",
+ "managed-fields": "Kezelt mezők",
+ "whole-resource": "Minden mező",
+ "ignored-fields": "Itt szerkeszthető",
+ "serial": "Sorszám",
+ "last-apply": "Utoljára alkalmazva",
+ "applied-by": "Alkalmazta",
+ "nothing-managed": "Nincs alkalmazott konfiguráció. Minden itt állítható be."
+ },
"sso": {
"authorization-endpoint": "Hitelesítési végpont",
"client-id": "Kliens ID",
diff --git a/web/src/locales/id.json b/web/src/locales/id.json
index b92477aad..d0371f913 100644
--- a/web/src/locales/id.json
+++ b/web/src/locales/id.json
@@ -439,6 +439,21 @@
"delete-success": "Tampilan `{{title}}` berhasil dihapus",
"change-icon": "Mengubah ikon tampilan"
},
+ "configuration": {
+ "label": "Konfigurasi",
+ "description": "Sumber daya yang diatur oleh berkas konfigurasi. Sunting berkas lalu terapkan untuk mengubahnya; bagian lain instans tetap dapat disunting di sini.",
+ "managed-by": "Dikelola oleh konfigurasi",
+ "managed-tooltip": "Diatur di {{source}}. Sunting berkas lalu terapkan untuk mengubahnya.",
+ "resource": "Sumber daya",
+ "source": "Berkas",
+ "managed-fields": "Bidang yang dikelola",
+ "whole-resource": "Semua bidang",
+ "ignored-fields": "Dapat disunting di sini",
+ "serial": "Nomor seri",
+ "last-apply": "Terakhir diterapkan",
+ "applied-by": "Diterapkan oleh",
+ "nothing-managed": "Belum ada konfigurasi yang diterapkan. Semuanya diatur di sini."
+ },
"sso": {
"authorization-endpoint": "Akhir Otorisasi",
"client-id": "ID Klien",
diff --git a/web/src/locales/it.json b/web/src/locales/it.json
index 5cd990aaa..d13c61fb0 100644
--- a/web/src/locales/it.json
+++ b/web/src/locales/it.json
@@ -528,6 +528,21 @@
"delete-success": "Vista `{{title}}` eliminata con successo",
"change-icon": "Cambia icona di visualizzazione"
},
+ "configuration": {
+ "label": "Configurazione",
+ "description": "Risorse impostate da file di configurazione. Modifica un file e applicalo per cambiarle; il resto dell'istanza resta modificabile qui.",
+ "managed-by": "Gestito dalla configurazione",
+ "managed-tooltip": "Impostato in {{source}}. Modifica il file e applicalo per cambiarlo.",
+ "resource": "Risorsa",
+ "source": "File",
+ "managed-fields": "Campi gestiti",
+ "whole-resource": "Tutti i campi",
+ "ignored-fields": "Modificabili qui",
+ "serial": "Numero di serie",
+ "last-apply": "Ultima applicazione",
+ "applied-by": "Applicato da",
+ "nothing-managed": "Nessuna configurazione applicata. Tutto si imposta qui."
+ },
"sso": {
"authorization-endpoint": "Endpoint autorizzazione",
"client-id": "Client ID",
diff --git a/web/src/locales/ja.json b/web/src/locales/ja.json
index 614e5b927..ab43963f4 100644
--- a/web/src/locales/ja.json
+++ b/web/src/locales/ja.json
@@ -528,6 +528,21 @@
"delete-success": "ビュー `{{title}}` を削除しました",
"change-icon": "ビューのアイコンを変更"
},
+ "configuration": {
+ "label": "構成",
+ "description": "構成ファイルで設定されたリソースです。変更するにはファイルを編集して適用してください。インスタンスのその他の部分は引き続きここで編集できます。",
+ "managed-by": "構成で管理",
+ "managed-tooltip": "{{source}} で設定されています。変更するにはファイルを編集して適用してください。",
+ "resource": "リソース",
+ "source": "ファイル",
+ "managed-fields": "管理対象のフィールド",
+ "whole-resource": "すべてのフィールド",
+ "ignored-fields": "ここで編集可能",
+ "serial": "シリアル",
+ "last-apply": "最終適用",
+ "applied-by": "適用者",
+ "nothing-managed": "構成はまだ適用されていません。すべてここで設定します。"
+ },
"sso": {
"authorization-endpoint": "認証エンドポイント",
"client-id": "クライアントID",
diff --git a/web/src/locales/ka-GE.json b/web/src/locales/ka-GE.json
index 7ea40a718..4a76a4022 100644
--- a/web/src/locales/ka-GE.json
+++ b/web/src/locales/ka-GE.json
@@ -528,6 +528,21 @@
"delete-success": "ხედი `{{title}}` წარმატებით წაიშალა",
"change-icon": "ხედის ხატულის შეცვლა"
},
+ "configuration": {
+ "label": "კონფიგურაცია",
+ "description": "რესურსები, რომლებიც კონფიგურაციის ფაილებით არის დაყენებული. მათ შესაცვლელად შეცვალეთ ფაილი და გამოიყენეთ; ინსტანციის დანარჩენი ნაწილი აქ რჩება რედაქტირებადი.",
+ "managed-by": "იმართება კონფიგურაციით",
+ "managed-tooltip": "დაყენებულია {{source}}-ში. ამის შესაცვლელად შეცვალეთ ფაილი და გამოიყენეთ.",
+ "resource": "რესურსი",
+ "source": "ფაილი",
+ "managed-fields": "მართული ველები",
+ "whole-resource": "ყველა ველი",
+ "ignored-fields": "რედაქტირებადია აქ",
+ "serial": "სერიული ნომერი",
+ "last-apply": "ბოლოს გამოყენებული",
+ "applied-by": "გამოიყენა",
+ "nothing-managed": "კონფიგურაცია ჯერ არ გამოყენებულა. ყველაფერი აქ დგინდება."
+ },
"sso": {
"authorization-endpoint": "ავტორიზაციის წერტილი",
"client-id": "კლიენტის ID",
diff --git a/web/src/locales/ko.json b/web/src/locales/ko.json
index dbcee783d..ce8a4f87c 100644
--- a/web/src/locales/ko.json
+++ b/web/src/locales/ko.json
@@ -439,6 +439,21 @@
"delete-success": "보기 `{{title}}`가 성공적으로 삭제되었습니다",
"change-icon": "뷰 아이콘 변경"
},
+ "configuration": {
+ "label": "구성",
+ "description": "구성 파일로 설정된 리소스입니다. 변경하려면 파일을 편집한 뒤 적용하세요. 인스턴스의 나머지는 여기에서 계속 편집할 수 있습니다.",
+ "managed-by": "구성으로 관리됨",
+ "managed-tooltip": "{{source}}에서 설정됩니다. 변경하려면 파일을 편집한 뒤 적용하세요.",
+ "resource": "리소스",
+ "source": "파일",
+ "managed-fields": "관리되는 필드",
+ "whole-resource": "모든 필드",
+ "ignored-fields": "여기서 편집 가능",
+ "serial": "일련번호",
+ "last-apply": "마지막 적용",
+ "applied-by": "적용한 주체",
+ "nothing-managed": "적용된 구성이 없습니다. 모든 설정은 여기에서 합니다."
+ },
"sso": {
"authorization-endpoint": "인증 엔드포인트",
"client-id": "클라이언트 ID",
diff --git a/web/src/locales/lt.json b/web/src/locales/lt.json
index 6e9f9d51f..14ef99cf2 100644
--- a/web/src/locales/lt.json
+++ b/web/src/locales/lt.json
@@ -644,6 +644,21 @@
"delete-success": "Rodinys `{{title}}` sėkmingai ištrintas",
"change-icon": "Keisti rodinio piktogramą"
},
+ "configuration": {
+ "label": "Konfigūracija",
+ "description": "Ištekliai, nustatyti konfigūracijos failais. Norėdami juos pakeisti, redaguokite failą ir pritaikykite jį; likusią egzemplioriaus dalį vis dar galima redaguoti čia.",
+ "managed-by": "Valdoma konfigūracijos",
+ "managed-tooltip": "Nustatyta faile {{source}}. Norėdami tai pakeisti, redaguokite failą ir pritaikykite jį.",
+ "resource": "Išteklius",
+ "source": "Failas",
+ "managed-fields": "Valdomi laukai",
+ "whole-resource": "Visi laukai",
+ "ignored-fields": "Redaguojama čia",
+ "serial": "Serijos numeris",
+ "last-apply": "Paskutinį kartą pritaikyta",
+ "applied-by": "Pritaikė",
+ "nothing-managed": "Konfigūracija nepritaikyta. Viskas nustatoma čia."
+ },
"sso": {
"account": "sąskaita",
"accounts-description": "Peržiūrėkite kiekvieną tapatybės teikėją, peržiūrėkite dabartinę susiejimo būseną ir prijunkite arba atjunkite išorines tapatybes nuo šios paskyros.",
diff --git a/web/src/locales/lv.json b/web/src/locales/lv.json
index 366f32cb4..8c573b831 100644
--- a/web/src/locales/lv.json
+++ b/web/src/locales/lv.json
@@ -644,6 +644,21 @@
"delete-success": "Skats `{{title}}` veiksmīgi izdzēsts",
"change-icon": "Mainīt skata ikonu"
},
+ "configuration": {
+ "label": "Konfigurācija",
+ "description": "Resursi, ko nosaka konfigurācijas faili. Lai tos mainītu, rediģējiet failu un lietojiet to; pārējā instance joprojām ir rediģējama šeit.",
+ "managed-by": "Pārvalda konfigurācija",
+ "managed-tooltip": "Iestatīts failā {{source}}. Lai to mainītu, rediģējiet failu un lietojiet to.",
+ "resource": "Resurss",
+ "source": "Fails",
+ "managed-fields": "Pārvaldītie lauki",
+ "whole-resource": "Visi lauki",
+ "ignored-fields": "Rediģējams šeit",
+ "serial": "Sērijas numurs",
+ "last-apply": "Pēdējoreiz lietots",
+ "applied-by": "Lietoja",
+ "nothing-managed": "Neviena konfigurācija nav lietota. Viss tiek iestatīts šeit."
+ },
"sso": {
"account": "Konts",
"accounts-description": "Pārskatiet katru identitātes nodrošinātāju, skatiet pašreizējo saites stāvokli un pievienojiet vai atvienojiet ārējās identitātes no šī konta.",
diff --git a/web/src/locales/mr.json b/web/src/locales/mr.json
index 94450b7a3..d76411826 100644
--- a/web/src/locales/mr.json
+++ b/web/src/locales/mr.json
@@ -439,6 +439,21 @@
"delete-success": "दृश्य `{{title}}` यशस्वीरित्या हटवले",
"change-icon": "व्ह्यू आयकॉन बदला"
},
+ "configuration": {
+ "label": "कॉन्फिगरेशन",
+ "description": "कॉन्फिगरेशन फायलींद्वारे सेट केलेली संसाधने. ती बदलण्यासाठी फाइल संपादित करा आणि लागू करा; इन्स्टन्सचा उर्वरित भाग इथे संपादनयोग्य राहतो.",
+ "managed-by": "कॉन्फिगरेशनद्वारे व्यवस्थापित",
+ "managed-tooltip": "{{source}} मध्ये सेट केले आहे. हे बदलण्यासाठी फाइल संपादित करा आणि लागू करा.",
+ "resource": "संसाधन",
+ "source": "फाइल",
+ "managed-fields": "व्यवस्थापित फील्ड",
+ "whole-resource": "सर्व फील्ड",
+ "ignored-fields": "इथे संपादनयोग्य",
+ "serial": "अनुक्रमांक",
+ "last-apply": "शेवटचे लागू",
+ "applied-by": "लागू करणारे",
+ "nothing-managed": "कोणतेही कॉन्फिगरेशन लागू केलेले नाही. सर्व काही इथेच सेट होते."
+ },
"sso": {
"authorization-endpoint": "अधिकृतता एन्डपाॅंइन्ट",
"client-id": "क्लायंट आयडी",
diff --git a/web/src/locales/nb.json b/web/src/locales/nb.json
index 4ea98010b..ef3b2a4f7 100644
--- a/web/src/locales/nb.json
+++ b/web/src/locales/nb.json
@@ -528,6 +528,21 @@
"delete-success": "Visning `{{title}}` slettet vellykket",
"change-icon": "Endre visningsikon"
},
+ "configuration": {
+ "label": "Konfigurasjon",
+ "description": "Ressurser som er satt av konfigurasjonsfiler. Rediger en fil og bruk den for å endre dem; resten av instansen kan fortsatt redigeres her.",
+ "managed-by": "Styrt av konfigurasjon",
+ "managed-tooltip": "Satt i {{source}}. Rediger filen og bruk den for å endre dette.",
+ "resource": "Ressurs",
+ "source": "Fil",
+ "managed-fields": "Styrte felt",
+ "whole-resource": "Alle felt",
+ "ignored-fields": "Kan redigeres her",
+ "serial": "Serienummer",
+ "last-apply": "Sist brukt",
+ "applied-by": "Brukt av",
+ "nothing-managed": "Ingen konfigurasjon er brukt. Alt stilles inn her."
+ },
"sso": {
"authorization-endpoint": "Autorisasjon endepunkt",
"client-id": "Klient-ID",
diff --git a/web/src/locales/nl.json b/web/src/locales/nl.json
index 4fa96c55a..9be184494 100644
--- a/web/src/locales/nl.json
+++ b/web/src/locales/nl.json
@@ -528,6 +528,21 @@
"delete-success": "Weergave `{{title}}` succesvol verwijderd",
"change-icon": "Weergavepictogram wijzigen"
},
+ "configuration": {
+ "label": "Configuratie",
+ "description": "Resources die door configuratiebestanden worden ingesteld. Bewerk een bestand en pas het toe om ze te wijzigen; de rest van de instantie blijft hier bewerkbaar.",
+ "managed-by": "Beheerd door configuratie",
+ "managed-tooltip": "Ingesteld in {{source}}. Bewerk het bestand en pas het toe om dit te wijzigen.",
+ "resource": "Resource",
+ "source": "Bestand",
+ "managed-fields": "Beheerde velden",
+ "whole-resource": "Alle velden",
+ "ignored-fields": "Hier bewerkbaar",
+ "serial": "Volgnummer",
+ "last-apply": "Laatst toegepast",
+ "applied-by": "Toegepast door",
+ "nothing-managed": "Er is geen configuratie toegepast. Alles wordt hier ingesteld."
+ },
"sso": {
"authorization-endpoint": "Autorisatie-eindpunt",
"client-id": "Client-ID",
diff --git a/web/src/locales/nn.json b/web/src/locales/nn.json
index a46cf9f46..7965f7ffa 100644
--- a/web/src/locales/nn.json
+++ b/web/src/locales/nn.json
@@ -856,6 +856,21 @@
"your-access": "Åtgangen din",
"your-spaces": "Romma dine"
},
+ "configuration": {
+ "label": "Konfigurasjon",
+ "description": "Ressursar som er sette av konfigurasjonsfiler. Rediger ei fil og bruk henne for å endre dei; resten av instansen kan framleis redigerast her.",
+ "managed-by": "Styrt av konfigurasjon",
+ "managed-tooltip": "Sett i {{source}}. Rediger fila og bruk henne for å endre dette.",
+ "resource": "Ressurs",
+ "source": "Fil",
+ "managed-fields": "Styrte felt",
+ "whole-resource": "Alle felt",
+ "ignored-fields": "Kan redigerast her",
+ "serial": "Serienummer",
+ "last-apply": "Sist brukt",
+ "applied-by": "Brukt av",
+ "nothing-managed": "Ingen konfigurasjon er brukt. Alt blir stilt inn her."
+ },
"sso": {
"account": "Konto",
"accounts-description": "Sjå gjennom kvar identitetstilbydar, sjå gjeldande tilknytingsstatus, og knyt til eller fjern eksterne identitetar frå denne kontoen.",
diff --git a/web/src/locales/pl.json b/web/src/locales/pl.json
index 4b042c59a..fd7567b90 100644
--- a/web/src/locales/pl.json
+++ b/web/src/locales/pl.json
@@ -528,6 +528,21 @@
"delete-success": "Widok `{{title}}` usunięty pomyślnie",
"change-icon": "Zmień ikonę widoku"
},
+ "configuration": {
+ "label": "Konfiguracja",
+ "description": "Zasoby ustawione w plikach konfiguracyjnych. Aby je zmienić, edytuj plik i zastosuj go; reszta instancji pozostaje tu edytowalna.",
+ "managed-by": "Zarządzane przez konfigurację",
+ "managed-tooltip": "Ustawione w {{source}}. Aby to zmienić, edytuj plik i zastosuj go.",
+ "resource": "Zasób",
+ "source": "Plik",
+ "managed-fields": "Zarządzane pola",
+ "whole-resource": "Wszystkie pola",
+ "ignored-fields": "Edytowalne tutaj",
+ "serial": "Numer seryjny",
+ "last-apply": "Ostatnio zastosowano",
+ "applied-by": "Zastosował",
+ "nothing-managed": "Nie zastosowano żadnej konfiguracji. Wszystko ustawia się tutaj."
+ },
"sso": {
"authorization-endpoint": "Endpoint autoryzacji",
"client-id": "ID klienta",
diff --git a/web/src/locales/pt-BR.json b/web/src/locales/pt-BR.json
index 8fc9ee09e..b68e164a1 100644
--- a/web/src/locales/pt-BR.json
+++ b/web/src/locales/pt-BR.json
@@ -439,6 +439,21 @@
"delete-success": "Vista `{{title}}` excluída com sucesso",
"change-icon": "Alterar ícone de visualização"
},
+ "configuration": {
+ "label": "Configuração",
+ "description": "Recursos definidos por arquivos de configuração. Edite um arquivo e aplique-o para alterá-los; o restante da instância continua editável aqui.",
+ "managed-by": "Gerenciado pela configuração",
+ "managed-tooltip": "Definido em {{source}}. Edite o arquivo e aplique-o para alterar isto.",
+ "resource": "Recurso",
+ "source": "Arquivo",
+ "managed-fields": "Campos gerenciados",
+ "whole-resource": "Todos os campos",
+ "ignored-fields": "Editáveis aqui",
+ "serial": "Número de série",
+ "last-apply": "Última aplicação",
+ "applied-by": "Aplicado por",
+ "nothing-managed": "Nenhuma configuração foi aplicada. Tudo é definido aqui."
+ },
"sso": {
"authorization-endpoint": "Endpoint de autenticação",
"client-id": "ID do cliente",
diff --git a/web/src/locales/pt-PT.json b/web/src/locales/pt-PT.json
index 6e17732c0..b3a7b8294 100644
--- a/web/src/locales/pt-PT.json
+++ b/web/src/locales/pt-PT.json
@@ -528,6 +528,21 @@
"delete-success": "Vista `{{title}}` eliminada com sucesso",
"change-icon": "Alterar ícone de visualização"
},
+ "configuration": {
+ "label": "Configuração",
+ "description": "Recursos definidos por ficheiros de configuração. Edite um ficheiro e aplique-o para os alterar; o resto da instância continua editável aqui.",
+ "managed-by": "Gerido pela configuração",
+ "managed-tooltip": "Definido em {{source}}. Edite o ficheiro e aplique-o para alterar isto.",
+ "resource": "Recurso",
+ "source": "Ficheiro",
+ "managed-fields": "Campos geridos",
+ "whole-resource": "Todos os campos",
+ "ignored-fields": "Editáveis aqui",
+ "serial": "Número de série",
+ "last-apply": "Última aplicação",
+ "applied-by": "Aplicado por",
+ "nothing-managed": "Não foi aplicada nenhuma configuração. Tudo é definido aqui."
+ },
"sso": {
"authorization-endpoint": "Ponto de Autorização",
"client-id": "ID do Cliente",
diff --git a/web/src/locales/ro.json b/web/src/locales/ro.json
index e9bd57f14..ee4c6bc8e 100644
--- a/web/src/locales/ro.json
+++ b/web/src/locales/ro.json
@@ -644,6 +644,21 @@
"delete-success": "Vizualizarea `{{title}}` a fost ștearsă cu succes",
"change-icon": "Schimbă pictograma vizualizării"
},
+ "configuration": {
+ "label": "Configurație",
+ "description": "Resurse setate prin fișiere de configurație. Editați un fișier și aplicați-l pentru a le modifica; restul instanței rămâne editabil aici.",
+ "managed-by": "Gestionat prin configurație",
+ "managed-tooltip": "Setat în {{source}}. Editați fișierul și aplicați-l pentru a modifica acest lucru.",
+ "resource": "Resursă",
+ "source": "Fișier",
+ "managed-fields": "Câmpuri gestionate",
+ "whole-resource": "Toate câmpurile",
+ "ignored-fields": "Editabile aici",
+ "serial": "Număr de serie",
+ "last-apply": "Ultima aplicare",
+ "applied-by": "Aplicat de",
+ "nothing-managed": "Nu a fost aplicată nicio configurație. Totul se setează aici."
+ },
"sso": {
"account": "Cont",
"accounts-description": "Examinați fiecare furnizor de identitate, vedeți starea actuală a conexiunii și conectați sau deconectați identitățile externe de la acest cont.",
diff --git a/web/src/locales/ru.json b/web/src/locales/ru.json
index 784357e43..640335c8e 100644
--- a/web/src/locales/ru.json
+++ b/web/src/locales/ru.json
@@ -528,6 +528,21 @@
"delete-success": "Представление `{{title}}` успешно удалено",
"change-icon": "Изменить значок представления"
},
+ "configuration": {
+ "label": "Конфигурация",
+ "description": "Ресурсы, заданные файлами конфигурации. Чтобы изменить их, отредактируйте файл и примените его; остальная часть экземпляра по-прежнему редактируется здесь.",
+ "managed-by": "Управляется конфигурацией",
+ "managed-tooltip": "Задано в {{source}}. Чтобы изменить это, отредактируйте файл и примените его.",
+ "resource": "Ресурс",
+ "source": "Файл",
+ "managed-fields": "Управляемые поля",
+ "whole-resource": "Все поля",
+ "ignored-fields": "Редактируется здесь",
+ "serial": "Серийный номер",
+ "last-apply": "Последнее применение",
+ "applied-by": "Применил",
+ "nothing-managed": "Конфигурация не применялась. Всё настраивается здесь."
+ },
"sso": {
"authorization-endpoint": "Конечная точка авторизации",
"client-id": "ID клиента",
diff --git a/web/src/locales/sk.json b/web/src/locales/sk.json
index 022d3a07b..f10905381 100644
--- a/web/src/locales/sk.json
+++ b/web/src/locales/sk.json
@@ -644,6 +644,21 @@
"delete-success": "Zobrazenie `{{title}}` bolo úspešne odstránené",
"change-icon": "Zmeniť ikonu zobrazenia"
},
+ "configuration": {
+ "label": "Konfigurácia",
+ "description": "Zdroje nastavené konfiguračnými súbormi. Ak ich chcete zmeniť, upravte súbor a použite ho; zvyšok inštancie zostáva upraviteľný tu.",
+ "managed-by": "Spravované konfiguráciou",
+ "managed-tooltip": "Nastavené v {{source}}. Ak to chcete zmeniť, upravte súbor a použite ho.",
+ "resource": "Zdroj",
+ "source": "Súbor",
+ "managed-fields": "Spravované polia",
+ "whole-resource": "Všetky polia",
+ "ignored-fields": "Upraviteľné tu",
+ "serial": "Poradové číslo",
+ "last-apply": "Naposledy použité",
+ "applied-by": "Použil",
+ "nothing-managed": "Nebola použitá žiadna konfigurácia. Všetko sa nastavuje tu."
+ },
"sso": {
"account": "účtu",
"accounts-description": "Skontrolujte každého poskytovateľa identity, pozrite si aktuálny stav prepojenia a pripojte alebo odpojte externé identity od tohto účtu.",
diff --git a/web/src/locales/sl.json b/web/src/locales/sl.json
index 93cef075b..fc28f022c 100644
--- a/web/src/locales/sl.json
+++ b/web/src/locales/sl.json
@@ -528,6 +528,21 @@
"delete-success": "Pogled \"{{title}}\" je uspešno izbrisan",
"change-icon": "Spremeni ikono pogleda"
},
+ "configuration": {
+ "label": "Konfiguracija",
+ "description": "Viri, nastavljeni s konfiguracijskimi datotekami. Če jih želite spremeniti, uredite datoteko in jo uveljavite; preostali del primerka ostaja urejljiv tukaj.",
+ "managed-by": "Upravlja konfiguracija",
+ "managed-tooltip": "Nastavljeno v {{source}}. Če želite to spremeniti, uredite datoteko in jo uveljavite.",
+ "resource": "Vir",
+ "source": "Datoteka",
+ "managed-fields": "Upravljana polja",
+ "whole-resource": "Vsa polja",
+ "ignored-fields": "Urejljivo tukaj",
+ "serial": "Zaporedna številka",
+ "last-apply": "Nazadnje uveljavljeno",
+ "applied-by": "Uveljavil",
+ "nothing-managed": "Nobena konfiguracija ni bila uveljavljena. Vse se nastavi tukaj."
+ },
"sso": {
"authorization-endpoint": "Končna točka avtorizacije",
"client-id": "ID odjemalca",
diff --git a/web/src/locales/sr.json b/web/src/locales/sr.json
index 3440e64bf..d47c8654f 100644
--- a/web/src/locales/sr.json
+++ b/web/src/locales/sr.json
@@ -644,6 +644,21 @@
"delete-success": "Приказ `{{title}}` је успешно избрисан",
"change-icon": "Промени икону приказа"
},
+ "configuration": {
+ "label": "Конфигурација",
+ "description": "Ресурси постављени конфигурационим датотекама. Уредите датотеку и примените је да бисте их променили; остатак инстанце остаје овде уредив.",
+ "managed-by": "Управља конфигурација",
+ "managed-tooltip": "Постављено у {{source}}. Уредите датотеку и примените је да бисте ово променили.",
+ "resource": "Ресурс",
+ "source": "Датотека",
+ "managed-fields": "Управљана поља",
+ "whole-resource": "Сва поља",
+ "ignored-fields": "Уредиво овде",
+ "serial": "Серијски број",
+ "last-apply": "Последња примена",
+ "applied-by": "Применио",
+ "nothing-managed": "Није примењена ниједна конфигурација. Све се подешава овде."
+ },
"sso": {
"account": "Рачун",
"accounts-description": "Прегледајте сваког добављача идентитета, погледајте тренутно стање везе и повежите или искључите спољне идентитете са овог налога.",
diff --git a/web/src/locales/sv.json b/web/src/locales/sv.json
index 5b1362063..cf373ad87 100644
--- a/web/src/locales/sv.json
+++ b/web/src/locales/sv.json
@@ -528,6 +528,21 @@
"delete-success": "Vyn `{{title}}` raderades framgångsrikt",
"change-icon": "Ändra vyikon"
},
+ "configuration": {
+ "label": "Konfiguration",
+ "description": "Resurser som anges av konfigurationsfiler. Redigera en fil och tillämpa den för att ändra dem; resten av instansen går fortfarande att redigera här.",
+ "managed-by": "Styrs av konfiguration",
+ "managed-tooltip": "Anges i {{source}}. Redigera filen och tillämpa den för att ändra detta.",
+ "resource": "Resurs",
+ "source": "Fil",
+ "managed-fields": "Styrda fält",
+ "whole-resource": "Alla fält",
+ "ignored-fields": "Kan redigeras här",
+ "serial": "Serienummer",
+ "last-apply": "Senast tillämpad",
+ "applied-by": "Tillämpad av",
+ "nothing-managed": "Ingen konfiguration har tillämpats. Allt ställs in här."
+ },
"sso": {
"authorization-endpoint": "Auktoriseringsendpoint",
"client-id": "Klient-ID",
diff --git a/web/src/locales/th.json b/web/src/locales/th.json
index 024795590..668fd5655 100644
--- a/web/src/locales/th.json
+++ b/web/src/locales/th.json
@@ -439,6 +439,21 @@
"delete-success": "ลบมุมมอง `{{title}}` เรียบร้อยแล้ว",
"change-icon": "เปลี่ยนไอคอนการดู"
},
+ "configuration": {
+ "label": "การกำหนดค่า",
+ "description": "ทรัพยากรที่ตั้งค่าโดยไฟล์การกำหนดค่า แก้ไขไฟล์แล้วนำไปใช้เพื่อเปลี่ยนแปลง ส่วนอื่นของอินสแตนซ์ยังแก้ไขได้ที่นี่",
+ "managed-by": "จัดการโดยการกำหนดค่า",
+ "managed-tooltip": "ตั้งค่าไว้ใน {{source}} แก้ไขไฟล์แล้วนำไปใช้เพื่อเปลี่ยนค่านี้",
+ "resource": "ทรัพยากร",
+ "source": "ไฟล์",
+ "managed-fields": "ฟิลด์ที่จัดการ",
+ "whole-resource": "ทุกฟิลด์",
+ "ignored-fields": "แก้ไขได้ที่นี่",
+ "serial": "หมายเลขลำดับ",
+ "last-apply": "นำไปใช้ล่าสุด",
+ "applied-by": "นำไปใช้โดย",
+ "nothing-managed": "ยังไม่มีการนำการกำหนดค่าไปใช้ ทุกอย่างตั้งค่าได้ที่นี่"
+ },
"sso": {
"authorization-endpoint": "Endpoint การอนุญาต",
"client-id": "รหัสไคลเอ็นต์",
diff --git a/web/src/locales/tr.json b/web/src/locales/tr.json
index 99e82f5b2..1f146076e 100644
--- a/web/src/locales/tr.json
+++ b/web/src/locales/tr.json
@@ -689,6 +689,21 @@
"delete-confirm": "`{{title}}` görünümünü silmek istediğinizden emin misiniz?",
"delete-success": "`{{title}}` görünümü başarıyla silindi"
},
+ "configuration": {
+ "label": "Yapılandırma",
+ "description": "Yapılandırma dosyalarıyla belirlenen kaynaklar. Değiştirmek için bir dosyayı düzenleyip uygulayın; örneğin geri kalanı burada düzenlenebilir kalır.",
+ "managed-by": "Yapılandırma tarafından yönetiliyor",
+ "managed-tooltip": "{{source}} dosyasında belirlendi. Bunu değiştirmek için dosyayı düzenleyip uygulayın.",
+ "resource": "Kaynak",
+ "source": "Dosya",
+ "managed-fields": "Yönetilen alanlar",
+ "whole-resource": "Tüm alanlar",
+ "ignored-fields": "Burada düzenlenebilir",
+ "serial": "Seri numarası",
+ "last-apply": "Son uygulama",
+ "applied-by": "Uygulayan",
+ "nothing-managed": "Hiçbir yapılandırma uygulanmadı. Her şey burada ayarlanır."
+ },
"sso": {
"authorization-endpoint": "Yetkilendirme uç noktası",
"client-id": "İstemci Kimliği",
diff --git a/web/src/locales/uk.json b/web/src/locales/uk.json
index 3e763d530..92c640622 100644
--- a/web/src/locales/uk.json
+++ b/web/src/locales/uk.json
@@ -528,6 +528,21 @@
"delete-success": "Подання `{{title}}` успішно видалено",
"change-icon": "Змінити піктограму подання"
},
+ "configuration": {
+ "label": "Конфігурація",
+ "description": "Ресурси, задані файлами конфігурації. Щоб змінити їх, відредагуйте файл і застосуйте його; решта екземпляра й далі редагується тут.",
+ "managed-by": "Керується конфігурацією",
+ "managed-tooltip": "Задано в {{source}}. Щоб змінити це, відредагуйте файл і застосуйте його.",
+ "resource": "Ресурс",
+ "source": "Файл",
+ "managed-fields": "Керовані поля",
+ "whole-resource": "Усі поля",
+ "ignored-fields": "Редагується тут",
+ "serial": "Серійний номер",
+ "last-apply": "Останнє застосування",
+ "applied-by": "Застосував",
+ "nothing-managed": "Конфігурацію не застосовано. Усе налаштовується тут."
+ },
"sso": {
"authorization-endpoint": "Точка авторизації",
"client-id": "Ідентифікатор клієнта",
diff --git a/web/src/locales/vi.json b/web/src/locales/vi.json
index 6e5e0face..17f18649a 100644
--- a/web/src/locales/vi.json
+++ b/web/src/locales/vi.json
@@ -439,6 +439,21 @@
"delete-success": "Đã xóa chế độ xem `{{title}}` thành công",
"change-icon": "Thay đổi biểu tượng xem"
},
+ "configuration": {
+ "label": "Cấu hình",
+ "description": "Tài nguyên được đặt bởi tệp cấu hình. Chỉnh sửa tệp và áp dụng để thay đổi chúng; phần còn lại của phiên bản vẫn có thể chỉnh sửa tại đây.",
+ "managed-by": "Được quản lý bởi cấu hình",
+ "managed-tooltip": "Được đặt trong {{source}}. Chỉnh sửa tệp và áp dụng để thay đổi mục này.",
+ "resource": "Tài nguyên",
+ "source": "Tệp",
+ "managed-fields": "Trường được quản lý",
+ "whole-resource": "Tất cả các trường",
+ "ignored-fields": "Có thể chỉnh sửa tại đây",
+ "serial": "Số sê-ri",
+ "last-apply": "Áp dụng lần cuối",
+ "applied-by": "Áp dụng bởi",
+ "nothing-managed": "Chưa áp dụng cấu hình nào. Mọi thứ được đặt tại đây."
+ },
"sso": {
"authorization-endpoint": "Điểm cuối xác thực",
"client-id": "ID khách hàng",
diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.json
index 6f0e6b8fd..69935cbd0 100644
--- a/web/src/locales/zh-Hans.json
+++ b/web/src/locales/zh-Hans.json
@@ -513,6 +513,21 @@
"delete-success": "视图 `{{title}}` 删除成功",
"change-icon": "更改视图图标"
},
+ "configuration": {
+ "label": "配置文件",
+ "description": "由配置文件设置的资源。要修改它们,请编辑文件并应用;实例的其余部分仍可在此编辑。",
+ "managed-by": "由配置文件管理",
+ "managed-tooltip": "在 {{source}} 中设置。要修改此项,请编辑该文件并应用。",
+ "resource": "资源",
+ "source": "文件",
+ "managed-fields": "受管理的字段",
+ "whole-resource": "全部字段",
+ "ignored-fields": "可在此编辑",
+ "serial": "序号",
+ "last-apply": "上次应用",
+ "applied-by": "应用者",
+ "nothing-managed": "尚未应用任何配置。所有设置都在这里完成。"
+ },
"sso": {
"account": "账户",
"accounts-description": "查看每个身份提供程序的当前绑定状态,并为当前账户连接或解绑外部身份。",
diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.json
index 6cdd29d0c..1499a486c 100644
--- a/web/src/locales/zh-Hant.json
+++ b/web/src/locales/zh-Hant.json
@@ -685,6 +685,21 @@
"delete-success": "檢視 `{{title}}` 刪除成功",
"change-icon": "變更檢視圖示"
},
+ "configuration": {
+ "label": "設定檔",
+ "description": "由設定檔設定的資源。若要變更,請編輯檔案並套用;執行個體的其餘部分仍可在此編輯。",
+ "managed-by": "由設定檔管理",
+ "managed-tooltip": "在 {{source}} 中設定。若要變更,請編輯該檔案並套用。",
+ "resource": "資源",
+ "source": "檔案",
+ "managed-fields": "受管理的欄位",
+ "whole-resource": "所有欄位",
+ "ignored-fields": "可在此編輯",
+ "serial": "序號",
+ "last-apply": "上次套用",
+ "applied-by": "套用者",
+ "nothing-managed": "尚未套用任何設定。所有設定都在這裡完成。"
+ },
"sso": {
"account": "帳號",
"accounts-description": "檢視每個身分識別提供者、查看目前的連結狀態,並從此帳號連接或斷開外部身分。",
diff --git a/web/src/types/proto/api/configuration_pb.ts b/web/src/types/proto/api/configuration_pb.ts
new file mode 100644
index 000000000..d08ca520e
--- /dev/null
+++ b/web/src/types/proto/api/configuration_pb.ts
@@ -0,0 +1,364 @@
+// @generated by protoc-gen-es v2.12.1 with parameter "target=ts"
+// @generated from file api/configuration.proto (package memos.api, syntax proto3)
+/* eslint-disable */
+
+import type { GenEnum, GenFile, GenMessage } from "@bufbuild/protobuf/codegenv2";
+import { enumDesc, fileDesc, messageDesc } from "@bufbuild/protobuf/codegenv2";
+import type { IdentityProvider } from "./idp_service_pb";
+import { file_api_idp_service } from "./idp_service_pb";
+import type { InstanceSetting } from "./instance_service_pb";
+import { file_api_instance_service } from "./instance_service_pb";
+import type { User } from "./user_service_pb";
+import { file_api_user_service } from "./user_service_pb";
+import { file_google_api_field_behavior } from "../google/api/field_behavior_pb";
+import type { Message } from "@bufbuild/protobuf";
+
+/**
+ * Describes the file api/configuration.proto.
+ */
+export const file_api_configuration: GenFile = /*@__PURE__*/
+ fileDesc("ChdhcGkvY29uZmlndXJhdGlvbi5wcm90bxIJbWVtb3MuYXBpIoYCCg1Db25maWd1cmF0aW9uEjwKEmlkZW50aXR5X3Byb3ZpZGVycxgBIAMoCzIbLm1lbW9zLmFwaS5JZGVudGl0eVByb3ZpZGVyQgPgQQESOgoRaW5zdGFuY2Vfc2V0dGluZ3MYAiADKAsyGi5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nQgPgQQESIwoFdXNlcnMYAyADKAsyDy5tZW1vcy5hcGkuVXNlckID4EEBEiwKCWxpZmVjeWNsZRgEIAMoCzIULm1lbW9zLmFwaS5MaWZlY3ljbGVCA+BBARIoCgdyZW1vdmVkGAUgAygLMhIubWVtb3MuYXBpLlJlbW92ZWRCA+BBASJ+CglMaWZlY3ljbGUSFQoIcmVzb3VyY2UYASABKAlCA+BBAhIbCg5pZ25vcmVfY2hhbmdlcxgCIAMoCUID4EEBEhwKD3ByZXZlbnRfZGVzdHJveRgDIAEoCEID4EEBEh8KEndyaXRlX29ubHlfdmVyc2lvbhgEIAEoBUID4EEBIjYKB1JlbW92ZWQSFQoIcmVzb3VyY2UYASABKAlCA+BBAhIUCgdkZXN0cm95GAIgASgIQgPgQQEiiwEKBFBsYW4SDgoGc2VyaWFsGAEgASgDEjMKEHJlc291cmNlX2NoYW5nZXMYAiADKAsyGS5tZW1vcy5hcGkuUmVzb3VyY2VDaGFuZ2USHAoUc3RhdGVfcmVjb3JkX2NoYW5nZXMYAyABKAgSDgoGZXJyb3JzGAQgAygJEhAKCHdhcm5pbmdzGAUgAygJIrMCCg5SZXNvdXJjZUNoYW5nZRIQCghyZXNvdXJjZRgBIAEoCRIOCgZzb3VyY2UYAiABKAkSMAoGYWN0aW9uGAMgASgOMiAubWVtb3MuYXBpLlJlc291cmNlQ2hhbmdlLkFjdGlvbhINCgVkcmlmdBgEIAEoCBItCg1maWVsZF9jaGFuZ2VzGAUgAygLMhYubWVtb3MuYXBpLkZpZWxkQ2hhbmdlEg8KB21lc3NhZ2UYBiABKAkifgoGQWN0aW9uEhYKEkFDVElPTl9VTlNQRUNJRklFRBAAEgoKBkNSRUFURRABEgkKBUFET1BUEAISCgoGVVBEQVRFEAMSCQoFTk9fT1AQBBILCgdERVNUUk9ZEAUSCQoFUkVTRVQQBhILCgdSRUxFQVNFEAcSCQoFRVJST1IQCCI6CgtGaWVsZENoYW5nZRIMCgRwYXRoGAEgASgJEg4KBmJlZm9yZRgCIAEoCRINCgVhZnRlchgDIAEoCUKRAQoNY29tLm1lbW9zLmFwaUISQ29uZmlndXJhdGlvblByb3RvUAFaJ2dpdGh1Yi5jb20vdXNlbWVtb3MvbWVtb3MvcHJvdG8vZ2VuL2FwaaICA01BWKoCCU1lbW9zLkFwacoCCU1lbW9zXEFwaeICFU1lbW9zXEFwaVxHUEJNZXRhZGF0YeoCCk1lbW9zOjpBcGliBnByb3RvMw", [file_api_idp_service, file_api_instance_service, file_api_user_service, file_google_api_field_behavior]);
+
+/**
+ * Configuration is one declarative configuration document. Every file in the
+ * configuration directory is one Configuration, and all files are merged into
+ * one desired state. A resource may be declared in exactly one file.
+ *
+ * @generated from message memos.api.Configuration
+ */
+export type Configuration = Message<"memos.api.Configuration"> & {
+ /**
+ * Optional. Identity providers to manage, by resource name.
+ *
+ * @generated from field: repeated memos.api.IdentityProvider identity_providers = 1;
+ */
+ identityProviders: IdentityProvider[];
+
+ /**
+ * Optional. Instance setting groups to manage, by resource name.
+ *
+ * @generated from field: repeated memos.api.InstanceSetting instance_settings = 2;
+ */
+ instanceSettings: InstanceSetting[];
+
+ /**
+ * Optional. Users to manage, by resource name. Intended for bootstrap administrators.
+ *
+ * @generated from field: repeated memos.api.User users = 3;
+ */
+ users: User[];
+
+ /**
+ * Optional. Lifecycle rules for declared resources.
+ *
+ * @generated from field: repeated memos.api.Lifecycle lifecycle = 4;
+ */
+ lifecycle: Lifecycle[];
+
+ /**
+ * Optional. Resources to take out of management.
+ *
+ * @generated from field: repeated memos.api.Removed removed = 5;
+ */
+ removed: Removed[];
+};
+
+/**
+ * Describes the message memos.api.Configuration.
+ * Use `create(ConfigurationSchema)` to create a new message.
+ */
+export const ConfigurationSchema: GenMessage<Configuration> = /*@__PURE__*/
+ messageDesc(file_api_configuration, 0);
+
+/**
+ * Lifecycle adjusts how one declared resource is planned and applied.
+ *
+ * @generated from message memos.api.Lifecycle
+ */
+export type Lifecycle = Message<"memos.api.Lifecycle"> & {
+ /**
+ * Required. The resource name of a resource declared in the configuration.
+ * Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ *
+ * @generated from field: string resource = 1;
+ */
+ resource: string;
+
+ /**
+ * Optional. Field paths, in JSON name form, that the configuration does not manage.
+ * Apply writes them only when it creates the resource, and the API does not protect them.
+ *
+ * @generated from field: repeated string ignore_changes = 2;
+ */
+ ignoreChanges: string[];
+
+ /**
+ * Optional. Plan fails instead of destroying the resource.
+ *
+ * @generated from field: bool prevent_destroy = 3;
+ */
+ preventDestroy: boolean;
+
+ /**
+ * Optional. Increment to send write-only fields, such as a user's password, again.
+ *
+ * @generated from field: int32 write_only_version = 4;
+ */
+ writeOnlyVersion: number;
+};
+
+/**
+ * Describes the message memos.api.Lifecycle.
+ * Use `create(LifecycleSchema)` to create a new message.
+ */
+export const LifecycleSchema: GenMessage<Lifecycle> = /*@__PURE__*/
+ messageDesc(file_api_configuration, 1);
+
+/**
+ * Removed takes a resource out of management.
+ *
+ * @generated from message memos.api.Removed
+ */
+export type Removed = Message<"memos.api.Removed"> & {
+ /**
+ * Required. The resource name of a resource the configuration manages.
+ * Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ *
+ * @generated from field: string resource = 1;
+ */
+ resource: string;
+
+ /**
+ * Optional. Delete the resource, or reset an instance setting group to its defaults,
+ * instead of only releasing it from management.
+ *
+ * @generated from field: bool destroy = 2;
+ */
+ destroy: boolean;
+};
+
+/**
+ * Describes the message memos.api.Removed.
+ * Use `create(RemovedSchema)` to create a new message.
+ */
+export const RemovedSchema: GenMessage<Removed> = /*@__PURE__*/
+ messageDesc(file_api_configuration, 2);
+
+/**
+ * Plan is the difference between the declarative configuration and the
+ * instance: what apply would change. Configured values never appear in it.
+ *
+ * @generated from message memos.api.Plan
+ */
+export type Plan = Message<"memos.api.Plan"> & {
+ /**
+ * The state record serial the plan was computed against.
+ *
+ * @generated from field: int64 serial = 1;
+ */
+ serial: bigint;
+
+ /**
+ * One entry per resource the configuration declares or manages, in the order apply would act.
+ *
+ * @generated from field: repeated memos.api.ResourceChange resource_changes = 2;
+ */
+ resourceChanges: ResourceChange[];
+
+ /**
+ * Whether apply would write the state record. It is true whenever a resource
+ * changes, and also when only what the record holds changes, such as a lifecycle rule.
+ *
+ * @generated from field: bool state_record_changes = 3;
+ */
+ stateRecordChanges: boolean;
+
+ /**
+ * Problems that stop the plan from being applied.
+ *
+ * @generated from field: repeated string errors = 4;
+ */
+ errors: string[];
+
+ /**
+ * Diagnostics that do not stop the plan.
+ *
+ * @generated from field: repeated string warnings = 5;
+ */
+ warnings: string[];
+};
+
+/**
+ * Describes the message memos.api.Plan.
+ * Use `create(PlanSchema)` to create a new message.
+ */
+export const PlanSchema: GenMessage<Plan> = /*@__PURE__*/
+ messageDesc(file_api_configuration, 3);
+
+/**
+ * ResourceChange is what apply would do to one resource.
+ *
+ * @generated from message memos.api.ResourceChange
+ */
+export type ResourceChange = Message<"memos.api.ResourceChange"> & {
+ /**
+ * The resource name.
+ * Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ *
+ * @generated from field: string resource = 1;
+ */
+ resource: string;
+
+ /**
+ * The configuration file that declares the resource; empty for one that is no longer declared.
+ *
+ * @generated from field: string source = 2;
+ */
+ source: string;
+
+ /**
+ * What apply would do.
+ *
+ * @generated from field: memos.api.ResourceChange.Action action = 3;
+ */
+ action: ResourceChange_Action;
+
+ /**
+ * Whether the change undoes an edit made outside the configuration since the last apply.
+ *
+ * @generated from field: bool drift = 4;
+ */
+ drift: boolean;
+
+ /**
+ * The fields apply would write, with their values before and after.
+ *
+ * @generated from field: repeated memos.api.FieldChange field_changes = 5;
+ */
+ fieldChanges: FieldChange[];
+
+ /**
+ * Why the resource has this action, when the action alone does not say.
+ *
+ * @generated from field: string message = 6;
+ */
+ message: string;
+};
+
+/**
+ * Describes the message memos.api.ResourceChange.
+ * Use `create(ResourceChangeSchema)` to create a new message.
+ */
+export const ResourceChangeSchema: GenMessage<ResourceChange> = /*@__PURE__*/
+ messageDesc(file_api_configuration, 4);
+
+/**
+ * Action is what apply does to a resource.
+ *
+ * @generated from enum memos.api.ResourceChange.Action
+ */
+export enum ResourceChange_Action {
+ /**
+ * @generated from enum value: ACTION_UNSPECIFIED = 0;
+ */
+ ACTION_UNSPECIFIED = 0,
+
+ /**
+ * Write a resource that does not exist.
+ *
+ * @generated from enum value: CREATE = 1;
+ */
+ CREATE = 1,
+
+ /**
+ * Bring an existing resource under management and write the declared value.
+ *
+ * @generated from enum value: ADOPT = 2;
+ */
+ ADOPT = 2,
+
+ /**
+ * Write a managed resource that differs from its declaration.
+ *
+ * @generated from enum value: UPDATE = 3;
+ */
+ UPDATE = 3,
+
+ /**
+ * Nothing; the managed resource matches its declaration.
+ *
+ * @generated from enum value: NO_OP = 4;
+ */
+ NO_OP = 4,
+
+ /**
+ * Delete a managed resource a removed entry destroys.
+ *
+ * @generated from enum value: DESTROY = 5;
+ */
+ DESTROY = 5,
+
+ /**
+ * Reset a managed instance setting a removed entry destroys to its defaults.
+ *
+ * @generated from enum value: RESET = 6;
+ */
+ RESET = 6,
+
+ /**
+ * Stop managing a resource and leave it as it is.
+ *
+ * @generated from enum value: RELEASE = 7;
+ */
+ RELEASE = 7,
+
+ /**
+ * None; the resource is managed but no longer declared and has no removed entry.
+ *
+ * @generated from enum value: ERROR = 8;
+ */
+ ERROR = 8,
+}
+
+/**
+ * Describes the enum memos.api.ResourceChange.Action.
+ */
+export const ResourceChange_ActionSchema: GenEnum<ResourceChange_Action> = /*@__PURE__*/
+ enumDesc(file_api_configuration, 4, 0);
+
+/**
+ * FieldChange is one field apply would write.
+ *
+ * @generated from message memos.api.FieldChange
+ */
+export type FieldChange = Message<"memos.api.FieldChange"> & {
+ /**
+ * The field path, in JSON names from the resource, such as config.oauth2Config.scopes.
+ *
+ * @generated from field: string path = 1;
+ */
+ path: string;
+
+ /**
+ * The value before, as JSON. Sensitive values print as (sensitive) and write-only values
+ * as (write-only); an empty string means the resource does not exist yet.
+ *
+ * @generated from field: string before = 2;
+ */
+ before: string;
+
+ /**
+ * The value after, in the same form as before.
+ *
+ * @generated from field: string after = 3;
+ */
+ after: string;
+};
+
+/**
+ * Describes the message memos.api.FieldChange.
+ * Use `create(FieldChangeSchema)` to create a new message.
+ */
+export const FieldChangeSchema: GenMessage<FieldChange> = /*@__PURE__*/
+ messageDesc(file_api_configuration, 5);
+
diff --git a/web/src/types/proto/api/instance_service_pb.ts b/web/src/types/proto/api/instance_service_pb.ts
index c552b8686..700549555 100644
--- a/web/src/types/proto/api/instance_service_pb.ts
+++ b/web/src/types/proto/api/instance_service_pb.ts
@@ -20,7 +20,7 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file api/instance_service.proto.
*/
export const file_api_instance_service: GenFile = /*@__PURE__*/
- fileDesc("ChphcGkvaW5zdGFuY2Vfc2VydmljZS5wcm90bxIJbWVtb3MuYXBpIqkCCg9JbnN0YW5jZVByb2ZpbGUSDwoHdmVyc2lvbhgBIAEoCRIOCgZjb21taXQYAiABKAkSDAoEZGVtbxgDIAEoCBIUCgxpbnN0YW5jZV91cmwYBCABKAkSMgoLYWNjZXNzX21vZGUYBSABKA4yHS5tZW1vcy5hcGkuSW5zdGFuY2VBY2Nlc3NNb2RlEhMKC25lZWRzX3NldHVwGAYgASgIEh4KBWFkbWluGAcgASgLMg8ubWVtb3MuYXBpLlVzZXISNwoJY2hhbGxlbmdlGAggASgLMiQubWVtb3MuYXBpLkluc3RhbmNlUHJvZmlsZS5DaGFsbGVuZ2UaLwoJQ2hhbGxlbmdlEhAKCHByb3ZpZGVyGAEgASgJEhAKCHNpdGVfa2V5GAIgASgJIhsKGUdldEluc3RhbmNlUHJvZmlsZVJlcXVlc3Qilh0KD0luc3RhbmNlU2V0dGluZxIRCgRuYW1lGAEgASgJQgPgQQgSRAoPZ2VuZXJhbF9zZXR0aW5nGAIgASgLMikubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5HZW5lcmFsU2V0dGluZ0gAEkQKD3N0b3JhZ2Vfc2V0dGluZxgDIAEoCzIpLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuU3RvcmFnZVNldHRpbmdIABJNChRtZW1vX3JlbGF0ZWRfc2V0dGluZxgEIAEoCzItLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuTWVtb1JlbGF0ZWRTZXR0aW5nSAASPgoMdGFnc19zZXR0aW5nGAUgASgLMiYubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5UYWdzU2V0dGluZ0gAEk4KFG5vdGlmaWNhdGlvbl9zZXR0aW5nGAYgASgLMi4ubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5Ob3RpZmljYXRpb25TZXR0aW5nSAASOgoKYWlfc2V0dGluZxgHIAEoCzIkLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuQUlTZXR0aW5nSAASQgoOYWNjZXNzX3NldHRpbmcYCCABKAsyKC5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLkFjY2Vzc1NldHRpbmdIABJNChR1c2FnZV9saW1pdHNfc2V0dGluZxgJIAEoCzItLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuVXNhZ2VMaW1pdHNTZXR0aW5nSAAahAMKDkdlbmVyYWxTZXR0aW5nEk8KDmN1c3RvbV9wcm9maWxlGAEgASgLMjcubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5HZW5lcmFsU2V0dGluZy5DdXN0b21Qcm9maWxlEiIKGmRpc2FsbG93X3VzZXJfcmVnaXN0cmF0aW9uGAIgASgIEh4KFmRpc2FsbG93X3Bhc3N3b3JkX2F1dGgYAyABKAgSIAoYZGlzYWxsb3dfY2hhbmdlX3VzZXJuYW1lGAQgASgIEiAKGGRpc2FsbG93X2NoYW5nZV9uaWNrbmFtZRgFIAEoCBIdChV3ZWVrX3N0YXJ0X2RheV9vZmZzZXQYBiABKAUSGAoQYWRkaXRpb25hbF9zdHlsZRgHIAEoCRIZChFhZGRpdGlvbmFsX3NjcmlwdBgIIAEoCRpFCg1DdXN0b21Qcm9maWxlEg0KBXRpdGxlGAEgASgJEhMKC2Rlc2NyaXB0aW9uGAIgASgJEhAKCGxvZ29fdXJsGAMgASgJGo8ECg5TdG9yYWdlU2V0dGluZxI0CghzdG9yYWdlcxgBIAMoCzIiLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuU3RvcmFnZRIaChJkZWZhdWx0X3N0b3JhZ2VfaWQYAiABKAkSGQoRZmlsZXBhdGhfdGVtcGxhdGUYAyABKAkSSwoMc3RvcmFnZV90eXBlGAQgASgOMjUubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5TdG9yYWdlU2V0dGluZy5TdG9yYWdlVHlwZRJFCglzM19jb25maWcYBSABKAsyMi5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLlN0b3JhZ2VTZXR0aW5nLlMzQ29uZmlnGq0BCghTM0NvbmZpZxIQCghlbmRwb2ludBgBIAEoCRIOCgZyZWdpb24YAiABKAkSDgoGYnVja2V0GAMgASgJEhUKDWFjY2Vzc19rZXlfaWQYBCABKAkSHgoRYWNjZXNzX2tleV9zZWNyZXQYBSABKAlCA+BBBBIWCg51c2VfcGF0aF9zdHlsZRgGIAEoCBIgChhpbnNlY3VyZV9za2lwX3Rsc192ZXJpZnkYByABKAgiTAoLU3RvcmFnZVR5cGUSHAoYU1RPUkFHRV9UWVBFX1VOU1BFQ0lGSUVEEAASDAoIREFUQUJBU0UQARIJCgVMT0NBTBACEgYKAlMzEAMa1QIKB1N0b3JhZ2USCgoCaWQYASABKAkSDAoEbmFtZRgCIAEoCRI0CgR0eXBlGAMgASgOMiYubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5TdG9yYWdlVHlwZRJACglzM19jb25maWcYBCABKAsyKy5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLlN0b3JhZ2UuUzNDb25maWdIABqtAQoIUzNDb25maWcSEAoIZW5kcG9pbnQYASABKAkSDgoGcmVnaW9uGAIgASgJEg4KBmJ1Y2tldBgDIAEoCRIVCg1hY2Nlc3Nfa2V5X2lkGAQgASgJEh4KEWFjY2Vzc19rZXlfc2VjcmV0GAUgASgJQgPgQQQSFgoOdXNlX3BhdGhfc3R5bGUYBiABKAgSIAoYaW5zZWN1cmVfc2tpcF90bHNfdmVyaWZ5GAcgASgIQggKBmNvbmZpZxonChJNZW1vUmVsYXRlZFNldHRpbmcSEQoJcmVhY3Rpb25zGAEgAygJGqIBCgtUYWdzU2V0dGluZxI+CgR0YWdzGAEgAygLMjAubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5UYWdzU2V0dGluZy5UYWdzRW50cnkaUwoJVGFnc0VudHJ5EgsKA2tleRgBIAEoCRI1CgV2YWx1ZRgCIAEoCzImLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuVGFnTWV0YWRhdGE6AjgBGlEKC1RhZ01ldGFkYXRhEiwKEGJhY2tncm91bmRfY29sb3IYASABKAsyEi5nb29nbGUudHlwZS5Db2xvchIUCgxibHVyX2NvbnRlbnQYAiABKAgatwIKE05vdGlmaWNhdGlvblNldHRpbmcSSgoFZW1haWwYASABKAsyOy5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLk5vdGlmaWNhdGlvblNldHRpbmcuRW1haWxTZXR0aW5nGtMBCgxFbWFpbFNldHRpbmcSDwoHZW5hYmxlZBgBIAEoCBIRCglzbXRwX2hvc3QYAiABKAkSEQoJc210cF9wb3J0GAMgASgFEhUKDXNtdHBfdXNlcm5hbWUYBCABKAkSGgoNc210cF9wYXNzd29yZBgFIAEoCUID4EEEEg8KB3VzZV90bHMYBiABKAgSDwoHdXNlX3NzbBgHIAEoCBISCgpmcm9tX2VtYWlsGAggASgJEhEKCWZyb21fbmFtZRgJIAEoCRIQCghyZXBseV90bxgKIAEoCRqSAQoJQUlTZXR0aW5nEj4KCXByb3ZpZGVycxgBIAMoCzIrLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuQUlQcm92aWRlckNvbmZpZxJFCg10cmFuc2NyaXB0aW9uGAIgASgLMi4ubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5UcmFuc2NyaXB0aW9uQ29uZmlnGsMBChBBSVByb3ZpZGVyQ29uZmlnEgoKAmlkGAEgASgJEg0KBXRpdGxlGAIgASgJEjcKBHR5cGUYAyABKA4yKS5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLkFJUHJvdmlkZXJUeXBlEhAKCGVuZHBvaW50GAQgASgJEhQKB2FwaV9rZXkYBSABKAlCA+BBBBIYCgthcGlfa2V5X3NldBgGIAEoCEID4EEDEhkKDGFwaV9rZXlfaGludBgHIAEoCUID4EEDGlsKE1RyYW5zY3JpcHRpb25Db25maWcSEwoLcHJvdmlkZXJfaWQYASABKAkSDQoFbW9kZWwYAiABKAkSEAoIbGFuZ3VhZ2UYAyABKAkSDgoGcHJvbXB0GAQgASgJGkMKDUFjY2Vzc1NldHRpbmcSMgoLYWNjZXNzX21vZGUYASABKA4yHS5tZW1vcy5hcGkuSW5zdGFuY2VBY2Nlc3NNb2RlGt4CChJVc2FnZUxpbWl0c1NldHRpbmcSSAoGbGltaXRzGAEgAygLMjgubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5Vc2FnZUxpbWl0c1NldHRpbmcuVXNhZ2VMaW1pdBr9AQoKVXNhZ2VMaW1pdBIiCgV1c2VycxgBIAMoCUIT+kEQCg5tZW1vcy5hcGkvVXNlchIRCglhbGxfdXNlcnMYAyABKAgSFwoKbWVtb19jb3VudBgEIAEoA0gAiAEBEh8KEm1lbW9fY29udGVudF9ieXRlcxgFIAEoA0gBiAEBEhoKDXN0b3JhZ2VfYnl0ZXMYBiABKANIAogBARIZCgx1cGxvYWRfYnl0ZXMYByABKANIA4gBAUINCgtfbWVtb19jb3VudEIVChNfbWVtb19jb250ZW50X2J5dGVzQhAKDl9zdG9yYWdlX2J5dGVzQg8KDV91cGxvYWRfYnl0ZXMiiAEKA0tleRITCg9LRVlfVU5TUEVDSUZJRUQQABILCgdHRU5FUkFMEAESCwoHU1RPUkFHRRACEhAKDE1FTU9fUkVMQVRFRBADEggKBFRBR1MQBBIQCgxOT1RJRklDQVRJT04QBRIGCgJBSRAGEgoKBkFDQ0VTUxAHEhAKDFVTQUdFX0xJTUlUUxAIIkwKC1N0b3JhZ2VUeXBlEhwKGFNUT1JBR0VfVFlQRV9VTlNQRUNJRklFRBAAEgwKCERBVEFCQVNFEAESCQoFTE9DQUwQAhIGCgJTMxADIkoKDkFJUHJvdmlkZXJUeXBlEiAKHEFJX1BST1ZJREVSX1RZUEVfVU5TUEVDSUZJRUQQABIKCgZPUEVOQUkQARIKCgZHRU1JTkkQAjpe6kFbChltZW1vcy5hcGkvSW5zdGFuY2VTZXR0aW5nEhtpbnN0YW5jZS9zZXR0aW5ncy97c2V0dGluZ30qEGluc3RhbmNlU2V0dGluZ3MyD2luc3RhbmNlU2V0dGluZ0IHCgV2YWx1ZSJMChlHZXRJbnN0YW5jZVNldHRpbmdSZXF1ZXN0Ei8KBG5hbWUYASABKAlCIeBBAvpBGwoZbWVtb3MuYXBpL0luc3RhbmNlU2V0dGluZyJTCh9CYXRjaEdldEluc3RhbmNlU2V0dGluZ3NSZXF1ZXN0EjAKBW5hbWVzGAEgAygJQiHgQQL6QRsKGW1lbW9zLmFwaS9JbnN0YW5jZVNldHRpbmciWQogQmF0Y2hHZXRJbnN0YW5jZVNldHRpbmdzUmVzcG9uc2USNQoRaW5zdGFuY2Vfc2V0dGluZ3MYASADKAsyGi5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nIo8BChxVcGRhdGVJbnN0YW5jZVNldHRpbmdSZXF1ZXN0EjkKEGluc3RhbmNlX3NldHRpbmcYASABKAsyGi5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nQgPgQQISNAoLdXBkYXRlX21hc2sYAiABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrQgPgQQEikAEKH1Rlc3RJbnN0YW5jZUVtYWlsU2V0dGluZ1JlcXVlc3QSTwoFZW1haWwYASABKAsyOy5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLk5vdGlmaWNhdGlvblNldHRpbmcuRW1haWxTZXR0aW5nQgPgQQESHAoPcmVjaXBpZW50X2VtYWlsGAIgASgJQgPgQQEizwEKDUluc3RhbmNlU3RhdHMSOAoIZGF0YWJhc2UYASABKAsyJi5tZW1vcy5hcGkuSW5zdGFuY2VTdGF0cy5EYXRhYmFzZVN0YXRzEhsKE2xvY2FsX3N0b3JhZ2VfYnl0ZXMYAiABKAMSMgoOZ2VuZXJhdGVkX3RpbWUYAyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wGjMKDURhdGFiYXNlU3RhdHMSDgoGZHJpdmVyGAEgASgJEhIKCnNpemVfYnl0ZXMYAiABKAMiGQoXR2V0SW5zdGFuY2VTdGF0c1JlcXVlc3QqfQoSSW5zdGFuY2VBY2Nlc3NNb2RlEiQKIElOU1RBTkNFX0FDQ0VTU19NT0RFX1VOU1BFQ0lGSUVEEAASIAocSU5TVEFOQ0VfQUNDRVNTX01PREVfUFJJVkFURRABEh8KG0lOU1RBTkNFX0FDQ0VTU19NT0RFX1BVQkxJQxACMocHCg9JbnN0YW5jZVNlcnZpY2USdQoSR2V0SW5zdGFuY2VQcm9maWxlEiQubWVtb3MuYXBpLkdldEluc3RhbmNlUHJvZmlsZVJlcXVlc3QaGi5tZW1vcy5hcGkuSW5zdGFuY2VQcm9maWxlIh2C0+STAhcSFS9hcGkvaW5zdGFuY2UvcHJvZmlsZRKGAQoSR2V0SW5zdGFuY2VTZXR0aW5nEiQubWVtb3MuYXBpLkdldEluc3RhbmNlU2V0dGluZ1JlcXVlc3QaGi5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nIi7aQQRuYW1lgtPkkwIhEh8vYXBpL3tuYW1lPWluc3RhbmNlL3NldHRpbmdzLyp9Ep8BChhCYXRjaEdldEluc3RhbmNlU2V0dGluZ3MSKi5tZW1vcy5hcGkuQmF0Y2hHZXRJbnN0YW5jZVNldHRpbmdzUmVxdWVzdBorLm1lbW9zLmFwaS5CYXRjaEdldEluc3RhbmNlU2V0dGluZ3NSZXNwb25zZSIqgtPkkwIkOgEqIh8vYXBpL2luc3RhbmNlL3NldHRpbmdzOmJhdGNoR2V0EscBChVVcGRhdGVJbnN0YW5jZVNldHRpbmcSJy5tZW1vcy5hcGkuVXBkYXRlSW5zdGFuY2VTZXR0aW5nUmVxdWVzdBoaLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmciadpBHGluc3RhbmNlX3NldHRpbmcsdXBkYXRlX21hc2uC0+STAkQ6EGluc3RhbmNlX3NldHRpbmcyMC9hcGkve2luc3RhbmNlX3NldHRpbmcubmFtZT1pbnN0YW5jZS9zZXR0aW5ncy8qfRKYAQoYVGVzdEluc3RhbmNlRW1haWxTZXR0aW5nEioubWVtb3MuYXBpLlRlc3RJbnN0YW5jZUVtYWlsU2V0dGluZ1JlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiOILT5JMCMjoBKiItL2FwaS9pbnN0YW5jZS9zZXR0aW5ncy9ub3RpZmljYXRpb246dGVzdEVtYWlsEm0KEEdldEluc3RhbmNlU3RhdHMSIi5tZW1vcy5hcGkuR2V0SW5zdGFuY2VTdGF0c1JlcXVlc3QaGC5tZW1vcy5hcGkuSW5zdGFuY2VTdGF0cyIbgtPkkwIVEhMvYXBpL2luc3RhbmNlL3N0YXRzQpMBCg1jb20ubWVtb3MuYXBpQhRJbnN0YW5jZVNlcnZpY2VQcm90b1ABWidnaXRodWIuY29tL3VzZW1lbW9zL21lbW9zL3Byb3RvL2dlbi9hcGmiAgNNQViqAglNZW1vcy5BcGnKAglNZW1vc1xBcGniAhVNZW1vc1xBcGlcR1BCTWV0YWRhdGHqAgpNZW1vczo6QXBpYgZwcm90bzM", [file_api_user_service, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_google_type_color]);
+ fileDesc("ChphcGkvaW5zdGFuY2Vfc2VydmljZS5wcm90bxIJbWVtb3MuYXBpIqkCCg9JbnN0YW5jZVByb2ZpbGUSDwoHdmVyc2lvbhgBIAEoCRIOCgZjb21taXQYAiABKAkSDAoEZGVtbxgDIAEoCBIUCgxpbnN0YW5jZV91cmwYBCABKAkSMgoLYWNjZXNzX21vZGUYBSABKA4yHS5tZW1vcy5hcGkuSW5zdGFuY2VBY2Nlc3NNb2RlEhMKC25lZWRzX3NldHVwGAYgASgIEh4KBWFkbWluGAcgASgLMg8ubWVtb3MuYXBpLlVzZXISNwoJY2hhbGxlbmdlGAggASgLMiQubWVtb3MuYXBpLkluc3RhbmNlUHJvZmlsZS5DaGFsbGVuZ2UaLwoJQ2hhbGxlbmdlEhAKCHByb3ZpZGVyGAEgASgJEhAKCHNpdGVfa2V5GAIgASgJIhsKGUdldEluc3RhbmNlUHJvZmlsZVJlcXVlc3Qilh0KD0luc3RhbmNlU2V0dGluZxIRCgRuYW1lGAEgASgJQgPgQQgSRAoPZ2VuZXJhbF9zZXR0aW5nGAIgASgLMikubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5HZW5lcmFsU2V0dGluZ0gAEkQKD3N0b3JhZ2Vfc2V0dGluZxgDIAEoCzIpLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuU3RvcmFnZVNldHRpbmdIABJNChRtZW1vX3JlbGF0ZWRfc2V0dGluZxgEIAEoCzItLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuTWVtb1JlbGF0ZWRTZXR0aW5nSAASPgoMdGFnc19zZXR0aW5nGAUgASgLMiYubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5UYWdzU2V0dGluZ0gAEk4KFG5vdGlmaWNhdGlvbl9zZXR0aW5nGAYgASgLMi4ubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5Ob3RpZmljYXRpb25TZXR0aW5nSAASOgoKYWlfc2V0dGluZxgHIAEoCzIkLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuQUlTZXR0aW5nSAASQgoOYWNjZXNzX3NldHRpbmcYCCABKAsyKC5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLkFjY2Vzc1NldHRpbmdIABJNChR1c2FnZV9saW1pdHNfc2V0dGluZxgJIAEoCzItLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuVXNhZ2VMaW1pdHNTZXR0aW5nSAAahAMKDkdlbmVyYWxTZXR0aW5nEk8KDmN1c3RvbV9wcm9maWxlGAEgASgLMjcubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5HZW5lcmFsU2V0dGluZy5DdXN0b21Qcm9maWxlEiIKGmRpc2FsbG93X3VzZXJfcmVnaXN0cmF0aW9uGAIgASgIEh4KFmRpc2FsbG93X3Bhc3N3b3JkX2F1dGgYAyABKAgSIAoYZGlzYWxsb3dfY2hhbmdlX3VzZXJuYW1lGAQgASgIEiAKGGRpc2FsbG93X2NoYW5nZV9uaWNrbmFtZRgFIAEoCBIdChV3ZWVrX3N0YXJ0X2RheV9vZmZzZXQYBiABKAUSGAoQYWRkaXRpb25hbF9zdHlsZRgHIAEoCRIZChFhZGRpdGlvbmFsX3NjcmlwdBgIIAEoCRpFCg1DdXN0b21Qcm9maWxlEg0KBXRpdGxlGAEgASgJEhMKC2Rlc2NyaXB0aW9uGAIgASgJEhAKCGxvZ29fdXJsGAMgASgJGo8ECg5TdG9yYWdlU2V0dGluZxI0CghzdG9yYWdlcxgBIAMoCzIiLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuU3RvcmFnZRIaChJkZWZhdWx0X3N0b3JhZ2VfaWQYAiABKAkSGQoRZmlsZXBhdGhfdGVtcGxhdGUYAyABKAkSSwoMc3RvcmFnZV90eXBlGAQgASgOMjUubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5TdG9yYWdlU2V0dGluZy5TdG9yYWdlVHlwZRJFCglzM19jb25maWcYBSABKAsyMi5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLlN0b3JhZ2VTZXR0aW5nLlMzQ29uZmlnGq0BCghTM0NvbmZpZxIQCghlbmRwb2ludBgBIAEoCRIOCgZyZWdpb24YAiABKAkSDgoGYnVja2V0GAMgASgJEhUKDWFjY2Vzc19rZXlfaWQYBCABKAkSHgoRYWNjZXNzX2tleV9zZWNyZXQYBSABKAlCA+BBBBIWCg51c2VfcGF0aF9zdHlsZRgGIAEoCBIgChhpbnNlY3VyZV9za2lwX3Rsc192ZXJpZnkYByABKAgiTAoLU3RvcmFnZVR5cGUSHAoYU1RPUkFHRV9UWVBFX1VOU1BFQ0lGSUVEEAASDAoIREFUQUJBU0UQARIJCgVMT0NBTBACEgYKAlMzEAMa1QIKB1N0b3JhZ2USCgoCaWQYASABKAkSDAoEbmFtZRgCIAEoCRI0CgR0eXBlGAMgASgOMiYubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5TdG9yYWdlVHlwZRJACglzM19jb25maWcYBCABKAsyKy5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLlN0b3JhZ2UuUzNDb25maWdIABqtAQoIUzNDb25maWcSEAoIZW5kcG9pbnQYASABKAkSDgoGcmVnaW9uGAIgASgJEg4KBmJ1Y2tldBgDIAEoCRIVCg1hY2Nlc3Nfa2V5X2lkGAQgASgJEh4KEWFjY2Vzc19rZXlfc2VjcmV0GAUgASgJQgPgQQQSFgoOdXNlX3BhdGhfc3R5bGUYBiABKAgSIAoYaW5zZWN1cmVfc2tpcF90bHNfdmVyaWZ5GAcgASgIQggKBmNvbmZpZxonChJNZW1vUmVsYXRlZFNldHRpbmcSEQoJcmVhY3Rpb25zGAEgAygJGqIBCgtUYWdzU2V0dGluZxI+CgR0YWdzGAEgAygLMjAubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5UYWdzU2V0dGluZy5UYWdzRW50cnkaUwoJVGFnc0VudHJ5EgsKA2tleRgBIAEoCRI1CgV2YWx1ZRgCIAEoCzImLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuVGFnTWV0YWRhdGE6AjgBGlEKC1RhZ01ldGFkYXRhEiwKEGJhY2tncm91bmRfY29sb3IYASABKAsyEi5nb29nbGUudHlwZS5Db2xvchIUCgxibHVyX2NvbnRlbnQYAiABKAgatwIKE05vdGlmaWNhdGlvblNldHRpbmcSSgoFZW1haWwYASABKAsyOy5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLk5vdGlmaWNhdGlvblNldHRpbmcuRW1haWxTZXR0aW5nGtMBCgxFbWFpbFNldHRpbmcSDwoHZW5hYmxlZBgBIAEoCBIRCglzbXRwX2hvc3QYAiABKAkSEQoJc210cF9wb3J0GAMgASgFEhUKDXNtdHBfdXNlcm5hbWUYBCABKAkSGgoNc210cF9wYXNzd29yZBgFIAEoCUID4EEEEg8KB3VzZV90bHMYBiABKAgSDwoHdXNlX3NzbBgHIAEoCBISCgpmcm9tX2VtYWlsGAggASgJEhEKCWZyb21fbmFtZRgJIAEoCRIQCghyZXBseV90bxgKIAEoCRqSAQoJQUlTZXR0aW5nEj4KCXByb3ZpZGVycxgBIAMoCzIrLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmcuQUlQcm92aWRlckNvbmZpZxJFCg10cmFuc2NyaXB0aW9uGAIgASgLMi4ubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5UcmFuc2NyaXB0aW9uQ29uZmlnGsMBChBBSVByb3ZpZGVyQ29uZmlnEgoKAmlkGAEgASgJEg0KBXRpdGxlGAIgASgJEjcKBHR5cGUYAyABKA4yKS5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLkFJUHJvdmlkZXJUeXBlEhAKCGVuZHBvaW50GAQgASgJEhQKB2FwaV9rZXkYBSABKAlCA+BBBBIYCgthcGlfa2V5X3NldBgGIAEoCEID4EEDEhkKDGFwaV9rZXlfaGludBgHIAEoCUID4EEDGlsKE1RyYW5zY3JpcHRpb25Db25maWcSEwoLcHJvdmlkZXJfaWQYASABKAkSDQoFbW9kZWwYAiABKAkSEAoIbGFuZ3VhZ2UYAyABKAkSDgoGcHJvbXB0GAQgASgJGkMKDUFjY2Vzc1NldHRpbmcSMgoLYWNjZXNzX21vZGUYASABKA4yHS5tZW1vcy5hcGkuSW5zdGFuY2VBY2Nlc3NNb2RlGt4CChJVc2FnZUxpbWl0c1NldHRpbmcSSAoGbGltaXRzGAEgAygLMjgubWVtb3MuYXBpLkluc3RhbmNlU2V0dGluZy5Vc2FnZUxpbWl0c1NldHRpbmcuVXNhZ2VMaW1pdBr9AQoKVXNhZ2VMaW1pdBIiCgV1c2VycxgBIAMoCUIT+kEQCg5tZW1vcy5hcGkvVXNlchIRCglhbGxfdXNlcnMYAyABKAgSFwoKbWVtb19jb3VudBgEIAEoA0gAiAEBEh8KEm1lbW9fY29udGVudF9ieXRlcxgFIAEoA0gBiAEBEhoKDXN0b3JhZ2VfYnl0ZXMYBiABKANIAogBARIZCgx1cGxvYWRfYnl0ZXMYByABKANIA4gBAUINCgtfbWVtb19jb3VudEIVChNfbWVtb19jb250ZW50X2J5dGVzQhAKDl9zdG9yYWdlX2J5dGVzQg8KDV91cGxvYWRfYnl0ZXMiiAEKA0tleRITCg9LRVlfVU5TUEVDSUZJRUQQABILCgdHRU5FUkFMEAESCwoHU1RPUkFHRRACEhAKDE1FTU9fUkVMQVRFRBADEggKBFRBR1MQBBIQCgxOT1RJRklDQVRJT04QBRIGCgJBSRAGEgoKBkFDQ0VTUxAHEhAKDFVTQUdFX0xJTUlUUxAIIkwKC1N0b3JhZ2VUeXBlEhwKGFNUT1JBR0VfVFlQRV9VTlNQRUNJRklFRBAAEgwKCERBVEFCQVNFEAESCQoFTE9DQUwQAhIGCgJTMxADIkoKDkFJUHJvdmlkZXJUeXBlEiAKHEFJX1BST1ZJREVSX1RZUEVfVU5TUEVDSUZJRUQQABIKCgZPUEVOQUkQARIKCgZHRU1JTkkQAjpe6kFbChltZW1vcy5hcGkvSW5zdGFuY2VTZXR0aW5nEhtpbnN0YW5jZS9zZXR0aW5ncy97c2V0dGluZ30qEGluc3RhbmNlU2V0dGluZ3MyD2luc3RhbmNlU2V0dGluZ0IHCgV2YWx1ZSJMChlHZXRJbnN0YW5jZVNldHRpbmdSZXF1ZXN0Ei8KBG5hbWUYASABKAlCIeBBAvpBGwoZbWVtb3MuYXBpL0luc3RhbmNlU2V0dGluZyJTCh9CYXRjaEdldEluc3RhbmNlU2V0dGluZ3NSZXF1ZXN0EjAKBW5hbWVzGAEgAygJQiHgQQL6QRsKGW1lbW9zLmFwaS9JbnN0YW5jZVNldHRpbmciWQogQmF0Y2hHZXRJbnN0YW5jZVNldHRpbmdzUmVzcG9uc2USNQoRaW5zdGFuY2Vfc2V0dGluZ3MYASADKAsyGi5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nIo8BChxVcGRhdGVJbnN0YW5jZVNldHRpbmdSZXF1ZXN0EjkKEGluc3RhbmNlX3NldHRpbmcYASABKAsyGi5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nQgPgQQISNAoLdXBkYXRlX21hc2sYAiABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrQgPgQQEikAEKH1Rlc3RJbnN0YW5jZUVtYWlsU2V0dGluZ1JlcXVlc3QSTwoFZW1haWwYASABKAsyOy5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nLk5vdGlmaWNhdGlvblNldHRpbmcuRW1haWxTZXR0aW5nQgPgQQESHAoPcmVjaXBpZW50X2VtYWlsGAIgASgJQgPgQQEizwEKDUluc3RhbmNlU3RhdHMSOAoIZGF0YWJhc2UYASABKAsyJi5tZW1vcy5hcGkuSW5zdGFuY2VTdGF0cy5EYXRhYmFzZVN0YXRzEhsKE2xvY2FsX3N0b3JhZ2VfYnl0ZXMYAiABKAMSMgoOZ2VuZXJhdGVkX3RpbWUYAyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wGjMKDURhdGFiYXNlU3RhdHMSDgoGZHJpdmVyGAEgASgJEhIKCnNpemVfYnl0ZXMYAiABKAMiGQoXR2V0SW5zdGFuY2VTdGF0c1JlcXVlc3QiHwodR2V0Q29uZmlndXJhdGlvblN0YXR1c1JlcXVlc3QiwQIKE0NvbmZpZ3VyYXRpb25TdGF0dXMSDgoGc2VyaWFsGAEgASgDEhUKDWNvbmZpZ19kaWdlc3QYAiABKAkSEgoKYXBwbGllZF9ieRgDIAEoCRIPCgd2ZXJzaW9uGAQgASgJEkkKEW1hbmFnZWRfcmVzb3VyY2VzGAUgAygLMi4ubWVtb3MuYXBpLkNvbmZpZ3VyYXRpb25TdGF0dXMuTWFuYWdlZFJlc291cmNlEi4KCmFwcGx5X3RpbWUYBiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wGmMKD01hbmFnZWRSZXNvdXJjZRIQCghyZXNvdXJjZRgBIAEoCRIOCgZzb3VyY2UYAiABKAkSFgoObWFuYWdlZF9maWVsZHMYAyADKAkSFgoOaWdub3JlZF9maWVsZHMYBCADKAkqfQoSSW5zdGFuY2VBY2Nlc3NNb2RlEiQKIElOU1RBTkNFX0FDQ0VTU19NT0RFX1VOU1BFQ0lGSUVEEAASIAocSU5TVEFOQ0VfQUNDRVNTX01PREVfUFJJVkFURRABEh8KG0lOU1RBTkNFX0FDQ0VTU19NT0RFX1BVQkxJQxACMpEICg9JbnN0YW5jZVNlcnZpY2USdQoSR2V0SW5zdGFuY2VQcm9maWxlEiQubWVtb3MuYXBpLkdldEluc3RhbmNlUHJvZmlsZVJlcXVlc3QaGi5tZW1vcy5hcGkuSW5zdGFuY2VQcm9maWxlIh2C0+STAhcSFS9hcGkvaW5zdGFuY2UvcHJvZmlsZRKGAQoSR2V0SW5zdGFuY2VTZXR0aW5nEiQubWVtb3MuYXBpLkdldEluc3RhbmNlU2V0dGluZ1JlcXVlc3QaGi5tZW1vcy5hcGkuSW5zdGFuY2VTZXR0aW5nIi7aQQRuYW1lgtPkkwIhEh8vYXBpL3tuYW1lPWluc3RhbmNlL3NldHRpbmdzLyp9Ep8BChhCYXRjaEdldEluc3RhbmNlU2V0dGluZ3MSKi5tZW1vcy5hcGkuQmF0Y2hHZXRJbnN0YW5jZVNldHRpbmdzUmVxdWVzdBorLm1lbW9zLmFwaS5CYXRjaEdldEluc3RhbmNlU2V0dGluZ3NSZXNwb25zZSIqgtPkkwIkOgEqIh8vYXBpL2luc3RhbmNlL3NldHRpbmdzOmJhdGNoR2V0EscBChVVcGRhdGVJbnN0YW5jZVNldHRpbmcSJy5tZW1vcy5hcGkuVXBkYXRlSW5zdGFuY2VTZXR0aW5nUmVxdWVzdBoaLm1lbW9zLmFwaS5JbnN0YW5jZVNldHRpbmciadpBHGluc3RhbmNlX3NldHRpbmcsdXBkYXRlX21hc2uC0+STAkQ6EGluc3RhbmNlX3NldHRpbmcyMC9hcGkve2luc3RhbmNlX3NldHRpbmcubmFtZT1pbnN0YW5jZS9zZXR0aW5ncy8qfRKYAQoYVGVzdEluc3RhbmNlRW1haWxTZXR0aW5nEioubWVtb3MuYXBpLlRlc3RJbnN0YW5jZUVtYWlsU2V0dGluZ1JlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiOILT5JMCMjoBKiItL2FwaS9pbnN0YW5jZS9zZXR0aW5ncy9ub3RpZmljYXRpb246dGVzdEVtYWlsEm0KEEdldEluc3RhbmNlU3RhdHMSIi5tZW1vcy5hcGkuR2V0SW5zdGFuY2VTdGF0c1JlcXVlc3QaGC5tZW1vcy5hcGkuSW5zdGFuY2VTdGF0cyIbgtPkkwIVEhMvYXBpL2luc3RhbmNlL3N0YXRzEocBChZHZXRDb25maWd1cmF0aW9uU3RhdHVzEigubWVtb3MuYXBpLkdldENvbmZpZ3VyYXRpb25TdGF0dXNSZXF1ZXN0Gh4ubWVtb3MuYXBpLkNvbmZpZ3VyYXRpb25TdGF0dXMiI4LT5JMCHRIbL2FwaS9pbnN0YW5jZS9jb25maWd1cmF0aW9uQpMBCg1jb20ubWVtb3MuYXBpQhRJbnN0YW5jZVNlcnZpY2VQcm90b1ABWidnaXRodWIuY29tL3VzZW1lbW9zL21lbW9zL3Byb3RvL2dlbi9hcGmiAgNNQViqAglNZW1vcy5BcGnKAglNZW1vc1xBcGniAhVNZW1vc1xBcGlcR1BCTWV0YWRhdGHqAgpNZW1vczo6QXBpYgZwcm90bzM", [file_api_user_service, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_google_type_color]);
/**
* InstanceProfile is the basic information about the instance.
@@ -1382,6 +1382,120 @@ export type GetInstanceStatsRequest = Message<"memos.api.GetInstanceStatsRequest
export const GetInstanceStatsRequestSchema: GenMessage<GetInstanceStatsRequest> = /*@__PURE__*/
messageDesc(file_api_instance_service, 9);
+/**
+ * Request message for InstanceService.GetConfigurationStatus.
+ *
+ * @generated from message memos.api.GetConfigurationStatusRequest
+ */
+export type GetConfigurationStatusRequest = Message<"memos.api.GetConfigurationStatusRequest"> & {
+};
+
+/**
+ * Describes the message memos.api.GetConfigurationStatusRequest.
+ * Use `create(GetConfigurationStatusRequestSchema)` to create a new message.
+ */
+export const GetConfigurationStatusRequestSchema: GenMessage<GetConfigurationStatusRequest> = /*@__PURE__*/
+ messageDesc(file_api_instance_service, 10);
+
+/**
+ * ConfigurationStatus is what declarative configuration manages on the instance.
+ *
+ * @generated from message memos.api.ConfigurationStatus
+ */
+export type ConfigurationStatus = Message<"memos.api.ConfigurationStatus"> & {
+ /**
+ * The state record serial; zero before any apply has changed something.
+ *
+ * @generated from field: int64 serial = 1;
+ */
+ serial: bigint;
+
+ /**
+ * Identifies the applied configuration, with sensitive values masked before hashing.
+ *
+ * @generated from field: string config_digest = 2;
+ */
+ configDigest: string;
+
+ /**
+ * The apply path ("cli" or "startup") and the host of the last apply.
+ *
+ * @generated from field: string applied_by = 3;
+ */
+ appliedBy: string;
+
+ /**
+ * The Memos version of the last apply.
+ *
+ * @generated from field: string version = 4;
+ */
+ version: string;
+
+ /**
+ * The resources the configuration manages.
+ *
+ * @generated from field: repeated memos.api.ConfigurationStatus.ManagedResource managed_resources = 5;
+ */
+ managedResources: ConfigurationStatus_ManagedResource[];
+
+ /**
+ * When the last apply that changed something ran.
+ *
+ * @generated from field: google.protobuf.Timestamp apply_time = 6;
+ */
+ applyTime?: Timestamp | undefined;
+};
+
+/**
+ * Describes the message memos.api.ConfigurationStatus.
+ * Use `create(ConfigurationStatusSchema)` to create a new message.
+ */
+export const ConfigurationStatusSchema: GenMessage<ConfigurationStatus> = /*@__PURE__*/
+ messageDesc(file_api_instance_service, 11);
+
+/**
+ * ManagedResource is one resource the configuration manages.
+ *
+ * @generated from message memos.api.ConfigurationStatus.ManagedResource
+ */
+export type ConfigurationStatus_ManagedResource = Message<"memos.api.ConfigurationStatus.ManagedResource"> & {
+ /**
+ * The resource name.
+ * Format: identity-providers/{idp}, instance/settings/{setting}, or users/{user}
+ *
+ * @generated from field: string resource = 1;
+ */
+ resource: string;
+
+ /**
+ * The configuration file that declares the resource.
+ *
+ * @generated from field: string source = 2;
+ */
+ source: string;
+
+ /**
+ * The field paths, in JSON names, the configuration manages; "*" means the whole resource.
+ *
+ * @generated from field: repeated string managed_fields = 3;
+ */
+ managedFields: string[];
+
+ /**
+ * The managed field paths the configuration does not write after creation, so the API accepts edits to them.
+ *
+ * @generated from field: repeated string ignored_fields = 4;
+ */
+ ignoredFields: string[];
+};
+
+/**
+ * Describes the message memos.api.ConfigurationStatus.ManagedResource.
+ * Use `create(ConfigurationStatus_ManagedResourceSchema)` to create a new message.
+ */
+export const ConfigurationStatus_ManagedResourceSchema: GenMessage<ConfigurationStatus_ManagedResource> = /*@__PURE__*/
+ messageDesc(file_api_instance_service, 11, 0);
+
/**
* InstanceAccessMode controls whether unauthenticated users may access instance content.
*
@@ -1454,8 +1568,8 @@ export const InstanceService: GenService<{
output: typeof BatchGetInstanceSettingsResponseSchema;
},
/**
- * UpdateInstanceSetting replaces an instance setting. Admin only. Settings configured by the deployment cannot be
- * updated. Empty write-only credentials keep the stored values.
+ * UpdateInstanceSetting replaces an instance setting. Admin only. Fields declarative configuration manages cannot be
+ * changed. Empty write-only credentials keep the stored values.
*
* @generated from rpc memos.api.InstanceService.UpdateInstanceSetting
*/
@@ -1484,6 +1598,17 @@ export const InstanceService: GenService<{
input: typeof GetInstanceStatsRequestSchema;
output: typeof InstanceStatsSchema;
},
+ /**
+ * GetConfigurationStatus gets what declarative configuration manages: the managed resources and the last apply.
+ * Admin only. It carries resource names and field paths, never a configured value.
+ *
+ * @generated from rpc memos.api.InstanceService.GetConfigurationStatus
+ */
+ getConfigurationStatus: {
+ methodKind: "unary";
+ input: typeof GetConfigurationStatusRequestSchema;
+ output: typeof ConfigurationStatusSchema;
+ },
}> = /*@__PURE__*/
serviceDesc(file_api_instance_service, 0);
diff --git a/web/tests/configuration-queries.test.ts b/web/tests/configuration-queries.test.ts
new file mode 100644
index 000000000..dfaca2abf
--- /dev/null
+++ b/web/tests/configuration-queries.test.ts
@@ -0,0 +1,29 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, it } from "vitest";
+import { findManagedResource, isFieldManaged } from "@/hooks/useConfigurationQueries";
+import { ConfigurationStatus_ManagedResourceSchema, ConfigurationStatusSchema } from "@/types/proto/api/instance_service_pb";
+
+describe("isFieldManaged", () => {
+ const general = create(ConfigurationStatus_ManagedResourceSchema, {
+ resource: "instance/settings/GENERAL",
+ managedFields: ["*"],
+ ignoredFields: ["generalSetting.customProfile"],
+ });
+ const user = create(ConfigurationStatus_ManagedResourceSchema, { resource: "users/admin", managedFields: ["username", "role"] });
+
+ it("follows the managed and ignored paths the server enforces", () => {
+ expect(isFieldManaged(general, "generalSetting.disallowPasswordAuth")).toBe(true);
+ expect(isFieldManaged(general, "generalSetting.customProfile")).toBe(false);
+ expect(isFieldManaged(general, "generalSetting.customProfile.title")).toBe(false);
+ expect(isFieldManaged(user, "role")).toBe(true);
+ expect(isFieldManaged(user, "displayName")).toBe(false);
+ expect(isFieldManaged(undefined, "role")).toBe(false);
+ });
+
+ it("finds a managed resource by name", () => {
+ const status = create(ConfigurationStatusSchema, { managedResources: [general, user] });
+ expect(findManagedResource(status, "users/admin")).toBe(user);
+ expect(findManagedResource(status, "users/jane")).toBeUndefined();
+ expect(findManagedResource(undefined, "users/admin")).toBeUndefined();
+ });
+});
diff --git a/web/tests/instance-section-access.test.tsx b/web/tests/instance-section-access.test.tsx
index 72968a58f..6e0e66ce0 100644
--- a/web/tests/instance-section-access.test.tsx
+++ b/web/tests/instance-section-access.test.tsx
@@ -1,7 +1,8 @@
+import { create } from "@bufbuild/protobuf";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import InstanceSection from "@/components/Settings/InstanceSection";
-import { InstanceAccessMode } from "@/types/proto/api/instance_service_pb";
+import { type ConfigurationStatus, ConfigurationStatusSchema, InstanceAccessMode } from "@/types/proto/api/instance_service_pb";
const instance = vi.hoisted(() => ({
accessSetting: { accessMode: 1 },
@@ -20,6 +21,7 @@ const instance = vi.hoisted(() => ({
updateSetting: vi.fn(),
}));
const listIdentityProviders = vi.hoisted(() => vi.fn());
+const configuration = vi.hoisted(() => ({ status: undefined as ConfigurationStatus | undefined }));
vi.mock("@/contexts/InstanceContext", () => ({
useInstance: () => instance,
@@ -31,6 +33,15 @@ vi.mock("@/connect", () => ({
},
}));
+vi.mock("@/hooks/useConfigurationQueries", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/hooks/useConfigurationQueries")>();
+ return {
+ ...actual,
+ useConfigurationStatus: () => configuration.status,
+ useManagedResource: (name: string) => actual.findManagedResource(configuration.status, name),
+ };
+});
+
vi.mock("@/components/UpdateCustomizedProfileDialog", () => ({ default: () => null }));
vi.mock("@/utils/i18n", () => ({
@@ -43,6 +54,7 @@ describe("<InstanceSection> access setting", () => {
listIdentityProviders.mockResolvedValue({ identityProviders: [] });
instance.fetchSetting.mockReset().mockResolvedValue(undefined);
instance.updateSetting.mockReset().mockResolvedValue(undefined);
+ configuration.status = undefined;
});
it("saves public access through the dedicated ACCESS setting", async () => {
@@ -73,4 +85,29 @@ describe("<InstanceSection> access setting", () => {
const accessHeading = screen.getByRole("heading", { level: 4, name: "setting.instance.access-title" });
expect(weekStartDay.compareDocumentPosition(accessHeading) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
+
+ it("locks fields configuration manages and leaves released ones editable", () => {
+ configuration.status = create(ConfigurationStatusSchema, {
+ serial: 1n,
+ managedResources: [
+ {
+ resource: "instance/settings/GENERAL",
+ source: "instance.json",
+ managedFields: ["*"],
+ ignoredFields: ["generalSetting.additionalStyle"],
+ },
+ ],
+ });
+ render(<InstanceSection />);
+
+ const switches = screen.getAllByRole("switch");
+ expect(switches[0]).not.toHaveAttribute("aria-disabled");
+ // Base UI switches are spans that report being disabled through ARIA.
+ expect(switches[1]).toHaveAttribute("aria-disabled", "true");
+ expect(screen.getByRole("button", { name: "common.edit" })).toBeDisabled();
+ expect(screen.getByPlaceholderText("setting.system.additional-style-placeholder")).not.toBeDisabled();
+ expect(screen.getByPlaceholderText("setting.system.additional-script-placeholder")).toBeDisabled();
+ // Basic, access, and custom code each have a managed field, so each names the file.
+ expect(screen.getAllByText("instance.json")).toHaveLength(3);
+ });
});
diff --git a/web/tests/memo-related-settings.test.tsx b/web/tests/memo-related-settings.test.tsx
index e378a13ae..0bea38c9e 100644
--- a/web/tests/memo-related-settings.test.tsx
+++ b/web/tests/memo-related-settings.test.tsx
@@ -2,7 +2,13 @@ import { create } from "@bufbuild/protobuf";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import MemoRelatedSettings from "@/components/Settings/MemoRelatedSettings";
-import { type InstanceSetting, InstanceSetting_Key, InstanceSetting_MemoRelatedSettingSchema } from "@/types/proto/api/instance_service_pb";
+import {
+ type ConfigurationStatus,
+ ConfigurationStatusSchema,
+ type InstanceSetting,
+ InstanceSetting_Key,
+ InstanceSetting_MemoRelatedSettingSchema,
+} from "@/types/proto/api/instance_service_pb";
const mocks = vi.hoisted(() => ({
instance: {
@@ -13,11 +19,21 @@ const mocks = vi.hoisted(() => ({
toastError: vi.fn(),
toastSuccess: vi.fn(),
}));
+const configuration = vi.hoisted(() => ({ status: undefined as ConfigurationStatus | undefined }));
vi.mock("@/contexts/InstanceContext", () => ({
useInstance: () => mocks.instance,
}));
+vi.mock("@/hooks/useConfigurationQueries", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/hooks/useConfigurationQueries")>();
+ return {
+ ...actual,
+ useConfigurationStatus: () => configuration.status,
+ useManagedResource: (name: string) => actual.findManagedResource(configuration.status, name),
+ };
+});
+
vi.mock("@/utils/i18n", () => ({
useTranslate: () => (key: string) => key,
}));
@@ -38,6 +54,7 @@ describe("<MemoRelatedSettings>", () => {
mocks.instance.fetchSetting.mockReset().mockResolvedValue(undefined);
mocks.toastError.mockReset();
mocks.toastSuccess.mockReset();
+ configuration.status = undefined;
});
it("saves only the reaction list", async () => {
@@ -53,4 +70,14 @@ describe("<MemoRelatedSettings>", () => {
expect(setting.value.value).toEqual(create(InstanceSetting_MemoRelatedSettingSchema, { reactions: ["thumbs-up", "heart"] }));
expect(mocks.instance.fetchSetting).toHaveBeenCalledWith(InstanceSetting_Key.MEMO_RELATED);
});
+
+ it("locks the reactions configuration manages", () => {
+ configuration.status = create(ConfigurationStatusSchema, {
+ managedResources: [{ resource: "instance/settings/MEMO_RELATED", source: "memo.json", managedFields: ["*"] }],
+ });
+ render(<MemoRelatedSettings />);
+ expect(screen.getByPlaceholderText("setting.memo.reaction-placeholder")).toBeDisabled();
+ expect(screen.getByRole("button", { name: "setting.memo.remove-reaction" })).toBeDisabled();
+ expect(screen.getByText("memo.json")).toBeInTheDocument();
+ });
});