Vegard Cowie Jørgensen
NO

Article · Security architecture and AI

When the AI may only do what the user may do

Lessons from security architecture, prompt injection and red teaming in a cloud-based business system built for many organizations

A manipulated model asks for all data, but the database returns only what the user has access to, and the other organizations' data is untouched.

The model can be fooled. The boundary sits in the database, which answers with the user's own permissions.

An AI assistant in a business system can easily seem like a small miracle. The user asks what is overdue, where a document is, or for help filling in a form. Behind those questions sit cases, documents and personnel data, in a system built to be shared by many organizations. To a developer, a personnel record is a row in a table. To the person it describes, it may hold something they would never want a colleague to see.

That is a fundamental architectural problem. In ordinary software, the instructions come from the developers, and data that turns into instructions, as in SQL injection, is a bug that can be fixed. A language model can be steered by the very data it is meant to process, because it cannot reliably tell instructions from data, and yet the assistant is allowed to look up exactly this information. The usual assumption that an application's own components can be trusted does not hold for such a component.

Here I describe how I built and tested such an assistant: where I put the security boundary, how I layer the defenses against prompt injection, and how I deliberately try to make the system fail. Many of the most useful lessons came from errors I found in my own assumptions and in the tests that were supposed to catch them. All the testing I describe was done in a staging environment with fictitious data, and the flaws were found and fixed there, before they reached production.

The model is not the security boundary

The first decision shaped everything else: the language model must not be what prevents a data leak. Prompt injection is among the most significant attack classes against systems built on language models, and no model is immune.

The database is therefore the primary authorization boundary for organization data. Row-level security (RLS) in PostgreSQL isolates each organization, and the access system checks specific permissions ("can read cases") rather than role names ("is a manager"). Roles are bundles of permissions that each organization assembles and can rename. The service layer and the AI gateway enforce the rest: who may use AI, where the text is sent, quotas and logging.

RLS does not cover everything. Privileged database functions and service identities bypass the row policies (a SECURITY DEFINER function owned by a role with BYPASSRLS or by the table owner, and the table owner itself when FORCE ROW LEVEL SECURITY is not set), so I treat them as separate control surfaces. Such a function has to check for itself who is calling and which organization the call concerns, and a service identity may only do what it needs. Views are similar: by default they check permissions and row policies as their owner, unless they are created with security_invoker. RLS also filters rows without hiding everything around them. Unique and foreign key constraints, error messages and timing can reveal that a row exists. RLS also enforces the policies as written; it does not prove that they are right. The guarantee assumes correct policies and that the user's identity reaches the database correctly.

The assistant builds on this. When it looks up data, it does so with the user's own identity, so the database decides what comes back. If a manipulated model response asks for something the user has no access to, it gets the same thing the user would get in the app: nothing. The user's permissions are thus the ceiling for what the assistant can look up, not for what it can do with what it finds.

Throughout this text I distinguish between three kinds of defense:

  • What enforces. Deterministic controls that hold even if the model obeys the attacker completely: RLS, a permission check on every tool call, residency controls in the code. A breach here is a vulnerability.
  • What reduces risk. Behavioral defenses that make attacks harder without guaranteeing anything: instructions to the model, wrapping and sanitizing of data, length limits.
  • What detects. Tests, red teaming and monitoring that show when any of the above is not working.

Three kinds of defense: controls that enforce, measures that reduce risk, and tests and monitoring that detect.

Figure 1Only what enforces has to hold when the model obeys the attacker. The rest is defense in depth and alerting.

Who the system has to defend against

The threat model is short on purpose:

ActorWhat they haveWhat has to hold
Unauthenticated attackerPublic endpointsAuthentication, no data without a valid identity
Employee with ordinary accessValid account, own organizationTheir permissions, nothing more
Employee who plants instructions in dataWrite access to ordinary fieldsThe text stays data for whoever reads it
Administrator in another organizationBroad access in their own organizationIsolation between organizations
Attacker with a stolen token or passwordValid credentialsRevocation and limited damage
Manipulated or compromised modelArbitrary responses and tool proposalsChecks at execution time and in the database
Developer who misconfigures somethingLegitimate access to code and configurationAutomated checks in the build pipeline (CI)

