Every pipeline, notebook, model, report and application we build touches client or company data. A single hard-coded password, an unchecked input or a publicly shared dashboard can expose that data. Secure coding means building safeguards in from the first line, not adding them after an incident.
This training is mandatory for everyone in the Data Science and AI, Data Engineering, Application Development and Business Intelligence teams. It gives us a shared, practical baseline for writing code, pipelines, models and reports that protect client and company data. Where we process personal data of people in India, the Digital Personal Data Protection Act, 2023 also requires reasonable security safeguards.
The content follows widely used public standards, so what you learn here matches what clients, reviewers and security tools expect.
Passwords, API keys, tokens, connection strings and private keys must never be written into source code, notebooks, configuration files in Git, report files or chat messages. Hard-coded credentials are a well-known weakness (CWE-798). Load them at run time from an approved secret store or a platform identity.
API_KEY = "sk_live_51H8xQ2..."
db = connect("postgres://etl:Pa55w0rd@prod-db/sales")import os
API_KEY = os.environ["PAYMENTS_API_KEY"]
db = connect(secrets.get("sales-db-conn"))If a secret leaks: revoke or rotate it immediately, then tell the Information Security team. Deleting the line in a new commit is not enough, because the old value remains in Git history and in every clone.
Most security problems come from a small set of repeated mistakes. These habits apply to every team, whatever language or tool you use.
Define what valid input looks like, such as its type, length, format and range, and reject everything else. Blocklists of "bad characters" are always incomplete. Validate on the server or in the pipeline, because client-side checks can be bypassed.
Use parameterised queries and safe APIs so that input is always treated as data, never as part of a command. This one rule prevents SQL injection, command injection and many other injection attacks.
Software supply chain failures are now third in the OWASP Top 10. In September 2025 a self-replicating worm called Shai-Hulud compromised hundreds of npm packages. It stole developer and CI tokens during installation and used them to publish more infected packages.
Log security events such as failed logins, permission changes and data exports, with a timestamp and the user or service involved. The 2025 OWASP list renamed this category to "Logging and Alerting Failures" because logs nobody watches do not stop attacks. Make sure important events raise an alert to a person. Never log passwords, tokens, session IDs, full card numbers, Aadhaar or PAN numbers, or other personal data.
Every merge to a main branch needs a peer review that includes the security checklist. Automated scanning, such as Semgrep, SonarQube or CodeQL, supports reviewers but does not replace them.
Treat AI-generated code like code from an unknown contributor: read it, test it and review it. Assistants sometimes suggest packages that do not exist. Attackers register those invented names and fill them with malware, an attack called "slopsquatting". Before installing anything an assistant suggests, confirm the package is real, established and the one you meant. Only use company-approved AI tools, and never paste confidential code, credentials or client data into tools that are not approved.
Report, don't hide. If you find a vulnerability or think data may have been exposed, report it to Information Security straight away. Early reporting is always treated as the right thing to do.
Data scientists often work with the richest and most sensitive data in the company. Sensitive information disclosure is the second-ranked risk in the OWASP Top 10 for LLM Applications. The safest data is the data you never copy.
Do not download production extracts to laptops, personal drives, USB sticks or personal cloud accounts. Work inside the approved platform, where access is controlled and logged.
A notebook saves every printed dataframe, chart and error message inside the file. Committing or emailing it shares that data too. Clear outputs before committing, or use a tool such as nbstripout, and add data files such as csv, parquet and xlsx to your .gitignore.
df = pd.read_sql("SELECT * FROM customers", conn)
df.head(50) # 50 real customers saved in the .ipynbcols = ["customer_token", "segment", "tenure_m"] df = pd.read_sql(q_selected_cols, conn) df.shape # inspect structure, not people
Models can memorise and repeat training data, especially language models fine-tuned on documents or chat logs. A membership inference attack tries to find out whether a specific person's record was in the training set, and model inversion tries to reconstruct training data from outputs.
Pre-trained models, datasets, notebooks and libraries all come from outside the company. Some model file formats can run code when they are loaded, so opening an untrusted model can be as dangerous as running an untrusted program.
Python's pickle format, which joblib and many model files use, can execute arbitrary commands during loading. Only unpickle files that your own team created and stored in a controlled location.
Since PyTorch 2.6, torch.load uses weights_only=True by default, which blocks arbitrary code in checkpoints. If a file fails with "Weights only load failed", do not simply switch to weights_only=False. PyTorch warns that this can lead to arbitrary code execution. Do that only for files you created or fully trust, and prefer converting them to safetensors.
trust_remote_code off. Turning it on runs Python code from the model repository on your machine.state = torch.load("weights.pt", weights_only=False)
model = AutoModel.from_pretrained(
"someone/cool-model", trust_remote_code=True)from safetensors.torch import load_file
state = load_file("weights.safetensors")
model = AutoModel.from_pretrained(
"verified-org/model", revision="3f2c9a1...",
use_safetensors=True)yaml.safe_load, never with the full loader on untrusted files.eval() or exec() on strings from data, files, users or model output.Notebook servers and Python environments are powerful and easy to misconfigure. A Jupyter server is a remote code execution service by design: anyone who can reach it can run commands as you.
jupyter lab --ip=0.0.0.0 --NotebookApp.token=''
jupyter lab --ip=127.0.0.1 # connect: ssh -L 8888:localhost:8888 user@host
Do not type passwords or keys into cells. Read them from the environment or the platform's secret store, such as Databricks secrets, or prompt with getpass so they are not saved in the file.
The OWASP Top 10 for LLM Applications 2026 lists, in order: Prompt Injection, Sensitive Information Disclosure, Excessive Agency, Supply Chain, Data and Model Poisoning, Unbounded Consumption, Misinformation, Hidden Context Exposure, Vector and Embedding Weaknesses, and Improper Output Handling. This module covers what each means when you build an application on a language model.
Text the model reads can contain instructions that override yours. Direct injection comes from the user. Indirect injection hides inside documents, emails, web pages or retrieved records. Assume the model will sometimes be fooled, and design so that a fooled model cannot do much harm.
Treat every model output as untrusted input. Never run it directly as SQL, shell commands or code. Encode it before showing it in a web page, and validate it against an expected structure.
sql = llm.generate(f"Write SQL for: {question}")
cursor.execute(sql) # model decides what runsintent = llm.classify(question, allowed=REPORTS) cursor.execute(REPORT_SQL[intent], params) # read-only role, fixed queries, bound params
System prompts, retrieved context and conversation memory can be extracted by a determined user. Never put secrets, credentials or access-control rules in them. Enforce permissions in code, not in instructions to the model.
An agent plans multi-step tasks, keeps memory and calls tools with delegated access. Excessive Agency is now third in the 2026 LLM list, and OWASP published a separate Top 10 for Agentic Applications. Its central idea is least agency: give an agent only the autonomy, tools and permissions a bounded task needs.
Model Context Protocol servers connect agents to tools and data. The OWASP MCP Top 10, still in beta, warns about tool poisoning, over-permissioned servers and unapproved "shadow" MCP servers. Use only MCP servers approved by the company, pin their versions, review their tool descriptions and requested scopes, and never store long-lived tokens in their config files.
agent = Agent( tools=[crm.all_tools, email.send, shell.run], credentials=ADMIN_TOKEN, approval="never")
agent = Agent(
tools=[crm.read_contact, email.draft],
credentials=agent_identity(scope="crm:read"),
approval={"email.send": "human"},
max_steps=15)Pipelines build a lot of SQL dynamically, from configuration files, parameters and upstream data. SQL injection is the second most dangerous weakness in the 2025 CWE Top 25. Any value that reaches a query as text can change what the query does.
Pass values as query parameters. The driver sends them separately from the SQL text, so they can never run as commands. This works in Python DB-API drivers (psycopg, pyodbc, the Snowflake connector), JDBC, and Spark SQL, which accepts named parameters.
spark.sql(
f"SELECT * FROM sales WHERE region = '{region}'")
cur.execute(
f"DELETE FROM staging WHERE batch_id = '{batch_id}'")spark.sql(
"SELECT * FROM sales WHERE region = :region",
args={"region": region})
cur.execute(
"DELETE FROM staging WHERE batch_id = %s", (batch_id,))Table and column names usually cannot be bound like values. When they come from configuration or input, check them against a fixed list of known names, then quote them with the engine's own function.
spark.sql(f"SELECT * FROM {cfg['table']}")ALLOWED = {"sales_daily", "sales_monthly"}
t = cfg["table"]
if t not in ALLOWED:
raise ValueError("unknown table")
spark.sql(f"SELECT * FROM {t}")EXECUTE IMMEDIATE ... USING with bind variables, and IDENTIFIER() for object names.sp_executesql with parameters, and QUOTENAME() for identifiers.format() with %I for identifiers and %L for literals, or EXECUTE ... USING.Pipelines hold some of the most powerful credentials in the company, often with access to whole warehouses. Snowflake and Databricks have both moved away from passwords and personal tokens for automation, and our pipelines must follow.
TYPE = SERVICE, and authenticate them with key-pair authentication, OAuth or workload identity federation. Snowflake describes workload identity federation as the preferred method for service-to-service workloads.snowflake.connector.connect( user="ETL_USER", password="Summer2024!", role="ACCOUNTADMIN", account=ACCT)
snowflake.connector.connect( user="SVC_SALES_ETL", # TYPE = SERVICE private_key_file=key_path, # from secret store role="SALES_ETL_RW", account=ACCT)
jdbc_pwd = "Pa55w0rd!" # typed into a notebook cell
jdbc_pwd = dbutils.secrets.get(scope="sales-etl",
key="warehouse-pwd")Data engineers set the access rules that every analyst, report and model inherits. Enforce them in the platform, where every client and tool has to obey them, not in each report or notebook.
-- a separate unmasked copy for "trusted" users CREATE TABLE customers_full AS SELECT * FROM customers; GRANT SELECT ON customers_full TO ROLE ANALYST;
CREATE MASKING POLICY pii_mask AS (v STRING)
RETURNS STRING ->
CASE WHEN IS_ROLE_IN_SESSION('PII_READER')
THEN v ELSE '***MASKED***' END;
ALTER TAG sensitivity SET MASKING POLICY pii_mask;Applications and pipelines connect with their own least-privilege accounts. Use the engine's row-level security (for example in PostgreSQL or SQL Server) or secure views where users share tables, and review grants regularly.
Data engineers decide where data is stored and how it moves. Those decisions set the default security for every user downstream.
Use TLS for every connection: databases, APIs, message queues and file transfers. Verify the server certificate, for example with sslmode=verify-full in PostgreSQL. Use SFTP or HTTPS, never plain FTP or HTTP. Where the platform offers it, use private connectivity such as PrivateLink so traffic does not cross the public internet.
Snowflake and Databricks encrypt stored data by default. Use customer-managed keys where policy requires them. For other databases, file shares and backups, turn on encryption yourself, including for exported files.
Tag datasets with their classification, such as public, internal, confidential or restricted, and apply access rules to match. Follow the retention schedule, and delete data, including temporary and staging copies, when it is no longer needed.
Pipelines ingest files and feeds from outside the company. Treat every incoming file as untrusted.
A malicious archive can contain paths like ../../etc/cron.d/job that write outside the target folder. This "zip slip" attack is a form of path traversal, which is in the CWE Top 25. Check every path before extracting.
zipfile.ZipFile(upload).extractall(dest)
root = os.path.realpath(dest)
with zipfile.ZipFile(upload) as z:
for m in z.namelist():
p = os.path.realpath(os.path.join(root, m))
if not p.startswith(root + os.sep):
raise ValueError("unsafe path")
z.extractall(root)Development and test environments have weaker controls. Before copying production data there, mask, tokenise or synthesise personal and confidential fields, and get the data owner's approval. Snowflake zero-copy clones and Delta clones copy the data too, so the same rule applies.
Record lineage, who ran which job and when, and what changed. Snowflake access history and Unity Catalog lineage and audit logs help you investigate incidents and show exactly who accessed or changed what.
Broken access control is first in the OWASP Top 10:2025, and missing authorisation rose to fourth in the 2025 CWE Top 25. Users must reach only the data and actions they are entitled to, whatever framework you use: Spring, Django, FastAPI, Express, Laravel, Rails or any other.
@app.get("/invoices/{id}")
def get_invoice(id):
return db.invoices.get(id)@app.get("/invoices/{id}")
def get_invoice(id, user=Depends(current_user)):
inv = db.invoices.get(id)
if not inv or inv.customer_id != user.customer_id:
raise HTTPException(404)
return invDo not bind a whole request body to a database model. Accept only the fields a user may change, through a separate input object.
user.update(**request.json) # includes "is_admin": true
data = ProfileUpdate(**request.json) # name, phone only user.update(name=data.name, phone=data.phone)
OWASP 2025 folded SSRF into broken access control. If your server fetches URLs that users supply, such as webhooks, link previews or imports, an attacker can point it at internal systems or the cloud metadata address 169.254.169.254. Allow only known destinations, block private and link-local IP ranges after DNS resolution, and do not follow redirects blindly.
Cross-site scripting, SQL injection and cross-site request forgery are the top three weaknesses in the 2025 CWE Top 25. All injection happens when untrusted input is interpreted as code.
Encode output for the context it appears in. React, Angular, Vue, Django, Jinja2, Thymeleaf and Razor escape output by default, so avoid the features that bypass them: innerHTML, dangerouslySetInnerHTML, v-html, |safe, th:utext and Html.Raw. If you must render user HTML, sanitise it with a vetted library such as DOMPurify. Add a Content Security Policy as a second layer.
el.innerHTML = "Hello " + comment.author;
el.textContent = "Hello " + comment.author;
Use parameterised queries or the ORM's query builder. Raw SQL features in ORMs are just as vulnerable if you concatenate input into them, for example Django raw(), SQLAlchemy text() without bound parameters, or string-built HQL and JPQL.
If you use cookie-based sessions, keep the framework's CSRF protection switched on for every state-changing request, and set the SameSite cookie attribute.
Avoid running shell commands with user input. If you must, pass arguments as a list without a shell, and validate them first.
subprocess.run(f"convert {name} out.pdf", shell=True)if not SAFE_NAME.fullmatch(name):
raise ValueError("bad file name")
subprocess.run(["convert", name, "out.pdf"])Authentication proves who someone is. Cryptography protects data and secrets. Both fail when teams build their own instead of using proven components.
secrets module or Java's SecureRandom.token = str(random.random()) requests.get(url, verify=False) hashlib.md5(password.encode()).hexdigest()
token = secrets.token_urlsafe(32) requests.get(url) # certificate verified argon2.PasswordHasher().hash(password)
Open-source development means most of the code you ship was written by someone else. In 2025, OWASP widened "vulnerable components" into Software Supply Chain Failures, which covers dependencies, build systems and distribution. It is now third on the list.
In September 2025 a self-replicating worm spread through the npm registry. Malicious package versions ran a post-install script that searched developer machines and CI systems for npm, GitHub and cloud tokens. It then used those tokens to publish infected versions of the victims' other packages. A second wave followed in November 2025. Any team that installed an affected version could have leaked its credentials.
npm ci, pip install --require-hashes, poetry install, Maven or Gradle dependency locking.npm ci --ignore-scripts, and allow them only for packages that need them..npmrc or .pypirc on build machines.# CI npm install - uses: some-org/deploy-action@main permissions: write-all
# CI npm ci --ignore-scripts - uses: some-org/deploy-action@8f4b7c1e... # full SHA permissions: contents: read
Security misconfiguration rose to second in the OWASP Top 10:2025. A new category, Mishandling of Exceptional Conditions, covers what happens when things go wrong.
When a check throws an error or times out, the code must fail closed: deny the request, roll back partial changes and release resources. Show users a generic message with a reference ID, and log the details on the server. Never return stack traces, SQL errors or framework versions.
try:
allowed = policy.check(user, action)
except Exception:
allowed = True # fail open
try:
allowed = policy.check(user, action)
except PolicyError:
log.exception("authz check failed ref=%s", ref)
allowed = False # fail closedLog authentication events, access-control failures, admin actions and input-validation failures, then route the important ones to alerts that a person will act on. Protect logs from tampering, and keep them as long as policy requires.
A dashboard is an application. Anyone who can open it, export from it or connect to its semantic model can see its data. When different people should see different rows or columns, enforce that in the model or the source, never with filters.
USERPRINCIPALNAME().The same principle applies under different names: user filters or entitlement tables on the data source in Tableau, access filters and access grants in Looker, and section access in Qlik. Where the tool queries a governed warehouse live, using the viewer's own identity lets the source's row and column policies, such as Snowflake row access and masking policies, protect the data.
Page filters, slicers, hidden pages and separate report copies do not protect data. Users can change them, use Analyse in Excel, or export the underlying data.
// one report page per region, // each with a fixed Region filter, // shared with all managers
// RLS role "Regional manager" on table Sales:
[Region] IN
CALCULATETABLE(VALUES(UserRegion[Region]),
UserRegion[Email] = USERPRINCIPALNAME())BI tools make sharing easy, so most BI data leaks come from oversharing rather than hacking.
Power BI "Publish to web" creates a public URL that needs no sign-in and no company account. The US CISA security baseline for Power BI says this setting should be disabled unless the organisation's mission requires it. Where an exception is approved, only specific security groups should be able to use it. Tableau Public and public links in other tools carry the same risk. For internal audiences, use apps, secure embedding or direct sharing instead.
BI administrators should review the tenant or server settings for publishing, export, external sharing, custom visuals and scripting against a written standard, and recheck them on a schedule. Changes to these settings should go through change control.
Reports connect to warehouses, databases, files and APIs. The credentials behind those connections often have far more access than any single report needs.
Snowflake is deprecating single-factor password sign-ins. Its Strong Authentication Hub specifically flags users who still sign in with only a password through applications like Power BI. Move BI connections to SSO or OAuth, or to a service user with key-pair authentication, before enforcement breaks your refreshes.
Store data source credentials in the BI service or the on-premises gateway, not embedded in workbook files that people pass around. Keep gateways patched, run them on managed servers, and limit who can administer them or add data sources.
Files such as .pbix, .twbx and Excel workbooks with Power Query can contain a full copy of the imported data and connection details. Treat them as datasets: share them through governed workspaces, not by email, chat or USB.
Reports are designed to be shared, which makes it easy to share more than intended.
Apply Microsoft Purview sensitivity labels to semantic models, reports and dashboards. Labels mark content as Confidential or Restricted, can be inherited from labelled data sources, and travel with supported exports such as Excel, PowerPoint and PDF. Data loss prevention (DLP) policies can detect sensitive information and labels on semantic models and alert administrators.
Very small counts, such as 1 or 2 people in a pin code with a particular condition, can identify individuals even without names. Aggregate to a higher level, or suppress cells below a threshold agreed with the data owner.
BI developers write code too: custom SQL, DAX, M, LookML, calculated fields, and Python or R visuals. The same secure coding rules apply.
If a report parameter or user selection is concatenated into a custom SQL statement, a user can inject SQL. Use the tool's native parameter binding, limit parameters to a fixed list of allowed values, and connect with a read-only account so any mistake has limited impact.
"SELECT * FROM sales WHERE region = '" & RegionParam & "'"
// RegionParam: list of allowed values only // filter applied in the model, or bound // as a query parameter by the connector
When values from a source system are exported to CSV or Excel, a value that starts with =, +, - or @ may run as a formula when someone opens the file. Neutralise such values, for example by prefixing them with an apostrophe, in exports and extracts you build.
Keep semantic models, SQL and report definitions in source control, for example Power BI Project (.pbip) files with Git integration, or LookML in Git, and review changes like any other code.