Project Development Using Java and Python

Chapter 10
Secure, Ethical and Governed Development

Diploma in Programming Languages (Java & Python)
Project Development Using Java and Python   •   Diploma

Secure, Ethical and Governed Development

Introduction

Software projects do not succeed merely because they compile and satisfy functional requirements. They must also protect people, organizations, information, and public trust. A program that exposes passwords, discriminates against users, violates a software licence, or cannot be used by people with disabilities is not a professionally successful product.

Secure, ethical, and governed development integrates three related responsibilities:

  • Security protects confidentiality, integrity, availability, authenticity, and accountability.
  • Ethics guides decisions about harm, fairness, consent, privacy, ownership, and professional responsibility.
  • Governance establishes the policies, roles, controls, approvals, records, and monitoring needed to make responsible practice consistent.

For Java and Python developers, these responsibilities apply throughout the software development life cycle: requirements analysis, design, implementation, testing, deployment, maintenance, and retirement.

Learning Objectives

By the end of this chapter, you should be able to:

  1. Explain common software threats and perform a basic threat-modelling exercise.
  2. Apply secure coding principles in Java and Python.
  3. Design appropriate authentication, authorization, and access-control mechanisms.
  4. Explain privacy, responsible data use, intellectual property, and open-source licensing.
  5. Identify accessibility requirements and evaluate ethical risks in software projects.
  6. Describe how organizational governance, assurance, and incident response support responsible development.
  7. Apply these ideas to a realistic project scenario.

1. Security as a Development Property

Security is a property of the complete system, not a feature added at the end. It includes the application, libraries, operating system, deployment environment, data stores, users, administrators, and operational procedures.

The traditional security objectives are often described as the CIA triad:

ObjectiveMeaningExample control
ConfidentialityInformation is disclosed only to authorized partiesEncryption and access control
IntegrityInformation and software are not changed improperlyInput validation, signatures, audit logs
AvailabilityAuthorized users can access services when neededBackups, redundancy, rate limiting

Modern systems also require authenticity—confidence that a user, service, or message is genuine—and accountability, meaning that significant actions can be attributed to an identity and investigated.

Security requirements should be stated as testable requirements. “The system must be secure” is not testable. “After five failed login attempts within ten minutes, the account is temporarily locked and the event is logged” is more precise, although the time and threshold must be justified by risk analysis.

Defense in depth and least privilege

Defense in depth uses multiple independent controls. For example, a database may be protected by network segmentation, encrypted connections, strong authentication, database permissions, application authorization, monitoring, and backups. No single control is assumed to be perfect.

Least privilege gives each user, process, and service only the permissions necessary for its legitimate task. A web application that only reads product data should not use a database account capable of deleting every table.

Other foundational principles include:

  • Secure defaults: the safest practical configuration is used automatically.
  • Fail securely: failures should not disclose secrets or grant access.
  • Complete mediation: authorization is checked whenever a protected resource is accessed.
  • Separation of duties: sensitive actions require different people or roles where practical.
  • Economy of mechanism: simpler security mechanisms are easier to review and maintain.
  • Psychological acceptability: controls should be usable; otherwise users may bypass them.

2. Threat Modelling

Threat modelling is a structured way to identify what can go wrong, who may cause harm, how an attack could occur, and which controls reduce the risk. It should begin during requirements and be revisited when architecture or dependencies change.

A practical process is:

  1. Define scope and assumptions. Identify users, systems, data, trust boundaries, and excluded components.
  2. Identify assets. Examples include credentials, personal information, source code, payment records, and service availability.
  3. Draw data flows. Show processes, data stores, external actors, and connections.
  4. Identify threats. Consider misuse, accidental failure, malicious insiders, external attackers, and supply-chain compromise.
  5. Estimate risk. Consider likelihood, impact, exposure, and existing controls.
  6. Select treatments. Avoid, reduce, transfer, or accept the risk with documented justification.
  7. Verify and monitor. Convert controls into requirements and tests.

A useful classification is STRIDE:

CategoryQuestionTypical control
SpoofingCan an attacker impersonate someone?Strong authentication
TamperingCan data or code be changed?Integrity checks and authorization
RepudiationCan an actor deny an action?Reliable audit records
Information disclosureCan confidential data leak?Encryption and minimization
Denial of serviceCan the service be made unavailable?Rate limits and resilience
Elevation of privilegeCan a user gain excess authority?Server-side authorization

Risk scoring may use qualitative labels such as low, medium, and high. A numerical score can also be used, but it is not an objective probability unless the organization defines how scores are calibrated. A common prioritization aid is:

Risk priority = Likelihood × Impact

Here, likelihood and impact are organizational rating scales, not physical units. The multiplication is useful for ranking risks only when the scales and interpretation are consistently defined. It does not prove that a risk has a precise probability.

3. Secure Coding in Java and Python

Secure coding means writing code that anticipates hostile input, failure, misuse, and changing dependencies.

Input validation and output encoding

Treat all external input as untrusted, including HTTP parameters, uploaded files, environment variables, messages, and data from another internal service. Validation should be performed on the server and should check type, length, range, format, and business rules. Prefer allowlists—for example, accepting only known status values—over attempting to list every dangerous value.

Validation is not the same as output encoding. Input validation determines whether data is acceptable for a particular operation; output encoding ensures that data is interpreted as text rather than executable content in its destination context, such as HTML, SQL, a shell, or JavaScript.

Injection vulnerabilities

SQL injection occurs when untrusted text is concatenated into a query. Use parameterized queries or a carefully implemented data-access framework.

Java example:

String sql = "SELECT id, name FROM users WHERE email = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
    ps.setString(1, email);
    try (ResultSet rs = ps.executeQuery()) {
        // Process results
    }
}

Python example:

cursor.execute(
    "SELECT id, name FROM users WHERE email = %s",
    (email,)
)

The placeholder syntax depends on the database driver. The essential principle is that the driver treats the value as data, not as query syntax. String concatenation is unsafe even when the input appears to come from a trusted interface.

Avoid constructing operating-system commands from user input. If a command is unavoidable, use a library API, an argument list rather than a shell string, strict allowlists, and least-privileged execution.

Secrets and cryptography

Passwords must not be stored in plaintext or with reversible encryption. Store them using a password-hashing algorithm designed for password storage, with a unique salt and an appropriate work factor. Developers should use a current, well-reviewed library rather than implementing hashing themselves.

Cryptography has different purposes:

  • Encryption provides confidentiality.
  • Hashing produces a one-way digest, useful for integrity and password verification when an appropriate password-hashing scheme is used.
  • Message authentication codes provide integrity and authenticity when a shared secret exists.
  • Digital signatures provide integrity and evidence that a private-key holder signed data.

Keys and tokens must not be embedded in source code or committed to a public repository. Use a secrets manager or protected deployment configuration. TLS should protect data in transit, and sensitive data at rest should be encrypted where the threat model justifies it. Certificate validation must not be disabled merely to resolve development errors.

Error handling and logging

User-facing errors should be useful without revealing stack traces, SQL statements, file paths, tokens, or personal data. Detailed diagnostic information belongs in protected logs. Logs should record security-relevant events such as authentication failures, privilege changes, and administrative actions, while avoiding unnecessary sensitive content.

Logs require protection against unauthorized reading, alteration, and deletion. Their clocks should be synchronized sufficiently for investigation, and retention should be defined rather than unlimited.

Dependency and supply-chain security

Third-party packages reduce development effort but introduce inherited risk. Record direct and transitive dependencies, use trusted repositories, review licences, pin or constrain versions appropriately, scan for known vulnerabilities, and update dependencies through controlled testing. A vulnerability scanner is an aid, not a guarantee: false positives, unreported vulnerabilities, and insecure configuration remain possible.

Java projects commonly use Maven or Gradle; Python projects commonly use pip with a virtual environment and a dependency declaration such as requirements.txt or pyproject.toml. Locking versions improves reproducibility, but locked versions still require maintenance.

4. Identity, Authentication, and Access Control

Authentication answers “Who are you?” Authorization answers “What are you allowed to do?” Confusing the two is a common cause of vulnerabilities.

Authentication may use knowledge factors, possession factors, and inherence factors. Multi-factor authentication combines factors from different categories. Passwords should have sensible length requirements, protection against credential stuffing, secure reset procedures, and no unnecessary forced rotation that encourages predictable changes.

Authorization models include:

  • Role-based access control (RBAC): permissions are assigned to roles such as clerk or manager.
  • Attribute-based access control (ABAC): decisions use attributes such as department, resource classification, location, or time.
  • Discretionary access control: owners or administrators may assign permissions.
  • Mandatory access control: policy classifications constrain access independently of individual ownership.

Authorization must be enforced on the server for every protected operation. Hiding a button in a user interface is not authorization. Developers should test horizontal privilege escalation—one user accessing another user’s records—and vertical escalation—a lower-privilege user performing an administrator action.

An authorization decision can be represented conceptually as:

Permit if Subject, Action, Resource, and Environment satisfy Policy