The last row is me. Experience has made it difficult to justify leaving it out.

The threat model does not cover a compromised vendor (cloud, model or database), a compromised operations environment or build pipeline, or someone sitting at an unlocked device. There I rely on vendor agreements, access management for operations and ordinary device security. The security claims below apply within this scope.

One entry point for all text generation

The client holds no key to a model vendor, and an AI call passes through three stages. A serverless function per AI feature receives the message and the identity, checks that the organization has AI enabled, reserves quota and owns the conversation with the model, including the tool lookups. An internal AI gateway, which users cannot reach directly, owns the keys, the choice of route and model, data residency, cost protection and logging. The database enforces permissions as before, without knowing that an AI is asking.

The app never reaches the model directly. The call goes through an AI feature and an internal gateway, and the database enforces permissions.

Figure 2All text generation goes through one gateway, which owns routing, cost protection and logging.

The gateway knows nothing about the business domain. The assistant, translation and other features use it the same way. A new AI feature inherits residency controls, cost protection and logging without building them itself. An automated check requires every server function that requests text generation for an organization to pass through the shared permission check first.

The conversation is not stored on the server, and intermediate results are discarded once the response is delivered. That means a smaller attack surface and less data to manage. The price is that I cannot read conversations back for debugging. I log metadata instead, only what operations, cost control and abuse detection need.

Tools: from menu to execution

To answer questions about the organization's own data, the model needs tools, that is, functions it can ask to have run. Customer data is not retrieved from a vector database. The tools query the database directly with the user's identity, and the same row policies apply as in the app. In a separate vector store over embedded text chunks (embeddings), access would have had to be copied onto every chunk, where it can go stale, and filtering would have had to happen before or after the search, each with its own way of letting matches through or hiding them. Embeddings stored in the same database, with pgvector for example, could inherit the row policies, but for structured records, direct queries give more precise answers anyway.

Which tools are exposed to the model is decided per request from the user's permissions, fetched fresh every time. The permission required for each tool lives in a single shared registry, and a tool missing from it requires a permission no one has and becomes invisible to everyone. A snapshot test makes any change to the menu visible in code review.

The menu on its own protects little, though. A manipulated model can ask for a tool it was not offered, send odd arguments or supply an id from another organization. So the call is checked again at execution time, in four stages:

  1. The registry. The name is looked up in the list of tools the user was offered in this request. Unknown names return an error code to the model, and nothing runs.
  2. Authorization. The list is built from the permissions fetched at the start of this request, not when the conversation began. It is a snapshot that lives for a few seconds. If the user loses a permission in the middle of a request, the fourth stage is what catches it. The row policies read the organization from the token, but look up permissions, profile status and the kill switch in tables on every query.
  3. The arguments. Each tool validates its own arguments: ids must have the right shape, numbers are clamped to an allowed range, free text is truncated, and the number of rows is capped.
  4. The database. The query runs with the user's identity, so RLS applies no matter what the first three stages let through.

The last stage turns the rest into defense in depth. If a bug in the registry or the validation lets a call through, it only gets rows the user could have read anyway.

The tools are described to the model with a JSON schema, and a call comes back as a separate block with a JSON object, apart from the response text. The server reads the calls from this structure and never interprets free text as commands. The schema steers what the model tries to send but enforces nothing, so the arguments are treated as untrusted input, like a form on the web: only known fields are read, values from fixed lists are checked, and categories are looked up against the organization's own list. If the response stops in the middle of a call because the length limit has been reached, the call is not run.

The user's read access sets a ceiling, but it does not say what the assistant needs. An employee may be allowed to open a hundred cases, while a question about what is overdue only needs title, due date and status. Each tool is built for one task and fetches only the fields that task needs, never whole rows, with a cap on the number of rows. That gives the model less to repeat incorrectly, less untrusted text to be steered by, and less information sitting with the vendor.

