Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions internal/panel/backup/validate_vault.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ var restoredSealedValueQueries = []sealedValueQuery{
// telegram_bot.token is sealed with tokenRecordID; see telegram.rpc.SetTelegramBot in telegram/rpc.go.
{description: "Telegram bot token", table: "telegram_bot", columns: []string{"token"},
query: "SELECT token, 'telegram_bot.token' FROM telegram_bot WHERE length(token) > 0"},
// user_telegram_bot.token is sealed with userTokenRecordID; see telegram.rpc.SetUserBot in telegram/user_rpc.go.
{description: "Telegram bot token of the people", table: "user_telegram_bot", columns: []string{"token"},
query: "SELECT token, 'user_telegram_bot.token' FROM user_telegram_bot WHERE length(token) > 0"},
// user_telegram_chat.chat_enc is sealed to the chat's own MAC (the row id is born inside the store insert); see
// telegram.Service.linkUserChat and chatRecordID in telegram/user_bot.go. The hex is lower case, as Go prints it.
{description: "Telegram chat of a person", table: "user_telegram_chat", columns: []string{"chat_enc", "chat_mac"}, aadParts: 1,
aadFrom: func(parts ...string) string { return "user_telegram_chat:" + parts[0] },
query: "SELECT chat_enc, lower(hex(chat_mac)) FROM user_telegram_chat WHERE length(chat_enc) > 0"},
// auth_ceremony.totp_enc uses auth.AuthCeremonyTOTPRecordID; see auth.Service.ceremonyRow in auth/service.go.
{description: "auth ceremony TOTP", table: "auth_ceremony", columns: []string{"totp_enc", "id"}, aadParts: 1,
aadFrom: func(parts ...string) string { return auth.AuthCeremonyTOTPRecordID(parts[0]) },
Expand Down
126 changes: 126 additions & 0 deletions internal/panel/store/migrations/00165_user_notify.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
-- Notifications to people (store/user_telegram.go, store/user_notice.go). A person's subscription gets news through two channels:
-- Telegram (a bot of its own, not the admins' one) and the Mistgate app (pulled with its sync). The outbox user_notice feeds both.
--
-- Secrets: the bot token is vault ciphertext; a chat id is never stored in the clear. chat_enc is the sealed id (to send), chat_mac
-- is its keyed MAC (to find a chat from an update, and to keep one chat from belonging to two people). A chat belongs to a bot:
-- replacing or clearing the bot deletes every chat, every pending link code and the Telegram channel of unfinished notices.
--
-- user_notice is an outbox with at-least-once delivery. A row is unfinished while done_at = 0 and finished when it has a result
-- (the CHECK keeps the two in step). Rules that are not obvious from the columns:
-- * dedupe is unique for the life of the row: a producer inserts its event again and again, the second insert is a no-op, and a
-- row that finished keeps the event from coming back until retention purges it.
-- * approval is '' (no approval needed), pending (a draft waits for the owner), approved, dismissed or expired. A pending row is
-- never leased. dismissed and expired rows are finished at once (done_at and the same result), so retention removes them.
-- * draft_id groups the rows of one owner's draft: a failure draft is one per incident, the rows are one per person, and
-- approving, dismissing or expiring the draft touches them all. NULL = the row is its own draft.
-- * incident_id and draft_id are NULL when absent (a partial index covers only the rows that have one), never ''.
-- * a worker leases a row (lease_id, lease_until) and may finish or retry it only while it still holds that lease id; a lease
-- that ran out is taken again, so a crash costs a repeat, not a loss.
-- * channels is a bit mask, Telegram = 1, app = 2; the app pulls its events, so it has no retries. tg_sent counts the chats that
-- got the message, app_taken_count counts the devices that pulled it (written by the sync, never by the sender).
-- * tg_message_refs is a JSON object user_telegram_chat.id -> message id (the row id, never a Telegram chat id), kept to edit
-- an incident message and to not send twice on a retry.
--
-- user_incident is a service failure of one person (every server of the subscription down). A person has at most one open
-- incident, which the partial unique index enforces. No foreign key on notice_id: the notice is purged earlier than the incident.
--
-- Default values of the settings live in the code: a key with no row means its default, so this migration writes none.

-- +goose Up
CREATE TABLE user_telegram_bot (
id INTEGER PRIMARY KEY CHECK (id = 1),
token BLOB NOT NULL, -- vault ciphertext, record "user_telegram_bot.token"; never returned by an RPC
bot_id INTEGER NOT NULL, -- from getMe: tells a new bot from the same one pasted again
username TEXT NOT NULL,
updated_at INTEGER NOT NULL,
poll_offset INTEGER NOT NULL DEFAULT 0, -- next getUpdates offset
last_error TEXT NOT NULL DEFAULT '', -- code of the last failure, for the bot card; never a message text
last_ok INTEGER NOT NULL DEFAULT 0 -- last successful call to the Bot API
) STRICT;

CREATE TABLE user_telegram_chat (
id TEXT PRIMARY KEY, -- utc_...
user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
chat_mac BLOB NOT NULL UNIQUE, -- keyed MAC of the chat id: one chat belongs to one person
chat_enc BLOB NOT NULL, -- vault ciphertext of the chat id, AAD user_telegram_chat:<hex of chat_mac>
lang TEXT NOT NULL, -- language of the messages to this chat
muted INTEGER NOT NULL DEFAULT 0 CHECK (muted IN (0, 1)), -- announcements off
linked_at INTEGER NOT NULL,
last_sent_at INTEGER NOT NULL DEFAULT 0
) STRICT;
-- The chats of a person, oldest first, and how many there are.
CREATE INDEX user_telegram_chat_user ON user_telegram_chat (user_id, linked_at);

CREATE TABLE user_telegram_code (
hash TEXT PRIMARY KEY CHECK (length(hash) = 64), -- sha256 of the code, hex
user_id TEXT NOT NULL UNIQUE REFERENCES user (id) ON DELETE CASCADE, -- one pending code per person
expires_at INTEGER NOT NULL
) STRICT;
CREATE INDEX user_telegram_code_expiry ON user_telegram_code (expires_at);

CREATE TABLE user_notice (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
kind TEXT NOT NULL,
dedupe TEXT NOT NULL UNIQUE,
params_json TEXT NOT NULL,
loud INTEGER NOT NULL CHECK (loud IN (0, 1)),
channels INTEGER NOT NULL CHECK (channels BETWEEN 1 AND 3),
created_at INTEGER NOT NULL,
due_at INTEGER NOT NULL,
draft_id TEXT,
approval TEXT NOT NULL DEFAULT '' CHECK (approval IN ('', 'pending', 'approved', 'dismissed', 'expired')),
approval_text TEXT NOT NULL DEFAULT '', -- the owner's own text ("edit"), '' = the rendered one
lease_id TEXT NOT NULL DEFAULT '',
lease_until INTEGER NOT NULL DEFAULT 0,
attempts INTEGER NOT NULL DEFAULT 0,
done_at INTEGER NOT NULL DEFAULT 0,
result TEXT NOT NULL DEFAULT '' CHECK (result IN ('', 'sent', 'dropped', 'unlinked', 'skipped_stale', 'dismissed', 'expired')),
tg_sent INTEGER NOT NULL DEFAULT 0,
app_taken_count INTEGER NOT NULL DEFAULT 0,
incident_id TEXT,
tg_message_refs TEXT NOT NULL DEFAULT '{}',
CHECK ((done_at = 0) = (result = ''))
) STRICT;
-- The sender's queue: unfinished rows by due time (the lease and the approval are filtered per row, they are few).
CREATE INDEX user_notice_due ON user_notice (due_at, id) WHERE done_at = 0;
-- The retention purge reads finished rows only.
CREATE INDEX user_notice_done ON user_notice (done_at) WHERE done_at > 0;
-- Drafts that wait: the expiry scan, and an approval of the whole draft.
CREATE INDEX user_notice_pending ON user_notice (created_at) WHERE approval = 'pending';
CREATE INDEX user_notice_draft ON user_notice (draft_id) WHERE draft_id IS NOT NULL;
-- The events a person's app pulls and the history of the person's page.
CREATE INDEX user_notice_user ON user_notice (user_id, created_at);

CREATE TABLE user_incident (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
opened_at INTEGER NOT NULL,
resolved_at INTEGER NOT NULL DEFAULT 0, -- 0 = still open
nodes_json TEXT NOT NULL, -- ids of the nodes that went down
notice_id TEXT -- the notice that carries the incident message; NULL until it exists
) STRICT;
CREATE UNIQUE INDEX user_incident_open ON user_incident (user_id) WHERE resolved_at = 0;
-- The anti-storm rule asks when a person's last incident began.
CREATE INDEX user_incident_user ON user_incident (user_id, opened_at);

CREATE TABLE user_notify_setting (
key TEXT PRIMARY KEY,
value_json TEXT NOT NULL
) STRICT;

CREATE TABLE user_notify_override (
user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
key TEXT NOT NULL,
value_json TEXT NOT NULL,
PRIMARY KEY (user_id, key)
) STRICT, WITHOUT ROWID;

-- +goose Down
DROP TABLE user_notify_override;
DROP TABLE user_notify_setting;
DROP TABLE user_incident;
DROP TABLE user_notice;
DROP TABLE user_telegram_code;
DROP TABLE user_telegram_chat;
DROP TABLE user_telegram_bot;
81 changes: 79 additions & 2 deletions internal/panel/store/schema_snapshot.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
-- Schema and data of a new, fully migrated panel database.
-- goose version 164
-- goose version 165
-- Generated by `go test ./internal/panel/store -run '^TestSchemaSnapshot$' -update`; do not edit by hand.
PRAGMA defer_foreign_keys = ON;
CREATE TABLE admin (
Expand Down Expand Up @@ -1162,6 +1162,14 @@ CREATE TABLE user_group_profile (
profile_id TEXT NOT NULL REFERENCES profile (id) ON DELETE CASCADE,
PRIMARY KEY (group_id, profile_id)
) STRICT, WITHOUT ROWID;
CREATE TABLE user_incident (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
opened_at INTEGER NOT NULL,
resolved_at INTEGER NOT NULL DEFAULT 0, -- 0 = still open
nodes_json TEXT NOT NULL, -- ids of the nodes that went down
notice_id TEXT -- the notice that carries the incident message; NULL until it exists
) STRICT;
CREATE TABLE user_link_dns (
user_id TEXT NOT NULL PRIMARY KEY REFERENCES user (id) ON DELETE CASCADE,
preset_id TEXT NOT NULL REFERENCES dns_preset (id) ON DELETE CASCADE,
Expand All @@ -1186,6 +1194,65 @@ CREATE TABLE user_node_dns (
updated_at INTEGER NOT NULL,
PRIMARY KEY (user_id, node_id)
) STRICT;
CREATE TABLE user_notice (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
kind TEXT NOT NULL,
dedupe TEXT NOT NULL UNIQUE,
params_json TEXT NOT NULL,
loud INTEGER NOT NULL CHECK (loud IN (0, 1)),
channels INTEGER NOT NULL CHECK (channels BETWEEN 1 AND 3),
created_at INTEGER NOT NULL,
due_at INTEGER NOT NULL,
draft_id TEXT,
approval TEXT NOT NULL DEFAULT '' CHECK (approval IN ('', 'pending', 'approved', 'dismissed', 'expired')),
approval_text TEXT NOT NULL DEFAULT '', -- the owner's own text ("edit"), '' = the rendered one
lease_id TEXT NOT NULL DEFAULT '',
lease_until INTEGER NOT NULL DEFAULT 0,
attempts INTEGER NOT NULL DEFAULT 0,
done_at INTEGER NOT NULL DEFAULT 0,
result TEXT NOT NULL DEFAULT '' CHECK (result IN ('', 'sent', 'dropped', 'unlinked', 'skipped_stale', 'dismissed', 'expired')),
tg_sent INTEGER NOT NULL DEFAULT 0,
app_taken_count INTEGER NOT NULL DEFAULT 0,
incident_id TEXT,
tg_message_refs TEXT NOT NULL DEFAULT '{}',
CHECK ((done_at = 0) = (result = ''))
) STRICT;
CREATE TABLE user_notify_override (
user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
key TEXT NOT NULL,
value_json TEXT NOT NULL,
PRIMARY KEY (user_id, key)
) STRICT, WITHOUT ROWID;
CREATE TABLE user_notify_setting (
key TEXT PRIMARY KEY,
value_json TEXT NOT NULL
) STRICT;
CREATE TABLE user_telegram_bot (
id INTEGER PRIMARY KEY CHECK (id = 1),
token BLOB NOT NULL, -- vault ciphertext, record "user_telegram_bot.token"; never returned by an RPC
bot_id INTEGER NOT NULL, -- from getMe: tells a new bot from the same one pasted again
username TEXT NOT NULL,
updated_at INTEGER NOT NULL,
poll_offset INTEGER NOT NULL DEFAULT 0, -- next getUpdates offset
last_error TEXT NOT NULL DEFAULT '', -- code of the last failure, for the bot card; never a message text
last_ok INTEGER NOT NULL DEFAULT 0 -- last successful call to the Bot API
) STRICT;
CREATE TABLE user_telegram_chat (
id TEXT PRIMARY KEY, -- utc_...
user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
chat_mac BLOB NOT NULL UNIQUE, -- keyed MAC of the chat id: one chat belongs to one person
chat_enc BLOB NOT NULL, -- vault ciphertext of the chat id, AAD user_telegram_chat:<hex of chat_mac>
lang TEXT NOT NULL, -- language of the messages to this chat
muted INTEGER NOT NULL DEFAULT 0 CHECK (muted IN (0, 1)), -- announcements off
linked_at INTEGER NOT NULL,
last_sent_at INTEGER NOT NULL DEFAULT 0
) STRICT;
CREATE TABLE user_telegram_code (
hash TEXT PRIMARY KEY CHECK (length(hash) = 64), -- sha256 of the code, hex
user_id TEXT NOT NULL UNIQUE REFERENCES user (id) ON DELETE CASCADE, -- one pending code per person
expires_at INTEGER NOT NULL
) STRICT;
CREATE TABLE warp_account ( -- at most one per node
node_id TEXT PRIMARY KEY REFERENCES node (id) ON DELETE CASCADE,
source TEXT NOT NULL CHECK (source IN ('registered', 'imported')),
Expand Down Expand Up @@ -1320,11 +1387,20 @@ CREATE INDEX user_by_group ON user (group_id, name COLLATE NOCASE);
CREATE INDEX user_expires ON user (expires_at) WHERE expires_at IS NOT NULL;
CREATE INDEX user_extra_group_by_group ON user_extra_group (group_id);
CREATE INDEX user_group_profile_profile ON user_group_profile (profile_id);
CREATE UNIQUE INDEX user_incident_open ON user_incident (user_id) WHERE resolved_at = 0;
CREATE INDEX user_incident_user ON user_incident (user_id, opened_at);
CREATE INDEX user_network_last_hour ON user_network (last_hour);
CREATE INDEX user_node_dns_node ON user_node_dns (node_id);
CREATE INDEX user_node_node ON user_node (node_id);
CREATE INDEX user_notice_done ON user_notice (done_at) WHERE done_at > 0;
CREATE INDEX user_notice_draft ON user_notice (draft_id) WHERE draft_id IS NOT NULL;
CREATE INDEX user_notice_due ON user_notice (due_at, id) WHERE done_at = 0;
CREATE INDEX user_notice_pending ON user_notice (created_at) WHERE approval = 'pending';
CREATE INDEX user_notice_user ON user_notice (user_id, created_at);
CREATE INDEX user_quota ON user (used_bytes) WHERE quota_bytes > 0;
CREATE INDEX user_status ON user (status);
CREATE INDEX user_telegram_chat_user ON user_telegram_chat (user_id, linked_at);
CREATE INDEX user_telegram_code_expiry ON user_telegram_code (expires_at);
CREATE TRIGGER job_name_node_insert
BEFORE INSERT ON node_provision_job
WHEN NEW.state IN ('queued', 'running', 'cancel_requested')
Expand Down Expand Up @@ -1557,8 +1633,9 @@ INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALU
INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALUES (154, 162, 1, datetime('now'));
INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALUES (155, 163, 1, datetime('now'));
INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALUES (156, 164, 1, datetime('now'));
INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALUES (157, 165, 1, datetime('now'));
INSERT INTO "setting" ("k", "v") VALUES ('device_idle_after_days', '30');
DELETE FROM sqlite_sequence;
INSERT INTO "sqlite_sequence" ("name", "seq") VALUES ('audit', 0);
INSERT INTO "sqlite_sequence" ("name", "seq") VALUES ('goose_db_version', 156);
INSERT INTO "sqlite_sequence" ("name", "seq") VALUES ('goose_db_version', 157);
INSERT INTO "sqlite_sequence" ("name", "seq") VALUES ('node_provision_event', 0);
Loading
Loading