The subject is the requesting identity, the action is the operation, the resource is the protected object, and the environment contains relevant context. A default-deny policy is safer than granting access unless a particular denial is found.

5. Privacy and Responsible Data Use

Privacy is not simply secrecy. It includes appropriate collection, use, disclosure, retention, accuracy, user control, and protection of personal information. Laws differ by jurisdiction, so legal review is required; technical teams must not assume that one legal framework applies everywhere.

Responsible data practice commonly follows these principles:

  • Purpose limitation: collect and use data for specified legitimate purposes.
  • Data minimization: collect only what is needed.
  • Transparency: explain what is collected and why.
  • Accuracy: enable correction of materially inaccurate information.
  • Retention limitation: delete or anonymize data when the purpose ends.
  • Security: protect data proportionately to its sensitivity.
  • Accountability: document decisions and demonstrate compliance.

A privacy impact assessment is appropriate when processing is extensive, sensitive, innovative, or likely to affect individuals significantly. It should describe data flows, purposes, risks, safeguards, retention, access, and residual risk.

Responsible use of analytics and artificial intelligence requires additional care. A model may reproduce historical bias, infer sensitive attributes, or make decisions that users cannot meaningfully challenge. Teams should define the model’s purpose, data provenance, evaluation population, acceptable error trade-offs, human oversight, monitoring, and appeal process. Generated code must also be reviewed for security, licensing, correctness, and unintended disclosure of confidential prompts or source code.

6. Intellectual Property and Open-Source Licensing

Software may involve copyright in source code, patents, trademarks, database rights, trade secrets, and contractual restrictions. Ownership often depends on employment terms, commissioned-work arrangements, jurisdiction, and project agreements. Developers should preserve notices and seek advice rather than assuming that publicly available code is free of obligations.

Open-source software is licensed, not ownerless. Important licence families include:

Licence approachTypical obligation pattern
Permissive licences such as MIT or BSDPreserve notices; other conditions may apply
Apache License 2.0Notices and licence terms; includes explicit patent provisions
Weak copyleft licences such as LGPLConditions may apply to modifications or linking, depending on use
Strong copyleft licences such as GPLDistribution of covered derivative works may require corresponding source under the licence

The exact licence text controls. A project should maintain a software bill of materials or dependency inventory, record each component’s version and licence, preserve required notices, and obtain approval for incompatible or uncertain combinations. “Open source” does not mean “no attribution,” “no security risk,” or “usable for every commercial purpose.”

7. Accessibility and Inclusive Design

Accessibility enables people with visual, auditory, motor, cognitive, and speech-related disabilities to use software. It is both an ethical responsibility and, in many contexts, a legal or procurement requirement.

Practical measures include:

  • keyboard operation for all essential functions;
  • visible focus indicators;
  • meaningful labels and instructions;
  • semantic HTML and accessible names for controls;
  • sufficient colour contrast and non-colour cues;
  • captions or transcripts for multimedia;
  • scalable text and responsive layouts;
  • clear error messages and predictable navigation;
  • compatibility with screen readers and assistive technologies.

Accessibility should be tested with automated tools, keyboard-only operation, manual inspection, and users with relevant lived experience. Automated testing detects only a subset of barriers. Accessibility requirements should appear in acceptance criteria, not be postponed to final testing.

8. Governance and Professional Practice

Governance converts principles into repeatable organizational behaviour. It defines who may decide, what evidence is required, how exceptions are approved, and how performance is monitored.

A practical governance structure includes:

  • security and privacy policies;
  • named system and data owners;
  • risk registers and treatment plans;
  • secure development standards;
  • code review and branch protection;
  • automated testing and security scanning in CI/CD;
  • change management and release approval;
  • asset, dependency, and licence inventories;
  • backup, recovery, and retention procedures;
  • incident response and breach notification processes;
  • periodic access reviews and audit evidence.

Governance should be proportionate. Excessive bureaucracy can encourage workarounds, while weak governance leaves critical decisions undocumented. A useful distinction is between policy—what must be achieved; standard—the required level or method; procedure—the steps to follow; and guideline—recommended advice that may allow judgment.

When an incident occurs, the organization should identify and contain it, preserve evidence, eradicate the cause, recover safely, notify appropriate parties where required, and conduct a blameless lessons-learned review. Blameless does not mean consequence-free; it means seeking systemic causes rather than hiding information or focusing only on individual fault.

Applied Case: Campus Placement Portal

This is an illustrative case.

Background

A college commissions a Java REST API and Python analytics service for a placement portal. Students submit personal details, academic records, resumes, and employment preferences. Employers view shortlisted candidates. Staff manage vacancies and produce reports.

Problem