The most sensitive areas, those bordering on special categories of personal data, have no tools at all. Where insight is needed, I provide aggregates and status instead of free text, and an aggregate over a small group is withheld below a minimum group size, so that a single aggregate does not single out individuals. Combining several aggregates is covered under semantic leakage.

Some answers should not be phrased by a model either. If the question concerns something urgent where bad advice can have safety consequences, the assistant does not improvise. It shows the source and the relevant contact information as a card, and the critical information is rendered deterministically from the data.

Here is the full path for a single request:

The model can only ask for tool calls. The registry, the authorization, the argument check and the database decide, and the database stops whatever the others let through.

Figure 3The model proposes, everything else decides. The solid lines are controlled code, and the dashed ones are the model's wishes.

Conversation history lives on the client

When the server does not store the conversation, the client has to hold it. Picture an employee who asks about something they have access to, gets the answer, and then loses that access. If the old history is sent along with the next question, the model can repeat the information without a new database lookup. RLS does not fail, but the database is not asked again.

The history lives only in memory on the device, never on disk, in a cache or in the database, and it disappears when the app closes. It is bound to the person in the active organization. On logout, a new user on the same device or a switch of organization, the conversation is cleared, and a response in flight is aborted so it does not land with the wrong person.

A permission change in the middle of a conversation within the same organization does not clear the history. The user has already seen the information, the conversation is short-lived, and clearing it would require the client to track permissions in real time. I chose data minimization and a short lifetime over immediate revocation of what has already been shown. New lookups always run against the permissions as they are now. It also means that what has been shown can be sent to the model again in the same conversation after the access has been removed. That is a chosen limit on revocation, and the database boundary does not cover it.

The server does not trust the history either. It is accepted only as plain text from two allowed senders, in a limited amount, and the last message must be the user's. Tool calls and tool results are built only on the server, within a single request. A forged history cannot smuggle in tool blocks. Invented "earlier answers" grant no new access, but they can steer how the model behaves. That is a weakness in the behavioral defenses, not in the boundary.

Prompt injection

Prompt injection is a family of attacks in which text the attacker controls ends up in the model's context and is read as an instruction. There are two ways in: the user's own message (direct) and everything the tools fetch from the database (indirect). The NCSC has pointed out that this is different from SQL injection. A database can separate code from data with parameterized queries, while a language model has no equivalent hard boundary.

The confused deputy

The indirect path is the most dangerous, because the attacker and the person asking need not be the same person. Employee A, with limited access, writes an instruction into an ordinary field, for example the description of a case. Employee B, who has broader access, asks the assistant something that makes it read that field. The assistant is now acting with B's rights, but partly on A's instruction. It is a variant of the classic "confused deputy" problem.

An employee with narrow access plants an instruction in a field. A colleague with broad access asks the assistant, which reads the field, but anything to be written becomes a draft the colleague must confirm.

Figure 4Indirect injection: everything is authorized for B, so the question is whether the action is what B actually wanted.

The database does not help much here, because everything that happens is authorized for B. The question is whether the action matches what B wanted. I address it with three things: the tools only read, the model has few ways out, and anything that changes something goes through a human who sees the proposal before it happens.

What enforces

Simon Willison calls the combination of access to private data, exposure to untrusted content and a way out "the lethal trifecta". The assistant needs the first two to be useful, so I remove the third. The tools read, there is no web search or other outbound call, and the model cannot create links or images. It points only with reference markers the server has given it through the tools, and the client translates only such markers against its own route table. An invented marker does not become a link. The client does not render images either, so an image URL cannot be used for zero-click exfiltration. The response is rendered with the app's own components from a small, known text format, never as HTML or as Markdown with links, so a URL the model writes stays text.

Leakage requires private data, untrusted content and a way out. Here the model's own way out is removed: no links, images or web calls from the model.

