Database Security, Privacy, and EthicsIntroductionDatabases are among an organisation’s most valuable assets because they store information about customers, employees, transactions, products, health, finances, and operations. Their value also makes them attractive targets for misuse. A database may be compromised through stolen passwords, excessive privileges, insecure applications, accidental disclosure, insider abuse, weak backups, or poorly managed cloud services. Database security is therefore broader than placing a password on a database server. It includes identity management, authorization, encryption, monitoring, secure development, backup protection, incident response, and governance. Privacy concerns how personal information is collected, used, shared, retained, and deleted. Ethics asks whether data practices are fair, responsible, transparent, and respectful of human rights, even when a practice is technically legal. For full-stack developers, security and privacy are not optional database administration topics. Application code determines which queries are executed, which users can access them, and whether sensitive values appear in logs or interfaces. Secure database design must therefore be integrated with application architecture from the beginning. Learning ObjectivesBy the end of this chapter, you should be able to: - Distinguish authentication, authorization, accounting, and auditing.
- Design roles and permissions according to least privilege.
- Explain encryption in transit, encryption at rest, hashing, and tokenization.
- Apply secure secrets management and parameterized database access.
- Describe privacy principles, consent, retention, masking, and data-subject rights.
- Evaluate ethical risks involving surveillance, bias, secondary use, and automated decisions.
- Recommend practical controls for a small full-stack application.
1. The Security ObjectivesA useful starting point is the CIA triad: - Confidentiality: only authorized people and systems can view data.
- Integrity: data remains accurate, complete, and protected from unauthorized alteration.
- Availability: authorized users can access systems and data when needed.
These objectives often conflict. Strong encryption and extensive checking can increase processing time. Broad availability can increase exposure. A sound design balances business requirements with acceptable risk. Security also includes accountability and authenticity. Accountability means actions can be traced to responsible identities. Authenticity means that a user, service, or message is genuine. A database system that prevents unauthorized reading but cannot reveal who changed a payment record has incomplete security. A basic risk model is: Risk = Likelihood × Impact Likelihood describes how probable an adverse event is, while impact describes the harm if it occurs. This is a qualitative or semi-quantitative planning model, not a universal physical law. Organisations may use scales such as 1–5 for each variable, but the scales must be defined consistently. A high-impact event with moderate likelihood may deserve priority over a frequent event causing minor inconvenience. 2. Authentication and IdentityAuthentication verifies who or what is requesting access. Authorization determines what that identity may do. Accounting records usage, and auditing examines those records and controls to detect inappropriate activity. Authentication factors are commonly grouped into: - Something the user knows, such as a password.
- Something the user has, such as a hardware token or authenticator application.
- Something the user is, such as a fingerprint.
Multi-factor authentication (MFA) combines factors from different categories. Two passwords are not genuine MFA because both are knowledge factors. MFA substantially reduces the usefulness of stolen passwords, although it does not eliminate phishing, session theft, or compromised devices. Passwords should not be stored in plaintext. A password-verification system stores a salted, slow password hash produced by a password-hashing algorithm such as Argon2id, bcrypt, or scrypt. A salt is a unique random value stored with the resulting hash. It prevents identical passwords from producing identical stored values and makes precomputed attacks less effective. Hashing is one-way in intended use; encryption is reversible with a key. Database accounts should be linked to people or managed services rather than shared among developers. Shared accounts undermine accountability and make offboarding difficult. Service accounts should have narrowly defined permissions, non-interactive use where possible, and controlled credential rotation. 3. Authorization, Roles, and Least PrivilegeAuthorization may be implemented through discretionary access control, role-based access control (RBAC), attribute-based access control (ABAC), or combinations of these models. In RBAC, users receive roles and roles receive permissions. For example, an online shop might define: | Role | Typical permissions |
|---|
| Customer | Read and update own profile; create orders | | Support agent | Read customer service data; no payment-secret access | | Inventory staff | Read and update stock records | | Analyst | Read approved, masked reporting views | | Database administrator | Maintain infrastructure; access subject to monitoring | | |
A role should represent a work responsibility, not a person’s status or technical convenience. The principle of least privilege grants only the permissions required for an approved task, for only as long as required. Related practices include separation of duties, privileged-access approval, time-limited elevation, and periodic access reviews. Permissions should be explicit. A web application should normally connect with an application account that cannot create database users, drop production tables, or read unrelated administrative tables. Development, testing, and production environments must use separate credentials and preferably separate accounts and networks. A common failure is granting broad permissions because troubleshooting is easier. This creates excessive blast radius: if the application is compromised, the attacker inherits all permissions of its account. Least privilege reduces, but does not eliminate, this risk. 4. SQL Injection and Secure Database AccessSQL injection occurs when untrusted input changes the structure of a query. For example, concatenating a supplied username into a SQL string can allow an attacker to insert operators or additional commands. The primary defence is a parameterized query or prepared statement. The SQL structure is supplied separately from data values. Conceptually: SELECT id, password_hash
FROM users
WHERE email = ? The email value is then bound as data rather than inserted into the SQL text. Object-relational mappers can help, but they do not make every query automatically safe; raw SQL, unsafe filtering, and dynamic table or column names still require care. Input validation, allowlists, suitable database permissions, and monitoring provide additional layers. Escaping alone is fragile because its correctness depends on database dialect, character encoding, and context. It should not replace parameterization. Error messages shown to users should not reveal SQL statements, table names, credentials, or stack traces. 5. Encryption, Hashing, Masking, and TokenizationEncryption in transitConnections between applications and database servers should use authenticated transport encryption, normally TLS configured according to current organisational standards. Certificate validation matters: encryption without authenticating the server can permit interception by an impostor. Encryption at restEncryption at rest protects database files, disks, snapshots, and backups if storage is stolen or accessed outside the database service. It does not automatically protect data from an application account that is already authorized to read it. Database-level or column-level encryption may be needed for particularly sensitive fields. Key managementEncryption security depends heavily on key management. Keys should be separated from encrypted data where practical, protected by a key-management service or hardware security module for higher-risk systems, rotated according to policy, and recoverable through controlled procedures. Losing the key can make legitimate data permanently unreadable; allowing every administrator to access the key defeats the intended separation. Hashing and tokenizationHashing is appropriate for verifying passwords and, in some cases, creating integrity evidence. It is not suitable when the original value must be recovered. Tokenization replaces a sensitive value with a token and stores the mapping in a protected system. It is often useful for payment or identity workflows. Unlike encryption, a token may have no mathematical relationship to the original value. Data maskingMasking reduces exposure when full values are unnecessary. A customer-service screen might show only the final four digits of a card-like identifier. Static masking creates a transformed copy for testing or reporting; dynamic masking changes what a user sees while preserving the underlying value. Masking is not a substitute for authorization: a poorly protected system may still expose the original data through another query or export. 6. Auditing, Logging, and MonitoringAn audit trail should answer: who performed an action, what action occurred, which object was affected, when it occurred, from where, and whether it succeeded. Important events include login failures, privilege changes, access to sensitive records, exports, schema changes, deletion, and changes to audit settings. Logs should be tamper-resistant, time-synchronized, access-controlled, and retained according to policy. They must not contain passwords, private keys, session tokens, or unnecessary personal information. A log that records every event without a review process can create cost without improving security. Monitoring seeks meaningful signals, such as an unusual export volume, access from an unexpected region, repeated authorization failures, or a service account querying administrative tables. Alerts require triage procedures, ownership, and escalation. Audit systems themselves must be protected because an attacker may attempt to disable or alter them. Backups are part of security. They should be encrypted, tested through restoration exercises, protected from ransomware through appropriate isolation or immutability, and governed by a defined recovery plan. A backup that cannot be restored is not a reliable backup. 7. Secure Secrets ManagementSecrets include database passwords, API keys, certificates, encryption keys, and connection strings. They should not be committed to source-control repositories, embedded in frontend code, printed in logs, or placed casually in shared documents. A secrets manager or protected deployment mechanism should provide access control, auditability, rotation, and environment-specific values. Applications should receive only the secrets they require. Rotation must be designed so that valid services can transition without avoidable outages. Developers should scan repositories and build artifacts for accidental exposure and revoke any secret that may have been disclosed. A .env file may be convenient for local development, but it is not automatically secure. Production secrets require stronger controls, restricted operating-system permissions, and monitored delivery. 8. Privacy Principles and Data GovernancePrivacy is not merely secrecy. It concerns appropriate control over information about identifiable or identifiable individuals. Common privacy principles include: - Purpose limitation: collect and use information for specified legitimate purposes.
- Data minimization: collect only what is reasonably necessary.
- Accuracy: keep information correct and provide ways to correct it.
- Storage limitation: retain information no longer than justified.
- Transparency: explain collection, use, sharing, and rights clearly.
- Security: protect information against unauthorized access and loss.
- Accountability: document decisions and demonstrate compliance.
A privacy notice should be understandable and specific. It should identify categories of data, purposes, recipients or recipient types, retention, choices, and contact mechanisms. Consent, where used, should be informed, specific, freely given, and withdrawable. Consent is not always the only lawful or ethical basis for processing; contractual necessity, legal obligations, and legitimate organisational purposes may apply depending on the jurisdiction. Organisations must not disguise optional processing as necessary service access. Privacy impact assessments help identify risks before deploying a system. They should consider sensitive categories, vulnerable populations, data flows, recipients, retention, security controls, and possible effects on individuals. Data-subject rights vary by law but commonly include access, correction, deletion in applicable circumstances, restriction or objection, and portability. A database design should support these rights through identifiable records, documented data lineage, controlled export, deletion workflows, and procedures for data held in backups and third-party systems. 9. Retention, Deletion, and Data LifecycleData should have a lifecycle: collection, active use, sharing, archival where justified, and secure deletion. Retention must be based on a documented business, legal, or operational requirement rather than the fact that storage is inexpensive. Deletion is more complex than removing one row. Copies may exist in indexes, caches, exports, backups, logs, replicas, and analytics platforms. A retention schedule should identify systems of record, copies, responsible owners, exceptions such as legal holds, and deletion verification. Anonymization may permit continued statistical use, but it must be assessed carefully because combining supposedly anonymous data with other sources can permit re-identification. 10. Ethical Use of DataLegal compliance is a minimum standard, not a complete ethical analysis. Ethical data use asks whether people would reasonably expect the practice, whether power is distributed fairly, and whether harms fall disproportionately on particular groups. Important ethical risks include: - Secondary use: using data collected for one purpose to make unrelated inferences.
- Surveillance: monitoring people more extensively than necessary.
- Discrimination: data or models producing systematically unfair outcomes.
- Opacity: individuals being unable to understand or challenge decisions.
- Function creep: gradual expansion from a narrow purpose to broad monitoring.
- Re-identification: combining datasets to identify supposedly anonymous people.
AI systems intensify these risks because training data may encode historical bias and automated outputs may be treated as objective. Developers should document data provenance, test outcomes across relevant groups, provide human review for high-impact decisions, and avoid collecting data merely because it might later be useful. Explanations should be proportionate to the decision’s impact. Ethical governance benefits from data owners, security officers, privacy specialists, developers, and affected stakeholders. A data ethics review should ask: What benefit is intended? Who might be harmed? Is collection necessary? Are less intrusive alternatives available? Can individuals challenge errors? What happens if the system fails? 11. An Applied Case: Community Learning PlatformBackgroundThis illustrative case concerns a small online learning platform that stores learner profiles, assessment results, payment references, support messages, and login records. ProblemThe first version uses one database administrator account for the web application. Passwords are stored using a fast general-purpose hash without unique salts. Support staff can query the entire learner table, and detailed SQL errors appear in the browser. Backups are unencrypted and retained indefinitely. The organisation plans to use learning activity data to rank learners for employment opportunities. AnalysisThe shared administrator account destroys accountability and creates severe blast radius. Excessive support access violates least privilege. Password storage is vulnerable to offline guessing. Error disclosure assists attackers. Unencrypted, indefinite backups create privacy and security exposure. Finally, using educational activity for employment ranking is a secondary use with potential fairness and transparency problems. Approach and solutionThe platform creates separate application, reporting, support, and migration accounts. The application account receives only required permissions; support users receive approved views that mask sensitive fields. MFA is enabled for privileged users. Passwords are rehashed using a modern password-hashing function with unique salts when users next authenticate, with a controlled reset process for higher-risk accounts. Prepared statements replace query concatenation. TLS protects database connections. Backups are encrypted, access-controlled, tested for restoration, and assigned a retention schedule. Secrets move from configuration files to a secrets manager. Security events are sent to protected logs, and alerts are configured for unusual exports and privilege changes. The employment-ranking proposal undergoes a privacy and ethics review. The organisation defines a specific purpose, obtains appropriate authorization or another valid basis where required, tests for disparate effects, explains the process, and provides a human review and appeal route. If the use cannot be justified fairly, it is rejected. OutcomeThe revised design reduces unauthorized access, improves accountability, limits exposure during application compromise, and makes privacy obligations operational. It also demonstrates that technical controls cannot resolve an ethically unjustified purpose. Learning points- Security architecture must include application accounts, not only database infrastructure.
- Masking and views can make least privilege practical.
- Backup and secret-management controls are part of database security.
- A technically possible use of data may still be inappropriate.
- Governance must address both security incidents and harmful ordinary operations.
12. Implementation Checklist for Full-Stack ProjectsBefore deployment, a development team should be able to answer yes to most of the following: - Are users authenticated through an appropriate identity mechanism and MFA for privileged access?
- Are application queries parameterized?
- Are production and development credentials separated?
- Does each service have only the permissions it needs?
- Are sensitive connections encrypted and certificates validated?
- Are passwords hashed with a suitable password-hashing function and unique salts?
- Are secrets absent from source control and logs?
- Are sensitive fields masked in interfaces, reports, and test data?
- Are important access and administrative events audited?
- Are backups encrypted, access-controlled, and restoration-tested?
- Is there a documented purpose, consent or other valid basis, retention period, and deletion process?
- Can individuals correct or obtain their data where applicable?
- Has the team considered fairness, transparency, accessibility, and unintended use?
- Is there an incident-response plan with assigned responsibilities?
Challenges and LimitationsNo control is perfect. Encryption does not stop an authorized application from leaking data. MFA can be defeated through social engineering. RBAC can become difficult to maintain when roles proliferate. Audit logs can create privacy risks of their own. Anonymization may fail when datasets are combined. Deletion may be constrained by legal holds, immutable backups, or technical dependencies. Security also involves usability and cost. Excessive friction can lead users to bypass controls, while underfunded monitoring may produce unreviewed alerts. Effective governance is therefore iterative: identify risks, select proportionate controls, test them, review evidence, and improve the design as threats and purposes change. Chapter SummaryDatabase security protects confidentiality, integrity, availability, authenticity, and accountability. Authentication establishes identity, while authorization determines permitted actions. Roles, least privilege, separation of duties, and periodic access reviews reduce the damage caused by misuse or compromise. Parameterized queries are the primary defence against SQL injection. Encryption protects data in transit and at rest, but keys require careful management. Hashing is appropriate for password verification, whereas tokenization and masking reduce exposure when complete values are unnecessary. Auditing, monitoring, protected logs, secure backups, and secrets management make security observable and operational. Privacy requires purpose limitation, minimization, transparency, accuracy, retention control, security, and accountability. Consent must be meaningful where relied upon, and data-subject rights should be supported by system design. Ethical analysis goes beyond legality by considering fairness, power, secondary use, surveillance, bias, and the ability to challenge decisions. Secure database practice is therefore both a technical discipline and a governance responsibility. Key TermsAuthentication: Verification of a user or system identity. Authorization: Determination of which actions an authenticated identity may perform. Auditing: Examination and review of records and controls to establish accountability. Availability: The property that authorized users can access systems and data when needed. Confidentiality: Protection against unauthorized disclosure. Data masking: Transforming displayed or copied data to conceal sensitive values. Data minimization: Collecting and processing only data necessary for a defined purpose. Encryption: Reversible transformation of data using a cryptographic key. Hashing: One-way transformation commonly used for password verification or integrity evidence. Least privilege: Granting only the permissions necessary for an approved task. MFA: Authentication using factors from at least two different categories. Parameterized query: A query whose structure and values are supplied separately. Privacy impact assessment: A structured evaluation of privacy risks before or during a project. Purpose limitation: Restricting data use to specified, legitimate purposes. RBAC: Role-based access control, in which permissions are assigned to roles and users receive roles. Retention: The planned period for keeping data. Risk: The combination of the likelihood and impact of an adverse event. Secrets management: Controlled storage, delivery, rotation, and auditing of credentials and keys. Tokenization: Replacing a sensitive value with a separately managed token. Review QuestionsShort Answer Questions- Distinguish authentication from authorization.
- What is the principle of least privilege?
- Why should passwords not be stored in plaintext?
- State two purposes of database auditing.
- What is data minimization?
Long Answer Questions- Explain how RBAC, separation of duties, and periodic access reviews work together.
- Compare encryption, hashing, masking, and tokenization, giving one suitable use for each.
- Describe a secure approach to database backups and secrets management.
- Explain the privacy principles of purpose limitation, transparency, accuracy, and storage limitation.
- Discuss why legal compliance alone does not guarantee ethical data use.
Analytical / Application Questions- A reporting service has permission to read every production table, although it uses only three columns from two tables. Analyse the risk and propose a revised authorization design.
- A company wants to use customer support conversations to train an unrelated recommendation system. Evaluate the proposal using purpose limitation, consent, minimization, retention, and ethical considerations.
- A developer reports that a database password was committed to a public repository for two hours. Construct an incident-response sequence, including containment, investigation, credential rotation, notification considerations, and preventive controls.
Multiple Choice Questions with AnswersQuestion 1Which statement best distinguishes authentication from authorization? A. Authentication verifies identity; authorization determines permitted actions. B. Authentication encrypts data; authorization backs it up. C. Authentication records events; authorization deletes logs. D. Authentication masks data; authorization hashes passwords. Correct Answer: A. Authentication verifies identity; authorization determines permitted actions. Question 2Which control most directly prevents SQL injection in an application query? A. Displaying detailed SQL errors B. Using a parameterized query C. Granting the application administrator privileges D. Storing SQL statements in a browser cookie Correct Answer: B. Using a parameterized query Question 3What is the main purpose of a unique password salt? A. To make passwords reversible B. To allow passwords to be stored in plaintext C. To prevent identical passwords from producing identical stored hashes D. To replace multi-factor authentication Correct Answer: C. To prevent identical passwords from producing identical stored hashes Question 4Which example best demonstrates least privilege? A. Every developer uses the production administrator account B. A reporting service can read only its approved reporting views C. Support staff can alter database permissions D. A customer can read all customer records Correct Answer: B. A reporting service can read only its approved reporting views Question 5Which technique is most appropriate when a system must verify a password without recovering its original value? A. Password hashing B. Database replication C. Data masking D. Plaintext encoding Correct Answer: A. Password hashing Question 6Which privacy principle requires collecting only information reasonably necessary for a defined purpose? A. Availability B. Data minimization C. Separation of duties D. Authentication Correct Answer: B. Data minimization Question 7Which statement about encryption at rest is correct? A. It automatically prevents an authorized application from reading data. B. It protects stored data such as database files and backups from certain storage-level exposures. C. It eliminates the need for access control. D. It is the same as password hashing. Correct Answer: B. It protects stored data such as database files and backups from certain storage-level exposures. Question 8Which item should generally not be placed in application logs? A. A timestamp for a failed login B. An event identifier for a privilege change C. A password or private encryption key D. The result status of a database operation Correct Answer: C. A password or private encryption key Question 9Why is an untested backup insufficient as a recovery control? A. Backups are never useful for availability B. A backup may not be restorable or complete when needed C. Testing backups always destroys the original database D. Encryption prevents all restoration Correct Answer: B. A backup may not be restorable or complete when needed Question 10Which question is primarily an ethical question rather than a purely technical one? A. Is the database connection protected with TLS? B. Does the application use prepared statements? C. Would using learner activity for employment ranking be fair and reasonably expected? D. Are backups stored in a separate region? Correct Answer: C. Would using learner activity for employment ranking be fair and reasonably expected?
|