An early prototype uses a shared database account, stores uploaded resumes in a public directory, builds a search query by string concatenation, and allows an employer to request candidates by changing a numeric URL identifier. The project team also copies an open-source resume parser into the repository without recording its licence.

Analysis

Threat modelling identifies:

  • information disclosure of resumes and personal data;
  • SQL injection through search fields;
  • horizontal privilege escalation between employers;
  • excessive database privileges;
  • malware or unsafe files in uploads;
  • licence non-compliance;
  • inaccessible forms for keyboard and screen-reader users;
  • unjustified bias if analytics ranks candidates using historical hiring outcomes.

The data is sensitive enough to require data minimization, restricted access, retention rules, auditability, and a documented privacy assessment.

Approach and solution

The team creates separate service accounts with least privilege, stores resumes outside the public web root, validates file type and size, generates non-guessable identifiers, and checks that the authenticated employer is authorized for each candidate record. Parameterized queries replace concatenated SQL. Uploaded files are scanned and served through an authorization-controlled endpoint.

Passwords are handled by a proven password-hashing library, administrative accounts use multi-factor authentication, and secrets move to protected configuration. Logs record access and administrative events without storing resume contents. The dependency inventory records the parser’s licence, version, notices, and approval status.

The API receives security tests for injection and object-level authorization. Accessibility acceptance criteria cover keyboard navigation, labels, focus, contrast, and error messages. The analytics service is changed to provide descriptive statistics rather than an unexplained ranking until fairness, validation, human review, and appeal procedures are established.

Outcome

The portal’s risk is reduced, but not eliminated. The organization accepts a documented residual risk concerning malicious uploads and schedules periodic review. A data owner, security reviewer, and accessibility representative are assigned. The release pipeline blocks unreviewed dependencies and high-severity test findings, with a formal exception process.

Learning points

Security controls must address architecture, code, configuration, and operations together. Privacy and fairness influence requirements, not merely documentation. Licensing and accessibility are delivery requirements. Governance creates evidence that decisions were considered and can be revisited.

Challenges and Limitations

No framework guarantees safety. Threat models can omit assets, attackers, or dependencies. Risk ratings may reflect subjective judgments. Scanners miss business-logic flaws, and tests cannot prove the absence of vulnerabilities. Encryption does not solve excessive collection or poor authorization. Compliance checklists may produce paperwork without genuine risk reduction. Accessibility standards may still fail to capture an individual user’s experience.

Security also creates trade-offs. Stronger controls may increase cost, latency, or complexity. Data minimization may reduce analytical convenience. Open-source restrictions may affect component choice. The correct response is not to ignore constraints but to make them explicit, consult affected stakeholders, and document proportionate decisions.

Best-Practice Checklist

Before release, a project team should be able to answer “yes” to most of the following:

  • Have assets, trust boundaries, threats, and assumptions been documented?
  • Are authentication and server-side authorization tested?
  • Are inputs validated and outputs encoded for their context?
  • Are parameterized queries used?
  • Are secrets absent from source control and logs?
  • Are dependencies inventoried, reviewed, and maintained?
  • Are personal data, retention, consent, and user rights addressed?
  • Are licences and attribution obligations recorded?
  • Can users with disabilities complete essential tasks?
  • Are security events logged and monitored appropriately?
  • Are backups, recovery, incident response, and ownership defined?
  • Are exceptions approved, time-limited, and reviewed?

Chapter Summary

Secure, ethical, and governed development is a continuous professional responsibility. Threat modelling identifies assets, trust boundaries, attack paths, and treatments before implementation becomes expensive to change. Secure coding uses validation, contextual encoding, parameterized queries, protected secrets, safe error handling, dependency management, and least privilege. Authentication establishes identity, while authorization controls actions on resources and must be enforced server-side.

Privacy requires purpose limitation, minimization, transparency, accuracy, retention control, security, and accountability. Intellectual property and open-source licences impose real obligations that should be tracked in a component inventory. Accessibility must be designed and tested throughout the project. Governance supplies policies, roles, evidence, review, incident response, and controlled exceptions. Ethical development also requires attention to fairness, human oversight, responsible data use, and the social consequences of automated decisions.

Key Terms

Threat modelling: Structured identification and treatment of possible threats.

Asset: Something valuable that requires protection.

Trust boundary: A point where data or authority crosses between different levels of trust.

Confidentiality: Protection against unauthorized disclosure.

Integrity: Protection against unauthorized or improper modification.

Availability: Readiness of a system for authorized use.

Authentication: Verification of an identity.

Authorization: Determination of permitted actions.