Figure 5The assistant needs the first two. That is why the model's own way out is removed.

The architecture removes the model's direct exfiltration channels. Indirect relaying through the user or ordinary workflows has to be handled separately. The assistant could, for example, suggest that something be entered into a form others can read, or phrase an answer that leads the user to pass something on.

The assistant does not write on its own either. A write action becomes a draft card with pre-filled fields that the user can edit and must confirm, and the write itself goes through the same paths as a manually completed form, with the same permission check and audit trail. The write is built only from the fields the card shows, plus values the client sets itself, such as organization and timestamp. The model cannot attach hidden parameters. Each action type can be switched off centrally. A user who confirms without reading is a real residual risk. The action cannot exceed the user's own access, but it can move information the user may read into a field others may read. Being allowed to read something and to write somewhere does not mean being allowed to move it there. Confirmation also enforces approval, not understanding, and the model that phrased the proposal shapes how the user reads it. What counts is the fields on the card as they actually stand, and the model's description of them does not change that.

Injected text can also pose as the CEO, a regulator or the system itself. That changes nothing in the database, where rights follow from who is asking.

What reduces risk

The rest of the defenses make attacks harder without guaranteeing anything. For each measure, I have written down what it does not protect against.

The rules for the model's behavior come only from the system. The user's message is the task, not new rules, and both it and the tool results are marked as data. The model is told not to accept new rules from them, and not to follow instructions found in tool results. The behavioral rules (data is not instructions, the instructions are not disclosed, no role is adopted from data, claimed authority is reported with its source) sit in a layer owned by the code. That way they survive someone adjusting the part of the prompt that can be edited in an admin panel. This lowers the success rate of naive attempts, but a model can still be talked into things.

Data is placed in delimited sections with markers. In an internal review I found that the markers were not neutralized inside the data itself. A text containing a closing marker could end the section early and make the rest look like an instruction. The fix lives in the shared sanitizer, and every AI feature got the protection at the same time. Even so, the wrapping does nothing against persuasive text that stays inside the section.

Invisible characters (zero-width, directional, tag and control characters) are stripped from user messages and tool data. This does not catch visible text, homoglyphs or encodings such as base64, and some of these characters have legitimate uses in certain languages.

Messages, tool results, history and the number of tool rounds are capped, and truncation happens with a clear marker and the most important content first. This limits attacks that drown the instructions in text, and cost attacks via huge fields. The system's own instructions are capped as well, and because truncation there would happen silently, the code writes a warning to the log before the cap is reached.

Every free-text field a tool returns is a possible channel for indirect injection. I map which fields the tools read, keep the sensitive ones out, and pass the rest through wrapping, stripping and truncation. Where possible, the server builds the most important information (key figures, source documents, contact information, suggested actions) as cards from the tool results, so a manipulated model has less to alter.

The system instructions must not contain anything that does harm if it leaks: no keys, no one else's data, no backdoors.

Bedrock and data residency

I chose AWS Bedrock because it offers access to current models in EU regions, with an account setting for data retention (the none mode) under which requests and responses are not stored by the vendor. The identity the gateway uses may only invoke models and cannot change retention or logging settings. It therefore cannot turn on model invocation logging (off by default), which could otherwise store both inputs and responses in the account. The keys are kept as secrets in the server environment.

An EU endpoint does not by itself mean inference happens in the EU. Bedrock distinguishes between calls to a model in a single region and calls through an inference profile that can route to other regions. A geographic profile stays within its geography, while a global profile can send the call anywhere. Where the text is processed depends on both the endpoint and the model id. I allow only regional model ids or EU profiles, and only regions in the EU/EEA. Some regions whose names start with "eu-" are outside the EEA (London and Zurich, for example) and are kept off the list.

