Zero Labs
Industry News / AI

Building a Secure, Multi-Persona Streamlit in Snowflake App for AI_EXTRACT Document Review

Source · Towards AI By Satish Kumar

From the publisher’s feed, collected in the ZeroLabs newsroom.

How much of a document workflow a business can automate depends on how safely people can step in when automation isn’t sure. Consider a procurement team onboarding new suppliers. Every supplier sends a registration form, a W-9 and a certificate of insurance. The goal is to approve complete, valid suppliers quickly, catch expired or inconsistent documents, and keep a clear record of who approved what.In our proof of concept, Cortex AI_EXTRACT reads those documents and returns fields with scores and citations, and validation sends uncertain critical fields to a reviewer. What was missing was the app those reviewers, and the operators running the pipeline, would work in.The obvious build is a Streamlit in Snowflake app with a page per audience. But Streamlit in Snowflake runs with owner’s rights by default: every query runs as the app’s owner role, whoever is looking at the screen. Hiding a page doesn’t stop the owner role from doing what that page did. That’s why, when an app runs as its owner, authorization belongs in the database, not in the UI.TL;DRFor the POC I built one container-runtime Streamlit app (APP.SUPPLIER_CONSOLE) for three personas: REVIEWER, OPERATOR and ADMIN.Pages are filtered by persona, but every write goes through an APP.SP_*_AS procedure that re-checks the persona, and the app's owner role has no direct DML.Review decisions are race-safe: a conditional UPDATE … WHERE status = 'OPEN' guarantees one decision per task. I verified it with two concurrent connections.Validation in our DEV account: 248 offline tests, 132 live integration checks and 45 live page-level checks, all passing.The page-level tests found a bug the other two layers missed: GET_PRESIGNED_URL rejects a bound path argument.The remaining trust boundary is viewer identity under owner’s rights. Restricted caller’s rights (GA since June 2026) is the native answer. I haven’t tested it yet.What you’ll learn: how to structure authorization for a multi-persona, owner’s-rights Streamlit app; how to make human-review decisions race-safe and atomic; and how to build a test harness that runs your real Streamlit pages against live Snowflake.The problemThe pipeline runs as owner’s-rights stored procedures behind a scheduled task: register, preflight, AI_EXTRACT, validate, then publish to masked curated tables. When validation fails on a critical field (a missing COI expiry, a W-9 signed in the future, an invalid country), it opens a review task. A person approves, corrects or rejects it; decisions are append-only, and the original AI value is never overwritten.The app has to serve three kinds of user on top of that:Why the obvious design falls shortThe naive version is a Streamlit app that hides pages by persona and calls the pipeline’s procedures directly. It has four problems, and all of them come from owner’s rights:The other common answer, one app per audience, each with its own least-privilege owner role, keeps roles separate but doubles the deploys, grants and code, and still doesn’t solve identity or races. I compare the two at the end.Design goalsOne app, with pages chosen by the viewer’s persona.A hidden page is not the only control. Every state change is re-authorized in SQL.No direct DML for the app’s owner role.Exactly one decision per task, even under concurrency.Atomic multi-field decisions for a whole document.Every action audited, with friendly errors on screen and raw errors in the log.The architectureThe app layer adds a small APP schema next to the pipeline:APP.APP_USER: one row per console user and their persona. It's seeded from environment config at deploy time and maintained on an Admin page.APP.REASON_CODE: structured reasons for decisions. A free-text reason stays mandatory.APP.APP_EVENT: an append-only log of every console action, successful or not.Eight persona-checked procedures: claim, release, submit, submit a whole document, run the pipeline, manage users, the persona check itself, and event logging.Implementation1. An owner role that cannot do muchThe owner role inherits no functional role. It gets SELECT on exactly what the console displays, and USAGE on the persona-checked procedures:CREATE ROLE IF NOT EXISTS SDI_DEV_CONSOLE_APP;GRANT SELECT ON VIEW OPS.V_REVIEW_BACKLOG TO ROLE SDI_DEV_CONSOLE_APP;GRANT SELECT ON TABLE VALIDATE.FIELD_RESULT TO ROLE SDI_DEV_CONSOLE_APP;GRANT USAGE ON PROCEDURE APP.SP_SUBMIT_REVIEW_AS(STRING, STRING, STRING, STRING, STRING, STRING) TO ROLE SDI_DEV_CONSOLE_APP;GRANT USAGE ON PROCEDURE APP.SP_RUN_PIPELINE_AS(STRING) TO ROLE SDI_DEV_CONSOLE_APP;It has no access to EXTRACT, CONFIG or CURATED, and it can't call OPS.SP_RUN_PIPELINE directly. I didn't just assume this held; the live suite runs each of those calls as the owner role and expects them to be refused.2. Every write re-checks the personaCREATE OR REPLACE PROCEDURE APP.SP_REQUIRE_PERSONA(P_VIEWER STRING, P_ALLOWED ARRAY)RETURNS STRING LANGUAGE SQL EXECUTE AS OWNER AS$$DECLARE not_authorized EXCEPTION (-20207, 'Not authorized: viewer is not an active console user with the required persona'); v_persona STRING;BEGIN SELECT MAX(persona) INTO :v_persona FROM APP.APP_USER WHERE user_name = UPPER(TRIM(:P_VIEWER)) AND is_active; IF (v_persona IS NULL OR NOT ARRAY_CONTAINS(v_persona::VARIANT, :P_ALLOWED)) THEN RAISE not_authorized; END IF; RETURN v_persona;END;$$;Each _AS procedure calls this before any write. A unit test parses the procedure bodies and fails if an INSERT, UPDATE, MERGE or nested CALL appears before the persona check. That's cheap, and it catches the easiest mistake to make during a refactor.3. Making decisions race-safeThe tempting shape is to check the task is open, then update it. That’s a classic check-then-act window: two reviewers can both pass the check. In this design the update itself is the guard:UPDATE REVIEW.REVIEW_TASK SET status = DECODE(:v_decision, 'APPROVE', 'APPROVED', 'CORRECT', 'CORRECTED', 'REJECTED'), resolved_at = CURRENT_TIMESTAMP(), claimed_by = NULL, claimed_until = NULL WHERE review_id = :P_REVIEW_ID AND status = 'OPEN' AND (claimed_by IS NULL OR claimed_until IF (SQLROWCOUNT = 0) THEN RAISE not_open; END IF; -- lost a raceThree decisions sit behind that block:The task closes before the decision is written. If closing it updates zero rows, nothing else happens.SP_RECORD_DECISION has no transaction control of its own. Every caller wraps it in BEGIN TRANSACTION … COMMIT, with ROLLBACK; RAISE; in the exception handler, so the task update, the decision row and the document status change commit together.Claims are leases, not locks. A reviewer claims a task for review_claim_minutes (default 15). An expired lease can be taken over, so an abandoned browser tab can't block the queue.4. Whole-document decisions, all or nothingAPP.SP_SUBMIT_DOCUMENT_AS(document_id, decisions ARRAY, viewer) validates the entire batch first:every task belongs to this document and is still open;no task appears twice;every reason code applies to its decision.Only then does it open one transaction and record each decision. One invalid value rolls back the whole batch.5. The app sideThe Streamlit code is deliberately thin:core/db.py is the only module that sends SQL. Every statement is a constant with ? placeholders, and a test fails if any other module calls .sql(.core/errors.py maps the database's named exceptions (NOT_OPEN, CLAIMED_OTHER, BAD_CORRECTION, …) to plain sentences. Anything else is logged to APP.APP_EVENT with the raw error, and the user sees Reference: .Navigation: st.navigation only registers the pages a persona may see.Caching: on the container runtime one process serves every viewer, so st.cache_data is shared. I cache only data that's identical for everyone, plus the persona lookup keyed by user name. Nothing is cached per "current user".ValidationI tested in three layers, because each one misses things the others catch.The concurrency testTwo threads, two connections, one barrier, the same task:barrier = threading.Barrier(2)# each worker: USE ROLE SDI_DEV_CONSOLE_APP; barrier.wait(); CALL APP.SP_SUBMIT_REVIEW_AS('T12-R2', 'APPROVE', ...)Recorded result: one call returned OK. The other failed with NOT_OPEN, raised by the SQLROWCOUNT = 0 guard after the update, not by the earlier lookup. That detail matters. The losing transaction got past the "is it open?" read, exactly as in a real race, and was stopped by the guarded update itself. Exactly one decision row exists.Running real pages against live SnowflakeThe page test is the part I’d reuse on any Streamlit in Snowflake project. AppTest normally runs against mocks; here st.connection returns a real Snowpark session that has switched to the app's owner role:session = Session.builder.configs({"connection_name": "default"}).create()for s in ("USE ROLE SDI_DEV_CONSOLE_APP", "USE SECONDARY ROLES NONE", "USE WAREHOUSE SDI_DEV_WH"): session.sql(s).collect()streamlit.connection = lambda *a, **k: _Conn(session) # .session() -> the live sessionstreamlit.user = {"user_name": "LIVE_REVIEWER"} # one viewer per personaat = AppTest.from_file("streamlit_app.py").run()at.button(key="next-task").click().run()It seeds a synthetic document with four open tasks and five LIVE_* users. It never decides real tasks, and it removes everything in a finally block. It costs no AI_EXTRACT, because "Run pipeline" is clicked only when nothing is pending.The bug only the page test could catchThe first two layers passed. Then I clicked Get source document link in the deployed app and got:Something went wrong and the action was not completed. Reference: 690f6a6310d6The reference led straight to the cause in the activity log:Argument 2 to function 'GET_PRESIGNED_URL' cannot be null or empty.The app sent SELECT GET_PRESIGNED_URL(@RAW.DOC_LANDING, ?, 900) with the path as a server-side bound parameter, and the function rejects it at compile time. My offline tests used a fake session. My integration runner used the Python connector's default style, which interpolates values into the SQL text before sending it. Neither exercised real binding.The fix reads the path from the document registry instead:SELECT GET_PRESIGNED_URL(@RAW.DOC_LANDING, relative_path, 900)FROM RAW.DOCUMENT_REGISTRY WHERE relative_path = ? LIMIT 1As a side effect, links can now only be created for registered documents, which is safer than signing any path a caller supplies. I also changed the live suite to run every read query from core/db.py with paramstyle="qmark", exactly as Snowpark sends it.Lesson: if your test harness binds parameters differently from production, you’re testing a different program.Security: where the trust boundaries areThat last row is the honest limitation. Under owner’s rights, Snowflake can’t tell the procedure who is looking at the screen; it trusts the app. My mitigation is that no human role can call the _AS procedures, so impersonation requires compromising the app's owner role.The native improvement is restricted caller’s rights. It’s GA for container-runtime apps and needs Streamlit 1.53.1 or later. An administrator uses caller grants to define which of the viewer’s own privileges the app may use. That would let Snowflake vouch for identity instead of the app. I haven’t implemented or tested it in this POC. It’s the next thing I’d spike.One more gap I chose to accept: uploads. A stage PUT can’t be routed through a stored procedure, so the Upload page is gated in the app only, and every upload is written to the activity log. A stricter design would have operators upload into a quarantine location, then move validated files with an operator-only procedure.From POC to productionCost:AI_EXTRACT is billed by tokens; it's the dominant cost and is unaffected by the console. "Run pipeline" requires an explicit confirmation checkbox for that reason.The container runtime uses a compute pool (here SYSTEM_COMPUTE_POOL_CPU).The query warehouse runs the app’s SQL.I didn’t measure costs in this POC, so I make no cost claims.Monitoring: APP.APP_EVENT with outcome = 'FAILED' is the operator's first stop. Every user-facing error carries the reference that finds its row.Scale: the queue and the metrics pages load data into pandas. That’s fine at POC volumes; at thousands of open tasks I’d paginate the queue and push aggregation into views.Retention: the activity log is append-only and nothing purges it yet. It needs a retention policy.Citations status: the review page shows the page number and bounding box from AI_EXTRACT(..., citation => TRUE), which is Preview and requires cross-region inference. Account for that before production.YouTube Demo:https://medium.com/media/dea9dce5aa4a2c5c9b7bfa8d480481d9/hrefTrade-offsUse this pattern when several audiences share one workflow, you need an auditable “who decided what”, and writes can go through procedures.Avoid it when the audiences must never share a data plane (the owner role is a union of their reads), or when restricted caller’s rights covers your case. Then let Snowflake enforce the viewer’s own privileges.Architect’s takeawaysUnder owner’s rights, the UI is a convenience, not a control. Re-authorize every write in SQL.Make the update the guard. A conditional UPDATE plus SQLROWCOUNT beats a check followed by a write.Keep transaction control out of shared procedures. Let callers own the transaction, so single and batch paths share one atomic core.Test with production’s parameter binding. Interpolating in tests hid a real failure.Error references pay for themselves. One reference ID turned a vague failure into a one-query diagnosis.The useful lesson from this POC isn’t how to build a Streamlit page. Authorization lives in “what the database lets this person do”, not in “which page they can see”, and that’s the boundary that holds when the next page, app or agent gets built on the same tables.Found this useful? Clap 👏, share, and follow Snowflake Chronicles for practical Snowflake architecture insights. Let’s also connect on LinkedIn.Reuse & Attribution: Feel free to share or adapt with proper credit and a link to the original post. Shared for educational purposes — please test and validate before production use. Views are my own and do not represent any current or former employerBuilding a Secure, Multi-Persona Streamlit in Snowflake App for AI_EXTRACT Document Review was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.