Least privilege: Granting only the permissions necessary for a task.

Defense in depth: Use of multiple independent protective controls.

Input validation: Checking whether input meets defined technical and business rules.

Output encoding: Representing data safely for its destination context.

Parameterized query: A database query that separates instructions from supplied values.

Personal data: Information relating to an identifiable person.

Data minimization: Collecting and using no more personal data than necessary.

Open-source licence: Legal terms governing use, modification, and distribution of software.

Accessibility: Design enabling people with diverse abilities to use a product.

Governance: Authority, policies, processes, and evidence guiding organizational decisions.

Residual risk: Risk remaining after controls are applied.

Software bill of materials: An inventory of software components and their versions.

Review Questions

Short Answer Questions

  1. What are the three elements of the CIA triad?
  2. Distinguish authentication from authorization.
  3. Why are parameterized queries preferred to string-concatenated SQL?
  4. State three principles of responsible data use.
  5. What is the purpose of a software bill of materials?

Long Answer Questions

  1. Explain the threat-modelling process and illustrate how STRIDE can support it.
  2. Discuss secure coding practices for secrets, errors, logging, and dependencies in Java and Python projects.
  3. Compare RBAC and ABAC, including situations in which each may be appropriate.
  4. Explain how privacy, accessibility, and intellectual property should influence project requirements.
  5. Describe the role of governance before, during, and after a software release.

Analytical / Application Questions

  1. A student-management API lets any logged-in user retrieve another student’s record by changing an identifier in the URL. Identify the vulnerability, explain why hiding the interface control is insufficient, and propose layered controls.
  2. A Python analytics service ranks job applicants using historical hiring data. Design an ethical and governed evaluation plan addressing data provenance, bias, explainability, human review, and appeals.
  3. A Java application uses five external libraries, one with an uncertain licence and two with known vulnerabilities. Recommend a decision process covering technical mitigation, licence review, documentation, and release approval.

Multiple Choice Questions with Answers

Question 1

Which activity is the primary purpose of threat modelling?

A. Choosing a programming language

B. Identifying assets, threats, and appropriate controls

C. Measuring application performance only

D. Replacing all software testing

Correct Answer: B. Identifying assets, threats, and appropriate controls

Question 2

Which control most directly prevents SQL injection?

A. Hiding database errors from users

B. Using a parameterized query

C. Increasing the database server memory

D. Changing the user interface colour

Correct Answer: B. Using a parameterized query

Question 3

What is the correct distinction between authentication and authorization?

A. Authentication identifies a user; authorization determines permitted actions

B. Authentication encrypts data; authorization compresses it

C. Authentication records logs; authorization deletes them

D. Authentication validates input; authorization formats output

Correct Answer: A. Authentication identifies a user; authorization determines permitted actions

Question 4

Which principle gives a service only the permissions required for its task?

A. Open design

B. Least privilege

C. Data duplication

D. Maximum availability

Correct Answer: B. Least privilege

Question 5

Which practice best protects passwords stored by an application?

A. Plaintext storage

B. Reversible encryption with one shared key

C. A suitable password-hashing scheme with unique salts

D. Storing passwords in source code

Correct Answer: C. A suitable password-hashing scheme with unique salts

Question 6

Which is an example of data minimization?

A. Collecting every available user attribute for possible future use

B. Retaining all records indefinitely

C. Collecting only the information necessary for the stated purpose

D. Publishing personal data to improve transparency

Correct Answer: C. Collecting only the information necessary for the stated purpose

Question 7

What does an open-source licence primarily specify?

A. The processor speed required to run the software

B. Legal conditions for using, modifying, and distributing the software

C. The guaranteed absence of vulnerabilities

D. The number of users who may log in simultaneously

Correct Answer: B. Legal conditions for using, modifying, and distributing the software

Question 8

Which measure is most directly associated with accessibility?

A. Requiring a mouse for every operation

B. Removing visible focus indicators

C. Providing keyboard access and meaningful control labels

D. Using colour alone to communicate errors

Correct Answer: C. Providing keyboard access and meaningful control labels

Question 9

Why is server-side authorization necessary?

A. Users can always be trusted to follow the interface

B. Client-side controls can be bypassed or modified

C. It eliminates the need for authentication

D. It makes all data public

Correct Answer: B. Client-side controls can be bypassed or modified

Question 10

In governance, what is a residual risk?

A. A risk identified before any controls are considered

B. A risk remaining after controls have been applied

C. A risk that has never been documented

D. A risk caused only by hardware failure

Correct Answer: B. A risk remaining after controls have been applied

Project Development Using Java and Python
Chapter 10 of 15