Routing can be changed from an admin panel, and a residency guarantee that lives only in configuration can be broken by a typo. So before every call, the gateway checks that the base URL in the route configuration is a known EU host in strict form, with no path or parameters of its own that could steer the call toward another API on the same host (the code appends the path for the model call itself). It also checks that the model is on an allowlist of version-pinned models confirmed to run without retention, and that the request does not ask for vendor features that store content. A rejection returns a generic error code. The boundary is also enforced in the cloud setup, where access control allows calls only to EU regions, changes to the logging settings are denied, and it has been verified with the provider that content is not stored.

A flag is not a control

An internal security review showed that the residency control accepted routes marked "EU" for tasks involving personal data, but the mark was just a field in a table, and the address was not checked. A fallback route without an explicit address would have fallen back to the vendor's global endpoint, while still being marked EU and with the log saying "eu". The logs would have looked reassuring. The actual destination, less so. The flaw was found and fixed in the staging environment, on fictitious data, before it reached production.

Now a route counts as EU only when the same check in the code approves its actual address. If no route remains, the gateway fails closed and alerts operations instead of silently falling back to something less strict. The same rule is enforced when routes are written to the database, so the error is caught both on the way in and at the point of use.

Before, the system trusted an EU mark in a table. Now the code checks the actual address, and without an approved route the call is rejected and operations are alerted.

Figure 6A mark in a table is a claim. The check in the code decides whether the route is actually EU.

When the model changes

Model ids are version-pinned. A new model or version is put into use only once it has been added to the allowlist along with a test, the tests against the real model have been rerun, and retention and residency have been assessed for that specific model. Vendors change their terms and offerings over time, so I review the list regularly.

Classification and logging

Each AI feature has a privacy class that determines whether its content may be logged and whether the residency requirement applies. What matters most is which way the default points. A feature nobody has classified is treated as the strictest class: its content is not logged, and it may only use approved EU routes. "No personal data" has to be chosen and justified, and a catalog-driven test requires every feature with that class to appear on a list with a justification.

Every model call is logged with task, model, region, status, duration, usage and a correlation id that ties together the rounds within one user message. Content is logged only for features without personal data, and the rule applies to everything derived from the content: raw input, the prompt and the model's response. I test it against what is actually written, not just against the column names.

Metadata can also be personal data. Task type, timestamp, user reference and organization can together reveal a lot without a single sentence being stored. I treat the AI log as a record of personal data: it is used only for operations, cost and abuse detection, only the people who operate the platform can read it, and the retention period comes from the register of legal values.

Usage per organization is counted in separate counters scoped to each organization, so nothing an organization sees is built from the platform log. The log has no column for the organization, but the user reference links it to one, which is why only operations can read it.

Errors are mapped to fixed codes before they leave the system, and secrets are not logged. Data changes write an audit event via database triggers, also when the change followed an AI suggestion, independently of the service logic and without free text.

Sign-in and tokens

When security rests on the user's identity, sign-in becomes part of AI security. A stolen token does not give the model more than the user has, but it gives the attacker everything the user has.

A rate limit per IP address does little against password spraying from many addresses. Failed sign-ins feed into monitoring, and I prefer progressive throttling, CAPTCHA and two-factor authentication over locking accounts, because account lockout hands the attacker a button for locking others out. Administrators use two-factor authentication, and critical actions require fresh confirmation.

A signed access token is valid until it expires, and logging out or changing a password does not automatically make it stop working against the database. Whatever is in the token follows the token's lifetime. That includes which organization the user is signed in to, so switching organization requires a new token. Permissions, on the other hand, are not in the token. The row policies look them up in tables on every query, along with whether the profile is active and whether the kill switch has been pulled, so a removed permission or a deactivated user takes effect on the live token from the next query. A query that is already running completes on its own snapshot, and what has already been shown stays shown. The access token lifetime is a deliberate choice, and where the organization or the user has set a session limit, the database also looks up the session on every call and rejects the token when the session is gone or too old. The user and the organization also have a kill switch that stops all further lookups at once.

I test logout, expiry and deactivation with tokens from the ordinary sign-in flow, for test users in staging: sign in, perform the action, try the old token again.

Cost and abuse

