/* Permission modes: see perm.h and docs/dev/permissions.md. Core: the record, the gate, the wait. */ #ifndef _DEFAULT_SOURCE #define _DEFAULT_SOURCE 1 #endif #include #include #include #include #include "ask.h" #include "perm.h" #include "toolreg.h" #include "wake.h" /* One row a conversation, made IF NOT EXISTS by every full open and by a set: additive, so no * schema version. allowed: the tools "Allow for this conversation" answered for, a JSON array. */ const char pic_perm_sql[] = "CREATE TABLE IF NOT EXISTS pic_permission(" " session_id TEXT PRIMARY KEY," " mode TEXT NOT NULL CHECK(mode IN ('allow','ask-edits','ask-all','read-only'))," " allowed TEXT NOT NULL DEFAULT '[]'," " updated_ms INTEGER NOT NULL);" /* a phone's set_permission_mode, once per key (rc:DEVICE:KEY), and its answer */ "CREATE TABLE IF NOT EXISTS pic_permission_key(" " key TEXT PRIMARY KEY," " session_id TEXT NOT NULL," " answer TEXT NOT NULL," " created_ms INTEGER NOT NULL)"; static const char *const perm_modes[] = {"allow", "ask-edits", "ask-all", "read-only"}; int pic_perm_valid(const char *mode) { for (size_t i = 0; mode && i < sizeof perm_modes / sizeof perm_modes[0]; i++) { if (strcmp(mode, perm_modes[i]) == 0) { return 1; } } return 0; } const char *pic_perm_claude_name(const char *mode) { return !mode || strcmp(mode, "allow") == 0 ? "bypassPermissions" : strcmp(mode, "read-only") == 0 ? "plan" : "default"; } static int perm_sql_fail(pic_store *s) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); return -1; } static int perm_table(pic_store *s) { sqlite3_stmt *q = NULL; int has = 0; if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'pic_permission'", -1, &q, NULL) == SQLITE_OK) { has = sqlite3_step(q) == SQLITE_ROW; } sqlite3_finalize(q); return has; } int pic_perm_get(pic_store *s, const char *session, char *mode, size_t cap) { sqlite3_stmt *q = NULL; int rc; (void)snprintf(mode, cap, "allow"); if (!session || !*session || !perm_table(s)) { return 0; } if (sqlite3_prepare_v2(s->db, "SELECT mode FROM pic_permission WHERE session_id = ?", -1, &q, NULL) != SQLITE_OK) { return perm_sql_fail(s); } sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC); rc = sqlite3_step(q); if (rc == SQLITE_ROW) { (void)snprintf(mode, cap, "%s", (const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); return rc == SQLITE_ROW || rc == SQLITE_DONE ? 0 : perm_sql_fail(s); } /* Inside a transaction: SESSION's mode becomes MODE, its allowances kept. */ static int perm_put(pic_store *s, const char *session, const char *mode) { sqlite3_stmt *q = NULL; int rc; if (pic_exec(s, pic_perm_sql) != 0 || sqlite3_prepare_v2(s->db, "INSERT INTO pic_permission(session_id, mode, updated_ms) VALUES(?1, ?2, ?9)" " ON CONFLICT(session_id) DO UPDATE SET mode = excluded.mode, updated_ms = excluded.updated_ms", -1, &q, NULL) != SQLITE_OK) { return perm_sql_fail(s); } sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, mode, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 9, pic_wake_now_ms()); rc = sqlite3_step(q); sqlite3_finalize(q); return rc == SQLITE_DONE ? 0 : perm_sql_fail(s); } int pic_perm_set(pic_store *s, const char *session, const char *mode) { if (!pic_perm_valid(mode)) { (void)snprintf(s->err, sizeof s->err, "a permission mode is %s", PIC_PERM_MODES); return 1; } if (!session || !*session) { (void)snprintf(s->err, sizeof s->err, "no conversation yet: send a message first"); return 1; } if (pic_begin(s) != 0) { return -1; } if (perm_put(s, session, mode) != 0 || pic_commit(s) != 0) { pic_rollback(s); return -1; } return 0; } int pic_perm_admit(pic_store *s, const char *session) { sqlite3_stmt *q = NULL; int fresh = 0, rc; if (s->permission_set) { return perm_put(s, session, s->permission_set); } if (!s->permission_default || strcmp(s->permission_default, "allow") == 0) { return 0; } if (sqlite3_prepare_v2(s->db, "SELECT NOT EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ?)", -1, &q, NULL) != SQLITE_OK) { return perm_sql_fail(s); } sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC); rc = sqlite3_step(q); if (rc == SQLITE_ROW) { fresh = sqlite3_column_int(q, 0); } sqlite3_finalize(q); if (rc != SQLITE_ROW) { return perm_sql_fail(s); } return fresh ? perm_put(s, session, s->permission_default) : 0; } int pic_perm_set_keyed(pic_store *s, const char *session, const char *mode, const char *key, char **data) { sqlite3_stmt *q = NULL; int rc; *data = NULL; if (!pic_perm_valid(mode)) { (void)snprintf(s->err, sizeof s->err, "a permission mode is %s", PIC_PERM_MODES); return 1; } if (pic_begin(s) != 0) { return -1; } if (pic_exec(s, pic_perm_sql) != 0 || sqlite3_prepare_v2(s->db, "SELECT answer FROM pic_permission_key WHERE key = ?1 AND session_id = ?2", -1, &q, NULL) != SQLITE_OK) { rc = perm_sql_fail(s); pic_rollback(s); return rc; } sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, session, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { *data = strdup((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); q = NULL; if (!*data) { /* the first time: set it, and keep the answer under the key */ if (perm_put(s, session, mode) != 0 || !(*data = pic_perm_json(s, session)) || sqlite3_prepare_v2(s->db, "INSERT INTO pic_permission_key(key, session_id, answer, created_ms) VALUES(?1, ?2, ?3, ?4)", -1, &q, NULL) != SQLITE_OK) { rc = *data ? perm_sql_fail(s) : -1; free(*data); *data = NULL; pic_rollback(s); return rc; } sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, session, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, *data, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 4, pic_wake_now_ms()); rc = sqlite3_step(q); sqlite3_finalize(q); if (rc != SQLITE_DONE) { rc = perm_sql_fail(s); free(*data); *data = NULL; pic_rollback(s); return rc; } } if (pic_commit(s) != 0) { free(*data); *data = NULL; pic_rollback(s); return -1; } return 0; } int pic_perm_copy(pic_store *s, const char *from, const char *to) { sqlite3_stmt *q = NULL; int rc; if (!perm_table(s)) { return 0; } if (sqlite3_prepare_v2(s->db, "INSERT OR REPLACE INTO pic_permission(session_id, mode, allowed, updated_ms)" " SELECT ?2, mode, allowed, ?3 FROM pic_permission WHERE session_id = ?1", -1, &q, NULL) != SQLITE_OK) { return perm_sql_fail(s); } sqlite3_bind_text(q, 1, from, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, to, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 3, pic_wake_now_ms()); rc = sqlite3_step(q); sqlite3_finalize(q); return rc == SQLITE_DONE ? 0 : perm_sql_fail(s); } char *pic_perm_json(pic_store *s, const char *session) { sqlite3_stmt *q = NULL; char *out = NULL; if (!perm_table(s)) { return strdup("{\"permissionMode\":\"allow\",\"allowed\":[]}"); } if (sqlite3_prepare_v2(s->db, "SELECT json_object('permissionMode', coalesce((SELECT mode FROM pic_permission WHERE session_id = ?1), 'allow')," " 'allowed', json(coalesce((SELECT allowed FROM pic_permission WHERE session_id = ?1), '[]')))", -1, &q, NULL) != SQLITE_OK) { (void)perm_sql_fail(s); return NULL; } sqlite3_bind_text(q, 1, session ? session : "", -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { out = strdup((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); return out; } /* Whether SESSION allowed TOOL for the conversation: 1, 0, or -1. */ static int perm_allowed(pic_store *s, const char *session, const char *tool) { sqlite3_stmt *q = NULL; int rc, yes = 0; if (!perm_table(s)) { return 0; } if (sqlite3_prepare_v2(s->db, "SELECT EXISTS (SELECT 1 FROM pic_permission, json_each(allowed) WHERE session_id = ?1 AND value = ?2)", -1, &q, NULL) != SQLITE_OK) { return perm_sql_fail(s); } sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, tool, -1, SQLITE_STATIC); rc = sqlite3_step(q); if (rc == SQLITE_ROW) { yes = sqlite3_column_int(q, 0); } sqlite3_finalize(q); return rc == SQLITE_ROW ? yes : perm_sql_fail(s); } /* TOOL allowed for SESSION from now on, in a transaction of its own; a second time changes nothing. */ static int perm_allow(pic_store *s, const char *session, const char *tool) { sqlite3_stmt *q = NULL; char mode[16]; int rc; if (pic_perm_get(s, session, mode, sizeof mode) != 0 || pic_begin(s) != 0) { return -1; } if (pic_exec(s, pic_perm_sql) != 0 || sqlite3_prepare_v2(s->db, "INSERT INTO pic_permission(session_id, mode, allowed, updated_ms) VALUES(?1, ?3, json_array(?2)," " ?9) ON CONFLICT(session_id) DO UPDATE SET" " allowed = json_insert(allowed, '$[#]', ?2), updated_ms = excluded.updated_ms" " WHERE NOT EXISTS (SELECT 1 FROM json_each(allowed) WHERE value = ?2)", -1, &q, NULL) != SQLITE_OK) { rc = perm_sql_fail(s); pic_rollback(s); return rc; } sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, tool, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, mode, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 9, pic_wake_now_ms()); rc = sqlite3_step(q); sqlite3_finalize(q); if (rc != SQLITE_DONE) { rc = perm_sql_fail(s); pic_rollback(s); return rc; } if (pic_commit(s) != 0) { pic_rollback(s); return -1; } return 0; } /* ---- the question ---------------------------------------------------------------------- */ typedef struct { char *buf; size_t len, cap; } perm_buf; static void perm_add(perm_buf *b, const char *fmt, ...) { va_list ap; int n; va_start(ap, fmt); n = vsnprintf(NULL, 0, fmt, ap); va_end(ap); if (n < 0) { return; } if (b->len + (size_t)n + 1 > b->cap) { size_t cap = (b->len + (size_t)n + 1) * 2; char *nb = realloc(b->buf, cap); if (!nb) { return; } b->buf = nb; b->cap = cap; } va_start(ap, fmt); (void)vsnprintf(b->buf + b->len, b->cap - b->len, fmt, ap); va_end(ap); b->len += (size_t)n; } /* TEXT's lines, each after PREFIX, at most MAX of them ("..." when there are more), the last * newline dropped. */ static void perm_lines(perm_buf *b, const char *prefix, const char *text, int max) { int k = 0; while (text && *text) { const char *nl = strchr(text, '\n'); size_t n = nl ? (size_t)(nl - text) : strlen(text); if (k == max) { perm_add(b, "\n%s...", prefix); return; } perm_add(b, "%s%s%.*s", k || b->len ? "\n" : "", prefix, (int)n, text); k++; text = nl ? nl + 1 : text + n; } } /* The ask's title and body for C (malloc'd each): "Allow TOOL: KEY?", and a short preview. */ static void perm_texts(pic_store *s, const pic_perm_call *c, char **title, char **body) { sqlite3_stmt *q = NULL; char *key = NULL, *content = NULL, *edits = NULL; perm_buf b = {NULL, 0, 0}; const char *t = c->tool; if (sqlite3_prepare_v2(s->db, "SELECT coalesce(json_extract(?1, '$.command'), json_extract(?1, '$.path'), json_extract(?1, '$.file_path')," " (SELECT value FROM json_each(?1) WHERE type = 'text' ORDER BY key LIMIT 1))," " json_extract(?1, '$.content'), (SELECT group_concat(json_extract(value, '$.oldText') || char(2) ||" " json_extract(value, '$.newText'), char(1)) FROM json_each(?1, '$.edits'))" " WHERE json_valid(?1) AND json_type(?1) = 'object'", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, c->input ? c->input : "{}", -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { for (int i = 0; i < 3; i++) { if (sqlite3_column_type(q, i) != SQLITE_NULL) { *(i == 0 ? &key : i == 1 ? &content : &edits) = strdup((const char *)sqlite3_column_text(q, i)); } } } } sqlite3_finalize(q); if (key) { char *nl = strchr(key, '\n'); perm_add(&b, "Allow %s: %.*s%s?", t, nl ? (int)(nl - key) : (int)strlen(key), key, nl ? " ..." : ""); } else { perm_add(&b, "Allow %s?", t); } *title = b.buf ? b.buf : strdup("Allow this call?"); b = (perm_buf){NULL, 0, 0}; if (c->hook_ask) { perm_add(&b, "A hook asks%s%s\n\n", c->hook_reason && *c->hook_reason ? ": " : ".", c->hook_reason ? c->hook_reason : ""); } if (strcmp(t, "bash") == 0 && key) { perm_add(&b, "%s", key); } else if (strcmp(t, "write") == 0 && key) { perm_add(&b, "%s\n", key); perm_lines(&b, "", content, 20); } else if (strcmp(t, "edit") == 0 && key) { perm_add(&b, "%s", key); for (char *e = edits; e && *e;) { char *end = strchr(e, '\1'), *mid; if (end) { *end = '\0'; } if ((mid = strchr(e, '\2'))) { *mid++ = '\0'; } perm_add(&b, "\n"); perm_lines(&b, "- ", e, 10); perm_lines(&b, "+ ", mid, 10); e = end ? end + 1 : NULL; } } else { perm_add(&b, "%s", c->input ? c->input : "{}"); } *body = b.buf; free(key); free(content); free(edits); } static char *perm_say(const char *fmt, const char *tool) { size_t n = strlen(fmt) + strlen(tool) + 1; char *out = malloc(n); if (out) { (void)snprintf(out, n, fmt, tool); } return out; } /* The existing ask under KEY, its id in ID: 1, 0 none, -1. */ static int perm_find(pic_store *s, const char *key, char id[PIC_ASK_ID_LEN + 1]) { sqlite3_stmt *q = NULL; int rc, found = 0; if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_ask WHERE ask_key = ?", -1, &q, NULL) != SQLITE_OK) { return 0; /* a journal with no asks has none */ } sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC); rc = sqlite3_step(q); if (rc == SQLITE_ROW) { (void)snprintf(id, PIC_ASK_ID_LEN + 1, "%s", (const char *)sqlite3_column_text(q, 0)); found = 1; } sqlite3_finalize(q); return rc == SQLITE_ROW || rc == SQLITE_DONE ? found : perm_sql_fail(s); } static long long perm_expires(void) { #ifdef PIC_FAULTS const char *v = getenv("PIC_TEST_PERM_EXPIRY_MS"); /* a test seam: dev builds only */ if (v && atoll(v) > 0) { return atoll(v); } #endif return 0; } /* Whether TOOL counts as read-only: its registration says so (pic's own tools), or the person's * readOnlyTools names it (a name, or a prefix before *); never a server's word alone. */ static int perm_read_only(const pic_store *s, const pic_tool_def *def, const char *tool) { const char *p = s->read_only_tools; if (def && def->read_only) { return 1; } while (p && *p) { const char *end = strchr(p, ','); size_t n = end ? (size_t)(end - p) : strlen(p); while (n && *p == ' ') { p++, n--; } while (n && p[n - 1] == ' ') { n--; } if (n && (p[n - 1] == '*' ? strncmp(tool, p, n - 1) == 0 : strlen(tool) == n && strncmp(tool, p, n) == 0)) { return 1; } p = end ? end + 1 : NULL; } return 0; } /* The refusal when SESSION is read-only and TOOL is not: 1 with *REASON, 0 when it may go on, -1. */ static int perm_refused(pic_store *s, const pic_perm_call *c, int read_only, char **reason) { char mode[16]; if (pic_perm_get(s, c->session, mode, sizeof mode) != 0) { return -1; } if (strcmp(mode, "read-only") != 0 || read_only) { return 0; } *reason = perm_say("This conversation is read-only (its permission mode): %s was not run. Read, search and list only," " or ask the person to change the mode.", c->tool); return *reason ? 1 : -1; } int pic_perm_gate(pic_store *s, const pic_perm_call *c, char **reason) { char id[PIC_ASK_ID_LEN + 1], mode[16], state[16] = "", *value = NULL; const pic_tool_def *def = pic_tool_named(c->tool); int found, need = 0, rc, read_only = perm_read_only(s, def, c->tool); *reason = NULL; if ((found = perm_find(s, c->key, id)) < 0) { return -1; } if (!found) { int edits = strcmp(c->tool, "write") == 0 || strcmp(c->tool, "edit") == 0; if (!def || !pic_toolset_on(c->tool)) { return 0; /* it answers "Tool X not found" */ } if ((rc = perm_refused(s, c, read_only, reason)) != 0) { return rc; } if (pic_perm_get(s, c->session, mode, sizeof mode) != 0) { return -1; } if (c->hook_ask) { need = 1; } else if (!c->hook_allow) { need = strcmp(mode, "ask-all") == 0 ? !read_only : strcmp(mode, "ask-edits") == 0 ? edits : 0; if (need && (rc = perm_allowed(s, c->session, c->tool)) != 0) { return rc < 0 ? -1 : 0; } } if (!need) { return 0; } { char *title = NULL, *body = NULL; pic_ask_new a = {c->key, c->session, c->submission, "select", NULL, NULL, "[\"Allow\",\"" PIC_PERM_ALWAYS "\",\"Deny\"]", NULL, 0}; long long ttl = perm_expires(); perm_texts(s, c, &title, &body); a.title = title ? title : "Allow this call?"; a.body = body; if (ttl > 0) { a.expires_ms = pic_wake_now_ms() + ttl; } rc = pic_ask_open(s, &a, id); free(title); free(body); if (rc != 0) { return -1; } } } pic_fault("perm_ask"); rc = pic_ask_wait(s, id, state, sizeof state, &value); if (rc == 1) { (void)pic_ask_withdraw(s, c->key); return 2; } if (rc != 0) { return -1; } pic_fault("perm_ask"); if (strcmp(state, "answered") == 0 && value && strncmp(value, "\"Allow", 6) == 0 && (rc = perm_refused(s, c, read_only, reason)) != 0) { /* the mode became read-only meanwhile */ free(value); return rc; } rc = 1; if (strcmp(state, "answered") == 0 && value && strcmp(value, "\"Allow\"") == 0) { rc = 0; } else if (strcmp(state, "answered") == 0 && value && strcmp(value, "\"" PIC_PERM_ALWAYS "\"") == 0) { rc = perm_allow(s, c->session, c->tool) == 0 ? 0 : -1; } else if (strcmp(state, "expired") == 0) { *reason = perm_say("Nobody answered whether to run this %s call before the question expired; it was not run.", c->tool); fprintf(stderr, "pic: nobody answered whether to run a %s call; it was denied\n", c->tool); } else if (strcmp(state, "withdrawn") == 0) { *reason = perm_say("The question whether to run this %s call was withdrawn; it was not run.", c->tool); } else { *reason = perm_say("The person denied this %s call; it was not run.", c->tool); } free(value); if (rc == 1 && !*reason) { return -1; } return rc; } /* ---- the commands ---------------------------------------------------------------------- */ static int perm_rpc_open(pic_rpc_call *c, pic_store *s) { if (!c->db || !*c->db) { (void)snprintf(c->err, sizeof c->err, "no journal"); return -1; } if (pic_open_narrow(s, c->db) != 0) { (void)snprintf(c->err, sizeof c->err, "%s", s->err); pic_close(s); return -1; } return 0; } static int rpc_get_permission_mode(pic_rpc_call *c) { pic_store s; if (!c->session || !*c->session || perm_rpc_open(c, &s) != 0) { /* nothing run here yet */ c->err[0] = '\0'; c->data = strdup("{\"permissionMode\":\"allow\",\"allowed\":[]}"); return c->data ? 0 : -1; } c->data = pic_perm_json(&s, c->session); if (!c->data) { (void)snprintf(c->err, sizeof c->err, "%s", s.err); } pic_close(&s); return c->data ? 0 : -1; } static int rpc_set_permission_mode(pic_rpc_call *c) { pic_store s; char *mode = pic_rpc_text(c, "$.mode"); int rc = -1; if (!pic_perm_valid(mode)) { (void)snprintf(c->err, sizeof c->err, "a permission mode is %s", PIC_PERM_MODES); } else if (!c->session || !*c->session) { (void)snprintf(c->err, sizeof c->err, "no conversation yet: send a message first"); } else if (perm_rpc_open(c, &s) == 0) { if (pic_perm_set(&s, c->session, mode) == 0 && (c->data = pic_perm_json(&s, c->session))) { rc = 0; } else { (void)snprintf(c->err, sizeof c->err, "%s", s.err); } pic_close(&s); } free(mode); return rc; } const pic_rpc_command pic_get_permission_mode_rpc = {"get_permission_mode", "the conversation's permission mode and the tools allowed for it", PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_get_permission_mode}; const pic_rpc_command pic_set_permission_mode_rpc = {"set_permission_mode", "set the conversation's permission mode: allow, ask-edits, ask-all or read-only", PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_set_permission_mode};