feat(instance): persist access mode independently of URL (#6225)

This commit is contained in:
amblued 2026-08-22 14:15:31 +08:00 committed by GitHub
parent ee6560e0d9
commit 76a7629243
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
60 changed files with 2369 additions and 480 deletions

View file

@ -4,18 +4,19 @@ import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/internal/version"
"github.com/usememos/memos/internal/webhook"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/server"
"github.com/usememos/memos/store"
"github.com/usememos/memos/store/db"
@ -31,79 +32,12 @@ func initSlogDefault() {
var (
rootCmd = &cobra.Command{
Use: "memos",
Short: `An open source, lightweight note-taking service. Easily capture and share your great thoughts.`,
Run: func(_ *cobra.Command, _ []string) {
instanceProfile := &profile.Profile{
Demo: viper.GetBool("demo"),
Addr: viper.GetString("addr"),
Port: viper.GetInt("port"),
UNIXSock: viper.GetString("unix-sock"),
Data: viper.GetString("data"),
Driver: viper.GetString("driver"),
DSN: viper.GetString("dsn"),
InstanceURL: viper.GetString("instance-url"),
}
instanceProfile.Version = version.GetCurrentVersion()
instanceProfile.Commit = version.Commit
webhook.AllowPrivateIPs = viper.GetBool("allow-private-webhooks")
if err := instanceProfile.Validate(); err != nil {
slog.Error("failed to validate profile", "error", err)
return
}
ctx, cancel := context.WithCancel(context.Background())
dbDriver, err := db.NewDBDriver(instanceProfile)
if err != nil {
cancel()
slog.Error("failed to create db driver", "error", err)
return
}
storeInstance := store.New(dbDriver, instanceProfile)
if err := storeInstance.Migrate(ctx); err != nil {
cancel()
slog.Error("failed to migrate", "error", err)
return
}
if err := storeInstance.LoadDeploymentConfiguration(ctx); err != nil {
cancel()
slog.Error("failed to load deployment configuration", "error", err)
return
}
s, err := server.NewServer(ctx, instanceProfile, storeInstance)
if err != nil {
cancel()
slog.Error("failed to create server", "error", err)
return
}
c := make(chan os.Signal, 1)
// Trigger graceful shutdown on SIGINT or SIGTERM.
// The default signal sent by the `kill` command is SIGTERM,
// which is taken as the graceful shutdown signal for many systems, eg., Kubernetes, Gunicorn.
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
if err := s.Start(); err != nil {
if err != http.ErrServerClosed {
slog.Error("failed to start server", "error", err)
cancel()
return
}
}
printGreetings(instanceProfile)
go func() {
<-c
s.Shutdown(ctx)
cancel()
}()
// Wait for CTRL-C.
<-ctx.Done()
Use: "memos",
Short: `An open source, lightweight note-taking service. Easily capture and share your great thoughts.`,
SilenceErrors: true,
SilenceUsage: true,
RunE: func(_ *cobra.Command, _ []string) error {
return runServer()
},
}
versionCmd = &cobra.Command{
@ -122,46 +56,37 @@ func init() {
viper.SetDefault("driver", "sqlite")
viper.SetDefault("port", 8081)
rootCmd.PersistentFlags().Bool("demo", false, "enable demo mode")
rootCmd.PersistentFlags().String("addr", "", "address of server")
rootCmd.PersistentFlags().Int("port", 8081, "port of server")
rootCmd.PersistentFlags().String("unix-sock", "", "path to the unix socket, overrides --addr and --port")
rootCmd.PersistentFlags().String("data", "", "data directory")
rootCmd.PersistentFlags().String("driver", "sqlite", "database driver")
rootCmd.PersistentFlags().String("dsn", "", "database source name(aka. DSN)")
rootCmd.PersistentFlags().String("instance-url", "", "the url of your memos instance")
rootCmd.PersistentFlags().Bool("allow-private-webhooks", false, "allow webhook URLs to resolve to private/reserved IP addresses")
rootCmd.PersistentFlags().String("log-level", "info", "log verbosity level (debug, info, warn, error)")
rootCmd.Flags().Bool("demo", false, "enable demo mode")
rootCmd.Flags().String("addr", "", "address of server")
rootCmd.Flags().Int("port", 8081, "port of server")
rootCmd.Flags().String("unix-sock", "", "path to the unix socket, overrides --addr and --port")
rootCmd.Flags().String("data", "", "data directory")
rootCmd.Flags().String("driver", "sqlite", "database driver")
rootCmd.Flags().String("dsn", "", "database source name (DSN)")
rootCmd.Flags().String("instance-url", "", "canonical external URL of the Memos instance")
rootCmd.Flags().Bool("allow-private-webhooks", false, "allow webhooks to access any private/reserved IP address")
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)")
if err := viper.BindPFlag("demo", rootCmd.PersistentFlags().Lookup("demo")); err != nil {
if err := rootCmd.Flags().MarkDeprecated("allow-private-webhooks", "use --webhook-private-network-allowlist to allow only required destinations"); err != nil {
panic(err)
}
if err := viper.BindPFlag("addr", rootCmd.PersistentFlags().Lookup("addr")); err != nil {
panic(err)
}
if err := viper.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port")); err != nil {
panic(err)
}
if err := viper.BindPFlag("unix-sock", rootCmd.PersistentFlags().Lookup("unix-sock")); err != nil {
panic(err)
}
if err := viper.BindPFlag("data", rootCmd.PersistentFlags().Lookup("data")); err != nil {
panic(err)
}
if err := viper.BindPFlag("driver", rootCmd.PersistentFlags().Lookup("driver")); err != nil {
panic(err)
}
if err := viper.BindPFlag("dsn", rootCmd.PersistentFlags().Lookup("dsn")); err != nil {
panic(err)
}
if err := viper.BindPFlag("instance-url", rootCmd.PersistentFlags().Lookup("instance-url")); err != nil {
panic(err)
}
if err := viper.BindPFlag("allow-private-webhooks", rootCmd.PersistentFlags().Lookup("allow-private-webhooks")); err != nil {
panic(err)
}
if err := viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level")); err != nil {
panic(err)
for _, key := range []string{
"demo",
"addr",
"port",
"unix-sock",
"data",
"driver",
"dsn",
"instance-url",
"allow-private-webhooks",
"webhook-private-network-allowlist",
"log-level",
} {
if err := viper.BindPFlag(key, rootCmd.Flags().Lookup(key)); err != nil {
panic(err)
}
}
viper.SetEnvPrefix("memos")
@ -171,14 +96,96 @@ func init() {
rootCmd.AddCommand(versionCmd)
}
func printGreetings(profile *profile.Profile) {
func runServer() error {
instanceProfile := &profile.Profile{
Demo: viper.GetBool("demo"),
Addr: viper.GetString("addr"),
Port: viper.GetInt("port"),
UNIXSock: viper.GetString("unix-sock"),
Data: viper.GetString("data"),
Driver: viper.GetString("driver"),
DSN: viper.GetString("dsn"),
InstanceURL: viper.GetString("instance-url"),
Version: version.GetCurrentVersion(),
Commit: version.Commit,
}
allowPrivateWebhooks := viper.GetBool("allow-private-webhooks")
//nolint:staticcheck // The deprecated CLI/env input remains supported for upgrade compatibility.
webhook.AllowPrivateIPs = allowPrivateWebhooks
if allowPrivateWebhooks {
slog.Warn("--allow-private-webhooks is deprecated and disables webhook private-network protection; use --webhook-private-network-allowlist")
}
if err := webhook.ConfigurePrivateDestinationAllowlist(privateWebhookAllowlist()); err != nil {
return errors.Wrap(err, "failed to configure private webhook destinations")
}
if err := instanceProfile.Validate(); err != nil {
return errors.Wrap(err, "failed to validate profile")
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dbDriver, err := db.NewDBDriver(instanceProfile)
if err != nil {
return errors.Wrap(err, "failed to create database driver")
}
storeInstance := store.New(dbDriver, instanceProfile)
closeStore := true
defer func() {
if closeStore {
if err := storeInstance.Close(); err != nil {
slog.Error("failed to close store", "error", err)
}
}
}()
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")
}
accessSetting, err := storeInstance.GetInstanceAccessSetting(ctx)
if err != nil {
return errors.Wrap(err, "failed to get instance access setting")
}
s, err := server.NewServer(ctx, instanceProfile, storeInstance)
if err != nil {
return errors.Wrap(err, "failed to create server")
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(signals)
if err := s.Start(); err != nil {
return errors.Wrap(err, "failed to start server")
}
closeStore = false
printGreetings(instanceProfile, accessSetting.AccessMode)
<-signals
s.Shutdown(context.Background())
return nil
}
func privateWebhookAllowlist() []string {
var entries []string
for _, value := range viper.GetStringSlice("webhook-private-network-allowlist") {
for entry := range strings.SplitSeq(value, ",") {
if entry = strings.TrimSpace(entry); entry != "" {
entries = append(entries, entry)
}
}
}
return entries
}
func printGreetings(profile *profile.Profile, accessMode storepb.InstanceAccessMode) {
fmt.Printf("Memos %s started successfully!\n", profile.Version)
if profile.Demo {
fmt.Fprint(os.Stderr, "Development mode is enabled\n")
if profile.DSN != "" {
fmt.Fprintf(os.Stderr, "Database: %s\n", profile.DSN)
}
fmt.Fprint(os.Stderr, "Demo mode is enabled\n")
}
// Server information
@ -198,12 +205,11 @@ func printGreetings(profile *profile.Profile) {
fmt.Printf("Server running on unix socket: %s\n", profile.UNIXSock)
}
// Access mode is derived from instance_url: set = public, unset = private.
accessMode := "private"
if profile.AllowAnonymous() {
accessMode = "public"
accessModeLabel := "private"
if accessMode == storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC {
accessModeLabel = "public"
}
fmt.Printf("Access mode: %s\n", accessMode)
fmt.Printf("Access mode: %s\n", accessModeLabel)
fmt.Println()
fmt.Printf("Documentation: %s\n", "https://usememos.com")
@ -213,6 +219,7 @@ func printGreetings(profile *profile.Profile) {
func main() {
if err := rootCmd.Execute(); err != nil {
slog.Error("memos failed", slog.String("error", err.Error()))
os.Exit(1)
}
}

26
cmd/memos/main_test.go Normal file
View file

@ -0,0 +1,26 @@
package main
import (
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
)
func TestServerFlagsAreNotInheritedBySubcommands(t *testing.T) {
require.Nil(t, versionCmd.InheritedFlags().Lookup("dsn"))
require.Nil(t, versionCmd.InheritedFlags().Lookup("instance-url"))
require.Nil(t, versionCmd.InheritedFlags().Lookup("allow-private-webhooks"))
}
func TestPrivateWebhookAllowlistSplitsFlagAndEnvironmentForms(t *testing.T) {
const key = "webhook-private-network-allowlist"
original := viper.Get(key)
t.Cleanup(func() { viper.Set(key, original) })
viper.Set(key, "hooks.internal,10.0.0.0/8")
require.Equal(t, []string{"hooks.internal", "10.0.0.0/8"}, privateWebhookAllowlist())
viper.Set(key, []string{"hooks.internal, 10.0.0.0/8", "192.168.1.10"})
require.Equal(t, []string{"hooks.internal", "10.0.0.0/8", "192.168.1.10"}, privateWebhookAllowlist())
}

View file

@ -10,7 +10,7 @@ remains authoritative for that process lifetime. It is not imported into the dat
The first supported file-backed configuration resources are:
- OAuth2 identity providers.
- Instance settings for general policy, storage, memo behavior, notifications, and AI 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.
@ -88,6 +88,7 @@ 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` |
@ -189,6 +190,21 @@ Example `/etc/secrets/memos-instance-setting-general.json`:
}
```
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
@ -215,6 +231,7 @@ 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 |
@ -281,6 +298,7 @@ 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
@ -341,6 +359,9 @@ Every effective instance-setting getter checks the runtime snapshot before its d
- 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.
@ -354,6 +375,7 @@ 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.
@ -414,6 +436,19 @@ an administrator attempts to create, update, or delete a deployment-managed reso
- 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
@ -423,17 +458,28 @@ A rolling deployment can temporarily run old and new configuration generations a
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 and no migrations:
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
@ -462,6 +508,7 @@ The implementation:
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
@ -487,6 +534,8 @@ The implementation requires tests for:
- 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

View file

@ -3,6 +3,7 @@ package profile
import (
"fmt"
"log/slog"
"net/url"
"os"
"path/filepath"
"runtime"
@ -32,21 +33,10 @@ type Profile struct {
Version string
// Commit is the current build commit of server
Commit string
// InstanceURL is the url of your memos instance.
// InstanceURL is the canonical external URL of the Memos instance.
InstanceURL string
}
// AllowAnonymous reports whether unauthenticated visitors may access the instance.
//
// Anonymous access is enabled only when an InstanceURL is configured. An instance
// with no InstanceURL set is treated as private: anonymous callers are limited to
// the auth-bootstrap endpoints (sign-in, share links, etc.) and the web UI redirects
// them to the sign-in page instead of the public Explore view. Authenticated callers
// (session, access token, or personal access token) are never affected.
func (p *Profile) AllowAnonymous() bool {
return strings.TrimSpace(p.InstanceURL) != ""
}
func checkDataDir(dataDir string) (string, error) {
// Convert to absolute path if relative path is supplied.
if !filepath.IsAbs(dataDir) {
@ -68,6 +58,16 @@ func checkDataDir(dataDir string) (string, error) {
}
func (p *Profile) Validate() error {
if p.Demo && p.Driver != "sqlite" {
return errors.Errorf("demo mode requires the sqlite database driver, got %q", p.Driver)
}
instanceURL, err := normalizeInstanceURL(p.InstanceURL)
if err != nil {
return err
}
p.InstanceURL = instanceURL
// Set default data directory if not specified
if p.Data == "" {
if runtime.GOOS == "windows" {
@ -118,3 +118,31 @@ func (p *Profile) Validate() error {
return nil
}
func normalizeInstanceURL(rawURL string) (string, error) {
rawURL = strings.TrimSpace(rawURL)
if rawURL == "" {
return "", nil
}
instanceURL, err := url.Parse(rawURL)
if err != nil {
return "", errors.Wrap(err, "failed to parse instance URL")
}
if instanceURL.Scheme != "http" && instanceURL.Scheme != "https" {
return "", errors.Errorf("instance URL must use http or https, got %q", instanceURL.Scheme)
}
if instanceURL.Host == "" {
return "", errors.New("instance URL must include a host")
}
if instanceURL.User != nil {
return "", errors.New("instance URL must not include user credentials")
}
if instanceURL.RawQuery != "" || instanceURL.Fragment != "" {
return "", errors.New("instance URL must not include a query or fragment")
}
instanceURL.Path = strings.TrimRight(instanceURL.Path, "/")
instanceURL.RawPath = strings.TrimRight(instanceURL.RawPath, "/")
return instanceURL.String(), nil
}

View file

@ -1,24 +1,44 @@
package profile
import "testing"
import (
"testing"
func TestAllowAnonymous(t *testing.T) {
"github.com/stretchr/testify/require"
)
func TestValidateInstanceURL(t *testing.T) {
cases := []struct {
name string
url string
want bool
name string
url string
want string
wantErr bool
}{
{"empty is private", "", false},
{"whitespace only is private", " ", false},
{"configured url is public", "https://memos.example.com", true},
{"configured url with padding is public", " https://memos.example.com ", true},
{name: "empty", url: ""},
{name: "canonical https", url: "https://memos.example.com", want: "https://memos.example.com"},
{name: "trim spaces and trailing slash", url: " https://memos.example.com/app/ ", want: "https://memos.example.com/app"},
{name: "http with port", url: "http://localhost:8080/", want: "http://localhost:8080"},
{name: "missing scheme", url: "memos.example.com", wantErr: true},
{name: "unsupported scheme", url: "ftp://memos.example.com", wantErr: true},
{name: "missing host", url: "https:///memos", wantErr: true},
{name: "credentials", url: "https://user:pass@memos.example.com", wantErr: true},
{name: "query", url: "https://memos.example.com?tenant=one", wantErr: true},
{name: "fragment", url: "https://memos.example.com/#top", wantErr: true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
p := &Profile{InstanceURL: c.url}
if got := p.AllowAnonymous(); got != c.want {
t.Fatalf("AllowAnonymous() with InstanceURL=%q = %v, want %v", c.url, got, c.want)
p := &Profile{Data: t.TempDir(), Driver: "sqlite", InstanceURL: c.url}
err := p.Validate()
if c.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
require.Equal(t, c.want, p.InstanceURL)
})
}
}
func TestValidateRejectsDemoWithNonSQLiteDriver(t *testing.T) {
p := &Profile{Demo: true, Driver: "postgres", Data: t.TempDir()}
require.ErrorContains(t, p.Validate(), "demo mode requires the sqlite database driver")
}

View file

@ -2,57 +2,178 @@ package webhook
import (
"net"
"net/netip"
"net/url"
"strings"
"sync/atomic"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// reservedCIDRs lists IP ranges that must never be targeted by outbound webhook requests.
// Covers loopback, RFC-1918 private, link-local (including cloud IMDS at 169.254.169.254),
// and their IPv6 equivalents.
var reservedCIDRs = []string{
"127.0.0.0/8", // IPv4 loopback
"10.0.0.0/8", // RFC-1918 class A
"172.16.0.0/12", // RFC-1918 class B
"192.168.0.0/16", // RFC-1918 class C
"169.254.0.0/16", // Link-local / cloud IMDS
"::1/128", // IPv6 loopback
"fc00::/7", // IPv6 unique local
"fe80::/10", // IPv6 link-local
// reservedNetworks lists IP ranges blocked by default for outbound webhook requests.
// Explicit allowlist entries or the deprecated blanket override may permit them. The
// ranges cover loopback, RFC-1918 private, link-local (including cloud IMDS at
// 169.254.169.254), and their IPv6 equivalents.
var reservedNetworks = []netip.Prefix{
netip.MustParsePrefix("127.0.0.0/8"), // IPv4 loopback
netip.MustParsePrefix("10.0.0.0/8"), // RFC-1918 class A
netip.MustParsePrefix("172.16.0.0/12"), // RFC-1918 class B
netip.MustParsePrefix("192.168.0.0/16"), // RFC-1918 class C
netip.MustParsePrefix("169.254.0.0/16"), // Link-local / cloud IMDS
netip.MustParsePrefix("::1/128"), // IPv6 loopback
netip.MustParsePrefix("fc00::/7"), // IPv6 unique local
netip.MustParsePrefix("fe80::/10"), // IPv6 link-local
}
// reservedNetworks is the parsed form of reservedCIDRs, built once at startup.
var reservedNetworks []*net.IPNet
func init() {
for _, cidr := range reservedCIDRs {
_, network, err := net.ParseCIDR(cidr)
if err != nil {
panic("webhook: invalid reserved CIDR " + cidr + ": " + err.Error())
}
reservedNetworks = append(reservedNetworks, network)
}
type privateDestinationPolicy struct {
hostnames map[string]struct{}
prefixes []netip.Prefix
}
var configuredPrivateDestinations atomic.Pointer[privateDestinationPolicy]
// AllowPrivateIPs controls whether webhook URLs may resolve to reserved/private
// IP addresses. When true, the SSRF protection is disabled. This is useful for
// self-hosted deployments where webhooks target services on the local network.
//
// Deprecated: use ConfigurePrivateDestinationAllowlist to allow only the
// destinations that the deployment needs.
var AllowPrivateIPs bool
// isReservedIP reports whether ip falls within any reserved/private range.
func isReservedIP(ip net.IP) bool {
if AllowPrivateIPs {
addr, ok := netip.AddrFromSlice(ip)
if !ok {
return false
}
addr = addr.Unmap()
for _, network := range reservedNetworks {
if network.Contains(ip) {
if network.Contains(addr) {
return true
}
}
return false
}
// ConfigurePrivateDestinationAllowlist replaces the deployment's webhook
// allowlist. Each entry must be an exact hostname, an IP address, or a CIDR.
// Hostnames are matched case-insensitively, IP addresses are treated as
// single-address CIDRs, and CIDRs are masked to their network address.
//
// The new policy is published only after every entry is valid, so a failed
// configuration leaves the previous policy intact. Passing an empty slice
// clears the allowlist.
func ConfigurePrivateDestinationAllowlist(entries []string) error {
policy := &privateDestinationPolicy{
hostnames: make(map[string]struct{}),
prefixes: make([]netip.Prefix, 0, len(entries)),
}
for _, rawEntry := range entries {
entry := strings.TrimSpace(rawEntry)
if entry == "" {
return errors.Errorf("webhook: private destination allowlist contains an empty entry")
}
if addr, err := netip.ParseAddr(entry); err == nil {
if addr.Zone() != "" {
return errors.Errorf("webhook: invalid private destination allowlist entry %q: scoped IP addresses are not supported", rawEntry)
}
addr = addr.Unmap()
policy.prefixes = append(policy.prefixes, netip.PrefixFrom(addr, addr.BitLen()))
continue
}
if prefix, err := netip.ParsePrefix(entry); err == nil {
normalized, err := normalizePrefix(prefix)
if err != nil {
return errors.Wrapf(err, "webhook: invalid private destination allowlist entry %q", rawEntry)
}
policy.prefixes = append(policy.prefixes, normalized)
continue
} else if strings.Contains(entry, "/") {
return errors.Wrapf(err, "webhook: invalid private destination allowlist entry %q", rawEntry)
}
hostname, err := normalizeHostname(entry)
if err != nil {
return errors.Wrapf(err, "webhook: invalid private destination allowlist entry %q", rawEntry)
}
policy.hostnames[hostname] = struct{}{}
}
configuredPrivateDestinations.Store(policy)
return nil
}
func normalizePrefix(prefix netip.Prefix) (netip.Prefix, error) {
addr := prefix.Addr()
bits := prefix.Bits()
if addr.Is4In6() {
if bits < 96 {
return netip.Prefix{}, errors.Errorf("IPv4-mapped IPv6 prefix must have at least 96 prefix bits")
}
addr = addr.Unmap()
bits -= 96
}
return netip.PrefixFrom(addr, bits).Masked(), nil
}
func normalizeHostname(hostname string) (string, error) {
hostname = strings.ToLower(strings.TrimSuffix(hostname, "."))
if hostname == "" || len(hostname) > 253 {
return "", errors.Errorf("hostname must contain between 1 and 253 characters")
}
for _, label := range strings.Split(hostname, ".") {
if label == "" || len(label) > 63 {
return "", errors.Errorf("hostname labels must contain between 1 and 63 characters")
}
for i, r := range label {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || (r == '-' && i > 0 && i < len(label)-1) {
continue
}
return "", errors.Errorf("hostname contains an invalid character")
}
}
return hostname, nil
}
func isPrivateDestinationAllowed(hostname string, ip net.IP) bool {
if AllowPrivateIPs {
return true
}
policy := configuredPrivateDestinations.Load()
if policy == nil {
return false
}
if normalizedHostname, err := normalizeHostname(hostname); err == nil {
if _, ok := policy.hostnames[normalizedHostname]; ok {
return true
}
}
addr, ok := netip.AddrFromSlice(ip)
if !ok {
return false
}
addr = addr.Unmap()
for _, prefix := range policy.prefixes {
if prefix.Contains(addr) {
return true
}
}
return false
}
func isBlockedDestination(hostname string, ip net.IP) bool {
return isReservedIP(ip) && !isPrivateDestinationAllowed(hostname, ip)
}
// ValidateURL checks that rawURL:
// 1. Parses as a valid absolute URL.
// 2. Uses the http or https scheme.
@ -75,7 +196,7 @@ func ValidateURL(rawURL string) error {
for _, ipStr := range ips {
ip := net.ParseIP(ipStr)
if ip != nil && isReservedIP(ip) {
if ip != nil && isBlockedDestination(u.Hostname(), ip) {
return status.Errorf(codes.InvalidArgument, "webhook URL must not resolve to a reserved or private IP address")
}
}

View file

@ -12,6 +12,7 @@ import (
"log/slog"
"net"
"net/http"
"net/netip"
"strconv"
"strings"
"time"
@ -55,25 +56,47 @@ func init() {
}
// safeDialContext is a net.Dialer.DialContext replacement that resolves the target
// hostname and rejects any address that falls within a reserved/private IP range.
// hostname, rejects disallowed reserved/private addresses, and dials an already
// checked IP address so DNS cannot be rebound between validation and connection.
func safeDialContext(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, errors.Errorf("webhook: invalid address %q", addr)
}
ips, err := net.DefaultResolver.LookupHost(ctx, host)
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
if err != nil {
return nil, errors.Wrapf(err, "webhook: failed to resolve host %q", host)
}
for _, ipStr := range ips {
if ip := net.ParseIP(ipStr); ip != nil && isReservedIP(ip) {
validIPs := make([]net.IPAddr, 0, len(ips))
for _, ip := range ips {
if parsed, ok := netip.AddrFromSlice(ip.IP); !ok || !parsed.IsValid() {
continue
}
if isBlockedDestination(host, ip.IP) {
return nil, errors.Errorf("webhook: connection to reserved/private IP address is not allowed")
}
validIPs = append(validIPs, ip)
}
return (&net.Dialer{}).DialContext(ctx, network, net.JoinHostPort(host, port))
var dialErr error
dialer := &net.Dialer{}
for _, ip := range validIPs {
dialHost := ip.IP.String()
if ip.Zone != "" {
dialHost += "%" + ip.Zone
}
conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(dialHost, port))
if err == nil {
return conn, nil
}
dialErr = err
}
if dialErr != nil {
return nil, errors.Wrapf(dialErr, "webhook: failed to connect to host %q", host)
}
return nil, errors.Errorf("webhook: host %q resolved to no IP addresses", host)
}
type WebhookRequestPayload struct {

View file

@ -5,14 +5,155 @@ import (
"crypto/sha256"
"encoding/base64"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/require"
)
func resetPrivateDestinationPolicy(t *testing.T) {
t.Helper()
previousAllowPrivateIPs := AllowPrivateIPs
AllowPrivateIPs = false
require.NoError(t, ConfigurePrivateDestinationAllowlist(nil))
t.Cleanup(func() {
AllowPrivateIPs = previousAllowPrivateIPs
require.NoError(t, ConfigurePrivateDestinationAllowlist(nil))
})
}
func TestConfigurePrivateDestinationAllowlist(t *testing.T) {
t.Run("exact hostname is normalized", func(t *testing.T) {
resetPrivateDestinationPolicy(t)
require.NoError(t, ConfigurePrivateDestinationAllowlist([]string{" LOCALHOST. "}))
require.NoError(t, ValidateURL("http://localhost:8080/hook"))
})
t.Run("exact IP is allowed", func(t *testing.T) {
resetPrivateDestinationPolicy(t)
require.NoError(t, ConfigurePrivateDestinationAllowlist([]string{"127.0.0.42"}))
require.NoError(t, ValidateURL("http://127.0.0.42/hook"))
require.Error(t, ValidateURL("http://127.0.0.43/hook"))
})
t.Run("CIDR is normalized and allowed", func(t *testing.T) {
resetPrivateDestinationPolicy(t)
require.NoError(t, ConfigurePrivateDestinationAllowlist([]string{"127.0.0.99/24"}))
require.NoError(t, ValidateURL("http://127.0.0.42/hook"))
require.Error(t, ValidateURL("http://127.0.1.42/hook"))
})
t.Run("invalid entry leaves prior policy intact", func(t *testing.T) {
resetPrivateDestinationPolicy(t)
require.NoError(t, ConfigurePrivateDestinationAllowlist([]string{"localhost"}))
invalidEntries := []string{
"",
"http://localhost",
"localhost:8080",
"*.example.com",
"bad_name",
"127.0.0.1/999",
"-invalid.example",
}
for _, entry := range invalidEntries {
require.Error(t, ConfigurePrivateDestinationAllowlist([]string{entry}), entry)
require.NoError(t, ValidateURL("http://localhost/hook"), "failed configuration must not replace the active policy")
}
})
t.Run("nonmatching private target remains blocked", func(t *testing.T) {
resetPrivateDestinationPolicy(t)
require.NoError(t, ConfigurePrivateDestinationAllowlist([]string{"10.0.0.0/8", "hooks.internal"}))
require.Error(t, ValidateURL("http://127.0.0.1/hook"))
})
t.Run("public target remains allowed", func(t *testing.T) {
resetPrivateDestinationPolicy(t)
require.False(t, isBlockedDestination("dns.google", net.ParseIP("8.8.8.8")))
})
}
func TestPrivateDestinationPolicyConcurrentAccess(t *testing.T) {
resetPrivateDestinationPolicy(t)
privateIP := net.ParseIP("127.0.0.1")
var waitGroup sync.WaitGroup
for range 8 {
waitGroup.Go(func() {
for range 100 {
_ = isPrivateDestinationAllowed("localhost", privateIP)
}
})
waitGroup.Go(func() {
for range 100 {
if err := ConfigurePrivateDestinationAllowlist([]string{"localhost", "127.0.0.0/8"}); err != nil {
t.Errorf("ConfigurePrivateDestinationAllowlist() error = %v", err)
}
}
})
}
waitGroup.Wait()
}
func TestAllowPrivateIPsCompatibility(t *testing.T) {
resetPrivateDestinationPolicy(t)
AllowPrivateIPs = true
require.NoError(t, ValidateURL("http://127.0.0.1/hook"))
}
func TestPostChecksRedirectDestinationAtDialTime(t *testing.T) {
resetPrivateDestinationPolicy(t)
require.NoError(t, ConfigurePrivateDestinationAllowlist([]string{"localhost"}))
var redirectedRequestReceived atomic.Bool
redirectTarget := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
redirectedRequestReceived.Store(true)
_, _ = w.Write([]byte(`{"code":0}`))
}))
defer redirectTarget.Close()
redirectSource := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Location", redirectTarget.URL)
w.WriteHeader(http.StatusFound)
}))
defer redirectSource.Close()
sourceURL := strings.Replace(redirectSource.URL, "127.0.0.1", "localhost", 1)
err := Post(&WebhookRequestPayload{URL: sourceURL})
require.ErrorContains(t, err, "connection to reserved/private IP address is not allowed")
require.False(t, redirectedRequestReceived.Load())
}
func TestPostAllowsExplicitPrivateIPPolicyAtDialTime(t *testing.T) {
tests := []struct {
name string
allowlist []string
}{
{name: "exact IP", allowlist: []string{"127.0.0.1"}},
{name: "CIDR", allowlist: []string{"127.0.0.99/8"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
resetPrivateDestinationPolicy(t)
require.NoError(t, ConfigurePrivateDestinationAllowlist(tc.allowlist))
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"code":0}`))
}))
defer server.Close()
require.NoError(t, Post(&WebhookRequestPayload{URL: server.URL}))
})
}
}
func TestPostAsyncNilPayloadDoesNotPanic(t *testing.T) {
require.NotPanics(t, func() {
PostAsync(nil)

View file

@ -57,6 +57,13 @@ service InstanceService {
}
}
// InstanceAccessMode controls whether unauthenticated users may access instance content.
enum InstanceAccessMode {
INSTANCE_ACCESS_MODE_UNSPECIFIED = 0;
INSTANCE_ACCESS_MODE_PRIVATE = 1;
INSTANCE_ACCESS_MODE_PUBLIC = 2;
}
// Instance profile message containing basic instance information.
message InstanceProfile {
// Version is the current version of instance.
@ -81,6 +88,9 @@ message InstanceProfile {
// false once any user exists, so an instance that has lost its admins is not
// mistaken for a fresh install.
bool needs_setup = 9;
// Access mode controls whether unauthenticated users may access instance content.
InstanceAccessMode access_mode = 10;
}
// Request for instance profile.
@ -106,6 +116,7 @@ message InstanceSetting {
TagsSetting tags_setting = 5;
NotificationSetting notification_setting = 6;
AISetting ai_setting = 7;
AccessSetting access_setting = 8;
}
// Enumeration of instance setting keys.
@ -123,6 +134,8 @@ message InstanceSetting {
NOTIFICATION = 5;
// AI is the key for AI provider settings.
AI = 6;
// ACCESS is the key for instance access policy settings.
ACCESS = 7;
}
// General instance settings configuration.
@ -335,6 +348,11 @@ message InstanceSetting {
// prompt is a default spelling/vocabulary hint passed to the provider.
string prompt = 4;
}
// Access policy configuration for the instance.
message AccessSetting {
InstanceAccessMode access_mode = 1;
}
}
// Request message for GetInstanceSetting method.

View file

@ -26,6 +26,56 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// InstanceAccessMode controls whether unauthenticated users may access instance content.
type InstanceAccessMode int32
const (
InstanceAccessMode_INSTANCE_ACCESS_MODE_UNSPECIFIED InstanceAccessMode = 0
InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE InstanceAccessMode = 1
InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC InstanceAccessMode = 2
)
// Enum value maps for InstanceAccessMode.
var (
InstanceAccessMode_name = map[int32]string{
0: "INSTANCE_ACCESS_MODE_UNSPECIFIED",
1: "INSTANCE_ACCESS_MODE_PRIVATE",
2: "INSTANCE_ACCESS_MODE_PUBLIC",
}
InstanceAccessMode_value = map[string]int32{
"INSTANCE_ACCESS_MODE_UNSPECIFIED": 0,
"INSTANCE_ACCESS_MODE_PRIVATE": 1,
"INSTANCE_ACCESS_MODE_PUBLIC": 2,
}
)
func (x InstanceAccessMode) Enum() *InstanceAccessMode {
p := new(InstanceAccessMode)
*p = x
return p
}
func (x InstanceAccessMode) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (InstanceAccessMode) Descriptor() protoreflect.EnumDescriptor {
return file_api_v1_instance_service_proto_enumTypes[0].Descriptor()
}
func (InstanceAccessMode) Type() protoreflect.EnumType {
return &file_api_v1_instance_service_proto_enumTypes[0]
}
func (x InstanceAccessMode) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use InstanceAccessMode.Descriptor instead.
func (InstanceAccessMode) EnumDescriptor() ([]byte, []int) {
return file_api_v1_instance_service_proto_rawDescGZIP(), []int{0}
}
// Enumeration of instance setting keys.
type InstanceSetting_Key int32
@ -43,6 +93,8 @@ const (
InstanceSetting_NOTIFICATION InstanceSetting_Key = 5
// AI is the key for AI provider settings.
InstanceSetting_AI InstanceSetting_Key = 6
// ACCESS is the key for instance access policy settings.
InstanceSetting_ACCESS InstanceSetting_Key = 7
)
// Enum value maps for InstanceSetting_Key.
@ -55,6 +107,7 @@ var (
4: "TAGS",
5: "NOTIFICATION",
6: "AI",
7: "ACCESS",
}
InstanceSetting_Key_value = map[string]int32{
"KEY_UNSPECIFIED": 0,
@ -64,6 +117,7 @@ var (
"TAGS": 4,
"NOTIFICATION": 5,
"AI": 6,
"ACCESS": 7,
}
)
@ -78,11 +132,11 @@ func (x InstanceSetting_Key) String() string {
}
func (InstanceSetting_Key) Descriptor() protoreflect.EnumDescriptor {
return file_api_v1_instance_service_proto_enumTypes[0].Descriptor()
return file_api_v1_instance_service_proto_enumTypes[1].Descriptor()
}
func (InstanceSetting_Key) Type() protoreflect.EnumType {
return &file_api_v1_instance_service_proto_enumTypes[0]
return &file_api_v1_instance_service_proto_enumTypes[1]
}
func (x InstanceSetting_Key) Number() protoreflect.EnumNumber {
@ -133,11 +187,11 @@ func (x InstanceSetting_StorageType) String() string {
}
func (InstanceSetting_StorageType) Descriptor() protoreflect.EnumDescriptor {
return file_api_v1_instance_service_proto_enumTypes[1].Descriptor()
return file_api_v1_instance_service_proto_enumTypes[2].Descriptor()
}
func (InstanceSetting_StorageType) Type() protoreflect.EnumType {
return &file_api_v1_instance_service_proto_enumTypes[1]
return &file_api_v1_instance_service_proto_enumTypes[2]
}
func (x InstanceSetting_StorageType) Number() protoreflect.EnumNumber {
@ -183,11 +237,11 @@ func (x InstanceSetting_AIProviderType) String() string {
}
func (InstanceSetting_AIProviderType) Descriptor() protoreflect.EnumDescriptor {
return file_api_v1_instance_service_proto_enumTypes[2].Descriptor()
return file_api_v1_instance_service_proto_enumTypes[3].Descriptor()
}
func (InstanceSetting_AIProviderType) Type() protoreflect.EnumType {
return &file_api_v1_instance_service_proto_enumTypes[2]
return &file_api_v1_instance_service_proto_enumTypes[3]
}
func (x InstanceSetting_AIProviderType) Number() protoreflect.EnumNumber {
@ -239,11 +293,11 @@ func (x InstanceSetting_StorageSetting_StorageType) String() string {
}
func (InstanceSetting_StorageSetting_StorageType) Descriptor() protoreflect.EnumDescriptor {
return file_api_v1_instance_service_proto_enumTypes[3].Descriptor()
return file_api_v1_instance_service_proto_enumTypes[4].Descriptor()
}
func (InstanceSetting_StorageSetting_StorageType) Type() protoreflect.EnumType {
return &file_api_v1_instance_service_proto_enumTypes[3]
return &file_api_v1_instance_service_proto_enumTypes[4]
}
func (x InstanceSetting_StorageSetting_StorageType) Number() protoreflect.EnumNumber {
@ -274,7 +328,9 @@ type InstanceProfile struct {
// setup (creating the first admin account). Unlike a null admin, this stays
// false once any user exists, so an instance that has lost its admins is not
// mistaken for a fresh install.
NeedsSetup bool `protobuf:"varint,9,opt,name=needs_setup,json=needsSetup,proto3" json:"needs_setup,omitempty"`
NeedsSetup bool `protobuf:"varint,9,opt,name=needs_setup,json=needsSetup,proto3" json:"needs_setup,omitempty"`
// Access mode controls whether unauthenticated users may access instance content.
AccessMode InstanceAccessMode `protobuf:"varint,10,opt,name=access_mode,json=accessMode,proto3,enum=memos.api.v1.InstanceAccessMode" json:"access_mode,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -351,6 +407,13 @@ func (x *InstanceProfile) GetNeedsSetup() bool {
return false
}
func (x *InstanceProfile) GetAccessMode() InstanceAccessMode {
if x != nil {
return x.AccessMode
}
return InstanceAccessMode_INSTANCE_ACCESS_MODE_UNSPECIFIED
}
// Request for instance profile.
type GetInstanceProfileRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
@ -402,6 +465,7 @@ type InstanceSetting struct {
// *InstanceSetting_TagsSetting_
// *InstanceSetting_NotificationSetting_
// *InstanceSetting_AiSetting
// *InstanceSetting_AccessSetting_
Value isInstanceSetting_Value `protobuf_oneof:"value"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@ -505,6 +569,15 @@ func (x *InstanceSetting) GetAiSetting() *InstanceSetting_AISetting {
return nil
}
func (x *InstanceSetting) GetAccessSetting() *InstanceSetting_AccessSetting {
if x != nil {
if x, ok := x.Value.(*InstanceSetting_AccessSetting_); ok {
return x.AccessSetting
}
}
return nil
}
type isInstanceSetting_Value interface {
isInstanceSetting_Value()
}
@ -533,6 +606,10 @@ type InstanceSetting_AiSetting struct {
AiSetting *InstanceSetting_AISetting `protobuf:"bytes,7,opt,name=ai_setting,json=aiSetting,proto3,oneof"`
}
type InstanceSetting_AccessSetting_ struct {
AccessSetting *InstanceSetting_AccessSetting `protobuf:"bytes,8,opt,name=access_setting,json=accessSetting,proto3,oneof"`
}
func (*InstanceSetting_GeneralSetting_) isInstanceSetting_Value() {}
func (*InstanceSetting_StorageSetting_) isInstanceSetting_Value() {}
@ -545,6 +622,8 @@ func (*InstanceSetting_NotificationSetting_) isInstanceSetting_Value() {}
func (*InstanceSetting_AiSetting) isInstanceSetting_Value() {}
func (*InstanceSetting_AccessSetting_) isInstanceSetting_Value() {}
// Request message for GetInstanceSetting method.
type GetInstanceSettingRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
@ -1636,6 +1715,51 @@ func (x *InstanceSetting_TranscriptionConfig) GetPrompt() string {
return ""
}
// Access policy configuration for the instance.
type InstanceSetting_AccessSetting struct {
state protoimpl.MessageState `protogen:"open.v1"`
AccessMode InstanceAccessMode `protobuf:"varint,1,opt,name=access_mode,json=accessMode,proto3,enum=memos.api.v1.InstanceAccessMode" json:"access_mode,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *InstanceSetting_AccessSetting) Reset() {
*x = InstanceSetting_AccessSetting{}
mi := &file_api_v1_instance_service_proto_msgTypes[20]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *InstanceSetting_AccessSetting) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*InstanceSetting_AccessSetting) ProtoMessage() {}
func (x *InstanceSetting_AccessSetting) ProtoReflect() protoreflect.Message {
mi := &file_api_v1_instance_service_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 InstanceSetting_AccessSetting.ProtoReflect.Descriptor instead.
func (*InstanceSetting_AccessSetting) Descriptor() ([]byte, []int) {
return file_api_v1_instance_service_proto_rawDescGZIP(), []int{2, 10}
}
func (x *InstanceSetting_AccessSetting) GetAccessMode() InstanceAccessMode {
if x != nil {
return x.AccessMode
}
return InstanceAccessMode_INSTANCE_ACCESS_MODE_UNSPECIFIED
}
// Custom profile configuration for instance branding.
type InstanceSetting_GeneralSetting_CustomProfile struct {
state protoimpl.MessageState `protogen:"open.v1"`
@ -1648,7 +1772,7 @@ type InstanceSetting_GeneralSetting_CustomProfile struct {
func (x *InstanceSetting_GeneralSetting_CustomProfile) Reset() {
*x = InstanceSetting_GeneralSetting_CustomProfile{}
mi := &file_api_v1_instance_service_proto_msgTypes[20]
mi := &file_api_v1_instance_service_proto_msgTypes[21]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@ -1660,7 +1784,7 @@ func (x *InstanceSetting_GeneralSetting_CustomProfile) String() string {
func (*InstanceSetting_GeneralSetting_CustomProfile) ProtoMessage() {}
func (x *InstanceSetting_GeneralSetting_CustomProfile) ProtoReflect() protoreflect.Message {
mi := &file_api_v1_instance_service_proto_msgTypes[20]
mi := &file_api_v1_instance_service_proto_msgTypes[21]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@ -1717,7 +1841,7 @@ type InstanceSetting_Storage_S3Config struct {
func (x *InstanceSetting_Storage_S3Config) Reset() {
*x = InstanceSetting_Storage_S3Config{}
mi := &file_api_v1_instance_service_proto_msgTypes[21]
mi := &file_api_v1_instance_service_proto_msgTypes[22]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@ -1729,7 +1853,7 @@ func (x *InstanceSetting_Storage_S3Config) String() string {
func (*InstanceSetting_Storage_S3Config) ProtoMessage() {}
func (x *InstanceSetting_Storage_S3Config) ProtoReflect() protoreflect.Message {
mi := &file_api_v1_instance_service_proto_msgTypes[21]
mi := &file_api_v1_instance_service_proto_msgTypes[22]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@ -1814,7 +1938,7 @@ type InstanceSetting_StorageSetting_S3Config struct {
func (x *InstanceSetting_StorageSetting_S3Config) Reset() {
*x = InstanceSetting_StorageSetting_S3Config{}
mi := &file_api_v1_instance_service_proto_msgTypes[22]
mi := &file_api_v1_instance_service_proto_msgTypes[23]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@ -1826,7 +1950,7 @@ func (x *InstanceSetting_StorageSetting_S3Config) String() string {
func (*InstanceSetting_StorageSetting_S3Config) ProtoMessage() {}
func (x *InstanceSetting_StorageSetting_S3Config) ProtoReflect() protoreflect.Message {
mi := &file_api_v1_instance_service_proto_msgTypes[22]
mi := &file_api_v1_instance_service_proto_msgTypes[23]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@ -1910,7 +2034,7 @@ type InstanceSetting_NotificationSetting_EmailSetting struct {
func (x *InstanceSetting_NotificationSetting_EmailSetting) Reset() {
*x = InstanceSetting_NotificationSetting_EmailSetting{}
mi := &file_api_v1_instance_service_proto_msgTypes[24]
mi := &file_api_v1_instance_service_proto_msgTypes[25]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@ -1922,7 +2046,7 @@ func (x *InstanceSetting_NotificationSetting_EmailSetting) String() string {
func (*InstanceSetting_NotificationSetting_EmailSetting) ProtoMessage() {}
func (x *InstanceSetting_NotificationSetting_EmailSetting) ProtoReflect() protoreflect.Message {
mi := &file_api_v1_instance_service_proto_msgTypes[24]
mi := &file_api_v1_instance_service_proto_msgTypes[25]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@ -2021,7 +2145,7 @@ type InstanceStats_DatabaseStats struct {
func (x *InstanceStats_DatabaseStats) Reset() {
*x = InstanceStats_DatabaseStats{}
mi := &file_api_v1_instance_service_proto_msgTypes[25]
mi := &file_api_v1_instance_service_proto_msgTypes[26]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@ -2033,7 +2157,7 @@ func (x *InstanceStats_DatabaseStats) String() string {
func (*InstanceStats_DatabaseStats) ProtoMessage() {}
func (x *InstanceStats_DatabaseStats) ProtoReflect() protoreflect.Message {
mi := &file_api_v1_instance_service_proto_msgTypes[25]
mi := &file_api_v1_instance_service_proto_msgTypes[26]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@ -2067,7 +2191,7 @@ var File_api_v1_instance_service_proto protoreflect.FileDescriptor
const file_api_v1_instance_service_proto_rawDesc = "" +
"\n" +
"\x1dapi/v1/instance_service.proto\x12\fmemos.api.v1\x1a\x19api/v1/user_service.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/type/color.proto\"\xc5\x01\n" +
"\x1dapi/v1/instance_service.proto\x12\fmemos.api.v1\x1a\x19api/v1/user_service.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/type/color.proto\"\x88\x02\n" +
"\x0fInstanceProfile\x12\x18\n" +
"\aversion\x18\x02 \x01(\tR\aversion\x12\x12\n" +
"\x04demo\x18\x03 \x01(\bR\x04demo\x12!\n" +
@ -2075,8 +2199,11 @@ const file_api_v1_instance_service_proto_rawDesc = "" +
"\x05admin\x18\a \x01(\v2\x12.memos.api.v1.UserR\x05admin\x12\x16\n" +
"\x06commit\x18\b \x01(\tR\x06commit\x12\x1f\n" +
"\vneeds_setup\x18\t \x01(\bR\n" +
"needsSetup\"\x1b\n" +
"\x19GetInstanceProfileRequest\"\x9a!\n" +
"needsSetup\x12A\n" +
"\vaccess_mode\x18\n" +
" \x01(\x0e2 .memos.api.v1.InstanceAccessModeR\n" +
"accessMode\"\x1b\n" +
"\x19GetInstanceProfileRequest\"\xd0\"\n" +
"\x0fInstanceSetting\x12\x17\n" +
"\x04name\x18\x01 \x01(\tB\x03\xe0A\bR\x04name\x12W\n" +
"\x0fgeneral_setting\x18\x02 \x01(\v2,.memos.api.v1.InstanceSetting.GeneralSettingH\x00R\x0egeneralSetting\x12W\n" +
@ -2085,7 +2212,8 @@ const file_api_v1_instance_service_proto_rawDesc = "" +
"\ftags_setting\x18\x05 \x01(\v2).memos.api.v1.InstanceSetting.TagsSettingH\x00R\vtagsSetting\x12f\n" +
"\x14notification_setting\x18\x06 \x01(\v21.memos.api.v1.InstanceSetting.NotificationSettingH\x00R\x13notificationSetting\x12H\n" +
"\n" +
"ai_setting\x18\a \x01(\v2'.memos.api.v1.InstanceSetting.AISettingH\x00R\taiSetting\x1a\xca\x04\n" +
"ai_setting\x18\a \x01(\v2'.memos.api.v1.InstanceSetting.AISettingH\x00R\taiSetting\x12T\n" +
"\x0eaccess_setting\x18\b \x01(\v2+.memos.api.v1.InstanceSetting.AccessSettingH\x00R\raccessSetting\x1a\xca\x04\n" +
"\x0eGeneralSetting\x12<\n" +
"\x1adisallow_user_registration\x18\x02 \x01(\bR\x18disallowUserRegistration\x124\n" +
"\x16disallow_password_auth\x18\x03 \x01(\bR\x14disallowPasswordAuth\x12+\n" +
@ -2178,7 +2306,10 @@ const file_api_v1_instance_service_proto_rawDesc = "" +
"providerId\x12\x14\n" +
"\x05model\x18\x02 \x01(\tR\x05model\x12\x1a\n" +
"\blanguage\x18\x03 \x01(\tR\blanguage\x12\x16\n" +
"\x06prompt\x18\x04 \x01(\tR\x06prompt\"j\n" +
"\x06prompt\x18\x04 \x01(\tR\x06prompt\x1aR\n" +
"\rAccessSetting\x12A\n" +
"\vaccess_mode\x18\x01 \x01(\x0e2 .memos.api.v1.InstanceAccessModeR\n" +
"accessMode\"v\n" +
"\x03Key\x12\x13\n" +
"\x0fKEY_UNSPECIFIED\x10\x00\x12\v\n" +
"\aGENERAL\x10\x01\x12\v\n" +
@ -2186,7 +2317,9 @@ const file_api_v1_instance_service_proto_rawDesc = "" +
"\fMEMO_RELATED\x10\x03\x12\b\n" +
"\x04TAGS\x10\x04\x12\x10\n" +
"\fNOTIFICATION\x10\x05\x12\x06\n" +
"\x02AI\x10\x06\"L\n" +
"\x02AI\x10\x06\x12\n" +
"\n" +
"\x06ACCESS\x10\a\"L\n" +
"\vStorageType\x12\x1c\n" +
"\x18STORAGE_TYPE_UNSPECIFIED\x10\x00\x12\f\n" +
"\bDATABASE\x10\x01\x12\t\n" +
@ -2223,7 +2356,11 @@ const file_api_v1_instance_service_proto_rawDesc = "" +
"\rDatabaseStats\x12\x16\n" +
"\x06driver\x18\x01 \x01(\tR\x06driver\x12\x1d\n" +
"\n" +
"size_bytes\x18\x02 \x01(\x03R\tsizeBytes2\x9f\a\n" +
"size_bytes\x18\x02 \x01(\x03R\tsizeBytes*}\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\x9f\a\n" +
"\x0fInstanceService\x12~\n" +
"\x12GetInstanceProfile\x12'.memos.api.v1.GetInstanceProfileRequest\x1a\x1d.memos.api.v1.InstanceProfile\" \x82\xd3\xe4\x93\x02\x1a\x12\x18/api/v1/instance/profile\x12\x8f\x01\n" +
"\x12GetInstanceSetting\x12'.memos.api.v1.GetInstanceSettingRequest\x1a\x1d.memos.api.v1.InstanceSetting\"1\xdaA\x04name\x82\xd3\xe4\x93\x02$\x12\"/api/v1/{name=instance/settings/*}\x12\xa8\x01\n" +
@ -2245,89 +2382,94 @@ func file_api_v1_instance_service_proto_rawDescGZIP() []byte {
return file_api_v1_instance_service_proto_rawDescData
}
var file_api_v1_instance_service_proto_enumTypes = make([]protoimpl.EnumInfo, 4)
var file_api_v1_instance_service_proto_msgTypes = make([]protoimpl.MessageInfo, 26)
var file_api_v1_instance_service_proto_enumTypes = make([]protoimpl.EnumInfo, 5)
var file_api_v1_instance_service_proto_msgTypes = make([]protoimpl.MessageInfo, 27)
var file_api_v1_instance_service_proto_goTypes = []any{
(InstanceSetting_Key)(0), // 0: memos.api.v1.InstanceSetting.Key
(InstanceSetting_StorageType)(0), // 1: memos.api.v1.InstanceSetting.StorageType
(InstanceSetting_AIProviderType)(0), // 2: memos.api.v1.InstanceSetting.AIProviderType
(InstanceSetting_StorageSetting_StorageType)(0), // 3: memos.api.v1.InstanceSetting.StorageSetting.StorageType
(*InstanceProfile)(nil), // 4: memos.api.v1.InstanceProfile
(*GetInstanceProfileRequest)(nil), // 5: memos.api.v1.GetInstanceProfileRequest
(*InstanceSetting)(nil), // 6: memos.api.v1.InstanceSetting
(*GetInstanceSettingRequest)(nil), // 7: memos.api.v1.GetInstanceSettingRequest
(*BatchGetInstanceSettingsRequest)(nil), // 8: memos.api.v1.BatchGetInstanceSettingsRequest
(*BatchGetInstanceSettingsResponse)(nil), // 9: memos.api.v1.BatchGetInstanceSettingsResponse
(*UpdateInstanceSettingRequest)(nil), // 10: memos.api.v1.UpdateInstanceSettingRequest
(*TestInstanceEmailSettingRequest)(nil), // 11: memos.api.v1.TestInstanceEmailSettingRequest
(*GetInstanceStatsRequest)(nil), // 12: memos.api.v1.GetInstanceStatsRequest
(*InstanceStats)(nil), // 13: memos.api.v1.InstanceStats
(*InstanceSetting_GeneralSetting)(nil), // 14: memos.api.v1.InstanceSetting.GeneralSetting
(*InstanceSetting_Storage)(nil), // 15: memos.api.v1.InstanceSetting.Storage
(*InstanceSetting_StorageSetting)(nil), // 16: memos.api.v1.InstanceSetting.StorageSetting
(*InstanceSetting_MemoRelatedSetting)(nil), // 17: memos.api.v1.InstanceSetting.MemoRelatedSetting
(*InstanceSetting_TagMetadata)(nil), // 18: memos.api.v1.InstanceSetting.TagMetadata
(*InstanceSetting_TagsSetting)(nil), // 19: memos.api.v1.InstanceSetting.TagsSetting
(*InstanceSetting_NotificationSetting)(nil), // 20: memos.api.v1.InstanceSetting.NotificationSetting
(*InstanceSetting_AISetting)(nil), // 21: memos.api.v1.InstanceSetting.AISetting
(*InstanceSetting_AIProviderConfig)(nil), // 22: memos.api.v1.InstanceSetting.AIProviderConfig
(*InstanceSetting_TranscriptionConfig)(nil), // 23: memos.api.v1.InstanceSetting.TranscriptionConfig
(*InstanceSetting_GeneralSetting_CustomProfile)(nil), // 24: memos.api.v1.InstanceSetting.GeneralSetting.CustomProfile
(*InstanceSetting_Storage_S3Config)(nil), // 25: memos.api.v1.InstanceSetting.Storage.S3Config
(*InstanceSetting_StorageSetting_S3Config)(nil), // 26: memos.api.v1.InstanceSetting.StorageSetting.S3Config
nil, // 27: memos.api.v1.InstanceSetting.TagsSetting.TagsEntry
(*InstanceSetting_NotificationSetting_EmailSetting)(nil), // 28: memos.api.v1.InstanceSetting.NotificationSetting.EmailSetting
(*InstanceStats_DatabaseStats)(nil), // 29: memos.api.v1.InstanceStats.DatabaseStats
(*User)(nil), // 30: memos.api.v1.User
(*fieldmaskpb.FieldMask)(nil), // 31: google.protobuf.FieldMask
(*timestamppb.Timestamp)(nil), // 32: google.protobuf.Timestamp
(*color.Color)(nil), // 33: google.type.Color
(*emptypb.Empty)(nil), // 34: google.protobuf.Empty
(InstanceAccessMode)(0), // 0: memos.api.v1.InstanceAccessMode
(InstanceSetting_Key)(0), // 1: memos.api.v1.InstanceSetting.Key
(InstanceSetting_StorageType)(0), // 2: memos.api.v1.InstanceSetting.StorageType
(InstanceSetting_AIProviderType)(0), // 3: memos.api.v1.InstanceSetting.AIProviderType
(InstanceSetting_StorageSetting_StorageType)(0), // 4: memos.api.v1.InstanceSetting.StorageSetting.StorageType
(*InstanceProfile)(nil), // 5: memos.api.v1.InstanceProfile
(*GetInstanceProfileRequest)(nil), // 6: memos.api.v1.GetInstanceProfileRequest
(*InstanceSetting)(nil), // 7: memos.api.v1.InstanceSetting
(*GetInstanceSettingRequest)(nil), // 8: memos.api.v1.GetInstanceSettingRequest
(*BatchGetInstanceSettingsRequest)(nil), // 9: memos.api.v1.BatchGetInstanceSettingsRequest
(*BatchGetInstanceSettingsResponse)(nil), // 10: memos.api.v1.BatchGetInstanceSettingsResponse
(*UpdateInstanceSettingRequest)(nil), // 11: memos.api.v1.UpdateInstanceSettingRequest
(*TestInstanceEmailSettingRequest)(nil), // 12: memos.api.v1.TestInstanceEmailSettingRequest
(*GetInstanceStatsRequest)(nil), // 13: memos.api.v1.GetInstanceStatsRequest
(*InstanceStats)(nil), // 14: memos.api.v1.InstanceStats
(*InstanceSetting_GeneralSetting)(nil), // 15: memos.api.v1.InstanceSetting.GeneralSetting
(*InstanceSetting_Storage)(nil), // 16: memos.api.v1.InstanceSetting.Storage
(*InstanceSetting_StorageSetting)(nil), // 17: memos.api.v1.InstanceSetting.StorageSetting
(*InstanceSetting_MemoRelatedSetting)(nil), // 18: memos.api.v1.InstanceSetting.MemoRelatedSetting
(*InstanceSetting_TagMetadata)(nil), // 19: memos.api.v1.InstanceSetting.TagMetadata
(*InstanceSetting_TagsSetting)(nil), // 20: memos.api.v1.InstanceSetting.TagsSetting
(*InstanceSetting_NotificationSetting)(nil), // 21: memos.api.v1.InstanceSetting.NotificationSetting
(*InstanceSetting_AISetting)(nil), // 22: memos.api.v1.InstanceSetting.AISetting
(*InstanceSetting_AIProviderConfig)(nil), // 23: memos.api.v1.InstanceSetting.AIProviderConfig
(*InstanceSetting_TranscriptionConfig)(nil), // 24: memos.api.v1.InstanceSetting.TranscriptionConfig
(*InstanceSetting_AccessSetting)(nil), // 25: memos.api.v1.InstanceSetting.AccessSetting
(*InstanceSetting_GeneralSetting_CustomProfile)(nil), // 26: memos.api.v1.InstanceSetting.GeneralSetting.CustomProfile
(*InstanceSetting_Storage_S3Config)(nil), // 27: memos.api.v1.InstanceSetting.Storage.S3Config
(*InstanceSetting_StorageSetting_S3Config)(nil), // 28: memos.api.v1.InstanceSetting.StorageSetting.S3Config
nil, // 29: memos.api.v1.InstanceSetting.TagsSetting.TagsEntry
(*InstanceSetting_NotificationSetting_EmailSetting)(nil), // 30: memos.api.v1.InstanceSetting.NotificationSetting.EmailSetting
(*InstanceStats_DatabaseStats)(nil), // 31: memos.api.v1.InstanceStats.DatabaseStats
(*User)(nil), // 32: memos.api.v1.User
(*fieldmaskpb.FieldMask)(nil), // 33: google.protobuf.FieldMask
(*timestamppb.Timestamp)(nil), // 34: google.protobuf.Timestamp
(*color.Color)(nil), // 35: google.type.Color
(*emptypb.Empty)(nil), // 36: google.protobuf.Empty
}
var file_api_v1_instance_service_proto_depIdxs = []int32{
30, // 0: memos.api.v1.InstanceProfile.admin:type_name -> memos.api.v1.User
14, // 1: memos.api.v1.InstanceSetting.general_setting:type_name -> memos.api.v1.InstanceSetting.GeneralSetting
16, // 2: memos.api.v1.InstanceSetting.storage_setting:type_name -> memos.api.v1.InstanceSetting.StorageSetting
17, // 3: memos.api.v1.InstanceSetting.memo_related_setting:type_name -> memos.api.v1.InstanceSetting.MemoRelatedSetting
19, // 4: memos.api.v1.InstanceSetting.tags_setting:type_name -> memos.api.v1.InstanceSetting.TagsSetting
20, // 5: memos.api.v1.InstanceSetting.notification_setting:type_name -> memos.api.v1.InstanceSetting.NotificationSetting
21, // 6: memos.api.v1.InstanceSetting.ai_setting:type_name -> memos.api.v1.InstanceSetting.AISetting
6, // 7: memos.api.v1.BatchGetInstanceSettingsResponse.settings:type_name -> memos.api.v1.InstanceSetting
6, // 8: memos.api.v1.UpdateInstanceSettingRequest.setting:type_name -> memos.api.v1.InstanceSetting
31, // 9: memos.api.v1.UpdateInstanceSettingRequest.update_mask:type_name -> google.protobuf.FieldMask
28, // 10: memos.api.v1.TestInstanceEmailSettingRequest.email:type_name -> memos.api.v1.InstanceSetting.NotificationSetting.EmailSetting
29, // 11: memos.api.v1.InstanceStats.database:type_name -> memos.api.v1.InstanceStats.DatabaseStats
32, // 12: memos.api.v1.InstanceStats.generated_time:type_name -> google.protobuf.Timestamp
24, // 13: memos.api.v1.InstanceSetting.GeneralSetting.custom_profile:type_name -> memos.api.v1.InstanceSetting.GeneralSetting.CustomProfile
1, // 14: memos.api.v1.InstanceSetting.Storage.type:type_name -> memos.api.v1.InstanceSetting.StorageType
25, // 15: memos.api.v1.InstanceSetting.Storage.s3_config:type_name -> memos.api.v1.InstanceSetting.Storage.S3Config
3, // 16: memos.api.v1.InstanceSetting.StorageSetting.storage_type:type_name -> memos.api.v1.InstanceSetting.StorageSetting.StorageType
26, // 17: memos.api.v1.InstanceSetting.StorageSetting.s3_config:type_name -> memos.api.v1.InstanceSetting.StorageSetting.S3Config
15, // 18: memos.api.v1.InstanceSetting.StorageSetting.storages:type_name -> memos.api.v1.InstanceSetting.Storage
33, // 19: memos.api.v1.InstanceSetting.TagMetadata.background_color:type_name -> google.type.Color
27, // 20: memos.api.v1.InstanceSetting.TagsSetting.tags:type_name -> memos.api.v1.InstanceSetting.TagsSetting.TagsEntry
28, // 21: memos.api.v1.InstanceSetting.NotificationSetting.email:type_name -> memos.api.v1.InstanceSetting.NotificationSetting.EmailSetting
22, // 22: memos.api.v1.InstanceSetting.AISetting.providers:type_name -> memos.api.v1.InstanceSetting.AIProviderConfig
23, // 23: memos.api.v1.InstanceSetting.AISetting.transcription:type_name -> memos.api.v1.InstanceSetting.TranscriptionConfig
2, // 24: memos.api.v1.InstanceSetting.AIProviderConfig.type:type_name -> memos.api.v1.InstanceSetting.AIProviderType
18, // 25: memos.api.v1.InstanceSetting.TagsSetting.TagsEntry.value:type_name -> memos.api.v1.InstanceSetting.TagMetadata
5, // 26: memos.api.v1.InstanceService.GetInstanceProfile:input_type -> memos.api.v1.GetInstanceProfileRequest
7, // 27: memos.api.v1.InstanceService.GetInstanceSetting:input_type -> memos.api.v1.GetInstanceSettingRequest
8, // 28: memos.api.v1.InstanceService.BatchGetInstanceSettings:input_type -> memos.api.v1.BatchGetInstanceSettingsRequest
10, // 29: memos.api.v1.InstanceService.UpdateInstanceSetting:input_type -> memos.api.v1.UpdateInstanceSettingRequest
11, // 30: memos.api.v1.InstanceService.TestInstanceEmailSetting:input_type -> memos.api.v1.TestInstanceEmailSettingRequest
12, // 31: memos.api.v1.InstanceService.GetInstanceStats:input_type -> memos.api.v1.GetInstanceStatsRequest
4, // 32: memos.api.v1.InstanceService.GetInstanceProfile:output_type -> memos.api.v1.InstanceProfile
6, // 33: memos.api.v1.InstanceService.GetInstanceSetting:output_type -> memos.api.v1.InstanceSetting
9, // 34: memos.api.v1.InstanceService.BatchGetInstanceSettings:output_type -> memos.api.v1.BatchGetInstanceSettingsResponse
6, // 35: memos.api.v1.InstanceService.UpdateInstanceSetting:output_type -> memos.api.v1.InstanceSetting
34, // 36: memos.api.v1.InstanceService.TestInstanceEmailSetting:output_type -> google.protobuf.Empty
13, // 37: memos.api.v1.InstanceService.GetInstanceStats:output_type -> memos.api.v1.InstanceStats
32, // [32:38] is the sub-list for method output_type
26, // [26:32] 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
32, // 0: memos.api.v1.InstanceProfile.admin:type_name -> memos.api.v1.User
0, // 1: memos.api.v1.InstanceProfile.access_mode:type_name -> memos.api.v1.InstanceAccessMode
15, // 2: memos.api.v1.InstanceSetting.general_setting:type_name -> memos.api.v1.InstanceSetting.GeneralSetting
17, // 3: memos.api.v1.InstanceSetting.storage_setting:type_name -> memos.api.v1.InstanceSetting.StorageSetting
18, // 4: memos.api.v1.InstanceSetting.memo_related_setting:type_name -> memos.api.v1.InstanceSetting.MemoRelatedSetting
20, // 5: memos.api.v1.InstanceSetting.tags_setting:type_name -> memos.api.v1.InstanceSetting.TagsSetting
21, // 6: memos.api.v1.InstanceSetting.notification_setting:type_name -> memos.api.v1.InstanceSetting.NotificationSetting
22, // 7: memos.api.v1.InstanceSetting.ai_setting:type_name -> memos.api.v1.InstanceSetting.AISetting
25, // 8: memos.api.v1.InstanceSetting.access_setting:type_name -> memos.api.v1.InstanceSetting.AccessSetting
7, // 9: memos.api.v1.BatchGetInstanceSettingsResponse.settings:type_name -> memos.api.v1.InstanceSetting
7, // 10: memos.api.v1.UpdateInstanceSettingRequest.setting:type_name -> memos.api.v1.InstanceSetting
33, // 11: memos.api.v1.UpdateInstanceSettingRequest.update_mask:type_name -> google.protobuf.FieldMask
30, // 12: memos.api.v1.TestInstanceEmailSettingRequest.email:type_name -> memos.api.v1.InstanceSetting.NotificationSetting.EmailSetting
31, // 13: memos.api.v1.InstanceStats.database:type_name -> memos.api.v1.InstanceStats.DatabaseStats
34, // 14: memos.api.v1.InstanceStats.generated_time:type_name -> google.protobuf.Timestamp
26, // 15: memos.api.v1.InstanceSetting.GeneralSetting.custom_profile:type_name -> memos.api.v1.InstanceSetting.GeneralSetting.CustomProfile
2, // 16: memos.api.v1.InstanceSetting.Storage.type:type_name -> memos.api.v1.InstanceSetting.StorageType
27, // 17: memos.api.v1.InstanceSetting.Storage.s3_config:type_name -> memos.api.v1.InstanceSetting.Storage.S3Config
4, // 18: memos.api.v1.InstanceSetting.StorageSetting.storage_type:type_name -> memos.api.v1.InstanceSetting.StorageSetting.StorageType
28, // 19: memos.api.v1.InstanceSetting.StorageSetting.s3_config:type_name -> memos.api.v1.InstanceSetting.StorageSetting.S3Config
16, // 20: memos.api.v1.InstanceSetting.StorageSetting.storages:type_name -> memos.api.v1.InstanceSetting.Storage
35, // 21: memos.api.v1.InstanceSetting.TagMetadata.background_color:type_name -> google.type.Color
29, // 22: memos.api.v1.InstanceSetting.TagsSetting.tags:type_name -> memos.api.v1.InstanceSetting.TagsSetting.TagsEntry
30, // 23: memos.api.v1.InstanceSetting.NotificationSetting.email:type_name -> memos.api.v1.InstanceSetting.NotificationSetting.EmailSetting
23, // 24: memos.api.v1.InstanceSetting.AISetting.providers:type_name -> memos.api.v1.InstanceSetting.AIProviderConfig
24, // 25: memos.api.v1.InstanceSetting.AISetting.transcription:type_name -> memos.api.v1.InstanceSetting.TranscriptionConfig
3, // 26: memos.api.v1.InstanceSetting.AIProviderConfig.type:type_name -> memos.api.v1.InstanceSetting.AIProviderType
0, // 27: memos.api.v1.InstanceSetting.AccessSetting.access_mode:type_name -> memos.api.v1.InstanceAccessMode
19, // 28: memos.api.v1.InstanceSetting.TagsSetting.TagsEntry.value:type_name -> memos.api.v1.InstanceSetting.TagMetadata
6, // 29: memos.api.v1.InstanceService.GetInstanceProfile:input_type -> memos.api.v1.GetInstanceProfileRequest
8, // 30: memos.api.v1.InstanceService.GetInstanceSetting:input_type -> memos.api.v1.GetInstanceSettingRequest
9, // 31: memos.api.v1.InstanceService.BatchGetInstanceSettings:input_type -> memos.api.v1.BatchGetInstanceSettingsRequest
11, // 32: memos.api.v1.InstanceService.UpdateInstanceSetting:input_type -> memos.api.v1.UpdateInstanceSettingRequest
12, // 33: memos.api.v1.InstanceService.TestInstanceEmailSetting:input_type -> memos.api.v1.TestInstanceEmailSettingRequest
13, // 34: memos.api.v1.InstanceService.GetInstanceStats:input_type -> memos.api.v1.GetInstanceStatsRequest
5, // 35: memos.api.v1.InstanceService.GetInstanceProfile:output_type -> memos.api.v1.InstanceProfile
7, // 36: memos.api.v1.InstanceService.GetInstanceSetting:output_type -> memos.api.v1.InstanceSetting
10, // 37: memos.api.v1.InstanceService.BatchGetInstanceSettings:output_type -> memos.api.v1.BatchGetInstanceSettingsResponse
7, // 38: memos.api.v1.InstanceService.UpdateInstanceSetting:output_type -> memos.api.v1.InstanceSetting
36, // 39: memos.api.v1.InstanceService.TestInstanceEmailSetting:output_type -> google.protobuf.Empty
14, // 40: memos.api.v1.InstanceService.GetInstanceStats:output_type -> memos.api.v1.InstanceStats
35, // [35:41] is the sub-list for method output_type
29, // [29:35] is the sub-list for method input_type
29, // [29:29] is the sub-list for extension type_name
29, // [29:29] is the sub-list for extension extendee
0, // [0:29] is the sub-list for field type_name
}
func init() { file_api_v1_instance_service_proto_init() }
@ -2343,6 +2485,7 @@ func file_api_v1_instance_service_proto_init() {
(*InstanceSetting_TagsSetting_)(nil),
(*InstanceSetting_NotificationSetting_)(nil),
(*InstanceSetting_AiSetting)(nil),
(*InstanceSetting_AccessSetting_)(nil),
}
file_api_v1_instance_service_proto_msgTypes[11].OneofWrappers = []any{
(*InstanceSetting_Storage_S3Config_)(nil),
@ -2352,8 +2495,8 @@ func file_api_v1_instance_service_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_v1_instance_service_proto_rawDesc), len(file_api_v1_instance_service_proto_rawDesc)),
NumEnums: 4,
NumMessages: 26,
NumEnums: 5,
NumMessages: 27,
NumExtensions: 0,
NumServices: 1,
},

View file

@ -2788,6 +2788,14 @@ components:
setup (creating the first admin account). Unlike a null admin, this stays
false once any user exists, so an instance that has lost its admins is not
mistaken for a fresh install.
accessMode:
enum:
- INSTANCE_ACCESS_MODE_UNSPECIFIED
- INSTANCE_ACCESS_MODE_PRIVATE
- INSTANCE_ACCESS_MODE_PUBLIC
type: string
description: Access mode controls whether unauthenticated users may access instance content.
format: enum
description: Instance profile message containing basic instance information.
InstanceSetting:
type: object
@ -2809,6 +2817,8 @@ components:
$ref: '#/components/schemas/InstanceSetting_NotificationSetting'
aiSetting:
$ref: '#/components/schemas/InstanceSetting_AISetting'
accessSetting:
$ref: '#/components/schemas/InstanceSetting_AccessSetting'
description: An instance setting resource.
InstanceSetting_AIProviderConfig:
type: object
@ -2854,6 +2864,17 @@ components:
transcription is the speech-to-text feature configuration.
When unset or transcription.provider_id is empty, transcription is disabled.
description: AI provider configuration settings.
InstanceSetting_AccessSetting:
type: object
properties:
accessMode:
enum:
- INSTANCE_ACCESS_MODE_UNSPECIFIED
- INSTANCE_ACCESS_MODE_PRIVATE
- INSTANCE_ACCESS_MODE_PUBLIC
type: string
format: enum
description: Access policy configuration for the instance.
InstanceSetting_GeneralSetting:
type: object
properties:

View file

@ -40,6 +40,8 @@ const (
InstanceSettingKey_NOTIFICATION InstanceSettingKey = 6
// AI is the key for AI provider settings.
InstanceSettingKey_AI InstanceSettingKey = 7
// ACCESS is the key for instance access policy settings.
InstanceSettingKey_ACCESS InstanceSettingKey = 8
)
// Enum value maps for InstanceSettingKey.
@ -53,6 +55,7 @@ var (
5: "TAGS",
6: "NOTIFICATION",
7: "AI",
8: "ACCESS",
}
InstanceSettingKey_value = map[string]int32{
"INSTANCE_SETTING_KEY_UNSPECIFIED": 0,
@ -63,6 +66,7 @@ var (
"TAGS": 5,
"NOTIFICATION": 6,
"AI": 7,
"ACCESS": 8,
}
)
@ -197,6 +201,55 @@ func (AIProviderType) EnumDescriptor() ([]byte, []int) {
return file_store_instance_setting_proto_rawDescGZIP(), []int{2}
}
type InstanceAccessMode int32
const (
InstanceAccessMode_INSTANCE_ACCESS_MODE_UNSPECIFIED InstanceAccessMode = 0
InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE InstanceAccessMode = 1
InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC InstanceAccessMode = 2
)
// Enum value maps for InstanceAccessMode.
var (
InstanceAccessMode_name = map[int32]string{
0: "INSTANCE_ACCESS_MODE_UNSPECIFIED",
1: "INSTANCE_ACCESS_MODE_PRIVATE",
2: "INSTANCE_ACCESS_MODE_PUBLIC",
}
InstanceAccessMode_value = map[string]int32{
"INSTANCE_ACCESS_MODE_UNSPECIFIED": 0,
"INSTANCE_ACCESS_MODE_PRIVATE": 1,
"INSTANCE_ACCESS_MODE_PUBLIC": 2,
}
)
func (x InstanceAccessMode) Enum() *InstanceAccessMode {
p := new(InstanceAccessMode)
*p = x
return p
}
func (x InstanceAccessMode) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (InstanceAccessMode) Descriptor() protoreflect.EnumDescriptor {
return file_store_instance_setting_proto_enumTypes[3].Descriptor()
}
func (InstanceAccessMode) Type() protoreflect.EnumType {
return &file_store_instance_setting_proto_enumTypes[3]
}
func (x InstanceAccessMode) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use InstanceAccessMode.Descriptor instead.
func (InstanceAccessMode) EnumDescriptor() ([]byte, []int) {
return file_store_instance_setting_proto_rawDescGZIP(), []int{3}
}
// Legacy storage type enum retained for compatibility with existing settings.
type InstanceStorageSetting_StorageType int32
@ -237,11 +290,11 @@ func (x InstanceStorageSetting_StorageType) String() string {
}
func (InstanceStorageSetting_StorageType) Descriptor() protoreflect.EnumDescriptor {
return file_store_instance_setting_proto_enumTypes[3].Descriptor()
return file_store_instance_setting_proto_enumTypes[4].Descriptor()
}
func (InstanceStorageSetting_StorageType) Type() protoreflect.EnumType {
return &file_store_instance_setting_proto_enumTypes[3]
return &file_store_instance_setting_proto_enumTypes[4]
}
func (x InstanceStorageSetting_StorageType) Number() protoreflect.EnumNumber {
@ -265,6 +318,7 @@ type InstanceSetting struct {
// *InstanceSetting_TagsSetting
// *InstanceSetting_NotificationSetting
// *InstanceSetting_AiSetting
// *InstanceSetting_AccessSetting
Value isInstanceSetting_Value `protobuf_oneof:"value"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@ -377,6 +431,15 @@ func (x *InstanceSetting) GetAiSetting() *InstanceAISetting {
return nil
}
func (x *InstanceSetting) GetAccessSetting() *InstanceAccessSetting {
if x != nil {
if x, ok := x.Value.(*InstanceSetting_AccessSetting); ok {
return x.AccessSetting
}
}
return nil
}
type isInstanceSetting_Value interface {
isInstanceSetting_Value()
}
@ -409,6 +472,10 @@ type InstanceSetting_AiSetting struct {
AiSetting *InstanceAISetting `protobuf:"bytes,8,opt,name=ai_setting,json=aiSetting,proto3,oneof"`
}
type InstanceSetting_AccessSetting struct {
AccessSetting *InstanceAccessSetting `protobuf:"bytes,9,opt,name=access_setting,json=accessSetting,proto3,oneof"`
}
func (*InstanceSetting_BasicSetting) isInstanceSetting_Value() {}
func (*InstanceSetting_GeneralSetting) isInstanceSetting_Value() {}
@ -423,6 +490,8 @@ func (*InstanceSetting_NotificationSetting) isInstanceSetting_Value() {}
func (*InstanceSetting_AiSetting) isInstanceSetting_Value() {}
func (*InstanceSetting_AccessSetting) isInstanceSetting_Value() {}
type InstanceBasicSetting struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The secret key for instance. Mainly used for session management.
@ -1359,6 +1428,50 @@ func (x *TranscriptionConfig) GetPrompt() string {
return ""
}
type InstanceAccessSetting struct {
state protoimpl.MessageState `protogen:"open.v1"`
AccessMode InstanceAccessMode `protobuf:"varint,1,opt,name=access_mode,json=accessMode,proto3,enum=memos.store.InstanceAccessMode" json:"access_mode,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *InstanceAccessSetting) Reset() {
*x = InstanceAccessSetting{}
mi := &file_store_instance_setting_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *InstanceAccessSetting) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*InstanceAccessSetting) ProtoMessage() {}
func (x *InstanceAccessSetting) ProtoReflect() protoreflect.Message {
mi := &file_store_instance_setting_proto_msgTypes[14]
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 InstanceAccessSetting.ProtoReflect.Descriptor instead.
func (*InstanceAccessSetting) Descriptor() ([]byte, []int) {
return file_store_instance_setting_proto_rawDescGZIP(), []int{14}
}
func (x *InstanceAccessSetting) GetAccessMode() InstanceAccessMode {
if x != nil {
return x.AccessMode
}
return InstanceAccessMode_INSTANCE_ACCESS_MODE_UNSPECIFIED
}
type InstanceNotificationSetting_EmailSetting struct {
state protoimpl.MessageState `protogen:"open.v1"`
Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
@ -1377,7 +1490,7 @@ type InstanceNotificationSetting_EmailSetting struct {
func (x *InstanceNotificationSetting_EmailSetting) Reset() {
*x = InstanceNotificationSetting_EmailSetting{}
mi := &file_store_instance_setting_proto_msgTypes[15]
mi := &file_store_instance_setting_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@ -1389,7 +1502,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[15]
mi := &file_store_instance_setting_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@ -1479,7 +1592,7 @@ var File_store_instance_setting_proto protoreflect.FileDescriptor
const file_store_instance_setting_proto_rawDesc = "" +
"\n" +
"\x1cstore/instance_setting.proto\x12\vmemos.store\x1a\x17google/type/color.proto\"\xfb\x04\n" +
"\x1cstore/instance_setting.proto\x12\vmemos.store\x1a\x17google/type/color.proto\"\xc8\x05\n" +
"\x0fInstanceSetting\x121\n" +
"\x03key\x18\x01 \x01(\x0e2\x1f.memos.store.InstanceSettingKeyR\x03key\x12H\n" +
"\rbasic_setting\x18\x02 \x01(\v2!.memos.store.InstanceBasicSettingH\x00R\fbasicSetting\x12N\n" +
@ -1489,7 +1602,8 @@ const file_store_instance_setting_proto_rawDesc = "" +
"\ftags_setting\x18\x06 \x01(\v2 .memos.store.InstanceTagsSettingH\x00R\vtagsSetting\x12]\n" +
"\x14notification_setting\x18\a \x01(\v2(.memos.store.InstanceNotificationSettingH\x00R\x13notificationSetting\x12?\n" +
"\n" +
"ai_setting\x18\b \x01(\v2\x1e.memos.store.InstanceAISettingH\x00R\taiSettingB\a\n" +
"ai_setting\x18\b \x01(\v2\x1e.memos.store.InstanceAISettingH\x00R\taiSetting\x12K\n" +
"\x0eaccess_setting\x18\t \x01(\v2\".memos.store.InstanceAccessSettingH\x00R\raccessSettingB\a\n" +
"\x05value\"\\\n" +
"\x14InstanceBasicSetting\x12\x1d\n" +
"\n" +
@ -1576,7 +1690,10 @@ const file_store_instance_setting_proto_rawDesc = "" +
"providerId\x12\x14\n" +
"\x05model\x18\x02 \x01(\tR\x05model\x12\x1a\n" +
"\blanguage\x18\x03 \x01(\tR\blanguage\x12\x16\n" +
"\x06prompt\x18\x04 \x01(\tR\x06prompt*\x95\x01\n" +
"\x06prompt\x18\x04 \x01(\tR\x06prompt\"Y\n" +
"\x15InstanceAccessSetting\x12@\n" +
"\vaccess_mode\x18\x01 \x01(\x0e2\x1f.memos.store.InstanceAccessModeR\n" +
"accessMode*\xa1\x01\n" +
"\x12InstanceSettingKey\x12$\n" +
" INSTANCE_SETTING_KEY_UNSPECIFIED\x10\x00\x12\t\n" +
"\x05BASIC\x10\x01\x12\v\n" +
@ -1585,7 +1702,9 @@ const file_store_instance_setting_proto_rawDesc = "" +
"\fMEMO_RELATED\x10\x04\x12\b\n" +
"\x04TAGS\x10\x05\x12\x10\n" +
"\fNOTIFICATION\x10\x06\x12\x06\n" +
"\x02AI\x10\a*s\n" +
"\x02AI\x10\a\x12\n" +
"\n" +
"\x06ACCESS\x10\b*s\n" +
"\vStorageType\x12\x1c\n" +
"\x18STORAGE_TYPE_UNSPECIFIED\x10\x00\x12\x19\n" +
"\x15STORAGE_TYPE_DATABASE\x10\x01\x12\x16\n" +
@ -1596,7 +1715,11 @@ const file_store_instance_setting_proto_rawDesc = "" +
"\n" +
"\x06OPENAI\x10\x01\x12\n" +
"\n" +
"\x06GEMINI\x10\x02B\x9f\x01\n" +
"\x06GEMINI\x10\x02*}\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\x02B\x9f\x01\n" +
"\x0fcom.memos.storeB\x14InstanceSettingProtoP\x01Z)github.com/usememos/memos/proto/gen/store\xa2\x02\x03MSX\xaa\x02\vMemos.Store\xca\x02\vMemos\\Store\xe2\x02\x17Memos\\Store\\GPBMetadata\xea\x02\fMemos::Storeb\x06proto3"
var (
@ -1611,58 +1734,62 @@ func file_store_instance_setting_proto_rawDescGZIP() []byte {
return file_store_instance_setting_proto_rawDescData
}
var file_store_instance_setting_proto_enumTypes = make([]protoimpl.EnumInfo, 4)
var file_store_instance_setting_proto_msgTypes = make([]protoimpl.MessageInfo, 16)
var file_store_instance_setting_proto_enumTypes = make([]protoimpl.EnumInfo, 5)
var file_store_instance_setting_proto_msgTypes = make([]protoimpl.MessageInfo, 17)
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
(InstanceStorageSetting_StorageType)(0), // 3: memos.store.InstanceStorageSetting.StorageType
(*InstanceSetting)(nil), // 4: memos.store.InstanceSetting
(*InstanceBasicSetting)(nil), // 5: memos.store.InstanceBasicSetting
(*InstanceGeneralSetting)(nil), // 6: memos.store.InstanceGeneralSetting
(*InstanceCustomProfile)(nil), // 7: memos.store.InstanceCustomProfile
(*Storage)(nil), // 8: memos.store.Storage
(*InstanceStorageSetting)(nil), // 9: memos.store.InstanceStorageSetting
(*StorageS3Config)(nil), // 10: memos.store.StorageS3Config
(*InstanceMemoRelatedSetting)(nil), // 11: memos.store.InstanceMemoRelatedSetting
(*InstanceTagMetadata)(nil), // 12: memos.store.InstanceTagMetadata
(*InstanceTagsSetting)(nil), // 13: memos.store.InstanceTagsSetting
(*InstanceNotificationSetting)(nil), // 14: memos.store.InstanceNotificationSetting
(*InstanceAISetting)(nil), // 15: memos.store.InstanceAISetting
(*AIProviderConfig)(nil), // 16: memos.store.AIProviderConfig
(*TranscriptionConfig)(nil), // 17: memos.store.TranscriptionConfig
nil, // 18: memos.store.InstanceTagsSetting.TagsEntry
(*InstanceNotificationSetting_EmailSetting)(nil), // 19: memos.store.InstanceNotificationSetting.EmailSetting
(*color.Color)(nil), // 20: google.type.Color
(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
nil, // 20: memos.store.InstanceTagsSetting.TagsEntry
(*InstanceNotificationSetting_EmailSetting)(nil), // 21: memos.store.InstanceNotificationSetting.EmailSetting
(*color.Color)(nil), // 22: google.type.Color
}
var file_store_instance_setting_proto_depIdxs = []int32{
0, // 0: memos.store.InstanceSetting.key:type_name -> memos.store.InstanceSettingKey
5, // 1: memos.store.InstanceSetting.basic_setting:type_name -> memos.store.InstanceBasicSetting
6, // 2: memos.store.InstanceSetting.general_setting:type_name -> memos.store.InstanceGeneralSetting
9, // 3: memos.store.InstanceSetting.storage_setting:type_name -> memos.store.InstanceStorageSetting
11, // 4: memos.store.InstanceSetting.memo_related_setting:type_name -> memos.store.InstanceMemoRelatedSetting
13, // 5: memos.store.InstanceSetting.tags_setting:type_name -> memos.store.InstanceTagsSetting
14, // 6: memos.store.InstanceSetting.notification_setting:type_name -> memos.store.InstanceNotificationSetting
15, // 7: memos.store.InstanceSetting.ai_setting:type_name -> memos.store.InstanceAISetting
7, // 8: memos.store.InstanceGeneralSetting.custom_profile:type_name -> memos.store.InstanceCustomProfile
1, // 9: memos.store.Storage.type:type_name -> memos.store.StorageType
10, // 10: memos.store.Storage.s3_config:type_name -> memos.store.StorageS3Config
3, // 11: memos.store.InstanceStorageSetting.storage_type:type_name -> memos.store.InstanceStorageSetting.StorageType
10, // 12: memos.store.InstanceStorageSetting.s3_config:type_name -> memos.store.StorageS3Config
8, // 13: memos.store.InstanceStorageSetting.storages:type_name -> memos.store.Storage
20, // 14: memos.store.InstanceTagMetadata.background_color:type_name -> google.type.Color
18, // 15: memos.store.InstanceTagsSetting.tags:type_name -> memos.store.InstanceTagsSetting.TagsEntry
19, // 16: memos.store.InstanceNotificationSetting.email:type_name -> memos.store.InstanceNotificationSetting.EmailSetting
16, // 17: memos.store.InstanceAISetting.providers:type_name -> memos.store.AIProviderConfig
17, // 18: memos.store.InstanceAISetting.transcription:type_name -> memos.store.TranscriptionConfig
2, // 19: memos.store.AIProviderConfig.type:type_name -> memos.store.AIProviderType
12, // 20: memos.store.InstanceTagsSetting.TagsEntry.value:type_name -> memos.store.InstanceTagMetadata
21, // [21:21] is the sub-list for method output_type
21, // [21:21] is the sub-list for method input_type
21, // [21:21] is the sub-list for extension type_name
21, // [21:21] is the sub-list for extension extendee
0, // [0:21] is the sub-list for field type_name
6, // 1: memos.store.InstanceSetting.basic_setting:type_name -> memos.store.InstanceBasicSetting
7, // 2: memos.store.InstanceSetting.general_setting:type_name -> memos.store.InstanceGeneralSetting
10, // 3: memos.store.InstanceSetting.storage_setting:type_name -> memos.store.InstanceStorageSetting
12, // 4: memos.store.InstanceSetting.memo_related_setting:type_name -> memos.store.InstanceMemoRelatedSetting
14, // 5: memos.store.InstanceSetting.tags_setting:type_name -> memos.store.InstanceTagsSetting
15, // 6: memos.store.InstanceSetting.notification_setting:type_name -> memos.store.InstanceNotificationSetting
16, // 7: memos.store.InstanceSetting.ai_setting:type_name -> memos.store.InstanceAISetting
19, // 8: memos.store.InstanceSetting.access_setting:type_name -> memos.store.InstanceAccessSetting
8, // 9: memos.store.InstanceGeneralSetting.custom_profile:type_name -> memos.store.InstanceCustomProfile
1, // 10: memos.store.Storage.type:type_name -> memos.store.StorageType
11, // 11: memos.store.Storage.s3_config:type_name -> memos.store.StorageS3Config
4, // 12: memos.store.InstanceStorageSetting.storage_type:type_name -> memos.store.InstanceStorageSetting.StorageType
11, // 13: memos.store.InstanceStorageSetting.s3_config:type_name -> memos.store.StorageS3Config
9, // 14: memos.store.InstanceStorageSetting.storages:type_name -> memos.store.Storage
22, // 15: memos.store.InstanceTagMetadata.background_color:type_name -> google.type.Color
20, // 16: memos.store.InstanceTagsSetting.tags:type_name -> memos.store.InstanceTagsSetting.TagsEntry
21, // 17: memos.store.InstanceNotificationSetting.email:type_name -> memos.store.InstanceNotificationSetting.EmailSetting
17, // 18: memos.store.InstanceAISetting.providers:type_name -> memos.store.AIProviderConfig
18, // 19: memos.store.InstanceAISetting.transcription:type_name -> memos.store.TranscriptionConfig
2, // 20: memos.store.AIProviderConfig.type:type_name -> memos.store.AIProviderType
3, // 21: memos.store.InstanceAccessSetting.access_mode:type_name -> memos.store.InstanceAccessMode
13, // 22: memos.store.InstanceTagsSetting.TagsEntry.value:type_name -> memos.store.InstanceTagMetadata
23, // [23:23] is the sub-list for method output_type
23, // [23:23] is the sub-list for method input_type
23, // [23:23] is the sub-list for extension type_name
23, // [23:23] is the sub-list for extension extendee
0, // [0:23] is the sub-list for field type_name
}
func init() { file_store_instance_setting_proto_init() }
@ -1678,6 +1805,7 @@ func file_store_instance_setting_proto_init() {
(*InstanceSetting_TagsSetting)(nil),
(*InstanceSetting_NotificationSetting)(nil),
(*InstanceSetting_AiSetting)(nil),
(*InstanceSetting_AccessSetting)(nil),
}
file_store_instance_setting_proto_msgTypes[4].OneofWrappers = []any{
(*Storage_S3Config)(nil),
@ -1687,8 +1815,8 @@ func file_store_instance_setting_proto_init() {
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: 4,
NumMessages: 16,
NumEnums: 5,
NumMessages: 17,
NumExtensions: 0,
NumServices: 0,
},

View file

@ -22,6 +22,8 @@ enum InstanceSettingKey {
NOTIFICATION = 6;
// AI is the key for AI provider settings.
AI = 7;
// ACCESS is the key for instance access policy settings.
ACCESS = 8;
}
message InstanceSetting {
@ -34,6 +36,7 @@ message InstanceSetting {
InstanceTagsSetting tags_setting = 6;
InstanceNotificationSetting notification_setting = 7;
InstanceAISetting ai_setting = 8;
InstanceAccessSetting access_setting = 9;
}
}
@ -232,3 +235,13 @@ message TranscriptionConfig {
// spelling hints" block (which the LLM will treat more literally).
string prompt = 4;
}
enum InstanceAccessMode {
INSTANCE_ACCESS_MODE_UNSPECIFIED = 0;
INSTANCE_ACCESS_MODE_PRIVATE = 1;
INSTANCE_ACCESS_MODE_PUBLIC = 2;
}
message InstanceAccessSetting {
InstanceAccessMode access_mode = 1;
}

View file

@ -52,7 +52,7 @@ func IsPublicMethod(procedure string) bool {
}
// AuthBootstrapMethods is the subset of PublicMethods that stays reachable by
// anonymous callers even when the instance is private (no InstanceURL configured).
// anonymous callers even when the instance access mode is PRIVATE.
//
// It is the minimum required to render the sign-in page, authenticate, and follow
// share links, and register when instance settings permit it. Every entry here

View file

@ -106,7 +106,7 @@ func TestAuthBootstrapMethodsAreSubsetOfPublic(t *testing.T) {
}
// TestAuthBootstrapClassification verifies which endpoints remain reachable by
// anonymous callers on a private instance (no InstanceURL configured).
// anonymous callers when the instance access mode is PRIVATE.
func TestAuthBootstrapClassification(t *testing.T) {
// Reachable while private: sign-in flow, registration, instance metadata, SSO, share links.
bootstrap := []string{
@ -125,7 +125,7 @@ func TestAuthBootstrapClassification(t *testing.T) {
})
}
// Public on an open instance, but gated on a private one: browsing and profiles.
// Public in PUBLIC mode, but gated in PRIVATE mode: browsing and profiles.
gatedWhilePrivate := []string{
"/memos.api.v1.MemoService/ListMemos",
"/memos.api.v1.MemoService/GetMemo",

View file

@ -2,9 +2,9 @@ package v1
import (
"context"
"errors"
"github.com/usememos/memos/internal/profile"
"github.com/pkg/errors"
"github.com/usememos/memos/server/auth"
"github.com/usememos/memos/store"
)
@ -25,15 +25,18 @@ var ErrUnauthenticated = errors.New("authentication required")
// governs only authentication and anonymous access.
type Authorizer struct {
authenticator *auth.Authenticator
profile *profile.Profile
accessStore anonymousAccessStore
}
// NewAuthorizer creates an Authorizer backed by the given store, token secret, and
// instance profile.
func NewAuthorizer(store *store.Store, secret string, profile *profile.Profile) *Authorizer {
type anonymousAccessStore interface {
AllowsAnonymousAccess(ctx context.Context) (bool, error)
}
// NewAuthorizer creates an Authorizer backed by the given store and token secret.
func NewAuthorizer(store *store.Store, secret string) *Authorizer {
return &Authorizer{
authenticator: auth.NewAuthenticator(store, secret),
profile: profile,
accessStore: store,
}
}
@ -50,9 +53,9 @@ func (a *Authorizer) Authenticate(ctx context.Context, authHeader string) *auth.
// Policy:
// - Authenticated caller (access token or PAT): always permitted here.
// - Anonymous + protected method: denied.
// - Anonymous + public method, open instance: permitted.
// - Anonymous + public method, private instance (no InstanceURL): permitted only
// for the auth-bootstrap set.
// - Anonymous + auth-bootstrap method: permitted on every instance.
// - Anonymous + other public method: permitted only when the stored access mode
// is PUBLIC.
func (a *Authorizer) CheckAccess(ctx context.Context, procedure string, result *auth.AuthResult) error {
if result != nil {
return nil
@ -60,14 +63,15 @@ func (a *Authorizer) CheckAccess(ctx context.Context, procedure string, result *
if !IsPublicMethod(procedure) {
return ErrUnauthenticated
}
if a.profile.AllowAnonymous() || a.allowedOnPrivateInstance(ctx, procedure) {
if IsAuthBootstrapMethod(procedure) {
return nil
}
allowsAnonymous, err := a.accessStore.AllowsAnonymousAccess(ctx)
if err != nil {
return errors.Wrap(err, "failed to resolve instance access policy")
}
if allowsAnonymous {
return nil
}
return ErrUnauthenticated
}
// allowedOnPrivateInstance reports whether an anonymous request to a public
// procedure is still permitted while the instance is private.
func (*Authorizer) allowedOnPrivateInstance(_ context.Context, procedure string) bool {
return IsAuthBootstrapMethod(procedure)
}

View file

@ -2,23 +2,45 @@ package v1
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/server/auth"
)
type stubAnonymousAccessStore struct {
allowsAnonymous bool
err error
}
func (s stubAnonymousAccessStore) AllowsAnonymousAccess(context.Context) (bool, error) {
return s.allowsAnonymous, s.err
}
func TestWriteGatewayAuthorizationErrorMapsFailureClass(t *testing.T) {
unauthenticated := httptest.NewRecorder()
writeGatewayAuthorizationError(unauthenticated, ErrUnauthenticated)
assert.Equal(t, http.StatusUnauthorized, unauthenticated.Code)
internal := httptest.NewRecorder()
writeGatewayAuthorizationError(internal, errors.New("database unavailable"))
assert.Equal(t, http.StatusInternalServerError, internal.Code)
assert.NotContains(t, internal.Body.String(), "database unavailable")
}
// TestAuthorizerCheckAccess exercises the method-level access policy matrix.
//
// Every case here is decided without touching the store, so a nil store is safe.
func TestAuthorizerCheckAccess(t *testing.T) {
ctx := context.Background()
authenticated := &auth.AuthResult{AccessToken: "token"}
accessStoreError := errors.New("store unavailable")
openInstance := &Authorizer{profile: &profile.Profile{InstanceURL: "https://memos.example.com"}}
privateInstance := &Authorizer{profile: &profile.Profile{InstanceURL: ""}}
publicInstance := &Authorizer{accessStore: stubAnonymousAccessStore{allowsAnonymous: true}}
privateInstance := &Authorizer{accessStore: stubAnonymousAccessStore{allowsAnonymous: false}}
unavailableInstance := &Authorizer{accessStore: stubAnonymousAccessStore{err: accessStoreError}}
const (
protectedMethod = "/memos.api.v1.MemoService/CreateMemo"
@ -33,22 +55,23 @@ func TestAuthorizerCheckAccess(t *testing.T) {
az *Authorizer
procedure string
result *auth.AuthResult
wantErr bool
wantErr error
}{
{"authenticated reaches protected method", privateInstance, protectedMethod, authenticated, false},
{"authenticated reaches public method on private instance", privateInstance, publicMethod, authenticated, false},
{"anonymous denied on protected method", openInstance, protectedMethod, nil, true},
{"anonymous allowed on public method, open instance", openInstance, publicMethod, nil, false},
{"anonymous denied on public method, private instance", privateInstance, publicMethod, nil, true},
{"anonymous allowed on bootstrap method, private instance", privateInstance, bootstrapMethod, nil, false},
{"anonymous allowed to register on private instance", privateInstance, createUser, nil, false},
{"anonymous allowed on share access, private instance", privateInstance, shareMethod, nil, false},
{"authenticated reaches protected method", privateInstance, protectedMethod, authenticated, nil},
{"authenticated reaches public method on private instance", privateInstance, publicMethod, authenticated, nil},
{"anonymous denied on protected method", publicInstance, protectedMethod, nil, ErrUnauthenticated},
{"anonymous allowed on public method, public instance", publicInstance, publicMethod, nil, nil},
{"anonymous denied on public method, private instance", privateInstance, publicMethod, nil, ErrUnauthenticated},
{"anonymous allowed on bootstrap method, private instance", privateInstance, bootstrapMethod, nil, nil},
{"anonymous allowed to register on private instance", privateInstance, createUser, nil, nil},
{"anonymous allowed on share access, private instance", privateInstance, shareMethod, nil, nil},
{"access-store failure is not authentication failure", unavailableInstance, publicMethod, nil, accessStoreError},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
err := c.az.CheckAccess(ctx, c.procedure, c.result)
if c.wantErr {
assert.ErrorIs(t, err, ErrUnauthenticated)
if c.wantErr != nil {
assert.ErrorIs(t, err, c.wantErr)
} else {
assert.NoError(t, err)
}

View file

@ -221,7 +221,7 @@ func (in *AuthInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
result := in.authorizer.Authenticate(ctx, authHeader)
if err := in.authorizer.CheckAccess(ctx, req.Spec().Procedure, result); err != nil {
return nil, connect.NewError(connect.CodeUnauthenticated, err)
return nil, newAuthorizationConnectError(err)
}
ctx = auth.ApplyToContext(ctx, result)
@ -230,6 +230,14 @@ func (in *AuthInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
}
}
func newAuthorizationConnectError(err error) *connect.Error {
if pkgerrors.Is(err, ErrUnauthenticated) {
return connect.NewError(connect.CodeUnauthenticated, ErrUnauthenticated)
}
slog.Error("failed to resolve API access policy", "error", err)
return connect.NewError(connect.CodeInternal, pkgerrors.New("failed to resolve API access policy"))
}
func (*AuthInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
return next
}

View file

@ -2,6 +2,7 @@ package v1
import (
"context"
"errors"
"testing"
"connectrpc.com/connect"
@ -37,3 +38,18 @@ func TestMetadataInterceptorForwardsSecurityHeaders(t *testing.T) {
t.Fatalf("metadata interceptor returned error: %v", err)
}
}
func TestNewAuthorizationConnectErrorMapsFailureClass(t *testing.T) {
unauthenticated := newAuthorizationConnectError(ErrUnauthenticated)
if got := unauthenticated.Code(); got != connect.CodeUnauthenticated {
t.Fatalf("unauthenticated error code = %v, want %v", got, connect.CodeUnauthenticated)
}
internal := newAuthorizationConnectError(errors.New("database unavailable"))
if got := internal.Code(); got != connect.CodeInternal {
t.Fatalf("internal error code = %v, want %v", got, connect.CodeInternal)
}
if got := internal.Message(); got != "failed to resolve API access policy" {
t.Fatalf("internal error message = %q", got)
}
}

View file

@ -57,6 +57,10 @@ func (s *APIV1Service) GetInstanceProfile(ctx context.Context, _ *v1pb.GetInstan
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to list users: %v", err)
}
accessSetting, err := s.Store.GetInstanceAccessSetting(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get instance access setting: %v", err)
}
instanceProfile := &v1pb.InstanceProfile{
Version: s.Profile.Version,
@ -65,6 +69,7 @@ func (s *APIV1Service) GetInstanceProfile(ctx context.Context, _ *v1pb.GetInstan
Admin: admin, // for display only; may be nil even on a populated instance
Commit: s.Profile.Commit,
NeedsSetup: len(users) == 0,
AccessMode: convertInstanceAccessModeFromStore(accessSetting.AccessMode),
}
return instanceProfile, nil
}
@ -130,6 +135,10 @@ func (s *APIV1Service) getInstanceSettingByName(ctx context.Context, name string
var setting *storepb.InstanceAISetting
setting, err = s.Store.GetInstanceAISetting(ctx)
instanceSetting = &storepb.InstanceSetting{Key: instanceSettingKey, Value: &storepb.InstanceSetting_AiSetting{AiSetting: setting}}
case storepb.InstanceSettingKey_ACCESS:
var setting *storepb.InstanceAccessSetting
setting, err = s.Store.GetInstanceAccessSetting(ctx)
instanceSetting = &storepb.InstanceSetting{Key: instanceSettingKey, Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: setting}}
default:
return nil, status.Errorf(codes.InvalidArgument, "unsupported instance setting key: %v", instanceSettingKey)
}

View file

@ -36,6 +36,10 @@ func convertInstanceSettingFromStore(setting *storepb.InstanceSetting) *v1pb.Ins
instanceSetting.Value = &v1pb.InstanceSetting_AiSetting{
AiSetting: convertInstanceAISettingFromStore(setting.GetAiSetting()),
}
case *storepb.InstanceSetting_AccessSetting:
instanceSetting.Value = &v1pb.InstanceSetting_AccessSetting_{
AccessSetting: convertInstanceAccessSettingFromStore(setting.GetAccessSetting()),
}
default:
// Leave Value unset for unsupported setting variants.
}
@ -75,12 +79,38 @@ func convertInstanceSettingToStore(setting *v1pb.InstanceSetting) *storepb.Insta
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) *v1pb.InstanceSetting_AccessSetting {
if setting == nil {
return nil
}
return &v1pb.InstanceSetting_AccessSetting{
AccessMode: convertInstanceAccessModeFromStore(setting.AccessMode),
}
}
func convertInstanceAccessSettingToStore(setting *v1pb.InstanceSetting_AccessSetting) *storepb.InstanceAccessSetting {
if setting == nil {
return nil
}
return &storepb.InstanceAccessSetting{
AccessMode: storepb.InstanceAccessMode(setting.AccessMode),
}
}
func convertInstanceAccessModeFromStore(mode storepb.InstanceAccessMode) v1pb.InstanceAccessMode {
return v1pb.InstanceAccessMode(mode)
}
func convertInstanceGeneralSettingFromStore(setting *storepb.InstanceGeneralSetting) *v1pb.InstanceSetting_GeneralSetting {
if setting == nil {
return nil

View file

@ -19,10 +19,26 @@ func validateInstanceSetting(setting *v1pb.InstanceSetting) error {
if err != nil {
return err
}
if key != storepb.InstanceSettingKey_TAGS.String() {
switch key {
case storepb.InstanceSettingKey_TAGS.String():
return validateInstanceTagsSetting(setting.GetTagsSetting())
case storepb.InstanceSettingKey_ACCESS.String():
return validateInstanceAccessSetting(setting.GetAccessSetting())
default:
return nil
}
return validateInstanceTagsSetting(setting.GetTagsSetting())
}
func validateInstanceAccessSetting(setting *v1pb.InstanceSetting_AccessSetting) error {
if setting == nil {
return errors.New("access setting is required")
}
switch setting.AccessMode {
case v1pb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, v1pb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC:
return nil
default:
return errors.New("access_mode must be PRIVATE or PUBLIC")
}
}
func (s *APIV1Service) prepareInstanceAISettingForUpdate(ctx context.Context, setting *storepb.InstanceAISetting) error {

View file

@ -60,7 +60,13 @@ func (s *APIV1Service) checkMemoReadAccessWithParent(ctx context.Context, memo,
if err != nil {
return status.Errorf(codes.Internal, "failed to get user")
}
allowAnonymous := s.Profile != nil && s.Profile.AllowAnonymous()
allowAnonymous := false
if user == nil {
allowAnonymous, err = s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return status.Errorf(codes.Internal, "failed to resolve instance access policy")
}
}
return memoAccessDecisionError(access.CheckMemoRead(memo, parent, user, allowAnonymous, nil))
}
@ -207,6 +213,15 @@ func (s *APIV1Service) ListMemos(ctx context.Context, request *v1pb.ListMemosReq
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get user")
}
if currentUser == nil {
allowAnonymous, err := s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to resolve instance access policy")
}
if !allowAnonymous {
return nil, status.Errorf(codes.Unauthenticated, "user not authenticated")
}
}
if request.State == v1pb.State_ARCHIVED {
state := store.Archived

View file

@ -7,7 +7,6 @@ import (
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/internal/util"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/server/auth"
@ -22,8 +21,8 @@ func TestAuthorizerPrivateInstanceRegistration(t *testing.T) {
ts := NewTestService(t)
defer ts.Cleanup()
// InstanceURL empty => private instance.
authorizer := apiv1.NewAuthorizer(ts.Store, ts.Secret, &profile.Profile{InstanceURL: ""})
require.NoError(t, ts.SetInstanceAccessMode(ctx, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE))
authorizer := apiv1.NewAuthorizer(ts.Store, ts.Secret)
const (
createUser = "/memos.api.v1.UserService/CreateUser"
@ -41,6 +40,10 @@ func TestAuthorizerPrivateInstanceRegistration(t *testing.T) {
require.NoError(t, authorizer.CheckAccess(ctx, getSharedMemo, nil))
require.ErrorIs(t, authorizer.CheckAccess(ctx, listMemos, nil), apiv1.ErrUnauthenticated)
// Policy reads are fresh: changing to PUBLIC immediately opens browsing.
require.NoError(t, ts.SetInstanceAccessMode(ctx, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC))
require.NoError(t, authorizer.CheckAccess(ctx, listMemos, nil))
// Once a user exists, CreateUser remains reachable so UserService can enforce
// disallow_user_registration and disallow_password_auth.
_, err := ts.CreateHostUser(ctx, "host")
@ -68,8 +71,8 @@ func TestAuthorizerAccessTokenAlwaysWorksOnPrivateInstance(t *testing.T) {
CreatedAt: timestamppb.Now(),
}))
// InstanceURL empty => private instance; the PAT must still authenticate.
authorizer := apiv1.NewAuthorizer(ts.Store, ts.Secret, &profile.Profile{InstanceURL: ""})
require.NoError(t, ts.SetInstanceAccessMode(ctx, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE))
authorizer := apiv1.NewAuthorizer(ts.Store, ts.Secret)
result := authorizer.Authenticate(ctx, "Bearer "+token)
require.NotNil(t, result)

View file

@ -34,6 +34,7 @@ func TestGetInstanceProfile(t *testing.T) {
require.Equal(t, "test-commit", resp.Commit)
require.True(t, resp.Demo)
require.Equal(t, "http://localhost:8080", resp.InstanceUrl)
require.Equal(t, v1pb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC, resp.AccessMode)
// Instance should not be initialized since no users exist at all.
require.Nil(t, resp.Admin)
@ -233,6 +234,19 @@ func TestGetInstanceSetting(t *testing.T) {
require.Empty(t, resp.GetTagsSetting().GetTags())
})
t.Run("GetInstanceSetting - access setting", func(t *testing.T) {
ts := NewTestService(t)
defer ts.Cleanup()
resp, err := ts.Service.GetInstanceSetting(ctx, &v1pb.GetInstanceSettingRequest{
Name: "instance/settings/ACCESS",
})
require.NoError(t, err)
require.Equal(t, "instance/settings/ACCESS", resp.Name)
require.Equal(t, v1pb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC, resp.GetAccessSetting().GetAccessMode())
})
t.Run("GetInstanceSetting - notification setting requires admin", func(t *testing.T) {
ts := NewTestService(t)
defer ts.Cleanup()
@ -452,6 +466,54 @@ func TestTestInstanceEmailSettingRequiresPasswordWhenSMTPIdentityChanges(t *test
func TestUpdateInstanceSetting(t *testing.T) {
ctx := context.Background()
t.Run("UpdateInstanceSetting - access setting", func(t *testing.T) {
ts := NewTestService(t)
defer ts.Cleanup()
admin, err := ts.CreateHostUser(ctx, "access-admin")
require.NoError(t, err)
adminCtx := ts.CreateUserContext(ctx, admin.ID)
resp, err := ts.Service.UpdateInstanceSetting(adminCtx, &v1pb.UpdateInstanceSettingRequest{
Setting: &v1pb.InstanceSetting{
Name: "instance/settings/ACCESS",
Value: &v1pb.InstanceSetting_AccessSetting_{
AccessSetting: &v1pb.InstanceSetting_AccessSetting{
AccessMode: v1pb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE,
},
},
},
})
require.NoError(t, err)
require.Equal(t, v1pb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, resp.GetAccessSetting().GetAccessMode())
profile, err := ts.Service.GetInstanceProfile(ctx, &v1pb.GetInstanceProfileRequest{})
require.NoError(t, err)
require.Equal(t, v1pb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, profile.AccessMode)
_, err = ts.Service.UpdateInstanceSetting(adminCtx, &v1pb.UpdateInstanceSettingRequest{
Setting: &v1pb.InstanceSetting{
Name: "instance/settings/ACCESS",
Value: &v1pb.InstanceSetting_AccessSetting_{
AccessSetting: &v1pb.InstanceSetting_AccessSetting{},
},
},
})
require.Error(t, err)
require.Contains(t, err.Error(), "access_mode must be PRIVATE or PUBLIC")
_, err = ts.Service.UpdateInstanceSetting(adminCtx, &v1pb.UpdateInstanceSettingRequest{
Setting: &v1pb.InstanceSetting{
Name: "instance/settings/ACCESS",
Value: &v1pb.InstanceSetting_GeneralSetting_{
GeneralSetting: &v1pb.InstanceSetting_GeneralSetting{},
},
},
})
require.Error(t, err)
require.Contains(t, err.Error(), "access setting is required")
})
t.Run("UpdateInstanceSetting - AI setting requires admin", func(t *testing.T) {
ts := NewTestService(t)
defer ts.Cleanup()

View file

@ -14,9 +14,43 @@ import (
"google.golang.org/protobuf/types/known/timestamppb"
apiv1 "github.com/usememos/memos/proto/gen/api/v1"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
)
func TestAnonymousMemoAccessFollowsInstanceAccessSetting(t *testing.T) {
ctx := context.Background()
ts := NewTestService(t)
defer ts.Cleanup()
owner, err := ts.CreateRegularUser(ctx, "access-mode-owner")
require.NoError(t, err)
ownerCtx := ts.CreateUserContext(ctx, owner.ID)
memo, err := ts.Service.CreateMemo(ownerCtx, &apiv1.CreateMemoRequest{Memo: &apiv1.Memo{
Content: "public memo",
Visibility: apiv1.Visibility_PUBLIC,
}})
require.NoError(t, err)
_, err = ts.Service.GetMemo(ctx, &apiv1.GetMemoRequest{Name: memo.Name})
require.NoError(t, err)
_, err = ts.Service.ListMemos(ctx, &apiv1.ListMemosRequest{})
require.NoError(t, err)
require.NoError(t, ts.SetInstanceAccessMode(ctx, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE))
_, err = ts.Service.GetMemo(ctx, &apiv1.GetMemoRequest{Name: memo.Name})
require.Equal(t, codes.Unauthenticated, status.Code(err))
_, err = ts.Service.ListMemos(ctx, &apiv1.ListMemosRequest{})
require.Equal(t, codes.Unauthenticated, status.Code(err))
_, err = ts.Service.GetMemo(ownerCtx, &apiv1.GetMemoRequest{Name: memo.Name})
require.NoError(t, err)
require.NoError(t, ts.SetInstanceAccessMode(ctx, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC))
_, err = ts.Service.GetMemo(ctx, &apiv1.GetMemoRequest{Name: memo.Name})
require.NoError(t, err)
}
func TestCreateMemoAcceptsUUID(t *testing.T) {
ctx := context.Background()
ts := NewTestService(t)

View file

@ -6,6 +6,7 @@ import (
"github.com/usememos/memos/internal/markdown"
"github.com/usememos/memos/internal/profile"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/server/auth"
apiv1 "github.com/usememos/memos/server/router/api/v1"
"github.com/usememos/memos/store"
@ -26,6 +27,14 @@ func NewTestService(t *testing.T) *TestService {
// Create a test store with SQLite
testStore := teststore.NewTestingStore(ctx, t)
if _, err := testStore.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
Key: storepb.InstanceSettingKey_ACCESS,
Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{
AccessMode: storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC,
}},
}); err != nil {
t.Fatalf("failed to configure public access for API test service: %v", err)
}
// Align the profile data directory with the test store so attachment files and
// derived caches resolve against the same location as DeleteAttachmentStorage.
@ -61,6 +70,17 @@ func NewTestService(t *testing.T) *TestService {
}
}
// SetInstanceAccessMode updates the instance access policy for a test.
func (ts *TestService) SetInstanceAccessMode(ctx context.Context, mode storepb.InstanceAccessMode) error {
_, err := ts.Store.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
Key: storepb.InstanceSettingKey_ACCESS,
Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{
AccessMode: mode,
}},
})
return err
}
// Cleanup closes resources after test.
func (ts *TestService) Cleanup() {
ts.Store.Close()

View file

@ -2,6 +2,7 @@ package v1
import (
"context"
"log/slog"
"net/http"
"connectrpc.com/connect"
@ -94,7 +95,7 @@ func newGatewayMarshaler() *runtime.HTTPBodyMarshaler {
func (s *APIV1Service) RegisterGateway(ctx context.Context, echoServer *echo.Echo) error {
// Shared authorizer: one source of truth for authentication and anonymous-access
// policy, used by both the gRPC-Gateway middleware and the Connect interceptor.
authorizer := NewAuthorizer(s.Store, s.Secret, s.Profile)
authorizer := NewAuthorizer(s.Store, s.Secret)
// grpc-gateway does not hand the matched procedure to middleware:
// runtime.RPCMethod is only populated by the generated handler, which runs
@ -118,7 +119,7 @@ func (s *APIV1Service) RegisterGateway(ctx context.Context, echoServer *echo.Ech
// access-control gap.
procedure, _ := routeResolver.resolveRequest(r)
if err := authorizer.CheckAccess(ctx, procedure, result); err != nil {
http.Error(w, `{"code": 16, "message": "authentication required"}`, http.StatusUnauthorized)
writeGatewayAuthorizationError(w, err)
return
}
@ -185,3 +186,12 @@ func (s *APIV1Service) RegisterGateway(ctx context.Context, echoServer *echo.Ech
return nil
}
func writeGatewayAuthorizationError(w http.ResponseWriter, err error) {
if errors.Is(err, ErrUnauthenticated) {
http.Error(w, `{"code": 16, "message": "authentication required"}`, http.StatusUnauthorized)
return
}
slog.Error("failed to resolve API access policy", "error", err)
http.Error(w, `{"code": 13, "message": "failed to resolve API access policy"}`, http.StatusInternalServerError)
}

View file

@ -169,9 +169,15 @@ func (s *FileServerService) serveAttachmentFile(c *echo.Context) error {
func (s *FileServerService) serveUserAvatar(c *echo.Context) error {
ctx := c.Request().Context()
// On a private instance (no InstanceURL), avatars are not exposed to anonymous
// visitors; a valid session, access token, or PAT is required.
if !s.Profile.AllowAnonymous() {
allowAnonymous, err := s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get instance access policy").Wrap(err)
}
cacheControl := cacheMaxAge
// On a private instance, avatars are not exposed to anonymous visitors; a
// valid session, access token, or PAT is required.
if !allowAnonymous {
cacheControl = privateAttachmentCacheControl
viewer, err := s.getCurrentUser(ctx, c)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get current user").Wrap(err)
@ -204,7 +210,7 @@ func (s *FileServerService) serveUserAvatar(c *echo.Context) error {
}
setSecurityHeaders(c)
c.Response().Header().Set(echo.HeaderCacheControl, cacheMaxAge)
c.Response().Header().Set(echo.HeaderCacheControl, cacheControl)
return c.Blob(http.StatusOK, imageType, imageData)
}
@ -626,7 +632,10 @@ func (s *FileServerService) checkAttachmentPermission(ctx context.Context, c *ec
}
}
allowAnonymous := s.Profile != nil && s.Profile.AllowAnonymous()
allowAnonymous, err := s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusInternalServerError, "failed to get instance access policy").Wrap(err)
}
if decision := access.CheckMemoRead(memo, parent, nil, allowAnonymous, nil); decision.Allowed() {
return decision.Class, nil
}

View file

@ -160,13 +160,13 @@ func TestServeAttachmentFile_S3MinIO(t *testing.T) {
// Authorization happens before storage resolution, so a private instance
// must not expose object bytes.
fs.Profile.InstanceURL = ""
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE)
privateRecorder := httptest.NewRecorder()
e.ServeHTTP(privateRecorder, httptest.NewRequest(http.MethodGet, textURL, nil))
require.Equal(t, http.StatusUnauthorized, privateRecorder.Code)
require.Empty(t, privateRecorder.Header().Get(echo.HeaderLocation))
fs.Profile.InstanceURL = "http://localhost:8080"
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
textRecorder := httptest.NewRecorder()
e.ServeHTTP(textRecorder, httptest.NewRequest(http.MethodGet, textURL, nil))
require.Equal(t, http.StatusOK, textRecorder.Code)
@ -218,7 +218,7 @@ func TestServeAttachmentFile_S3MinIO(t *testing.T) {
func TestServeAttachmentFile_ShareTokenAllowsDirectMemoAttachment(t *testing.T) {
ctx := context.Background()
svc, fs, _, cleanup := newShareAttachmentTestServices(ctx, t)
svc, fs, stores, cleanup := newShareAttachmentTestServices(ctx, t)
defer cleanup()
creator, err := svc.Store.CreateUser(ctx, &store.User{
@ -261,6 +261,7 @@ func TestServeAttachmentFile_ShareTokenAllowsDirectMemoAttachment(t *testing.T)
fs.RegisterRoutes(e)
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/%s?share_token=%s", attachment.Name, attachment.Filename, shareToken), nil)
req.AddCookie(newExpiredRefreshTokenCookie(ctx, t, stores, creator.ID, svc.Secret))
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
@ -679,6 +680,7 @@ func newShareAttachmentTestServices(ctx context.Context, t *testing.T) (*apiv1se
t.Helper()
testStore := teststore.NewTestingStore(ctx, t)
setInstanceAccessMode(ctx, t, testStore, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
testProfile := &profile.Profile{
Demo: true,
Version: "test-1.0.0",
@ -703,6 +705,17 @@ func newShareAttachmentTestServices(ctx context.Context, t *testing.T) (*apiv1se
}
}
func setInstanceAccessMode(ctx context.Context, t *testing.T, stores *store.Store, mode storepb.InstanceAccessMode) {
t.Helper()
_, err := stores.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
Key: storepb.InstanceSettingKey_ACCESS,
Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{
AccessMode: mode,
}},
})
require.NoError(t, err)
}
// makePNGDataURI returns a minimal valid PNG encoded as a data URI, suitable for a
// user avatar.
func makePNGDataURI(t *testing.T) string {
@ -716,10 +729,10 @@ func makePNGDataURI(t *testing.T) string {
// TestServeAttachmentFile_PrivateInstanceDeniesAnonymous verifies that a public
// memo's attachment is served to anonymous visitors on an open instance but denied
// on a private instance (no InstanceURL configured).
// when the instance access policy is private.
func TestServeAttachmentFile_PrivateInstanceDeniesAnonymous(t *testing.T) {
ctx := context.Background()
svc, fs, _, cleanup := newShareAttachmentTestServices(ctx, t)
svc, fs, stores, cleanup := newShareAttachmentTestServices(ctx, t)
defer cleanup()
creator, err := svc.Store.CreateUser(ctx, &store.User{
@ -759,11 +772,20 @@ func TestServeAttachmentFile_PrivateInstanceDeniesAnonymous(t *testing.T) {
}
// Open instance: anonymous access to a public memo's attachment is allowed.
fs.Profile.InstanceURL = "http://localhost:8080"
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
require.Equal(t, http.StatusOK, anonymousGet())
// A stale browser session must not prevent access to an otherwise public
// attachment. Public authorization is independent of invalid credentials.
req := httptest.NewRequest(http.MethodGet, url, nil)
req.AddCookie(newExpiredRefreshTokenCookie(ctx, t, stores, creator.ID, svc.Secret))
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "public content", rec.Body.String())
// Private instance: the same anonymous request is denied.
fs.Profile.InstanceURL = ""
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE)
require.Equal(t, http.StatusUnauthorized, anonymousGet())
}
@ -772,10 +794,10 @@ func TestServeAttachmentFile_PrivateInstanceDeniesAnonymous(t *testing.T) {
// instance.
func TestServeUserAvatar_PrivateInstanceRequiresAuth(t *testing.T) {
ctx := context.Background()
svc, fs, _, cleanup := newShareAttachmentTestServices(ctx, t)
svc, fs, stores, cleanup := newShareAttachmentTestServices(ctx, t)
defer cleanup()
_, err := svc.Store.CreateUser(ctx, &store.User{
owner, err := svc.Store.CreateUser(ctx, &store.User{
Username: "avatar-owner",
Role: store.RoleUser,
Email: "avatar-owner@example.com",
@ -786,19 +808,47 @@ func TestServeUserAvatar_PrivateInstanceRequiresAuth(t *testing.T) {
e := echo.New()
fs.RegisterRoutes(e)
anonymousGet := func() int {
anonymousGet := func() *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/file/users/avatar-owner/avatar", nil))
return rec.Code
return rec
}
// Open instance: anonymous avatar access is allowed.
fs.Profile.InstanceURL = "http://localhost:8080"
require.Equal(t, http.StatusOK, anonymousGet())
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
publicRec := anonymousGet()
require.Equal(t, http.StatusOK, publicRec.Code)
require.Equal(t, cacheMaxAge, publicRec.Header().Get(echo.HeaderCacheControl))
// A stale browser session must not turn a public avatar request into an
// authentication error.
req := httptest.NewRequest(http.MethodGet, "/file/users/avatar-owner/avatar", nil)
req.AddCookie(newExpiredRefreshTokenCookie(ctx, t, stores, owner.ID, svc.Secret))
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "image/png", rec.Header().Get(echo.HeaderContentType))
// Private instance: anonymous avatar access is denied.
fs.Profile.InstanceURL = ""
require.Equal(t, http.StatusUnauthorized, anonymousGet())
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE)
require.Equal(t, http.StatusUnauthorized, anonymousGet().Code)
// An authenticated private-instance response must not be stored by shared
// or browser caches.
tokenID := util.GenUUID()
require.NoError(t, stores.AddUserRefreshToken(ctx, owner.ID, &storepb.RefreshTokensUserSetting_RefreshToken{
TokenId: tokenID,
ExpiresAt: timestamppb.New(time.Now().Add(auth.RefreshTokenDuration)),
CreatedAt: timestamppb.Now(),
}))
refreshToken, _, err := auth.GenerateRefreshToken(owner.ID, tokenID, []byte(svc.Secret))
require.NoError(t, err)
privateReq := httptest.NewRequest(http.MethodGet, "/file/users/avatar-owner/avatar", nil)
privateReq.AddCookie(&http.Cookie{Name: auth.RefreshTokenCookieName, Value: refreshToken})
privateRec := httptest.NewRecorder()
e.ServeHTTP(privateRec, privateReq)
require.Equal(t, http.StatusOK, privateRec.Code)
require.Equal(t, privateAttachmentCacheControl, privateRec.Header().Get(echo.HeaderCacheControl))
}
// TestServeAttachmentFile_RefreshCookieAuthenticatesOwner verifies that the file
@ -863,3 +913,16 @@ func TestServeAttachmentFile_RefreshCookieAuthenticatesOwner(t *testing.T) {
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "secret content", rec.Body.String())
}
func newExpiredRefreshTokenCookie(ctx context.Context, t *testing.T, stores *store.Store, userID int32, secret string) *http.Cookie {
t.Helper()
tokenID := util.GenUUID()
require.NoError(t, stores.AddUserRefreshToken(ctx, userID, &storepb.RefreshTokensUserSetting_RefreshToken{
TokenId: tokenID,
ExpiresAt: timestamppb.New(time.Now().Add(-time.Hour)),
CreatedAt: timestamppb.New(time.Now().Add(-2 * time.Hour)),
}))
refreshToken, _, err := auth.GenerateRefreshToken(userID, tokenID, []byte(secret))
require.NoError(t, err)
return &http.Cookie{Name: auth.RefreshTokenCookieName, Value: refreshToken}
}

View file

@ -126,6 +126,9 @@ func (s *FrontendService) registerRoutes(e *echo.Echo) {
}
func (s *FrontendService) getRobotsTXT(c *echo.Context) error {
if err := s.requirePublicAccess(c.Request().Context()); err != nil {
return err
}
instanceURL, err := normalizeInstanceURL(s.Profile.InstanceURL)
if err != nil {
return err
@ -141,6 +144,9 @@ func (s *FrontendService) getRobotsTXT(c *echo.Context) error {
}
func (s *FrontendService) getSitemapXML(c *echo.Context) error {
if err := s.requirePublicAccess(c.Request().Context()); err != nil {
return err
}
instanceURL, err := normalizeInstanceURL(s.Profile.InstanceURL)
if err != nil {
return err
@ -166,6 +172,17 @@ func (s *FrontendService) getSitemapXML(c *echo.Context) error {
})
}
func (s *FrontendService) requirePublicAccess(ctx context.Context) error {
allowsAnonymous, err := s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get instance access policy").Wrap(err)
}
if !allowsAnonymous {
return echo.NewHTTPError(http.StatusNotFound, "public instance discovery is unavailable")
}
return nil
}
func normalizeInstanceURL(instanceURL string) (string, error) {
instanceURL = strings.TrimRight(instanceURL, "/")
if instanceURL == "" {

View file

@ -10,6 +10,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/usememos/memos/internal/profile"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
teststore "github.com/usememos/memos/store/test"
)
@ -157,6 +158,7 @@ func TestFrontendService_SkipsDynamicRoutes(t *testing.T) {
func TestFrontendService_RobotsTXT(t *testing.T) {
ctx := context.Background()
testStore := teststore.NewTestingStore(ctx, t)
setFrontendAccessMode(ctx, t, testStore, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
profile := &profile.Profile{
InstanceURL: "https://demo.usememos.com/",
}
@ -176,6 +178,7 @@ func TestFrontendService_RobotsTXT(t *testing.T) {
func TestFrontendService_SitemapXML(t *testing.T) {
ctx := context.Background()
testStore := teststore.NewTestingStore(ctx, t)
setFrontendAccessMode(ctx, t, testStore, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
profile := &profile.Profile{
InstanceURL: "https://demo.usememos.com",
}
@ -219,6 +222,7 @@ func TestFrontendService_SitemapXML(t *testing.T) {
func TestFrontendService_SitemapRoutesRequireInstanceURL(t *testing.T) {
ctx := context.Background()
testStore := teststore.NewTestingStore(ctx, t)
setFrontendAccessMode(ctx, t, testStore, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
e := echo.New()
NewFrontendService(&profile.Profile{}, testStore).Serve(ctx, e)
@ -231,3 +235,31 @@ func TestFrontendService_SitemapRoutesRequireInstanceURL(t *testing.T) {
require.Equal(t, http.StatusNotFound, rec.Code)
}
}
func TestFrontendService_SitemapRoutesRequirePublicAccess(t *testing.T) {
ctx := context.Background()
testStore := teststore.NewTestingStore(ctx, t)
setFrontendAccessMode(ctx, t, testStore, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE)
e := echo.New()
NewFrontendService(&profile.Profile{InstanceURL: "https://private.example.com"}, testStore).Serve(ctx, e)
for _, path := range []string{"/robots.txt", "/sitemap.xml"} {
req := httptest.NewRequest(http.MethodGet, path, nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
require.Equal(t, http.StatusNotFound, rec.Code)
}
}
func setFrontendAccessMode(ctx context.Context, t *testing.T, stores *store.Store, mode storepb.InstanceAccessMode) {
t.Helper()
_, err := stores.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
Key: storepb.InstanceSettingKey_ACCESS,
Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{
AccessMode: mode,
}},
})
require.NoError(t, err)
}

View file

@ -15,7 +15,6 @@ import (
"github.com/labstack/echo/v5"
"github.com/usememos/memos/internal/markdown"
"github.com/usememos/memos/internal/profile"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
)
@ -40,7 +39,6 @@ type cacheEntry struct {
}
type RSSService struct {
Profile *profile.Profile
Store *store.Store
MarkdownService markdown.Service
@ -55,9 +53,9 @@ type RSSHeading struct {
Language string
}
func NewRSSService(profile *profile.Profile, store *store.Store, markdownService markdown.Service) *RSSService {
// NewRSSService creates an RSS service backed by the store and markdown renderer.
func NewRSSService(store *store.Store, markdownService markdown.Service) *RSSService {
return &RSSService{
Profile: profile,
Store: store,
MarkdownService: markdownService,
cache: make(map[string]*cacheEntry),
@ -70,11 +68,15 @@ func (s *RSSService) RegisterRoutes(g *echo.Group) {
}
func (s *RSSService) GetExploreRSS(c *echo.Context) error {
if s.Profile == nil || !s.Profile.AllowAnonymous() {
ctx := c.Request().Context()
allowAnonymous, err := s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get instance access policy").Wrap(err)
}
if !allowAnonymous {
return echo.NewHTTPError(http.StatusNotFound, "RSS is unavailable")
}
ctx := c.Request().Context()
cacheKey := "explore"
// Check cache first
@ -113,11 +115,15 @@ func (s *RSSService) GetExploreRSS(c *echo.Context) error {
}
func (s *RSSService) GetUserRSS(c *echo.Context) error {
if s.Profile == nil || !s.Profile.AllowAnonymous() {
ctx := c.Request().Context()
allowAnonymous, err := s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get instance access policy").Wrap(err)
}
if !allowAnonymous {
return echo.NewHTTPError(http.StatusNotFound, "RSS is unavailable")
}
ctx := c.Request().Context()
username := c.Param("username")
cacheKey := "user:" + username

View file

@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/usememos/memos/internal/markdown"
"github.com/usememos/memos/internal/profile"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
teststore "github.com/usememos/memos/store/test"
)
@ -20,6 +20,7 @@ func TestPublicRSSExcludesComments(t *testing.T) {
ctx := context.Background()
stores := teststore.NewTestingStore(ctx, t)
defer stores.Close()
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
user, err := stores.CreateUser(ctx, &store.User{
Username: "rss-comment-owner",
@ -51,7 +52,7 @@ func TestPublicRSSExcludesComments(t *testing.T) {
})
require.NoError(t, err)
service := NewRSSService(&profile.Profile{InstanceURL: "https://memos.example.com"}, stores, markdown.NewService())
service := NewRSSService(stores, markdown.NewService())
exploreRSS := renderRSS(t, service, "/explore/rss.xml", "")
require.Contains(t, exploreRSS, "public parent should stay in rss")
@ -63,7 +64,11 @@ func TestPublicRSSExcludesComments(t *testing.T) {
}
func TestPrivateInstanceDisablesRSS(t *testing.T) {
service := NewRSSService(&profile.Profile{}, nil, nil)
ctx := context.Background()
stores := teststore.NewTestingStore(ctx, t)
defer stores.Close()
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE)
service := NewRSSService(stores, nil)
for _, test := range []struct {
name string
@ -96,6 +101,17 @@ func TestPrivateInstanceDisablesRSS(t *testing.T) {
}
}
func setInstanceAccessMode(ctx context.Context, t *testing.T, stores *store.Store, mode storepb.InstanceAccessMode) {
t.Helper()
_, err := stores.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
Key: storepb.InstanceSettingKey_ACCESS,
Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{
AccessMode: mode,
}},
})
require.NoError(t, err)
}
func renderRSS(t *testing.T, service *RSSService, target string, username string) string {
t.Helper()

View file

@ -77,7 +77,7 @@ func NewServer(ctx context.Context, profile *profile.Profile, store *store.Store
fileServerService.RegisterRoutes(echoServer)
// Create and register RSS routes (needs markdown service from apiV1Service).
rss.NewRSSService(s.Profile, s.Store, apiV1Service.MarkdownService).RegisterRoutes(rootGroup)
rss.NewRSSService(s.Store, apiV1Service.MarkdownService).RegisterRoutes(rootGroup)
// Register gRPC gateway as api v1 (includes SSE endpoint on CORS-enabled group).
if err := apiV1Service.RegisterGateway(ctx, echoServer); err != nil {

View file

@ -26,6 +26,7 @@ import (
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/internal/version"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/server"
"github.com/usememos/memos/store"
"github.com/usememos/memos/store/db"
@ -40,8 +41,9 @@ const (
type instanceOptions struct {
// demo enables demo mode, which seeds the database during migration.
demo bool
// instanceURL is the public instance URL. An empty value makes the
// instance private, which restricts anonymous access to bootstrap methods.
// instanceURL is the canonical external instance URL. On the first boot of
// a database without ACCESS, it is also the legacy compatibility input used
// to initialize that dedicated setting exactly once.
instanceURL string
// dataDir reuses an existing data directory instead of a fresh one, which
// is how a restart against an already-migrated database is simulated.
@ -349,14 +351,15 @@ func TestStartupRestartPreservesData(t *testing.T) {
second.requireMemo(t, restartToken, "startup-after-restart", "written after restart")
}
// TestStartupPrivateInstance verifies an instance with no InstanceURL boots,
// still exposes the auth bootstrap surface, and refuses anonymous callers on
// non-bootstrap procedures.
// TestStartupPrivateInstance verifies a private instance still exposes the auth
// bootstrap surface and refuses anonymous callers on non-bootstrap procedures.
func TestStartupPrivateInstance(t *testing.T) {
ctx := context.Background()
inst := bootInstance(ctx, t, instanceOptions{instanceURL: ""})
require.False(t, inst.profile.AllowAnonymous(), "an instance without InstanceURL should be private")
accessSetting, err := inst.server.Store.GetInstanceAccessSetting(ctx)
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, accessSetting.AccessMode)
// Bootstrap methods stay reachable so the sign-in page can render.
status, body := inst.do(t, http.MethodGet, "/api/v1/instance/profile", "", nil)
@ -379,6 +382,47 @@ func TestStartupPrivateInstance(t *testing.T) {
inst.requireMemo(t, token, "startup-private", "private instance sentinel")
}
// TestStartupInitializesLegacyAccessOnce verifies the compatibility bridge from
// the former instance-URL-derived policy to the database-backed ACCESS setting.
// Later URL changes must not silently change authorization behavior.
func TestStartupInitializesLegacyAccessOnce(t *testing.T) {
ctx := context.Background()
t.Run("public remains public after URL removal", func(t *testing.T) {
dataDir := t.TempDir()
first := bootInstance(ctx, t, instanceOptions{instanceURL: "https://memos.example.com", dataDir: dataDir})
accessSetting, err := first.server.Store.GetInstanceAccessSetting(ctx)
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC, accessSetting.AccessMode)
first.shutdown(ctx)
second := bootInstance(ctx, t, instanceOptions{instanceURL: "", dataDir: dataDir})
accessSetting, err = second.server.Store.GetInstanceAccessSetting(ctx)
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC, accessSetting.AccessMode)
status, body := second.do(t, http.MethodGet, "/api/v1/memos", "", nil)
require.Equal(t, http.StatusOK, status, "persisted PUBLIC mode should still allow anonymous access: %s", body)
})
t.Run("private remains private after URL addition", func(t *testing.T) {
dataDir := t.TempDir()
first := bootInstance(ctx, t, instanceOptions{instanceURL: "", dataDir: dataDir})
accessSetting, err := first.server.Store.GetInstanceAccessSetting(ctx)
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, accessSetting.AccessMode)
first.shutdown(ctx)
second := bootInstance(ctx, t, instanceOptions{instanceURL: "https://memos.example.com", dataDir: dataDir})
accessSetting, err = second.server.Store.GetInstanceAccessSetting(ctx)
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, accessSetting.AccessMode)
status, _ := second.do(t, http.MethodGet, "/api/v1/memos", "", nil)
require.Equal(t, http.StatusUnauthorized, status, "canonical URL must not reopen a persisted PRIVATE instance")
})
}
// TestStartupPrivateInstanceGatewayPolicy asserts the private-instance policy is
// enforced on the gRPC-Gateway transport, not just on Connect.
//

View file

@ -4,9 +4,25 @@ import (
"context"
"strings"
"github.com/pkg/errors"
"github.com/usememos/memos/store"
)
// 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) {
stmt := "INSERT IGNORE INTO `system_setting` (`name`, `value`, `description`) VALUES (?, ?, ?)"
result, err := d.db.ExecContext(ctx, stmt, create.Name, create.Value, create.Description)
if err != nil {
return false, errors.Wrap(err, "failed to conditionally create instance setting")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return false, errors.Wrap(err, "failed to inspect conditional instance setting insert")
}
return rowsAffected == 1, nil
}
func (d *DB) UpsertInstanceSetting(ctx context.Context, upsert *store.InstanceSetting) (*store.InstanceSetting, error) {
stmt := "INSERT INTO `system_setting` (`name`, `value`, `description`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `value` = ?, `description` = ?"
_, err := d.db.ExecContext(

View file

@ -4,9 +4,31 @@ import (
"context"
"strings"
"github.com/pkg/errors"
"github.com/usememos/memos/store"
)
// 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) {
stmt := `
INSERT INTO system_setting (
name, value, description
)
VALUES ($1, $2, $3)
ON CONFLICT(name) DO NOTHING
`
result, err := d.db.ExecContext(ctx, stmt, create.Name, create.Value, create.Description)
if err != nil {
return false, errors.Wrap(err, "failed to conditionally create instance setting")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return false, errors.Wrap(err, "failed to inspect conditional instance setting insert")
}
return rowsAffected == 1, nil
}
func (d *DB) UpsertInstanceSetting(ctx context.Context, upsert *store.InstanceSetting) (*store.InstanceSetting, error) {
stmt := `
INSERT INTO system_setting (

View file

@ -4,9 +4,31 @@ import (
"context"
"strings"
"github.com/pkg/errors"
"github.com/usememos/memos/store"
)
// 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) {
stmt := `
INSERT INTO system_setting (
name, value, description
)
VALUES (?, ?, ?)
ON CONFLICT(name) DO NOTHING
`
result, err := d.db.ExecContext(ctx, stmt, create.Name, create.Value, create.Description)
if err != nil {
return false, errors.Wrap(err, "failed to conditionally create instance setting")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return false, errors.Wrap(err, "failed to inspect conditional instance setting insert")
}
return rowsAffected == 1, nil
}
func (d *DB) UpsertInstanceSetting(ctx context.Context, upsert *store.InstanceSetting) (*store.InstanceSetting, error) {
stmt := `
INSERT INTO system_setting (

View file

@ -287,6 +287,16 @@ func validateAndNormalizeDeploymentInstanceSetting(setting *storepb.InstanceSett
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_BASIC, storepb.InstanceSettingKey_TAGS:
return errors.Errorf("key %s cannot be deployment configured", setting.Key)
default:

View file

@ -237,6 +237,12 @@ func TestLoadDeploymentConfigurationSupportsEveryProvisionableSettingGroup(t *te
{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)
@ -249,6 +255,9 @@ func TestLoadDeploymentConfigurationSupportsEveryProvisionableSettingGroup(t *te
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) {
@ -261,6 +270,8 @@ func TestLoadDeploymentConfigurationRejectsInvalidSettingResources(t *testing.T)
{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 {

View file

@ -38,6 +38,8 @@ type Driver interface {
DeleteMemoRelation(ctx context.Context, delete *DeleteMemoRelation) error
// InstanceSetting model related methods.
// CreateInstanceSettingIfNotExists atomically creates the setting when its name is absent and reports whether it inserted the row.
CreateInstanceSettingIfNotExists(ctx context.Context, create *InstanceSetting) (bool, error)
UpsertInstanceSetting(ctx context.Context, upsert *InstanceSetting) (*InstanceSetting, error)
ListInstanceSettings(ctx context.Context, find *FindInstanceSetting) ([]*InstanceSetting, error)
DeleteInstanceSetting(ctx context.Context, delete *DeleteInstanceSetting) error

View file

@ -47,6 +47,8 @@ func (s *Store) UpsertInstanceSetting(ctx context.Context, upsert *storepb.Insta
valueBytes, err = protojson.Marshal(upsert.GetNotificationSetting())
} else if upsert.Key == storepb.InstanceSettingKey_AI {
valueBytes, err = protojson.Marshal(upsert.GetAiSetting())
} else if upsert.Key == storepb.InstanceSettingKey_ACCESS {
valueBytes, err = protojson.Marshal(upsert.GetAccessSetting())
} else {
return nil, errors.Errorf("unsupported instance setting key: %v", upsert.Key)
}
@ -227,6 +229,38 @@ func (s *Store) GetInstanceGeneralSetting(ctx context.Context) (*storepb.Instanc
return instanceGeneralSetting, nil
}
// 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")
}
}
instanceAccessSetting := &storepb.InstanceAccessSetting{}
if instanceSetting != nil && instanceSetting.GetAccessSetting() != nil {
instanceAccessSetting = instanceSetting.GetAccessSetting()
}
if instanceAccessSetting.AccessMode == storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_UNSPECIFIED {
instanceAccessSetting.AccessMode = storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE
}
return instanceAccessSetting, nil
}
// AllowsAnonymousAccess reports whether the effective instance access policy is public.
func (s *Store) AllowsAnonymousAccess(ctx context.Context) (bool, error) {
setting, err := s.GetInstanceAccessSetting(ctx)
if err != nil {
return false, err
}
return setting.AccessMode == storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC, nil
}
// DefaultContentLengthLimit is the default limit of content length in bytes. 8KB.
const DefaultContentLengthLimit = 8 * 1024
@ -411,6 +445,12 @@ func convertInstanceSettingFromRaw(instanceSettingRaw *InstanceSetting) (*storep
return nil, err
}
instanceSetting.Value = &storepb.InstanceSetting_AiSetting{AiSetting: aiSetting}
case storepb.InstanceSettingKey_ACCESS.String():
accessSetting := &storepb.InstanceAccessSetting{}
if err := protojsonUnmarshaler.Unmarshal([]byte(instanceSettingRaw.Value), accessSetting); err != nil {
return nil, err
}
instanceSetting.Value = &storepb.InstanceSetting_AccessSetting{AccessSetting: accessSetting}
default:
// Skip unsupported instance setting key.
return nil, nil

View file

@ -13,6 +13,7 @@ import (
"strings"
"github.com/pkg/errors"
"google.golang.org/protobuf/encoding/protojson"
"github.com/usememos/memos/internal/version"
storepb "github.com/usememos/memos/proto/gen/store"
@ -132,6 +133,31 @@ func (s *Store) Migrate(ctx context.Context) error {
return errors.Wrap(err, "failed to seed")
}
}
if err := s.initializeInstanceAccessSetting(ctx); err != nil {
return errors.Wrap(err, "failed to initialize instance access setting")
}
return nil
}
// initializeInstanceAccessSetting captures the pre-ACCESS behavior exactly once.
// Existing installations that configured an external URL were public; all others
// were private. Once persisted, later URL changes do not alter the access policy.
func (s *Store) initializeInstanceAccessSetting(ctx context.Context) error {
accessMode := storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE
if strings.TrimSpace(s.profile.InstanceURL) != "" {
accessMode = storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC
}
value, err := protojson.Marshal(&storepb.InstanceAccessSetting{AccessMode: accessMode})
if err != nil {
return errors.Wrap(err, "failed to marshal initial instance access setting")
}
_, err = s.driver.CreateInstanceSettingIfNotExists(ctx, &InstanceSetting{
Name: storepb.InstanceSettingKey_ACCESS.String(),
Value: string(value),
})
if err != nil {
return errors.Wrap(err, "failed to conditionally create initial instance access setting")
}
return nil
}

View file

@ -2,6 +2,7 @@ package test
import (
"context"
"fmt"
"sync"
"testing"
@ -152,6 +153,94 @@ func TestInstanceSettingGeneralSetting(t *testing.T) {
ts.Close()
}
func TestInstanceAccessSetting(t *testing.T) {
t.Parallel()
ctx := context.Background()
ts := NewTestingStore(ctx, t)
defer ts.Close()
accessSetting, err := ts.GetInstanceAccessSetting(ctx)
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, accessSetting.AccessMode)
allowsAnonymous, err := ts.AllowsAnonymousAccess(ctx)
require.NoError(t, err)
require.False(t, allowsAnonymous)
_, err = ts.UpsertInstanceSetting(ctx, &storepb.InstanceSetting{
Key: storepb.InstanceSettingKey_ACCESS,
Value: &storepb.InstanceSetting_AccessSetting{AccessSetting: &storepb.InstanceAccessSetting{
AccessMode: storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC,
}},
})
require.NoError(t, err)
stored, err := ts.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{Name: storepb.InstanceSettingKey_ACCESS.String()})
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC, stored.GetAccessSetting().AccessMode)
accessSetting, err = ts.GetInstanceAccessSetting(ctx)
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC, accessSetting.AccessMode)
allowsAnonymous, err = ts.AllowsAnonymousAccess(ctx)
require.NoError(t, err)
require.True(t, allowsAnonymous)
}
func TestCreateInstanceSettingIfNotExistsIsFirstWriterWins(t *testing.T) {
t.Parallel()
ctx := context.Background()
ts := NewTestingStore(ctx, t)
defer ts.Close()
const candidateCount = 16
type result struct {
value string
created bool
err error
}
start := make(chan struct{})
results := make(chan result, candidateCount)
for i := 0; i < candidateCount; i++ {
value := fmt.Sprintf("candidate-%02d", i)
go func() {
<-start
created, err := ts.GetDriver().CreateInstanceSettingIfNotExists(ctx, &store.InstanceSetting{
Name: "ATOMIC_CREATE_TEST",
Value: value,
})
results <- result{value: value, created: created, err: err}
}()
}
close(start)
winner := ""
for range candidateCount {
result := <-results
require.NoError(t, result.err)
if result.created {
require.Empty(t, winner, "only one concurrent insert may create the setting")
winner = result.value
}
}
require.NotEmpty(t, winner, "one concurrent insert must create the setting")
settings, err := ts.GetDriver().ListInstanceSettings(ctx, &store.FindInstanceSetting{Name: "ATOMIC_CREATE_TEST"})
require.NoError(t, err)
require.Len(t, settings, 1)
require.Equal(t, winner, settings[0].Value, "the database must retain the first inserted value")
created, err := ts.GetDriver().CreateInstanceSettingIfNotExists(ctx, &store.InstanceSetting{
Name: "ATOMIC_CREATE_TEST",
Value: "must-not-overwrite",
})
require.NoError(t, err)
require.False(t, created)
settings, err = ts.GetDriver().ListInstanceSettings(ctx, &store.FindInstanceSetting{Name: "ATOMIC_CREATE_TEST"})
require.NoError(t, err)
require.Len(t, settings, 1)
require.Equal(t, winner, settings[0].Value, "a later insert attempt must not overwrite the persisted value")
}
func TestInstanceSettingMemoRelatedSetting(t *testing.T) {
t.Parallel()
ctx := context.Background()

View file

@ -14,8 +14,21 @@ import (
"github.com/usememos/memos/internal/testutil/minio"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
storedb "github.com/usememos/memos/store/db"
)
type delayedInstanceSettingCreateDriver struct {
store.Driver
entered chan<- struct{}
release <-chan struct{}
}
func (d *delayedInstanceSettingCreateDriver) CreateInstanceSettingIfNotExists(ctx context.Context, create *store.InstanceSetting) (bool, error) {
d.entered <- struct{}{}
<-d.release
return d.Driver.CreateInstanceSettingIfNotExists(ctx, create)
}
// TestFreshInstall verifies that LATEST.sql applies correctly on a fresh database.
// This is essentially what NewTestingStore already does, but we make it explicit.
func TestFreshInstall(t *testing.T) {
@ -115,6 +128,76 @@ func TestMigrationMultipleReRuns(t *testing.T) {
require.Equal(t, initialVersion, finalVersion, "version should remain unchanged after multiple re-runs")
}
func TestConcurrentInstanceAccessInitializationKeepsFirstInsert(t *testing.T) {
ctx := context.Background()
driverName := getDriverFromEnv()
baseProfile := getTestingProfileForDriver(t, driverName)
baseDriver, err := storedb.NewDBDriver(baseProfile)
require.NoError(t, err)
baseStore := store.New(baseDriver, baseProfile)
require.NoError(t, baseStore.Migrate(ctx))
require.NoError(t, baseStore.DeleteInstanceSetting(ctx, &store.DeleteInstanceSetting{
Name: storepb.InstanceSettingKey_ACCESS.String(),
}))
require.NoError(t, baseStore.Close())
publicProfile := *baseProfile
publicProfile.InstanceURL = "https://public.example.com"
publicDriver, err := storedb.NewDBDriver(&publicProfile)
require.NoError(t, err)
entered := make(chan struct{}, 1)
release := make(chan struct{})
delayedPublicDriver := &delayedInstanceSettingCreateDriver{
Driver: publicDriver,
entered: entered,
release: release,
}
publicStore := store.New(delayedPublicDriver, &publicProfile)
defer publicStore.Close()
privateProfile := *baseProfile
privateProfile.InstanceURL = ""
privateDriver, err := storedb.NewDBDriver(&privateProfile)
require.NoError(t, err)
privateStore := store.New(privateDriver, &privateProfile)
defer privateStore.Close()
publicMigration := make(chan error, 1)
go func() {
publicMigration <- publicStore.Migrate(ctx)
}()
<-entered
released := false
defer func() {
if !released {
close(release)
}
}()
// The private instance reaches the database first. The delayed public
// initializer must lose the unique-key race without overwriting it.
require.NoError(t, privateStore.Migrate(ctx))
close(release)
released = true
require.NoError(t, <-publicMigration)
setting, err := privateStore.GetStoredInstanceSetting(ctx, &store.FindInstanceSetting{
Name: storepb.InstanceSettingKey_ACCESS.String(),
})
require.NoError(t, err)
require.NotNil(t, setting)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, setting.GetAccessSetting().AccessMode)
// 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{
Name: storepb.InstanceSettingKey_ACCESS.String(),
})
require.NoError(t, err)
require.Equal(t, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE, setting.GetAccessSetting().AccessMode)
}
// TestMigrationStorageSetting verifies that the legacy singleton storage
// configuration is expanded into a named storage without removing fields used
// by older clients and rollback versions.

View file

@ -2,6 +2,7 @@ import { ArrowRightIcon, CompassIcon } from "lucide-react";
import { Link } from "react-router-dom";
import { useInstance } from "@/contexts/InstanceContext";
import { ROUTES } from "@/router/routes";
import { InstanceAccessMode } from "@/types/proto/api/v1/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
import AuthFooter from "./AuthFooter";
@ -55,7 +56,7 @@ export const AuthOptionsLoading = () => <div className="h-9 w-full animate-pulse
const AuthPageLayout = ({ chip, title, subtitle, hideExplore, children }: Props) => {
const t = useTranslate();
const { generalSetting, profile } = useInstance();
const showExplore = Boolean(profile.instanceUrl) && !hideExplore;
const showExplore = profile.accessMode === InstanceAccessMode.PUBLIC && !hideExplore;
return (
<div className="min-h-svh w-full flex flex-col items-center px-4 py-4 sm:py-8">

View file

@ -10,6 +10,9 @@ import { useInstance } from "@/contexts/InstanceContext";
import useDialog from "@/hooks/useDialog";
import { IdentityProvider } from "@/types/proto/api/v1/idp_service_pb";
import {
InstanceAccessMode,
InstanceSetting_AccessSetting,
InstanceSetting_AccessSettingSchema,
InstanceSetting_GeneralSetting,
InstanceSetting_GeneralSettingSchema,
InstanceSetting_Key,
@ -26,13 +29,18 @@ const InstanceSection = () => {
const t = useTranslate();
const customizeDialog = useDialog();
const saveInstanceSetting = useInstanceSettingUpdater();
const { generalSetting: originalSetting, profile } = useInstance();
const [instanceGeneralSetting, setInstanceGeneralSetting] = useState<InstanceSetting_GeneralSetting>(originalSetting);
const { accessSetting: originalAccessSetting, generalSetting: originalGeneralSetting, profile } = useInstance();
const [instanceAccessSetting, setInstanceAccessSetting] = useState<InstanceSetting_AccessSetting>(originalAccessSetting);
const [instanceGeneralSetting, setInstanceGeneralSetting] = useState<InstanceSetting_GeneralSetting>(originalGeneralSetting);
const [identityProviderList, setIdentityProviderList] = useState<IdentityProvider[]>([]);
useEffect(() => {
setInstanceGeneralSetting(originalSetting);
}, [originalSetting]);
setInstanceAccessSetting(originalAccessSetting);
}, [originalAccessSetting]);
useEffect(() => {
setInstanceGeneralSetting(originalGeneralSetting);
}, [originalGeneralSetting]);
const fetchIdentityProviderList = async () => {
const { identityProviders } = await identityProviderServiceClient.listIdentityProviders({});
@ -61,20 +69,50 @@ const InstanceSection = () => {
);
};
const handleSaveGeneralSetting = async () => {
await saveInstanceSetting({
key: InstanceSetting_Key.GENERAL,
setting: create(InstanceSettingSchema, {
name: buildInstanceSettingName(InstanceSetting_Key.GENERAL),
value: {
case: "generalSetting",
value: instanceGeneralSetting,
},
}),
errorContext: "Update general settings",
});
const updateAccessMode = (accessMode: InstanceAccessMode) => {
setInstanceAccessSetting(create(InstanceSetting_AccessSettingSchema, { accessMode }));
};
const handleSaveSettings = async () => {
const generalSettingChanged = !isEqual(instanceGeneralSetting, originalGeneralSetting);
const accessSettingChanged = !isEqual(instanceAccessSetting, originalAccessSetting);
if (generalSettingChanged) {
const generalSettingSaved = await saveInstanceSetting({
key: InstanceSetting_Key.GENERAL,
setting: create(InstanceSettingSchema, {
name: buildInstanceSettingName(InstanceSetting_Key.GENERAL),
value: {
case: "generalSetting",
value: instanceGeneralSetting,
},
}),
errorContext: "Update general settings",
showSuccessToast: !accessSettingChanged,
});
if (!generalSettingSaved) {
return;
}
}
if (accessSettingChanged) {
await saveInstanceSetting({
key: InstanceSetting_Key.ACCESS,
setting: create(InstanceSettingSchema, {
name: buildInstanceSettingName(InstanceSetting_Key.ACCESS),
value: {
case: "accessSetting",
value: instanceAccessSetting,
},
}),
errorContext: "Update access settings",
});
}
};
const hasUnsavedChanges =
!isEqual(instanceGeneralSetting, originalGeneralSetting) || !isEqual(instanceAccessSetting, originalAccessSetting);
return (
<SettingSection title={t("setting.system.label")}>
<SettingGroup title={t("common.basic")} description={t("setting.system.basic-description")}>
@ -107,6 +145,17 @@ const InstanceSection = () => {
<SettingGroup title={t("setting.instance.access-title")} description={t("setting.instance.access-description")} showSeparator>
<SettingList>
<SettingListItem
label={t("setting.instance.allow-public-access")}
description={t("setting.instance.allow-public-access-description")}
>
<Switch
disabled={profile.demo}
checked={instanceAccessSetting.accessMode === InstanceAccessMode.PUBLIC}
onCheckedChange={(checked) => updateAccessMode(checked ? InstanceAccessMode.PUBLIC : InstanceAccessMode.PRIVATE)}
/>
</SettingListItem>
<SettingListItem
label={t("setting.instance.disallow-user-registration")}
description={t("setting.instance.disallow-user-registration-description")}
@ -173,7 +222,7 @@ const InstanceSection = () => {
</SettingGroup>
<div className="w-full flex justify-end">
<Button disabled={isEqual(instanceGeneralSetting, originalSetting)} onClick={handleSaveGeneralSetting}>
<Button disabled={!hasUnsavedChanges} onClick={handleSaveSettings}>
{t("common.save")}
</Button>
</div>

View file

@ -9,6 +9,7 @@ interface SaveInstanceSettingOptions {
key: InstanceSetting_Key;
setting: InstanceSetting;
errorContext: string;
showSuccessToast?: boolean;
}
export const buildInstanceSettingName = (key: InstanceSetting_Key) => `instance/settings/${InstanceSetting_Key[key]}`;
@ -18,11 +19,17 @@ const useInstanceSettingUpdater = () => {
const { updateSetting, fetchSetting } = useInstance();
return useCallback(
async ({ key, setting, errorContext }: SaveInstanceSettingOptions) => {
async ({ key, setting, errorContext, showSuccessToast = true }: SaveInstanceSettingOptions) => {
try {
await updateSetting(setting);
await fetchSetting(key);
toast.success(t("message.update-succeed"));
// ACCESS is updated in the React Query cache from the mutation response.
// Refetching it here would duplicate the request after every save.
if (key !== InstanceSetting_Key.ACCESS) {
await fetchSetting(key);
}
if (showSuccessToast) {
toast.success(t("message.update-succeed"));
}
return true;
} catch (error: unknown) {
await handleError(error, toast.error, { context: errorContext });

View file

@ -1,10 +1,13 @@
import { create } from "@bufbuild/protobuf";
import { createContext, type ReactNode, useCallback, useContext, useMemo, useRef, useState } from "react";
import { instanceServiceClient } from "@/connect";
import { useAccessSetting, useUpdateInstanceSetting } from "@/hooks/useInstanceQueries";
import {
InstanceProfile,
InstanceProfileSchema,
InstanceSetting,
InstanceSetting_AccessSetting,
InstanceSetting_AccessSettingSchema,
InstanceSetting_AISetting,
InstanceSetting_AISettingSchema,
InstanceSetting_GeneralSetting,
@ -40,6 +43,7 @@ interface InstanceState {
}
interface InstanceContextValue extends InstanceState {
accessSetting: InstanceSetting_AccessSetting;
generalSetting: InstanceSetting_GeneralSetting;
memoRelatedSetting: InstanceSetting_MemoRelatedSetting;
storageSetting: InstanceSetting_StorageSetting;
@ -64,8 +68,17 @@ export function InstanceProvider({ children }: { children: ReactNode }) {
});
const fetchedSettingsRef = useRef<Set<string>>(new Set());
const { data: queriedAccessSetting } = useAccessSetting();
const { mutateAsync: updateAccessSetting } = useUpdateInstanceSetting();
// Memoize derived settings to prevent unnecessary recalculations
const accessSetting = useMemo((): InstanceSetting_AccessSetting => {
if (queriedAccessSetting) {
return queriedAccessSetting;
}
return create(InstanceSetting_AccessSettingSchema, { accessMode: state.profile.accessMode });
}, [queriedAccessSetting, state.profile.accessMode]);
const generalSetting = useMemo((): InstanceSetting_GeneralSetting => {
const setting = state.settings.find((s) => s.name === `${instanceSettingNamePrefix}GENERAL`);
if (setting?.value.case === "generalSetting") {
@ -153,7 +166,10 @@ export function InstanceProvider({ children }: { children: ReactNode }) {
}, []);
const fetchSettings = useCallback(async (keys: InstanceSetting_Key[]) => {
const names = keys.map(buildInstanceSettingName).filter((name) => !fetchedSettingsRef.current.has(name));
const names = keys
.filter((key) => key !== InstanceSetting_Key.ACCESS)
.map(buildInstanceSettingName)
.filter((name) => !fetchedSettingsRef.current.has(name));
if (names.length === 0) {
return;
}
@ -178,6 +194,11 @@ export function InstanceProvider({ children }: { children: ReactNode }) {
}, []);
const fetchSetting = useCallback(async (key: InstanceSetting_Key) => {
// ACCESS is always fetched and cached by useAccessSetting.
if (key === InstanceSetting_Key.ACCESS) {
return;
}
const name = buildInstanceSettingName(key);
if (fetchedSettingsRef.current.has(name)) {
return;
@ -195,18 +216,32 @@ export function InstanceProvider({ children }: { children: ReactNode }) {
}
}, []);
const updateSetting = useCallback(async (setting: InstanceSetting) => {
const updatedSetting = await instanceServiceClient.updateInstanceSetting({ setting });
setState((prev) => ({
...prev,
settings: [...prev.settings.filter((s) => s.name !== updatedSetting.name), updatedSetting],
}));
}, []);
const updateSetting = useCallback(
async (setting: InstanceSetting) => {
const isAccessSetting = setting.value.case === "accessSetting";
const updatedSetting = isAccessSetting
? await updateAccessSetting(setting)
: await instanceServiceClient.updateInstanceSetting({ setting });
setState((prev) => ({
...prev,
profile:
updatedSetting.value.case === "accessSetting"
? {
...prev.profile,
accessMode: updatedSetting.value.value.accessMode,
}
: prev.profile,
settings: isAccessSetting ? prev.settings : [...prev.settings.filter((s) => s.name !== updatedSetting.name), updatedSetting],
}));
},
[updateAccessSetting],
);
// Memoize context value to prevent unnecessary re-renders of consumers
const value = useMemo(
() => ({
...state,
accessSetting,
generalSetting,
memoRelatedSetting,
storageSetting,
@ -219,6 +254,7 @@ export function InstanceProvider({ children }: { children: ReactNode }) {
}),
[
state,
accessSetting,
generalSetting,
memoRelatedSetting,
storageSetting,

View file

@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { instanceServiceClient } from "@/connect";
import { InstanceSetting, InstanceSetting_Key } from "@/types/proto/api/v1/instance_service_pb";
import { InstanceSetting, InstanceSetting_AccessSetting, InstanceSetting_Key } from "@/types/proto/api/v1/instance_service_pb";
// Query keys factory
export const instanceKeys = {
@ -72,26 +72,36 @@ export function useUpdateInstanceSetting() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (setting: InstanceSetting) => {
await instanceServiceClient.updateInstanceSetting({ setting });
return setting;
},
onSuccess: (setting) => {
// Extract key from setting name and invalidate
mutationFn: async (setting: InstanceSetting) => instanceServiceClient.updateInstanceSetting({ setting }),
onSuccess: async (setting) => {
// Update the exact setting cache from the server response. Batch caches
// are marked stale without refetching so an active setting query does not
// issue a duplicate request immediately after a successful mutation.
const keyMatch = setting.name.match(/instance\/settings\/(\w+)/);
if (keyMatch) {
const keyName = keyMatch[1] as keyof typeof InstanceSetting_Key;
const key = InstanceSetting_Key[keyName];
if (key !== undefined) {
await queryClient.cancelQueries({ queryKey: instanceKeys.setting(key), exact: true });
queryClient.setQueryData(instanceKeys.setting(key), setting);
}
}
queryClient.invalidateQueries({ queryKey: instanceKeys.settings() });
void queryClient.invalidateQueries({
predicate: (query) => query.queryKey[0] === "instance" && query.queryKey[1] === "settings" && query.queryKey[2] === "batch",
refetchType: "none",
});
},
});
}
// Derived hooks for common settings
export function useAccessSetting() {
const { data: setting, ...rest } = useInstanceSetting(InstanceSetting_Key.ACCESS);
const accessSetting: InstanceSetting_AccessSetting | undefined =
setting?.value.case === "accessSetting" ? setting.value.value : undefined;
return { data: accessSetting, ...rest };
}
export function useGeneralSetting() {
const { data: setting, ...rest } = useInstanceSetting(InstanceSetting_Key.GENERAL);
const generalSetting = setting?.value.case === "generalSetting" ? setting.value.value : undefined;

View file

@ -15,6 +15,7 @@ import { useInstance } from "@/contexts/InstanceContext";
import { MemoFilterProvider, useMemoFilterContext } from "@/contexts/MemoFilterContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import useMediaQuery from "@/hooks/useMediaQuery";
import { InstanceAccessMode } from "@/types/proto/api/v1/instance_service_pb";
import { buildAuthRoute, shouldGatePrivateInstance } from "@/utils/auth-redirect";
import { useTranslate } from "@/utils/i18n";
@ -59,10 +60,15 @@ const RootLayoutContent = () => {
prevPathnameRef.current = pathname;
}, [pathname, searchParams, removeFilter]);
// Private instance (no InstanceURL configured): anonymous visitors may only reach
// share links; everything else redirects to the sign-in page, preserving the intended
// destination. Public instances keep the open Explore behavior for logged-out users.
if (shouldGatePrivateInstance({ isPrivateInstance: !profile.instanceUrl, isAuthenticated: !!currentUser, pathname })) {
// Anonymous visitors to private instances may only reach share links. Treat an
// unspecified mode as private so a partial or older response cannot expose content.
if (
shouldGatePrivateInstance({
isPrivateInstance: profile.accessMode !== InstanceAccessMode.PUBLIC,
isAuthenticated: !!currentUser,
pathname,
})
) {
const redirect = `${pathname}${location.search}${location.hash}`;
return <Navigate to={buildAuthRoute({ redirect })} replace />;
}

View file

@ -382,6 +382,8 @@
"delete-account-description": "Permanently remove this account and all associated access from this instance. This action cannot be undone."
},
"instance": {
"allow-public-access": "Allow public access",
"allow-public-access-description": "Allow signed-out visitors to browse public memos. Shared memo links remain available when this is disabled.",
"disallow-change-nickname": "Disallow changing nickname",
"disallow-change-username": "Disallow changing username",
"disallow-password-auth": "Disallow password auth",
@ -390,7 +392,7 @@
"saturday": "Saturday",
"sunday": "Sunday",
"week-start-day": "Week start day",
"access-description": "Control sign-up, authentication, profile editing, and calendar defaults for this instance.",
"access-description": "Control anonymous browsing, sign-up, authentication, profile editing, and calendar defaults for this instance.",
"access-title": "Access and policies",
"disallow-change-nickname-description": "Prevent users from changing their display name.",
"disallow-change-username-description": "Prevent users from changing their login username.",

View file

@ -604,8 +604,10 @@
"transcription-warning-no-key": "The selected provider has no API key set. Edit the integration above to add one."
},
"instance": {
"access-description": "Control sign-up, authentication, profile editing, and calendar defaults for this instance.",
"access-description": "Control anonymous browsing, sign-up, authentication, profile editing, and calendar defaults for this instance.",
"access-title": "Access and policies",
"allow-public-access-description": "Allow signed-out visitors to browse public memos. Shared memo links remain available when this is disabled.",
"allow-public-access": "Allow public access",
"disallow-change-nickname-description": "Prevent users from changing their display name.",
"disallow-change-nickname": "Disallow changing nickname",
"disallow-change-username-description": "Prevent users from changing their login username.",

File diff suppressed because one or more lines are too long

View file

@ -2,8 +2,9 @@ import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import AuthPageLayout from "@/components/AuthPageLayout";
import { InstanceAccessMode } from "@/types/proto/api/v1/instance_service_pb";
const instance = vi.hoisted(() => ({ instanceUrl: "" }));
const instance = vi.hoisted(() => ({ instanceUrl: "https://notes.example.com", accessMode: 1 }));
vi.mock("@/contexts/InstanceContext", () => ({
useInstance: () => ({ profile: instance, generalSetting: {} }),
@ -27,24 +28,24 @@ const renderLayout = (props?: { hideExplore?: boolean }) =>
describe("<AuthPageLayout> explore band", () => {
beforeEach(() => {
instance.instanceUrl = "";
instance.accessMode = InstanceAccessMode.PRIVATE;
});
it("links to Explore on public instances", () => {
instance.instanceUrl = "https://demo.example.com";
instance.accessMode = InstanceAccessMode.PUBLIC;
renderLayout();
expect(screen.getByRole("link", { name: /auth\.explore-public-memos/ })).toHaveAttribute("href", "/explore");
});
it("omits the band on private instances", () => {
it("omits the band on private instances even when an instance URL is configured", () => {
renderLayout();
expect(screen.queryByRole("link", { name: /auth\.explore-public-memos/ })).not.toBeInTheDocument();
});
it("omits the band when hideExplore is set (first-run setup)", () => {
instance.instanceUrl = "https://demo.example.com";
instance.accessMode = InstanceAccessMode.PUBLIC;
renderLayout({ hideExplore: true });
expect(screen.queryByRole("link", { name: /auth\.explore-public-memos/ })).not.toBeInTheDocument();

View file

@ -0,0 +1,125 @@
import { create } from "@bufbuild/protobuf";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, fireEvent, render, renderHook, screen, waitFor } from "@testing-library/react";
import type { PropsWithChildren } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { InstanceProvider, useInstance } from "@/contexts/InstanceContext";
import { instanceKeys, useAccessSetting, useUpdateInstanceSetting } from "@/hooks/useInstanceQueries";
import {
InstanceAccessMode,
InstanceProfileSchema,
InstanceSetting_AccessSettingSchema,
InstanceSetting_Key,
InstanceSettingSchema,
} from "@/types/proto/api/v1/instance_service_pb";
const clients = vi.hoisted(() => ({
batchGetInstanceSettings: vi.fn(),
getInstanceProfile: vi.fn(),
getInstanceSetting: vi.fn(),
updateInstanceSetting: vi.fn(),
}));
vi.mock("@/connect", () => ({
instanceServiceClient: clients,
}));
const buildAccessSetting = (accessMode: InstanceAccessMode) =>
create(InstanceSettingSchema, {
name: "instance/settings/ACCESS",
value: {
case: "accessSetting",
value: create(InstanceSetting_AccessSettingSchema, { accessMode }),
},
});
const createQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
const createWrapper = (queryClient: QueryClient) =>
function QueryWrapper({ children }: PropsWithChildren) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
};
const InstanceProbe = () => {
const { accessSetting, initialize, profile, updateSetting } = useInstance();
return (
<div>
<output data-testid="profile-access">{profile.accessMode}</output>
<output data-testid="setting-access">{accessSetting.accessMode}</output>
<button type="button" onClick={() => void initialize()}>
Initialize
</button>
<button type="button" onClick={() => void updateSetting(buildAccessSetting(InstanceAccessMode.PUBLIC))}>
Make public
</button>
</div>
);
};
describe("instance ACCESS React Query integration", () => {
beforeEach(() => {
clients.batchGetInstanceSettings.mockReset().mockResolvedValue({ settings: [] });
clients.getInstanceProfile.mockReset().mockResolvedValue(create(InstanceProfileSchema, { accessMode: InstanceAccessMode.PRIVATE }));
clients.getInstanceSetting.mockReset().mockResolvedValue(buildAccessSetting(InstanceAccessMode.PRIVATE));
clients.updateInstanceSetting.mockReset().mockResolvedValue(buildAccessSetting(InstanceAccessMode.PUBLIC));
});
it("updates the exact ACCESS cache from the mutation response without refetching", async () => {
const queryClient = createQueryClient();
const { result } = renderHook(
() => ({
access: useAccessSetting(),
update: useUpdateInstanceSetting(),
}),
{ wrapper: createWrapper(queryClient) },
);
await waitFor(() => expect(result.current.access.data?.accessMode).toBe(InstanceAccessMode.PRIVATE));
await act(async () => {
await result.current.update.mutateAsync(buildAccessSetting(InstanceAccessMode.PUBLIC));
});
await waitFor(() => expect(result.current.access.data?.accessMode).toBe(InstanceAccessMode.PUBLIC));
expect(clients.getInstanceSetting).toHaveBeenCalledTimes(1);
expect(clients.updateInstanceSetting).toHaveBeenCalledTimes(1);
expect(queryClient.getQueryData(instanceKeys.setting(InstanceSetting_Key.ACCESS))).toEqual(
buildAccessSetting(InstanceAccessMode.PUBLIC),
);
});
it("keeps ACCESS out of context settings state and synchronizes the routing profile after update", async () => {
const queryClient = createQueryClient();
render(
<QueryClientProvider client={queryClient}>
<InstanceProvider>
<InstanceProbe />
</InstanceProvider>
</QueryClientProvider>,
);
// Until either request settles, both values remain UNSPECIFIED, which the
// routing layer treats as private.
expect(screen.getByTestId("profile-access")).toHaveTextContent(String(InstanceAccessMode.UNSPECIFIED));
expect(screen.getByTestId("setting-access")).toHaveTextContent(String(InstanceAccessMode.UNSPECIFIED));
fireEvent.click(screen.getByRole("button", { name: "Initialize" }));
await waitFor(() => expect(screen.getByTestId("profile-access")).toHaveTextContent(String(InstanceAccessMode.PRIVATE)));
await waitFor(() => expect(screen.getByTestId("setting-access")).toHaveTextContent(String(InstanceAccessMode.PRIVATE)));
expect(clients.batchGetInstanceSettings).toHaveBeenCalledWith({
names: ["instance/settings/GENERAL", "instance/settings/MEMO_RELATED"],
});
fireEvent.click(screen.getByRole("button", { name: "Make public" }));
await waitFor(() => expect(screen.getByTestId("profile-access")).toHaveTextContent(String(InstanceAccessMode.PUBLIC)));
expect(screen.getByTestId("setting-access")).toHaveTextContent(String(InstanceAccessMode.PUBLIC));
expect(clients.getInstanceSetting).toHaveBeenCalledTimes(1);
});
});

View file

@ -0,0 +1,61 @@
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/v1/instance_service_pb";
const instance = vi.hoisted(() => ({
accessSetting: { accessMode: 1 },
generalSetting: {
additionalScript: "",
additionalStyle: "",
customProfile: undefined,
disallowChangeNickname: false,
disallowChangeUsername: false,
disallowPasswordAuth: false,
disallowUserRegistration: false,
weekStartDayOffset: 0,
},
profile: { demo: false },
fetchSetting: vi.fn(),
updateSetting: vi.fn(),
}));
const listIdentityProviders = vi.hoisted(() => vi.fn());
vi.mock("@/contexts/InstanceContext", () => ({
useInstance: () => instance,
}));
vi.mock("@/connect", () => ({
identityProviderServiceClient: {
listIdentityProviders,
},
}));
vi.mock("@/components/UpdateCustomizedProfileDialog", () => ({ default: () => null }));
vi.mock("@/utils/i18n", () => ({
useTranslate: () => (key: string) => key,
}));
describe("<InstanceSection> access setting", () => {
beforeEach(() => {
instance.accessSetting.accessMode = InstanceAccessMode.PRIVATE;
listIdentityProviders.mockResolvedValue({ identityProviders: [] });
instance.fetchSetting.mockReset().mockResolvedValue(undefined);
instance.updateSetting.mockReset().mockResolvedValue(undefined);
});
it("saves public access through the dedicated ACCESS setting", async () => {
render(<InstanceSection />);
fireEvent.click(screen.getAllByRole("switch")[0]);
fireEvent.click(screen.getByRole("button", { name: "common.save" }));
await waitFor(() => expect(instance.updateSetting).toHaveBeenCalledTimes(1));
const setting = instance.updateSetting.mock.calls[0][0];
expect(setting.name).toBe("instance/settings/ACCESS");
expect(setting.value.case).toBe("accessSetting");
expect(setting.value.value.accessMode).toBe(InstanceAccessMode.PUBLIC);
expect(instance.fetchSetting).not.toHaveBeenCalled();
});
});

View file

@ -1,8 +1,11 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import { describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import RootLayout from "@/layouts/RootLayout";
const authState = vi.hoisted(() => ({ currentUser: { name: "users/test" } as { name: string } | undefined }));
const instanceState = vi.hoisted(() => ({ accessMode: 2, instanceUrl: "https://example.com", demo: true }));
vi.mock("@/components/AppSidebar", () => ({
default: () => <aside data-testid="desktop-sidebar">Desktop sidebar</aside>,
MobileAppHeader: () => <header data-testid="mobile-header">Mobile header</header>,
@ -21,11 +24,11 @@ vi.mock("@/contexts/AuthContext", () => ({
}));
vi.mock("@/contexts/InstanceContext", () => ({
useInstance: () => ({ profile: { instanceUrl: "https://example.com", demo: true } }),
useInstance: () => ({ profile: instanceState }),
}));
vi.mock("@/hooks/useCurrentUser", () => ({
default: () => ({ name: "users/test" }),
default: () => authState.currentUser,
}));
vi.mock("@/hooks/useMediaQuery", () => ({
@ -52,6 +55,11 @@ const RouteState = () => {
};
describe("RootLayout global editor shell", () => {
beforeEach(() => {
authState.currentUser = { name: "users/test" };
instanceState.accessMode = 2;
});
it("mounts the composer provider inside the sidebar provider and keeps the shell across routes", () => {
render(
<MemoryRouter initialEntries={["/attachments"]}>
@ -77,4 +85,22 @@ describe("RootLayout global editor shell", () => {
expect(screen.getByTestId(testId)).toBeInTheDocument();
}
});
it("gates anonymous visitors by access mode even when an instance URL is configured", () => {
authState.currentUser = undefined;
instanceState.accessMode = 1;
render(
<MemoryRouter initialEntries={["/explore"]}>
<Routes>
<Route element={<RootLayout />}>
<Route path="explore" element={<div>Explore</div>} />
</Route>
<Route path="auth" element={<RouteState />} />
</Routes>
</MemoryRouter>,
);
expect(screen.getByTestId("route")).toHaveTextContent("/auth");
});
});

View file

@ -16,7 +16,7 @@ const state = vi.hoisted(() => ({
vi.mock("@/contexts/InstanceContext", () => ({
useInstance: () => ({
generalSetting: state.generalSetting,
profile: { instanceUrl: "" },
profile: { accessMode: 1 },
}),
}));