AI costs money per call, and a loop that gets out of control can cost a lot before anyone notices. Every request has caps on length, tool rounds, response size and time. Every user and every organization has caps that are checked in the database before the model is called, and the managed service has monthly quotas with a soft warning before the hard stop. The number of new organizations per unit of time is capped too, so throwaway accounts cannot burn through resources on trial periods.

Quota is reserved atomically before the call, with a single conditional statement that succeeds only if there is room, and the per-organization cap is serialized with a lock. Two concurrent messages therefore cannot both pass before the counter is updated. Quota is charged per user message, because one message can lead to several model rounds, and "X calls per month" would otherwise mean far fewer conversations than the customer thinks. Rounds, tokens and price are tracked separately in the log. Because length, the number of rounds and response size are capped, every message has a maximum cost, so the quota per message also caps the cost. In generic form, the reservation looks like this:

-- Reserve one unit. Nothing is written if the cap is zero or already reached.
insert into usage_counter (tenant_id, period, used)
select :tenant_id, :period, 1
 where :quota > 0
on conflict (tenant_id, period) do update
   set used = usage_counter.used + 1
 where usage_counter.used < :quota
returning used;
-- No row returned: the cap is reached, and the model is not called.

On top of this sits an automatic emergency stop (circuit breaker). A scheduled job compares total usage against caps, budget and previous peak days, stops all AI on unusual usage until a human reopens it, and alerts operations. The per-organization caps are set well below the level that trips the circuit breaker, so a single customer cannot shut off AI for the others. The circuit breaker is the last safety net against systemic failures and is not an absolute cost ceiling, because costs can accrue between two runs. If the user drops the connection, the call to the model is aborted where the platform and the vendor support it.

Every layer has a deliberate choice between fail open and fail closed, and when a defense cannot do its job, it has to say so with a log line and an alert that describes what is happening. That applies to the counting itself as well. A circuit breaker that counts log rows is blind the moment log writes fail, so a row that cannot be written must itself be treated as an alarm.

Red teaming

Type of failure and severity are two different things

Boundary tests ask whether the attacker can get data they have no right to, even if the model obeys completely. Behavioral tests ask whether the model behaved as it should.

The type of failure still does not tell the whole story about how severe it is. An assistant that answers like a pirate is a behavioral failure with low severity. Bad advice with safety consequences, or an incorrect status message saying a required check has been completed, does not break any access control either, but it can be critical, because integrity weighs as much as confidentiality. A boundary breach is always treated as critical, but a behavioral failure can be too, and then it blocks a release in the same way.

I weight threats by both severity and likelihood. Data leakage across organizations is the most severe, but unlikely when the boundary sits in the database. Most likely is a colleague who writes an instruction to answer like a pirate in a field the assistant often reads. No data leaks, but the product looks manipulable, so the tests cover that too.

Three levels of testing

The oracle that decides whether a test passed can be deterministic (a specific string in the response or not) even though the outcome varies from run to run when the attack is sent to a real model. That is why I test the boundary at three levels:

  1. Direct authorization tests. The database and the API are called without a model: unauthenticated, as another organization, with a deactivated account. What gets tested is derived from the database catalog, so new tables and functions are included automatically.
  2. A simulated compromised model. Instead of trying to get a real model to do something forbidden, I have a simulated model try every time: ask for tools it was not given, send invalid arguments, supply ids from another organization. This is the test that shows whether the boundary holds independently of the model, because it does not depend on the attack succeeding against the model.
  3. Red teaming with a real model. A targeted set of attack scenarios is run against the assistant to see how the model actually behaves. The test covers this system and is not a full red-team evaluation of the model. It says something about the behavioral defenses under the test conditions and does not prove what is impossible.

Three levels of testing: authorization tests without a model, a simulated hostile model, and red teaming against a real model.

Figure 7The bottom two levels test the architecture no matter what the model does. The top one shows how the model actually behaves.

The attack categories are anchored in publicly known techniques, including the OWASP list for LLM applications. I keep the concrete test prompts out of this text.

To give a sense of scale: the boundary is covered by around 1,800 automated database tests, and the network-facing tests have so far run more than 45,000 checks as an unauthenticated user, as a user with narrow access and across organizations. The scenarios against the real model span several attack classes, and no canary token has leaked in any run.

Canary tokens and other oracles

Canary tokens are unique strings that cannot be guessed. They are planted in protected data in synthetic test organizations: in sensitive fields and in a neighboring organization. The attacks ask for exactly these. If a canary token shows up anywhere in the response, that is a confirmed boundary breach, and the oracle normalizes the response first. A canary token split by invisible characters or encoded in ways the normalization recognizes is found as well. The absence of a canary token, however, does not prove that nothing leaked, because the model may have summarized or paraphrased the content. The response is also the last place a leak shows. Data that has reached the model has crossed a boundary even if it never appears in the response, which is why the boundary itself is tested at the two lower levels, without going through the response.

Instruction extraction is caught the same way, with a fixed, harmless marker in the instructions that must not appear in any response. For behavior, pattern oracles look for a URL in the response, an order issued in someone's name, a persona, or a safety recommendation the model phrased on its own instead of taking it from the data. When a non-critical test fails, a model can write a short explanation for the test report, but inputs and outputs are checked for canary tokens first, and a boundary breach is never sent to a model for assessment.

Where the tests run

All the testing I describe, not just red teaming, runs outside production and on fictitious data: in the staging environment, and destructive tests against a short-lived local database. The test organizations are permanent, clearly labeled and synthetic, and a secret that exists only in the test environment prevents the test against the assistant from running anywhere else. An automated security scanner tests the network surfaces as an unauthenticated user and as an administrator in another organization.

It is a practice I would recommend to others: red teaming belongs in a separate environment with fictitious data, not in production. If an attack succeeds against real data, it is no longer just a test result but a personal data breach. It has to be documented, and reported to the data protection authority within 72 hours, unless the breach is unlikely to result in a risk to the rights and freedoms of the people concerned. Using real personal data for testing also requires its own purpose and legal basis.

Model responses are not stored, only the verdict. The tests against a real model run after changes to the AI surface, on model changes and on a fixed schedule, because behavior can change silently even behind a version-pinned model id. The deterministic tests run every time the database changes. Confirmed findings become regression tests.

The tests have to be tested

Several of the most important lessons were about the tests. One test forbade a specific piece of contact information in the response, while the policy requires it to appear there verbatim. The false red undermined trust in the test overview just as much as a false green would have.

In a local environment, test users can lack an organization membership, and then every access check denies trivially, so the tests look clean without testing anything. Everything was green. Nothing was being tested. The destructive tests have a positive control that checks that the legitimate action succeeds.

Once, a "critical" finding was an error code that happened to appear as digits in a timestamp. Since then I verify every critical finding before treating it as real. When the response gets a new channel, for example a new card type, the leak check has to cover it in the same change.

Privacy and the EU AI Act

What follows is a developer's reading of the rules, and the assessments should be checked by a lawyer. The EU AI Act is being phased in. In the EU, the prohibitions in art. 5 have applied since February 2025, and the transparency obligations in art. 50 have applied since August 2026. Norway's implementation is in progress, and the GDPR applies regardless. I built to the transparency obligations from the start, because it was cheap then and expensive to retrofit: the assistant states clearly that it is an AI, and write actions have a human in the loop. The latter is a product choice, not human oversight in the regulation's sense, which applies to high-risk systems.

Some boundaries are product choices that go further than the law requires. AI must not evaluate or rank individual employees, and there is no emotion or sentiment analysis of employees' speech or text. The assistant should help people do their jobs, not turn the people doing those jobs into another source of behavioral data. Art. 5 prohibits emotion recognition in the workplace, except for medical or safety reasons. The regulation defines it as inference from biometric data such as face or voice, so text analysis falls outside, and it sets strict requirements for more of this area. I have still chosen to keep the whole area out, even where it could have been lawful with the right documentation.

That a user may read personal data does not by itself mean the organization may process it with an AI service. That requires its own purpose and legal basis. Nor does human approval document compliance on its own. The technical part has to be accompanied by a sub-processor chain, a record of processing activities and, where the processing is likely to involve high risk, an impact assessment.

Not everything needs a language model

A problem that can be described with rules is one I solve best without a model: scheduling by fixed criteria, calculations, deadlines and a voice-driven registration that interprets what the user says step by step. A deterministic solution gives the same answer for the same input, has no per-call model cost, is not exposed to prompt injection and is easier to test. When the voice control did not understand users well enough, I measured what they actually said and made the interpretation more tolerant, instead of adding a model. The safest AI call is the one you don't need to make.

Checks that catch the next bug

I turn most lessons into automated checks. The goal is that the next developer does not have to remember them: the build pipeline does. An access rule is tested against the database where it is enforced, never against a hand-written copy in a test double. When I find a bug, I ask how the next bug of the same kind will turn red. A missing permission check in one AI feature, found in staging before production, became a check that requires it in all of them. For patterns that cannot be fixed all at once, a check counts the occurrences and only accepts that the number goes down.

A security test counts as done only once I have seen it fail against a deliberately broken state, and the checks in the build pipeline have self-tests with sabotaged copies. A test that attempts the action carries more weight than one that scans the source for a pattern. Before a new security-critical surface goes into use, it is reviewed separately, without build context, and each finding has to be proven with a failing test. That gives a fresh reading of the code, but it does not replace an external security audit.

I have checked every security claim in this text against the code. That a log lacks a column for the organization does not mean it cannot be linked to an organization, and "one entry point" has to hold for every single call.

What the architecture does not solve

The architecture moves a lot of risk from the model to controls that can be tested. The goal is not to stop the model from being manipulated, but to limit what a manipulation can lead to: authorization is enforced independently of the model. Whether an action matches what the user wanted, whether the answer is correct and where information may go next are separate problems that the architecture only partly solves. Some risk therefore remains in any system that gives a language model access to organization data.

  • Hallucinations. A model can state something wrong with great confidence, even when the data is correct. Cards built from the data and references to the source reduce the problem without eliminating it.
  • Authorized misuse. A user with legitimate access can find and combine what they are allowed to see, faster than before. The access control sees nothing wrong. Narrow tools slow this down, but what the user is allowed to see, they can still ask for. Nor does a cap per tool call by itself limit how much is gathered over one or more conversations.
  • Leakage after legitimate disclosure. What has been shown can be copied, photographed or forwarded.
  • Semantic leakage. A response can reveal something without repeating it: an aggregate, a paraphrase or a hint. Two aggregates over groups that differ by one person can be subtracted from each other even if both are above the minimum group size. Canary tokens and pattern oracles only see what they recognize.
  • Vendor risk. The model and cloud vendors can change behavior, terms or offerings, or be compromised themselves. EU residency also only says where the data is processed. Which country's law the vendor is subject to is a separate question. Version pinning, agreements and regular reassessment limit the risk, but code cannot enforce it away.

The order has been the same from the start: the boundary and the control first, then the feature. That costs time, but it has meant that the findings from red teaming and reviews have mostly concerned the defense-in-depth layers, not the primary boundary.

The most useful change in my own thinking has been to stop treating the model's behavior as the foundation of security. I still spend time getting it to behave, but more time deciding what happens when it doesn't.

A secure AI assistant, then, is not one where the model never follows a hostile instruction, but one where following it grants no new authority. Authorization has to be enforced outside the model, intent and information flow have to be handled separately, and every boundary has to be tested as if the model has already failed. That also pays off over time: better models bring better features without needing more trust.

Sources

Vegard Cowie Jørgensen

Software architecture, security and AI-assisted development, with a particular interest in systems whose correctness and security do not depend on AI behaving as expected.

Back to the front page · GitHub

Published